Skip to content

check: implement HYB-E2001 (reject non-call defer operand); hoist ? in deferred call args - #288

Merged
limitlessprojects merged 2 commits into
limitlessprojects:mainfrom
Leimiu-G:fix/defer-e2001-non-call-operand
Oct 18, 2026
Merged

limitlessprojects merged 2 commits into
limitlessprojects:mainfrom
Leimiu-G:fix/defer-e2001-non-call-operand

Conversation

@Leimiu-G

@Leimiu-G Leimiu-G commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What

SPEC-LANGUAGE.md §7 P1: defer f.close() is "the only legal defer operand
shape in MVP"
, and "defer of a non-call expression is a compile error
(HYB-E2001)"
. The registry defines HYB-E2001, but no pass enforced it —
the parser accepted any expression after defer and the checker never looked.

Why it matters (check→emit gap)

defer cleanup()? has a Try operand, not a Call. Today:

$ hyb check repro.hy      # 0 diagnostics — clean
$ hyb build repro.hy      # error: `?` outside a binding position ...

The front-end calls the program clean; the emitter refuses it late with a
message that names neither defer nor the real rule. Reported as R4 in the
try-legality report (#155).

A second instance of the same gap: defer f(g?) — the operand is a call, but
a ? in its arguments hoisted nowhere, so the emitter refused that too, even
though P1 evaluates a deferred call's arguments at defer time.

Fix

  • hy-check — implement HYB-E2001 in one shared helper
    (check_defer_operand). A defer whose operand (parens unwrapped) is not a
    Call is rejected at check time, at the operand's span, with a note showing
    the bind-then-defer rewrite. defer f.close() and defer (f.close()) pass.
  • hy-check / closures — the helper is wired into both walks. Closure
    bodies sit outside Tier-0's flat walk (walk.rs skips FnLit bodies; the A5
    perimeter), so the per-function Pass B loop alone leaves the same gap one
    scope in: defer cleanup()? inside a closure still passed the checker and
    failed late in the emitter. The closure pass (closures.rs) now enforces it
    too, so the message is identical wherever the statement appears.
  • hy-emit — hoist ? inside a deferred call's arguments (gated on a
    Call operand, which the checker now guarantees), so defer f(g?) lowers to
    Go's "arguments evaluated at defer time".
  • Docs/registry — two places contradicted the rule and only became
    user-visible once E2001 fires: the HYB-E2001 fix-it suggested
    defer f.close()? (the very shape the rule rejects), and the Defer AST doc
    comment showed the same illegal form. Both now read defer f.close().

Tests

  • hy-check: defer cleanup()? and defer x + 1 → HYB-E2001;
    defer (zap()) and defer zap() → accept; plus a closure-body case
    (defer cleanup()? inside fn() { … } → HYB-E2001; defer zap() → accept).
  • hy-emit: defer sink(probe()?) → the argument ? hoists before the
    defer; the existing example02_try_desugar_and_defer still passes.

Verification

cargo test --workspace (rustc 1.99.0, x86_64-pc-windows-gnu): hy-check
106/106, hy-emit 111/111, every other suite green. The only failures are the
hyb generate tests, and only because this sandbox has no Go toolchain
(gofmt: program not found) — unrelated to this change.

Because the rule must hold wherever a defer can appear, I also swept every
syntactic position and confirmed defer cleanup()? reports HYB-E2001 in all
of them: function body, nested if, else, for body, range-for, match
arm, select arm, select arm block, managed block, closure body, closure
inside a closure, closure as a call argument, closure inside an if, and
managed inside a closure.

Refs #155.

@limitlessprojects

Copy link
Copy Markdown
Owner

Wave-2 triage: queued — port assessment. The E2001 half is same-fix with landed #191, but the '?-hoist in deferred call args' half may be new — will assess that part on a fresh base and land only what main lacks.

@limitlessprojects

Copy link
Copy Markdown
Owner

