cli: propagate host allocation errors from source queries
This commit is contained in:
1 parent
6945b511a4
commit
50a7575efb
6 files changed
+401
-127
No files matched your search
@@ -135,7 +135,7 @@ The complete 4,096-array check still accepts before and after. The 16,384-array
|
||||
|
||||
## Source annotation resolution
|
||||
|
||||
The 16,384-array source again aborts before this increment at 24a3876: the fresh traceback contains 5,440 resolveType frames, exit -6 and no diagnostic JSON. Lowering now records array/wrapper continuations, resolves the leaf and constructs the source Ty chain from inside outward. Array-length and known-wrapper checks remain before child resolution; array value-content and AtomicScalar checks remain after it, with the original spans, messages and fields. Nominal names still stop at their declaration index. Pending storage is released on success, rejection or allocation error; metadata and resulting type allocation failures propagate as host OutOfMemory. No source/AIR constructor, semantic limit, diagnostic code, runtime/fuel/effect/ownership rule or bundle is changed.
|
||||
The 16,384-array source again aborts before this increment at 24a3876: the fresh traceback contains 5,440 resolveType frames, exit -6 and no diagnostic JSON. Lowering now records array/wrapper continuations, resolves the leaf and constructs the source Ty chain from inside outward. Array-length and known-wrapper checks remain before child resolution; array value-content and AtomicScalar checks remain after it, with the original spans, messages and fields. Nominal names still stop at their declaration index. The pending list is deinitialized on success, rejection or allocation error; its caller-arena buffers remain until arena destruction. Metadata and resulting type allocation failures propagate as host OutOfMemory. No source/AIR constructor, semantic limit, diagnostic code, runtime/fuel/effect/ownership rule or bundle is changed.
|
||||
|
||||
Tests compare 1,736 shallow leaf/array/wrapper combinations against the independent pre-repair derivation, including unknown names/constructors, array boundary lengths and competing error priority. A 32,768-level mixed annotation is constructed and inspected iteratively; unknown and nonvalue leaves retain their original diagnostics. Every allocator request is failed in turn, with arena cleanup checked. Type-position and Copy-content CLI integration pass 74 and 119 checks. All units and format checks pass. All 1,791 conformance cases pass with exact corpus coverage; all 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr.
|
||||
|
||||
@@ -159,7 +159,7 @@ The complete formerly failing Copy chain accepts with no output. Replacing its f
|
||||
|
||||
## Source type text repair
|
||||
|
||||
The 65,536-array invalid-atomic source's confirmed typeText abort is repaired by an iterative prefix/leaf/suffix writer. One growing byte buffer replaces recursively copied ancestor strings; temporary parent storage and failed output buffers are released. Canonical spelling, array decimal lengths/spaces, source-versus-AIR nominal names and the resources feature side effect are preserved. The internal typeText/tyText/diagnosticTyText APIs now propagate host OutOfMemory at every caller, replacing the old array/borrow/cap fallback strings. Failed metadata allocation must not fabricate a found type or generated AIR; ordinary diagnostics, syntax, effects, ownership/runtime/fuel and acceptance rules are unchanged.
|
||||
The 65,536-array invalid-atomic source's confirmed typeText abort is repaired by an iterative prefix/leaf/suffix writer. One growing byte buffer replaces recursively copied ancestor strings; parent lists are deinitialized, while their buffers and failed output buffers retain caller-arena lifetime. Canonical spelling, array decimal lengths/spaces, source-versus-AIR nominal names and the resources feature side effect are preserved. The internal typeText/tyText/diagnosticTyText APIs now propagate host OutOfMemory at every caller, replacing the old array/borrow/cap fallback strings. Failed metadata allocation must not fabricate a found type or generated AIR; ordinary diagnostics, syntax, effects, ownership/runtime/fuel and acceptance rules are unchanged.
|
||||
|
||||
Independent shallow tests compare 3,696 canonical/diagnostic outputs and feature states against the old printer, covering every wrapper/leaf, nominal display-name fallbacks and zero/max-u64 array lengths. A 65,536-level mixed chain has independently assembled exact text in both modes. Allocation failures cover direct printing, diagnostics and local AIR emission, with arena cleanup and no fabricated diagnostic/partial instruction; constant leaves retain the allocation-free path. Units and format checks pass. Repair-advice/nonvalue/static-function CLI integration passes 299/635/25 checks; all 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. All 1,791 conformance cases pass with exact corpus coverage.
|
||||
|
||||
@@ -216,7 +216,7 @@ Only child core capture is disabled; no timeout ends a probe.
|
||||
|
||||
The query now validates the chain and resolves its leaf before allocating,
|
||||
then constructs output with a fresh-node cursor. Its restricted name/array
|
||||
classification, length rules and best-effort OOM-to-null behavior are unchanged.
|
||||
classification and length rules are unchanged. OOM-to-null was retained at this historical checkpoint; the [Q-061 host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) supersedes that error policy and renames the helper `queryAnnotation`.
|
||||
Invalid/unknown leaves allocate nothing. Nodes are allocated outer-to-inner
|
||||
instead of inner-to-outer; request counts, sizes and alignments match the old
|
||||
query, and a partial private type is never returned. The caller arena owns
|
||||
|
||||
@@ -533,4 +533,6 @@ The [expected-use increment](source-expression-depth-audit.md#expected-use-query
|
||||
|
||||
The [binary operand increment](source-expression-depth-audit.md#binary-operand-lowering-continuations) shares explicit continuations with unary lowering, preserving type/error priority, instruction order and short-circuit CFG. Arithmetic checks/lowerings accept through 65,536 operations; deep boolean chains now reach the existing E5101 block limit without stack failure. No normative depth limit or operator rule changes. Current parenthesized and generic-unary checks still abort at 1,024 levels; Q-061's remaining inventory and independent Phase 6 gates stay open.
|
||||
|
||||
The [external review and host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) supersede the initial query OOM-to-unknown policy. A one-shot allocation failure reproduces false E7007 before repair. Expression/expected-use queries and their annotation, field, signature and place callbacks now propagate host OOM separately from optional unknown answers. Worklist buffers retain caller-arena lifetime; list deinit is not immediate physical release. The audit explicitly inventories non-scalar parsing/lowering, generic cloning/path callbacks and liveness/read/assignment scans. Build/units/format checks, all 1,793 ordinary conformance cases, 360 expression-depth and 234 independent-error CLI checks pass; frozen old/new public checks/lowerings remain exact (1,423/506). Recovering caller/callback and public-lowering allocation tests reject false diagnostics and partial publication. Q-061 remains open; this follow-up has no external review yet.
|
||||
|
||||
Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one.
|
||||
@@ -31,7 +31,9 @@ such as `ref -value`, `mut not value` or `ref move value`.
|
||||
Each rebuilt node retains its own start and the final operand end, including
|
||||
comments, newlines and file provenance. AST node order, operator association,
|
||||
postfix precedence and syntax failure positions are unchanged. Pending metadata
|
||||
is host compiler storage and is released on completion/error. Allocation failure
|
||||
is host compiler storage allocated from the caller arena. Its logical list
|
||||
is deinitialized on completion/error; backing storage is retained until that
|
||||
arena is destroyed. Allocation failure
|
||||
still propagates OutOfMemory; no partial AST escapes, new code or depth rejection
|
||||
is introduced. AIR, verifier ownership/borrow rules, runtime evaluation, fuel,
|
||||
effects and source/reference bundle text are unchanged.
|
||||
@@ -81,8 +83,9 @@ preserves root-bound-before-base order, left/right and statement/tail order,
|
||||
callee/argument order and the final split_at root visit. The old skipped select
|
||||
and lock-place inputs stay skipped; storage policy is not extended here.
|
||||
|
||||
Both worklists are host metadata, released on error/completion; finished values
|
||||
and addressability facts retain their caller-arena lifetime. OOM propagates
|
||||
Both worklists are host metadata in the caller arena. Their lists are
|
||||
deinitialized on error/completion, but backing buffers, finished values and
|
||||
addressability facts retain their caller-arena lifetime. OOM propagates
|
||||
without a source diagnostic or public partial AIR. The verifier's load/borrow,
|
||||
initialization and atomic-access rules, runtime operations, ownership, lexical
|
||||
ends, effects and source/AIR formats are unchanged. Borrowed scalar reads remain
|
||||
@@ -132,11 +135,12 @@ Expression and built-in result queries now share an explicit continuation
|
||||
worklist. It preserves left-before-right fallback, first-known match arm,
|
||||
first array element, branch-tail policy, field/len classification, callee
|
||||
priority and built-in argument/borrow handling. Negation, shift, block and
|
||||
if-tail queries use loop transitions. Queries remain best-effort: type-output
|
||||
OOM already returned unknown, and continuation-allocation OOM now does too,
|
||||
without a diagnostic. This adds host metadata requests; allocation counts and
|
||||
failure-index classifications are not claimed identical. Pending storage is
|
||||
released, and type nodes keep their caller-arena lifetime.
|
||||
if-tail queries use loop transitions. At this initial checkpoint, type-output
|
||||
and continuation-allocation OOM returned unknown. The external review below
|
||||
identifies why that can become a false diagnostic at a caller; the host-OOM
|
||||
repair supersedes this behavior. Allocation counts and failure-index
|
||||
classifications are not promised identical. Pending lists are deinitialized;
|
||||
their buffers and output type nodes retain their caller-arena lifetime.
|
||||
|
||||
The query's callee callbacks also exposed recursive `expressionPath` and
|
||||
bounded `dotted`. Both now walk field chains iteratively. `expressionPath`
|
||||
@@ -183,9 +187,11 @@ after the earlier use fails. The outer `inferUses` rest cursor and top-level
|
||||
let rebinding barrier are unchanged; nested blocks and skipped expression/
|
||||
statement kinds retain their original policy. No new inference is introduced.
|
||||
|
||||
The requests are host metadata, released on success/error; hint type nodes
|
||||
retain their caller-arena lifetime. As in other best-effort type queries,
|
||||
metadata OOM produces unknown without a diagnostic or instructions. This adds
|
||||
The requests are host metadata in the caller arena. Logical lists are
|
||||
deinitialized on success/error; their buffers and hint type nodes remain
|
||||
until arena destruction. Initially, metadata OOM returned unknown. The
|
||||
review and host-OOM repair below supersede that behavior because a caller
|
||||
can turn unknown into a false inference diagnostic. This adds
|
||||
allocation requests and does not promise identical failure-index outcomes.
|
||||
Plain unary descent is a loop without work allocations. Runtime memory,
|
||||
ownership, fuel and verifier rules are unchanged; no normative rule, format,
|
||||
@@ -236,8 +242,9 @@ lower/check right, branch to the stored join and resume there. Runtime still
|
||||
evaluates right only when needed; both operands are lowered and type checked.
|
||||
Negative zero order, signed-minimum literal handling, cast checks, atomic
|
||||
diagnostics and iref identity rules remain unchanged. Host worklist OOM
|
||||
propagates without a query diagnostic or public partial AIR; its metadata is
|
||||
released while generated values retain their caller-arena lifetime. Allocation
|
||||
propagates without a query diagnostic or public partial AIR. Its list is
|
||||
deinitialized; backing buffers and generated values retain their caller-arena
|
||||
lifetime. Allocation
|
||||
counts/failure-index outcomes are not promised identical.
|
||||
|
||||
The independent old scalar derivation now covers binary rules as well as
|
||||
@@ -272,19 +279,67 @@ GC validation or a model-capability result.
|
||||
No normative rule, source/AIR format, feature, error code, bundle text, runtime
|
||||
instruction, ownership rule or acceptance limit changes. Q-061 remains open.
|
||||
|
||||
## External review and host-OOM follow-up
|
||||
|
||||
The owner relayed a read-only Claude review of c36b269, dd73b84, e862e03,
|
||||
e3f4695 and 6945b51, with the local report `/tmp/aji-q061-review.md`.
|
||||
It found no divergence in grammar, spans, query/error/emission order or
|
||||
short-circuit CFG. The reviewer ran selected synthetic CLI probes, but did
|
||||
not build or run the full suites.
|
||||
|
||||
The review identifies a real failure-policy defect: `peekType` and expected-use
|
||||
queries erase host OOM into null; callers can then emit E7007. The existing
|
||||
array-annotation and qualified-callee helpers have the same problem. A
|
||||
regression test with a one-shot allocation failure reproduces E7007 at a
|
||||
negation before the repair (`query-oom-before-tests.log`, terminal exit 1).
|
||||
The allocator resumes working after its single failure, so allocating a false
|
||||
diagnostic cannot hide this defect behind a second OOM.
|
||||
|
||||
The implementation follow-up separates optional unknown answers from fallible
|
||||
host allocation in expression/expected-use queries and their annotation,
|
||||
field, signature, borrow-return and assignment-place callbacks. Callers use
|
||||
`try` and retain their lazy fallback policy. Type-output allocations also
|
||||
propagate OOM. No inference, grammar, diagnostic fields/codes, acceptance limit,
|
||||
ownership, runtime or bundle rule changes. Generated nodes and worklist buffers
|
||||
remain caller-arena storage; list deinit does not establish immediate physical
|
||||
release. Cleanup claims refer to arena destruction, or direct allocator tests
|
||||
that actually observe frees.
|
||||
|
||||
Validation passes: build/units/Zig format checks, all 1,793 ordinary
|
||||
conformance cases with exact unique corpus coverage (`query-oom-conformance.jsonl`
|
||||
and its audit), 360 expression-depth CLI checks and 234 independent-error CLI
|
||||
checks. Frozen old/new executables retain exact exit/stdout/stderr on 1,423 public
|
||||
source checks and 506 accepted lowerings (`query-oom-cli-compatibility.json`).
|
||||
Allocation tests cover ten lowering callers, twelve annotation/signature/builtin
|
||||
callback cases, every recovering direct-allocation failure in three finite
|
||||
public `lower` fixtures, and the existing exhaustive worklist/array-output
|
||||
failure loops. Recovery tests check that no diagnostic/output or retry follows
|
||||
the failure; arena/direct-allocator tests check actual cleanup at their ownership
|
||||
boundary. Invalid/unknown lookups still return null without allocating, and
|
||||
lazy-query tests still avoid unnecessary right-side work. This establishes
|
||||
compiler error policy, not a new model result or full GC pass. Q-061 is open;
|
||||
this follow-up has not yet received external review.
|
||||
|
||||
## Remaining work
|
||||
|
||||
Current follow-up checks still abort with empty stdout at 1,024 parenthesized
|
||||
levels and 1,024 generic unary levels (`binary-followup-depth-probes.json` and
|
||||
`binary-followup-*.stdout/.stderr`). Parenthesized parsing and generic expression
|
||||
transformation require separate repairs.
|
||||
`binary-followup-*.stdout/.stderr`). The remaining inventory is broader than
|
||||
these two observed failures:
|
||||
|
||||
Inspection of the generic transformation also finds a recursive qualified-path
|
||||
callback (`generics.path`). Its deep full-source behavior is unverified here;
|
||||
it belongs in that repair's callback inventory, rather than Q-059's type scope.
|
||||
| Production path | Evidence and next scope |
|
||||
|---|---|
|
||||
| Parser `postfix`/`primary` through parenthesized `expr` | Confirmed failure at 1,024 levels; preserve grouping, precedence and spans. |
|
||||
| Parser `callArgs`, array/index/struct initializers, `ifExpr`, block/statement and match/arm expression entry | Recursive callbacks inspected; deep behavior unverified. Include mixed forms such as `n + f(n + f(...))`, not only homogeneous spines. |
|
||||
| Parser `exprPath` | Recursive qualified-field callback inspected; deep source behavior unverified. |
|
||||
| Generic `expression`/reflective `walk` | Confirmed generic unary failure at 1,024; include call/type/static-worker handling and nested statement/block cloning. |
|
||||
| Generic `path` | Recursive qualified-field callback inspected; deep full-source behavior unverified. |
|
||||
| Lowerer non-scalar `expr` callbacks: calls, fields/indices/places, arrays/structs, if/match/arms and blocks/statements | Native re-entry remains outside the repaired scalar driver; deep behavior unverified, including alternating scalar/non-scalar expressions. |
|
||||
| Lowerer use-after-region/liveness and assignment scans (`After`, first-use/read scans, `blockAssigns`/`stmtAssigns`/`exprAssigns`, match/select helpers) | Recursive AST walks inspected; audit their callers and finite deep inputs separately. |
|
||||
|
||||
Other expression/block handlers and their complete depth behavior need further
|
||||
auditing. The formatter's expression-marking traversal already uses a worklist,
|
||||
as inspected and exercised by the deep syntax-only probes. Q-061 and Phase 6
|
||||
remain open; Q-060's unfinished full GC validation is independent. No fresh
|
||||
Claude review covers these expression increments.
|
||||
The formatter's expression-marking traversal already uses a worklist, as
|
||||
inspected and exercised by deep syntax-only probes. This inventory does not
|
||||
claim every listed callback fails, or that all other paths have been cleared.
|
||||
Q-061 and Phase 6 remain open; Q-060's unfinished full GC validation is
|
||||
independent. The five reviewed increments now have a scoped external review;
|
||||
the host-OOM follow-up and later repairs need their own review.
|
||||
@@ -25,7 +25,7 @@ or statement nesting, or bounded processing of fabricated cyclic host pointers.
|
||||
| Source type-position and Copy-content scans (`src/frontend/type_positions.zig`, `src/frontend/type_properties.zig`) | Anonymous cursors, explicit nominal argument/member continuations and indexed cycle paths. |
|
||||
| Source resolution, text, AIR conversion, equality (`src/frontend/lower.zig`) | Pending constructors/suffixes, fresh output-target cursor or two comparison cursors. |
|
||||
| Source linearity, signature feature discovery, SSA zero | Iterative chains; the existing module-sized feature-discovery guard remains. Unsupported zero leaves reject before emission. |
|
||||
| Source best-effort `typeOfNoFail` | Validate chain/leaf before allocation, then build fresh output nodes iteratively. Only names/arrays are recognized; OOM remains `null`, without a diagnostic or published partial type. |
|
||||
| Source optional `queryAnnotation` (formerly `typeOfNoFail`) | Validate chain/leaf before allocation, then build fresh output nodes iteratively. Only names/arrays are recognized. Unknown stays `null`; the [Q-061 host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) propagates allocation failure separately, without a diagnostic or published partial type. |
|
||||
| Source `forbiddenIn` | Remaining recursion checks `depth > 32` before descent; named cached distance prunes unreachable witnesses. Calls to annotation resolution use the iterative path above. |
|
||||
| Generic headers/substitution/static arguments | `headerType`/`headerArgument` and `ty`/`instantiate` retain their existing guards at 64. Static-function argument resolution re-enters guarded instantiation; reflective specialization intercepts `ast.Type` before visiting its representation. |
|
||||
| Composed specialization identities | Iterative prefix/leaf/suffix writer. Substitution can return an already composed type deeper than one guarded `ty` traversal, so identity emission must not rely on that guard. Existing key-size checks retain their postorder spans. |
|
||||
|
||||
@@ -511,7 +511,7 @@ Units/format checks, shallow/deep key-boundary and OOM tests, generic/static-fun
|
||||
|
||||
## Type-depth closing audit (2026-10-10)
|
||||
|
||||
Q-059 is resolved for the [compiler type-traversal inventory](../design/type-traversal-inventory.md). The final repair removes a confirmed `typeOfNoFail` failure reached through shallow field expressions; complete checks accept 16,384/65,536 nested field-array levels. The best-effort query retains its type classification and OOM-to-null contract without publishing partial output. Independent shallow/deep/allocation tests, units/format checks, all 1,793 conformance cases with exact coverage, nominal CLI integration (130 checks) and byte-identical old/new source checks/lowerings (1,423/506) pass.
|
||||
Q-059 is resolved for the [compiler type-traversal inventory](../design/type-traversal-inventory.md). The final repair removes a confirmed `typeOfNoFail` failure reached through shallow field expressions; complete checks accept 16,384/65,536 nested field-array levels. At this historical checkpoint the query retained its type classification and OOM-to-null contract; the host-OOM follow-up below supersedes that error policy. Independent shallow/deep/allocation tests, units/format checks, all 1,793 conformance cases with exact coverage, nominal CLI integration (130 checks) and byte-identical old/new source checks/lowerings (1,423/506) pass.
|
||||
|
||||
This closes type descent, not arbitrary expression/statement recursion (inspection-only Q-061), Q-056 policy, Q-060's unfinished full per-step GC validation or Phase 6 exit review. No normative/bundle/feature/code or acceptance-limit changes; Claude's earlier nominal-property review does not cover these later frontend increments.
|
||||
|
||||
@@ -535,13 +535,13 @@ Independent unary/addressability oracles, 32,768-node cases and allocation clean
|
||||
|
||||
## Source expression type queries (2026-10-10)
|
||||
|
||||
The [Q-061 query increment](../design/source-expression-depth-audit.md#expression-type-query-continuations) replaces expression/built-in result recursion with explicit continuations, retaining classification, lazy fallback and callee priority. Its callee callbacks build qualified paths iteratively with one complete string. Best-effort queries retain unknown on output OOM and now use the same outcome on continuation OOM; host allocation counts need not match. No normative/bundle/feature/code/acceptance-limit or runtime/ownership change.
|
||||
The [Q-061 query increment](../design/source-expression-depth-audit.md#expression-type-query-continuations) replaces expression/built-in result recursion with explicit continuations, retaining classification, lazy fallback and callee priority. Its callee callbacks build qualified paths iteratively with one complete string. At this historical checkpoint, queries returned unknown on output/continuation OOM; the host-OOM follow-up below supersedes that policy. Host allocation counts need not match. No normative/bundle/feature/code/acceptance-limit or runtime/ownership change.
|
||||
|
||||
Independent shallow descent comparisons (703), deep structural/built-in/fallback cases, 65,536-field path construction and allocation cleanup tests pass. Final build/units/format checks and all 1,793 ordinary conformance cases with exact coverage pass, as do 139 expression-depth, 635 non-value, 33 atomic-access and 6,078 formatter CLI checks; old/new public checks/lowerings remain exact (1,423/506). The formerly crashing cast/dereference source now returns its inner E7005. A separate unsuffixed-binding probe accepts 1,024 negations but confirms the next native failure in useIn at 16,384. Q-061's expected-use, other expression/statement and generic paths, Q-060's full per-step validation and Phase 6 exit review remain open. Claude's earlier Q-059 property review does not cover this increment.
|
||||
|
||||
## Source expected-use queries (2026-10-10)
|
||||
|
||||
The [Q-061 expected-use increment](../design/source-expression-depth-audit.md#expected-use-query-continuations) replaces mutual expression/statement/block query recursion with explicit requests. Deferred comparison/shift/for hints preserve lazy search order; the outer rest cursor, top-level let rebinding barrier, cast hint removal and skipped kinds retain their original policy. Host metadata OOM is unknown without diagnostics/output; no new inference, normative/bundle/feature/code/acceptance-limit or runtime/ownership rule is introduced.
|
||||
The [Q-061 expected-use increment](../design/source-expression-depth-audit.md#expected-use-query-continuations) replaces mutual expression/statement/block query recursion with explicit requests. Deferred comparison/shift/for hints preserve lazy search order; the outer rest cursor, top-level let rebinding barrier, cast hint removal and skipped kinds retain their original policy. The initial metadata-OOM-to-unknown policy is superseded by the host-OOM follow-up below; no new inference, normative/bundle/feature/code/acceptance-limit or runtime/ownership rule is introduced.
|
||||
|
||||
Independent shallow comparisons (967), 32,768-level unary/mixed/block helpers, deferred-hint allocation traps and worklist-OOM cleanup tests pass. Final build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 186 expression-depth, 635 non-value and 234 independent-error CLI checks pass; old/new public checks/lowerings remain exact (1,423/506). The previously crashing inferred-binding source accepts through 65,536 negations, while missing context retains E7007. Follow-up probes confirm separate native failures at 1,024 levels in binary lowering, parenthesized parsing and generic expression transformation. Q-061's remaining inventory, Q-060's full per-step validation and Phase 6 exit review remain open. No fresh Claude review covers this increment.
|
||||
|
||||
@@ -550,3 +550,25 @@ Independent shallow comparisons (967), 32,768-level unary/mixed/block helpers, d
|
||||
The [Q-061 binary increment](../design/source-expression-depth-audit.md#binary-operand-lowering-continuations) shares scalar continuations with unary lowering, eliminating native re-entry on alternating operator trees. Eager operand type/error priority, instruction/span/name order and boolean RHS/join construction are retained; runtime short-circuit behavior and fuel remain unchanged. Worklist OOM propagates without public partial AIR. No normative/bundle/feature/code/acceptance-limit or ownership/runtime rule changes.
|
||||
|
||||
Independent binary/wrapper/context comparisons (6,048), deep left/right/mixed/boolean helpers and exact failed-allocation block prefixes pass. Build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 360 expression-depth, 635 non-value and 234 independent-error CLI checks pass; old/new public checks/lowerings remain exact (1,423/506). Arithmetic checks/lowerings accept through 65,536 operations. Boolean chains accept at 1,024; at 16,384 they reach the existing E5101 block limit (`max: 16384`, `found: 32769`), rather than aborting. Current probes retain separate parenthesized/generic failures at 1,024 levels; their callbacks and other expression/block paths still need repair/audit. Q-061, Q-060's full per-step validation and Phase 6 exit review remain open. No fresh Claude review covers this increment.
|
||||
|
||||
## Source query host-OOM follow-up (2026-10-10)
|
||||
|
||||
Claude's relayed read-only review covers the five Q-061 increments through
|
||||
6945b51. It found no grammar/span/query/error/emission/CFG divergence, but
|
||||
identified host OOM erased into unknown and subsequently reported as E7007.
|
||||
The [follow-up](../design/source-expression-depth-audit.md#external-review-and-host-oom-follow-up) reproduces this with a recovering one-shot allocation failure
|
||||
and makes the query/callback closure fallible. Unknown remains optional; lazy
|
||||
lookup and source diagnostics without OOM are unchanged. No normative, bundle,
|
||||
feature, code, acceptance-limit or runtime rule change.
|
||||
|
||||
The audit corrects worklist memory claims: buffers allocated in the caller arena
|
||||
remain until arena destruction. It also lists the remaining non-scalar parser/
|
||||
lowerer and liveness/read/assignment paths explicitly. Build/units/format
|
||||
checks, all 1,793 ordinary conformance cases with exact coverage, 360
|
||||
expression-depth and 234 independent-error CLI checks pass. Recovering failures
|
||||
are covered at ten callers, twelve callbacks and every direct allocation in
|
||||
three public-lowering fixtures; existing worklist/array-output failure loops
|
||||
now assert OOM propagation and cleanup. Frozen old/new public checks/lowerings
|
||||
remain exact (1,423/506). Generic transformation and parenthesized parsing still
|
||||
have confirmed depth failures; Q-061, Q-060's full per-step validation and the
|
||||
Phase 6 exit gates remain open. The existing review does not cover this repair.
|
||||
+292
-97
@@ -465,13 +465,13 @@ const Lowerer = struct {
|
||||
return out.toOwnedSlice(l.arena);
|
||||
}
|
||||
|
||||
fn wrap(l: *Lowerer, comptime tag: std.meta.Tag(Ty), t: Ty) Error!Ty {
|
||||
fn wrap(l: *Lowerer, comptime tag: std.meta.Tag(Ty), t: Ty) Allocator.Error!Ty {
|
||||
const b = try l.arena.create(Ty);
|
||||
b.* = t;
|
||||
return @unionInit(Ty, @tagName(tag), b);
|
||||
}
|
||||
|
||||
fn arrayOf(l: *Lowerer, elem: Ty, len: u64) Error!Ty {
|
||||
fn arrayOf(l: *Lowerer, elem: Ty, len: u64) Allocator.Error!Ty {
|
||||
const a = try l.arena.create(Ty.Arr);
|
||||
a.* = .{ .elem = elem, .len = len };
|
||||
return .{ .array = a };
|
||||
@@ -1287,7 +1287,7 @@ const Lowerer = struct {
|
||||
var want: ?Ty = annotation;
|
||||
// An untyped `let` takes its type from how the name is used
|
||||
// later (`return`, arguments, operations, annotations).
|
||||
if (want == null and l.peekType(x.e) == null) want = l.inferUses(x.names[0]);
|
||||
if (want == null and (try l.peekType(x.e)) == null) want = (try l.inferUses(x.names[0]));
|
||||
if (x.e.kind == .or_trap) {
|
||||
const v = try l.expr(x.e, want);
|
||||
if (want) |w| try l.checkTy(x.e.span, v.ty, w);
|
||||
@@ -1354,7 +1354,7 @@ const Lowerer = struct {
|
||||
const scope_start = l.scopeBindingStart();
|
||||
for (l.bindings.items[scope_start..]) |b| if (b.kind == .borrow and std.mem.eql(u8, b.name, x.name))
|
||||
return l.invalid(.invalid_binding, s.span, "a borrow of this name is already active in this scope", &.{.{ .name = "name", .value = x.name }});
|
||||
if (x.place.kind == .call) if (l.borrowReturnSig(x.place.kind.call.callee.*)) |sig| if (sig.ret.isBorrow()) {
|
||||
if (x.place.kind == .call) if ((try l.borrowReturnSig(x.place.kind.call.callee.*))) |sig| if (sig.ret.isBorrow()) {
|
||||
if (x.unchecked) return l.invalid(.invalid_place, s.span, "unchecked applies to element places, not calls", &.{});
|
||||
if (x.mutable != sig.ret.isMutBorrow()) return l.fail("E7005", s.span, "binding mode must match the returned borrow; use ref for shared or mut for exclusive", &.{});
|
||||
const call_expr = x.place.kind.call;
|
||||
@@ -1505,7 +1505,7 @@ const Lowerer = struct {
|
||||
fn forLoop(l: *Lowerer, span: Span, name: []const u8, lo: ast.Expr, hi: ast.Expr, body: ast.Block) Error!void {
|
||||
const depth = l.bindings.items.len;
|
||||
defer l.bindings.shrinkRetainingCapacity(depth);
|
||||
const ty = l.peekType(lo) orelse l.peekType(hi) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{});
|
||||
const ty = (try l.peekType(lo)) orelse (try l.peekType(hi)) orelse return l.fail("E7007", lo.span, "the type of the range cannot be determined; add a suffix such as `0usize`", &.{});
|
||||
if (ty != .int) return l.fail("E7005", lo.span, "a range needs an integer type", &.{.{ .name = "found", .value = try l.diagnosticTyText(ty) }});
|
||||
const a = try l.expr(lo, ty);
|
||||
try l.checkOperandTy(lo.span, a.ty, ty);
|
||||
@@ -1561,12 +1561,12 @@ const Lowerer = struct {
|
||||
return l.sigs.get(l.boundName(name, span) orelse return null);
|
||||
}
|
||||
|
||||
fn calleeSig(l: *Lowerer, e: ast.Expr) ?FnSig {
|
||||
const name = expressionPath(l.arena, e) catch return null;
|
||||
fn calleeSig(l: *Lowerer, e: ast.Expr) Allocator.Error!?FnSig {
|
||||
const name = try expressionPath(l.arena, e);
|
||||
return l.functionSig(name orelse return null, e.span);
|
||||
}
|
||||
|
||||
fn borrowReturnSig(l: *Lowerer, e: ast.Expr) ?FnSig {
|
||||
fn borrowReturnSig(l: *Lowerer, e: ast.Expr) Allocator.Error!?FnSig {
|
||||
if (pathOf(e) != null) return null;
|
||||
if (e.kind == .name and (std.mem.eql(u8, e.kind.name, "assert") or std.mem.eql(u8, e.kind.name, "assume"))) return null;
|
||||
return l.calleeSig(e);
|
||||
@@ -1586,10 +1586,10 @@ const Lowerer = struct {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Best-effort query: output construction already treats host OOM as
|
||||
// unknown. Continuation OOM follows that contract without a diagnostic.
|
||||
fn peekType(l: *Lowerer, e: ast.Expr) ?Ty {
|
||||
return l.queryType(.{ .expr = e }) catch null;
|
||||
// Unknown types return null; host allocation failure propagates separately
|
||||
// so callers cannot mistake OOM for a source inference error.
|
||||
fn peekType(l: *Lowerer, e: ast.Expr) Allocator.Error!?Ty {
|
||||
return l.queryType(.{ .expr = e });
|
||||
}
|
||||
|
||||
const TypeRequest = union(enum) { expr: ast.Expr, path: struct { name: []const u8, args: []const ast.Expr } };
|
||||
@@ -1640,7 +1640,7 @@ const Lowerer = struct {
|
||||
request = .{ .expr = xs[0] };
|
||||
continue :query;
|
||||
},
|
||||
.cast => |x| l.typeOfNoFail(x.ty),
|
||||
.cast => |x| (try l.queryAnnotation(x.ty)),
|
||||
.binary => |x| switch (x.op) {
|
||||
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
|
||||
else => {
|
||||
@@ -1653,7 +1653,7 @@ const Lowerer = struct {
|
||||
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
|
||||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||||
else => blk: {
|
||||
if (l.calleeSig(x.callee.*)) |sig| break :blk sig.ret;
|
||||
if ((try l.calleeSig(x.callee.*))) |sig| break :blk sig.ret;
|
||||
const name = pathOf(x.callee.*) orelse break :blk null;
|
||||
request = .{ .path = .{ .name = name, .args = x.args } };
|
||||
continue :query;
|
||||
@@ -1689,8 +1689,8 @@ const Lowerer = struct {
|
||||
if (eq(u8, p.name, "buffer.len") or eq(u8, p.name, "buffer.capacity")) break :blk Ty{ .int = "usize" };
|
||||
if (eq(u8, p.name, "task.cancelled")) break :blk Ty.bool;
|
||||
if (eq(u8, p.name, "task.spawn") and p.args.len >= 2) {
|
||||
const sig = l.calleeSig(p.args[1]) orelse break :blk null;
|
||||
break :blk l.wrap(.task, sig.ret) catch null;
|
||||
const sig = (try l.calleeSig(p.args[1])) orelse break :blk null;
|
||||
break :blk (try l.wrap(.task, sig.ret));
|
||||
}
|
||||
if ((eq(u8, p.name, "own.take") or eq(u8, p.name, "task.join")) and p.args.len == 1) {
|
||||
try pending.append(l.arena, .inner);
|
||||
@@ -1718,7 +1718,7 @@ const Lowerer = struct {
|
||||
while (pending.pop()) |frame| switch (frame) {
|
||||
.inner => result = if (result) |t| t.inner() else null,
|
||||
.element => result = if (result) |t| elemOf(t) else null,
|
||||
.array => |len| result = if (result) |t| l.arrayOf(t, len) catch null else null,
|
||||
.array => |len| result = if (result) |t| (try l.arrayOf(t, len)) else null,
|
||||
.alternative => |e| if (result == null) {
|
||||
request = .{ .expr = e };
|
||||
continue :query;
|
||||
@@ -1728,14 +1728,14 @@ const Lowerer = struct {
|
||||
request = .{ .expr = arms[0].body };
|
||||
continue :query;
|
||||
},
|
||||
.field => |name| result = l.queryField(result, name),
|
||||
.field => |name| result = (try l.queryField(result, name)),
|
||||
.operation => |op| result = if (result) |t| switch (op) {
|
||||
.atomic_new => l.wrap(.atomic, t) catch null,
|
||||
.atomic_new => (try l.wrap(.atomic, t)),
|
||||
.atomic_load_inline => if (t == .atomic) t.inner() else null,
|
||||
.atomic_load_borrow => if (t.inner()) |c| (if (c == .atomic) c.inner() else null) else null,
|
||||
.graph_root => if (t.inner()) |o| (if (o.inner()) |r| l.wrap(.iref, r) catch null else null) else null,
|
||||
.freeze => if (t == .island) l.wrap(.frozen, t.inner().?) catch null else null,
|
||||
.arc_from => if (t == .frozen) l.wrap(.arc, t.inner().?) catch null else null,
|
||||
.graph_root => if (t.inner()) |o| (if (o.inner()) |r| (try l.wrap(.iref, r)) else null) else null,
|
||||
.freeze => if (t == .island) (try l.wrap(.frozen, t.inner().?)) else null,
|
||||
.arc_from => if (t == .frozen) (try l.wrap(.arc, t.inner().?)) else null,
|
||||
.arc_clone => if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null,
|
||||
.channel_dup => if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null,
|
||||
} else null,
|
||||
@@ -1744,44 +1744,44 @@ const Lowerer = struct {
|
||||
}
|
||||
}
|
||||
|
||||
fn queryField(l: *Lowerer, known: ?Ty, name: []const u8) ?Ty {
|
||||
fn queryField(l: *Lowerer, known: ?Ty, name: []const u8) Allocator.Error!?Ty {
|
||||
if (std.mem.eql(u8, name, "len") and (known == null or !isNominalFieldBase(known.?))) return .{ .int = "usize" };
|
||||
var base = known orelse return null;
|
||||
if (base.isBorrow()) base = base.inner().?;
|
||||
const d = l.decl(base) orelse return null;
|
||||
if (d.kind != .@"struct") return null;
|
||||
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, name)) return l.typeOfNoFail(f.ty);
|
||||
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, name)) return l.queryAnnotation(f.ty);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The type the following code expects for the name `n`, if any use
|
||||
/// determines one. Stops at a rebinding of `n`.
|
||||
fn inferUses(l: *Lowerer, n: []const u8) ?Ty {
|
||||
fn inferUses(l: *Lowerer, n: []const u8) Allocator.Error!?Ty {
|
||||
var i = l.rest.items.len;
|
||||
while (i > 0) {
|
||||
i -= 1;
|
||||
const r = l.rest.items[i];
|
||||
for (r.stmts) |s| {
|
||||
if (l.usesInStmt(n, s)) |t| return t;
|
||||
if ((try l.usesInStmt(n, s))) |t| return t;
|
||||
if (s.kind == .let) for (s.kind.let.names) |bn| if (std.mem.eql(u8, bn, n)) return null;
|
||||
}
|
||||
if (r.tail) |t| if (l.useIn(n, t.*, if (i == 0) l.ret else null)) |ty| return ty;
|
||||
if (r.tail) |t| if ((try l.useIn(n, t.*, if (i == 0) l.ret else null))) |ty| return ty;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty {
|
||||
return l.queryUse(n, .{ .statement = s }) catch null;
|
||||
fn usesInStmt(l: *Lowerer, n: []const u8, s: ast.Stmt) Allocator.Error!?Ty {
|
||||
return l.queryUse(n, .{ .statement = s });
|
||||
}
|
||||
|
||||
fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) ?Ty {
|
||||
return l.queryUse(n, .{ .block = b }) catch null;
|
||||
fn usesInBlock(l: *Lowerer, n: []const u8, b: ast.Block) Allocator.Error!?Ty {
|
||||
return l.queryUse(n, .{ .block = b });
|
||||
}
|
||||
|
||||
/// The expected type of `n` inside `e`, evaluated where `e` is expected
|
||||
/// to have type `want`. Like peekType, this is a best-effort query.
|
||||
fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) ?Ty {
|
||||
return l.queryUse(n, .{ .expression = .{ .e = e, .want = .{ .known = want } } }) catch null;
|
||||
/// to have type `want`. Unknown is null; host OOM propagates separately.
|
||||
fn useIn(l: *Lowerer, n: []const u8, e: ast.Expr, want: ?Ty) Allocator.Error!?Ty {
|
||||
return l.queryUse(n, .{ .expression = .{ .e = e, .want = .{ .known = want } } });
|
||||
}
|
||||
|
||||
// Right-hand hints are resolved only after an earlier use was unknown.
|
||||
@@ -1809,8 +1809,8 @@ const Lowerer = struct {
|
||||
const e = x.e;
|
||||
const want: ?Ty = switch (x.want) {
|
||||
.known => |t| t,
|
||||
.peek => |other| l.peekType(other),
|
||||
.peek_or => |other| l.peekType(other.e) orelse other.fallback,
|
||||
.peek => |other| (try l.peekType(other)),
|
||||
.peek_or => |other| (try l.peekType(other.e)) orelse other.fallback,
|
||||
};
|
||||
switch (e.kind) {
|
||||
.name => |name| if (std.mem.eql(u8, name, n)) {
|
||||
@@ -1835,9 +1835,9 @@ const Lowerer = struct {
|
||||
.binary => |b| {
|
||||
const left: ?Ty = switch (b.op) {
|
||||
.@"and", .@"or" => .bool,
|
||||
.eq, .ne, .lt, .le, .gt, .ge => l.peekType(b.r.*),
|
||||
.eq, .ne, .lt, .le, .gt, .ge => (try l.peekType(b.r.*)),
|
||||
.shl, .shr => want,
|
||||
else => want orelse l.peekType(b.l.*) orelse l.peekType(b.r.*),
|
||||
else => want orelse (try l.peekType(b.l.*)) orelse (try l.peekType(b.r.*)),
|
||||
};
|
||||
const right: UseExpected = switch (b.op) {
|
||||
.eq, .ne, .lt, .le, .gt, .ge => .{ .peek = b.l.* },
|
||||
@@ -1849,7 +1849,7 @@ const Lowerer = struct {
|
||||
continue :search;
|
||||
},
|
||||
.call => |c| {
|
||||
const sig = l.calleeSig(c.callee.*) orelse {
|
||||
const sig = (try l.calleeSig(c.callee.*)) orelse {
|
||||
request = pending.pop() orelse return null;
|
||||
continue :search;
|
||||
};
|
||||
@@ -1877,11 +1877,11 @@ const Lowerer = struct {
|
||||
},
|
||||
.statement => |s| switch (s.kind) {
|
||||
.let => |x| {
|
||||
request = .{ .expression = .{ .e = x.e, .want = .{ .known = if (x.ty) |t| l.typeOfNoFail(t) else null } } };
|
||||
request = .{ .expression = .{ .e = x.e, .want = .{ .known = if (x.ty) |t| (try l.queryAnnotation(t)) else null } } };
|
||||
continue :search;
|
||||
},
|
||||
.@"var" => |x| if (x.init) |e| {
|
||||
request = .{ .expression = .{ .e = e, .want = .{ .known = l.typeOfNoFail(x.ty) } } };
|
||||
request = .{ .expression = .{ .e = e, .want = .{ .known = (try l.queryAnnotation(x.ty)) } } };
|
||||
continue :search;
|
||||
},
|
||||
.assign => |x| {
|
||||
@@ -1938,9 +1938,9 @@ const Lowerer = struct {
|
||||
}
|
||||
}
|
||||
|
||||
fn typeOfNoFail(l: *Lowerer, annotation: ast.Type) ?Ty {
|
||||
fn queryAnnotation(l: *Lowerer, annotation: ast.Type) Allocator.Error!?Ty {
|
||||
// Validate before allocating, as the old postorder query did. This
|
||||
// best-effort lookup recognizes only names and fixed array chains.
|
||||
// optional lookup recognizes only names and fixed array chains.
|
||||
var t = annotation;
|
||||
while (t.kind == .array) {
|
||||
const a = t.kind.array;
|
||||
@@ -1959,7 +1959,7 @@ const Lowerer = struct {
|
||||
const a = t.kind.array;
|
||||
// Only fresh output nodes are writable; no source AST is borrowed
|
||||
// or changed. The caller arena retains partial nodes on OOM.
|
||||
const node = l.arena.create(Ty.Arr) catch return null;
|
||||
const node = try l.arena.create(Ty.Arr);
|
||||
node.len = a.len;
|
||||
target.* = .{ .array = node };
|
||||
target = &node.elem;
|
||||
@@ -2078,7 +2078,7 @@ const Lowerer = struct {
|
||||
e = x.*;
|
||||
},
|
||||
.neg => |x| {
|
||||
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
|
||||
const ty = want orelse (try l.peekType(x.*)) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
|
||||
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
|
||||
// Negative literals retain the boundary magnitude rule
|
||||
// and bypass ordinary positive-literal lowering.
|
||||
@@ -2099,7 +2099,7 @@ const Lowerer = struct {
|
||||
.cast => |x| {
|
||||
const to = try l.typeOf(x.ty);
|
||||
if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{});
|
||||
want = l.peekType(x.e.*) orelse to;
|
||||
want = (try l.peekType(x.e.*)) orelse to;
|
||||
try pending.append(l.arena, .{ .unary = .{ .e = e, .ty = to } });
|
||||
e = x.e.*;
|
||||
},
|
||||
@@ -2113,7 +2113,7 @@ const Lowerer = struct {
|
||||
else => false,
|
||||
};
|
||||
const shift = x.op == .shl or x.op == .shr;
|
||||
const operand: ?Ty = if (cmp) (l.peekType(x.l.*) orelse l.peekType(x.r.*)) else if (shift) (want orelse l.peekType(x.l.*)) else (want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*));
|
||||
const operand: ?Ty = if (cmp) ((try l.peekType(x.l.*)) orelse (try l.peekType(x.r.*))) else if (shift) (want orelse (try l.peekType(x.l.*))) else (want orelse (try l.peekType(x.l.*)) orelse (try l.peekType(x.r.*)));
|
||||
const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{});
|
||||
try pending.append(l.arena, .{ .binary_left = .{ .e = e, .ty = ty } });
|
||||
want = ty;
|
||||
@@ -2420,7 +2420,7 @@ const Lowerer = struct {
|
||||
|
||||
/// `v.f` on a struct value: `struct.get` (borrows come in layer 4).
|
||||
fn fieldValue(l: *Lowerer, e: ast.Expr, base: ast.Expr, name: []const u8) Error!Value {
|
||||
var bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
var bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
if (bt.isBorrow()) bt = bt.inner().?;
|
||||
const d = l.decl(bt) orelse return l.fail("E7005", e.span, "field access on a value that is not a struct", &.{.{ .name = "found", .value = try l.diagnosticTyText(bt) }});
|
||||
if (d.kind != .@"struct") return l.fail("E7005", e.span, "field access on an enum; use `match`", &.{.{ .name = "type", .value = d.display_name orelse d.name }});
|
||||
@@ -2483,7 +2483,7 @@ const Lowerer = struct {
|
||||
/// integer (`switch`; `_` required). Payload names live in their arm.
|
||||
fn matchExpr(l: *Lowerer, m: ast.Match, want: ?Ty) Error!Value {
|
||||
if (m.kind == .outcome) return l.outcomeMatch(m, want);
|
||||
const st = l.peekType(m.scrutinee) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
|
||||
const st = (try l.peekType(m.scrutinee)) orelse return l.fail("E7007", m.scrutinee.span, "the type of this value cannot be determined", &.{});
|
||||
if (st == .builtin) return l.builtinMatch(m, st.builtin, want);
|
||||
const sv = try l.consuming(m.scrutinee, st);
|
||||
const depth = l.bindings.items.len;
|
||||
@@ -2944,7 +2944,7 @@ const Lowerer = struct {
|
||||
if (place.kind == .index and place.kind.index.hi != null) return l.invalid(.invalid_assignment, place.span, "assign elements one by one, or use `slice.copy(mut dst, ref src)`", &.{});
|
||||
// The value is evaluated first, then the place is borrowed for the
|
||||
// store (spec 15 §4), so `s[i] = s[i] + 1` reads before it writes.
|
||||
const target_type = l.placeType(place);
|
||||
const target_type = (try l.placeType(place));
|
||||
const v = try l.expr(value, target_type);
|
||||
if (v.ty == .never) return l.noOperandValue(value.span, if (target_type) |t| try l.diagnosticTyText(t) else "a stored value");
|
||||
const p = try l.placeBorrow(place, true, false, span);
|
||||
@@ -2957,10 +2957,10 @@ const Lowerer = struct {
|
||||
}
|
||||
|
||||
/// The type stored at a place, without lowering it.
|
||||
fn placeType(l: *Lowerer, place: ast.Expr) ?Ty {
|
||||
fn placeType(l: *Lowerer, place: ast.Expr) Allocator.Error!?Ty {
|
||||
return switch (place.kind) {
|
||||
.deref => |d| if (l.peekType(d.*)) |t| t.inner() else null,
|
||||
.field, .index => l.peekType(place),
|
||||
.deref => |d| if ((try l.peekType(d.*))) |t| t.inner() else null,
|
||||
.field, .index => (try l.peekType(place)),
|
||||
else => null,
|
||||
};
|
||||
}
|
||||
@@ -2973,7 +2973,7 @@ const Lowerer = struct {
|
||||
|
||||
/// `x.len`: a nominal field, `slice.len`, or the static array length.
|
||||
fn lenOf(l: *Lowerer, e: ast.Expr, base: ast.Expr) Error!Value {
|
||||
const bt = l.peekType(base) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
const bt = (try l.peekType(base)) orelse return l.fail("E7007", base.span, "the type of this expression cannot be determined", &.{});
|
||||
if (isNominalFieldBase(bt)) return l.fieldValue(e, base, "len");
|
||||
const arr: ?u64 = switch (bt) {
|
||||
.array => |a| a.len,
|
||||
@@ -4065,7 +4065,7 @@ const Lowerer = struct {
|
||||
const cv = blk: {
|
||||
const c = x.cond;
|
||||
if (c.kind == .binary and c.kind.binary.op == .lt and c.kind.binary.r.kind == .field and std.mem.eql(u8, c.kind.binary.r.kind.field.name, "len")) {
|
||||
const st = l.peekType(c.kind.binary.r.kind.field.e.*);
|
||||
const st = (try l.peekType(c.kind.binary.r.kind.field.e.*));
|
||||
if (st != null and (st.? == .slice or st.? == .slice_mut)) {
|
||||
const iv = try l.expr(c.kind.binary.l.*, .{ .int = "usize" });
|
||||
try l.checkOperandTy(c.kind.binary.l.span, iv.ty, .{ .int = "usize" });
|
||||
@@ -4576,13 +4576,13 @@ const ReferenceUseQuery = struct {
|
||||
|
||||
fn statement(l: *Lowerer, n: []const u8, s: ast.Stmt) ?Ty {
|
||||
return switch (s.kind) {
|
||||
.let => |x| expression(l, n, x.e, if (x.ty) |t| l.typeOfNoFail(t) else null),
|
||||
.@"var" => |x| if (x.init) |e| expression(l, n, e, l.typeOfNoFail(x.ty)) else null,
|
||||
.let => |x| expression(l, n, x.e, if (x.ty) |t| (l.queryAnnotation(t) catch null) else null),
|
||||
.@"var" => |x| if (x.init) |e| expression(l, n, e, (l.queryAnnotation(x.ty) catch null)) else null,
|
||||
.assign => |x| expression(l, n, x.e, if (x.place.kind == .name) (if (l.lookup(x.place.kind.name)) |b| b.ty else null) else null),
|
||||
.@"return" => |e| if (e) |x| expression(l, n, x, l.ret) else null,
|
||||
.expr => |e| expression(l, n, e, null),
|
||||
.@"while" => |x| expression(l, n, x.cond, .bool) orelse block(l, n, x.body),
|
||||
.@"for" => |x| expression(l, n, x.lo, l.peekType(x.hi)) orelse expression(l, n, x.hi, l.peekType(x.lo)) orelse block(l, n, x.body),
|
||||
.@"for" => |x| expression(l, n, x.lo, (l.peekType(x.hi) catch null)) orelse expression(l, n, x.hi, (l.peekType(x.lo) catch null)) orelse block(l, n, x.body),
|
||||
.loop, .shield => |b| block(l, n, b),
|
||||
.scope => |x| block(l, n, x.body),
|
||||
else => null,
|
||||
@@ -4605,15 +4605,15 @@ const ReferenceUseQuery = struct {
|
||||
.cast => |x| expression(l, n, x.e.*, null),
|
||||
.binary => |x| switch (x.op) {
|
||||
.@"and", .@"or" => expression(l, n, x.l.*, .bool) orelse expression(l, n, x.r.*, .bool),
|
||||
.eq, .ne, .lt, .le, .gt, .ge => expression(l, n, x.l.*, l.peekType(x.r.*)) orelse expression(l, n, x.r.*, l.peekType(x.l.*)),
|
||||
.shl, .shr => expression(l, n, x.l.*, want) orelse expression(l, n, x.r.*, l.peekType(x.l.*) orelse want),
|
||||
.eq, .ne, .lt, .le, .gt, .ge => expression(l, n, x.l.*, (l.peekType(x.r.*) catch null)) orelse expression(l, n, x.r.*, (l.peekType(x.l.*) catch null)),
|
||||
.shl, .shr => expression(l, n, x.l.*, want) orelse expression(l, n, x.r.*, (l.peekType(x.l.*) catch null) orelse want),
|
||||
else => blk: {
|
||||
const t = want orelse l.peekType(x.l.*) orelse l.peekType(x.r.*);
|
||||
const t = want orelse (l.peekType(x.l.*) catch null) orelse (l.peekType(x.r.*) catch null);
|
||||
break :blk expression(l, n, x.l.*, t) orelse expression(l, n, x.r.*, t);
|
||||
},
|
||||
},
|
||||
.call => |x| blk: {
|
||||
const sig = l.calleeSig(x.callee.*) orelse break :blk null;
|
||||
const sig = (l.calleeSig(x.callee.*) catch null) orelse break :blk null;
|
||||
for (x.args, 0..) |a, i| {
|
||||
const pt: ?Ty = if (i < sig.params.len) sig.params[i] else null;
|
||||
if (expression(l, n, a, pt)) |t| break :blk t;
|
||||
@@ -4658,7 +4658,7 @@ test "expected-use queries match independent shallow expression and statement de
|
||||
const parsed = try parse_mod.parse(a, source);
|
||||
try std.testing.expect(parsed == .ok);
|
||||
const e = parsed.ok.functions[0].body.stmts[0].kind.@"return".?;
|
||||
for ([_]?Ty{ null, .bool, .{ .int = "u64" } }) |want| try expectUseQueryEqual(ReferenceUseQuery.expression(&l, "n", e, want), l.useIn("n", e, want));
|
||||
for ([_]?Ty{ null, .bool, .{ .int = "u64" } }) |want| try expectUseQueryEqual(ReferenceUseQuery.expression(&l, "n", e, want), (try l.useIn("n", e, want)));
|
||||
};
|
||||
const statements = [_][]const u8{
|
||||
"let y: u8 = n;", "let y = n;", "let n: u8 = n;", "let (n, y) = f(n);", "var y: u32 = n;", "var y: u32 = zero;",
|
||||
@@ -4673,8 +4673,8 @@ test "expected-use queries match independent shallow expression and statement de
|
||||
if (parsed != .ok) std.debug.print("failed expected-use fixture: {s}\n", .{text});
|
||||
try std.testing.expect(parsed == .ok);
|
||||
const body = parsed.ok.functions[0].body;
|
||||
try expectUseQueryEqual(ReferenceUseQuery.block(&l, "n", body), l.usesInBlock("n", body));
|
||||
for (body.stmts) |stmt| try expectUseQueryEqual(ReferenceUseQuery.statement(&l, "n", stmt), l.usesInStmt("n", stmt));
|
||||
try expectUseQueryEqual(ReferenceUseQuery.block(&l, "n", body), (try l.usesInBlock("n", body)));
|
||||
for (body.stmts) |stmt| try expectUseQueryEqual(ReferenceUseQuery.statement(&l, "n", stmt), (try l.usesInStmt("n", stmt)));
|
||||
}
|
||||
try std.testing.expect(l.problem == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
|
||||
@@ -4700,7 +4700,7 @@ test "expected-use rest queries preserve scope order tails and top-level let reb
|
||||
const b = parsed.ok.functions[0].body;
|
||||
try l.rest.append(a, .{ .stmts = b.stmts, .tail = b.tail });
|
||||
}
|
||||
try expectUseQueryEqual(ReferenceUseQuery.infer(&l, "n"), l.inferUses("n"));
|
||||
try expectUseQueryEqual(ReferenceUseQuery.infer(&l, "n"), (try l.inferUses("n")));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4715,7 +4715,7 @@ test "expected-use queries do not evaluate deferred right-hand type hints after
|
||||
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 1 });
|
||||
var l: Lowerer = .{ .arena = failing.allocator(), .m = .{ .name = "uses", .types = &.{}, .functions = &.{} } };
|
||||
const e: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = op, .l = &left, .r = &right } } };
|
||||
try expectUseQueryEqual(.{ .int = "u16" }, l.useIn("n", e, .{ .int = "u16" }));
|
||||
try expectUseQueryEqual(.{ .int = "u16" }, (try l.useIn("n", e, .{ .int = "u16" })));
|
||||
// One worklist allocation is allowed. An eager peekType(left) would
|
||||
// construct the array type on a second request and induce host OOM.
|
||||
try std.testing.expect(!failing.has_induced_failure);
|
||||
@@ -4729,7 +4729,7 @@ test "expected-use queries do not evaluate deferred right-hand type hints after
|
||||
.hi = right,
|
||||
.body = .{ .span = span, .stmts = &.{}, .tail = null },
|
||||
} } };
|
||||
try expectUseQueryEqual(.{ .int = "u16" }, l.usesInStmt("n", loop));
|
||||
try expectUseQueryEqual(.{ .int = "u16" }, (try l.usesInStmt("n", loop)));
|
||||
try std.testing.expect(!failing.has_induced_failure);
|
||||
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
|
||||
}
|
||||
@@ -4770,12 +4770,12 @@ test "expected-use queries handle deep unary branches calls and statement blocks
|
||||
},
|
||||
}
|
||||
}
|
||||
try expectUseQueryEqual(.{ .int = "u16" }, l.useIn("n", unary, .{ .int = "u16" }));
|
||||
try expectUseQueryEqual(.bool, l.useIn("n", mixed, null));
|
||||
try expectUseQueryEqual(.{ .int = "u16" }, (try l.useIn("n", unary, .{ .int = "u16" })));
|
||||
try expectUseQueryEqual(.bool, (try l.useIn("n", mixed, null)));
|
||||
// Plain unary traversal does not need host metadata allocation.
|
||||
var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
|
||||
var no_alloc: Lowerer = .{ .arena = none.allocator(), .m = m };
|
||||
try expectUseQueryEqual(.bool, no_alloc.useIn("n", unary, .bool));
|
||||
try expectUseQueryEqual(.bool, (try no_alloc.useIn("n", unary, .bool)));
|
||||
try std.testing.expect(!none.has_induced_failure);
|
||||
var body: ast.Block = .{ .span = span, .stmts = &.{.{ .span = span, .kind = .{ .@"return" = name } }}, .tail = null };
|
||||
for (0..32_768) |_| {
|
||||
@@ -4788,13 +4788,13 @@ test "expected-use queries handle deep unary branches calls and statement blocks
|
||||
tail.* = .{ .span = span, .kind = .{ .not = &name } };
|
||||
body = .{ .span = span, .stmts = stmts, .tail = tail };
|
||||
}
|
||||
try expectUseQueryEqual(.{ .int = "u64" }, l.usesInBlock("n", body));
|
||||
try expectUseQueryEqual(.{ .int = "u64" }, (try l.usesInBlock("n", body)));
|
||||
try std.testing.expect(l.problem == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
|
||||
}
|
||||
|
||||
test "expected-use worklist OOM is unknown and releases all backing allocations" {
|
||||
test "expected-use worklist propagates OOM and releases all backing allocations" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const a = fixture.allocator();
|
||||
@@ -4815,7 +4815,7 @@ test "expected-use worklist OOM is unknown and releases all backing allocations"
|
||||
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
|
||||
var l: Lowerer = .{ .arena = arena.allocator(), .m = .{ .name = "uses", .types = &.{}, .functions = &.{} } };
|
||||
const result = l.useIn("n", e, null);
|
||||
if (failing.has_induced_failure) try std.testing.expect(result == null) else try expectUseQueryEqual(.bool, result);
|
||||
if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else try expectUseQueryEqual(.bool, try result);
|
||||
try std.testing.expect(l.problem == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
|
||||
@@ -4844,7 +4844,7 @@ const ReferenceExpressionQuery = struct {
|
||||
.array_list => |xs| if (xs.len != 0) (if (query(l, xs[0])) |t| (l.arrayOf(t, xs.len) catch null) else null) else null,
|
||||
.neg => unreachable,
|
||||
.not => .bool,
|
||||
.cast => |x| l.typeOfNoFail(x.ty),
|
||||
.cast => |x| (l.queryAnnotation(x.ty) catch null),
|
||||
.binary => |x| switch (x.op) {
|
||||
.eq, .ne, .lt, .le, .gt, .ge, .@"and", .@"or" => .bool,
|
||||
.shl, .shr => query(l, x.l.*),
|
||||
@@ -4853,7 +4853,7 @@ const ReferenceExpressionQuery = struct {
|
||||
.call => |x| switch (x.callee.kind) {
|
||||
.name => |n| if (l.functionSig(n, e.span)) |sig| sig.ret else null,
|
||||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||||
else => if (l.calleeSig(x.callee.*)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| path(l, p, x.args) else null,
|
||||
else => if ((l.calleeSig(x.callee.*) catch null)) |sig| sig.ret else if (pathOf(x.callee.*)) |p| path(l, p, x.args) else null,
|
||||
},
|
||||
.move => |n| if (l.lookup(n)) |b| b.ty else null,
|
||||
.variant => |v| l.enumType(v.@"enum", e.span),
|
||||
@@ -4865,7 +4865,7 @@ const ReferenceExpressionQuery = struct {
|
||||
if (base.isBorrow()) base = base.inner().?;
|
||||
const d = l.decl(base) orelse break :blk null;
|
||||
if (d.kind != .@"struct") break :blk null;
|
||||
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk l.typeOfNoFail(f.ty);
|
||||
for (d.kind.@"struct") |f| if (std.mem.eql(u8, f.name, x.name)) break :blk (l.queryAnnotation(f.ty) catch null);
|
||||
break :blk null;
|
||||
},
|
||||
.if_expr => |x| if (x.then.tail) |t| query(l, t.*) else null,
|
||||
@@ -4897,7 +4897,7 @@ const ReferenceExpressionQuery = struct {
|
||||
if (eq(u8, p, "arc.clone") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .arc) t else if (t.inner()) |in| (if (in == .arc) in else null) else null) else null;
|
||||
if (eq(u8, p, "channel.dup") and args.len == 1) return if (query(l, args[0])) |t| (if (t == .sender) t else if (t.inner()) |in| (if (in == .sender) in else null) else null) else null;
|
||||
if (eq(u8, p, "task.spawn") and args.len >= 2) {
|
||||
const sig = l.calleeSig(args[1]) orelse return null;
|
||||
const sig = (l.calleeSig(args[1]) catch null) orelse return null;
|
||||
return l.wrap(.task, sig.ret) catch null;
|
||||
}
|
||||
return null;
|
||||
@@ -4952,7 +4952,7 @@ test "expression type queries match the independent shallow derivation" {
|
||||
try std.testing.expect(r == .ok);
|
||||
const e = r.ok.functions[0].body.stmts[0].kind.@"return".?;
|
||||
const expected = ReferenceExpressionQuery.query(&l, e);
|
||||
const actual = l.peekType(e);
|
||||
const actual = (try l.peekType(e));
|
||||
if (expected) |ty| try std.testing.expect(actual != null and ty.eql(actual.?)) else try std.testing.expect(actual == null);
|
||||
try std.testing.expect(l.problem == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
|
||||
@@ -4993,14 +4993,14 @@ test "expression queries suspend deep structural, branch and builtin requests" {
|
||||
},
|
||||
}
|
||||
}
|
||||
const result = l.peekType(e);
|
||||
const result = (try l.peekType(e));
|
||||
try std.testing.expect(result != null and result.?.eql(.{ .int = "u8" }));
|
||||
try std.testing.expect(l.problem == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
|
||||
}
|
||||
}
|
||||
|
||||
test "best-effort expression query OOM releases all backing blocks without diagnostics" {
|
||||
test "expression query propagates OOM and releases all backing blocks without diagnostics" {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const a = fixture.allocator();
|
||||
@@ -5019,8 +5019,8 @@ test "best-effort expression query OOM releases all backing blocks without diagn
|
||||
var arena: std.heap.ArenaAllocator = .init(failing.allocator());
|
||||
var l: Lowerer = .{ .arena = arena.allocator(), .m = m };
|
||||
const result = l.peekType(e);
|
||||
if (failing.has_induced_failure) try std.testing.expect(result == null) else {
|
||||
var t = result.?;
|
||||
if (failing.has_induced_failure) try std.testing.expectError(error.OutOfMemory, result) else {
|
||||
var t = (try result).?;
|
||||
for (0..128) |_| {
|
||||
try std.testing.expect(t == .array and t.array.len == 1);
|
||||
t = t.array.elem;
|
||||
@@ -5036,7 +5036,7 @@ test "best-effort expression query OOM releases all backing blocks without diagn
|
||||
var none: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
|
||||
var l: Lowerer = .{ .arena = none.allocator(), .m = m };
|
||||
const leaf: ast.Expr = .{ .span = span, .kind = .{ .boolean = false } };
|
||||
try std.testing.expect(l.peekType(leaf).? == .bool);
|
||||
try std.testing.expect((try l.peekType(leaf)).? == .bool);
|
||||
try std.testing.expect(!none.has_induced_failure);
|
||||
}
|
||||
|
||||
@@ -5081,7 +5081,7 @@ const ReferenceOperands = struct {
|
||||
return l.def("not", .bool, try l.fmt("xor.bool %{s}, %{s}", .{ v.name, t.name }), e.span);
|
||||
},
|
||||
.neg => |x| {
|
||||
const ty = want orelse l.peekType(x.*) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
|
||||
const ty = want orelse (try l.peekType(x.*)) orelse return l.fail("E7007", e.span, "the type of this negation cannot be determined", &.{});
|
||||
if (ty != .int) return l.fail("E7005", e.span, "negation of a non-integer", &.{});
|
||||
if (x.kind == .int) {
|
||||
const v = parse_mod.parseIntText(x.kind.int.text) orelse return l.fail("E7001", e.span, "malformed integer literal", &.{});
|
||||
@@ -5108,7 +5108,7 @@ const ReferenceOperands = struct {
|
||||
.cast => |x| {
|
||||
const to = try l.typeOf(x.ty);
|
||||
if (to != .int) return l.fail("E7005", x.ty.span, "casts convert between integer types", &.{});
|
||||
const from = l.peekType(x.e.*) orelse to;
|
||||
const from = (try l.peekType(x.e.*)) orelse to;
|
||||
const v = try expr(l, x.e.*, from);
|
||||
if (v.ty != .int) return l.fail("E7005", x.e.span, "casts convert between integer types", &.{.{ .name = "found", .value = try l.diagnosticTyText(v.ty) }});
|
||||
if (x.mode == .widen) {
|
||||
@@ -5156,7 +5156,7 @@ const ReferenceOperands = struct {
|
||||
else => false,
|
||||
};
|
||||
const shift = op == .shl or op == .shr;
|
||||
const operand: ?Ty = if (cmp) (l.peekType(a) orelse l.peekType(b)) else if (shift) (want orelse l.peekType(a)) else (want orelse l.peekType(a) orelse l.peekType(b));
|
||||
const operand: ?Ty = if (cmp) ((try l.peekType(a)) orelse (try l.peekType(b))) else if (shift) (want orelse (try l.peekType(a))) else (want orelse (try l.peekType(a)) orelse (try l.peekType(b)));
|
||||
const ty = operand orelse return l.fail("E7007", e.span, "the type of this operation cannot be determined; add a suffix or annotation", &.{});
|
||||
const lv = try expr(l, a, ty);
|
||||
try l.checkOperandTy(a.span, lv.ty, ty);
|
||||
@@ -6424,7 +6424,7 @@ fn referenceTypeHint(l: *Lowerer, t: ast.Type) ?Ty {
|
||||
|
||||
fn expectTypeHintMatches(l: *Lowerer, t: ast.Type) !void {
|
||||
const before = referenceTypeHint(l, t);
|
||||
const after = l.typeOfNoFail(t);
|
||||
const after = (try l.queryAnnotation(t));
|
||||
try std.testing.expectEqual(before == null, after == null);
|
||||
if (before) |b| try std.testing.expect(b.eql(after.?));
|
||||
try std.testing.expect(l.problem == null and l.unimpl == null);
|
||||
@@ -6477,7 +6477,7 @@ test "deep best-effort source type lookup owns output and rejects without alloca
|
||||
for (nodes[1..], 1..) |*node, i| node.* = .{ .span = span, .kind = .{ .array = .{ .elem = &nodes[i - 1], .len = i } } };
|
||||
var allocations: std.testing.FailingAllocator = .init(std.testing.allocator, .{});
|
||||
var l: Lowerer = .{ .arena = allocations.allocator(), .m = m };
|
||||
var current = l.typeOfNoFail(nodes[count]).?;
|
||||
var current = (try l.queryAnnotation(nodes[count])).?;
|
||||
var remaining: usize = count;
|
||||
while (remaining != 0) : (remaining -= 1) {
|
||||
try std.testing.expect(current == .array);
|
||||
@@ -6494,18 +6494,18 @@ test "deep best-effort source type lookup owns output and rejects without alloca
|
||||
var invalid: Lowerer = .{ .arena = no_alloc.allocator(), .m = m };
|
||||
for ([_][]const u8{ "missing", "void", "never" }) |name| {
|
||||
nodes[0].kind = .{ .name = name };
|
||||
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
|
||||
try std.testing.expect((try invalid.queryAnnotation(nodes[count])) == null);
|
||||
}
|
||||
nodes[0].kind = .{ .name = "u8" };
|
||||
nodes[1].kind.array.len = 0;
|
||||
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
|
||||
try std.testing.expect((try invalid.queryAnnotation(nodes[count])) == null);
|
||||
nodes[1].kind.array.len = (@as(u64, 1) << 32) + 1;
|
||||
try std.testing.expect(invalid.typeOfNoFail(nodes[count]) == null);
|
||||
try std.testing.expect((try invalid.queryAnnotation(nodes[count])) == null);
|
||||
try std.testing.expect(!no_alloc.has_induced_failure);
|
||||
try std.testing.expect(invalid.problem == null and invalid.unimpl == null);
|
||||
}
|
||||
|
||||
test "best-effort source type lookup preserves null on every allocation failure" {
|
||||
test "optional source type lookup propagates every allocation failure" {
|
||||
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer scratch.deinit();
|
||||
const a = scratch.allocator();
|
||||
@@ -6522,10 +6522,11 @@ test "best-effort source type lookup preserves null on every allocation failure"
|
||||
var before: Lowerer = .{ .arena = before_nodes.allocator(), .m = m };
|
||||
var after: Lowerer = .{ .arena = after_nodes.allocator(), .m = m };
|
||||
const original = referenceTypeHint(&before, nodes[64]);
|
||||
const current = after.typeOfNoFail(nodes[64]);
|
||||
try std.testing.expectEqual(original == null, current == null);
|
||||
try std.testing.expectEqual(fail_index < 64, current == null);
|
||||
if (original) |ty| try std.testing.expect(ty.eql(current.?));
|
||||
const current = after.queryAnnotation(nodes[64]);
|
||||
if (fail_index < 64) {
|
||||
try std.testing.expect(original == null);
|
||||
try std.testing.expectError(error.OutOfMemory, current);
|
||||
} else try std.testing.expect(original.?.eql((try current).?));
|
||||
try std.testing.expectEqual(before_nodes.count, after_nodes.count);
|
||||
for (before_nodes.nodes[0..before_nodes.count], after_nodes.nodes[0..after_nodes.count]) |old, new| {
|
||||
try std.testing.expectEqual(old.length, new.length);
|
||||
@@ -6867,3 +6868,197 @@ test "source SSA zero OOM propagates with complete instruction prefixes and aren
|
||||
if (!failing.has_induced_failure) break;
|
||||
}
|
||||
}
|
||||
|
||||
// Fails exactly one allocation, then recovers. A persistent failure could
|
||||
// mask a false E7007 because allocating the diagnostic would fail as well.
|
||||
const QueryAllocationFailure = struct {
|
||||
backing: Allocator,
|
||||
attempts: usize = 0,
|
||||
fail_at: usize = 0,
|
||||
failed: bool = false,
|
||||
|
||||
fn allocator(self: *@This()) Allocator {
|
||||
return .{ .ptr = self, .vtable = &.{ .alloc = alloc, .resize = resize, .remap = remap, .free = free } };
|
||||
}
|
||||
fn alloc(raw: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 {
|
||||
const self: *@This() = @ptrCast(@alignCast(raw));
|
||||
self.attempts += 1;
|
||||
if (!self.failed and self.attempts == self.fail_at + 1) {
|
||||
self.failed = true;
|
||||
return null;
|
||||
}
|
||||
return self.backing.rawAlloc(len, alignment, ra);
|
||||
}
|
||||
fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool {
|
||||
return false;
|
||||
}
|
||||
fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 {
|
||||
return null;
|
||||
}
|
||||
fn free(raw: *anyopaque, memory: []u8, alignment: std.mem.Alignment, ra: usize) void {
|
||||
const self: *@This() = @ptrCast(@alignCast(raw));
|
||||
self.backing.rawFree(memory, alignment, ra);
|
||||
}
|
||||
};
|
||||
|
||||
test "recovering host OOM escapes query callers without language diagnostics or AIR" {
|
||||
for ([_]enum { negation, binary, cast, let_peek, let_use, range, field, match, length, assignment }{
|
||||
.negation, .binary, .cast, .let_peek, .let_use, .range, .field, .match, .length, .assignment,
|
||||
}) |mode| {
|
||||
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer scratch.deinit();
|
||||
const a = scratch.allocator();
|
||||
const span = unaryTestSpan(19);
|
||||
const literal: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1i64" } } };
|
||||
const unsuffixed: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1" } } };
|
||||
const name: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } };
|
||||
const sum: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &literal, .r = &literal } } };
|
||||
const hint: ast.Expr = .{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &name, .r = &literal } } };
|
||||
const field: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &sum, .name = "x" } } };
|
||||
const empty: ast.Block = .{ .span = span, .stmts = &.{}, .tail = null };
|
||||
var l: Lowerer = .{ .arena = a, .m = .{ .name = "oom", .types = &.{}, .functions = &.{} }, .ret = .{ .int = "i64" } };
|
||||
l.cur = try l.newBlock("entry", span);
|
||||
try l.rest.append(a, .{ .stmts = &.{}, .tail = &hint });
|
||||
var failure: QueryAllocationFailure = .{ .backing = a };
|
||||
l.arena = failure.allocator();
|
||||
const result: Error!void = switch (mode) {
|
||||
.negation => blk: {
|
||||
_ = l.expr(.{ .span = span, .kind = .{ .neg = &sum } }, null) catch |err| break :blk err;
|
||||
},
|
||||
.binary => blk: {
|
||||
_ = l.expr(.{ .span = span, .kind = .{ .binary = .{ .op = .add, .l = &sum, .r = &literal } } }, null) catch |err| break :blk err;
|
||||
},
|
||||
.cast => blk: {
|
||||
_ = l.expr(.{ .span = span, .kind = .{ .cast = .{ .mode = .checked, .e = &sum, .ty = .{ .span = span, .kind = .{ .name = "i64" } } } } }, null) catch |err| break :blk err;
|
||||
},
|
||||
.let_peek, .let_use => l.stmt(.{ .span = span, .kind = .{ .let = .{ .names = &.{"n"}, .ty = null, .e = if (mode == .let_use) unsuffixed else sum } } }),
|
||||
.range => l.forLoop(span, "i", sum, unsuffixed, empty),
|
||||
.field => blk: {
|
||||
_ = l.fieldValue(field, sum, "x") catch |err| break :blk err;
|
||||
},
|
||||
.match => blk: {
|
||||
_ = l.matchExpr(.{ .scrutinee = sum, .arms = &.{}, .span = span, .kind = .integer }, null) catch |err| break :blk err;
|
||||
},
|
||||
.length => blk: {
|
||||
_ = l.lenOf(field, sum) catch |err| break :blk err;
|
||||
},
|
||||
.assignment => l.assignPlace(span, field, unsuffixed),
|
||||
};
|
||||
try std.testing.expect(failure.failed);
|
||||
try std.testing.expectError(error.OutOfMemory, result);
|
||||
try std.testing.expect(l.problem == null and l.unimpl == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items[0].insts.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 1), failure.attempts);
|
||||
}
|
||||
}
|
||||
|
||||
test "query callback OOM stops annotations signatures and builtin output without fallback" {
|
||||
for ([_]enum { annotation, field, callee, borrow_signature, call, use_signature, use_annotation, spawn, atomic, graph, freeze, arc }{
|
||||
.annotation, .field, .callee, .borrow_signature, .call, .use_signature, .use_annotation, .spawn, .atomic, .graph, .freeze, .arc,
|
||||
}) |mode| {
|
||||
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer scratch.deinit();
|
||||
const a = scratch.allocator();
|
||||
const span = unaryTestSpan(23);
|
||||
const byte: ast.Type = .{ .span = span, .kind = .{ .name = "u8" } };
|
||||
const annotation: ast.Type = .{ .span = span, .kind = .{ .array = .{ .elem = &byte, .len = 7 } } };
|
||||
const root: ast.Expr = .{ .span = span, .kind = .{ .name = "ns" } };
|
||||
const qualified: ast.Expr = .{ .span = span, .kind = .{ .field = .{ .e = &root, .name = "worker" } } };
|
||||
const worker: ast.Expr = .{ .span = span, .kind = .{ .name = "worker" } };
|
||||
const name: ast.Expr = .{ .span = span, .kind = .{ .name = "n" } };
|
||||
const scalar: ast.Expr = .{ .span = span, .kind = .{ .int = .{ .text = "1u8" } } };
|
||||
const call: ast.Expr = .{ .span = span, .kind = .{ .call = .{ .callee = &qualified, .type_arg = null, .args = &.{name} } } };
|
||||
var l: Lowerer = .{ .arena = a, .m = .{ .name = "oom", .types = &.{.{ .name = "S", .span = span, .kind = .{ .@"struct" = &.{.{ .name = "items", .span = span, .ty = annotation }} } }}, .functions = &.{} } };
|
||||
const sig: FnSig = .{ .params = &.{.{ .int = "u8" }}, .ret = .{ .int = "u8" }, .air_name = "worker", .display_name = "worker" };
|
||||
try l.sigs.put(a, "worker", sig);
|
||||
try l.sigs.put(a, "ns.worker", sig);
|
||||
const owned = try l.wrap(.own, .{ .int = "u8" });
|
||||
try l.bindings.appendSlice(a, &.{
|
||||
.{ .name = "graph", .value = "g", .mutable = false, .ty = try l.wrap(.mut, try l.wrap(.island, owned)) },
|
||||
.{ .name = "island", .value = "i", .mutable = false, .ty = try l.wrap(.island, owned) },
|
||||
.{ .name = "frozen", .value = "f", .mutable = false, .ty = try l.wrap(.frozen, owned) },
|
||||
});
|
||||
const output_failure = mode == .atomic or mode == .graph or mode == .freeze or mode == .arc;
|
||||
var failure: QueryAllocationFailure = .{ .backing = a, .fail_at = if (output_failure) 1 else 0 };
|
||||
l.arena = failure.allocator();
|
||||
const result: Allocator.Error!void = switch (mode) {
|
||||
.annotation => blk: {
|
||||
_ = l.queryAnnotation(annotation) catch |err| break :blk err;
|
||||
},
|
||||
.field => blk: {
|
||||
_ = l.queryField(.{ .named = 0 }, "items") catch |err| break :blk err;
|
||||
},
|
||||
.callee, .borrow_signature => blk: {
|
||||
_ = (if (mode == .callee) l.calleeSig(qualified) else l.borrowReturnSig(qualified)) catch |err| break :blk err;
|
||||
},
|
||||
.call => blk: {
|
||||
_ = l.peekType(call) catch |err| break :blk err;
|
||||
},
|
||||
.use_signature => blk: {
|
||||
_ = l.useIn("n", call, null) catch |err| break :blk err;
|
||||
},
|
||||
.use_annotation => blk: {
|
||||
_ = l.usesInStmt("n", .{ .span = span, .kind = .{ .@"var" = .{ .name = "v", .ty = annotation, .init = name } } }) catch |err| break :blk err;
|
||||
},
|
||||
.spawn => blk: {
|
||||
_ = l.queryType(.{ .path = .{ .name = "task.spawn", .args = &.{ scalar, worker } } }) catch |err| break :blk err;
|
||||
},
|
||||
.atomic, .graph, .freeze, .arc => blk: {
|
||||
const operation = switch (mode) {
|
||||
.atomic => "atomic.new",
|
||||
.graph => "island.root",
|
||||
.freeze => "island.freeze",
|
||||
.arc => "arc.from_frozen",
|
||||
else => unreachable,
|
||||
};
|
||||
const argument: ast.Expr = if (mode == .atomic) scalar else .{ .span = span, .kind = .{ .name = switch (mode) {
|
||||
.graph => "graph",
|
||||
.freeze => "island",
|
||||
.arc => "frozen",
|
||||
else => unreachable,
|
||||
} } };
|
||||
_ = l.queryType(.{ .path = .{ .name = operation, .args = &.{argument} } }) catch |err| break :blk err;
|
||||
},
|
||||
};
|
||||
try std.testing.expect(failure.failed);
|
||||
try std.testing.expectError(error.OutOfMemory, result);
|
||||
try std.testing.expectEqual(failure.fail_at + 1, failure.attempts);
|
||||
try std.testing.expect(l.problem == null and l.unimpl == null);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.out.items.len);
|
||||
try std.testing.expectEqual(@as(usize, 0), l.blocks.items.len);
|
||||
}
|
||||
}
|
||||
|
||||
test "public source lowering propagates each recovering allocation failure" {
|
||||
const sources = [_][]const u8{
|
||||
"module oom\nfn main() -> i64 effects [] { let n = 1; return - (n + 2i64); }\n",
|
||||
"module oom\nstruct S { items: [u8; 7] }\nfn main() -> usize effects [] { let s: S = S { items: [1u8; 7] }; return s.items.len; }\n",
|
||||
"module oom\nfn worker(x: i64) -> i64 effects [] { return - x; }\nfn main() -> i64 effects [] { let n = 1; return worker(n + 1i64); }\n",
|
||||
};
|
||||
for (sources) |source| {
|
||||
var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer fixture.deinit();
|
||||
const parsed = try parse_mod.parse(fixture.allocator(), source);
|
||||
try std.testing.expect(parsed == .ok);
|
||||
var fail_at: usize = 0;
|
||||
while (true) : (fail_at += 1) {
|
||||
try std.testing.expect(fail_at < 1024);
|
||||
var output: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer output.deinit();
|
||||
var failure: QueryAllocationFailure = .{ .backing = output.allocator(), .fail_at = fail_at };
|
||||
const result = lower(failure.allocator(), parsed.ok);
|
||||
if (failure.failed) {
|
||||
// An error union carries no source Problem or public partial
|
||||
// Output. The caller owns and destroys the output arena.
|
||||
try std.testing.expectError(error.OutOfMemory, result);
|
||||
try std.testing.expectEqual(fail_at + 1, failure.attempts);
|
||||
} else {
|
||||
const accepted = try result;
|
||||
try std.testing.expect(accepted == .ok);
|
||||
try std.testing.expect(accepted.ok.air.len != 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user