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 {...@@ -250,14 +250,7 @@ pub const HashHelper = struct {
250 pub fn final(hh: *HashHelper) HexDigest {250 pub fn final(hh: *HashHelper) HexDigest {
251 var bin_digest: BinDigest = undefined;251 var bin_digest: BinDigest = undefined;
252 hh.hasher.final(&bin_digest);252 hh.hasher.final(&bin_digest);
253253 return binToHex(bin_digest);
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;
261 }254 }
262255
263 pub fn oneShot(bytes: []const u8) [hex_digest_len]u8 {256 pub fn oneShot(bytes: []const u8) [hex_digest_len]u8 {
...@@ -265,16 +258,20 @@ pub const HashHelper = struct {...@@ -265,16 +258,20 @@ pub const HashHelper = struct {
265 hasher.update(bytes);258 hasher.update(bytes);
266 var bin_digest: BinDigest = undefined;259 var bin_digest: BinDigest = undefined;
267 hasher.final(&bin_digest);260 hasher.final(&bin_digest);
268 var out_digest: [hex_digest_len]u8 = undefined;261 return binToHex(bin_digest);
269 _ = fmt.bufPrint(
270 &out_digest,
271 "{s}",
272 .{fmt.fmtSliceHexLower(&bin_digest)},
273 ) catch unreachable;
274 return out_digest;
275 }262 }
276};263};
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
278pub const Lock = struct {275pub const Lock = struct {
279 manifest_file: fs.File,276 manifest_file: fs.File,
280277
...@@ -426,11 +423,7 @@ pub const Manifest = struct {...@@ -426,11 +423,7 @@ pub const Manifest = struct {
426 var bin_digest: BinDigest = undefined;423 var bin_digest: BinDigest = undefined;
427 self.hash.hasher.final(&bin_digest);424 self.hash.hasher.final(&bin_digest);
428425
429 _ = fmt.bufPrint(426 self.hex_digest = binToHex(bin_digest);
430 &self.hex_digest,
431 "{s}",
432 .{fmt.fmtSliceHexLower(&bin_digest)},
433 ) catch unreachable;
434427
435 self.hash.hasher = hasher_init;428 self.hash.hasher = hasher_init;
436 self.hash.hasher.update(&bin_digest);429 self.hash.hasher.update(&bin_digest);
...@@ -899,14 +892,7 @@ pub const Manifest = struct {...@@ -899,14 +892,7 @@ pub const Manifest = struct {
899 var bin_digest: BinDigest = undefined;892 var bin_digest: BinDigest = undefined;
900 self.hash.hasher.final(&bin_digest);893 self.hash.hasher.final(&bin_digest);
901894
902 var out_digest: HexDigest = undefined;895 return binToHex(bin_digest);
903 _ = fmt.bufPrint(
904 &out_digest,
905 "{s}",
906 .{fmt.fmtSliceHexLower(&bin_digest)},
907 ) catch unreachable;
908
909 return out_digest;
910 }896 }
911897
912 /// If `want_shared_lock` is true, this function automatically downgrades the898 /// 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 {...@@ -398,20 +398,30 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
398 }398 }
399}399}
400400
401/// This function invokes undefined behavior when `ok` is `false`.401/// Invokes detectable illegal behavior when `ok` is `false`.
402///
402/// In Debug and ReleaseSafe modes, calls to this function are always403/// In Debug and ReleaseSafe modes, calls to this function are always
403/// generated, and the `unreachable` statement triggers a panic.404/// generated, and the `unreachable` statement triggers a panic.
404/// In ReleaseFast and ReleaseSmall modes, calls to this function are405///
405/// optimized away, and in fact the optimizer is able to use the assertion406/// In ReleaseFast and ReleaseSmall modes, calls to this function are optimized
406/// in its heuristics.407/// away, and in fact the optimizer is able to use the assertion in its
407/// Inside a test block, it is best to use the `std.testing` module rather408/// heuristics.
408/// than this function, because this function may not detect a test failure409///
409/// in ReleaseFast and ReleaseSmall mode. Outside of a test block, this assert410/// 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
410/// function is the correct function to use.413/// function is the correct function to use.
411pub fn assert(ok: bool) void {414pub fn assert(ok: bool) void {
412 if (!ok) unreachable; // assertion failure415 if (!ok) unreachable; // assertion failure
413}416}
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
415pub fn panic(comptime format: []const u8, args: anytype) noreturn {425pub fn panic(comptime format: []const u8, args: anytype) noreturn {
416 @setCold(true);426 @setCold(true);
417427
src/Compilation.zig+136-101
...@@ -116,7 +116,7 @@ win32_resource_work_queue: if (build_options.only_core_functionality) void else...@@ -116,7 +116,7 @@ win32_resource_work_queue: if (build_options.only_core_functionality) void else
116/// These jobs are to tokenize, parse, and astgen files, which may be outdated116/// These jobs are to tokenize, parse, and astgen files, which may be outdated
117/// since the last compilation, as well as scan for `@import` and queue up117/// since the last compilation, as well as scan for `@import` and queue up
118/// additional jobs corresponding to those new files.118/// 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),
120/// These jobs are to inspect the file system stat() and if the embedded file has changed120/// These jobs are to inspect the file system stat() and if the embedded file has changed
121/// on disk, mark the corresponding Decl outdated and queue up an `analyze_decl`121/// on disk, mark the corresponding Decl outdated and queue up an `analyze_decl`
122/// task for it.122/// task for it.
...@@ -1433,7 +1433,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil...@@ -1433,7 +1433,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
1433 .work_queue = std.fifo.LinearFifo(Job, .Dynamic).init(gpa),1433 .work_queue = std.fifo.LinearFifo(Job, .Dynamic).init(gpa),
1434 .c_object_work_queue = std.fifo.LinearFifo(*CObject, .Dynamic).init(gpa),1434 .c_object_work_queue = std.fifo.LinearFifo(*CObject, .Dynamic).init(gpa),
1435 .win32_resource_work_queue = if (build_options.only_core_functionality) {} else std.fifo.LinearFifo(*Win32Resource, .Dynamic).init(gpa),1435 .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),
1437 .embed_file_work_queue = std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic).init(gpa),1437 .embed_file_work_queue = std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic).init(gpa),
1438 .c_source_files = options.c_source_files,1438 .c_source_files = options.c_source_files,
1439 .rc_source_files = options.rc_source_files,1439 .rc_source_files = options.rc_source_files,
...@@ -2095,13 +2095,13 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {...@@ -2095,13 +2095,13 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
2095 }2095 }
2096 }2096 }
20972097
2098 if (comp.module) |module| {2098 if (comp.module) |zcu| {
2099 module.compile_log_text.shrinkAndFree(gpa, 0);2099 zcu.compile_log_text.shrinkAndFree(gpa, 0);
21002100
2101 // Make sure std.zig is inside the import_table. We unconditionally need2101 // Make sure std.zig is inside the import_table. We unconditionally need
2102 // it for start.zig.2102 // it for start.zig.
2103 const std_mod = module.std_mod;2103 const std_mod = zcu.std_mod;
2104 _ = try module.importPkg(std_mod);2104 _ = try zcu.importPkg(std_mod);
21052105
2106 // Normally we rely on importing std to in turn import the root source file2106 // Normally we rely on importing std to in turn import the root source file
2107 // in the start code, but when using the stage1 backend that won't happen,2107 // 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 {...@@ -2110,64 +2110,65 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
2110 // Likewise, in the case of `zig test`, the test runner is the root source file,2110 // Likewise, in the case of `zig test`, the test runner is the root source file,
2111 // and so there is nothing to import the main file.2111 // and so there is nothing to import the main file.
2112 if (comp.config.is_test) {2112 if (comp.config.is_test) {
2113 _ = try module.importPkg(module.main_mod);2113 _ = try zcu.importPkg(zcu.main_mod);
2114 }2114 }
21152115
2116 if (module.root_mod.deps.get("compiler_rt")) |compiler_rt_mod| {2116 if (zcu.root_mod.deps.get("compiler_rt")) |compiler_rt_mod| {
2117 _ = try module.importPkg(compiler_rt_mod);2117 _ = try zcu.importPkg(compiler_rt_mod);
2118 }2118 }
21192119
2120 // Put a work item in for every known source file to detect if2120 // Put a work item in for every known source file to detect if
2121 // it changed, and, if so, re-compute ZIR and then queue the job2121 // it changed, and, if so, re-compute ZIR and then queue the job
2122 // to update it.2122 // to update it.
2123 try comp.astgen_work_queue.ensureUnusedCapacity(module.import_table.count());2123 try comp.astgen_work_queue.ensureUnusedCapacity(zcu.import_table.count());
2124 for (module.import_table.values()) |file| {2124 for (zcu.import_table.values(), 0..) |file, file_index_usize| {
2125 const file_index: Zcu.File.Index = @enumFromInt(file_index_usize);
2125 if (file.mod.isBuiltin()) continue;2126 if (file.mod.isBuiltin()) continue;
2126 comp.astgen_work_queue.writeItemAssumeCapacity(file);2127 comp.astgen_work_queue.writeItemAssumeCapacity(file_index);
2127 }2128 }
21282129
2129 // Put a work item in for checking if any files used with `@embedFile` changed.2130 // 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 try comp.embed_file_work_queue.ensureUnusedCapacity(zcu.embed_table.count());
2131 for (module.embed_table.values()) |embed_file| {2132 for (zcu.embed_table.values()) |embed_file| {
2132 comp.embed_file_work_queue.writeItemAssumeCapacity(embed_file);2133 comp.embed_file_work_queue.writeItemAssumeCapacity(embed_file);
2133 }2134 }
21342135
2135 try comp.work_queue.writeItem(.{ .analyze_mod = std_mod });2136 try comp.work_queue.writeItem(.{ .analyze_mod = std_mod });
2136 if (comp.config.is_test) {2137 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 });
2138 }2139 }
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| {
2141 try comp.work_queue.writeItem(.{ .analyze_mod = compiler_rt_mod });2142 try comp.work_queue.writeItem(.{ .analyze_mod = compiler_rt_mod });
2142 }2143 }
2143 }2144 }
21442145
2145 try comp.performAllTheWork(main_progress_node);2146 try comp.performAllTheWork(main_progress_node);
21462147
2147 if (comp.module) |module| {2148 if (comp.module) |zcu| {
2148 if (build_options.enable_debug_extensions and comp.verbose_intern_pool) {2149 if (build_options.enable_debug_extensions and comp.verbose_intern_pool) {
2149 std.debug.print("intern pool stats for '{s}':\n", .{2150 std.debug.print("intern pool stats for '{s}':\n", .{
2150 comp.root_name,2151 comp.root_name,
2151 });2152 });
2152 module.intern_pool.dump();2153 zcu.intern_pool.dump();
2153 }2154 }
21542155
2155 if (build_options.enable_debug_extensions and comp.verbose_generic_instances) {2156 if (build_options.enable_debug_extensions and comp.verbose_generic_instances) {
2156 std.debug.print("generic instances for '{s}:0x{x}':\n", .{2157 std.debug.print("generic instances for '{s}:0x{x}':\n", .{
2157 comp.root_name,2158 comp.root_name,
2158 @as(usize, @intFromPtr(module)),2159 @as(usize, @intFromPtr(zcu)),
2159 });2160 });
2160 module.intern_pool.dumpGenericInstances(gpa);2161 zcu.intern_pool.dumpGenericInstances(gpa);
2161 }2162 }
21622163
2163 if (comp.config.is_test and comp.totalErrorCount() == 0) {2164 if (comp.config.is_test and comp.totalErrorCount() == 0) {
2164 // The `test_functions` decl has been intentionally postponed until now,2165 // The `test_functions` decl has been intentionally postponed until now,
2165 // at which point we must populate it with the list of test functions that2166 // at which point we must populate it with the list of test functions that
2166 // have been discovered and not filtered out.2167 // have been discovered and not filtered out.
2167 try module.populateTestFunctions(main_progress_node);2168 try zcu.populateTestFunctions(main_progress_node);
2168 }2169 }
21692170
2170 try module.processExports();2171 try zcu.processExports();
2171 }2172 }
21722173
2173 if (comp.totalErrorCount() != 0) {2174 if (comp.totalErrorCount() != 0) {
...@@ -2615,7 +2616,9 @@ fn resolveEmitLoc(...@@ -2615,7 +2616,9 @@ fn resolveEmitLoc(
2615 return slice.ptr;2616 return slice.ptr;
2616}2617}
26172618
2618fn reportMultiModuleErrors(mod: *Module) !void {2619fn reportMultiModuleErrors(zcu: *Zcu) !void {
2620 const gpa = zcu.gpa;
2621 const ip = &zcu.intern_pool;
2619 // Some cases can give you a whole bunch of multi-module errors, which it's not helpful to2622 // Some cases can give you a whole bunch of multi-module errors, which it's not helpful to
2620 // print all of, so we'll cap the number of these to emit.2623 // print all of, so we'll cap the number of these to emit.
2621 var num_errors: u32 = 0;2624 var num_errors: u32 = 0;
...@@ -2623,37 +2626,39 @@ fn reportMultiModuleErrors(mod: *Module) !void {...@@ -2623,37 +2626,39 @@ fn reportMultiModuleErrors(mod: *Module) !void {
2623 // Attach the "some omitted" note to the final error message2626 // Attach the "some omitted" note to the final error message
2624 var last_err: ?*Module.ErrorMsg = null;2627 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| {
2627 if (!file.multi_pkg) continue;2630 if (!file.multi_pkg) continue;
26282631
2629 num_errors += 1;2632 num_errors += 1;
2630 if (num_errors > max_errors) continue;2633 if (num_errors > max_errors) continue;
26312634
2635 const file_index: Zcu.File.Index = @enumFromInt(file_index_usize);
2636
2632 const err = err_blk: {2637 const err = err_blk: {
2633 // Like with errors, let's cap the number of notes to prevent a huge error spew.2638 // Like with errors, let's cap the number of notes to prevent a huge error spew.
2634 const max_notes = 5;2639 const max_notes = 5;
2635 const omitted = file.references.items.len -| max_notes;2640 const omitted = file.references.items.len -| max_notes;
2636 const num_notes = file.references.items.len - omitted;2641 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);2643 const notes = try gpa.alloc(Module.ErrorMsg, if (omitted > 0) num_notes + 1 else num_notes);
2639 errdefer mod.gpa.free(notes);2644 errdefer gpa.free(notes);
26402645
2641 for (notes[0..num_notes], file.references.items[0..num_notes], 0..) |*note, ref, i| {2646 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);
2643 note.* = switch (ref) {2648 note.* = switch (ref) {
2644 .import => |import| try Module.ErrorMsg.init(2649 .import => |import| try Module.ErrorMsg.init(
2645 mod.gpa,2650 gpa,
2646 .{2651 .{
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),
2648 .offset = .{ .token_abs = import.token },2653 .offset = .{ .token_abs = import.token },
2649 },2654 },
2650 "imported from module {s}",2655 "imported from module {s}",
2651 .{import.file.mod.fully_qualified_name},2656 .{zcu.fileByIndex(import.file).mod.fully_qualified_name},
2652 ),2657 ),
2653 .root => |pkg| try Module.ErrorMsg.init(2658 .root => |pkg| try Module.ErrorMsg.init(
2654 mod.gpa,2659 gpa,
2655 .{2660 .{
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),
2657 .offset = .entire_file,2662 .offset = .entire_file,
2658 },2663 },
2659 "root of module {s}",2664 "root of module {s}",
...@@ -2661,25 +2666,25 @@ fn reportMultiModuleErrors(mod: *Module) !void {...@@ -2661,25 +2666,25 @@ fn reportMultiModuleErrors(mod: *Module) !void {
2661 ),2666 ),
2662 };2667 };
2663 }2668 }
2664 errdefer for (notes[0..num_notes]) |*n| n.deinit(mod.gpa);2669 errdefer for (notes[0..num_notes]) |*n| n.deinit(gpa);
26652670
2666 if (omitted > 0) {2671 if (omitted > 0) {
2667 notes[num_notes] = try Module.ErrorMsg.init(2672 notes[num_notes] = try Module.ErrorMsg.init(
2668 mod.gpa,2673 gpa,
2669 .{2674 .{
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),
2671 .offset = .entire_file,2676 .offset = .entire_file,
2672 },2677 },
2673 "{} more references omitted",2678 "{} more references omitted",
2674 .{omitted},2679 .{omitted},
2675 );2680 );
2676 }2681 }
2677 errdefer if (omitted > 0) notes[num_notes].deinit(mod.gpa);2682 errdefer if (omitted > 0) notes[num_notes].deinit(gpa);
26782683
2679 const err = try Module.ErrorMsg.create(2684 const err = try Module.ErrorMsg.create(
2680 mod.gpa,2685 gpa,
2681 .{2686 .{
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),
2683 .offset = .entire_file,2688 .offset = .entire_file,
2684 },2689 },
2685 "file exists in multiple modules",2690 "file exists in multiple modules",
...@@ -2688,8 +2693,8 @@ fn reportMultiModuleErrors(mod: *Module) !void {...@@ -2688,8 +2693,8 @@ fn reportMultiModuleErrors(mod: *Module) !void {
2688 err.notes = notes;2693 err.notes = notes;
2689 break :err_blk err;2694 break :err_blk err;
2690 };2695 };
2691 errdefer err.destroy(mod.gpa);2696 errdefer err.destroy(gpa);
2692 try mod.failed_files.putNoClobber(mod.gpa, file, err);2697 try zcu.failed_files.putNoClobber(gpa, file, err);
2693 last_err = err;2698 last_err = err;
2694 }2699 }
26952700
...@@ -2700,15 +2705,15 @@ fn reportMultiModuleErrors(mod: *Module) !void {...@@ -2700,15 +2705,15 @@ fn reportMultiModuleErrors(mod: *Module) !void {
2700 // There isn't really any meaningful place to put this note, so just attach it to the2705 // There isn't really any meaningful place to put this note, so just attach it to the
2701 // last failed file2706 // last failed file
2702 var note = try Module.ErrorMsg.init(2707 var note = try Module.ErrorMsg.init(
2703 mod.gpa,2708 gpa,
2704 err.src_loc,2709 err.src_loc,
2705 "{} more errors omitted",2710 "{} more errors omitted",
2706 .{num_errors - max_errors},2711 .{num_errors - max_errors},
2707 );2712 );
2708 errdefer note.deinit(mod.gpa);2713 errdefer note.deinit(gpa);
27092714
2710 const i = err.notes.len;2715 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);
2712 err.notes[i] = note;2717 err.notes[i] = note;
2713 }2718 }
27142719
...@@ -2719,8 +2724,8 @@ fn reportMultiModuleErrors(mod: *Module) !void {...@@ -2719,8 +2724,8 @@ fn reportMultiModuleErrors(mod: *Module) !void {
2719 // to add this flag after reporting the errors however, as otherwise2724 // to add this flag after reporting the errors however, as otherwise
2720 // we'd get an error for every single downstream file, which wouldn't be2725 // we'd get an error for every single downstream file, which wouldn't be
2721 // very useful.2726 // very useful.
2722 for (mod.import_table.values()) |file| {2727 for (zcu.import_table.values()) |file| {
2723 if (file.multi_pkg) file.recursiveMarkMultiPkg(mod);2728 if (file.multi_pkg) file.recursiveMarkMultiPkg(zcu);
2724 }2729 }
2725}2730}
27262731
...@@ -2752,6 +2757,7 @@ const Header = extern struct {...@@ -2752,6 +2757,7 @@ const Header = extern struct {
2752 first_dependency_len: u32,2757 first_dependency_len: u32,
2753 dep_entries_len: u32,2758 dep_entries_len: u32,
2754 free_dep_entries_len: u32,2759 free_dep_entries_len: u32,
2760 files_len: u32,
2755 },2761 },
2756};2762};
27572763
...@@ -2759,7 +2765,7 @@ const Header = extern struct {...@@ -2759,7 +2765,7 @@ const Header = extern struct {
2759/// saved, such as the target and most CLI flags. A cache hit will only occur2765/// saved, such as the target and most CLI flags. A cache hit will only occur
2760/// when subsequent compiler invocations use the same set of flags.2766/// when subsequent compiler invocations use the same set of flags.
2761pub fn saveState(comp: *Compilation) !void {2767pub 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;
2763 var bufs_len: usize = 0;2769 var bufs_len: usize = 0;
27642770
2765 const lf = comp.bin_file orelse return;2771 const lf = comp.bin_file orelse return;
...@@ -2780,6 +2786,7 @@ pub fn saveState(comp: *Compilation) !void {...@@ -2780,6 +2786,7 @@ pub fn saveState(comp: *Compilation) !void {
2780 .first_dependency_len = @intCast(ip.first_dependency.count()),2786 .first_dependency_len = @intCast(ip.first_dependency.count()),
2781 .dep_entries_len = @intCast(ip.dep_entries.items.len),2787 .dep_entries_len = @intCast(ip.dep_entries.items.len),
2782 .free_dep_entries_len = @intCast(ip.free_dep_entries.items.len),2788 .free_dep_entries_len = @intCast(ip.free_dep_entries.items.len),
2789 .files_len = @intCast(ip.files.entries.len),
2783 },2790 },
2784 };2791 };
2785 addBuf(&bufs_list, &bufs_len, mem.asBytes(&header));2792 addBuf(&bufs_list, &bufs_len, mem.asBytes(&header));
...@@ -2804,8 +2811,10 @@ pub fn saveState(comp: *Compilation) !void {...@@ -2804,8 +2811,10 @@ pub fn saveState(comp: *Compilation) !void {
2804 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.dep_entries.items));2811 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.dep_entries.items));
2805 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.free_dep_entries.items));2812 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
2807 // TODO: compilation errors2817 // TODO: compilation errors
2808 // TODO: files
2809 // TODO: namespaces2818 // TODO: namespaces
2810 // TODO: decls2819 // TODO: decls
2811 // TODO: linker state2820 // TODO: linker state
...@@ -2827,6 +2836,9 @@ pub fn saveState(comp: *Compilation) !void {...@@ -2827,6 +2836,9 @@ pub fn saveState(comp: *Compilation) !void {
2827}2836}
28282837
2829fn addBuf(bufs_list: []std.posix.iovec_const, bufs_len: *usize, buf: []const u8) void {2838fn 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
2830 const i = bufs_len.*;2842 const i = bufs_len.*;
2831 bufs_len.* = i + 1;2843 bufs_len.* = i + 1;
2832 bufs_list[i] = .{2844 bufs_list[i] = .{
...@@ -3350,16 +3362,31 @@ pub fn performAllTheWork(...@@ -3350,16 +3362,31 @@ pub fn performAllTheWork(
3350 }3362 }
3351 }3363 }
33523364
3353 while (comp.astgen_work_queue.readItem()) |file| {3365 if (comp.module) |zcu| {
3354 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerAstGenFile, .{3366 {
3355 comp, file, zir_prog_node, &comp.astgen_wait_group, .root,3367 // Worker threads may append to zcu.files and zcu.import_table
3356 });3368 // so we must hold the lock while spawning those tasks, since
3357 }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| {3373 while (comp.astgen_work_queue.readItem()) |file_index| {
3360 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerCheckEmbedFile, .{3374 // Pre-load these things from our single-threaded context since they
3361 comp, embed_file,3375 // will be needed by the worker threads.
3362 });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 }
3363 }3390 }
33643391
3365 while (comp.c_object_work_queue.readItem()) |c_object| {3392 while (comp.c_object_work_queue.readItem()) |c_object| {
...@@ -3423,8 +3450,8 @@ pub fn performAllTheWork(...@@ -3423,8 +3450,8 @@ pub fn performAllTheWork(
3423fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !void {3450fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !void {
3424 switch (job) {3451 switch (job) {
3425 .codegen_decl => |decl_index| {3452 .codegen_decl => |decl_index| {
3426 const module = comp.module.?;3453 const zcu = comp.module.?;
3427 const decl = module.declPtr(decl_index);3454 const decl = zcu.declPtr(decl_index);
34283455
3429 switch (decl.analysis) {3456 switch (decl.analysis) {
3430 .unreferenced => unreachable,3457 .unreferenced => unreachable,
...@@ -3442,7 +3469,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3442,7 +3469,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34423469
3443 assert(decl.has_tv);3470 assert(decl.has_tv);
34443471
3445 try module.linkerUpdateDecl(decl_index);3472 try zcu.linkerUpdateDecl(decl_index);
3446 return;3473 return;
3447 },3474 },
3448 }3475 }
...@@ -3451,16 +3478,16 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3451,16 +3478,16 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
3451 const named_frame = tracy.namedFrame("codegen_func");3478 const named_frame = tracy.namedFrame("codegen_func");
3452 defer named_frame.end();3479 defer named_frame.end();
34533480
3454 const module = comp.module.?;3481 const zcu = comp.module.?;
3455 // This call takes ownership of `func.air`.3482 // This call takes ownership of `func.air`.
3456 try module.linkerUpdateFunc(func.func, func.air);3483 try zcu.linkerUpdateFunc(func.func, func.air);
3457 },3484 },
3458 .analyze_func => |func| {3485 .analyze_func => |func| {
3459 const named_frame = tracy.namedFrame("analyze_func");3486 const named_frame = tracy.namedFrame("analyze_func");
3460 defer named_frame.end();3487 defer named_frame.end();
34613488
3462 const module = comp.module.?;3489 const zcu = comp.module.?;
3463 module.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {3490 zcu.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
3464 error.OutOfMemory => return error.OutOfMemory,3491 error.OutOfMemory => return error.OutOfMemory,
3465 error.AnalysisFail => return,3492 error.AnalysisFail => return,
3466 };3493 };
...@@ -3469,8 +3496,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3469,8 +3496,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
3469 if (true) @panic("regressed compiler feature: emit-h should hook into updateExports, " ++3496 if (true) @panic("regressed compiler feature: emit-h should hook into updateExports, " ++
3470 "not decl analysis, which is too early to know about @export calls");3497 "not decl analysis, which is too early to know about @export calls");
34713498
3472 const module = comp.module.?;3499 const zcu = comp.module.?;
3473 const decl = module.declPtr(decl_index);3500 const decl = zcu.declPtr(decl_index);
34743501
3475 switch (decl.analysis) {3502 switch (decl.analysis) {
3476 .unreferenced => unreachable,3503 .unreferenced => unreachable,
...@@ -3488,7 +3515,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3488,7 +3515,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
3488 defer named_frame.end();3515 defer named_frame.end();
34893516
3490 const gpa = comp.gpa;3517 const gpa = comp.gpa;
3491 const emit_h = module.emit_h.?;3518 const emit_h = zcu.emit_h.?;
3492 _ = try emit_h.decl_table.getOrPut(gpa, decl_index);3519 _ = try emit_h.decl_table.getOrPut(gpa, decl_index);
3493 const decl_emit_h = emit_h.declPtr(decl_index);3520 const decl_emit_h = emit_h.declPtr(decl_index);
3494 const fwd_decl = &decl_emit_h.fwd_decl;3521 const fwd_decl = &decl_emit_h.fwd_decl;
...@@ -3496,10 +3523,12 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3496,10 +3523,12 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
3496 var ctypes_arena = std.heap.ArenaAllocator.init(gpa);3523 var ctypes_arena = std.heap.ArenaAllocator.init(gpa);
3497 defer ctypes_arena.deinit();3524 defer ctypes_arena.deinit();
34983525
3526 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
3527
3499 var dg: c_codegen.DeclGen = .{3528 var dg: c_codegen.DeclGen = .{
3500 .gpa = gpa,3529 .gpa = gpa,
3501 .zcu = module,3530 .zcu = zcu,
3502 .mod = module.namespacePtr(decl.src_namespace).file_scope.mod,3531 .mod = file_scope.mod,
3503 .error_msg = null,3532 .error_msg = null,
3504 .pass = .{ .decl = decl_index },3533 .pass = .{ .decl = decl_index },
3505 .is_naked_fn = false,3534 .is_naked_fn = false,
...@@ -3528,17 +3557,17 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3528,17 +3557,17 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
3528 }3557 }
3529 },3558 },
3530 .analyze_decl => |decl_index| {3559 .analyze_decl => |decl_index| {
3531 const module = comp.module.?;3560 const zcu = comp.module.?;
3532 module.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {3561 zcu.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
3533 error.OutOfMemory => return error.OutOfMemory,3562 error.OutOfMemory => return error.OutOfMemory,
3534 error.AnalysisFail => return,3563 error.AnalysisFail => return,
3535 };3564 };
3536 const decl = module.declPtr(decl_index);3565 const decl = zcu.declPtr(decl_index);
3537 if (decl.kind == .@"test" and comp.config.is_test) {3566 if (decl.kind == .@"test" and comp.config.is_test) {
3538 // Tests are always emitted in test binaries. The decl_refs are created by3567 // Tests are always emitted in test binaries. The decl_refs are created by
3539 // Module.populateTestFunctions, but this will not queue body analysis, so do3568 // Zcu.populateTestFunctions, but this will not queue body analysis, so do
3540 // that now.3569 // that now.
3541 try module.ensureFuncBodyAnalysisQueued(decl.val.toIntern());3570 try zcu.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
3542 }3571 }
3543 },3572 },
3544 .resolve_type_fully => |ty| {3573 .resolve_type_fully => |ty| {
...@@ -3556,30 +3585,30 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo...@@ -3556,30 +3585,30 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
3556 defer named_frame.end();3585 defer named_frame.end();
35573586
3558 const gpa = comp.gpa;3587 const gpa = comp.gpa;
3559 const module = comp.module.?;3588 const zcu = comp.module.?;
3560 const decl = module.declPtr(decl_index);3589 const decl = zcu.declPtr(decl_index);
3561 const lf = comp.bin_file.?;3590 const lf = comp.bin_file.?;
3562 lf.updateDeclLineNumber(module, decl_index) catch |err| {3591 lf.updateDeclLineNumber(zcu, decl_index) catch |err| {
3563 try module.failed_analysis.ensureUnusedCapacity(gpa, 1);3592 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3564 module.failed_analysis.putAssumeCapacityNoClobber(3593 zcu.failed_analysis.putAssumeCapacityNoClobber(
3565 InternPool.AnalUnit.wrap(.{ .decl = decl_index }),3594 InternPool.AnalUnit.wrap(.{ .decl = decl_index }),
3566 try Module.ErrorMsg.create(3595 try Zcu.ErrorMsg.create(
3567 gpa,3596 gpa,
3568 decl.navSrcLoc(module),3597 decl.navSrcLoc(zcu),
3569 "unable to update line number: {s}",3598 "unable to update line number: {s}",
3570 .{@errorName(err)},3599 .{@errorName(err)},
3571 ),3600 ),
3572 );3601 );
3573 decl.analysis = .codegen_failure;3602 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 }));
3575 };3604 };
3576 },3605 },
3577 .analyze_mod => |pkg| {3606 .analyze_mod => |pkg| {
3578 const named_frame = tracy.namedFrame("analyze_mod");3607 const named_frame = tracy.namedFrame("analyze_mod");
3579 defer named_frame.end();3608 defer named_frame.end();
35803609
3581 const module = comp.module.?;3610 const zcu = comp.module.?;
3582 module.semaPkg(pkg) catch |err| switch (err) {3611 zcu.semaPkg(pkg) catch |err| switch (err) {
3583 error.OutOfMemory => return error.OutOfMemory,3612 error.OutOfMemory => return error.OutOfMemory,
3584 error.AnalysisFail => return,3613 error.AnalysisFail => return,
3585 };3614 };
...@@ -4012,14 +4041,17 @@ fn workerDocsWasmFallible(comp: *Compilation, prog_node: std.Progress.Node) anye...@@ -4012,14 +4041,17 @@ fn workerDocsWasmFallible(comp: *Compilation, prog_node: std.Progress.Node) anye
4012const AstGenSrc = union(enum) {4041const AstGenSrc = union(enum) {
4013 root,4042 root,
4014 import: struct {4043 import: struct {
4015 importing_file: *Module.File,4044 importing_file: Zcu.File.Index,
4016 import_tok: std.zig.Ast.TokenIndex,4045 import_tok: std.zig.Ast.TokenIndex,
4017 },4046 },
4018};4047};
40194048
4020fn workerAstGenFile(4049fn workerAstGenFile(
4021 comp: *Compilation,4050 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,
4023 prog_node: std.Progress.Node,4055 prog_node: std.Progress.Node,
4024 wg: *WaitGroup,4056 wg: *WaitGroup,
4025 src: AstGenSrc,4057 src: AstGenSrc,
...@@ -4027,12 +4059,12 @@ fn workerAstGenFile(...@@ -4027,12 +4059,12 @@ fn workerAstGenFile(
4027 const child_prog_node = prog_node.start(file.sub_file_path, 0);4059 const child_prog_node = prog_node.start(file.sub_file_path, 0);
4028 defer child_prog_node.end();4060 defer child_prog_node.end();
40294061
4030 const mod = comp.module.?;4062 const zcu = comp.module.?;
4031 mod.astGenFile(file) catch |err| switch (err) {4063 zcu.astGenFile(file, file_index, path_digest, root_decl) catch |err| switch (err) {
4032 error.AnalysisFail => return,4064 error.AnalysisFail => return,
4033 else => {4065 else => {
4034 file.status = .retryable_failure;4066 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) {
4036 // Swallowing this error is OK because it's implied to be OOM when4068 // Swallowing this error is OK because it's implied to be OOM when
4037 // there is a missing `failed_files` error message.4069 // there is a missing `failed_files` error message.
4038 error.OutOfMemory => {},4070 error.OutOfMemory => {},
...@@ -4059,29 +4091,31 @@ fn workerAstGenFile(...@@ -4059,29 +4091,31 @@ fn workerAstGenFile(
4059 // `@import("builtin")` is handled specially.4091 // `@import("builtin")` is handled specially.
4060 if (mem.eql(u8, import_path, "builtin")) continue;4092 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: {
4063 comp.mutex.lock();4095 comp.mutex.lock();
4064 defer comp.mutex.unlock();4096 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;
4067 if (!res.is_pkg) {4099 if (!res.is_pkg) {
4068 res.file.addReference(mod.*, .{ .import = .{4100 res.file.addReference(zcu.*, .{ .import = .{
4069 .file = file,4101 .file = file_index,
4070 .token = item.data.token,4102 .token = item.data.token,
4071 } }) catch continue;4103 } }) catch continue;
4072 }4104 }
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 };
4074 };4108 };
4075 if (import_result.is_new) {4109 if (import_result.is_new) {
4076 log.debug("AstGen of {s} has import '{s}'; queuing AstGen of {s}", .{4110 log.debug("AstGen of {s} has import '{s}'; queuing AstGen of {s}", .{
4077 file.sub_file_path, import_path, import_result.file.sub_file_path,4111 file.sub_file_path, import_path, import_result.file.sub_file_path,
4078 });4112 });
4079 const sub_src: AstGenSrc = .{ .import = .{4113 const sub_src: AstGenSrc = .{ .import = .{
4080 .importing_file = file,4114 .importing_file = file_index,
4081 .import_tok = item.data.token,4115 .import_tok = item.data.token,
4082 } };4116 } };
4083 comp.thread_pool.spawnWg(wg, workerAstGenFile, .{4117 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,
4085 });4119 });
4086 }4120 }
4087 }4121 }
...@@ -4432,21 +4466,22 @@ fn reportRetryableWin32ResourceError(...@@ -4432,21 +4466,22 @@ fn reportRetryableWin32ResourceError(
4432fn reportRetryableAstGenError(4466fn reportRetryableAstGenError(
4433 comp: *Compilation,4467 comp: *Compilation,
4434 src: AstGenSrc,4468 src: AstGenSrc,
4435 file: *Module.File,4469 file_index: Zcu.File.Index,
4436 err: anyerror,4470 err: anyerror,
4437) error{OutOfMemory}!void {4471) error{OutOfMemory}!void {
4438 const mod = comp.module.?;4472 const zcu = comp.module.?;
4439 const gpa = mod.gpa;4473 const gpa = zcu.gpa;
44404474
4475 const file = zcu.fileByIndex(file_index);
4441 file.status = .retryable_failure;4476 file.status = .retryable_failure;
44424477
4443 const src_loc: Module.LazySrcLoc = switch (src) {4478 const src_loc: Module.LazySrcLoc = switch (src) {
4444 .root => .{4479 .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),
4446 .offset = .entire_file,4481 .offset = .entire_file,
4447 },4482 },
4448 .import => |info| .{4483 .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),
4450 .offset = .{ .token_abs = info.import_tok },4485 .offset = .{ .token_abs = info.import_tok },
4451 },4486 },
4452 };4487 };
...@@ -4459,7 +4494,7 @@ fn reportRetryableAstGenError(...@@ -4459,7 +4494,7 @@ fn reportRetryableAstGenError(
4459 {4494 {
4460 comp.mutex.lock();4495 comp.mutex.lock();
4461 defer comp.mutex.unlock();4496 defer comp.mutex.unlock();
4462 try mod.failed_files.putNoClobber(gpa, file, err_msg);4497 try zcu.failed_files.putNoClobber(gpa, file, err_msg);
4463 }4498 }
4464}4499}
44654500
src/InternPool.zig+26-4
...@@ -92,12 +92,27 @@ dep_entries: std.ArrayListUnmanaged(DepEntry) = .{},...@@ -92,12 +92,27 @@ dep_entries: std.ArrayListUnmanaged(DepEntry) = .{},
92/// garbage collection pass.92/// garbage collection pass.
93free_dep_entries: std.ArrayListUnmanaged(DepEntry.Index) = .{},93free_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
95pub const TrackedInst = extern struct {110pub const TrackedInst = extern struct {
96 path_digest: Cache.BinDigest,111 file: FileIndex,
97 inst: Zir.Inst.Index,112 inst: Zir.Inst.Index,
98 comptime {113 comptime {
99 // The fields should be tightly packed. See also serialiation logic in `Compilation.saveState`.114 // 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));
101 }116 }
102 pub const Index = enum(u32) {117 pub const Index = enum(u32) {
103 _,118 _,
...@@ -123,9 +138,14 @@ pub const TrackedInst = extern struct {...@@ -123,9 +138,14 @@ pub const TrackedInst = extern struct {
123 };138 };
124};139};
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 {
127 const key: TrackedInst = .{147 const key: TrackedInst = .{
128 .path_digest = file.path_digest,148 .file = file,
129 .inst = inst,149 .inst = inst,
130 };150 };
131 const gop = try ip.tracked_insts.getOrPut(gpa, key);151 const gop = try ip.tracked_insts.getOrPut(gpa, key);
...@@ -4592,6 +4612,8 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {...@@ -4592,6 +4612,8 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
4592 ip.dep_entries.deinit(gpa);4612 ip.dep_entries.deinit(gpa);
4593 ip.free_dep_entries.deinit(gpa);4613 ip.free_dep_entries.deinit(gpa);
45944614
4615 ip.files.deinit(gpa);
4616
4595 ip.* = undefined;4617 ip.* = undefined;
4596}4618}
45974619
src/Package/Module.zig+2-6
...@@ -379,7 +379,7 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {...@@ -379,7 +379,7 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {
379379
380 const new_file = try arena.create(File);380 const new_file = try arena.create(File);
381381
382 const bin_digest, const hex_digest = digest: {382 const hex_digest = digest: {
383 var hasher: Cache.Hasher = Cache.hasher_init;383 var hasher: Cache.Hasher = Cache.hasher_init;
384 hasher.update(generated_builtin_source);384 hasher.update(generated_builtin_source);
385385
...@@ -393,7 +393,7 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {...@@ -393,7 +393,7 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {
393 .{std.fmt.fmtSliceHexLower(&bin_digest)},393 .{std.fmt.fmtSliceHexLower(&bin_digest)},
394 ) catch unreachable;394 ) catch unreachable;
395395
396 break :digest .{ bin_digest, hex_digest };396 break :digest hex_digest;
397 };397 };
398398
399 const builtin_sub_path = try arena.dupe(u8, "b" ++ std.fs.path.sep_str ++ hex_digest);399 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 {...@@ -443,10 +443,6 @@ pub fn create(arena: Allocator, options: CreateOptions) !*Package.Module {
443 .zir = undefined,443 .zir = undefined,
444 .status = .never_loaded,444 .status = .never_loaded,
445 .mod = new,445 .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,
450 };446 };
451 break :b new;447 break :b new;
452 };448 };
src/Sema.zig+123-106
...@@ -546,8 +546,12 @@ pub const Block = struct {...@@ -546,8 +546,12 @@ pub const Block = struct {
546 };546 };
547 }547 }
548548
549 pub fn getFileScope(block: *Block, mod: *Module) *Module.File {549 pub fn getFileScope(block: *Block, zcu: *Zcu) *Zcu.File {
550 return mod.namespacePtr(block.namespace).file_scope;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;
551 }555 }
552556
553 fn addTy(557 fn addTy(
...@@ -826,7 +830,16 @@ pub const Block = struct {...@@ -826,7 +830,16 @@ pub const Block = struct {
826830
827 pub fn ownerModule(block: Block) *Package.Module {831 pub fn ownerModule(block: Block) *Package.Module {
828 const zcu = block.sema.mod;832 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);
830 }843 }
831};844};
832845
...@@ -979,7 +992,7 @@ fn analyzeBodyInner(...@@ -979,7 +992,7 @@ fn analyzeBodyInner(
979992
980 try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);993 try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);
981994
982 const mod = sema.mod;995 const zcu = sema.mod;
983 const map = &sema.inst_map;996 const map = &sema.inst_map;
984 const tags = sema.code.instructions.items(.tag);997 const tags = sema.code.instructions.items(.tag);
985 const datas = sema.code.instructions.items(.data);998 const datas = sema.code.instructions.items(.data);
...@@ -999,9 +1012,9 @@ fn analyzeBodyInner(...@@ -999,9 +1012,9 @@ fn analyzeBodyInner(
999 // The hashmap lookup in here is a little expensive, and LLVM fails to optimize it away.1012 // The hashmap lookup in here is a little expensive, and LLVM fails to optimize it away.
1000 if (build_options.enable_logging) {1013 if (build_options.enable_logging) {
1001 std.log.scoped(.sema_zir).debug("sema ZIR {s} %{d}", .{ sub_file_path: {1014 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;1015 const file_index = block.src_base_inst.resolveFull(&zcu.intern_pool).file;
1003 const index = mod.path_digest_map.getIndex(path_digest).?;1016 const file = zcu.fileByIndex(file_index);
1004 break :sub_file_path mod.import_table.values()[index].sub_file_path;1017 break :sub_file_path file.sub_file_path;
1005 }, inst });1018 }, inst });
1006 }1019 }
10071020
...@@ -1762,9 +1775,9 @@ fn analyzeBodyInner(...@@ -1762,9 +1775,9 @@ fn analyzeBodyInner(
1762 const inline_body = sema.code.bodySlice(extra.end, extra.data.body_len);1775 const inline_body = sema.code.bodySlice(extra.end, extra.data.body_len);
1763 const err_union = try sema.resolveInst(extra.data.operand);1776 const err_union = try sema.resolveInst(extra.data.operand);
1764 const err_union_ty = sema.typeOf(err_union);1777 const err_union_ty = sema.typeOf(err_union);
1765 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {1778 if (err_union_ty.zigTypeTag(zcu) != .ErrorUnion) {
1766 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{1779 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
1767 err_union_ty.fmt(mod),1780 err_union_ty.fmt(zcu),
1768 });1781 });
1769 }1782 }
1770 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);1783 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
...@@ -2730,7 +2743,7 @@ fn zirStructDecl(...@@ -2730,7 +2743,7 @@ fn zirStructDecl(
2730 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);2743 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
2731 const extra = sema.code.extraData(Zir.Inst.StructDecl, extended.operand);2744 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);
2734 const src: LazySrcLoc = .{2747 const src: LazySrcLoc = .{
2735 .base_node_inst = tracked_inst,2748 .base_node_inst = tracked_inst,
2736 .offset = LazySrcLoc.Offset.nodeOffset(0),2749 .offset = LazySrcLoc.Offset.nodeOffset(0),
...@@ -2806,7 +2819,7 @@ fn zirStructDecl(...@@ -2806,7 +2819,7 @@ fn zirStructDecl(
2806 try ip.addDependency(2819 try ip.addDependency(
2807 sema.gpa,2820 sema.gpa,
2808 AnalUnit.wrap(.{ .decl = new_decl_index }),2821 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) },
2810 );2823 );
2811 }2824 }
28122825
...@@ -2814,7 +2827,7 @@ fn zirStructDecl(...@@ -2814,7 +2827,7 @@ fn zirStructDecl(
2814 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{2827 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{
2815 .parent = block.namespace.toOptional(),2828 .parent = block.namespace.toOptional(),
2816 .decl_index = new_decl_index,2829 .decl_index = new_decl_index,
2817 .file_scope = block.getFileScope(mod),2830 .file_scope = block.getFileScopeIndex(mod),
2818 })).toOptional() else .none;2831 })).toOptional() else .none;
2819 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);2832 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
28202833
...@@ -2947,7 +2960,7 @@ fn zirEnumDecl(...@@ -2947,7 +2960,7 @@ fn zirEnumDecl(
2947 const extra = sema.code.extraData(Zir.Inst.EnumDecl, extended.operand);2960 const extra = sema.code.extraData(Zir.Inst.EnumDecl, extended.operand);
2948 var extra_index: usize = extra.end;2961 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);
2951 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };2964 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };
2952 const tag_ty_src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = .{ .node_offset_container_tag = 0 } };2965 const tag_ty_src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = .{ .node_offset_container_tag = 0 } };
29532966
...@@ -3040,9 +3053,9 @@ fn zirEnumDecl(...@@ -3040,9 +3053,9 @@ fn zirEnumDecl(
30403053
3041 if (sema.mod.comp.debug_incremental) {3054 if (sema.mod.comp.debug_incremental) {
3042 try mod.intern_pool.addDependency(3055 try mod.intern_pool.addDependency(
3043 sema.gpa,3056 gpa,
3044 AnalUnit.wrap(.{ .decl = new_decl_index }),3057 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) },
3046 );3059 );
3047 }3060 }
30483061
...@@ -3050,7 +3063,7 @@ fn zirEnumDecl(...@@ -3050,7 +3063,7 @@ fn zirEnumDecl(
3050 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{3063 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{
3051 .parent = block.namespace.toOptional(),3064 .parent = block.namespace.toOptional(),
3052 .decl_index = new_decl_index,3065 .decl_index = new_decl_index,
3053 .file_scope = block.getFileScope(mod),3066 .file_scope = block.getFileScopeIndex(mod),
3054 })).toOptional() else .none;3067 })).toOptional() else .none;
3055 errdefer if (!done) if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);3068 errdefer if (!done) if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
30563069
...@@ -3232,7 +3245,7 @@ fn zirUnionDecl(...@@ -3232,7 +3245,7 @@ fn zirUnionDecl(
3232 const extra = sema.code.extraData(Zir.Inst.UnionDecl, extended.operand);3245 const extra = sema.code.extraData(Zir.Inst.UnionDecl, extended.operand);
3233 var extra_index: usize = extra.end;3246 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);
3236 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };3249 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };
32373250
3238 extra_index += @intFromBool(small.has_tag_type);3251 extra_index += @intFromBool(small.has_tag_type);
...@@ -3306,9 +3319,9 @@ fn zirUnionDecl(...@@ -3306,9 +3319,9 @@ fn zirUnionDecl(
33063319
3307 if (sema.mod.comp.debug_incremental) {3320 if (sema.mod.comp.debug_incremental) {
3308 try mod.intern_pool.addDependency(3321 try mod.intern_pool.addDependency(
3309 sema.gpa,3322 gpa,
3310 AnalUnit.wrap(.{ .decl = new_decl_index }),3323 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) },
3312 );3325 );
3313 }3326 }
33143327
...@@ -3316,7 +3329,7 @@ fn zirUnionDecl(...@@ -3316,7 +3329,7 @@ fn zirUnionDecl(
3316 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{3329 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (true or decls_len > 0) (try mod.createNamespace(.{
3317 .parent = block.namespace.toOptional(),3330 .parent = block.namespace.toOptional(),
3318 .decl_index = new_decl_index,3331 .decl_index = new_decl_index,
3319 .file_scope = block.getFileScope(mod),3332 .file_scope = block.getFileScopeIndex(mod),
3320 })).toOptional() else .none;3333 })).toOptional() else .none;
3321 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);3334 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
33223335
...@@ -3348,7 +3361,7 @@ fn zirOpaqueDecl(...@@ -3348,7 +3361,7 @@ fn zirOpaqueDecl(
3348 const extra = sema.code.extraData(Zir.Inst.OpaqueDecl, extended.operand);3361 const extra = sema.code.extraData(Zir.Inst.OpaqueDecl, extended.operand);
3349 var extra_index: usize = extra.end;3362 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);
3352 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };3365 const src: LazySrcLoc = .{ .base_node_inst = tracked_inst, .offset = LazySrcLoc.Offset.nodeOffset(0) };
33533366
3354 const captures_len = if (small.has_captures_len) blk: {3367 const captures_len = if (small.has_captures_len) blk: {
...@@ -3397,14 +3410,14 @@ fn zirOpaqueDecl(...@@ -3397,14 +3410,14 @@ fn zirOpaqueDecl(
3397 try ip.addDependency(3410 try ip.addDependency(
3398 gpa,3411 gpa,
3399 AnalUnit.wrap(.{ .decl = new_decl_index }),3412 AnalUnit.wrap(.{ .decl = new_decl_index }),
3400 .{ .src_hash = try ip.trackZir(gpa, block.getFileScope(mod), inst) },3413 .{ .src_hash = try block.trackZir(inst) },
3401 );3414 );
3402 }3415 }
34033416
3404 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (decls_len > 0) (try mod.createNamespace(.{3417 const new_namespace_index: InternPool.OptionalNamespaceIndex = if (decls_len > 0) (try mod.createNamespace(.{
3405 .parent = block.namespace.toOptional(),3418 .parent = block.namespace.toOptional(),
3406 .decl_index = new_decl_index,3419 .decl_index = new_decl_index,
3407 .file_scope = block.getFileScope(mod),3420 .file_scope = block.getFileScopeIndex(mod),
3408 })).toOptional() else .none;3421 })).toOptional() else .none;
3409 errdefer if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);3422 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...@@ -5893,8 +5906,8 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
5893 const tracy = trace(@src());5906 const tracy = trace(@src());
5894 defer tracy.end();5907 defer tracy.end();
58955908
5896 const mod = sema.mod;5909 const zcu = sema.mod;
5897 const comp = mod.comp;5910 const comp = zcu.comp;
5898 const gpa = sema.gpa;5911 const gpa = sema.gpa;
5899 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;5912 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
5900 const src = parent_block.nodeOffset(pl_node.src_node);5913 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...@@ -5940,7 +5953,7 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
5940 if (!comp.config.link_libc)5953 if (!comp.config.link_libc)
5941 try sema.errNote(src, msg, "libc headers not available; compilation does not link against libc", .{});5954 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());
5944 if (!gop.found_existing) {5957 if (!gop.found_existing) {
5945 gop.value_ptr.* = c_import_res.errors;5958 gop.value_ptr.* = c_import_res.errors;
5946 c_import_res.errors = std.zig.ErrorBundle.empty;5959 c_import_res.errors = std.zig.ErrorBundle.empty;
...@@ -5984,14 +5997,16 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr...@@ -5984,14 +5997,16 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
5984 else => |e| return e,5997 else => |e| return e,
5985 };5998 };
59865999
5987 const result = mod.importPkg(c_import_mod) catch |err|6000 const result = zcu.importPkg(c_import_mod) catch |err|
5988 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});6001 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|
5991 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});6006 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
59926007
5993 try mod.ensureFileAnalyzed(result.file);6008 try zcu.ensureFileAnalyzed(result.file_index);
5994 const file_root_decl_index = result.file.root_decl.unwrap().?;6009 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
5995 return sema.analyzeDeclVal(parent_block, src, file_root_decl_index);6010 return sema.analyzeDeclVal(parent_block, src, file_root_decl_index);
5996}6011}
59976012
...@@ -6730,7 +6745,9 @@ fn lookupInNamespace(...@@ -6730,7 +6745,9 @@ fn lookupInNamespace(
6730 // Skip decls which are not marked pub, which are in a different6745 // Skip decls which are not marked pub, which are in a different
6731 // file than the `a.b`/`@hasDecl` syntax.6746 // file than the `a.b`/`@hasDecl` syntax.
6732 const decl = mod.declPtr(decl_index);6747 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 {
6734 try candidates.append(gpa, decl_index);6751 try candidates.append(gpa, decl_index);
6735 }6752 }
6736 }6753 }
...@@ -6741,7 +6758,7 @@ fn lookupInNamespace(...@@ -6741,7 +6758,7 @@ fn lookupInNamespace(
6741 if (sub_usingnamespace_decl_index == sema.owner_decl_index) continue;6758 if (sub_usingnamespace_decl_index == sema.owner_decl_index) continue;
6742 const sub_usingnamespace_decl = mod.declPtr(sub_usingnamespace_decl_index);6759 const sub_usingnamespace_decl = mod.declPtr(sub_usingnamespace_decl_index);
6743 const sub_is_pub = entry.value_ptr.*;6760 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)) {
6745 // Skip usingnamespace decls which are not marked pub, which are in6762 // Skip usingnamespace decls which are not marked pub, which are in
6746 // a different file than the `a.b`/`@hasDecl` syntax.6763 // a different file than the `a.b`/`@hasDecl` syntax.
6747 continue;6764 continue;
...@@ -6749,7 +6766,7 @@ fn lookupInNamespace(...@@ -6749,7 +6766,7 @@ fn lookupInNamespace(
6749 try sema.ensureDeclAnalyzed(sub_usingnamespace_decl_index);6766 try sema.ensureDeclAnalyzed(sub_usingnamespace_decl_index);
6750 const ns_ty = sub_usingnamespace_decl.val.toType();6767 const ns_ty = sub_usingnamespace_decl.val.toType();
6751 const sub_ns = mod.namespacePtrUnwrap(ns_ty.getNamespaceIndex(mod)) orelse continue;6768 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));
6753 }6770 }
6754 }6771 }
67556772
...@@ -8067,20 +8084,20 @@ fn instantiateGenericCall(...@@ -8067,20 +8084,20 @@ fn instantiateGenericCall(
8067 call_tag: Air.Inst.Tag,8084 call_tag: Air.Inst.Tag,
8068 call_dbg_node: ?Zir.Inst.Index,8085 call_dbg_node: ?Zir.Inst.Index,
8069) CompileError!Air.Inst.Ref {8086) CompileError!Air.Inst.Ref {
8070 const mod = sema.mod;8087 const zcu = sema.mod;
8071 const gpa = sema.gpa;8088 const gpa = sema.gpa;
8072 const ip = &mod.intern_pool;8089 const ip = &zcu.intern_pool;
80738090
8074 const func_val = try sema.resolveConstDefinedValue(block, func_src, func, .{8091 const func_val = try sema.resolveConstDefinedValue(block, func_src, func, .{
8075 .needed_comptime_reason = "generic function being called must be comptime-known",8092 .needed_comptime_reason = "generic function being called must be comptime-known",
8076 });8093 });
8077 const generic_owner = switch (mod.intern_pool.indexToKey(func_val.toIntern())) {8094 const generic_owner = switch (zcu.intern_pool.indexToKey(func_val.toIntern())) {
8078 .func => func_val.toIntern(),8095 .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(),
8080 else => unreachable,8097 else => unreachable,
8081 };8098 };
8082 const generic_owner_func = mod.intern_pool.indexToKey(generic_owner).func;8099 const generic_owner_func = zcu.intern_pool.indexToKey(generic_owner).func;
8083 const generic_owner_ty_info = mod.typeToFunc(Type.fromInterned(generic_owner_func.ty)).?;8100 const generic_owner_ty_info = zcu.typeToFunc(Type.fromInterned(generic_owner_func.ty)).?;
80848101
8085 try sema.declareDependency(.{ .src_hash = generic_owner_func.zir_body_inst });8102 try sema.declareDependency(.{ .src_hash = generic_owner_func.zir_body_inst });
80868103
...@@ -8092,10 +8109,10 @@ fn instantiateGenericCall(...@@ -8092,10 +8109,10 @@ fn instantiateGenericCall(
8092 // The actual monomorphization happens via adding `func_instance` to8109 // The actual monomorphization happens via adding `func_instance` to
8093 // `InternPool`.8110 // `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);
8096 const namespace_index = fn_owner_decl.src_namespace;8113 const namespace_index = fn_owner_decl.src_namespace;
8097 const namespace = mod.namespacePtr(namespace_index);8114 const namespace = zcu.namespacePtr(namespace_index);
8098 const fn_zir = namespace.file_scope.zir;8115 const fn_zir = namespace.fileScope(zcu).zir;
8099 const fn_info = fn_zir.getFnInfo(generic_owner_func.zir_body_inst.resolve(ip));8116 const fn_info = fn_zir.getFnInfo(generic_owner_func.zir_body_inst.resolve(ip));
81008117
8101 const comptime_args = try sema.arena.alloc(InternPool.Index, args_info.count());8118 const comptime_args = try sema.arena.alloc(InternPool.Index, args_info.count());
...@@ -8110,7 +8127,7 @@ fn instantiateGenericCall(...@@ -8110,7 +8127,7 @@ fn instantiateGenericCall(
8110 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a8127 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
8111 // new, monomorphized function, with the comptime parameters elided.8128 // new, monomorphized function, with the comptime parameters elided.
8112 var child_sema: Sema = .{8129 var child_sema: Sema = .{
8113 .mod = mod,8130 .mod = zcu,
8114 .gpa = gpa,8131 .gpa = gpa,
8115 .arena = sema.arena,8132 .arena = sema.arena,
8116 .code = fn_zir,8133 .code = fn_zir,
...@@ -8199,7 +8216,7 @@ fn instantiateGenericCall(...@@ -8199,7 +8216,7 @@ fn instantiateGenericCall(
8199 const arg_ref = try args_info.analyzeArg(sema, block, arg_index, param_ty, generic_owner_ty_info, func);8216 const arg_ref = try args_info.analyzeArg(sema, block, arg_index, param_ty, generic_owner_ty_info, func);
8200 try sema.validateRuntimeValue(block, args_info.argSrc(block, arg_index), arg_ref);8217 try sema.validateRuntimeValue(block, args_info.argSrc(block, arg_index), arg_ref);
8201 const arg_ty = sema.typeOf(arg_ref);8218 const arg_ty = sema.typeOf(arg_ref);
8202 if (arg_ty.zigTypeTag(mod) == .NoReturn) {8219 if (arg_ty.zigTypeTag(zcu) == .NoReturn) {
8203 // This terminates argument analysis.8220 // This terminates argument analysis.
8204 return arg_ref;8221 return arg_ref;
8205 }8222 }
...@@ -8283,12 +8300,12 @@ fn instantiateGenericCall(...@@ -8283,12 +8300,12 @@ fn instantiateGenericCall(
8283 const new_func_inst = try child_sema.resolveInlineBody(&child_block, fn_info.param_body[args_info.count()..], fn_info.param_body_inst);8300 const new_func_inst = try child_sema.resolveInlineBody(&child_block, fn_info.param_body[args_info.count()..], fn_info.param_body_inst);
8284 const callee_index = (child_sema.resolveConstDefinedValue(&child_block, LazySrcLoc.unneeded, new_func_inst, undefined) catch unreachable).toIntern();8301 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);
8287 callee.branchQuota(ip).* = @max(callee.branchQuota(ip).*, sema.branch_quota);8304 callee.branchQuota(ip).* = @max(callee.branchQuota(ip).*, sema.branch_quota);
82888305
8289 // Make a runtime call to the new function, making sure to omit the comptime args.8306 // Make a runtime call to the new function, making sure to omit the comptime args.
8290 const func_ty = Type.fromInterned(callee.ty);8307 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
8293 // If the call evaluated to a return type that requires comptime, never mind8310 // If the call evaluated to a return type that requires comptime, never mind
8294 // our generic instantiation. Instead we need to perform a comptime call.8311 // our generic instantiation. Instead we need to perform a comptime call.
...@@ -8304,13 +8321,13 @@ fn instantiateGenericCall(...@@ -8304,13 +8321,13 @@ fn instantiateGenericCall(
8304 if (call_dbg_node) |some| try sema.zirDbgStmt(block, some);8321 if (call_dbg_node) |some| try sema.zirDbgStmt(block, some);
83058322
8306 if (sema.owner_func_index != .none and8323 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))
8308 {8325 {
8309 ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn = true;8326 ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn = true;
8310 }8327 }
83118328
8312 try sema.addReferenceEntry(call_src, AnalUnit.wrap(.{ .func = callee_index }));8329 try sema.addReferenceEntry(call_src, AnalUnit.wrap(.{ .func = callee_index }));
8313 try mod.ensureFuncBodyAnalysisQueued(callee_index);8330 try zcu.ensureFuncBodyAnalysisQueued(callee_index);
83148331
8315 try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.Call).Struct.fields.len + runtime_args.items.len);8332 try sema.air_extra.ensureUnusedCapacity(sema.gpa, @typeInfo(Air.Call).Struct.fields.len + runtime_args.items.len);
8316 const result = try block.addInst(.{8333 const result = try block.addInst(.{
...@@ -8333,7 +8350,7 @@ fn instantiateGenericCall(...@@ -8333,7 +8350,7 @@ fn instantiateGenericCall(
8333 if (call_tag == .call_always_tail) {8350 if (call_tag == .call_always_tail) {
8334 return sema.handleTailCall(block, call_src, func_ty, result);8351 return sema.handleTailCall(block, call_src, func_ty, result);
8335 }8352 }
8336 if (func_ty.fnReturnType(mod).isNoReturn(mod)) {8353 if (func_ty.fnReturnType(zcu).isNoReturn(zcu)) {
8337 _ = try block.addNoOp(.unreach);8354 _ = try block.addNoOp(.unreach);
8338 return .unreachable_value;8355 return .unreachable_value;
8339 }8356 }
...@@ -9653,7 +9670,7 @@ fn funcCommon(...@@ -9653,7 +9670,7 @@ fn funcCommon(
9653 .is_generic = final_is_generic,9670 .is_generic = final_is_generic,
9654 .is_noinline = is_noinline,9671 .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),
9657 .lbrace_line = src_locs.lbrace_line,9674 .lbrace_line = src_locs.lbrace_line,
9658 .rbrace_line = src_locs.rbrace_line,9675 .rbrace_line = src_locs.rbrace_line,
9659 .lbrace_column = @as(u16, @truncate(src_locs.columns)),9676 .lbrace_column = @as(u16, @truncate(src_locs.columns)),
...@@ -9731,7 +9748,7 @@ fn funcCommon(...@@ -9731,7 +9748,7 @@ fn funcCommon(
9731 .ty = func_ty,9748 .ty = func_ty,
9732 .cc = cc,9749 .cc = cc,
9733 .is_noinline = is_noinline,9750 .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),
9735 .lbrace_line = src_locs.lbrace_line,9752 .lbrace_line = src_locs.lbrace_line,
9736 .rbrace_line = src_locs.rbrace_line,9753 .rbrace_line = src_locs.rbrace_line,
9737 .lbrace_column = @as(u16, @truncate(src_locs.columns)),9754 .lbrace_column = @as(u16, @truncate(src_locs.columns)),
...@@ -13787,18 +13804,18 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air....@@ -13787,18 +13804,18 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
13787 const tracy = trace(@src());13804 const tracy = trace(@src());
13788 defer tracy.end();13805 defer tracy.end();
1378913806
13790 const mod = sema.mod;13807 const zcu = sema.mod;
13791 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;13808 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
13792 const operand_src = block.tokenOffset(inst_data.src_tok);13809 const operand_src = block.tokenOffset(inst_data.src_tok);
13793 const operand = inst_data.get(sema.code);13810 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) {
13796 error.ImportOutsideModulePath => {13813 error.ImportOutsideModulePath => {
13797 return sema.fail(block, operand_src, "import of file outside module path: '{s}'", .{operand});13814 return sema.fail(block, operand_src, "import of file outside module path: '{s}'", .{operand});
13798 },13815 },
13799 error.ModuleNotFound => {13816 error.ModuleNotFound => {
13800 return sema.fail(block, operand_src, "no module named '{s}' available within module {s}", .{13817 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,
13802 });13819 });
13803 },13820 },
13804 else => {13821 else => {
...@@ -13807,8 +13824,8 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air....@@ -13807,8 +13824,8 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
13807 return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });13824 return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
13808 },13825 },
13809 };13826 };
13810 try mod.ensureFileAnalyzed(result.file);13827 try zcu.ensureFileAnalyzed(result.file_index);
13811 const file_root_decl_index = result.file.root_decl.unwrap().?;13828 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
13812 return sema.analyzeDeclVal(block, operand_src, file_root_decl_index);13829 return sema.analyzeDeclVal(block, operand_src, file_root_decl_index);
13813}13830}
1381413831
...@@ -21089,7 +21106,7 @@ fn zirReify(...@@ -21089,7 +21106,7 @@ fn zirReify(
21089 const ip = &mod.intern_pool;21106 const ip = &mod.intern_pool;
21090 const name_strategy: Zir.Inst.NameStrategy = @enumFromInt(extended.small);21107 const name_strategy: Zir.Inst.NameStrategy = @enumFromInt(extended.small);
21091 const extra = sema.code.extraData(Zir.Inst.Reify, extended.operand).data;21108 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);
21093 const src: LazySrcLoc = .{21110 const src: LazySrcLoc = .{
21094 .base_node_inst = tracked_inst,21111 .base_node_inst = tracked_inst,
21095 .offset = LazySrcLoc.Offset.nodeOffset(0),21112 .offset = LazySrcLoc.Offset.nodeOffset(0),
...@@ -21466,7 +21483,7 @@ fn zirReify(...@@ -21466,7 +21483,7 @@ fn zirReify(
21466 const wip_ty = switch (try ip.getOpaqueType(gpa, .{21483 const wip_ty = switch (try ip.getOpaqueType(gpa, .{
21467 .has_namespace = false,21484 .has_namespace = false,
21468 .key = .{ .reified = .{21485 .key = .{ .reified = .{
21469 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),21486 .zir_index = try block.trackZir(inst),
21470 } },21487 } },
21471 })) {21488 })) {
21472 .existing => |ty| return Air.internedToRef(ty),21489 .existing => |ty| return Air.internedToRef(ty),
...@@ -21660,7 +21677,7 @@ fn reifyEnum(...@@ -21660,7 +21677,7 @@ fn reifyEnum(
21660 .tag_mode = if (is_exhaustive) .explicit else .nonexhaustive,21677 .tag_mode = if (is_exhaustive) .explicit else .nonexhaustive,
21661 .fields_len = fields_len,21678 .fields_len = fields_len,
21662 .key = .{ .reified = .{21679 .key = .{ .reified = .{
21663 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),21680 .zir_index = try block.trackZir(inst),
21664 .type_hash = hasher.final(),21681 .type_hash = hasher.final(),
21665 } },21682 } },
21666 })) {21683 })) {
...@@ -21810,7 +21827,7 @@ fn reifyUnion(...@@ -21810,7 +21827,7 @@ fn reifyUnion(
21810 .field_types = &.{}, // set later21827 .field_types = &.{}, // set later
21811 .field_aligns = &.{}, // set later21828 .field_aligns = &.{}, // set later
21812 .key = .{ .reified = .{21829 .key = .{ .reified = .{
21813 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),21830 .zir_index = try block.trackZir(inst),
21814 .type_hash = hasher.final(),21831 .type_hash = hasher.final(),
21815 } },21832 } },
21816 })) {21833 })) {
...@@ -22062,7 +22079,7 @@ fn reifyStruct(...@@ -22062,7 +22079,7 @@ fn reifyStruct(
22062 .inits_resolved = true,22079 .inits_resolved = true,
22063 .has_namespace = false,22080 .has_namespace = false,
22064 .key = .{ .reified = .{22081 .key = .{ .reified = .{
22065 .zir_index = try ip.trackZir(gpa, block.getFileScope(mod), inst),22082 .zir_index = try block.trackZir(inst),
22066 .type_hash = hasher.final(),22083 .type_hash = hasher.final(),
22067 } },22084 } },
22068 })) {22085 })) {
...@@ -34894,14 +34911,14 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {...@@ -34894,14 +34911,14 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
34894 _ = try sema.typeRequiresComptime(ty);34911 _ = try sema.typeRequiresComptime(ty);
34895}34912}
3489634913
34897fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) CompileError!void {34914fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) CompileError!void {
34898 const gpa = mod.gpa;34915 const gpa = zcu.gpa;
34899 const ip = &mod.intern_pool;34916 const ip = &zcu.intern_pool;
3490034917
34901 const decl_index = struct_type.decl.unwrap().?;34918 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
34906 var analysis_arena = std.heap.ArenaAllocator.init(gpa);34923 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
34907 defer analysis_arena.deinit();34924 defer analysis_arena.deinit();
...@@ -34910,7 +34927,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co...@@ -34910,7 +34927,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co
34910 defer comptime_err_ret_trace.deinit();34927 defer comptime_err_ret_trace.deinit();
3491134928
34912 var sema: Sema = .{34929 var sema: Sema = .{
34913 .mod = mod,34930 .mod = zcu,
34914 .gpa = gpa,34931 .gpa = gpa,
34915 .arena = analysis_arena.allocator(),34932 .arena = analysis_arena.allocator(),
34916 .code = zir,34933 .code = zir,
...@@ -34941,7 +34958,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co...@@ -34941,7 +34958,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co
34941 var accumulator: u64 = 0;34958 var accumulator: u64 = 0;
34942 for (0..struct_type.field_types.len) |i| {34959 for (0..struct_type.field_types.len) |i| {
34943 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);34960 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);
34945 }34962 }
34946 break :blk accumulator;34963 break :blk accumulator;
34947 };34964 };
...@@ -34987,7 +35004,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co...@@ -34987,7 +35004,7 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.LoadedStructType) Co
34987 if (fields_bit_sum > std.math.maxInt(u16)) {35004 if (fields_bit_sum > std.math.maxInt(u16)) {
34988 return sema.fail(&block, block.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});35005 return sema.fail(&block, block.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});
34989 }35006 }
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));
34991 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();35008 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
34992 }35009 }
3499335010
...@@ -35597,23 +35614,23 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {...@@ -35597,23 +35614,23 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {
35597}35614}
3559835615
35599fn semaStructFields(35616fn semaStructFields(
35600 mod: *Module,35617 zcu: *Zcu,
35601 arena: Allocator,35618 arena: Allocator,
35602 struct_type: InternPool.LoadedStructType,35619 struct_type: InternPool.LoadedStructType,
35603) CompileError!void {35620) CompileError!void {
35604 const gpa = mod.gpa;35621 const gpa = zcu.gpa;
35605 const ip = &mod.intern_pool;35622 const ip = &zcu.intern_pool;
35606 const decl_index = struct_type.decl.unwrap() orelse return;35623 const decl_index = struct_type.decl.unwrap() orelse return;
35607 const decl = mod.declPtr(decl_index);35624 const decl = zcu.declPtr(decl_index);
35608 const namespace_index = struct_type.namespace.unwrap() orelse decl.src_namespace;35625 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;
35610 const zir_index = struct_type.zir_index.unwrap().?.resolve(ip);35627 const zir_index = struct_type.zir_index.unwrap().?.resolve(ip);
3561135628
35612 const fields_len, const small, var extra_index = structZirInfo(zir, zir_index);35629 const fields_len, const small, var extra_index = structZirInfo(zir, zir_index);
3561335630
35614 if (fields_len == 0) switch (struct_type.layout) {35631 if (fields_len == 0) switch (struct_type.layout) {
35615 .@"packed" => {35632 .@"packed" => {
35616 try semaBackingIntType(mod, struct_type);35633 try semaBackingIntType(zcu, struct_type);
35617 return;35634 return;
35618 },35635 },
35619 .auto, .@"extern" => {35636 .auto, .@"extern" => {
...@@ -35627,7 +35644,7 @@ fn semaStructFields(...@@ -35627,7 +35644,7 @@ fn semaStructFields(
35627 defer comptime_err_ret_trace.deinit();35644 defer comptime_err_ret_trace.deinit();
3562835645
35629 var sema: Sema = .{35646 var sema: Sema = .{
35630 .mod = mod,35647 .mod = zcu,
35631 .gpa = gpa,35648 .gpa = gpa,
35632 .arena = arena,35649 .arena = arena,
35633 .code = zir,35650 .code = zir,
...@@ -35749,7 +35766,7 @@ fn semaStructFields(...@@ -35749,7 +35766,7 @@ fn semaStructFields(
3574935766
35750 struct_type.field_types.get(ip)[field_i] = field_ty.toIntern();35767 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) {
35753 const msg = msg: {35770 const msg = msg: {
35754 const msg = try sema.errMsg(ty_src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});35771 const msg = try sema.errMsg(ty_src, "opaque types have unknown size and therefore cannot be directly embedded in structs", .{});
35755 errdefer msg.destroy(sema.gpa);35772 errdefer msg.destroy(sema.gpa);
...@@ -35759,7 +35776,7 @@ fn semaStructFields(...@@ -35759,7 +35776,7 @@ fn semaStructFields(
35759 };35776 };
35760 return sema.failWithOwnedErrorMsg(&block_scope, msg);35777 return sema.failWithOwnedErrorMsg(&block_scope, msg);
35761 }35778 }
35762 if (field_ty.zigTypeTag(mod) == .NoReturn) {35779 if (field_ty.zigTypeTag(zcu) == .NoReturn) {
35763 const msg = msg: {35780 const msg = msg: {
35764 const msg = try sema.errMsg(ty_src, "struct fields cannot be 'noreturn'", .{});35781 const msg = try sema.errMsg(ty_src, "struct fields cannot be 'noreturn'", .{});
35765 errdefer msg.destroy(sema.gpa);35782 errdefer msg.destroy(sema.gpa);
...@@ -35772,7 +35789,7 @@ fn semaStructFields(...@@ -35772,7 +35789,7 @@ fn semaStructFields(
35772 switch (struct_type.layout) {35789 switch (struct_type.layout) {
35773 .@"extern" => if (!try sema.validateExternType(field_ty, .struct_field)) {35790 .@"extern" => if (!try sema.validateExternType(field_ty, .struct_field)) {
35774 const msg = msg: {35791 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)});
35776 errdefer msg.destroy(sema.gpa);35793 errdefer msg.destroy(sema.gpa);
3577735794
35778 try sema.explainWhyTypeIsNotExtern(msg, ty_src, field_ty, .struct_field);35795 try sema.explainWhyTypeIsNotExtern(msg, ty_src, field_ty, .struct_field);
...@@ -35784,7 +35801,7 @@ fn semaStructFields(...@@ -35784,7 +35801,7 @@ fn semaStructFields(
35784 },35801 },
35785 .@"packed" => if (!try sema.validatePackedType(field_ty)) {35802 .@"packed" => if (!try sema.validatePackedType(field_ty)) {
35786 const msg = msg: {35803 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)});
35788 errdefer msg.destroy(sema.gpa);35805 errdefer msg.destroy(sema.gpa);
3578935806
35790 try sema.explainWhyTypeIsNotPacked(msg, ty_src, field_ty);35807 try sema.explainWhyTypeIsNotPacked(msg, ty_src, field_ty);
...@@ -35820,19 +35837,19 @@ fn semaStructFields(...@@ -35820,19 +35837,19 @@ fn semaStructFields(
3582035837
35821// This logic must be kept in sync with `semaStructFields`35838// This logic must be kept in sync with `semaStructFields`
35822fn semaStructFieldInits(35839fn semaStructFieldInits(
35823 mod: *Module,35840 zcu: *Zcu,
35824 arena: Allocator,35841 arena: Allocator,
35825 struct_type: InternPool.LoadedStructType,35842 struct_type: InternPool.LoadedStructType,
35826) CompileError!void {35843) CompileError!void {
35827 const gpa = mod.gpa;35844 const gpa = zcu.gpa;
35828 const ip = &mod.intern_pool;35845 const ip = &zcu.intern_pool;
3582935846
35830 assert(!struct_type.haveFieldInits(ip));35847 assert(!struct_type.haveFieldInits(ip));
3583135848
35832 const decl_index = struct_type.decl.unwrap() orelse return;35849 const decl_index = struct_type.decl.unwrap() orelse return;
35833 const decl = mod.declPtr(decl_index);35850 const decl = zcu.declPtr(decl_index);
35834 const namespace_index = struct_type.namespace.unwrap() orelse decl.src_namespace;35851 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;
35836 const zir_index = struct_type.zir_index.unwrap().?.resolve(ip);35853 const zir_index = struct_type.zir_index.unwrap().?.resolve(ip);
35837 const fields_len, const small, var extra_index = structZirInfo(zir, zir_index);35854 const fields_len, const small, var extra_index = structZirInfo(zir, zir_index);
3583835855
...@@ -35840,7 +35857,7 @@ fn semaStructFieldInits(...@@ -35840,7 +35857,7 @@ fn semaStructFieldInits(
35840 defer comptime_err_ret_trace.deinit();35857 defer comptime_err_ret_trace.deinit();
3584135858
35842 var sema: Sema = .{35859 var sema: Sema = .{
35843 .mod = mod,35860 .mod = zcu,
35844 .gpa = gpa,35861 .gpa = gpa,
35845 .arena = arena,35862 .arena = arena,
35846 .code = zir,35863 .code = zir,
...@@ -35950,7 +35967,7 @@ fn semaStructFieldInits(...@@ -35950,7 +35967,7 @@ fn semaStructFieldInits(
35950 });35967 });
35951 };35968 };
3595235969
35953 if (default_val.canMutateComptimeVarState(mod)) {35970 if (default_val.canMutateComptimeVarState(zcu)) {
35954 return sema.fail(&block_scope, init_src, "field default value contains reference to comptime-mutable memory", .{});35971 return sema.fail(&block_scope, init_src, "field default value contains reference to comptime-mutable memory", .{});
35955 }35972 }
35956 struct_type.field_inits.get(ip)[field_i] = default_val.toIntern();35973 struct_type.field_inits.get(ip)[field_i] = default_val.toIntern();
...@@ -35960,14 +35977,14 @@ fn semaStructFieldInits(...@@ -35960,14 +35977,14 @@ fn semaStructFieldInits(
35960 try sema.flushExports();35977 try sema.flushExports();
35961}35978}
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 {
35964 const tracy = trace(@src());35981 const tracy = trace(@src());
35965 defer tracy.end();35982 defer tracy.end();
3596635983
35967 const gpa = mod.gpa;35984 const gpa = zcu.gpa;
35968 const ip = &mod.intern_pool;35985 const ip = &zcu.intern_pool;
35969 const decl_index = union_type.decl;35986 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;
35971 const zir_index = union_type.zir_index.resolve(ip);35988 const zir_index = union_type.zir_index.resolve(ip);
35972 const extended = zir.instructions.items(.data)[@intFromEnum(zir_index)].extended;35989 const extended = zir.instructions.items(.data)[@intFromEnum(zir_index)].extended;
35973 assert(extended.opcode == .union_decl);35990 assert(extended.opcode == .union_decl);
...@@ -36011,13 +36028,13 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36011,13 +36028,13 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36011 const body = zir.bodySlice(extra_index, body_len);36028 const body = zir.bodySlice(extra_index, body_len);
36012 extra_index += body.len;36029 extra_index += body.len;
3601336030
36014 const decl = mod.declPtr(decl_index);36031 const decl = zcu.declPtr(decl_index);
3601536032
36016 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);36033 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);
36017 defer comptime_err_ret_trace.deinit();36034 defer comptime_err_ret_trace.deinit();
3601836035
36019 var sema: Sema = .{36036 var sema: Sema = .{
36020 .mod = mod,36037 .mod = zcu,
36021 .gpa = gpa,36038 .gpa = gpa,
36022 .arena = arena,36039 .arena = arena,
36023 .code = zir,36040 .code = zir,
...@@ -36063,18 +36080,18 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36063,18 +36080,18 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36063 if (small.auto_enum_tag) {36080 if (small.auto_enum_tag) {
36064 // The provided type is an integer type and we must construct the enum tag type here.36081 // The provided type is an integer type and we must construct the enum tag type here.
36065 int_tag_ty = provided_ty;36082 int_tag_ty = provided_ty;
36066 if (int_tag_ty.zigTypeTag(mod) != .Int and int_tag_ty.zigTypeTag(mod) != .ComptimeInt) {36083 if (int_tag_ty.zigTypeTag(zcu) != .Int and int_tag_ty.zigTypeTag(zcu) != .ComptimeInt) {
36067 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(mod)});36084 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(zcu)});
36068 }36085 }
3606936086
36070 if (fields_len > 0) {36087 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);
36072 if (!(try sema.intFitsInType(field_count_val, int_tag_ty, null))) {36089 if (!(try sema.intFitsInType(field_count_val, int_tag_ty, null))) {
36073 const msg = msg: {36090 const msg = msg: {
36074 const msg = try sema.errMsg(tag_ty_src, "specified integer tag type cannot represent every field", .{});36091 const msg = try sema.errMsg(tag_ty_src, "specified integer tag type cannot represent every field", .{});
36075 errdefer msg.destroy(sema.gpa);36092 errdefer msg.destroy(sema.gpa);
36076 try sema.errNote(tag_ty_src, msg, "type '{}' cannot fit values in range 0...{d}", .{36093 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),
36078 fields_len - 1,36095 fields_len - 1,
36079 });36096 });
36080 break :msg msg;36097 break :msg msg;
...@@ -36089,7 +36106,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36089,7 +36106,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36089 union_type.tagTypePtr(ip).* = provided_ty.toIntern();36106 union_type.tagTypePtr(ip).* = provided_ty.toIntern();
36090 const enum_type = switch (ip.indexToKey(provided_ty.toIntern())) {36107 const enum_type = switch (ip.indexToKey(provided_ty.toIntern())) {
36091 .enum_type => ip.loadEnumType(provided_ty.toIntern()),36108 .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)}),
36093 };36110 };
36094 // The fields of the union must match the enum exactly.36111 // The fields of the union must match the enum exactly.
36095 // A flag per field is used to check for missing and extraneous fields.36112 // 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...@@ -36185,7 +36202,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36185 const val = if (last_tag_val) |val|36202 const val = if (last_tag_val) |val|
36186 try sema.intAdd(val, Value.one_comptime_int, int_tag_ty, undefined)36203 try sema.intAdd(val, Value.one_comptime_int, int_tag_ty, undefined)
36187 else36204 else
36188 try mod.intValue(int_tag_ty, 0);36205 try zcu.intValue(int_tag_ty, 0);
36189 last_tag_val = val;36206 last_tag_val = val;
3619036207
36191 break :blk val;36208 break :blk val;
...@@ -36197,7 +36214,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36197,7 +36214,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36197 .offset = .{ .container_field_value = @intCast(gop.index) },36214 .offset = .{ .container_field_value = @intCast(gop.index) },
36198 };36215 };
36199 const msg = msg: {36216 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)});
36201 errdefer msg.destroy(gpa);36218 errdefer msg.destroy(gpa);
36202 try sema.errNote(other_value_src, msg, "other occurrence here", .{});36219 try sema.errNote(other_value_src, msg, "other occurrence here", .{});
36203 break :msg msg;36220 break :msg msg;
...@@ -36227,7 +36244,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36227,7 +36244,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36227 const tag_info = ip.loadEnumType(union_type.tagTypePtr(ip).*);36244 const tag_info = ip.loadEnumType(union_type.tagTypePtr(ip).*);
36228 const enum_index = tag_info.nameIndex(ip, field_name) orelse {36245 const enum_index = tag_info.nameIndex(ip, field_name) orelse {
36229 return sema.fail(&block_scope, name_src, "no field named '{}' in enum '{}'", .{36246 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),
36231 });36248 });
36232 };36249 };
3623336250
...@@ -36254,7 +36271,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36254,7 +36271,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36254 }36271 }
36255 }36272 }
3625636273
36257 if (field_ty.zigTypeTag(mod) == .Opaque) {36274 if (field_ty.zigTypeTag(zcu) == .Opaque) {
36258 const msg = msg: {36275 const msg = msg: {
36259 const msg = try sema.errMsg(type_src, "opaque types have unknown size and therefore cannot be directly embedded in unions", .{});36276 const msg = try sema.errMsg(type_src, "opaque types have unknown size and therefore cannot be directly embedded in unions", .{});
36260 errdefer msg.destroy(sema.gpa);36277 errdefer msg.destroy(sema.gpa);
...@@ -36269,7 +36286,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36269,7 +36286,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36269 !try sema.validateExternType(field_ty, .union_field))36286 !try sema.validateExternType(field_ty, .union_field))
36270 {36287 {
36271 const msg = msg: {36288 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)});
36273 errdefer msg.destroy(sema.gpa);36290 errdefer msg.destroy(sema.gpa);
3627436291
36275 try sema.explainWhyTypeIsNotExtern(msg, type_src, field_ty, .union_field);36292 try sema.explainWhyTypeIsNotExtern(msg, type_src, field_ty, .union_field);
...@@ -36280,7 +36297,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36280,7 +36297,7 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36280 return sema.failWithOwnedErrorMsg(&block_scope, msg);36297 return sema.failWithOwnedErrorMsg(&block_scope, msg);
36281 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {36298 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
36282 const msg = msg: {36299 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)});
36284 errdefer msg.destroy(sema.gpa);36301 errdefer msg.destroy(sema.gpa);
3628536302
36286 try sema.explainWhyTypeIsNotPacked(msg, type_src, field_ty);36303 try sema.explainWhyTypeIsNotPacked(msg, type_src, field_ty);
...@@ -36325,10 +36342,10 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded...@@ -36325,10 +36342,10 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Loaded
36325 return sema.failWithOwnedErrorMsg(&block_scope, msg);36342 return sema.failWithOwnedErrorMsg(&block_scope, msg);
36326 }36343 }
36327 } else if (enum_field_vals.count() > 0) {36344 } 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));
36329 union_type.tagTypePtr(ip).* = enum_ty;36346 union_type.tagTypePtr(ip).* = enum_ty;
36330 } else {36347 } 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));
36332 union_type.tagTypePtr(ip).* = enum_ty;36349 union_type.tagTypePtr(ip).* = enum_ty;
36333 }36350 }
3633436351
src/Type.zig+1-1
...@@ -3455,7 +3455,7 @@ pub fn typeDeclSrcLine(ty: Type, zcu: *const Zcu) ?u32 {...@@ -3455,7 +3455,7 @@ pub fn typeDeclSrcLine(ty: Type, zcu: *const Zcu) ?u32 {
3455 else => return null,3455 else => return null,
3456 };3456 };
3457 const info = tracked.resolveFull(&zcu.intern_pool);3457 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);
3459 assert(file.zir_loaded);3459 assert(file.zir_loaded);
3460 const zir = file.zir;3460 const zir = file.zir;
3461 const inst = zir.instructions.get(@intFromEnum(info.inst));3461 const inst = zir.instructions.get(@intFromEnum(info.inst));
src/Zcu.zig+318-252
...@@ -72,6 +72,7 @@ codegen_prog_node: std.Progress.Node = undefined,...@@ -72,6 +72,7 @@ codegen_prog_node: std.Progress.Node = undefined,
72global_zir_cache: Compilation.Directory,72global_zir_cache: Compilation.Directory,
73/// Used by AstGen worker to load and store ZIR cache.73/// Used by AstGen worker to load and store ZIR cache.
74local_zir_cache: Compilation.Directory,74local_zir_cache: Compilation.Directory,
75
75/// This is where all `Export` values are stored. Not all values here are necessarily valid exports;76/// This is where all `Export` values are stored. Not all values here are necessarily valid exports;
76/// to enumerate all exports, `single_exports` and `multi_exports` must be consulted.77/// to enumerate all exports, `single_exports` and `multi_exports` must be consulted.
77all_exports: ArrayListUnmanaged(Export) = .{},78all_exports: ArrayListUnmanaged(Export) = .{},
...@@ -88,14 +89,22 @@ multi_exports: std.AutoArrayHashMapUnmanaged(AnalUnit, extern struct {...@@ -88,14 +89,22 @@ multi_exports: std.AutoArrayHashMapUnmanaged(AnalUnit, extern struct {
88 index: u32,89 index: u32,
89 len: u32,90 len: u32,
90}) = .{},91}) = .{},
91/// The set of all the Zig source files in the Module. We keep track of this in order92
92/// to iterate over it and check which source files have been modified on the file system when93/// The set of all the Zig source files in the Zig Compilation Unit. Tracked in
93/// an update is requested, as well as to cache `@import` results.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///
94/// Keys are fully resolved file paths. This table owns the keys and values.98/// 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`.
95import_table: std.StringArrayHashMapUnmanaged(*File) = .{},106import_table: std.StringArrayHashMapUnmanaged(*File) = .{},
96/// This acts as a map from `path_digest` to the corresponding `File`.107
97/// The value is omitted, as keys are ordered identically to `import_table`.
98path_digest_map: std.AutoArrayHashMapUnmanaged(Cache.BinDigest, void) = .{},
99/// The set of all the files which have been loaded with `@embedFile` in the Module.108/// The set of all the files which have been loaded with `@embedFile` in the Module.
100/// We keep track of this in order to iterate over it and check which files have been109/// We keep track of this in order to iterate over it and check which files have been
101/// modified on the file system when an update is requested, as well as to cache110/// modified on the file system when an update is requested, as well as to cache
...@@ -387,8 +396,8 @@ pub const Decl = struct {...@@ -387,8 +396,8 @@ pub const Decl = struct {
387 anon,396 anon,
388 };397 };
389398
390 const Index = InternPool.DeclIndex;399 pub const Index = InternPool.DeclIndex;
391 const OptionalIndex = InternPool.OptionalDeclIndex;400 pub const OptionalIndex = InternPool.OptionalDeclIndex;
392401
393 pub fn zirBodies(decl: Decl, zcu: *Zcu) Zir.Inst.Declaration.Bodies {402 pub fn zirBodies(decl: Decl, zcu: *Zcu) Zir.Inst.Declaration.Bodies {
394 const zir = decl.getFileScope(zcu).zir;403 const zir = decl.getFileScope(zcu).zir;
...@@ -490,6 +499,10 @@ pub const Decl = struct {...@@ -490,6 +499,10 @@ pub const Decl = struct {
490 }499 }
491500
492 pub fn getFileScope(decl: Decl, zcu: *Zcu) *File {501 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 {
493 return zcu.namespacePtr(decl.src_namespace).file_scope;506 return zcu.namespacePtr(decl.src_namespace).file_scope;
494 }507 }
495508
...@@ -546,19 +559,20 @@ pub const Decl = struct {...@@ -546,19 +559,20 @@ pub const Decl = struct {
546 }559 }
547560
548 pub fn navSrcLine(decl: Decl, zcu: *Zcu) u32 {561 pub fn navSrcLine(decl: Decl, zcu: *Zcu) u32 {
562 const ip = &zcu.intern_pool;
549 const tracked = decl.zir_decl_index.unwrap() orelse inst: {563 const tracked = decl.zir_decl_index.unwrap() orelse inst: {
550 // generic instantiation564 // generic instantiation
551 assert(decl.has_tv);565 assert(decl.has_tv);
552 assert(decl.owns_tv);566 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())) {
554 .func => |func| func.generic_owner,568 .func => |func| func.generic_owner,
555 else => return 0, // TODO: this is probably a `variable` or something; figure this out when we finish sorting out `Decl`.569 else => return 0, // TODO: this is probably a `variable` or something; figure this out when we finish sorting out `Decl`.
556 };570 };
557 const generic_owner_decl = zcu.declPtr(zcu.funcInfo(generic_owner_func).owner_decl);571 const generic_owner_decl = zcu.declPtr(zcu.funcInfo(generic_owner_func).owner_decl);
558 break :inst generic_owner_decl.zir_decl_index.unwrap().?;572 break :inst generic_owner_decl.zir_decl_index.unwrap().?;
559 };573 };
560 const info = tracked.resolveFull(&zcu.intern_pool);574 const info = tracked.resolveFull(ip);
561 const file = zcu.import_table.values()[zcu.path_digest_map.getIndex(info.path_digest).?];575 const file = zcu.fileByIndex(info.file);
562 assert(file.zir_loaded);576 assert(file.zir_loaded);
563 const zir = file.zir;577 const zir = file.zir;
564 const inst = zir.instructions.get(@intFromEnum(info.inst));578 const inst = zir.instructions.get(@intFromEnum(info.inst));
...@@ -595,7 +609,7 @@ pub const DeclAdapter = struct {...@@ -595,7 +609,7 @@ pub const DeclAdapter = struct {
595/// The container that structs, enums, unions, and opaques have.609/// The container that structs, enums, unions, and opaques have.
596pub const Namespace = struct {610pub const Namespace = struct {
597 parent: OptionalIndex,611 parent: OptionalIndex,
598 file_scope: *File,612 file_scope: File.Index,
599 /// Will be a struct, enum, union, or opaque.613 /// Will be a struct, enum, union, or opaque.
600 decl_index: Decl.Index,614 decl_index: Decl.Index,
601 /// Direct children of the namespace.615 /// Direct children of the namespace.
...@@ -627,6 +641,10 @@ pub const Namespace = struct {...@@ -627,6 +641,10 @@ pub const Namespace = struct {
627 }641 }
628 };642 };
629643
644 pub fn fileScope(ns: Namespace, zcu: *Zcu) *File {
645 return zcu.fileByIndex(ns.file_scope);
646 }
647
630 // This renders e.g. "std.fs.Dir.OpenOptions"648 // This renders e.g. "std.fs.Dir.OpenOptions"
631 pub fn renderFullyQualifiedName(649 pub fn renderFullyQualifiedName(
632 ns: Namespace,650 ns: Namespace,
...@@ -641,7 +659,7 @@ pub const Namespace = struct {...@@ -641,7 +659,7 @@ pub const Namespace = struct {
641 writer,659 writer,
642 );660 );
643 } else {661 } else {
644 try ns.file_scope.renderFullyQualifiedName(writer);662 try ns.fileScope(zcu).renderFullyQualifiedName(writer);
645 }663 }
646 if (name != .empty) try writer.print(".{}", .{name.fmt(&zcu.intern_pool)});664 if (name != .empty) try writer.print(".{}", .{name.fmt(&zcu.intern_pool)});
647 }665 }
...@@ -661,7 +679,7 @@ pub const Namespace = struct {...@@ -661,7 +679,7 @@ pub const Namespace = struct {
661 );679 );
662 break :sep '.';680 break :sep '.';
663 } else sep: {681 } else sep: {
664 try ns.file_scope.renderFullyQualifiedDebugName(writer);682 try ns.fileScope(zcu).renderFullyQualifiedDebugName(writer);
665 break :sep ':';683 break :sep ':';
666 };684 };
667 if (name != .empty) try writer.print("{c}{}", .{ sep, name.fmt(&zcu.intern_pool) });685 if (name != .empty) try writer.print("{c}{}", .{ sep, name.fmt(&zcu.intern_pool) });
...@@ -680,7 +698,7 @@ pub const Namespace = struct {...@@ -680,7 +698,7 @@ pub const Namespace = struct {
680 const decl = zcu.declPtr(cur_ns.decl_index);698 const decl = zcu.declPtr(cur_ns.decl_index);
681 count += decl.name.length(ip) + 1;699 count += decl.name.length(ip) + 1;
682 cur_ns = zcu.namespacePtr(cur_ns.parent.unwrap() orelse {700 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;
684 break :count count;702 break :count count;
685 });703 });
686 }704 }
...@@ -715,8 +733,6 @@ pub const Namespace = struct {...@@ -715,8 +733,6 @@ pub const Namespace = struct {
715};733};
716734
717pub const File = struct {735pub const File = struct {
718 /// The Decl of the struct that represents this File.
719 root_decl: Decl.OptionalIndex,
720 status: enum {736 status: enum {
721 never_loaded,737 never_loaded,
722 retryable_failure,738 retryable_failure,
...@@ -744,8 +760,6 @@ pub const File = struct {...@@ -744,8 +760,6 @@ pub const File = struct {
744 multi_pkg: bool = false,760 multi_pkg: bool = false,
745 /// List of references to this file, used for multi-package errors.761 /// List of references to this file, used for multi-package errors.
746 references: std.ArrayListUnmanaged(File.Reference) = .{},762 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
750 /// The most recent successful ZIR for this file, with no errors.764 /// The most recent successful ZIR for this file, with no errors.
751 /// This is only populated when a previously successful ZIR765 /// This is only populated when a previously successful ZIR
...@@ -757,7 +771,7 @@ pub const File = struct {...@@ -757,7 +771,7 @@ pub const File = struct {
757 pub const Reference = union(enum) {771 pub const Reference = union(enum) {
758 /// The file is imported directly (i.e. not as a package) with @import.772 /// The file is imported directly (i.e. not as a package) with @import.
759 import: struct {773 import: struct {
760 file: *File,774 file: File.Index,
761 token: Ast.TokenIndex,775 token: Ast.TokenIndex,
762 },776 },
763 /// The file is the root of a module.777 /// The file is the root of a module.
...@@ -791,28 +805,6 @@ pub const File = struct {...@@ -791,28 +805,6 @@ pub const File = struct {
791 }805 }
792 }806 }
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
816 pub const Source = struct {808 pub const Source = struct {
817 bytes: [:0]const u8,809 bytes: [:0]const u8,
818 stat: Cache.File.Stat,810 stat: Cache.File.Stat,
...@@ -865,13 +857,6 @@ pub const File = struct {...@@ -865,13 +857,6 @@ pub const File = struct {
865 return &file.tree;857 return &file.tree;
866 }858 }
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
875 pub fn renderFullyQualifiedName(file: File, writer: anytype) !void {860 pub fn renderFullyQualifiedName(file: File, writer: anytype) !void {
876 // Convert all the slashes into dots and truncate the extension.861 // Convert all the slashes into dots and truncate the extension.
877 const ext = std.fs.path.extension(file.sub_file_path);862 const ext = std.fs.path.extension(file.sub_file_path);
...@@ -937,7 +922,7 @@ pub const File = struct {...@@ -937,7 +922,7 @@ pub const File = struct {
937 }922 }
938923
939 const mod = switch (ref) {924 const mod = switch (ref) {
940 .import => |import| import.file.mod,925 .import => |import| zcu.fileByIndex(import.file).mod,
941 .root => |mod| mod,926 .root => |mod| mod,
942 };927 };
943 if (mod != file.mod) file.multi_pkg = true;928 if (mod != file.mod) file.multi_pkg = true;
...@@ -971,6 +956,8 @@ pub const File = struct {...@@ -971,6 +956,8 @@ pub const File = struct {
971 }956 }
972 }957 }
973 }958 }
959
960 pub const Index = InternPool.FileIndex;
974};961};
975962
976pub const EmbedFile = struct {963pub const EmbedFile = struct {
...@@ -2350,14 +2337,12 @@ pub const LazySrcLoc = struct {...@@ -2350,14 +2337,12 @@ pub const LazySrcLoc = struct {
2350 };2337 };
23512338
2352 pub fn resolveBaseNode(base_node_inst: InternPool.TrackedInst.Index, zcu: *Zcu) struct { *File, Ast.Node.Index } {2339 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: {2340 const ip = &zcu.intern_pool;
2354 const info = base_node_inst.resolveFull(&zcu.intern_pool);2341 const file_index, const zir_inst = inst: {
2355 break :inst .{ info.path_digest, info.inst };2342 const info = base_node_inst.resolveFull(ip);
2356 };2343 break :inst .{ info.file, info.inst };
2357 const file = file: {
2358 const index = zcu.path_digest_map.getIndex(want_path_digest).?;
2359 break :file zcu.import_table.values()[index];
2360 };2344 };
2345 const file = zcu.fileByIndex(file_index);
2361 assert(file.zir_loaded);2346 assert(file.zir_loaded);
23622347
2363 const zir = file.zir;2348 const zir = file.zir;
...@@ -2423,11 +2408,11 @@ pub fn deinit(zcu: *Zcu) void {...@@ -2423,11 +2408,11 @@ pub fn deinit(zcu: *Zcu) void {
2423 for (zcu.import_table.keys()) |key| {2408 for (zcu.import_table.keys()) |key| {
2424 gpa.free(key);2409 gpa.free(key);
2425 }2410 }
2426 for (zcu.import_table.values()) |value| {2411 for (0..zcu.import_table.entries.len) |file_index_usize| {
2427 value.destroy(zcu);2412 const file_index: File.Index = @enumFromInt(file_index_usize);
2413 zcu.destroyFile(file_index);
2428 }2414 }
2429 zcu.import_table.deinit(gpa);2415 zcu.import_table.deinit(gpa);
2430 zcu.path_digest_map.deinit(gpa);
24312416
2432 for (zcu.embed_table.keys(), zcu.embed_table.values()) |path, embed_file| {2417 for (zcu.embed_table.keys(), zcu.embed_table.values()) |path, embed_file| {
2433 gpa.free(path);2418 gpa.free(path);
...@@ -2531,6 +2516,37 @@ pub fn destroyDecl(mod: *Module, decl_index: Decl.Index) void {...@@ -2531,6 +2516,37 @@ pub fn destroyDecl(mod: *Module, decl_index: Decl.Index) void {
2531 }2516 }
2532}2517}
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
2534pub fn declPtr(mod: *Module, index: Decl.Index) *Decl {2550pub fn declPtr(mod: *Module, index: Decl.Index) *Decl {
2535 return mod.intern_pool.declPtr(index);2551 return mod.intern_pool.declPtr(index);
2536}2552}
...@@ -2563,14 +2579,23 @@ comptime {...@@ -2563,14 +2579,23 @@ comptime {
2563 }2579 }
2564}2580}
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 {
2567 assert(!file.mod.isBuiltin());2592 assert(!file.mod.isBuiltin());
25682593
2569 const tracy = trace(@src());2594 const tracy = trace(@src());
2570 defer tracy.end();2595 defer tracy.end();
25712596
2572 const comp = mod.comp;2597 const comp = zcu.comp;
2573 const gpa = mod.gpa;2598 const gpa = zcu.gpa;
25742599
2575 // In any case we need to examine the stat of the file to determine the course of action.2600 // In any case we need to examine the stat of the file to determine the course of action.
2576 var source_file = try file.mod.root.openFile(file.sub_file_path, .{});2601 var source_file = try file.mod.root.openFile(file.sub_file_path, .{});
...@@ -2578,17 +2603,9 @@ pub fn astGenFile(mod: *Module, file: *File) !void {...@@ -2578,17 +2603,9 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
25782603
2579 const stat = try source_file.stat();2604 const stat = try source_file.stat();
25802605
2581 const want_local_cache = file.mod == mod.main_mod;2606 const want_local_cache = file.mod == zcu.main_mod;
2582 const hex_digest = hex: {2607 const hex_digest = Cache.binToHex(path_digest);
2583 var hex: Cache.HexDigest = undefined;2608 const cache_directory = if (want_local_cache) zcu.local_zir_cache else zcu.global_zir_cache;
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;
2592 const zir_dir = cache_directory.handle;2609 const zir_dir = cache_directory.handle;
25932610
2594 // Determine whether we need to reload the file from disk and redo parsing and AstGen.2611 // 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 {...@@ -2688,7 +2705,7 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
2688 {2705 {
2689 comp.mutex.lock();2706 comp.mutex.lock();
2690 defer comp.mutex.unlock();2707 defer comp.mutex.unlock();
2691 try mod.failed_files.putNoClobber(gpa, file, null);2708 try zcu.failed_files.putNoClobber(gpa, file, null);
2692 }2709 }
2693 file.status = .astgen_failure;2710 file.status = .astgen_failure;
2694 return error.AnalysisFail;2711 return error.AnalysisFail;
...@@ -2712,7 +2729,7 @@ pub fn astGenFile(mod: *Module, file: *File) !void {...@@ -2712,7 +2729,7 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
2712 else => |e| return e,2729 else => |e| return e,
2713 };2730 };
27142731
2715 mod.lockAndClearFileCompileError(file);2732 zcu.lockAndClearFileCompileError(file);
27162733
2717 // If the previous ZIR does not have compile errors, keep it around2734 // If the previous ZIR does not have compile errors, keep it around
2718 // in case parsing or new ZIR fails. In case of successful ZIR update2735 // 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 {...@@ -2818,27 +2835,27 @@ pub fn astGenFile(mod: *Module, file: *File) !void {
2818 {2835 {
2819 comp.mutex.lock();2836 comp.mutex.lock();
2820 defer comp.mutex.unlock();2837 defer comp.mutex.unlock();
2821 try mod.failed_files.putNoClobber(gpa, file, null);2838 try zcu.failed_files.putNoClobber(gpa, file, null);
2822 }2839 }
2823 file.status = .astgen_failure;2840 file.status = .astgen_failure;
2824 return error.AnalysisFail;2841 return error.AnalysisFail;
2825 }2842 }
28262843
2827 if (file.prev_zir) |prev_zir| {2844 if (file.prev_zir) |prev_zir| {
2828 try updateZirRefs(mod, file, prev_zir.*);2845 try updateZirRefs(zcu, file, file_index, prev_zir.*);
2829 // No need to keep previous ZIR.2846 // No need to keep previous ZIR.
2830 prev_zir.deinit(gpa);2847 prev_zir.deinit(gpa);
2831 gpa.destroy(prev_zir);2848 gpa.destroy(prev_zir);
2832 file.prev_zir = null;2849 file.prev_zir = null;
2833 }2850 }
28342851
2835 if (file.root_decl.unwrap()) |root_decl| {2852 if (opt_root_decl.unwrap()) |root_decl| {
2836 // The root of this file must be re-analyzed, since the file has changed.2853 // The root of this file must be re-analyzed, since the file has changed.
2837 comp.mutex.lock();2854 comp.mutex.lock();
2838 defer comp.mutex.unlock();2855 defer comp.mutex.unlock();
28392856
2840 log.debug("outdated root Decl: {}", .{root_decl});2857 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, {});
2842 }2859 }
2843}2860}
28442861
...@@ -2914,7 +2931,7 @@ fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_file: std.fs.File)...@@ -2914,7 +2931,7 @@ fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_file: std.fs.File)
29142931
2915/// This is called from the AstGen thread pool, so must acquire2932/// This is called from the AstGen thread pool, so must acquire
2916/// the Compilation mutex when acting on shared state.2933/// 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 {
2918 const gpa = zcu.gpa;2935 const gpa = zcu.gpa;
2919 const new_zir = file.zir;2936 const new_zir = file.zir;
29202937
...@@ -2930,7 +2947,7 @@ fn updateZirRefs(zcu: *Module, file: *File, old_zir: Zir) !void {...@@ -2930,7 +2947,7 @@ fn updateZirRefs(zcu: *Module, file: *File, old_zir: Zir) !void {
2930 // iterating over this full set for every updated file.2947 // iterating over this full set for every updated file.
2931 for (zcu.intern_pool.tracked_insts.keys(), 0..) |*ti, idx_raw| {2948 for (zcu.intern_pool.tracked_insts.keys(), 0..) |*ti, idx_raw| {
2932 const ti_idx: InternPool.TrackedInst.Index = @enumFromInt(idx_raw);2949 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;
2934 const old_inst = ti.inst;2951 const old_inst = ti.inst;
2935 ti.inst = inst_map.get(ti.inst) orelse {2952 ti.inst = inst_map.get(ti.inst) orelse {
2936 // Tracking failed for this instruction. Invalidate associated `src_hash` deps.2953 // Tracking failed for this instruction. Invalidate associated `src_hash` deps.
...@@ -3378,11 +3395,11 @@ pub fn mapOldZirToNew(...@@ -3378,11 +3395,11 @@ pub fn mapOldZirToNew(
3378}3395}
33793396
3380/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.3397/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.
3381pub fn ensureFileAnalyzed(zcu: *Zcu, file: *File) SemaError!void {3398pub fn ensureFileAnalyzed(zcu: *Zcu, file_index: File.Index) SemaError!void {
3382 if (file.root_decl.unwrap()) |existing_root| {3399 if (zcu.fileRootDecl(file_index).unwrap()) |existing_root| {
3383 return zcu.ensureDeclAnalyzed(existing_root);3400 return zcu.ensureDeclAnalyzed(existing_root);
3384 } else {3401 } else {
3385 return zcu.semaFile(file);3402 return zcu.semaFile(file_index);
3386 }3403 }
3387}3404}
33883405
...@@ -3455,7 +3472,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl_index: Decl.Index) SemaError!void {...@@ -3455,7 +3472,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl_index: Decl.Index) SemaError!void {
3455 }3472 }
34563473
3457 if (mod.declIsRoot(decl_index)) {3474 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);
3459 break :blk .{3476 break :blk .{
3460 .invalidate_decl_val = changed,3477 .invalidate_decl_val = changed,
3461 .invalidate_decl_ref = changed,3478 .invalidate_decl_ref = changed,
...@@ -3787,17 +3804,23 @@ pub fn ensureFuncBodyAnalysisQueued(mod: *Module, func_index: InternPool.Index)...@@ -3787,17 +3804,23 @@ pub fn ensureFuncBodyAnalysisQueued(mod: *Module, func_index: InternPool.Index)
3787 func.analysis(ip).state = .queued;3804 func.analysis(ip).state = .queued;
3788}3805}
37893806
3790/// https://github.com/ziglang/zig/issues/143073807pub fn semaPkg(zcu: *Zcu, pkg: *Package.Module) !void {
3791pub fn semaPkg(mod: *Module, pkg: *Package.Module) !void {3808 const import_file_result = try zcu.importPkg(pkg);
3792 const file = (try mod.importPkg(pkg)).file;3809 const root_decl_index = zcu.fileRootDecl(import_file_result.file_index);
3793 if (file.root_decl == .none) {3810 if (root_decl_index == .none) {
3794 return mod.semaFile(file);3811 return zcu.semaFile(import_file_result.file_index);
3795 }3812 }
3796}3813}
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 {
3799 const gpa = zcu.gpa;3821 const gpa = zcu.gpa;
3800 const ip = &zcu.intern_pool;3822 const ip = &zcu.intern_pool;
3823 const file = zcu.fileByIndex(file_index);
3801 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;3824 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
3802 assert(extended.opcode == .struct_decl);3825 assert(extended.opcode == .struct_decl);
3803 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);3826 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
...@@ -3818,7 +3841,7 @@ fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespa...@@ -3818,7 +3841,7 @@ fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespa
3818 const decls = file.zir.bodySlice(extra_index, decls_len);3841 const decls = file.zir.bodySlice(extra_index, decls_len);
3819 extra_index += decls_len;3842 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);
3822 const wip_ty = switch (try ip.getStructType(gpa, .{3845 const wip_ty = switch (try ip.getStructType(gpa, .{
3823 .layout = .auto,3846 .layout = .auto,
3824 .fields_len = fields_len,3847 .fields_len = fields_len,
...@@ -3863,8 +3886,9 @@ fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespa...@@ -3863,8 +3886,9 @@ fn getFileRootStruct(zcu: *Zcu, decl_index: Decl.Index, namespace_index: Namespa
3863/// If `type_outdated`, the struct type itself is considered outdated and is3886/// If `type_outdated`, the struct type itself is considered outdated and is
3864/// reconstructed at a new InternPool index. Otherwise, the namespace is just3887/// reconstructed at a new InternPool index. Otherwise, the namespace is just
3865/// re-analyzed. Returns whether the decl's tyval was invalidated.3888/// re-analyzed. Returns whether the decl's tyval was invalidated.
3866fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {3889fn semaFileUpdate(zcu: *Zcu, file_index: File.Index, type_outdated: bool) SemaError!bool {
3867 const decl = zcu.declPtr(file.root_decl.unwrap().?);3890 const file = zcu.fileByIndex(file_index);
3891 const decl = zcu.declPtr(zcu.fileRootDecl(file_index).unwrap().?);
38683892
3869 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{3893 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{
3870 file.mod.fully_qualified_name,3894 file.mod.fully_qualified_name,
...@@ -3883,7 +3907,8 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {...@@ -3883,7 +3907,8 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
38833907
3884 if (decl.analysis == .file_failure) {3908 if (decl.analysis == .file_failure) {
3885 // No struct type currently exists. Create one!3909 // 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);
3887 return true;3912 return true;
3888 }3913 }
38893914
...@@ -3892,10 +3917,13 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {...@@ -3892,10 +3917,13 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
38923917
3893 if (type_outdated) {3918 if (type_outdated) {
3894 // Invalidate the existing type, reusing the decl and namespace.3919 // 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 }));
3896 zcu.intern_pool.remove(decl.val.toIntern());3924 zcu.intern_pool.remove(decl.val.toIntern());
3897 decl.val = undefined;3925 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);
3899 return true;3927 return true;
3900 }3928 }
39013929
...@@ -3923,35 +3951,36 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {...@@ -3923,35 +3951,36 @@ fn semaFileUpdate(zcu: *Zcu, file: *File, type_outdated: bool) SemaError!bool {
39233951
3924/// Regardless of the file status, will create a `Decl` if none exists so that we can track3952/// Regardless of the file status, will create a `Decl` if none exists so that we can track
3925/// dependencies and re-analyze when the file becomes outdated.3953/// 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 {
3927 const tracy = trace(@src());3955 const tracy = trace(@src());
3928 defer tracy.end();3956 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;3961 const gpa = zcu.gpa;
3933 log.debug("semaFile mod={s} sub_file_path={s}", .{3962 log.debug("semaFile zcu={s} sub_file_path={s}", .{
3934 file.mod.fully_qualified_name, file.sub_file_path,3963 file.mod.fully_qualified_name, file.sub_file_path,
3935 });3964 });
39363965
3937 // Because these three things each reference each other, `undefined`3966 // Because these three things each reference each other, `undefined`
3938 // placeholders are used before being set after the struct type gains an3967 // placeholders are used before being set after the struct type gains an
3939 // InternPool index.3968 // InternPool index.
3940 const new_namespace_index = try mod.createNamespace(.{3969 const new_namespace_index = try zcu.createNamespace(.{
3941 .parent = .none,3970 .parent = .none,
3942 .decl_index = undefined,3971 .decl_index = undefined,
3943 .file_scope = file,3972 .file_scope = file_index,
3944 });3973 });
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);3976 const new_decl_index = try zcu.allocateNewDecl(new_namespace_index);
3948 const new_decl = mod.declPtr(new_decl_index);3977 const new_decl = zcu.declPtr(new_decl_index);
3949 errdefer @panic("TODO error handling");3978 errdefer @panic("TODO error handling");
39503979
3951 file.root_decl = new_decl_index.toOptional();3980 zcu.setFileRootDecl(file_index, new_decl_index.toOptional());
3952 mod.namespacePtr(new_namespace_index).decl_index = new_decl_index;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);
3955 new_decl.name_fully_qualified = true;3984 new_decl.name_fully_qualified = true;
3956 new_decl.is_pub = true;3985 new_decl.is_pub = true;
3957 new_decl.is_exported = false;3986 new_decl.is_exported = false;
...@@ -3965,13 +3994,13 @@ fn semaFile(mod: *Module, file: *File) SemaError!void {...@@ -3965,13 +3994,13 @@ fn semaFile(mod: *Module, file: *File) SemaError!void {
3965 }3994 }
3966 assert(file.zir_loaded);3995 assert(file.zir_loaded);
39673996
3968 const struct_ty = try mod.getFileRootStruct(new_decl_index, new_namespace_index, file);3997 const struct_ty = try zcu.getFileRootStruct(new_decl_index, new_namespace_index, file_index);
3969 errdefer mod.intern_pool.remove(struct_ty);3998 errdefer zcu.intern_pool.remove(struct_ty);
39703999
3971 switch (mod.comp.cache_use) {4000 switch (zcu.comp.cache_use) {
3972 .whole => |whole| if (whole.cache_manifest) |man| {4001 .whole => |whole| if (whole.cache_manifest) |man| {
3973 const source = file.getSource(gpa) catch |err| {4002 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)});
3975 return error.AnalysisFail;4004 return error.AnalysisFail;
3976 };4005 };
39774006
...@@ -3980,7 +4009,7 @@ fn semaFile(mod: *Module, file: *File) SemaError!void {...@@ -3980,7 +4009,7 @@ fn semaFile(mod: *Module, file: *File) SemaError!void {
3980 file.mod.root.sub_path,4009 file.mod.root.sub_path,
3981 file.sub_file_path,4010 file.sub_file_path,
3982 }) catch |err| {4011 }) 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)});
3984 return error.AnalysisFail;4013 return error.AnalysisFail;
3985 };4014 };
3986 errdefer gpa.free(resolved_path);4015 errdefer gpa.free(resolved_path);
...@@ -4000,57 +4029,58 @@ const SemaDeclResult = packed struct {...@@ -4000,57 +4029,58 @@ const SemaDeclResult = packed struct {
4000 invalidate_decl_ref: bool,4029 invalidate_decl_ref: bool,
4001};4030};
40024031
4003fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {4032fn semaDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
4004 const tracy = trace(@src());4033 const tracy = trace(@src());
4005 defer tracy.end();4034 defer tracy.end();
40064035
4007 const decl = mod.declPtr(decl_index);4036 const decl = zcu.declPtr(decl_index);
4008 const ip = &mod.intern_pool;4037 const ip = &zcu.intern_pool;
40094038
4010 if (decl.getFileScope(mod).status != .success_zir) {4039 if (decl.getFileScope(zcu).status != .success_zir) {
4011 return error.AnalysisFail;4040 return error.AnalysisFail;
4012 }4041 }
40134042
4014 assert(!mod.declIsRoot(decl_index));4043 assert(!zcu.declIsRoot(decl_index));
40154044
4016 if (decl.zir_decl_index == .none and decl.owns_tv) {4045 if (decl.zir_decl_index == .none and decl.owns_tv) {
4017 // We are re-analyzing an anonymous owner Decl (for a function or a namespace type).4046 // 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);
4019 }4048 }
40204049
4021 log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});4050 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)});
4023 defer blk: {4052 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)});
4025 }4054 }
40264055
4027 const old_has_tv = decl.has_tv;4056 const old_has_tv = decl.has_tv;
4028 // The following values are ignored if `!old_has_tv`4057 // 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;
4030 const old_val = decl.val;4059 const old_val = decl.val;
4031 const old_align = decl.alignment;4060 const old_align = decl.alignment;
4032 const old_linksection = decl.@"linksection";4061 const old_linksection = decl.@"linksection";
4033 const old_addrspace = decl.@"addrspace";4062 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|
4035 prev_func.analysis(ip).state == .inline_only4064 prev_func.analysis(ip).state == .inline_only
4036 else4065 else
4037 false;4066 false;
40384067
4039 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);4068 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);
40404069
4041 const gpa = mod.gpa;4070 const gpa = zcu.gpa;
4042 const zir = decl.getFileScope(mod).zir;4071 const zir = decl.getFileScope(zcu).zir;
40434072
4044 const builtin_type_target_index: InternPool.Index = ip_index: {4073 const builtin_type_target_index: InternPool.Index = ip_index: {
4045 const std_mod = mod.std_mod;4074 const std_mod = zcu.std_mod;
4046 if (decl.getFileScope(mod).mod != std_mod) break :ip_index .none;4075 if (decl.getFileScope(zcu).mod != std_mod) break :ip_index .none;
4047 // We're in the std module.4076 // We're in the std module.
4048 const std_file = (try mod.importPkg(std_mod)).file;4077 const std_file_imported = try zcu.importPkg(std_mod);
4049 const std_decl = mod.declPtr(std_file.root_decl.unwrap().?);4078 const std_file_root_decl_index = zcu.fileRootDecl(std_file_imported.file_index);
4050 const std_namespace = std_decl.getInnerNamespace(mod).?;4079 const std_decl = zcu.declPtr(std_file_root_decl_index.unwrap().?);
4080 const std_namespace = std_decl.getInnerNamespace(zcu).?;
4051 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);4081 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);4082 const builtin_decl = zcu.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, DeclAdapter{ .zcu = zcu }) orelse break :ip_index .none);
4053 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(mod).unwrap() orelse break :ip_index .none;4083 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(zcu).unwrap() orelse break :ip_index .none;
4054 if (decl.src_namespace != builtin_namespace) break :ip_index .none;4084 if (decl.src_namespace != builtin_namespace) break :ip_index .none;
4055 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.4085 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.
4056 for ([_][]const u8{4086 for ([_][]const u8{
...@@ -4083,7 +4113,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4083,7 +4113,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4083 break :ip_index .none;4113 break :ip_index .none;
4084 };4114 };
40854115
4086 mod.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .decl = decl_index }));4116 zcu.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .decl = decl_index }));
40874117
4088 decl.analysis = .in_progress;4118 decl.analysis = .in_progress;
40894119
...@@ -4094,7 +4124,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4094,7 +4124,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4094 defer comptime_err_ret_trace.deinit();4124 defer comptime_err_ret_trace.deinit();
40954125
4096 var sema: Sema = .{4126 var sema: Sema = .{
4097 .mod = mod,4127 .mod = zcu,
4098 .gpa = gpa,4128 .gpa = gpa,
4099 .arena = analysis_arena.allocator(),4129 .arena = analysis_arena.allocator(),
4100 .code = zir,4130 .code = zir,
...@@ -4112,8 +4142,8 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4112,8 +4142,8 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
41124142
4113 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.4143 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.
4114 try sema.declareDependency(.{ .src_hash = try ip.trackZir(4144 try sema.declareDependency(.{ .src_hash = try ip.trackZir(
4115 sema.gpa,4145 gpa,
4116 decl.getFileScope(mod),4146 decl.getFileScopeIndex(zcu),
4117 decl_inst,4147 decl_inst,
4118 ) });4148 ) });
41194149
...@@ -4129,7 +4159,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4129,7 +4159,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4129 };4159 };
4130 defer block_scope.instructions.deinit(gpa);4160 defer block_scope.instructions.deinit(gpa);
41314161
4132 const decl_bodies = decl.zirBodies(mod);4162 const decl_bodies = decl.zirBodies(zcu);
41334163
4134 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);4164 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);
4135 // We'll do some other bits with the Sema. Clear the type target index just4165 // 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 {...@@ -4141,22 +4171,22 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4141 const ty_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_ty = 0 });4171 const ty_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_ty = 0 });
4142 const init_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_init = 0 });4172 const init_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_init = 0 });
4143 const decl_val = try sema.resolveFinalDeclValue(&block_scope, init_src, result_ref);4173 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
4146 // Note this resolves the type of the Decl, not the value; if this Decl4176 // Note this resolves the type of the Decl, not the value; if this Decl
4147 // is a struct, for example, this resolves `type` (which needs no resolution),4177 // is a struct, for example, this resolves `type` (which needs no resolution),
4148 // not the struct itself.4178 // not the struct itself.
4149 try decl_ty.resolveLayout(mod);4179 try decl_ty.resolveLayout(zcu);
41504180
4151 if (decl.kind == .@"usingnamespace") {4181 if (decl.kind == .@"usingnamespace") {
4152 if (!decl_ty.eql(Type.type, mod)) {4182 if (!decl_ty.eql(Type.type, zcu)) {
4153 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{4183 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{
4154 decl_ty.fmt(mod),4184 decl_ty.fmt(zcu),
4155 });4185 });
4156 }4186 }
4157 const ty = decl_val.toType();4187 const ty = decl_val.toType();
4158 if (ty.getNamespace(mod) == null) {4188 if (ty.getNamespace(zcu) == null) {
4159 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(mod)});4189 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(zcu)});
4160 }4190 }
41614191
4162 decl.val = ty.toValue();4192 decl.val = ty.toValue();
...@@ -4194,7 +4224,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4194,7 +4224,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4194 .func => |func| {4224 .func => |func| {
4195 decl.owns_tv = func.owner_decl == decl_index;4225 decl.owns_tv = func.owner_decl == decl_index;
4196 queue_linker_work = false;4226 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;
4198 is_func = decl.owns_tv;4228 is_func = decl.owns_tv;
4199 },4229 },
42004230
...@@ -4246,10 +4276,10 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4246,10 +4276,10 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4246 decl.analysis = .complete;4276 decl.analysis = .complete;
42474277
4248 const result: SemaDeclResult = if (old_has_tv) .{4278 const result: SemaDeclResult = if (old_has_tv) .{
4249 .invalidate_decl_val = !decl_ty.eql(old_ty, mod) or4279 .invalidate_decl_val = !decl_ty.eql(old_ty, zcu) or
4250 !decl.val.eql(old_val, decl_ty, mod) or4280 !decl.val.eql(old_val, decl_ty, zcu) or
4251 is_inline != old_is_inline,4281 is_inline != old_is_inline,
4252 .invalidate_decl_ref = !decl_ty.eql(old_ty, mod) or4282 .invalidate_decl_ref = !decl_ty.eql(old_ty, zcu) or
4253 decl.alignment != old_align or4283 decl.alignment != old_align or
4254 decl.@"linksection" != old_linksection or4284 decl.@"linksection" != old_linksection or
4255 decl.@"addrspace" != old_addrspace or4285 decl.@"addrspace" != old_addrspace or
...@@ -4263,12 +4293,12 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {...@@ -4263,12 +4293,12 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
4263 if (has_runtime_bits) {4293 if (has_runtime_bits) {
4264 // Needed for codegen_decl which will call updateDecl and then the4294 // Needed for codegen_decl which will call updateDecl and then the
4265 // codegen backend wants full access to the Decl Type.4295 // 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) {4300 if (result.invalidate_decl_ref and zcu.emit_h != null) {
4271 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });4301 try zcu.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
4272 }4302 }
4273 }4303 }
42744304
...@@ -4322,6 +4352,7 @@ fn semaAnonOwnerDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {...@@ -4322,6 +4352,7 @@ fn semaAnonOwnerDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
43224352
4323pub const ImportFileResult = struct {4353pub const ImportFileResult = struct {
4324 file: *File,4354 file: *File,
4355 file_index: File.Index,
4325 is_new: bool,4356 is_new: bool,
4326 is_pkg: bool,4357 is_pkg: bool,
4327};4358};
...@@ -4344,20 +4375,27 @@ pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {...@@ -4344,20 +4375,27 @@ pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
4344 errdefer _ = zcu.import_table.pop();4375 errdefer _ = zcu.import_table.pop();
4345 if (gop.found_existing) {4376 if (gop.found_existing) {
4346 try gop.value_ptr.*.addReference(zcu.*, .{ .root = mod });4377 try gop.value_ptr.*.addReference(zcu.*, .{ .root = mod });
4347 return ImportFileResult{4378 return .{
4348 .file = gop.value_ptr.*,4379 .file = gop.value_ptr.*,
4380 .file_index = @enumFromInt(gop.index),
4349 .is_new = false,4381 .is_new = false,
4350 .is_pkg = true,4382 .is_pkg = true,
4351 };4383 };
4352 }4384 }
43534385
4386 const ip = &zcu.intern_pool;
4387
4388 try ip.files.ensureUnusedCapacity(gpa, 1);
4389
4354 if (mod.builtin_file) |builtin_file| {4390 if (mod.builtin_file) |builtin_file| {
4355 keep_resolved_path = true; // It's now owned by import_table.4391 keep_resolved_path = true; // It's now owned by import_table.
4356 gop.value_ptr.* = builtin_file;4392 gop.value_ptr.* = builtin_file;
4357 try builtin_file.addReference(zcu.*, .{ .root = mod });4393 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);
4359 return .{4396 return .{
4360 .file = builtin_file,4397 .file = builtin_file,
4398 .file_index = @enumFromInt(ip.files.entries.len - 1),
4361 .is_new = false,4399 .is_new = false,
4362 .is_pkg = true,4400 .is_pkg = true,
4363 };4401 };
...@@ -4382,43 +4420,36 @@ pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {...@@ -4382,43 +4420,36 @@ pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
4382 .zir = undefined,4420 .zir = undefined,
4383 .status = .never_loaded,4421 .status = .never_loaded,
4384 .mod = mod,4422 .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 },
4400 };4423 };
4424
4425 const path_digest = computePathDigest(zcu, mod, sub_file_path);
4426
4401 try new_file.addReference(zcu.*, .{ .root = mod });4427 try new_file.addReference(zcu.*, .{ .root = mod });
4402 try zcu.path_digest_map.put(gpa, new_file.path_digest, {});4428 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
4403 return ImportFileResult{4429 return .{
4404 .file = new_file,4430 .file = new_file,
4431 .file_index = @enumFromInt(ip.files.entries.len - 1),
4405 .is_new = true,4432 .is_new = true,
4406 .is_pkg = true,4433 .is_pkg = true,
4407 };4434 };
4408}4435}
44094436
4437/// Called from a worker thread during AstGen.
4438/// Also called from Sema during semantic analysis.
4410pub fn importFile(4439pub fn importFile(
4411 zcu: *Zcu,4440 zcu: *Zcu,
4412 cur_file: *File,4441 cur_file: *File,
4413 import_string: []const u8,4442 import_string: []const u8,
4414) !ImportFileResult {4443) !ImportFileResult {
4444 const mod = cur_file.mod;
4445
4415 if (std.mem.eql(u8, import_string, "std")) {4446 if (std.mem.eql(u8, import_string, "std")) {
4416 return zcu.importPkg(zcu.std_mod);4447 return zcu.importPkg(zcu.std_mod);
4417 }4448 }
4418 if (std.mem.eql(u8, import_string, "root")) {4449 if (std.mem.eql(u8, import_string, "root")) {
4419 return zcu.importPkg(zcu.root_mod);4450 return zcu.importPkg(zcu.root_mod);
4420 }4451 }
4421 if (cur_file.mod.deps.get(import_string)) |pkg| {4452 if (mod.deps.get(import_string)) |pkg| {
4422 return zcu.importPkg(pkg);4453 return zcu.importPkg(pkg);
4423 }4454 }
4424 if (!mem.endsWith(u8, import_string, ".zig")) {4455 if (!mem.endsWith(u8, import_string, ".zig")) {
...@@ -4430,8 +4461,8 @@ pub fn importFile(...@@ -4430,8 +4461,8 @@ pub fn importFile(
4430 // an import refers to the same as another, despite different relative paths4461 // an import refers to the same as another, despite different relative paths
4431 // or differently mapped package names.4462 // or differently mapped package names.
4432 const resolved_path = try std.fs.path.resolve(gpa, &.{4463 const resolved_path = try std.fs.path.resolve(gpa, &.{
4433 cur_file.mod.root.root_dir.path orelse ".",4464 mod.root.root_dir.path orelse ".",
4434 cur_file.mod.root.sub_path,4465 mod.root.sub_path,
4435 cur_file.sub_file_path,4466 cur_file.sub_file_path,
4436 "..",4467 "..",
4437 import_string,4468 import_string,
...@@ -4442,18 +4473,23 @@ pub fn importFile(...@@ -4442,18 +4473,23 @@ pub fn importFile(
44424473
4443 const gop = try zcu.import_table.getOrPut(gpa, resolved_path);4474 const gop = try zcu.import_table.getOrPut(gpa, resolved_path);
4444 errdefer _ = zcu.import_table.pop();4475 errdefer _ = zcu.import_table.pop();
4445 if (gop.found_existing) return ImportFileResult{4476 if (gop.found_existing) return .{
4446 .file = gop.value_ptr.*,4477 .file = gop.value_ptr.*,
4478 .file_index = @enumFromInt(gop.index),
4447 .is_new = false,4479 .is_new = false,
4448 .is_pkg = false,4480 .is_pkg = false,
4449 };4481 };
44504482
4483 const ip = &zcu.intern_pool;
4484
4485 try ip.files.ensureUnusedCapacity(gpa, 1);
4486
4451 const new_file = try gpa.create(File);4487 const new_file = try gpa.create(File);
4452 errdefer gpa.destroy(new_file);4488 errdefer gpa.destroy(new_file);
44534489
4454 const resolved_root_path = try std.fs.path.resolve(gpa, &.{4490 const resolved_root_path = try std.fs.path.resolve(gpa, &.{
4455 cur_file.mod.root.root_dir.path orelse ".",4491 mod.root.root_dir.path orelse ".",
4456 cur_file.mod.root.sub_path,4492 mod.root.sub_path,
4457 });4493 });
4458 defer gpa.free(resolved_root_path);4494 defer gpa.free(resolved_root_path);
44594495
...@@ -4484,26 +4520,14 @@ pub fn importFile(...@@ -4484,26 +4520,14 @@ pub fn importFile(
4484 .tree = undefined,4520 .tree = undefined,
4485 .zir = undefined,4521 .zir = undefined,
4486 .status = .never_loaded,4522 .status = .never_loaded,
4487 .mod = cur_file.mod,4523 .mod = 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 },
4503 };4524 };
4504 try zcu.path_digest_map.put(gpa, new_file.path_digest, {});4525
4505 return ImportFileResult{4526 const path_digest = computePathDigest(zcu, mod, sub_file_path);
4527 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
4528 return .{
4506 .file = new_file,4529 .file = new_file,
4530 .file_index = @enumFromInt(ip.files.entries.len - 1),
4507 .is_new = true,4531 .is_new = true,
4508 .is_pkg = false,4532 .is_pkg = false,
4509 };4533 };
...@@ -4581,6 +4605,21 @@ pub fn embedFile(...@@ -4581,6 +4605,21 @@ pub fn embedFile(
4581 return newEmbedFile(mod, cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);4605 return newEmbedFile(mod, cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);
4582}4606}
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
4584/// https://github.com/ziglang/zig/issues/143074623/// https://github.com/ziglang/zig/issues/14307
4585fn newEmbedFile(4624fn newEmbedFile(
4586 mod: *Module,4625 mod: *Module,
...@@ -4765,7 +4804,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void...@@ -4765,7 +4804,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
4765 const namespace_index = iter.namespace_index;4804 const namespace_index = iter.namespace_index;
4766 const namespace = zcu.namespacePtr(namespace_index);4805 const namespace = zcu.namespacePtr(namespace_index);
4767 const gpa = zcu.gpa;4806 const gpa = zcu.gpa;
4768 const zir = namespace.file_scope.zir;4807 const zir = namespace.fileScope(zcu).zir;
4769 const ip = &zcu.intern_pool;4808 const ip = &zcu.intern_pool;
47704809
4771 const inst_data = zir.instructions.items(.data)[@intFromEnum(decl_inst)].declaration;4810 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...@@ -4848,7 +4887,8 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
4848 else => {},4887 else => {},
4849 }4888 }
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
4853 // We create a Decl for it regardless of analysis status.4893 // 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...@@ -4878,7 +4918,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
4878 namespace.decls.putAssumeCapacityNoClobberContext(decl_index, {}, .{ .zcu = zcu });4918 namespace.decls.putAssumeCapacityNoClobberContext(decl_index, {}, .{ .zcu = zcu });
48794919
4880 const comp = zcu.comp;4920 const comp = zcu.comp;
4881 const decl_mod = namespace.file_scope.mod;4921 const decl_mod = namespace.fileScope(zcu).mod;
4882 const want_analysis = declaration.flags.is_export or switch (kind) {4922 const want_analysis = declaration.flags.is_export or switch (kind) {
4883 .anon => unreachable,4923 .anon => unreachable,
4884 .@"comptime" => true,4924 .@"comptime" => true,
...@@ -4908,7 +4948,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void...@@ -4908,7 +4948,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
4908 // re-analysis for us if necessary.4948 // re-analysis for us if necessary.
4909 if (prev_exported != declaration.flags.is_export or decl.analysis == .unreferenced) {4949 if (prev_exported != declaration.flags.is_export or decl.analysis == .unreferenced) {
4910 log.debug("scanDecl queue analyze_decl file='{s}' decl_name='{}' decl_index={d}", .{4950 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,
4912 });4952 });
4913 comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = decl_index });4953 comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = decl_index });
4914 }4954 }
...@@ -5512,77 +5552,78 @@ fn handleUpdateExports(...@@ -5512,77 +5552,78 @@ fn handleUpdateExports(
5512}5552}
55135553
5514pub fn populateTestFunctions(5554pub fn populateTestFunctions(
5515 mod: *Module,5555 zcu: *Zcu,
5516 main_progress_node: std.Progress.Node,5556 main_progress_node: std.Progress.Node,
5517) !void {5557) !void {
5518 const gpa = mod.gpa;5558 const gpa = zcu.gpa;
5519 const ip = &mod.intern_pool;5559 const ip = &zcu.intern_pool;
5520 const builtin_mod = mod.root_mod.getBuiltinDependency();5560 const builtin_mod = zcu.root_mod.getBuiltinDependency();
5521 const builtin_file = (mod.importPkg(builtin_mod) catch unreachable).file;5561 const builtin_file_index = (zcu.importPkg(builtin_mod) catch unreachable).file_index;
5522 const root_decl = mod.declPtr(builtin_file.root_decl.unwrap().?);5562 const root_decl_index = zcu.fileRootDecl(builtin_file_index);
5523 const builtin_namespace = mod.namespacePtr(root_decl.src_namespace);5563 const root_decl = zcu.declPtr(root_decl_index.unwrap().?);
5564 const builtin_namespace = zcu.namespacePtr(root_decl.src_namespace);
5524 const test_functions_str = try ip.getOrPutString(gpa, "test_functions", .no_embedded_nulls);5565 const test_functions_str = try ip.getOrPutString(gpa, "test_functions", .no_embedded_nulls);
5525 const decl_index = builtin_namespace.decls.getKeyAdapted(5566 const decl_index = builtin_namespace.decls.getKeyAdapted(
5526 test_functions_str,5567 test_functions_str,
5527 DeclAdapter{ .zcu = mod },5568 DeclAdapter{ .zcu = zcu },
5528 ).?;5569 ).?;
5529 {5570 {
5530 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`5571 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`
5531 // was not referenced by start code.5572 // 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);
5533 defer {5574 defer {
5534 mod.sema_prog_node.end();5575 zcu.sema_prog_node.end();
5535 mod.sema_prog_node = undefined;5576 zcu.sema_prog_node = undefined;
5536 }5577 }
5537 try mod.ensureDeclAnalyzed(decl_index);5578 try zcu.ensureDeclAnalyzed(decl_index);
5538 }5579 }
55395580
5540 const decl = mod.declPtr(decl_index);5581 const decl = zcu.declPtr(decl_index);
5541 const test_fn_ty = decl.typeOf(mod).slicePtrFieldType(mod).childType(mod);5582 const test_fn_ty = decl.typeOf(zcu).slicePtrFieldType(zcu).childType(zcu);
55425583
5543 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {5584 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
5544 // Add mod.test_functions to an array decl then make the test_functions5585 // Add zcu.test_functions to an array decl then make the test_functions
5545 // decl reference it as a slice.5586 // 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());
5547 defer gpa.free(test_fn_vals);5588 defer gpa.free(test_fn_vals);
55485589
5549 for (test_fn_vals, mod.test_functions.keys()) |*test_fn_val, test_decl_index| {5590 for (test_fn_vals, zcu.test_functions.keys()) |*test_fn_val, test_decl_index| {
5550 const test_decl = mod.declPtr(test_decl_index);5591 const test_decl = zcu.declPtr(test_decl_index);
5551 const test_decl_name = try test_decl.fullyQualifiedName(mod);5592 const test_decl_name = try test_decl.fullyQualifiedName(zcu);
5552 const test_decl_name_len = test_decl_name.length(ip);5593 const test_decl_name_len = test_decl_name.length(ip);
5553 const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {5594 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(.{
5555 .len = test_decl_name_len,5596 .len = test_decl_name_len,
5556 .child = .u8_type,5597 .child = .u8_type,
5557 });5598 });
5558 const test_name_val = try mod.intern(.{ .aggregate = .{5599 const test_name_val = try zcu.intern(.{ .aggregate = .{
5559 .ty = test_name_ty.toIntern(),5600 .ty = test_name_ty.toIntern(),
5560 .storage = .{ .bytes = test_decl_name.toString() },5601 .storage = .{ .bytes = test_decl_name.toString() },
5561 } });5602 } });
5562 break :n .{5603 break :n .{
5563 .orig_ty = (try mod.singleConstPtrType(test_name_ty)).toIntern(),5604 .orig_ty = (try zcu.singleConstPtrType(test_name_ty)).toIntern(),
5564 .val = test_name_val,5605 .val = test_name_val,
5565 };5606 };
5566 };5607 };
55675608
5568 const test_fn_fields = .{5609 const test_fn_fields = .{
5569 // name5610 // name
5570 try mod.intern(.{ .slice = .{5611 try zcu.intern(.{ .slice = .{
5571 .ty = .slice_const_u8_type,5612 .ty = .slice_const_u8_type,
5572 .ptr = try mod.intern(.{ .ptr = .{5613 .ptr = try zcu.intern(.{ .ptr = .{
5573 .ty = .manyptr_const_u8_type,5614 .ty = .manyptr_const_u8_type,
5574 .base_addr = .{ .anon_decl = test_name_anon_decl },5615 .base_addr = .{ .anon_decl = test_name_anon_decl },
5575 .byte_offset = 0,5616 .byte_offset = 0,
5576 } }),5617 } }),
5577 .len = try mod.intern(.{ .int = .{5618 .len = try zcu.intern(.{ .int = .{
5578 .ty = .usize_type,5619 .ty = .usize_type,
5579 .storage = .{ .u64 = test_decl_name_len },5620 .storage = .{ .u64 = test_decl_name_len },
5580 } }),5621 } }),
5581 } }),5622 } }),
5582 // func5623 // func
5583 try mod.intern(.{ .ptr = .{5624 try zcu.intern(.{ .ptr = .{
5584 .ty = try mod.intern(.{ .ptr_type = .{5625 .ty = try zcu.intern(.{ .ptr_type = .{
5585 .child = test_decl.typeOf(mod).toIntern(),5626 .child = test_decl.typeOf(zcu).toIntern(),
5586 .flags = .{5627 .flags = .{
5587 .is_const = true,5628 .is_const = true,
5588 },5629 },
...@@ -5591,29 +5632,29 @@ pub fn populateTestFunctions(...@@ -5591,29 +5632,29 @@ pub fn populateTestFunctions(
5591 .byte_offset = 0,5632 .byte_offset = 0,
5592 } }),5633 } }),
5593 };5634 };
5594 test_fn_val.* = try mod.intern(.{ .aggregate = .{5635 test_fn_val.* = try zcu.intern(.{ .aggregate = .{
5595 .ty = test_fn_ty.toIntern(),5636 .ty = test_fn_ty.toIntern(),
5596 .storage = .{ .elems = &test_fn_fields },5637 .storage = .{ .elems = &test_fn_fields },
5597 } });5638 } });
5598 }5639 }
55995640
5600 const array_ty = try mod.arrayType(.{5641 const array_ty = try zcu.arrayType(.{
5601 .len = test_fn_vals.len,5642 .len = test_fn_vals.len,
5602 .child = test_fn_ty.toIntern(),5643 .child = test_fn_ty.toIntern(),
5603 .sentinel = .none,5644 .sentinel = .none,
5604 });5645 });
5605 const array_val = try mod.intern(.{ .aggregate = .{5646 const array_val = try zcu.intern(.{ .aggregate = .{
5606 .ty = array_ty.toIntern(),5647 .ty = array_ty.toIntern(),
5607 .storage = .{ .elems = test_fn_vals },5648 .storage = .{ .elems = test_fn_vals },
5608 } });5649 } });
5609 break :array .{5650 break :array .{
5610 .orig_ty = (try mod.singleConstPtrType(array_ty)).toIntern(),5651 .orig_ty = (try zcu.singleConstPtrType(array_ty)).toIntern(),
5611 .val = array_val,5652 .val = array_val,
5612 };5653 };
5613 };5654 };
56145655
5615 {5656 {
5616 const new_ty = try mod.ptrType(.{5657 const new_ty = try zcu.ptrType(.{
5617 .child = test_fn_ty.toIntern(),5658 .child = test_fn_ty.toIntern(),
5618 .flags = .{5659 .flags = .{
5619 .is_const = true,5660 .is_const = true,
...@@ -5621,14 +5662,14 @@ pub fn populateTestFunctions(...@@ -5621,14 +5662,14 @@ pub fn populateTestFunctions(
5621 },5662 },
5622 });5663 });
5623 const new_val = decl.val;5664 const new_val = decl.val;
5624 const new_init = try mod.intern(.{ .slice = .{5665 const new_init = try zcu.intern(.{ .slice = .{
5625 .ty = new_ty.toIntern(),5666 .ty = new_ty.toIntern(),
5626 .ptr = try mod.intern(.{ .ptr = .{5667 .ptr = try zcu.intern(.{ .ptr = .{
5627 .ty = new_ty.slicePtrFieldType(mod).toIntern(),5668 .ty = new_ty.slicePtrFieldType(zcu).toIntern(),
5628 .base_addr = .{ .anon_decl = array_anon_decl },5669 .base_addr = .{ .anon_decl = array_anon_decl },
5629 .byte_offset = 0,5670 .byte_offset = 0,
5630 } }),5671 } }),
5631 .len = (try mod.intValue(Type.usize, mod.test_functions.count())).toIntern(),5672 .len = (try zcu.intValue(Type.usize, zcu.test_functions.count())).toIntern(),
5632 } });5673 } });
5633 ip.mutateVarInit(decl.val.toIntern(), new_init);5674 ip.mutateVarInit(decl.val.toIntern(), new_init);
56345675
...@@ -5638,13 +5679,13 @@ pub fn populateTestFunctions(...@@ -5638,13 +5679,13 @@ pub fn populateTestFunctions(
5638 decl.has_tv = true;5679 decl.has_tv = true;
5639 }5680 }
5640 {5681 {
5641 mod.codegen_prog_node = main_progress_node.start("Code Generation", 0);5682 zcu.codegen_prog_node = main_progress_node.start("Code Generation", 0);
5642 defer {5683 defer {
5643 mod.codegen_prog_node.end();5684 zcu.codegen_prog_node.end();
5644 mod.codegen_prog_node = undefined;5685 zcu.codegen_prog_node = undefined;
5645 }5686 }
56465687
5647 try mod.linkerUpdateDecl(decl_index);5688 try zcu.linkerUpdateDecl(decl_index);
5648 }5689 }
5649}5690}
56505691
...@@ -5684,31 +5725,35 @@ pub fn linkerUpdateDecl(zcu: *Zcu, decl_index: Decl.Index) !void {...@@ -5684,31 +5725,35 @@ pub fn linkerUpdateDecl(zcu: *Zcu, decl_index: Decl.Index) !void {
5684}5725}
56855726
5686fn reportRetryableFileError(5727fn reportRetryableFileError(
5687 mod: *Module,5728 zcu: *Zcu,
5688 file: *File,5729 file_index: File.Index,
5689 comptime format: []const u8,5730 comptime format: []const u8,
5690 args: anytype,5731 args: anytype,
5691) error{OutOfMemory}!void {5732) error{OutOfMemory}!void {
5733 const gpa = zcu.gpa;
5734 const ip = &zcu.intern_pool;
5735
5736 const file = zcu.fileByIndex(file_index);
5692 file.status = .retryable_failure;5737 file.status = .retryable_failure;
56935738
5694 const err_msg = try ErrorMsg.create(5739 const err_msg = try ErrorMsg.create(
5695 mod.gpa,5740 gpa,
5696 .{5741 .{
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),
5698 .offset = .entire_file,5743 .offset = .entire_file,
5699 },5744 },
5700 format,5745 format,
5701 args,5746 args,
5702 );5747 );
5703 errdefer err_msg.destroy(mod.gpa);5748 errdefer err_msg.destroy(gpa);
57045749
5705 mod.comp.mutex.lock();5750 zcu.comp.mutex.lock();
5706 defer mod.comp.mutex.unlock();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);
5709 if (gop.found_existing) {5754 if (gop.found_existing) {
5710 if (gop.value_ptr.*) |old_err_msg| {5755 if (gop.value_ptr.*) |old_err_msg| {
5711 old_err_msg.destroy(mod.gpa);5756 old_err_msg.destroy(gpa);
5712 }5757 }
5713 }5758 }
5714 gop.value_ptr.* = err_msg;5759 gop.value_ptr.* = err_msg;
...@@ -6528,8 +6573,9 @@ pub fn getBuiltin(zcu: *Zcu, name: []const u8) Allocator.Error!Air.Inst.Ref {...@@ -6528,8 +6573,9 @@ pub fn getBuiltin(zcu: *Zcu, name: []const u8) Allocator.Error!Air.Inst.Ref {
6528pub fn getBuiltinDecl(zcu: *Zcu, name: []const u8) Allocator.Error!InternPool.DeclIndex {6573pub fn getBuiltinDecl(zcu: *Zcu, name: []const u8) Allocator.Error!InternPool.DeclIndex {
6529 const gpa = zcu.gpa;6574 const gpa = zcu.gpa;
6530 const ip = &zcu.intern_pool;6575 const ip = &zcu.intern_pool;
6531 const std_file = (zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig")).file;6576 const std_file_imported = zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig");
6532 const std_namespace = zcu.declPtr(std_file.root_decl.unwrap().?).getOwnedInnerNamespace(zcu).?;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).?;
6533 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);6579 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
6534 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");6580 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
6535 zcu.ensureDeclAnalyzed(builtin_decl) catch @panic("std.builtin is corrupt");6581 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 {...@@ -6544,3 +6590,23 @@ pub fn getBuiltinType(zcu: *Zcu, name: []const u8) Allocator.Error!Type {
6544 ty.resolveFully(zcu) catch @panic("std.builtin is corrupt");6590 ty.resolveFully(zcu) catch @panic("std.builtin is corrupt");
6545 return ty;6591 return ty;
6546}6592}
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(...@@ -345,7 +345,7 @@ pub fn generate(
345 assert(fn_owner_decl.has_tv);345 assert(fn_owner_decl.has_tv);
346 const fn_type = fn_owner_decl.typeOf(zcu);346 const fn_type = fn_owner_decl.typeOf(zcu);
347 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);347 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
350 var branch_stack = std.ArrayList(Branch).init(gpa);350 var branch_stack = std.ArrayList(Branch).init(gpa);
351 defer {351 defer {
src/arch/arm/CodeGen.zig+1-1
...@@ -352,7 +352,7 @@ pub fn generate(...@@ -352,7 +352,7 @@ pub fn generate(
352 assert(fn_owner_decl.has_tv);352 assert(fn_owner_decl.has_tv);
353 const fn_type = fn_owner_decl.typeOf(zcu);353 const fn_type = fn_owner_decl.typeOf(zcu);
354 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);354 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
357 var branch_stack = std.ArrayList(Branch).init(gpa);357 var branch_stack = std.ArrayList(Branch).init(gpa);
358 defer {358 defer {
src/arch/riscv64/CodeGen.zig+2-2
...@@ -712,8 +712,8 @@ pub fn generate(...@@ -712,8 +712,8 @@ pub fn generate(
712 assert(fn_owner_decl.has_tv);712 assert(fn_owner_decl.has_tv);
713 const fn_type = fn_owner_decl.typeOf(zcu);713 const fn_type = fn_owner_decl.typeOf(zcu);
714 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);714 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
715 const target = &namespace.file_scope.mod.resolved_target.result;715 const target = &namespace.fileScope(zcu).mod.resolved_target.result;
716 const mod = namespace.file_scope.mod;716 const mod = namespace.fileScope(zcu).mod;
717717
718 var branch_stack = std.ArrayList(Branch).init(gpa);718 var branch_stack = std.ArrayList(Branch).init(gpa);
719 defer {719 defer {
src/arch/sparc64/CodeGen.zig+1-1
...@@ -277,7 +277,7 @@ pub fn generate(...@@ -277,7 +277,7 @@ pub fn generate(
277 assert(fn_owner_decl.has_tv);277 assert(fn_owner_decl.has_tv);
278 const fn_type = fn_owner_decl.typeOf(zcu);278 const fn_type = fn_owner_decl.typeOf(zcu);
279 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);279 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
282 var branch_stack = std.ArrayList(Branch).init(gpa);282 var branch_stack = std.ArrayList(Branch).init(gpa);
283 defer {283 defer {
src/arch/wasm/CodeGen.zig+6-6
...@@ -1212,11 +1212,11 @@ pub fn generate(...@@ -1212,11 +1212,11 @@ pub fn generate(
1212 _ = src_loc;1212 _ = src_loc;
1213 const comp = bin_file.comp;1213 const comp = bin_file.comp;
1214 const gpa = comp.gpa;1214 const gpa = comp.gpa;
1215 const mod = comp.module.?;1215 const zcu = comp.module.?;
1216 const func = mod.funcInfo(func_index);1216 const func = zcu.funcInfo(func_index);
1217 const decl = mod.declPtr(func.owner_decl);1217 const decl = zcu.declPtr(func.owner_decl);
1218 const namespace = mod.namespacePtr(decl.src_namespace);1218 const namespace = zcu.namespacePtr(decl.src_namespace);
1219 const target = namespace.file_scope.mod.resolved_target.result;1219 const target = namespace.fileScope(zcu).mod.resolved_target.result;
1220 var code_gen: CodeGen = .{1220 var code_gen: CodeGen = .{
1221 .gpa = gpa,1221 .gpa = gpa,
1222 .air = air,1222 .air = air,
...@@ -7706,7 +7706,7 @@ fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {...@@ -7706,7 +7706,7 @@ fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7706 // for a single-threaded build, can we emit the `fence` instruction.7706 // for a single-threaded build, can we emit the `fence` instruction.
7707 // In all other cases, we emit no instructions for a fence.7707 // In all other cases, we emit no instructions for a fence.
7708 const func_namespace = zcu.namespacePtr(func.decl.src_namespace);7708 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;
7710 if (func.useAtomicFeature() and !single_threaded) {7710 if (func.useAtomicFeature() and !single_threaded) {
7711 try func.addAtomicTag(.atomic_fence);7711 try func.addAtomicTag(.atomic_fence);
7712 }7712 }
src/arch/x86_64/CodeGen.zig+1-1
...@@ -810,7 +810,7 @@ pub fn generate(...@@ -810,7 +810,7 @@ pub fn generate(
810 assert(fn_owner_decl.has_tv);810 assert(fn_owner_decl.has_tv);
811 const fn_type = fn_owner_decl.typeOf(zcu);811 const fn_type = fn_owner_decl.typeOf(zcu);
812 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);812 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
813 const mod = namespace.file_scope.mod;813 const mod = namespace.fileScope(zcu).mod;
814814
815 var function = Self{815 var function = Self{
816 .gpa = gpa,816 .gpa = gpa,
src/codegen.zig+6-6
...@@ -58,7 +58,7 @@ pub fn generateFunction(...@@ -58,7 +58,7 @@ pub fn generateFunction(
58 const func = zcu.funcInfo(func_index);58 const func = zcu.funcInfo(func_index);
59 const decl = zcu.declPtr(func.owner_decl);59 const decl = zcu.declPtr(func.owner_decl);
60 const namespace = zcu.namespacePtr(decl.src_namespace);60 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;
62 switch (target.cpu.arch) {62 switch (target.cpu.arch) {
63 .arm,63 .arm,
64 .armeb,64 .armeb,
...@@ -88,7 +88,7 @@ pub fn generateLazyFunction(...@@ -88,7 +88,7 @@ pub fn generateLazyFunction(
88 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);88 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
89 const decl = zcu.declPtr(decl_index);89 const decl = zcu.declPtr(decl_index);
90 const namespace = zcu.namespacePtr(decl.src_namespace);90 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;
92 switch (target.cpu.arch) {92 switch (target.cpu.arch) {
93 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, src_loc, lazy_sym, code, debug_output),93 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, src_loc, lazy_sym, code, debug_output),
94 else => unreachable,94 else => unreachable,
...@@ -742,7 +742,7 @@ fn lowerDeclRef(...@@ -742,7 +742,7 @@ fn lowerDeclRef(
742 const zcu = lf.comp.module.?;742 const zcu = lf.comp.module.?;
743 const decl = zcu.declPtr(decl_index);743 const decl = zcu.declPtr(decl_index);
744 const namespace = zcu.namespacePtr(decl.src_namespace);744 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
747 const ptr_width = target.ptrBitWidth();747 const ptr_width = target.ptrBitWidth();
748 const is_fn_body = decl.typeOf(zcu).zigTypeTag(zcu) == .Fn;748 const is_fn_body = decl.typeOf(zcu).zigTypeTag(zcu) == .Fn;
...@@ -836,7 +836,7 @@ fn genDeclRef(...@@ -836,7 +836,7 @@ fn genDeclRef(
836836
837 const ptr_decl = zcu.declPtr(ptr_decl_index);837 const ptr_decl = zcu.declPtr(ptr_decl_index);
838 const namespace = zcu.namespacePtr(ptr_decl.src_namespace);838 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
841 const ptr_bits = target.ptrBitWidth();841 const ptr_bits = target.ptrBitWidth();
842 const ptr_bytes: u64 = @divExact(ptr_bits, 8);842 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
...@@ -875,7 +875,7 @@ fn genDeclRef(...@@ -875,7 +875,7 @@ fn genDeclRef(
875 }875 }
876876
877 const decl_namespace = zcu.namespacePtr(decl.src_namespace);877 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;
879 const is_threadlocal = val.isPtrToThreadLocal(zcu) and !single_threaded;879 const is_threadlocal = val.isPtrToThreadLocal(zcu) and !single_threaded;
880 const is_extern = decl.isExtern(zcu);880 const is_extern = decl.isExtern(zcu);
881881
...@@ -985,7 +985,7 @@ pub fn genTypedValue(...@@ -985,7 +985,7 @@ pub fn genTypedValue(
985985
986 const owner_decl = zcu.declPtr(owner_decl_index);986 const owner_decl = zcu.declPtr(owner_decl_index);
987 const namespace = zcu.namespacePtr(owner_decl.src_namespace);987 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;
989 const ptr_bits = target.ptrBitWidth();989 const ptr_bits = target.ptrBitWidth();
990990
991 if (!ty.isSlice(zcu)) switch (ip.indexToKey(val.toIntern())) {991 if (!ty.isSlice(zcu)) switch (ip.indexToKey(val.toIntern())) {
src/codegen/c.zig+1-1
...@@ -2581,7 +2581,7 @@ pub fn genTypeDecl(...@@ -2581,7 +2581,7 @@ pub fn genTypeDecl(
2581 _ = try renderTypePrefix(.flush, global_ctype_pool, zcu, writer, global_ctype, .suffix, .{});2581 _ = try renderTypePrefix(.flush, global_ctype_pool, zcu, writer, global_ctype, .suffix, .{});
2582 try writer.writeByte(';');2582 try writer.writeByte(';');
2583 const owner_decl = zcu.declPtr(owner_decl_index);2583 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;
2585 if (!owner_mod.strip) {2585 if (!owner_mod.strip) {
2586 try writer.writeAll(" /* ");2586 try writer.writeAll(" /* ");
2587 try owner_decl.renderFullyQualifiedName(zcu, writer);2587 try owner_decl.renderFullyQualifiedName(zcu, writer);
src/codegen/llvm.zig+150-141
...@@ -1362,7 +1362,8 @@ pub const Object = struct {...@@ -1362,7 +1362,8 @@ pub const Object = struct {
1362 const decl_index = func.owner_decl;1362 const decl_index = func.owner_decl;
1363 const decl = zcu.declPtr(decl_index);1363 const decl = zcu.declPtr(decl_index);
1364 const namespace = zcu.namespacePtr(decl.src_namespace);1364 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;
1366 const fn_info = zcu.typeToFunc(decl.typeOf(zcu)).?;1367 const fn_info = zcu.typeToFunc(decl.typeOf(zcu)).?;
1367 const target = owner_mod.resolved_target.result;1368 const target = owner_mod.resolved_target.result;
1368 const ip = &zcu.intern_pool;1369 const ip = &zcu.intern_pool;
...@@ -1633,7 +1634,7 @@ pub const Object = struct {...@@ -1633,7 +1634,7 @@ pub const Object = struct {
1633 function_index.setAttributes(try attributes.finish(&o.builder), &o.builder);1634 function_index.setAttributes(try attributes.finish(&o.builder), &o.builder);
16341635
1635 const file, const subprogram = if (!wip.strip) debug_info: {1636 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
1638 const line_number = decl.navSrcLine(zcu) + 1;1639 const line_number = decl.navSrcLine(zcu) + 1;
1639 const is_internal_linkage = decl.val.getExternFunc(zcu) == null;1640 const is_internal_linkage = decl.val.getExternFunc(zcu) == null;
...@@ -1720,23 +1721,23 @@ pub const Object = struct {...@@ -1720,23 +1721,23 @@ pub const Object = struct {
17201721
1721 pub fn updateExports(1722 pub fn updateExports(
1722 self: *Object,1723 self: *Object,
1723 mod: *Module,1724 zcu: *Zcu,
1724 exported: Module.Exported,1725 exported: Module.Exported,
1725 export_indices: []const u32,1726 export_indices: []const u32,
1726 ) link.File.UpdateExportsError!void {1727 ) link.File.UpdateExportsError!void {
1727 const decl_index = switch (exported) {1728 const decl_index = switch (exported) {
1728 .decl_index => |i| i,1729 .decl_index => |i| i,
1729 .value => |val| return updateExportedValue(self, mod, val, export_indices),1730 .value => |val| return updateExportedValue(self, zcu, val, export_indices),
1730 };1731 };
1731 const ip = &mod.intern_pool;1732 const ip = &zcu.intern_pool;
1732 const global_index = self.decl_map.get(decl_index).?;1733 const global_index = self.decl_map.get(decl_index).?;
1733 const decl = mod.declPtr(decl_index);1734 const decl = zcu.declPtr(decl_index);
1734 const comp = mod.comp;1735 const comp = zcu.comp;
17351736
1736 if (export_indices.len != 0) {1737 if (export_indices.len != 0) {
1737 return updateExportedGlobal(self, mod, global_index, export_indices);1738 return updateExportedGlobal(self, zcu, global_index, export_indices);
1738 } else {1739 } 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));
1740 try global_index.rename(fqn, &self.builder);1741 try global_index.rename(fqn, &self.builder);
1741 global_index.setLinkage(.internal, &self.builder);1742 global_index.setLinkage(.internal, &self.builder);
1742 if (comp.config.dll_export_fns)1743 if (comp.config.dll_export_fns)
...@@ -1908,12 +1909,12 @@ pub const Object = struct {...@@ -1908,12 +1909,12 @@ pub const Object = struct {
19081909
1909 const gpa = o.gpa;1910 const gpa = o.gpa;
1910 const target = o.target;1911 const target = o.target;
1911 const mod = o.module;1912 const zcu = o.module;
1912 const ip = &mod.intern_pool;1913 const ip = &zcu.intern_pool;
19131914
1914 if (o.debug_type_map.get(ty)) |debug_type| return debug_type;1915 if (o.debug_type_map.get(ty)) |debug_type| return debug_type;
19151916
1916 switch (ty.zigTypeTag(mod)) {1917 switch (ty.zigTypeTag(zcu)) {
1917 .Void,1918 .Void,
1918 .NoReturn,1919 .NoReturn,
1919 => {1920 => {
...@@ -1925,12 +1926,12 @@ pub const Object = struct {...@@ -1925,12 +1926,12 @@ pub const Object = struct {
1925 return debug_void_type;1926 return debug_void_type;
1926 },1927 },
1927 .Int => {1928 .Int => {
1928 const info = ty.intInfo(mod);1929 const info = ty.intInfo(zcu);
1929 assert(info.bits != 0);1930 assert(info.bits != 0);
1930 const name = try o.allocTypeName(ty);1931 const name = try o.allocTypeName(ty);
1931 defer gpa.free(name);1932 defer gpa.free(name);
1932 const builder_name = try o.builder.metadataString(name);1933 const builder_name = try o.builder.metadataString(name);
1933 const debug_bits = ty.abiSize(mod) * 8; // lldb cannot handle non-byte sized types1934 const debug_bits = ty.abiSize(zcu) * 8; // lldb cannot handle non-byte sized types
1934 const debug_int_type = switch (info.signedness) {1935 const debug_int_type = switch (info.signedness) {
1935 .signed => try o.builder.debugSignedType(builder_name, debug_bits),1936 .signed => try o.builder.debugSignedType(builder_name, debug_bits),
1936 .unsigned => try o.builder.debugUnsignedType(builder_name, debug_bits),1937 .unsigned => try o.builder.debugUnsignedType(builder_name, debug_bits),
...@@ -1939,10 +1940,10 @@ pub const Object = struct {...@@ -1939,10 +1940,10 @@ pub const Object = struct {
1939 return debug_int_type;1940 return debug_int_type;
1940 },1941 },
1941 .Enum => {1942 .Enum => {
1942 const owner_decl_index = ty.getOwnerDecl(mod);1943 const owner_decl_index = ty.getOwnerDecl(zcu);
1943 const owner_decl = o.module.declPtr(owner_decl_index);1944 const owner_decl = o.module.declPtr(owner_decl_index);
19441945
1945 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) {1946 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1946 const debug_enum_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);1947 const debug_enum_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
1947 try o.debug_type_map.put(gpa, ty, debug_enum_type);1948 try o.debug_type_map.put(gpa, ty, debug_enum_type);
1948 return debug_enum_type;1949 return debug_enum_type;
...@@ -1954,13 +1955,13 @@ pub const Object = struct {...@@ -1954,13 +1955,13 @@ pub const Object = struct {
1954 defer gpa.free(enumerators);1955 defer gpa.free(enumerators);
19551956
1956 const int_ty = Type.fromInterned(enum_type.tag_ty);1957 const int_ty = Type.fromInterned(enum_type.tag_ty);
1957 const int_info = ty.intInfo(mod);1958 const int_info = ty.intInfo(zcu);
1958 assert(int_info.bits != 0);1959 assert(int_info.bits != 0);
19591960
1960 for (enum_type.names.get(ip), 0..) |field_name_ip, i| {1961 for (enum_type.names.get(ip), 0..) |field_name_ip, i| {
1961 var bigint_space: Value.BigIntSpace = undefined;1962 var bigint_space: Value.BigIntSpace = undefined;
1962 const bigint = if (enum_type.values.len != 0)1963 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)
1964 else1965 else
1965 std.math.big.int.Mutable.init(&bigint_space.limbs, i).toConst();1966 std.math.big.int.Mutable.init(&bigint_space.limbs, i).toConst();
19661967
...@@ -1972,7 +1973,8 @@ pub const Object = struct {...@@ -1972,7 +1973,8 @@ pub const Object = struct {
1972 );1973 );
1973 }1974 }
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);
1976 const scope = try o.namespaceToDebugScope(owner_decl.src_namespace);1978 const scope = try o.namespaceToDebugScope(owner_decl.src_namespace);
19771979
1978 const name = try o.allocTypeName(ty);1980 const name = try o.allocTypeName(ty);
...@@ -1982,10 +1984,10 @@ pub const Object = struct {...@@ -1982,10 +1984,10 @@ pub const Object = struct {
1982 try o.builder.metadataString(name),1984 try o.builder.metadataString(name),
1983 file,1985 file,
1984 scope,1986 scope,
1985 owner_decl.typeSrcLine(mod) + 1, // Line1987 owner_decl.typeSrcLine(zcu) + 1, // Line
1986 try o.lowerDebugType(int_ty),1988 try o.lowerDebugType(int_ty),
1987 ty.abiSize(mod) * 8,1989 ty.abiSize(zcu) * 8,
1988 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,1990 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
1989 try o.builder.debugTuple(enumerators),1991 try o.builder.debugTuple(enumerators),
1990 );1992 );
19911993
...@@ -2014,7 +2016,7 @@ pub const Object = struct {...@@ -2014,7 +2016,7 @@ pub const Object = struct {
2014 },2016 },
2015 .Pointer => {2017 .Pointer => {
2016 // Normalize everything that the debug info does not represent.2018 // Normalize everything that the debug info does not represent.
2017 const ptr_info = ty.ptrInfo(mod);2019 const ptr_info = ty.ptrInfo(zcu);
20182020
2019 if (ptr_info.sentinel != .none or2021 if (ptr_info.sentinel != .none or
2020 ptr_info.flags.address_space != .generic or2022 ptr_info.flags.address_space != .generic or
...@@ -2025,10 +2027,10 @@ pub const Object = struct {...@@ -2025,10 +2027,10 @@ pub const Object = struct {
2025 ptr_info.flags.is_const or2027 ptr_info.flags.is_const or
2026 ptr_info.flags.is_volatile or2028 ptr_info.flags.is_volatile or
2027 ptr_info.flags.size == .Many or ptr_info.flags.size == .C or2029 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))
2029 {2031 {
2030 const bland_ptr_ty = try mod.ptrType(.{2032 const bland_ptr_ty = try zcu.ptrType(.{
2031 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(mod))2033 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
2032 .anyopaque_type2034 .anyopaque_type
2033 else2035 else
2034 ptr_info.child,2036 ptr_info.child,
...@@ -2050,18 +2052,18 @@ pub const Object = struct {...@@ -2050,18 +2052,18 @@ pub const Object = struct {
2050 // Set as forward reference while the type is lowered in case it references itself2052 // Set as forward reference while the type is lowered in case it references itself
2051 try o.debug_type_map.put(gpa, ty, debug_fwd_ref);2053 try o.debug_type_map.put(gpa, ty, debug_fwd_ref);
20522054
2053 if (ty.isSlice(mod)) {2055 if (ty.isSlice(zcu)) {
2054 const ptr_ty = ty.slicePtrFieldType(mod);2056 const ptr_ty = ty.slicePtrFieldType(zcu);
2055 const len_ty = Type.usize;2057 const len_ty = Type.usize;
20562058
2057 const name = try o.allocTypeName(ty);2059 const name = try o.allocTypeName(ty);
2058 defer gpa.free(name);2060 defer gpa.free(name);
2059 const line = 0;2061 const line = 0;
20602062
2061 const ptr_size = ptr_ty.abiSize(mod);2063 const ptr_size = ptr_ty.abiSize(zcu);
2062 const ptr_align = ptr_ty.abiAlignment(mod);2064 const ptr_align = ptr_ty.abiAlignment(zcu);
2063 const len_size = len_ty.abiSize(mod);2065 const len_size = len_ty.abiSize(zcu);
2064 const len_align = len_ty.abiAlignment(mod);2066 const len_align = len_ty.abiAlignment(zcu);
20652067
2066 const len_offset = len_align.forward(ptr_size);2068 const len_offset = len_align.forward(ptr_size);
20672069
...@@ -2093,8 +2095,8 @@ pub const Object = struct {...@@ -2093,8 +2095,8 @@ pub const Object = struct {
2093 o.debug_compile_unit, // Scope2095 o.debug_compile_unit, // Scope
2094 line,2096 line,
2095 .none, // Underlying type2097 .none, // Underlying type
2096 ty.abiSize(mod) * 8,2098 ty.abiSize(zcu) * 8,
2097 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2099 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2098 try o.builder.debugTuple(&.{2100 try o.builder.debugTuple(&.{
2099 debug_ptr_type,2101 debug_ptr_type,
2100 debug_len_type,2102 debug_len_type,
...@@ -2122,7 +2124,7 @@ pub const Object = struct {...@@ -2122,7 +2124,7 @@ pub const Object = struct {
2122 0, // Line2124 0, // Line
2123 debug_elem_ty,2125 debug_elem_ty,
2124 target.ptrBitWidth(),2126 target.ptrBitWidth(),
2125 (ty.ptrAlignment(mod).toByteUnits() orelse 0) * 8,2127 (ty.ptrAlignment(zcu).toByteUnits() orelse 0) * 8,
2126 0, // Offset2128 0, // Offset
2127 );2129 );
21282130
...@@ -2146,13 +2148,14 @@ pub const Object = struct {...@@ -2146,13 +2148,14 @@ pub const Object = struct {
21462148
2147 const name = try o.allocTypeName(ty);2149 const name = try o.allocTypeName(ty);
2148 defer gpa.free(name);2150 defer gpa.free(name);
2149 const owner_decl_index = ty.getOwnerDecl(mod);2151 const owner_decl_index = ty.getOwnerDecl(zcu);
2150 const owner_decl = o.module.declPtr(owner_decl_index);2152 const owner_decl = o.module.declPtr(owner_decl_index);
2153 const file_scope = zcu.namespacePtr(owner_decl.src_namespace).fileScope(zcu);
2151 const debug_opaque_type = try o.builder.debugStructType(2154 const debug_opaque_type = try o.builder.debugStructType(
2152 try o.builder.metadataString(name),2155 try o.builder.metadataString(name),
2153 try o.getDebugFile(mod.namespacePtr(owner_decl.src_namespace).file_scope),2156 try o.getDebugFile(file_scope),
2154 try o.namespaceToDebugScope(owner_decl.src_namespace),2157 try o.namespaceToDebugScope(owner_decl.src_namespace),
2155 owner_decl.typeSrcLine(mod) + 1, // Line2158 owner_decl.typeSrcLine(zcu) + 1, // Line
2156 .none, // Underlying type2159 .none, // Underlying type
2157 0, // Size2160 0, // Size
2158 0, // Align2161 0, // Align
...@@ -2167,13 +2170,13 @@ pub const Object = struct {...@@ -2167,13 +2170,13 @@ pub const Object = struct {
2167 .none, // File2170 .none, // File
2168 .none, // Scope2171 .none, // Scope
2169 0, // Line2172 0, // Line
2170 try o.lowerDebugType(ty.childType(mod)),2173 try o.lowerDebugType(ty.childType(zcu)),
2171 ty.abiSize(mod) * 8,2174 ty.abiSize(zcu) * 8,
2172 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2175 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2173 try o.builder.debugTuple(&.{2176 try o.builder.debugTuple(&.{
2174 try o.builder.debugSubrange(2177 try o.builder.debugSubrange(
2175 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),2178 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))),
2177 ),2180 ),
2178 }),2181 }),
2179 );2182 );
...@@ -2181,14 +2184,14 @@ pub const Object = struct {...@@ -2181,14 +2184,14 @@ pub const Object = struct {
2181 return debug_array_type;2184 return debug_array_type;
2182 },2185 },
2183 .Vector => {2186 .Vector => {
2184 const elem_ty = ty.elemType2(mod);2187 const elem_ty = ty.elemType2(zcu);
2185 // Vector elements cannot be padded since that would make2188 // Vector elements cannot be padded since that would make
2186 // @bitSizOf(elem) * len > @bitSizOf(vec).2189 // @bitSizOf(elem) * len > @bitSizOf(vec).
2187 // Neither gdb nor lldb seem to be able to display non-byte sized2190 // Neither gdb nor lldb seem to be able to display non-byte sized
2188 // vectors properly.2191 // vectors properly.
2189 const debug_elem_type = switch (elem_ty.zigTypeTag(mod)) {2192 const debug_elem_type = switch (elem_ty.zigTypeTag(zcu)) {
2190 .Int => blk: {2193 .Int => blk: {
2191 const info = elem_ty.intInfo(mod);2194 const info = elem_ty.intInfo(zcu);
2192 assert(info.bits != 0);2195 assert(info.bits != 0);
2193 const name = try o.allocTypeName(ty);2196 const name = try o.allocTypeName(ty);
2194 defer gpa.free(name);2197 defer gpa.free(name);
...@@ -2202,7 +2205,7 @@ pub const Object = struct {...@@ -2202,7 +2205,7 @@ pub const Object = struct {
2202 try o.builder.metadataString("bool"),2205 try o.builder.metadataString("bool"),
2203 1,2206 1,
2204 ),2207 ),
2205 else => try o.lowerDebugType(ty.childType(mod)),2208 else => try o.lowerDebugType(ty.childType(zcu)),
2206 };2209 };
22072210
2208 const debug_vector_type = try o.builder.debugVectorType(2211 const debug_vector_type = try o.builder.debugVectorType(
...@@ -2211,12 +2214,12 @@ pub const Object = struct {...@@ -2211,12 +2214,12 @@ pub const Object = struct {
2211 .none, // Scope2214 .none, // Scope
2212 0, // Line2215 0, // Line
2213 debug_elem_type,2216 debug_elem_type,
2214 ty.abiSize(mod) * 8,2217 ty.abiSize(zcu) * 8,
2215 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2218 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2216 try o.builder.debugTuple(&.{2219 try o.builder.debugTuple(&.{
2217 try o.builder.debugSubrange(2220 try o.builder.debugSubrange(
2218 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),2221 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))),
2220 ),2223 ),
2221 }),2224 }),
2222 );2225 );
...@@ -2227,8 +2230,8 @@ pub const Object = struct {...@@ -2227,8 +2230,8 @@ pub const Object = struct {
2227 .Optional => {2230 .Optional => {
2228 const name = try o.allocTypeName(ty);2231 const name = try o.allocTypeName(ty);
2229 defer gpa.free(name);2232 defer gpa.free(name);
2230 const child_ty = ty.optionalChild(mod);2233 const child_ty = ty.optionalChild(zcu);
2231 if (!child_ty.hasRuntimeBitsIgnoreComptime(mod)) {2234 if (!child_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2232 const debug_bool_type = try o.builder.debugBoolType(2235 const debug_bool_type = try o.builder.debugBoolType(
2233 try o.builder.metadataString(name),2236 try o.builder.metadataString(name),
2234 8,2237 8,
...@@ -2242,7 +2245,7 @@ pub const Object = struct {...@@ -2242,7 +2245,7 @@ pub const Object = struct {
2242 // Set as forward reference while the type is lowered in case it references itself2245 // Set as forward reference while the type is lowered in case it references itself
2243 try o.debug_type_map.put(gpa, ty, debug_fwd_ref);2246 try o.debug_type_map.put(gpa, ty, debug_fwd_ref);
22442247
2245 if (ty.optionalReprIsPayload(mod)) {2248 if (ty.optionalReprIsPayload(zcu)) {
2246 const debug_optional_type = try o.lowerDebugType(child_ty);2249 const debug_optional_type = try o.lowerDebugType(child_ty);
22472250
2248 o.builder.debugForwardReferenceSetType(debug_fwd_ref, debug_optional_type);2251 o.builder.debugForwardReferenceSetType(debug_fwd_ref, debug_optional_type);
...@@ -2255,10 +2258,10 @@ pub const Object = struct {...@@ -2255,10 +2258,10 @@ pub const Object = struct {
2255 }2258 }
22562259
2257 const non_null_ty = Type.u8;2260 const non_null_ty = Type.u8;
2258 const payload_size = child_ty.abiSize(mod);2261 const payload_size = child_ty.abiSize(zcu);
2259 const payload_align = child_ty.abiAlignment(mod);2262 const payload_align = child_ty.abiAlignment(zcu);
2260 const non_null_size = non_null_ty.abiSize(mod);2263 const non_null_size = non_null_ty.abiSize(zcu);
2261 const non_null_align = non_null_ty.abiAlignment(mod);2264 const non_null_align = non_null_ty.abiAlignment(zcu);
2262 const non_null_offset = non_null_align.forward(payload_size);2265 const non_null_offset = non_null_align.forward(payload_size);
22632266
2264 const debug_data_type = try o.builder.debugMemberType(2267 const debug_data_type = try o.builder.debugMemberType(
...@@ -2289,8 +2292,8 @@ pub const Object = struct {...@@ -2289,8 +2292,8 @@ pub const Object = struct {
2289 o.debug_compile_unit, // Scope2292 o.debug_compile_unit, // Scope
2290 0, // Line2293 0, // Line
2291 .none, // Underlying type2294 .none, // Underlying type
2292 ty.abiSize(mod) * 8,2295 ty.abiSize(zcu) * 8,
2293 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2296 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2294 try o.builder.debugTuple(&.{2297 try o.builder.debugTuple(&.{
2295 debug_data_type,2298 debug_data_type,
2296 debug_some_type,2299 debug_some_type,
...@@ -2306,8 +2309,8 @@ pub const Object = struct {...@@ -2306,8 +2309,8 @@ pub const Object = struct {
2306 return debug_optional_type;2309 return debug_optional_type;
2307 },2310 },
2308 .ErrorUnion => {2311 .ErrorUnion => {
2309 const payload_ty = ty.errorUnionPayload(mod);2312 const payload_ty = ty.errorUnionPayload(zcu);
2310 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {2313 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2311 // TODO: Maybe remove?2314 // TODO: Maybe remove?
2312 const debug_error_union_type = try o.lowerDebugType(Type.anyerror);2315 const debug_error_union_type = try o.lowerDebugType(Type.anyerror);
2313 try o.debug_type_map.put(gpa, ty, debug_error_union_type);2316 try o.debug_type_map.put(gpa, ty, debug_error_union_type);
...@@ -2317,10 +2320,10 @@ pub const Object = struct {...@@ -2317,10 +2320,10 @@ pub const Object = struct {
2317 const name = try o.allocTypeName(ty);2320 const name = try o.allocTypeName(ty);
2318 defer gpa.free(name);2321 defer gpa.free(name);
23192322
2320 const error_size = Type.anyerror.abiSize(mod);2323 const error_size = Type.anyerror.abiSize(zcu);
2321 const error_align = Type.anyerror.abiAlignment(mod);2324 const error_align = Type.anyerror.abiAlignment(zcu);
2322 const payload_size = payload_ty.abiSize(mod);2325 const payload_size = payload_ty.abiSize(zcu);
2323 const payload_align = payload_ty.abiAlignment(mod);2326 const payload_align = payload_ty.abiAlignment(zcu);
23242327
2325 var error_index: u32 = undefined;2328 var error_index: u32 = undefined;
2326 var payload_index: u32 = undefined;2329 var payload_index: u32 = undefined;
...@@ -2368,8 +2371,8 @@ pub const Object = struct {...@@ -2368,8 +2371,8 @@ pub const Object = struct {
2368 o.debug_compile_unit, // Sope2371 o.debug_compile_unit, // Sope
2369 0, // Line2372 0, // Line
2370 .none, // Underlying type2373 .none, // Underlying type
2371 ty.abiSize(mod) * 8,2374 ty.abiSize(zcu) * 8,
2372 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2375 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2373 try o.builder.debugTuple(&fields),2376 try o.builder.debugTuple(&fields),
2374 );2377 );
23752378
...@@ -2390,14 +2393,14 @@ pub const Object = struct {...@@ -2390,14 +2393,14 @@ pub const Object = struct {
2390 const name = try o.allocTypeName(ty);2393 const name = try o.allocTypeName(ty);
2391 defer gpa.free(name);2394 defer gpa.free(name);
23922395
2393 if (mod.typeToPackedStruct(ty)) |struct_type| {2396 if (zcu.typeToPackedStruct(ty)) |struct_type| {
2394 const backing_int_ty = struct_type.backingIntType(ip).*;2397 const backing_int_ty = struct_type.backingIntType(ip).*;
2395 if (backing_int_ty != .none) {2398 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);
2397 const builder_name = try o.builder.metadataString(name);2400 const builder_name = try o.builder.metadataString(name);
2398 const debug_int_type = switch (info.signedness) {2401 const debug_int_type = switch (info.signedness) {
2399 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(mod) * 8),2402 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(zcu) * 8),
2400 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(mod) * 8),2403 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(zcu) * 8),
2401 };2404 };
2402 try o.debug_type_map.put(gpa, ty, debug_int_type);2405 try o.debug_type_map.put(gpa, ty, debug_int_type);
2403 return debug_int_type;2406 return debug_int_type;
...@@ -2417,10 +2420,10 @@ pub const Object = struct {...@@ -2417,10 +2420,10 @@ pub const Object = struct {
2417 const debug_fwd_ref = try o.builder.debugForwardReference();2420 const debug_fwd_ref = try o.builder.debugForwardReference();
24182421
2419 for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {2422 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);2425 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
2423 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);2426 const field_align = Type.fromInterned(field_ty).abiAlignment(zcu);
2424 const field_offset = field_align.forward(offset);2427 const field_offset = field_align.forward(offset);
2425 offset = field_offset + field_size;2428 offset = field_offset + field_size;
24262429
...@@ -2448,8 +2451,8 @@ pub const Object = struct {...@@ -2448,8 +2451,8 @@ pub const Object = struct {
2448 o.debug_compile_unit, // Scope2451 o.debug_compile_unit, // Scope
2449 0, // Line2452 0, // Line
2450 .none, // Underlying type2453 .none, // Underlying type
2451 ty.abiSize(mod) * 8,2454 ty.abiSize(zcu) * 8,
2452 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2455 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2453 try o.builder.debugTuple(fields.items),2456 try o.builder.debugTuple(fields.items),
2454 );2457 );
24552458
...@@ -2467,7 +2470,7 @@ pub const Object = struct {...@@ -2467,7 +2470,7 @@ pub const Object = struct {
2467 // into. Therefore we can satisfy this by making an empty namespace,2470 // into. Therefore we can satisfy this by making an empty namespace,
2468 // rather than changing the frontend to unnecessarily resolve the2471 // rather than changing the frontend to unnecessarily resolve the
2469 // struct field types.2472 // struct field types.
2470 const owner_decl_index = ty.getOwnerDecl(mod);2473 const owner_decl_index = ty.getOwnerDecl(zcu);
2471 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);2474 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
2472 try o.debug_type_map.put(gpa, ty, debug_struct_type);2475 try o.debug_type_map.put(gpa, ty, debug_struct_type);
2473 return debug_struct_type;2476 return debug_struct_type;
...@@ -2476,14 +2479,14 @@ pub const Object = struct {...@@ -2476,14 +2479,14 @@ pub const Object = struct {
2476 else => {},2479 else => {},
2477 }2480 }
24782481
2479 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) {2482 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2480 const owner_decl_index = ty.getOwnerDecl(mod);2483 const owner_decl_index = ty.getOwnerDecl(zcu);
2481 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);2484 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
2482 try o.debug_type_map.put(gpa, ty, debug_struct_type);2485 try o.debug_type_map.put(gpa, ty, debug_struct_type);
2483 return debug_struct_type;2486 return debug_struct_type;
2484 }2487 }
24852488
2486 const struct_type = mod.typeToStruct(ty).?;2489 const struct_type = zcu.typeToStruct(ty).?;
24872490
2488 var fields: std.ArrayListUnmanaged(Builder.Metadata) = .{};2491 var fields: std.ArrayListUnmanaged(Builder.Metadata) = .{};
2489 defer fields.deinit(gpa);2492 defer fields.deinit(gpa);
...@@ -2499,14 +2502,14 @@ pub const Object = struct {...@@ -2499,14 +2502,14 @@ pub const Object = struct {
2499 var it = struct_type.iterateRuntimeOrder(ip);2502 var it = struct_type.iterateRuntimeOrder(ip);
2500 while (it.next()) |field_index| {2503 while (it.next()) |field_index| {
2501 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);2504 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
2502 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;2505 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
2503 const field_size = field_ty.abiSize(mod);2506 const field_size = field_ty.abiSize(zcu);
2504 const field_align = mod.structFieldAlignment(2507 const field_align = zcu.structFieldAlignment(
2505 struct_type.fieldAlign(ip, field_index),2508 struct_type.fieldAlign(ip, field_index),
2506 field_ty,2509 field_ty,
2507 struct_type.layout,2510 struct_type.layout,
2508 );2511 );
2509 const field_offset = ty.structFieldOffset(field_index, mod);2512 const field_offset = ty.structFieldOffset(field_index, zcu);
25102513
2511 const field_name = struct_type.fieldName(ip, field_index).unwrap() orelse2514 const field_name = struct_type.fieldName(ip, field_index).unwrap() orelse
2512 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);2515 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
...@@ -2529,8 +2532,8 @@ pub const Object = struct {...@@ -2529,8 +2532,8 @@ pub const Object = struct {
2529 o.debug_compile_unit, // Scope2532 o.debug_compile_unit, // Scope
2530 0, // Line2533 0, // Line
2531 .none, // Underlying type2534 .none, // Underlying type
2532 ty.abiSize(mod) * 8,2535 ty.abiSize(zcu) * 8,
2533 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2536 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2534 try o.builder.debugTuple(fields.items),2537 try o.builder.debugTuple(fields.items),
2535 );2538 );
25362539
...@@ -2543,14 +2546,14 @@ pub const Object = struct {...@@ -2543,14 +2546,14 @@ pub const Object = struct {
2543 return debug_struct_type;2546 return debug_struct_type;
2544 },2547 },
2545 .Union => {2548 .Union => {
2546 const owner_decl_index = ty.getOwnerDecl(mod);2549 const owner_decl_index = ty.getOwnerDecl(zcu);
25472550
2548 const name = try o.allocTypeName(ty);2551 const name = try o.allocTypeName(ty);
2549 defer gpa.free(name);2552 defer gpa.free(name);
25502553
2551 const union_type = ip.loadUnionType(ty.toIntern());2554 const union_type = ip.loadUnionType(ty.toIntern());
2552 if (!union_type.haveFieldTypes(ip) or2555 if (!union_type.haveFieldTypes(ip) or
2553 !ty.hasRuntimeBitsIgnoreComptime(mod) or2556 !ty.hasRuntimeBitsIgnoreComptime(zcu) or
2554 !union_type.haveLayout(ip))2557 !union_type.haveLayout(ip))
2555 {2558 {
2556 const debug_union_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);2559 const debug_union_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
...@@ -2558,7 +2561,7 @@ pub const Object = struct {...@@ -2558,7 +2561,7 @@ pub const Object = struct {
2558 return debug_union_type;2561 return debug_union_type;
2559 }2562 }
25602563
2561 const layout = mod.getUnionLayout(union_type);2564 const layout = zcu.getUnionLayout(union_type);
25622565
2563 const debug_fwd_ref = try o.builder.debugForwardReference();2566 const debug_fwd_ref = try o.builder.debugForwardReference();
25642567
...@@ -2572,8 +2575,8 @@ pub const Object = struct {...@@ -2572,8 +2575,8 @@ pub const Object = struct {
2572 o.debug_compile_unit, // Scope2575 o.debug_compile_unit, // Scope
2573 0, // Line2576 0, // Line
2574 .none, // Underlying type2577 .none, // Underlying type
2575 ty.abiSize(mod) * 8,2578 ty.abiSize(zcu) * 8,
2576 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2579 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2577 try o.builder.debugTuple(2580 try o.builder.debugTuple(
2578 &.{try o.lowerDebugType(Type.fromInterned(union_type.enum_tag_ty))},2581 &.{try o.lowerDebugType(Type.fromInterned(union_type.enum_tag_ty))},
2579 ),2582 ),
...@@ -2600,12 +2603,12 @@ pub const Object = struct {...@@ -2600,12 +2603,12 @@ pub const Object = struct {
26002603
2601 for (0..tag_type.names.len) |field_index| {2604 for (0..tag_type.names.len) |field_index| {
2602 const field_ty = union_type.field_types.get(ip)[field_index];2605 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);
2606 const field_align: InternPool.Alignment = switch (union_type.flagsPtr(ip).layout) {2609 const field_align: InternPool.Alignment = switch (union_type.flagsPtr(ip).layout) {
2607 .@"packed" => .none,2610 .@"packed" => .none,
2608 .auto, .@"extern" => mod.unionFieldNormalAlignment(union_type, @intCast(field_index)),2611 .auto, .@"extern" => zcu.unionFieldNormalAlignment(union_type, @intCast(field_index)),
2609 };2612 };
26102613
2611 const field_name = tag_type.names.get(ip)[field_index];2614 const field_name = tag_type.names.get(ip)[field_index];
...@@ -2634,8 +2637,8 @@ pub const Object = struct {...@@ -2634,8 +2637,8 @@ pub const Object = struct {
2634 o.debug_compile_unit, // Scope2637 o.debug_compile_unit, // Scope
2635 0, // Line2638 0, // Line
2636 .none, // Underlying type2639 .none, // Underlying type
2637 ty.abiSize(mod) * 8,2640 ty.abiSize(zcu) * 8,
2638 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2641 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2639 try o.builder.debugTuple(fields.items),2642 try o.builder.debugTuple(fields.items),
2640 );2643 );
26412644
...@@ -2693,8 +2696,8 @@ pub const Object = struct {...@@ -2693,8 +2696,8 @@ pub const Object = struct {
2693 o.debug_compile_unit, // Scope2696 o.debug_compile_unit, // Scope
2694 0, // Line2697 0, // Line
2695 .none, // Underlying type2698 .none, // Underlying type
2696 ty.abiSize(mod) * 8,2699 ty.abiSize(zcu) * 8,
2697 (ty.abiAlignment(mod).toByteUnits() orelse 0) * 8,2700 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2698 try o.builder.debugTuple(&full_fields),2701 try o.builder.debugTuple(&full_fields),
2699 );2702 );
27002703
...@@ -2707,7 +2710,7 @@ pub const Object = struct {...@@ -2707,7 +2710,7 @@ pub const Object = struct {
2707 return debug_tagged_union_type;2710 return debug_tagged_union_type;
2708 },2711 },
2709 .Fn => {2712 .Fn => {
2710 const fn_info = mod.typeToFunc(ty).?;2713 const fn_info = zcu.typeToFunc(ty).?;
27112714
2712 var debug_param_types = std.ArrayList(Builder.Metadata).init(gpa);2715 var debug_param_types = std.ArrayList(Builder.Metadata).init(gpa);
2713 defer debug_param_types.deinit();2716 defer debug_param_types.deinit();
...@@ -2715,32 +2718,32 @@ pub const Object = struct {...@@ -2715,32 +2718,32 @@ pub const Object = struct {
2715 try debug_param_types.ensureUnusedCapacity(3 + fn_info.param_types.len);2718 try debug_param_types.ensureUnusedCapacity(3 + fn_info.param_types.len);
27162719
2717 // Return type goes first.2720 // Return type goes first.
2718 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(mod)) {2721 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(zcu)) {
2719 const sret = firstParamSRet(fn_info, mod, target);2722 const sret = firstParamSRet(fn_info, zcu, target);
2720 const ret_ty = if (sret) Type.void else Type.fromInterned(fn_info.return_type);2723 const ret_ty = if (sret) Type.void else Type.fromInterned(fn_info.return_type);
2721 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ret_ty));2724 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ret_ty));
27222725
2723 if (sret) {2726 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));
2725 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));2728 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
2726 }2729 }
2727 } else {2730 } else {
2728 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(Type.void));2731 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(Type.void));
2729 }2732 }
27302733
2731 if (Type.fromInterned(fn_info.return_type).isError(mod) and2734 if (Type.fromInterned(fn_info.return_type).isError(zcu) and
2732 o.module.comp.config.any_error_tracing)2735 o.module.comp.config.any_error_tracing)
2733 {2736 {
2734 const ptr_ty = try mod.singleMutPtrType(try o.getStackTraceType());2737 const ptr_ty = try zcu.singleMutPtrType(try o.getStackTraceType());
2735 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));2738 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
2736 }2739 }
27372740
2738 for (0..fn_info.param_types.len) |i| {2741 for (0..fn_info.param_types.len) |i| {
2739 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[i]);2742 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)) {2745 if (isByRef(param_ty, zcu)) {
2743 const ptr_ty = try mod.singleMutPtrType(param_ty);2746 const ptr_ty = try zcu.singleMutPtrType(param_ty);
2744 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));2747 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
2745 } else {2748 } else {
2746 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(param_ty));2749 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(param_ty));
...@@ -2767,9 +2770,10 @@ pub const Object = struct {...@@ -2767,9 +2770,10 @@ pub const Object = struct {
2767 }2770 }
27682771
2769 fn namespaceToDebugScope(o: *Object, namespace_index: InternPool.NamespaceIndex) !Builder.Metadata {2772 fn namespaceToDebugScope(o: *Object, namespace_index: InternPool.NamespaceIndex) !Builder.Metadata {
2770 const mod = o.module;2773 const zcu = o.module;
2771 const namespace = mod.namespacePtr(namespace_index);2774 const namespace = zcu.namespacePtr(namespace_index);
2772 if (namespace.parent == .none) return try o.getDebugFile(namespace.file_scope);2775 const file_scope = namespace.fileScope(zcu);
2776 if (namespace.parent == .none) return try o.getDebugFile(file_scope);
27732777
2774 const gop = try o.debug_unresolved_namespace_scopes.getOrPut(o.gpa, namespace_index);2778 const gop = try o.debug_unresolved_namespace_scopes.getOrPut(o.gpa, namespace_index);
27752779
...@@ -2779,13 +2783,14 @@ pub const Object = struct {...@@ -2779,13 +2783,14 @@ pub const Object = struct {
2779 }2783 }
27802784
2781 fn makeEmptyNamespaceDebugType(o: *Object, decl_index: InternPool.DeclIndex) !Builder.Metadata {2785 fn makeEmptyNamespaceDebugType(o: *Object, decl_index: InternPool.DeclIndex) !Builder.Metadata {
2782 const mod = o.module;2786 const zcu = o.module;
2783 const decl = mod.declPtr(decl_index);2787 const decl = zcu.declPtr(decl_index);
2788 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
2784 return o.builder.debugStructType(2789 return o.builder.debugStructType(
2785 try o.builder.metadataString(decl.name.toSlice(&mod.intern_pool)), // TODO use fully qualified name2790 try o.builder.metadataString(decl.name.toSlice(&zcu.intern_pool)), // TODO use fully qualified name
2786 try o.getDebugFile(mod.namespacePtr(decl.src_namespace).file_scope),2791 try o.getDebugFile(file_scope),
2787 try o.namespaceToDebugScope(decl.src_namespace),2792 try o.namespaceToDebugScope(decl.src_namespace),
2788 decl.typeSrcLine(mod) + 1,2793 decl.typeSrcLine(zcu) + 1,
2789 .none,2794 .none,
2790 0,2795 0,
2791 0,2796 0,
...@@ -2794,21 +2799,22 @@ pub const Object = struct {...@@ -2794,21 +2799,22 @@ pub const Object = struct {
2794 }2799 }
27952800
2796 fn getStackTraceType(o: *Object) Allocator.Error!Type {2801 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;2804 const std_mod = zcu.std_mod;
2800 const std_file = (mod.importPkg(std_mod) catch unreachable).file;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);2807 const builtin_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "builtin", .no_embedded_nulls);
2803 const std_namespace = mod.namespacePtr(mod.declPtr(std_file.root_decl.unwrap().?).src_namespace);2808 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index);
2804 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Module.DeclAdapter{ .zcu = mod }).?;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);
2807 // buffer is only used for int_type, `builtin` is a struct.2813 // buffer is only used for int_type, `builtin` is a struct.
2808 const builtin_ty = mod.declPtr(builtin_decl).val.toType();2814 const builtin_ty = zcu.declPtr(builtin_decl).val.toType();
2809 const builtin_namespace = mod.namespacePtrUnwrap(builtin_ty.getNamespaceIndex(mod)).?;2815 const builtin_namespace = zcu.namespacePtrUnwrap(builtin_ty.getNamespaceIndex(zcu)).?;
2810 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Module.DeclAdapter{ .zcu = mod }).?;2816 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Module.DeclAdapter{ .zcu = zcu }).?;
2811 const stack_trace_decl = mod.declPtr(stack_trace_decl_index);2817 const stack_trace_decl = zcu.declPtr(stack_trace_decl_index);
28122818
2813 // Sema should have ensured that StackTrace was analyzed.2819 // Sema should have ensured that StackTrace was analyzed.
2814 assert(stack_trace_decl.has_tv);2820 assert(stack_trace_decl.has_tv);
...@@ -2834,7 +2840,7 @@ pub const Object = struct {...@@ -2834,7 +2840,7 @@ pub const Object = struct {
2834 const gpa = o.gpa;2840 const gpa = o.gpa;
2835 const decl = zcu.declPtr(decl_index);2841 const decl = zcu.declPtr(decl_index);
2836 const namespace = zcu.namespacePtr(decl.src_namespace);2842 const namespace = zcu.namespacePtr(decl.src_namespace);
2837 const owner_mod = namespace.file_scope.mod;2843 const owner_mod = namespace.fileScope(zcu).mod;
2838 const zig_fn_type = decl.typeOf(zcu);2844 const zig_fn_type = decl.typeOf(zcu);
2839 const gop = try o.decl_map.getOrPut(gpa, decl_index);2845 const gop = try o.decl_map.getOrPut(gpa, decl_index);
2840 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.function;2846 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.function;
...@@ -3059,17 +3065,17 @@ pub const Object = struct {...@@ -3059,17 +3065,17 @@ pub const Object = struct {
3059 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.variable;3065 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.variable;
3060 errdefer assert(o.decl_map.remove(decl_index));3066 errdefer assert(o.decl_map.remove(decl_index));
30613067
3062 const mod = o.module;3068 const zcu = o.module;
3063 const decl = mod.declPtr(decl_index);3069 const decl = zcu.declPtr(decl_index);
3064 const is_extern = decl.isExtern(mod);3070 const is_extern = decl.isExtern(zcu);
30653071
3066 const variable_index = try o.builder.addVariable(3072 const variable_index = try o.builder.addVariable(
3067 try o.builder.strtabString((if (is_extern)3073 try o.builder.strtabString((if (is_extern)
3068 decl.name3074 decl.name
3069 else3075 else
3070 try decl.fullyQualifiedName(mod)).toSlice(&mod.intern_pool)),3076 try decl.fullyQualifiedName(zcu)).toSlice(&zcu.intern_pool)),
3071 try o.lowerType(decl.typeOf(mod)),3077 try o.lowerType(decl.typeOf(zcu)),
3072 toLlvmGlobalAddressSpace(decl.@"addrspace", mod.getTarget()),3078 toLlvmGlobalAddressSpace(decl.@"addrspace", zcu.getTarget()),
3073 );3079 );
3074 gop.value_ptr.* = variable_index.ptrConst(&o.builder).global;3080 gop.value_ptr.* = variable_index.ptrConst(&o.builder).global;
30753081
...@@ -3077,9 +3083,9 @@ pub const Object = struct {...@@ -3077,9 +3083,9 @@ pub const Object = struct {
3077 if (is_extern) {3083 if (is_extern) {
3078 variable_index.setLinkage(.external, &o.builder);3084 variable_index.setLinkage(.external, &o.builder);
3079 variable_index.setUnnamedAddr(.default, &o.builder);3085 variable_index.setUnnamedAddr(.default, &o.builder);
3080 if (decl.val.getVariable(mod)) |decl_var| {3086 if (decl.val.getVariable(zcu)) |decl_var| {
3081 const decl_namespace = mod.namespacePtr(decl.src_namespace);3087 const decl_namespace = zcu.namespacePtr(decl.src_namespace);
3082 const single_threaded = decl_namespace.file_scope.mod.single_threaded;3088 const single_threaded = decl_namespace.fileScope(zcu).mod.single_threaded;
3083 variable_index.setThreadLocal(3089 variable_index.setThreadLocal(
3084 if (decl_var.is_threadlocal and !single_threaded) .generaldynamic else .default,3090 if (decl_var.is_threadlocal and !single_threaded) .generaldynamic else .default,
3085 &o.builder,3091 &o.builder,
...@@ -4638,7 +4644,8 @@ pub const DeclGen = struct {...@@ -4638,7 +4644,8 @@ pub const DeclGen = struct {
4638 const o = dg.object;4644 const o = dg.object;
4639 const zcu = o.module;4645 const zcu = o.module;
4640 const namespace = zcu.namespacePtr(dg.decl.src_namespace);4646 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;
4642 }4649 }
46434650
4644 fn todo(dg: *DeclGen, comptime format: []const u8, args: anytype) Error {4651 fn todo(dg: *DeclGen, comptime format: []const u8, args: anytype) Error {
...@@ -4682,7 +4689,7 @@ pub const DeclGen = struct {...@@ -4682,7 +4689,7 @@ pub const DeclGen = struct {
46824689
4683 if (decl.val.getVariable(zcu)) |decl_var| {4690 if (decl.val.getVariable(zcu)) |decl_var| {
4684 const decl_namespace = zcu.namespacePtr(decl.src_namespace);4691 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;
4686 variable_index.setThreadLocal(4693 variable_index.setThreadLocal(
4687 if (decl_var.is_threadlocal and !single_threaded) .generaldynamic else .default,4694 if (decl_var.is_threadlocal and !single_threaded) .generaldynamic else .default,
4688 &o.builder,4695 &o.builder,
...@@ -4692,10 +4699,11 @@ pub const DeclGen = struct {...@@ -4692,10 +4699,11 @@ pub const DeclGen = struct {
4692 const line_number = decl.navSrcLine(zcu) + 1;4699 const line_number = decl.navSrcLine(zcu) + 1;
46934700
4694 const namespace = zcu.namespacePtr(decl.src_namespace);4701 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
4697 if (!owner_mod.strip) {4705 if (!owner_mod.strip) {
4698 const debug_file = try o.getDebugFile(namespace.file_scope);4706 const debug_file = try o.getDebugFile(file_scope);
46994707
4700 const debug_global_var = try o.builder.debugGlobalVar(4708 const debug_global_var = try o.builder.debugGlobalVar(
4701 try o.builder.metadataString(decl.name.toSlice(ip)), // Name4709 try o.builder.metadataString(decl.name.toSlice(ip)), // Name
...@@ -5143,9 +5151,10 @@ pub const FuncGen = struct {...@@ -5143,9 +5151,10 @@ pub const FuncGen = struct {
5143 const decl_index = func.owner_decl;5151 const decl_index = func.owner_decl;
5144 const decl = zcu.declPtr(decl_index);5152 const decl = zcu.declPtr(decl_index);
5145 const namespace = zcu.namespacePtr(decl.src_namespace);5153 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
5150 const line_number = decl.navSrcLine(zcu) + 1;5159 const line_number = decl.navSrcLine(zcu) + 1;
5151 self.inlined = self.wip.debug_location;5160 self.inlined = self.wip.debug_location;
src/codegen/spirv.zig+10-9
...@@ -188,19 +188,20 @@ pub const Object = struct {...@@ -188,19 +188,20 @@ pub const Object = struct {
188188
189 fn genDecl(189 fn genDecl(
190 self: *Object,190 self: *Object,
191 mod: *Module,191 zcu: *Zcu,
192 decl_index: InternPool.DeclIndex,192 decl_index: InternPool.DeclIndex,
193 air: Air,193 air: Air,
194 liveness: Liveness,194 liveness: Liveness,
195 ) !void {195 ) !void {
196 const decl = mod.declPtr(decl_index);196 const gpa = self.gpa;
197 const namespace = mod.namespacePtr(decl.src_namespace);197 const decl = zcu.declPtr(decl_index);
198 const structured_cfg = namespace.file_scope.mod.structured_cfg;198 const namespace = zcu.namespacePtr(decl.src_namespace);
199 const structured_cfg = namespace.fileScope(zcu).mod.structured_cfg;
199200
200 var decl_gen = DeclGen{201 var decl_gen = DeclGen{
201 .gpa = self.gpa,202 .gpa = gpa,
202 .object = self,203 .object = self,
203 .module = mod,204 .module = zcu,
204 .spv = &self.spv,205 .spv = &self.spv,
205 .decl_index = decl_index,206 .decl_index = decl_index,
206 .air = air,207 .air = air,
...@@ -212,19 +213,19 @@ pub const Object = struct {...@@ -212,19 +213,19 @@ pub const Object = struct {
212 false => .{ .unstructured = .{} },213 false => .{ .unstructured = .{} },
213 },214 },
214 .current_block_label = undefined,215 .current_block_label = undefined,
215 .base_line = decl.navSrcLine(mod),216 .base_line = decl.navSrcLine(zcu),
216 };217 };
217 defer decl_gen.deinit();218 defer decl_gen.deinit();
218219
219 decl_gen.genDecl() catch |err| switch (err) {220 decl_gen.genDecl() catch |err| switch (err) {
220 error.CodegenFail => {221 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.?);
222 },223 },
223 else => |other| {224 else => |other| {
224 // There might be an error that happened *after* self.error_msg225 // There might be an error that happened *after* self.error_msg
225 // was already allocated, so be sure to free it.226 // was already allocated, so be sure to free it.
226 if (decl_gen.error_msg) |error_msg| {227 if (decl_gen.error_msg) |error_msg| {
227 error_msg.deinit(mod.gpa);228 error_msg.deinit(gpa);
228 }229 }
229230
230 return other;231 return other;
src/link/C.zig+8-4
...@@ -208,6 +208,8 @@ pub fn updateFunc(...@@ -208,6 +208,8 @@ pub fn updateFunc(
208 fwd_decl.clearRetainingCapacity();208 fwd_decl.clearRetainingCapacity();
209 code.clearRetainingCapacity();209 code.clearRetainingCapacity();
210210
211 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
212
211 var function: codegen.Function = .{213 var function: codegen.Function = .{
212 .value_map = codegen.CValueMap.init(gpa),214 .value_map = codegen.CValueMap.init(gpa),
213 .air = air,215 .air = air,
...@@ -217,7 +219,7 @@ pub fn updateFunc(...@@ -217,7 +219,7 @@ pub fn updateFunc(
217 .dg = .{219 .dg = .{
218 .gpa = gpa,220 .gpa = gpa,
219 .zcu = zcu,221 .zcu = zcu,
220 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,222 .mod = file_scope.mod,
221 .error_msg = null,223 .error_msg = null,
222 .pass = .{ .decl = decl_index },224 .pass = .{ .decl = decl_index },
223 .is_naked_fn = decl.typeOf(zcu).fnCallingConvention(zcu) == .Naked,225 .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 {...@@ -335,11 +337,13 @@ pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
335 fwd_decl.clearRetainingCapacity();337 fwd_decl.clearRetainingCapacity();
336 code.clearRetainingCapacity();338 code.clearRetainingCapacity();
337339
340 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
341
338 var object: codegen.Object = .{342 var object: codegen.Object = .{
339 .dg = .{343 .dg = .{
340 .gpa = gpa,344 .gpa = gpa,
341 .zcu = zcu,345 .zcu = zcu,
342 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,346 .mod = file_scope.mod,
343 .error_msg = null,347 .error_msg = null,
344 .pass = .{ .decl = decl_index },348 .pass = .{ .decl = decl_index },
345 .is_naked_fn = false,349 .is_naked_fn = false,
...@@ -491,7 +495,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo...@@ -491,7 +495,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
491 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, *decl_block| {495 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, *decl_block| {
492 const decl = zcu.declPtr(decl_index);496 const decl = zcu.declPtr(decl_index);
493 const extern_name = if (decl.isExtern(zcu)) decl.name.toOptional() else .none;497 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;
495 try self.flushDeclBlock(499 try self.flushDeclBlock(
496 zcu,500 zcu,
497 mod,501 mod,
...@@ -848,7 +852,7 @@ pub fn updateExports(...@@ -848,7 +852,7 @@ pub fn updateExports(
848 const gpa = self.base.comp.gpa;852 const gpa = self.base.comp.gpa;
849 const mod, const pass: codegen.DeclGen.Pass, const decl_block, const exported_block = switch (exported) {853 const mod, const pass: codegen.DeclGen.Pass, const decl_block, const exported_block = switch (exported) {
850 .decl_index => |decl_index| .{854 .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,
852 .{ .decl = decl_index },856 .{ .decl = decl_index },
853 self.decl_table.getPtr(decl_index).?,857 self.decl_table.getPtr(decl_index).?,
854 (try self.exported_decls.getOrPut(gpa, decl_index)).value_ptr,858 (try self.exported_decls.getOrPut(gpa, decl_index)).value_ptr,
src/link/Dwarf.zig+1-1
...@@ -1204,7 +1204,7 @@ pub fn commitDeclState(...@@ -1204,7 +1204,7 @@ pub fn commitDeclState(
1204 const decl = zcu.declPtr(decl_index);1204 const decl = zcu.declPtr(decl_index);
1205 const ip = &zcu.intern_pool;1205 const ip = &zcu.intern_pool;
1206 const namespace = zcu.namespacePtr(decl.src_namespace);1206 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;
1208 const target_endian = target.cpu.arch.endian();1208 const target_endian = target.cpu.arch.endian();
12091209
1210 var dbg_line_buffer = &decl_state.dbg_line;1210 var dbg_line_buffer = &decl_state.dbg_line;
src/link/Wasm/ZigObject.zig+11-11
...@@ -335,29 +335,29 @@ fn finishUpdateDecl(...@@ -335,29 +335,29 @@ fn finishUpdateDecl(
335 code: []const u8,335 code: []const u8,
336) !void {336) !void {
337 const gpa = wasm_file.base.comp.gpa;337 const gpa = wasm_file.base.comp.gpa;
338 const mod = wasm_file.base.comp.module.?;338 const zcu = wasm_file.base.comp.module.?;
339 const decl = mod.declPtr(decl_index);339 const decl = zcu.declPtr(decl_index);
340 const decl_info = zig_object.decls_map.get(decl_index).?;340 const decl_info = zig_object.decls_map.get(decl_index).?;
341 const atom_index = decl_info.atom;341 const atom_index = decl_info.atom;
342 const atom = wasm_file.getAtomPtr(atom_index);342 const atom = wasm_file.getAtomPtr(atom_index);
343 const sym = zig_object.symbol(atom.sym_index);343 const sym = zig_object.symbol(atom.sym_index);
344 const full_name = try decl.fullyQualifiedName(mod);344 const full_name = try decl.fullyQualifiedName(zcu);
345 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&mod.intern_pool));345 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&zcu.intern_pool));
346 try atom.code.appendSlice(gpa, code);346 try atom.code.appendSlice(gpa, code);
347 atom.size = @intCast(code.len);347 atom.size = @intCast(code.len);
348348
349 switch (decl.typeOf(mod).zigTypeTag(mod)) {349 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
350 .Fn => {350 .Fn => {
351 sym.index = try zig_object.appendFunction(gpa, .{ .type_index = zig_object.atom_types.get(atom_index).? });351 sym.index = try zig_object.appendFunction(gpa, .{ .type_index = zig_object.atom_types.get(atom_index).? });
352 sym.tag = .function;352 sym.tag = .function;
353 },353 },
354 else => {354 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: {
356 if (variable.is_const) {356 if (variable.is_const) {
357 break :name ".rodata.";357 break :name ".rodata.";
358 } else if (Value.fromInterned(variable.init).isUndefDeep(mod)) {358 } else if (Value.fromInterned(variable.init).isUndefDeep(zcu)) {
359 const decl_namespace = mod.namespacePtr(decl.src_namespace);359 const decl_namespace = zcu.namespacePtr(decl.src_namespace);
360 const optimize_mode = decl_namespace.file_scope.mod.optimize_mode;360 const optimize_mode = decl_namespace.fileScope(zcu).mod.optimize_mode;
361 const is_initialized = switch (optimize_mode) {361 const is_initialized = switch (optimize_mode) {
362 .Debug, .ReleaseSafe => true,362 .Debug, .ReleaseSafe => true,
363 .ReleaseFast, .ReleaseSmall => false,363 .ReleaseFast, .ReleaseSmall => false,
...@@ -382,7 +382,7 @@ fn finishUpdateDecl(...@@ -382,7 +382,7 @@ fn finishUpdateDecl(
382 // Will be freed upon freeing of decl or after cleanup of Wasm binary.382 // Will be freed upon freeing of decl or after cleanup of Wasm binary.
383 const full_segment_name = try std.mem.concat(gpa, u8, &.{383 const full_segment_name = try std.mem.concat(gpa, u8, &.{
384 segment_name,384 segment_name,
385 full_name.toSlice(&mod.intern_pool),385 full_name.toSlice(&zcu.intern_pool),
386 });386 });
387 errdefer gpa.free(full_segment_name);387 errdefer gpa.free(full_segment_name);
388 sym.tag = .data;388 sym.tag = .data;
...@@ -390,7 +390,7 @@ fn finishUpdateDecl(...@@ -390,7 +390,7 @@ fn finishUpdateDecl(
390 },390 },
391 }391 }
392 if (code.len == 0) return;392 if (code.len == 0) return;
393 atom.alignment = decl.getAlignment(mod);393 atom.alignment = decl.getAlignment(zcu);
394}394}
395395
396/// Creates and initializes a new segment in the 'Data' section.396/// Creates and initializes a new segment in the 'Data' section.
src/main.zig+7-15
...@@ -27,8 +27,6 @@ const Cache = std.Build.Cache;...@@ -27,8 +27,6 @@ const Cache = std.Build.Cache;
27const target_util = @import("target.zig");27const target_util = @import("target.zig");
28const crash_report = @import("crash_report.zig");28const crash_report = @import("crash_report.zig");
29const Zcu = @import("Zcu.zig");29const Zcu = @import("Zcu.zig");
30/// Deprecated.
31const Module = Zcu;
32const AstGen = std.zig.AstGen;30const AstGen = std.zig.AstGen;
33const mingw = @import("mingw.zig");31const mingw = @import("mingw.zig");
34const Server = std.zig.Server;32const Server = std.zig.Server;
...@@ -919,7 +917,7 @@ fn buildOutputType(...@@ -919,7 +917,7 @@ fn buildOutputType(
919 var contains_res_file: bool = false;917 var contains_res_file: bool = false;
920 var reference_trace: ?u32 = null;918 var reference_trace: ?u32 = null;
921 var pdb_out_path: ?[]const u8 = null;919 var pdb_out_path: ?[]const u8 = null;
922 var error_limit: ?Module.ErrorInt = null;920 var error_limit: ?Zcu.ErrorInt = null;
923 // These are before resolving sysroot.921 // These are before resolving sysroot.
924 var extra_cflags: std.ArrayListUnmanaged([]const u8) = .{};922 var extra_cflags: std.ArrayListUnmanaged([]const u8) = .{};
925 var extra_rcflags: std.ArrayListUnmanaged([]const u8) = .{};923 var extra_rcflags: std.ArrayListUnmanaged([]const u8) = .{};
...@@ -1107,7 +1105,7 @@ fn buildOutputType(...@@ -1107,7 +1105,7 @@ fn buildOutputType(
1107 );1105 );
1108 } else if (mem.eql(u8, arg, "--error-limit")) {1106 } else if (mem.eql(u8, arg, "--error-limit")) {
1109 const next_arg = args_iter.nextOrFatal();1107 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| {
1111 fatal("unable to parse error limit '{s}': {s}", .{ next_arg, @errorName(err) });1109 fatal("unable to parse error limit '{s}': {s}", .{ next_arg, @errorName(err) });
1112 };1110 };
1113 } else if (mem.eql(u8, arg, "-cflags")) {1111 } else if (mem.eql(u8, arg, "-cflags")) {
...@@ -5956,7 +5954,7 @@ fn cmdAstCheck(...@@ -5956,7 +5954,7 @@ fn cmdAstCheck(
5956 }5954 }
5957 }5955 }
59585956
5959 var file: Module.File = .{5957 var file: Zcu.File = .{
5960 .status = .never_loaded,5958 .status = .never_loaded,
5961 .source_loaded = false,5959 .source_loaded = false,
5962 .tree_loaded = false,5960 .tree_loaded = false,
...@@ -5967,8 +5965,6 @@ fn cmdAstCheck(...@@ -5967,8 +5965,6 @@ fn cmdAstCheck(
5967 .tree = undefined,5965 .tree = undefined,
5968 .zir = undefined,5966 .zir = undefined,
5969 .mod = undefined,5967 .mod = undefined,
5970 .root_decl = .none,
5971 .path_digest = undefined,
5972 };5968 };
5973 if (zig_source_file) |file_name| {5969 if (zig_source_file) |file_name| {
5974 var f = fs.cwd().openFile(file_name, .{}) catch |err| {5970 var f = fs.cwd().openFile(file_name, .{}) catch |err| {
...@@ -6275,7 +6271,7 @@ fn cmdDumpZir(...@@ -6275,7 +6271,7 @@ fn cmdDumpZir(
6275 };6271 };
6276 defer f.close();6272 defer f.close();
62776273
6278 var file: Module.File = .{6274 var file: Zcu.File = .{
6279 .status = .never_loaded,6275 .status = .never_loaded,
6280 .source_loaded = false,6276 .source_loaded = false,
6281 .tree_loaded = false,6277 .tree_loaded = false,
...@@ -6284,10 +6280,8 @@ fn cmdDumpZir(...@@ -6284,10 +6280,8 @@ fn cmdDumpZir(
6284 .source = undefined,6280 .source = undefined,
6285 .stat = undefined,6281 .stat = undefined,
6286 .tree = undefined,6282 .tree = undefined,
6287 .zir = try Module.loadZirCache(gpa, f),6283 .zir = try Zcu.loadZirCache(gpa, f),
6288 .mod = undefined,6284 .mod = undefined,
6289 .root_decl = .none,
6290 .path_digest = undefined,
6291 };6285 };
6292 defer file.zir.deinit(gpa);6286 defer file.zir.deinit(gpa);
62936287
...@@ -6342,7 +6336,7 @@ fn cmdChangelist(...@@ -6342,7 +6336,7 @@ fn cmdChangelist(
6342 if (stat.size > std.zig.max_src_size)6336 if (stat.size > std.zig.max_src_size)
6343 return error.FileTooBig;6337 return error.FileTooBig;
63446338
6345 var file: Module.File = .{6339 var file: Zcu.File = .{
6346 .status = .never_loaded,6340 .status = .never_loaded,
6347 .source_loaded = false,6341 .source_loaded = false,
6348 .tree_loaded = false,6342 .tree_loaded = false,
...@@ -6357,8 +6351,6 @@ fn cmdChangelist(...@@ -6357,8 +6351,6 @@ fn cmdChangelist(
6357 .tree = undefined,6351 .tree = undefined,
6358 .zir = undefined,6352 .zir = undefined,
6359 .mod = undefined,6353 .mod = undefined,
6360 .root_decl = .none,
6361 .path_digest = undefined,
6362 };6354 };
63636355
6364 file.mod = try Package.Module.createLimited(arena, .{6356 file.mod = try Package.Module.createLimited(arena, .{
...@@ -6431,7 +6423,7 @@ fn cmdChangelist(...@@ -6431,7 +6423,7 @@ fn cmdChangelist(
6431 var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{};6423 var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{};
6432 defer inst_map.deinit(gpa);6424 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
6436 var bw = io.bufferedWriter(io.getStdOut().writer());6428 var bw = io.bufferedWriter(io.getStdOut().writer());
6437 const stdout = bw.writer();6429 const stdout = bw.writer();