Skip to content

Implement user Deref trait for auto-deref (§3.7) #407

Closed

Description

@ehartford

Summary

Implement the user-facing Deref trait promised by §3.7 so smart-pointer-like user types get the same field and method transparency as built-in references and future Box/Rc/Arc. Today auto-deref only strips &T, raw pointers, and references inside sema, so the spec promise is not reachable for library or user abstractions. This keeps the ergonomics rule consistent: if a type models dereference safely, users should not have to spell manual unwrap/access boilerplate at every field and method call.

Spec

§3.7 says the compiler automatically follows references, boxes, and smart pointers to find fields and methods, and that auto-deref applies to &T, Box[T], Arc[T], Rc[T], and any type implementing the Deref trait. The examples at docs/with-specification.md:641 and docs/with-specification.md:647 show repeated dereferencing through Box[User], &User, and &&User until .name is found.

The missing user-trait form should behave equivalently:

type Handle[T] { ptr: *const T }

impl[T] Deref[T] for Handle[T]:
    fn deref(self: &Self) -> &T:
        unsafe { self.ptr as &T }

let h = Handle[User].new(user)
let name = h.name
let label = h.label()

The chain must be finite and deterministic. If deref expansion cycles or exceeds the compiler limit, sema must report a diagnostic rather than silently falling back to an unknown-field error.

Current state

The original issue says auto-deref is hardcoded; that is still accurate. Sema.auto_deref_ref_ptr_type strips only TY_PTR and TY_REF, with a hard limit of 32 layers, and returns the first non-pointer/reference type without consulting trait impls (src/SemaCheck.w:5448). Field access calls that helper before struct/tuple/array/string/enum lookup (src/SemaCheck.w:5431, src/SemaCheck.w:5522). Method dispatch uses separate lookup paths and a generic-collection allowlist (src/SemaCheck.w:7286, src/SemaCheck.w:7302) rather than a general deref adjustment chain.

lib/std/traits.w defines core language traits such as Clone, Drop, Iter, and indexing traits, but there is no Deref trait declaration today (lib/std/traits.w:33, lib/std/traits.w:171). The prelude imports std.traits ambiently (lib/std/prelude.w:9), so adding the trait there is the right user-visible surface once sema recognizes it.

The current spec test for §3.7 covers references and raw pointers only (test/spec/spec_ss03_7_auto_dereferencing.w:9, test/spec/spec_ss03_7_auto_dereferencing.w:35). It does not cover a user-defined smart pointer, which is the gap captured here. docs/completed/spec-impl-unalignment.md:73 and docs/completed/spec-impl-unalignment.md:313 explicitly keep user Deref spec'd instead of deleting it.

Implementation plan

  1. Add pub trait Deref[T] to lib/std/traits.w with a single method, preferably fn deref(self: &Self) -> &T. Keep it near Clone/Drop and document that it is for pointer-like types only.
  2. Intern the Deref and deref symbols in SemaBuiltinSymbols (src/Sema.w:95, src/Sema.w:1440) so sema can identify the language trait without string comparisons in hot paths.
  3. Add a sema helper that computes an auto-deref adjustment chain for a receiver type. It should first strip built-in TY_REF/TY_PTR as today, then look for a visible Deref[T] impl on the current type, use that impl's deref return type as the next step, and stop after a fixed depth such as 32.
  4. Use that helper in both field and method lookup. field_access_type_no_diagnostic and check_field_access must try the adjusted base type before emitting unknown field; check_method_call_parts/pipeline_method_exists must search methods on each adjusted receiver type in order. Do not add another stdlib-specific allowlist.
  5. Detect cycles by tracking visited type ids during the adjustment walk. Emit a clear error such as auto-deref cycle through Deref implementation at the field/method access node.
  6. Treat the deref result as a borrow, not a move. A Deref.deref method that returns by value should be rejected as an invalid Deref implementation because auto-deref must not hide ownership transfer.
  7. Sequence this after Fix sema generic type instantiation (TY_GENERIC_INST erasure) — prerequisite for stdlib-as-generics #391 if the generic trait lookup cannot distinguish Deref[Foo] from Deref[Bar] reliably. The current TY_GENERIC_INST erasure is the same root cause called out in the original body's "after generics fix" note.

Test plan

Add or extend test/spec/spec_ss03_7_auto_dereferencing.w with:

Add compile-error tests:

  • test/compile_errors/err_deref_returns_value.w with //! expect-error: Deref.deref must return a reference;
  • test/compile_errors/err_deref_cycle.w with //! expect-error: auto-deref cycle;
  • test/compile_errors/err_deref_unknown_target_field.w to confirm a real unknown field still reports the final adjusted type.

Run with build && with build :fixpoint && with build :test.

Acceptance criteria

  • Deref is part of std.traits and available through the prelude.
  • Field access, method calls, and pipeline method lookup all use the same auto-deref adjustment chain.
  • Built-in &T/&&T/raw-pointer behavior covered by existing tests still passes.
  • User Deref implementations work without stdlib-specific compiler allowlists.
  • Invalid Deref implementations and deref cycles fail loudly with diagnostics.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

#391 is a prerequisite for generic Deref[T] correctness. #475 and #470 should use this instead of adding separate compiler-only auto-deref paths for Box, Rc, and Arc.

Activity

  1. ehartford commented on Jun 13, 2026

    @ehartford
    ContributorAuthor

    Implemented in 3862114. Added std.traits.Deref[T], semantic/MIR/codegen support for user-defined auto-deref through field, method, and pipeline lookup, compile-time diagnostics for non-reference deref returns and cycles, plus positive and negative coverage. Verification passed: build, fixpoint, full test suite, test-green, last-green, and install-user.

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