diff --git a/docs/decisions/ATOMA-BETA-SCALAR.adoc b/docs/decisions/ATOMA-BETA-SCALAR.adoc new file mode 100644 index 00000000..dca5de9f --- /dev/null +++ b/docs/decisions/ATOMA-BETA-SCALAR.adoc @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += First beta slice for new Zig source + +Atoma's pilot alpha qualifies pinned Proven and UAA profiles. The first beta +slice exercises the ordinary source checker on a function written after those +profiles. It admits nested wrapping arithmetic by inspecting Zig syntax, so +admission does not depend on recognising the function name or its body text. + +[source,zig] +---- +/// @ensures result == value +% 5 +export fn advance_five(value: u8) callconv(.c) u8 { + return (value +% 253) +% 8; +} +---- + +Keep a closed module with one exported function, one named `u8` parameter and +one return. Lower the returned Zig AST expression into a bounded typed tree. +Admit the declared parameter, literals in the byte range, grouping, and +wrapping addition with a byte-typed operand. Track source spans for diagnostics. +Refuse imports, calls, extra declarations, other operators, and expressions +that would require rules for untyped comptime arithmetic. The separate +`@ensures` directive still describes the result as the input plus one byte +literal modulo 256. + +The evaluator traverses the body for all 256 inputs. SMT and Coq obligations +compare the lowered body with the independently parsed contract. ECHIDNA +compiles the generated theorem, coqchk checks the compiled library, and the +replay audit restates the expected theorem from the source. A separately +compiled native witness compares the actual exported function with widened +arithmetic over the same domain. + +Changing only the outer constant from eight to seven must expose input zero +with actual result four and expected result five. A nested ordinary addition +must produce a source diagnostic. Replay must reject reused proof text after a +source edit. The native evidence records the compiler, target and build mode. +The model replay remains target independent and its receipt remains INCOMPLETE. +The Zig frontend, lowering and compiler are still trusted for correspondence +with native execution. Proven and UAA retain their alpha proof and consumer +gates. diff --git a/docs/decisions/ATOMA-SOURCE-TO-PROOF.adoc b/docs/decisions/ATOMA-SOURCE-TO-PROOF.adoc index 6e291769..9a1140a1 100644 --- a/docs/decisions/ATOMA-SOURCE-TO-PROOF.adoc +++ b/docs/decisions/ATOMA-SOURCE-TO-PROOF.adoc @@ -67,6 +67,10 @@ cycles; imports, aliases and higher-order calls are not generally resolved. == Next semantic work +The first beta extension is scoped in +link:ATOMA-BETA-SCALAR.adoc[the new Zig source slice]. It exercises a nested +expression under the same closed byte contract and evidence boundary. + The R1 finite-model replay slice adds `source-coq` and `scripts/atoma-replay.sh`: actual ECHIDNA compilation, independent `coqchk`, and a closed-assumptions audit, with exact regenerated-proof/source binding. diff --git a/examples/atoma/source-u8/advance-five-unsupported.zig b/examples/atoma/source-u8/advance-five-unsupported.zig new file mode 100644 index 00000000..0f6b33b5 --- /dev/null +++ b/examples/atoma/source-u8/advance-five-unsupported.zig @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +/// @ensures result == value +% 5 +export fn advance_five(value: u8) callconv(.c) u8 { + return (value + 253) +% 8; +} diff --git a/examples/atoma/source-u8/advance-five-witness.zig b/examples/atoma/source-u8/advance-five-witness.zig new file mode 100644 index 00000000..e2a25d84 --- /dev/null +++ b/examples/atoma/source-u8/advance-five-witness.zig @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +const std = @import("std"); +extern fn advance_five(value: u8) callconv(.c) u8; + +test "compiled advance_five matches the widened oracle over all 256 inputs" { + for (0..256) |i| { + const value: u8 = @intCast(i); + const expected: u16 = (@as(u16, value) + 5) % 256; + try std.testing.expectEqual(expected, @as(u16, advance_five(value))); + } +} diff --git a/examples/atoma/source-u8/advance-five-wrong-body.zig b/examples/atoma/source-u8/advance-five-wrong-body.zig new file mode 100644 index 00000000..f084afa7 --- /dev/null +++ b/examples/atoma/source-u8/advance-five-wrong-body.zig @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +/// @ensures result == value +% 5 +export fn advance_five(value: u8) callconv(.c) u8 { + return (value +% 253) +% 7; +} diff --git a/examples/atoma/source-u8/advance-five.zig b/examples/atoma/source-u8/advance-five.zig new file mode 100644 index 00000000..e247544b --- /dev/null +++ b/examples/atoma/source-u8/advance-five.zig @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +/// @ensures result == value +% 5 +export fn advance_five(value: u8) callconv(.c) u8 { + return (value +% 253) +% 8; +} diff --git a/scripts/atoma-gate.sh b/scripts/atoma-gate.sh index e2de457b..369b0236 100644 --- a/scripts/atoma-gate.sh +++ b/scripts/atoma-gate.sh @@ -72,6 +72,49 @@ if "$ZIG" test "$pilot/compiled-witness.zig" "$evidence/wrong-body.o" > "$eviden fi grep -q 'TestExpectedEqual' "$evidence/compiled-bad.txt" +# Compositional scalar body with independent contract and native oracle. +beta="$evidence/beta-scalar" +mkdir -p "$beta" +positive="$pilot/advance-five.zig" +mutant="$pilot/advance-five-wrong-body.zig" +unsupported="$pilot/advance-five-unsupported.zig" +witness="$pilot/advance-five-witness.zig" +sed 's/+% 8;/+% 7;/' "$positive" | cmp - "$mutant" +sed 's/value +% 253/value + 253/' "$positive" | cmp - "$unsupported" +"$atoma" source-check "$positive" > "$beta/source-good.txt" +grep -q '^SOURCE-PILOT-CHECKED inputs=256 ' "$beta/source-good.txt" +status=0 +"$atoma" source-check "$mutant" > "$beta/source-counterexample.txt" || status=$? +[[ $status == 1 ]] +grep -qx 'SOURCE-COUNTEREXAMPLE input=0 actual=4 expected=5' "$beta/source-counterexample.txt" +status=0 +"$atoma" source-vc "$unsupported" > "$beta/source-unsupported.txt" || status=$? +[[ $status == 1 ]] +grep -Eq '^SOURCE-REFUSED .*UnsupportedSource at 5:19 \(byte [0-9]+\): unsupported return expression' "$beta/source-unsupported.txt" +"$atoma" source-vc "$positive" > "$beta/source-good.smt2" +"$atoma" source-vc "$mutant" > "$beta/source-bad.smt2" +beta_good=$("$Z3" -T:15 -smt2 "$beta/source-good.smt2") +beta_bad=$("$Z3" -T:15 -smt2 "$beta/source-bad.smt2") +printf 'advance-five %s\nsource-only mutant %s\n' "$beta_good" "$beta_bad" > "$beta/source-verdicts.txt" +[[ $beta_good == unsat && $beta_bad == sat ]] + +native_flags=(-target native -O Debug) +{ + printf 'target=native\nmode=Debug\n' + "$ZIG" env | grep -E '^[[:space:]]*\.target = ' + "$ZIG" version + sha256sum "$(realpath "$(command -v "$ZIG")")" +} > "$beta/native-profile.txt" +"$ZIG" build-obj "$positive" "${native_flags[@]}" -femit-bin="$beta/advance-five.o" +"$ZIG" test "$witness" "$beta/advance-five.o" "${native_flags[@]}" > "$beta/compiled-good.txt" 2>&1 +"$ZIG" build-obj "$mutant" "${native_flags[@]}" -femit-bin="$beta/advance-five-mutant.o" +if "$ZIG" test "$witness" "$beta/advance-five-mutant.o" "${native_flags[@]}" > "$beta/compiled-bad.txt" 2>&1; then + echo 'FAIL advance-five mutant survived exhaustive native witness'; exit 1 +fi +grep -Fq 'expected 5, found 4' "$beta/compiled-bad.txt" +grep -q 'TestExpectedEqual' "$beta/compiled-bad.txt" +sha256sum "$positive" "$mutant" "$unsupported" "$witness" "$beta"/{native-profile.txt,advance-five.o,advance-five-mutant.o,compiled-good.txt,compiled-bad.txt} > "$beta/native-inputs.sha256" + bash scripts/atoma-gate-falsifiers.sh | tee "$evidence/falsifiers.txt" bash scripts/atoma-replay-gate.sh | tee "$evidence/replay.txt" bash scripts/atoma-consumer-scalar-gate.sh | tee "$evidence/scalar-consumers.txt" diff --git a/scripts/atoma-replay-gate.sh b/scripts/atoma-replay-gate.sh index d4761b95..f9fb9a83 100644 --- a/scripts/atoma-replay-gate.sh +++ b/scripts/atoma-replay-gate.sh @@ -27,6 +27,14 @@ reject() { } "$ATOMA" source-coq "$pilot/wrong-body.zig" > "$work/wrong.v" reject wrong-body 'ECHIDNA did not verify' bash "$replay" "$pilot/wrong-body.zig" "$work/wrong.v" "$work/wrong-body" +"$ATOMA" source-coq "$pilot/advance-five.zig" > "$work/advance-five.v" +bash "$replay" "$pilot/advance-five.zig" "$work/advance-five.v" "$work/advance-five" +(cd "$work/advance-five" && sha256sum -c inputs.sha256) +reject advance-five-stale 'proof does not match current source' \ + bash "$replay" "$pilot/advance-five-wrong-body.zig" "$work/advance-five.v" "$work/advance-five-stale" +"$ATOMA" source-coq "$pilot/advance-five-wrong-body.zig" > "$work/advance-five-wrong.v" +reject advance-five-wrong 'ECHIDNA did not verify' \ + bash "$replay" "$pilot/advance-five-wrong-body.zig" "$work/advance-five-wrong.v" "$work/advance-five-wrong" printf '/// @ensures result == x +%% 0\nexport fn constant(x: u8) callconv(.c) u8 { return 0; }\n' > "$work/literal.zig" "$ATOMA" source-coq "$work/literal.zig" > "$work/literal.v" reject literal 'ECHIDNA did not verify' bash "$replay" "$work/literal.zig" "$work/literal.v" "$work/literal" @@ -83,4 +91,4 @@ printf 'Theorem admitted_control : False. Admitted.\nPrint Assumptions admitted_ grep -q '^Axioms:' assumptions.txt ! grep -q '^Closed under the global context$' assumptions.txt ) -echo 'REPLAY GATE PASS: two source-derived models checked, 11 rejection controls, axiom control; INCOMPLETE' +echo 'REPLAY GATE PASS: three source-derived models checked, 13 rejection controls, axiom control; INCOMPLETE' diff --git a/tools/atoma/src/main.zig b/tools/atoma/src/main.zig index 50a8e253..bd09c37e 100644 --- a/tools/atoma/src/main.zig +++ b/tools/atoma/src/main.zig @@ -112,8 +112,10 @@ pub fn main() !void { print("SOURCE-IO-ERROR {s}: {s}\n", .{ args[2], @errorName(e) }); std.process.exit(3); }; - const p = source.lower(gpa, src) catch |e| { - print("SOURCE-REFUSED {s}: {s}\n", .{ args[2], @errorName(e) }); + var diagnostic: source.Diagnostic = .{}; + const p = source.lower(gpa, src, &diagnostic) catch |e| { + const loc = diagnostic.location(src); + sourceReport("SOURCE-REFUSED {s}: {s} at {d}:{d} (byte {d}): {s}\n", .{ args[2], @errorName(e), loc.line, loc.column, diagnostic.offset, diagnostic.reason }); std.process.exit(switch (e) { error.ParseError, error.OutOfMemory => @as(u8, 3), else => @as(u8, 1), @@ -132,7 +134,7 @@ pub fn main() !void { std.process.exit(3); }; } else if (p.counterexample()) |x| { - print("SOURCE-COUNTEREXAMPLE input={d} actual={d} expected={d}\n", .{ x, p.body.eval(x), x +% p.ensures_add }); + sourceReport("SOURCE-COUNTEREXAMPLE input={d} actual={d} expected={d}\n", .{ x, p.body.eval(x), p.contract.expected(x) }); std.process.exit(1); } else { const hash = std.fmt.bytesToHex(p.source_hash, .lower); diff --git a/tools/atoma/src/source.zig b/tools/atoma/src/source.zig index cb722961..b40717ec 100644 --- a/tools/atoma/src/source.zig +++ b/tools/atoma/src/source.zig @@ -1,73 +1,140 @@ // SPDX-License-Identifier: MPL-2.0 // SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell -//! Experimental source-bound u8 pilot. This is deliberately a closed language: -//! one export, one u8 input, one return, and an equality postcondition. Anything -//! else is refused. Parsing/lowering and this evaluator are still trusted; -//! finite enumeration is evidence, not a kernel-checked refinement theorem. +//! Experimental source-bound u8 model with one export, one input, one return, +//! and an equality postcondition. Parsing and lowering remain trusted. const std = @import("std"); const Allocator = std.mem.Allocator; const Ast = std.zig.Ast; -pub const Expr = union(enum) { +const max_nodes = 63; +const max_depth = 16; +const max_tokens = 256; +const NodeIndex = u8; + +const Span = struct { + start: usize, + end: usize, +}; + +const Expr = union(enum) { input, literal: u8, - add_wrap: u8, + group: NodeIndex, + add_wrap: struct { left: NodeIndex, right: NodeIndex }, +}; - pub fn eval(self: Expr, x: u8) u8 { - return switch (self) { +const Node = struct { + expr: Expr, + span: Span, + // Each wrapping add requires a u8 operand. An input-free expression can + // only be an integer literal (possibly grouped), still needing coercion. + has_input: bool, +}; + +const Body = struct { + nodes: [max_nodes]Node = undefined, + len: u8 = 0, + + fn root(self: *const Body) NodeIndex { + return self.len - 1; + } + + fn append(self: *Body, node: Node) NodeIndex { + const index = self.len; + self.nodes[index] = node; + self.len += 1; + return index; + } + + pub fn eval(self: *const Body, x: u8) u8 { + return self.evalNode(self.root(), x); + } + + fn evalNode(self: *const Body, index: NodeIndex, x: u8) u8 { + return switch (self.nodes[index].expr) { .input => x, .literal => |n| n, - .add_wrap => |n| x +% n, + .group => |child| self.evalNode(child, x), + .add_wrap => |op| self.evalNode(op.left, x) +% self.evalNode(op.right, x), }; } - fn smt(self: Expr, w: *std.Io.Writer) !void { - switch (self) { + fn smt(self: *const Body, index: NodeIndex, w: *std.Io.Writer) std.Io.Writer.Error!void { + switch (self.nodes[index].expr) { .input => try w.writeAll("x"), .literal => |n| try w.print("(_ bv{d} 8)", .{n}), - .add_wrap => |n| try w.print("(bvadd x (_ bv{d} 8))", .{n}), + .group => |child| try self.smt(child, w), + .add_wrap => |op| { + try w.writeAll("(bvadd "); + try self.smt(op.left, w); + try w.writeByte(' '); + try self.smt(op.right, w); + try w.writeByte(')'); + }, } } - fn coq(self: Expr, w: *std.Io.Writer) !void { - switch (self) { + fn coq(self: *const Body, index: NodeIndex, w: *std.Io.Writer, operand: bool) std.Io.Writer.Error!void { + switch (self.nodes[index].expr) { .input => try w.writeAll("x"), .literal => |n| try w.print("{d}", .{n}), - .add_wrap => |n| try w.print("(x + {d}) mod 256", .{n}), + .group => |child| { + try w.writeByte('('); + try self.coq(child, w, false); + try w.writeByte(')'); + }, + .add_wrap => |op| { + if (operand) try w.writeByte('('); + try w.writeByte('('); + try self.coq(op.left, w, true); + try w.writeAll(" + "); + try self.coq(op.right, w, true); + try w.writeAll(") mod 256"); + if (operand) try w.writeByte(')'); + }, } } }; +const Contract = struct { + add: u8, + span: Span, + + pub fn expected(self: Contract, x: u8) u8 { + return x +% self.add; + } +}; + pub const Program = struct { - body: Expr, - ensures_add: u8, + body: Body, + contract: Contract, source_hash: [32]u8, - pub fn counterexample(self: Program) ?u8 { + pub fn counterexample(self: *const Program) ?u8 { for (0..256) |i| { const x: u8 = @intCast(i); - if (self.body.eval(x) != x +% self.ensures_add) return x; + if (self.body.eval(x) != self.contract.expected(x)) return x; } return null; } - pub fn emit(self: Program, w: *std.Io.Writer) !void { + pub fn emit(self: *const Program, w: *std.Io.Writer) !void { const hash = std.fmt.bytesToHex(self.source_hash, .lower); try w.print("; atoma.source.u8.v1 source-blake3:{s}\n", .{hash}); try w.writeAll("; Warrant only: frontend and compiler refinement remain trusted\n(set-logic QF_BV)\n(declare-fun x () (_ BitVec 8))\n(assert (not (= "); - try self.body.smt(w); - try w.print(" (bvadd x (_ bv{d} 8)))))\n(check-sat)\n", .{self.ensures_add}); + try self.body.smt(self.body.root(), w); + try w.print(" (bvadd x (_ bv{d} 8)))))\n(check-sat)\n", .{self.contract.add}); } /// A closed finite-model theorem, not a Zig/compiler refinement proof or /// a translation of a solver certificate. A wrong body emits a false /// obligation that Coq must reject; no evaluator verdict selects the proof. - pub fn emitCoq(self: Program, w: *std.Io.Writer) !void { + pub fn emitCoq(self: *const Program, w: *std.Io.Writer) !void { const hash = std.fmt.bytesToHex(self.source_hash, .lower); try w.print("(* atoma.source.u8.coq.v1 source-blake3:{s} *)\n", .{hash}); try w.writeAll("From Coq Require Import Arith List Bool.\nDefinition body (x : nat) : nat := "); - try self.body.coq(w); - try w.print(".\nDefinition specification (x : nat) : nat := (x + {d}) mod 256.\n", .{self.ensures_add}); + try self.body.coq(self.body.root(), w, false); + try w.print(".\nDefinition specification (x : nat) : nat := (x + {d}) mod 256.\n", .{self.contract.add}); try w.writeAll( \\Definition domain_check : bool := \\ forallb (fun x => Nat.eqb (body x) (specification x)) (seq 0 256). @@ -89,64 +156,166 @@ pub const Program = struct { /// Restate the expected theorem from source. Referring to body/specification /// inside the returned library would only check that library against itself. - pub fn emitCoqAudit(self: Program, w: *std.Io.Writer) !void { + pub fn emitCoqAudit(self: *const Program, w: *std.Io.Writer) !void { const hash = std.fmt.bytesToHex(self.source_hash, .lower); try w.print("(* atoma.source.u8.audit.v1 source-blake3:{s} *)\n", .{hash}); try w.writeAll("From Coq Require Import Arith.\nRequire Import AtomaProof.\nCheck (AtomaProof.atoma_u8 : forall x : nat, x < 256 -> "); - try self.body.coq(w); - try w.print(" = (x + {d}) mod 256).\nPrint Assumptions AtomaProof.atoma_u8.\n", .{self.ensures_add}); + try self.body.coq(self.body.root(), w, false); + try w.print(" = (x + {d}) mod 256).\nPrint Assumptions AtomaProof.atoma_u8.\n", .{self.contract.add}); + } +}; + +pub const Diagnostic = struct { + offset: usize = 0, + reason: []const u8 = "source could not be read by the frontend", + + fn record(self: *Diagnostic, offset: usize, reason: []const u8) void { + self.* = .{ .offset = offset, .reason = reason }; + } + + pub fn location(self: Diagnostic, src: []const u8) struct { line: usize, column: usize } { + var line: usize = 1; + var column: usize = 1; + for (src[0..self.offset]) |byte| { + if (byte == '\n') { + line += 1; + column = 1; + } else column += 1; + } + return .{ .line = line, .column = column }; } }; +fn tokenSpan(ast: *const Ast, token: Ast.TokenIndex) Span { + const start: usize = ast.tokenStart(token); + return .{ .start = start, .end = start + ast.tokenSlice(token).len }; +} + const Cursor = struct { ast: *const Ast, - pos: u32 = 0, + diag: *Diagnostic, + pos: Ast.TokenIndex = 0, fn text(self: *Cursor) []const u8 { return self.ast.tokenSlice(self.pos); } + + fn refuse(self: *Cursor, token: Ast.TokenIndex, reason: []const u8) error{UnsupportedSource} { + self.diag.record(self.ast.tokenStart(token), reason); + return error.UnsupportedSource; + } + fn take(self: *Cursor, want: []const u8) !void { - if (!std.mem.eql(u8, self.text(), want)) return error.UnsupportedSource; + if (!std.mem.eql(u8, self.text(), want)) return self.refuse(self.pos, "expected the closed export or single-return syntax"); self.pos += 1; } + fn ident(self: *Cursor) ![]const u8 { - if (self.ast.tokens.items(.tag)[self.pos] != .identifier) return error.UnsupportedSource; + if (self.ast.tokenTag(self.pos) != .identifier) return self.refuse(self.pos, "expected a plain identifier"); const name = self.text(); - // No quoted identifiers or builtin/type shadowing in this pilot. - if (name.len == 0 or name[0] == '@' or std.mem.eql(u8, name, "_") or std.zig.isPrimitive(name)) return error.UnsupportedSource; + if (name.len == 0 or name[0] == '@' or std.mem.eql(u8, name, "_") or std.zig.isPrimitive(name)) + return self.refuse(self.pos, "quoted, discard, and primitive names are outside the profile"); self.pos += 1; return name; } - fn number(self: *Cursor) !u8 { - if (self.ast.tokens.items(.tag)[self.pos] != .number_literal) return error.UnsupportedSource; - const n = std.fmt.parseInt(u8, self.text(), 0) catch return error.UnsupportedSource; - self.pos += 1; - return n; + + fn lowerExpr(self: *Cursor, body: *Body, input: []const u8, node: Ast.Node.Index, depth: usize) error{UnsupportedSource}!NodeIndex { + const ast = self.ast; + const token = ast.nodeMainToken(node); + if (depth > max_depth) return self.refuse(token, "expression depth exceeds 16"); + var lowered: Node = .{ .expr = undefined, .span = tokenSpan(ast, token), .has_input = false }; + switch (ast.nodeTag(node)) { + .identifier => { + if (!std.mem.eql(u8, ast.tokenSlice(token), input)) return self.refuse(token, "expected the declared u8 parameter"); + lowered.expr = .input; + lowered.has_input = true; + }, + .number_literal => { + const n = switch (std.zig.parseNumberLiteral(ast.tokenSlice(token))) { + .int => |value| std.math.cast(u8, value) orelse return self.refuse(token, "expected an integer literal in 0..255"), + else => return self.refuse(token, "expected an integer literal in 0..255"), + }; + lowered.expr = .{ .literal = n }; + }, + .grouped_expression => { + const child_node, const close_token = ast.nodeData(node).node_and_token; + const child = try self.lowerExpr(body, input, child_node, depth + 1); + lowered.expr = .{ .group = child }; + lowered.span.end = tokenSpan(ast, close_token).end; + lowered.has_input = body.nodes[child].has_input; + }, + .add_wrap => { + const left_node, const right_node = ast.nodeData(node).node_and_node; + const left = try self.lowerExpr(body, input, left_node, depth + 1); + const right = try self.lowerExpr(body, input, right_node, depth + 1); + if (!body.nodes[left].has_input and !body.nodes[right].has_input) + return self.refuse(token, "wrapping addition requires an operand typed by the u8 parameter"); + lowered.expr = .{ .add_wrap = .{ .left = left, .right = right } }; + lowered.span = .{ .start = body.nodes[left].span.start, .end = body.nodes[right].span.end }; + lowered.has_input = true; + }, + else => return self.refuse(token, "unsupported return expression; expected parameter, u8 literal, grouping, or +%"), + } + if (body.len == max_nodes) return self.refuse(token, "expression exceeds 63 nodes"); + return body.append(lowered); } }; -pub fn lower(alloc: Allocator, src: []const u8) !Program { +pub fn lower(alloc: Allocator, src: []const u8, diagnostic: ?*Diagnostic) !Program { + var local_diag: Diagnostic = .{}; + const diag = diagnostic orelse &local_diag; + diag.* = .{}; + if (std.mem.indexOfScalar(u8, src, 0)) |offset| { + diag.record(offset, "embedded NUL byte"); + return error.ParseError; + } const srcz = try alloc.dupeZ(u8, src); defer alloc.free(srcz); + // Bound work in the pinned Zig parser before it sees nested syntax. + var tokenizer = std.zig.Tokenizer.init(srcz); + for (0..max_tokens + 1) |count| { + const token = tokenizer.next(); + if (token.tag == .eof) break; + if (count == max_tokens) { + diag.record(token.loc.start, "source exceeds 256 tokens"); + return error.UnsupportedSource; + } + } var ast = try Ast.parse(alloc, srcz, .zig); defer ast.deinit(alloc); - if (ast.errors.len != 0) return error.ParseError; - var c = Cursor{ .ast = &ast }; - var post: ?[]const u8 = null; - while (ast.tokens.items(.tag)[c.pos] == .doc_comment) : (c.pos += 1) { + if (ast.errors.len != 0) { + diag.record(ast.tokenStart(ast.errors[0].token), "invalid Zig syntax"); + return error.ParseError; + } + var c = Cursor{ .ast = &ast, .diag = diag }; + var post_token: ?Ast.TokenIndex = null; + while (ast.tokenTag(c.pos) == .doc_comment) : (c.pos += 1) { const comment = std.mem.trim(u8, c.text()[3..], " \t\r"); if (std.mem.startsWith(u8, comment, "@ensures ")) { - if (post != null) return error.UnsupportedContract; - post = comment[9..]; - } else if (std.mem.indexOfScalar(u8, comment, '@') != null) return error.UnsupportedContract; + if (post_token != null) { + diag.record(ast.tokenStart(c.pos), "duplicate @ensures clause"); + return error.UnsupportedContract; + } + post_token = c.pos; + } else if (std.mem.indexOfScalar(u8, comment, '@') != null) { + diag.record(ast.tokenStart(c.pos), "unsupported contract annotation"); + return error.UnsupportedContract; + } } - const formula = post orelse return error.MissingContract; + const annotation = post_token orelse { + diag.record(ast.tokenStart(c.pos), "expected an @ensures clause on the export"); + return error.MissingContract; + }; + + // Constrain the declaration independently from lowering the return value. try c.take("export"); + const fn_token = c.pos; try c.take("fn"); const function_name = try c.ident(); try c.take("("); + const input_token = c.pos; const input = try c.ident(); - if (std.mem.eql(u8, input, function_name)) return error.UnsupportedSource; + if (std.mem.eql(u8, input, function_name)) return c.refuse(input_token, "parameter shadows the export name"); try c.take(":"); try c.take("u8"); try c.take(")"); @@ -156,32 +325,52 @@ pub fn lower(alloc: Allocator, src: []const u8) !Program { try c.take("c"); try c.take(")"); try c.take("u8"); + const block_token = c.pos; try c.take("{"); + const return_token = c.pos; try c.take("return"); - var body: Expr = undefined; - if (std.mem.eql(u8, c.text(), input)) { - c.pos += 1; - if (std.mem.eql(u8, c.text(), "+%")) { - c.pos += 1; - body = .{ .add_wrap = try c.number() }; - } else body = .input; - } else body = .{ .literal = try c.number() }; + + const decls = ast.rootDecls(); + if (decls.len == 0 or ast.nodeTag(decls[0]) != .fn_decl or ast.nodeMainToken(decls[0]) != fn_token) + return c.refuse(fn_token, "expected a top-level function definition"); + if (decls.len != 1) return c.refuse(ast.firstToken(decls[1]), "expected exactly one top-level declaration"); + const block = ast.nodeData(decls[0]).node_and_node[1]; + var statement_buffer: [2]Ast.Node.Index = undefined; + const statements = ast.blockStatements(&statement_buffer, block) orelse return c.refuse(block_token, "expected a plain function block"); + if (ast.nodeMainToken(block) != block_token or statements.len == 0 or ast.nodeTag(statements[0]) != .@"return" or ast.nodeMainToken(statements[0]) != return_token) + return c.refuse(return_token, "expected one return statement"); + if (statements.len != 1) return c.refuse(ast.nodeMainToken(statements[1]), "expected one return statement"); + const expr = ast.nodeData(statements[0]).opt_node.unwrap() orelse return c.refuse(return_token, "expected a return value"); + if (ast.firstToken(expr) != c.pos) return c.refuse(c.pos, "expected the return expression"); + var body: Body = .{}; + _ = try c.lowerExpr(&body, input, expr, 1); + c.pos = ast.lastToken(expr) + 1; try c.take(";"); try c.take("}"); - if (ast.tokens.items(.tag)[c.pos] != .eof) return error.UnsupportedSource; + if (ast.tokenTag(c.pos) != .eof) return c.refuse(c.pos, "expected the end of the closed module"); + const contract_span = tokenSpan(&ast, annotation); + const formula = std.mem.trim(u8, ast.tokenSlice(annotation)[3..], " \t\r")[9..]; + const add = parseContract(formula, input) catch |err| { + diag.record(contract_span.start, "expected @ensures result == +% "); + return err; + }; + var hash: [32]u8 = undefined; + var hasher = std.crypto.hash.Blake3.init(.{}); + hasher.update("atoma.source.u8.v1\n"); + hasher.update(src); + hasher.final(&hash); + return .{ .body = body, .contract = .{ .add = add, .span = contract_span }, .source_hash = hash }; +} + +fn parseContract(formula: []const u8, input: []const u8) !u8 { var words = std.mem.tokenizeAny(u8, formula, " \t\r"); for ([_][]const u8{ "result", "==", input, "+%" }) |want| { if (!std.mem.eql(u8, words.next() orelse return error.UnsupportedContract, want)) return error.UnsupportedContract; } const add = std.fmt.parseInt(u8, words.next() orelse return error.UnsupportedContract, 0) catch return error.UnsupportedContract; if (words.next() != null) return error.UnsupportedContract; - var hash: [32]u8 = undefined; - var hasher = std.crypto.hash.Blake3.init(.{}); - hasher.update("atoma.source.u8.v1\n"); - hasher.update(src); - hasher.final(&hash); - return .{ .body = body, .ensures_add = add, .source_hash = hash }; + return add; } const good = @@ -190,10 +379,10 @@ const good = ; test "source-derived u8 obligation includes overflow edge and source identity" { - const p = try lower(std.testing.allocator, good); + const p = try lower(std.testing.allocator, good, null); try std.testing.expectEqual(@as(?u8, null), p.counterexample()); try std.testing.expectEqual(@as(u8, 0), p.body.eval(255)); - const q = try lower(std.testing.allocator, good ++ "\n// changed source\n"); + const q = try lower(std.testing.allocator, good ++ "\n// changed source\n", null); try std.testing.expect(!std.mem.eql(u8, &p.source_hash, &q.source_hash)); var out = std.Io.Writer.Allocating.init(std.testing.allocator); defer out.deinit(); @@ -206,7 +395,7 @@ test "wrong body with unchanged contract has a counterexample" { \\/// @ensures result == x +% 1 \\export fn increment(x: u8) callconv(.c) u8 { return x +% 2; } ; - const p = try lower(std.testing.allocator, bad); + const p = try lower(std.testing.allocator, bad, null); try std.testing.expectEqual(@as(?u8, 0), p.counterexample()); } @@ -218,10 +407,33 @@ test "closed pilot rejects calls imports branching ordinary addition and contrac prefix ++ "if (x == 0) return 1; return x; }", prefix ++ "return x +% 256; }", good ++ "\nconst other = @import(\"other.zig\");", - }) |src| try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, src)); - try std.testing.expectError(error.MissingContract, lower(std.testing.allocator, "const hidden = @import(\"other.zig\");\n" ++ good)); - try std.testing.expectError(error.UnsupportedContract, lower(std.testing.allocator, "/// @requires true\n" ++ good)); - try std.testing.expectError(error.UnsupportedContract, lower(std.testing.allocator, "/// @ensures result == x +% 1\n" ++ good)); - try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, "/// @ensures result == _ +% 1\nexport fn f(_: u8) callconv(.c) u8 { return _; }")); - try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, "/// @ensures result == x +% 1\nexport fn bool(x: u8) callconv(.c) u8 { return x; }")); + }) |src| try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, src, null)); + try std.testing.expectError(error.MissingContract, lower(std.testing.allocator, "const hidden = @import(\"other.zig\");\n" ++ good, null)); + try std.testing.expectError(error.UnsupportedContract, lower(std.testing.allocator, "/// @requires true\n" ++ good, null)); + try std.testing.expectError(error.UnsupportedContract, lower(std.testing.allocator, "/// @ensures result == x +% 1\n" ++ good, null)); + try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, "/// @ensures result == _ +% 1\nexport fn f(_: u8) callconv(.c) u8 { return _; }", null)); + try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, "/// @ensures result == x +% 1\nexport fn bool(x: u8) callconv(.c) u8 { return x; }", null)); +} + +test "grouped operands retain their source span and take their type from either side" { + const src = "/// @ensures result == value +% 0\nexport fn identity(value: u8) callconv(.c) u8 { return (1) +% (value +% 0xff); }"; + const p = try lower(std.testing.allocator, src, null); + try std.testing.expectEqual(@as(?u8, null), p.counterexample()); + const span = p.body.nodes[p.body.root()].span; + try std.testing.expectEqualStrings("(1) +% (value +% 0xff)", src[span.start..span.end]); + try std.testing.expectEqualStrings("/// @ensures result == value +% 0", src[p.contract.span.start..p.contract.span.end]); +} + +test "nested unsupported operations report the offending token" { + const prefix = "/// @ensures result == x +% 1\nexport fn increment(x: u8) callconv(.c) u8 { return "; + for ([_][]const u8{ "x +% (2 + 3)", "x +% (2 +% 3)", "x +% 0x_1" }, [_][]const u8{ "+", "+%", "0x_1" }) |expr, token| { + var diagnostic: Diagnostic = .{}; + const src = try std.fmt.allocPrint(std.testing.allocator, "{s}{s}; }}", .{ prefix, expr }); + defer std.testing.allocator.free(src); + try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, src, &diagnostic)); + try std.testing.expectEqualStrings(token, src[diagnostic.offset..][0..token.len]); + try std.testing.expectEqual(@as(usize, 2), diagnostic.location(src).line); + } + const deep = prefix ++ ("(" ** 16) ++ "x" ++ (")" ** 16) ++ "; }"; + try std.testing.expectError(error.UnsupportedSource, lower(std.testing.allocator, deep, null)); }