606 lines
30 KiB
Zig
606 lines
30 KiB
Zig
//! `aji` command-line driver.
|
||
//!
|
||
//! Output contract (stable, consumed by agents):
|
||
//! - diagnostics go to stdout as JSON Lines, one object per line;
|
||
//! - human-oriented notes go to stderr;
|
||
//! - `aji run` writes one run record (spec 07a "Run result") to stdout;
|
||
//! - exit codes: 0 accepted / returned, 1 rejected, 2 usage or I/O error,
|
||
//! 3 input not decidable yet (pipeline stage unimplemented), 4 trapped,
|
||
//! 5 execution limit exceeded (`--fuel`, spec 11 §7),
|
||
//! 6 not instantiated (missing or invalid `--grant`, spec 05 §10.2),
|
||
//! 7 blocked: no future event can complete a wait (spec 11 §8).
|
||
|
||
const std = @import("std");
|
||
const aji = @import("aji");
|
||
|
||
const usage =
|
||
\\usage: aji <command> [args]
|
||
\\
|
||
\\commands:
|
||
\\ check [--report unsafe] <file.air | file.aji | --manifest aji.toml>
|
||
\\ parse and verify a text AIR module; the unsafe report
|
||
\\ lists trusted boundaries and unsafe operations
|
||
\\ run [--fuel N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji | --manifest aji.toml>
|
||
\\ verify, then run @main and print the run record;
|
||
\\ --fuel stops after N executed instructions;
|
||
\\ --grant binds capability parameter P of @main
|
||
\\ (and replaces the manifest's grant for P);
|
||
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
|
||
\\ --seed N; scheduler: --quantum N, --task-limit N,
|
||
\\ --schedule-seed N; --profile hosted uses the real OS and
|
||
\\ writes the record only to --result-file PATH
|
||
\\ lower [--annotate | --stats] <file.aji | --manifest aji.toml>
|
||
\\ print the canonical AIR a source module lowers to;
|
||
\\ --annotate adds source spans as comments (not canonical);
|
||
\\ --stats prints source/AIR size and expansion ratio
|
||
\\ fmt [--check | --write] <file.aji>
|
||
\\ print formatted source; --check checks without writing,
|
||
\\ --write replaces a regular file; both print a JSON record
|
||
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji | --manifest aji.toml>
|
||
\\ run @main under every schedule and weak-memory choice
|
||
\\ (depth first, up to N runs, default 100000) and print the
|
||
\\ distinct outcomes; "complete" is true when the whole
|
||
\\ choice tree was explored (spec 04 §20.5)
|
||
\\ report <file.air | file.aji | --manifest aji.toml> verify, then print the audit report (spec 10 §6.1)
|
||
\\ codes list diagnostic codes as JSON Lines
|
||
\\ features print supported AIR format, language version and features
|
||
\\ explain <code> show one diagnostic code
|
||
\\ version print toolchain version
|
||
\\
|
||
;
|
||
|
||
const ExitCode = enum(u8) { accepted = 0, rejected = 1, usage = 2, unimplemented = 3, trapped = 4, limit_exceeded = 5, not_instantiated = 6, blocked = 7 };
|
||
|
||
pub fn main(init: std.process.Init) !void {
|
||
const arena = init.arena.allocator();
|
||
const io = init.io;
|
||
const args = try init.minimal.args.toSlice(arena);
|
||
|
||
var stdout_buf: [4096]u8 = undefined;
|
||
var stdout_fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf);
|
||
const out = &stdout_fw.interface;
|
||
|
||
const code = run(io, arena, args, out) catch |err| switch (err) {
|
||
error.WriteFailed => return stdout_fw.err.?,
|
||
else => |e| return e,
|
||
};
|
||
try out.flush();
|
||
std.process.exit(@backingInt(code));
|
||
}
|
||
|
||
fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *std.Io.Writer) !ExitCode {
|
||
if (args.len < 2) {
|
||
std.debug.print("{s}", .{usage});
|
||
return .usage;
|
||
}
|
||
const cmd = args[1];
|
||
if (std.mem.eql(u8, cmd, "fmt")) return formatCommand(io, arena, args[2..], out);
|
||
if (std.mem.eql(u8, cmd, "version")) {
|
||
try out.print("aji {s} (air format {d})\n", .{ aji.version, aji.air.format_version });
|
||
return .accepted;
|
||
}
|
||
if (std.mem.eql(u8, cmd, "report")) {
|
||
const from_manifest = args.len == 4 and std.mem.eql(u8, args[2], "--manifest");
|
||
if (args.len != 3 and !from_manifest) return usageError("report takes a file or --manifest PATH");
|
||
const input = try readInput(arena, io, args[args.len - 1], from_manifest) orelse return .usage;
|
||
const result = try aji.check.checkWithModules(arena, input.path, input.source, input.modules);
|
||
for (result.diagnostics) |d| {
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
}
|
||
if (result.status == .unimplemented) return .unimplemented;
|
||
const module = result.module orelse return .rejected;
|
||
try aji.report.write(arena, module, out);
|
||
try out.writeByte('\n');
|
||
return .accepted;
|
||
}
|
||
if (std.mem.eql(u8, cmd, "lower")) {
|
||
var annotate = false;
|
||
var stats = false;
|
||
var manifest_path: ?[]const u8 = null;
|
||
var rest = args[2..];
|
||
while (rest.len != 0) {
|
||
if (std.mem.eql(u8, rest[0], "--annotate") and !annotate and !stats) {
|
||
annotate = true;
|
||
rest = rest[1..];
|
||
} else if (std.mem.eql(u8, rest[0], "--stats") and !annotate and !stats) {
|
||
stats = true;
|
||
rest = rest[1..];
|
||
} else if (std.mem.eql(u8, rest[0], "--manifest") and rest.len >= 2 and manifest_path == null) {
|
||
manifest_path = rest[1];
|
||
rest = rest[2..];
|
||
} else break;
|
||
}
|
||
if ((manifest_path != null and rest.len != 0) or (manifest_path == null and rest.len != 1)) return usageError("lower takes [--annotate | --stats] and a file or --manifest PATH");
|
||
const input = try readInput(arena, io, manifest_path orelse rest[0], manifest_path != null) orelse return .usage;
|
||
const path = input.path;
|
||
const source = input.source;
|
||
if (manifest_path != null and !std.mem.endsWith(u8, path, ".aji")) return usageError("lower requires a .aji entry");
|
||
switch (try aji.frontend.compileWithModules(arena, path, source, input.modules)) {
|
||
.ok => |o| {
|
||
if (stats) {
|
||
// How much mechanical work the frontend took over.
|
||
// Code only: blank lines and `//` / `;` comment lines are not counted.
|
||
const Code = struct { bytes: usize, lines: usize };
|
||
const code = struct {
|
||
fn count(t: []const u8) Code {
|
||
var c: Code = .{ .bytes = 0, .lines = 0 };
|
||
var it = std.mem.splitScalar(u8, t, '\n');
|
||
while (it.next()) |ln| {
|
||
const tr = std.mem.trim(u8, ln, " \t\r");
|
||
if (tr.len == 0 or std.mem.startsWith(u8, tr, "//") or std.mem.startsWith(u8, tr, ";")) continue;
|
||
c.bytes += ln.len + 1;
|
||
c.lines += 1;
|
||
}
|
||
return c;
|
||
}
|
||
}.count;
|
||
const sc = code(source);
|
||
const ac = code(o.air);
|
||
const nc = try aji.frontend.normalizedSize(arena, o);
|
||
const ratio = struct {
|
||
fn f(a: usize, b: usize) f64 {
|
||
return @as(f64, @floatFromInt(a)) / @as(f64, @floatFromInt(@max(b, 1)));
|
||
}
|
||
}.f;
|
||
var s: std.json.Stringify = .{ .writer = out };
|
||
try s.write(.{
|
||
.source_bytes = sc.bytes,
|
||
.source_lines = sc.lines,
|
||
.air_bytes = ac.bytes,
|
||
.air_lines = ac.lines,
|
||
.air_bytes_normalized = nc.bytes,
|
||
.air_lines_normalized = nc.lines,
|
||
.byte_string_constants = o.constants.len,
|
||
.expansion_bytes = ratio(ac.bytes, sc.bytes),
|
||
.expansion_lines = ratio(ac.lines, sc.lines),
|
||
// 1 − source/AIR: the share of AIR text the frontend writes for the author.
|
||
.mechanical_air_eliminated_raw = 1.0 - ratio(sc.bytes, ac.bytes),
|
||
// The same against AIR with each byte-string materialization counted
|
||
// as one logical constant operation (spec 15 §11).
|
||
.mechanical_air_eliminated_normalized = 1.0 - ratio(sc.bytes, nc.bytes),
|
||
});
|
||
try out.writeByte('\n');
|
||
return .accepted;
|
||
}
|
||
try out.writeAll(if (annotate) o.annotated else o.air);
|
||
return .accepted;
|
||
},
|
||
.err => |d| {
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
return .rejected;
|
||
},
|
||
.errors => |ds| {
|
||
for (ds) |d| {
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
}
|
||
return .rejected;
|
||
},
|
||
.unimplemented => |what| {
|
||
std.debug.print("aji: not implemented yet: {s}\n", .{what});
|
||
return .unimplemented;
|
||
},
|
||
}
|
||
}
|
||
if (std.mem.eql(u8, cmd, "features")) {
|
||
var s: std.json.Stringify = .{ .writer = out };
|
||
try s.write(.{
|
||
.air = aji.air.format_version,
|
||
.lang = std.fmt.comptimePrint("{d}.{d}", .{ aji.air.lang_version[0], aji.air.lang_version[1] }),
|
||
.features = &aji.air.features.supported,
|
||
});
|
||
try out.writeByte('\n');
|
||
return .accepted;
|
||
}
|
||
if (std.mem.eql(u8, cmd, "codes")) {
|
||
for (aji.diag.registry) |c| try writeCode(out, c);
|
||
return .accepted;
|
||
}
|
||
if (std.mem.eql(u8, cmd, "explain")) {
|
||
if (args.len != 3) return usageError("explain takes exactly one code");
|
||
const c = aji.diag.lookup(args[2]) orelse return usageError("unknown diagnostic code");
|
||
try writeCode(out, c.*);
|
||
return .accepted;
|
||
}
|
||
if (std.mem.eql(u8, cmd, "explore")) return explore(arena, io, args[2..], out);
|
||
if (std.mem.eql(u8, cmd, "check") or std.mem.eql(u8, cmd, "run")) {
|
||
var options: aji.interp.Options = .{};
|
||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||
var files: std.ArrayList(struct { []const u8, []const u8 }) = .empty;
|
||
var result_file: ?[]const u8 = null;
|
||
var rest = args[2..];
|
||
var unsafe_report = false;
|
||
if (std.mem.eql(u8, cmd, "check") and rest.len >= 3 and std.mem.eql(u8, rest[0], "--report")) {
|
||
if (!std.mem.eql(u8, rest[1], "unsafe")) return usageError("--report takes unsafe");
|
||
unsafe_report = true;
|
||
rest = rest[2..];
|
||
}
|
||
var manifest_path: ?[]const u8 = null;
|
||
if (std.mem.eql(u8, cmd, "check") and rest.len >= 2 and std.mem.eql(u8, rest[0], "--manifest")) {
|
||
manifest_path = rest[1];
|
||
rest = rest[2..];
|
||
}
|
||
while (std.mem.eql(u8, cmd, "run") and rest.len >= 2) {
|
||
const flag = rest[0];
|
||
const value = rest[1];
|
||
if (std.mem.eql(u8, flag, "--fuel")) {
|
||
options.fuel = std.fmt.parseInt(u64, value, 10) catch return usageError("--fuel takes a non-negative integer");
|
||
} else if (std.mem.eql(u8, flag, "--grant")) {
|
||
try grants.append(arena, parseGrant(value) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||
} else if (std.mem.eql(u8, flag, "--profile")) {
|
||
if (std.mem.eql(u8, value, "hosted")) {
|
||
options.hosted = io;
|
||
} else if (!std.mem.eql(u8, value, "deterministic")) return usageError("--profile takes deterministic or hosted");
|
||
} else if (std.mem.eql(u8, flag, "--stdin")) {
|
||
options.world.stdin = value;
|
||
} else if (std.mem.eql(u8, flag, "--vfs")) {
|
||
const eq = std.mem.indexOfScalar(u8, value, '=') orelse return usageError("--vfs takes <path>=<text>");
|
||
try files.append(arena, .{ value[0..eq], value[eq + 1 ..] });
|
||
} else if (std.mem.eql(u8, flag, "--seed")) {
|
||
options.world.seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--seed takes a non-negative integer");
|
||
} else if (std.mem.eql(u8, flag, "--quantum")) {
|
||
options.quantum = std.fmt.parseInt(u64, value, 10) catch return usageError("--quantum takes a positive integer");
|
||
if (options.quantum == 0) return usageError("--quantum takes a positive integer");
|
||
} else if (std.mem.eql(u8, flag, "--task-limit")) {
|
||
options.task_limit = std.fmt.parseInt(u64, value, 10) catch return usageError("--task-limit takes a non-negative integer");
|
||
} else if (std.mem.eql(u8, flag, "--schedule-seed")) {
|
||
options.schedule_seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--schedule-seed takes a non-negative integer");
|
||
} else if (std.mem.eql(u8, flag, "--result-file")) {
|
||
result_file = value;
|
||
} else if (std.mem.eql(u8, flag, "--manifest")) {
|
||
manifest_path = value;
|
||
} else break;
|
||
rest = rest[2..];
|
||
}
|
||
options.world.files = files.items;
|
||
var input: aji.source_package.Input = undefined;
|
||
if (manifest_path) |mp| {
|
||
if (rest.len != 0) return usageError("a file argument cannot be combined with --manifest");
|
||
input = try readInput(arena, io, mp, true) orelse return .usage;
|
||
options.grants = try mergeGrants(arena, input.grants, grants.items);
|
||
} else {
|
||
if (rest.len != 1) return usageError("check and run take a file or --manifest PATH");
|
||
input = try readInput(arena, io, rest[0], false) orelse return .usage;
|
||
options.grants = grants.items;
|
||
}
|
||
const path = input.path;
|
||
const report = try aji.check.checkWithModules(arena, path, input.source, input.modules);
|
||
for (report.diagnostics) |d| {
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
}
|
||
if (unsafe_report) if (report.module) |module| try aji.verifier.unsafe_.writeReport(module, out);
|
||
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
|
||
const module = report.module.?;
|
||
var output: aji.interp.Output = undefined;
|
||
const hosted = options.hosted != null;
|
||
// In the hosted profile the program owns stdout and stderr: flush
|
||
// what the toolchain wrote before the program starts.
|
||
if (hosted) try out.flush() else options.output = &output;
|
||
const outcome = aji.interp.run(arena, module, "main", options) catch |err| switch (err) {
|
||
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
|
||
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
|
||
else => |e| return e,
|
||
};
|
||
const captured: ?aji.interp.Output = if (hosted) null else output;
|
||
if (!hosted) {
|
||
try writeRecord(arena, module, outcome, captured, report, path, out);
|
||
try out.writeByte('\n');
|
||
} else if (result_file == null) {
|
||
// Human summary only; the machine interface is --result-file (spec 11 §8).
|
||
var rec: std.Io.Writer.Allocating = .init(arena);
|
||
try aji.interp.writeOutcome(module, outcome, null, &rec.writer);
|
||
std.debug.print("aji: {s}\n", .{rec.written()});
|
||
}
|
||
if (result_file) |rpath| {
|
||
var rec: std.Io.Writer.Allocating = .init(arena);
|
||
try aji.interp.writeOutcome(module, outcome, captured, &rec.writer);
|
||
try rec.writer.writeByte('\n');
|
||
std.Io.Dir.cwd().writeFile(io, .{ .sub_path = rpath, .data = rec.written() }) catch |err| {
|
||
std.debug.print("aji: cannot write {s}: {t}\n", .{ rpath, err });
|
||
return .usage;
|
||
};
|
||
}
|
||
return switch (outcome) {
|
||
.returned => .accepted,
|
||
.trapped => .trapped,
|
||
.limit_exceeded => .limit_exceeded,
|
||
.not_instantiated => .not_instantiated,
|
||
.blocked => .blocked,
|
||
// Only with Options.detect_races, which the CLI does not set.
|
||
.race_detected => .trapped,
|
||
};
|
||
}
|
||
return switch (report.status) {
|
||
.accepted => .accepted,
|
||
.rejected => .rejected,
|
||
.unimplemented => {
|
||
std.debug.print("aji: not implemented yet: {s}\n", .{report.missing_stage});
|
||
return .unimplemented;
|
||
},
|
||
};
|
||
}
|
||
return usageError("unknown command");
|
||
}
|
||
|
||
/// `aji explore`: exhaustive depth-first exploration of the choice tree
|
||
/// (scheduler, `select` and weak-memory choices). Instructions other than
|
||
/// scheduling points are not interleaved: the quantum is unbounded, so the
|
||
/// tree branches only at synchronization and atomic operations.
|
||
fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out: *std.Io.Writer) !ExitCode {
|
||
var max_runs: u64 = 100_000;
|
||
var grants: std.ArrayList(aji.interp.Grant) = .empty;
|
||
var rest = argv;
|
||
var manifest_path: ?[]const u8 = null;
|
||
while (rest.len >= 2) {
|
||
if (std.mem.eql(u8, rest[0], "--max-runs")) {
|
||
max_runs = std.fmt.parseInt(u64, rest[1], 10) catch return usageError("--max-runs takes a positive integer");
|
||
} else if (std.mem.eql(u8, rest[0], "--grant")) {
|
||
try grants.append(arena, parseGrant(rest[1]) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
|
||
} else if (std.mem.eql(u8, rest[0], "--manifest") and manifest_path == null) {
|
||
manifest_path = rest[1];
|
||
} else break;
|
||
rest = rest[2..];
|
||
}
|
||
if ((manifest_path != null and rest.len != 0) or (manifest_path == null and rest.len != 1)) return usageError("explore takes a file or --manifest PATH");
|
||
const input = try readInput(arena, io, manifest_path orelse rest[0], manifest_path != null) orelse return .usage;
|
||
const all_grants = try mergeGrants(arena, input.grants, grants.items);
|
||
const path = input.path;
|
||
const report = try aji.check.checkWithModules(arena, path, input.source, input.modules);
|
||
for (report.diagnostics) |d| {
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
}
|
||
if (report.status != .accepted) return .rejected;
|
||
const module = report.module.?;
|
||
|
||
var counts: std.StringArrayHashMapUnmanaged(u64) = .empty;
|
||
var prefix: std.ArrayList(u32) = .empty;
|
||
var runs: u64 = 0;
|
||
var complete = false;
|
||
while (runs < max_runs) {
|
||
var run_arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||
defer run_arena.deinit();
|
||
var ex: aji.interp.Explore = .{ .prefix = prefix.items };
|
||
const outcome = aji.interp.run(run_arena.allocator(), module, "main", .{
|
||
.grants = all_grants,
|
||
.quantum = std.math.maxInt(u64),
|
||
.explore = &ex,
|
||
}) catch |err| switch (err) {
|
||
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
|
||
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
|
||
else => |e| return e,
|
||
};
|
||
runs += 1;
|
||
var rec: std.Io.Writer.Allocating = .init(run_arena.allocator());
|
||
try aji.interp.writeOutcome(module, outcome, null, &rec.writer);
|
||
const gop = try counts.getOrPut(arena, rec.written());
|
||
if (!gop.found_existing) {
|
||
gop.key_ptr.* = try arena.dupe(u8, rec.written());
|
||
gop.value_ptr.* = 0;
|
||
}
|
||
gop.value_ptr.* += 1;
|
||
// The next path: increment the deepest choice that has an untried
|
||
// option, and drop everything after it.
|
||
const widths = ex.widths.items;
|
||
var i = widths.len;
|
||
const next = while (i > 0) {
|
||
i -= 1;
|
||
const taken: u32 = if (i < prefix.items.len) prefix.items[i] else 0;
|
||
if (taken + 1 < widths[i]) break i;
|
||
} else null;
|
||
const at = next orelse {
|
||
complete = true;
|
||
break;
|
||
};
|
||
var np: std.ArrayList(u32) = .empty;
|
||
for (0..at) |k| try np.append(arena, if (k < prefix.items.len) prefix.items[k] else 0);
|
||
try np.append(arena, (if (at < prefix.items.len) prefix.items[at] else 0) + 1);
|
||
prefix = np;
|
||
}
|
||
const keys = counts.keys();
|
||
const order = try arena.alloc(usize, keys.len);
|
||
for (order, 0..) |*o, k| o.* = k;
|
||
std.mem.sort(usize, order, keys, struct {
|
||
fn lt(ks: []const []const u8, a: usize, b: usize) bool {
|
||
return std.mem.lessThan(u8, ks[a], ks[b]);
|
||
}
|
||
}.lt);
|
||
try out.print("{{\"runs\":{d},\"complete\":{},\"outcomes\":[", .{ runs, complete });
|
||
for (order, 0..) |k, n| {
|
||
if (n != 0) try out.writeByte(',');
|
||
try out.print("{{\"outcome\":{s},\"count\":{d}}}", .{ keys[k], counts.values()[k] });
|
||
}
|
||
try out.writeAll("]}\n");
|
||
return if (complete) .accepted else .limit_exceeded;
|
||
}
|
||
|
||
/// The run record; for a `.aji` module a trap also carries its
|
||
/// `source_location` (spec 15 §10).
|
||
fn writeRecord(arena: std.mem.Allocator, module: aji.air.Module, outcome: aji.interp.Outcome, captured: ?aji.interp.Output, report: aji.check.Report, path: []const u8, out: *std.Io.Writer) !void {
|
||
var rec: std.Io.Writer.Allocating = .init(arena);
|
||
try aji.interp.writeOutcome(module, outcome, captured, &rec.writer);
|
||
const text = rec.written();
|
||
const lowered = report.lowered orelse return out.writeAll(text);
|
||
const t = switch (outcome) {
|
||
.trapped => |t| t,
|
||
else => return out.writeAll(text),
|
||
};
|
||
var loc: ?aji.frontend.Span = null;
|
||
for (module.functions) |f| {
|
||
if (!std.mem.eql(u8, f.name, t.function)) continue;
|
||
for (f.blocks) |b| {
|
||
if (!std.mem.eql(u8, b.name, t.block)) continue;
|
||
const air_line = b.insts[t.inst].span.line;
|
||
if (air_line >= 1 and air_line <= lowered.lines.len) loc = lowered.lines[air_line - 1];
|
||
}
|
||
}
|
||
const s = loc orelse return out.writeAll(text);
|
||
try out.writeAll(text[0 .. text.len - 1]);
|
||
var j: std.json.Stringify = .{ .writer = out };
|
||
try out.writeAll(",\"source_location\":");
|
||
try j.write(.{ .file = s.file orelse path, .line = s.start.line, .col = s.start.col });
|
||
try out.writeAll("}");
|
||
}
|
||
|
||
fn writeCode(out: *std.Io.Writer, c: aji.diag.Code) !void {
|
||
var s: std.json.Stringify = .{ .writer = out };
|
||
try s.write(.{ .code = c.id, .kind = c.kind, .meaning = c.meaning });
|
||
try out.writeByte('\n');
|
||
}
|
||
|
||
fn usageError(msg: []const u8) ExitCode {
|
||
std.debug.print("aji: {s}\n\n{s}", .{ msg, usage });
|
||
return .usage;
|
||
}
|
||
|
||
/// `<parameter>=<kind>[:<scope>]` (reference/capabilities.md).
|
||
pub fn parseGrant(text: []const u8) ?aji.interp.Grant {
|
||
const eq = std.mem.indexOfScalar(u8, text, '=') orelse return null;
|
||
const rest = text[eq + 1 ..];
|
||
const colon = std.mem.indexOfScalar(u8, rest, ':');
|
||
const g: aji.interp.Grant = .{
|
||
.parameter = text[0..eq],
|
||
.kind = if (colon) |c| rest[0..c] else rest,
|
||
.scope = if (colon) |c| rest[c + 1 ..] else null,
|
||
};
|
||
if (g.parameter.len == 0 or g.kind.len == 0) return null;
|
||
return g;
|
||
}
|
||
|
||
test parseGrant {
|
||
const g = parseGrant("data=fs.read:/var/data").?;
|
||
try std.testing.expectEqualStrings("data", g.parameter);
|
||
try std.testing.expectEqualStrings("fs.read", g.kind);
|
||
try std.testing.expectEqualStrings("/var/data", g.scope.?);
|
||
try std.testing.expect(parseGrant("out=io.write").?.scope == null);
|
||
try std.testing.expect(parseGrant("io.write") == null);
|
||
}
|
||
|
||
test "standard library trap record identifies the bundled source" {
|
||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||
defer arena.deinit();
|
||
const allocator = arena.allocator();
|
||
const report = try aji.check.checkFile(allocator, "client.aji", "module t\nimport std.math;\nfn main() -> u64\neffects []\n{ return std.math.clamp_u64(5, 9, 4); }\n");
|
||
try std.testing.expectEqual(aji.check.Status.accepted, report.status);
|
||
const module = report.module.?;
|
||
const outcome = try aji.interp.run(allocator, module, "main", .{ .fuel = 10000 });
|
||
try std.testing.expect(outcome == .trapped);
|
||
var output: std.Io.Writer.Allocating = .init(allocator);
|
||
try writeRecord(allocator, module, outcome, null, report, "client.aji", &output.writer);
|
||
const record = try std.json.parseFromSlice(std.json.Value, allocator, output.written(), .{});
|
||
const location = record.value.object.get("source_location").?.object;
|
||
try std.testing.expectEqualStrings("std/math.aji", location.get("file").?.string);
|
||
try std.testing.expectEqual(@as(i64, 20), location.get("line").?.integer);
|
||
}
|
||
|
||
fn formatCommand(io: std.Io, arena: std.mem.Allocator, arguments: []const [:0]const u8, out: *std.Io.Writer) !ExitCode {
|
||
var rest = arguments;
|
||
const Mode = enum { stdout, check, write };
|
||
var mode: Mode = .stdout;
|
||
if (rest.len != 0 and (std.mem.eql(u8, rest[0], "--check") or std.mem.eql(u8, rest[0], "--write"))) {
|
||
mode = if (std.mem.eql(u8, rest[0], "--check")) .check else .write;
|
||
rest = rest[1..];
|
||
}
|
||
if (rest.len != 1 or std.mem.startsWith(u8, rest[0], "--") or !std.mem.endsWith(u8, rest[0], ".aji")) return usageError("fmt takes [--check | --write] and one .aji file");
|
||
const path = rest[0];
|
||
var permissions: ?std.Io.File.Permissions = null;
|
||
if (mode == .write) {
|
||
const stat = std.Io.Dir.cwd().statFile(io, path, .{ .follow_symlinks = false }) catch |err| {
|
||
std.debug.print("aji: {s}: {t}\n", .{ path, err });
|
||
return .usage;
|
||
};
|
||
if (stat.kind != .file) {
|
||
std.debug.print("aji: fmt --write requires a regular file\n", .{});
|
||
return .usage;
|
||
}
|
||
permissions = stat.permissions;
|
||
}
|
||
const input = try readInput(arena, io, path, false) orelse return .usage;
|
||
const formatted = aji.frontend.format.format(arena, input.source) catch |err| switch (err) {
|
||
error.Invariant => {
|
||
std.debug.print("aji: formatter token preservation invariant failed\n", .{});
|
||
return .usage;
|
||
},
|
||
error.OutOfMemory => return error.OutOfMemory,
|
||
};
|
||
const text = switch (formatted) {
|
||
.err => |f| {
|
||
const d = try aji.frontend.syntaxDiagnostic(arena, path, f);
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
return .rejected;
|
||
},
|
||
.errors => |fs| {
|
||
for (try aji.frontend.syntaxDiagnostics(arena, path, fs)) |d| {
|
||
try d.writeJson(out);
|
||
try out.writeByte('\n');
|
||
}
|
||
return .rejected;
|
||
},
|
||
.ok => |text| text,
|
||
};
|
||
if (mode == .stdout) {
|
||
try out.writeAll(text);
|
||
return .accepted;
|
||
}
|
||
const changed = !std.mem.eql(u8, input.source, text);
|
||
if (mode == .write) {
|
||
const dir = std.Io.Dir.cwd();
|
||
if (changed) {
|
||
var file = dir.createFileAtomic(io, path, .{ .replace = true, .permissions = permissions.? }) catch |err| {
|
||
std.debug.print("aji: {s}: {t}\n", .{ path, err });
|
||
return .usage;
|
||
};
|
||
defer file.deinit(io);
|
||
// Creation may apply umask; restore the complete original mode.
|
||
file.file.setPermissions(io, permissions.?) catch |err| {
|
||
std.debug.print("aji: {s}: {t}\n", .{ path, err });
|
||
return .usage;
|
||
};
|
||
var buffer: [4096]u8 = undefined;
|
||
var writer = file.file.writer(io, &buffer);
|
||
writer.interface.writeAll(text) catch |err| {
|
||
std.debug.print("aji: {s}: {t}\n", .{ path, writer.err orelse err });
|
||
return .usage;
|
||
};
|
||
writer.flush() catch |err| {
|
||
std.debug.print("aji: {s}: {t}\n", .{ path, err });
|
||
return .usage;
|
||
};
|
||
file.replace(io) catch |err| {
|
||
std.debug.print("aji: {s}: {t}\n", .{ path, err });
|
||
return .usage;
|
||
};
|
||
}
|
||
}
|
||
var json: std.json.Stringify = .{ .writer = out };
|
||
try json.write(.{ .file = path, .status = if (mode == .check and changed) "needs_format" else "formatted", .changed = changed });
|
||
try out.writeByte('\n');
|
||
return if (mode == .check and changed) .rejected else .accepted;
|
||
}
|
||
|
||
fn readInput(arena: std.mem.Allocator, io: std.Io, path: []const u8, from_manifest: bool) !?aji.source_package.Input {
|
||
return switch (if (from_manifest) try aji.source_package.load(arena, io, path) else try aji.source_package.single(arena, io, path)) {
|
||
.ok => |input| input,
|
||
.err => |err| blk: {
|
||
std.debug.print("aji: {s}:{d}: {s}\n", .{ err.path, err.line, err.message });
|
||
break :blk null;
|
||
},
|
||
};
|
||
}
|
||
|
||
fn mergeGrants(arena: std.mem.Allocator, baseline: []const aji.manifest.Grant, overrides: []const aji.interp.Grant) ![]const aji.interp.Grant {
|
||
var result: std.ArrayList(aji.interp.Grant) = .empty;
|
||
for (baseline) |grant| {
|
||
const replaced = for (overrides) |override| {
|
||
if (std.mem.eql(u8, grant.parameter, override.parameter)) break true;
|
||
} else false;
|
||
if (!replaced) try result.append(arena, .{ .parameter = grant.parameter, .kind = grant.kind, .scope = grant.scope });
|
||
}
|
||
try result.appendSlice(arena, overrides);
|
||
return result.items;
|
||
}
|