Skip to content

var PATTERN binds mutable names; let PATTERN: TYPE = EXPR (§9.7, §30.4) - #1370

Merged
ehartford merged 2 commits into
mainfrom
fix-1354-var-destructure-mut
Sep 23, 2026
Merged

ehartford merged 2 commits into
mainfrom
fix-1354-var-destructure-mut

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Fixes #1354.

Also: let PATTERN: TYPE = EXPR (§30.4 LET_STMT := 'let' PATTERN [ ':' TYPE ] '=' EXPR) now parses and type-checks. It used to be a parse error. The annotation demands the whole subject's type (D27) and drives its inference (let (a, b): (i64, i64) = (1, 2)). A mismatch is a Sema type error.

Root cause (exact line)

Parser.parse_let_binding (src/Parser.w) set is_mut for var, then built every pattern let as NK_LET_ELSE(pattern, value, else_body). That covers tuple/struct/slice patterns through parse_let_pattern_rest and the .V(..) / V(..) let-else forms, and none of them had a slot for mutability. SemaCheck.check_pattern then bound every name with scope_put(sym, ty, 0). The missing slot is also why : TYPE was unparseable.

Change

  • New NK_LET_PATTERN head at NK_LET_ELSE.d0: pattern, bit0 = var, type annotation. Read through AstPool.let_pattern / let_pattern_is_mut / let_pattern_type_ann. Every reader of d0 was updated: Resolve, render, check_let_else, lower_let_else.
  • Sema: pattern_bind_mut is set around the let's check_pattern, and each binding site uses it. MirLower: pattern-let locals carry the flag. An annotated subject lowers against the annotation.
  • check_binding_annotation is one rule, shared by let x: T and let PATTERN: T. It also rejects an aggregate whose element representation differs from the annotation (let t: (i64, i64) = pair() with pair -> (i32, i32)). Named lets used to fail that case at MIR validation. Constructors lowered against the annotation ((1, x), Some(x)) are unaffected.
  • Boy-scout: expr_may_suspend / expr_creates_ephemeral_task walked a let-else's pattern (d0) as though it were its value. They walk d1 now.

Matrix (stage1 of this branch; run --debug-alloc)

case before after
var (x, y) = f(); =, += cannot assign to immutable 14 6, leak 0
nested var ((a, b), c); =, *=, -= error ok
var P { x, y } = p / var { x, y, .. } error ok; p untouched
wildcard var (x, _, z) (the _ part is a str) error ok, leak 0
non-Copy var (v, s): v.push, s = s ++ .., v = Vec.new() error ok, leak 0
var Bag { items, name, n }: push, reassign, += error ok, leak 0
refutable var Some(n) = .. else, var .Some(m), var Ok(v) + push error ok, leak 0
D12 mut fn on scalar/str bindings (n.bump(), s.behead()), nested error ok
var (x, y) = t (named Copy subject) error fresh locals; t unchanged
var [a, ..rest] = arr else: return; a +=, rest += error ok
let of each shape + assign / compound / D12 receiver immutable error immutable error (unchanged)
for (a, b) in ps: a = .. immutable error unchanged: FOR_STMT has no var (§30.4)
let (a, b): (i64, i64) = (1, 2); var + annotation; let Some(n): Option[i64] = .. else; var P {..}: P parse error ok
let (a, b): (i64, i64) = names() (str pair) parse error type mismatch in binding
let (a, b): (i64, i64) = pair_i32() / Option[i64] from Option[i32] parse error type mismatch in binding: ... an aggregate's elements do not convert
let t: (i64, i64) = pair_i32() (named) invalid MIR before codegen same Sema error
let (a, b): (i32, i32, i32) = (1, 2, 3) parse error tuple pattern arity mismatch
var Pair { n, .. } = p with p: &Pair, then n += 1 error error: n is a &i32 view (D22); var changes rebinding, not ownership
same with v.push(9) through the view requires a mutable receiver unchanged

let (v, n) = ..; v.push(n) is accepted before and after. It matches a named let v: Vec[i32], so it is not part of this change.

Evidence (iterate tier only; the battery has not run)

  • WITH=$PWD/src/main src/main build :dev: green.
  • check sweep over test/behavior (1129) + test/compile_errors (850), baseline stage1 (origin/main) vs this branch: 1978 same, 1 diff (a random /tmp/with_cimport_* path in a message), 11 new fixtures.
  • New fixture da_var_destructure_owned_moves_once: tools/debug_drop.w check PASS, leak count=0.

Spec note for Eric

§30.4 has VAR_STMT := 'var' IDENT [ ':' TYPE ] '=' EXPR, but §9.7 says "All pattern forms are available in let/var bindings". This PR follows §9.7 and #1354, and the spec text is unchanged. The grammar line needs your wording, e.g. 'var' PATTERN.

Filed while building the matrix (not in this PR)

NK_TUPLE_DESTRUCTURE is no longer produced by the parser. Its handlers are dead code, left in place.

@ehartford

Copy link
Copy Markdown
Contributor Author

Final stage1 (a7e2004): the full debug-alloc lane (tools/debug_drop.w check over test/debug_alloc, 85 fixtures) is ok. The matrix above was rerun on this stage1 with identical results. The check sweep ran on the stage1 before the last edit. That edit only narrowed aggregate_repr_differs (a mixed numeric/non-numeric element pair now falls back to types_compatible).

@ehartford

Copy link
Copy Markdown
Contributor Author

