Repository navigation
Description
Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6)
Summary
The §10.5/§10.6 combinator tables are required standard-library surface. Roughly half is implemented (as compiler-lowered intrinsics — lib/std/option.w/result.w deliberately hold only the type definitions); the rest fails to compile. This completes the missing 14 methods. Verify-first note from the original body is resolved: context()/with_context() do exist and are tested — the medium-confidence survey claim was stale; the flagship §1.7/§10.6 error-context story already works.
Spec
§10.5 (Option) and §10.6 (Result) combinator tables ("Standard Library Requirement"). Missing today:
| Type | Method | Signature |
|---|---|---|
| Option | or_else |
(fn() -> Option[T]) -> Option[T] |
| Option | unwrap_or_else |
(fn() -> T) -> T |
| Option | zip |
(Option[U]) -> Option[(T, U)] |
| Option | unzip |
() -> (Option[A], Option[B]) |
| Option | flatten |
() -> Option[T] where Self = Option[Option[T]] |
| Option | cloned |
() -> Option[T] where T: Clone |
| Option | inspect |
(fn(&T)) -> Option[T] |
| Result | and_then |
(fn(T) -> Result[U, E]) -> Result[U, E] |
| Result | or_else |
(fn(E) -> Result[T, F]) -> Result[T, F] |
| Result | unwrap_or_else |
(fn(E) -> T) -> T |
| Result | ok |
() -> Option[T] |
| Result | err |
() -> Option[E] |
| Result | inspect |
(fn(&T)) -> Result[T, E] |
| Result | inspect_err |
(fn(&E)) -> Result[T, E] |
(expect from both tables is implemented under #545 together with the unwrap panic fix.)
Current state
- Implemented Option:
map/and_then(MirBuilder.lower_option_combinator_method,src/MirLower.w:7001-7061; semaoption_combinator_return_type,src/SemaCheck.w:9672-9707),filter/is_some/is_none/unwrapintrinsics (classify_intrinsic,src/MirLower.w:6015-6020),unwrap_or(lower_unwrap_or_method,src/MirLower.w:7162ff, dispatched at 6120-6121),transpose(src/MirLower.w:6698ff). - Implemented Result:
map/map_err/context/with_context(lower_result_combinator_method,src/MirLower.w:7062-7150; semaresult_combinator_return_type,src/SemaCheck.w:9708-9756),transpose(src/MirLower.w:6781ff),unwrap_or,unwrap/is_okintrinsics (src/MirLower.w:6021-6024), plus auto enum accessorsis_ok/is_err/as_ok/as_err(Sema.enum_accessor_variant_for_method,src/SemaCheck.w:6476-6515; lowered atsrc/MirLower.w:6410ff). ContextError[E]exists (lib/std/result.w:21-24); context behavior is covered bytest/spec/spec_ss10_6_error_context.w— the original issue's "context methods not found" is stale.- Campaign gaps map to the table above: Option 10.5.1.4/.6/.12/.13/.14/.15/.16; Result 10.6.1.3/.4/.6/.11/.12/.13/.14.
- Method dispatch happens in
lower_method_call(src/MirLower.w:6105-6121) viais_option_type/is_result_typename gates; sema typing incheck_method_callreachesoption_combinator_return_type/result_combinator_return_type. - Watch out:
zipalready classifies toMirIntrinsic.ITER_ZIPfor iterator receivers (src/MirLower.w:5929,5948) — Option receivers must dispatch before the iterator path.lib/std/task.w:43,103already callsresult.err().unwrap(), currently uncompilable if instantiated —Result.err()makes those combinators real (see Await combinators: cancel+join when cancelled mid-flight (§14.11.1) #421).
Implementation plan
Phased; each phase passes the full gates independently.
Phase A — Result closure combinators (and_then, or_else, unwrap_or_else):
src/SemaCheck.wresult_combinator_return_type(9708): add arms —and_then: argfn(T) -> Result[U, E2], validateE2compatible withE, return the closure's return type;or_else: argfn(E) -> Result[T, F], returnensure_result_type_for(ok_ty, F-from-closure);unwrap_or_else: argfn(E) -> T2compatible withT, returnok_ty. Error-message style matches existing arms ("Result.and_then() expects a function argument"etc.).src/MirLower.w: extend the dispatch gate at 6108 andlower_result_combinator_method:and_thenmirrors the Optionand_thenarm (ok-branch calls the closure and assigns the whole result, 7050-7052 pattern; err-branch re-wraps payload as today);or_elseis its dual (err-branch calls closure, ok-branch re-wraps);unwrap_or_elsefollowslower_unwrap_or_method's skeleton with a closure call in the err block (closure receives the Err payload).
Phase B — structural methods (Result.ok/err; Option zip/unzip/flatten):
3. Sema: ok() → ensure_option_type_for(ok_ty); err() → ensure_option_type_for(err_ty); zip(other: Option[U]) → ensure_option_type_for(ensure_tuple_type([T, U])); unzip() (require T = tuple of 2) → ensure_tuple_type([Option[A], Option[B]]); flatten() (require T = Option[U]) → T; diagnostics for shape misuse: "Option.flatten() requires Option[Option[T]]", "Option.unzip() requires Option[(A, B)]" (same voice as Option.transpose() errors, 9672-9682).
4. MirLower: no closures — discriminant switch + new_downcast_place/assign_enum_variant_to_place constructions, in the style of lower_option_transpose_method (6698) / lower_result_transpose_method (6781). Option-receiver zip must be gated in lower_method_call before classify_intrinsic returns ITER_ZIP.
Phase C — inspect/inspect_err/cloned and Option or_else/unwrap_or_else:
5. Sema: inspect: arg fn(&T) → return recv_type; inspect_err: arg fn(&E) → recv_type; cloned: no args, T: Clone (or copy) → recv_type; Option or_else: fn() -> Option[T] → recv_type; Option unwrap_or_else: fn() -> T → payload type.
6. MirLower: inspect/inspect_err call the closure with a shared-ref temp of the payload (the auto-ref pattern of lower_optional_chain_receiver_operand, src/MirLower.w:7526-7536) then pass the original receiver value through to the result place; cloned maps payload through .clone() (reuse the NK_COPY_ARG clone-emission pattern, src/MirLower.w:8410-8416).
7. Update MirLower's intrinsic_return_type fallback table (src/MirLower.w:1097-1118) for any method reachable through void-typed chained receivers.
Edge cases: non-Copy payloads (operand kinds via is_copy, as existing arms do); closures with captured state (already exercised by map/filter); laziness — or_else/unwrap_or_else/with_context closures must not run on the happy path (block structure guarantees it; tests assert it); nested generics in zip tuples; inspect returning the receiver must not double-move it (materialize once, copy/move out of the same place).
Test plan
test/spec/spec_ss10_5_option_combinators_complete.w: every new Option method × (Some, None):or_elsefallback used only on None (side-effect assert via closure that callsassert(false)on the wrong path);unwrap_or_elselazy;zipSome+Some → Some(tuple), Some+None → None;unzipround-tripszip;flattenonSome(Some(v))/Some(None)/None;clonedyields an independent value;inspectobserves payload and returns the original.test/spec/spec_ss10_6_result_combinators_complete.w:and_thenOk-chain and Err-shortcircuit;or_elserecovery with new error typeF;unwrap_or_elsereceives the Err payload;ok()/err()on both variants;inspect/inspect_errfire on exactly one variant each and pass the value through.- Combinator pipeline test reproducing the §10.6 example shape:
read.map_err(...).and_then(...).unwrap_or_else(...). test/compile_errors/:flattenonOption[i32]→ expect-errorrequires Option[Option;zipwith non-Option arg;Result.and_thenclosure returning mismatched error type;unzipon non-tuple payload.- Regression:
spec_ss10_3_option_result_combinators.w,spec_ss10_5_sequence_traverse_transpose.w,spec_ss10_6_error_context.wstay green.
Acceptance criteria
- All §10.5/§10.6 table methods compile and behave per the tables (with
expectdelivered by Bug: .unwrap()/.expect() do not panic on None/Err — return garbage (§10.5, §10.6) #545) - Closure-taking combinators are lazy on the non-relevant variant
-
Option.zipdoes not regress iteratorzip -
lib/std/task.w'sresult.err().unwrap()call sites compile when instantiated - with build && with build :fixpoint && with build :test pass
Dependencies
- Overlaps Bug: .unwrap()/.expect() do not panic on None/Err — return garbage (§10.5, §10.6) #545 (
unwrap/expectpanic semantics — implemented there; do not duplicate). - Soft-blocks Await combinators: cancel+join when cancelled mid-flight (§14.11.1) #421 (
task.wcombinators rely onResult.err()). - Related: Add the Error trait; error declarations implement it (§10.6, §10.8) #434 (
ContextError/Error trait), Tests: optional chaining coverage (§10) #515/Tests: result discard coverage (§10) #521 (tests exercising these methods).
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 10.5.1.1, 10.5.1.4, 10.5.1.6, 10.5.1.8, 10.5.1.12–10.5.1.16, 10.6.1.3, 10.6.1.4, 10.6.1.6, 10.6.1.8, 10.6.1.11–10.6.1.14, 10.6.1.18, 10.6.1.20.
Activity
ehartford commentedon Jun 10, 2026
Scope correction from the requirements campaign (2026-06-10):
context()/with_context()are now implemented and tested (spec_ss10_6_error_context.wpasses) — drop them from this issue's list. Confirmed still absent on v0.15.1: Optionor_else/unwrap_or_else/expect/zip/unzip/flatten/cloned/inspect; Resultand_then/or_else/unwrap_or_else/expect/ok/err/inspect/inspect_err. Related new issues: #434 (Error trait), #444 (unwrap/expect don't panic — bug).ehartford commentedon Jun 10, 2026
Correction to the previous comment: the unwrap/expect-don't-panic bug is #545 (not #444). #434 (Error trait) was correct.
ehartford commentedon Jun 14, 2026
Implemented in 6c40336. Completed the §10.5/§10.6 Option/Result combinator surface: Option.or_else, unwrap_or_else, zip, unzip, flatten, cloned, inspect; Result.and_then, or_else, unwrap_or_else, ok, err, inspect, inspect_err. Added positive spec coverage for all new methods plus negative shape/type tests. Verification passed: build, fixpoint, full test suite, and explicit test-green.