Skip to content

Bug: .unwrap()/.expect() do not panic on None/Err — return garbage (§10.5, §10.6) #545

Closed

Description

@ehartford

Bug: .unwrap()/.expect() do not panic on None/Err — return garbage (§10.5, §10.6)

Summary

.unwrap() on None/Err compiles to an unconditional payload extraction with no discriminant check, so it returns zeroed/uninitialized memory instead of panicking; .expect() is not implemented at all. Verified on v0.15.1. This is memory-safety-grade — the spec'd panic semantics are load-bearing for "safe With code" — and was the highest-priority finding of the requirements campaign.

Spec

§10.5 Option combinator table: unwrap — () -> T — "Extract value; panics if None"; expect — (msg: &str) -> T — "Extract value; panics with message if None". §10.6 Result table: same pair, panicking on Err. §10.6 normative text:

.unwrap() panics with a message that includes the source location and the Debug representation of the None/Err value. .expect() panics with the provided message plus the same debug info.

let user = find_user(id).unwrap()                       // panics if None
let user = find_user(id).expect("user must exist")      // panics with message

Current state

  • MIR lowering: lower_method_call routes unwrap to MirIntrinsic.OPT_UNWRAP via classify_intrinsic (src/MirLower.w:6015-6024 — both the Option and Result arms), plus void-receiver fallbacks for chained map.get(k).unwrap() (src/MirLower.w:6125-6147). lower_option_unwrap_place (src/MirLower.w:1957-1968, used by regex lowering) emits the same intrinsic. No panic branch is emitted anywhere.
  • Codegen: the OPT_UNWRAP handler (src/CodegenDispatch.w:5849-5876) extracts the payload unconditionally: Result receivers go through extract_result_payload (src/Codegen.w:5018); struct Option receivers do wl_build_extract_value(recv, 1); pointer Options return the raw pointer. None/Err therefore yields whatever bytes sit in the payload slot.
  • expect is absent end-to-end: no entry in Sema.builtin_intrinsic_method_return_type (src/SemaCheck.w:9765ff has unwrap/unwrap_or only), no classify_intrinsic entry, no MirIntrinsic. test/spec/spec_ss10_6_unwrap_and_expect.w has the expect tests commented out as "blocked: .expect() not implemented".
  • Panic substrate exists: with_panic (rt/panic_runtime.w:23-30) renders panic at <file>:<line>: <msg> to stderr and _exit(134), with fiber-aware capture; it is what assert/require/check already call with src() locations (lib/std/builtins.w:19,55-83). (with_panic_core in rt/rt_core.w:737-754 still exits 1 — exit-code unification is Bug: todo()/unreachable() lower to LLVM unreachable, not a panic (§29.10, §4.10, §14.11.1) #544; this issue targets with_panic.)
  • Debug formatting for the Err payload exists: FMT_DEBUG intrinsic → gen_debug_format (src/CodegenDispatch.w:7447-7459 dispatch, 2346-2364 implementation) handles str/struct/enum/primitive payloads.
  • Source locations: MirBuilder.source_location_operand (src/MirLower.w:1798-1812) already builds a path:line:col constant string from a node span (used for src() default args).
  • Runtime-panic test directives are supported: //! expect-exit / //! expect-stderr (build/selfhost.w:335-373).

Implementation plan

  1. Mir.w: add MirIntrinsic.OPT_EXPECT next to OPT_UNWRAP (src/Mir.w:105).
  2. Sema (src/SemaCheck.w): type expect like unwrap: in builtin_intrinsic_method_return_type (9765ff), under owner_sym == syms.option and syms.result, return generic arg 0 for expect; validate exactly one str-compatible argument (reuse builtin_arg_type_compatible as Result.context does at 9726-9729). Mirror the return type in MirLower's local intrinsic_return_type fallback (src/MirLower.w:1097-1118).
  3. MirLower.w:
    • classify_intrinsic: add "expect" → OPT_EXPECT in both the Option (6015) and Result (6021) arms.
    • When emitting OPT_UNWRAP/OPT_EXPECT calls (lower_intrinsic_call path and lower_option_unwrap_place:1957), append a trailing constant-str location operand built the same way as source_location_operand(node) so codegen gets file:line:col from the call node span without re-deriving spans. Internal callers with no user node (regex lowering at 2033) pass an empty location.
  4. Codegen (src/CodegenDispatch.w:5849-5876): replace the unconditional extraction with discriminant check + cold panic branch, for both intrinsics:
    • Struct Option receiver: extract discriminant (field 0; Some = 0, None = 1 per the OPT_IS_SOME comment at 5841), icmp eq 0 → ok_bb extracts payload exactly as today; panic_bb calls with_panic(msg, loc, 0) via call_internal_runtime_fn (src/CodegenDispatch.w:2315) followed by unreachable.
    • Result receiver (recv_is_result path): guard on the Ok tag; in panic_bb, extract the Err payload (variant index 1; payload sema type via mir_builtin_variant_payload_sema_type(recv_sema, 1)), format it with gen_debug_format (2346), and concatenate into the message.
    • Pointer Option receiver: guard recv != null (same comparison OPT_IS_SOME builds at 5843-5844).
    • Non-struct "always Some" receivers (the encoded-optional legacy path for HashMap.get chains): keep current passthrough; there is no discriminant to check at this representation. Note this in a comment.
    • Message text (§10.6): unwrap on None → called unwrap on None; unwrap on Err → called unwrap on Err: {payload:?}; expect → the user message, plus : {payload:?} on the Result path. Location goes in with_panic's file argument (renders panic at file:line:col: ...).
  5. expect message operand: lower the user's msg argument as intrinsic arg 1; codegen passes it through (concatenated with debug info on the Err path).
  6. C backend (src/CCodegen.w:75,179,4384 CcBuiltin.OPT_UNWRAP): replicate the guard+panic. If the --emit-c path cannot express it yet, it must fail loudly for unwrap-on-sum-type rather than keep the unguarded extraction (No Silent Fallbacks).
  7. No rt/Link.w changes needed (with_panic already exists on both link paths) — no bootstrap hazard beyond the normal with build && with build :fixpoint gates. The compiler source itself uses .unwrap() heavily, so any unwrap-on-None latent bug in the compiler will now panic during stage builds: triage such panics as real bugs, not as a reason to soften the check.

Edge cases: Option[str]/struct payloads (non-scalar extraction on both paths); chained map.get(k).unwrap() fallback receivers (step 4, legacy path); unwrap inside fibers (with_panic fiber capture already handles); unwrap in defer blocks (panic during unwind is process-exit anyway).

Test plan

All runtime-panic tests use //! expect-exit: 134 + //! expect-stderr: (supported, build/selfhost.w:335-373).

  • test/behavior/behav_unwrap_none_panics.w: let x: Option[i32] = None then x.unwrap() → expect-exit 134, expect-stderr called unwrap on None.
  • test/behavior/behav_unwrap_err_panics.w: let r: Result[i32, str] = Err("boom") then r.unwrap() → expect-stderr contains called unwrap on Err and "boom" (Debug repr of the payload).
  • test/behavior/behav_expect_none_panics.w: .expect("user must exist in test setup") → expect-stderr contains that message.
  • test/behavior/behav_expect_err_panics.w: message plus Err Debug info.
  • Location: one test asserts expect-stderr contains its own file name (source-location requirement of §10.6).
  • Positive: re-enable the commented-out tests in test/spec/spec_ss10_6_unwrap_and_expect.w (expect on Some/Ok returns the payload); keep existing unwrap-on-Some/Ok tests green.
  • Payload-shape coverage: unwrap on Option[str] and on a struct payload (exercises gen_debug_format struct path on Err).

Acceptance criteria

  • None.unwrap() / Err(e).unwrap() terminate with a panic message including source location (and Err Debug repr), exit code 134
  • .expect(msg) implemented on both Option and Result; panics with msg + same debug info; returns payload on Some/Ok
  • No unguarded payload extraction remains for sum-type receivers in either the LLVM or C backend
  • Existing unwrap-on-success tests (spec_ss10_, behav_option, behav_result*) unchanged and green
  • 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: 10.5.1.7, 10.6.1.19, 10.6.1.7.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Implemented in d4aea87.

    Summary:

    • Added checked Option.unwrap, Result.unwrap, Option.expect, and Result.expect panic semantics with call-site source locations.
    • Added OPT_EXPECT through sema, MIR lowering, LLVM codegen, and emit-C.
    • Replaced unchecked payload extraction with discriminant/null checks before extracting payloads; Result panic messages include Debug-formatted Err payloads.
    • Added focused behavior, compile-error, spec, and emit-C smoke coverage.

    Verification passed:

    • WITH=$PWD/out/bin/with ./out/release/bin/with build
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :fixpoint
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :test
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :test-green
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :last-green
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :install-user
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