Batch battery (seed-driven) on main dd786a4 + #1355 → #1357 → #1370 → #1371 as one linear chain (head 45f8aa4): build ok, :fixpoint ok, :test ok (no reds), :test-green ok, :last-green ok. The four PRs are now stacked exactly as tested (each branch = its commit on top of the previous PR); merge in order #1355, #1357, #1370, #1371, retargeting each to main as its parent merges.

@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven) on main 00408eb + #1400 → #1370 → #1371 → #1397 as one chain (head 37a2441): build ok, :fixpoint ok, :test ok (no reds), :test-green ok, :last-green ok. Each branch holds exactly its tested commit on top of the previous PR's; all target main. Merge in order #1400, #1370, #1371, #1397.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 02:54
@ehartford
ehartford marked this pull request as draft September 23, 2026 02:55
Eric Hartford added 2 commits September 22, 2026 22:55
…orms (#1346)

parse_trait_decl and parse_impl_block treated ':' as optional punctuation,
skipped newlines, and collected members until one started at column 0, so
an inline first member followed by indented members was one body, and a
bodyless `impl Foo for X` (§2.3) swallowed the indented `fn` lines after it.

Both now name the body form once (parse_decl_body_introducer) and read
member boundaries from it (decl_member_continues):
- Form 1 (':' then content): one member; a second is reported
  ("an inline trait body is a single member ...", fix-it: end the line
  after the header and indent the first member). Newlines inside the
  member's parentheses stay part of it.
- Form 2 (':' ends the line): members indented deeper than the header
  line; nothing indented below is "expected an indented trait body
  after ':'", as for `fn f:`.
- Form 3 (braces): members separated by newlines or semicolons
  (semicolons were rejected before).
- impl/extend with no introducer is bodyless and ends at its newline;
  indented lines after it are reported with the fix-it `impl Foo for X:`.
  Any other token after an impl header is "expected ':' or '{' after
  the impl header" (it used to fall through silently).

Sweep: every .w under src lib rt tools test examples build build.w
parsed with the installed compiler and this stage1; no file changes
verdict except the new fixtures and files that use syntax newer than
the installed compiler.

(cherry picked from commit 7aff486)
(cherry picked from commit 225ea6ed80a74de2a10e312b4fc7e91d61cde028)
…checks (§9.7, §30.4) (#1354)

Root cause: Parser.parse_let_binding computed is_mut for `var`, then built
every pattern let (tuple/struct/slice via parse_let_pattern_rest, and the
`.V(..)`/`V(..)` let-else forms) as NK_LET_ELSE(pattern, value, else) with
no slot for it. SemaCheck.check_pattern then bound every name with
scope_put(sym, ty, 0), so `var (x, y) = f()` then `x = ...` failed with
"cannot assign to immutable variable". The same missing slot made
`let (a, b): (i64, i64) = ...` a parse error, though LET_STMT allows it.

- Ast: a pattern let's NK_LET_ELSE.d0 is now an NK_LET_PATTERN head
  (pattern, bit0 = var, type annotation), read through let_pattern /
  let_pattern_is_mut / let_pattern_type_ann.
- Parser: every pattern-let form builds the head and accepts `: TYPE`
  before `=`.
- Sema: check_let_else sets pattern_bind_mut around check_pattern, and each
  binding site in check_pattern uses it. The annotation demands the
  subject's type and drives its inference through check_binding_annotation,
  which is now shared with the named `let x: T` check.
- check_binding_annotation also rejects an aggregate whose element
  representation differs from the annotation (`let t: (i64, i64) = pair()`
  with pair -> (i32, i32)). Both spellings used to reach codegen as invalid
  MIR. Constructors lowered against the annotation are unaffected.
- MirLower: pattern-let binding locals carry var's mutability; an
  annotated subject lowers against the annotation.
- Resolve walks the annotation. render prints var, the annotation, and
  `else` only when there is one.
- expr_may_suspend / expr_creates_ephemeral_task walked a let-else's
  pattern (d0) as though it were its value. They walk d1 now.

`for` patterns stay immutable: FOR_STMT has no var or mut (§30.4).

Tests: behav_var_destructure_mutable, behav_let_pattern_annotation,
da_var_destructure_owned_moves_once (leak count 0), and compile-error
fixtures for let tuple/nested/struct/let-else immutability, D12 scalar
receivers, annotation mismatch/width/arity, and the named-let width case.

(cherry picked from commit a7e2004)
(cherry picked from commit 7fec2a143214f00f0f121fea8767f3d4750126b3)
@ehartford
ehartford force-pushed the fix-1354-var-destructure-mut branch from 075b0dd to 16e5839 Compare September 23, 2026 02:56
@ehartford

Copy link
Copy Markdown
Contributor Author

Rebased onto main 43796ac: conflict with #1385 in MirLower.lower_let_else, resolved by keeping #1385's order (fail path lowered first, drops the whole subject) and binding the success path through this PR's lower_let_pattern_bindings (var mutability) plus the annotation expected-type. Re-battery queued with :drop-audit/:move-audit; draft until green.

@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, with :drop-audit/:move-audit) on main 43796ac + #1400 → #1370 → #1371 → #1397 (head c846339, including the #1385 lower_let_else merge resolution): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. Merge in order #1370, #1371, #1397 (#1400 already merged).

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 03:58
@ehartford
ehartford merged commit 8da26ad into main Sep 23, 2026
@ehartford
ehartford deleted the fix-1354-var-destructure-mut branch September 24, 2026 16:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Parser/Sema: var (a, b) = ... binds immutable names — the var is dropped for destructuring patterns (§9.7)

1 participant