Repository navigation
Description
Implement user Try trait for ? (§10.2, §11.7)
Summary
? is hardcoded to Option/Result; the spec says it is controlled by the Try syntax trait, which user types (parser results, validation types) can implement. Neither Try nor ControlFlow exists. Kept spec'd by ruling (docs/completed/spec-impl-unalignment.md §E item 9, EXECUTED → this issue); low priority — no flagship consumer. This delivers the trait, the ControlFlow carrier, and ? dispatch through user impls, with the §11.7 ParseResult example as the conformance test.
Spec
§10.2: "The ? operator is controlled by the Try syntax trait (§11.7). Result and Option implement Try in the standard library. User types can also implement Try to participate in ? propagation."
§11.7 syntax-trait table: Try[T, E] unlocks expr?. Example (normative shape):
enum ParseResult[T]:
ParseOk(T, remaining: str)
ParseErr(msg: str, pos: usize)
impl Try[T, ParseError] for ParseResult[T]:
fn branch(self: Self) -> ControlFlow[ParseError, T]:
match self:
ParseOk(v, _) => ControlFlow.Continue(v)
ParseErr(m, p) => ControlFlow.Break(ParseError { msg: m, pos: p })
Design constraints (§11.7): the syntax-trait set is fixed and closed; resolution is always static.
Current state
- Sema:
check_unaryUOP_TRY (src/SemaCheck.w:4310-4335) accepts only Option/Result viatry_unwrapped_type; anything else → "? operator requires an Option or Result with a single success payload". Error-type conversion for Result goes througherror_conversion_variant(src/SemaCheck.w:6355). - MIR:
lower_question_mark(src/MirLower.w:6486-6566) handles exactly three shapes: Result (Err re-wrap + return), Option (None return), raw passthrough. No trait dispatch. - No
Trytrait, noControlFlowtype anywhere inlib/orsrc/(verified by grep; campaign 10.2.1.3 absent, 10.2.1.4 partial, 10.2.1.5 absent). - Trait machinery available: blanket impls with bounds (
blanket_*in sema), generic impl type params,select_trait_impl. - Spec gap to resolve while implementing:
Try.branch()alone cannot rebuild the carrier for the early return. In the §11.7 example,parse_pairreturnsParseResult[(Expr, Expr)]; whenparse_expr(input)?breaks with aParseError, the compiler must construct aParseResult.ParseErr(...)from thatParseError— the spec defines no constructor for this direction (Rust splits this intoTry/FromResidual). The trait needs a second member, e.g. a staticfn from_break(b: E) -> Self, or an equivalent ruling.
Implementation plan
Sizing honesty: this is a large, cross-cutting feature. Phase it; each phase gates green.
Phase 0 — design ruling: settle the residual-construction question above with the maintainer: recommend extending the closed trait to
pub trait Try[T, E] =
fn branch(self: Self) -> ControlFlow[E, T]
fn from_break(b: E) -> Self
and record the delta in the spec-feedback log. Everything below assumes this shape.
Phase 1 — stdlib types (lib/std/traits.w):
pub enum ControlFlow[B, C] { Continue(C) | Break(B) }(also satisfies the §11.7 prose mention; name must be importable via the prelude).pub trait Try[T, E]as above. Do not write With-source impls for Option/Result — their?lowering stays on the existing fast path (semantically "implements Try in the standard library" per §10.2; document this in a comment).
Phase 2 — sema dispatch (src/SemaCheck.w):
3. In check_unary UOP_TRY (4310-4335), after the Option/Result paths fail: select_trait_impl(operand_type, Try). If found, the expression type is the impl's T argument (Continue payload). Record the resolution for MIR in a node-keyed map (pattern: comp_resolved / typed_expr_types).
4. Enclosing-function check: the return type must be (a) the same user Try carrier whose impl's Break type matches the operand impl's Break type exactly (v1: exact match; conversion via error_conversion_chain can come later), or (b) Result/Option per existing rules when the Break type lines up with their error/none shape. Diagnostics: update the fallback message to "? operator requires an Option, Result, or a type implementing Try"; add "? on X requires the enclosing function to return a Try-compatible type (found Y)".
Phase 3 — MIR lowering (src/MirLower.w):
5. In lower_question_mark (6486), add a third branch keyed off the sema-recorded impl: lower operand.branch() as a normal resolved method call; switch on the ControlFlow discriminant (Continue index via enum_variant_index_for_type); Continue path: downcast payload → result operand; Break path: downcast Break payload, call the return-carrier's from_break (static call, resolved at sema time), assign to the return place, then emit_errdefers_for_return/emit_defers_for_return/emit_drops_for_return + TK_RETURN exactly as the existing fail path (6549-6552).
6. Generic impls (impl[T] Try[T, ParseError] for ParseResult[T]) must monomorphize through the existing generic-instantiation path; verify with the conformance test before claiming done.
Phase 4 — guard rails:
7. ? in defer stays rejected (4312-4314). Static resolution only — no dyn fallback. Trait stays in the closed syntax-trait set: no user-defined syntax hooks beyond implementing Try.
Test plan
test/spec/spec_ss11_7_try_trait.w: the §11.7 ParseResult example, adapted minimally to current syntax:parse_pairsucceeds (both?continue) and fails (first?breaks; assert returnedParseErrcarries msg/pos). Generic payload instantiated at two types.?through a non-generic user Try type (validation-style carrier) in a function returning the same carrier.- Mixed: user-Try operand inside a function returning
Resultwith matching Break/error type (if Phase 2(b) is in scope; otherwise negative-test it). test/compile_errors/try_trait_negative.w:?on a type with no Try impl → expect-error "requires an Option, Result, or a type implementing Try";?where the enclosing return type's Break type mismatches → expect-error naming both types;?in defer unchanged.- Regression: all existing
?tests (behav_option_question_mark, behav_error_propagation, errdefer_question_mark) green — the Option/Result fast path must be untouched.
Acceptance criteria
-
ControlFlow[B, C]andTry[T, E]exist in the prelude -
?dispatches statically through userTryimpls; §11.7 ParseResult example compiles and behaves as written - Early return reconstructs the carrier via the agreed residual mechanism (
from_breakor per ruling) - Option/Result
?behavior and diagnostics unchanged (modulo the extended fallback message) - Design delta (trait shape) recorded for the spec
- with build && with build :fixpoint && with build :test pass
Dependencies
- Related: error ... from: transitive ? conversion (§10.9) #433 (error conversion in
?— shareslower_question_mark; land error ... from: transitive ? conversion (§10.9) #433 first to avoid merge churn in the same function). No hard blockers.
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 10.2.1.3, 10.2.1.4, 10.2.1.5. Ruling: docs/completed/spec-impl-unalignment.md §E item 9 (EXECUTED → #408).
Activity
ehartford commentedon Jun 13, 2026
Implemented in 36fcfaf. Added the public ControlFlow and Try surface, user-carrier ? sema checks, MIR lowering through branch/from_break, generic enum payload support needed by Try carriers, and positive/negative coverage for generic/non-generic Try propagation and invalid usages. Verification passed: build, fixpoint, full test suite, and test-green.