Skip to content

[soundness] ? is never checked against its operand — on option/int/closure-local calls accepted with 0 diagnostics and emits non-compiling Go (E4/T20 unimplemented) #155

Open

Description

@Leimiu-G

[soundness] ? is never checked against its operand — ? on option-returning, int-returning, and closure-local calls is accepted with 0 diagnostics and emits non-compiling Go (E4/T20 type error unimplemented; closure ? binds to the wrong scope)

Revision (git rev-parse HEAD)

f99d6d0b37722de206015be9e1c59b04e827c794 (origin/main, 2026-10-15 04:45 UTC; hyb built from this exact tree).

Summary

SPEC-LANGUAGE E4 pins two type errors for the try operator:

"? on an expression that is not an error-returning call is a type error; ? on option is a type error (T20) — absence and failure stay distinct."

And E3b pins where a ? may propagate:

"Where the propagation cannot land (no error result, not main, not an E11 handler), it is a compile error — never a silent swallow."

None of this is checked. In hy-check, Expr::Try exists only as a transparent operand-walk (shape.rs:155: Expr::Move {..} | Expr::Try { operand, .. } | Expr::Paren {..} => self.shape_of_expr(st, operand)) — the checker never inspects whether the operand returns error at all, whether the enclosing function (or closure) can host the propagation, or whether an option result was confused with a failure. ? is not a checker special case in the sense the spec means; it is a no-op case.

Consequences, all reproduced on main @ f99d6d0 with OK (0 diagnostics):

  1. ? on an option-returning call (the T20 type error): accepted; the emitter hoists a two-name binding from a one-result call → emitted Go fails with assignment mismatch.
  2. ? on a plain int-returning call (the E4 "not an error-returning call" type error): same — accepted, non-compiling Go.
  3. ? inside a closure whose results do not end in error (the E3b "compile error — never a silent swallow" case): accepted, and the emitter binds the propagation to the enclosing main's exit contract, violating E4's lexical rule ("binds to the closure's own results, not the enclosing function's") — before the emitted Go fails to compile anyway.
  4. ? in a defer argument: the checker accepts; the emitter refuses ("? outside a binding position") — a check→emit gap.

The four smallest .hy programs that demonstrate it

R1 — ? on an option-returning call (T20 type error; checker: OK)

// try_r1_option.hy — OK (0 diagnostics) on main @ f99d6d0
fn find(k string) option[int] {
    if k == "a" {
        return some(1)
    }
    return none
}

fn main() {
    v := find("a")?
    fmt.println(v)
}

hyb check → OK (0 diagnostics). hyb build --emit-go emits (t6-out.go):

hyT0, hyErr0 := find("a")   // line 28

go build → .\t6-out.go:28:16: assignment mismatch: 2 variables but find returns 1 value.

The emitter's hoist_one_try (hy-emit/src/stmt.rs) only special-cases call_results == Some((0, true)) (error-only calls); everything else — including a 1-result, no-error call — gets the hyT, hyErr := two-name form.

R2 — ? on a plain int-returning call (E4 type error; checker: OK)

// try_r2_int.hy — OK (0 diagnostics) on main @ f99d6d0
fn five() int {
    return 5
}

fn main() {
    x := five()?
    fmt.println(x)
}

hyb check → OK (0 diagnostics). go build on the emission → .\t7-out.go:15:16: assignment mismatch: 2 variables but five returns 1 value.

R3 — ? in a closure without an error result (E3b compile error missing; propagation binds to the wrong scope)

// try_r3_closure.hy — OK (0 diagnostics) on main @ f99d6d0
fn five() int {
    return 5
}

fn main() {
    f := fn() {
        x := five()?
        fmt.println(x)
    }
    f()
}

hyb check → OK (0 diagnostics). Emitted (t8-out.go, abridged):

hyErr := func() (hyErr error) {
	f := func() {
		x, hyErr0 := five()      // line 16: assignment mismatch
		if hyErr0 != nil {
			hyErr = hyErr0      // the closure's "?" assigns the OUTER main-exit error
			return
		}
		fmt.Println(x)
	}
	f()
	return
}()
if hyErr != nil { ...; os.Exit(1) }

