Skip to content

Sema: imports are not transitive; locals shadow interface globals; shadowing diagnostics name the collision (§18.2, #1703) - #1708

Merged
ehartford merged 3 commits into
mainfrom
import-visibility
Sep 26, 2026
Merged

ehartford merged 3 commits into
mainfrom
import-visibility

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Spec-settled parts of #1703: use is not transitive (the compiler tree checks unchanged with direct edges), a lexical binding shadows a corpus' interface global, and the shadowing diagnostic names the colliding binding's origin. The remaining question on #1703 — a module-level const beside another module's flat-scope global — is a ruling (D52 flat globals vs §18.2 tier 2). Draft until the battery is posted.

@ehartford

Copy link
Copy Markdown
Contributor Author

Seed-driven battery at 9220eed (seed nightly-20260925-local-1, WITH=src/main), this host:

9220eed6 visibility /Users/eric/.local/with-staging/visibility
visibility build  rc=0
visibility build :fixpoint rc=0
visibility build :test rc=0
visibility build :test-green rc=0
visibility build :last-green rc=0
visibility build :user-programs-safe rc=0
BATTERY_DONE

Then rebased cleanly onto main 37d87fc (no conflicts; D49 clean-rebase rule).

@ehartford
ehartford marked this pull request as ready for review September 26, 2026 07:14
@ehartford
ehartford marked this pull request as draft September 26, 2026 07:14
Eric Hartford added 3 commits September 26, 2026 03:14
…, and the shadowing diagnostic names the colliding binding (§18.2, #1703)

- module_is_visible_from_current walked the import graph transitively, so
  `use helper` made everything helper imported visible (helper2's `deep`,
  std.re's globals through the prelude chain). §18.2's precedence names
  explicit imports, the prelude and the std fallback — nothing transitive.
  The whole compiler tree checks unchanged with direct edges only.
- A lexical binding (tier 1) shadows a bundle-interface global (a corpus'
  `pub let`) as it shadows any other module's global.
- "shadowing is not allowed for 'X'" now says what X is: a global of which
  module, a bundle interface global, or an earlier binding in this scope.

What stays: a MODULE-LEVEL `const PACKAGE` beside std.re's `pub let PACKAGE`
is one flat-scope global declared twice (D39/D52) — whether module-level
declarations shadow another module's global is a ruling (§18.2 tier 2 vs
D52's flat table), tracked on #1703.
…and build.w imports std.process itself

Direct-edge visibility cut build.w off from `env`: it reached std.process
through build.compiler, a user-module hop §18.2 does not grant. Every public
std declaration is the lowest resolution tier (tier 5, #752 not yet
implemented), so the walk continues through std modules only; build.w
spells its own `use std.process`, the import the spec requires.
…mports BuildGraphSupport itself; a name a transitive chain used to expose is "not visible from this module"; the imports test checks in the enforced spelling (#1520)
@ehartford

Copy link
Copy Markdown
Contributor Author

Seed-driven battery green on 89b393c (host darwin-aarch64, seed per seed.lock):

visibility build  rc=0
visibility build :fixpoint rc=0
visibility build :test rc=0
visibility build :test-green rc=0
visibility build :last-green rc=0
visibility build :user-programs-safe rc=0

@ehartford
ehartford marked this pull request as ready for review September 26, 2026 08:05
@ehartford
ehartford merged commit d739fb1 into main Sep 26, 2026
@ehartford
ehartford deleted the import-visibility branch September 26, 2026 16:23
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…sitive (#1708) and src/ has no privacy waiver (#1520), so a module that named MirCore, InternPool, SemaTypes or compiler.* types through another module's import now says so
ehartford pushed a commit that referenced this pull request Sep 26, 2026
… of every name a log reports unresolved

Imports are not transitive (§18.2, #1708) and src/ has no privacy waiver
(§18.3, #1520), so a compiler module that named a declaration through a
third module's import fails with "undefined variable" (the name is read at
the caret), "unknown type 'X'" or "symbol 'X' is not visible from this
module". For each such name that exactly one module under the source roots
declares at top level, the referencing module gets `use <owner>` after its
header's last `use` and the owner's declaration gets `pub ` when it lacks
it. A name with no owner, several owners, or its own module as owner is
reported and left alone. The compiler's own "add: use M.n" fix-it is
applied verbatim. Nothing changes without --apply.
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…declares an extension `m` (#1708 fallout)

check_qualified_extension_call claimed every `pkg.m(...)` whose `pkg` was a
directly imported module alias, before asking whether that module declares
any extension method `m`. Once imports stopped being transitive (§18.2,
#1708), `use Compilation` (a shim that only imported compiler.Compilation)
bound the alias `Compilation` and nothing else, and `Compilation.init()` in
Lsp.w was reported five times as "qualified extension method
'Compilation.init' requires a receiver argument" — a method no module
declares. The call now falls through when the module has no such extension
method, and the ordinary path names the unresolved `Compilation`
("undefined variable"). behav_module_alias_named_like_type pins both the
refused alias spelling and the accepted direct import.
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…ler.Compilation

The shim existed so `use Compilation` kept working after the orchestration
root moved to src/compiler/Compilation.w: it imported that module and relied
on the import carrying through. Imports are not transitive (§18.2, #1708),
so the shim re-exports nothing; main.w, Lsp.w and bootstrap_main.w import
compiler.Compilation directly (main.w already did).
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…1520 layer

Applied by tools/import_unresolved_symbols.w over the stage2 build log of
the rebased branch (1320 "undefined variable", "unknown type 'TypeId'",
"not visible from this module", the std sha256 fix-its) and the stage1
check that followed (TargetSpec in SemaCheck.w): 42 `use` lines in 27
modules, each naming the one module that declares the symbol. SemaFacade.w
takes `use Span` by hand — Span is declared by src/Span.w and by
src/compiler/foundation/Span.w, and the facade builds the Diagnostic span.
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…as with no such type keeps "unknown qualified extension method"

5e266cb let every `alias.m()` whose module declares no extension `m` fall
through, which also dropped err_extension_method_unknown_qualified's
diagnostic for a plain module alias (`slug.missing(t)`). The fall-through
is now limited to its cause: the module declares no extension `m` and a
type of the alias's name exists that this module cannot see
(`use Compilation; Compilation.init()` after #1708). That case reports
"symbol 'Compilation' is not visible from this module" at the alias; every
other alias keeps the qualified-extension diagnostics.
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…y (§18.1, #1708)

With non-transitive imports the release binary refuses build.w: "'arch'
requires an explicit import; add: use std.sysinfo.arch" and the same for
std.process.env. The pinned seed predates #1708 and accepted them, so the
battery's build layer (evaluated by the seed) never saw it; the fresh
binary's `check build.w` did. Applied the compiler's fix-its.
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…sts lane)

src/MirValidationTests.w is compiled only by test/internals, so the stage2
log never showed it; its TypeKind reads failed as "undefined variable" in
all 15 internals tests. Applied by tools/import_unresolved_symbols.w.
ehartford pushed a commit that referenced this pull request Sep 26, 2026
…aTypes` (imports are not transitive, #1708); the ABI convention is unchanged, so WITH_ABI_VERSION stays
ehartford added a commit that referenced this pull request Sep 26, 2026
* Sema: let-else checks the else branch before the pattern binds its names (#1476)

check_let_else bound the pattern's names into the enclosing scope with
check_pattern and only then checked the else body, so the body resolved a
name that does not exist on its path (`else: return v.len()`); `with check`
said ok and MIR lowering failed. The else branch runs only when the pattern
did not match, so it is checked first, before anything is bound (§9.7).

Fixes #1476

* Sema: a method-path call marks a plain owned argument moved as the free-call path does (#1588)

propagate_method_call_param_effects recorded the consume site for a plain
non-Copy argument bound to an owned parameter but never marked the binding
moved — the #714 mark landed only in check_call's free-function loop. So
`T.make(p)` and `x.m(p)` transferred `p` in MIR while Sema still held it
live, and a later `{p}` compiled and read the moved-from str.

Fixes #1588

* Sema: the unsafe-global-access advice is located at the recorded access, and skips <c_import> translations (#1590)

validate_global_data_race_accesses runs after every body and emitted the
warning through emit_warning, which reads local_file_id — whatever file was
checked last (the root, or a rendered `<facade …>` file) — at the access
node's offsets, an empty line of the wrong file. The pass already keeps
each access's file id (global_race_access_files, as the error path uses);
the warning now carries that span. A `<c_import …>` translation is not a
user lint source: nobody can edit the `unsafe` blocks the translator wrote.

Fixes #1590

* codegen: Type.from_int compares at a width that holds the argument, never truncated to the repr (#1499)

gen_disc_enum_from_int_val narrowed the argument to the enum's repr with
coerce_int before the switch, so an integer outside the repr's range that
shared low bits with a discriminant matched it: Tiny.from_int(456) was
Some(Hi = 200), K.from_int(2^32 + 1) was Some(A), Tiny.from_int(-56) was
Some(Hi). The switch now runs at i64 (or the argument's own wider type),
the argument extended by its own signedness (mir_operand_sema_type) and
each discriminant by the repr's (a new per-enum disc_enum_repr_unsigned
row), so an out-of-range value reaches the None default (§4.4a).

Fixes #1499

* Sema: module privacy no longer depends on the entry path's directory (#1520)

decl_visible_from_current waived §18.3 whenever both the current and the
target module path lay under a `src/`, `build/`, `rt/` or `out/gen/`
directory (sema_paths_share_internal_implementation_boundary) — a guess at
"the compiler's own tree" from the directory name. A user project laid out
as `src/a.w`, `src/b.w` therefore had privacy only when checked from inside
`src/` (`check p1.w` rejected the private type, `check src/p1.w` and an
absolute path accepted it), and a module saw another module's private C
declarations the same way. The waiver is gone; the std tier keeps reading
its own private declarations (one implementation, D39 corpora). The
compiler's cross-module types that the waiver had covered are declared
`pub`, which is what they are.

Fixes #1520

* Sema: a bare fn coerces to a generic callee's extern "C" fn parameter (#1609)

The generic call paths (check_call with sig_idx < 0, check_method_call_parts
for a generic method) bind the type parameters from every argument at once
and gave a bare fn argument no expected type, so §12.4's coercion to an
`extern "C" fn` parameter never ran and `g2(1, my)` was "wrong argument
type". null_arg_expected_type's rule — the template parameter's type when
it names no type parameter — is now fixed_param_expected_type, shared with
extern_fn_arg_expected_type, and an identifier argument takes that type
when it is an extern fn type. The SQLite facade's typed-local workaround is
no longer needed.

Fixes #1609

* Sema/MIR: `for (k, v) in bt` traverses a BTreeMap in place (D44, #1561)

infer_for_element_type knew HashMap but not BTreeMap, so a BTreeMap loop
fell to the generic next() protocol, found no `next` and typed the element
i32 — "tuple pattern requires tuple subject", and in a generic body the
bindings came back undefined. Sema now types the traversal as the traversal
of the map's `Vec[(K, V)]` storage (a Drop-class pair binds as a `&(K, V)`
view whose pattern projects `&K`/`&V`, a Copy pair by value), and
MirLower lowers it as the Vec loop over the `entries` field place — the
two Vec loops are split into place-based cores (lower_for_iter_ref_place,
lower_for_vec_place) that lower_for_btreemap shares. A `&BTreeMap` binding
and `for … in &bt` traverse the same way; the map stays whole after.

Fixes #1561

* Sema: a field view borrows its root, and an explicit move is a write under live views (#1530)

`let p = x.s` binds a view of the field (D22, field_let_binds_as_view) but
registered no borrow: the binding was never view-bound and
record_view_binding_from_expr's owned-root fallback covered only index
places. So neither `x.s = …` nor `move x.s` under the live view was
refused, and `p` read the blank or the freed string. A non-Copy field view
is now view-bound and borrows its root exactly as an element view does,
and the NK_MOVE_ARG branches run check_mutation_against_views (a vacate is
a write, §2.2 D32; a move under a live view is refused, §21.1 Rule 2) as
the assignment path already did.

Fixes #1530

* test: pin str/&str lent to a translated inline C function's const char * (#1589)

The marshalling landed with D66 (main prints 5 5 and the debug allocator is
clean); this pins the three spellings — a literal `str`, a `&str` view and
an owned `str` — against a translated `static inline` callee.

Fixes #1589

* build: spell the clones the method-path move check now sees (#1588 fallout)

With the method path marking plain owned arguments moved, the build layer's
uses after `target.arg(asset)` / `.input(prefix)` / `diagnostics().error(result.stderr)`
and ProcessRunner.run_spec's field moves are reported. Each is a real
second use of a consumed value; the reads become explicit clones
(build_owned_text / .clone() / with_str_clone_ref), and run_spec vacates
the spec's env explicitly before threading it.

* tools: publish_private_symbols — declare pub the top-level symbols a build log reports as private

A saved build/check log names every cross-module reference of a private
declaration ("symbol 'X' is private to module 'src/Y.w'", "symbol 'X' is not
visible from this module") and every published signature naming a private
type (§18.1). The tool collects the (module, symbol) pairs, prefixes `pub `
to the one top-level declaration of each in its owning module, and changes
nothing without --apply. Written for #1520's fallout: module privacy is no
longer waived under src/, and the compiler's own modules relied on it
(~9000 errors, visible only when stage1 compiles stage2).

* Declare pub the compiler's cross-module symbols that the src/ privacy waiver had covered (#1520 fallout)

Applied by tools/publish_private_symbols.w over the stage2 build log and the
stage1 check logs that followed (types, enums, fns, consts, lets, vars;
`pub unsafe fn` for the comptime entry points; the take_* partners and
Codegen itself, whose `impl Codegen:` blocks live in CodegenDispatch.w and
CodegenTraits.w). Five `use` lines make the modules that reach SemaCheck.w,
SemaDecl.w and CImport.w helpers import them ("not visible from this
module"). The rule (b8c1edf) is right; the compiler's tree now conforms to
§18.3 like any project.

* Sema: an impl on another module's private type names the cause at the impl header (#1520)

collect_impl_decl attached the block to nothing when the target type was
private to another module, so every method's `self` was an error type and
each use surfaced as "unknown method 'm' for type '&<error>'" far from the
cause (`impl Codegen:` in CodegenDispatch.w: 300 such lines). The impl
header now reports "symbol 'T' is private to module 'src/X.w'" through
emit_private_symbol_error; behav_module_privacy_under_src_dir pins it.

* Sema: a field view borrows its field's path, not its whole root (#1530 follow-up, §3.8/D22)

b5bd597 registered `let src = self.source` as a borrow of `self` with an
empty path, so every sibling write — `self.pos = self.pos + 1` in the
Lexer, the Sema save/restore pairs, 210 sites of the compiler's own sources
— was refused as invalidating the view. A write to a disjoint field leaves
the viewed value where it is. register_view_binding_borrows now records the
initializer's projection path (root-to-leaf, stopping at an index — an
element's storage can move under any write to its collection, #887), so
are_borrows_disjoint_paths admits sibling writes and still refuses a write
to the viewed path or an ancestor of it.

behav_sibling_field_mutation_under_field_view pins the accepted shapes
(sibling, sibling of an ancestor, element view with sibling writes);
err_assign_field_under_live_field_view and
err_assign_parent_under_live_field_view pin the refused ones.

* Parser/Sema: DeclBody and SemaExhClass are Copy — tag enums passed by value are not consumed

Both are plain discriminants read at several call sites in one function
(skip_member_separators(form) per member; exh_constructor_of(…, cls, …) per
constructor). Without the Copy impl the method-path move check (#1588) marks
the first pass a move and the next a use of a moved value.

* Spell the transfers the field-view borrow and the method-path move check now see in the compiler's own sources (#1530, #1588 fallout)

A `let saved = self.f` before `self.f = …; …; self.f = saved` is a transfer,
not a view: the seed aliased it, #1530 registers the view and refuses the
reassignment, and consuming the view binding at the restore is refused too.
Every such save/restore pair is now `let saved = move self.f` (139 sites,
rewritten from the check log). The comptime evaluator's signal values are
moved into the calls that take them by value, cloned where the value is
still read after (update_slot_value, write_back_mut_receiver); a builder's
finished body is moved out; a path that is read after the call is cloned; a
Copy element read across a write to its collection is an owned `: i32` /
`: StackifyTarget` value. The hot-path comptime call moves the module path
out only when it switches context, so a same-file call keeps it in place
(#679). main.w vacates the parsed build options from a `var`.

* Sema: consuming a `const` never marks it moved — it is a value, not a place (D52, §9.1c)

mark_moved_if_consumed set the symbol of a `const` to MOVED when it fed a
consuming parameter, so `take(C); take(C)` reported "use of moved value"
at the second use — the seed's free-call path did this already, and the
method path (#1588) now did it too, which refused build.w: line 2400's
`.extra_output(FIXPOINT_STAGE2_UNITS)` marked the const moved and lines
2478 and 2494 read it. D52: every use of a `const` materializes it, so a
transfer from one moves nothing; a non-local const symbol is now exempt
from the mark (reject_move_out_of_global already skips it through
global_value_ident_nodes). A `global`'s move stays "cannot move out of
global" at the consuming use, on the method path too
(err_move_out_of_global_method_arg).

* Sema: a generic template's fixed parameter type resolves in parameter position (#1609 follow-up, #604)

fixed_param_expected_type resolved the template parameter's type node as a
bare type expression, so `[]mut T` there hit #604's "can only be a function
parameter type" — the argument check refused every facade whose generic
helper takes an element buffer (behav_c_facade_buffer_elements). Reached
only for null literals before; #1609 widened the path to identifier
arguments. The node is a signature parameter, so it resolves through
resolve_parameter_type_expr, as declaration and specialization do.

* rt: publish str_data and make_str for rt_core.w; the tool maps <embedded-rt>/ to rt/ (#1520 fallout)

With the runtime parsed into the unit (WITH_RT_IN_UNIT=1,
behav_rt_in_unit_check_lane) module privacy now applies across rt/*.w too,
and rt_core.w calls panic_runtime.w's str_data and fiber_runtime.w's
make_str. publish_private_symbols reads the lane's `<embedded-rt>/rt/…`
module names as the tree's rt/*.w.

* tests: two pre-D22/D32 pins conform to the spec — a consumed field is cloned, a saved field view refuses the mutation

behav_mut_recv_disjoint_args passed `b.buf` and a `let piece = a.buf` view
to `Acc.add(mut self, piece: str)`, which consumes: a field never moves out
implicitly (§2.2, D32) and an unannotated field let is a view (§3.8, D22),
so both are `.clone()` — the independent value the parameter takes.

dump_mir_str_field_concat_saved_alias_copy pinned `let saved = a.buf;
a.buf = a.buf ++ "x"; saved ++ a.buf` reading through the alias — the
pre-D27 behavior. Under §3.8 the mutation of a viewed field while its
view is live is refused; err_assign_field_under_saved_field_view pins the
diagnostic and behav_str_field_concat_saved_clone the accepted spelling
(`let saved = a.buf.clone()`).

* std.compiler: SourceLocation is Clone; the project-info test clones the location it attaches twice

FunctionInfo.new and TypeInfo.new retain their SourceLocation through a
plain `T` parameter, which consumes (§3.8); behav_std_compiler_project_info
passed one `loc` to both and only compiled because the assoc-call path
never marked the move (#1588). A location attached to several records is
cloned, and a std value type that callers retain is Clone.

* MirCore: publish the validator entry points and drop-state type the internals tests use from test/internals (#1520 fallout, tools/publish_private_symbols.w over the internals lane)

* examples: nebula and service conform to §18.3 and §2.2 (PENDING ERIC'S RULING — examples are contracts)

Spec §18.3: "`pub` exports names. No `pub` = module-private." Both
examples used non-pub declarations across their own modules
(session.handle_session; domain's User, UserId, UserProfile, Role,
CreateUserRequest, Notification), accepted only by the entry-directory
privacy waiver #1520 removes. §2.2/D32: a field never moves out
implicitly; Database.open retains its path, so the call site clones.

Prepared so the branch's battery can run; lands only if Eric rules that
the examples, not the compiler, were the non-conforming side.

* SemaTypes/InternPool: publish TypeId, which main 410fe68 now names across modules (#1520 fallout after rebase)

* Import directly what each compiler module names: imports are not transitive (#1708) and src/ has no privacy waiver (#1520), so a module that named MirCore, InternPool, SemaTypes or compiler.* types through another module's import now says so

* tools: import_unresolved_symbols — import (and publish) the one owner of every name a log reports unresolved

Imports are not transitive (§18.2, #1708) and src/ has no privacy waiver
(§18.3, #1520), so a compiler module that named a declaration through a
third module's import fails with "undefined variable" (the name is read at
the caret), "unknown type 'X'" or "symbol 'X' is not visible from this
module". For each such name that exactly one module under the source roots
declares at top level, the referencing module gets `use <owner>` after its
header's last `use` and the owner's declaration gets `pub ` when it lacks
it. A name with no owner, several owners, or its own module as owner is
reported and left alone. The compiler's own "add: use M.n" fix-it is
applied verbatim. Nothing changes without --apply.

* Sema: `alias.m()` is a qualified extension call only when the module declares an extension `m` (#1708 fallout)

check_qualified_extension_call claimed every `pkg.m(...)` whose `pkg` was a
directly imported module alias, before asking whether that module declares
any extension method `m`. Once imports stopped being transitive (§18.2,
#1708), `use Compilation` (a shim that only imported compiler.Compilation)
bound the alias `Compilation` and nothing else, and `Compilation.init()` in
Lsp.w was reported five times as "qualified extension method
'Compilation.init' requires a receiver argument" — a method no module
declares. The call now falls through when the module has no such extension
method, and the ordinary path names the unresolved `Compilation`
("undefined variable"). behav_module_alias_named_like_type pins both the
refused alias spelling and the accepted direct import.

* Remove the src/Compilation.w re-export shim; its callers import compiler.Compilation

The shim existed so `use Compilation` kept working after the orchestration
root moved to src/compiler/Compilation.w: it imported that module and relied
on the import carrying through. Imports are not transitive (§18.2, #1708),
so the shim re-exports nothing; main.w, Lsp.w and bootstrap_main.w import
compiler.Compilation directly (main.w already did).

* Import directly what each compiler module names: the remaining #1708/#1520 layer

Applied by tools/import_unresolved_symbols.w over the stage2 build log of
the rebased branch (1320 "undefined variable", "unknown type 'TypeId'",
"not visible from this module", the std sha256 fix-its) and the stage1
check that followed (TargetSpec in SemaCheck.w): 42 `use` lines in 27
modules, each naming the one module that declares the symbol. SemaFacade.w
takes `use Span` by hand — Span is declared by src/Span.w and by
src/compiler/foundation/Span.w, and the facade builds the Diagnostic span.

* Sema: an alias that shadows an invisible type names that type; an alias with no such type keeps "unknown qualified extension method"

5e266cb let every `alias.m()` whose module declares no extension `m` fall
through, which also dropped err_extension_method_unknown_qualified's
diagnostic for a plain module alias (`slug.missing(t)`). The fall-through
is now limited to its cause: the module declares no extension `m` and a
type of the alias's name exists that this module cannot see
(`use Compilation; Compilation.init()` after #1708). That case reports
"symbol 'Compilation' is not visible from this module" at the alias; every
other alias keeps the qualified-extension diagnostics.

* build: clang_resource.w and retention.w import arch and env explicitly (§18.1, #1708)

With non-transitive imports the release binary refuses build.w: "'arch'
requires an explicit import; add: use std.sysinfo.arch" and the same for
std.process.env. The pinned seed predates #1708 and accepted them, so the
battery's build layer (evaluated by the seed) never saw it; the fresh
binary's `check build.w` did. Applied the compiler's fix-its.

* MirValidationTests: import SemaTypes (#1708 fallout, the internals-tests lane)

src/MirValidationTests.w is compiled only by test/internals, so the stage2
log never showed it; its TypeKind reads failed as "undefined variable" in
all 15 internals tests. Applied by tools/import_unresolved_symbols.w.

* Re-record docs/with-abi.sha256: src/TypeLayout.w gained only `use SemaTypes` (imports are not transitive, #1708); the ABI convention is unchanged, so WITH_ABI_VERSION stays

* Revert the #1589 test: it passed by coincidence (strlen read a str header's address, whose low bytes are usually five non-zero bytes), so #1589 is not fixed here; it moves to its own PR

---------

Co-authored-by: Eric Hartford <[email protected]>
ehartford pushed a commit that referenced this pull request Sep 27, 2026
…`let`/`const`/`global` of another module is displaced, not "shadowing is not allowed" (§18.2, §18.3)

Fixes #1703

Every module's `let`, `var`, `const` and `global` shared one flat Sema
table keyed by name, so register_top_level_global_decl reported "shadowing
is not allowed" for the second declaration of a name in any module: a
program's `const PACKAGE` beside the source-compiled std.re's `pub let
PACKAGE` (stage1 only — the release binary reads std.re as bundle-interface
storage, which already had its own table), two modules' private `SCALE`, a
program's `let PI` beside `use std.math`.

The fix is #1350's for fns, applied to values: displace_colliding_globals
(run once every source, interface and c_import declaration is in the pool)
keeps the short name for the root module's declaration, then the first
other owner, and gives each other owner's declaration its module-qualified
identity `name$in$<module>`. Sema records it (record_displaced_fn, now
also for module values) and resolve_displaced_global_ident binds each
reference: a lexical binding; the current module's own declaration (a
c_import's value is an import, not the importer's declaration); the flat
declaration when visible; else a visible displaced one. The ident is
rewritten, so MIR, comptime and codegen read the declaration Sema chose.

The repro still failed on a stage1 built from this tree before the change
(`shadowing is not allowed for 'PACKAGE' (a global of module
lib/std/re/defs.w)`), so #1708 had not closed it.
ehartford pushed a commit that referenced this pull request Sep 27, 2026
…`let`/`const`/`global` of another module is displaced, not "shadowing is not allowed" (§18.2, §18.3)

Fixes #1703

Every module's `let`, `var`, `const` and `global` shared one flat Sema
table keyed by name, so register_top_level_global_decl reported "shadowing
is not allowed" for the second declaration of a name in any module: a
program's `const PACKAGE` beside the source-compiled std.re's `pub let
PACKAGE` (stage1 only — the release binary reads std.re as bundle-interface
storage, which already had its own table), two modules' private `SCALE`, a
program's `let PI` beside `use std.math`.

The fix is #1350's for fns, applied to values: displace_colliding_globals
(run once every source, interface and c_import declaration is in the pool)
keeps the short name for the root module's declaration, then the first
other owner, and gives each other owner's declaration its module-qualified
identity `name$in$<module>`. Sema records it (record_displaced_fn, now
also for module values) and resolve_displaced_global_ident binds each
reference: a lexical binding; the current module's own declaration (a
c_import's value is an import, not the importer's declaration); the flat
declaration when visible; else a visible displaced one. The ident is
rewritten, so MIR, comptime and codegen read the declaration Sema chose.

The repro still failed on a stage1 built from this tree before the change
(`shadowing is not allowed for 'PACKAGE' (a global of module
lib/std/re/defs.w)`), so #1708 had not closed it.
ehartford pushed a commit that referenced this pull request Sep 27, 2026
…`let`/`const`/`global` of another module is displaced, not "shadowing is not allowed" (§18.2, §18.3)

Fixes #1703

Every module's `let`, `var`, `const` and `global` shared one flat Sema
table keyed by name, so register_top_level_global_decl reported "shadowing
is not allowed" for the second declaration of a name in any module: a
program's `const PACKAGE` beside the source-compiled std.re's `pub let
PACKAGE` (stage1 only — the release binary reads std.re as bundle-interface
storage, which already had its own table), two modules' private `SCALE`, a
program's `let PI` beside `use std.math`.

The fix is #1350's for fns, applied to values: displace_colliding_globals
(run once every source, interface and c_import declaration is in the pool)
keeps the short name for the root module's declaration, then the first
other owner, and gives each other owner's declaration its module-qualified
identity `name$in$<module>`. Sema records it (record_displaced_fn, now
also for module values) and resolve_displaced_global_ident binds each
reference: a lexical binding; the current module's own declaration (a
c_import's value is an import, not the importer's declaration); the flat
declaration when visible; else a visible displaced one. The ident is
rewritten, so MIR, comptime and codegen read the declaration Sema chose.

The repro still failed on a stage1 built from this tree before the change
(`shadowing is not allowed for 'PACKAGE' (a global of module
lib/std/re/defs.w)`), so #1708 had not closed it.
ehartford pushed a commit that referenced this pull request Sep 27, 2026
…`let`/`const`/`global` of another module is displaced, not "shadowing is not allowed" (§18.2, §18.3)

Fixes #1703

Every module's `let`, `var`, `const` and `global` shared one flat Sema
table keyed by name, so register_top_level_global_decl reported "shadowing
is not allowed" for the second declaration of a name in any module: a
program's `const PACKAGE` beside the source-compiled std.re's `pub let
PACKAGE` (stage1 only — the release binary reads std.re as bundle-interface
storage, which already had its own table), two modules' private `SCALE`, a
program's `let PI` beside `use std.math`.

The fix is #1350's for fns, applied to values: displace_colliding_globals
(run once every source, interface and c_import declaration is in the pool)
keeps the short name for the root module's declaration, then the first
other owner, and gives each other owner's declaration its module-qualified
identity `name$in$<module>`. Sema records it (record_displaced_fn, now
also for module values) and resolve_displaced_global_ident binds each
reference: a lexical binding; the current module's own declaration (a
c_import's value is an import, not the importer's declaration); the flat
declaration when visible; else a visible displaced one. The ident is
rewritten, so MIR, comptime and codegen read the declaration Sema chose.

The repro still failed on a stage1 built from this tree before the change
(`shadowing is not allowed for 'PACKAGE' (a global of module
lib/std/re/defs.w)`), so #1708 had not closed it.
ehartford pushed a commit that referenced this pull request Sep 27, 2026
…`let`/`const`/`global` of another module is displaced, not "shadowing is not allowed" (§18.2, §18.3)

Fixes #1703

Every module's `let`, `var`, `const` and `global` shared one flat Sema
table keyed by name, so register_top_level_global_decl reported "shadowing
is not allowed" for the second declaration of a name in any module: a
program's `const PACKAGE` beside the source-compiled std.re's `pub let
PACKAGE` (stage1 only — the release binary reads std.re as bundle-interface
storage, which already had its own table), two modules' private `SCALE`, a
program's `let PI` beside `use std.math`.

The fix is #1350's for fns, applied to values: displace_colliding_globals
(run once every source, interface and c_import declaration is in the pool)
keeps the short name for the root module's declaration, then the first
other owner, and gives each other owner's declaration its module-qualified
identity `name$in$<module>`. Sema records it (record_displaced_fn, now
also for module values) and resolve_displaced_global_ident binds each
reference: a lexical binding; the current module's own declaration (a
c_import's value is an import, not the importer's declaration); the flat
declaration when visible; else a visible displaced one. The ident is
rewritten, so MIR, comptime and codegen read the declaration Sema chose.

The repro still failed on a stage1 built from this tree before the change
(`shadowing is not allowed for 'PACKAGE' (a global of module
lib/std/re/defs.w)`), so #1708 had not closed it.
ehartford added a commit that referenced this pull request Sep 27, 2026
…are their own, unused import collisions are not errors (#1751)

* Sema/MIR: a place against a `&T` enum payload borrows — `Some(ctx)` for `Option[&Ctx]` observes `ctx` (§3.8, D22)

Fixes #1627

- Sema: check_call's no-signature argument loop marked every variant
  constructor argument moved, whatever the payload type; the static
  `Option[&Ctx].Some(x)` path did the same. payload_arg_auto_refs asks the
  payload demand (can_auto_ref_arg): a `&T` payload borrows the place
  (check_borrow_create) and records the node in auto_ref_payload_args, which
  collect_expr_view_deps reads as `&place` — so the Option carries the view's
  origin and a write to `ctx` while `z` is live is refused.
- Sema: `.Some(x)` (check_variant_shorthand_args) marked nothing at all, so
  `.Some(ctx)` into an owned `Option[Ctx]` left `ctx` usable over its
  moved-out bytes (#764 class); it now consumes or borrows by the same rule.
- MIR: the call-form and static constructors lowered the argument plainly —
  `move ctx` into the `&Ctx` slot, blanking `ctx` (analyze audit:all:
  "use-after-kill"). lower_payload_arg applies the #933 adjustment chain
  (auto-ref, contextual copy, auto-deref) for all three spellings.
- Validator: validate-all said ok over that aggregate. The typed validator
  now rejects an enum payload that is a value where the payload is a
  reference to it (mir_validate_aggregate_missing_borrow), pinned by a
  hand-built MIR test.

* Frontend/Sema: a module's top-level values are its own — a colliding `let`/`const`/`global` of another module is displaced, not "shadowing is not allowed" (§18.2, §18.3)

Fixes #1703

Every module's `let`, `var`, `const` and `global` shared one flat Sema
table keyed by name, so register_top_level_global_decl reported "shadowing
is not allowed" for the second declaration of a name in any module: a
program's `const PACKAGE` beside the source-compiled std.re's `pub let
PACKAGE` (stage1 only — the release binary reads std.re as bundle-interface
storage, which already had its own table), two modules' private `SCALE`, a
program's `let PI` beside `use std.math`.

The fix is #1350's for fns, applied to values: displace_colliding_globals
(run once every source, interface and c_import declaration is in the pool)
keeps the short name for the root module's declaration, then the first
other owner, and gives each other owner's declaration its module-qualified
identity `name$in$<module>`. Sema records it (record_displaced_fn, now
also for module values) and resolve_displaced_global_ident binds each
reference: a lexical binding; the current module's own declaration (a
c_import's value is an import, not the importer's declaration); the flat
declaration when visible; else a visible displaced one. The ident is
rewritten, so MIR, comptime and codegen read the declaration Sema chose.

The repro still failed on a stage1 built from this tree before the change
(`shadowing is not allowed for 'PACKAGE' (a global of module
lib/std/re/defs.w)`), so #1708 had not closed it.

* Sema: two imports that provide one name are an error only where the name is used; a named import provides only what it selects (§18.2)

Fixes #1221

`use c_import("raylib.h")` beside `use std.math` (or even `use
std.math.TAU`) was "shadowing is not allowed for 'PI'" at the header's
declaration, in a program that never names PI. With module values
displaced per module (#1703) the declarations coexist; this change decides
the uses by §18.2 precedence (resolve_displaced_global_ident):

- tier 2: the current module's own declaration;
- tier 3: the explicit imports that provide the name — a c_import provides
  its values to the module that imports it, `use m` provides m's public
  names, and `use m.X` / `use m.{X, Y}` provides the names it selects and
  nothing else (Resolve records them: ResolvedImport.selected, carried to
  Sema as module_import_selected); a named import beats a whole-module one;
- tier 5: the one declaration the std fallback reaches.

Two providers at the tier that decides a use is an error at that use —
"'PI' is ambiguous: `std.math` and this module's c_import both provide it",
a label at each declaration, and the spelling that picks one ("a named
import picks one: `use std.math.PI`"). A same-module redeclaration keeps
"shadowing is not allowed".

* tests: pin that a producer's `lend` fn item renders its constructor only (§16.2b.4, ruling §9)

Fixes #1500

The bug does not reproduce on this tree: Modeled C stage 8 (d783366,
#1601) made facade_render_lend_item refuse an fn item that names a
resource operation (facade_render_is_resource_op: a `from`, `init`,
`preinit`, `drop` or `destroys` of any resource), so `fn db_prepare /
lend` beside `from db_prepare(out param 2)` adds facts to the constructor
and renders no lend method. The installed compiler (main) and this
branch's base both render only `Statement.prepare(d, sql, tail)` and the
receiver form `Database.prepare(sql, tail)`. Nothing pinned it: this test
calls the parent with an out slot and expects the one `prepare` Database
has to refuse it.

* docs: the one-liner table shows sed's global regex substitution as `/re/g.replace` (#1607: `g` is the regex spec's replace-all flag)

* Sema: the later import shadows the earlier (§18.2, Eric's ruling; Fixes #1221)

Fixes #1221
Fixes #993

Eric's ruling on explicit imports that provide one name: "which comes last
shadows the others." There is no ambiguity error among explicit imports and
no named-vs-whole-module ordering; a `use c_import(...)` is an import and
takes its place in the order. Tiers are unchanged.

- Values (resolve_displaced_global_ident): lexical, then the current
  module's own declaration, then last_import_provider — of the candidates an
  explicit import of the current module provides, the one whose import sits
  at the highest offset — then the std fallback, where D29's ambiguity for two
  std candidates stays (emit_ambiguous_fallback_use). The use-site ambiguity
  error of the previous commit is gone.
- Import order: Resolve's span_start of each `use` is carried to Sema as
  module_import_offsets; a c_import declaration's decl_is_c_import is now
  1 + the offset of its importing `use c_import` (was 1). A named import
  still provides only what it selects; the prelude edge is tier 4.
- Fns (#993) share the mechanism: resolve_displaced_fn_ident asks
  last_import_provider after the current module's own fn. The flat merge
  had ordered modules by dependency, so `use c` then `use a` (c importing a)
  called c's helper whatever the program wrote.

Tests: both orders of a header `PI 3` and `use std.math` (3.14159 / 3),
a module's own declaration beating the header, same-module redeclaration
still an error, and #993's two orders; err_1221_ambiguous_import_use is
removed with the error it pinned.

* Sema: every import is also a namespace (§18.2, D70)

§18.2 (D70, #1752): a name a later import shadows stays reachable through
its import's namespace — a module's last path segment (`math.PI`) or its
full path (`std.math.PI`), a header's file name without `.h`
(`raylib.PI`), or the `as` name (`use m as n`, `use c_import(...) as n`).
None of these compiled before (`undefined variable`, `unknown qualified
extension method 'math.sqrt'`, `use … as` a parse error).

- Parser: `as NAME` after a `use` path or a `use c_import(...)`, kept in
  AstPool.use_alias_map.
- Resolve: each import carries its namespace name and its module's dotted
  path (ResolvedImport.namespace / module_text); inline C text has no
  namespace. Frontend.init_module_graph hands every namespace, c_imports
  included, to Sema (ns_modules/ns_names/ns_fulls/ns_targets/ns_offsets).
- Sema (D65: it owns the resolution): rewrite_namespace_access resolves
  `ns.member` — in check_expr for a value and at the top of check_call for
  a callee, before the method / qualified-extension reading — to the
  declaration that import provides: the module's own declaration, by the
  per-module identity #1703's displacement gives it; a c_import's value by
  the offset of its `use c_import` (decl_is_c_import). The node becomes that
  declaration's ident (Ast.bind_namespace_ident), marked so the short name is
  never re-resolved by import precedence; MIR and codegen read an ordinary
  ident. A namespace name is tier 3: a binding, visible type or fn of that
  name keeps it (a local `math` shadows the namespace). std.math's
  transcendental builtins (§17.6a) are reachable as `math.sqrt(x)`.
- Errors: two imports sharing a namespace name, at the use, naming both
  and offering `as`; a member the import does not provide; a private
  member. A callee the module does not declare stays a qualified extension
  call (`slug.tag(t)`). A namespaced type that another visible declaration
  shadows is refused loudly (types keep short names; #1757).

* MIR: a constructor payload borrows where Sema recorded the borrow, and re-derives no other adjustment (#1627 follow-up)

The #1627 fix made the call-form (`Some(x)`) and static (`Option[&T].Some(x)`)
constructors lower every payload through lower_payload_arg — the
shorthand's whole type-driven call-argument chain (auto-ref, contextual
copy, auto-deref). On a generic specialization that chain reached
MirBuilder.lower_auto_deref_call_arg, whose type walk asks
Sema.type_implements_trait_frozen about a generic instance no Sema pass had
preregistered, and the frozen phase check aborted
test/spec/spec_ss10_8_error_trait.w (std.result's ContextError path):
"BUG: type_implements_trait_frozen generic blanket path needs preregistered
answer" (lldb: lower_concrete_specialization → lower_expr's NK_CALL
constructor arm → lower_payload_arg → lower_auto_deref_call_arg).

The cause is MIR deciding what Sema already decided (D65). Sema records
every payload it borrows (auto_ref_payload_args, payload_arg_auto_refs);
lower_constructor_payload_arg now borrows exactly those nodes — a recorded
borrow MIR cannot realize is a phase bug — and lowers every other payload
as before (`lower_expr`). The shorthand `.V(x)` path keeps its own #933
chain, unchanged from before #1627.

* Sema: a nullable facade callback's `Some(...)` userdata is borrowed, a temporary as a place (#1627/#1618)

A nullable callback's userdata parameter is `Option[&U]`, but
Sema.facade_prepare_callback_call checks the userdata argument with no
expected type (its `U` is bound from that argument), so `Some(Ctx { .. })`
checked as `Option[Ctx]`: check_call's variant loop took the payload as
owned (payload type `T`), payload_arg_auto_refs never saw a `&T` demand,
and nothing recorded the borrow. MIR then retyped the constructor to the
parameter's `Option[&Ctx]` and, since f272a5d borrows only where Sema
recorded it, stored the temporary's value in the `&Ctx` slot; the typed
validator refused it (behav_sqlite_facade_end_to_end.w:54, "enum payload 0
is a value where the variant's payload is a reference to it"). Before
f272a5d MIR borrowed by type on its own; main never drops the temporary
(debug-alloc: leak count=2) and reports `Some(ctx)` of a place as a move.

facade_prepare_callback_call now marks the userdata constructor it checks
(Sema.facade_userdata_ctor) when the callback is nullable, and
payload_arg_auto_refs borrows an owned payload of that constructor as it
borrows one against a `&T` payload: the borrow is recorded
(auto_ref_payload_args), a place stays live (check_borrow_create, no
move), and MIR materializes a temporary and borrows it, dropped once at
the end of the statement.

behav_c_facade_callback_userdata_temporary.w pins a temporary (dropped
once, after its call's line), the static `Option[&Ctx].Some(..)` spelling
and a place used again after the call; on f272a5d's stage1 the temporary
case is the validator error above and the place case "use of moved value".

* MirValidationTests: the #1627 test fn needs no explicit Unit return (unit-return-review)

---------

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant