Skip to content

Unreachable-code detection: goto and Never-call divergence (§20b.5) #543

Closed

Description

@ehartford

Unreachable-code detection: goto and Never-call divergence (§20b.5)

Summary

Unreachable-code detection currently recognizes only three statement kinds as diverging (return, break, continue). Code after goto or after a call to a Never-returning function (panic, exit, todo(), unreachable()) is silently accepted, and the labeled-statement suppression rules of §20b.5 are vacuous because goto is never treated as a divergence source. This issue completes divergence detection so the spec's "all code after unconditional control flow transfers" rule actually holds.

Spec

§20b.5 Unreachable Code (docs/with-specification.md:10436):

The compiler detects unreachable code via control flow analysis and rejects it. This applies to all code after unconditional control flow transfers, including return, labeled or unlabeled break, labeled or unlabeled continue, goto, and calls to functions with return type Never (e.g., exit(), panic()).

A labeled statement may be reachable only via goto. Ordinary unreachable-code diagnostics are suppressed for a labeled statement and for following statements until the next control-flow terminator or the next labeled statement:

fn example:
    goto 'done
    print("never")    // unreachable
    'done
    print("finished") // reachable via goto

Also relevant: §29.10 (todo()/unreachable() "are treated as diverging control-flow points for typing and reachability analysis") and the §20b.5 comptime-if exemption (the check runs after comptime evaluation; must not regress).

Current state

  • Divergence detection lives in Sema.check_block (src/SemaCheck.w:4356-4395). Per-statement, block_diverged is set only by node kind at src/SemaCheck.w:4382-4383:
    if stmt_kind == NodeKind.NK_RETURN or stmt_kind == NodeKind.NK_BREAK or stmt_kind == NodeKind.NK_CONTINUE:
        block_diverged = 1
    
    The "unreachable code" error is emitted at src/SemaCheck.w:4363-4365 (statements) and 4391-4393 (block tail).
  • NK_GOTO is type-checked at src/SemaCheck.w:2900-2906 and returns self.ty_void — it never marks divergence. Statements after a goto are accepted (requirement verdicts 20.2.5.1/.3/.4: "goto/Never divergence undetected", "kind-based, not full CFA").
  • The type facts needed for Never-call divergence already exist: each statement's type is computed at src/SemaCheck.w:4374 (let stmt_ty = self.check_expr(stmt)), todo()/unreachable() return self.ty_never (src/SemaCheck.w:11277), break/continue expressions return ty_never (src/SemaCheck.w:2992, 3005), and a user/stdlib function declared -> Never resolves through the Never primitive (src/Sema.w:1284, src/SemaDecl.w:2227). check_block even consults last_stmt_ty == self.ty_never for the block result type (src/SemaCheck.w:4390) — but never for divergence.
  • Labeled statements: NK_LABEL (d0=label_sym, d1=statement, src/Ast.w:99-101) is checked transparently at src/SemaCheck.w:2897-2898. There is no suppression logic, which is currently harmless only because goto never sets block_diverged (requirements 20.2.5.5/.6 verdict: "vacuous").
  • The comptime-if exemption already works and is tested (test/spec/spec_ss20b_6_comptime_unreachable_exemption.w; requirement 20.2.5.7/.8 verdicts ok).

Root cause: divergence is a syntactic node-kind whitelist instead of using the Never type fact that sema already computes for every statement.

