cli: add explicit package source modules
Link manifest-selected source graphs with module-local names, qualified structs/enums/functions and task workers through ordinary AIR verification. Keep source inputs bounded, reject source symlinks and preserve explicit grants, diagnostics and deterministic canonical lowering. Integrate spec 12/15, RFC 0021, source reference budgets, roadmap, examples and CI coverage. Validate 579 conformance tests, unit tests, 76 source constructs, hosted smoke, 36 package CLI checks and task schedule stress.
This commit is contained in:
81 files changed
+1419
-234
No files matched your search
+70
-1
@@ -30,8 +30,12 @@ pub const Report = struct {
|
||||
/// Checks a `.aji` module (frontend, then the AIR pipeline, with every
|
||||
/// diagnostic at its source location) or a text AIR module.
|
||||
pub fn checkFile(arena: std.mem.Allocator, file_name: []const u8, source: []const u8) !Report {
|
||||
return checkWithModules(arena, file_name, source, &.{});
|
||||
}
|
||||
|
||||
pub fn checkWithModules(arena: std.mem.Allocator, file_name: []const u8, source: []const u8, sources: []const frontend.modules.Source) !Report {
|
||||
if (!std.mem.endsWith(u8, file_name, ".aji")) return checkAir(arena, file_name, source);
|
||||
const lowered = switch (try frontend.compile(arena, file_name, source)) {
|
||||
const lowered = switch (try frontend.compileWithModules(arena, file_name, source, sources)) {
|
||||
.ok => |o| o,
|
||||
.err => |d| return .{ .status = .rejected, .diagnostics = try arena.dupe(diag.Diagnostic, &.{d}) },
|
||||
.unimplemented => |what| return .{ .status = .unimplemented, .diagnostics = &.{}, .missing_stage = what },
|
||||
@@ -168,3 +172,68 @@ test "standard type diagnostics use the public source name" {
|
||||
try std.testing.expectEqualStrings(case.found, found);
|
||||
}
|
||||
}
|
||||
|
||||
test "package module order, nominal names and diagnostic paths are independent" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const a: frontend.modules.Source = .{ .name = "app.a", .file = "same.aji", .source = "module app.a\nstruct Pair { value: u64 }\nfn value(p: Pair) -> u64 effects [] { return p.value; }\n" };
|
||||
const b: frontend.modules.Source = .{ .name = "app.b", .file = "same.aji", .source = "module app.b\nimport app.a;\nfn value() -> u64 effects [] { return app.a.value(app.a.Pair { value: 42 }); }\n" };
|
||||
const body = "fn main() -> u64 effects [] { return app.b.value(); }\n";
|
||||
const first = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.a;\nimport app.b;\n" ++ body, &.{ a, b });
|
||||
const second = try checkWithModules(arena, "/elsewhere/root.aji", "module app.entry\nimport app.b;\nimport app.a;\n" ++ body, &.{ b, a });
|
||||
try std.testing.expectEqual(Status.accepted, first.status);
|
||||
try std.testing.expectEqual(Status.accepted, second.status);
|
||||
try std.testing.expectEqualStrings(first.lowered.?.air, second.lowered.?.air);
|
||||
try std.testing.expect(std.mem.indexOf(u8, first.lowered.?.annotated, "; same.aji:") != null);
|
||||
const bad = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.b;\nfn main() -> u64 effects [] { let p: app.a.Pair = app.a.Pair { value: 42 }; return 0; }", &.{ a, b });
|
||||
try std.testing.expectEqualStrings("E7002", bad.diagnostics[0].code.id);
|
||||
}
|
||||
|
||||
test "module syntax and verifier errors retain imported source provenance" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const root = "module app.entry\nimport app.lib;\nfn main() -> u64 effects [] { return 42; }";
|
||||
const syntax = try checkWithModules(arena, "entry.aji", root, &.{.{ .name = "app.lib", .file = "src/lib.aji", .source = "module app.lib\nfn broken(" }});
|
||||
try std.testing.expectEqualStrings("E7001", syntax.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("src/lib.aji", syntax.diagnostics[0].span.?.file);
|
||||
try std.testing.expectEqualStrings("expected", syntax.diagnostics[0].fields[0].name);
|
||||
const alias = try checkWithModules(arena, "entry.aji", root, &.{.{ .name = "app.lib", .file = "src/lib.aji", .source = "module app.lib\nfn broken() -> u8 effects [] { var b: [u8; 4] = zero; ref held = b; b[0] = 1; return held[0]; }" }});
|
||||
try std.testing.expectEqualStrings("E2101", alias.diagnostics[0].code.id);
|
||||
try std.testing.expectEqualStrings("src/lib.aji", alias.diagnostics[0].span.?.file);
|
||||
}
|
||||
|
||||
test "module graph depth is bounded even with a cached shared tail" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
var sources: std.ArrayList(frontend.modules.Source) = .empty;
|
||||
for (0..257) |i| {
|
||||
const name = try std.fmt.allocPrint(arena, "app.m{d}", .{i});
|
||||
const source = if (i == 256) try std.fmt.allocPrint(arena, "module {s}\n", .{name}) else try std.fmt.allocPrint(arena, "module {s}\nimport app.m{d};\n", .{ name, i + 1 });
|
||||
try sources.append(arena, .{ .name = name, .file = name, .source = source });
|
||||
}
|
||||
const prefix = "module app.entry\nimport app.m200;\nimport app.m0;\nfn main() -> u64 effects [] { return 42; }";
|
||||
const excessive = try checkWithModules(arena, "root.aji", prefix, sources.items);
|
||||
try std.testing.expectEqualStrings("E7006", excessive.diagnostics[0].code.id);
|
||||
const valid = try checkWithModules(arena, "root.aji", "module app.entry\nimport app.m1;\nfn main() -> u64 effects [] { return 42; }", sources.items);
|
||||
try std.testing.expectEqual(Status.accepted, valid.status);
|
||||
const many = try arena.alloc(frontend.modules.Source, 1025);
|
||||
@memset(many, sources.items[0]);
|
||||
const limited = try checkWithModules(arena, "root.aji", prefix, many);
|
||||
try std.testing.expectEqualStrings("E7006", limited.diagnostics[0].code.id);
|
||||
}
|
||||
|
||||
test "qualified module names are not limited by builtin path storage" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const component = try arena.alloc(u8, 300);
|
||||
@memset(component, 'a');
|
||||
const name = try std.fmt.allocPrint(arena, "app.{s}", .{component});
|
||||
const source = try std.fmt.allocPrint(arena, "module {s}\nstruct Pair {{ value: u64 }}\nfn total(p: Pair) -> u64 effects [] {{ return p.value; }}", .{name});
|
||||
const entry = try std.fmt.allocPrint(arena, "module app.entry\nimport {s};\nfn main() -> u64 effects [] {{ return {s}.total({s}.Pair {{ value: 42 }}); }}", .{ name, name, name });
|
||||
const checked = try checkWithModules(arena, "root.aji", entry, &.{.{ .name = name, .file = "lib.aji", .source = source }});
|
||||
try std.testing.expectEqual(Status.accepted, checked.status);
|
||||
}
|
||||
+6
-1
@@ -8,6 +8,7 @@ pub const lex = @import("frontend/lex.zig");
|
||||
pub const ast = @import("frontend/ast.zig");
|
||||
pub const parse = @import("frontend/parse.zig");
|
||||
pub const lower_mod = @import("frontend/lower.zig");
|
||||
pub const modules = @import("frontend/modules.zig");
|
||||
pub const stdlib = @import("frontend/stdlib.zig");
|
||||
|
||||
pub const Span = ast.Span;
|
||||
@@ -21,6 +22,10 @@ pub const Compiled = union(enum) {
|
||||
};
|
||||
|
||||
pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) std.mem.Allocator.Error!Compiled {
|
||||
return compileWithModules(arena, file, source, &.{});
|
||||
}
|
||||
|
||||
pub fn compileWithModules(arena: std.mem.Allocator, file: []const u8, source: []const u8, sources: []const modules.Source) std.mem.Allocator.Error!Compiled {
|
||||
const parsed = try parse.parse(arena, source);
|
||||
const m = switch (parsed) {
|
||||
.ok => |m| m,
|
||||
@@ -34,7 +39,7 @@ pub fn compile(arena: std.mem.Allocator, file: []const u8, source: []const u8) s
|
||||
}),
|
||||
} },
|
||||
};
|
||||
const linked = try stdlib.link(arena, m);
|
||||
const linked = try modules.link(arena, m, sources);
|
||||
const result = switch (linked) {
|
||||
.ok => |combined| try lower_mod.lower(arena, combined),
|
||||
.err => |p| lower_mod.Result{ .err = p },
|
||||
|
||||
@@ -6,7 +6,7 @@ const lex = @import("lex.zig");
|
||||
|
||||
pub const Pos = lex.Pos;
|
||||
|
||||
pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null };
|
||||
pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null, namespace: ?[]const u8 = null };
|
||||
|
||||
pub const Type = struct {
|
||||
span: Span,
|
||||
@@ -168,7 +168,7 @@ pub const Variant = struct { name: []const u8, payload: []const Type, span: Span
|
||||
|
||||
pub const TypeDecl = struct {
|
||||
name: []const u8,
|
||||
/// Linker-chosen AIR identifier for a qualified standard type.
|
||||
/// Linker-chosen AIR identifier for a qualified imported type.
|
||||
air_name: ?[]const u8 = null,
|
||||
span: Span,
|
||||
kind: union(enum) { @"struct": []const Field, @"enum": []const Variant },
|
||||
@@ -178,7 +178,7 @@ pub const Param = struct { name: []const u8, ty: Type, span: Span };
|
||||
|
||||
pub const FnDecl = struct {
|
||||
name: []const u8,
|
||||
/// Linker-chosen AIR identifier for a qualified standard function.
|
||||
/// Linker-chosen AIR identifier for a qualified imported function.
|
||||
air_name: ?[]const u8 = null,
|
||||
span: Span,
|
||||
params: []const Param,
|
||||
@@ -192,8 +192,12 @@ pub const FnDecl = struct {
|
||||
pub const Module = struct {
|
||||
name: []const u8,
|
||||
imports: []const Import = &.{},
|
||||
scopes: []const ModuleScope = &.{},
|
||||
types: []const TypeDecl,
|
||||
functions: []const FnDecl,
|
||||
};
|
||||
|
||||
pub const Import = struct { path: []const u8, span: Span };
|
||||
|
||||
/// Source name resolution stays separate from diagnostic file paths.
|
||||
pub const ModuleScope = struct { name: []const u8, entry: bool, qualified_self: bool = true, imports: []const Import };
|
||||
+77
-31
@@ -530,7 +530,7 @@ const Lowerer = struct {
|
||||
if (std.mem.eql(u8, n, "bool")) return .bool;
|
||||
if (std.mem.eql(u8, n, "void")) return .void;
|
||||
if (std.mem.eql(u8, n, "never")) return .never;
|
||||
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
|
||||
if (l.enumOrStruct(n, t.span)) |ty| return ty;
|
||||
if (std.mem.eql(u8, n, "region")) return .region;
|
||||
if (std.meta.stringToEnum(authority.Builtin, n)) |b| return .{ .builtin = b };
|
||||
if (std.mem.eql(u8, n, "stream")) return .{ .resource = .stream };
|
||||
@@ -1109,12 +1109,47 @@ const Lowerer = struct {
|
||||
|
||||
/// The type of an expression without lowering it, where it follows
|
||||
/// from names, suffixes, casts and calls; null otherwise.
|
||||
fn sourceScope(l: *Lowerer, span: Span) ?ast.ModuleScope {
|
||||
const name = span.namespace orelse l.m.name;
|
||||
for (l.m.scopes) |scope| if (std.mem.eql(u8, scope.name, name)) return scope;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn boundName(l: *Lowerer, name: []const u8, span: Span) ?[]const u8 {
|
||||
const scope = l.sourceScope(span) orelse return name;
|
||||
if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| {
|
||||
const owner = name[0..at];
|
||||
if (std.mem.eql(u8, owner, scope.name)) return if (!scope.qualified_self) null else if (scope.entry) name[at + 1 ..] else name;
|
||||
for (scope.imports) |imp| if (std.mem.eql(u8, imp.path, owner)) return name;
|
||||
return null;
|
||||
}
|
||||
if (scope.entry) return name;
|
||||
for (l.m.types) |t| if (localName(t.name, scope.name, name)) return t.name;
|
||||
for (l.m.functions) |f| if (localName(f.name, scope.name, name)) return f.name;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn functionSig(l: *Lowerer, name: []const u8, span: Span) ?FnSig {
|
||||
return l.sigs.get(l.boundName(name, span) orelse return null);
|
||||
}
|
||||
|
||||
fn calleeSig(l: *Lowerer, e: ast.Expr) ?FnSig {
|
||||
if (e.kind == .name) return l.sigs.get(e.kind.name);
|
||||
var buf: [256]u8 = undefined;
|
||||
const name = dotted(e, &buf) orelse return null;
|
||||
if (!std.mem.startsWith(u8, name, "std.")) return null;
|
||||
return l.sigs.get(name);
|
||||
const name = expressionPath(l.arena, e) catch return null;
|
||||
return l.functionSig(name orelse return null, e.span);
|
||||
}
|
||||
|
||||
fn moduleCall(l: *Lowerer, e: ast.Expr) Error!?[]const u8 {
|
||||
if (e.kind != .field) return null;
|
||||
const name = try expressionPath(l.arena, e) orelse return null;
|
||||
if (standardPath(e)) return name;
|
||||
if (pathOf(e) != null) return null;
|
||||
const owner = name[0..std.mem.lastIndexOfScalar(u8, name, '.').?];
|
||||
for (l.m.scopes) |scope| if (std.mem.eql(u8, owner, scope.name)) return name;
|
||||
if (l.sourceScope(e.span)) |scope| for (scope.imports) |imp| if (std.mem.eql(u8, owner, imp.path)) return name;
|
||||
var root = e;
|
||||
while (root.kind == .field) root = root.kind.field.e.*;
|
||||
if (root.kind == .name and l.lookup(root.kind.name) == null) return name;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
|
||||
@@ -1134,13 +1169,13 @@ const Lowerer = struct {
|
||||
else => l.peekType(x.l.*) orelse l.peekType(x.r.*),
|
||||
},
|
||||
.call => |x| switch (x.callee.kind) {
|
||||
.name => |n| if (l.sigs.get(n)) |sig| sig.ret else null,
|
||||
.variant => |v| l.enumType(v.@"enum"),
|
||||
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
|
||||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||||
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null,
|
||||
},
|
||||
.move => |n| if (l.lookup(n)) |b| b.ty else null,
|
||||
.variant => |v| l.enumType(v.@"enum"),
|
||||
.struct_lit => |x| l.enumOrStruct(x.name),
|
||||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||||
.struct_lit => |x| l.enumOrStruct(x.name, e.span),
|
||||
.field => |x| blk: {
|
||||
if (std.mem.eql(u8, x.name, "len")) break :blk Ty{ .int = "usize" };
|
||||
var base = l.peekType(x.e.*) orelse break :blk null;
|
||||
@@ -1232,18 +1267,19 @@ const Lowerer = struct {
|
||||
|
||||
fn typeOfNoFail(l: *Lowerer, t: ast.Type) ?Ty {
|
||||
return switch (t.kind) {
|
||||
.name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else l.enumOrStruct(n),
|
||||
.name => |n| if (isIntName(n)) Ty{ .int = n } else if (std.mem.eql(u8, n, "bool")) .bool else l.enumOrStruct(n, t.span),
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
|
||||
fn enumOrStruct(l: *Lowerer, n: []const u8) ?Ty {
|
||||
fn enumOrStruct(l: *Lowerer, name: []const u8, span: Span) ?Ty {
|
||||
const n = l.boundName(name, span) orelse return null;
|
||||
for (l.m.types, 0..) |d, i| if (std.mem.eql(u8, d.name, n)) return .{ .named = @intCast(i) };
|
||||
return null;
|
||||
}
|
||||
|
||||
fn enumType(l: *Lowerer, n: []const u8) ?Ty {
|
||||
const t = l.enumOrStruct(n) orelse return null;
|
||||
fn enumType(l: *Lowerer, n: []const u8, span: Span) ?Ty {
|
||||
const t = l.enumOrStruct(n, span) orelse return null;
|
||||
return if (l.m.types[t.named].kind == .@"enum") t else null;
|
||||
}
|
||||
|
||||
@@ -1429,9 +1465,7 @@ const Lowerer = struct {
|
||||
|
||||
fn call(l: *Lowerer, e: ast.Expr, callee: ast.Expr, args: []const ast.Expr) Error!Value {
|
||||
if (callee.kind == .variant) return l.variantValue(e, callee.kind.variant.@"enum", callee.kind.variant.name, args);
|
||||
var buf: [256]u8 = undefined;
|
||||
if (standardPath(callee)) {
|
||||
const name = dotted(callee, &buf) orelse return l.unknown(callee.span, callee.kind.field.name);
|
||||
if (try l.moduleCall(callee)) |name| {
|
||||
// Reuse ordinary call typing/borrowing/lowering, including E7002.
|
||||
const owned_name = try l.arena.dupe(u8, name);
|
||||
return l.call(e, .{ .span = callee.span, .kind = .{ .name = owned_name } }, args);
|
||||
@@ -1496,7 +1530,7 @@ const Lowerer = struct {
|
||||
try l.emit(try l.fmt("assume %{s}", .{v.name}), e.span);
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
const sig = l.sigs.get(name) orelse return l.unknown(callee.span, name);
|
||||
const sig = l.functionSig(name, callee.span) orelse return l.unknown(callee.span, name);
|
||||
if (args.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = name }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{args.len}) } });
|
||||
var arg_names: std.ArrayList(u8) = .empty;
|
||||
var temps: std.ArrayList([]const u8) = .empty;
|
||||
@@ -1515,14 +1549,14 @@ const Lowerer = struct {
|
||||
}
|
||||
return .{ .name = "", .ty = .void };
|
||||
}
|
||||
return l.def(if (std.mem.startsWith(u8, name, "std.")) "std_call" else name, sig.ret, text, e.span);
|
||||
return l.def(if (std.mem.startsWith(u8, name, "std.")) "std_call" else if (std.mem.indexOfScalar(u8, name, '.') != null) "module_call" else name, sig.ret, text, e.span);
|
||||
}
|
||||
|
||||
/// `Name { f: e, … }`: every field exactly once; initializers are
|
||||
/// evaluated in declaration order, so the AIR does not depend on the
|
||||
/// order the fields are written in (spec 15 §5).
|
||||
fn structLit(l: *Lowerer, e: ast.Expr, name: []const u8, inits: []const ast.FieldInit) Error!Value {
|
||||
const t = l.enumOrStruct(name) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||||
const t = l.enumOrStruct(name, e.span) orelse return l.fail("E7002", e.span, "unknown type", &.{.{ .name = "name", .value = name }});
|
||||
const d = l.m.types[t.named];
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "`Name { … }` constructs a struct; this is an enum (use `Enum::Variant`)", &.{.{ .name = "type", .value = name }});
|
||||
const fields = d.kind.@"struct";
|
||||
@@ -1547,7 +1581,7 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
fn variantValue(l: *Lowerer, e: ast.Expr, enum_name: []const u8, variant: []const u8, args: []const ast.Expr) Error!Value {
|
||||
const t = l.enumType(enum_name) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
|
||||
const t = l.enumType(enum_name, e.span) orelse return l.fail("E7002", e.span, "unknown enum", &.{.{ .name = "name", .value = enum_name }});
|
||||
const vs = l.m.types[t.named].kind.@"enum";
|
||||
const v = for (vs) |x| {
|
||||
if (std.mem.eql(u8, x.name, variant)) break x;
|
||||
@@ -1580,7 +1614,7 @@ const Lowerer = struct {
|
||||
return v;
|
||||
};
|
||||
const v = try l.expr(base, bt);
|
||||
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.name, name, v.name }), e.span);
|
||||
return l.def(name, try l.typeOf(f.ty), try l.fmt("struct.get @{s}.{s}, %{s}", .{ d.air_name orelse d.name, name, v.name }), e.span);
|
||||
}
|
||||
|
||||
/// One branch of a conditional or `match`: where it ended (null if it
|
||||
@@ -1646,8 +1680,9 @@ const Lowerer = struct {
|
||||
if (arm.pattern.kind != .ctor or arm.pattern.kind.ctor.qualifier == null)
|
||||
return l.fail("E7006", arm.pattern.span, "an arm of a `match` over an enum names one variant as `Enum::Variant`; `_` is not allowed", &.{.{ .name = "enum", .value = d.name }});
|
||||
const c = arm.pattern.kind.ctor;
|
||||
if (std.mem.startsWith(u8, c.qualifier.?, "std.") and l.enumType(c.qualifier.?) == null) return l.unknown(arm.pattern.span, c.qualifier.?);
|
||||
if (!std.mem.eql(u8, c.qualifier.?, d.name)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.name }, .{ .name = "found", .value = c.qualifier.? } });
|
||||
const pattern_type = l.enumType(c.qualifier.?, arm.pattern.span);
|
||||
if (std.mem.indexOfScalar(u8, c.qualifier.?, '.') != null and pattern_type == null) return l.unknown(arm.pattern.span, c.qualifier.?);
|
||||
if (pattern_type == null or !Ty.eql(st, pattern_type.?)) return l.fail("E7005", arm.pattern.span, "variant of a different enum", &.{ .{ .name = "expected", .value = d.name }, .{ .name = "found", .value = c.qualifier.? } });
|
||||
const vi = for (vs, 0..) |v, k| {
|
||||
if (std.mem.eql(u8, v.name, c.name)) break k;
|
||||
} else return l.fail("E7002", arm.pattern.span, "no such variant", &.{ .{ .name = "enum", .value = d.name }, .{ .name = "variant", .value = c.name } });
|
||||
@@ -1781,8 +1816,8 @@ const Lowerer = struct {
|
||||
if (eq(u8, p, "arc.from_frozen") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null) else null;
|
||||
if (eq(u8, p, "arc.clone") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
|
||||
if (eq(u8, p, "channel.dup") and args.len == 1) return if (l.peekType(args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
|
||||
if (eq(u8, p, "task.spawn") and args.len >= 2 and args[1].kind == .name) {
|
||||
const sig = l.sigs.get(args[1].kind.name) orelse return null;
|
||||
if (eq(u8, p, "task.spawn") and args.len >= 2) {
|
||||
const sig = l.calleeSig(args[1]) orelse return null;
|
||||
return l.wrap(.task, sig.ret) catch null;
|
||||
}
|
||||
return null;
|
||||
@@ -1979,7 +2014,7 @@ const Lowerer = struct {
|
||||
if (std.mem.eql(u8, x.name, f.name)) break x;
|
||||
} else return l.fail("E7002", place.span, "no such field", &.{ .{ .name = "type", .value = d.name }, .{ .name = "field", .value = f.name } });
|
||||
const ft = try l.typeOf(fd.ty);
|
||||
const v = try l.def(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.name, f.name, base.v.name }), span);
|
||||
const v = try l.def(f.name, if (base.v.ty.isMutBorrow()) try l.wrap(.mut, ft) else try l.wrap(.ref, ft), try l.fmt("borrow.field @{s}.{s}, %{s}", .{ d.air_name orelse d.name, f.name, base.v.name }), span);
|
||||
return .{ .v = v, .ends = try l.concat(base.ends, v.name) };
|
||||
},
|
||||
.index => |x| {
|
||||
@@ -2345,9 +2380,8 @@ const Lowerer = struct {
|
||||
const sb = try l.bindingOf(args[0], "a task scope");
|
||||
if (sb.ty != .scope) return l.fail("E7005", args[0].span, "`task.spawn` spawns into a scope: `scope s { … task.spawn(s, f, …) … }`", &.{.{ .name = "found", .value = l.diagnosticTyText(sb.ty) }});
|
||||
const scope_name = sb.value;
|
||||
if (args[1].kind != .name) return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
|
||||
const fname = args[1].kind.name;
|
||||
const sig = l.sigs.get(fname) orelse return l.unknown(args[1].span, fname);
|
||||
const fname = try expressionPath(l.arena, args[1]) orelse return l.fail("E7005", args[1].span, "the function to spawn is named", &.{});
|
||||
const sig = l.functionSig(fname, args[1].span) orelse return l.unknown(args[1].span, fname);
|
||||
const fargs = args[2..];
|
||||
if (fargs.len != sig.params.len) return l.fail("E7005", e.span, "wrong number of arguments", &.{ .{ .name = "function", .value = fname }, .{ .name = "expected", .value = try l.fmt("{d}", .{sig.params.len}) }, .{ .name = "found", .value = try l.fmt("{d}", .{fargs.len}) } });
|
||||
var names: std.ArrayList(u8) = .empty;
|
||||
@@ -2359,7 +2393,7 @@ const Lowerer = struct {
|
||||
try l.checkTy(a.span, v.ty, pt);
|
||||
try names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
|
||||
}
|
||||
return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, fname, names.items }), e.span);
|
||||
return try l.def("t", try l.wrap(.task, sig.ret), try l.fmt("task.spawn %{s}, @{s}({s})", .{ scope_name, sig.air_name, names.items }), e.span);
|
||||
}
|
||||
if (eq(p, "task.join")) {
|
||||
if (args.len != 1) return l.fail("E7005", e.span, "`task.join` takes one task", &.{});
|
||||
@@ -3450,3 +3484,15 @@ fn selectAssigns(x: ast.Select, name: []const u8) bool {
|
||||
for (x.cancelled_binds) |b| if (std.mem.eql(u8, b, name)) return true;
|
||||
return exprAssigns(x.cancelled, name);
|
||||
}
|
||||
|
||||
fn localName(full: []const u8, module: []const u8, short: []const u8) bool {
|
||||
return full.len == module.len + 1 + short.len and std.mem.startsWith(u8, full, module) and full[module.len] == '.' and std.mem.eql(u8, full[module.len + 1 ..], short);
|
||||
}
|
||||
|
||||
fn expressionPath(arena: Allocator, e: ast.Expr) Allocator.Error!?[]const u8 {
|
||||
return switch (e.kind) {
|
||||
.name => |name| name,
|
||||
.field => |field| if (try expressionPath(arena, field.e.*)) |base| try std.fmt.allocPrint(arena, "{s}.{s}", .{ base, field.name }) else null,
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Pure linking of explicit source inputs; no filesystem or authority.
|
||||
const std = @import("std");
|
||||
const ast = @import("ast.zig");
|
||||
const parse = @import("parse.zig");
|
||||
const lower = @import("lower.zig");
|
||||
const stdlib = @import("stdlib.zig");
|
||||
const authority = @import("../air/authority.zig");
|
||||
|
||||
pub const Source = stdlib.Source;
|
||||
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem };
|
||||
const Error = error{ OutOfMemory, InvalidSource };
|
||||
const Node = struct { module: ast.Module, active: bool, height: usize = 0 };
|
||||
|
||||
pub fn reserved(name: []const u8) bool {
|
||||
const first = if (std.mem.indexOfScalar(u8, name, '.')) |at| name[0..at] else name;
|
||||
for ([_][]const u8{ "std", "slice", "own", "region", "cap", "task", "channel", "mutex", "island", "frozen", "arc", "atomic" }) |word| {
|
||||
if (std.mem.eql(u8, first, word)) return true;
|
||||
}
|
||||
for (authority.intrinsics) |intrinsic| {
|
||||
const at = std.mem.indexOfScalar(u8, intrinsic.name, '.').?;
|
||||
if (std.mem.eql(u8, first, intrinsic.name[0..at])) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
pub fn link(arena: std.mem.Allocator, entry: ast.Module, sources: []const Source) std.mem.Allocator.Error!Result {
|
||||
var g: Graph = .{ .arena = arena, .sources = sources };
|
||||
const span: ast.Span = if (entry.functions.len != 0) entry.functions[0].span else .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } };
|
||||
const combined = g.run(entry, span) catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
error.InvalidSource => return .{ .err = g.problem.? },
|
||||
};
|
||||
return .{ .ok = combined };
|
||||
}
|
||||
|
||||
const Graph = struct {
|
||||
arena: std.mem.Allocator,
|
||||
sources: []const Source,
|
||||
nodes: std.ArrayList(Node) = .empty,
|
||||
problem: ?lower.Problem = null,
|
||||
|
||||
fn fail(g: *Graph, code: []const u8, span: ast.Span, message: []const u8, name: []const u8) Error {
|
||||
g.problem = .{ .code = code, .span = span, .message = message, .fields = g.arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = name }}) catch return error.OutOfMemory };
|
||||
return error.InvalidSource;
|
||||
}
|
||||
|
||||
fn run(g: *Graph, entry: ast.Module, span: ast.Span) Error!ast.Module {
|
||||
if (g.sources.len > 1024) return g.fail("E7006", span, "more than 1024 mapped modules", entry.name);
|
||||
for (g.sources, 0..) |source, i| {
|
||||
if (reserved(source.name)) return g.fail("E7006", span, "package mapping uses a reserved namespace", source.name);
|
||||
for (g.sources[0..i]) |previous| if (std.mem.eql(u8, previous.name, source.name)) return g.fail("E7006", span, "module mapped twice", source.name);
|
||||
}
|
||||
try g.nodes.append(g.arena, .{ .module = entry, .active = true });
|
||||
const root_height = try g.imports(entry, 0);
|
||||
g.nodes.items[0].height = root_height;
|
||||
g.nodes.items[0].active = false;
|
||||
std.mem.sort(Node, g.nodes.items[1..], {}, struct {
|
||||
fn less(_: void, a: Node, b: Node) bool {
|
||||
return std.mem.lessThan(u8, a.module.name, b.module.name);
|
||||
}
|
||||
}.less);
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
var functions: std.ArrayList(ast.FnDecl) = .empty;
|
||||
var scopes: std.ArrayList(ast.ModuleScope) = .empty;
|
||||
try types.appendSlice(g.arena, entry.types);
|
||||
try functions.appendSlice(g.arena, entry.functions);
|
||||
for (g.nodes.items, 0..) |node, i| {
|
||||
const m = node.module;
|
||||
try scopes.append(g.arena, .{ .name = m.name, .entry = i == 0, .qualified_self = i != 0 or !reserved(m.name), .imports = m.imports });
|
||||
if (i == 0) continue;
|
||||
for (m.types) |t| {
|
||||
var qualified = t;
|
||||
qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, t.name });
|
||||
qualified.air_name = try airName(g.arena, m.name, t.name, types.items, functions.items);
|
||||
try types.append(g.arena, qualified);
|
||||
}
|
||||
for (m.functions) |f| {
|
||||
var qualified = f;
|
||||
qualified.name = try std.fmt.allocPrint(g.arena, "{s}.{s}", .{ m.name, f.name });
|
||||
qualified.air_name = try airName(g.arena, m.name, f.name, types.items, functions.items);
|
||||
try functions.append(g.arena, qualified);
|
||||
}
|
||||
}
|
||||
var result = entry;
|
||||
result.types = types.items;
|
||||
result.functions = functions.items;
|
||||
result.scopes = scopes.items;
|
||||
return result;
|
||||
}
|
||||
|
||||
fn imports(g: *Graph, m: ast.Module, depth: usize) Error!usize {
|
||||
var height: usize = 0;
|
||||
for (m.imports, 0..) |imp, i| {
|
||||
for (m.imports[0..i]) |previous| if (std.mem.eql(u8, imp.path, previous.path)) return g.fail("E7006", imp.span, "module imported twice", imp.path);
|
||||
height = @max(height, 1 + try g.visit(imp, depth + 1));
|
||||
}
|
||||
return height;
|
||||
}
|
||||
|
||||
fn visit(g: *Graph, imp: ast.Import, depth: usize) Error!usize {
|
||||
for (g.nodes.items) |node| if (std.mem.eql(u8, node.module.name, imp.path)) {
|
||||
if (node.active) return g.fail("E7006", imp.span, "cyclic module import", imp.path);
|
||||
if (depth + node.height > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path);
|
||||
return node.height;
|
||||
};
|
||||
if (depth > 256) return g.fail("E7006", imp.span, "module import depth exceeds 256", imp.path);
|
||||
const source = for (stdlib.registry) |source| {
|
||||
if (std.mem.eql(u8, source.name, imp.path)) break source;
|
||||
} else for (g.sources) |source| {
|
||||
if (std.mem.eql(u8, source.name, imp.path)) break source;
|
||||
} else return g.fail("E7002", imp.span, "unknown module in explicit source mapping", imp.path);
|
||||
const m = switch (try parse.parseWithFile(g.arena, source.source, source.file)) {
|
||||
.ok => |m| m,
|
||||
.err => |failure| {
|
||||
g.problem = .{
|
||||
.code = if (std.mem.startsWith(u8, source.name, "std.")) "E7900" else "E7001",
|
||||
.span = .{ .start = failure.pos, .end = failure.pos, .file = source.file, .namespace = source.name },
|
||||
.message = try std.fmt.allocPrint(g.arena, "expected {s}", .{failure.expected}),
|
||||
.fields = try g.arena.dupe(lower.Problem.Field, &.{ .{ .name = "expected", .value = failure.expected }, .{ .name = "found", .value = failure.found } }),
|
||||
};
|
||||
return error.InvalidSource;
|
||||
},
|
||||
};
|
||||
if (!std.mem.eql(u8, m.name, source.name)) return g.fail("E7006", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 }, .file = source.file, .namespace = source.name }, "module header differs from its mapped name", source.name);
|
||||
const index = g.nodes.items.len;
|
||||
try g.nodes.append(g.arena, .{ .module = m, .active = true });
|
||||
const height = try g.imports(m, depth);
|
||||
g.nodes.items[index].height = height;
|
||||
g.nodes.items[index].active = false;
|
||||
return g.nodes.items[index].height;
|
||||
}
|
||||
};
|
||||
|
||||
fn airName(arena: std.mem.Allocator, module: []const u8, name: []const u8, types: []const ast.TypeDecl, functions: []const ast.FnDecl) std.mem.Allocator.Error![]const u8 {
|
||||
const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ module, name });
|
||||
for (base) |*c| if (c.* == '.') {
|
||||
c.* = '_';
|
||||
};
|
||||
var candidate: []const u8 = base;
|
||||
var suffix: usize = 0;
|
||||
while (used(types, functions, candidate)) {
|
||||
suffix += 1;
|
||||
candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
fn used(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool {
|
||||
for (types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true;
|
||||
for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
+27
-14
@@ -36,6 +36,7 @@ const Parser = struct {
|
||||
pos: usize = 0,
|
||||
failure: ?Failure = null,
|
||||
file: ?[]const u8 = null,
|
||||
module_name: ?[]const u8 = null,
|
||||
/// Struct literals are not allowed where a `{` starts a block (conditions).
|
||||
no_struct: bool = false,
|
||||
|
||||
@@ -104,7 +105,7 @@ const Parser = struct {
|
||||
}
|
||||
|
||||
fn span(p: *Parser, start: lex.Pos) ast.Span {
|
||||
return .{ .start = start, .end = p.prevEnd(), .file = p.file };
|
||||
return .{ .start = start, .end = p.prevEnd(), .file = p.file, .namespace = p.module_name };
|
||||
}
|
||||
|
||||
fn box(p: *Parser, comptime T: type, v: T) Error!*const T {
|
||||
@@ -118,6 +119,7 @@ const Parser = struct {
|
||||
fn module(p: *Parser) Error!ast.Module {
|
||||
_ = try p.expectWord("module");
|
||||
const name = try p.path();
|
||||
p.module_name = name;
|
||||
var imports: std.ArrayList(ast.Import) = .empty;
|
||||
while (p.atWord("import")) {
|
||||
const start = p.next().pos;
|
||||
@@ -658,6 +660,13 @@ const Parser = struct {
|
||||
e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = ty, .args = args } } };
|
||||
}
|
||||
},
|
||||
.l_brace => {
|
||||
if (p.no_struct) return e;
|
||||
const name = try p.exprPath(e) orelse return e;
|
||||
const last = if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name;
|
||||
if (!std.ascii.isUpper(last[0])) return e;
|
||||
e = try p.structLiteral(start, name);
|
||||
},
|
||||
.l_paren => {
|
||||
const args = try p.callArgs();
|
||||
const callee = try p.box(ast.Expr, e);
|
||||
@@ -722,6 +731,22 @@ const Parser = struct {
|
||||
};
|
||||
}
|
||||
|
||||
fn structLiteral(p: *Parser, start: lex.Pos, name: []const u8) Error!ast.Expr {
|
||||
_ = try p.expect(.l_brace, "`{`");
|
||||
var fields: std.ArrayList(ast.FieldInit) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fs = p.peek().pos;
|
||||
const fname = try p.ident("a field name");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const fe = try p.expr();
|
||||
try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = name, .fields = fields.items } } };
|
||||
}
|
||||
|
||||
fn primary(p: *Parser) Error!ast.Expr {
|
||||
const start = p.peek().pos;
|
||||
const t = p.peek();
|
||||
@@ -786,19 +811,7 @@ const Parser = struct {
|
||||
return .{ .span = p.span(start), .kind = .{ .variant = .{ .@"enum" = t.text, .name = v } } };
|
||||
}
|
||||
if (p.peek().tag == .l_brace and !p.no_struct and std.ascii.isUpper(t.text[0])) {
|
||||
_ = p.next();
|
||||
var fields: std.ArrayList(ast.FieldInit) = .empty;
|
||||
while (p.peek().tag != .r_brace) {
|
||||
const fs = p.peek().pos;
|
||||
const fname = try p.ident("a field name");
|
||||
_ = try p.expect(.colon, "`:`");
|
||||
const fe = try p.expr();
|
||||
try fields.append(p.arena, .{ .name = fname, .span = p.span(fs), .e = fe });
|
||||
if (p.peek().tag != .comma) break;
|
||||
_ = p.next();
|
||||
}
|
||||
_ = try p.expect(.r_brace, "`}`");
|
||||
return .{ .span = p.span(start), .kind = .{ .struct_lit = .{ .name = t.text, .fields = fields.items } } };
|
||||
return p.structLiteral(start, t.text);
|
||||
}
|
||||
return .{ .span = p.span(start), .kind = .{ .name = t.text } };
|
||||
},
|
||||
|
||||
+3
-93
@@ -1,13 +1,8 @@
|
||||
//! Closed, compiler-pinned registry of safe `.aji` standard modules.
|
||||
//! No host file lookup, runtime initialization or verifier privilege.
|
||||
//! Compiler-pinned safe source modules. General linking lives in modules.zig.
|
||||
|
||||
const std = @import("std");
|
||||
const ast = @import("ast.zig");
|
||||
const parse = @import("parse.zig");
|
||||
const lower = @import("lower.zig");
|
||||
pub const Source = struct { name: []const u8, file: []const u8, source: []const u8 };
|
||||
|
||||
const Entry = struct { name: []const u8, file: []const u8, source: []const u8 };
|
||||
const registry = [_]Entry{
|
||||
pub const registry = [_]Source{
|
||||
.{ .name = "std.bytes", .file = "std/bytes.aji", .source = @embedFile("std_bytes_aji") },
|
||||
.{ .name = "std.encoding.base64", .file = "std/encoding/base64.aji", .source = @embedFile("std_encoding_base64_aji") },
|
||||
.{ .name = "std.encoding.hex", .file = "std/encoding/hex.aji", .source = @embedFile("std_encoding_hex_aji") },
|
||||
@@ -15,88 +10,3 @@ const registry = [_]Entry{
|
||||
.{ .name = "std.math", .file = "std/math.aji", .source = @embedFile("std_math_aji") },
|
||||
.{ .name = "std.utf8", .file = "std/utf8.aji", .source = @embedFile("std_utf8_aji") },
|
||||
};
|
||||
|
||||
pub const Result = union(enum) { ok: ast.Module, err: lower.Problem };
|
||||
|
||||
pub fn link(arena: std.mem.Allocator, module: ast.Module) std.mem.Allocator.Error!Result {
|
||||
// Validate in source order, before lowering, so the first error is stable.
|
||||
for (module.imports, 0..) |imp, i| {
|
||||
for (module.imports[0..i]) |prev| {
|
||||
if (std.mem.eql(u8, imp.path, prev.path)) return problem(arena, "E7006", imp, "module imported twice");
|
||||
}
|
||||
const known = for (registry) |entry| {
|
||||
if (std.mem.eql(u8, entry.name, imp.path)) break true;
|
||||
} else false;
|
||||
if (!known) return problem(arena, "E7002", imp, "unknown built-in standard module");
|
||||
}
|
||||
if (module.imports.len == 0) return .{ .ok = module };
|
||||
|
||||
var functions: std.ArrayList(ast.FnDecl) = .empty;
|
||||
try functions.appendSlice(arena, module.functions);
|
||||
var types: std.ArrayList(ast.TypeDecl) = .empty;
|
||||
try types.appendSlice(arena, module.types);
|
||||
// Registry order is lexicographic; import declaration order never affects AIR.
|
||||
for (registry) |entry| {
|
||||
const imported = for (module.imports) |imp| {
|
||||
if (std.mem.eql(u8, imp.path, entry.name)) break true;
|
||||
} else false;
|
||||
if (!imported) continue;
|
||||
const library = switch (try parse.parseWithFile(arena, entry.source, entry.file)) {
|
||||
.ok => |m| m,
|
||||
.err => |failure| return .{ .err = .{
|
||||
.code = "E7900",
|
||||
.span = .{ .start = failure.pos, .end = failure.pos, .file = entry.file },
|
||||
.message = "malformed bundled standard source: a compiler bug",
|
||||
} },
|
||||
};
|
||||
// Bundled source spells standard type references by their full path.
|
||||
std.debug.assert(std.mem.eql(u8, library.name, entry.name));
|
||||
std.debug.assert(library.imports.len == 0);
|
||||
for (library.types) |t| {
|
||||
std.debug.assert(t.kind == .@"enum");
|
||||
var qualified = t;
|
||||
qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, t.name });
|
||||
qualified.air_name = try airName(arena, entry.name, t.name, types.items, functions.items);
|
||||
try types.append(arena, qualified);
|
||||
}
|
||||
for (library.functions) |f| {
|
||||
var qualified = f;
|
||||
qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, f.name });
|
||||
qualified.air_name = try airName(arena, entry.name, f.name, types.items, functions.items);
|
||||
try functions.append(arena, qualified);
|
||||
}
|
||||
}
|
||||
var combined = module;
|
||||
combined.types = types.items;
|
||||
combined.functions = functions.items;
|
||||
return .{ .ok = combined };
|
||||
}
|
||||
|
||||
fn airName(arena: std.mem.Allocator, module: []const u8, name: []const u8, types: []const ast.TypeDecl, functions: []const ast.FnDecl) std.mem.Allocator.Error![]const u8 {
|
||||
const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ module, name });
|
||||
for (base) |*c| if (c.* == '.') {
|
||||
c.* = '_';
|
||||
};
|
||||
var candidate: []const u8 = base;
|
||||
var suffix: usize = 0;
|
||||
while (airNameUsed(types, functions, candidate)) {
|
||||
suffix += 1;
|
||||
candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix });
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
fn airNameUsed(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool {
|
||||
for (types) |t| if (std.mem.eql(u8, t.air_name orelse t.name, name)) return true;
|
||||
for (functions) |f| if (std.mem.eql(u8, f.air_name orelse f.name, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
fn problem(arena: std.mem.Allocator, code: []const u8, imp: ast.Import, message: []const u8) std.mem.Allocator.Error!Result {
|
||||
return .{ .err = .{
|
||||
.code = code,
|
||||
.span = imp.span,
|
||||
.message = message,
|
||||
.fields = try arena.dupe(lower.Problem.Field, &.{.{ .name = "name", .value = imp.path }}),
|
||||
} };
|
||||
}
|
||||
+75
-65
@@ -17,10 +17,10 @@ const usage =
|
||||
\\usage: aji <command> [args]
|
||||
\\
|
||||
\\commands:
|
||||
\\ check [--report unsafe] <file.air>
|
||||
\\ 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 | --manifest aji.toml>
|
||||
\\ 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
|
||||
@@ -29,16 +29,16 @@ const usage =
|
||||
\\ --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>
|
||||
\\ 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
|
||||
\\ explore [--max-runs N] [--grant P=KIND[:SCOPE]]... <file.air | file.aji>
|
||||
\\ 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> verify, then print the audit report (spec 10 §6.1)
|
||||
\\ 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
|
||||
@@ -76,32 +76,43 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
return .accepted;
|
||||
}
|
||||
if (std.mem.eql(u8, cmd, "report")) {
|
||||
if (args.len != 3) return usageError("report takes exactly one file");
|
||||
const path = args[2];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const result = try aji.check.checkAir(arena, path, source);
|
||||
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")) {
|
||||
const annotate = args.len == 4 and std.mem.eql(u8, args[2], "--annotate");
|
||||
const stats = args.len == 4 and std.mem.eql(u8, args[2], "--stats");
|
||||
if (args.len != 3 and !annotate and !stats) return usageError("lower takes [--annotate | --stats] and one .aji file");
|
||||
const path = args[args.len - 1];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
switch (try aji.frontend.compile(arena, path, source)) {
|
||||
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.
|
||||
@@ -190,12 +201,16 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
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, 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];
|
||||
@@ -229,46 +244,18 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
|
||||
rest = rest[2..];
|
||||
}
|
||||
options.world.files = files.items;
|
||||
var path: []const u8 = undefined;
|
||||
var input: aji.source_package.Input = undefined;
|
||||
if (manifest_path) |mp| {
|
||||
// spec 12 §1.2: the module is the manifest's entry; its grants
|
||||
// are applied, each replaced by a --grant for the same parameter.
|
||||
if (rest.len != 0) return usageError("a file argument cannot be combined with --manifest");
|
||||
const text = std.Io.Dir.cwd().readFileAlloc(io, mp, arena, .limited(1 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ mp, err });
|
||||
return .usage;
|
||||
};
|
||||
const m = switch (try aji.manifest.parse(arena, text)) {
|
||||
.ok => |m| m,
|
||||
.err => |e| {
|
||||
std.debug.print("aji: manifest {s}:{d}: {s}\n", .{ mp, e.line, e.message });
|
||||
return .usage;
|
||||
},
|
||||
};
|
||||
const entry = m.entry orelse {
|
||||
std.debug.print("aji: manifest {s}: [package] entry is required for aji run\n", .{mp});
|
||||
return .usage;
|
||||
};
|
||||
path = try std.fs.path.join(arena, &.{ std.fs.path.dirname(mp) orelse ".", entry });
|
||||
var merged: std.ArrayList(aji.interp.Grant) = .empty;
|
||||
for (m.grants) |g| {
|
||||
const overridden = for (grants.items) |cg| {
|
||||
if (std.mem.eql(u8, cg.parameter, g.parameter)) break true;
|
||||
} else false;
|
||||
if (!overridden) try merged.append(arena, .{ .parameter = g.parameter, .kind = g.kind, .scope = g.scope });
|
||||
}
|
||||
try merged.appendSlice(arena, grants.items);
|
||||
options.grants = merged.items;
|
||||
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 exactly one file");
|
||||
path = rest[0];
|
||||
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 source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const report = try aji.check.checkFile(arena, path, source);
|
||||
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');
|
||||
@@ -335,21 +322,22 @@ fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out:
|
||||
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 (rest.len != 1) return usageError("explore takes exactly one file");
|
||||
const path = rest[0];
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
|
||||
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
|
||||
return .usage;
|
||||
};
|
||||
const report = try aji.check.checkFile(arena, path, source);
|
||||
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');
|
||||
@@ -366,7 +354,7 @@ fn explore(arena: std.mem.Allocator, io: std.Io, argv: []const []const u8, out:
|
||||
defer run_arena.deinit();
|
||||
var ex: aji.interp.Explore = .{ .prefix = prefix.items };
|
||||
const outcome = aji.interp.run(run_arena.allocator(), module, "main", .{
|
||||
.grants = grants.items,
|
||||
.grants = all_grants,
|
||||
.quantum = std.math.maxInt(u64),
|
||||
.explore = &ex,
|
||||
}) catch |err| switch (err) {
|
||||
@@ -496,3 +484,25 @@ test "standard library trap record identifies the bundled source" {
|
||||
try std.testing.expectEqualStrings("std/math.aji", location.get("file").?.string);
|
||||
try std.testing.expectEqual(@as(i64, 20), location.get("line").?.integer);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
+60
-3
@@ -6,13 +6,18 @@
|
||||
//! drop or misplace authority.
|
||||
|
||||
const std = @import("std");
|
||||
const modules = @import("frontend/modules.zig");
|
||||
|
||||
pub const Grant = struct { parameter: []const u8, kind: []const u8, scope: ?[]const u8 };
|
||||
|
||||
pub const ModuleBinding = struct { name: []const u8, file: []const u8, line: u32 };
|
||||
|
||||
pub const Manifest = struct {
|
||||
name: []const u8,
|
||||
version: []const u8,
|
||||
entry: ?[]const u8,
|
||||
modules: []const ModuleBinding = &.{},
|
||||
has_modules: bool = false,
|
||||
/// `[capabilities]` in file order.
|
||||
grants: []const Grant,
|
||||
};
|
||||
@@ -46,14 +51,32 @@ fn isKey(s: []const u8) bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
fn isModuleName(name: []const u8) bool {
|
||||
var parts = std.mem.splitScalar(u8, name, '.');
|
||||
while (parts.next()) |part| {
|
||||
if (part.len == 0 or !(std.ascii.isAlphabetic(part[0]) or part[0] == '_')) return false;
|
||||
for (part[1..]) |ch| if (!(std.ascii.isAlphanumeric(ch) or ch == '_')) return false;
|
||||
}
|
||||
return name.len != 0;
|
||||
}
|
||||
|
||||
pub fn sourcePath(path: []const u8) bool {
|
||||
if (!std.mem.endsWith(u8, path, ".aji") or std.mem.indexOfAny(u8, path, "\\:\x00") != null) return false;
|
||||
var parts = std.mem.splitScalar(u8, path, '/');
|
||||
while (parts.next()) |part| if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||
const Section = enum { none, package, capabilities, metadata };
|
||||
const Section = enum { none, package, capabilities, metadata, modules };
|
||||
var section: Section = .none;
|
||||
var seen_sections: [3]bool = .{ false, false, false };
|
||||
var seen_sections: [4]bool = @splat(false);
|
||||
var name: ?[]const u8 = null;
|
||||
var version: ?[]const u8 = null;
|
||||
var entry: ?[]const u8 = null;
|
||||
var grants: std.ArrayList(Grant) = .empty;
|
||||
var bindings: std.ArrayList(ModuleBinding) = .empty;
|
||||
var entry_line: u32 = 0;
|
||||
var keys: std.StringHashMapUnmanaged(void) = .empty;
|
||||
|
||||
var lines = std.mem.splitScalar(u8, text, '\n');
|
||||
@@ -74,7 +97,7 @@ pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||
}
|
||||
const eq = std.mem.indexOfScalar(u8, line, '=') orelse return fail(arena, line_no, "expected key = \"value\"", .{});
|
||||
const key = std.mem.trim(u8, line[0..eq], " \t");
|
||||
if (!isKey(key)) return fail(arena, line_no, "malformed key", .{});
|
||||
if (!(if (section == .modules) isModuleName(key) else isKey(key))) return fail(arena, line_no, "malformed key", .{});
|
||||
const value = (try parseString(arena, std.mem.trim(u8, line[eq + 1 ..], " \t"))) orelse
|
||||
return fail(arena, line_no, "value of {s} must be a string \"...\" (escapes \\\", \\\\, \\n), optionally followed by a # comment", .{key});
|
||||
if (section == .none) return fail(arena, line_no, "key {s} outside a section", .{key});
|
||||
@@ -89,15 +112,29 @@ pub fn parse(arena: std.mem.Allocator, text: []const u8) !Result {
|
||||
version = value;
|
||||
} else if (std.mem.eql(u8, key, "entry")) {
|
||||
entry = value;
|
||||
entry_line = line_no;
|
||||
} else return fail(arena, line_no, "unknown key {s} in [package]", .{key});
|
||||
},
|
||||
.capabilities => try grants.append(arena, parseGrantValue(key, value) orelse
|
||||
return fail(arena, line_no, "grant {s} must be \"kind[:scope]\"", .{key})),
|
||||
.modules => {
|
||||
if (modules.reserved(key)) return fail(arena, line_no, "reserved module namespace {s}", .{key});
|
||||
if (!sourcePath(value)) return fail(arena, line_no, "module {s} needs a portable relative .aji path", .{key});
|
||||
if (bindings.items.len >= 1024) return fail(arena, line_no, "at most 1024 modules are allowed", .{});
|
||||
try bindings.append(arena, .{ .name = key, .file = value, .line = line_no });
|
||||
},
|
||||
.metadata => {},
|
||||
.none => unreachable,
|
||||
}
|
||||
}
|
||||
const has_modules = seen_sections[3];
|
||||
if (has_modules) {
|
||||
const source_entry = entry orelse return fail(arena, line_no, "[modules] requires an entry .aji source", .{});
|
||||
if (!sourcePath(source_entry)) return fail(arena, entry_line, "[modules] requires a portable relative entry .aji path", .{});
|
||||
}
|
||||
return .{ .ok = .{
|
||||
.modules = bindings.items,
|
||||
.has_modules = has_modules,
|
||||
.name = name orelse return fail(arena, line_no, "[package] name is required", .{}),
|
||||
.version = version orelse return fail(arena, line_no, "[package] version is required", .{}),
|
||||
.entry = entry,
|
||||
@@ -177,3 +214,23 @@ test "strict parsing" {
|
||||
try expectErr("[package]\nname = \"a\"\nversion = \"1\"\n[capabilities]\nout = \":x\"\n", 5); // empty kind
|
||||
try expectErr("[package]\nname = \"a\"\n", 3); // missing version: reported at the end of the file
|
||||
}
|
||||
|
||||
test "explicit package module mapping and portable paths" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const prefix = "[package]\nname = \"a\"\nversion = \"1\"\nentry = \"src/main.aji\"\n[modules]\n";
|
||||
const good = try parse(arena, prefix ++ "app.model = \"src/model.aji\"\n");
|
||||
try std.testing.expect(good == .ok);
|
||||
try std.testing.expectEqualStrings("app.model", good.ok.modules[0].name);
|
||||
try std.testing.expect(good.ok.has_modules);
|
||||
for ([_][]const u8{
|
||||
"app.model = \"../model.aji\"", "app.model = \"/model.aji\"", "app.model = \"src//model.aji\"",
|
||||
"app.model = \"src/./model.aji\"", "app.model = \"src/model.air\"", "app.model = \"C:/model.aji\"",
|
||||
"std.bytes = \"model.aji\"", "task.work = \"model.aji\"", "io.work = \"model.aji\"",
|
||||
"app..model = \"model.aji\"", "app.0model = \"model.aji\"", "app-model = \"model.aji\"",
|
||||
}) |line| try expectErr(try std.mem.concat(arena, u8, &.{ prefix, line }), 6);
|
||||
try expectErr(prefix ++ "app.model = \"model.aji\"\napp.model = \"other.aji\"", 7);
|
||||
try expectErr("[package]\nname = \"a\"\nversion = \"1\"\nentry = \"main.air\"\n[modules]\n", 4);
|
||||
for ([_][]const u8{ "src\\model.aji", "a\x00.aji", "src/../a.aji", "src/.aji/../b.aji" }) |path| try std.testing.expect(!sourcePath(path));
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub const check = @import("check.zig");
|
||||
pub const frontend = @import("frontend.zig");
|
||||
pub const report = @import("report.zig");
|
||||
pub const manifest = @import("manifest.zig");
|
||||
pub const source_package = @import("source_package.zig");
|
||||
|
||||
test {
|
||||
@import("std").testing.refAllDecls(@This());
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Explicit manifest source snapshot. No source is executed here.
|
||||
const std = @import("std");
|
||||
const manifest = @import("manifest.zig");
|
||||
const frontend = @import("frontend.zig");
|
||||
|
||||
pub const Input = struct {
|
||||
path: []const u8,
|
||||
source: []const u8,
|
||||
modules: []const frontend.modules.Source = &.{},
|
||||
grants: []const manifest.Grant = &.{},
|
||||
};
|
||||
pub const Failure = struct { path: []const u8, line: u32 = 0, message: []const u8 };
|
||||
pub const Result = union(enum) { ok: Input, err: Failure };
|
||||
const source_limit: usize = 64 << 20;
|
||||
|
||||
fn fail(arena: std.mem.Allocator, path: []const u8, err: anyerror) std.mem.Allocator.Error!Result {
|
||||
if (err == error.OutOfMemory) return error.OutOfMemory;
|
||||
return .{ .err = .{ .path = path, .message = try std.fmt.allocPrint(arena, "cannot read source: {t}", .{err}) } };
|
||||
}
|
||||
|
||||
pub fn single(arena: std.mem.Allocator, io: std.Io, path: []const u8) std.mem.Allocator.Error!Result {
|
||||
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(source_limit)) catch |err| return fail(arena, path, err);
|
||||
return .{ .ok = .{ .path = path, .source = source } };
|
||||
}
|
||||
|
||||
pub fn load(arena: std.mem.Allocator, io: std.Io, path: []const u8) std.mem.Allocator.Error!Result {
|
||||
const text = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| return fail(arena, path, err);
|
||||
const m = switch (try manifest.parse(arena, text)) {
|
||||
.ok => |m| m,
|
||||
.err => |err| return .{ .err = .{ .path = path, .line = err.line, .message = err.message } },
|
||||
};
|
||||
const entry = m.entry orelse return .{ .err = .{ .path = path, .message = "[package] entry is required" } };
|
||||
const parent = std.fs.path.dirname(path) orelse ".";
|
||||
const entry_path = try std.fs.path.join(arena, &.{ parent, entry });
|
||||
if (!m.has_modules) {
|
||||
var result = try single(arena, io, entry_path);
|
||||
if (result == .ok) result.ok.grants = m.grants;
|
||||
return result;
|
||||
}
|
||||
const root = std.Io.Dir.cwd().openDir(io, parent, .{}) catch |err| return fail(arena, parent, err);
|
||||
defer root.close(io);
|
||||
const source = readSource(arena, io, root, entry, source_limit) catch |err| return fail(arena, entry, err);
|
||||
var remaining = source_limit - source.len;
|
||||
const bindings = try arena.dupe(manifest.ModuleBinding, m.modules);
|
||||
std.mem.sort(manifest.ModuleBinding, bindings, {}, struct {
|
||||
fn less(_: void, a: manifest.ModuleBinding, b: manifest.ModuleBinding) bool {
|
||||
return std.mem.lessThan(u8, a.name, b.name);
|
||||
}
|
||||
}.less);
|
||||
var sources: std.ArrayList(frontend.modules.Source) = .empty;
|
||||
for (bindings) |binding| {
|
||||
const bytes = readSource(arena, io, root, binding.file, remaining) catch |err| return fail(arena, binding.file, err);
|
||||
remaining -= bytes.len;
|
||||
try sources.append(arena, .{ .name = binding.name, .file = binding.file, .source = bytes });
|
||||
}
|
||||
return .{ .ok = .{ .path = entry_path, .source = source, .modules = sources.items, .grants = m.grants } };
|
||||
}
|
||||
|
||||
fn readSource(arena: std.mem.Allocator, io: std.Io, root: std.Io.Dir, path: []const u8, limit: usize) ![]const u8 {
|
||||
std.debug.assert(manifest.sourcePath(path));
|
||||
var dirs: std.ArrayList(std.Io.Dir) = .empty;
|
||||
defer for (dirs.items) |dir| dir.close(io);
|
||||
var current = root;
|
||||
var parts = std.mem.splitScalar(u8, path, '/');
|
||||
while (parts.next()) |part| {
|
||||
if (parts.peek() != null) {
|
||||
const next = try current.openDir(io, part, .{ .follow_symlinks = false });
|
||||
dirs.append(arena, next) catch |err| {
|
||||
next.close(io);
|
||||
return err;
|
||||
};
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
// Avoid opening a static pipe/device; the opened handle is checked too.
|
||||
if ((try current.statFile(io, part, .{ .follow_symlinks = false })).kind != .file) return error.NotRegularSource;
|
||||
const file = try current.openFile(io, part, .{ .follow_symlinks = false, .allow_directory = false });
|
||||
defer file.close(io);
|
||||
const stat = try file.stat(io);
|
||||
if (stat.kind != .file) return error.NotRegularSource;
|
||||
if (stat.size > limit) return error.StreamTooLong;
|
||||
var reader = file.reader(io, &.{});
|
||||
const bytes = reader.interface.allocRemaining(arena, .limited(limit + 1)) catch |err| switch (err) {
|
||||
error.ReadFailed => return reader.err.?,
|
||||
else => return err,
|
||||
};
|
||||
if (bytes.len > limit) return error.StreamTooLong;
|
||||
return bytes;
|
||||
}
|
||||
unreachable;
|
||||
}
|
||||
Reference in new issue
Block a user