Skip to content

fix: resolve hy-check: ? operator never validated against operand or enclosing scope (E4, T20, E3b) + closure error scoping in hy-emit (#155) - #469

Closed
gelismarvel wants to merge 5 commits into
limitlessprojects:mainfrom
gelismarvel:fix/issue-155-real-patch
Closed

gelismarvel wants to merge 5 commits into
limitlessprojects:mainfrom
gelismarvel:fix/issue-155-real-patch

Conversation

@gelismarvel

@gelismarvel gelismarvel commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Root Cause Analysis (#155)

  1. hy-check never validated Expr::Try against its operand or enclosing scope (E4, T20, E3b):
    • Expr::Try was only walked transparently as its inner operand, so:
      • ? on an option[T] result (v := find("a")?) was accepted with 0 diagnostics (T20 violation: absence and failure stay distinct) and emitted Go that failed go build (assignment mismatch: 2 variables but find returns 1 value).
      • ? on a call returning a non-error type (x := five()?, fmt.println("hi")?, serde_json.new_object()?) or a shadowed non-function local (run := 42; run()?) was accepted with 0 diagnostics (E4 violation).
      • ? inside a function or closure whose declared results do not end in error (and is neither main nor an E11 http.handler conversion target) was accepted with 0 diagnostics (E3b violation).
  2. hy-emit leaked in_main_closure and cur_fn_error_returns into nested Expr::FnLit closures:
    • When emitting Expr::FnLit in compiler/crates/hy-emit/src/expr.rs, self.in_main_closure and self.cur_fn_error_returns were not scoped to the closure's own declared results, causing closures inside main() or an error-returning function to inherit the outer function's error return target instead of propagating via the closure's own (..., error) signature (or refusing when the closure has no error return).

Fix Summary (Reconciled with #288 on main)

  1. Diagnostic Registry (compiler/crates/hy-diag/data/diagnostics.json):
    • Registers HYB-E4003 (try-operand-not-error, rule E4), HYB-E4004 (try-on-option, rule T20), and HYB-E4005 (try-cannot-propagate, rule E3b) in the E400x range (avoiding any E200x numbering collision).
    • Defer-operand HYB-E2001 ownership stays solely in builtins.rs as established by #288.
  2. hy-check Try-Legality Pass (compiler/crates/hy-check/src/try_check.rs, compiler/crates/hy-check/src/lib.rs):
    • Adds try_check::check_tries_in_fn with lexical block/closure scope tracking and type-alias resolution:
      • Emits HYB-E4004 (rule: T20) when ? is applied to an option-returning call (some, none, user fn/method/closure returning option[T]).
      • Emits HYB-E4003 (rule: E4) when ? is applied to a non-call or a call known not to return error (user fn/method/closure, non-function local binding, builtin, or foreign package/handle method).
      • Emits HYB-E4005 (rule: E3b) when ? is used inside a function or closure that cannot propagate errors (neither main, nor ending in error, nor an E11 http.handler(...) closure).
  3. hy-emit Closure Error-Scoping & Non-Error Call Guards (compiler/crates/hy-emit/src/expr.rs, compiler/crates/hy-emit/src/stmt.rs):
    • Saves and restores self.in_main_closure and self.cur_fn_error_returns around Expr::FnLit emission, computing cur_fn_error_returns from the closure's own declared results.
    • Guards hoist_one_try and emit_try_define against calls whose call_results shape has has_error == false.

Verification

  • cargo test -p hy-diag -p hy-syntax -p hy-check -p hy-emit: 888/888 passed (0 warnings, 0 failures)

@Leimiu-G

Copy link
Copy Markdown
Contributor

Thanks for the thorough write-up — the CallResultKind classification (alias peeling, binding/builtin branches, ?-on-non-call → NotError) and the emit-side closure scoping (saving/restoring in_main_closure / cur_fn_error_returns around FnLit bodies) look right, and the E4003/E4004/E4005 split reads well against E4/T20/E3b.

Two notes on the defer interaction, one of which I'd consider blocking:

1. in_defer covers the whole operand expression tree, so argument-position ? is rejected too.

check_stmt sets in_defer: true for the entire call of Stmt::Defer, and check_expr's Expr::Try arm fires E2001 whenever in_defer — including a ? nested in an argument:

fn load() (int, error) { return 1, nil }
fn close_it(n int) error { return nil }

fn run() error {
    defer close_it(load()?)   // argument `?` — legitimately hoistable
    return nil
}

Argument-position ? is not the same case as defer f()?: a deferred call's arguments are evaluated at defer time (SPEC §7 P1), so the ? propagates from the enclosing function at the defer statement, not at function return — it desugars to t, hyErr := load() before the defer, and the deferred call itself stays deferred. Supporting evidence:

Your tests cover the outer form (REPRO_DEFER_TRY = defer cleanup()?) but not the argument form, so this looks like a blind spot rather than intent. Minimal fix: reject only when the try is the defer's direct operand — i.e. unwrap_parens(call) is Expr::Try — and leave in_defer false while recursing into the call's arguments.

2. The PR edits the E2001 fixit away from ?.

-        "defer the call itself: `defer f.close()?` instead of `defer f.close`"
+        "defer the call itself: `defer f.close()` instead of `defer f.close`"

If the ruling is "no ? anywhere inside a defer", the shipped fixit contradicts it and #288 v2's argument hoist becomes dead code. If the ruling is "no ? as the deferred call's own result", the fixit is right as shipped and note 1 applies. Either way the fixit text should follow a ruling rather than legitimize the implementation — worth a maintainer call.

On the outer form itself: rejecting defer f()? at check time is the right direction — main currently accepts it with 0 diagnostics and lets the emitter fail late ("? outside a binding position"), which is the exact check→emit gap #155's R4 describes, and E3b says the propagation cannot land there. (That outer hole is also still live in #288 v2 — check accepts, emit refuses — so a check-side E2001 restricted to the direct operand is the shape both PRs can agree on.)

@gelismarvel

Copy link
Copy Markdown
Contributor Author

Thanks @Leimiu-G for the spot-on review! Rebased onto latest main (07d63ec) and updated in 65c229f:

  1. Restricted HYB-E2001 to the direct operand of Stmt::Defer (unwrap_parens(call) is Expr::Try) and left in_defer = false when recursing into call arguments (compiler/crates/hy-check/src/try_check.rs):
    • Outer defer cleanup()? is still rejected at check time with HYB-E2001 (since the deferred call runs at function return and cannot propagate ?).
    • Argument-position defer close_it(load()?) is evaluated at defer-registration time (SPEC §7 P1), so load()? is now checked against the enclosing function's error-propagation scope (E4 / T20 / E3b) and accepted when valid.
  2. Emit-side hoisting for Stmt::Defer arguments (compiler/crates/hy-emit/src/stmt.rs):
    • Added self.hoist_tries_expr(call)? in Stmt::Defer before emitting defer ..., so defer close_it(load()?) lowers to hyTry0, hyErr0 := load(); if hyErr0 != nil { ... }; defer close_it(hyTry0).
  3. Regression tests:
    • Added valid_defer_argument_try_accepts in compiler/crates/hy-check/tests/try_legality.rs (14/14 PASS).
    • Added defer_argument_try_hoists_before_defer_issue_155 in compiler/crates/hy-emit/tests/try_closure_scope.rs (4/4 PASS).

@gelismarvel
gelismarvel force-pushed the fix/issue-155-real-patch branch from b6164da to 65c229f Compare October 17, 2026 16:41
@Leimiu-G

Copy link
Copy Markdown
Contributor

Thanks for adopting the split — narrowing HYB-E2001 to unwrap_parens(call) is Expr::Try and recursing into arguments with in_defer = false is exactly the right shape, and the arg-position hoist matches P1 (a deferred call's arguments are evaluated at defer time, so the ? lands at the defer, not at return).

Two gaps this branch still has — both covered by #288 v2 (in flight; the wave-2 integration bar is addressed) — flagging so the two PRs land as complements rather than duplicates:

1. A parenthesized defer operand emits invalid Go. The Stmt::Defer arm hoists and emits the unpeeled call. hoist_tries_expr recurses through Expr::Paren (the Unary/AddrOf/Move/Paren arm), so the hoist itself is fine — but emit_expr(call, 0) keeps the parens:

defer (fmt.println("done"))

lowers to defer (fmt.Println("done")), and Go rejects a parenthesized defer operand ("expression in defer must be function call"). The checker accepts it (builtins unwraps Paren for the E2001 shape test), so this is a fresh check→emit gap of exactly the #155 family — on this branch. The emitter already has Self::peel_parens (stmt.rs:336); peeling before the emit closes it. #288 v2 pins three cases here: the flat paren case, defer (sink(probe()?)) (hoist through the parens, no parens in the output), and the unparenthesized arg case.

2. defer 3 inside a closure body still passes check with 0 diagnostics. try_check's Defer arm only fires on a Try operand, and builtins' E2001 owner is not wired into the closure walk — so a non-call defer one scope in still passes the checker and dies late in the emitter. That is gap (1) from the wave-2 triage on #288 (reproduced by the maintainer on main: 0 diagnostics). #288 v2 wires the one-owner rule into closures.rs::check_stmt_boundaries and pins it three ways.

One policy heads-up, since the two PRs now collide on test expectations: the wave-2 triage on #288 recorded that main intentionally treats the Try-wrapping-call defer operand as the documented legal shape at check time ("builtins.rs unwraps Try today"), and called an outright reject "a policy change vs landed code". Your E2001 on the direct operand is the buildable resolution of R4 — an outermost ? cannot hoist, because the deferred call runs at function return and the error has nowhere to land, and hoisting the call itself would break the defer — so we think rejecting is right, and we will flip #288 v2's two landed-policy pins to match once the maintainer rules. Flagging so both PRs don't land on contradictory expectations.

Two smaller notes:

  • After the 65c229f narrowing, nothing passes in_defer = true into check_stmt anymore (the Defer arm passes false in both branches), so the if in_defer arm in check_expr is unreachable — the parameter can go.
  • E4003/E4005 force edits to two landed lib.rs tests (the 12-shape suite: int → (int, error)). The tightening itself follows E3b, but it changes landed expectations — worth an explicit nod from the maintainer that it is intended.

@gelismarvel

Copy link
Copy Markdown
Contributor Author

Thanks @Leimiu-G — updated in �147f14 so the two PRs stay completely aligned:

  1. Peel outer parentheses on Stmt::Defer in compiler/crates/hy-emit/src/stmt.rs: Self::peel_parens(call) is now applied before hoisting and emitting, so defer (close_it(load()?)) hoists load()? and emits defer close_it(hyT2) without outer parentheses.
  2. Wire check_stmt_defer_call into closure bodies (compiler/crates/hy-check/src/builtins.rs & closures.rs): Stmt::Defer inside closure bodies now runs the same HYB-E2001 non-call check (defer 3 inside a closure rejects with HYB-E2001).
  3. Removed the unused in_defer parameter from check_block / check_stmt / check_expr in compiler/crates/hy-check/src/try_check.rs.
  4. Regression tests: Added closure_body_non_call_defer_rejects_e2001 in ry_legality.rs (15/15 PASS) and parenthesized defer (close_it(load()?)) verification in ry_closure_scope.rs (4/4 PASS).

@Leimiu-G

Copy link
Copy Markdown
Contributor

Confirmed on b147f14 — the paren peel, the closure wiring, and the in_defer removal all land cleanly, and the new pins cover exactly the shapes flagged. Thanks for the fast turnaround; the two PRs are fully aligned now, and this branch is the stronger take of the #155 family.

Two small hardening notes for the triage pass — defense-in-depth rather than correctness, since the checker covers both paths today:

  1. The defer arm's hoist lost its Expr::Call gate. With hoist_tries_expr(inner) unconditional, a defer f()? that ever slips past the check-time E2001 (a future walk gap — select arms, E11 handler bodies, generated code) would hoist into v, hyErr := f(); if hyErr != nil { ... } and then emit defer v — deferring the value, not the call, which is both wrong and invalid Go when f returns a non-function. Gating on matches!(inner, Expr::Call) keeps the emitter fail-loud ("? outside a binding position") instead of silently wrong — the same principle your new ?-on-non-error guards apply one level down.

  2. A dedupe pin for the merged tree. Once this lands, three passes see the same defer statement (builtins flat walk, the closures wiring, try_check's Defer arm). Today only one fires per shape, but nothing pins that. check: implement HYB-E2001 (reject non-call defer operand); hoist ? in deferred call args #288 v2's defer_non_call_flat_body_rejected_exactly_once asserts exactly-one-E2001 for defer 3 / defer x + 1 — happy to contribute it here as a regression guard if useful.

Either way this is in good shape — thanks again for the collaboration.

@gelismarvel
gelismarvel force-pushed the fix/issue-155-real-patch branch from b147f14 to 005a65d Compare October 17, 2026 18:04
@gelismarvel

Copy link
Copy Markdown
Contributor Author

Thanks @Leimiu-G! Applied both defense-in-depth hardening updates and rebased onto latest main (a2cf3a0) in 005a65d:

  1. compiler/crates/hy-emit/src/stmt.rs (Stmt::Defer): Gated self.hoist_tries_expr(inner)? on if matches!(inner, Expr::Call { .. }) so any hypothetical direct emit call bypassing hy-check on defer f()? fails loud in emit_expr (Expr::Try) instead of hoisting into a value temporary.
  2. compiler/crates/hy-check/tests/try_legality.rs: Added defer_non_call_flat_body_rejected_exactly_once and tightened closure_body_non_call_defer_rejects_e2001 to assert codes == vec!["HYB-E2001"] (exact diagnostic count 1, no duplicate across structure and try_legality).

Verified 17/17 tests in hy-check --test try_legality and 4/4 tests in hy-emit --test try_closure_scope.

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).
@gelismarvel gelismarvel changed the title fix: resolve hy-check: ? operator never validated against operand or enclosing scope (E4, T20, E3b, defer E3) + closure error scoping in hy-emit (#155) fix: resolve hy-check: ? operator never validated against operand or enclosing scope (E4, T20, E3b) + closure error scoping in hy-emit (#155) Oct 18, 2026
Resolve hy-emit/expr.rs conflict with pr-536: keep limitlessprojects#155's closure state restores (in_main_closure, cur_fn_error_returns) alongside main's restore_scope and deferred body_res? (replacing the old bindings.retain).
isHeSatoshi added a commit to isHeSatoshi/Go-Hybrid that referenced this pull request Oct 20, 2026
…gnment (limitlessprojects#726)

SPEC E1: "Functions signal failure by returning `error` as the final result:
`(string, error)`, `(total int, err error)`, **or bare `error`**." SPEC E3/E4:
`?` applies to an error-returning call inside a function whose results end in
`error`, or in `main`. So `step()?` on a `fn step() error` is the simplest legal
use — the Hybrid spelling of `if err := step(); err != nil { return err }`.

`hyb check` accepted it correctly. The LOWERING was wrong:

```go
func run() error {
    hyT0, hyErr1 := step()   // step returns ONE value
    if hyErr1 != nil { return hyErr1 }
    hyT0                     // and: evaluated but not used
    return nil
}
```

Two causes, both in how the `?` hoist learns a call's arity:

1. `fn_shapes` stored `results.len()`, which INCLUDES the trailing `error`, so
   `fn step() error` recorded `(1, true)` and never matched the dedicated
   zero-value path (`(0, true)`). The descriptor tables spell the count the
   other way — `serde_json.value.set` is `(0, true)`, it returns only an error —
   so only user-declared functions hit this. Now stores the value-result count,
   `results.len() - usize::from(err)`.

2. A method on a USER struct was in no table at all, so `s.save()?` found no
   entry and fell through to the two-name form. Added `method_results`, keyed
   `(receiver struct name, method name)`, filled from `file.fns()` — a method is
   a `Decl::Fn` with a receiver, so it was already in that iterator and only
   needed the receiver's struct name to become findable. `call_results` joins it
   through the existing `var_struct` registry, which already maps a binding to
   its struct name.

Verified against main @ aa4a9d9:

  - 4 bare-`error` shapes (free fn, fn with args, user method, in `main`):
    `hyb check` ACCEPT + `go build` FAILS before, ACCEPT + BUILDS after
  - the two-result forms (`(int, error)`, named `(n int, err error)`) still
    build, and `two_result_call_under_try_keeps_its_value_temp` pins that the
    fix did NOT collapse the value token for a call that genuinely has one
  - corpus 113 -> 114 (1 ACCEPT fixture), verdict agreement 114/114, tripwire
    not fired
  - differential reject-side 76/76, accept-side 36/38 (the 2 are the known
    cgo-bridge programs, unchanged from baseline)
  - managed gate PASS, test registration OK, conflict markers none, census OK
  - 7 new tests in `hy-emit/tests/bare_error_try_lowering.rs`; hy-emit and
    hy-check suites green

The fixture is deliberately an ACCEPT, not a REJECT: the checker was right to
accept, and it reported 0 diagnostics both before and after the fix, so a reject
fixture would have been the wrong shape and would have passed for the wrong
reason. That is also why the real assertion lives at the emitter level — the
harness alone cannot see a lowering bug behind a clean check, which is exactly
how this survived.

Not a duplicate of limitlessprojects#155 / limitlessprojects#166 / limitlessprojects#469: those cover `?` on a call that does NOT
return `error` (option/int results, closures with no error result), which should
be REJECTED. Those are still open and unlanded. This change is about lowering a
call that is already legal — it adds no new rejection, so the two do not
interact.

Refs limitlessprojects#726.
isHeSatoshi added a commit to isHeSatoshi/Go-Hybrid that referenced this pull request Oct 20, 2026
…gnment (limitlessprojects#726)

SPEC E1: "Functions signal failure by returning `error` as the final result:
`(string, error)`, `(total int, err error)`, **or bare `error`**." SPEC E3/E4:
`?` applies to an error-returning call inside a function whose results end in
`error`, or in `main`. So `step()?` on a `fn step() error` is the simplest legal
use — the Hybrid spelling of `if err := step(); err != nil { return err }`.

`hyb check` accepted it correctly. The LOWERING was wrong:

```go
func run() error {
    hyT0, hyErr1 := step()   // step returns ONE value
    if hyErr1 != nil { return hyErr1 }
    hyT0                     // and: evaluated but not used
    return nil
}
```

Two causes, both in how the `?` hoist learns a call's arity:

1. `fn_shapes` stored `results.len()`, which INCLUDES the trailing `error`, so
   `fn step() error` recorded `(1, true)` and never matched the dedicated
   zero-value path (`(0, true)`). The descriptor tables spell the count the
   other way — `serde_json.value.set` is `(0, true)`, it returns only an error —
   so only user-declared functions hit this. Now stores the value-result count,
   `results.len() - usize::from(err)`.

2. A method on a USER struct was in no table at all, so `s.save()?` found no
   entry and fell through to the two-name form. Added `method_results`, keyed
   `(receiver struct name, method name)`, filled from `file.fns()` — a method is
   a `Decl::Fn` with a receiver, so it was already in that iterator and only
   needed the receiver's struct name to become findable. `call_results` joins it
   through the existing `var_struct` registry, which already maps a binding to
   its struct name.

Verified against main @ aa4a9d9:

  - 4 bare-`error` shapes (free fn, fn with args, user method, in `main`):
    `hyb check` ACCEPT + `go build` FAILS before, ACCEPT + BUILDS after
  - the two-result forms (`(int, error)`, named `(n int, err error)`) still
    build, and `two_result_call_under_try_keeps_its_value_temp` pins that the
    fix did NOT collapse the value token for a call that genuinely has one
  - corpus 113 -> 114 (1 ACCEPT fixture), verdict agreement 114/114, tripwire
    not fired
  - differential reject-side 76/76, accept-side 36/38 (the 2 are the known
    cgo-bridge programs, unchanged from baseline)
  - managed gate PASS, test registration OK, conflict markers none, census OK
  - 7 new tests in `hy-emit/tests/bare_error_try_lowering.rs`; hy-emit and
    hy-check suites green

The fixture is deliberately an ACCEPT, not a REJECT: the checker was right to
accept, and it reported 0 diagnostics both before and after the fix, so a reject
fixture would have been the wrong shape and would have passed for the wrong
reason. That is also why the real assertion lives at the emitter level — the
harness alone cannot see a lowering bug behind a clean check, which is exactly
how this survived.

Not a duplicate of limitlessprojects#155 / limitlessprojects#166 / limitlessprojects#469: those cover `?` on a call that does NOT
return `error` (option/int results, closures with no error result), which should
be REJECTED. Those are still open and unlanded. This change is about lowering a
call that is already legal — it adds no new rejection, so the two do not
interact.

Refs limitlessprojects#726.
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