Skip to content

Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393

Closed

Description

@ehartford

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; sema option_combinator_return_type, src/SemaCheck.w:9672-9707), filter/is_some/is_none/unwrap intrinsics (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; sema result_combinator_return_type, src/SemaCheck.w:9708-9756), transpose (src/MirLower.w:6781ff), unwrap_or, unwrap/is_ok intrinsics (src/MirLower.w:6021-6024), plus auto enum accessors is_ok/is_err/as_ok/as_err (Sema.enum_accessor_variant_for_method, src/SemaCheck.w:6476-6515; lowered at src/MirLower.w:6410ff).
  • ContextError[E] exists (lib/std/result.w:21-24); context behavior is covered by test/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) via is_option_type/is_result_type name gates; sema typing in check_method_call reaches option_combinator_return_type/result_combinator_return_type.
  • Watch out: zip already classifies to MirIntrinsic.ITER_ZIP for iterator receivers (src/MirLower.w:5929,5948) — Option receivers must dispatch before the iterator path. lib/std/task.w:43,103 already calls result.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):

  1. src/SemaCheck.w result_combinator_return_type (9708): add arms — and_then: arg fn(T) -> Result[U, E2], validate E2 compatible with E, return the closure's return type; or_else: arg fn(E) -> Result[T, F], return ensure_result_type_for(ok_ty, F-from-closure); unwrap_or_else: arg fn(E) -> T2 compatible with T, return ok_ty. Error-message style matches existing arms ("Result.and_then() expects a function argument" etc.).
  2. src/MirLower.w: extend the dispatch gate at 6108 and lower_result_combinator_method: and_then mirrors the Option and_then arm (ok-branch calls the closure and assigns the whole result, 7050-7052 pattern; err-branch re-wraps payload as today); or_else is its dual (err-branch calls closure, ok-branch re-wraps); unwrap_or_else follows lower_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_else fallback used only on None (side-effect assert via closure that calls assert(false) on the wrong path); unwrap_or_else lazy; zip Some+Some → Some(tuple), Some+None → None; unzip round-trips zip; flatten on Some(Some(v))/Some(None)/None; cloned yields an independent value; inspect observes payload and returns the original.
  • test/spec/spec_ss10_6_result_combinators_complete.w: and_then Ok-chain and Err-shortcircuit; or_else recovery with new error type F; unwrap_or_else receives the Err payload; ok()/err() on both variants; inspect/inspect_err fire 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/: flatten on Option[i32] → expect-error requires Option[Option; zip with non-Option arg; Result.and_then closure returning mismatched error type; unzip on non-tuple payload.
  • Regression: spec_ss10_3_option_result_combinators.w, spec_ss10_5_sequence_traverse_transpose.w, spec_ss10_6_error_context.w stay green.

Acceptance criteria

Dependencies

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

  1. ehartford commented on Jun 10, 2026

    @ehartford
    ContributorAuthor

    Scope correction from the requirements campaign (2026-06-10): context()/with_context() are now implemented and tested (spec_ss10_6_error_context.w passes) — drop them from this issue's list. Confirmed still absent on v0.15.1: Option or_else/unwrap_or_else/expect/zip/unzip/flatten/cloned/inspect; Result and_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).

  2. ehartford commented on Jun 10, 2026

    @ehartford
    ContributorAuthor

    Correction to the previous comment: the unwrap/expect-don't-panic bug is #545 (not #444). #434 (Error trait) was correct.

  3. ehartford commented on Jun 14, 2026

    @ehartford
    ContributorAuthor

    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.

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