Implementation plan

  1. src/SemaCheck.w check_block (~4380-4388): extend the divergence condition:
    • keep the existing NK_RETURN/NK_BREAK/NK_CONTINUE kind checks (return statements may not be typed ty_never in all paths);
    • add stmt_kind == NodeKind.NK_GOTO;
    • add stmt_ty == self.ty_never as TypeId — this covers calls to Never-returning functions (panic, exit once typed Never, todo(), unreachable()) and any expression sema already types as Never (e.g. a match whose arms all diverge), giving the "control flow analysis" behavior the spec asks for without a separate CFG.
  2. Labeled-statement suppression (same loop): before the unreachable check, if self.ast.kind(stmt) == NodeKind.NK_LABEL, reset block_diverged = 0 (and leave reported_unreachable untouched so each dead region reports once). This implements §20b.5 exactly: suppression starts at the labeled statement and lasts until the next terminator (which sets block_diverged again) or the next labeled statement (which resets again). The label's inner statement (d1) must still be checked for its own divergence (e.g. 'done return x).
  3. Audit Never signatures: verify that the diverging stdlib entry points the spec names (exit(), panic) are actually declared -> Never. Today lib/std/libc.w:60 declares pub extern fn exit(code: i32) -> void. Decide per-symbol with the maintainer's spec reading: §20b.5 explicitly lists exit()/panic() as Never examples, so retype the user-facing wrappers (lib/std/process.w, prelude panic) as -> Never. This is a stdlib-only change (no rt//Link.w hazard), but watch for knock-on type errors in callers that relied on void.
  4. Determinism note: the new condition uses only per-statement AST order and the statement's computed type — no map iteration — so fixpoint determinism is unaffected.
  5. Do not regress the comptime exemption: check_block runs after comptime branch elimination, so no change is needed; the existing spec test guards it.

Edge cases to handle/verify:

  • goto as the inner statement of a label ('top goto 'top) — divergence applies after the labeled statement.
  • An if/else where both arms diverge types as Never only if sema already computes that; if it does not, that is acceptable (kind-based + Never-based detection is what §20b.5 requires; do not build a full CFG here — src/BorrowCfg.w notes its CFG is for future borrow analyses).
  • Error-message text: reuse the existing "unreachable code" message for consistency with current tests.

Test plan

test/compile_errors/ (one error each, //! expect-check-fail: or //! expect-error: unreachable code):

  • err_unreachable_after_goto.w — statement after goto 'done with no intervening label.
  • err_unreachable_after_panic.w — statement after panic("boom").
  • err_unreachable_after_todo.w — statement after todo() in a function body.
  • err_unreachable_after_exit.w — statement after exit(0) (once exit is -> Never).
  • err_unreachable_after_never_call.w — statement after a call to a user function declared -> Never.

test/spec/:

  • spec_ss20b_5_goto_label_reachability.w (//! expect-stdout: finished) — the exact §20b.5 example: goto 'done, dead print removed, 'done, then reachable code executes; plus a case where the label is followed by another terminator and then a second labeled region (suppression window boundaries).
  • Re-run spec_ss20b_6_comptime_unreachable_exemption.w unchanged (regression guard).

Negative-of-the-negative (must still compile): code after a conditional goto/panic inside an if arm.

Acceptance criteria

  • Code after goto is rejected with "unreachable code".
  • Code after calls typed Never (panic, exit, todo(), unreachable(), user -> Never fns) is rejected.
  • A labeled statement after a terminator is accepted, and statements following it up to the next terminator are accepted (suppression per §20b.5).
  • Comptime-if-eliminated branches still produce no unreachable error.
  • All new tests pass; no existing test regresses.
  • with build && with build :fixpoint && with build :test pass; with build :test-green recorded.

Dependencies

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 20.2.5.1, 20.2.5.3, 20.2.5.4, 20.2.5.5, 20.2.5.6.

Activity

  1. ehartford commented on Jun 11, 2026

    @ehartford
    ContributorAuthor

    Implemented in 58043ae. Added unreachable-code detection after goto and after expressions/calls typed Never, preserved label/goto reachability, corrected unannotated return inference so ordinary bare-return helpers do not falsely diverge, and made std process/libc exit signatures return Never. Added positive and negative tests for goto, todo/unreachable, exit, user Never calls, labeled reachability, and unannotated return inference. Verification passed: build, fixpoint, full test suite, and test-green. The full suite hit one transient raylib package-fetch failure; cli-selfhost-project-tests passed on direct rerun and the full suite passed cleanly afterward.

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