fix(lower): bare-call resolver binds same-name flat authors per source [0102c]

Third of four fix-0102 sub-steps — the behaviour fix for NORMAL call sites.
Adds THE bare-name resolver `resolveBareCallee(name, caller_file)` over
fix-0102a's `module_fns` + `flat_import_graph` and routes the primary call
path through it:

- own-author wins: a file's bare call to a name IT authors binds its OWN
  author, not the first-wins merge winner. (When the winner already is the
  caller's own — every single-author and first-importer case — the resolver
  returns `.none` so the existing path binds it byte-for-byte.)
- a bare call to a name two or more FLAT imports both provide is `.ambiguous`
  and rejected with a loud diagnostic ("declared by multiple imported
  modules — qualify the call"); a namespaced author never collides.
- a single flat-reachable author that differs from the winner binds that
  author; otherwise `.none`.

The resolved shadow author lowers into its OWN FuncId via fix-0102b's
identity-addressable `lowerFunctionBodyInto` (shared `bareAuthorFuncId`
helper, also used by `lowerRetainedSameNameAuthors`). Only plain free
functions route — generic / comptime / foreign / builtin authors and any
scope-mangled / UFCS-aliased / locally-shadowed name fall straight to the
existing dispatch, so single-author / local / std / qualified resolution is
unchanged (full example suite stays green, including bundle.sx and the
comptime format/pack examples).

Examples 0722 (flat file per-source bind), 0723 (flat vs namespaced, no false
ambiguity), 0724 (ambiguous → diagnostic), 0725 (flat directory per-source
bind), 0727 (user namespace literally named __m0). Each fails on
wt-fix-0102-base (first-wins mis-bind / no diagnostic) and passes here. The
fix-0102b unit test now calls a per-module wrapper (main can't bare-call the
2-author name) and asserts the resolver's three variants directly.

Gate: zig build, zig build test (400/400), bash tests/run_examples.sh
(462 passed) all green.
This commit is contained in:
agra
2026-06-06 14:04:03 +03:00
parent b077e8e29c
commit ea35a05b26
34 changed files with 316 additions and 26 deletions

View File

@@ -1290,14 +1290,15 @@ fn countRealBodies(module: *ir_mod.Module, name: []const u8) usize {
}
// fix-0102b: two flat-imported modules each author `greet`. The first-wins merge
// keeps a.sx's author in the merged decl list (the WINNER — lowered when `main`
// calls `greet()`) and drops b.sx's, which `module_fns` still retains (0102a).
// keeps a.sx's author in the merged decl list (the WINNER) and drops b.sx's,
// which `module_fns` still retains (0102a). `main` itself can't bare-call `greet`
// — under fix-0102c two flat authors make that ambiguous — so it calls a.sx's
// `use_greet` wrapper, whose own-author call to `greet` binds a.sx's winner.
// BEFORE the identity-addressable pass, only the winner has a real body — the
// shadowed author has no slot at all (the pre-fix symptom: one `greet`).
// `lowerRetainedSameNameAuthors` declares the shadowed author its OWN same-name
// FuncId and lowers its body there, so BOTH authors carry distinct, non-extern
// bodies. Call resolution is untouched: `resolveFuncByName` still returns the
// winner, so `main`'s `greet()` binds first-wins (rerouting is fix-0102c).
// bodies, and `resolveFuncByName` still returns the winner (the name-keyed slot).
test "lower: shadowed same-name author gets its own FuncId + real body (fix-0102b)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
@@ -1307,12 +1308,12 @@ test "lower: shadowed same-name author gets its own FuncId + real body (fix-0102
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(io, .{ .sub_path = "a.sx", .data = "greet :: () -> s64 { 1 }\n" });
try tmp.dir.writeFile(io, .{ .sub_path = "a.sx", .data = "greet :: () -> s64 { 1 }\nuse_greet :: () -> s64 { greet() }\n" });
try tmp.dir.writeFile(io, .{ .sub_path = "b.sx", .data = "greet :: () -> s64 { 2 }\n" });
const main_src =
\\#import "a.sx";
\\#import "b.sx";
\\main :: () -> s64 { greet() }
\\main :: () -> s64 { use_greet() }
\\
;
try tmp.dir.writeFile(io, .{ .sub_path = "main.sx", .data = main_src });
@@ -1426,4 +1427,20 @@ test "lower: shadowed same-name author gets its own FuncId + real body (fix-0102
const shadow_fid = lowering.fn_decl_fids.get(shadow_fd.?);
try std.testing.expect(shadow_fid != null);
try std.testing.expect(shadow_fid.? != winner_fid.?);
// fix-0102c: THE bare-name resolver routes per caller file. `main` flat-
// imports two `greet` authors and is its own author of neither → a bare
// `greet()` from `main` is ambiguous. a.sx authors the WINNER, so its bare
// `greet` resolves through the existing path (`.none`). b.sx authors the
// SHADOW, so own-author-wins binds b.sx's distinct FuncId — not first-wins.
const a_path = try std.fmt.allocPrint(alloc, "{s}/a.sx", .{absdir});
const b_path = try std.fmt.allocPrint(alloc, "{s}/b.sx", .{absdir});
try std.testing.expect(lowering.resolveBareCallee("greet", main_path) == .ambiguous);
try std.testing.expect(lowering.resolveBareCallee("greet", a_path) == .none);
switch (lowering.resolveBareCallee("greet", b_path)) {
.func => |fid| try std.testing.expectEqual(shadow_fid.?, fid),
else => return error.TestUnexpectedResult,
}
// A name no module authors (and no flat import provides) never routes.
try std.testing.expect(lowering.resolveBareCallee("nonexistent", b_path) == .none);
}

