Repository navigation
Description
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 theDebugrepresentation of theNone/Errvalue..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_callroutesunwraptoMirIntrinsic.OPT_UNWRAPviaclassify_intrinsic(src/MirLower.w:6015-6024— both theOptionandResultarms), plus void-receiver fallbacks for chainedmap.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_UNWRAPhandler (src/CodegenDispatch.w:5849-5876) extracts the payload unconditionally: Result receivers go throughextract_result_payload(src/Codegen.w:5018); struct Option receivers dowl_build_extract_value(recv, 1); pointer Options return the raw pointer.None/Errtherefore yields whatever bytes sit in the payload slot. expectis absent end-to-end: no entry inSema.builtin_intrinsic_method_return_type(src/SemaCheck.w:9765ffhasunwrap/unwrap_oronly), noclassify_intrinsicentry, noMirIntrinsic.test/spec/spec_ss10_6_unwrap_and_expect.whas the expect tests commented out as "blocked: .expect() not implemented".- Panic substrate exists:
with_panic(rt/panic_runtime.w:23-30) renderspanic at <file>:<line>: <msg>to stderr and_exit(134), with fiber-aware capture; it is whatassert/require/checkalready call withsrc()locations (lib/std/builtins.w:19,55-83). (with_panic_coreinrt/rt_core.w:737-754still 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 targetswith_panic.) - Debug formatting for the Err payload exists:
FMT_DEBUGintrinsic →gen_debug_format(src/CodegenDispatch.w:7447-7459dispatch,2346-2364implementation) handles str/struct/enum/primitive payloads. - Source locations:
MirBuilder.source_location_operand(src/MirLower.w:1798-1812) already builds apath:line:colconstant string from a node span (used forsrc()default args). - Runtime-panic test directives are supported:
//! expect-exit///! expect-stderr(build/selfhost.w:335-373).
Implementation plan
- Mir.w: add
MirIntrinsic.OPT_EXPECTnext toOPT_UNWRAP(src/Mir.w:105). - Sema (
src/SemaCheck.w): typeexpectlikeunwrap: inbuiltin_intrinsic_method_return_type(9765ff), underowner_sym == syms.optionandsyms.result, return generic arg 0 forexpect; validate exactly one str-compatible argument (reusebuiltin_arg_type_compatibleasResult.contextdoes at 9726-9729). Mirror the return type in MirLower's localintrinsic_return_typefallback (src/MirLower.w:1097-1118). - MirLower.w:
classify_intrinsic: add"expect"→OPT_EXPECTin both theOption(6015) andResult(6021) arms.- When emitting
OPT_UNWRAP/OPT_EXPECTcalls (lower_intrinsic_callpath andlower_option_unwrap_place:1957), append a trailing constant-str location operand built the same way assource_location_operand(node)so codegen getsfile:line:colfrom the call node span without re-deriving spans. Internal callers with no user node (regex lowering at 2033) pass an empty location.
- 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 = 1per theOPT_IS_SOMEcomment at 5841),icmp eq 0→ok_bbextracts payload exactly as today;panic_bbcallswith_panic(msg, loc, 0)viacall_internal_runtime_fn(src/CodegenDispatch.w:2315) followed by unreachable. - Result receiver (
recv_is_resultpath): guard on the Ok tag; inpanic_bb, extract the Err payload (variant index 1; payload sema type viamir_builtin_variant_payload_sema_type(recv_sema, 1)), format it withgen_debug_format(2346), and concatenate into the message. - Pointer Option receiver: guard
recv != null(same comparisonOPT_IS_SOMEbuilds at 5843-5844). - Non-struct "always Some" receivers (the encoded-optional legacy path for
HashMap.getchains): 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 inwith_panic'sfileargument (renderspanic at file:line:col: ...).
- Struct Option receiver: extract discriminant (field 0;
expectmessage operand: lower the user'smsgargument as intrinsic arg 1; codegen passes it through (concatenated with debug info on the Err path).- C backend (
src/CCodegen.w:75,179,4384CcBuiltin.OPT_UNWRAP): replicate the guard+panic. If the--emit-cpath cannot express it yet, it must fail loudly for unwrap-on-sum-type rather than keep the unguarded extraction (No Silent Fallbacks). - No rt/Link.w changes needed (
with_panicalready exists on both link paths) — no bootstrap hazard beyond the normalwith build && with build :fixpointgates. 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] = Nonethenx.unwrap()→ expect-exit 134, expect-stderrcalled unwrap on None.test/behavior/behav_unwrap_err_panics.w:let r: Result[i32, str] = Err("boom")thenr.unwrap()→ expect-stderr containscalled unwrap on Errand"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 onSome/Okreturns the payload); keep existing unwrap-on-Some/Ok tests green. - Payload-shape coverage: unwrap on
Option[str]and on a struct payload (exercisesgen_debug_formatstruct 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 withmsg+ 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
- Bug: todo()/unreachable() lower to LLVM unreachable, not a panic (§29.10, §4.10, §14.11.1) #544 (panic exit-code unification for
with_panic_core/todo()/unreachable()) — referenced, not a blocker: this issue useswith_panic, which already exits 134. - Overlaps Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393 (its combinator list also names
expect10.5.1.8/10.6.1.8 — implemented here, not there). - Tests: optional chaining coverage (§10) #515/Tests: result discard coverage (§10) #521 test suites exercise unwrap and benefit from real panic semantics.
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
Requirements triage campaign: checkbox, verdict, and issue-link every…
ehartford commentedon Jun 12, 2026
Implemented in d4aea87.
Summary:
Verification passed: