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
@@ -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 }}),
|
||||
} };
|
||||
}
|
||||
Reference in new issue
Block a user