View File

@@ -1512,31 +1512,107 @@ pub const Lowering = struct {
// Only plain free functions get an out-of-line slot; generic /
// foreign / builtin / #compiler authors keep their existing
// dispatch (mirrors lazyLowerFunction / declareFunction guards).
if (fd.type_params.len > 0) continue;
switch (fd.body.data) {
.foreign_expr, .builtin_expr, .compiler_expr => continue,
else => {},
}
if (!isPlainFreeFn(fd)) continue;
// Already given its own slot + body? (idempotent across reruns.)
if (self.fn_decl_fids.get(fd)) |existing| {
if (self.lowered_fids.contains(existing)) continue;
}
// Declare a fresh same-name FuncId for this author and lower its
// body in its OWN module's visibility context (the path key IS
// the author's source file, matching `module_scopes`).
const saved_src = self.current_source_file;
self.setCurrentSourceFile(path);
if (!self.fn_decl_fids.contains(fd)) self.declareFunction(fd, name);
self.setCurrentSourceFile(saved_src);
const fid = self.fn_decl_fids.get(fd) orelse continue;
self.lowerFunctionBodyInto(fd, fid, name);
self.lowered_fids.put(fid, {}) catch {};
_ = self.bareAuthorFuncId(fd, name, path);
}
}
}
/// Result of bare-call disambiguation (fix-0102c).
pub const BareCallee = union(enum) {
/// Bind the call to this specific author's FuncId — the identity-
/// addressable body lowered by `bareAuthorFuncId` (fix-0102b).
func: FuncId,
/// ≥2 distinct flat authors are reachable from the caller and none is
/// the caller's own — the bare call can't pick one; require a qualifier.
ambiguous,
/// 0 or 1 reachable author, or the resolved author IS the existing
/// bare-name winner — defer to the existing path, byte-for-byte.
none,
};
/// THE bare-name call resolver (fix-0102c). One canonical traversal over
/// fix-0102a's `module_fns` + `flat_import_graph` that routes a bare
/// identifier call `name` from `caller_file` to the right same-name author
/// when flat imports introduce a genuine collision. Every single-author /
/// local / parameter / std / qualified name resolves through the EXISTING
/// path unchanged: the resolver returns `.none` whenever the outcome would
/// match first-wins, so nothing on the common path is perturbed.
///
/// - **own-author wins**: if `caller_file` authors `name` and the bare-name
/// first-wins winner is a DIFFERENT author, bind the caller's own author.
/// (When the winner already IS the caller's own — the single-author and
/// first-importer cases — `.none` lets the existing path bind it.)
/// - else collect the authors reachable via `caller_file`'s FLAT import
/// edges (bare `#import` of a file or directory, never a namespaced
/// `ns :: #import`), deduped by `FnDecl` identity (a diamond import of the
/// same module is one author): `≥2 distinct` → `.ambiguous`; exactly one
/// that DIFFERS from the winner → bind it; otherwise `.none`.
///
/// Generic / comptime / foreign / builtin authors are never rerouted — the
/// existing dispatch owns those shapes — so the resolver returns `.none`.
pub fn resolveBareCallee(self: *Lowering, name: []const u8, caller_file: []const u8) BareCallee {
const module_fns = self.program_index.module_fns orelse return .none;
const winner = self.program_index.fn_ast_map.get(name);
// own-author wins.
if (module_fns.get(caller_file)) |own_fns| {
if (own_fns.get(name)) |own| {
if (winner != null and winner.? == own) return .none;
if (!isPlainFreeFn(own)) return .none;
return .{ .func = self.bareAuthorFuncId(own, name, caller_file) };
}
}
// Caller does not author `name` → collect its flat-reachable authors.
const flat_graph = self.program_index.flat_import_graph orelse return .none;
const edges = flat_graph.get(caller_file) orelse return .none;
var distinct = std.AutoHashMap(*const ast.FnDecl, []const u8).init(self.alloc);
defer distinct.deinit();
var edge_it = edges.iterator();
while (edge_it.next()) |e| {
const fns = module_fns.get(e.key_ptr.*) orelse continue;
if (fns.get(name)) |fd| distinct.put(fd, e.key_ptr.*) catch {};
}
if (distinct.count() == 0) return .none;
if (distinct.count() >= 2) return .ambiguous;
var one_it = distinct.iterator();
const entry = one_it.next().?;
const the_one = entry.key_ptr.*;
const the_path = entry.value_ptr.*;
if (winner != null and winner.? == the_one) return .none;
if (!isPlainFreeFn(the_one)) return .none;
return .{ .func = self.bareAuthorFuncId(the_one, name, the_path) };
}
/// The FuncId for a resolved bare-call author, ensuring its body is lowered.
/// Only ever called for a SHADOW (an author that is not the name-keyed
/// winner): the winner owns the name-keyed slot and lowers through the
/// normal lazy path, so `resolveBareCallee` returns `.none` for it. A shadow
/// is declared a fresh same-name FuncId in its OWN module's visibility
/// context and its body lowered into that slot via fix-0102b's identity-
/// addressable `lowerFunctionBodyInto`. Idempotent: `lowered_fids` tracks
/// which slots already carry a body.
fn bareAuthorFuncId(self: *Lowering, fd: *const ast.FnDecl, name: []const u8, path: []const u8) FuncId {
if (self.fn_decl_fids.get(fd)) |fid| {
if (!self.lowered_fids.contains(fid)) {
self.lowered_fids.put(fid, {}) catch {};
self.lowerFunctionBodyInto(fd, fid, name);
}
return fid;
}
const saved_src = self.current_source_file;
self.setCurrentSourceFile(path);
self.declareFunction(fd, name);
self.setCurrentSourceFile(saved_src);
const fid = self.fn_decl_fids.get(fd).?;
self.lowered_fids.put(fid, {}) catch {};
self.lowerFunctionBodyInto(fd, fid, name);
return fid;
}
/// Declare a function as an extern stub (signature only, no body).
pub fn declareFunction(self: *Lowering, fd: *const ast.FnDecl, name: []const u8) void {
// Skip generic templates — they're monomorphized on demand, not declared as extern
@@ -7466,6 +7542,39 @@ pub const Lowering = struct {
}
}
}
// fix-0102c: a genuine flat same-name collision — bind the
// caller file's OWN author (or its single flat-reachable
// author), or reject a bare call to a name ≥2 imported modules
// author. Only a plain top-level identifier call routes here:
// scope-mangled / UFCS-aliased / locally-shadowed names and
// 0/1-author names fall straight to the existing path below
// (`resolveBareCallee` returns `.none`).
if (std.mem.eql(u8, func_name, id.name) and
(if (self.scope) |scope| scope.lookup(id.name) == null else true))
{
if (self.current_source_file) |caller_file| {
switch (self.resolveBareCallee(func_name, caller_file)) {
.none => {},
.ambiguous => {
if (self.diagnostics) |d|
d.addFmt(.err, c.callee.span, "'{s}' is ambiguous; declared by multiple imported modules — qualify the call", .{func_name});
return Ref.none;
},
.func => |fid| {
const func = &self.module.functions.items[@intFromEnum(fid)];
const ret_ty = func.ret;
const params = func.params;
if (self.program_index.fn_ast_map.get(func_name)) |fd| {
self.packVariadicCallArgs(fd, c, &args);
}
const final_args = self.prependCtxIfNeeded(func, args.items);
self.coerceCallArgs(final_args, params);
if (func.is_variadic) self.promoteCVariadicArgs(final_args, params.len);
return self.builder.call(fid, final_args, ret_ty);
},
}
}
}
// Check for comptime-expanded or generic functions
if (self.program_index.fn_ast_map.get(func_name)) |fd| {
if (hasComptimeParams(fd)) {
@@ -12018,6 +12127,19 @@ pub const Lowering = struct {
return false;
}
/// A plain free function: no type params (not generic) and an ordinary sx
/// body (not `#foreign` / `#builtin` / `#compiler`). Only these get an
/// out-of-line identity-addressable slot — the bare-call disambiguation
/// (fix-0102c) and the shadow-author lowering pass leave every other shape
/// to the existing name-keyed dispatch.
fn isPlainFreeFn(fd: *const ast.FnDecl) bool {
if (fd.type_params.len > 0) return false;
return switch (fd.body.data) {
.foreign_expr, .builtin_expr, .compiler_expr => false,
else => true,
};
}
/// Pack-fn: has a trailing heterogeneous pack param (`is_variadic
/// AND is_comptime`). Mixed shapes — non-pack comptime params
/// before the pack — are also accepted; the mono folds those