Repository navigation
Description
Add the Error trait; error declarations implement it (§10.6, §10.8)
Summary
The standard library has no Error trait, so nothing can be bounded by E: Error, &dyn Error source chains cannot be expressed, and the spec'd impl Error for ContextError[E] where E: Error cannot be written. Error declarations (error Foo = ...) format fine via the structural Debug/Display codegen but do not implement any trait. This delivers the Error trait and the automatic implementation for error declarations.
Spec
§10.8: "Automatically implements Error, Debug, Display." (for error declarations).
§10.6:
ContextError[E]implementsErrorwhenE: Error, and the error chain is traversable via thesourcefield:impl Error for ContextError[E] where E: Error: fn display(self: &Self) -> str: self.message fn source(self: &Self) -> Option[&dyn Error]: Some(&self.source)
The trait surface implied by the spec example: fn display(self: &Self) -> str and fn source(self: &Self) -> Option[&dyn Error].
Current state
- No
Errortrait anywhere (grep -rn "trait Error" lib/ src/→ nothing).lib/std/traits.w:21-27definesDebug(debug_str) andDisplay(to_str) only. errordecls desugar in the parser to plain enumNK_TYPE_DECLnodes (src/Parser.w:2459-2503;fromform at 2465-2492,=form at 2494-2503) with no marker distinguishing them from ordinary enums — sema cannot currently auto-implement anything error-specific.- Enum Debug/Display formatting works structurally in codegen (
gen_debug_enum/gen_display_enum, dispatched fromgen_debug_format,src/CodegenDispatch.w:2346-2364), not via trait impls. Campaign verdicts: 10.6.1.26 partial ("source chain ok; Error trait absent"), 10.8.1.1 partial ("Debug/Display work, untested; Error absent"). ContextError[E]exists (lib/std/result.w:21-24) withmessage/sourcefields;.context()/.with_context()produce it (src/MirLower.w:7062-7150,src/SemaCheck.w:9708-9756).- Derive-style impl generation machinery exists and is the natural place for the auto-impl:
ct_generate_debug_derive(src/ComptimeTransform.w:1917-1975) synthesizes a method +NK_IMPL_DECLregistered viact_add_generated_impl_target. - Trait default methods,
whereclauses, and blanket impls are supported (spec §11.6; semablanket_*machinery). - Type-decl flag bits exist for packing extra decl info (
src/Ast.w:182-188,pack_type_decl_kind).
Implementation plan
- Trait definition (
lib/std/traits.w):Givepub trait Error = fn display(self: &Self) -> str fn source(self: &Self) -> Option[&dyn Error]sourcea default method body returningNone(defaults are supported, §11.6), so most impls only writedisplay. Hazard to verify early:Option[&dyn Error]requires a trait-object reference insideOption(TY_TRAIT_OBJ behind TY_REF as a generic arg). Ifensure_option_type_for/codegen cannot represent it yet, that is a compiler gap to fix loudly in this issue — do not substitute a stub signature. - Mark error decls (
src/Ast.w,src/Parser.w): add aTDK_FLAG_ERRORbit to the type-decl flag bits (src/Ast.w:182-188); set it inparse_error_declfor both forms (src/Parser.w:2492and2503). This is the durable "this enum came fromerror" signal. - Auto-impl for error decls (
src/ComptimeTransform.w): newct_generate_error_implmodeled onct_generate_debug_derive(1917-1975): for decls carryingTDK_FLAG_ERROR, generateimpl Error for Xwithfn display(self: &Self) -> strwhose body is the structural display (f"{self}"— the enum Display path codegen already implements), and rely on the trait default forsource(→None). Skip generation when the user already declared a conflicting method/impl (same guard pattern as 1925-1928). - Debug/Display trait registration for error decls: §10.8 also promises
Debug/Displayimplementations. f-string formatting already works structurally, butE: Debug/E: Displaybounds will not accept an error decl without registered impls. In the same generator, registerDebug(debug_str) andDisplay(to_str) impls whose bodies delegate to the structural formatters (bodyf"{self:?}"/f"{self}"). Verify first whetherselect_trait_implalready special-cases enums for these bounds; only generate what is actually missing. ContextError[E]impl (lib/std/result.w): add the spec'd generic impl:
impl Error for ContextError[E] where E: Errorwithdisplay → self.message,source → Some(&self.source). Requires&E where E: Errorto coerce to&dyn Errorat the impl site — exercise the existing trait-object coercion; if generic-to-dyn coercion under a bound is unsupported, that gap blocks and must be fixed here or split out loudly.- Object safety:
Errormust be usable asdyn Error(methods take&Self, return concrete types) — covered by the §11.3 object-safety rules; add it to whatever builtin-trait registration listDebug/Displayuse if such a list gates resolution (the traits.w header comment mentions compiler registration; verify and mirror). - No rt/Link changes; stdlib + parser + sema/comptime-transform only. One logical commit for the trait + auto-impl; the ContextError impl can be a follow-up commit if the dyn-coercion work is separable. Standard gates after each.
Edge cases: error decls with payload variants (display must include payloads — structural formatter already does); error X from A, B decls (also get the flag and the impl); generic user error types; user writing their own impl Error for X for an error decl (generator must skip, not collide); source() chains of length ≥ 2 (ContextError[ContextError[E]] from chained .context() calls).
Test plan
test/spec/spec_ss10_8_error_trait.w:error ParseError = UnexpectedChar(pos: usize, got: u8) | UnexpectedEofsatisfies a generic bound:fn describe[E: Error](e: &E) -> str: e.display(); assert non-empty / contains variant name.&dyn Errorusage:let e: &dyn Error = &my_err; e.display();e.source()→Nonefor a plain error decl.- chain traversal: a
Resultpassed through.context("outer")twice; walksource()from the outerContextErrordown to the root error; assert messages at each level (extendstest/spec/spec_ss10_6_error_context.w). ContextError[E]satisfiesE: Erroritself (nesting works because of the blanket-bounded impl).
test/compile_errors/error_trait_bound.w: a plain struct (no Error impl) failsfn f[E: Error](e: &E)instantiation →//! expect-error:naming the unsatisfied bound.- Display/Debug-as-traits:
fn show[E: Display](e: &E)accepts an error decl (step 4 evidence).
Acceptance criteria
-
pub trait Errorexists in the prelude withdisplay+ defaultedsource - Every
errordeclaration (both=andfromforms) satisfiesE: Error,E: Debug,E: Displaybounds with no user-written impl -
impl Error for ContextError[E] where E: Errorcompiles as written in §10.6 andsource()returns the wrapped error -
dyn Erroris object-safe and usable as&dyn Error - with build && with build :fixpoint && with build :test pass
Dependencies
- Blocks Tests: error decls coverage (§10) #498 (error-decl test coverage includes the Error-trait assertions).
- Related: Complete Option/Result combinators incl. context()/with_context() (§10.5, §10.6) #393 (
context/with_contextproduceContextError— already implemented), error ... from: transitive ? conversion (§10.9) #433 (error ... fromconversion uses the same error-decl machinery).
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 10.6.1.26, 10.8.1.1.
Activity
ehartford commentedon Jun 14, 2026
Implemented in 9c0cd0f. Added the standard Error trait, automatic Error/Debug/Display impls for error declarations, ContextError[E: Error] source chaining through &dyn Error, monomorphized generic trait vtables needed for dyn error chains, and emit-C support for generated payload-enum formatting. Added positive spec coverage for generic bounds, dyn Error, display/debug, and nested source chains, plus a negative plain-struct Error-bound test. Verification passed after rebase: build, fixpoint, full :test, and explicit :test-green.