Skip to content

Language design: should instance-method bodies access fields without writing self.? (56 of 1,334 tokens in nbody) #1930

Closed

Description

@ehartford

Summary

D7 removed the declared receiver (mut fn advance(dt: f64)), but instance-method bodies still have to write self. before every field access. Under the mission's first law, is self. in self.bodies a character the program has already determined? Swift, which D7 names as its model, lets instance methods refer to fields by bare name.

Measurement

This came up while rewriting benchmarks/workloads/nbody/nbody.w in current idiomatic With: D7 receivers, positional struct literals, compound assignment, for b in self.bodies, and float consts now that #1668 is closed. The rewrite gives the same checksum (-0.169059907).

nbody, o200k tokens
idiomatic With 1,334
Go 1,293
Rust 1,372
the self. prefixes alone (28 sites) 56

Safe With has no &mut parameters (§3.1), so code that mutates shared state has to be a mut fn on a wrapper type. That puts self. on every access in exactly the hot, field-heavy code:

extend System:
    mut fn advance(dt: f64):
        let n = self.bodies.len()
        for i in 0..n:
            for j in (i + 1)..n:
                let dx = self.bodies[i].x - self.bodies[j].x
                ...
                self.bodies[i].vx -= dx * mj

With bare field access, the method would read bodies[i].vx -= dx * mj.

The case against

A bare name inside a method could mean either a local or a field. That is the "two meanings remain" situation where the mission says the programmer should spell the choice. Swift resolves it with a shadowing rule: a local wins, and self.x is required only when it is shadowed. Whether that rule counts as "one meaning forced" or as a hidden default between meanings is a ruling question, so I'm filing this as a design question rather than a bug.

Relation to existing work

  • D7 / docs/proposals/eliminate-self.md §5 deliberately keeps self.field resolving against the synthesised binding. This issue asks whether the next step is in scope; it does not reopen D7.

Activity

  1. ehartford commented on Oct 3, 2026

    @ehartford
    ContributorAuthor

    Decision brief (coordinator, 2026-10-02).

    1. What the others do (verified in .reference/). Swift: a bare member name in an instance method resolves through the implicit self; a local of the same name wins and self.x reaches the member; self. is required only inside an escaping closure (DiagnosticsSema.def:5145 property_use_in_closure_without_explicit_self) because the capture of a class reference is significant there. Jai: opt-in using imports a struct's fields into scope (The_Way_to_Jai 12.7). Go/Zig/Rust: the receiver is named and every field access is qualified (go/src/strings/builder.go).

    2. What the spec says. Nothing rules bare field access either way. D7 keeps self.field ("self remains an implicit binding in instance-method bodies") and its reopen clause is narrow, so this is an extension of D7, not a reversal. The relevant rule is §29.8: "Shadowing is disallowed for local bindings. Rebinding an existing visible name emits a diagnostic", with the consuming-rebind exception. With already refuses the situation that makes Swift need a precedence rule.

    3. Mission fit. In an instance method with no local named bodies, self.bodies has one meaning, so the prefix is a character the program already determined (56 of 1,334 tokens in nbody, all in the hot field-heavy mut fns that §3.1's no-&mut rule pushes code into). The objection is "two meanings remain" when a local and a field share a name. Under §29.8 they can't both exist, so there is never a hidden default.

    • (A) keep self. everywhere: safe, but ceremony in exactly the code With pushes users into.
    • (B) Swift's rule: bare field, a local/param wins, self.x reaches the field. Silent precedence. Adding a param count later changes what an existing bare count means, which is the shadowing-at-a-distance §29.8 exists to prevent.
    • (C) bare field access, and a local or parameter named like a field of the receiver is the existing §29.8 shadowing error (fix-it: rename it). One meaning always. Cost: a setter can't name its parameter after the field (mut fn set_name(name: str) → new_name). Constructors are top-level associated fn Type.new with no receiver, so they're unaffected.
    • Omitted: Jai-style opt-in using self writes a declaration to remove characters the compiler already knows. No Swift-style closure rule needed: a closure's capture of the receiver is already checked by §21.1/D62.

    4. Prediction. C, ~60%. D7 ("if self can be avoided, avoid it") plus §29.8 (you chose no-shadowing, then carved out consuming-rebind only where it cost ergonomics without catching a bug). A field-named parameter is exactly the case where shadowing hides a bug (x = x), so the carve-out logic says no exception. If you weight setter naming, B is the alternative.

    Draft words if C (§9.5, after the receiver-mode paragraph): "In an instance method body, a field of the receiver is in scope by its bare name; self.field remains valid. A local binding or parameter with the name of a receiver field is a shadowing error (§29.8)."

  2. ehartford commented on Oct 3, 2026

    @ehartford
    ContributorAuthor

    Eric's direction (2026-10-03): C, scoped to the type's own module, field-vs-global/function is the same shadowing error, and count the cost first. Census (Lexer-based scan of 2,113 files, 1,585 types, 6,468 fields; with analyze parameter facts carry no names, so it could not answer this):

    corpus methods own / ext param = field local = field field = fn/global self.field own / ext
    src 2996 / 2250 56 / 73 40 / 31 7 16,764 / 19,277
    lib/std 458 / 0 2 / 0 24 / 0 3 740 / 0
    test/behavior 450 / 12 5 / 0 3 / 0 4 475 / 0
    examples 85 / 7 1 / 0 0 / 1 0 139 / 30
    rest 27 / 0 0 0 2 135 / 0
    total 4016 / 2269 64 / 73 67 / 32 16 18,253 / 19,307

    Reading it:

    • Scoped to the own module, C removes 18,253 self. prefixes and costs 131 renames (64 params, 67 locals) plus 16 field/function clashes. Outside src/, almost every method is in its type's own module; in src/, Sema/Codegen/Zcu are split across files, so half the prefixes stay.
    • Setters and builders are rare: 7 set_*, 6 add_*, one with_*-style output, one new(prefix) using field shorthand.
    • 90 of the 137 parameter collisions are one pattern: an AstPool parameter named pool on a receiver whose pool field is an InternPool. Same name, different meaning: the case the shadowing error exists for.
    • 39 of the 99 local collisions copy a field into a same-named local (let ptr = self.ptr, var zcu = move self.zcu). Under C the first becomes unnecessary; the take-and-restore form needs a rename.
    • Field = function examples: Command.args vs std.process.args, Target.parallel, SysInfo.page_size, and Sema's builtin table fields todo/unreachable/drop.

    Revised draft words for §9.5 (need Eric's blessing of the words):

    In an instance method declared in its type's own module, a field of the receiver is in scope by its bare name; self.field remains valid. A parameter or local binding named like a receiver field is a shadowing error (§29.8). A bare name that names both a receiver field and a global or a module-level function is a shadowing error; self.field and the qualified name remain valid. A method declared in another module reaches the receiver's fields only through self..

    Accepted knowingly: a bare count += 1 in a mut fn reads like a local write; the mut fn marker carries the signal.

  3. 64 remaining items

  4. ehartford commented on Oct 4, 2026

    @ehartford
    ContributorAuthor

    Fixed on main in 8cc883a (stack #2072, ten PRs; seed-driven battery GREEN on 92add22, tree identical to main).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions