authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-07-04 23:13:22-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-07-04 23:13:22-04:00
log0f8561d099e4d08be0a6e547dd88f21026504490
tree69bdcb7800608daed4a8908406623f3bab38f0e4
parent790b8428a26457e7ed9ea20485b9d3085011b989
parent74346b0f79ca4bf67d61008030c7cc3565bff3f9
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #20487 from ziglang/incremental-serialization

Zcu: extract serializable state from File

22 files changed, 843 insertions(+), 705 deletions(-)

lib/std/Build/Cache.zig+14-28
......@@ -250,14 +250,7 @@ pub const HashHelper = struct {
250250 pub fn final(hh: *HashHelper) HexDigest {
251251 var bin_digest: BinDigest = undefined;
252252 hh.hasher.final(&bin_digest);
253
254 var out_digest: HexDigest = undefined;
255 _ = fmt.bufPrint(
256 &out_digest,
257 "{s}",
258 .{fmt.fmtSliceHexLower(&bin_digest)},
259 ) catch unreachable;
260 return out_digest;
253 return binToHex(bin_digest);
261254 }
262255
263256 pub fn oneShot(bytes: []const u8) [hex_digest_len]u8 {
......@@ -265,16 +258,20 @@ pub const HashHelper = struct {
265258 hasher.update(bytes);
266259 var bin_digest: BinDigest = undefined;
267260 hasher.final(&bin_digest);
268 var out_digest: [hex_digest_len]u8 = undefined;
269 _ = fmt.bufPrint(
270 &out_digest,
271 "{s}",
272 .{fmt.fmtSliceHexLower(&bin_digest)},
273 ) catch unreachable;
274 return out_digest;
261 return binToHex(bin_digest);
275262 }
276263};
277264
265pub fn binToHex(bin_digest: BinDigest) HexDigest {
266 var out_digest: HexDigest = undefined;
267 _ = fmt.bufPrint(
268 &out_digest,
269 "{s}",
270 .{fmt.fmtSliceHexLower(&bin_digest)},
271 ) catch unreachable;
272 return out_digest;
273}
274
278275pub const Lock = struct {
279276 manifest_file: fs.File,
280277
......@@ -426,11 +423,7 @@ pub const Manifest = struct {
426423 var bin_digest: BinDigest = undefined;
427424 self.hash.hasher.final(&bin_digest);
428425
429 _ = fmt.bufPrint(
430 &self.hex_digest,
431 "{s}",
432 .{fmt.fmtSliceHexLower(&bin_digest)},
433 ) catch unreachable;
426 self.hex_digest = binToHex(bin_digest);
434427
435428 self.hash.hasher = hasher_init;
436429 self.hash.hasher.update(&bin_digest);
......@@ -899,14 +892,7 @@ pub const Manifest = struct {
899892 var bin_digest: BinDigest = undefined;
900893 self.hash.hasher.final(&bin_digest);
901894
902 var out_digest: HexDigest = undefined;
903 _ = fmt.bufPrint(
904 &out_digest,
905 "{s}",
906 .{fmt.fmtSliceHexLower(&bin_digest)},
907 ) catch unreachable;
908
909 return out_digest;
895 return binToHex(bin_digest);
910896 }
911897
912898 /// If `want_shared_lock` is true, this function automatically downgrades the
lib/std/debug.zig+17-7
......@@ -398,20 +398,30 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
398398 }
399399}
400400
401/// This function invokes undefined behavior when `ok` is `false`.
401/// Invokes detectable illegal behavior when `ok` is `false`.
402///
402403/// In Debug and ReleaseSafe modes, calls to this function are always
403404/// generated, and the `unreachable` statement triggers a panic.
404/// In ReleaseFast and ReleaseSmall modes, calls to this function are
405/// optimized away, and in fact the optimizer is able to use the assertion
406/// in its heuristics.
407/// Inside a test block, it is best to use the `std.testing` module rather
408/// than this function, because this function may not detect a test failure
409/// in ReleaseFast and ReleaseSmall mode. Outside of a test block, this assert
405///
406/// In ReleaseFast and ReleaseSmall modes, calls to this function are optimized
407/// away, and in fact the optimizer is able to use the assertion in its
408/// heuristics.
409///
410/// Inside a test block, it is best to use the `std.testing` module rather than
411/// this function, because this function may not detect a test failure in
412/// ReleaseFast and ReleaseSmall mode. Outside of a test block, this assert
410413/// function is the correct function to use.
411414pub fn assert(ok: bool) void {
412415 if (!ok) unreachable; // assertion failure
413416}
414417
418/// Invokes detectable illegal behavior when the provided slice is not mapped
419/// or lacks read permissions.
420pub fn assertReadable(slice: []const volatile u8) void {
421 if (!runtime_safety) return;
422 for (slice) |*byte| _ = byte.*;
423}
424
415425pub fn panic(comptime format: []const u8, args: anytype) noreturn {
416426 @setCold(true);
417427
src/Compilation.zig+136-101
......@@ -116,7 +116,7 @@ win32_resource_work_queue: if (build_options.only_core_functionality) void else
116116/// These jobs are to tokenize, parse, and astgen files, which may be outdated
117117/// since the last compilation, as well as scan for `@import` and queue up
118118/// additional jobs corresponding to those new files.
119astgen_work_queue: std.fifo.LinearFifo(*Module.File, .Dynamic),
119astgen_work_queue: std.fifo.LinearFifo(Zcu.File.Index, .Dynamic),
120120/// These jobs are to inspect the file system stat() and if the embedded file has changed
121121/// on disk, mark the corresponding Decl outdated and queue up an `analyze_decl`
122122/// task for it.
......@@ -1433,7 +1433,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
14331433 .work_queue = std.fifo.LinearFifo(Job, .Dynamic).init(gpa),
14341434 .c_object_work_queue = std.fifo.LinearFifo(*CObject, .Dynamic).init(gpa),
14351435 .win32_resource_work_queue = if (build_options.only_core_functionality) {} else std.fifo.LinearFifo(*Win32Resource, .Dynamic).init(gpa),
1436 .astgen_work_queue = std.fifo.LinearFifo(*Module.File, .Dynamic).init(gpa),
1436 .astgen_work_queue = std.fifo.LinearFifo(Zcu.File.Index, .Dynamic).init(gpa),
14371437 .embed_file_work_queue = std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic).init(gpa),
14381438 .c_source_files = options.c_source_files,
14391439 .rc_source_files = options.rc_source_files,
......@@ -2095,13 +2095,13 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
20952095 }
20962096 }
20972097
2098 if (comp.module) |module| {
2099 module.compile_log_text.shrinkAndFree(gpa, 0);
2098 if (comp.module) |zcu| {
2099 zcu.compile_log_text.shrinkAndFree(gpa, 0);
21002100
21012101 // Make sure std.zig is inside the import_table. We unconditionally need
21022102 // it for start.zig.
2103 const std_mod = module.std_mod;
2104 _ = try module.importPkg(std_mod);
2103 const std_mod = zcu.std_mod;
2104 _ = try zcu.importPkg(std_mod);
21052105
21062106 // Normally we rely on importing std to in turn import the root source file
21072107 // in the start code, but when using the stage1 backend that won't happen,
......@@ -2110,64 +2110,65 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21102110 // Likewise, in the case of `zig test`, the test runner is the root source file,
21112111 // and so there is nothing to import the main file.
21122112 if (comp.config.is_test) {
2113 _ = try module.importPkg(module.main_mod);
2113 _ = try zcu.importPkg(zcu.main_mod);
21142114 }
21152115
2116 if (module.root_mod.deps.get("compiler_rt")) |compiler_rt_mod| {
2117 _ = try module.importPkg(compiler_rt_mod);
2116 if (zcu.root_mod.deps.get("compiler_rt")) |compiler_rt_mod| {
2117 _ = try zcu.importPkg(compiler_rt_mod);
21182118 }
21192119
21202120 // Put a work item in for every known source file to detect if
21212121 // it changed, and, if so, re-compute ZIR and then queue the job
21222122 // to update it.
2123 try comp.astgen_work_queue.ensureUnusedCapacity(module.import_table.count());
2124 for (module.import_table.values()) |file| {
2123 try comp.astgen_work_queue.ensureUnusedCapacity(zcu.import_table.count());
2124 for (zcu.import_table.values(), 0..) |file, file_index_usize| {
2125 const file_index: Zcu.File.Index = @enumFromInt(file_index_usize);
21252126 if (file.mod.isBuiltin()) continue;
2126 comp.astgen_work_queue.writeItemAssumeCapacity(file);
2127 comp.astgen_work_queue.writeItemAssumeCapacity(file_index);
21272128 }
21282129
21292130 // Put a work item in for checking if any files used with `@embedFile` changed.
2130 try comp.embed_file_work_queue.ensureUnusedCapacity(module.embed_table.count());
2131 for (module.embed_table.values()) |embed_file| {
2131 try comp.embed_file_work_queue.ensureUnusedCapacity(zcu.embed_table.count());
2132 for (zcu.embed_table.values()) |embed_file| {
21322133 comp.embed_file_work_queue.writeItemAssumeCapacity(embed_file);
21332134 }
21342135
21352136 try comp.work_queue.writeItem(.{ .analyze_mod = std_mod });
21362137 if (comp.config.is_test) {
2137 try comp.work_queue.writeItem(.{ .analyze_mod = module.main_mod });
2138 try comp.work_queue.writeItem(.{ .analyze_mod = zcu.main_mod });
21382139 }
21392140
2140 if (module.root_mod.deps.get("compiler_rt")) |compiler_rt_mod| {
2141 if (zcu.root_mod.deps.get("compiler_rt")) |compiler_rt_mod| {
21412142 try comp.work_queue.writeItem(.{ .analyze_mod = compiler_rt_mod });
21422143 }
21432144 }
21442145
21452146 try comp.performAllTheWork(main_progress_node);
21462147
2147 if (comp.module) |module| {
2148 if (comp.module) |zcu| {
21482149 if (build_options.enable_debug_extensions and comp.verbose_intern_pool) {
21492150 std.debug.print("intern pool stats for '{s}':\n", .{
21502151 comp.root_name,
21512152 });
2152 module.intern_pool.dump();
2153 zcu.intern_pool.dump();
21532154 }
21542155
21552156 if (build_options.enable_debug_extensions and comp.verbose_generic_instances) {
21562157 std.debug.print("generic instances for '{s}:0x{x}':\n", .{
21572158 comp.root_name,
2158 @as(usize, @intFromPtr(module)),
2159 @as(usize, @intFromPtr(zcu)),
21592160 });
2160 module.intern_pool.dumpGenericInstances(gpa);
2161 zcu.intern_pool.dumpGenericInstances(gpa);
21612162 }
21622163
21632164 if (comp.config.is_test and comp.totalErrorCount() == 0) {
21642165 // The `test_functions` decl has been intentionally postponed until now,
21652166 // at which point we must populate it with the list of test functions that
21662167 // have been discovered and not filtered out.
2167 try module.populateTestFunctions(main_progress_node);
2168 try zcu.populateTestFunctions(main_progress_node);
21682169 }
21692170
2170 try module.processExports();
2171 try zcu.processExports();
21712172 }
21722173
21732174 if (comp.totalErrorCount() != 0) {
......@@ -2615,7 +2616,9 @@ fn resolveEmitLoc(
26152616 return slice.ptr;
26162617}
26172618
2618fn reportMultiModuleErrors(mod: *Module) !void {
2619fn reportMultiModuleErrors(zcu: *Zcu) !void {
2620 const gpa = zcu.gpa;
2621 const ip = &zcu.intern_pool;
26192622 // Some cases can give you a whole bunch of multi-module errors, which it's not helpful to
26202623 // print all of, so we'll cap the number of these to emit.
26212624 var num_errors: u32 = 0;
......@@ -2623,37 +2626,39 @@ fn reportMultiModuleErrors(mod: *Module) !void {
26232626 // Attach the "some omitted" note to the final error message
26242627 var last_err: ?*Module.ErrorMsg = null;
26252628
2626 for (mod.import_table.values()) |file| {
2629 for (zcu.import_table.values(), 0..) |file, file_index_usize| {
26272630 if (!file.multi_pkg) continue;
26282631
26292632 num_errors += 1;
26302633 if (num_errors > max_errors) continue;
26312634
2635 const file_index: Zcu.File.Index = @enumFromInt(file_index_usize);
2636
26322637 const err = err_blk: {
26332638 // Like with errors, let's cap the number of notes to prevent a huge error spew.
26342639 const max_notes = 5;
26352640 const omitted = file.references.items.len -| max_notes;
26362641 const num_notes = file.references.items.len - omitted;
26372642
2638 const notes = try mod.gpa.alloc(Module.ErrorMsg, if (omitted > 0) num_notes + 1 else num_notes);
2639 errdefer mod.gpa.free(notes);
2643 const notes = try gpa.alloc(Module.ErrorMsg, if (omitted > 0) num_notes + 1 else num_notes);
2644 errdefer gpa.free(notes);
26402645
26412646 for (notes[0..num_notes], file.references.items[0..num_notes], 0..) |*note, ref, i| {
2642 errdefer for (notes[0..i]) |*n| n.deinit(mod.gpa);
2647 errdefer for (notes[0..i]) |*n| n.deinit(gpa);
26432648 note.* = switch (ref) {
26442649 .import => |import| try Module.ErrorMsg.init(
2645 mod.gpa,
2650 gpa,
26462651 .{
2647 .base_node_inst = try mod.intern_pool.trackZir(mod.gpa, import.file, .main_struct_inst),
2652 .base_node_inst = try ip.trackZir(gpa, import.file, .main_struct_inst),
26482653 .offset = .{ .token_abs = import.token },
26492654 },
26502655 "imported from module {s}",
2651 .{import.file.mod.fully_qualified_name},
2656 .{zcu.fileByIndex(import.file).mod.fully_qualified_name},
26522657 ),
26532658 .root => |pkg| try Module.ErrorMsg.init(
2654 mod.gpa,
2659 gpa,
26552660 .{
2656 .base_node_inst = try mod.intern_pool.trackZir(mod.gpa, file, .main_struct_inst),
2661 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
26572662 .offset = .entire_file,
26582663 },
26592664 "root of module {s}",
......@@ -2661,25 +2666,25 @@ fn reportMultiModuleErrors(mod: *Module) !void {
26612666 ),
26622667 };
26632668 }
2664 errdefer for (notes[0..num_notes]) |*n| n.deinit(mod.gpa);
2669 errdefer for (notes[0..num_notes]) |*n| n.deinit(gpa);
26652670
26662671 if (omitted > 0) {
26672672 notes[num_notes] = try Module.ErrorMsg.init(
2668 mod.gpa,
2673 gpa,
26692674 .{
2670 .base_node_inst = try mod.intern_pool.trackZir(mod.gpa, file, .main_struct_inst),
2675 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
26712676 .offset = .entire_file,
26722677 },
26732678 "{} more references omitted",
26742679 .{omitted},
26752680 );
26762681 }
2677 errdefer if (omitted > 0) notes[num_notes].deinit(mod.gpa);
2682 errdefer if (omitted > 0) notes[num_notes].deinit(gpa);
26782683
26792684 const err = try Module.ErrorMsg.create(
2680 mod.gpa,
2685 gpa,
26812686 .{
2682 .base_node_inst = try mod.intern_pool.trackZir(mod.gpa, file, .main_struct_inst),
2687 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
26832688 .offset = .entire_file,
26842689 },
26852690 "file exists in multiple modules",
......@@ -2688,8 +2693,8 @@ fn reportMultiModuleErrors(mod: *Module) !void {
26882693 err.notes = notes;
26892694 break :err_blk err;
26902695 };
2691 errdefer err.destroy(mod.gpa);
2692 try mod.failed_files.putNoClobber(mod.gpa, file, err);
2696 errdefer err.destroy(gpa);
2697 try zcu.failed_files.putNoClobber(gpa, file, err);
26932698 last_err = err;
26942699 }
26952700
......@@ -2700,15 +2705,15 @@ fn reportMultiModuleErrors(mod: *Module) !void {
27002705 // There isn't really any meaningful place to put this note, so just attach it to the
27012706 // last failed file
27022707 var note = try Module.ErrorMsg.init(
2703 mod.gpa,
2708 gpa,
27042709 err.src_loc,
27052710 "{} more errors omitted",
27062711 .{num_errors - max_errors},
27072712 );
2708 errdefer note.deinit(mod.gpa);
2713 errdefer note.deinit(gpa);
27092714
27102715 const i = err.notes.len;
2711 err.notes = try mod.gpa.realloc(err.notes, i + 1);
2716 err.notes = try gpa.realloc(err.notes, i + 1);
27122717 err.notes[i] = note;
27132718 }
27142719
......@@ -2719,8 +2724,8 @@ fn reportMultiModuleErrors(mod: *Module) !void {
27192724 // to add this flag after reporting the errors however, as otherwise
27202725 // we'd get an error for every single downstream file, which wouldn't be
27212726 // very useful.
2722 for (mod.import_table.values()) |file| {
2723 if (file.multi_pkg) file.recursiveMarkMultiPkg(mod);
2727 for (zcu.import_table.values()) |file| {
2728 if (file.multi_pkg) file.recursiveMarkMultiPkg(zcu);
27242729 }
27252730}
27262731
......@@ -2752,6 +2757,7 @@ const Header = extern struct {
27522757 first_dependency_len: u32,
27532758 dep_entries_len: u32,
27542759 free_dep_entries_len: u32,
2760 files_len: u32,
27552761 },
27562762};
27572763
......@@ -2759,7 +2765,7 @@ const Header = extern struct {
27592765/// saved, such as the target and most CLI flags. A cache hit will only occur
27602766/// when subsequent compiler invocations use the same set of flags.
27612767pub fn saveState(comp: *Compilation) !void {
2762 var bufs_list: [19]std.posix.iovec_const = undefined;
2768 var bufs_list: [21]std.posix.iovec_const = undefined;
27632769 var bufs_len: usize = 0;
27642770
27652771 const lf = comp.bin_file orelse return;
......@@ -2780,6 +2786,7 @@ pub fn saveState(comp: *Compilation) !void {
27802786 .first_dependency_len = @intCast(ip.first_dependency.count()),
27812787 .dep_entries_len = @intCast(ip.dep_entries.items.len),
27822788 .free_dep_entries_len = @intCast(ip.free_dep_entries.items.len),
2789 .files_len = @intCast(ip.files.entries.len),
27832790 },
27842791 };
27852792 addBuf(&bufs_list, &bufs_len, mem.asBytes(&header));
......@@ -2804,8 +2811,10 @@ pub fn saveState(comp: *Compilation) !void {
28042811 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.dep_entries.items));
28052812 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.free_dep_entries.items));
28062813
2814 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.files.keys()));
2815 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.files.values()));
2816
28072817 // TODO: compilation errors
2808 // TODO: files
28092818 // TODO: namespaces
28102819 // TODO: decls
28112820 // TODO: linker state
......@@ -2827,6 +2836,9 @@ pub fn saveState(comp: *Compilation) !void {
28272836}
28282837
28292838fn addBuf(bufs_list: []std.posix.iovec_const, bufs_len: *usize, buf: []const u8) void {
2839 // Even when len=0, the undefined pointer might cause EFAULT.
2840 if (buf.len == 0) return;
2841
28302842 const i = bufs_len.*;
28312843 bufs_len.* = i + 1;
28322844 bufs_list[i] = .{
......@@ -3350,16 +3362,31 @@ pub fn performAllTheWork(
33503362 }
33513363 }
33523364
3353 while (comp.astgen_work_queue.readItem()) |file| {
3354 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerAstGenFile, .{
3355 comp, file, zir_prog_node, &comp.astgen_wait_group, .root,
3356 });
3357 }
3365 if (comp.module) |zcu| {
3366 {
3367 // Worker threads may append to zcu.files and zcu.import_table
3368 // so we must hold the lock while spawning those tasks, since
3369 // we access those tables in this loop.
3370 comp.mutex.lock();
3371 defer comp.mutex.unlock();
33583372
3359 while (comp.embed_file_work_queue.readItem()) |embed_file| {
3360 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerCheckEmbedFile, .{
3361 comp, embed_file,
3362 });
3373 while (comp.astgen_work_queue.readItem()) |file_index| {
3374 // Pre-load these things from our single-threaded context since they
3375 // will be needed by the worker threads.
3376 const path_digest = zcu.filePathDigest(file_index);
3377 const root_decl = zcu.fileRootDecl(file_index);
3378 const file = zcu.fileByIndex(file_index);
3379 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerAstGenFile, .{
3380 comp, file, file_index, path_digest, root_decl, zir_prog_node, &comp.astgen_wait_group, .root,
3381 });
3382 }
3383 }
3384
3385 while (comp.embed_file_work_queue.readItem()) |embed_file| {
3386 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerCheckEmbedFile, .{
3387 comp, embed_file,
3388 });
3389 }
33633390 }
33643391
33653392 while (comp.c_object_work_queue.readItem()) |c_object| {
......@@ -3423,8 +3450,8 @@ pub fn performAllTheWork(
34233450fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !void {
34243451 switch (job) {
34253452 .codegen_decl => |decl_index| {
3426 const module = comp.module.?;
3427 const decl = module.declPtr(decl_index);
3453 const zcu = comp.module.?;
3454 const decl = zcu.declPtr(decl_index);
34283455
34293456 switch (decl.analysis) {
34303457 .unreferenced => unreachable,
......@@ -3442,7 +3469,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34423469
34433470 assert(decl.has_tv);
34443471
3445 try module.linkerUpdateDecl(decl_index);
3472 try zcu.linkerUpdateDecl(decl_index);
34463473 return;
34473474 },
34483475 }
......@@ -3451,16 +3478,16 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34513478 const named_frame = tracy.namedFrame("codegen_func");
34523479 defer named_frame.end();
34533480
3454 const module = comp.module.?;
3481 const zcu = comp.module.?;
34553482 // This call takes ownership of `func.air`.
3456 try module.linkerUpdateFunc(func.func, func.air);
3483 try zcu.linkerUpdateFunc(func.func, func.air);
34573484 },
34583485 .analyze_func => |func| {
34593486 const named_frame = tracy.namedFrame("analyze_func");
34603487 defer named_frame.end();
34613488
3462 const module = comp.module.?;
3463 module.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
3489 const zcu = comp.module.?;
3490 zcu.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
34643491 error.OutOfMemory => return error.OutOfMemory,
34653492 error.AnalysisFail => return,
34663493 };
......@@ -3469,8 +3496,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34693496 if (true) @panic("regressed compiler feature: emit-h should hook into updateExports, " ++
34703497 "not decl analysis, which is too early to know about @export calls");
34713498
3472 const module = comp.module.?;
3473 const decl = module.declPtr(decl_index);
3499 const zcu = comp.module.?;
3500 const decl = zcu.declPtr(decl_index);
34743501
34753502 switch (decl.analysis) {
34763503 .unreferenced => unreachable,
......@@ -3488,7 +3515,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34883515 defer named_frame.end();
34893516
34903517 const gpa = comp.gpa;
3491 const emit_h = module.emit_h.?;
3518 const emit_h = zcu.emit_h.?;
34923519 _ = try emit_h.decl_table.getOrPut(gpa, decl_index);
34933520 const decl_emit_h = emit_h.declPtr(decl_index);
34943521 const fwd_decl = &decl_emit_h.fwd_decl;
......@@ -3496,10 +3523,12 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34963523 var ctypes_arena = std.heap.ArenaAllocator.init(gpa);
34973524 defer ctypes_arena.deinit();
34983525
3526 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
3527
34993528 var dg: c_codegen.DeclGen = .{
35003529 .gpa = gpa,
3501 .zcu = module,
3502 .mod = module.namespacePtr(decl.src_namespace).file_scope.mod,
3530 .zcu = zcu,
3531 .mod = file_scope.mod,
35033532 .error_msg = null,
35043533 .pass = .{ .decl = decl_index },
35053534 .is_naked_fn = false,
......@@ -3528,17 +3557,17 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35283557 }
35293558 },
35303559 .analyze_decl => |decl_index| {
3531 const module = comp.module.?;
3532 module.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
3560 const zcu = comp.module.?;
3561 zcu.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
35333562 error.OutOfMemory => return error.OutOfMemory,
35343563 error.AnalysisFail => return,
35353564 };
3536 const decl = module.declPtr(decl_index);
3565 const decl = zcu.declPtr(decl_index);
35373566 if (decl.kind == .@"test" and comp.config.is_test) {
35383567 // Tests are always emitted in test binaries. The decl_refs are created by
3539 // Module.populateTestFunctions, but this will not queue body analysis, so do
3568 // Zcu.populateTestFunctions, but this will not queue body analysis, so do
35403569 // that now.
3541 try module.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
3570 try zcu.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
35423571 }
35433572 },
35443573 .resolve_type_fully => |ty| {
......@@ -3556,30 +3585,30 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35563585 defer named_frame.end();
35573586
35583587 const gpa = comp.gpa;
3559 const module = comp.module.?;
3560 const decl = module.declPtr(decl_index);
3588 const zcu = comp.module.?;
3589 const decl = zcu.declPtr(decl_index);
35613590 const lf = comp.bin_file.?;
3562 lf.updateDeclLineNumber(module, decl_index) catch |err| {
3563 try module.failed_analysis.ensureUnusedCapacity(gpa, 1);
3564 module.failed_analysis.putAssumeCapacityNoClobber(
3591 lf.updateDeclLineNumber(zcu, decl_index) catch |err| {
3592 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3593 zcu.failed_analysis.putAssumeCapacityNoClobber(
35653594 InternPool.AnalUnit.wrap(.{ .decl = decl_index }),
3566 try Module.ErrorMsg.create(
3595 try Zcu.ErrorMsg.create(
35673596 gpa,
3568 decl.navSrcLoc(module),
3597 decl.navSrcLoc(zcu),
35693598 "unable to update line number: {s}",
35703599 .{@errorName(err)},
35713600 ),
35723601 );
35733602 decl.analysis = .codegen_failure;
3574 try module.retryable_failures.append(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
3603 try zcu.retryable_failures.append(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
35753604 };
35763605 },
35773606 .analyze_mod => |pkg| {
35783607 const named_frame = tracy.namedFrame("analyze_mod");
35793608 defer named_frame.end();
35803609
3581 const module = comp.module.?;
3582 module.semaPkg(pkg) catch |err| switch (err) {
3610 const zcu = comp.module.?;
3611 zcu.semaPkg(pkg) catch |err| switch (err) {
35833612 error.OutOfMemory => return error.OutOfMemory,
35843613 error.AnalysisFail => return,
35853614 };
......@@ -4012,14 +4041,17 @@ fn workerDocsWasmFallible(comp: *Compilation, prog_node: std.Progress.Node) anye
40124041const AstGenSrc = union(enum) {
40134042 root,
40144043 import: struct {
4015 importing_file: *Module.File,
4044 importing_file: Zcu.File.Index,
40164045 import_tok: std.zig.Ast.TokenIndex,
40174046 },
40184047};
40194048
40204049fn workerAstGenFile(
40214050 comp: *Compilation,
4022 file: *Module.File,
4051 file: *Zcu.File,
4052 file_index: Zcu.File.Index,
4053 path_digest: Cache.BinDigest,
4054 root_decl: Zcu.Decl.OptionalIndex,
40234055 prog_node: std.Progress.Node,
40244056 wg: *WaitGroup,
40254057 src: AstGenSrc,
......@@ -4027,12 +4059,12 @@ fn workerAstGenFile(
40274059 const child_prog_node = prog_node.start(file.sub_file_path, 0);
40284060 defer child_prog_node.end();
40294061
4030 const mod = comp.module.?;
4031 mod.astGenFile(file) catch |err| switch (err) {
4062 const zcu = comp.module.?;
4063 zcu.astGenFile(file, file_index, path_digest, root_decl) catch |err| switch (err) {
40324064 error.AnalysisFail => return,
40334065 else => {
40344066 file.status = .retryable_failure;
4035 comp.reportRetryableAstGenError(src, file, err) catch |oom| switch (oom) {
4067 comp.reportRetryableAstGenError(src, file_index, err) catch |oom| switch (oom) {
40364068 // Swallowing this error is OK because it's implied to be OOM when
40374069 // there is a missing `failed_files` error message.
40384070 error.OutOfMemory => {},
......@@ -4059,29 +4091,31 @@ fn workerAstGenFile(
40594091 // `@import("builtin")` is handled specially.
40604092 if (mem.eql(u8, import_path, "builtin")) continue;
40614093
4062 const import_result = blk: {
4094 const import_result, const imported_path_digest, const imported_root_decl = blk: {
40634095 comp.mutex.lock();
40644096 defer comp.mutex.unlock();
40654097
4066 const res = mod.importFile(file, import_path) catch continue;
4098 const res = zcu.importFile(file, import_path) catch continue;
40674099 if (!res.is_pkg) {
4068 res.file.addReference(mod.*, .{ .import = .{
4069 .file = file,
4100 res.file.addReference(zcu.*, .{ .import = .{
4101 .file = file_index,
40704102 .token = item.data.token,
40714103 } }) catch continue;
40724104 }
4073 break :blk res;
4105 const imported_path_digest = zcu.filePathDigest(res.file_index);
4106 const imported_root_decl = zcu.fileRootDecl(res.file_index);
4107 break :blk .{ res, imported_path_digest, imported_root_decl };
40744108 };
40754109 if (import_result.is_new) {
40764110 log.debug("AstGen of {s} has import '{s}'; queuing AstGen of {s}", .{
40774111 file.sub_file_path, import_path, import_result.file.sub_file_path,
40784112 });
40794113 const sub_src: AstGenSrc = .{ .import = .{
4080 .importing_file = file,
4114 .importing_file = file_index,
40814115 .import_tok = item.data.token,
40824116 } };
40834117 comp.thread_pool.spawnWg(wg, workerAstGenFile, .{
4084 comp, import_result.file, prog_node, wg, sub_src,
4118 comp, import_result.file, import_result.file_index, imported_path_digest, imported_root_decl, prog_node, wg, sub_src,
40854119 });
40864120 }
40874121 }
......@@ -4432,21 +4466,22 @@ fn reportRetryableWin32ResourceError(
44324466fn reportRetryableAstGenError(
44334467 comp: *Compilation,
44344468 src: AstGenSrc,
4435 file: *Module.File,
4469 file_index: Zcu.File.Index,
44364470 err: anyerror,
44374471) error{OutOfMemory}!void {
4438 const mod = comp.module.?;
4439 const gpa = mod.gpa;
4472 const zcu = comp.module.?;
4473 const gpa = zcu.gpa;
44404474
4475 const file = zcu.fileByIndex(file_index);
44414476 file.status = .retryable_failure;
44424477
44434478 const src_loc: Module.LazySrcLoc = switch (src) {
44444479 .root => .{
4445 .base_node_inst = try mod.intern_pool.trackZir(gpa, file, .main_struct_inst),
4480 .base_node_inst = try zcu.intern_pool.trackZir(gpa, file_index, .main_struct_inst),
44464481 .offset = .entire_file,
44474482 },
44484483 .import => |info| .{
4449 .base_node_inst = try mod.intern_pool.trackZir(gpa, info.importing_file, .main_struct_inst),
4484 .base_node_inst = try zcu.intern_pool.trackZir(gpa, info.importing_file, .main_struct_inst),
44504485 .offset = .{ .token_abs = info.import_tok },
44514486 },
44524487 };
......@@ -4459,7 +4494,7 @@ fn reportRetryableAstGenError(
44594494 {
44604495 comp.mutex.lock();
44614496 defer comp.mutex.unlock();
4462 try mod.failed_files.putNoClobber(gpa, file, err_msg);
4497 try zcu.failed_files.putNoClobber(gpa, file, err_msg);
44634498 }
44644499}
44654500
src/InternPool.zig+26-4
......@@ -92,12 +92,27 @@ dep_entries: std.ArrayListUnmanaged(DepEntry) = .{},
9292/// garbage collection pass.
9393free_dep_entries: std.ArrayListUnmanaged(DepEntry.Index) = .{},
9494
95/// Elements are ordered identically to the `import_table` field of `Zcu`.
96///
97/// Unlike `import_table`, this data is serialized as part of incremental
98/// compilation state.
99///
100/// Key is the hash of the path to this file, used to store
101/// `InternPool.TrackedInst`.
102///
103/// Value is the `Decl` of the struct that represents this `File`.
104files: std.AutoArrayHashMapUnmanaged(Cache.BinDigest, OptionalDeclIndex) = .{},
105
106pub const FileIndex = enum(u32) {
107 _,
108};
109
95110pub const TrackedInst = extern struct {
96 path_digest: Cache.BinDigest,
111 file: FileIndex,
97112 inst: Zir.Inst.Index,
98113 comptime {
99114 // The fields should be tightly packed. See also serialiation logic in `Compilation.saveState`.
100 assert(@sizeOf(@This()) == Cache.bin_digest_len + @sizeOf(Zir.Inst.Index));
115 assert(@sizeOf(@This()) == @sizeOf(FileIndex) + @sizeOf(Zir.Inst.Index));
101116 }
102117 pub const Index = enum(u32) {
103118 _,
......@@ -123,9 +138,14 @@ pub const TrackedInst = extern struct {
123138 };
124139};
125140
126pub fn trackZir(ip: *InternPool, gpa: Allocator, file: *Module.File, inst: Zir.Inst.Index) Allocator.Error!TrackedInst.Index {
141pub fn trackZir(
142 ip: *InternPool,
143 gpa: Allocator,
144 file: FileIndex,
145 inst: Zir.Inst.Index,
146) Allocator.Error!TrackedInst.Index {
127147 const key: TrackedInst = .{
128 .path_digest = file.path_digest,
148 .file = file,
129149 .inst = inst,
130150 };
131151 const gop = try ip.tracked_insts.getOrPut(gpa, key);
......@@ -4592,6 +4612,8 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
45924612 ip.dep_entries.deinit(gpa);
45934613 ip.free_dep_entries.deinit(gpa);
45944614
4615 ip.files.deinit(gpa);
4616
45954617 ip.* = undefined;
45964618}
45974619
src/Package/Module.zig+2-6
......@@ -379,7 +379,7 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {
379379
380380 const new_file = try arena.create(File);
381381
382 const bin_digest, const hex_digest = digest: {
382 const hex_digest = digest: {
383383 var hasher: Cache.Hasher = Cache.hasher_init;
384384 hasher.update(generated_builtin_source);
385385
......@@ -393,7 +393,7 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {
393393 .{std.fmt.fmtSliceHexLower(&bin_digest)},
394394 ) catch unreachable;
395395
396 break :digest .{ bin_digest, hex_digest };
396 break :digest hex_digest;
397397 };
398398
399399 const builtin_sub_path = try arena.dupe(u8, "b" ++ std.fs.path.sep_str ++ hex_digest);
......@@ -443,10 +443,6 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {
443443 .zir = undefined,
444444 .status = .never_loaded,
445445 .mod = new,
446 .root_decl = .none,
447 // We might as well use this digest for the File `path digest`, since there's a
448 // one-to-one correspondence here between distinct paths and distinct contents.
449 .path_digest = bin_digest,
450446 };
451447 break :b new;
452448 };
src/Sema.zig+123-106
......@@ -546,8 +546,12 @@ pub const Block = struct {
546546 };
547547 }
548548
549 pub fn getFileScope(block: *Block, mod: *Module) *Module.File {
550 return mod.namespacePtr(block.namespace).file_scope;
549 pub fn getFileScope(block: *Block, zcu: *Zcu) *Zcu.File {
550 return zcu.fileByIndex(getFileScopeIndex(block, zcu));
551 }
552
553 pub fn getFileScopeIndex(block: *Block, zcu: *Zcu) Zcu.File.Index {
554 return zcu.namespacePtr(block.namespace).file_scope;
551555 }
552556
553557 fn addTy(
......@@ -826,7 +830,16 @@ pub const Block = struct {
826830
827831 pub fn ownerModule(block: Block) *Package.Module {
828832 const zcu = block.sema.mod;
829 return zcu.namespacePtr(block.namespace).file_scope.mod;
833 return zcu.namespacePtr(block.namespace).fileScope(zcu).mod;
834 }
835
836 fn trackZir(block: *Block, inst: Zir.Inst.Index) Allocator.Error!InternPool.TrackedInst.Index {
837 const sema = block.sema;
838 const gpa = sema.gpa;
839 const zcu = sema.mod;
840 const ip = &zcu.intern_pool;
841 const file_index = block.getFileScopeIndex(zcu);
842 return ip.trackZir(gpa, file_index, inst);
830843 }
831844};
832845
......@@ -979,7 +992,7 @@ fn analyzeBodyInner(
979992
980993 try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);
981994
982 const mod = sema.mod;
995 const zcu = sema.mod;
983996 const map = &sema.inst_map;
984997 const tags = sema.code.instructions.items(.tag);
985998 const datas = sema.code.instructions.items(.data);
......@@ -999,9 +1012,9 @@ fn analyzeBodyInner(
9991012 // The hashmap lookup in here is a little expensive, and LLVM fails to optimize it away.
10001013 if (build_options.enable_logging) {
10011014 std.log.scoped(.sema_zir).debug("sema ZIR {s} %{d}", .{ sub_file_path: {
1002 const path_digest = block.src_base_inst.resolveFull(&mod.intern_pool).path_digest;
1003 const index = mod.path_digest_map.getIndex(path_digest).?;
1004 break :sub_file_path mod.import_table.values()[index].sub_file_path;
1015 const file_index = block.src_base_inst.resolveFull(&zcu.intern_pool).file;
1016 const file = zcu.fileByIndex(file_index);
1017 break :sub_file_path file.sub_file_path;
10051018 }, inst });
10061019 }
10071020
......@@ -1762,9 +1775,9 @@ fn analyzeBodyInner(
17621775 const inline_body = sema.code.bodySlice(extra.end, extra.data.body_len);
17631776 const err_union = try sema.resolveInst(extra.data.operand);
17641777 const err_union_ty = sema.typeOf(err_union);
1765 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
1778 if (err_union_ty.zigTypeTag(zcu) != .ErrorUnion) {
17661779 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
1767 err_union_ty.fmt(mod),
1780 err_union_ty.fmt(zcu),
17681781 });
17691782 }
17701783 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
......@@ -2730,7 +2743,7 @@ fn zirStructDecl(
27302743 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
27312744 const extra = sema.code.extraData(Zir.Inst.StructDecl, extended.operand);
27322745
2733 const tracked_inst = try ip.trackZir(gpa, block.getFileScope(mod), inst);
2746 const tracked_inst = try block.trackZir(inst);
27342747 const src: LazySrcLoc = .{
27352748 .base_node_inst = tracked_inst,
27362749 .offset = LazySrcLoc.Offset.nodeOffset(0),
......@@ -2806,7 +2819,7 @@ fn zirStructDecl(
28062819 try ip.addDependency(
28072820 sema.gpa,
28082821 AnalUnit.wrap(.{ .decl = new_decl_index }),
2809 .{ .src_hash = try ip.trackZir(sema.gpa, block.getFileScope(mod), inst) },
2822 .{ .src_hash = try block.trackZir(inst) },
28102823 );
28112824 }
28122825
......@@ -2814,7 +2827,7 @@ fn zirStructDecl(
28142827 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{
28152828 .parent = block.namespace.toOptional(),
28162829 .decl_index = new_decl_index,
2817 .file_scope = block.getFileScope(mod),
2830 .file_scope = block.getFileScopeIndex(mod),
28182831 })).toOptional() else .none;
28192832 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
28202833
......@@ -2947,7 +2960,7 @@ fn zirEnumDecl(
29472960 const extra = sema.code.extraData(Zir.Inst.EnumDecl, extended.operand);
29482961 var extra_index: usize = extra.end;
29492962
2950 const tracked_inst = try ip.trackZir(gpa, block.getFileScope(mod), inst);
2963 const tracked_inst = try block.trackZir(inst);
29512964 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };
29522965 const tag_ty_src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = .{ .node_offset_container_tag = 0 } };
29532966
......@@ -3040,9 +3053,9 @@ fn zirEnumDecl(
30403053
30413054 if (sema.mod.comp.debug_incremental) {
30423055 try mod.intern_pool.addDependency(
3043 sema.gpa,
3056 gpa,
30443057 AnalUnit.wrap(.{ .decl = new_decl_index }),
3045 .{ .src_hash = try mod.intern_pool.trackZir(sema.gpa, block.getFileScope(mod), inst) },
3058 .{ .src_hash = try block.trackZir(inst) },
30463059 );
30473060 }
30483061
......@@ -3050,7 +3063,7 @@ fn zirEnumDecl(
30503063 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{
30513064 .parent = block.namespace.toOptional(),
30523065 .decl_index = new_decl_index,
3053 .file_scope = block.getFileScope(mod),
3066 .file_scope = block.getFileScopeIndex(mod),
30543067 })).toOptional() else .none;
30553068 errdefer if (!done) if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
30563069
......@@ -3232,7 +3245,7 @@ fn zirUnionDecl(
32323245 const extra = sema.code.extraData(Zir.Inst.UnionDecl, extended.operand);
32333246 var extra_index: usize = extra.end;
32343247
3235 const tracked_inst = try ip.trackZir(gpa, block.getFileScope(mod), inst);
3248 const tracked_inst = try block.trackZir(inst);
32363249 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };
32373250
32383251 extra_index += @intFromBool(small.has_tag_type);
......@@ -3306,9 +3319,9 @@ fn zirUnionDecl(
33063319
33073320 if (sema.mod.comp.debug_incremental) {
33083321 try mod.intern_pool.addDependency(
3309 sema.gpa,
3322 gpa,
33103323 AnalUnit.wrap(.{ .decl = new_decl_index }),
3311 .{ .src_hash = try mod.intern_pool.trackZir(sema.gpa, block.getFileScope(mod), inst) },
3324 .{ .src_hash = try block.trackZir(inst) },
33123325 );
33133326 }
33143327
......@@ -3316,7 +3329,7 @@ fn zirUnionDecl(
33163329 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{
33173330 .parent = block.namespace.toOptional(),
33183331 .decl_index = new_decl_index,
3319 .file_scope = block.getFileScope(mod),
3332 .file_scope = block.getFileScopeIndex(mod),
33203333 })).toOptional() else .none;
33213334 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
33223335
......@@ -3348,7 +3361,7 @@ fn zirOpaqueDecl(
33483361 const extra = sema.code.extraData(Zir.Inst.OpaqueDecl, extended.operand);
33493362 var extra_index: usize = extra.end;
33503363
3351 const tracked_inst = try ip.trackZir(gpa, block.getFileScope(mod), inst);
3364 const tracked_inst = try block.trackZir(inst);
33523365 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };
33533366
33543367 const captures_len = if (small.has_captures_len) blk: {
......@@ -3397,14 +3410,14 @@ fn zirOpaqueDecl(
33973410 try ip.addDependency(
33983411 gpa,
33993412 AnalUnit.wrap(.{ .decl = new_decl_index }),
3400 .{ .src_hash = try ip.trackZir(gpa, block.getFileScope(mod), inst) },
3413 .{ .src_hash = try block.trackZir(inst) },
34013414 );
34023415 }
34033416
34043417 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (decls_len > 0) (try mod.createNamespace(.{
34053418 .parent = block.namespace.toOptional(),
34063419 .decl_index = new_decl_index,
3407 .file_scope = block.getFileScope(mod),
3420 .file_scope = block.getFileScopeIndex(mod),
34083421 })).toOptional() else .none;
34093422 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
34103423
......@@ -5893,8 +5906,8 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
58935906 const tracy = trace(@src());
58945907 defer tracy.end();
58955908
5896 const mod = sema.mod;
5897 const comp = mod.comp;
5909 const zcu = sema.mod;
5910 const comp = zcu.comp;
58985911 const gpa = sema.gpa;
58995912 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
59005913 const src = parent_block.nodeOffset(pl_node.src_node);
......@@ -5940,7 +5953,7 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
59405953 if (!comp.config.link_libc)
59415954 try sema.errNote(src, msg, "libc headers not available; compilation does not link against libc", .{});
59425955
5943 const gop = try mod.cimport_errors.getOrPut(gpa, sema.ownerUnit());
5956 const gop = try zcu.cimport_errors.getOrPut(gpa, sema.ownerUnit());
59445957 if (!gop.found_existing) {
59455958 gop.value_ptr.* = c_import_res.errors;
59465959 c_import_res.errors = std.zig.ErrorBundle.empty;
......@@ -5984,14 +5997,16 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
59845997 else => |e| return e,
59855998 };
59865999
5987 const result = mod.importPkg(c_import_mod) catch |err|
6000 const result = zcu.importPkg(c_import_mod) catch |err|
59886001 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
59896002
5990 mod.astGenFile(result.file) catch |err|
6003 const path_digest = zcu.filePathDigest(result.file_index);
6004 const root_decl = zcu.fileRootDecl(result.file_index);
6005 zcu.astGenFile(result.file, result.file_index, path_digest, root_decl) catch |err|
59916006 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
59926007
5993 try mod.ensureFileAnalyzed(result.file);
5994 const file_root_decl_index = result.file.root_decl.unwrap().?;
6008 try zcu.ensureFileAnalyzed(result.file_index);
6009 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
59956010 return sema.analyzeDeclVal(parent_block, src, file_root_decl_index);
59966011}
59976012
......@@ -6730,7 +6745,9 @@ fn lookupInNamespace(
67306745 // Skip decls which are not marked pub, which are in a different
67316746 // file than the `a.b`/`@hasDecl` syntax.
67326747 const decl = mod.declPtr(decl_index);
6733 if (decl.is_pub or (src_file == decl.getFileScope(mod) and checked_namespaces.values()[check_i])) {
6748 if (decl.is_pub or (src_file == decl.getFileScopeIndex(mod) and
6749 checked_namespaces.values()[check_i]))
6750 {
67346751 try candidates.append(gpa, decl_index);
67356752 }
67366753 }
......@@ -6741,7 +6758,7 @@ fn lookupInNamespace(
67416758 if (sub_usingnamespace_decl_index == sema.owner_decl_index) continue;
67426759 const sub_usingnamespace_decl = mod.declPtr(sub_usingnamespace_decl_index);
67436760 const sub_is_pub = entry.value_ptr.*;
6744 if (!sub_is_pub and src_file != sub_usingnamespace_decl.getFileScope(mod)) {
6761 if (!sub_is_pub and src_file != sub_usingnamespace_decl.getFileScopeIndex(mod)) {
67456762 // Skip usingnamespace decls which are not marked pub, which are in
67466763 // a different file than the `a.b`/`@hasDecl` syntax.
67476764 continue;
......@@ -6749,7 +6766,7 @@ fn lookupInNamespace(
67496766 try sema.ensureDeclAnalyzed(sub_usingnamespace_decl_index);
67506767 const ns_ty = sub_usingnamespace_decl.val.toType();
67516768 const sub_ns = mod.namespacePtrUnwrap(ns_ty.getNamespaceIndex(mod)) orelse continue;
6752 try checked_namespaces.put(gpa, sub_ns, src_file == sub_usingnamespace_decl.getFileScope(mod));
6769 try checked_namespaces.put(gpa, sub_ns, src_file == sub_usingnamespace_decl.getFileScopeIndex(mod));
67536770 }
67546771 }
67556772
......@@ -8067,20 +8084,20 @@ fn instantiateGenericCall(
80678084 call_tag: Air.Inst.Tag,
80688085 call_dbg_node: ?Zir.Inst.Index,
80698086) CompileError!Air.Inst.Ref {
8070 const mod = sema.mod;
8087 const zcu = sema.mod;
80718088 const gpa = sema.gpa;
8072 const ip = &mod.intern_pool;
8089 const ip = &zcu.intern_pool;
80738090
80748091 const func_val = try sema.resolveConstDefinedValue(block, func_src, func, .{
80758092 .needed_comptime_reason = "generic function being called must be comptime-known",
80768093 });
8077 const generic_owner = switch (mod.intern_pool.indexToKey(func_val.toIntern())) {
8094 const generic_owner = switch (zcu.intern_pool.indexToKey(func_val.toIntern())) {
80788095 .func => func_val.toIntern(),
8079 .ptr => |ptr| mod.declPtr(ptr.base_addr.decl).val.toIntern(),
8096 .ptr => |ptr| zcu.declPtr(ptr.base_addr.decl).val.toIntern(),
80808097 else => unreachable,
80818098 };
8082 const generic_owner_func = mod.intern_pool.indexToKey(generic_owner).func;
8083 const generic_owner_ty_info = mod.typeToFunc(Type.fromInterned(generic_owner_func.ty)).?;
8099 const generic_owner_func = zcu.intern_pool.indexToKey(generic_owner).func;
8100 const generic_owner_ty_info = zcu.typeToFunc(Type.fromInterned(generic_owner_func.ty)).?;
80848101
80858102 try sema.declareDependency(.{ .src_hash = generic_owner_func.zir_body_inst });
80868103
......@@ -8092,10 +8109,10 @@ fn instantiateGenericCall(
80928109 // The actual monomorphization happens via adding `func_instance` to
80938110 // `InternPool`.
80948111
8095 const fn_owner_decl = mod.declPtr(generic_owner_func.owner_decl);
8112 const fn_owner_decl = zcu.declPtr(generic_owner_func.owner_decl);
80968113 const namespace_index = fn_owner_decl.src_namespace;
8097 const namespace = mod.namespacePtr(namespace_index);
8098 const fn_zir = namespace.file_scope.zir;
8114 const namespace = zcu.namespacePtr(namespace_index);
8115 const fn_zir = namespace.fileScope(zcu).zir;
80998116 const fn_info = fn_zir.getFnInfo(generic_owner_func.zir_body_inst.resolve(ip));
81008117
81018118 const comptime_args = try sema.arena.alloc(InternPool.Index, args_info.count());
......@@ -8110,7 +8127,7 @@ fn instantiateGenericCall(
81108127 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
81118128 // new, monomorphized function, with the comptime parameters elided.
81128129 var child_sema: Sema = .{
8113 .mod = mod,
8130 .mod = zcu,
81148131 .gpa = gpa,
81158132 .arena = sema.arena,
81168133 .code = fn_zir,
......@@ -8199,7 +8216,7 @@ fn instantiateGenericCall(
81998216 const arg_ref = try args_info.analyzeArg(sema, block, arg_index, param_ty, generic_owner_ty_info, func);
82008217 try sema.validateRuntimeValue(block, args_info.argSrc(block, arg_index), arg_ref);
82018218 const arg_ty = sema.typeOf(arg_ref);
8202 if (arg_ty.zigTypeTag(mod) == .NoReturn) {
8219 if (arg_ty.zigTypeTag(zcu) == .NoReturn) {
82038220 // This terminates argument analysis.
82048221 return arg_ref;
82058222 }
......@@ -8283,12 +8300,12 @@ fn instantiateGenericCall(
82838300 const new_func_inst = try child_sema.resolveInlineBody(&child_block, fn_info.param_body[args_info.count()..], fn_info.param_body_inst);
82848301 const callee_index = (child_sema.resolveConstDefinedValue(&child_block, LazySrcLoc.unneeded, new_func_inst, undefined) catch unreachable).toIntern();
82858302
8286 const callee = mod.funcInfo(callee_index);
8303 const callee = zcu.funcInfo(callee_index);
82878304 callee.branchQuota(ip).* = @max(callee.branchQuota(ip).*, sema.branch_quota);
82888305
82898306 // Make a runtime call to the new function, making sure to omit the comptime args.
82908307 const func_ty = Type.fromInterned(callee.ty);
8291 const func_ty_info = mod.typeToFunc(func_ty).?;
8308 const func_ty_info = zcu.typeToFunc(func_ty).?;
82928309
82938310 // If the call evaluated to a return type that requires comptime, never mind
82948311 // our generic instantiation. Instead we need to perform a comptime call.
......@@ -8304,13 +8321,13 @@ fn instantiateGenericCall(
83048321 if (call_dbg_node) |some| try sema.zirDbgStmt(block, some);
83058322
83068323 if (sema.owner_func_index != .none and
8307 Type.fromInterned(func_ty_info.return_type).isError(mod))
8324 Type.fromInterned(func_ty_info.return_type).isError(zcu))
83088325 {
83098326 ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn = true;
83108327 }
83118328
83128329 try sema.addReferenceEntry(call_src, AnalUnit.wrap(.{ .func = callee_index }));
8313 try mod.ensureFuncBodyAnalysisQueued(callee_index);
8330 try zcu.ensureFuncBodyAnalysisQueued(callee_index);
83148331
83158332 try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.Call).Struct.fields.len + runtime_args.items.len);
83168333 const result = try block.addInst(.{
......@@ -8333,7 +8350,7 @@ fn instantiateGenericCall(
83338350 if (call_tag == .call_always_tail) {
83348351 return sema.handleTailCall(block, call_src, func_ty, result);
83358352 }
8336 if (func_ty.fnReturnType(mod).isNoReturn(mod)) {
8353 if (func_ty.fnReturnType(zcu).isNoReturn(zcu)) {
83378354 _ = try block.addNoOp(.unreach);
83388355 return .unreachable_value;
83398356 }
......@@ -9653,7 +9670,7 @@ fn funcCommon(
96539670 .is_generic = final_is_generic,
96549671 .is_noinline = is_noinline,
96559672
9656 .zir_body_inst = try ip.trackZir(gpa, block.getFileScope(mod), func_inst),
9673 .zir_body_inst = try block.trackZir(func_inst),
96579674 .lbrace_line = src_locs.lbrace_line,
96589675 .rbrace_line = src_locs.rbrace_line,
96599676 .lbrace_column = @as(u16, @truncate(src_locs.columns)),
......@@ -9731,7 +9748,7 @@ fn funcCommon(
97319748 .ty = func_ty,
97329749 .cc = cc,
97339750 .is_noinline = is_noinline,
9734 .zir_body_inst = try ip.trackZir(gpa, block.getFileScope(mod), func_inst),
9751 .zir_body_inst = try block.trackZir(func_inst),
97359752 .lbrace_line = src_locs.lbrace_line,
97369753 .rbrace_line = src_locs.rbrace_line,
97379754 .lbrace_column = @as(u16, @truncate(src_locs.columns)),
......@@ -13787,18 +13804,18 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1378713804 const tracy = trace(@src());
1378813805 defer tracy.end();
1378913806
13790 const mod = sema.mod;
13807 const zcu = sema.mod;
1379113808 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1379213809 const operand_src = block.tokenOffset(inst_data.src_tok);
1379313810 const operand = inst_data.get(sema.code);
1379413811
13795 const result = mod.importFile(block.getFileScope(mod), operand) catch |err| switch (err) {
13812 const result = zcu.importFile(block.getFileScope(zcu), operand) catch |err| switch (err) {
1379613813 error.ImportOutsideModulePath => {
1379713814 return sema.fail(block, operand_src, "import of file outside module path: '{s}'", .{operand});
1379813815 },
1379913816 error.ModuleNotFound => {
1380013817 return sema.fail(block, operand_src, "no module named '{s}' available within module {s}", .{
13801 operand, block.getFileScope(mod).mod.fully_qualified_name,
13818 operand, block.getFileScope(zcu).mod.fully_qualified_name,
1380213819 });
1380313820 },
1380413821 else => {
......@@ -13807,8 +13824,8 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1380713824 return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
1380813825 },
1380913826 };
13810 try mod.ensureFileAnalyzed(result.file);
13811 const file_root_decl_index = result.file.root_decl.unwrap().?;
13827 try zcu.ensureFileAnalyzed(result.file_index);
13828 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
1381213829 return sema.analyzeDeclVal(block, operand_src, file_root_decl_index);
1381313830}
1381413831
......@@ -21089,7 +21106,7 @@ fn zirReify(
2108921106 const ip = &mod.intern_pool;
2109021107 const name_strategy: Zir.Inst.NameStrategy = @enumFromInt(extended.small);
2109121108 const extra = sema.code.extraData(Zir.Inst.Reify, extended.operand).data;
21092 const tracked_inst = try ip.trackZir(gpa, block.getFileScope(mod), inst);
21109 const tracked_inst = try block.trackZir(inst);
2109321110 const src: LazySrcLoc = .{
2109421111 .base_node_inst = tracked_inst,
2109521112 .offset = LazySrcLoc.Offset.nodeOffset(0),
......@@ -21466,7 +21483,7 @@ fn zirReify(
2146621483 const wip_ty = switch (try ip.getOpaqueType(gpa, .{
2146721484 .has_namespace = false,
2146821485 .key = .{ .reified = .{
21469 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),
21486 .zir_index = try block.trackZir(inst),
2147021487 } },
2147121488 })) {
2147221489 .existing => |ty| return Air.internedToRef(ty),
......@@ -21660,7 +21677,7 @@ fn reifyEnum(
2166021677 .tag_mode = if (is_exhaustive) .explicit else .nonexhaustive,
2166121678 .fields_len = fields_len,
2166221679 .key = .{ .reified = .{
21663 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),
21680 .zir_index = try block.trackZir(inst),
2166421681 .type_hash = hasher.final(),
2166521682 } },
2166621683 })) {
......@@ -21810,7 +21827,7 @@ fn reifyUnion(
2181021827 .field_types = &.{}, // set later
2181121828 .field_aligns = &.{}, // set later
2181221829 .key = .{ .reified = .{
21813 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),
21830 .zir_index = try block.trackZir(inst),
2181421831 .type_hash = hasher.final(),
2181521832 } },
2181621833 })) {
......@@ -22062,7 +22079,7 @@ fn reifyStruct(
2206222079 .inits_resolved = true,
2206322080 .has_namespace = false,
2206422081 .key = .{ .reified = .{
22065 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),
22082 .zir_index = try block.trackZir(inst),
2206622083 .type_hash = hasher.final(),
2206722084 } },
2206822085 })) {
......@@ -34894,14 +34911,14 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3489434911 _ = try sema.typeRequiresComptime(ty);
3489534912}
3489634913
34897fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) CompileError!void {
34898 const gpa = mod.gpa;
34899 const ip = &mod.intern_pool;
34914fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) CompileError!void {
34915 const gpa = zcu.gpa;
34916 const ip = &zcu.intern_pool;
3490034917
3490134918 const decl_index = struct_type.decl.unwrap().?;
34902 const decl = mod.declPtr(decl_index);
34919 const decl = zcu.declPtr(decl_index);
3490334920
34904 const zir = mod.namespacePtr(struct_type.namespace.unwrap().?).file_scope.zir;
34921 const zir = zcu.namespacePtr(struct_type.namespace.unwrap().?).fileScope(zcu).zir;
3490534922
3490634923 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
3490734924 defer analysis_arena.deinit();
......@@ -34910,7 +34927,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co
3491034927 defer comptime_err_ret_trace.deinit();
3491134928
3491234929 var sema: Sema = .{
34913 .mod = mod,
34930 .mod = zcu,
3491434931 .gpa = gpa,
3491534932 .arena = analysis_arena.allocator(),
3491634933 .code = zir,
......@@ -34941,7 +34958,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co
3494134958 var accumulator: u64 = 0;
3494234959 for (0..struct_type.field_types.len) |i| {
3494334960 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
34944 accumulator += try field_ty.bitSizeAdvanced(mod, .sema);
34961 accumulator += try field_ty.bitSizeAdvanced(zcu, .sema);
3494534962 }
3494634963 break :blk accumulator;
3494734964 };
......@@ -34987,7 +35004,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co
3498735004 if (fields_bit_sum > std.math.maxInt(u16)) {
3498835005 return sema.fail(&block, block.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});
3498935006 }
34990 const backing_int_ty = try mod.intType(.unsigned, @intCast(fields_bit_sum));
35007 const backing_int_ty = try zcu.intType(.unsigned, @intCast(fields_bit_sum));
3499135008 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
3499235009 }
3499335010
......@@ -35597,23 +35614,23 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {
3559735614}
3559835615
3559935616fn semaStructFields(
35600 mod: *Module,
35617 zcu: *Zcu,
3560135618 arena: Allocator,
3560235619 struct_type: InternPool.LoadedStructType,
3560335620) CompileError!void {
35604 const gpa = mod.gpa;
35605 const ip = &mod.intern_pool;
35621 const gpa = zcu.gpa;
35622 const ip = &zcu.intern_pool;
3560635623 const decl_index = struct_type.decl.unwrap() orelse return;
35607 const decl = mod.declPtr(decl_index);
35624 const decl = zcu.declPtr(decl_index);
3560835625 const namespace_index = struct_type.namespace.unwrap() orelse decl.src_namespace;
35609 const zir = mod.namespacePtr(namespace_index).file_scope.zir;
35626 const zir = zcu.namespacePtr(namespace_index).fileScope(zcu).zir;
3561035627 const zir_index = struct_type.zir_index.unwrap().?.resolve(ip);
3561135628
3561235629 const fields_len, const small, var extra_index = structZirInfo(zir, zir_index);
3561335630
3561435631 if (fields_len == 0) switch (struct_type.layout) {
3561535632 .@"packed" => {
35616 try semaBackingIntType(mod, struct_type);
35633 try semaBackingIntType(zcu, struct_type);
3561735634 return;
3561835635 },
3561935636 .auto, .@"extern" => {
......@@ -35627,7 +35644,7 @@ fn semaStructFields(
3562735644 defer comptime_err_ret_trace.deinit();
3562835645
3562935646 var sema: Sema = .{
35630 .mod = mod,
35647 .mod = zcu,
3563135648 .gpa = gpa,
3563235649 .arena = arena,
3563335650 .code = zir,
......@@ -35749,7 +35766,7 @@ fn semaStructFields(
3574935766
3575035767 struct_type.field_types.get(ip)[field_i] = field_ty.toIntern();
3575135768
35752 if (field_ty.zigTypeTag(mod) == .Opaque) {
35769 if (field_ty.zigTypeTag(zcu) == .Opaque) {
3575335770 const msg = msg: {
3575435771 const msg = try sema.errMsg(ty_src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});
3575535772 errdefer msg.destroy(sema.gpa);
......@@ -35759,7 +35776,7 @@ fn semaStructFields(
3575935776 };
3576035777 return sema.failWithOwnedErrorMsg(&block_scope, msg);
3576135778 }
35762 if (field_ty.zigTypeTag(mod) == .NoReturn) {
35779 if (field_ty.zigTypeTag(zcu) == .NoReturn) {
3576335780 const msg = msg: {
3576435781 const msg = try sema.errMsg(ty_src, "struct fields cannot be 'noreturn'", .{});
3576535782 errdefer msg.destroy(sema.gpa);
......@@ -35772,7 +35789,7 @@ fn semaStructFields(
3577235789 switch (struct_type.layout) {
3577335790 .@"extern" => if (!try sema.validateExternType(field_ty, .struct_field)) {
3577435791 const msg = msg: {
35775 const msg = try sema.errMsg(ty_src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
35792 const msg = try sema.errMsg(ty_src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
3577635793 errdefer msg.destroy(sema.gpa);
3577735794
3577835795 try sema.explainWhyTypeIsNotExtern(msg, ty_src, field_ty, .struct_field);
......@@ -35784,7 +35801,7 @@ fn semaStructFields(
3578435801 },
3578535802 .@"packed" => if (!try sema.validatePackedType(field_ty)) {
3578635803 const msg = msg: {
35787 const msg = try sema.errMsg(ty_src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
35804 const msg = try sema.errMsg(ty_src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
3578835805 errdefer msg.destroy(sema.gpa);
3578935806
3579035807 try sema.explainWhyTypeIsNotPacked(msg, ty_src, field_ty);
......@@ -35820,19 +35837,19 @@ fn semaStructFields(
3582035837
3582135838// This logic must be kept in sync with `semaStructFields`
3582235839fn semaStructFieldInits(
35823 mod: *Module,
35840 zcu: *Zcu,
3582435841 arena: Allocator,
3582535842 struct_type: InternPool.LoadedStructType,
3582635843) CompileError!void {
35827 const gpa = mod.gpa;
35828 const ip = &mod.intern_pool;
35844 const gpa = zcu.gpa;
35845 const ip = &zcu.intern_pool;
3582935846
3583035847 assert(!struct_type.haveFieldInits(ip));
3583135848
3583235849 const decl_index = struct_type.decl.unwrap() orelse return;
35833 const decl = mod.declPtr(decl_index);
35850 const decl = zcu.declPtr(decl_index);
3583435851 const namespace_index = struct_type.namespace.unwrap() orelse decl.src_namespace;
35835 const zir = mod.namespacePtr(namespace_index).file_scope.zir;
35852 const zir = zcu.namespacePtr(namespace_index).fileScope(zcu).zir;
3583635853 const zir_index = struct_type.zir_index.unwrap().?.resolve(ip);
3583735854 const fields_len, const small, var extra_index = structZirInfo(zir, zir_index);
3583835855
......@@ -35840,7 +35857,7 @@ fn semaStructFieldInits(
3584035857 defer comptime_err_ret_trace.deinit();
3584135858
3584235859 var sema: Sema = .{
35843 .mod = mod,
35860 .mod = zcu,
3584435861 .gpa = gpa,
3584535862 .arena = arena,
3584635863 .code = zir,
......@@ -35950,7 +35967,7 @@ fn semaStructFieldInits(
3595035967 });
3595135968 };
3595235969
35953 if (default_val.canMutateComptimeVarState(mod)) {
35970 if (default_val.canMutateComptimeVarState(zcu)) {
3595435971 return sema.fail(&block_scope, init_src, "field default value contains reference to comptime-mutable memory", .{});
3595535972 }
3595635973 struct_type.field_inits.get(ip)[field_i] = default_val.toIntern();
......@@ -35960,14 +35977,14 @@ fn semaStructFieldInits(
3596035977 try sema.flushExports();
3596135978}
3596235979
35963fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.LoadedUnionType) CompileError!void {
35980fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUnionType) CompileError!void {
3596435981 const tracy = trace(@src());
3596535982 defer tracy.end();
3596635983
35967 const gpa = mod.gpa;
35968 const ip = &mod.intern_pool;
35984 const gpa = zcu.gpa;
35985 const ip = &zcu.intern_pool;
3596935986 const decl_index = union_type.decl;
35970 const zir = mod.namespacePtr(union_type.namespace.unwrap().?).file_scope.zir;
35987 const zir = zcu.namespacePtr(union_type.namespace.unwrap().?).fileScope(zcu).zir;
3597135988 const zir_index = union_type.zir_index.resolve(ip);
3597235989 const extended = zir.instructions.items(.data)[@intFromEnum(zir_index)].extended;
3597335990 assert(extended.opcode == .union_decl);
......@@ -36011,13 +36028,13 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3601136028 const body = zir.bodySlice(extra_index, body_len);
3601236029 extra_index += body.len;
3601336030
36014 const decl = mod.declPtr(decl_index);
36031 const decl = zcu.declPtr(decl_index);
3601536032
3601636033 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);
3601736034 defer comptime_err_ret_trace.deinit();
3601836035
3601936036 var sema: Sema = .{
36020 .mod = mod,
36037 .mod = zcu,
3602136038 .gpa = gpa,
3602236039 .arena = arena,
3602336040 .code = zir,
......@@ -36063,18 +36080,18 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3606336080 if (small.auto_enum_tag) {
3606436081 // The provided type is an integer type and we must construct the enum tag type here.
3606536082 int_tag_ty = provided_ty;
36066 if (int_tag_ty.zigTypeTag(mod) != .Int and int_tag_ty.zigTypeTag(mod) != .ComptimeInt) {
36067 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(mod)});
36083 if (int_tag_ty.zigTypeTag(zcu) != .Int and int_tag_ty.zigTypeTag(zcu) != .ComptimeInt) {
36084 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(zcu)});
3606836085 }
3606936086
3607036087 if (fields_len > 0) {
36071 const field_count_val = try mod.intValue(Type.comptime_int, fields_len - 1);
36088 const field_count_val = try zcu.intValue(Type.comptime_int, fields_len - 1);
3607236089 if (!(try sema.intFitsInType(field_count_val, int_tag_ty, null))) {
3607336090 const msg = msg: {
3607436091 const msg = try sema.errMsg(tag_ty_src, "specified integer tag type cannot represent every field", .{});
3607536092 errdefer msg.destroy(sema.gpa);
3607636093 try sema.errNote(tag_ty_src, msg, "type '{}' cannot fit values in range 0...{d}", .{
36077 int_tag_ty.fmt(mod),
36094 int_tag_ty.fmt(zcu),
3607836095 fields_len - 1,
3607936096 });
3608036097 break :msg msg;
......@@ -36089,7 +36106,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3608936106 union_type.tagTypePtr(ip).* = provided_ty.toIntern();
3609036107 const enum_type = switch (ip.indexToKey(provided_ty.toIntern())) {
3609136108 .enum_type => ip.loadEnumType(provided_ty.toIntern()),
36092 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(mod)}),
36109 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(zcu)}),
3609336110 };
3609436111 // The fields of the union must match the enum exactly.
3609536112 // A flag per field is used to check for missing and extraneous fields.
......@@ -36185,7 +36202,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3618536202 const val = if (last_tag_val) |val|
3618636203 try sema.intAdd(val, Value.one_comptime_int, int_tag_ty, undefined)
3618736204 else
36188 try mod.intValue(int_tag_ty, 0);
36205 try zcu.intValue(int_tag_ty, 0);
3618936206 last_tag_val = val;
3619036207
3619136208 break :blk val;
......@@ -36197,7 +36214,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3619736214 .offset = .{ .container_field_value = @intCast(gop.index) },
3619836215 };
3619936216 const msg = msg: {
36200 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(mod, &sema)});
36217 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(zcu, &sema)});
3620136218 errdefer msg.destroy(gpa);
3620236219 try sema.errNote(other_value_src, msg, "other occurrence here", .{});
3620336220 break :msg msg;
......@@ -36227,7 +36244,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3622736244 const tag_info = ip.loadEnumType(union_type.tagTypePtr(ip).*);
3622836245 const enum_index = tag_info.nameIndex(ip, field_name) orelse {
3622936246 return sema.fail(&block_scope, name_src, "no field named '{}' in enum '{}'", .{
36230 field_name.fmt(ip), Type.fromInterned(union_type.tagTypePtr(ip).*).fmt(mod),
36247 field_name.fmt(ip), Type.fromInterned(union_type.tagTypePtr(ip).*).fmt(zcu),
3623136248 });
3623236249 };
3623336250
......@@ -36254,7 +36271,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3625436271 }
3625536272 }
3625636273
36257 if (field_ty.zigTypeTag(mod) == .Opaque) {
36274 if (field_ty.zigTypeTag(zcu) == .Opaque) {
3625836275 const msg = msg: {
3625936276 const msg = try sema.errMsg(type_src, "opaque types have unknown size and therefore cannot be directly embedded in unions", .{});
3626036277 errdefer msg.destroy(sema.gpa);
......@@ -36269,7 +36286,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3626936286 !try sema.validateExternType(field_ty, .union_field))
3627036287 {
3627136288 const msg = msg: {
36272 const msg = try sema.errMsg(type_src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
36289 const msg = try sema.errMsg(type_src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
3627336290 errdefer msg.destroy(sema.gpa);
3627436291
3627536292 try sema.explainWhyTypeIsNotExtern(msg, type_src, field_ty, .union_field);
......@@ -36280,7 +36297,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3628036297 return sema.failWithOwnedErrorMsg(&block_scope, msg);
3628136298 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
3628236299 const msg = msg: {
36283 const msg = try sema.errMsg(type_src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
36300 const msg = try sema.errMsg(type_src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
3628436301 errdefer msg.destroy(sema.gpa);
3628536302
3628636303 try sema.explainWhyTypeIsNotPacked(msg, type_src, field_ty);
......@@ -36325,10 +36342,10 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
3632536342 return sema.failWithOwnedErrorMsg(&block_scope, msg);
3632636343 }
3632736344 } else if (enum_field_vals.count() > 0) {
36328 const enum_ty = try sema.generateUnionTagTypeNumbered(&block_scope, enum_field_names, enum_field_vals.keys(), mod.declPtr(union_type.decl));
36345 const enum_ty = try sema.generateUnionTagTypeNumbered(&block_scope, enum_field_names, enum_field_vals.keys(), zcu.declPtr(union_type.decl));
3632936346 union_type.tagTypePtr(ip).* = enum_ty;
3633036347 } else {
36331 const enum_ty = try sema.generateUnionTagTypeSimple(&block_scope, enum_field_names, mod.declPtr(union_type.decl));
36348 const enum_ty = try sema.generateUnionTagTypeSimple(&block_scope, enum_field_names, zcu.declPtr(union_type.decl));
3633236349 union_type.tagTypePtr(ip).* = enum_ty;
3633336350 }
3633436351
src/Type.zig+1-1
......@@ -3455,7 +3455,7 @@ pub fn typeDeclSrcLine(ty: Type, zcu: *const Zcu) ?u32 {
34553455 else => return null,
34563456 };
34573457 const info = tracked.resolveFull(&zcu.intern_pool);
3458 const file = zcu.import_table.values()[zcu.path_digest_map.getIndex(info.path_digest).?];
3458 const file = zcu.fileByIndex(info.file);
34593459 assert(file.zir_loaded);
34603460 const zir = file.zir;
34613461 const inst = zir.instructions.get(@intFromEnum(info.inst));
src/Zcu.zig+318-252
......@@ -72,6 +72,7 @@ codegen_prog_node: std.Progress.Node = undefined,
7272global_zir_cache: Compilation.Directory,
7373/// Used by AstGen worker to load and store ZIR cache.
7474local_zir_cache: Compilation.Directory,
75
7576/// This is where all `Export` values are stored. Not all values here are necessarily valid exports;
7677/// to enumerate all exports, `single_exports` and `multi_exports` must be consulted.
7778all_exports: ArrayListUnmanaged(Export) = .{},
......@@ -88,14 +89,22 @@ multi_exports: std.AutoArrayHashMapUnmanaged(AnalUnit, extern struct {
8889 index: u32,
8990 len: u32,
9091}) = .{},
91/// The set of all the Zig source files in the Module. We keep track of this in order
92/// to iterate over it and check which source files have been modified on the file system when
93/// an update is requested, as well as to cache `@import` results.
92
93/// The set of all the Zig source files in the Zig Compilation Unit. Tracked in
94/// order to iterate over it and check which source files have been modified on
95/// the file system when an update is requested, as well as to cache `@import`
96/// results.
97///
9498/// Keys are fully resolved file paths. This table owns the keys and values.
99///
100/// Protected by Compilation's mutex.
101///
102/// Not serialized. This state is reconstructed during the first call to
103/// `Compilation.update` of the process for a given `Compilation`.
104///
105/// Indexes correspond 1:1 to `files`.
95106import_table: std.StringArrayHashMapUnmanaged(*File) = .{},
96/// This acts as a map from `path_digest` to the corresponding `File`.
97/// The value is omitted, as keys are ordered identically to `import_table`.
98path_digest_map: std.AutoArrayHashMapUnmanaged(Cache.BinDigest, void) = .{},
107
99108/// The set of all the files which have been loaded with `@embedFile` in the Module.
100109/// We keep track of this in order to iterate over it and check which files have been
101110/// modified on the file system when an update is requested, as well as to cache
......@@ -387,8 +396,8 @@ pub const Decl = struct {
387396 anon,
388397 };
389398
390 const Index = InternPool.DeclIndex;
391 const OptionalIndex = InternPool.OptionalDeclIndex;
399 pub const Index = InternPool.DeclIndex;
400 pub const OptionalIndex = InternPool.OptionalDeclIndex;
392401
393402 pub fn zirBodies(decl: Decl, zcu: *Zcu) Zir.Inst.Declaration.Bodies {
394403 const zir = decl.getFileScope(zcu).zir;
......@@ -490,6 +499,10 @@ pub const Decl = struct {
490499 }
491500
492501 pub fn getFileScope(decl: Decl, zcu: *Zcu) *File {
502 return zcu.fileByIndex(getFileScopeIndex(decl, zcu));
503 }
504
505 pub fn getFileScopeIndex(decl: Decl, zcu: *Zcu) File.Index {
493506 return zcu.namespacePtr(decl.src_namespace).file_scope;
494507 }
495508
......@@ -546,19 +559,20 @@ pub const Decl = struct {
546559 }
547560
548561 pub fn navSrcLine(decl: Decl, zcu: *Zcu) u32 {
562 const ip = &zcu.intern_pool;
549563 const tracked = decl.zir_decl_index.unwrap() orelse inst: {
550564 // generic instantiation
551565 assert(decl.has_tv);
552566 assert(decl.owns_tv);
553 const generic_owner_func = switch (zcu.intern_pool.indexToKey(decl.val.toIntern())) {
567 const generic_owner_func = switch (ip.indexToKey(decl.val.toIntern())) {
554568 .func => |func| func.generic_owner,
555569 else => return 0, // TODO: this is probably a `variable` or something; figure this out when we finish sorting out `Decl`.
556570 };
557571 const generic_owner_decl = zcu.declPtr(zcu.funcInfo(generic_owner_func).owner_decl);
558572 break :inst generic_owner_decl.zir_decl_index.unwrap().?;
559573 };
560 const info = tracked.resolveFull(&zcu.intern_pool);
561 const file = zcu.import_table.values()[zcu.path_digest_map.getIndex(info.path_digest).?];
574 const info = tracked.resolveFull(ip);
575 const file = zcu.fileByIndex(info.file);
562576 assert(file.zir_loaded);
563577 const zir = file.zir;
564578 const inst = zir.instructions.get(@intFromEnum(info.inst));
......@@ -595,7 +609,7 @@ pub const DeclAdapter = struct {
595609/// The container that structs, enums, unions, and opaques have.
596610pub const Namespace = struct {
597611 parent: OptionalIndex,
598 file_scope: *File,
612 file_scope: File.Index,
599613 /// Will be a struct, enum, union, or opaque.
600614 decl_index: Decl.Index,
601615 /// Direct children of the namespace.
......@@ -627,6 +641,10 @@ pub const Namespace = struct {
627641 }
628642 };
629643
644 pub fn fileScope(ns: Namespace, zcu: *Zcu) *File {
645 return zcu.fileByIndex(ns.file_scope);
646 }
647
630648 // This renders e.g. "std.fs.Dir.OpenOptions"
631649 pub fn renderFullyQualifiedName(
632650 ns: Namespace,
......@@ -641,7 +659,7 @@ pub const Namespace = struct {
641659 writer,
642660 );
643661 } else {
644 try ns.file_scope.renderFullyQualifiedName(writer);
662 try ns.fileScope(zcu).renderFullyQualifiedName(writer);
645663 }
646664 if (name != .empty) try writer.print(".{}", .{name.fmt(&zcu.intern_pool)});
647665 }
......@@ -661,7 +679,7 @@ pub const Namespace = struct {
661679 );
662680 break :sep '.';
663681 } else sep: {
664 try ns.file_scope.renderFullyQualifiedDebugName(writer);
682 try ns.fileScope(zcu).renderFullyQualifiedDebugName(writer);
665683 break :sep ':';
666684 };
667685 if (name != .empty) try writer.print("{c}{}", .{ sep, name.fmt(&zcu.intern_pool) });
......@@ -680,7 +698,7 @@ pub const Namespace = struct {
680698 const decl = zcu.declPtr(cur_ns.decl_index);
681699 count += decl.name.length(ip) + 1;
682700 cur_ns = zcu.namespacePtr(cur_ns.parent.unwrap() orelse {
683 count += ns.file_scope.sub_file_path.len;
701 count += ns.fileScope(zcu).sub_file_path.len;
684702 break :count count;
685703 });
686704 }
......@@ -715,8 +733,6 @@ pub const Namespace = struct {
715733};
716734
717735pub const File = struct {
718 /// The Decl of the struct that represents this File.
719 root_decl: Decl.OptionalIndex,
720736 status: enum {
721737 never_loaded,
722738 retryable_failure,
......@@ -744,8 +760,6 @@ pub const File = struct {
744760 multi_pkg: bool = false,
745761 /// List of references to this file, used for multi-package errors.
746762 references: std.ArrayListUnmanaged(File.Reference) = .{},
747 /// The hash of the path to this file, used to store `InternPool.TrackedInst`.
748 path_digest: Cache.BinDigest,
749763
750764 /// The most recent successful ZIR for this file, with no errors.
751765 /// This is only populated when a previously successful ZIR
......@@ -757,7 +771,7 @@ pub const File = struct {
757771 pub const Reference = union(enum) {
758772 /// The file is imported directly (i.e. not as a package) with @import.
759773 import: struct {
760 file: *File,
774 file: File.Index,
761775 token: Ast.TokenIndex,
762776 },
763777 /// The file is the root of a module.
......@@ -791,28 +805,6 @@ pub const File = struct {
791805 }
792806 }
793807
794 pub fn deinit(file: *File, mod: *Module) void {
795 const gpa = mod.gpa;
796 const is_builtin = file.mod.isBuiltin();
797 log.debug("deinit File {s}", .{file.sub_file_path});
798 if (is_builtin) {
799 file.unloadTree(gpa);
800 file.unloadZir(gpa);
801 } else {
802 gpa.free(file.sub_file_path);
803 file.unload(gpa);
804 }
805 file.references.deinit(gpa);
806 if (file.root_decl.unwrap()) |root_decl| {
807 mod.destroyDecl(root_decl);
808 }
809 if (file.prev_zir) |prev_zir| {
810 prev_zir.deinit(gpa);
811 gpa.destroy(prev_zir);
812 }
813 file.* = undefined;
814 }
815
816808 pub const Source = struct {
817809 bytes: [:0]const u8,
818810 stat: Cache.File.Stat,
......@@ -865,13 +857,6 @@ pub const File = struct {
865857 return &file.tree;
866858 }
867859
868 pub fn destroy(file: *File, mod: *Module) void {
869 const gpa = mod.gpa;
870 const is_builtin = file.mod.isBuiltin();
871 file.deinit(mod);
872 if (!is_builtin) gpa.destroy(file);
873 }
874
875860 pub fn renderFullyQualifiedName(file: File, writer: anytype) !void {
876861 // Convert all the slashes into dots and truncate the extension.
877862 const ext = std.fs.path.extension(file.sub_file_path);
......@@ -937,7 +922,7 @@ pub const File = struct {
937922 }
938923
939924 const mod = switch (ref) {
940 .import => |import| import.file.mod,
925 .import => |import| zcu.fileByIndex(import.file).mod,
941926 .root => |mod| mod,
942927 };
943928 if (mod != file.mod) file.multi_pkg = true;
......@@ -971,6 +956,8 @@ pub const File = struct {
971956 }
972957 }
973958 }
959
960 pub const Index = InternPool.FileIndex;
974961};
975962
976963pub const EmbedFile = struct {
......@@ -2350,14 +2337,12 @@ pub const LazySrcLoc = struct {
23502337 };
23512338
23522339 pub fn resolveBaseNode(base_node_inst: InternPool.TrackedInst.Index, zcu: *Zcu) struct { *File, Ast.Node.Index } {
2353 const want_path_digest, const zir_inst = inst: {
2354 const info = base_node_inst.resolveFull(&zcu.intern_pool);
2355 break :inst .{ info.path_digest, info.inst };
2356 };
2357 const file = file: {
2358 const index = zcu.path_digest_map.getIndex(want_path_digest).?;
2359 break :file zcu.import_table.values()[index];
2340 const ip = &zcu.intern_pool;
2341 const file_index, const zir_inst = inst: {
2342 const info = base_node_inst.resolveFull(ip);
2343 break :inst .{ info.file, info.inst };
23602344 };
2345 const file = zcu.fileByIndex(file_index);
23612346 assert(file.zir_loaded);
23622347
23632348 const zir = file.zir;
......@@ -2423,11 +2408,11 @@ pub fn deinit(zcu: *Zcu) void {
24232408 for (zcu.import_table.keys()) |key| {
24242409 gpa.free(key);
24252410 }
2426 for (zcu.import_table.values()) |value| {
2427 value.destroy(zcu);
2411 for (0..zcu.import_table.entries.len) |file_index_usize| {
2412 const file_index: File.Index = @enumFromInt(file_index_usize);
2413 zcu.destroyFile(file_index);
24282414 }
24292415 zcu.import_table.deinit(gpa);
2430 zcu.path_digest_map.deinit(gpa);
24312416
24322417 for (zcu.embed_table.keys(), zcu.embed_table.values()) |path, embed_file| {
24332418 gpa.free(path);
......@@ -2531,6 +2516,37 @@ pub fn destroyDecl(mod: *Module, decl_index: Decl.Index) void {
25312516 }
25322517}
25332518
2519fn deinitFile(zcu: *Zcu, file_index: File.Index) void {
2520 const gpa = zcu.gpa;
2521 const file = zcu.fileByIndex(file_index);
2522 const is_builtin = file.mod.isBuiltin();
2523 log.debug("deinit File {s}", .{file.sub_file_path});
2524 if (is_builtin) {
2525 file.unloadTree(gpa);
2526 file.unloadZir(gpa);
2527 } else {
2528 gpa.free(file.sub_file_path);
2529 file.unload(gpa);
2530 }
2531 file.references.deinit(gpa);
2532 if (zcu.fileRootDecl(file_index).unwrap()) |root_decl| {
2533 zcu.destroyDecl(root_decl);
2534 }
2535 if (file.prev_zir) |prev_zir| {
2536 prev_zir.deinit(gpa);
2537 gpa.destroy(prev_zir);
2538 }
2539 file.* = undefined;
2540}
2541
2542pub fn destroyFile(zcu: *Zcu, file_index: File.Index) void {
2543 const gpa = zcu.gpa;
2544 const file = zcu.fileByIndex(file_index);
2545 const is_builtin = file.mod.isBuiltin();
2546 zcu.deinitFile(file_index);
2547 if (!is_builtin) gpa.destroy(file);
2548}
2549
25342550pub fn declPtr(mod: *Module, index: Decl.Index) *Decl {
25352551 return mod.intern_pool.declPtr(index);
25362552}
......@@ -2563,14 +2579,23 @@ comptime {
25632579 }
25642580}
25652581
2566pub fn astGenFile(mod: *Module, file: *File) !void {
2582pub fn astGenFile(
2583 zcu: *Zcu,
2584 file: *File,
2585 /// This parameter is provided separately from `file` because it is not
2586 /// safe to access `import_table` without a lock, and this index is needed
2587 /// in the call to `updateZirRefs`.
2588 file_index: File.Index,
2589 path_digest: Cache.BinDigest,
2590 opt_root_decl: Zcu.Decl.OptionalIndex,
2591) !void {
25672592 assert(!file.mod.isBuiltin());
25682593
25692594 const tracy = trace(@src());
25702595 defer tracy.end();
25712596
2572 const comp = mod.comp;
2573 const gpa = mod.gpa;
2597 const comp = zcu.comp;
2598 const gpa = zcu.gpa;
25742599
25752600 // In any case we need to examine the stat of the file to determine the course of action.
25762601 var source_file = try file.mod.root.openFile(file.sub_file_path, .{});
......@@ -2578,17 +2603,9 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
25782603
25792604 const stat = try source_file.stat();
25802605
2581 const want_local_cache = file.mod == mod.main_mod;
2582 const hex_digest = hex: {
2583 var hex: Cache.HexDigest = undefined;
2584 _ = std.fmt.bufPrint(
2585 &hex,
2586 "{s}",
2587 .{std.fmt.fmtSliceHexLower(&file.path_digest)},
2588 ) catch unreachable;
2589 break :hex hex;
2590 };
2591 const cache_directory = if (want_local_cache) mod.local_zir_cache else mod.global_zir_cache;
2606 const want_local_cache = file.mod == zcu.main_mod;
2607 const hex_digest = Cache.binToHex(path_digest);
2608 const cache_directory = if (want_local_cache) zcu.local_zir_cache else zcu.global_zir_cache;
25922609 const zir_dir = cache_directory.handle;
25932610
25942611 // Determine whether we need to reload the file from disk and redo parsing and AstGen.
......@@ -2688,7 +2705,7 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
26882705 {
26892706 comp.mutex.lock();
26902707 defer comp.mutex.unlock();
2691 try mod.failed_files.putNoClobber(gpa, file, null);
2708 try zcu.failed_files.putNoClobber(gpa, file, null);
26922709 }
26932710 file.status = .astgen_failure;
26942711 return error.AnalysisFail;
......@@ -2712,7 +2729,7 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
27122729 else => |e| return e,
27132730 };
27142731
2715 mod.lockAndClearFileCompileError(file);
2732 zcu.lockAndClearFileCompileError(file);
27162733
27172734 // If the previous ZIR does not have compile errors, keep it around
27182735 // in case parsing or new ZIR fails. In case of successful ZIR update
......@@ -2818,27 +2835,27 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
28182835 {
28192836 comp.mutex.lock();
28202837 defer comp.mutex.unlock();
2821 try mod.failed_files.putNoClobber(gpa, file, null);
2838 try zcu.failed_files.putNoClobber(gpa, file, null);
28222839 }
28232840 file.status = .astgen_failure;
28242841 return error.AnalysisFail;
28252842 }
28262843
28272844 if (file.prev_zir) |prev_zir| {
2828 try updateZirRefs(mod, file, prev_zir.*);
2845 try updateZirRefs(zcu, file, file_index, prev_zir.*);
28292846 // No need to keep previous ZIR.
28302847 prev_zir.deinit(gpa);
28312848 gpa.destroy(prev_zir);
28322849 file.prev_zir = null;
28332850 }
28342851
2835 if (file.root_decl.unwrap()) |root_decl| {
2852 if (opt_root_decl.unwrap()) |root_decl| {
28362853 // The root of this file must be re-analyzed, since the file has changed.
28372854 comp.mutex.lock();
28382855 defer comp.mutex.unlock();
28392856
28402857 log.debug("outdated root Decl: {}", .{root_decl});
2841 try mod.outdated_file_root.put(gpa, root_decl, {});
2858 try zcu.outdated_file_root.put(gpa, root_decl, {});
28422859 }
28432860}
28442861
......@@ -2914,7 +2931,7 @@ fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_file: std.fs.File)
29142931
29152932/// This is called from the AstGen thread pool, so must acquire
29162933/// the Compilation mutex when acting on shared state.
2917fn updateZirRefs(zcu: *Module, file: *File, old_zir: Zir) !void {
2934fn updateZirRefs(zcu: *Module, file: *File, file_index: File.Index, old_zir: Zir) !void {
29182935 const gpa = zcu.gpa;
29192936 const new_zir = file.zir;
29202937
......@@ -2930,7 +2947,7 @@ fn updateZirRefs(zcu: *Module, file: *File, old_zir: Zir) !void {
29302947 // iterating over this full set for every updated file.
29312948 for (zcu.intern_pool.tracked_insts.keys(), 0..) |*ti, idx_raw| {
29322949 const ti_idx: InternPool.TrackedInst.Index = @enumFromInt(idx_raw);
2933 if (!std.mem.eql(u8, &ti.path_digest, &file.path_digest)) continue;
2950 if (ti.file != file_index) continue;
29342951 const old_inst = ti.inst;
29352952 ti.inst = inst_map.get(ti.inst) orelse {
29362953 // Tracking failed for this instruction. Invalidate associated `src_hash` deps.
......@@ -3378,11 +3395,11 @@ pub fn mapOldZirToNew(
33783395}
33793396
33803397/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.
3381pub fn ensureFileAnalyzed(zcu: *Zcu, file: *File) SemaError!void {
3382 if (file.root_decl.unwrap()) |existing_root| {
3398pub fn ensureFileAnalyzed(zcu: *Zcu, file_index: File.Index) SemaError!void {
3399 if (zcu.fileRootDecl(file_index).unwrap()) |existing_root| {
33833400 return zcu.ensureDeclAnalyzed(existing_root);
33843401 } else {
3385 return zcu.semaFile(file);
3402 return zcu.semaFile(file_index);
33863403 }
33873404}
33883405
......@@ -3455,7 +3472,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl_index: Decl.Index) SemaError!void {
34553472 }
34563473
34573474 if (mod.declIsRoot(decl_index)) {
3458 const changed = try mod.semaFileUpdate(decl.getFileScope(mod), decl_was_outdated);
3475 const changed = try mod.semaFileUpdate(decl.getFileScopeIndex(mod), decl_was_outdated);
34593476 break :blk .{
34603477 .invalidate_decl_val = changed,
34613478 .invalidate_decl_ref = changed,
......@@ -3787,17 +3804,23 @@ pub fn ensureFuncBodyAnalysisQueued(mod: *Module, func_index: InternPool.Index)
37873804 func.analysis(ip).state = .queued;
37883805}
37893806
3790/// https://github.com/ziglang/zig/issues/14307
3791pub fn semaPkg(mod: *Module, pkg: *Package.Module) !void {
3792 const file = (try mod.importPkg(pkg)).file;
3793 if (file.root_decl == .none) {
3794 return mod.semaFile(file);
3807pub fn semaPkg(zcu: *Zcu, pkg: *Package.Module) !void {
3808 const import_file_result = try zcu.importPkg(pkg);
3809 const root_decl_index = zcu.fileRootDecl(import_file_result.file_index);
3810 if (root_decl_index == .none) {
3811 return zcu.semaFile(import_file_result.file_index);
37953812 }
37963813}
37973814
3798fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespace.Index, file: *File) Allocator.Error!InternPool.Index {
3815fn getFileRootStruct(
3816 zcu: *Zcu,
3817 decl_index: Decl.Index,
3818 namespace_index: Namespace.Index,
3819 file_index: File.Index,
3820) Allocator.Error!InternPool.Index {
37993821 const gpa = zcu.gpa;
38003822 const ip = &zcu.intern_pool;
3823 const file = zcu.fileByIndex(file_index);
38013824 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
38023825 assert(extended.opcode == .struct_decl);
38033826 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
......@@ -3818,7 +3841,7 @@ fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespa
38183841 const decls = file.zir.bodySlice(extra_index, decls_len);
38193842 extra_index += decls_len;
38203843
3821 const tracked_inst = try ip.trackZir(gpa, file, .main_struct_inst);
3844 const tracked_inst = try ip.trackZir(gpa, file_index, .main_struct_inst);
38223845 const wip_ty = switch (try ip.getStructType(gpa, .{
38233846 .layout = .auto,
38243847 .fields_len = fields_len,
......@@ -3863,8 +3886,9 @@ fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespa
38633886/// If `type_outdated`, the struct type itself is considered outdated and is
38643887/// reconstructed at a new InternPool index. Otherwise, the namespace is just
38653888/// re-analyzed. Returns whether the decl's tyval was invalidated.
3866fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
3867 const decl = zcu.declPtr(file.root_decl.unwrap().?);
3889fn semaFileUpdate(zcu: *Zcu, file_index: File.Index, type_outdated: bool) SemaError!bool {
3890 const file = zcu.fileByIndex(file_index);
3891 const decl = zcu.declPtr(zcu.fileRootDecl(file_index).unwrap().?);
38683892
38693893 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{
38703894 file.mod.fully_qualified_name,
......@@ -3883,7 +3907,8 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
38833907
38843908 if (decl.analysis == .file_failure) {
38853909 // No struct type currently exists. Create one!
3886 _ = try zcu.getFileRootStruct(file.root_decl.unwrap().?, decl.src_namespace, file);
3910 const root_decl = zcu.fileRootDecl(file_index);
3911 _ = try zcu.getFileRootStruct(root_decl.unwrap().?, decl.src_namespace, file_index);
38873912 return true;
38883913 }
38893914
......@@ -3892,10 +3917,13 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
38923917
38933918 if (type_outdated) {
38943919 // Invalidate the existing type, reusing the decl and namespace.
3895 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{ .decl = file.root_decl.unwrap().? }));
3920 const file_root_decl = zcu.fileRootDecl(file_index).unwrap().?;
3921 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{
3922 .decl = file_root_decl,
3923 }));
38963924 zcu.intern_pool.remove(decl.val.toIntern());
38973925 decl.val = undefined;
3898 _ = try zcu.getFileRootStruct(file.root_decl.unwrap().?, decl.src_namespace, file);
3926 _ = try zcu.getFileRootStruct(file_root_decl, decl.src_namespace, file_index);
38993927 return true;
39003928 }
39013929
......@@ -3923,35 +3951,36 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
39233951
39243952/// Regardless of the file status, will create a `Decl` if none exists so that we can track
39253953/// dependencies and re-analyze when the file becomes outdated.
3926fn semaFile(mod: *Module, file: *File) SemaError!void {
3954fn semaFile(zcu: *Zcu, file_index: File.Index) SemaError!void {
39273955 const tracy = trace(@src());
39283956 defer tracy.end();
39293957
3930 assert(file.root_decl == .none);
3958 const file = zcu.fileByIndex(file_index);
3959 assert(zcu.fileRootDecl(file_index) == .none);
39313960
3932 const gpa = mod.gpa;
3933 log.debug("semaFile mod={s} sub_file_path={s}", .{
3961 const gpa = zcu.gpa;
3962 log.debug("semaFile zcu={s} sub_file_path={s}", .{
39343963 file.mod.fully_qualified_name, file.sub_file_path,
39353964 });
39363965
39373966 // Because these three things each reference each other, `undefined`
39383967 // placeholders are used before being set after the struct type gains an
39393968 // InternPool index.
3940 const new_namespace_index = try mod.createNamespace(.{
3969 const new_namespace_index = try zcu.createNamespace(.{
39413970 .parent = .none,
39423971 .decl_index = undefined,
3943 .file_scope = file,
3972 .file_scope = file_index,
39443973 });
3945 errdefer mod.destroyNamespace(new_namespace_index);
3974 errdefer zcu.destroyNamespace(new_namespace_index);
39463975
3947 const new_decl_index = try mod.allocateNewDecl(new_namespace_index);
3948 const new_decl = mod.declPtr(new_decl_index);
3976 const new_decl_index = try zcu.allocateNewDecl(new_namespace_index);
3977 const new_decl = zcu.declPtr(new_decl_index);
39493978 errdefer @panic("TODO error handling");
39503979
3951 file.root_decl = new_decl_index.toOptional();
3952 mod.namespacePtr(new_namespace_index).decl_index = new_decl_index;
3980 zcu.setFileRootDecl(file_index, new_decl_index.toOptional());
3981 zcu.namespacePtr(new_namespace_index).decl_index = new_decl_index;
39533982
3954 new_decl.name = try file.fullyQualifiedName(mod);
3983 new_decl.name = try file.fullyQualifiedName(zcu);
39553984 new_decl.name_fully_qualified = true;
39563985 new_decl.is_pub = true;
39573986 new_decl.is_exported = false;
......@@ -3965,13 +3994,13 @@ fn semaFile(mod: *Module, file: *File) SemaError!void {
39653994 }
39663995 assert(file.zir_loaded);
39673996
3968 const struct_ty = try mod.getFileRootStruct(new_decl_index, new_namespace_index, file);
3969 errdefer mod.intern_pool.remove(struct_ty);
3997 const struct_ty = try zcu.getFileRootStruct(new_decl_index, new_namespace_index, file_index);
3998 errdefer zcu.intern_pool.remove(struct_ty);
39703999
3971 switch (mod.comp.cache_use) {
4000 switch (zcu.comp.cache_use) {
39724001 .whole => |whole| if (whole.cache_manifest) |man| {
39734002 const source = file.getSource(gpa) catch |err| {
3974 try reportRetryableFileError(mod, file, "unable to load source: {s}", .{@errorName(err)});
4003 try reportRetryableFileError(zcu, file_index, "unable to load source: {s}", .{@errorName(err)});
39754004 return error.AnalysisFail;
39764005 };
39774006
......@@ -3980,7 +4009,7 @@ fn semaFile(mod: *Module, file: *File) SemaError!void {
39804009 file.mod.root.sub_path,
39814010 file.sub_file_path,
39824011 }) catch |err| {
3983 try reportRetryableFileError(mod, file, "unable to resolve path: {s}", .{@errorName(err)});
4012 try reportRetryableFileError(zcu, file_index, "unable to resolve path: {s}", .{@errorName(err)});
39844013 return error.AnalysisFail;
39854014 };
39864015 errdefer gpa.free(resolved_path);
......@@ -4000,57 +4029,58 @@ const SemaDeclResult = packed struct {
40004029 invalidate_decl_ref: bool,
40014030};
40024031
4003fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4032fn semaDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
40044033 const tracy = trace(@src());
40054034 defer tracy.end();
40064035
4007 const decl = mod.declPtr(decl_index);
4008 const ip = &mod.intern_pool;
4036 const decl = zcu.declPtr(decl_index);
4037 const ip = &zcu.intern_pool;
40094038
4010 if (decl.getFileScope(mod).status != .success_zir) {
4039 if (decl.getFileScope(zcu).status != .success_zir) {
40114040 return error.AnalysisFail;
40124041 }
40134042
4014 assert(!mod.declIsRoot(decl_index));
4043 assert(!zcu.declIsRoot(decl_index));
40154044
40164045 if (decl.zir_decl_index == .none and decl.owns_tv) {
40174046 // We are re-analyzing an anonymous owner Decl (for a function or a namespace type).
4018 return mod.semaAnonOwnerDecl(decl_index);
4047 return zcu.semaAnonOwnerDecl(decl_index);
40194048 }
40204049
40214050 log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});
4022 log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
4051 log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(zcu)).fmt(ip)});
40234052 defer blk: {
4024 log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
4053 log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(zcu) catch break :blk).fmt(ip)});
40254054 }
40264055
40274056 const old_has_tv = decl.has_tv;
40284057 // The following values are ignored if `!old_has_tv`
4029 const old_ty = if (old_has_tv) decl.typeOf(mod) else undefined;
4058 const old_ty = if (old_has_tv) decl.typeOf(zcu) else undefined;
40304059 const old_val = decl.val;
40314060 const old_align = decl.alignment;
40324061 const old_linksection = decl.@"linksection";
40334062 const old_addrspace = decl.@"addrspace";
4034 const old_is_inline = if (decl.getOwnedFunction(mod)) |prev_func|
4063 const old_is_inline = if (decl.getOwnedFunction(zcu)) |prev_func|
40354064 prev_func.analysis(ip).state == .inline_only
40364065 else
40374066 false;
40384067
40394068 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);
40404069
4041 const gpa = mod.gpa;
4042 const zir = decl.getFileScope(mod).zir;
4070 const gpa = zcu.gpa;
4071 const zir = decl.getFileScope(zcu).zir;
40434072
40444073 const builtin_type_target_index: InternPool.Index = ip_index: {
4045 const std_mod = mod.std_mod;
4046 if (decl.getFileScope(mod).mod != std_mod) break :ip_index .none;
4074 const std_mod = zcu.std_mod;
4075 if (decl.getFileScope(zcu).mod != std_mod) break :ip_index .none;
40474076 // We're in the std module.
4048 const std_file = (try mod.importPkg(std_mod)).file;
4049 const std_decl = mod.declPtr(std_file.root_decl.unwrap().?);
4050 const std_namespace = std_decl.getInnerNamespace(mod).?;
4077 const std_file_imported = try zcu.importPkg(std_mod);
4078 const std_file_root_decl_index = zcu.fileRootDecl(std_file_imported.file_index);
4079 const std_decl = zcu.declPtr(std_file_root_decl_index.unwrap().?);
4080 const std_namespace = std_decl.getInnerNamespace(zcu).?;
40514081 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
4052 const builtin_decl = mod.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, DeclAdapter{ .zcu = mod }) orelse break :ip_index .none);
4053 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(mod).unwrap() orelse break :ip_index .none;
4082 const builtin_decl = zcu.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, DeclAdapter{ .zcu = zcu }) orelse break :ip_index .none);
4083 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(zcu).unwrap() orelse break :ip_index .none;
40544084 if (decl.src_namespace != builtin_namespace) break :ip_index .none;
40554085 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.
40564086 for ([_][]const u8{
......@@ -4083,7 +4113,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
40834113 break :ip_index .none;
40844114 };
40854115
4086 mod.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .decl = decl_index }));
4116 zcu.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .decl = decl_index }));
40874117
40884118 decl.analysis = .in_progress;
40894119
......@@ -4094,7 +4124,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
40944124 defer comptime_err_ret_trace.deinit();
40954125
40964126 var sema: Sema = .{
4097 .mod = mod,
4127 .mod = zcu,
40984128 .gpa = gpa,
40994129 .arena = analysis_arena.allocator(),
41004130 .code = zir,
......@@ -4112,8 +4142,8 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
41124142
41134143 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.
41144144 try sema.declareDependency(.{ .src_hash = try ip.trackZir(
4115 sema.gpa,
4116 decl.getFileScope(mod),
4145 gpa,
4146 decl.getFileScopeIndex(zcu),
41174147 decl_inst,
41184148 ) });
41194149
......@@ -4129,7 +4159,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
41294159 };
41304160 defer block_scope.instructions.deinit(gpa);
41314161
4132 const decl_bodies = decl.zirBodies(mod);
4162 const decl_bodies = decl.zirBodies(zcu);
41334163
41344164 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);
41354165 // We'll do some other bits with the Sema. Clear the type target index just
......@@ -4141,22 +4171,22 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
41414171 const ty_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_ty = 0 });
41424172 const init_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_init = 0 });
41434173 const decl_val = try sema.resolveFinalDeclValue(&block_scope, init_src, result_ref);
4144 const decl_ty = decl_val.typeOf(mod);
4174 const decl_ty = decl_val.typeOf(zcu);
41454175
41464176 // Note this resolves the type of the Decl, not the value; if this Decl
41474177 // is a struct, for example, this resolves `type` (which needs no resolution),
41484178 // not the struct itself.
4149 try decl_ty.resolveLayout(mod);
4179 try decl_ty.resolveLayout(zcu);
41504180
41514181 if (decl.kind == .@"usingnamespace") {
4152 if (!decl_ty.eql(Type.type, mod)) {
4182 if (!decl_ty.eql(Type.type, zcu)) {
41534183 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{
4154 decl_ty.fmt(mod),
4184 decl_ty.fmt(zcu),
41554185 });
41564186 }
41574187 const ty = decl_val.toType();
4158 if (ty.getNamespace(mod) == null) {
4159 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(mod)});
4188 if (ty.getNamespace(zcu) == null) {
4189 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(zcu)});
41604190 }
41614191
41624192 decl.val = ty.toValue();
......@@ -4194,7 +4224,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
41944224 .func => |func| {
41954225 decl.owns_tv = func.owner_decl == decl_index;
41964226 queue_linker_work = false;
4197 is_inline = decl.owns_tv and decl_ty.fnCallingConvention(mod) == .Inline;
4227 is_inline = decl.owns_tv and decl_ty.fnCallingConvention(zcu) == .Inline;
41984228 is_func = decl.owns_tv;
41994229 },
42004230
......@@ -4246,10 +4276,10 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
42464276 decl.analysis = .complete;
42474277
42484278 const result: SemaDeclResult = if (old_has_tv) .{
4249 .invalidate_decl_val = !decl_ty.eql(old_ty, mod) or
4250 !decl.val.eql(old_val, decl_ty, mod) or
4279 .invalidate_decl_val = !decl_ty.eql(old_ty, zcu) or
4280 !decl.val.eql(old_val, decl_ty, zcu) or
42514281 is_inline != old_is_inline,
4252 .invalidate_decl_ref = !decl_ty.eql(old_ty, mod) or
4282 .invalidate_decl_ref = !decl_ty.eql(old_ty, zcu) or
42534283 decl.alignment != old_align or
42544284 decl.@"linksection" != old_linksection or
42554285 decl.@"addrspace" != old_addrspace or
......@@ -4263,12 +4293,12 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
42634293 if (has_runtime_bits) {
42644294 // Needed for codegen_decl which will call updateDecl and then the
42654295 // codegen backend wants full access to the Decl Type.
4266 try decl_ty.resolveFully(mod);
4296 try decl_ty.resolveFully(zcu);
42674297
4268 try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
4298 try zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
42694299
4270 if (result.invalidate_decl_ref and mod.emit_h != null) {
4271 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
4300 if (result.invalidate_decl_ref and zcu.emit_h != null) {
4301 try zcu.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
42724302 }
42734303 }
42744304
......@@ -4322,6 +4352,7 @@ fn semaAnonOwnerDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
43224352
43234353pub const ImportFileResult = struct {
43244354 file: *File,
4355 file_index: File.Index,
43254356 is_new: bool,
43264357 is_pkg: bool,
43274358};
......@@ -4344,20 +4375,27 @@ pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
43444375 errdefer _ = zcu.import_table.pop();
43454376 if (gop.found_existing) {
43464377 try gop.value_ptr.*.addReference(zcu.*, .{ .root = mod });
4347 return ImportFileResult{
4378 return .{
43484379 .file = gop.value_ptr.*,
4380 .file_index = @enumFromInt(gop.index),
43494381 .is_new = false,
43504382 .is_pkg = true,
43514383 };
43524384 }
43534385
4386 const ip = &zcu.intern_pool;
4387
4388 try ip.files.ensureUnusedCapacity(gpa, 1);
4389
43544390 if (mod.builtin_file) |builtin_file| {
43554391 keep_resolved_path = true; // It's now owned by import_table.
43564392 gop.value_ptr.* = builtin_file;
43574393 try builtin_file.addReference(zcu.*, .{ .root = mod });
4358 try zcu.path_digest_map.put(gpa, builtin_file.path_digest, {});
4394 const path_digest = computePathDigest(zcu, mod, builtin_file.sub_file_path);
4395 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
43594396 return .{
43604397 .file = builtin_file,
4398 .file_index = @enumFromInt(ip.files.entries.len - 1),
43614399 .is_new = false,
43624400 .is_pkg = true,
43634401 };
......@@ -4382,43 +4420,36 @@ pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
43824420 .zir = undefined,
43834421 .status = .never_loaded,
43844422 .mod = mod,
4385 .root_decl = .none,
4386 .path_digest = digest: {
4387 const want_local_cache = mod == zcu.main_mod;
4388 var path_hash: Cache.HashHelper = .{};
4389 path_hash.addBytes(build_options.version);
4390 path_hash.add(builtin.zig_backend);
4391 if (!want_local_cache) {
4392 path_hash.addOptionalBytes(mod.root.root_dir.path);
4393 path_hash.addBytes(mod.root.sub_path);
4394 }
4395 path_hash.addBytes(sub_file_path);
4396 var bin: Cache.BinDigest = undefined;
4397 path_hash.hasher.final(&bin);
4398 break :digest bin;
4399 },
44004423 };
4424
4425 const path_digest = computePathDigest(zcu, mod, sub_file_path);
4426
44014427 try new_file.addReference(zcu.*, .{ .root = mod });
4402 try zcu.path_digest_map.put(gpa, new_file.path_digest, {});
4403 return ImportFileResult{
4428 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
4429 return .{
44044430 .file = new_file,
4431 .file_index = @enumFromInt(ip.files.entries.len - 1),
44054432 .is_new = true,
44064433 .is_pkg = true,
44074434 };
44084435}
44094436
4437/// Called from a worker thread during AstGen.
4438/// Also called from Sema during semantic analysis.
44104439pub fn importFile(
44114440 zcu: *Zcu,
44124441 cur_file: *File,
44134442 import_string: []const u8,
44144443) !ImportFileResult {
4444 const mod = cur_file.mod;
4445
44154446 if (std.mem.eql(u8, import_string, "std")) {
44164447 return zcu.importPkg(zcu.std_mod);
44174448 }
44184449 if (std.mem.eql(u8, import_string, "root")) {
44194450 return zcu.importPkg(zcu.root_mod);
44204451 }
4421 if (cur_file.mod.deps.get(import_string)) |pkg| {
4452 if (mod.deps.get(import_string)) |pkg| {
44224453 return zcu.importPkg(pkg);
44234454 }
44244455 if (!mem.endsWith(u8, import_string, ".zig")) {
......@@ -4430,8 +4461,8 @@ pub fn importFile(
44304461 // an import refers to the same as another, despite different relative paths
44314462 // or differently mapped package names.
44324463 const resolved_path = try std.fs.path.resolve(gpa, &.{
4433 cur_file.mod.root.root_dir.path orelse ".",
4434 cur_file.mod.root.sub_path,
4464 mod.root.root_dir.path orelse ".",
4465 mod.root.sub_path,
44354466 cur_file.sub_file_path,
44364467 "..",
44374468 import_string,
......@@ -4442,18 +4473,23 @@ pub fn importFile(
44424473
44434474 const gop = try zcu.import_table.getOrPut(gpa, resolved_path);
44444475 errdefer _ = zcu.import_table.pop();
4445 if (gop.found_existing) return ImportFileResult{
4476 if (gop.found_existing) return .{
44464477 .file = gop.value_ptr.*,
4478 .file_index = @enumFromInt(gop.index),
44474479 .is_new = false,
44484480 .is_pkg = false,
44494481 };
44504482
4483 const ip = &zcu.intern_pool;
4484
4485 try ip.files.ensureUnusedCapacity(gpa, 1);
4486
44514487 const new_file = try gpa.create(File);
44524488 errdefer gpa.destroy(new_file);
44534489
44544490 const resolved_root_path = try std.fs.path.resolve(gpa, &.{
4455 cur_file.mod.root.root_dir.path orelse ".",
4456 cur_file.mod.root.sub_path,
4491 mod.root.root_dir.path orelse ".",
4492 mod.root.sub_path,
44574493 });
44584494 defer gpa.free(resolved_root_path);
44594495
......@@ -4484,26 +4520,14 @@ pub fn importFile(
44844520 .tree = undefined,
44854521 .zir = undefined,
44864522 .status = .never_loaded,
4487 .mod = cur_file.mod,
4488 .root_decl = .none,
4489 .path_digest = digest: {
4490 const want_local_cache = cur_file.mod == zcu.main_mod;
4491 var path_hash: Cache.HashHelper = .{};
4492 path_hash.addBytes(build_options.version);
4493 path_hash.add(builtin.zig_backend);
4494 if (!want_local_cache) {
4495 path_hash.addOptionalBytes(cur_file.mod.root.root_dir.path);
4496 path_hash.addBytes(cur_file.mod.root.sub_path);
4497 }
4498 path_hash.addBytes(sub_file_path);
4499 var bin: Cache.BinDigest = undefined;
4500 path_hash.hasher.final(&bin);
4501 break :digest bin;
4502 },
4523 .mod = mod,
45034524 };
4504 try zcu.path_digest_map.put(gpa, new_file.path_digest, {});
4505 return ImportFileResult{
4525
4526 const path_digest = computePathDigest(zcu, mod, sub_file_path);
4527 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
4528 return .{
45064529 .file = new_file,
4530 .file_index = @enumFromInt(ip.files.entries.len - 1),
45074531 .is_new = true,
45084532 .is_pkg = false,
45094533 };
......@@ -4581,6 +4605,21 @@ pub fn embedFile(
45814605 return newEmbedFile(mod, cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);
45824606}
45834607
4608fn computePathDigest(zcu: *Zcu, mod: *Package.Module, sub_file_path: []const u8) Cache.BinDigest {
4609 const want_local_cache = mod == zcu.main_mod;
4610 var path_hash: Cache.HashHelper = .{};
4611 path_hash.addBytes(build_options.version);
4612 path_hash.add(builtin.zig_backend);
4613 if (!want_local_cache) {
4614 path_hash.addOptionalBytes(mod.root.root_dir.path);
4615 path_hash.addBytes(mod.root.sub_path);
4616 }
4617 path_hash.addBytes(sub_file_path);
4618 var bin: Cache.BinDigest = undefined;
4619 path_hash.hasher.final(&bin);
4620 return bin;
4621}
4622
45844623/// https://github.com/ziglang/zig/issues/14307
45854624fn newEmbedFile(
45864625 mod: *Module,
......@@ -4765,7 +4804,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
47654804 const namespace_index = iter.namespace_index;
47664805 const namespace = zcu.namespacePtr(namespace_index);
47674806 const gpa = zcu.gpa;
4768 const zir = namespace.file_scope.zir;
4807 const zir = namespace.fileScope(zcu).zir;
47694808 const ip = &zcu.intern_pool;
47704809
47714810 const inst_data = zir.instructions.items(.data)[@intFromEnum(decl_inst)].declaration;
......@@ -4848,7 +4887,8 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
48484887 else => {},
48494888 }
48504889
4851 const tracked_inst = try ip.trackZir(gpa, iter.parent_decl.getFileScope(zcu), decl_inst);
4890 const parent_file_scope_index = iter.parent_decl.getFileScopeIndex(zcu);
4891 const tracked_inst = try ip.trackZir(gpa, parent_file_scope_index, decl_inst);
48524892
48534893 // We create a Decl for it regardless of analysis status.
48544894
......@@ -4878,7 +4918,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
48784918 namespace.decls.putAssumeCapacityNoClobberContext(decl_index, {}, .{ .zcu = zcu });
48794919
48804920 const comp = zcu.comp;
4881 const decl_mod = namespace.file_scope.mod;
4921 const decl_mod = namespace.fileScope(zcu).mod;
48824922 const want_analysis = declaration.flags.is_export or switch (kind) {
48834923 .anon => unreachable,
48844924 .@"comptime" => true,
......@@ -4908,7 +4948,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
49084948 // re-analysis for us if necessary.
49094949 if (prev_exported != declaration.flags.is_export or decl.analysis == .unreferenced) {
49104950 log.debug("scanDecl queue analyze_decl file='{s}' decl_name='{}' decl_index={d}", .{
4911 namespace.file_scope.sub_file_path, decl_name.fmt(ip), decl_index,
4951 namespace.fileScope(zcu).sub_file_path, decl_name.fmt(ip), decl_index,
49124952 });
49134953 comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = decl_index });
49144954 }
......@@ -5512,77 +5552,78 @@ fn handleUpdateExports(
55125552}
55135553
55145554pub fn populateTestFunctions(
5515 mod: *Module,
5555 zcu: *Zcu,
55165556 main_progress_node: std.Progress.Node,
55175557) !void {
5518 const gpa = mod.gpa;
5519 const ip = &mod.intern_pool;
5520 const builtin_mod = mod.root_mod.getBuiltinDependency();
5521 const builtin_file = (mod.importPkg(builtin_mod) catch unreachable).file;
5522 const root_decl = mod.declPtr(builtin_file.root_decl.unwrap().?);
5523 const builtin_namespace = mod.namespacePtr(root_decl.src_namespace);
5558 const gpa = zcu.gpa;
5559 const ip = &zcu.intern_pool;
5560 const builtin_mod = zcu.root_mod.getBuiltinDependency();
5561 const builtin_file_index = (zcu.importPkg(builtin_mod) catch unreachable).file_index;
5562 const root_decl_index = zcu.fileRootDecl(builtin_file_index);
5563 const root_decl = zcu.declPtr(root_decl_index.unwrap().?);
5564 const builtin_namespace = zcu.namespacePtr(root_decl.src_namespace);
55245565 const test_functions_str = try ip.getOrPutString(gpa, "test_functions", .no_embedded_nulls);
55255566 const decl_index = builtin_namespace.decls.getKeyAdapted(
55265567 test_functions_str,
5527 DeclAdapter{ .zcu = mod },
5568 DeclAdapter{ .zcu = zcu },
55285569 ).?;
55295570 {
55305571 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`
55315572 // was not referenced by start code.
5532 mod.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
5573 zcu.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
55335574 defer {
5534 mod.sema_prog_node.end();
5535 mod.sema_prog_node = undefined;
5575 zcu.sema_prog_node.end();
5576 zcu.sema_prog_node = undefined;
55365577 }
5537 try mod.ensureDeclAnalyzed(decl_index);
5578 try zcu.ensureDeclAnalyzed(decl_index);
55385579 }
55395580
5540 const decl = mod.declPtr(decl_index);
5541 const test_fn_ty = decl.typeOf(mod).slicePtrFieldType(mod).childType(mod);
5581 const decl = zcu.declPtr(decl_index);
5582 const test_fn_ty = decl.typeOf(zcu).slicePtrFieldType(zcu).childType(zcu);
55425583
55435584 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
5544 // Add mod.test_functions to an array decl then make the test_functions
5585 // Add zcu.test_functions to an array decl then make the test_functions
55455586 // decl reference it as a slice.
5546 const test_fn_vals = try gpa.alloc(InternPool.Index, mod.test_functions.count());
5587 const test_fn_vals = try gpa.alloc(InternPool.Index, zcu.test_functions.count());
55475588 defer gpa.free(test_fn_vals);
55485589
5549 for (test_fn_vals, mod.test_functions.keys()) |*test_fn_val, test_decl_index| {
5550 const test_decl = mod.declPtr(test_decl_index);
5551 const test_decl_name = try test_decl.fullyQualifiedName(mod);
5590 for (test_fn_vals, zcu.test_functions.keys()) |*test_fn_val, test_decl_index| {
5591 const test_decl = zcu.declPtr(test_decl_index);
5592 const test_decl_name = try test_decl.fullyQualifiedName(zcu);
55525593 const test_decl_name_len = test_decl_name.length(ip);
55535594 const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
5554 const test_name_ty = try mod.arrayType(.{
5595 const test_name_ty = try zcu.arrayType(.{
55555596 .len = test_decl_name_len,
55565597 .child = .u8_type,
55575598 });
5558 const test_name_val = try mod.intern(.{ .aggregate = .{
5599 const test_name_val = try zcu.intern(.{ .aggregate = .{
55595600 .ty = test_name_ty.toIntern(),
55605601 .storage = .{ .bytes = test_decl_name.toString() },
55615602 } });
55625603 break :n .{
5563 .orig_ty = (try mod.singleConstPtrType(test_name_ty)).toIntern(),
5604 .orig_ty = (try zcu.singleConstPtrType(test_name_ty)).toIntern(),
55645605 .val = test_name_val,
55655606 };
55665607 };
55675608
55685609 const test_fn_fields = .{
55695610 // name
5570 try mod.intern(.{ .slice = .{
5611 try zcu.intern(.{ .slice = .{
55715612 .ty = .slice_const_u8_type,
5572 .ptr = try mod.intern(.{ .ptr = .{
5613 .ptr = try zcu.intern(.{ .ptr = .{
55735614 .ty = .manyptr_const_u8_type,
55745615 .base_addr = .{ .anon_decl = test_name_anon_decl },
55755616 .byte_offset = 0,
55765617 } }),
5577 .len = try mod.intern(.{ .int = .{
5618 .len = try zcu.intern(.{ .int = .{
55785619 .ty = .usize_type,
55795620 .storage = .{ .u64 = test_decl_name_len },
55805621 } }),
55815622 } }),
55825623 // func
5583 try mod.intern(.{ .ptr = .{
5584 .ty = try mod.intern(.{ .ptr_type = .{
5585 .child = test_decl.typeOf(mod).toIntern(),
5624 try zcu.intern(.{ .ptr = .{
5625 .ty = try zcu.intern(.{ .ptr_type = .{
5626 .child = test_decl.typeOf(zcu).toIntern(),
55865627 .flags = .{
55875628 .is_const = true,
55885629 },
......@@ -5591,29 +5632,29 @@ pub fn populateTestFunctions(
55915632 .byte_offset = 0,
55925633 } }),
55935634 };
5594 test_fn_val.* = try mod.intern(.{ .aggregate = .{
5635 test_fn_val.* = try zcu.intern(.{ .aggregate = .{
55955636 .ty = test_fn_ty.toIntern(),
55965637 .storage = .{ .elems = &test_fn_fields },
55975638 } });
55985639 }
55995640
5600 const array_ty = try mod.arrayType(.{
5641 const array_ty = try zcu.arrayType(.{
56015642 .len = test_fn_vals.len,
56025643 .child = test_fn_ty.toIntern(),
56035644 .sentinel = .none,
56045645 });
5605 const array_val = try mod.intern(.{ .aggregate = .{
5646 const array_val = try zcu.intern(.{ .aggregate = .{
56065647 .ty = array_ty.toIntern(),
56075648 .storage = .{ .elems = test_fn_vals },
56085649 } });
56095650 break :array .{
5610 .orig_ty = (try mod.singleConstPtrType(array_ty)).toIntern(),
5651 .orig_ty = (try zcu.singleConstPtrType(array_ty)).toIntern(),
56115652 .val = array_val,
56125653 };
56135654 };
56145655
56155656 {
5616 const new_ty = try mod.ptrType(.{
5657 const new_ty = try zcu.ptrType(.{
56175658 .child = test_fn_ty.toIntern(),
56185659 .flags = .{
56195660 .is_const = true,
......@@ -5621,14 +5662,14 @@ pub fn populateTestFunctions(
56215662 },
56225663 });
56235664 const new_val = decl.val;
5624 const new_init = try mod.intern(.{ .slice = .{
5665 const new_init = try zcu.intern(.{ .slice = .{
56255666 .ty = new_ty.toIntern(),
5626 .ptr = try mod.intern(.{ .ptr = .{
5627 .ty = new_ty.slicePtrFieldType(mod).toIntern(),
5667 .ptr = try zcu.intern(.{ .ptr = .{
5668 .ty = new_ty.slicePtrFieldType(zcu).toIntern(),
56285669 .base_addr = .{ .anon_decl = array_anon_decl },
56295670 .byte_offset = 0,
56305671 } }),
5631 .len = (try mod.intValue(Type.usize, mod.test_functions.count())).toIntern(),
5672 .len = (try zcu.intValue(Type.usize, zcu.test_functions.count())).toIntern(),
56325673 } });
56335674 ip.mutateVarInit(decl.val.toIntern(), new_init);
56345675
......@@ -5638,13 +5679,13 @@ pub fn populateTestFunctions(
56385679 decl.has_tv = true;
56395680 }
56405681 {
5641 mod.codegen_prog_node = main_progress_node.start("Code Generation", 0);
5682 zcu.codegen_prog_node = main_progress_node.start("Code Generation", 0);
56425683 defer {
5643 mod.codegen_prog_node.end();
5644 mod.codegen_prog_node = undefined;
5684 zcu.codegen_prog_node.end();
5685 zcu.codegen_prog_node = undefined;
56455686 }
56465687
5647 try mod.linkerUpdateDecl(decl_index);
5688 try zcu.linkerUpdateDecl(decl_index);
56485689 }
56495690}
56505691
......@@ -5684,31 +5725,35 @@ pub fn linkerUpdateDecl(zcu: *Zcu, decl_index: Decl.Index) !void {
56845725}
56855726
56865727fn reportRetryableFileError(
5687 mod: *Module,
5688 file: *File,
5728 zcu: *Zcu,
5729 file_index: File.Index,
56895730 comptime format: []const u8,
56905731 args: anytype,
56915732) error{OutOfMemory}!void {
5733 const gpa = zcu.gpa;
5734 const ip = &zcu.intern_pool;
5735
5736 const file = zcu.fileByIndex(file_index);
56925737 file.status = .retryable_failure;
56935738
56945739 const err_msg = try ErrorMsg.create(
5695 mod.gpa,
5740 gpa,
56965741 .{
5697 .base_node_inst = try mod.intern_pool.trackZir(mod.gpa, file, .main_struct_inst),
5742 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
56985743 .offset = .entire_file,
56995744 },
57005745 format,
57015746 args,
57025747 );
5703 errdefer err_msg.destroy(mod.gpa);
5748 errdefer err_msg.destroy(gpa);
57045749
5705 mod.comp.mutex.lock();
5706 defer mod.comp.mutex.unlock();
5750 zcu.comp.mutex.lock();
5751 defer zcu.comp.mutex.unlock();
57075752
5708 const gop = try mod.failed_files.getOrPut(mod.gpa, file);
5753 const gop = try zcu.failed_files.getOrPut(gpa, file);
57095754 if (gop.found_existing) {
57105755 if (gop.value_ptr.*) |old_err_msg| {
5711 old_err_msg.destroy(mod.gpa);
5756 old_err_msg.destroy(gpa);
57125757 }
57135758 }
57145759 gop.value_ptr.* = err_msg;
......@@ -6528,8 +6573,9 @@ pub fn getBuiltin(zcu: *Zcu, name: []const u8) Allocator.Error!Air.Inst.Ref {
65286573pub fn getBuiltinDecl(zcu: *Zcu, name: []const u8) Allocator.Error!InternPool.DeclIndex {
65296574 const gpa = zcu.gpa;
65306575 const ip = &zcu.intern_pool;
6531 const std_file = (zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig")).file;
6532 const std_namespace = zcu.declPtr(std_file.root_decl.unwrap().?).getOwnedInnerNamespace(zcu).?;
6576 const std_file_imported = zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig");
6577 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index).unwrap().?;
6578 const std_namespace = zcu.declPtr(std_file_root_decl).getOwnedInnerNamespace(zcu).?;
65336579 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
65346580 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
65356581 zcu.ensureDeclAnalyzed(builtin_decl) catch @panic("std.builtin is corrupt");
......@@ -6544,3 +6590,23 @@ pub fn getBuiltinType(zcu: *Zcu, name: []const u8) Allocator.Error!Type {
65446590 ty.resolveFully(zcu) catch @panic("std.builtin is corrupt");
65456591 return ty;
65466592}
6593
6594pub fn fileByIndex(zcu: *const Zcu, i: File.Index) *File {
6595 return zcu.import_table.values()[@intFromEnum(i)];
6596}
6597
6598/// Returns the `Decl` of the struct that represents this `File`.
6599pub fn fileRootDecl(zcu: *const Zcu, i: File.Index) Decl.OptionalIndex {
6600 const ip = &zcu.intern_pool;
6601 return ip.files.values()[@intFromEnum(i)];
6602}
6603
6604pub fn setFileRootDecl(zcu: *Zcu, i: File.Index, root_decl: Decl.OptionalIndex) void {
6605 const ip = &zcu.intern_pool;
6606 ip.files.values()[@intFromEnum(i)] = root_decl;
6607}
6608
6609pub fn filePathDigest(zcu: *const Zcu, i: File.Index) Cache.BinDigest {
6610 const ip = &zcu.intern_pool;
6611 return ip.files.keys()[@intFromEnum(i)];
6612}
src/arch/aarch64/CodeGen.zig+1-1
......@@ -345,7 +345,7 @@ pub fn generate(
345345 assert(fn_owner_decl.has_tv);
346346 const fn_type = fn_owner_decl.typeOf(zcu);
347347 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
348 const target = &namespace.file_scope.mod.resolved_target.result;
348 const target = &namespace.fileScope(zcu).mod.resolved_target.result;
349349
350350 var branch_stack = std.ArrayList(Branch).init(gpa);
351351 defer {
src/arch/arm/CodeGen.zig+1-1
......@@ -352,7 +352,7 @@ pub fn generate(
352352 assert(fn_owner_decl.has_tv);
353353 const fn_type = fn_owner_decl.typeOf(zcu);
354354 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
355 const target = &namespace.file_scope.mod.resolved_target.result;
355 const target = &namespace.fileScope(zcu).mod.resolved_target.result;
356356
357357 var branch_stack = std.ArrayList(Branch).init(gpa);
358358 defer {
src/arch/riscv64/CodeGen.zig+2-2
......@@ -712,8 +712,8 @@ pub fn generate(
712712 assert(fn_owner_decl.has_tv);
713713 const fn_type = fn_owner_decl.typeOf(zcu);
714714 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
715 const target = &namespace.file_scope.mod.resolved_target.result;
716 const mod = namespace.file_scope.mod;
715 const target = &namespace.fileScope(zcu).mod.resolved_target.result;
716 const mod = namespace.fileScope(zcu).mod;
717717
718718 var branch_stack = std.ArrayList(Branch).init(gpa);
719719 defer {
src/arch/sparc64/CodeGen.zig+1-1
......@@ -277,7 +277,7 @@ pub fn generate(
277277 assert(fn_owner_decl.has_tv);
278278 const fn_type = fn_owner_decl.typeOf(zcu);
279279 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
280 const target = &namespace.file_scope.mod.resolved_target.result;
280 const target = &namespace.fileScope(zcu).mod.resolved_target.result;
281281
282282 var branch_stack = std.ArrayList(Branch).init(gpa);
283283 defer {
src/arch/wasm/CodeGen.zig+6-6
......@@ -1212,11 +1212,11 @@ pub fn generate(
12121212 _ = src_loc;
12131213 const comp = bin_file.comp;
12141214 const gpa = comp.gpa;
1215 const mod = comp.module.?;
1216 const func = mod.funcInfo(func_index);
1217 const decl = mod.declPtr(func.owner_decl);
1218 const namespace = mod.namespacePtr(decl.src_namespace);
1219 const target = namespace.file_scope.mod.resolved_target.result;
1215 const zcu = comp.module.?;
1216 const func = zcu.funcInfo(func_index);
1217 const decl = zcu.declPtr(func.owner_decl);
1218 const namespace = zcu.namespacePtr(decl.src_namespace);
1219 const target = namespace.fileScope(zcu).mod.resolved_target.result;
12201220 var code_gen: CodeGen = .{
12211221 .gpa = gpa,
12221222 .air = air,
......@@ -7706,7 +7706,7 @@ fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77067706 // for a single-threaded build, can we emit the `fence` instruction.
77077707 // In all other cases, we emit no instructions for a fence.
77087708 const func_namespace = zcu.namespacePtr(func.decl.src_namespace);
7709 const single_threaded = func_namespace.file_scope.mod.single_threaded;
7709 const single_threaded = func_namespace.fileScope(zcu).mod.single_threaded;
77107710 if (func.useAtomicFeature() and !single_threaded) {
77117711 try func.addAtomicTag(.atomic_fence);
77127712 }
src/arch/x86_64/CodeGen.zig+1-1
......@@ -810,7 +810,7 @@ pub fn generate(
810810 assert(fn_owner_decl.has_tv);
811811 const fn_type = fn_owner_decl.typeOf(zcu);
812812 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
813 const mod = namespace.file_scope.mod;
813 const mod = namespace.fileScope(zcu).mod;
814814
815815 var function = Self{
816816 .gpa = gpa,
src/codegen.zig+6-6
......@@ -58,7 +58,7 @@ pub fn generateFunction(
5858 const func = zcu.funcInfo(func_index);
5959 const decl = zcu.declPtr(func.owner_decl);
6060 const namespace = zcu.namespacePtr(decl.src_namespace);
61 const target = namespace.file_scope.mod.resolved_target.result;
61 const target = namespace.fileScope(zcu).mod.resolved_target.result;
6262 switch (target.cpu.arch) {
6363 .arm,
6464 .armeb,
......@@ -88,7 +88,7 @@ pub fn generateLazyFunction(
8888 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
8989 const decl = zcu.declPtr(decl_index);
9090 const namespace = zcu.namespacePtr(decl.src_namespace);
91 const target = namespace.file_scope.mod.resolved_target.result;
91 const target = namespace.fileScope(zcu).mod.resolved_target.result;
9292 switch (target.cpu.arch) {
9393 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, src_loc, lazy_sym, code, debug_output),
9494 else => unreachable,
......@@ -742,7 +742,7 @@ fn lowerDeclRef(
742742 const zcu = lf.comp.module.?;
743743 const decl = zcu.declPtr(decl_index);
744744 const namespace = zcu.namespacePtr(decl.src_namespace);
745 const target = namespace.file_scope.mod.resolved_target.result;
745 const target = namespace.fileScope(zcu).mod.resolved_target.result;
746746
747747 const ptr_width = target.ptrBitWidth();
748748 const is_fn_body = decl.typeOf(zcu).zigTypeTag(zcu) == .Fn;
......@@ -836,7 +836,7 @@ fn genDeclRef(
836836
837837 const ptr_decl = zcu.declPtr(ptr_decl_index);
838838 const namespace = zcu.namespacePtr(ptr_decl.src_namespace);
839 const target = namespace.file_scope.mod.resolved_target.result;
839 const target = namespace.fileScope(zcu).mod.resolved_target.result;
840840
841841 const ptr_bits = target.ptrBitWidth();
842842 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
......@@ -875,7 +875,7 @@ fn genDeclRef(
875875 }
876876
877877 const decl_namespace = zcu.namespacePtr(decl.src_namespace);
878 const single_threaded = decl_namespace.file_scope.mod.single_threaded;
878 const single_threaded = decl_namespace.fileScope(zcu).mod.single_threaded;
879879 const is_threadlocal = val.isPtrToThreadLocal(zcu) and !single_threaded;
880880 const is_extern = decl.isExtern(zcu);
881881
......@@ -985,7 +985,7 @@ pub fn genTypedValue(
985985
986986 const owner_decl = zcu.declPtr(owner_decl_index);
987987 const namespace = zcu.namespacePtr(owner_decl.src_namespace);
988 const target = namespace.file_scope.mod.resolved_target.result;
988 const target = namespace.fileScope(zcu).mod.resolved_target.result;
989989 const ptr_bits = target.ptrBitWidth();
990990
991991 if (!ty.isSlice(zcu)) switch (ip.indexToKey(val.toIntern())) {
src/codegen/c.zig+1-1
......@@ -2581,7 +2581,7 @@ pub fn genTypeDecl(
25812581 _ = try renderTypePrefix(.flush, global_ctype_pool, zcu, writer, global_ctype, .suffix, .{});
25822582 try writer.writeByte(';');
25832583 const owner_decl = zcu.declPtr(owner_decl_index);
2584 const owner_mod = zcu.namespacePtr(owner_decl.src_namespace).file_scope.mod;
2584 const owner_mod = zcu.namespacePtr(owner_decl.src_namespace).fileScope(zcu).mod;
25852585 if (!owner_mod.strip) {
25862586 try writer.writeAll(" /* ");
25872587 try owner_decl.renderFullyQualifiedName(zcu, writer);
src/codegen/llvm.zig+150-141
......@@ -1362,7 +1362,8 @@ pub const Object = struct {
13621362 const decl_index = func.owner_decl;
13631363 const decl = zcu.declPtr(decl_index);
13641364 const namespace = zcu.namespacePtr(decl.src_namespace);
1365 const owner_mod = namespace.file_scope.mod;
1365 const file_scope = namespace.fileScope(zcu);
1366 const owner_mod = file_scope.mod;
13661367 const fn_info = zcu.typeToFunc(decl.typeOf(zcu)).?;
13671368 const target = owner_mod.resolved_target.result;
13681369 const ip = &zcu.intern_pool;
......@@ -1633,7 +1634,7 @@ pub const Object = struct {
16331634 function_index.setAttributes(try attributes.finish(&o.builder), &o.builder);
16341635
16351636 const file, const subprogram = if (!wip.strip) debug_info: {
1636 const file = try o.getDebugFile(namespace.file_scope);
1637 const file = try o.getDebugFile(file_scope);
16371638
16381639 const line_number = decl.navSrcLine(zcu) + 1;
16391640 const is_internal_linkage = decl.val.getExternFunc(zcu) == null;
......@@ -1720,23 +1721,23 @@ pub const Object = struct {
17201721
17211722 pub fn updateExports(
17221723 self: *Object,
1723 mod: *Module,
1724 zcu: *Zcu,
17241725 exported: Module.Exported,
17251726 export_indices: []const u32,
17261727 ) link.File.UpdateExportsError!void {
17271728 const decl_index = switch (exported) {
17281729 .decl_index => |i| i,
1729 .value => |val| return updateExportedValue(self, mod, val, export_indices),
1730 .value => |val| return updateExportedValue(self, zcu, val, export_indices),
17301731 };
1731 const ip = &mod.intern_pool;
1732 const ip = &zcu.intern_pool;
17321733 const global_index = self.decl_map.get(decl_index).?;
1733 const decl = mod.declPtr(decl_index);
1734 const comp = mod.comp;
1734 const decl = zcu.declPtr(decl_index);
1735 const comp = zcu.comp;
17351736
17361737 if (export_indices.len != 0) {
1737 return updateExportedGlobal(self, mod, global_index, export_indices);
1738 return updateExportedGlobal(self, zcu, global_index, export_indices);
17381739 } else {
1739 const fqn = try self.builder.strtabString((try decl.fullyQualifiedName(mod)).toSlice(ip));
1740 const fqn = try self.builder.strtabString((try decl.fullyQualifiedName(zcu)).toSlice(ip));
17401741 try global_index.rename(fqn, &self.builder);
17411742 global_index.setLinkage(.internal, &self.builder);
17421743 if (comp.config.dll_export_fns)
......@@ -1908,12 +1909,12 @@ pub const Object = struct {
19081909
19091910 const gpa = o.gpa;
19101911 const target = o.target;
1911 const mod = o.module;
1912 const ip = &mod.intern_pool;
1912 const zcu = o.module;
1913 const ip = &zcu.intern_pool;
19131914
19141915 if (o.debug_type_map.get(ty)) |debug_type| return debug_type;
19151916
1916 switch (ty.zigTypeTag(mod)) {
1917 switch (ty.zigTypeTag(zcu)) {
19171918 .Void,
19181919 .NoReturn,
19191920 => {
......@@ -1925,12 +1926,12 @@ pub const Object = struct {
19251926 return debug_void_type;
19261927 },
19271928 .Int => {
1928 const info = ty.intInfo(mod);
1929 const info = ty.intInfo(zcu);
19291930 assert(info.bits != 0);
19301931 const name = try o.allocTypeName(ty);
19311932 defer gpa.free(name);
19321933 const builder_name = try o.builder.metadataString(name);
1933 const debug_bits = ty.abiSize(mod) * 8; // lldb cannot handle non-byte sized types
1934 const debug_bits = ty.abiSize(zcu) * 8; // lldb cannot handle non-byte sized types
19341935 const debug_int_type = switch (info.signedness) {
19351936 .signed => try o.builder.debugSignedType(builder_name, debug_bits),
19361937 .unsigned => try o.builder.debugUnsignedType(builder_name, debug_bits),
......@@ -1939,10 +1940,10 @@ pub const Object = struct {
19391940 return debug_int_type;
19401941 },
19411942 .Enum => {
1942 const owner_decl_index = ty.getOwnerDecl(mod);
1943 const owner_decl_index = ty.getOwnerDecl(zcu);
19431944 const owner_decl = o.module.declPtr(owner_decl_index);
19441945
1945 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) {
1946 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
19461947 const debug_enum_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
19471948 try o.debug_type_map.put(gpa, ty, debug_enum_type);
19481949 return debug_enum_type;
......@@ -1954,13 +1955,13 @@ pub const Object = struct {
19541955 defer gpa.free(enumerators);
19551956
19561957 const int_ty = Type.fromInterned(enum_type.tag_ty);
1957 const int_info = ty.intInfo(mod);
1958 const int_info = ty.intInfo(zcu);
19581959 assert(int_info.bits != 0);
19591960
19601961 for (enum_type.names.get(ip), 0..) |field_name_ip, i| {
19611962 var bigint_space: Value.BigIntSpace = undefined;
19621963 const bigint = if (enum_type.values.len != 0)
1963 Value.fromInterned(enum_type.values.get(ip)[i]).toBigInt(&bigint_space, mod)
1964 Value.fromInterned(enum_type.values.get(ip)[i]).toBigInt(&bigint_space, zcu)
19641965 else
19651966 std.math.big.int.Mutable.init(&bigint_space.limbs, i).toConst();
19661967
......@@ -1972,7 +1973,8 @@ pub const Object = struct {
19721973 );
19731974 }
19741975
1975 const file = try o.getDebugFile(mod.namespacePtr(owner_decl.src_namespace).file_scope);
1976 const file_scope = zcu.namespacePtr(owner_decl.src_namespace).fileScope(zcu);
1977 const file = try o.getDebugFile(file_scope);
19761978 const scope = try o.namespaceToDebugScope(owner_decl.src_namespace);
19771979
19781980 const name = try o.allocTypeName(ty);
......@@ -1982,10 +1984,10 @@ pub const Object = struct {
19821984 try o.builder.metadataString(name),
19831985 file,
19841986 scope,
1985 owner_decl.typeSrcLine(mod) + 1, // Line
1987 owner_decl.typeSrcLine(zcu) + 1, // Line
19861988 try o.lowerDebugType(int_ty),
1987 ty.abiSize(mod) * 8,
1988 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
1989 ty.abiSize(zcu) * 8,
1990 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
19891991 try o.builder.debugTuple(enumerators),
19901992 );
19911993
......@@ -2014,7 +2016,7 @@ pub const Object = struct {
20142016 },
20152017 .Pointer => {
20162018 // Normalize everything that the debug info does not represent.
2017 const ptr_info = ty.ptrInfo(mod);
2019 const ptr_info = ty.ptrInfo(zcu);
20182020
20192021 if (ptr_info.sentinel != .none or
20202022 ptr_info.flags.address_space != .generic or
......@@ -2025,10 +2027,10 @@ pub const Object = struct {
20252027 ptr_info.flags.is_const or
20262028 ptr_info.flags.is_volatile or
20272029 ptr_info.flags.size == .Many or ptr_info.flags.size == .C or
2028 !Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(mod))
2030 !Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
20292031 {
2030 const bland_ptr_ty = try mod.ptrType(.{
2031 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(mod))
2032 const bland_ptr_ty = try zcu.ptrType(.{
2033 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
20322034 .anyopaque_type
20332035 else
20342036 ptr_info.child,
......@@ -2050,18 +2052,18 @@ pub const Object = struct {
20502052 // Set as forward reference while the type is lowered in case it references itself
20512053 try o.debug_type_map.put(gpa, ty, debug_fwd_ref);
20522054
2053 if (ty.isSlice(mod)) {
2054 const ptr_ty = ty.slicePtrFieldType(mod);
2055 if (ty.isSlice(zcu)) {
2056 const ptr_ty = ty.slicePtrFieldType(zcu);
20552057 const len_ty = Type.usize;
20562058
20572059 const name = try o.allocTypeName(ty);
20582060 defer gpa.free(name);
20592061 const line = 0;
20602062
2061 const ptr_size = ptr_ty.abiSize(mod);
2062 const ptr_align = ptr_ty.abiAlignment(mod);
2063 const len_size = len_ty.abiSize(mod);
2064 const len_align = len_ty.abiAlignment(mod);
2063 const ptr_size = ptr_ty.abiSize(zcu);
2064 const ptr_align = ptr_ty.abiAlignment(zcu);
2065 const len_size = len_ty.abiSize(zcu);
2066 const len_align = len_ty.abiAlignment(zcu);
20652067
20662068 const len_offset = len_align.forward(ptr_size);
20672069
......@@ -2093,8 +2095,8 @@ pub const Object = struct {
20932095 o.debug_compile_unit, // Scope
20942096 line,
20952097 .none, // Underlying type
2096 ty.abiSize(mod) * 8,
2097 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2098 ty.abiSize(zcu) * 8,
2099 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
20982100 try o.builder.debugTuple(&.{
20992101 debug_ptr_type,
21002102 debug_len_type,
......@@ -2122,7 +2124,7 @@ pub const Object = struct {
21222124 0, // Line
21232125 debug_elem_ty,
21242126 target.ptrBitWidth(),
2125 (ty.ptrAlignment(mod).toByteUnits() orelse 0) * 8,
2127 (ty.ptrAlignment(zcu).toByteUnits() orelse 0) * 8,
21262128 0, // Offset
21272129 );
21282130
......@@ -2146,13 +2148,14 @@ pub const Object = struct {
21462148
21472149 const name = try o.allocTypeName(ty);
21482150 defer gpa.free(name);
2149 const owner_decl_index = ty.getOwnerDecl(mod);
2151 const owner_decl_index = ty.getOwnerDecl(zcu);
21502152 const owner_decl = o.module.declPtr(owner_decl_index);
2153 const file_scope = zcu.namespacePtr(owner_decl.src_namespace).fileScope(zcu);
21512154 const debug_opaque_type = try o.builder.debugStructType(
21522155 try o.builder.metadataString(name),
2153 try o.getDebugFile(mod.namespacePtr(owner_decl.src_namespace).file_scope),
2156 try o.getDebugFile(file_scope),
21542157 try o.namespaceToDebugScope(owner_decl.src_namespace),
2155 owner_decl.typeSrcLine(mod) + 1, // Line
2158 owner_decl.typeSrcLine(zcu) + 1, // Line
21562159 .none, // Underlying type
21572160 0, // Size
21582161 0, // Align
......@@ -2167,13 +2170,13 @@ pub const Object = struct {
21672170 .none, // File
21682171 .none, // Scope
21692172 0, // Line
2170 try o.lowerDebugType(ty.childType(mod)),
2171 ty.abiSize(mod) * 8,
2172 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2173 try o.lowerDebugType(ty.childType(zcu)),
2174 ty.abiSize(zcu) * 8,
2175 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
21732176 try o.builder.debugTuple(&.{
21742177 try o.builder.debugSubrange(
21752178 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),
2176 try o.builder.debugConstant(try o.builder.intConst(.i64, ty.arrayLen(mod))),
2179 try o.builder.debugConstant(try o.builder.intConst(.i64, ty.arrayLen(zcu))),
21772180 ),
21782181 }),
21792182 );
......@@ -2181,14 +2184,14 @@ pub const Object = struct {
21812184 return debug_array_type;
21822185 },
21832186 .Vector => {
2184 const elem_ty = ty.elemType2(mod);
2187 const elem_ty = ty.elemType2(zcu);
21852188 // Vector elements cannot be padded since that would make
21862189 // @bitSizOf(elem) * len > @bitSizOf(vec).
21872190 // Neither gdb nor lldb seem to be able to display non-byte sized
21882191 // vectors properly.
2189 const debug_elem_type = switch (elem_ty.zigTypeTag(mod)) {
2192 const debug_elem_type = switch (elem_ty.zigTypeTag(zcu)) {
21902193 .Int => blk: {
2191 const info = elem_ty.intInfo(mod);
2194 const info = elem_ty.intInfo(zcu);
21922195 assert(info.bits != 0);
21932196 const name = try o.allocTypeName(ty);
21942197 defer gpa.free(name);
......@@ -2202,7 +2205,7 @@ pub const Object = struct {
22022205 try o.builder.metadataString("bool"),
22032206 1,
22042207 ),
2205 else => try o.lowerDebugType(ty.childType(mod)),
2208 else => try o.lowerDebugType(ty.childType(zcu)),
22062209 };
22072210
22082211 const debug_vector_type = try o.builder.debugVectorType(
......@@ -2211,12 +2214,12 @@ pub const Object = struct {
22112214 .none, // Scope
22122215 0, // Line
22132216 debug_elem_type,
2214 ty.abiSize(mod) * 8,
2215 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2217 ty.abiSize(zcu) * 8,
2218 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
22162219 try o.builder.debugTuple(&.{
22172220 try o.builder.debugSubrange(
22182221 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),
2219 try o.builder.debugConstant(try o.builder.intConst(.i64, ty.vectorLen(mod))),
2222 try o.builder.debugConstant(try o.builder.intConst(.i64, ty.vectorLen(zcu))),
22202223 ),
22212224 }),
22222225 );
......@@ -2227,8 +2230,8 @@ pub const Object = struct {
22272230 .Optional => {
22282231 const name = try o.allocTypeName(ty);
22292232 defer gpa.free(name);
2230 const child_ty = ty.optionalChild(mod);
2231 if (!child_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2233 const child_ty = ty.optionalChild(zcu);
2234 if (!child_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
22322235 const debug_bool_type = try o.builder.debugBoolType(
22332236 try o.builder.metadataString(name),
22342237 8,
......@@ -2242,7 +2245,7 @@ pub const Object = struct {
22422245 // Set as forward reference while the type is lowered in case it references itself
22432246 try o.debug_type_map.put(gpa, ty, debug_fwd_ref);
22442247
2245 if (ty.optionalReprIsPayload(mod)) {
2248 if (ty.optionalReprIsPayload(zcu)) {
22462249 const debug_optional_type = try o.lowerDebugType(child_ty);
22472250
22482251 o.builder.debugForwardReferenceSetType(debug_fwd_ref, debug_optional_type);
......@@ -2255,10 +2258,10 @@ pub const Object = struct {
22552258 }
22562259
22572260 const non_null_ty = Type.u8;
2258 const payload_size = child_ty.abiSize(mod);
2259 const payload_align = child_ty.abiAlignment(mod);
2260 const non_null_size = non_null_ty.abiSize(mod);
2261 const non_null_align = non_null_ty.abiAlignment(mod);
2261 const payload_size = child_ty.abiSize(zcu);
2262 const payload_align = child_ty.abiAlignment(zcu);
2263 const non_null_size = non_null_ty.abiSize(zcu);
2264 const non_null_align = non_null_ty.abiAlignment(zcu);
22622265 const non_null_offset = non_null_align.forward(payload_size);
22632266
22642267 const debug_data_type = try o.builder.debugMemberType(
......@@ -2289,8 +2292,8 @@ pub const Object = struct {
22892292 o.debug_compile_unit, // Scope
22902293 0, // Line
22912294 .none, // Underlying type
2292 ty.abiSize(mod) * 8,
2293 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2295 ty.abiSize(zcu) * 8,
2296 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
22942297 try o.builder.debugTuple(&.{
22952298 debug_data_type,
22962299 debug_some_type,
......@@ -2306,8 +2309,8 @@ pub const Object = struct {
23062309 return debug_optional_type;
23072310 },
23082311 .ErrorUnion => {
2309 const payload_ty = ty.errorUnionPayload(mod);
2310 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2312 const payload_ty = ty.errorUnionPayload(zcu);
2313 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
23112314 // TODO: Maybe remove?
23122315 const debug_error_union_type = try o.lowerDebugType(Type.anyerror);
23132316 try o.debug_type_map.put(gpa, ty, debug_error_union_type);
......@@ -2317,10 +2320,10 @@ pub const Object = struct {
23172320 const name = try o.allocTypeName(ty);
23182321 defer gpa.free(name);
23192322
2320 const error_size = Type.anyerror.abiSize(mod);
2321 const error_align = Type.anyerror.abiAlignment(mod);
2322 const payload_size = payload_ty.abiSize(mod);
2323 const payload_align = payload_ty.abiAlignment(mod);
2323 const error_size = Type.anyerror.abiSize(zcu);
2324 const error_align = Type.anyerror.abiAlignment(zcu);
2325 const payload_size = payload_ty.abiSize(zcu);
2326 const payload_align = payload_ty.abiAlignment(zcu);
23242327
23252328 var error_index: u32 = undefined;
23262329 var payload_index: u32 = undefined;
......@@ -2368,8 +2371,8 @@ pub const Object = struct {
23682371 o.debug_compile_unit, // Sope
23692372 0, // Line
23702373 .none, // Underlying type
2371 ty.abiSize(mod) * 8,
2372 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2374 ty.abiSize(zcu) * 8,
2375 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
23732376 try o.builder.debugTuple(&fields),
23742377 );
23752378
......@@ -2390,14 +2393,14 @@ pub const Object = struct {
23902393 const name = try o.allocTypeName(ty);
23912394 defer gpa.free(name);
23922395
2393 if (mod.typeToPackedStruct(ty)) |struct_type| {
2396 if (zcu.typeToPackedStruct(ty)) |struct_type| {
23942397 const backing_int_ty = struct_type.backingIntType(ip).*;
23952398 if (backing_int_ty != .none) {
2396 const info = Type.fromInterned(backing_int_ty).intInfo(mod);
2399 const info = Type.fromInterned(backing_int_ty).intInfo(zcu);
23972400 const builder_name = try o.builder.metadataString(name);
23982401 const debug_int_type = switch (info.signedness) {
2399 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(mod) * 8),
2400 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(mod) * 8),
2402 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(zcu) * 8),
2403 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(zcu) * 8),
24012404 };
24022405 try o.debug_type_map.put(gpa, ty, debug_int_type);
24032406 return debug_int_type;
......@@ -2417,10 +2420,10 @@ pub const Object = struct {
24172420 const debug_fwd_ref = try o.builder.debugForwardReference();
24182421
24192422 for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {
2420 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
2423 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(zcu)) continue;
24212424
2422 const field_size = Type.fromInterned(field_ty).abiSize(mod);
2423 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
2425 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
2426 const field_align = Type.fromInterned(field_ty).abiAlignment(zcu);
24242427 const field_offset = field_align.forward(offset);
24252428 offset = field_offset + field_size;
24262429
......@@ -2448,8 +2451,8 @@ pub const Object = struct {
24482451 o.debug_compile_unit, // Scope
24492452 0, // Line
24502453 .none, // Underlying type
2451 ty.abiSize(mod) * 8,
2452 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2454 ty.abiSize(zcu) * 8,
2455 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
24532456 try o.builder.debugTuple(fields.items),
24542457 );
24552458
......@@ -2467,7 +2470,7 @@ pub const Object = struct {
24672470 // into. Therefore we can satisfy this by making an empty namespace,
24682471 // rather than changing the frontend to unnecessarily resolve the
24692472 // struct field types.
2470 const owner_decl_index = ty.getOwnerDecl(mod);
2473 const owner_decl_index = ty.getOwnerDecl(zcu);
24712474 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
24722475 try o.debug_type_map.put(gpa, ty, debug_struct_type);
24732476 return debug_struct_type;
......@@ -2476,14 +2479,14 @@ pub const Object = struct {
24762479 else => {},
24772480 }
24782481
2479 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) {
2480 const owner_decl_index = ty.getOwnerDecl(mod);
2482 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2483 const owner_decl_index = ty.getOwnerDecl(zcu);
24812484 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
24822485 try o.debug_type_map.put(gpa, ty, debug_struct_type);
24832486 return debug_struct_type;
24842487 }
24852488
2486 const struct_type = mod.typeToStruct(ty).?;
2489 const struct_type = zcu.typeToStruct(ty).?;
24872490
24882491 var fields: std.ArrayListUnmanaged(Builder.Metadata) = .{};
24892492 defer fields.deinit(gpa);
......@@ -2499,14 +2502,14 @@ pub const Object = struct {
24992502 var it = struct_type.iterateRuntimeOrder(ip);
25002503 while (it.next()) |field_index| {
25012504 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
2502 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2503 const field_size = field_ty.abiSize(mod);
2504 const field_align = mod.structFieldAlignment(
2505 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
2506 const field_size = field_ty.abiSize(zcu);
2507 const field_align = zcu.structFieldAlignment(
25052508 struct_type.fieldAlign(ip, field_index),
25062509 field_ty,
25072510 struct_type.layout,
25082511 );
2509 const field_offset = ty.structFieldOffset(field_index, mod);
2512 const field_offset = ty.structFieldOffset(field_index, zcu);
25102513
25112514 const field_name = struct_type.fieldName(ip, field_index).unwrap() orelse
25122515 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
......@@ -2529,8 +2532,8 @@ pub const Object = struct {
25292532 o.debug_compile_unit, // Scope
25302533 0, // Line
25312534 .none, // Underlying type
2532 ty.abiSize(mod) * 8,
2533 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2535 ty.abiSize(zcu) * 8,
2536 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
25342537 try o.builder.debugTuple(fields.items),
25352538 );
25362539
......@@ -2543,14 +2546,14 @@ pub const Object = struct {
25432546 return debug_struct_type;
25442547 },
25452548 .Union => {
2546 const owner_decl_index = ty.getOwnerDecl(mod);
2549 const owner_decl_index = ty.getOwnerDecl(zcu);
25472550
25482551 const name = try o.allocTypeName(ty);
25492552 defer gpa.free(name);
25502553
25512554 const union_type = ip.loadUnionType(ty.toIntern());
25522555 if (!union_type.haveFieldTypes(ip) or
2553 !ty.hasRuntimeBitsIgnoreComptime(mod) or
2556 !ty.hasRuntimeBitsIgnoreComptime(zcu) or
25542557 !union_type.haveLayout(ip))
25552558 {
25562559 const debug_union_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
......@@ -2558,7 +2561,7 @@ pub const Object = struct {
25582561 return debug_union_type;
25592562 }
25602563
2561 const layout = mod.getUnionLayout(union_type);
2564 const layout = zcu.getUnionLayout(union_type);
25622565
25632566 const debug_fwd_ref = try o.builder.debugForwardReference();
25642567
......@@ -2572,8 +2575,8 @@ pub const Object = struct {
25722575 o.debug_compile_unit, // Scope
25732576 0, // Line
25742577 .none, // Underlying type
2575 ty.abiSize(mod) * 8,
2576 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2578 ty.abiSize(zcu) * 8,
2579 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
25772580 try o.builder.debugTuple(
25782581 &.{try o.lowerDebugType(Type.fromInterned(union_type.enum_tag_ty))},
25792582 ),
......@@ -2600,12 +2603,12 @@ pub const Object = struct {
26002603
26012604 for (0..tag_type.names.len) |field_index| {
26022605 const field_ty = union_type.field_types.get(ip)[field_index];
2603 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
2606 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(zcu)) continue;
26042607
2605 const field_size = Type.fromInterned(field_ty).abiSize(mod);
2608 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
26062609 const field_align: InternPool.Alignment = switch (union_type.flagsPtr(ip).layout) {
26072610 .@"packed" => .none,
2608 .auto, .@"extern" => mod.unionFieldNormalAlignment(union_type, @intCast(field_index)),
2611 .auto, .@"extern" => zcu.unionFieldNormalAlignment(union_type, @intCast(field_index)),
26092612 };
26102613
26112614 const field_name = tag_type.names.get(ip)[field_index];
......@@ -2634,8 +2637,8 @@ pub const Object = struct {
26342637 o.debug_compile_unit, // Scope
26352638 0, // Line
26362639 .none, // Underlying type
2637 ty.abiSize(mod) * 8,
2638 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2640 ty.abiSize(zcu) * 8,
2641 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
26392642 try o.builder.debugTuple(fields.items),
26402643 );
26412644
......@@ -2693,8 +2696,8 @@ pub const Object = struct {
26932696 o.debug_compile_unit, // Scope
26942697 0, // Line
26952698 .none, // Underlying type
2696 ty.abiSize(mod) * 8,
2697 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,
2699 ty.abiSize(zcu) * 8,
2700 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
26982701 try o.builder.debugTuple(&full_fields),
26992702 );
27002703
......@@ -2707,7 +2710,7 @@ pub const Object = struct {
27072710 return debug_tagged_union_type;
27082711 },
27092712 .Fn => {
2710 const fn_info = mod.typeToFunc(ty).?;
2713 const fn_info = zcu.typeToFunc(ty).?;
27112714
27122715 var debug_param_types = std.ArrayList(Builder.Metadata).init(gpa);
27132716 defer debug_param_types.deinit();
......@@ -2715,32 +2718,32 @@ pub const Object = struct {
27152718 try debug_param_types.ensureUnusedCapacity(3 + fn_info.param_types.len);
27162719
27172720 // Return type goes first.
2718 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(mod)) {
2719 const sret = firstParamSRet(fn_info, mod, target);
2721 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(zcu)) {
2722 const sret = firstParamSRet(fn_info, zcu, target);
27202723 const ret_ty = if (sret) Type.void else Type.fromInterned(fn_info.return_type);
27212724 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ret_ty));
27222725
27232726 if (sret) {
2724 const ptr_ty = try mod.singleMutPtrType(Type.fromInterned(fn_info.return_type));
2727 const ptr_ty = try zcu.singleMutPtrType(Type.fromInterned(fn_info.return_type));
27252728 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27262729 }
27272730 } else {
27282731 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(Type.void));
27292732 }
27302733
2731 if (Type.fromInterned(fn_info.return_type).isError(mod) and
2734 if (Type.fromInterned(fn_info.return_type).isError(zcu) and
27322735 o.module.comp.config.any_error_tracing)
27332736 {
2734 const ptr_ty = try mod.singleMutPtrType(try o.getStackTraceType());
2737 const ptr_ty = try zcu.singleMutPtrType(try o.getStackTraceType());
27352738 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27362739 }
27372740
27382741 for (0..fn_info.param_types.len) |i| {
27392742 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[i]);
2740 if (!param_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2743 if (!param_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
27412744
2742 if (isByRef(param_ty, mod)) {
2743 const ptr_ty = try mod.singleMutPtrType(param_ty);
2745 if (isByRef(param_ty, zcu)) {
2746 const ptr_ty = try zcu.singleMutPtrType(param_ty);
27442747 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27452748 } else {
27462749 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(param_ty));
......@@ -2767,9 +2770,10 @@ pub const Object = struct {
27672770 }
27682771
27692772 fn namespaceToDebugScope(o: *Object, namespace_index: InternPool.NamespaceIndex) !Builder.Metadata {
2770 const mod = o.module;
2771 const namespace = mod.namespacePtr(namespace_index);
2772 if (namespace.parent == .none) return try o.getDebugFile(namespace.file_scope);
2773 const zcu = o.module;
2774 const namespace = zcu.namespacePtr(namespace_index);
2775 const file_scope = namespace.fileScope(zcu);
2776 if (namespace.parent == .none) return try o.getDebugFile(file_scope);
27732777
27742778 const gop = try o.debug_unresolved_namespace_scopes.getOrPut(o.gpa, namespace_index);
27752779
......@@ -2779,13 +2783,14 @@ pub const Object = struct {
27792783 }
27802784
27812785 fn makeEmptyNamespaceDebugType(o: *Object, decl_index: InternPool.DeclIndex) !Builder.Metadata {
2782 const mod = o.module;
2783 const decl = mod.declPtr(decl_index);
2786 const zcu = o.module;
2787 const decl = zcu.declPtr(decl_index);
2788 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
27842789 return o.builder.debugStructType(
2785 try o.builder.metadataString(decl.name.toSlice(&mod.intern_pool)), // TODO use fully qualified name
2786 try o.getDebugFile(mod.namespacePtr(decl.src_namespace).file_scope),
2790 try o.builder.metadataString(decl.name.toSlice(&zcu.intern_pool)), // TODO use fully qualified name
2791 try o.getDebugFile(file_scope),
27872792 try o.namespaceToDebugScope(decl.src_namespace),
2788 decl.typeSrcLine(mod) + 1,
2793 decl.typeSrcLine(zcu) + 1,
27892794 .none,
27902795 0,
27912796 0,
......@@ -2794,21 +2799,22 @@ pub const Object = struct {
27942799 }
27952800
27962801 fn getStackTraceType(o: *Object) Allocator.Error!Type {
2797 const mod = o.module;
2802 const zcu = o.module;
27982803
2799 const std_mod = mod.std_mod;
2800 const std_file = (mod.importPkg(std_mod) catch unreachable).file;
2804 const std_mod = zcu.std_mod;
2805 const std_file_imported = zcu.importPkg(std_mod) catch unreachable;
28012806
2802 const builtin_str = try mod.intern_pool.getOrPutString(mod.gpa, "builtin", .no_embedded_nulls);
2803 const std_namespace = mod.namespacePtr(mod.declPtr(std_file.root_decl.unwrap().?).src_namespace);
2804 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Module.DeclAdapter{ .zcu = mod }).?;
2807 const builtin_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "builtin", .no_embedded_nulls);
2808 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index);
2809 const std_namespace = zcu.namespacePtr(zcu.declPtr(std_file_root_decl.unwrap().?).src_namespace);
2810 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Module.DeclAdapter{ .zcu = zcu }).?;
28052811
2806 const stack_trace_str = try mod.intern_pool.getOrPutString(mod.gpa, "StackTrace", .no_embedded_nulls);
2812 const stack_trace_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "StackTrace", .no_embedded_nulls);
28072813 // buffer is only used for int_type, `builtin` is a struct.
2808 const builtin_ty = mod.declPtr(builtin_decl).val.toType();
2809 const builtin_namespace = mod.namespacePtrUnwrap(builtin_ty.getNamespaceIndex(mod)).?;
2810 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Module.DeclAdapter{ .zcu = mod }).?;
2811 const stack_trace_decl = mod.declPtr(stack_trace_decl_index);
2814 const builtin_ty = zcu.declPtr(builtin_decl).val.toType();
2815 const builtin_namespace = zcu.namespacePtrUnwrap(builtin_ty.getNamespaceIndex(zcu)).?;
2816 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Module.DeclAdapter{ .zcu = zcu }).?;
2817 const stack_trace_decl = zcu.declPtr(stack_trace_decl_index);
28122818
28132819 // Sema should have ensured that StackTrace was analyzed.
28142820 assert(stack_trace_decl.has_tv);
......@@ -2834,7 +2840,7 @@ pub const Object = struct {
28342840 const gpa = o.gpa;
28352841 const decl = zcu.declPtr(decl_index);
28362842 const namespace = zcu.namespacePtr(decl.src_namespace);
2837 const owner_mod = namespace.file_scope.mod;
2843 const owner_mod = namespace.fileScope(zcu).mod;
28382844 const zig_fn_type = decl.typeOf(zcu);
28392845 const gop = try o.decl_map.getOrPut(gpa, decl_index);
28402846 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.function;
......@@ -3059,17 +3065,17 @@ pub const Object = struct {
30593065 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.variable;
30603066 errdefer assert(o.decl_map.remove(decl_index));
30613067
3062 const mod = o.module;
3063 const decl = mod.declPtr(decl_index);
3064 const is_extern = decl.isExtern(mod);
3068 const zcu = o.module;
3069 const decl = zcu.declPtr(decl_index);
3070 const is_extern = decl.isExtern(zcu);
30653071
30663072 const variable_index = try o.builder.addVariable(
30673073 try o.builder.strtabString((if (is_extern)
30683074 decl.name
30693075 else
3070 try decl.fullyQualifiedName(mod)).toSlice(&mod.intern_pool)),
3071 try o.lowerType(decl.typeOf(mod)),
3072 toLlvmGlobalAddressSpace(decl.@"addrspace", mod.getTarget()),
3076 try decl.fullyQualifiedName(zcu)).toSlice(&zcu.intern_pool)),
3077 try o.lowerType(decl.typeOf(zcu)),
3078 toLlvmGlobalAddressSpace(decl.@"addrspace", zcu.getTarget()),
30733079 );
30743080 gop.value_ptr.* = variable_index.ptrConst(&o.builder).global;
30753081
......@@ -3077,9 +3083,9 @@ pub const Object = struct {
30773083 if (is_extern) {
30783084 variable_index.setLinkage(.external, &o.builder);
30793085 variable_index.setUnnamedAddr(.default, &o.builder);
3080 if (decl.val.getVariable(mod)) |decl_var| {
3081 const decl_namespace = mod.namespacePtr(decl.src_namespace);
3082 const single_threaded = decl_namespace.file_scope.mod.single_threaded;
3086 if (decl.val.getVariable(zcu)) |decl_var| {
3087 const decl_namespace = zcu.namespacePtr(decl.src_namespace);
3088 const single_threaded = decl_namespace.fileScope(zcu).mod.single_threaded;
30833089 variable_index.setThreadLocal(
30843090 if (decl_var.is_threadlocal and !single_threaded) .generaldynamic else .default,
30853091 &o.builder,
......@@ -4638,7 +4644,8 @@ pub const DeclGen = struct {
46384644 const o = dg.object;
46394645 const zcu = o.module;
46404646 const namespace = zcu.namespacePtr(dg.decl.src_namespace);
4641 return namespace.file_scope.mod;
4647 const file_scope = namespace.fileScope(zcu);
4648 return file_scope.mod;
46424649 }
46434650
46444651 fn todo(dg: *DeclGen, comptime format: []const u8, args: anytype) Error {
......@@ -4682,7 +4689,7 @@ pub const DeclGen = struct {
46824689
46834690 if (decl.val.getVariable(zcu)) |decl_var| {
46844691 const decl_namespace = zcu.namespacePtr(decl.src_namespace);
4685 const single_threaded = decl_namespace.file_scope.mod.single_threaded;
4692 const single_threaded = decl_namespace.fileScope(zcu).mod.single_threaded;
46864693 variable_index.setThreadLocal(
46874694 if (decl_var.is_threadlocal and !single_threaded) .generaldynamic else .default,
46884695 &o.builder,
......@@ -4692,10 +4699,11 @@ pub const DeclGen = struct {
46924699 const line_number = decl.navSrcLine(zcu) + 1;
46934700
46944701 const namespace = zcu.namespacePtr(decl.src_namespace);
4695 const owner_mod = namespace.file_scope.mod;
4702 const file_scope = namespace.fileScope(zcu);
4703 const owner_mod = file_scope.mod;
46964704
46974705 if (!owner_mod.strip) {
4698 const debug_file = try o.getDebugFile(namespace.file_scope);
4706 const debug_file = try o.getDebugFile(file_scope);
46994707
47004708 const debug_global_var = try o.builder.debugGlobalVar(
47014709 try o.builder.metadataString(decl.name.toSlice(ip)), // Name
......@@ -5143,9 +5151,10 @@ pub const FuncGen = struct {
51435151 const decl_index = func.owner_decl;
51445152 const decl = zcu.declPtr(decl_index);
51455153 const namespace = zcu.namespacePtr(decl.src_namespace);
5146 const owner_mod = namespace.file_scope.mod;
5154 const file_scope = namespace.fileScope(zcu);
5155 const owner_mod = file_scope.mod;
51475156
5148 self.file = try o.getDebugFile(namespace.file_scope);
5157 self.file = try o.getDebugFile(file_scope);
51495158
51505159 const line_number = decl.navSrcLine(zcu) + 1;
51515160 self.inlined = self.wip.debug_location;
src/codegen/spirv.zig+10-9
......@@ -188,19 +188,20 @@ pub const Object = struct {
188188
189189 fn genDecl(
190190 self: *Object,
191 mod: *Module,
191 zcu: *Zcu,
192192 decl_index: InternPool.DeclIndex,
193193 air: Air,
194194 liveness: Liveness,
195195 ) !void {
196 const decl = mod.declPtr(decl_index);
197 const namespace = mod.namespacePtr(decl.src_namespace);
198 const structured_cfg = namespace.file_scope.mod.structured_cfg;
196 const gpa = self.gpa;
197 const decl = zcu.declPtr(decl_index);
198 const namespace = zcu.namespacePtr(decl.src_namespace);
199 const structured_cfg = namespace.fileScope(zcu).mod.structured_cfg;
199200
200201 var decl_gen = DeclGen{
201 .gpa = self.gpa,
202 .gpa = gpa,
202203 .object = self,
203 .module = mod,
204 .module = zcu,
204205 .spv = &self.spv,
205206 .decl_index = decl_index,
206207 .air = air,
......@@ -212,19 +213,19 @@ pub const Object = struct {
212213 false => .{ .unstructured = .{} },
213214 },
214215 .current_block_label = undefined,
215 .base_line = decl.navSrcLine(mod),
216 .base_line = decl.navSrcLine(zcu),
216217 };
217218 defer decl_gen.deinit();
218219
219220 decl_gen.genDecl() catch |err| switch (err) {
220221 error.CodegenFail => {
221 try mod.failed_analysis.put(mod.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }), decl_gen.error_msg.?);
222 try zcu.failed_analysis.put(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }), decl_gen.error_msg.?);
222223 },
223224 else => |other| {
224225 // There might be an error that happened *after* self.error_msg
225226 // was already allocated, so be sure to free it.
226227 if (decl_gen.error_msg) |error_msg| {
227 error_msg.deinit(mod.gpa);
228 error_msg.deinit(gpa);
228229 }
229230
230231 return other;
src/link/C.zig+8-4
......@@ -208,6 +208,8 @@ pub fn updateFunc(
208208 fwd_decl.clearRetainingCapacity();
209209 code.clearRetainingCapacity();
210210
211 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
212
211213 var function: codegen.Function = .{
212214 .value_map = codegen.CValueMap.init(gpa),
213215 .air = air,
......@@ -217,7 +219,7 @@ pub fn updateFunc(
217219 .dg = .{
218220 .gpa = gpa,
219221 .zcu = zcu,
220 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,
222 .mod = file_scope.mod,
221223 .error_msg = null,
222224 .pass = .{ .decl = decl_index },
223225 .is_naked_fn = decl.typeOf(zcu).fnCallingConvention(zcu) == .Naked,
......@@ -335,11 +337,13 @@ pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
335337 fwd_decl.clearRetainingCapacity();
336338 code.clearRetainingCapacity();
337339
340 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
341
338342 var object: codegen.Object = .{
339343 .dg = .{
340344 .gpa = gpa,
341345 .zcu = zcu,
342 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,
346 .mod = file_scope.mod,
343347 .error_msg = null,
344348 .pass = .{ .decl = decl_index },
345349 .is_naked_fn = false,
......@@ -491,7 +495,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
491495 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, *decl_block| {
492496 const decl = zcu.declPtr(decl_index);
493497 const extern_name = if (decl.isExtern(zcu)) decl.name.toOptional() else .none;
494 const mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod;
498 const mod = zcu.namespacePtr(decl.src_namespace).fileScope(zcu).mod;
495499 try self.flushDeclBlock(
496500 zcu,
497501 mod,
......@@ -848,7 +852,7 @@ pub fn updateExports(
848852 const gpa = self.base.comp.gpa;
849853 const mod, const pass: codegen.DeclGen.Pass, const decl_block, const exported_block = switch (exported) {
850854 .decl_index => |decl_index| .{
851 zcu.namespacePtr(zcu.declPtr(decl_index).src_namespace).file_scope.mod,
855 zcu.namespacePtr(zcu.declPtr(decl_index).src_namespace).fileScope(zcu).mod,
852856 .{ .decl = decl_index },
853857 self.decl_table.getPtr(decl_index).?,
854858 (try self.exported_decls.getOrPut(gpa, decl_index)).value_ptr,
src/link/Dwarf.zig+1-1
......@@ -1204,7 +1204,7 @@ pub fn commitDeclState(
12041204 const decl = zcu.declPtr(decl_index);
12051205 const ip = &zcu.intern_pool;
12061206 const namespace = zcu.namespacePtr(decl.src_namespace);
1207 const target = namespace.file_scope.mod.resolved_target.result;
1207 const target = namespace.fileScope(zcu).mod.resolved_target.result;
12081208 const target_endian = target.cpu.arch.endian();
12091209
12101210 var dbg_line_buffer = &decl_state.dbg_line;
src/link/Wasm/ZigObject.zig+11-11
......@@ -335,29 +335,29 @@ fn finishUpdateDecl(
335335 code: []const u8,
336336) !void {
337337 const gpa = wasm_file.base.comp.gpa;
338 const mod = wasm_file.base.comp.module.?;
339 const decl = mod.declPtr(decl_index);
338 const zcu = wasm_file.base.comp.module.?;
339 const decl = zcu.declPtr(decl_index);
340340 const decl_info = zig_object.decls_map.get(decl_index).?;
341341 const atom_index = decl_info.atom;
342342 const atom = wasm_file.getAtomPtr(atom_index);
343343 const sym = zig_object.symbol(atom.sym_index);
344 const full_name = try decl.fullyQualifiedName(mod);
345 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&mod.intern_pool));
344 const full_name = try decl.fullyQualifiedName(zcu);
345 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&zcu.intern_pool));
346346 try atom.code.appendSlice(gpa, code);
347347 atom.size = @intCast(code.len);
348348
349 switch (decl.typeOf(mod).zigTypeTag(mod)) {
349 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
350350 .Fn => {
351351 sym.index = try zig_object.appendFunction(gpa, .{ .type_index = zig_object.atom_types.get(atom_index).? });
352352 sym.tag = .function;
353353 },
354354 else => {
355 const segment_name: []const u8 = if (decl.getOwnedVariable(mod)) |variable| name: {
355 const segment_name: []const u8 = if (decl.getOwnedVariable(zcu)) |variable| name: {
356356 if (variable.is_const) {
357357 break :name ".rodata.";
358 } else if (Value.fromInterned(variable.init).isUndefDeep(mod)) {
359 const decl_namespace = mod.namespacePtr(decl.src_namespace);
360 const optimize_mode = decl_namespace.file_scope.mod.optimize_mode;
358 } else if (Value.fromInterned(variable.init).isUndefDeep(zcu)) {
359 const decl_namespace = zcu.namespacePtr(decl.src_namespace);
360 const optimize_mode = decl_namespace.fileScope(zcu).mod.optimize_mode;
361361 const is_initialized = switch (optimize_mode) {
362362 .Debug, .ReleaseSafe => true,
363363 .ReleaseFast, .ReleaseSmall => false,
......@@ -382,7 +382,7 @@ fn finishUpdateDecl(
382382 // Will be freed upon freeing of decl or after cleanup of Wasm binary.
383383 const full_segment_name = try std.mem.concat(gpa, u8, &.{
384384 segment_name,
385 full_name.toSlice(&mod.intern_pool),
385 full_name.toSlice(&zcu.intern_pool),
386386 });
387387 errdefer gpa.free(full_segment_name);
388388 sym.tag = .data;
......@@ -390,7 +390,7 @@ fn finishUpdateDecl(
390390 },
391391 }
392392 if (code.len == 0) return;
393 atom.alignment = decl.getAlignment(mod);
393 atom.alignment = decl.getAlignment(zcu);
394394}
395395
396396/// Creates and initializes a new segment in the 'Data' section.
src/main.zig+7-15
......@@ -27,8 +27,6 @@ const Cache = std.Build.Cache;
2727const target_util = @import("target.zig");
2828const crash_report = @import("crash_report.zig");
2929const Zcu = @import("Zcu.zig");
30/// Deprecated.
31const Module = Zcu;
3230const AstGen = std.zig.AstGen;
3331const mingw = @import("mingw.zig");
3432const Server = std.zig.Server;
......@@ -919,7 +917,7 @@ fn buildOutputType(
919917 var contains_res_file: bool = false;
920918 var reference_trace: ?u32 = null;
921919 var pdb_out_path: ?[]const u8 = null;
922 var error_limit: ?Module.ErrorInt = null;
920 var error_limit: ?Zcu.ErrorInt = null;
923921 // These are before resolving sysroot.
924922 var extra_cflags: std.ArrayListUnmanaged([]const u8) = .{};
925923 var extra_rcflags: std.ArrayListUnmanaged([]const u8) = .{};
......@@ -1107,7 +1105,7 @@ fn buildOutputType(
11071105 );
11081106 } else if (mem.eql(u8, arg, "--error-limit")) {
11091107 const next_arg = args_iter.nextOrFatal();
1110 error_limit = std.fmt.parseUnsigned(Module.ErrorInt, next_arg, 0) catch |err| {
1108 error_limit = std.fmt.parseUnsigned(Zcu.ErrorInt, next_arg, 0) catch |err| {
11111109 fatal("unable to parse error limit '{s}': {s}", .{ next_arg, @errorName(err) });
11121110 };
11131111 } else if (mem.eql(u8, arg, "-cflags")) {
......@@ -5956,7 +5954,7 @@ fn cmdAstCheck(
59565954 }
59575955 }
59585956
5959 var file: Module.File = .{
5957 var file: Zcu.File = .{
59605958 .status = .never_loaded,
59615959 .source_loaded = false,
59625960 .tree_loaded = false,
......@@ -5967,8 +5965,6 @@ fn cmdAstCheck(
59675965 .tree = undefined,
59685966 .zir = undefined,
59695967 .mod = undefined,
5970 .root_decl = .none,
5971 .path_digest = undefined,
59725968 };
59735969 if (zig_source_file) |file_name| {
59745970 var f = fs.cwd().openFile(file_name, .{}) catch |err| {
......@@ -6275,7 +6271,7 @@ fn cmdDumpZir(
62756271 };
62766272 defer f.close();
62776273
6278 var file: Module.File = .{
6274 var file: Zcu.File = .{
62796275 .status = .never_loaded,
62806276 .source_loaded = false,
62816277 .tree_loaded = false,
......@@ -6284,10 +6280,8 @@ fn cmdDumpZir(
62846280 .source = undefined,
62856281 .stat = undefined,
62866282 .tree = undefined,
6287 .zir = try Module.loadZirCache(gpa, f),
6283 .zir = try Zcu.loadZirCache(gpa, f),
62886284 .mod = undefined,
6289 .root_decl = .none,
6290 .path_digest = undefined,
62916285 };
62926286 defer file.zir.deinit(gpa);
62936287
......@@ -6342,7 +6336,7 @@ fn cmdChangelist(
63426336 if (stat.size > std.zig.max_src_size)
63436337 return error.FileTooBig;
63446338
6345 var file: Module.File = .{
6339 var file: Zcu.File = .{
63466340 .status = .never_loaded,
63476341 .source_loaded = false,
63486342 .tree_loaded = false,
......@@ -6357,8 +6351,6 @@ fn cmdChangelist(
63576351 .tree = undefined,
63586352 .zir = undefined,
63596353 .mod = undefined,
6360 .root_decl = .none,
6361 .path_digest = undefined,
63626354 };
63636355
63646356 file.mod = try Package.Module.createLimited(arena, .{
......@@ -6431,7 +6423,7 @@ fn cmdChangelist(
64316423 var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{};
64326424 defer inst_map.deinit(gpa);
64336425
6434 try Module.mapOldZirToNew(gpa, old_zir, file.zir, &inst_map);
6426 try Zcu.mapOldZirToNew(gpa, old_zir, file.zir, &inst_map);
64356427
64366428 var bw = io.bufferedWriter(io.getStdOut().writer());
64376429 const stdout = bw.writer();