Skip to content

A user Option/Result displaces std's generic templates in the compiler's own lookups #750

Closed

Description

@ehartford

Restated (2026-10-25 triage)

A user declaration named like a prelude type leaks into the standard library's resolution: type Option = i32 makes the compile fail inside <embedded-std>/std/regex.w. §18.1: a visible user declaration wins in its scope; it must never change what std's own names mean. (The original symptom, user functions losing to prelude names, is fixed.)


Original report

Spec (rules the behavior twice)

§18.1: 'Name precedence is deterministic: local bindings and explicit use
imports win over prelude names. If you define print in a module, calls to
print(...) resolve to your definition in that scope.'

§2 (BDFL ruling 2026-07-05, #627): 'A user type declaration of the same
name shadows the alias by ordinary scoping (the visible user declaration
wins)...' — only the enumerated core lexical primitives plus Unit/Never
are non-shadowable.

Actual (probes, current stage1)

type Regex { r: i32 }
fn main:
    let x = Regex { r: 3 }   // error: unknown field 'ptr' for type 'Regex'

The literal resolves to std's Regex — the user's visible declaration
loses in the user's own file, silently.

type CString { n: i32 }
impl Copy for CString        // error: cannot implement Copy because it implements Drop

The impl attaches to std's CString.

extern fn write(fd: c_int, buf: *const c_void, len: c_ulonglong) -> c_longlong
// error: extern fn 'write' shadows prelude function 'write'

The diagnostic rejects exactly what §18.1's print example permits.

Reference basis (verified in-tree)

Go (spec: inner-block redeclaration over universe-block predeclared), Rust
(prelude is a lowest-precedence glob use), Swift (recordShadowedDeclsAfterTypeMatch;
module decls shadow imports), Vale (explicit imports only — no implicit
prelude), Zig (no prelude at all). All five make user declarations win or the
collision unrepresentable; none error, none prefer the library.

Fix

Sema name resolution: visible module-local types/functions/externs win over
prelude and embedded-std names; trait coherence (E1102) keys on the RESOLVED
type identity (std's impl Drop on std's CString, the user's impl Copy
on theirs — no conflict); delete the 'extern fn shadows prelude function'
diagnostic. Scope note per the natural reading (and pending nothing to the
contrary): embedded-std types reachable through the prelude ARE 'prelude
names' for precedence purposes.

Impact

Blocks the #740/#749 roundtrip at the build-migrated-compiler step: the
migrated self-hosting output defines its own CString/Regex/Captures
and currently cannot compile against the prelude (~11 collision-class
errors on the 5 MB fixture output). When this lands, revert the
prelude-surface entries added to ci_escape_reserved in 6bed71c (the
@[link_name]-on-renamed-externs emission stays — correct regardless), so
migrated output keeps the user's real names.

Repro loop: migrate the fixture C (~2 min), with check the output with
the prelude.

Activity

  1. ehartford commented on Aug 1, 2026

    @ehartford
    ContributorAuthor

    Investigation update — the quick fix is unsound; conformance requires scoped resolution.

    What was tried: generalizing the existing Box/Rc precedent (drop a prelude module wholesale when the user declares one of its type names). Probes passed (user type Regex/type CString + impl Copy work); the migrated fixture output improved — until scale.

    Why it is unsound: module-drop only works for LEAF modules. Dropping string.w (user declares CString/StringBuilder) rebinds every RETAINED std module that uses its types — traits.w's Display impls and regex.w internals resolve StringBuilder to the USER's shadowing type under the flat namespace and fail with dozens of type errors (reduced evidence: 24 return mismatches + with_str_slice/with_panic/++ errors, all inside embedded-std). Box/Rc work as ad-hoc cases precisely because nothing in std references them. The failure is scale/usage-emergent (small probes pass because generic std impls only check on instantiation), which is why with reduce could not shrink the 12.5k-line repro.

    The structural truth: under Sema's flat merged namespace, a user shadowing a type that std ITSELF uses is a contradiction — one name needs two meanings (std keeps its CString; the user gets theirs). No decl-dropping scheme resolves it. §18.1's 'in that scope' language points at the real fix: scoped name resolution (per-module type namespaces), which is a Sema architecture campaign.

    Kept from this pass (sound, landed): the migrator no longer re-declares interop primitives — the migrate preamble's type c_void = opaque is gone (builtins provides it), and system-header records modeled by std.libc (rlimit) skip with a libc note (the skip's location gate needs a follow-up — the sys/resource.h decl still slipped through in the fixture; and the emitted C's own struct c_void round-trip needs the same name-based skip). The Frontend generalization is reverted to the leaf-only Box/Rc cases with a comment explaining why.

    Roundtrip consequence: the migrated compiler output cannot compile against the full prelude until scoped resolution lands OR the roundtrip builds migrated output against a leaner prelude (core + libc, no regex/string-extras/thread — everything the file redefines). Which path to take is the open decision.

  2. ehartford commented on Aug 1, 2026

    @ehartford
    ContributorAuthor

    Ruled by Eric — D29 in docs/decisions.md carries the directive verbatim; spec §18.2 now states the destination model (implicit std availability as a lowest-priority exact-match fallback tier; precedence lexical/generic-params → current-module → imports/aliases → prelude → unique std fallback).

    This issue's resolution is work item 1: scaffolding (label every commit and doc comment as such — this is the interim state, not the destination):

    • Remove flat injection of lib/std declarations into user modules.
    • Enforce the spec §18.2 prelude exactly as enumerated; all other std names import-gated, with §18.1 precedence (user wins).
    • std internals resolve their own names via the existing tier machinery (prelude/user/root per-decl paths).
    • Ship a compiler fix-it that inserts the missing use line for any unresolved name uniquely matching a public std declaration. The migrator applies this fix-it automatically to its own output.
    • Migrate the affected behavior tests (~30+ using HashMap/HashSet/StringBuilder bare, plus the uncounted tail) via the fix-it, not by hand. Fork, don't overwrite: keep the import-free originals in a quarantined suite named as the D acceptance corpus.

    Acceptance: roundtrip output compiles; the type Regex { r: i32 } probe resolves to the user's type; the impl Copy for CString probe attaches to the user's type; the string.w module-drop probe no longer rebinds Display impls; all 935 behavior tests green post-migration.

    Campaign issues filed per the ruling: #751 (canonical module-qualified identity — record, don't start, sequenced after #747), #752 (fallback-tier activation — blocked on #751). The two loose ends recorded earlier (rlimit skip's location gate; the emitted C's round-tripped struct c_void needing a name-based skip) fold into work item 1 here.

  3. ehartford commented on Aug 1, 2026

    @ehartford
    ContributorAuthor

    Work item 1 (scaffolding) is implemented and committed: 6430d1ee (compiler) + 67816feb (corpora). Battery running on the exact tree.

    • §18.2 enforced exactly as enumerated: prelude-closure names are import-gated except the enumerated list plus two lowering-support names (c_void, assert_matches_failed); std implementation modules never resolve user-tier declarations; externs exempt; compiler demands (regex literals) resolve ambiently.
    • Denials carry the fix-it: 'HashMap' requires an explicit import (§18.1); add: use std.collections.HashMap.
    • Shadow coexistence works end to end: all three acceptance probes compile AND run (type Regex { r: i32 } binds the user's type while std's vtable-forced Regex.clone keeps its own; impl Copy for CString attaches to the user's type with real copy semantics despite std's Drop-bearing CString; the StringBuilder probe no longer rebinds string.w internals). Frontend's ad-hoc Box/Rc module drops are removed, superseded by tier-aware resolution + per-tier codegen symbols (name$std).
    • Sweeps, applied mechanically via the fix-it (not by hand): the compiler's own sources (994 bare HashMap sites), build/, tools/, 181 behavior tests, 242 files across the other lanes and examples — zero stuck. The 181 import-free originals are forked verbatim into quarantined test/d_acceptance/ (the D acceptance corpus; no lane globs it until Activate the std fallback tier: implicit standard-library availability (name-resolution D) #752).
    • with migrate applies the fix-it to its own output in-process (loud on non-convergence); -e/-n/-p synthesized headers import the ambient vocabulary.
    • Found en route and filed: View-liveness checker matches same-named identifiers across files by byte-span window (phantom 'cannot mutate while live view' errors) #753 (view-liveness checker matched same-named identifiers across files by byte-span window — insertion-sensitive phantom errors; guarded + victim annotated in this batch).

    Known scaffolding gaps, documented for #751/#752: trait names remain flat-ambient; enum-variant gating deferred; shadowed generic types and same-named methods across tiers still conflate (symbol-keyed tables); comptime/emit-C shadow paths untiered.

  4. ehartford commented on Aug 4, 2026

    @ehartford
    ContributorAuthor

    This is now the FIRST WALL of the #747 roundtrip census. After fixing the i32 key overflow that blocked checking at 3M-line scale (747-flip @ 01c8248), check of the freshly migrated compiler source (103.5 MB, 3,011,786 lines) reaches a clean diagnostics verdict — rc=1, 216.8s, 1.78 GB peak RSS, zero panics — and EVERY error it reports is an instance of this issue:

    • duplicate implementation of trait for type [E1102] at impl Copy for RegexFlags (migrated line 58353). The file contains exactly ONE such impl; the collision is with the prelude's lib/std/regex.w:43 impl Copy for RegexFlags. Sema's direct-impl coherence table is keyed by the bare interned type NAME (impl_lookup in src/SemaDecl.w, duplicate scan at ~2365-2371, which also ignores impl_extra_is_std), exactly the "trait coherence (E1102) keys on the RESOLVED type identity" fix this issue already prescribes.
    • The other two errors are pure cascades: the rejected impl leaves the user's RegexFlags non-Copy, so Result_RegexFlags__RegexError__anon_0 (union, payload0: RegexFlags) and Result_RegexFlags__RegexError_ fail their Copy impls.

    Minimal repro (errors on both the flip probe and the current installed main-world compiler — pre-existing, not flip-specific):

    type RegexFlags { a: i32 = 0 }
    impl Copy for RegexFlags
    fn main:
        let f = RegexFlags { }
        print_i32(f.a)
    

    The check aborts after the decl phase ("check failed during compilation"), so the roundtrip's full body-level census is unreachable until this is fixed. (Each diagnostic also renders twice — that is #759, a separate decl-phase double-emission.)

  5. ehartford commented on Aug 4, 2026

    @ehartford
    ContributorAuthor

    The E1102 trait-coherence lane is fixed on 747-flip @ 31fc99c: collect_impl_decl's duplicate-impl scan now tier-discriminates shadowed syms (skips records whose impl_extra_is_std tier differs from the tier of the type the gated lookup resolves from the impl's own module — same pattern as the function's existing Copy/Drop conflict checks; unshadowed syms keep the flat scan bit-for-bit). Shadow-coexistence repro compiles AND runs; shadowed and flat true duplicates still E1102. MAIN-LINE-worthy — rides the flip merge.

    With the decl gate cleared, the full body-level roundtrip census landed (handoff 04p): 188,427 errors in 9 kinds, zero E1102, zero panics (312.5s / 2.27 GB). The 62,359 wrong-argument-type errors plus all 76 embedded-std-located errors are this issue's EXTERN lane (the roundtrip file's with_* runtime extern redeclarations colliding with prelude/internal signatures under the flat extern namespace) — still open here.

  6. 18 remaining items

  7. changed the title [-]Sema: prelude/std names are not shadowable — visible user declarations lose, violating §18.1 and the #627 ruling[/-] [+]A user type named like a prelude type leaks into std's resolution (type Option breaks <embedded-std>/std/regex.w)[/+] on Oct 25, 2026
  8. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): the original symptom is fixed, and the class now shows the other way round. A user fn print and a user fn src win in their scope (print(1) prints 101; src() returns 7). But a user type named like a prelude type breaks the compile inside the embedded standard library:

    type Option = i32
    let x: Option = 5
    print(x)
    
    error: undefined variable
     --> <embedded-std>/std/regex.w:463:28
    463 |                         if found.end == found.start:
    

    The user's declaration reaches std's own resolution (the flat-namespace class #751 tracks).

    pre-release: ordinary code names a type Option, Result or Error, and the error points into the standard library with nothing the user can act on.

  9. ehartford commented on Oct 26, 2026

    @ehartford
    ContributorAuthor

    Fix campaign, 2026-10-25: flagged human attn needed. It still ships as a bug before release; I am not removing do-before-release.

    Proved (main c5fdc17, with v0.15.3.0). It still reproduces as the triage describes:

    type Option = i32
    fn main:
        let x: Option = 3
        print(x)
    
    error: undefined variable
     --> <embedded-std>/std/regex.w:463:28
    

    The user's type Option replaces the name Option in std's own resolution: Sema keys named types and signatures by the flat interned symbol, so one module's declaration changes what another module's spelling means. That is #751's definition of done ("a user type Regex { r: i32 } resolves to the user's type"; "no compiler phase re-resolves a short name after initial lookup"), and #751 is a recorded multi-PR campaign (D29, sequenced by Eric). A local patch here would be a second derivation of module identity in one lookup path, which D65 rules out.

    Narrowest open question. Should #750 wait for #751, which carries every phase (impl attachment, coherence, generic instantiation, MIR, comptime, backends, migrator), or does the release need an interim: refusing a user declaration that shadows a prelude type name (type Option, Result, Error) with a diagnostic, until #751 lands?

    Four-part brief:

    1. Others. Go, Rust, Swift: a user declaration shadows a prelude or universe name in its own scope and never changes the library's meaning. Zig and Vale have no implicit prelude, so the collision can't happen. None of them refuses the declaration.
    2. Spec. §18.1 says a visible user declaration wins in its scope. §2 (Box.as_ref() broken: primitive box run-fails, struct box segfaults (auto-deref path works) #627) lets a user type shadow a prelude alias. Neither allows a refusal.
    3. Mission fit. A refusal is a rule the user must learn because of how the compiler is built, which is ceremony. Campaign: canonical module-qualified identity for every declaration (name-resolution B) #751 is the with-y answer.
    4. Prediction (70%). Eric keeps A user Option/Result displaces std's generic templates in the compiler's own lookups #750 on Campaign: canonical module-qualified identity for every declaration (name-resolution B) #751 and refuses no names. A diagnostic that blames the user for a compiler limitation fails "Not a nanny".

    Since the prediction is below 75% and this is a semantics question, it waits for Eric.

  10. ehartford commented on Oct 27, 2026

    @ehartford
    ContributorAuthor

    Phase-3 fix campaign, 2026-10-26: re-reproduced on current main (dee141b79, installed with v0.15.3.0): type Option = i32 still fails inside <embedded-std>/std/regex.w ("undefined variable" at the regex internals), exactly as triaged. The cause is unchanged — Sema keys named types by the flat interned symbol (#751's multi-PR campaign), and a local patch would be a second derivation of module identity, which D65 rules out.

    It stays human attn needed on do-before-release. The open question is unchanged: wait for #751 (prediction 70%), or an interim refusal of a user declaration shadowing a prelude type name until #751 lands?

  11. added a commit that references this issue on Oct 28, 2026
  12. changed the title [-]A user type named like a prelude type leaks into std's resolution (type Option breaks <embedded-std>/std/regex.w)[/-] [+]A user Option/Result displaces std's generic templates in the compiler's own lookups[/+] on Oct 28, 2026
  13. ehartford commented on Oct 28, 2026

    @ehartford
    ContributorAuthor

    Fixed by #2763 (6126049), battery-green on 4062c27 and merged.

    Root cause (exact lines, lldb + traced stage1): Sema.try_unwrapped_type returned 0 for every std ? because resolve_generic_enum_payload fetched the instance's template from type_decl_nodes by bare name — the flat map where a user's type Option = i32, registered last, displaces std's enum. The same displacement in named_types fed MIR/TypeLayout/Codegen template fetches by base symbol.

    Fix: template lookups resolve through the instance's recorded template (generic_inst_decl_node / type_decl_nodes_by_tid); a non-generic declaration no longer displaces a generic template in the flat registries (candidates still record every declaration, so user-side shadowing is unchanged). Battery follow-up in the same PR: every remaining flat-map generic-ness/layout reader (blanket-Copy guard, generic-template registration, generic method inference, D72 liveness byte) now judges the declaration the type itself denotes — std's generic Handle[T] no longer answers for a user's Handle.

    Regression: test/behavior/behav_750_user_{option_shadows_std,option_struct,result_shadows_std,handle_drop}.w. The contained Option/Result fix per the 2026-10-26 ruling; generic-vs-generic same-name identity remains #751.

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