Repository navigation
Description
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
- Add
pub trait Deref[T]tolib/std/traits.wwith a single method, preferablyfn deref(self: &Self) -> &T. Keep it nearClone/Dropand document that it is for pointer-like types only. - Intern the
Derefandderefsymbols inSemaBuiltinSymbols(src/Sema.w:95,src/Sema.w:1440) so sema can identify the language trait without string comparisons in hot paths. - Add a sema helper that computes an auto-deref adjustment chain for a receiver type. It should first strip built-in
TY_REF/TY_PTRas today, then look for a visibleDeref[T]impl on the current type, use that impl'sderefreturn type as the next step, and stop after a fixed depth such as 32. - Use that helper in both field and method lookup.
field_access_type_no_diagnosticandcheck_field_accessmust try the adjusted base type before emittingunknown field;check_method_call_parts/pipeline_method_existsmust search methods on each adjusted receiver type in order. Do not add another stdlib-specific allowlist. - Detect cycles by tracking visited type ids during the adjustment walk. Emit a clear error such as
auto-deref cycle through Deref implementationat the field/method access node. - Treat the deref result as a borrow, not a move. A
Deref.derefmethod that returns by value should be rejected as an invalidDerefimplementation because auto-deref must not hide ownership transfer. - 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]fromDeref[Bar]reliably. The currentTY_GENERIC_INSTerasure 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:
- positive field and method access through a user
Derefwrapper around a concreteUser; - nested user deref plus reference deref, e.g.
&&Wrapper[User]; - generic wrapper coverage once Fix sema generic type instantiation (TY_GENERIC_INST erasure) — prerequisite for stdlib-as-generics #391 lands, e.g.
Wrapper[i32]andWrapper[str]resolve distinctly.
Add compile-error tests:
test/compile_errors/err_deref_returns_value.wwith//! expect-error: Deref.deref must return a reference;test/compile_errors/err_deref_cycle.wwith//! expect-error: auto-deref cycle;test/compile_errors/err_deref_unknown_target_field.wto confirm a real unknown field still reports the final adjusted type.
Run with build && with build :fixpoint && with build :test.
Acceptance criteria
Derefis part ofstd.traitsand 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
Derefimplementations work without stdlib-specific compiler allowlists. - Invalid
Derefimplementations and deref cycles fail loudly with diagnostics. with build && with build :fixpoint && with build :testpass.
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
ehartford commentedon Jun 13, 2026
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.