frontend: align source grammar and reject empty enum payload lists
This commit is contained in:
1 parent
48b9b42fed
commit
4c9c5626c9
44 files changed
+501
-33
No files matched your search
@@ -35,6 +35,7 @@ jobs:
|
||||
- run: python3 tests/hosted/source_nonvalue_operands.py
|
||||
- run: python3 tests/hosted/source_store_modes.py
|
||||
- run: python3 tests/hosted/source_nominal_queries.py
|
||||
- run: python3 tests/hosted/source_grammar.py
|
||||
- run: python3 tests/hosted/examples.py --stress 200
|
||||
- run: python3 tests/hosted/source_static_functions.py
|
||||
- run: python3 tests/hosted/source_linear.py
|
||||
|
||||
@@ -31,6 +31,7 @@ python3 tests/hosted/source_inferred_content.py # constructor content, transfers
|
||||
python3 tests/hosted/source_nonvalue_operands.py # never operands, divergent receivers, traps and package provenance
|
||||
python3 tests/hosted/source_store_modes.py # exclusive places, source positions, array modes and package provenance
|
||||
python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices
|
||||
python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity
|
||||
python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules
|
||||
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
|
||||
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
|
||||
|
||||
@@ -166,3 +166,5 @@ Q-046 inferred constructor content (cl100k): Quick Reference stays 8,948; other
|
||||
Q-047 non-value operands (cl100k): Quick Reference stays 8,948; other source docs 67,074 → 67,258 (+184), full source 76,022 → 76,206 (+0.24%). o200k groups are 8,984 / 67,461 / 76,445; Qwen2.5 9,226 / 68,912 / 78,138. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Typed operation inputs reject never before subsequent emission; divergent returns/branches/statements and variable receivers retain their control flow, and frame receivers skip writes. Store values remain required. Invalid-source diagnostic order may change; accepted canonical AIR is preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added. No empirical MCC benefit is claimed.
|
||||
|
||||
Q-048 source access modes (cl100k): Quick Reference stays 8,948; other source docs 67,258 → 67,343 (+85), full source 76,206 → 76,291 (+0.11%). o200k groups are 8,984 / 67,546 / 76,530; Qwen2.5 9,226 / 69,001 / 78,227. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Shared places reject at source stores and explicit mut bindings/arguments before array shape conversion; valid canonical AIR is preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added. No empirical MCC benefit is claimed.
|
||||
|
||||
DD-022 grammar surface (cl100k): Quick Reference stays 8,948; other source docs 67,343 → 68,219 (+876), full source 76,291 → 77,167 (+1.15%). o200k groups are 8,984 / 68,422 / 77,406; Qwen2.5 9,226 / 69,887 / 79,113. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing syntax and ordered parsing choices replace incomplete grammar descriptions. Empty qualified enum payload lists now reject E7001; accepted public-source canonical AIR is preserved. No new programming concept, feature, diagnostic code or verifier/runtime state is added. The grammar stays a reference read on demand; no empirical MCC benefit is claimed.
|
||||
@@ -131,3 +131,9 @@ Q-023 is resolved in spec 15 §5: a temporary `ref`/`mut` argument preserves its
|
||||
Invariant: temporary children and ancestors remain live through the call, then end child first; no view escapes a temporary origin. Existing AIR type, aliasing, initialization, bounds, origin and task-loan verification remains authoritative. Runtime and deterministic interpreter rules are unchanged. Valid: `fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }` called with `first(ref data)` for a two-element array. A different length or explicit mode rejects E7005; overlapping exclusive/shared arguments reject E2101. Returning a view from an inline origin and lending an inline argument to a task retain E7006.
|
||||
|
||||
Compatibility: formerly rejected array-borrow calls become available; accepted source retains canonical AIR. No new syntax, AIR instruction/feature, diagnostic, verifier/runtime state, allocation or cleanup semantics. The frontend selects array versus slice using the parameter, then emits existing borrow/reborrow and end instructions. Source/AIR conformance and CLI checks cover projections, modes, specialization, packages and temporary cleanup. Source budget growth is recorded in docs/agent/README.md; AIR is unchanged. This improves explicitness and completes source access to an existing primitive without a measured MCC claim.
|
||||
|
||||
## DD-022 — Document ordered source parsing and canonical enum payload lists
|
||||
|
||||
P6-1/P6-2 synchronizes the grammar with implemented syntax: graph/atomic wrappers, binary literals, signed integer patterns, parenthesized places, declared borrow-return calls and existing list/arm punctuation. Contextual words and the ordered choices for statements, body-opening braces and typed built-ins are explicit. The grammar is not claimed to be LL(k). Existing grouping and optional list delimiters introduce no operation; formatter token preservation remains mandatory.
|
||||
|
||||
Q-050 corrects empty parentheses on qualified enum variants, contrary to spec 15 §5–§6. Construction and pattern parsing reject E7001 at the opening parenthesis without symbol lookup, including generic, qualified and built-in variants. Payload-bearing variants with empty lists change from E7005 to E7001; non-empty arity/type checks remain. Bare variants, ordinary zero-argument calls and empty outcome bindings retain their meanings. No AIR, verifier, runtime, ownership/concurrency, feature or code changes; accepted public-source canonical AIR is preserved. Source grammar/CLI tests cover both sides and formatting. Bundle growth is recorded in docs/agent/README.md. Future grammar features still require their RFCs; P6-1 remains open. Q-051 separately records unknown ordinary-function effects.
|
||||
@@ -362,3 +362,13 @@ Audit existing place modes and referents against spec 15 §4/§5 and AIR borrow/
|
||||
## Q-049 — Immutable Copy bindings and mutable frame content
|
||||
|
||||
Read-only Q-048 review reproduced accepted `let p = Pair { a: 0u64 }; p.a = 42u64; return p.a;`, and exclusive borrows of Copy-let frame storage. Spec 15 §4 calls `let` an immutable binding; assignment by name already rejects. Whether this should also prohibit content writes through fields/indices/borrows is unresolved. Owned content through `let` intentionally remains mutable and is used by public std examples. Do not infer a new restriction from `Binding.mutable`: distinguish Copy frame storage from owners, regions, resources and borrow bindings, and settle the normative policy before changing accepted source. This question is independent of Q-048's existing shared/exclusive borrow modes.
|
||||
|
||||
## Q-050 — Empty parentheses on qualified enum variants
|
||||
|
||||
The parser accepted `E::Empty()` and the corresponding match pattern, although spec 15 §5 requires a bare payload-free variant. Public tests/examples/std contain no such forms. Outcome binding lists such as `closed()` are separate delimiters used by std and remain legal.
|
||||
|
||||
**Resolved (DD-022, spec 15 §5–§6):** qualified variant construction and patterns reject empty payload lists with E7001 at `(`, without symbol lookup. This includes payload-bearing variants formerly rejected with E7005; non-empty lists retain their existing arity/type checks. Ordinary calls, grouping and outcome bindings are unaffected. No AIR or runtime rule changes.
|
||||
|
||||
## Q-051 — Unknown effects in ordinary source signatures
|
||||
|
||||
An ordinary function declaring `effects [bogus.effect]` reaches AIR and reports E7900 with `air_code: E0004`; templates/static contracts reject the same known-invalid effect directly with E0006. Effect membership is determined entirely from source and the registry. A P6-2 task should align ordinary signature validation with the existing template contract, preserving effect/capability semantics and checking diagnostic priority/positions. No implementation is included in DD-022.
|
||||
@@ -129,7 +129,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
|
||||
| ID | Status | Task | Depends | Output | Done when |
|
||||
|---|---|---|---|---|---|
|
||||
| P6-1 | todo | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous |
|
||||
| P6-1 | doing | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous |
|
||||
| P6-2 | doing | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics |
|
||||
| P6-3 | done (RFC 0021 Implemented) | Explicit package modules, direct imports and qualified nominal types | P6-2 | `src/frontend/modules.zig`, spec 15 §14 | deterministic graph/name resolution; source/AIR and CLI tests |
|
||||
| P6-4 | done (RFC 0022 Implemented) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed |
|
||||
@@ -291,3 +291,9 @@ Validation: full conformance passes 1,543/1,543; units and Zig formatting pass.
|
||||
Q-044 replaces repeated nominal walks with a shared property table and memoizes the earlier AIR accounted-size query by index/depth. The invariant is exact structural classification: existing tag rules, graph/iref boundaries, ownership classes, diagnostic ordering and depth guards remain. The verifier rebuilds caches rather than trusting callers; lowering classifies only after finite-layout checks. No verifier rule, AIR meaning, diagnostic/code/reason, source syntax, feature, interpreter state, allocation/cleanup behavior or bundle text changes. Nominal size states have the documented polynomial bound V × (V + 2), preserving the former depth-dependent calculation. Valid deep diamonds/phantom nodes and rejected cycles, oversized values, annotations and constraints have source/AIR fixtures; runtime allocation uses the checked cache.
|
||||
|
||||
Validation: units and Zig formatting pass; full conformance is 1,560/1,560, with all 17 new fixtures also passing collection before every instruction. Counted tests cover shared/cyclic queries, witness visits and layout rejection before classification; 256 small mixed graphs compare cached predicates, witnesses, depth guards and sizes against uncached derivations. CLI integration passes 110 checks, including source/AIR/hosted execution, actual allocation accounting, imported types and diagnostics. Existing generic/content/store-mode suites pass 32/302/348 checks. Old/new comparison changes zero outputs on 1,257 public sources (686 old lowerings) and 333 public AIR checks. Coverage remains 121/121. Claude independently ran units and approved review. P6-2 remains open; Q-049 is a separate owner-policy question.
|
||||
|
||||
## P6-1/P6-2 grammar surface increment (2026-10-08)
|
||||
|
||||
DD-022 synchronizes the grammar/spec 15 with implemented wrappers, binary literals, negative patterns, parenthesized places, declared borrow-return calls and list/arm delimiters. Ordered statement, header-brace and typed-built-in choices are documented; no LL(k) claim is made. Q-050 rejects empty qualified enum payload lists with E7001 at `(`, including generic/grouped/built-in variants and patterns. Ordinary `f()`, bare variants, non-empty payloads and outcome bindings retain their rules. No AIR, verifier/runtime, ownership/concurrency, feature or diagnostic-code changes.
|
||||
|
||||
Validation: units and Zig formatting pass; full conformance is 1,594/1,594, and all 34 new fixtures pass collection before every instruction, including select schedules. CLI integration passes 288 checks for syntax locations, packages, formatting and source/AIR execution. Old/new comparison changes zero check/lower outputs on 1,269 public sources (695 old lowerings); source coverage remains 121/121. The public formatter corpus passes 5,435 checks on 1,303 files, preserving 709 lowered outputs. Claude independently reviewed the change and reran units and CLI checks. Bundle growth is recorded in docs/agent/README.md. P6-1/P6-2 remain open; future syntax still needs its RFCs, and Q-051 is a separate ordinary-effect validation task.
|
||||
+54
-26
@@ -5,17 +5,23 @@
|
||||
-------------------
|
||||
- `//` starts a comment that runs to the end of the line.
|
||||
- Whitespace and line breaks separate tokens and are otherwise insignificant.
|
||||
- Keywords: module struct enum fn effects trusted from let var zero
|
||||
- Keywords: module struct enum type fn effects trusted from let var zero
|
||||
if else while for in loop break continue return trap match select
|
||||
scope shield lock as cancelled ref mut move unchecked or and not
|
||||
true false recv send.
|
||||
true false.
|
||||
- import is contextual after the module header; recv/send are contextual
|
||||
inside select. They remain identifiers elsewhere. A lone `_` is not
|
||||
an identifier; it is a wildcard/discard binding. `_name` is an identifier.
|
||||
- as! and as% are single tokens: `as` immediately followed by `!` or `%`,
|
||||
without whitespace.
|
||||
- Every construct has one canonical spelling (spec 15 §1).
|
||||
*)
|
||||
|
||||
module = "module" path { module_import } { item } ;
|
||||
module_import = "import" path ";" ; (* contextual word, spec 15 §13/§14 *)
|
||||
item = type_decl | fn_decl ;
|
||||
path = ident { "." ident } ;
|
||||
path = ident { "." member } ; (* module/effect paths allow keywords after `.` *)
|
||||
name_path = ident { "." ident } ; (* qualified types and enum patterns *)
|
||||
|
||||
type_decl = struct_decl | enum_decl ;
|
||||
struct_decl = "struct" ident [ type_params ] "{" [ field { "," field } [ "," ] ] "}" ;
|
||||
@@ -23,28 +29,29 @@ field = ident ":" type ;
|
||||
enum_decl = "enum" ident [ type_params ] "{" variant { "," variant } [ "," ] "}" ;
|
||||
variant = ident [ "(" type { "," type } ")" ] ;
|
||||
|
||||
fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } ] ")" "->" type [ "from" ident ]
|
||||
"effects" "[" [ path { "," path } ] "]"
|
||||
fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } [ "," ] ] ")" "->" type [ "from" ident ]
|
||||
"effects" "[" [ path { "," path } [ "," ] ] "]"
|
||||
block ; (* `trusted` is reserved and rejected, E7006 *)
|
||||
param = ident ":" type ;
|
||||
type_params = "<" type_param { "," type_param } ">" ;
|
||||
type_param = ident [ ":" ( property { "+" property } | function_contract ) ] ;
|
||||
function_contract = "fn" "(" [ type { "," type } ] ")" "->" type
|
||||
"effects" "[" [ path { "," path } ] "]" ;
|
||||
function_contract = "fn" "(" [ type { "," type } [ "," ] ] ")" "->" type
|
||||
"effects" "[" [ path { "," path } [ "," ] ] "]" ;
|
||||
property = "Copy" | "Send" | "Share" | "Freeze" | "Local" ;
|
||||
type_args = "<" generic_arg { "," generic_arg } ">" ;
|
||||
generic_arg = type | "fn" path [ application ] ; (* static function selection; spec 15 §18 *)
|
||||
application = "::" type_args ; (* explicit; no inference, spec 15 §15 *)
|
||||
|
||||
type = int_type | "bool" | "void" | "never" | path
|
||||
| path type_args
|
||||
type = int_type | "bool" | "void" | "never" | name_path
|
||||
| name_path type_args
|
||||
| "[" type ";" int_lit "]"
|
||||
| wrapper "<" type ">"
|
||||
| "cap" "<" path ">"
|
||||
| "file" "<" ( "read" | "write" | "append" ) ">" ;
|
||||
(* `>>` closes two type arguments: mut<file<write>> *)
|
||||
wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array"
|
||||
| "task" | "sender" | "receiver" | "mutex" | "buffer" ;
|
||||
| "task" | "sender" | "receiver" | "mutex" | "buffer"
|
||||
| "island" | "frozen" | "arc" | "iref" | "atomic" ;
|
||||
int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
|
||||
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ;
|
||||
(* `region`, `listener`, `stream`, `io_error`, `alloc_error`,
|
||||
@@ -59,6 +66,18 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
|
||||
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. *)
|
||||
(* Other statements parse an expression first: the next `=` selects assignment,
|
||||
`;` selects an expression statement, and `}` selects a tail. Lowering checks
|
||||
that an assignment target is a place (E7006 invalid_assignment). This ordered
|
||||
choice, with the block rule above, has no LL(k) bound on the common prefix.
|
||||
In if/while conditions, match scrutinees, for bounds and lock places, a
|
||||
following `{` starts the body rather than a struct literal. Parenthesized
|
||||
expressions, call arguments and index expressions restore ordinary parsing.
|
||||
Struct literals require an uppercase ASCII initial in the final name.
|
||||
At a dot step only channel.make<T> and buffer.new<T> consume `<` as a type
|
||||
argument; that choice commits to a typed call, with no comparison fallback.
|
||||
Other expression `<` tokens are comparisons; generic calls use `::<...>`.
|
||||
Arm bodies starting with `{` likewise consume the whole block first. *)
|
||||
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
|
||||
statement = "let" binding [ ":" type ] "=" expr ";"
|
||||
| "var" ident ":" type "=" ( expr | "zero" ) ";"
|
||||
@@ -67,7 +86,9 @@ statement = "let" binding [ ":" type ] "=" expr ";"
|
||||
| "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";"
|
||||
| expr ";"
|
||||
| block_stmt ;
|
||||
binding = ident | "(" [ ( ident | "_" ) { "," ( ident | "_" ) } ] ")" ; (* complete unpack; pairs also split_at/compare_exchange *)
|
||||
binding = ident | binds ;
|
||||
binds = "(" [ bind { "," bind } [ "," ] ] ")" ;
|
||||
bind = ident | "_" ; (* complete unpack; pairs also split_at/compare_exchange *)
|
||||
block_stmt = if_expr | match_expr | select_stmt | block
|
||||
| "while" expr block
|
||||
| "for" ident "in" expr ".." expr block
|
||||
@@ -77,15 +98,17 @@ block_stmt = if_expr | match_expr | select_stmt | block
|
||||
| "lock" "ref" place "as" ident block "cancelled" block ;
|
||||
|
||||
if_expr = "if" expr block [ "else" ( if_expr | block ) ] ;
|
||||
match_expr = "match" expr "{" { arm } "}" ;
|
||||
arm = pattern "=>" ( block | expr "," ) ;
|
||||
pattern = "_" | int_lit (* integer matches only; `_` is required there *)
|
||||
| path [ application ] "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *)
|
||||
| ident [ "(" ident { "," ident } ")" ] ; (* outcome of a fallible operation: ok(n), closed *)
|
||||
match_expr = "match" expr "{" { arm } [ final_arm ] "}" ;
|
||||
arm = pattern "=>" ( block [ "," ] | expr "," ) ;
|
||||
final_arm = pattern "=>" expr ; (* final non-block arm may omit its comma *)
|
||||
pattern = "_" | [ "-" ] int_lit (* integer matches only; `_` is required there *)
|
||||
| name_path [ application ] "::" ident [ payload_binds ] (* exhaustive enum variants; §6 *)
|
||||
| ident [ binds ] ; (* outcome of a fallible operation: ok(n), closed *)
|
||||
payload_binds = "(" bind { "," bind } [ "," ] ")" ; (* enum payload list MUST NOT be empty *)
|
||||
|
||||
select_stmt = "select" "{" { select_arm } "cancelled" [ "(" ident { "," ident } ")" ] "=>" ( block | expr "," ) "}" ;
|
||||
select_arm = "recv" "(" ident ")" "{" { arm } "}"
|
||||
| "send" "(" ident "," expr ")" "{" { arm } "}" ;
|
||||
select_stmt = "select" "{" { select_arm } "cancelled" [ "(" [ ident { "," ident } [ "," ] ] ")" ] "=>" ( block [ "," ] | expr [ "," ] ) "}" ;
|
||||
select_arm = "recv" "(" ident ")" "{" { arm } [ final_arm ] "}"
|
||||
| "send" "(" ident "," expr ")" "{" { arm } [ final_arm ] "}" ;
|
||||
|
||||
expr = or_expr ;
|
||||
or_expr = and_expr { "or" ( and_expr | "trap" ) } ; (* `e or trap`: the only fallible shorthand *)
|
||||
@@ -100,9 +123,12 @@ unary = ( "-" | "not" | "*" ) unary
|
||||
| ( "ref" | "mut" ) [ "unchecked" ] place
|
||||
| "move" ident
|
||||
| postfix ;
|
||||
postfix = primary { application | "." member | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
postfix = primary { application | "." member [ typed_call_args ] | "[" expr [ ".." expr ] "]" | call_args } ;
|
||||
member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *)
|
||||
call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ;
|
||||
call_args = "(" [ expr { "," expr } [ "," ] ] ")" ;
|
||||
typed_call_args = "<" type ">" call_args ; (* only channel.make / buffer.new at the dot step *)
|
||||
(* A variant may be followed only by a non-empty payload call;
|
||||
payload-free variants MUST be bare. Payload arity is checked. *)
|
||||
primary = int_lit | "true" | "false" | string
|
||||
| "struct" "." "unpack" (* contextual built-in call, §16 *)
|
||||
| ident | path [ application ] "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *)
|
||||
@@ -112,11 +138,13 @@ primary = int_lit | "true" | "false" | string
|
||||
| "(" expr ")"
|
||||
| if_expr | match_expr | block ;
|
||||
field_init = ident ":" expr ;
|
||||
borrow_call = "buffer" "." "view" "(" ident ")"
|
||||
| ( "island" | "frozen" | "arc" ) "." "at" "(" expr "," expr ")" ;
|
||||
place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ;
|
||||
borrow_call = name_path [ application ] call_args ; (* only declared `from` calls (§19), buffer.view and graph .at (§17) *)
|
||||
place = ( ident | "(" place ")" ) { "." member | "[" expr [ ".." expr ] "]" } | "*" unary ;
|
||||
|
||||
int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ;
|
||||
int_lit = digit { digit | "_" } [ int_type ]
|
||||
| "0x" hexdigit { hexdigit | "_" } [ int_type ]
|
||||
| "0b" bindigit { bindigit | "_" } [ int_type ] ;
|
||||
bindigit = "0" | "1" ;
|
||||
string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \r \t \0 \\ \" \xHH *)
|
||||
ident = ( letter | "_" ) { letter | digit | "_" } ;
|
||||
ident = ( letter | "_" ) { letter | digit | "_" } ; (* excluding keywords and lone `_` *)
|
||||
keyword = ? any keyword listed under Lexical conventions ? ;
|
||||
@@ -32,7 +32,7 @@ Rules:
|
||||
1. Lowering is a pure function of its explicit source inputs: the same module graph gives byte-identical canonical AIR (spec 07 §8.5).
|
||||
2. No source construct admits a program whose AIR the verifier rejects. Errors the verifier would find are reported with the verifier's code (§9).
|
||||
3. `.aji` 0.1 covers the published features of Phases 0–3 and nothing else.
|
||||
4. Every construct has **one canonical spelling**. There are no alternative forms of the same operation.
|
||||
4. Every construct has **one canonical spelling**. There are no alternative forms of the same operation. Parentheses for expression grouping and the optional list delimiters of §2 do not introduce operations.
|
||||
|
||||
## 2. Modules and declarations
|
||||
|
||||
@@ -59,7 +59,8 @@ effects [io.read, io.write]
|
||||
|
||||
- A file holds one module: `module <dotted.path>`, then type and function declarations in any order.
|
||||
- Between the module header and declarations, `import <dotted.path>;` imports a standard (§13) or explicitly supplied package module (§14). `import` is contextual at this position; it remains an ordinary identifier elsewhere.
|
||||
- `//` starts a line comment.
|
||||
- `//` starts a line comment. `recv` and `send` are contextual in `select`, and remain identifiers elsewhere; a lone `_` is a wildcard/discard, not an identifier. Keywords are listed in the grammar; after `.` they may name a member.
|
||||
- Trailing commas MAY appear in parameter, argument, effect, field, variant, array-literal element and binding lists, including static-function contract parameters/effects. Type parameter/argument lists and enum declaration payload-type lists MUST NOT have trailing commas. Empty outcome/tuple/select-cancellation binding lists MAY retain `()`; the operation still checks the number and kinds of bindings. Enum payload lists MUST NOT be empty (§5–§6).
|
||||
- Function `f` lowers to `@f`; type `T` to `@T`.
|
||||
- **Signature.** `fn name(params) -> type`, then optionally `from p` for a borrow return (spec 08 §11.3), then the line `effects [...]`, then the body block.
|
||||
- **Parameter names are preserved.** A parameter `p` lowers to `%p`. Names the compiler generates are chosen so that they never equal a parameter name of the function. The names of `@main`'s parameters are part of the instantiation contract.
|
||||
@@ -80,6 +81,7 @@ The AIR spellings are used (spec 07 §8):
|
||||
- `cap<K>`;
|
||||
- `file<read|write|append>`, `listener`, `stream`;
|
||||
- `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>`;
|
||||
- `island<T>`, `frozen<T>`, `arc<T>`, `iref<T>`, `atomic<T>`;
|
||||
- the built-in enums `io_error`, `alloc_error`, `cap_error`.
|
||||
|
||||
Arrays are written `[T; N]`. `scope`, `shield` and `guard<T>` are not source types: they exist only inside the block forms of §7.
|
||||
@@ -150,14 +152,14 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
|
||||
|
||||
**Literals:**
|
||||
|
||||
- integers (`42`, `0xff`, `1_000`) take their type from context, or a suffix (`42u8`);
|
||||
- integers (`42`, `0xff`, `0b101`, `1_000`) take their type from context, or a suffix (`42u8`);
|
||||
- `true`, `false`;
|
||||
- `b"…"`: a byte string, of type `[u8; N]`, with escapes `\n`, `\t`, `\\`, `\"`, `\xHH`.
|
||||
|
||||
**Aggregates.**
|
||||
|
||||
- **Struct values.** `Pair { a: 1, b: 2 }` is the only way to build one: every field exactly once, in any order. A missing or repeated field is `E7006`, an unknown one `E7002`. The initializers are evaluated, and lowered, in **declaration order**, so the AIR does not depend on the order the fields are written in. There is no positional constructor.
|
||||
- **Enum values.** `Shape::Square(4)`, or `Shape::Empty` for a variant without payload, is the only form.
|
||||
- **Enum values.** `Shape::Square(4)`, or `Shape::Empty` for a variant without payload, is the only form. An empty `()` after a qualified variant MUST reject E7001, including a variant that requires payload values.
|
||||
- **Arrays.** `[e; N]` is `array.splat`.
|
||||
- **Field access.** `v.f` on a struct value is `struct.get`.
|
||||
|
||||
@@ -171,7 +173,8 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
|
||||
- `place.f`;
|
||||
- `place[i]`;
|
||||
- `place[a..b]`;
|
||||
- `*r`.
|
||||
- `*r`;
|
||||
- a parenthesized place, such as `(*r).field` or `(*r)[i]`. Dereference consumes a unary operand: `*r.field` means `*(r.field)`.
|
||||
|
||||
| Source | Meaning |
|
||||
|---|---|
|
||||
@@ -220,6 +223,8 @@ The value is evaluated first, then the place is borrowed for the store and the b
|
||||
|
||||
## 6. Fallible operations and `match`
|
||||
|
||||
Arm bodies beginning with `{` consume the whole block; a following comma MAY be present. Other expression arms MUST end with a comma unless immediately followed by the enclosing `}`. Integer patterns MAY have a leading minus. Qualified enum patterns use bare names for payload-free variants; an empty payload-binding `()` MUST reject E7001. Payload bindings MAY use `_` to discard a value, subject to the existing linear-value rules.
|
||||
|
||||
Every AIR terminator with outcome edges is written as a `match` over its outcomes. The arms are named after the edge roles and the match MUST be exhaustive (`E7004`):
|
||||
|
||||
| Operation | Outcomes |
|
||||
@@ -534,7 +539,7 @@ Module names use source paths. The first component of a package mapping MUST NOT
|
||||
|
||||
A module sees its own functions and types by short name, and declarations of directly imported modules by full path. Imports MUST NOT inject short names, aliases or transitive visibility. An entry outside reserved built-in namespaces can also qualify its own declarations with its module name; built-in operations retain precedence. An inaccessible or unknown function/type/member is `E7002`, even if a different module linked the declaration. Qualified names resolve by module identity, independently of local bindings with the same prefix. A value may have a type inferred from a directly imported function contract without importing that type's defining module; spelling the type or its constructors by name still requires a direct import. Module-local calls MUST NOT capture an entry's similarly named function; named types from different modules are nominally distinct.
|
||||
|
||||
Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref<app.model.Pair>` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals remain forbidden in unparenthesized conditions, where `{` starts a block. This adds no methods, reflection or permission to store forbidden borrowed values in aggregates; linear members follow §16. Generic forms are specified separately in §15.
|
||||
Type annotations and wrappers use qualified types, for example `app.model.Pair`, `ref<app.model.Pair>` and `[app.model.Pair; 2]`. Enum construction/patterns use `app.model.Result::ok(value)`. Qualified struct construction is `app.model.Pair { a: 1, b: 2 }`, with existing field typing/completeness and ownership rules. The final component must begin with an uppercase ASCII letter, as for current short-name struct literals. Struct literals MUST NOT consume the body-opening `{` in `if`/`while` conditions, `match` scrutinees, `for` bounds or `lock` places. Parenthesized expressions, call arguments and index expressions within those headers restore ordinary struct-literal parsing. This adds no methods, reflection or permission to store forbidden borrowed values in aggregates; linear members follow §16. Generic forms are specified separately in §15.
|
||||
|
||||
A qualified named function MAY be passed as the function operand of `task.spawn(scope, app.work.run, ...)`. Existing Send/effect/structured-lifetime rules still apply; there is no function value, dynamic dispatch or detached task. All other calls use the existing argument, borrow, move, failure and effect rules.
|
||||
|
||||
|
||||
@@ -623,6 +623,8 @@ const Parser = struct {
|
||||
} else if (!std.mem.eql(u8, name, t.text)) return p.fail(p.peek(), "`::` after enum path");
|
||||
var binds: std.ArrayList([]const u8) = .empty;
|
||||
if (p.peek().tag == .l_paren) {
|
||||
if (qualifier != null and p.peekAt(1).tag == .r_paren)
|
||||
return p.fail(p.peek(), "payload bindings or no parentheses for a payload-free variant");
|
||||
_ = p.next();
|
||||
while (p.peek().tag != .r_paren) {
|
||||
const b = p.peek();
|
||||
@@ -797,6 +799,8 @@ const Parser = struct {
|
||||
e.kind.struct_lit.type_args = type_args;
|
||||
},
|
||||
.l_paren => {
|
||||
if (e.kind == .variant and p.peekAt(1).tag == .r_paren)
|
||||
return p.fail(p.peek(), "payload values or no parentheses for a payload-free variant");
|
||||
const args = try p.callArgs();
|
||||
const callee = try p.box(ast.Expr, e);
|
||||
e = .{ .span = p.span(start), .kind = .{ .call = .{ .callee = callee, .type_arg = null, .args = args } } };
|
||||
@@ -1240,3 +1244,76 @@ test "dereferenced borrow consumes unary place without swallowing outer operatio
|
||||
try std.testing.expect((try parse(a, source)) == .err);
|
||||
}
|
||||
}
|
||||
|
||||
test "qualified enum payload lists are nonempty, including grouped and generic variants" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
for ([_][]const u8{
|
||||
"E::Empty()", "E::Pair()", "M.E::<u64>::Empty()", "(E::Empty)()",
|
||||
"alloc_error::budget_exceeded()", "E::Empty( // payload\n )",
|
||||
}) |expression| {
|
||||
const source = try std.fmt.allocPrint(a, "module grammar fn f() -> void effects [] {{ let x = {s}; }}", .{expression});
|
||||
const r = try parse(a, source);
|
||||
try std.testing.expect(r == .err);
|
||||
const at = std.mem.lastIndexOfScalar(u8, source, '(').?;
|
||||
try std.testing.expectEqual(@as(u32, @intCast(at + 1)), r.err.pos.col);
|
||||
try std.testing.expectEqualStrings("(", r.err.found);
|
||||
}
|
||||
for ([_][]const u8{ "E::Empty()", "E::Pair()", "M.E::<u64>::Empty()", "alloc_error::budget_exceeded()" }) |pattern_text| {
|
||||
const source = try std.fmt.allocPrint(a, "module grammar fn f() -> void effects [] {{ match v {{ {s} => {{}} }} }}", .{pattern_text});
|
||||
const r = try parse(a, source);
|
||||
try std.testing.expect(r == .err);
|
||||
const at = std.mem.lastIndexOfScalar(u8, source, '(').?;
|
||||
try std.testing.expectEqual(@as(u32, @intCast(at + 1)), r.err.pos.col);
|
||||
try std.testing.expectEqualStrings("(", r.err.found);
|
||||
}
|
||||
for ([_][]const u8{
|
||||
"let x = f();", "let x = E::Empty;", "let x = E::Pair(1u64,);",
|
||||
"let x = (E::Pair)(1u64);", "match v { E::Pair(_, n,) => {} }", "match operation() { ok() => {}, closed() => {} cancelled() => {} }",
|
||||
"select { cancelled() => {} }",
|
||||
}) |statement_text| {
|
||||
const source = try std.fmt.allocPrint(a, "module grammar fn f() -> void effects [] {{ {s} }}", .{statement_text});
|
||||
try std.testing.expect((try parse(a, source)) == .ok);
|
||||
}
|
||||
}
|
||||
|
||||
test "grammar surface preserves typed-call, comparison and body-brace choices" {
|
||||
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
const r = try parse(a,
|
||||
\\module grammar
|
||||
\\struct Node { value: u64, }
|
||||
\\fn wrappers(a: island<Node>, b: frozen<Node>, c: arc<Node>, d: iref<Node>, e: atomic<u64>,) -> void effects [] {}
|
||||
\\fn f() -> void effects [] {
|
||||
\\ let compare = left < right;
|
||||
\\ let ordinary = identity::<u64>(42u64,);
|
||||
\\ match channel.make<u64>(1u64, heap,) { ok(a, b,) => {}, err(e,) => {} }
|
||||
\\ let buffer_value = buffer.new<u64>(heap,);
|
||||
\\ if test(Node {value: 42u64}) {}
|
||||
\\ while (Node {value: 42u64}).value == 42u64 {break;}
|
||||
\\ let (a, b,) = split();
|
||||
\\ ref item = first::<u64>(slice_value,);
|
||||
\\ select { recv(rx) { ok(n,) => n, closed() => 0u64 } cancelled() => 0u64 }
|
||||
\\}
|
||||
);
|
||||
try std.testing.expect(r == .ok);
|
||||
const statements = r.ok.functions[1].body.stmts;
|
||||
try std.testing.expect(statements[0].kind.let.e.kind == .binary);
|
||||
try std.testing.expect(statements[1].kind.let.e.kind.call.callee.kind == .specialize);
|
||||
try std.testing.expect(statements[2].kind.expr.kind.match_expr.scrutinee.kind.call.type_arg != null);
|
||||
try std.testing.expect(statements[3].kind.let.e.kind.call.type_arg != null);
|
||||
try std.testing.expect(statements[4].kind.expr.kind.if_expr.cond.kind.call.args[0].kind == .struct_lit);
|
||||
try std.testing.expect(statements[6].kind.let.names.len == 2);
|
||||
try std.testing.expect(statements[7].kind.borrow.place.kind.call.callee.kind == .specialize);
|
||||
for ([_][]const u8{
|
||||
"let x = channel.make < value;", // Typed built-in commits, no fallback.
|
||||
"let x = buffer.new < value;",
|
||||
"if Node {value: 42u64} {}", // Header brace belongs to the body.
|
||||
"select { cancelled(_) => {} }", // Cancellation names are not discard bindings.
|
||||
}) |statement_text| {
|
||||
const source = try std.fmt.allocPrint(a, "module grammar fn f() -> void effects [] {{ {s} }}", .{statement_text});
|
||||
try std.testing.expect((try parse(a, source)) == .err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.array_places
|
||||
fn change(p: mut<[u64; 2]>) -> u64 effects [] { (*p)[0] = 42u64; return (*p)[0]; }
|
||||
fn main() -> u64 effects [] { var a: [u64; 2] = zero; return change(mut (a)); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.borrow_calls
|
||||
fn first<T: Copy>(s: slice<T>,) -> ref<T> from s effects [] { ref x = s[0]; return x; }
|
||||
fn main() -> u64 effects [] { let a = [42u64]; ref s = (a); ref x = first::<u64>(s,); return *x; }
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/reference/grammar.ebnf
|
||||
module grammar.cast_spacing
|
||||
fn main() -> u64 effects [] { return 42u64 as ! u8; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module grammar.casts
|
||||
fn main() -> u64 effects [] { let n = 42u64 as! u8; return (n as% u16) as u64; }
|
||||
@@ -0,0 +1,9 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.context_words
|
||||
struct Words { recv: u64, send: u64, }
|
||||
fn recv() -> u64 effects [] { return 40u64; }
|
||||
fn send() -> u64 effects [] { return 2u64; }
|
||||
fn main() -> u64 effects [] { let import = Words { recv: recv(), send: send(), }; return import.recv + import.send; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_builtin_call
|
||||
|
||||
fn main() -> u64 effects [] { let v = alloc_error::budget_exceeded(); return 0u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_builtin_pattern
|
||||
|
||||
fn main() -> u64 effects [] { let v = alloc_error::budget_exceeded; return match v { alloc_error::budget_exceeded() => 42u64 }; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_comment_call
|
||||
enum Value { Empty, }
|
||||
fn main() -> u64 effects [] { let v = Value::Empty( // no payload
|
||||
); return 0u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_enum_call
|
||||
enum Value { Empty, }
|
||||
fn main() -> u64 effects [] { let v = Value::Empty(); return 0u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_enum_pattern
|
||||
enum Value { Empty, }
|
||||
fn main() -> u64 effects [] { let v = Value::Empty; return match v { Value::Empty() => 42u64 }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_generic_call
|
||||
enum Value<T> { Empty, Pair(T), }
|
||||
fn main() -> u64 effects [] { let v = Value::<u64>::Empty(); return 0u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_generic_pattern
|
||||
enum Value<T> { Empty, Pair(T), }
|
||||
fn main() -> u64 effects [] { let v = Value::<u64>::Empty; return match v { Value::<u64>::Empty() => 42u64 }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_grouped_call
|
||||
enum Value { Empty, }
|
||||
fn main() -> u64 effects [] { let v = (Value::Empty)(); return 0u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_payload_call
|
||||
enum Value { Pair(u64), }
|
||||
fn main() -> u64 effects [] { let v = Value::Pair(); return 0u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_payload_pattern
|
||||
enum Value { Pair(u64), }
|
||||
fn main() -> u64 effects [] { let v = Value::Pair(42u64); return match v { Value::Pair() => 42u64 }; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.empty_unused_template
|
||||
enum Value { Empty, }
|
||||
fn unused<T>(x: T) -> T effects [] { let v = Value::Empty(); return x; }
|
||||
fn main() -> u64 effects [] { return 42u64; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.enum_binds
|
||||
enum Value<T> { Empty, Pair(T, T), }
|
||||
fn main() -> u64 effects [] { let v = Value::<u64>::Pair(1u64,42u64,); return match v { Value::<u64>::Empty => {0u64}, Value::<u64>::Pair(_, n,) => n }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.enum_decl_empty
|
||||
enum Value { Empty(), }
|
||||
fn main() -> u64 effects [] { return 42u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.enum_decl_trailing
|
||||
enum Value { Pair(u64,), }
|
||||
fn main() -> u64 effects [] { return 42u64; }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.header_structs
|
||||
struct Pair { a: u64, }
|
||||
fn test(p: Pair) -> bool effects [] { return p.a == 42u64; }
|
||||
fn main() -> u64 effects [] { if test(Pair { a: 42u64 }) { return 42u64; } return 0u64; }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.lists
|
||||
fn answer(value: u64,) -> u64 effects [] { return value; }
|
||||
fn main() -> u64 effects [] { return answer(0b10_1010u64,); }
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.lone_underscore
|
||||
fn _() -> u64 effects [] { return 42u64; }
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.missing_arm_comma
|
||||
fn main() -> u64 effects [] { return match 1u64 { 1u64 => 42u64 _ => 0u64 }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.negative_pattern
|
||||
fn main() -> u64 effects [] { return match -1i64 { -1i64 => {42u64}, _ => 0u64 }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7005
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §5
|
||||
module grammar.nonempty_arity
|
||||
enum Value { Pair(u64), }
|
||||
fn main() -> u64 effects [] { let v = Value::Pair(1u64, 2u64); return 42u64; }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.ordinary_empty_call
|
||||
enum Value { Empty, }
|
||||
fn value() -> Value effects [] { return Value::Empty; }
|
||||
fn main() -> u64 effects [] { return match value() { Value::Empty => 42u64 }; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.outcome_empty
|
||||
fn main() -> u64 effects [task.spawn,] { match task.check_cancel() { ok() => {return 42u64;}, cancelled() => {trap;} } }
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.places
|
||||
struct Pair { a: u64, }
|
||||
fn read(p: ref<Pair>) -> u64 effects [] { return (*p).a; }
|
||||
fn main() -> u64 effects [] { var p: Pair = zero; { mut q = (p); (*q).a = 42u64; } return read(ref (p)); }
|
||||
@@ -0,0 +1,5 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.reserved_type_word
|
||||
fn type() -> u64 effects [] { return 42u64; }
|
||||
@@ -0,0 +1,22 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// grant: heap=mem.alloc:256
|
||||
// schedules: 10
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §6, §7
|
||||
module grammar.select_lists
|
||||
fn main(heap: cap<mem.alloc>,) -> u64 effects [mem.alloc, task.wait,] {
|
||||
match channel.make<u64>(1usize, heap,) {
|
||||
ok(tx, rx,) => {
|
||||
channel.close_sender(move tx,);
|
||||
var answer: u64 = 0;
|
||||
select {
|
||||
recv(rx) { ok(n,) => {answer = n;}, closed() => {answer = 42u64;} }
|
||||
cancelled() => {trap;},
|
||||
}
|
||||
match channel.close_receiver(move rx,) { ok() => {}, pending(rx,) => {trap;} }
|
||||
return answer;
|
||||
},
|
||||
err(e,) => {trap;},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.static_lists
|
||||
fn identity(x: u64,) -> u64 effects [] { return x; }
|
||||
fn apply<F: fn(u64,) -> u64 effects []>(x: u64,) -> u64 effects [] { return F(x,); }
|
||||
fn main() -> u64 effects [] { return apply::<fn identity>(42u64,); }
|
||||
@@ -0,0 +1,7 @@
|
||||
// expect: run
|
||||
// result: 42
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §16
|
||||
module grammar.tuple_empty
|
||||
struct Empty {}
|
||||
fn main() -> u64 effects [] { let value = Empty {}; let () = struct.unpack(value,); return 42u64; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.type_args_trailing
|
||||
struct Pair<T> { a: T, }
|
||||
fn main() -> u64 effects [] { let x: Pair<u64,> = Pair::<u64> { a: 42u64 }; return x.a; }
|
||||
@@ -0,0 +1,6 @@
|
||||
// expect: reject E7001
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md §2, §5, §6
|
||||
module grammar.type_params_trailing
|
||||
struct Pair<T,> { a: T, }
|
||||
fn main() -> u64 effects [] { return 42u64; }
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grammar boundaries, exact syntax positions and source/AIR/formatter fidelity."""
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
AJI = REPO / 'zig-out/bin/aji'
|
||||
CORPUS = REPO / 'tests/conformance/source/grammar_surface'
|
||||
checks = 0
|
||||
|
||||
|
||||
def cli(*args, code=0):
|
||||
global checks
|
||||
result = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
|
||||
assert result.returncode == code, (args, result.returncode, result.stdout, result.stderr)
|
||||
checks += 1
|
||||
return result.stdout
|
||||
|
||||
|
||||
def position(source, offset):
|
||||
return source[:offset].count('\n') + 1, offset - source.rfind('\n', 0, offset)
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='aji-grammar-') as directory:
|
||||
root = Path(directory)
|
||||
for path in sorted(CORPUS.glob('*.aji')):
|
||||
source = path.read_text()
|
||||
if '// expect: reject' in source:
|
||||
error = json.loads(cli('check', path, code=1))
|
||||
assert error['code'] == re.search(r'// expect: reject (E\d+)', source)[1] and error['file'] == str(path), error
|
||||
assert 'air_line' not in error and 'air_col' not in error, error
|
||||
for command in ('lower', 'run', 'report', 'explore'):
|
||||
assert json.loads(cli(command, path, code=1)) == error
|
||||
if error['code'] == 'E7001':
|
||||
assert json.loads(cli('fmt', path, code=1)) == error
|
||||
assert json.loads(cli('fmt', '--check', path, code=1)) == error
|
||||
else:
|
||||
cli('fmt', path)
|
||||
if path.name.startswith('empty_'):
|
||||
# Qualified payload syntax points at the empty list, even
|
||||
# across comments/newlines; never at a declaration/function.
|
||||
marker = '::budget_exceeded' if '::budget_exceeded' in source else '::Pair' if 'empty_payload' in path.name else '::Empty'
|
||||
if 'pattern' in path.name:
|
||||
start = source.rindex(marker)
|
||||
else:
|
||||
start = source.index(marker, source.index('fn '))
|
||||
offset = source.index('(', start)
|
||||
assert (error['line'], error['col']) == position(source, offset), error
|
||||
assert error['found'] == '(' and 'payload' in error['expected'], error
|
||||
continue
|
||||
cli('check', path)
|
||||
formatted = root / path.name
|
||||
formatted.write_text(cli('fmt', path))
|
||||
cli('fmt', '--check', formatted)
|
||||
assert cli('fmt', formatted) == formatted.read_text()
|
||||
lowered = cli('lower', path)
|
||||
assert cli('lower', formatted) == lowered
|
||||
air = root / (path.stem + '.air')
|
||||
air.write_text(lowered)
|
||||
cli('check', air)
|
||||
if '// expect: run' in source:
|
||||
grants = [value for grant in re.findall(r'// grant: (.+)', source) for value in ('--grant', grant)]
|
||||
result = json.loads(cli('run', '--fuel', '100000', *grants, path))
|
||||
assert result == json.loads(cli('run', '--fuel', '100000', *grants, air))
|
||||
assert result == json.loads(cli('run', '--fuel', '100000', *grants, formatted))
|
||||
assert result['value'] == 42, result
|
||||
|
||||
# Imported qualifiers take the same syntax path and retain the actual file.
|
||||
helper = root / 'model.aji'
|
||||
helper.write_text('module app.model\nenum Value<T> { Empty, Payload(T), }\n')
|
||||
main = root / 'main.aji'
|
||||
main.write_text('module app.main\nimport app.model;\nfn main() -> u64 effects [] { let value = app.model.Value::<u64>::Empty(); return 42u64; }\n')
|
||||
manifest = root / 'aji.toml'
|
||||
manifest.write_text('[package]\nname = \"grammar\"\nversion = \"0.1.0\"\nentry = \"main.aji\"\n[modules]\napp.model = \"model.aji\"\n')
|
||||
error = json.loads(cli('check', '--manifest', manifest, code=1))
|
||||
assert error['code'] == 'E7001' and error['file'] == str(main), error
|
||||
offset = main.read_text().index('(', main.read_text().index('::Empty'))
|
||||
assert (error['line'], error['col']) == position(main.read_text(), offset), error
|
||||
main.write_text(main.read_text().replace('::Empty()', '::Empty'))
|
||||
cli('check', '--manifest', manifest)
|
||||
assert json.loads(cli('run', '--fuel', '100000', '--manifest', manifest))['value'] == 42
|
||||
main.write_text('module app.main\nimport app.model;\n'
|
||||
'fn main() -> u64 effects [] { let value = app.model.Value::<u64>::Empty; '
|
||||
'return match value { app.model.Value::<u64>::Empty() => 42u64, '
|
||||
'app.model.Value::<u64>::Payload(_) => 0u64 }; }\n')
|
||||
error = json.loads(cli('check', '--manifest', manifest, code=1))
|
||||
assert error['code'] == 'E7001' and error['file'] == str(main), error
|
||||
offset = main.read_text().index('(', main.read_text().rindex('::Empty'))
|
||||
assert (error['line'], error['col']) == position(main.read_text(), offset), error
|
||||
for command in ('lower', 'run', 'report', 'explore'):
|
||||
assert json.loads(cli(command, '--manifest', manifest, code=1)) == error
|
||||
main.write_text(main.read_text().replace('::Empty()', '::Empty'))
|
||||
assert json.loads(cli('run', '--fuel', '100000', '--manifest', manifest))['value'] == 42
|
||||
|
||||
print(f'source grammar: {checks} checks passed')
|
||||
Reference in new issue
Block a user