cli: disambiguate block statement boundaries

This commit is contained in:
dev committed 2026-10-07 18:21:07 +03:00
1 parent 462ddd2c5c
commit 911982dd1c
33 files changed
+465 -7

No files matched your search

+2
View File
@@ -142,3 +142,5 @@ RFC 0036 (Proposed), explicit source borrow returns (cl100k, relative to paths):
RFC 0036 review fixes clarify reserved task borrow returns and known array bounds in unused generic signatures. These rules add 54 cl100k tokens: other source docs 64,160 → 64,214, full source 72,848 → 72,902 (+0.07%); Quick Reference stays 8,688. o200k groups are 8,723 / 64,413 / 73,136; Qwen2.5 8,954 / 65,794 / 74,748. language/ownership.md is 1,873 cl100k tokens; AIR and library/std.md stay unchanged. The additions make source rejection predictable without adding a semantic feature.
P6-8 source formatter (cl100k): Quick Reference 8,688 → 8,728 (+40), other source docs 64,214 → 64,677 (+463), full source 72,902 → 73,405 (+0.69%). language/tooling.md is 3,051 tokens. o200k groups are 8,763 / 64,876 / 73,639; Qwen2.5 8,994 / 66,259 / 75,253. AIR stays 179,282 bytes / 46,300 cl100k tokens, and library/std.md stays unchanged. One command with check/write modes reduces whitespace repair and diff noise while preserving tokens, comments and canonical AIR; it adds no language concept, feature, verifier/runtime state or diagnostic code. No empirical MCC benefit is claimed.
Q-040 block boundaries (DD-016, cl100k): Quick Reference 8,728 → 8,769 (+41), other source docs 64,677 → 65,012 (+335), full source 73,405 → 73,781 (+0.51%). o200k groups are 8,805 / 65,212 / 74,017; Qwen2.5 9,037 / 66,603 / 75,640. AIR and library/std.md are unchanged. One syntactic boundary rule and an explicit-discard guard replace an ambiguity; there is no new syntax form, diagnostic code or verifier/runtime state. No empirical MCC benefit is claimed.
+1 -1
View File
@@ -23,7 +23,7 @@ effects [io.read, io.write]
- `main`'s parameters are capabilities, granted by name: `aji run --grant input=io.read --grant out=io.write --stdin 'hi' main.aji`.
- Every function lists its effects after the signature. A missing effect is `E3101`, whose `suggested_effects` field is the full list to write.
- Statements end with `;`; `if`/`while`/`for`/`loop`/`match`/`select`/`scope`/`shield`/`lock` blocks do not.
- Statements end with `;`; block statements do not require one. A bare `if`, `match` or `{…}` at statement/tail start ends at its final `}`. Parenthesize it to continue with an operator. Before another statement it must yield `void` or diverge; use `;` to explicitly discard a value (`E7006` otherwise). Initializers, returns and arguments use ordinary expression parsing.
## 2. Types
+8
View File
@@ -87,3 +87,11 @@ Reason: format 0 is frozen; features make it an extensible protocol without an o
AIR format 0 defines `max_value_size` = 1 048 576 bytes. Every materializable type in a module has an accounted size (spec 08 §7.1, a platform-independent metric, not a layout) of at most this value; violation, including overflow while computing a size, is `E5101`, checked during module validation. `max_local_frame` (1 MiB per function) is a separate guarantee. Neither depends on host memory.
Reason: a verified IR needs its own deterministic validity limits instead of inheriting host behavior; and large data should live in storage reached through borrows, not travel as SSA values. Total allocation is bounded separately in Phase 2, as fuel bounds execution.
## DD-016 — Explicit block statement boundaries
Spec 15 §4 and the grammar resolve Q-040 syntactically: leading bare `if`, `match` and `{…}` finish before outer expression operations in statement/tail position. A final construct remains a tail; `;` explicitly discards its value; without either, a value-producing block statement is E7006. Parentheses opt into continuation, while explicit expression contexts retain full expression parsing.
Reason: `if true { *p = 2u64; } *p = 3u64;` must denote two statements regardless of spacing. Greedy expression parsing consumed multiplication instead. Merely splitting would silently change `{2i64} -3i64` from −1 to −3; rejecting the undiscarded value avoids that change. Neither line-sensitive syntax nor assignment lookahead is needed. This is a small grammar decision, not a new AIR facility.
Compatibility: formerly accepted bare continuations in statement/tail position require parentheses around the initial construct. Formerly accepted value-producing bare block statements require explicit `;`, including mixed branches such as `if c { return 1u64; } else { 2u64 }` before another statement. Existing tails, explicit discards and initializer/return/argument/condition/expression-arm continuations retain their meanings. Ownership, lexical borrow ends, verifier transfers and deterministic runtime rules are unchanged. A borrow bound inside a preceding block remains inaccessible afterwards (E7002); aliasing and task rules still come from the existing verifier. No new diagnostic code, source syntax form, feature or verifier/runtime state is added. One frontend statement marker enforces the value guard and gives the formatter an explicit boundary; it never changes tokens or inserts separators. No empirical Model Capability Compression benefit is claimed; source documentation growth is measured in docs/agent/README.md.
+2
View File
@@ -295,3 +295,5 @@ General collections and algorithms need explicit typed hash/equality/order opera
## Q-040 — Block statements followed by unary-leading expressions
P6-8 review found an existing parser ambiguity: `if true { *p = 2u64; } *p = *p + 1u64;` is consumed as an expression continued by multiplication and then rejects E7006 at the assignment. The same failure is reproduced after a standalone block or `match`; `while` dispatches separately and is not affected. Source whitespace is insignificant; spec 15 §4 and the grammar admit both block statements and expressions beginning with block/control-flow forms. The intended disambiguation must be specified before changing which previously parsed expressions are accepted. Decide how a standalone block statement ends before a dereference/other unary-leading statement while preserving block-valued expressions in explicit expression contexts. Add positive/rejected parser and lowering cases for the chosen rule. The formatter preserves the current tokens/AST and MUST NOT insert semicolons or infer the intended statement boundary. This question is separate from P6-8.
**Resolved (DD-016, spec 15 §4):** leading bare `if`, `match` and `{…}` in statement/tail position stop before outer expression operations. The next `}` selects a tail, `;` an explicit discard, otherwise a block statement must yield `void` or diverge (E7006). Parentheses permit continuation; nested expression contexts retain ordinary parsing. The value guard prevents silent reinterpretation of former expressions such as `{2i64} -3i64`. Parser, lowering, formatter and source conformance cover the boundary and compatibility rules. This resolves one P6-1/P6-2 ambiguity, not the complete grammar tasks.
+1 -1
View File
@@ -141,7 +141,7 @@ Targets for Phase 6A, measured on dev tasks:
## Standard library track
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is implemented for review (RFC 0036 Proposed), and P6-8 implements the source formatter. The existing block-statement ambiguity Q-040 is recorded for P6-1/P6-2; larger syntax/contracts work retains its separate spec gate. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is implemented for review (RFC 0036 Proposed), and P6-8 implements the source formatter. Q-040 is resolved by explicit block statement boundaries (DD-016, spec 15 §4), one P6-1/P6-2 ambiguity; larger syntax/contracts work retains its separate spec gate. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
## Task conventions
+6
View File
@@ -156,3 +156,9 @@ Validation: full conformance 1,135/1,135 with no failures or pending tests; 56 f
`aji fmt` formats one source file without linking, specializing, verifying or running it; `--check` emits a JSON status, and explicit `--write` atomically replaces a regular file while preserving permissions. Libraries and semantically rejected programs remain formattable. Original token spellings, comments and declaration order are retained; output is re-tokenized before exposure, and layout traversal is iterative. No syntax, AIR feature, verifier/runtime state or diagnostic code is added. Invalid syntax reports the existing E7001. The CLI contract and layout are spec 15 §11; the public-corpus/CLI script runs in CI.
Validation: unit tests and Zig formatting pass, including 10,000-term expressions, comments/CRLF, continuation indentation and statement groups. The formatter CLI suite passes 3,146 checks over 853 public files: 844 parse and format idempotently, nine existing syntax-error fixtures report E7001, and 548 successful lowerings retain byte-identical AIR. The suite also checks explicit writes, unchanged inode/mtime, permissions, symbolic/hard links, FIFO rejection, JSON/exit codes and a source run. Full conformance remains 1,135/1,135. Independent read-only review by Claude identified layout/comment handling defects; fixes were independently rechecked and covered by unit cases. Original source files are not rewritten. Documentation budgets are recorded in docs/agent/README.md. Review found the separate existing block-statement ambiguity Q-040; resolving its syntax belongs to P6-1/P6-2 and is not inferred by the formatter. This increment does not complete Phase 6.
## P6-1/P6-2 block boundary increment (2026-10-07)
Q-040 is resolved in spec 15 §4 and the grammar (DD-016): leading bare `if`, `match` and `{…}` finish before outer expression operations in statement/tail position. The enclosing `}` selects a tail, `;` an explicit discard, otherwise a block statement must yield `void` or diverge. This E7006 guard prevents silent reinterpretation of former expressions such as `{2i64} -3i64`; parenthesized continuations and nested expression contexts remain available. The parser marks block statements, ordinary/generic lowering checks the guard, and the formatter derives line boundaries from statement spans. No AIR feature, diagnostic code or verifier/runtime state is added. P6-1/P6-2 remain open for the rest of their grammar work.
Validation: full conformance passes 1,154/1,154 with no failures or pending tests, including 19 focused source cases covering stores, other unary starts, tails, explicit contexts/discards, generic bodies, mixed diverging/value branches and lexical borrow ends. Unit tests, Zig formatting, bundle/example checks and 120/120 construct coverage pass. The formatter/CLI suite passes 3,267 checks over 872 public files: 860 parse idempotently, 12 syntax-error fixtures reject with E7001, and 557 successful lowerings preserve byte-identical AIR. A before/after comparison over the original 853 public files finds no exit-code changes and identical AIR for all 548 successful lowerings. Independent read-only review by Claude found the silent value-discard risk in the initial design; the guard fixes it, and final review found no remaining issues. Budgets are recorded in docs/agent/README.md; frozen evaluation inputs are unchanged.
+7
View File
@@ -52,6 +52,13 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
(* A built-in operation is a call whose callee is a dotted path:
`own.new(v, mem)`, `region.new(arena, v)`, `cap.narrow.budget(c, n)`. *)
(* Statement/tail disambiguation (spec 15 §4): leading bare if_expr,
match_expr or block is consumed whole before choosing the production.
Next `}` makes it the tail, `;` explicitly discards its result, otherwise
it is a block_stmt whose result must be void or divergence (E7006).
No outer postfix/cast/binary continuation is consumed here; parenthesize
the construct for continuation. Nested expr contexts are unrestricted.
Other block_stmt forms end at their final `}`. Whitespace is irrelevant. *)
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
statement = "let" binding [ ":" type ] "=" expr ";"
| "var" ident ":" type "=" ( expr | "zero" ) ";"
+5 -1
View File
@@ -86,7 +86,11 @@ Arrays are written `[T; N]`. `scope`, `shield` and `guard<T>` are not source typ
## 4. Statements and control flow
Statements end with `;`. Block constructs (`if`, `while`, `for`, `loop`, `match`, `select`, `scope`, `shield`, `lock`, `{ … }`) do not take one.
Statements end with `;`. Block constructs (`if`, `while`, `for`, `loop`, `match`, `select`, `scope`, `shield`, `lock`, `{ … }`) do not require one.
**Block boundary.** At a statement or block-tail start, an unparenthesized `if`, `match` or `{ … }` MUST be parsed as one complete construct, including its `else` chain or arms, without consuming subsequent postfix, cast or binary operations. Immediately before the enclosing `}`, it is the tail expression; followed by `;`, it is an expression statement that explicitly discards its result; otherwise it is a block statement and MUST yield `void` or diverge (`E7006` for a value). This prevents an old value-producing expression from silently becoming two statements. Other block statements likewise end at their final `}`. Whitespace and comments MUST NOT affect these boundaries.
To continue such an expression in statement/tail position, parenthesize the complete construct: `({ 2u64 }) * 3u64`. Expression contexts (initializers, assignment right-hand sides, returns, arguments, conditions and expression arms) retain ordinary expression parsing: `return { 2u64 } * 3u64;` needs no extra parentheses.
| Source | Meaning |
|---|---|
+2
View File
@@ -145,6 +145,8 @@ pub const Select = struct {
pub const Stmt = struct {
span: Span,
/// Bare if/match/block without `;`: a value must not be silently discarded.
block_statement: bool = false,
kind: union(enum) {
let: struct { names: []const []const u8, ty: ?Type, e: Expr, tuple: bool = false },
/// `init == null` is `= zero`.
+18 -3
View File
@@ -11,7 +11,7 @@ const Error = error{ OutOfMemory, Invariant };
pub const Result = union(enum) { ok: []const u8, err: parse.Failure };
const Curly = enum { block, list, literal };
const Mark = struct { angle: bool = false, prefix: bool = false, curly: Curly = .block, top: bool = false, module_end: bool = false, mate: usize = 0, multiline: bool = false, layout_scope: usize = 0 };
const Mark = struct { angle: bool = false, prefix: bool = false, curly: Curly = .block, top: bool = false, module_end: bool = false, statement_end: bool = false, mate: usize = 0, multiline: bool = false, layout_scope: usize = 0 };
const Node = union(enum) { block: *const ast.Block, stmt: *const ast.Stmt, expr: *const ast.Expr };
pub fn format(arena: Allocator, source: []const u8) Error!Result {
@@ -107,7 +107,11 @@ const Formatter = struct {
// Iterative traversal also handles long left-associated expressions.
while (queue.pop()) |node| switch (node) {
.block => |b| {
for (b.stmts) |*s| try queue.append(f.arena, .{ .stmt = s });
for (b.stmts) |*s| {
const end = f.index(s.span.end);
if (end != 0 and f.tokens[end - 1].tag == .r_brace) f.marks[end - 1].statement_end = true;
try queue.append(f.arena, .{ .stmt = s });
}
if (b.tail) |e| try queue.append(f.arena, .{ .expr = e });
},
.stmt => |s| switch (s.kind) {
@@ -346,7 +350,7 @@ const Formatter = struct {
const frame = f.frames.items[f.frames.items.len - 1];
f.pending_line = frame.tag == .l_brace and frame.curly == .list;
},
.r_brace => f.pending_line = closing.?.curly != .literal and afterBlock(next),
.r_brace => f.pending_line = f.marks[i].statement_end or (closing.?.curly != .literal and afterBlock(next)),
else => {},
}
if (f.marks[i].module_end) f.pending_line = true;
@@ -407,6 +411,17 @@ test "libraries and syntax failures are independent of semantics" {
try std.testing.expect((try format(a.allocator(), "module bad fn main()->u64 effects [] {return 1}")) == .err);
}
test "AST statement boundaries separate unary starts without splitting expression contexts" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const input = "module m fn f()->u64 effects [] {if true {} else {} *p=2u64; match 0u64 {0=>{} _=>{}} -3i64; {} (1u64); {} [1u64;2]; let x={2u64}*3u64; ({2u64})*3u64}";
const output = (try format(a.allocator(), input)).ok;
for ([_][]const u8{ "else {}\n *p =", "}\n -3i64;", "{}\n (1u64);", "{}\n [1u64; 2];", "} * 3u64;", "}) * 3u64" }) |part| {
try std.testing.expect(std.mem.indexOf(u8, output, part) != null);
}
try std.testing.expectEqualStrings(output, (try format(a.allocator(), output)).ok);
}
test "angles, shifts, literals, grouping and standalone comments" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
+1 -1
View File
@@ -1184,7 +1184,7 @@ const Lowerer = struct {
},
.expr => |e| {
const v = try l.expr(e, null);
_ = v;
if (s.block_statement and v.ty != .void and v.ty != .never) return l.fail("E7006", s.span, "value-producing block statement: use `;` to discard the value or parentheses to continue the expression", &.{});
},
.@"while" => |x| try l.whileLoop(s.span, x.cond, x.body, null),
.loop => |b| try l.whileLoop(s.span, null, b, null),
+50
View File
@@ -473,6 +473,20 @@ const Parser = struct {
}
if (isWord(t, "select")) return .{ .span = p.span(start), .kind = .{ .select = try p.selectStmt() } };
// A leading bare block construct has priority over an outer expression
// continuation in statement/tail position (spec 15 §4). Recursive
// expression contexts still use expr(), including parentheses.
if (isWord(t, "if") or isWord(t, "match") or t.tag == .l_brace) {
const e = try p.primary();
if (p.peek().tag == .r_brace) {
tail.* = try p.box(ast.Expr, e);
return null;
}
const discard = p.peek().tag == .semicolon;
if (discard) _ = p.next();
return .{ .span = p.span(start), .block_statement = !discard, .kind = .{ .expr = e } };
}
// Expression statement, assignment or tail expression.
const e = try p.expr();
if (p.peek().tag == .eq) {
@@ -1003,3 +1017,39 @@ test "parse a function" {
try std.testing.expectEqualStrings("`;`", bad.err.expected);
try std.testing.expectEqual(@as(u32, 2), bad.err.pos.line);
}
test "bare block constructs end before unary-leading statements regardless of gaps" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
for ([_][]const u8{ "{}", "if true {} else if false {} else {}", "match 0u64 { 0 => {} _ => {} }" }) |construct| {
for ([_][]const u8{ " ", "\n", " // boundary\n" }) |gap| {
const source = try std.fmt.allocPrint(a, "module m fn f()->u64 effects [] {{{s}{s}*p=3u64; 42u64}}", .{ construct, gap });
const r = try parse(a, source);
try std.testing.expect(r == .ok);
const b = r.ok.functions[0].body;
try std.testing.expectEqual(@as(usize, 2), b.stmts.len);
try std.testing.expect(b.stmts[0].block_statement);
try std.testing.expect(b.stmts[1].kind == .assign);
try std.testing.expect(b.stmts[1].kind.assign.place.kind == .deref);
try std.testing.expect(b.tail.?.kind == .int);
}
}
}
test "tail, explicit discard and parentheses choose expression context syntactically" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const r = try parse(a, "module m fn f()->u64 effects [] {{2u64}; ({2u64})*3u64; {4u64}}");
try std.testing.expect(r == .ok);
const b = r.ok.functions[0].body;
try std.testing.expectEqual(@as(usize, 2), b.stmts.len);
try std.testing.expect(!b.stmts[0].block_statement);
try std.testing.expect(b.stmts[1].kind.expr.kind == .binary);
try std.testing.expect(b.tail.?.kind == .block);
for ([_][]const u8{ "+3u64", "as u64", ".x" }) |suffix| {
const source = try std.fmt.allocPrint(a, "module m fn f()->u64 effects [] {{{{2u64}} {s}}}", .{suffix});
try std.testing.expect((try parse(a, source)) == .err);
}
}
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.bare_cast
fn main()->u64 effects [] {{2u8} as u64}
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.bare_field
struct S {x:u64} fn main()->u64 effects [] {{S{x:2u64}}.x}
@@ -0,0 +1,6 @@
// expect: reject E7001
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.bare_plus
fn main()->u64 effects [] {{2u64} +3u64}
@@ -0,0 +1,36 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.bare_tails
fn a() -> u64 effects [] {
{
2u64
}
}
fn b() -> u64 effects [] {
if false {
1u64
} else if true {
3u64
} else {
0u64
}
}
fn c() -> u64 effects [] {
match 0u64 {
0 => {
4u64
}
_ => {
0u64
}
}
}
fn main() -> u64 effects [] {
a() + b() + c() + 33u64
}
@@ -0,0 +1,15 @@
// expect: run
// result: 5
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.block_then_store
fn main() -> u64 effects [] {
var x: u64 = 1u64;
mut p = x;
{
*p = 2u64;
}
*p = *p + 3u64;
return *p;
}
@@ -0,0 +1,17 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.block_then_unary
fn main() -> u64 effects [] {
{}
-3i64;
{}
(1u64 + 2u64);
{}
[4u64; 2];
{}
not false;
42u64
}
@@ -0,0 +1,14 @@
// expect: reject E7002
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.borrow_ends
fn main() -> u64 effects [] {
var x: u64 = 0u64;
{
mut p = x;
*p = 2u64;
}
*p = 3u64;
return x;
}
@@ -0,0 +1,21 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.diverging_or_void
fn f(c: bool) -> u64 effects [] {
var x: u64 = 0u64;
mut p = x;
if c {
return 42u64;
} else {
*p = 40u64;
}
*p = *p + 2u64;
return *p;
}
fn main() -> u64 effects [] {
(f(true) + f(false)) / 2u64
}
@@ -0,0 +1,59 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.explicit_contexts
fn id(x: u64) -> u64 effects [] {
x
}
fn f() -> u64 effects [] {
return {
2u64
} * 3u64;
}
fn main() -> u64 effects [] {
let a = if true {
1u64
} else {
2u64
} * 3u64;
var b: u64 = 0u64;
b = match 0u64 {
0 => {
2u64
}
_ => {
3u64
}
} * 3u64;
let c = id({
2u64
} * 3u64);
let d = match 0u64 {
0 => if true {
1u64
} else {
2u64
} + 5u64,
_ => 0u64,
};
let e = 1u64 + {
2u64
} * 3u64;
if {
true
}
and true {
assert(a == 3u64);
} else {
trap;
}
(if true {
a + b + c + d + e + f()
} else {
0u64
}) + 8u64
}
@@ -0,0 +1,12 @@
// expect: run
// result: -3
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.explicit_discard
fn main() -> i64 effects [] {
{
2i64
};
-3i64
}
@@ -0,0 +1,18 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.generic_block_store
fn set<T: Copy>(p: mut<T>, x: T) -> void effects [] {
if true {
*p = x;
}
*p = x;
}
fn main() -> u64 effects [] {
var x: u64 = 0u64;
set::<u64>(mut x, 42u64);
x
}
@@ -0,0 +1,15 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.generic_value_statement
fn f<T: Copy>(x: T) -> T effects [] {
{
x
}
return x;
}
fn main() -> u64 effects [] {
f::<u64>(42u64)
}
@@ -0,0 +1,20 @@
// expect: run
// result: 5
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.if_then_store
fn main() -> u64 effects [] {
var x: u64 = 1u64;
mut p = x;
if true {
*p = 2u64;
} // else chain
else if false {
*p = 3u64;
} else {
*p = 4u64;
}
*p = *p + 3u64;
return *p;
}
@@ -0,0 +1,18 @@
// expect: run
// result: 5
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.match_then_store
fn main() -> u64 effects [] {
var x: u64 = 1u64;
mut p = x;
match 0u64 {
0 => {
*p = 2u64;
}
_ => {}
}
*p = *p + 3u64;
return *p;
}
@@ -0,0 +1,13 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.mixed_value_branch
fn main() -> u64 effects [] {
if false {
return 1u64;
} else {
2u64
}
return 42u64;
}
@@ -0,0 +1,11 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.value_before_minus
fn main() -> i64 effects [] {
{
2i64
}
-3i64
}
@@ -0,0 +1,11 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.value_before_star
fn main() -> u64 effects [] {
{
2u64
}
*3u64
}
@@ -0,0 +1,13 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.value_if_statement
fn main() -> u64 effects [] {
if true {
2u64
} else {
3u64
}
return 0u64;
}
@@ -0,0 +1,16 @@
// expect: reject E7006
// phase: 6
// spec: docs/spec/15-source-language.md §4
module demo.value_match_statement
fn main() -> u64 effects [] {
match 0u64 {
0 => {
2u64
}
_ => {
3u64
}
}
return 0u64;
}
+34
View File
@@ -112,6 +112,40 @@ with tempfile.TemporaryDirectory(prefix="aji-format-") as directory:
assert b"// lit \t\n b: 2u64" in text
assert b"not (true and false)" in text
# Q-040: statement boundaries are lexical, not dependent on the original
# line breaks. Formatting exposes them without inserting separators.
for construct in ("{*p=2u64;}", "if true {*p=2u64;} else {}",
"match 0u64 {0=>{*p=2u64;} _=>{}}"):
for gap in (" ", "\n", " // boundary\n"):
source = ("module boundary fn main()->u64 effects [] {"
"var x:u64=1u64; mut p=x;" + construct + gap +
"*p=*p+3u64;return *p;}").encode()
sample = root / "boundary.aji"
sample.write_bytes(source)
original_air = cli("lower", sample)
assert json.loads(cli("run", "--fuel", "10000", sample))["value"] == 5
text = cli("fmt", sample)
assert b"}\n *p = *p + 3u64;" in text or b"// boundary\n *p = *p + 3u64;" in text
sample.write_bytes(text)
assert cli("fmt", sample) == text
assert cli("lower", sample) == original_air
# Former value-producing continuations must reject, rather than silently
# discard their left operand. A formatter can still format rejected code.
for body in ("{2u64} *3u64", "{2i64} -3i64",
"if true {2u64} else {3u64} return 0u64;",
"match 0u64 {0=>{2u64} _=>{3u64}} return 0u64;"):
sample = root / "value-boundary.aji"
source = ("module boundary fn main()->u64 effects [] {" + body + "}").encode()
sample.write_bytes(source)
error = json.loads(cli("lower", sample, code=1))
assert error["code"] == "E7006" and "parentheses" in error["message"]
assert error["line"] == 1 and error["col"] == source.index(body.encode()) + 1
text = cli("fmt", sample)
sample.write_bytes(text)
assert cli("fmt", sample) == text
assert json.loads(cli("lower", sample, code=1))["code"] == "E7006"
parsed = syntax_errors = lowered = 0
files = sorted({p for directory in (REPO / "tests/conformance/source", REPO / "std", REPO / "examples")
for p in directory.rglob("*.aji")})
+1
View File
@@ -20,6 +20,7 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source")
# (area, construct, regex, needs a reject test)
CHECKLIST = [
("block boundaries", "bare block before dereference", r"\}\s*\*", True),
("borrow returns", "explicit return origin", r"-> (?:ref|mut|slice|slice_mut)<[^>]+> from ", True),
("borrow returns", "returned view binding", r"(?:ref|mut) \w+ = (?:first|view|allocate)(?:::<[^>]+>)?\(", True),
("hashmap", "explicit general key policy and owning insert", r"std\.hashmap\.(insert|contains|get)::<", True),