cli: bootstrap verified std bytes and math with source imports

This commit is contained in:
dev committed 2026-10-06 14:51:10 +03:00
1 parent 268926ca0f
commit 10a370471b
52 files changed
+1000 -22

No files matched your search

+6 -1
View File
@@ -6,7 +6,7 @@ const lex = @import("lex.zig");
pub const Pos = lex.Pos;
pub const Span = struct { start: Pos, end: Pos };
pub const Span = struct { start: Pos, end: Pos, file: ?[]const u8 = null };
pub const Type = struct {
span: Span,
@@ -176,6 +176,8 @@ 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.
air_name: ?[]const u8 = null,
span: Span,
params: []const Param,
ret: Type,
@@ -187,6 +189,9 @@ pub const FnDecl = struct {
pub const Module = struct {
name: []const u8,
imports: []const Import = &.{},
types: []const TypeDecl,
functions: []const FnDecl,
};
pub const Import = struct { path: []const u8, span: Span };
+32 -9
View File
@@ -263,7 +263,7 @@ const Rest = struct {
const LoopAst = struct { cond: ?ast.Expr, body: ast.Block, step: ?[]const u8 };
const FnSig = struct { params: []const Ty, ret: Ty };
const FnSig = struct { params: []const Ty, ret: Ty, air_name: []const u8 };
const Lowerer = struct {
arena: Allocator,
@@ -382,7 +382,9 @@ const Lowerer = struct {
try l.out.append(l.arena, '\n');
try l.lines.append(l.arena, span);
if (span) |s| if (std.mem.startsWith(u8, text, " ")) {
try l.annotated.appendSlice(l.arena, try l.fmt(" ; {d}:{d}-{d}:{d}\n", .{ s.start.line, s.start.col, s.end.line, s.end.col }));
if (s.file) |file| {
try l.annotated.appendSlice(l.arena, try l.fmt(" ; {s}:{d}:{d}-{d}:{d}\n", .{ file, s.start.line, s.start.col, s.end.line, s.end.col }));
} else try l.annotated.appendSlice(l.arena, try l.fmt(" ; {d}:{d}-{d}:{d}\n", .{ s.start.line, s.start.col, s.end.line, s.end.col }));
};
try l.annotated.appendSlice(l.arena, text);
try l.annotated.append(l.arena, '\n');
@@ -401,7 +403,7 @@ const Lowerer = struct {
if (l.sigs.contains(f.name)) return l.fail("E7006", f.span, "function defined twice", &.{.{ .name = "name", .value = f.name }});
const ps = try l.arena.alloc(Ty, f.params.len);
for (f.params, ps) |p, *t| t.* = try l.typeOf(p.ty);
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret) });
try l.sigs.put(l.arena, f.name, .{ .params = ps, .ret = try l.typeOf(f.ret), .air_name = f.air_name orelse f.name });
}
if (!l.sigs.contains("main")) return l.fail("E7002", .{ .start = .{ .line = 1, .col = 1 }, .end = .{ .line = 1, .col = 1 } }, "the module has no `main` function", &.{.{ .name = "name", .value = "main" }});
@@ -583,7 +585,7 @@ const Lowerer = struct {
for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) l.uses.insert(.unsafe);
var header: std.ArrayList(u8) = .empty;
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{f.name}));
try header.appendSlice(l.arena, try l.fmt("fn @{s}(", .{sig.air_name}));
for (f.params, sig.params, 0..) |p, t, i| {
// Parameters keep their source names: `@main` capabilities are granted by name.
const v = p.name;
@@ -1099,6 +1101,14 @@ const Lowerer = struct {
/// The type of an expression without lowering it, where it follows
/// from names, suffixes, casts and calls; null otherwise.
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);
}
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
return switch (e.kind) {
.int => |x| if (parse_mod.intSuffix(x.text)) |s| Ty{ .int = s } else null,
@@ -1118,7 +1128,7 @@ const Lowerer = struct {
.call => |x| switch (x.callee.kind) {
.name => |n| if (l.sigs.get(n)) |sig| sig.ret else null,
.variant => |v| l.enumType(v.@"enum"),
else => if (pathOf(x.callee.*)) |p| l.peekPath(p, x.args) else null,
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"),
@@ -1196,8 +1206,7 @@ const Lowerer = struct {
},
},
.call => |x| blk: {
if (x.callee.kind != .name) break :blk null;
const sig = l.sigs.get(x.callee.kind.name) orelse break :blk null;
const sig = l.calleeSig(x.callee.*) orelse break :blk null;
for (x.args, 0..) |a, i| {
const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null;
if (l.useIn(n, a, pt)) |t| break :blk t;
@@ -1412,6 +1421,13 @@ 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);
// 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);
}
if (pathOf(callee)) |p| {
if (std.mem.eql(u8, p, "slice.copy")) return l.sliceCopy(e, args);
if (l.fallible(p) != null) return l.fail("E7006", e.span, "a fallible operation is handled with `match` over its outcomes or with `or trap`", &.{.{ .name = "operation", .value = p }});
@@ -1481,7 +1497,7 @@ const Lowerer = struct {
try l.checkTy(a.span, v.ty, pt);
try arg_names.appendSlice(l.arena, try l.fmt("{s}%{s}", .{ if (i == 0) "" else ", ", v.name }));
}
const text = try l.fmt("call @{s}({s})", .{ name, arg_names.items });
const text = try l.fmt("call @{s}({s})", .{ sig.air_name, arg_names.items });
defer l.endNowIfLive(temps.items, e.span) catch {};
if (sig.ret == .void or sig.ret == .never) {
try l.emit(text, e.span);
@@ -1491,7 +1507,7 @@ const Lowerer = struct {
}
return .{ .name = "", .ty = .void };
}
return l.def(name, sig.ret, text, e.span);
return l.def(if (std.mem.startsWith(u8, name, "std.")) "std_call" else name, sig.ret, text, e.span);
}
/// `Name { f: e, … }`: every field exactly once; initializers are
@@ -3086,6 +3102,13 @@ fn dotted(e: ast.Expr, buf: []u8) ?[]const u8 {
}
}
fn standardPath(e: ast.Expr) bool {
if (e.kind != .field) return false;
var root = e;
while (root.kind == .field) root = root.kind.field.e.*;
return root.kind == .name and std.mem.eql(u8, root.kind.name, "std");
}
fn box(arena: Allocator, e: ast.Expr) Error!*const ast.Expr {
const b = try arena.create(ast.Expr);
b.* = e;
+15 -3
View File
@@ -15,8 +15,12 @@ pub const Failure = struct { pos: lex.Pos, expected: []const u8, found: []const
pub const Result = union(enum) { ok: ast.Module, err: Failure };
pub fn parse(arena: Allocator, src: []const u8) Allocator.Error!Result {
return parseWithFile(arena, src, null);
}
pub fn parseWithFile(arena: Allocator, src: []const u8, file: ?[]const u8) Allocator.Error!Result {
const tokens = try lex.tokenize(arena, src);
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens) };
var p: Parser = .{ .arena = arena, .tokens = try arena.dupe(Token, tokens), .file = file };
const m = p.module() catch |e| switch (e) {
error.Syntax => return .{ .err = p.failure.? },
error.OutOfMemory => return error.OutOfMemory,
@@ -31,6 +35,7 @@ const Parser = struct {
tokens: []Token,
pos: usize = 0,
failure: ?Failure = null,
file: ?[]const u8 = null,
/// Struct literals are not allowed where a `{` starts a block (conditions).
no_struct: bool = false,
@@ -99,7 +104,7 @@ const Parser = struct {
}
fn span(p: *Parser, start: lex.Pos) ast.Span {
return .{ .start = start, .end = p.prevEnd() };
return .{ .start = start, .end = p.prevEnd(), .file = p.file };
}
fn box(p: *Parser, comptime T: type, v: T) Error!*const T {
@@ -113,6 +118,13 @@ const Parser = struct {
fn module(p: *Parser) Error!ast.Module {
_ = try p.expectWord("module");
const name = try p.path();
var imports: std.ArrayList(ast.Import) = .empty;
while (p.atWord("import")) {
const start = p.next().pos;
const path_name = try p.path();
_ = try p.expect(.semicolon, "`;` after import");
try imports.append(p.arena, .{ .path = path_name, .span = p.span(start) });
}
var types: std.ArrayList(ast.TypeDecl) = .empty;
var fns: std.ArrayList(ast.FnDecl) = .empty;
while (p.peek().tag != .eof) {
@@ -122,7 +134,7 @@ const Parser = struct {
try fns.append(p.arena, try p.fnDecl());
} else return p.fail(p.peek(), "`struct`, `enum` or `fn`");
}
return .{ .name = name, .types = types.items, .functions = fns.items };
return .{ .name = name, .imports = imports.items, .types = types.items, .functions = fns.items };
}
fn path(p: *Parser) Error![]const u8 {
+84
View File
@@ -0,0 +1,84 @@
//! Closed, compiler-pinned registry of safe `.aji` standard modules.
//! No host file lookup, runtime initialization or verifier privilege.
const std = @import("std");
const ast = @import("ast.zig");
const parse = @import("parse.zig");
const lower = @import("lower.zig");
const Entry = struct { name: []const u8, file: []const u8, source: []const u8 };
const registry = [_]Entry{
.{ .name = "std.bytes", .file = "std/bytes.aji", .source = @embedFile("std_bytes_aji") },
.{ .name = "std.math", .file = "std/math.aji", .source = @embedFile("std_math_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);
// 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",
} },
};
// The bootstrap registry intentionally exposes no imported types/dependencies.
std.debug.assert(std.mem.eql(u8, library.name, entry.name));
std.debug.assert(library.types.len == 0 and library.imports.len == 0);
for (library.functions) |f| {
var qualified = f;
qualified.name = try std.fmt.allocPrint(arena, "{s}.{s}", .{ entry.name, f.name });
const base = try std.fmt.allocPrint(arena, "__aji_{s}_{s}", .{ entry.name, f.name });
for (base) |*c| if (c.* == '.') {
c.* = '_';
};
var candidate: []const u8 = base;
var suffix: usize = 0;
while (airNameUsed(module.types, functions.items, candidate)) {
suffix += 1;
candidate = try std.fmt.allocPrint(arena, "{s}_{d}", .{ base, suffix });
}
qualified.air_name = candidate;
try functions.append(arena, qualified);
}
}
var combined = module;
combined.functions = functions.items;
return .{ .ok = combined };
}
fn airNameUsed(types: []const ast.TypeDecl, functions: []const ast.FnDecl, name: []const u8) bool {
for (types) |t| if (std.mem.eql(u8, 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 }}),
} };
}