Wave-2 follow-up (validation pass, local main c53978b): NEEDS-INTEGRATION — E2001 half subsumed by landed #191; two of the remaining halves are real and unique.

Subsumption evidence: main already rejects defer 3 and defer x + 1 with HYB-E2001 (builtins.rs, #191), and it intentionally treats defer f.close() (Try-wrapping-call) as the documented legal shape at check time — so the PR's headline reject of defer cleanup()? is a policy change vs landed code, and on the merged tree both passes fire, producing duplicate E2001 diagnostics for defer 3 (verified via --json). What main genuinely lacks — all reproduced: (1) defer 3 inside a closure body passes main with 0 diagnostics (the builtins pass doesn't walk closures) and gets E2001 here; (2) defer work(pair()?) with a (int, error) callee passes main's check then dies at emit ("? outside a binding position"), and this PR's hoist emits hyT0 and go-builds clean — the unique '?'-hoist value; (3) defer (close_it()) emits invalid Go on main (defer (f()) — "expression in defer must not be parenthesized") and builds here (paren peel). Integration bar: dedupe the double-E2001 with builtins.rs (one owner), reconcile the Try-operand policy (builtins.rs unwraps Try today), and keep the closure wiring + arg-hoist + paren peel. Clean auto-merge with main, builds green. Thanks — parts (1)-(3) are exactly the check→emit gap the PR describes.

…peel paren operands

v2 per the wave-2 integration bar: E2001 has ONE owner (builtins.rs
check_stmt_defer_call, now pub(crate)) — the second emitter is gone, so
the merged-tree double diagnostic cannot occur; the Try-operand policy is
reconciled to landed code (Try-wrapping a call stays legal; the registry
and AST edits are dropped); and the three unique halves are kept on
current main: closure-body wiring, deferred-call argument ? hoist, and
paren-peeled emission.

Part of limitlessprojects#288; closes the R4 check->emit gap of limitlessprojects#155.
@Leimiu-G

Copy link
Copy Markdown
Contributor Author

v2 pushed addressing the integration bar — rebased on c53978b, one owner (builtins.rs), Try policy reconciled to landed code, the three unique halves kept and pinned.


v2 — the wave-2 integration bar, addressed

Rebased on current main @ c53978b. Every item from the triage's integration bar:

1. E2001 dedupe — one owner. The headline E2001 emission in this PR's lib.rs is gone. builtins.rs's check_stmt_defer_call (#191) is now the single owner (made pub(crate)); the closure walk calls it, nothing else emits E2001. New integration pin defer_non_call_flat_body_rejected_exactly_once asserts count == 1 for defer 3 / defer x + 1 — the duplicate-diagnostic failure mode from the triage can no longer exist by construction.

2. Try-operand policy reconciled to landed code. The v1 headline reject of defer cleanup()? is withdrawn — builtins.rs unwraps Paren/Try today, so the Try-wrapping call stays the documented legal shape. The two places that encoded the stricter reading are dropped from this branch (the registry fixit and the AST doc comment edits — both were only wrong under the v1 policy). Pins try_wrapping_call_operand_is_the_legal_shape (+ closure variant) lock the reconciled policy.

3. The three unique halves — kept, now on current main:

  • closure wiring (gap 1): closures.rs calls the one-owner check_stmt_defer_call, so defer 3 inside a closure body — which main passes with 0 diagnostics — is rejected. Pins: closure body, nested block in closure, plus legal-shape controls.
  • arg-? hoist (gap 2): defer work(pair())? hoists the argument ? to a binding before the defer and emits buildable Go. Three emit goldens carried over: bare call arg, paren-peeled operand, and the paren+hoist combination.
  • paren peel (gap 3): defer (close_it()) lowers to defer close_it() — Go rejects a parenthesized defer operand.

Scope now: builtins.rs (+pub(crate)), closures.rs (+7-line wiring), hy-emit/stmt.rs (defer branch: hoist gate + peel), hy-emit/tests.rs (3 goldens), new hy-check/tests/defer_operand.rs (6 pins). The v1 edits to diagnostics.json and ast.rs are reverted (not needed under the landed policy).

Verification: cargo test --release --workspace (rustc 1.99.0, x86_64-pc-windows-gnu): 36/37 suites green; the only failure is hyb generate's gofmt check — no Go toolchain in this sandbox, same environment-only failure documented in #420. defer_operand 6/6, emit goldens 3/3.

Fixes #155 (R4 + the arg-? sibling). Refs #191 (the one owner this now defers to), #409/#420 (same A5 perimeter wiring discipline).

AI-assisted: yes — operator applied the integration bar hunk-by-hunk and re-ran the full suite.

@Leimiu-G

Copy link
Copy Markdown
Contributor Author

Status update while this awaits the landing call — the defer/? family around it moved, and there is now a second in-flight PR on the same family that we should coordinate with.

#469 (@exantiv, /claim #155, head 65c229f) implements the same arg-position hoist on the emit side (hoist_tries_expr(call) in the Stmt::Defer arm — same technique as this branch), and additionally rejects the outermost defer f()? at check (E2001 when unwrap_parens(call) is Expr::Try). That reject closes R4's check→emit gap, which this branch deliberately leaves open under the landed Try-operand policy (wave-2 triage: builtins unwraps Try, so the shape is legal at check time). On reflection we agree the reject is the right resolution — an outermost ? cannot hoist, because the deferred call executes at function return and the error has nowhere to land — so this branch should reconcile to it. (This branch's emit gates the hoist on Expr::Call, so the unbuildable shape fails loudly at emit rather than lowering to wrong code; #469's check-time reject is the cleaner resolution of the same case.)

What remains unique to this branch — verified against #469's head, none of it is covered there:

  1. Closure wiring (gap 1). defer 3 inside a closure body still passes check with 0 diagnostics on fix: resolve hy-check: ? operator never validated against operand or enclosing scope (E4, T20, E3b) + closure error scoping in hy-emit (#155) #469 (builtins' E2001 owner doesn't walk closures; try_check's Defer arm only fires on Try operands) and dies late in the emitter. The one-owner wiring here closes it, pinned three ways.
  2. One-owner dedupe. Exactly one E2001 per deferred non-call — by construction, not by convention.
  3. Paren peel. defer (f.close()) lowers to defer f.Close(). fix: resolve hy-check: ? operator never validated against operand or enclosing scope (E4, T20, E3b) + closure error scoping in hy-emit (#155) #469's emit keeps the parens (defer (fmt.Println("done")) — invalid Go; details in the review on fix: resolve hy-check: ? operator never validated against operand or enclosing scope (E4, T20, E3b) + closure error scoping in hy-emit (#155) #469), because its Defer arm emits the unpeeled call.

The collision to rule on: this branch's pins try_wrapping_call_operand_is_the_legal_shape (+ the closure variant) assert the landed policy (0 E2001 for defer cleanup()?); #469 makes that E2001. If the outermost ? should be rejected, say the word and we will flip those two pins and rebase onto whichever lands first — this branch then contributes exactly the three unique halves above, with #469's try_check owning the ?-legality pass (E3/E3b/E4/T20). Our preference: land #469's try_check first, this branch rebased on top. If instead the landed policy stands, #469's E2001 on the direct operand needs a different resolution.

@Leimiu-G

Copy link
Copy Markdown
Contributor Author

Alignment update, now that #469 (b147f14) has been reviewed: it covers this branch's functional surface — the one-owner pub(crate) change in builtins.rs, the closures.rs wiring (inside the Defer arm rather than before the match — equivalent, arguably cleaner), the argument-position hoist, and the paren peel with emit pins. @exantiv's implementation is sound, and this branch no longer carries unique functional value.

What remains here is two hardening items, both now raised on #469: the emit-side Expr::Call gate (fail-loud if a defer f()? ever slips past check) and the exactly-one-E2001 dedupe pin.

Proposal, to keep this branch useful rather than redundant: if #469 lands first, we rebase onto it and reduce this PR to exactly those two hardening items — a small follow-up instead of an overlapping one. If #469 needs rework, this branch stands as the independent implementation of the same fixes. Ruling welcome either way — happy to be subsumed if that is the cleaner merge.

# Conflicts:
#	compiler/crates/hy-check/src/closures.rs
@limitlessprojects
limitlessprojects merged commit 5317e70 into limitlessprojects:main Oct 18, 2026
1 of 2 checks passed
gelismarvel added a commit to gelismarvel/Go-Hybrid that referenced this pull request Oct 18, 2026
Integrate limitlessprojects#288 (HYB-E2001 defer-operand, single owner in builtins.rs): take main's defer emission in hy-emit/stmt.rs; ignore the new SelectArmKind::Send is_move field in try_check.rs; remove try_check's own defer-E2001 arm and the duplicate check_stmt_defer_call in the closure walk, since defer f()? is now the documented legal shape; drop the three limitlessprojects#155 tests that asserted the superseded behaviour (defer_operand.rs covers it).
limitlessprojects pushed a commit to gelismarvel/Go-Hybrid that referenced this pull request Oct 18, 2026
…projects#449): unify lexical nested-closure capture/header scope collection in hy-check

Author: exantiv (head 0a8eeb8, branch fix/issue-445-449-real-patch).

What it fixes: closures inside else-if chain conditions / if-init headers /
match guards / loop headers inside a closure body never reached the nested
boundary pass (collect_stmt_direct_fnlits ran only over direct block stmts and
the If arm explicitly skipped Stmt::If else-links), so a task spawn sharing the
outer closure's map through an else-if condition closure passed hyb check with
0 diagnostics and raced at runtime (issue limitlessprojects#445, GUARANTEES row 5 / O4.10).
Direct FnLits are now collected at their exact lexical evaluation point
(if/else-if conditions while the init scope is live, match guards with the
arm pattern bound, for/range/while headers, local/assign RHS before LHS
defines overwrite the env); NestedClosure snapshots gain an overwritten set
so a later same-scope shadow no longer leaks post-shadow moves into the
lexical capture (deepens landed limitlessprojects#483/limitlessprojects#449); self-alias entries (name->name)
are no longer inserted on may-share rebinds. The PR's model.rs -11 (dead
duplicate FnLit arm in collect_ref_roots) was already removed on main during
the limitlessprojects#288 landing — merge keeps main's side; no landed content discarded.
Residual limitlessprojects#449 sub-block move propagation is already covered by main (limitlessprojects#483):
repros r449_shadow/r449_subblock reject identically on both trees.

Verification (merged tree on origin/main 1e1a665): cargo test --workspace
971/0 (+13, includes the PR's 11-test nested_closure_and_a3_scope_445_449
suite), corpus_harness 61/61 tripwire not fired, differential FULL 17+44.
Repros: r445_elseif.hy -> main OK (0 diagnostics, live data race per issue
limitlessprojects#445's go-race demo) vs merged tree HYB-E3001; positive control (closures in
if/else-if conds, loop headers, match-free reads) OK on both — no false
positives.

Credit: exantiv. Triage: task 20-d verified.
magomedta pushed a commit to magomedta/Go-Hybrid that referenced this pull request Oct 20, 2026
…ion scope (fixes limitlessprojects#155)

- hy-check: validate every Expr::Try site against E4/T20/E3b:
  * Reject '?' on option[T] (HYB-E2003, T20)
  * Reject '?' on non-error returning calls (HYB-E2003, E4)
  * Reject '?' in functions/closures without error return (HYB-E2004, E3b)
  * Defer operand checking preserved per landed limitlessprojects#288 policy
- hy-diag: register and sort HYB-E2003 and HYB-E2004 in data/diagnostics.json
- hy-emit: isolate closure error returns so closure '?' does not bind to main exit contract
- tests: add 13 unit tests in try_legality.rs covering valid & invalid usages
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.

2 participants