Two violations in one emission: the closure's ? is wired into main's exit contract (E4 says the closure's own results govern — it has none, so E3b demands a compile error), and the emitted Go does not compile (.\t8-out.go:16:17: assignment mismatch: 2 variables but five returns 1 value).

R4 — ? in a defer argument (checker: OK; emitter: unsupported)

// try_r4_defer.hy — OK (0 diagnostics) on main @ f99d6d0
fn cleanup() error {
    return nil
}

fn main() {
    defer cleanup()?
    fmt.println("done")
}

hyb check → OK (0 diagnostics). hyb build → error [emit]: emitter (MVP-0): not yet supported: \?` outside a binding position — E3 desugars binding-position and hoisted-expression `?` only. Same check→emit gap shape as #103, on the ?`/defer pair.

What the checker should say

  • R1: HYB-E…: \?` on an option result — absence and failure are distinct (T20); use match/if-ok or an (T, error) call`.
  • R2: HYB-E…: \?` on a call that does not return error (E4)`.
  • R3: HYB-E…: \?` in a closure whose results do not end in error — the propagation has nowhere to land (E3b)`.
  • R4: a defer-specific diagnostic (or an explicit not-yet-supported error at check time), so hyb check and hyb build agree.

What it actually said

try_r1_option.hy:   OK (0 diagnostics)
try_r2_int.hy:      OK (0 diagnostics)
try_r3_closure.hy:  OK (0 diagnostics)
try_r4_defer.hy:    OK (0 diagnostics)

Root cause

  1. hy-check has no ?-legality pass. Expr::Try appears only in operand-walk positions: shape.rs:155 (shape), walk.rs:327/488/548 (uses/calls/paths), closures.rs:479 (fn-lit collection), sendability.rs:191 catch-all (result-shape classification). Nothing asks the one question E4/T20 require: does this call return error, and can this site propagate it? The fn table (self.fns) already carries result signatures — call_shape consults it for shapes — so the legality check has the data it needs.
  2. The emitter guesses instead. hoist_one_try keys off call_results alone: (0, true) → error-only form; anything else → hyT, hyErr := call. A one-result, no-error call silently takes the two-name form and emits Go that cannot compile. propagate_error then picks a landing site by emission context (handler_writer → in_main_closure → cur_fn_error_returns), which is how R3's closure ? ends up bound to main's exit contract.
  3. SPEC E3's claim that "the checker expands this before loan checking" does not match the implementation — the desugar lives in the emitter (try_temps hoisting, hy-emit/src/lib.rs:354, hy-emit/src/stmt.rs). The checker never sees the hoisted bindings or the early-return propagation paths.

Suggested fix

  • In hy-check, validate every Expr::Try site: resolve the operand's call signature from self.fns (and method/builtin tables); reject when the call does not end in error (E4), when the result is option[T] (T20), and when the enclosing function/closure has no error result and is not main/an E11 handler (E3b). All four repros above must REJECT at hyb check time.
  • Until the check exists, make hoist_one_try fail closed when call_results reports a non-error shape (Some((n, false))) instead of emitting the two-name form.
  • Regression tests: R1-R4 reject; example 02/05's legitimate ? uses keep passing.

Relation to known issues / PRs

Claimed severity

Medium (BOUNTY.md: "a guarantee weaker than documented, or a misleading pass"). Four spec-pinned rejections never fire; three of the four programs emit non-compiling Go from a 0-diagnostic pass, and R3's emitted code — had the operand returned (int, error) — would have quietly rerouted a closure's error into main's exit path, a semantic change E4 forbids. Not a data race, but it voids the absence/failure distinction the error model is built on.


Report prepared with AI assistance (WorkBuddy agent); checker verdicts reproduced mechanically against main @ f99d6d0 — hyb check and hyb build --emit-go + go build on each .hy file quoted above.

Activity

  1. Leimiu-G commented on Oct 16, 2026

    @Leimiu-G
    ContributorAuthor

    Follow-up: the fix is up as #288.

    For this report's R4 (defer cleanup()?), the checker now reports the
    spec-mandated HYB-E2001 — SPEC-LANGUAGE §7 P1: "defer of a non-call
    expression is a compile error (HYB-E2001)"
    — at the operand's own span,
    instead of passing the program (0 diagnostics) and letting the emitter fail
    late with the unrelated "? outside a binding position" message.

    The same PR also covers the sibling case in the same family: a ? inside a
    deferred call's arguments (defer f(g?)) hit the identical check→emit gap
    even though P1 evaluates a deferred call's arguments at defer time. It is now
    hoisted to a binding before the defer.

    While wiring E2001 up, two spots turned out to contradict the rule and only
    became user-visible once the diagnostic actually fires: the registry fix-it
    and the Defer AST doc comment both showed defer f.close()? — the very shape
    the rule rejects. Both corrected to defer f.close().

    Verified: cargo test --workspace (rustc 1.99.0, x86_64-pc-windows-gnu) →
    hy-check 105/105, hy-emit 111/111, all other suites green. The only failures
    are the hyb generate tests, and only because this box has no Go toolchain
    (gofmt: program not found).

    R1/R2/R3 from the report (the TypeShape erasure family) are untouched here —
    they need the raw TypeExpr at the ? site and are a deeper change; not
    claimed by this PR.

  2. added a commit that references this issue on Oct 20, 2026
    9a3af3c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions