Skip to content

Add the Error trait; error declarations implement it (§10.6, §10.8) #434

Closed

Description

@ehartford

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] implements Error when E: Error, and the error chain is traversable via the source field:

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 Error trait anywhere (grep -rn "trait Error" lib/ src/ → nothing). lib/std/traits.w:21-27 defines Debug (debug_str) and Display (to_str) only.
  • error decls desugar in the parser to plain enum NK_TYPE_DECL nodes (src/Parser.w:2459-2503; from form 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 from gen_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) with message/source fields; .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_DECL registered via ct_add_generated_impl_target.
  • Trait default methods, where clauses, and blanket impls are supported (spec §11.6; sema blanket_* machinery).
  • Type-decl flag bits exist for packing extra decl info (src/Ast.w:182-188, pack_type_decl_kind).

Implementation plan

  1. Trait definition (lib/std/traits.w):
    pub trait Error =
        fn display(self: &Self) -> str
        fn source(self: &Self) -> Option[&dyn Error]
    
    Give source a default method body returning None (defaults are supported, §11.6), so most impls only write display. Hazard to verify early: Option[&dyn Error] requires a trait-object reference inside Option (TY_TRAIT_OBJ behind TY_REF as a generic arg). If ensure_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.
  2. Mark error decls (src/Ast.w, src/Parser.w): add a TDK_FLAG_ERROR bit to the type-decl flag bits (src/Ast.w:182-188); set it in parse_error_decl for both forms (src/Parser.w:2492 and 2503). This is the durable "this enum came from error" signal.
  3. Auto-impl for error decls (src/ComptimeTransform.w): new ct_generate_error_impl modeled on ct_generate_debug_derive (1917-1975): for decls carrying TDK_FLAG_ERROR, generate impl Error for X with fn display(self: &Self) -> str whose body is the structural display (f"{self}" — the enum Display path codegen already implements), and rely on the trait default for source (→ None). Skip generation when the user already declared a conflicting method/impl (same guard pattern as 1925-1928).
  4. Debug/Display trait registration for error decls: §10.8 also promises Debug/Display implementations. f-string formatting already works structurally, but E: Debug / E: Display bounds will not accept an error decl without registered impls. In the same generator, register Debug (debug_str) and Display (to_str) impls whose bodies delegate to the structural formatters (body f"{self:?}" / f"{self}"). Verify first whether select_trait_impl already special-cases enums for these bounds; only generate what is actually missing.
  5. ContextError[E] impl (lib/std/result.w): add the spec'd generic impl:
    impl Error for ContextError[E] where E: Error with display → self.message, source → Some(&self.source). Requires &E where E: Error to coerce to &dyn Error at 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.
  6. Object safety: Error must be usable as dyn Error (methods take &Self, return concrete types) — covered by the §11.3 object-safety rules; add it to whatever builtin-trait registration list Debug/Display use if such a list gates resolution (the traits.w header comment mentions compiler registration; verify and mirror).
  7. 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) | UnexpectedEof satisfies a generic bound: fn describe[E: Error](e: &E) -> str: e.display(); assert non-empty / contains variant name.
    • &dyn Error usage: let e: &dyn Error = &my_err; e.display(); e.source() → None for a plain error decl.
    • chain traversal: a Result passed through .context("outer") twice; walk source() from the outer ContextError down to the root error; assert messages at each level (extends test/spec/spec_ss10_6_error_context.w).
    • ContextError[E] satisfies E: Error itself (nesting works because of the blanket-bounded impl).
  • test/compile_errors/error_trait_bound.w: a plain struct (no Error impl) fails fn 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 Error exists in the prelude with display + defaulted source
  • Every error declaration (both = and from forms) satisfies E: Error, E: Debug, E: Display bounds with no user-written impl
  • impl Error for ContextError[E] where E: Error compiles as written in §10.6 and source() returns the wrapped error
  • dyn Error is object-safe and usable as &dyn Error
  • with build && with build :fixpoint && with build :test pass

Dependencies

Traceability

From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 10.6.1.26, 10.8.1.1.

Activity

  1. ehartford commented on Jun 14, 2026

    @ehartford
    ContributorAuthor

    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.

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