Skip to content

Type checker: D74 entry sources and chain moves, field-view bindings (#1531), generator/import follow-ups, tools lane - #1790

Merged
ehartford merged 21 commits into
batch2-emitc-modeledcfrom
batch2-sema
Sep 27, 2026
Merged

ehartford merged 21 commits into
batch2-emitc-modeledcfrom
batch2-sema

Conversation

@ehartford

@ehartford ehartford commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Stack layer 4. Fixes #1741 #1738 #1489 #1483 #1529 #1447 #1739 #1754 #1743 #1745 #1305 #1557 #1740 #1531 #1744 #1335 #1759; interim for #1710 (records the move). #1531 respelled 311 sites incl. two example lines (D74.3). New tools-tests lane compiles every tools/*.w. Stopped: #1478 #1438 #1746 #1732 #1737 #1457 #1757 (design / #751). Draft until green.

@ehartford
ehartford added this pull request to stack #1793 September 27, 2026 11:01
@ehartford ehartford changed the title batch2 sema Type checker: D74 entry sources and chain moves, field-view bindings (#1531), generator/import follow-ups, tools lane Sep 27, 2026
Eric Hartford added 21 commits September 27, 2026 09:18
…t call (#1741)

`g |> take(1)` is `take(g, 1)`, but check_generic_pipeline_call never
marked the left-hand side (or the stage's own arguments) moved, so a
generator used after `g |> stage(...)` was accepted and the later loop
ran over the reset-on-move blank (§13.4: a generator value is consumed
once; §2.2). The pipeline path now applies the direct generic call's
rule (check_call, #737): a by-value parameter consumes, a declared `&T`
parameter borrows.

Before (base stage1): err_1741_pipeline_moves_generator.w compiles and
prints `1` with an empty loop. After: `use of moved value` at `for x in g`.
behav_1741_pipeline_borrow_stage_keeps_value.w pins that a `&T` stage
still borrows.

Fixes #1741
…mber line is an error (#1738)

1. A match-arm binding that shadows a local was reported at 1:1:
   Sema.scope_put bound without a node, so scope_put_at's shadowing
   error had span 0. scope_put is gone; each of its 31 callers (pattern
   bindings, parameters, for/comprehension bindings, closure parameters,
   `with` bindings, tuple destructuring, regex captures, scope labels)
   now passes the node that declares the name.

2. The impl/extend and trait member loops ended silently at the first
   token they do not accept, and the rest of the indented body parsed as
   top-level declarations (a later method became a free fn and reported
   "undefined variable self"). A token still inside the indented body is
   now a parse error at that line, and the rest of the body is skipped.

Before (base stage1): the shadowing error printed at `shadow.w:1:1`;
`let k = 3` inside an impl produced "undefined variable" errors for the
next method. After: err_1738_match_binding_shadow_site.w reports 13:12
(the pattern), err_1738_impl_unrecognized_member_line.w reports
"expected a member of this `impl`" at 12:5. The unused-label warnings
the issue also names already point at their labels on main.

Fixes #1738
…ear time (#1489)

dump_drop_state_module (and its drop-plan and place-map siblings)
appended each body's text to a growing str, copying the whole dump per
body. A stage1 lowers every embedded corpus body in-unit (13k bodies, a
235 MB drop-state dump for a 30-line file), so
test/phase/dump_drop_state_move.w never finished: the base stage1 was
killed at the 120 s probe (the issue saw >8 min; the test runner's cap is
300 s). The module and body dumps now build into one StringBuilder.

After: the same check finishes in 20 s on stage1 and the fixture passes.
The dump still covers every lowered body, std's and the in-unit corpora
included; a release binary links the corpora as bundles, so its dump is
shorter by construction, not by a formatting difference.

Fixes #1489
…block (#1483)

A switch lowering creates `mir.default.unreachable` on demand, and each
MIR body emitter must terminate it after the body. The ordinary, mono
and closure emitters did (three inline copies); the module-constant
initializer (`__with_init_const_*`) and the trait default-method emitter
did not, so a module `let` whose initializer has `or`/`and`/`if`/`match`,
or a default method using `or`, failed LLVM verification ("Basic Block
... does not have terminator"). One helper,
mir_terminate_default_unreachable, now ends all five emitters.

Before (base stage1): behav_1483_module_let_control_flow_init.w fails
code generation (`__with_init_const_Z`, and `W.either` for the default
method alone). After: prints `true false 7 11` / `true`.

Fixes #1483
…move drop state (#1529)

dump_drop_plan_tuple_fields_moved.w expected `remaining=_2=Maybe, ...`
long after #1394 made the state `_2=Init` — and nothing failed, because
parse_test_directives_for_target stops at the first line that is not
`//!`, and the fixture's expectations sat below a `//` comment. The
fixture passed on a dead expectation (a tool that stayed silent). Two
other fixtures had the same shape: behav_callable_alias_field_call.w
(its three expect-stdout lines were never checked) and
test/mut_nested_mutating.w (its expect-error was never checked).

The parser now reports a directive it would honor that sits below the
header ("directive on line N is below the directive header ... move it
up"). The three fixtures move their directives up; each holds (42/21/126;
"nested mutating calls on the same place").

The drop-plan fixture now pins the state the reset-on-move lattice
produces: `storage-dead local=_2 remaining=_2=Init, _2.0=Reset,
_2.1=Reset` (a moved-out field is blanked to Reset, #1384/#1488; a move
out of a sub-place vacates only that sub-place, #1394). Its "no drop of
`_2`" half cannot be a substring check over a dump that covers std's
bodies too (they have `place=_2` rows), so it moves to
trace_ownership_tuple_fields_moved.w, scoped to `run:_2` (no `event=drop`).

Before (base stage1): the old fixture passes although `_2=Maybe` appears
nowhere in the dump. After: the old fixture fails with the directive
error; the rewritten fixtures pass.

Fixes #1529
…rnings keep their spans (#1447)

1. `print(m.unwrap())` with a non-Display `Match` reported the bound
   failure and then "unknown method 'to_str'" inside the embedded
   std/builtins.w: check_generic_call went on to check `print[T:
   Display]`'s body under the failed instantiation. A failed bound now
   returns before the body is checked, as an uninferable type parameter
   already did (#598).

2. Every warning a `build`/`run` printed read 1:1 of an empty line: the
   MIR phase and the four Codegen seams moved the root file's source text
   out of the compilation unit, and warnings render after codegen. They
   now clone it. (The issue's "three-line script does not warn" is the
   lint's design: `cur = cur ++ x` starts with the accumulator and is
   not flagged; the reorder.w warning is `types = cur ++ types`.)

The build-path span needed a way to assert on a successful build's
stderr, so the test runner gains `//! expect-build-stderr:` (the build
must succeed and print each line).

Before (base stage1): err_1447_failed_bound_no_std_cascade.w prints the
std/builtins.w error; `with-base build behav_1447_build_warning_span.w`
prints the warning at `:1:1` under an empty source line. After: one
error at the call; the warning at 13:9 under `types = cur ++ types`.

Fixes #1447
…hat collection (#1739)

`let st = Stack { items: ["p", "q"] }` with `type Stack[T] { items:
Vec[T] }` left T uninferred ("cannot infer generic method type parameter
'T'" at the first method call): with no expected instance the fields are
checked with no expectation, so the element list took the default
fixed-array type `[str; 2]` (§4.3c rule 1), which binds nothing against
`Vec[T]`. The initializer already decides T; the annotation was ceremony.
A generic fn's `Vec[T]` parameter had the same hole (`count_all(["a"])`,
`[1, 2, 3] |> count_all()`: "the argument's shape does not match").

A sequence or map literal whose declared destination names a collection
(Vec, HashSet, BTreeSet; HashMap, BTreeMap) with undecided type
arguments now builds that collection, and its elements decide the type
argument, exactly as under `let st: Stack[str] = ...`. The literal
records the collection in Sema.collection_literal_hints before it is
checked (hint_collection_literal): a generic struct literal's fields, a
generic callee's parameters, a pipeline stage's arguments and its
left-hand side. MIR lowers it from its Sema type as before.

Before (base stage1): behav_1739_generic_struct_literal_collection_field.w
fails "cannot infer generic method type parameter 'T'". After: `2 pq`,
`3 6`, `2 true`, `2 3` (Vec[str], Vec[i32], BTreeMap[i32, str], and the
generic call and pipeline).

Fixes #1739
…ide (#1754)

`f(if c: a ++ "yy" else: a ++ "z")` with `fn f(s: &str)` was refused ("if
expression of type `str` cannot produce `&str`"): check_call passed the
parameter type `&str` as the argument's expectation, resolve_contextual_join
kept it as the join's result type, and every owned arm failed. Per §3.8 an
owned `T` meets a `&T` parameter through auto-ref, and per D22 §8.2 a
reference expectation is not an owned anchor (rule 2) and no owned
temporary is borrowed to force a reference result (rule 5).

An if/match argument meeting an immutable `&T` parameter is now checked
with its arms against `T` (a literal arm is the owned `str`, a numeric
arm takes `T`'s width) and a join with no anchor: owned arms give an owned
result the call borrows, view arms a view (check_join_arg_at_ref_param;
Sema.borrow_pointee_join_node marks the one join it applies to). Method
arguments publish their declared `&T` parameter type too
(method_sig_expected_arg_type), as #1712 anticipated, so both call forms
share the rule.

Before (base stage1): behav_1754_owned_join_at_ref_param.w is refused
four times ("if/match expression of type `str` cannot produce `&str`",
"`i32` cannot produce `&i64`"). After: `3 3 4 1 6` / `42 7 9`.

Fixes #1754
`pub fn g[T](a: T) -> i32: K` with `pub let K: i32 = 5` in the same
module failed "undefined variable" at K when instantiated (pub or
private, let or const), while a private fn resolved. check_fn_body_concrete
checks a specialization "in the callee's own lexical environment" by
replacing the whole scope stack with empty vectors — and the module-level
scope (every module's globals, below scope_starts[1]) went with the
caller's locals. It now keeps that module-level prefix (and the map
entries of globals a caller local had shadowed); visibility is still
judged per lookup against the callee's module.

Once Sema accepted it, a generic body that reads a `global var` read an
unbound stack slot (41615428, -1): the specialization emitter was the one
MIR body emitter that did not bind global proxy locals to the global's
storage. All five emitters now share mir_bind_global_locals.

Before (base stage1): behav_1743_generic_reads_module_globals.w fails
"undefined variable". After: `735 735` / `4001 4002 60` (a pub let, a
private let, a const, a global var mutated through two instantiations,
and a generic method).

Fixes #1743
…in specializations (#1745)

With a user `type MutexState { x: i32 }`, `Mutex.new(40)` failed "cannot
lower projected assignment" and `g.pull()` beside a user `PullCore`
corrupted the heap. Sema typed std.sync's body against std's MutexState
(D29 keeps both declarations, the std one under the `$std` LLVM slot);
codegen lost it twice:

1. Only sema_type_to_llvm routed a std-tier TypeId of a shadowed name to
   its `$std` slot. The MIR paths (mir_sema_type_to_llvm,
   mir_type_cg_name_at, the #1446 split lookups) applied only the
   `name$tid` half, so `(*state).value` projected through the user's
   one-field struct. The routing now lives in nominal_cg_sym_for_tid,
   which every TypeId-to-LLVM path reads.

2. By-name type lookups in a body (`sizeof[MutexState]()`, casts) decide
   the tier from the current function's declaration. A specialization
   (`Mutex.new__receiver__…`, `gen_pull__sema__…`) has none under its own
   name, so it read as user code and `sizeof[MutexState]` allocated the
   user's 4 bytes for std's 16 (PullCore: 24 for 40). The specialization
   emitter now records its template's declaration as the tier node.

Before (base stage1): behav_1745_user_type_named_like_std_private.w
fails code generation; with the first half alone the pull program dies
at shutdown with "invalid free". After: `4 38` / `7 a 2`, and the IR
allocates 16 bytes for MutexState and 40 for PullCore.

Fixes #1745
…ire the audit exclusion (#1305)

MIR has typed an async call's result local as Task[T] since (the
`--dump-mir` of the issue's fixture now shows `_1: Task[Unit]` and
`copy _6.fiber_id`), so the codegen audit's stated #1305 exclusion — skip
every place that feeds a fiber intrinsic — is removed; audit:all over the
issue's fixture and the new one reports violations=0.

FIBER_AWAIT still chose the loaded type by convention: a side table keyed
by MIR local id (filled at each async spawn, never cleared between
functions), then the last spawn's type, then i32. In an async fn whose
Task[str] parameter is local _1 — the id an earlier function's spawn of
an i64 task used — the str result was loaded as an i64 and `s.len()`
crashed. The awaited type is now the Task[T]/ScopedTask[T] operand's own
generic argument (mir_task_awaited_sema_type); a task whose awaited type
cannot be lowered is a code-generation error, not an i32 guess.

Before (base stage1): behav_1305_await_reads_task_type.w exits 139.
After: `42 12 7`.

Fixes #1305
…op fn (#1557)

`type N { n: i32, next: Vec[N] }` with any drop of a Vec[N] crashed the
compiler (exit 139, a stack overflow in the LLVM backend's caller). The
Vec element loop (and the HashMap/HashSet and SlotMap element loops)
inlined each element's drop glue through mir_emit_drop_ptr_for_sema_type,
so N's glue expanded N -> Vec[N] -> N without end. Recursive enums already
went through a named per-type fn (ensure_enum_drop_fn); a struct element
now drops through ensure_structural_drop_fn, which declares the fn before
emitting its body, behind the same sentinel guard member drops use (#697).

Before (base stage1): `with test behav_1557_vec_recursive_type_drop.w`
itself dies with 139 while compiling. After: `7 7` / `7` — seven nodes
counted, seven Tag drops, each exactly once.

Fixes #1557
…lace (#1710)

`o?.b` (a Copy field) then `o?.a` printed `Some(4)` then `Some()`: Sema
types the chain as an observation of its base (it marks nothing moved and
carries the base's view origins), but lower_optional_chain moved the whole
Option into a temporary, and reset-on-move blanked `o`. The same for a
tuple element (`t?.1` then `t?.0`) and for a payload lent to a reader
(`s?.len()` twice read `Some(3)` then `Some(0)`, and `s.unwrap()` was "").

A chain whose base is a place and that takes nothing out of it — a Copy
field, a payload handed to a builtin reader, or one lent to a method
whose receiver borrows — now reads through the base's place
(optional_chain_observes_base); a reader intrinsic observes the payload
there instead of moving it.

Not changed: a chain that takes a non-Copy field out of a named place
(`o?.a`, `profile.address?.zip`) still moves the base into a temporary,
as the §10.3 `map` desugar does, and Sema still records no move of the
base. What that should be under D32/D22 is open on the issue.

Before (base stage1): behav_1710_optional_chain_observes_receiver.w prints
`Some()`, `Some(7) Some()`, `Some(3) Some(0) `, `4 `. After: `Some(4)`,
`Some(xyz)`, `Some(7) Some(pq)`, `Some(3) Some(3) abc`, `4 xyz`.

Refs #1710
…er's width (#1740)

`analyze audit:all` over a program that iterates a BTreeMap reported
"call BTreeMap.key_at__receiver__… param=1: marshaled LLVM type
disagrees with FnAbi": BTreeMap.insert's `var i = 0` (i32) widens into
key_at's `index: i64`. The direct call path evaluates each operand
against its parameter's type, but marshal_mir_call_arg — the one marshal
point of generic calls (receiver and __sema__ specializations) —
recorded and returned the operand at its source width; a later fixup
widened it at the call, a second derivation the audit (D6: one FnAbi,
read by caller and callee) rightly refused. The scalar argument is now
coerced to the parameter's own LLVM type, by the operand's signedness,
where it is marshaled.

Before (base stage1): the issue's program reports 1 violation; a user
`Bag[T].shift(k: i64)` called with i32 values reports 2. After: 0 for
both, and the program still prints `-2`.
behav_1740_generic_method_widened_arg_audit.w runs the audit through the
pre_d_build_runner (it needs a stage2 or release binary, like
behav_fn_abi_async.w).

Fixes #1740
…ement does (#1531)

§3.8: "an unannotated `let` binds the view unchanged, while a typed
binding is an owned-value demand (D22 §6.2, D27). This is uniform across
field projections and collection element access." `let x = v[0]` bound a
view, but `let x = s.n` (a Copy field) bound a copy, so `s.n = 5` under a
live `x` was accepted. The Copy field binding now registers the same
path-precise borrow of its root a non-Copy field view does (#1530), and a
join of Copy fields (`if c: s.n else: s.m`) is a view join like
`if c: v[0] else: v[1]`. `let x: i32 = s.n` is the copy. MIR still reads
a Copy field view's value at the binding: while the view is live its place
cannot change, so the copy and the alias read the same bytes. `var x =
s.n` is unchanged (a mutable binding is an owned demand here).

Two diagnostics follow the rule:
- Every view diagnostic that names a Copy-typed view binding (a live-view
  mutation, "view 'x' may outlive its origin", a write through a
  view-bound binding) now points at the binding and offers the ruling's
  copy spelling: "help: change the binding to `let x: i32 = ...`".
- A write *through* a raw-pointer binding (`let st = self.state;
  st.table.insert(..)` with `state: *mut S`) writes the pointee, not the
  viewed place; it is no longer refused as a write through a read-only
  view (§15.17).

Respelled to the copy (`let x = a.f` -> `let x: T = a.f`, each a
binding its function mutates or moves the field's owner under), 311
sites, all by the fix-it above (a diagnostic-driven rewrite, checked
until `with-stage1 check src/main.w` is clean):
  compiler: SemaCheck.w 98, CodegenDispatch.w 74, Parser.w 50,
    CodegenTraits.w 28, Codegen.w 13, compiler/Frontend.w 7, SemaFacade.w 4,
    compiler/Backend.w 4, ComptimeEval.w 3, Lexer.w 3, Lsp.w 3,
    MirLower.w 3, CImport.w 2, SemaDecl.w 2, AnalysisContract.w 1,
    AsyncMir.w 1, MirCore.w 1, compiler/Compilation.w 1
  std: json.w 3, regex.w 2 (find_all's span before the push), build.w 1
    (ToolArchiveFile.close's take-and-clear)
  build layer: build/zlib_gunzip.w 1 (OutputFile.close)
  examples (a spec change updates them in the same change):
    examples/json-parser/json.w 1, examples/ecs/src/world.w 1
  tests: behav_sibling_field_mutation_under_field_view.w 2,
    behav_iter_mut_self.w 1, behav_view_of_local_dead_before_mutation.w 1,
    spec_ss13_2_iter_one_implementation_rule.w 1,
    d_acceptance/behav_iter_mut_self.w 1
Each respelled test keeps its assertion: the values it prints were the
copies it now spells. test/non_compliant/d22/origin_ephemeral_struct_after_clear.w
now produces its required verdict ("cannot mutate `map` while `view` is a
live view into it"); it stays in the excluded matrix for its owner.

Before (base stage1): err_1531_copy_field_let_is_view.w compiles and
prints 1. After: "cannot mutate `s` while `x` is a live view into it",
with the fix-it; behav_1531_copy_field_view_and_copy.w pins the copy
spelling and the Copy field view join (`1 5` / `7 3 9`).

Fixes #1531
§18.2: "Names are imported with `use`" — `use math.vector.{Vec3, dot}`
introduces the names it selects. `use sa.X` made every public name of `sa`
visible: Resolve records each import's selection
(module_import_selected, #1221) but visibility asked only whether the
module is imported.

A name of a non-std module the current module imports only by named
imports, none of which selects it, is no longer visible through them
(unselected_import_path, read by decl_visible_from_current_gated and
decl_node_visible_from_current). The diagnostic names the import and the
fix: "'Y' is not imported: `use sa.X` names only what it selects (§18.2);
add `Y` to that import, or import the whole module". A whole import, or a
second named import that selects the name, brings it in. Unchanged: std
modules (every public std name stays available through the §18.2
fallback tier), a displaced identity (judged by its short name), and
methods — the selection governs the names a module spells, and
`UserService.builder().with_config(..)` calls a method of a type the
import never names (examples/service).

Sweep before the change landed: `with-stage1 check` over the compiler
(src/main.w) and every test/example/tool/uat file with a non-std dotted
`use` (177 files); against the base compiler, the only new failures were
this commit's own fixtures.

Before (base stage1): err_1744_named_import_hides_unselected_value.w
checks clean and the issue's program prints 5 and 6. After: the error
above at `print(Y)` (and at `fy()`), and
behav_1744_named_imports_select.w prints `1 5 6 7` through
`use m.{X, Y}`, `use m.fy`, `use m.Pt`.

Fixes #1744
…ed (#1335)

Nine of the 29 tools no longer compiled against the current language and
std: they named the D30-deprecated internal seams (with_fs_*,
with_exec_argv_capture), used str parameters that now consume, or
imported modules by retired paths. Nothing noticed because no lane
compiled them.

build/tools_lane.w adds the `tools-tests` target (a dep of :test): every
tools/*.w is built with the release compiler (a scratch-project build.w
is checked), never run. The list is the directory, so a new tool is
covered on arrival.

Ported: annotate_receivers, debug_sema_layout, insert_std_uses,
materialize_predicate, migrate_d22_copy_views, migrate_method_arg_moves,
migrate_seams, rt_in_unit_sweep, sweep_gate_corpus. All 29 compile with
stage1 at 76cf0bf+batch2-sema.

Fixes #1335
…nder every command (#1759, §18.5b, D74)

`with check tools/battery.w` failed "expected declaration" at the first
top-level statement while `run` and `build` accepted the file: `check`
(and `ir`, `emit-c-header`) parsed the root through Compilation.compile_file,
which never enables the parser's implicit-main mode, so top-level statements
were only accepted by the two entry paths. D74.1 (§18.5b): a module file
holds declarations; a file whose top level also holds executable statements
is an entry source whose statements are its `main`, it may not also declare
`fn main`, an imported module may not hold executable statements, and every
command applies one rule.

- `check`, `ir` and `emit-c-header` parse the root as an entry source
  (Compilation.compile_entry_file), the same path as `run` and `build`.
- An imported module (parsed by the frontend's import merge and by Resolve)
  is in module mode: a top-level statement is refused by name — "module
  '<path>' holds an executable statement at its top level; a module file
  holds declarations, and only an entry source runs statements (§18.5b,
  D74)" — instead of "expected declaration"; the statement is parsed so the
  span covers it and the rest of the module is still diagnosed.

Before (base stage1): err_implicit_main_check.w (now `expect-check-stdout:
ok`) fails "check failed with exit code 1"; err_1759_entry_source_with_fn_main.w
reports "expected declaration" instead of the fn-main conflict;
err_implicit_main_import_stmt.w reports "expected declaration";
`check tools/battery.w` rc=1 at 84:1. After: all four fixtures pass and
`check tools/battery.w` prints ok. behav_1759_entry_source_check.w pins a
tool-shaped entry source (a `use`, helper fns, a top-level `let`, a loop)
through the runner's build and run.

Not changed: the LSP still parses an open root through compile_source_text
(module mode); a tool script open in an editor reports the old error.

Fixes #1759
…t takes a field out records the move (#1710, §10.3, D74 interim)

`o?.a` (a non-Copy field of a named base) moved the whole Option into a
temporary with no move recorded: the next `o?.a` printed `Some()` — a
silent blank. D74 rules that a chain on a named place yields a view
(`Option[&U]`), which is D22 stage-4 work; until it lands, the move that
today's lowering performs is at least recorded.

- Sema decides, per chain, whether it reads its base in place (a Copy
  field, or a method whose receiver borrows the payload) and records it in
  Sema.optional_chain_observing_nodes (record_optional_chain_verdict). A
  chain on a named base that takes a non-Copy field out, or hands the
  payload to a consuming method, marks the base moved — a whole binding
  through mark_moved_if_consumed, a field path (`p.address?.zip`) through
  mark_field_moved as a partial move of its root — so a later use is the
  ordinary "use of moved value" / "use of partially moved value". A
  temporary base is taken apart freely.
- MirLower reads the verdict: an observing chain reads through the base's
  place; its own optional_chain_observes_base derivation from types is
  deleted (D65: one owner per fact).

Before (base stage1): err_1710_chain_moves_named_base.w compiles and runs,
printing `Some(xyz)` then `Some()`. After: "use of moved value" at the
second chain. Unchanged and passing: the four spec-pinned §10.3 fixtures
(`let city: Option[str] = profile.address?.city` and friends),
behav_1503_optional_chain_tuple.w, optional_chain_non_option_field.w, and
behav_1710_optional_chain_observes_receiver.w (a Copy field, a tuple
element and a borrowing method leave the base usable; debug-alloc leak
count=0).

Refs #1710
…§18.5b, D74)

The language server's slow tier compiled an open file through
compile_source_text (module mode) and its fast tier parsed it with a plain
Parser, so a tool script with top-level statements reported "expected
declaration" in the editor while `check`, `run` and `build` accepted it.
The slow tier now uses compile_entry_source_text and both fast-tier parsers
enable implicit-main mode.

Before (base stage1, a didOpen of `fn helper(s: &str) -> str: s ++ "!"` /
`print(helper("lsp"))`): publishDiagnostics carries "expected declaration
(fn, type, enum, let, use, extern)" at 1:0. After: the parse error is gone;
the remaining "undefined variable" on `print` is the slow tier's
PRELUDE_NONE compilation and is reported identically for an `fn main` file
on the base compiler.

Refs #1759
…le holds another executable statement (#1759 follow-up, §18.5b, D74)

The stack battery failed twice in this layer, both from d1bac30a:
err_comptime_mut_global_access.w lost "mutable global access is not
allowed in comptime" (its `var GLOBAL_COUNT` read as "undefined variable"
in the comptime fn), and the migrator core case
check-tentative-global-owner failed the same way on the migrated `var g:
ctx` below `issue127_read`. Root cause: implicit-main mode treats every
top-level `let`/`var` as a statement of the synthesized `main` when the
file declares no `fn main`, so once `check` parsed roots as entry sources
(d1bac30a), a library-shaped file — functions and a `var`, no statements
— had its global demoted to a local of a `main` nothing called. `run`
already misread these files; `check` had hidden it.

§18.5b: "A module file holds declarations. A file whose top level also
holds executable statements is an entry source". A `let`/`var` is a
declaration form; a file is an entry source only when its top level holds
an executable statement other than a `let`/`var`
(Parser.has_top_level_exec_stmt, mirroring has_top_level_main_decl's
column-0 scan), and only then do its top-level `let`/`var`s become
`main`'s locals. Tool scripts (`let argv = args()` beside a loop or a
call) are unchanged; a library file keeps its globals; the comptime
mutable-global check fires again because the global is a global.

Before (this layer's stage1 at 11242dd, the battery): the comptime fixture
reports "undefined variable" at GLOBAL_COUNT; the migrated
tentative_global_owner.w fails `check` with "undefined variable" at `g`.
After: the fixture reports the comptime error and passes; migrate + check
of the case print ok; the four #1759 fixtures and `check tools/battery.w`
still pass. behav_1759_top_level_var_is_declaration.w pins the library
shape (a fn reading a `var` declared below it, no `main`) under `check`.

Refs #1759
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on the stack top 57410c94 (docs-csharplang-shape, folds #1787→#1792): with run tools/battery.w — src/main build ok, :battery-checks (seed-driver, fixpoint, test-with-audits incl. drop/move audits, user-programs-safe, last-green) rc=0 in 1574 s. Pre-battery gate green on the same tip: full build, stage1 self-check of src/main.w, build.w with the fresh binary, abi-hash, unit-return-review, spec-inventory, examples-tests, c-migrator-basic-tests, deep-debug-tool-tests. Merge order: gh stack merge 1792 --yes --squash.

@ehartford
ehartford marked this pull request as ready for review September 27, 2026 14:33
@ehartford
ehartford merged commit b5c4b97 into main Sep 27, 2026
@ehartford
ehartford deleted the batch2-sema branch September 27, 2026 14:34
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.

Sema: a generator value used after g |> stage(...) consumed it is accepted (use after move not reported)

1 participant