From 008654999e832a8f01c8daf63b0218992fd52ec1 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 14:41:30 +0300 Subject: [PATCH] Phase 2: unsafe operations and trusted boundaries (RFC 0009) - air: string literals (trusted line only), trusted obligation on functions, assume, borrow.index.unchecked - verifier: unsafe stage (E6001 outside_boundary / trusted_declares_unsafe); effect stage leaves unsafe to it, so trusted functions discharge it; assume establishes bounds facts - interp: T0009 for detected unsafe precondition violations - aji check --report unsafe: trusted functions with obligations, unsafe functions, unsafe operations with their boundary - feature unsafe published and supported; 10 conformance tests; 3000 mutants without a crash --- AGENTS.md | 2 +- .../phase-2-effects-capabilities-resources.md | 2 +- src/air/features.zig | 4 +- src/air/module.zig | 8 +- src/air/parse.zig | 52 ++++++++- src/air/print.zig | 13 ++- src/diag.zig | 3 +- src/interp/machine.zig | 9 +- src/main.zig | 11 +- src/verifier.zig | 4 +- src/verifier/bounds.zig | 14 ++- src/verifier/effects.zig | 4 +- src/verifier/types.zig | 2 +- src/verifier/unsafe.zig | 102 ++++++++++++++++++ .../phase2/accept/unsafe_assume_fact.air | 19 ++++ .../phase2/accept/unsafe_trusted_boundary.air | 32 ++++++ .../phase2/reject/unsafe_call_from_safe.air | 19 ++++ .../phase2/reject/unsafe_empty_obligation.air | 14 +++ .../phase2/reject/unsafe_outside_boundary.air | 16 +++ .../reject/unsafe_trusted_declares_unsafe.air | 14 +++ .../reject/unsafe_trusted_without_feature.air | 14 +++ .../phase2/run/unsafe_assume_violated.air | 16 +++ .../run/unsafe_precondition_violated.air | 33 ++++++ .../phase2/run/unsafe_trusted_call.air | 33 ++++++ 24 files changed, 422 insertions(+), 18 deletions(-) create mode 100644 src/verifier/unsafe.zig create mode 100644 tests/conformance/phase2/accept/unsafe_assume_fact.air create mode 100644 tests/conformance/phase2/accept/unsafe_trusted_boundary.air create mode 100644 tests/conformance/phase2/reject/unsafe_call_from_safe.air create mode 100644 tests/conformance/phase2/reject/unsafe_empty_obligation.air create mode 100644 tests/conformance/phase2/reject/unsafe_outside_boundary.air create mode 100644 tests/conformance/phase2/reject/unsafe_trusted_declares_unsafe.air create mode 100644 tests/conformance/phase2/reject/unsafe_trusted_without_feature.air create mode 100644 tests/conformance/phase2/run/unsafe_assume_violated.air create mode 100644 tests/conformance/phase2/run/unsafe_precondition_violated.air create mode 100644 tests/conformance/phase2/run/unsafe_trusted_call.air diff --git a/AGENTS.md b/AGENTS.md index 3653a2c..189ce7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,7 +131,7 @@ zig fmt --check build.zig build.zig.zon src tools Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing. -`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` is specified but not implemented yet. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7). +`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` is specified but not implemented yet. `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted ""` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7). ## Testing policy diff --git a/docs/plan/phase-2-effects-capabilities-resources.md b/docs/plan/phase-2-effects-capabilities-resources.md index f7c5885..a731d78 100644 --- a/docs/plan/phase-2-effects-capabilities-resources.md +++ b/docs/plan/phase-2-effects-capabilities-resources.md @@ -31,7 +31,7 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7). | P2-4 | done | Effect verifier (calls and intrinsics) | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees | | P2-5 | done | Capability verifier: unforgeability, narrowing, transfer rules (E3201, E3202, instantiation) | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject | | P2-6 | done | Linear resource and typestate verifier | P2-3 | `src/verifier/resource.zig` | E3001, E3002 accept/reject; leak on an error path detected | -| P2-7 | todo | Unsafe boundary verifier | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject | +| P2-7 | done | Unsafe boundary verifier (RFC 0009: assume, borrow.index.unchecked, trusted, unsafe report) | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject | | P2-8 | doing | Runtime intrinsics in the interpreter; virtual filesystem and loopback network for the `deterministic` profile | P2-2 | `src/runtime/` | intrinsic unit tests pass under both profiles; deterministic profile output identical across runs | | P2-9 | doing | Entry-point capability instantiation (`--grant` done; `aji.toml` `[capabilities]` pending) | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) | | P2-10 | todo | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test | diff --git a/src/air/features.zig b/src/air/features.zig index f6590f7..6f0b601 100644 --- a/src/air/features.zig +++ b/src/air/features.zig @@ -37,10 +37,11 @@ pub const registry = [_]Feature{ .{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 }, .{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, .{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, + .{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 }, }; /// Features implemented by this toolchain, sorted. -pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources" }; +pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "unsafe" }; pub const Reason = enum { unknown_feature, @@ -118,6 +119,7 @@ const test_registry = [_]Feature{ .{ .name = "regions", .depends = &.{"ownership"}, .status = .published, .phase = 1 }, .{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .published, .phase = 4 }, .{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, + .{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 }, }; fn expectProblems(declared: []const []const u8, sup: []const []const u8, want: []const Reason) !void { diff --git a/src/air/module.zig b/src/air/module.zig index dcabfac..55d0400 100644 --- a/src/air/module.zig +++ b/src/air/module.zig @@ -221,7 +221,7 @@ pub const Op = union(enum) { store: struct { borrow: ValueId, value: ValueId }, // Feature `arrays`. array_splat: struct { ty: Type, value: ValueId }, - borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool }, + borrow_index: struct { borrow: ValueId, index: ValueId, proven: bool, unchecked: bool = false }, slice_make: ValueId, slice_len: ValueId, slice_sub: struct { slice: ValueId, start: ValueId, len: ValueId }, @@ -229,6 +229,8 @@ pub const Op = union(enum) { slice_split: struct { slice: ValueId, at: ValueId }, slice_copy: struct { dst: ValueId, src: ValueId }, guard: ValueId, + // Feature `unsafe` (spec 13 §6). + assume: ValueId, @"const": struct { ty: Type, bits: u128 }, copy: ValueId, @@ -302,6 +304,8 @@ pub const Function = struct { ret: Type, /// Index into `params` of the `from` parameter of a borrow return. ret_from: ?u32 = null, + /// Proof obligation of a `trusted` boundary (feature `unsafe`). + trusted: ?[]const u8 = null, effects: []const []const u8, blocks: []const Block, values: []const ValueInfo, @@ -427,7 +431,7 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v f(ctx, x.local); f(ctx, x.value); }, - .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_end, .load, .slice_make, .slice_len, .guard => |v| f(ctx, v), + .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_end, .load, .slice_make, .slice_len, .guard, .assume => |v| f(ctx, v), .borrow_field => |x| f(ctx, x.borrow), .store => |x| { f(ctx, x.borrow); diff --git a/src/air/parse.zig b/src/air/parse.zig index 0c992b7..4d783fe 100644 --- a/src/air/parse.zig +++ b/src/air/parse.zig @@ -60,6 +60,8 @@ const Tag = enum { global, /// Raw numeric text, including an optional leading `-` and any `.`. number, + /// `"…"`; text excludes the quotes, escapes not yet decoded. + string, invalid, eof, }; @@ -145,6 +147,18 @@ fn tokenize(arena: Allocator, src: []const u8) Allocator.Error![]const Token { else => .r_brace, }; }, + '"' => { + i += 1; + while (i < src.len and src[i] != '"' and src[i] != '\n') : (i += 1) { + if (src[i] == '\\' and i + 1 < src.len) i += 1; + } + if (i < src.len and src[i] == '"') { + i += 1; + try tokens.append(arena, .{ .tag = .string, .text = src[start + 1 .. i - 1], .span = span }); + continue; + } + tag = .invalid; + }, '%', '@' => { i += 1; while (i < src.len and isNameChar(src[i])) i += 1; @@ -643,6 +657,16 @@ const Parser = struct { const effects_tok = try p.expectWord("effects"); const effects = try p.parsePathList(); _ = try p.expect(.nl, "end of line"); + var trusted: ?[]const u8 = null; + p.skipNewlines(); + if (p.atWord("trusted")) { + const tok = p.next(); + try p.requireFeature("unsafe", tok.span, "trusted"); + const str = try p.expect(.string, "obligation string"); + trusted = unescapeString(p.arena, str.text) catch return p.fail(str, "string with escapes \\\", \\\\ or \\n"); + if (trusted.?.len == 0) return p.fail(str, "non-empty obligation string"); + _ = try p.expect(.nl, "end of line"); + } // Effect names are checked against the registry when the module // declares `effects` (spec 05 §9.1). if (p.declares("effects")) for (effects) |e| { @@ -671,6 +695,7 @@ const Parser = struct { .params = params.items, .ret = ret, .ret_from = ret_from, + .trusted = trusted, .effects = effects, .blocks = blocks.items, .values = p.values.items, @@ -1046,6 +1071,8 @@ const Parser = struct { @"array.splat", @"borrow.index", @"borrow.index.proven", + @"borrow.index.unchecked", + assume, @"slice.make", @"slice.len", @"slice.sub", @@ -1056,6 +1083,7 @@ const Parser = struct { const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null; const feature: []const u8 = switch (name) { .@"local.alloc", .@"local.store", .@"local.zero", .@"local.load", .@"borrow.ref", .@"borrow.mut", .@"borrow.field", .@"borrow.end", .load, .store => "ownership", + .@"borrow.index.unchecked", .assume => "unsafe", else => "arrays", }; try p.requireFeature(feature, op_tok.span, op_tok.text); @@ -1090,10 +1118,11 @@ const Parser = struct { const ty = try p.parseType(); break :blk .{ .array_splat = .{ .ty = ty, .value = try p.useValue() } }; }, - .@"borrow.index", .@"borrow.index.proven" => blk: { + .@"borrow.index", .@"borrow.index.proven", .@"borrow.index.unchecked" => blk: { const b, const i = try p.twoOperands(); - break :blk .{ .borrow_index = .{ .borrow = b, .index = i, .proven = name == .@"borrow.index.proven" } }; + break :blk .{ .borrow_index = .{ .borrow = b, .index = i, .proven = name == .@"borrow.index.proven", .unchecked = name == .@"borrow.index.unchecked" } }; }, + .assume => .{ .assume = try p.useValue() }, .@"slice.make" => .{ .slice_make = try p.useValue() }, .@"slice.len" => .{ .slice_len = try p.useValue() }, .@"slice.sub" => blk: { @@ -1217,6 +1246,25 @@ pub fn literalBits(text: []const u8, ty: air.IntType) ?u128 { return if (n == 128) raw else raw & ((@as(u128, 1) << @intCast(n)) - 1); } +fn unescapeString(arena: Allocator, s: []const u8) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < s.len) : (i += 1) { + if (s[i] != '\\') { + try out.append(arena, s[i]); + continue; + } + i += 1; + try out.append(arena, switch (s[i]) { + '"' => '"', + '\\' => '\\', + 'n' => '\n', + else => return error.BadEscape, + }); + } + return out.items; +} + fn parseScalarType(text: []const u8) ?air.Type { if (eql(text, "bool")) return .bool; if (std.meta.stringToEnum(air.IntType, text)) |it| return .{ .int = it }; diff --git a/src/air/print.zig b/src/air/print.zig index 9e654d4..deae090 100644 --- a/src/air/print.zig +++ b/src/air/print.zig @@ -51,6 +51,16 @@ pub fn print(m: air.Module, w: *Writer) Writer.Error!void { try w.writeAll("\neffects ["); try list(w, f.effects); try w.writeAll("]\n"); + if (f.trusted) |t| { + try w.writeAll("trusted \""); + for (t) |ch| switch (ch) { + '"' => try w.writeAll("\\\""), + '\\' => try w.writeAll("\\\\"), + '\n' => try w.writeAll("\\n"), + else => try w.writeByte(ch), + }; + try w.writeAll("\"\n"); + } for (f.blocks) |b| { try w.writeAll(b.name); if (b.params.len != 0) { @@ -276,7 +286,8 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error! try w.writeByte(' '); try value(f, x.value, w); }, - .borrow_index => |x| try two(f, w, if (x.proven) "borrow.index.proven" else "borrow.index", x.borrow, x.index), + .borrow_index => |x| try two(f, w, if (x.unchecked) "borrow.index.unchecked" else if (x.proven) "borrow.index.proven" else "borrow.index", x.borrow, x.index), + .assume => |v| try one(f, w, "assume", v), .slice_make => |v| try one(f, w, "slice.make", v), .slice_len => |v| try one(f, w, "slice.len", v), .slice_sub => |x| { diff --git a/src/diag.zig b/src/diag.zig index 2f439dd..b899ae0 100644 --- a/src/diag.zig +++ b/src/diag.zig @@ -60,7 +60,7 @@ pub const registry = [_]Code{ .{ .id = "E5002", .kind = "air.invalid_cfg", .meaning = "Invalid block/terminator structure" }, .{ .id = "E5101", .kind = "verifier.resource_limit", .meaning = "Deterministic verifier resource limit exceeded" }, // E6xxx — Unsafe/ABI - .{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary" }, + .{ .id = "E6001", .kind = "unsafe.required", .meaning = "Operation requires explicit unsafe boundary; field `reason`: `outside_boundary`, `trusted_declares_unsafe`" }, .{ .id = "E6101", .kind = "abi.unaligned_reference", .meaning = "Normal reference requested from insufficiently aligned storage" }, // T0xxx — Runtime traps (reported in trap records, not by the verifier) .{ .id = "T0001", .kind = "trap.explicit", .meaning = "`trap` instruction executed" }, @@ -71,6 +71,7 @@ pub const registry = [_]Code{ .{ .id = "T0006", .kind = "trap.cast_out_of_range", .meaning = "Checked cast value not representable in target type" }, .{ .id = "T0007", .kind = "trap.call_depth", .meaning = "Call depth limit (1 024 frames) exceeded" }, .{ .id = "T0008", .kind = "trap.out_of_bounds", .meaning = "Runtime bounds check failed" }, + .{ .id = "T0009", .kind = "trap.unsafe_precondition", .meaning = "Unsafe precondition violated (detected)" }, }; pub fn lookup(id: []const u8) ?*const Code { diff --git a/src/interp/machine.zig b/src/interp/machine.zig index a2501e2..3cd449d 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -190,6 +190,7 @@ const TrapKind = enum { cast_out_of_range, call_depth, out_of_bounds, + unsafe_precondition, fn code(k: TrapKind) *const diag.Code { return switch (k) { @@ -201,6 +202,7 @@ const TrapKind = enum { .cast_out_of_range => diag.lookup("T0006").?, .call_depth => diag.lookup("T0007").?, .out_of_bounds => diag.lookup("T0008").?, + .unsafe_precondition => diag.lookup("T0009").?, }; } }; @@ -376,7 +378,7 @@ const Machine = struct { .intrinsic => |x| return m.intrinsic(f, vals, inst, x), .ret => |v| return .{ .ret = if (v) |x| vals[x] else .void }, .trap => return .{ .trap = .explicit }, - .local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard => return m.execMemory(vals, inst), + .local_alloc, .local_store, .local_zero, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .borrow_end, .load, .store, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split, .slice_copy, .guard, .assume => return m.execMemory(vals, inst), } } @@ -782,7 +784,9 @@ const Machine = struct { }; // `.proven` was verified in bounds; the check is kept as a // defensive assertion that can never fire on verified AIR. - if (i >= len) return .{ .trap = .out_of_bounds }; + // The reference interpreter detects violated unsafe + // preconditions (spec 13 §6.1). + if (i >= len) return .{ .trap = if (x.unchecked) .unsafe_precondition else .out_of_bounds }; return bind(vals, inst.result, .{ .place = try m.extend(place, start + i) }); }, .slice_make => |v| { @@ -816,6 +820,7 @@ const Machine = struct { return .next; }, .guard => |v| return if (vals[v].boolean) .next else .{ .trap = .assert }, + .assume => |v| return if (vals[v].boolean) .next else .{ .trap = .unsafe_precondition }, else => unreachable, } } diff --git a/src/main.zig b/src/main.zig index 38d2672..fb8904c 100644 --- a/src/main.zig +++ b/src/main.zig @@ -17,7 +17,9 @@ const usage = \\usage: aji [args] \\ \\commands: - \\ check parse and verify a text AIR module + \\ check [--report unsafe] + \\ parse and verify a text AIR module; the unsafe report + \\ lists trusted boundaries and unsafe operations \\ run [--fuel N] [--grant P=KIND[:SCOPE]]... \\ verify, then run @main and print the run record; \\ --fuel stops after N executed instructions; @@ -87,6 +89,12 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s var files: std.ArrayList(struct { []const u8, []const u8 }) = .empty; var result_file: ?[]const u8 = null; var rest = args[2..]; + var unsafe_report = false; + if (std.mem.eql(u8, cmd, "check") and rest.len == 3 and std.mem.eql(u8, rest[0], "--report")) { + if (!std.mem.eql(u8, rest[1], "unsafe")) return usageError("--report takes unsafe"); + unsafe_report = true; + rest = rest[2..]; + } while (std.mem.eql(u8, cmd, "run") and rest.len >= 3) { const flag = rest[0]; const value = rest[1]; @@ -125,6 +133,7 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s try d.writeJson(out); try out.writeByte('\n'); } + if (unsafe_report) if (report.module) |module| try aji.verifier.unsafe_.writeReport(module, out); if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) { const module = report.module.?; var output: aji.interp.Output = undefined; diff --git a/src/verifier.zig b/src/verifier.zig index 5fac899..ad21dc7 100644 --- a/src/verifier.zig +++ b/src/verifier.zig @@ -17,6 +17,7 @@ pub const cfg = @import("verifier/cfg.zig"); pub const ssa = @import("verifier/ssa.zig"); pub const types = @import("verifier/types.zig"); pub const effects = @import("verifier/effects.zig"); +pub const unsafe_ = @import("verifier/unsafe.zig"); pub const init = @import("verifier/init.zig"); pub const borrow = @import("verifier/borrow.zig"); pub const bounds = @import("verifier/bounds.zig"); @@ -61,7 +62,7 @@ pub const Context = struct { /// stage, or an empty slice if the module verifies. pub fn verify(arena: std.mem.Allocator, file: []const u8, module: air.Module) std.mem.Allocator.Error![]const diag.Diagnostic { var c: Context = .{ .arena = arena, .file = file, .module = module }; - const stages = .{ budget.check, cfg.check, ssa.check, types.check, effects.check, init.check, borrow.check, bounds.check }; + const stages = .{ budget.check, cfg.check, ssa.check, types.check, effects.check, unsafe_.check, init.check, borrow.check, bounds.check }; inline for (stages) |stage| { try stage(&c); if (c.diags.items.len != 0) { @@ -86,6 +87,7 @@ test { _ = ssa; _ = types; _ = effects; + _ = unsafe_; _ = init; _ = borrow; _ = bounds; diff --git a/src/verifier/bounds.zig b/src/verifier/bounds.zig index 530b7ed..3615e49 100644 --- a/src/verifier/bounds.zig +++ b/src/verifier/bounds.zig @@ -49,6 +49,14 @@ fn factFrom(f: air.Function, cond: air.ValueId, truth: bool) ?Fact { }; } +/// `guard` (checked) and `assume` (unsafe) both establish their condition. +fn assertion(op: air.Op) ?air.ValueId { + return switch (op) { + .guard, .assume => |v| v, + else => null, + }; +} + fn constUsize(f: air.Function, v: air.ValueId) ?u128 { const inst = defOf(f, v) orelse return null; if (inst.op != .@"const") return null; @@ -69,8 +77,8 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { while (true) { if (d != 0 and preds[d].len == 1) if (edgeFact(f, preds[d][0], d)) |fact| try facts.append(c.arena, fact); // Guards anywhere in a strict dominator have executed before b. - if (d != b) for (f.blocks[d].insts) |inst| if (inst.op == .guard) { - if (factFrom(f, inst.op.guard, true)) |fact| try facts.append(c.arena, fact); + if (d != b) for (f.blocks[d].insts) |inst| if (assertion(inst.op)) |cond| { + if (factFrom(f, cond, true)) |fact| try facts.append(c.arena, fact); }; if (d == 0) break; d = dom.idom[d]; @@ -78,7 +86,7 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { for (f.blocks[b].insts, 0..) |inst, ii| { switch (inst.op) { - .guard => |g| if (factFrom(f, g, true)) |fact| try facts.append(c.arena, fact), + .guard, .assume => |g| if (factFrom(f, g, true)) |fact| try facts.append(c.arena, fact), .borrow_index => |x| if (x.proven and !proven(f, types, facts.items, x.borrow, x.index)) { try c.report("E2103", inst.span, "element access not proven in bounds", &.{ .{ .name = "function", .value = .{ .str = f.name } }, diff --git a/src/verifier/effects.zig b/src/verifier/effects.zig index 83554a0..4d28906 100644 --- a/src/verifier/effects.zig +++ b/src/verifier/effects.zig @@ -18,7 +18,9 @@ pub fn check(c: *Context) !void { for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) { .call => |x| { const callee = m.functions[x.callee]; - for (callee.effects) |e| if (!contains(f.effects, e)) { + // `unsafe` is checked by the unsafe stage, which knows about + // `trusted` boundaries (spec 13 §6.4). + for (callee.effects) |e| if (!std.mem.eql(u8, e, "unsafe") and !contains(f.effects, e)) { try c.report("E3101", inst.span, "callee effect not declared by the caller", &.{ .{ .name = "function", .value = .{ .str = f.name } }, .{ .name = "callee", .value = .{ .str = callee.name } }, diff --git a/src/verifier/types.zig b/src/verifier/types.zig index 392fd35..40efa2f 100644 --- a/src/verifier/types.zig +++ b/src/verifier/types.zig @@ -487,7 +487,7 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { const s = fc.typeOf(x.src); if (!s.isSlice() or !s.inner().?.eql(d.inner().?)) return fc.kindError(span, x.src, try std.fmt.allocPrint(fc.c.arena, "slice<{s}> or slice_mut<{s}>", .{ try fc.c.typeName(d.inner().?), try fc.c.typeName(d.inner().?) })); }, - .guard => |v| try fc.expectValue(span, v, .bool), + .guard, .assume => |v| try fc.expectValue(span, v, .bool), .arith => |x| { try fc.expectValue(span, x.a, .{ .int = x.ty }); try fc.expectValue(span, x.b, .{ .int = x.ty }); diff --git a/src/verifier/unsafe.zig b/src/verifier/unsafe.zig new file mode 100644 index 0000000..dc8b75b --- /dev/null +++ b/src/verifier/unsafe.zig @@ -0,0 +1,102 @@ +//! Unsafe boundaries (spec 13 §6.4). Reports E6001. +//! +//! An unsafe operation, or a call to a function declaring the effect +//! `unsafe`, is allowed only in a function that declares `unsafe` itself or +//! is `trusted`. A `trusted` function is the boundary and must not declare +//! `unsafe`. + +const std = @import("std"); +const air = @import("../air.zig"); +const verifier = @import("../verifier.zig"); + +const Context = verifier.Context; + +pub fn declaresUnsafe(f: air.Function) bool { + for (f.effects) |e| if (std.mem.eql(u8, e, "unsafe")) return true; + return false; +} + +/// Description of the unsafe operation `op`, or null if it is safe. +pub fn unsafeOp(m: air.Module, op: air.Op) ?[]const u8 { + return switch (op) { + .assume => "assume", + .borrow_index => |x| if (x.unchecked) "borrow.index.unchecked" else null, + .call => |x| if (declaresUnsafe(m.functions[x.callee])) "call of an unsafe function" else null, + else => null, + }; +} + +pub fn check(c: *Context) !void { + const m = c.module; + for (m.functions) |f| { + const is_unsafe = declaresUnsafe(f); + if (f.trusted != null and is_unsafe) { + try c.report("E6001", f.span, "a trusted boundary must not declare the effect unsafe", &.{ + .{ .name = "reason", .value = .{ .str = "trusted_declares_unsafe" } }, + .{ .name = "function", .value = .{ .str = f.name } }, + }); + } + if (is_unsafe or f.trusted != null) continue; + for (f.blocks) |b| for (b.insts) |inst| if (unsafeOp(m, inst.op)) |what| { + try c.report("E6001", inst.span, "unsafe operation outside an unsafe or trusted function", &.{ + .{ .name = "reason", .value = .{ .str = "outside_boundary" } }, + .{ .name = "function", .value = .{ .str = f.name } }, + .{ .name = "op", .value = .{ .str = what } }, + }); + }; + } +} + +/// The unsafe report (spec 13 §7): one JSON object per line, source order. +pub fn writeReport(m: air.Module, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (m.functions) |f| { + var s: std.json.Stringify = .{ .writer = w }; + if (f.trusted) |t| { + try s.write(.{ .report = "unsafe", .kind = "trusted_function", .function = f.name, .obligation = t }); + try w.writeByte('\n'); + } else if (declaresUnsafe(f)) { + try s.write(.{ .report = "unsafe", .kind = "unsafe_function", .function = f.name }); + try w.writeByte('\n'); + } + for (f.blocks) |b| for (b.insts, 0..) |inst, ii| if (unsafeOp(m, inst.op)) |what| { + var so: std.json.Stringify = .{ .writer = w }; + try so.write(.{ + .report = "unsafe", + .kind = "operation", + .function = f.name, + .block = b.name, + .inst = ii, + .op = what, + .boundary = if (f.trusted != null) f.name else null, + }); + try w.writeByte('\n'); + }; + } +} + +const h = "module t\nair 0\nlang 0.1\nfeatures [arrays, effects, ownership, unsafe]\n"; +const get = "\neffects []\ntrusted \"callers pass %i < len\"\nentry:\n %e = borrow.index.unchecked %s, %i\n %v = load %e\n borrow.end %e\n ret %v\n"; + +test "trusted boundary" { + try verifier.expectCodes(h ++ "fn @get(%s: slice, %i: usize) -> u8" ++ get, &.{}); + try verifier.expectCodes(h ++ "fn @get(%s: slice, %i: usize) -> u8\neffects []\nentry:\n %e = borrow.index.unchecked %s, %i\n %v = load %e\n borrow.end %e\n ret %v\n", &.{"E6001"}); + const raw = "fn @raw() -> void\neffects [unsafe]\nentry:\n ret\n"; + try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\nentry:\n call @raw()\n ret\n" ++ raw, &.{"E6001"}); + try verifier.expectCodes(h ++ "fn @f() -> void\neffects [unsafe]\nentry:\n call @raw()\n ret\n" ++ raw, &.{}); + try verifier.expectCodes(h ++ "fn @f() -> void\neffects []\ntrusted \"raw is fine here\"\nentry:\n call @raw()\n ret\n" ++ raw, &.{}); + try verifier.expectCodes(h ++ "fn @f() -> void\neffects [unsafe]\ntrusted \"x\"\nentry:\n ret\n", &.{"E6001"}); +} + +test writeReport { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const r = try air.parse.parse(arena_state.allocator(), "t.air", h ++ "fn @get(%s: slice, %i: usize) -> u8" ++ get); + var buf: [1024]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try writeReport(r.module.?, &w); + try std.testing.expectEqualStrings( + \\{"report":"unsafe","kind":"trusted_function","function":"get","obligation":"callers pass %i < len"} + \\{"report":"unsafe","kind":"operation","function":"get","block":"entry","inst":0,"op":"borrow.index.unchecked","boundary":"get"} + \\ + , w.buffered()); +} diff --git a/tests/conformance/phase2/accept/unsafe_assume_fact.air b/tests/conformance/phase2/accept/unsafe_assume_fact.air new file mode 100644 index 0000000..1ab5e54 --- /dev/null +++ b/tests/conformance/phase2/accept/unsafe_assume_fact.air @@ -0,0 +1,19 @@ +; assume establishes a bounds fact like guard, so borrow.index.proven is accepted. +; expect: accept +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_assume_fact +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @f(%s: slice, %i: usize) -> u8 +effects [unsafe] +entry: + %n = slice.len %s + %c = lt.usize %i, %n + assume %c + %e = borrow.index.proven %s, %i + %v = load %e + borrow.end %e + ret %v diff --git a/tests/conformance/phase2/accept/unsafe_trusted_boundary.air b/tests/conformance/phase2/accept/unsafe_trusted_boundary.air new file mode 100644 index 0000000..cf0c875 --- /dev/null +++ b/tests/conformance/phase2/accept/unsafe_trusted_boundary.air @@ -0,0 +1,32 @@ +; A trusted function wraps an unchecked access; its callers stay safe. +; expect: accept +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_trusted_boundary +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @get(%s: slice, %i: usize) -> u8 +effects [] +trusted "callers pass %i < slice.len(%s)" +entry: + %e = borrow.index.unchecked %s, %i + %v = load %e + borrow.end %e + ret %v + +fn @main() -> u8 +effects [] +entry: + %x = local.alloc array + %nine = const.u8 9 + %a = array.splat array %nine + local.store %x, %a + %r = borrow.ref %x + %s = slice.make %r + %i = const.usize 1 + %v = call @get(%s, %i) + borrow.end %s + borrow.end %r + ret %v diff --git a/tests/conformance/phase2/reject/unsafe_call_from_safe.air b/tests/conformance/phase2/reject/unsafe_call_from_safe.air new file mode 100644 index 0000000..ee939b8 --- /dev/null +++ b/tests/conformance/phase2/reject/unsafe_call_from_safe.air @@ -0,0 +1,19 @@ +; A safe function calls an unsafe one without a trusted boundary. +; expect: reject E6001 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_call_from_safe +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @f() -> void +effects [] +entry: + call @raw() + ret + +fn @raw() -> void +effects [unsafe] +entry: + ret diff --git a/tests/conformance/phase2/reject/unsafe_empty_obligation.air b/tests/conformance/phase2/reject/unsafe_empty_obligation.air new file mode 100644 index 0000000..9d59a30 --- /dev/null +++ b/tests/conformance/phase2/reject/unsafe_empty_obligation.air @@ -0,0 +1,14 @@ +; The obligation of a trusted function must not be empty. +; expect: reject E0001 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_empty_obligation +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @f() -> void +effects [] +trusted "" +entry: + ret diff --git a/tests/conformance/phase2/reject/unsafe_outside_boundary.air b/tests/conformance/phase2/reject/unsafe_outside_boundary.air new file mode 100644 index 0000000..be68b43 --- /dev/null +++ b/tests/conformance/phase2/reject/unsafe_outside_boundary.air @@ -0,0 +1,16 @@ +; An unchecked access in a function that is neither unsafe nor trusted. +; expect: reject E6001 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_outside_boundary +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @f(%s: slice, %i: usize) -> u8 +effects [] +entry: + %e = borrow.index.unchecked %s, %i + %v = load %e + borrow.end %e + ret %v diff --git a/tests/conformance/phase2/reject/unsafe_trusted_declares_unsafe.air b/tests/conformance/phase2/reject/unsafe_trusted_declares_unsafe.air new file mode 100644 index 0000000..e7690b4 --- /dev/null +++ b/tests/conformance/phase2/reject/unsafe_trusted_declares_unsafe.air @@ -0,0 +1,14 @@ +; A trusted boundary cannot itself declare the effect unsafe. +; expect: reject E6001 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_trusted_declares_unsafe +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @f() -> void +effects [unsafe] +trusted "nothing to rely on" +entry: + ret diff --git a/tests/conformance/phase2/reject/unsafe_trusted_without_feature.air b/tests/conformance/phase2/reject/unsafe_trusted_without_feature.air new file mode 100644 index 0000000..3989045 --- /dev/null +++ b/tests/conformance/phase2/reject/unsafe_trusted_without_feature.air @@ -0,0 +1,14 @@ +; trusted belongs to the feature unsafe. +; expect: reject E0006 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_trusted_without_feature +air 0 +lang 0.1 +features [effects] + +fn @f() -> void +effects [] +trusted "x" +entry: + ret diff --git a/tests/conformance/phase2/run/unsafe_assume_violated.air b/tests/conformance/phase2/run/unsafe_assume_violated.air new file mode 100644 index 0000000..8054522 --- /dev/null +++ b/tests/conformance/phase2/run/unsafe_assume_violated.air @@ -0,0 +1,16 @@ +; A false assume is a detected unsafe precondition violation. +; expect: run +; trap: T0009 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_assume_violated +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @main() -> void +effects [unsafe] +entry: + %f = const.bool false + assume %f + ret diff --git a/tests/conformance/phase2/run/unsafe_precondition_violated.air b/tests/conformance/phase2/run/unsafe_precondition_violated.air new file mode 100644 index 0000000..ce7b8e7 --- /dev/null +++ b/tests/conformance/phase2/run/unsafe_precondition_violated.air @@ -0,0 +1,33 @@ +; The reference interpreter detects a violated unsafe precondition (T0009), not a bounds trap. +; expect: run +; trap: T0009 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_precondition_violated +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @get(%s: slice, %i: usize) -> u8 +effects [] +trusted "callers pass %i < slice.len(%s)" +entry: + %e = borrow.index.unchecked %s, %i + %v = load %e + borrow.end %e + ret %v + +fn @main() -> u8 +effects [] +entry: + %x = local.alloc array + %nine = const.u8 9 + %a = array.splat array %nine + local.store %x, %a + %r = borrow.ref %x + %s = slice.make %r + %i = const.usize 4 + %v = call @get(%s, %i) + borrow.end %s + borrow.end %r + ret %v diff --git a/tests/conformance/phase2/run/unsafe_trusted_call.air b/tests/conformance/phase2/run/unsafe_trusted_call.air new file mode 100644 index 0000000..6225494 --- /dev/null +++ b/tests/conformance/phase2/run/unsafe_trusted_call.air @@ -0,0 +1,33 @@ +; Calling a trusted boundary within its obligation works. +; expect: run +; result: 9 +; phase: 2 +; spec: docs/spec/13-contracts-and-unsafe.md +module test.unsafe_trusted_call +air 0 +lang 0.1 +features [arrays, effects, ownership, unsafe] + +fn @get(%s: slice, %i: usize) -> u8 +effects [] +trusted "callers pass %i < slice.len(%s)" +entry: + %e = borrow.index.unchecked %s, %i + %v = load %e + borrow.end %e + ret %v + +fn @main() -> u8 +effects [] +entry: + %x = local.alloc array + %nine = const.u8 9 + %a = array.splat array %nine + local.store %x, %a + %r = borrow.ref %x + %s = slice.make %r + %i = const.usize 3 + %v = call @get(%s, %i) + borrow.end %s + borrow.end %r + ret %v