authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2024-02-06 01:55:22+00:00
committergravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2024-03-06 21:26:37+00:00
loga6ca20b9a1dfc7b6e8d004cb166c0714bb8db2db
tree8ecc7aae4a07f9e5a2fe1d2f2acfe0f40f5ea673
parent90ab8ea9e681a4ffac0b4dc500e3ec489014e12f
signaturelock-open Commit is signed but in an unrecognized format.

compiler: change representation of closures

This changes the representation of closures in Zir and Sema. Rather than a pair of instructions `closure_capture` and `closure_get`, the system now works as follows: * Each ZIR type declaration (`struct_decl` etc) contains a list of captures in the form of ZIR indices (or, for efficiency, direct references to parent captures). This is an ordered list; indexes into it are used to refer to captured values. * The `extended(closure_get)` ZIR instruction refers to a value in this list via a 16-bit index (limiting this index to 16 bits allows us to store this in `extended`). * `Module.Namespace` has a new field `captures` which contains the list of values captured in a given namespace. This is initialized based on the ZIR capture list whenever a type declaration is analyzed. This change eliminates `CaptureScope` from semantic analysis, which is a nice simplification; but the main motivation here is that this change is a prerequisite for #18816.

7 files changed, 563 insertions(+), 344 deletions(-)

lib/std/zig/AstGen.zig+149-96
......@@ -2205,7 +2205,7 @@ fn breakExpr(parent_gz: *GenZir, parent_scope: *Scope, node: Ast.Node.Index) Inn
22052205 },
22062206 .local_val => scope = scope.cast(Scope.LocalVal).?.parent,
22072207 .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent,
2208 .namespace, .enum_namespace => break,
2208 .namespace => break,
22092209 .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent,
22102210 .top => unreachable,
22112211 }
......@@ -2279,7 +2279,7 @@ fn continueExpr(parent_gz: *GenZir, parent_scope: *Scope, node: Ast.Node.Index)
22792279 try parent_gz.addDefer(defer_scope.index, defer_scope.len);
22802280 },
22812281 .defer_error => scope = scope.cast(Scope.Defer).?.parent,
2282 .namespace, .enum_namespace => break,
2282 .namespace => break,
22832283 .top => unreachable,
22842284 }
22852285 }
......@@ -2412,7 +2412,7 @@ fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: Ast.Toke
24122412 .local_val => scope = scope.cast(Scope.LocalVal).?.parent,
24132413 .local_ptr => scope = scope.cast(Scope.LocalPtr).?.parent,
24142414 .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent,
2415 .namespace, .enum_namespace => break,
2415 .namespace => break,
24162416 .top => unreachable,
24172417 }
24182418 }
......@@ -2790,7 +2790,6 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
27902790 .@"resume",
27912791 .@"await",
27922792 .ret_err_value_code,
2793 .closure_get,
27942793 .ret_ptr,
27952794 .ret_type,
27962795 .for_len,
......@@ -2860,7 +2859,6 @@ fn addEnsureResult(gz: *GenZir, maybe_unused_result: Zir.Inst.Ref, statement: As
28602859 .store_to_inferred_ptr,
28612860 .resolve_inferred_alloc,
28622861 .set_runtime_safety,
2863 .closure_capture,
28642862 .memcpy,
28652863 .memset,
28662864 .validate_deref,
......@@ -2928,7 +2926,7 @@ fn countDefers(outer_scope: *Scope, inner_scope: *Scope) struct {
29282926 const have_err_payload = defer_scope.remapped_err_code != .none;
29292927 need_err_code = need_err_code or have_err_payload;
29302928 },
2931 .namespace, .enum_namespace => unreachable,
2929 .namespace => unreachable,
29322930 .top => unreachable,
29332931 }
29342932 }
......@@ -2998,7 +2996,7 @@ fn genDefers(
29982996 .normal_only => continue,
29992997 }
30002998 },
3001 .namespace, .enum_namespace => unreachable,
2999 .namespace => unreachable,
30023000 .top => unreachable,
30033001 }
30043002 }
......@@ -3042,7 +3040,7 @@ fn checkUsed(gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope) InnerError!v
30423040 scope = s.parent;
30433041 },
30443042 .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent,
3045 .namespace, .enum_namespace => unreachable,
3043 .namespace => unreachable,
30463044 .top => unreachable,
30473045 }
30483046 }
......@@ -4732,7 +4730,7 @@ fn testDecl(
47324730 },
47334731 .gen_zir => s = s.cast(GenZir).?.parent,
47344732 .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent,
4735 .namespace, .enum_namespace => {
4733 .namespace => {
47364734 const ns = s.cast(Scope.Namespace).?;
47374735 if (ns.decls.get(name_str_index)) |i| {
47384736 if (found_already) |f| {
......@@ -4849,10 +4847,10 @@ fn structDeclInner(
48494847 try gz.setStruct(decl_inst, .{
48504848 .src_node = node,
48514849 .layout = layout,
4850 .captures_len = 0,
48524851 .fields_len = 0,
48534852 .decls_len = 0,
4854 .backing_int_ref = .none,
4855 .backing_int_body_len = 0,
4853 .has_backing_int = false,
48564854 .known_non_opv = false,
48574855 .known_comptime_only = false,
48584856 .is_tuple = false,
......@@ -5142,10 +5140,10 @@ fn structDeclInner(
51425140 try gz.setStruct(decl_inst, .{
51435141 .src_node = node,
51445142 .layout = layout,
5143 .captures_len = @intCast(namespace.captures.count()),
51455144 .fields_len = field_count,
51465145 .decls_len = decl_count,
5147 .backing_int_ref = backing_int_ref,
5148 .backing_int_body_len = @intCast(backing_int_body_len),
5146 .has_backing_int = backing_int_ref != .none,
51495147 .known_non_opv = known_non_opv,
51505148 .known_comptime_only = known_comptime_only,
51515149 .is_tuple = is_tuple,
......@@ -5159,15 +5157,22 @@ fn structDeclInner(
51595157 const decls_slice = wip_members.declsSlice();
51605158 const fields_slice = wip_members.fieldsSlice();
51615159 const bodies_slice = astgen.scratch.items[bodies_start..];
5162 try astgen.extra.ensureUnusedCapacity(gpa, backing_int_body_len +
5163 decls_slice.len + fields_slice.len + bodies_slice.len);
5164 astgen.extra.appendSliceAssumeCapacity(astgen.scratch.items[scratch_top..][0..backing_int_body_len]);
5160 try astgen.extra.ensureUnusedCapacity(gpa, backing_int_body_len + 2 +
5161 decls_slice.len + namespace.captures.count() + fields_slice.len + bodies_slice.len);
5162 astgen.extra.appendSliceAssumeCapacity(@ptrCast(namespace.captures.keys()));
5163 if (backing_int_ref != .none) {
5164 astgen.extra.appendAssumeCapacity(@intCast(backing_int_body_len));
5165 if (backing_int_body_len == 0) {
5166 astgen.extra.appendAssumeCapacity(@intFromEnum(backing_int_ref));
5167 } else {
5168 astgen.extra.appendSliceAssumeCapacity(astgen.scratch.items[scratch_top..][0..backing_int_body_len]);
5169 }
5170 }
51655171 astgen.extra.appendSliceAssumeCapacity(decls_slice);
51665172 astgen.extra.appendSliceAssumeCapacity(fields_slice);
51675173 astgen.extra.appendSliceAssumeCapacity(bodies_slice);
51685174
51695175 block_scope.unstack();
5170 try gz.addNamespaceCaptures(&namespace);
51715176 return decl_inst.toRef();
51725177}
51735178
......@@ -5368,6 +5373,7 @@ fn unionDeclInner(
53685373 .src_node = node,
53695374 .layout = layout,
53705375 .tag_type = arg_inst,
5376 .captures_len = @intCast(namespace.captures.count()),
53715377 .body_len = body_len,
53725378 .fields_len = field_count,
53735379 .decls_len = decl_count,
......@@ -5379,13 +5385,13 @@ fn unionDeclInner(
53795385 wip_members.finishBits(bits_per_field);
53805386 const decls_slice = wip_members.declsSlice();
53815387 const fields_slice = wip_members.fieldsSlice();
5382 try astgen.extra.ensureUnusedCapacity(gpa, decls_slice.len + body_len + fields_slice.len);
5388 try astgen.extra.ensureUnusedCapacity(gpa, namespace.captures.count() + decls_slice.len + body_len + fields_slice.len);
5389 astgen.extra.appendSliceAssumeCapacity(@ptrCast(namespace.captures.keys()));
53835390 astgen.extra.appendSliceAssumeCapacity(decls_slice);
53845391 astgen.appendBodyWithFixups(body);
53855392 astgen.extra.appendSliceAssumeCapacity(fields_slice);
53865393
53875394 block_scope.unstack();
5388 try gz.addNamespaceCaptures(&namespace);
53895395 return decl_inst.toRef();
53905396}
53915397
......@@ -5555,7 +5561,7 @@ fn containerDecl(
55555561 defer block_scope.unstack();
55565562
55575563 _ = try astgen.scanDecls(&namespace, container_decl.ast.members);
5558 namespace.base.tag = .enum_namespace;
5564 namespace.base.tag = .namespace;
55595565
55605566 const arg_inst: Zir.Inst.Ref = if (container_decl.ast.arg != 0)
55615567 try comptimeExpr(&block_scope, &namespace.base, coerced_type_ri, container_decl.ast.arg)
......@@ -5586,7 +5592,6 @@ fn containerDecl(
55865592 if (member_node == counts.nonexhaustive_node)
55875593 continue;
55885594 fields_hasher.update(tree.getNodeSource(member_node));
5589 namespace.base.tag = .namespace;
55905595 var member = switch (try containerMember(&block_scope, &namespace.base, &wip_members, member_node)) {
55915596 .decl => continue,
55925597 .field => |field| field,
......@@ -5630,7 +5635,6 @@ fn containerDecl(
56305635 },
56315636 );
56325637 }
5633 namespace.base.tag = .enum_namespace;
56345638 const tag_value_inst = try expr(&block_scope, &namespace.base, .{ .rl = .{ .ty = arg_inst } }, member.ast.value_expr);
56355639 wip_members.appendToField(@intFromEnum(tag_value_inst));
56365640 }
......@@ -5676,6 +5680,7 @@ fn containerDecl(
56765680 .src_node = node,
56775681 .nonexhaustive = nonexhaustive,
56785682 .tag_type = arg_inst,
5683 .captures_len = @intCast(namespace.captures.count()),
56795684 .body_len = body_len,
56805685 .fields_len = @intCast(counts.total_fields),
56815686 .decls_len = @intCast(counts.decls),
......@@ -5685,13 +5690,13 @@ fn containerDecl(
56855690 wip_members.finishBits(bits_per_field);
56865691 const decls_slice = wip_members.declsSlice();
56875692 const fields_slice = wip_members.fieldsSlice();
5688 try astgen.extra.ensureUnusedCapacity(gpa, decls_slice.len + body_len + fields_slice.len);
5693 try astgen.extra.ensureUnusedCapacity(gpa, namespace.captures.count() + decls_slice.len + body_len + fields_slice.len);
5694 astgen.extra.appendSliceAssumeCapacity(@ptrCast(namespace.captures.keys()));
56895695 astgen.extra.appendSliceAssumeCapacity(decls_slice);
56905696 astgen.appendBodyWithFixups(body);
56915697 astgen.extra.appendSliceAssumeCapacity(fields_slice);
56925698
56935699 block_scope.unstack();
5694 try gz.addNamespaceCaptures(&namespace);
56955700 return rvalue(gz, ri, decl_inst.toRef(), node);
56965701 },
56975702 .keyword_opaque => {
......@@ -5733,16 +5738,17 @@ fn containerDecl(
57335738
57345739 try gz.setOpaque(decl_inst, .{
57355740 .src_node = node,
5741 .captures_len = @intCast(namespace.captures.count()),
57365742 .decls_len = decl_count,
57375743 });
57385744
57395745 wip_members.finishBits(0);
57405746 const decls_slice = wip_members.declsSlice();
5741 try astgen.extra.ensureUnusedCapacity(gpa, decls_slice.len);
5747 try astgen.extra.ensureUnusedCapacity(gpa, namespace.captures.count() + decls_slice.len);
5748 astgen.extra.appendSliceAssumeCapacity(@ptrCast(namespace.captures.keys()));
57425749 astgen.extra.appendSliceAssumeCapacity(decls_slice);
57435750
57445751 block_scope.unstack();
5745 try gz.addNamespaceCaptures(&namespace);
57465752 return rvalue(gz, ri, decl_inst.toRef(), node);
57475753 },
57485754 else => unreachable,
......@@ -8238,12 +8244,12 @@ fn localVarRef(
82388244 ident_token: Ast.TokenIndex,
82398245) InnerError!Zir.Inst.Ref {
82408246 const astgen = gz.astgen;
8241 const gpa = astgen.gpa;
82428247 const name_str_index = try astgen.identAsString(ident_token);
82438248 var s = scope;
82448249 var found_already: ?Ast.Node.Index = null; // we have found a decl with the same name already
82458250 var num_namespaces_out: u32 = 0;
8246 var capturing_namespace: ?*Scope.Namespace = null;
8251 // defined when `num_namespaces_out != 0`
8252 var capturing_namespace: *Scope.Namespace = undefined;
82478253 while (true) switch (s.tag) {
82488254 .local_val => {
82498255 const local_val = s.cast(Scope.LocalVal).?;
......@@ -8257,15 +8263,14 @@ fn localVarRef(
82578263 local_val.used = ident_token;
82588264 }
82598265
8260 const value_inst = try tunnelThroughClosure(
8266 const value_inst = if (num_namespaces_out != 0) try tunnelThroughClosure(
82618267 gz,
82628268 ident,
82638269 num_namespaces_out,
82648270 capturing_namespace,
82658271 local_val.inst,
82668272 local_val.token_src,
8267 gpa,
8268 );
8273 ) else local_val.inst;
82698274
82708275 return rvalueNoCoercePreRef(gz, ri, value_inst, ident);
82718276 }
......@@ -8285,19 +8290,18 @@ fn localVarRef(
82858290 const ident_name = try astgen.identifierTokenString(ident_token);
82868291 return astgen.failNodeNotes(ident, "mutable '{s}' not accessible from here", .{ident_name}, &.{
82878292 try astgen.errNoteTok(local_ptr.token_src, "declared mutable here", .{}),
8288 try astgen.errNoteNode(capturing_namespace.?.node, "crosses namespace boundary here", .{}),
8293 try astgen.errNoteNode(capturing_namespace.node, "crosses namespace boundary here", .{}),
82898294 });
82908295 }
82918296
8292 const ptr_inst = try tunnelThroughClosure(
8297 const ptr_inst = if (num_namespaces_out != 0) try tunnelThroughClosure(
82938298 gz,
82948299 ident,
82958300 num_namespaces_out,
82968301 capturing_namespace,
82978302 local_ptr.ptr,
82988303 local_ptr.token_src,
8299 gpa,
8300 );
8304 ) else local_ptr.ptr;
83018305
83028306 switch (ri.rl) {
83038307 .ref, .ref_coerced_ty => {
......@@ -8314,7 +8318,7 @@ fn localVarRef(
83148318 },
83158319 .gen_zir => s = s.cast(GenZir).?.parent,
83168320 .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent,
8317 .namespace, .enum_namespace => {
8321 .namespace => {
83188322 const ns = s.cast(Scope.Namespace).?;
83198323 if (ns.decls.get(name_str_index)) |i| {
83208324 if (found_already) |f| {
......@@ -8326,7 +8330,7 @@ fn localVarRef(
83268330 // We found a match but must continue looking for ambiguous references to decls.
83278331 found_already = i;
83288332 }
8329 if (s.tag == .namespace) num_namespaces_out += 1;
8333 num_namespaces_out += 1;
83308334 capturing_namespace = ns;
83318335 s = ns.parent;
83328336 },
......@@ -8348,41 +8352,70 @@ fn localVarRef(
83488352 }
83498353}
83508354
8351/// Adds a capture to a namespace, if needed.
8352/// Returns the index of the closure_capture instruction.
8355/// Access a ZIR instruction through closure. May tunnel through arbitrarily
8356/// many namespaces, adding closure captures as required.
8357/// Returns the index of the `closure_get` instruction added to `gz`.
83538358fn tunnelThroughClosure(
83548359 gz: *GenZir,
8360 /// The node which references the value to be captured.
83558361 inner_ref_node: Ast.Node.Index,
8362 /// The number of namespaces being tunnelled through. At least 1.
83568363 num_tunnels: u32,
8357 ns: ?*Scope.Namespace,
8364 /// The namespace being captured from.
8365 ns: *Scope.Namespace,
8366 /// The value being captured.
83588367 value: Zir.Inst.Ref,
8368 /// The token of the value's declaration.
83598369 token: Ast.TokenIndex,
8360 gpa: Allocator,
83618370) !Zir.Inst.Ref {
8362 // For trivial values, we don't need a tunnel.
8363 // Just return the ref.
8364 if (num_tunnels == 0 or value.toIndex() == null) {
8371 const value_inst = value.toIndex() orelse {
8372 // For trivial values, we don't need a tunnel; just return the ref.
83658373 return value;
8374 };
8375
8376 const astgen = gz.astgen;
8377 const gpa = astgen.gpa;
8378
8379 // Otherwise we need a tunnel. First, figure out the path of namespaces we
8380 // are tunneling through. This is usually only going to be one or two, so
8381 // use an SFBA to optimize for the common case.
8382 var sfba = std.heap.stackFallback(@sizeOf(usize) * 2, astgen.arena);
8383 var intermediate_tunnels = try sfba.get().alloc(*Scope.Namespace, num_tunnels - 1);
8384
8385 {
8386 var i: usize = num_tunnels - 1;
8387 var scope: *Scope = gz.parent;
8388 while (i > 0) {
8389 if (scope.cast(Scope.Namespace)) |mid_ns| {
8390 i -= 1;
8391 intermediate_tunnels[i] = mid_ns;
8392 }
8393 scope = scope.parent().?;
8394 }
83668395 }
83678396
8368 // Otherwise we need a tunnel. Check if this namespace
8369 // already has one for this value.
8370 const gop = try ns.?.captures.getOrPut(gpa, value.toIndex().?);
8371 if (!gop.found_existing) {
8372 // Make a new capture for this value but don't add it to the declaring_gz yet
8373 try gz.astgen.instructions.append(gz.astgen.gpa, .{
8374 .tag = .closure_capture,
8375 .data = .{ .un_tok = .{
8376 .operand = value,
8377 .src_tok = ns.?.declaring_gz.?.tokenIndexToRelative(token),
8378 } },
8397 // Now that we know the scopes we're tunneling through, begin adding
8398 // captures as required, starting with the outermost namespace.
8399 var cur_capture_index = std.math.cast(
8400 u16,
8401 (try ns.captures.getOrPut(gpa, Zir.Inst.Capture.wrap(.{ .inst = value_inst }))).index,
8402 ) orelse return astgen.failNodeNotes(ns.node, "this compiler implementation only supports up to 65536 captures per namespace", .{}, &.{
8403 try astgen.errNoteTok(token, "captured value here", .{}),
8404 try astgen.errNoteNode(inner_ref_node, "value used here", .{}),
8405 });
8406
8407 for (intermediate_tunnels) |tunnel_ns| {
8408 cur_capture_index = std.math.cast(
8409 u16,
8410 (try tunnel_ns.captures.getOrPut(gpa, Zir.Inst.Capture.wrap(.{ .nested = cur_capture_index }))).index,
8411 ) orelse return astgen.failNodeNotes(tunnel_ns.node, "this compiler implementation only supports up to 65536 captures per namespace", .{}, &.{
8412 try astgen.errNoteTok(token, "captured value here", .{}),
8413 try astgen.errNoteNode(inner_ref_node, "value used here", .{}),
83798414 });
8380 gop.value_ptr.* = @enumFromInt(gz.astgen.instructions.len - 1);
83818415 }
83828416
8383 // Add an instruction to get the value from the closure into
8384 // our current context
8385 return try gz.addInstNode(.closure_get, gop.value_ptr.*, inner_ref_node);
8417 // Add an instruction to get the value from the closure.
8418 return gz.addExtendedNodeSmall(.closure_get, inner_ref_node, cur_capture_index);
83868419}
83878420
83888421fn stringLiteral(
......@@ -9095,7 +9128,7 @@ fn builtinCall(
90959128 },
90969129 .gen_zir => s = s.cast(GenZir).?.parent,
90979130 .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent,
9098 .namespace, .enum_namespace => {
9131 .namespace => {
90999132 const ns = s.cast(Scope.Namespace).?;
91009133 if (ns.decls.get(decl_name)) |i| {
91019134 if (found_already) |f| {
......@@ -11605,7 +11638,7 @@ const Scope = struct {
1160511638 }
1160611639 if (T == Namespace) {
1160711640 switch (base.tag) {
11608 .namespace, .enum_namespace => return @fieldParentPtr(T, "base", base),
11641 .namespace => return @fieldParentPtr(T, "base", base),
1160911642 else => return null,
1161011643 }
1161111644 }
......@@ -11621,7 +11654,7 @@ const Scope = struct {
1162111654 .local_val => base.cast(LocalVal).?.parent,
1162211655 .local_ptr => base.cast(LocalPtr).?.parent,
1162311656 .defer_normal, .defer_error => base.cast(Defer).?.parent,
11624 .namespace, .enum_namespace => base.cast(Namespace).?.parent,
11657 .namespace => base.cast(Namespace).?.parent,
1162511658 .top => null,
1162611659 };
1162711660 }
......@@ -11633,7 +11666,6 @@ const Scope = struct {
1163311666 defer_normal,
1163411667 defer_error,
1163511668 namespace,
11636 enum_namespace,
1163711669 top,
1163811670 };
1163911671
......@@ -11725,9 +11757,8 @@ const Scope = struct {
1172511757 /// Only valid during astgen.
1172611758 declaring_gz: ?*GenZir,
1172711759
11728 /// Map from the raw captured value to the instruction
11729 /// ref of the capture for decls in this namespace
11730 captures: std.AutoArrayHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{},
11760 /// Set of captures used by this namespace.
11761 captures: std.AutoArrayHashMapUnmanaged(Zir.Inst.Capture, void) = .{},
1173111762
1173211763 fn deinit(self: *Namespace, gpa: Allocator) void {
1173311764 self.decls.deinit(gpa);
......@@ -11787,12 +11818,6 @@ const GenZir = struct {
1178711818 // Set if this GenZir is a defer or it is inside a defer.
1178811819 any_defer_node: Ast.Node.Index = 0,
1178911820
11790 /// Namespace members are lazy. When executing a decl within a namespace,
11791 /// any references to external instructions need to be treated specially.
11792 /// This list tracks those references. See also .closure_capture and .closure_get.
11793 /// Keys are the raw instruction index, values are the closure_capture instruction.
11794 captures: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{},
11795
1179611821 const unstacked_top = std.math.maxInt(usize);
1179711822 /// Call unstack before adding any new instructions to containing GenZir.
1179811823 fn unstack(self: *GenZir) void {
......@@ -12534,6 +12559,30 @@ const GenZir = struct {
1253412559 return new_index.toRef();
1253512560 }
1253612561
12562 fn addExtendedNodeSmall(
12563 gz: *GenZir,
12564 opcode: Zir.Inst.Extended,
12565 src_node: Ast.Node.Index,
12566 small: u16,
12567 ) !Zir.Inst.Ref {
12568 const astgen = gz.astgen;
12569 const gpa = astgen.gpa;
12570
12571 try gz.instructions.ensureUnusedCapacity(gpa, 1);
12572 try astgen.instructions.ensureUnusedCapacity(gpa, 1);
12573 const new_index: Zir.Inst.Index = @enumFromInt(astgen.instructions.len);
12574 astgen.instructions.appendAssumeCapacity(.{
12575 .tag = .extended,
12576 .data = .{ .extended = .{
12577 .opcode = opcode,
12578 .small = small,
12579 .operand = @bitCast(gz.nodeIndexToRelative(src_node)),
12580 } },
12581 });
12582 gz.instructions.appendAssumeCapacity(new_index);
12583 return new_index.toRef();
12584 }
12585
1253712586 fn addUnTok(
1253812587 gz: *GenZir,
1253912588 tag: Zir.Inst.Tag,
......@@ -12957,10 +13006,10 @@ const GenZir = struct {
1295713006
1295813007 fn setStruct(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
1295913008 src_node: Ast.Node.Index,
13009 captures_len: u32,
1296013010 fields_len: u32,
1296113011 decls_len: u32,
12962 backing_int_ref: Zir.Inst.Ref,
12963 backing_int_body_len: u32,
13012 has_backing_int: bool,
1296413013 layout: std.builtin.Type.ContainerLayout,
1296513014 known_non_opv: bool,
1296613015 known_comptime_only: bool,
......@@ -12978,7 +13027,7 @@ const GenZir = struct {
1297813027
1297913028 const fields_hash_arr: [4]u32 = @bitCast(args.fields_hash);
1298013029
12981 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.StructDecl).Struct.fields.len + 4);
13030 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.StructDecl).Struct.fields.len + 3);
1298213031 const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.StructDecl{
1298313032 .fields_hash_0 = fields_hash_arr[0],
1298413033 .fields_hash_1 = fields_hash_arr[1],
......@@ -12987,26 +13036,24 @@ const GenZir = struct {
1298713036 .src_node = gz.nodeIndexToRelative(args.src_node),
1298813037 });
1298913038
13039 if (args.captures_len != 0) {
13040 astgen.extra.appendAssumeCapacity(args.captures_len);
13041 }
1299013042 if (args.fields_len != 0) {
1299113043 astgen.extra.appendAssumeCapacity(args.fields_len);
1299213044 }
1299313045 if (args.decls_len != 0) {
1299413046 astgen.extra.appendAssumeCapacity(args.decls_len);
1299513047 }
12996 if (args.backing_int_ref != .none) {
12997 astgen.extra.appendAssumeCapacity(args.backing_int_body_len);
12998 if (args.backing_int_body_len == 0) {
12999 astgen.extra.appendAssumeCapacity(@intFromEnum(args.backing_int_ref));
13000 }
13001 }
1300213048 astgen.instructions.set(@intFromEnum(inst), .{
1300313049 .tag = .extended,
1300413050 .data = .{ .extended = .{
1300513051 .opcode = .struct_decl,
1300613052 .small = @bitCast(Zir.Inst.StructDecl.Small{
13053 .has_captures_len = args.captures_len != 0,
1300713054 .has_fields_len = args.fields_len != 0,
1300813055 .has_decls_len = args.decls_len != 0,
13009 .has_backing_int = args.backing_int_ref != .none,
13056 .has_backing_int = args.has_backing_int,
1301013057 .known_non_opv = args.known_non_opv,
1301113058 .known_comptime_only = args.known_comptime_only,
1301213059 .is_tuple = args.is_tuple,
......@@ -13024,6 +13071,7 @@ const GenZir = struct {
1302413071 fn setUnion(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
1302513072 src_node: Ast.Node.Index,
1302613073 tag_type: Zir.Inst.Ref,
13074 captures_len: u32,
1302713075 body_len: u32,
1302813076 fields_len: u32,
1302913077 decls_len: u32,
......@@ -13039,7 +13087,7 @@ const GenZir = struct {
1303913087
1304013088 const fields_hash_arr: [4]u32 = @bitCast(args.fields_hash);
1304113089
13042 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.UnionDecl).Struct.fields.len + 4);
13090 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.UnionDecl).Struct.fields.len + 5);
1304313091 const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.UnionDecl{
1304413092 .fields_hash_0 = fields_hash_arr[0],
1304513093 .fields_hash_1 = fields_hash_arr[1],
......@@ -13051,6 +13099,9 @@ const GenZir = struct {
1305113099 if (args.tag_type != .none) {
1305213100 astgen.extra.appendAssumeCapacity(@intFromEnum(args.tag_type));
1305313101 }
13102 if (args.captures_len != 0) {
13103 astgen.extra.appendAssumeCapacity(args.captures_len);
13104 }
1305413105 if (args.body_len != 0) {
1305513106 astgen.extra.appendAssumeCapacity(args.body_len);
1305613107 }
......@@ -13066,6 +13117,7 @@ const GenZir = struct {
1306613117 .opcode = .union_decl,
1306713118 .small = @bitCast(Zir.Inst.UnionDecl.Small{
1306813119 .has_tag_type = args.tag_type != .none,
13120 .has_captures_len = args.captures_len != 0,
1306913121 .has_body_len = args.body_len != 0,
1307013122 .has_fields_len = args.fields_len != 0,
1307113123 .has_decls_len = args.decls_len != 0,
......@@ -13082,6 +13134,7 @@ const GenZir = struct {
1308213134 fn setEnum(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
1308313135 src_node: Ast.Node.Index,
1308413136 tag_type: Zir.Inst.Ref,
13137 captures_len: u32,
1308513138 body_len: u32,
1308613139 fields_len: u32,
1308713140 decls_len: u32,
......@@ -13095,7 +13148,7 @@ const GenZir = struct {
1309513148
1309613149 const fields_hash_arr: [4]u32 = @bitCast(args.fields_hash);
1309713150
13098 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.EnumDecl).Struct.fields.len + 4);
13151 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.EnumDecl).Struct.fields.len + 5);
1309913152 const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.EnumDecl{
1310013153 .fields_hash_0 = fields_hash_arr[0],
1310113154 .fields_hash_1 = fields_hash_arr[1],
......@@ -13107,6 +13160,9 @@ const GenZir = struct {
1310713160 if (args.tag_type != .none) {
1310813161 astgen.extra.appendAssumeCapacity(@intFromEnum(args.tag_type));
1310913162 }
13163 if (args.captures_len != 0) {
13164 astgen.extra.appendAssumeCapacity(args.captures_len);
13165 }
1311013166 if (args.body_len != 0) {
1311113167 astgen.extra.appendAssumeCapacity(args.body_len);
1311213168 }
......@@ -13122,6 +13178,7 @@ const GenZir = struct {
1312213178 .opcode = .enum_decl,
1312313179 .small = @bitCast(Zir.Inst.EnumDecl.Small{
1312413180 .has_tag_type = args.tag_type != .none,
13181 .has_captures_len = args.captures_len != 0,
1312513182 .has_body_len = args.body_len != 0,
1312613183 .has_fields_len = args.fields_len != 0,
1312713184 .has_decls_len = args.decls_len != 0,
......@@ -13135,6 +13192,7 @@ const GenZir = struct {
1313513192
1313613193 fn setOpaque(gz: *GenZir, inst: Zir.Inst.Index, args: struct {
1313713194 src_node: Ast.Node.Index,
13195 captures_len: u32,
1313813196 decls_len: u32,
1313913197 }) !void {
1314013198 const astgen = gz.astgen;
......@@ -13142,11 +13200,14 @@ const GenZir = struct {
1314213200
1314313201 assert(args.src_node != 0);
1314413202
13145 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.OpaqueDecl).Struct.fields.len + 1);
13203 try astgen.extra.ensureUnusedCapacity(gpa, @typeInfo(Zir.Inst.OpaqueDecl).Struct.fields.len + 2);
1314613204 const payload_index = astgen.addExtraAssumeCapacity(Zir.Inst.OpaqueDecl{
1314713205 .src_node = gz.nodeIndexToRelative(args.src_node),
1314813206 });
1314913207
13208 if (args.captures_len != 0) {
13209 astgen.extra.appendAssumeCapacity(args.captures_len);
13210 }
1315013211 if (args.decls_len != 0) {
1315113212 astgen.extra.appendAssumeCapacity(args.decls_len);
1315213213 }
......@@ -13155,6 +13216,7 @@ const GenZir = struct {
1315513216 .data = .{ .extended = .{
1315613217 .opcode = .opaque_decl,
1315713218 .small = @bitCast(Zir.Inst.OpaqueDecl.Small{
13219 .has_captures_len = args.captures_len != 0,
1315813220 .has_decls_len = args.decls_len != 0,
1315913221 .name_strategy = gz.anon_name_strategy,
1316013222 }),
......@@ -13197,15 +13259,6 @@ const GenZir = struct {
1319713259 }
1319813260 }
1319913261
13200 fn addNamespaceCaptures(gz: *GenZir, namespace: *Scope.Namespace) !void {
13201 if (namespace.captures.count() > 0) {
13202 try gz.instructions.ensureUnusedCapacity(gz.astgen.gpa, namespace.captures.count());
13203 for (namespace.captures.values()) |capture| {
13204 gz.instructions.appendAssumeCapacity(capture);
13205 }
13206 }
13207 }
13208
1320913262 fn addDbgVar(gz: *GenZir, tag: Zir.Inst.Tag, name: Zir.NullTerminatedString, inst: Zir.Inst.Ref) !void {
1321013263 if (gz.is_comptime) return;
1321113264
......@@ -13305,7 +13358,7 @@ fn detectLocalShadowing(
1330513358 }
1330613359 s = local_ptr.parent;
1330713360 },
13308 .namespace, .enum_namespace => {
13361 .namespace => {
1330913362 outer_scope = true;
1331013363 const ns = s.cast(Scope.Namespace).?;
1331113364 const decl_node = ns.decls.get(ident_name) orelse {
......@@ -13478,7 +13531,7 @@ fn scanDecls(astgen: *AstGen, namespace: *Scope.Namespace, members: []const Ast.
1347813531 }
1347913532 s = local_ptr.parent;
1348013533 },
13481 .namespace, .enum_namespace => s = s.cast(Scope.Namespace).?.parent,
13534 .namespace => s = s.cast(Scope.Namespace).?.parent,
1348213535 .gen_zir => s = s.cast(GenZir).?.parent,
1348313536 .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent,
1348413537 .top => break,
lib/std/zig/Zir.zig+99-48
......@@ -1004,17 +1004,6 @@ pub const Inst = struct {
10041004 @"resume",
10051005 @"await",
10061006
1007 /// When a type or function refers to a comptime value from an outer
1008 /// scope, that forms a closure over comptime value. The outer scope
1009 /// will record a capture of that value, which encodes its current state
1010 /// and marks it to persist. Uses `un_tok` field. Operand is the
1011 /// instruction value to capture.
1012 closure_capture,
1013 /// The inner scope of a closure uses closure_get to retrieve the value
1014 /// stored by the outer scope. Uses `inst_node` field. Operand is the
1015 /// closure_capture instruction ref.
1016 closure_get,
1017
10181007 /// A defer statement.
10191008 /// Uses the `defer` union field.
10201009 @"defer",
......@@ -1251,8 +1240,6 @@ pub const Inst = struct {
12511240 .@"await",
12521241 .ret_err_value_code,
12531242 .extended,
1254 .closure_get,
1255 .closure_capture,
12561243 .ret_ptr,
12571244 .ret_type,
12581245 .@"try",
......@@ -1542,8 +1529,6 @@ pub const Inst = struct {
15421529 .@"resume",
15431530 .@"await",
15441531 .ret_err_value_code,
1545 .closure_get,
1546 .closure_capture,
15471532 .@"break",
15481533 .break_inline,
15491534 .condbr,
......@@ -1829,9 +1814,6 @@ pub const Inst = struct {
18291814 .@"resume" = .un_node,
18301815 .@"await" = .un_node,
18311816
1832 .closure_capture = .un_tok,
1833 .closure_get = .inst_node,
1834
18351817 .@"defer" = .@"defer",
18361818 .defer_err_code = .defer_err_code,
18371819
......@@ -2074,6 +2056,10 @@ pub const Inst = struct {
20742056 /// `operand` is payload index to `RestoreErrRetIndex`.
20752057 /// `small` is undefined.
20762058 restore_err_ret_index,
2059 /// Retrieves a value from the current type declaration scope's closure.
2060 /// `operand` is `src_node: i32`.
2061 /// `small` is closure index.
2062 closure_get,
20772063 /// Used as a placeholder instruction which is just a dummy index for Sema to replace
20782064 /// with a specific value. For instance, this is used for the capture of an `errdefer`.
20792065 /// This should never appear in a body.
......@@ -2949,7 +2935,7 @@ pub const Inst = struct {
29492935 /// These are stored in trailing data in `extra` for each prong.
29502936 pub const ProngInfo = packed struct(u32) {
29512937 body_len: u28,
2952 capture: Capture,
2938 capture: ProngInfo.Capture,
29532939 is_inline: bool,
29542940 has_tag_capture: bool,
29552941
......@@ -3013,19 +2999,21 @@ pub const Inst = struct {
30132999 };
30143000
30153001 /// Trailing:
3016 /// 0. fields_len: u32, // if has_fields_len
3017 /// 1. decls_len: u32, // if has_decls_len
3018 /// 2. backing_int_body_len: u32, // if has_backing_int
3019 /// 3. backing_int_ref: Ref, // if has_backing_int and backing_int_body_len is 0
3020 /// 4. backing_int_body_inst: Inst, // if has_backing_int and backing_int_body_len is > 0
3021 /// 5. decl: Index, // for every decls_len; points to a `declaration` instruction
3022 /// 6. flags: u32 // for every 8 fields
3002 /// 0. captures_len: u32 // if has_captures_len
3003 /// 1. fields_len: u32, // if has_fields_len
3004 /// 2. decls_len: u32, // if has_decls_len
3005 /// 3. capture: Capture // for every captures_len
3006 /// 4. backing_int_body_len: u32, // if has_backing_int
3007 /// 5. backing_int_ref: Ref, // if has_backing_int and backing_int_body_len is 0
3008 /// 6. backing_int_body_inst: Inst, // if has_backing_int and backing_int_body_len is > 0
3009 /// 7. decl: Index, // for every decls_len; points to a `declaration` instruction
3010 /// 8. flags: u32 // for every 8 fields
30233011 /// - sets of 4 bits:
30243012 /// 0b000X: whether corresponding field has an align expression
30253013 /// 0b00X0: whether corresponding field has a default expression
30263014 /// 0b0X00: whether corresponding field is comptime
30273015 /// 0bX000: whether corresponding field has a type expression
3028 /// 7. fields: { // for every fields_len
3016 /// 9. fields: { // for every fields_len
30293017 /// field_name: u32, // if !is_tuple
30303018 /// doc_comment: NullTerminatedString, // .empty if no doc comment
30313019 /// field_type: Ref, // if corresponding bit is not set. none means anytype.
......@@ -3033,7 +3021,7 @@ pub const Inst = struct {
30333021 /// align_body_len: u32, // if corresponding bit is set
30343022 /// init_body_len: u32, // if corresponding bit is set
30353023 /// }
3036 /// 8. bodies: { // for every fields_len
3024 /// 10. bodies: { // for every fields_len
30373025 /// field_type_body_inst: Inst, // for each field_type_body_len
30383026 /// align_body_inst: Inst, // for each align_body_len
30393027 /// init_body_inst: Inst, // for each init_body_len
......@@ -3052,6 +3040,7 @@ pub const Inst = struct {
30523040 }
30533041
30543042 pub const Small = packed struct {
3043 has_captures_len: bool,
30553044 has_fields_len: bool,
30563045 has_decls_len: bool,
30573046 has_backing_int: bool,
......@@ -3063,10 +3052,35 @@ pub const Inst = struct {
30633052 any_default_inits: bool,
30643053 any_comptime_fields: bool,
30653054 any_aligned_fields: bool,
3066 _: u3 = undefined,
3055 _: u2 = undefined,
30673056 };
30683057 };
30693058
3059 /// Represents a single value being captured in a type declaration's closure.
3060 /// If high bit is 0, this represents a `Zir.Inst,Index`.
3061 /// If high bit is 1, this represents an index into the last closure.
3062 pub const Capture = enum(u32) {
3063 _,
3064 pub const Unwrapped = union(enum) {
3065 inst: Zir.Inst.Index,
3066 nested: u16,
3067 };
3068 pub fn wrap(cap: Unwrapped) Capture {
3069 return switch (cap) {
3070 .inst => |inst| @enumFromInt(@intFromEnum(inst)),
3071 .nested => |idx| @enumFromInt((1 << 31) | @as(u32, idx)),
3072 };
3073 }
3074 pub fn unwrap(cap: Capture) Unwrapped {
3075 const raw = @intFromEnum(cap);
3076 const tag: u1 = @intCast(raw >> 31);
3077 return switch (tag) {
3078 0 => .{ .inst = @enumFromInt(raw) },
3079 1 => .{ .nested = @truncate(raw) },
3080 };
3081 }
3082 };
3083
30703084 pub const NameStrategy = enum(u2) {
30713085 /// Use the same name as the parent declaration name.
30723086 /// e.g. `const Foo = struct {...};`.
......@@ -3098,14 +3112,16 @@ pub const Inst = struct {
30983112
30993113 /// Trailing:
31003114 /// 0. tag_type: Ref, // if has_tag_type
3101 /// 1. body_len: u32, // if has_body_len
3102 /// 2. fields_len: u32, // if has_fields_len
3103 /// 3. decls_len: u32, // if has_decls_len
3104 /// 4. decl: Index, // for every decls_len; points to a `declaration` instruction
3105 /// 5. inst: Index // for every body_len
3106 /// 6. has_bits: u32 // for every 32 fields
3115 /// 1. captures_len: u32, // if has_captures_len
3116 /// 2. body_len: u32, // if has_body_len
3117 /// 3. fields_len: u32, // if has_fields_len
3118 /// 4. decls_len: u32, // if has_decls_len
3119 /// 5. capture: Capture // for every captures_len
3120 /// 6. decl: Index, // for every decls_len; points to a `declaration` instruction
3121 /// 7. inst: Index // for every body_len
3122 /// 8. has_bits: u32 // for every 32 fields
31073123 /// - the bit is whether corresponding field has an value expression
3108 /// 7. fields: { // for every fields_len
3124 /// 9. fields: { // for every fields_len
31093125 /// field_name: u32,
31103126 /// doc_comment: u32, // .empty if no doc_comment
31113127 /// value: Ref, // if corresponding bit is set
......@@ -3125,29 +3141,32 @@ pub const Inst = struct {
31253141
31263142 pub const Small = packed struct {
31273143 has_tag_type: bool,
3144 has_captures_len: bool,
31283145 has_body_len: bool,
31293146 has_fields_len: bool,
31303147 has_decls_len: bool,
31313148 name_strategy: NameStrategy,
31323149 nonexhaustive: bool,
3133 _: u9 = undefined,
3150 _: u8 = undefined,
31343151 };
31353152 };
31363153
31373154 /// Trailing:
31383155 /// 0. tag_type: Ref, // if has_tag_type
3139 /// 1. body_len: u32, // if has_body_len
3140 /// 2. fields_len: u32, // if has_fields_len
3141 /// 3. decls_len: u32, // if has_decls_len
3142 /// 4. decl: Index, // for every decls_len; points to a `declaration` instruction
3143 /// 5. inst: Index // for every body_len
3144 /// 6. has_bits: u32 // for every 8 fields
3156 /// 1. captures_len: u32 // if has_captures_len
3157 /// 2. body_len: u32, // if has_body_len
3158 /// 3. fields_len: u32, // if has_fields_len
3159 /// 4. decls_len: u37, // if has_decls_len
3160 /// 5. capture: Capture // for every captures_len
3161 /// 6. decl: Index, // for every decls_len; points to a `declaration` instruction
3162 /// 7. inst: Index // for every body_len
3163 /// 8. has_bits: u32 // for every 8 fields
31453164 /// - sets of 4 bits:
31463165 /// 0b000X: whether corresponding field has a type expression
31473166 /// 0b00X0: whether corresponding field has a align expression
31483167 /// 0b0X00: whether corresponding field has a tag value expression
31493168 /// 0bX000: unused
3150 /// 7. fields: { // for every fields_len
3169 /// 9. fields: { // for every fields_len
31513170 /// field_name: NullTerminatedString, // null terminated string index
31523171 /// doc_comment: NullTerminatedString, // .empty if no doc comment
31533172 /// field_type: Ref, // if corresponding bit is set
......@@ -3170,6 +3189,7 @@ pub const Inst = struct {
31703189
31713190 pub const Small = packed struct {
31723191 has_tag_type: bool,
3192 has_captures_len: bool,
31733193 has_body_len: bool,
31743194 has_fields_len: bool,
31753195 has_decls_len: bool,
......@@ -3183,13 +3203,15 @@ pub const Inst = struct {
31833203 /// true | false | union(T) { }
31843204 auto_enum_tag: bool,
31853205 any_aligned_fields: bool,
3186 _: u6 = undefined,
3206 _: u5 = undefined,
31873207 };
31883208 };
31893209
31903210 /// Trailing:
3191 /// 0. decls_len: u32, // if has_decls_len
3192 /// 1. decl: Index, // for every decls_len; points to a `declaration` instruction
3211 /// 0. captures_len: u32, // if has_captures_len
3212 /// 1. decls_len: u32, // if has_decls_len
3213 /// 2. capture: Capture, // for every captures_len
3214 /// 3. decl: Index, // for every decls_len; points to a `declaration` instruction
31933215 pub const OpaqueDecl = struct {
31943216 src_node: i32,
31953217
......@@ -3198,9 +3220,10 @@ pub const Inst = struct {
31983220 }
31993221
32003222 pub const Small = packed struct {
3223 has_captures_len: bool,
32013224 has_decls_len: bool,
32023225 name_strategy: NameStrategy,
3203 _: u13 = undefined,
3226 _: u12 = undefined,
32043227 };
32053228 };
32063229
......@@ -3502,6 +3525,11 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35023525 .struct_decl => {
35033526 const small: Inst.StructDecl.Small = @bitCast(extended.small);
35043527 var extra_index: u32 = @intCast(extended.operand + @typeInfo(Inst.StructDecl).Struct.fields.len);
3528 const captures_len = if (small.has_captures_len) captures_len: {
3529 const captures_len = zir.extra[extra_index];
3530 extra_index += 1;
3531 break :captures_len captures_len;
3532 } else 0;
35053533 extra_index += @intFromBool(small.has_fields_len);
35063534 const decls_len = if (small.has_decls_len) decls_len: {
35073535 const decls_len = zir.extra[extra_index];
......@@ -3509,6 +3537,8 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35093537 break :decls_len decls_len;
35103538 } else 0;
35113539
3540 extra_index += captures_len;
3541
35123542 if (small.has_backing_int) {
35133543 const backing_int_body_len = zir.extra[extra_index];
35143544 extra_index += 1; // backing_int_body_len
......@@ -3529,6 +3559,11 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35293559 const small: Inst.EnumDecl.Small = @bitCast(extended.small);
35303560 var extra_index: u32 = @intCast(extended.operand + @typeInfo(Inst.EnumDecl).Struct.fields.len);
35313561 extra_index += @intFromBool(small.has_tag_type);
3562 const captures_len = if (small.has_captures_len) captures_len: {
3563 const captures_len = zir.extra[extra_index];
3564 extra_index += 1;
3565 break :captures_len captures_len;
3566 } else 0;
35323567 extra_index += @intFromBool(small.has_body_len);
35333568 extra_index += @intFromBool(small.has_fields_len);
35343569 const decls_len = if (small.has_decls_len) decls_len: {
......@@ -3537,6 +3572,8 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35373572 break :decls_len decls_len;
35383573 } else 0;
35393574
3575 extra_index += captures_len;
3576
35403577 return .{
35413578 .extra_index = extra_index,
35423579 .decls_remaining = decls_len,
......@@ -3547,6 +3584,11 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35473584 const small: Inst.UnionDecl.Small = @bitCast(extended.small);
35483585 var extra_index: u32 = @intCast(extended.operand + @typeInfo(Inst.UnionDecl).Struct.fields.len);
35493586 extra_index += @intFromBool(small.has_tag_type);
3587 const captures_len = if (small.has_captures_len) captures_len: {
3588 const captures_len = zir.extra[extra_index];
3589 extra_index += 1;
3590 break :captures_len captures_len;
3591 } else 0;
35503592 extra_index += @intFromBool(small.has_body_len);
35513593 extra_index += @intFromBool(small.has_fields_len);
35523594 const decls_len = if (small.has_decls_len) decls_len: {
......@@ -3555,6 +3597,8 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35553597 break :decls_len decls_len;
35563598 } else 0;
35573599
3600 extra_index += captures_len;
3601
35583602 return .{
35593603 .extra_index = extra_index,
35603604 .decls_remaining = decls_len,
......@@ -3569,6 +3613,13 @@ pub fn declIterator(zir: Zir, decl_inst: Zir.Inst.Index) DeclIterator {
35693613 extra_index += 1;
35703614 break :decls_len decls_len;
35713615 } else 0;
3616 const captures_len = if (small.has_captures_len) captures_len: {
3617 const captures_len = zir.extra[extra_index];
3618 extra_index += 1;
3619 break :captures_len captures_len;
3620 } else 0;
3621
3622 extra_index += captures_len;
35723623
35733624 return .{
35743625 .extra_index = extra_index,
src/Autodoc.zig+56-24
......@@ -450,7 +450,7 @@ const Scope = struct {
450450 Zir.NullTerminatedString, // index into the current file's string table (decl name)
451451 *DeclStatus,
452452 ) = .{},
453
453 captures: []const Zir.Inst.Capture = &.{},
454454 enclosing_type: ?usize, // index into `types`, null = file top-level struct
455455
456456 pub const DeclStatus = union(enum) {
......@@ -459,6 +459,14 @@ const Scope = struct {
459459 NotRequested: u32, // instr_index
460460 };
461461
462 fn getCapture(scope: Scope, idx: u16) struct { Zir.Inst.Index, *Scope } {
463 const parent = scope.parent.?;
464 return switch (scope.captures[idx].unwrap()) {
465 .inst => |inst| .{ inst, parent },
466 .nested => |parent_idx| parent.getCapture(parent_idx),
467 };
468 }
469
462470 /// Returns a pointer so that the caller has a chance to modify the value
463471 /// in case they decide to start analyzing a previously not requested decl.
464472 /// Another reason is that in some places we use the pointer to uniquely
......@@ -1151,29 +1159,6 @@ fn walkInstruction(
11511159 .expr = .{ .comptimeExpr = 0 },
11521160 };
11531161 },
1154 .closure_get => {
1155 const inst_node = data[@intFromEnum(inst)].inst_node;
1156
1157 const code = try self.getBlockSource(file, parent_src, inst_node.src_node);
1158 const idx = self.comptime_exprs.items.len;
1159 try self.exprs.append(self.arena, .{ .comptimeExpr = idx });
1160 try self.comptime_exprs.append(self.arena, .{ .code = code });
1161
1162 return DocData.WalkResult{
1163 .expr = .{ .comptimeExpr = idx },
1164 };
1165 },
1166 .closure_capture => {
1167 const un_tok = data[@intFromEnum(inst)].un_tok;
1168 return try self.walkRef(
1169 file,
1170 parent_scope,
1171 parent_src,
1172 un_tok.operand,
1173 need_type,
1174 call_ctx,
1175 );
1176 },
11771162 .str => {
11781163 const str = data[@intFromEnum(inst)].str.get(file.zir);
11791164
......@@ -3395,11 +3380,23 @@ fn walkInstruction(
33953380 .enclosing_type = type_slot_index,
33963381 };
33973382
3383 const small: Zir.Inst.OpaqueDecl.Small = @bitCast(extended.small);
33983384 const extra = file.zir.extraData(Zir.Inst.OpaqueDecl, extended.operand);
33993385 var extra_index: usize = extra.end;
34003386
34013387 const src_info = try self.srcLocInfo(file, extra.data.src_node, parent_src);
34023388
3389 const captures_len = if (small.has_captures_len) blk: {
3390 const captures_len = file.zir.extra[extra_index];
3391 extra_index += 1;
3392 break :blk captures_len;
3393 } else 0;
3394
3395 if (small.has_decls_len) extra_index += 1;
3396
3397 scope.captures = @ptrCast(file.zir.extra[extra_index..][0..captures_len]);
3398 extra_index += captures_len;
3399
34033400 var decl_indexes: std.ArrayListUnmanaged(usize) = .{};
34043401 var priv_decl_indexes: std.ArrayListUnmanaged(usize) = .{};
34053402
......@@ -3503,6 +3500,12 @@ fn walkInstruction(
35033500 break :blk tag_ref;
35043501 } else null;
35053502
3503 const captures_len = if (small.has_captures_len) blk: {
3504 const captures_len = file.zir.extra[extra_index];
3505 extra_index += 1;
3506 break :blk captures_len;
3507 } else 0;
3508
35063509 const body_len = if (small.has_body_len) blk: {
35073510 const body_len = file.zir.extra[extra_index];
35083511 extra_index += 1;
......@@ -3520,6 +3523,11 @@ fn walkInstruction(
35203523 else => .{ .enumLiteral = @tagName(small.layout) },
35213524 };
35223525
3526 if (small.has_decls_len) extra_index += 1;
3527
3528 scope.captures = @ptrCast(file.zir.extra[extra_index..][0..captures_len]);
3529 extra_index += captures_len;
3530
35233531 var decl_indexes: std.ArrayListUnmanaged(usize) = .{};
35243532 var priv_decl_indexes: std.ArrayListUnmanaged(usize) = .{};
35253533
......@@ -3631,6 +3639,12 @@ fn walkInstruction(
36313639 break :blk wr.expr;
36323640 } else null;
36333641
3642 const captures_len = if (small.has_captures_len) blk: {
3643 const captures_len = file.zir.extra[extra_index];
3644 extra_index += 1;
3645 break :blk captures_len;
3646 } else 0;
3647
36343648 const body_len = if (small.has_body_len) blk: {
36353649 const body_len = file.zir.extra[extra_index];
36363650 extra_index += 1;
......@@ -3643,6 +3657,11 @@ fn walkInstruction(
36433657 break :blk fields_len;
36443658 } else 0;
36453659
3660 if (small.has_decls_len) extra_index += 1;
3661
3662 scope.captures = @ptrCast(file.zir.extra[extra_index..][0..captures_len]);
3663 extra_index += captures_len;
3664
36463665 var decl_indexes: std.ArrayListUnmanaged(usize) = .{};
36473666 var priv_decl_indexes: std.ArrayListUnmanaged(usize) = .{};
36483667
......@@ -3759,6 +3778,12 @@ fn walkInstruction(
37593778
37603779 const src_info = try self.srcLocInfo(file, extra.data.src_node, parent_src);
37613780
3781 const captures_len = if (small.has_captures_len) blk: {
3782 const captures_len = file.zir.extra[extra_index];
3783 extra_index += 1;
3784 break :blk captures_len;
3785 } else 0;
3786
37623787 const fields_len = if (small.has_fields_len) blk: {
37633788 const fields_len = file.zir.extra[extra_index];
37643789 extra_index += 1;
......@@ -3768,6 +3793,9 @@ fn walkInstruction(
37683793 // We don't care about decls yet
37693794 if (small.has_decls_len) extra_index += 1;
37703795
3796 scope.captures = @ptrCast(file.zir.extra[extra_index..][0..captures_len]);
3797 extra_index += captures_len;
3798
37713799 var backing_int: ?DocData.Expr = null;
37723800 if (small.has_backing_int) {
37733801 const backing_int_body_len = file.zir.extra[extra_index];
......@@ -4018,6 +4046,10 @@ fn walkInstruction(
40184046 .expr = .{ .cmpxchgIndex = cmpxchg_index },
40194047 };
40204048 },
4049 .closure_get => {
4050 const captured, const scope = parent_scope.getCapture(extended.small);
4051 return self.walkInstruction(file, scope, parent_src, captured, need_type, call_ctx);
4052 },
40214053 }
40224054 },
40234055 }
src/InternPool.zig+1-2
......@@ -1,7 +1,6 @@
11//! All interned objects have both a value and a type.
22//! This data structure is self-contained, with the following exceptions:
33//! * Module.Namespace has a pointer to Module.File
4//! * Module.Decl has a pointer to Module.CaptureScope
54
65/// Maps `Key` to `Index`. `Key` objects are not stored anywhere; they are
76/// constructed lazily.
......@@ -6395,7 +6394,6 @@ fn finishFuncInstance(
63956394 .@"addrspace" = fn_owner_decl.@"addrspace",
63966395 .analysis = .complete,
63976396 .zir_decl_index = fn_owner_decl.zir_decl_index,
6398 .src_scope = fn_owner_decl.src_scope,
63996397 .is_pub = fn_owner_decl.is_pub,
64006398 .is_exported = fn_owner_decl.is_exported,
64016399 .alive = true,
......@@ -7891,6 +7889,7 @@ pub fn destroyNamespace(ip: *InternPool, gpa: Allocator, index: NamespaceIndex)
78917889 .parent = undefined,
78927890 .file_scope = undefined,
78937891 .decl_index = undefined,
7892 .captures = undefined,
78947893 };
78957894 ip.namespaces_free_list.append(gpa, index) catch {
78967895 // In order to keep `destroyNamespace` a non-fallible function, we ignore memory
src/Module.zig+48-52
......@@ -101,17 +101,6 @@ embed_table: std.StringArrayHashMapUnmanaged(*EmbedFile) = .{},
101101/// is not yet implemented.
102102intern_pool: InternPool = .{},
103103
104/// The index type for this array is `CaptureScope.Index` and the elements here are
105/// the indexes of the parent capture scopes.
106/// Memory is owned by gpa; garbage collected.
107capture_scope_parents: std.ArrayListUnmanaged(CaptureScope.Index) = .{},
108/// Value is index of type
109/// Memory is owned by gpa; garbage collected.
110runtime_capture_scopes: std.AutoArrayHashMapUnmanaged(CaptureScope.Key, InternPool.Index) = .{},
111/// Value is index of value
112/// Memory is owned by gpa; garbage collected.
113comptime_capture_scopes: std.AutoArrayHashMapUnmanaged(CaptureScope.Key, InternPool.Index) = .{},
114
115104/// To be eliminated in a future commit by moving more data into InternPool.
116105/// Current uses that must be eliminated:
117106/// * comptime pointer mutation
......@@ -305,28 +294,6 @@ pub const Export = struct {
305294 }
306295};
307296
308pub const CaptureScope = struct {
309 pub const Key = extern struct {
310 zir_index: Zir.Inst.Index,
311 index: Index,
312 };
313
314 /// Index into `capture_scope_parents` which uniquely identifies a capture scope.
315 pub const Index = enum(u32) {
316 none = std.math.maxInt(u32),
317 _,
318
319 pub fn parent(i: Index, mod: *Module) Index {
320 return mod.capture_scope_parents.items[@intFromEnum(i)];
321 }
322 };
323};
324
325pub fn createCaptureScope(mod: *Module, parent: CaptureScope.Index) error{OutOfMemory}!CaptureScope.Index {
326 try mod.capture_scope_parents.append(mod.gpa, parent);
327 return @enumFromInt(mod.capture_scope_parents.items.len - 1);
328}
329
330297const ValueArena = struct {
331298 state: std.heap.ArenaAllocator.State,
332299 state_acquired: ?*std.heap.ArenaAllocator.State = null,
......@@ -386,9 +353,6 @@ pub const Decl = struct {
386353 /// there is no parent.
387354 src_namespace: Namespace.Index,
388355
389 /// The scope which lexically contains this decl.
390 src_scope: CaptureScope.Index,
391
392356 /// The AST node index of this declaration.
393357 /// Must be recomputed when the corresponding source file is modified.
394358 src_node: Ast.Node.Index,
......@@ -792,11 +756,41 @@ pub const Namespace = struct {
792756 /// These are only declarations named directly by the AST; anonymous
793757 /// declarations are not stored here.
794758 decls: std.ArrayHashMapUnmanaged(Decl.Index, void, DeclContext, true) = .{},
795
796759 /// Key is usingnamespace Decl itself. To find the namespace being included,
797760 /// the Decl Value has to be resolved as a Type which has a Namespace.
798761 /// Value is whether the usingnamespace decl is marked `pub`.
799762 usingnamespace_set: std.AutoHashMapUnmanaged(Decl.Index, bool) = .{},
763 /// Allocated into `gpa`.
764 /// The ordered set of values captured in this type's closure.
765 /// `closure_get` instructions look up values in this list.
766 captures: []CaptureValue,
767
768 /// A single value captured in a container's closure. This is not an
769 /// `InternPool.Index` so we can differentiate between runtime-known values
770 /// (where only the type is comptime-known) and comptime-known values.
771 pub const CaptureValue = enum(u32) {
772 _,
773 pub const Unwrapped = union(enum) {
774 /// Index refers to the value.
775 @"comptime": InternPool.Index,
776 /// Index refers to the type.
777 runtime: InternPool.Index,
778 };
779 pub fn wrap(val: Unwrapped) CaptureValue {
780 return switch (val) {
781 .@"comptime" => |i| @enumFromInt(@intFromEnum(i)),
782 .runtime => |i| @enumFromInt((1 << 31) | @intFromEnum(i)),
783 };
784 }
785 pub fn unwrap(val: CaptureValue) Unwrapped {
786 const tag: u1 = @intCast(@intFromEnum(val) >> 31);
787 const raw = @intFromEnum(val);
788 return switch (tag) {
789 0 => .{ .@"comptime" = @enumFromInt(raw) },
790 1 => .{ .runtime = @enumFromInt(@as(u31, @truncate(raw))) },
791 };
792 }
793 };
800794
801795 const Index = InternPool.NamespaceIndex;
802796 const OptionalIndex = InternPool.OptionalNamespaceIndex;
......@@ -2135,15 +2129,12 @@ pub fn deinit(zcu: *Zcu) void {
21352129 while (it.next()) |namespace| {
21362130 namespace.decls.deinit(gpa);
21372131 namespace.usingnamespace_set.deinit(gpa);
2132 gpa.free(namespace.captures);
21382133 }
21392134 }
21402135
21412136 zcu.intern_pool.deinit(gpa);
21422137 zcu.tmp_hack_arena.deinit();
2143
2144 zcu.capture_scope_parents.deinit(gpa);
2145 zcu.runtime_capture_scopes.deinit(gpa);
2146 zcu.comptime_capture_scopes.deinit(gpa);
21472138}
21482139
21492140pub fn destroyDecl(mod: *Module, decl_index: Decl.Index) void {
......@@ -3362,11 +3353,12 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
33623353 .parent = .none,
33633354 .decl_index = undefined,
33643355 .file_scope = file,
3356 .captures = &.{},
33653357 });
33663358 const new_namespace = mod.namespacePtr(new_namespace_index);
33673359 errdefer mod.destroyNamespace(new_namespace_index);
33683360
3369 const new_decl_index = try mod.allocateNewDecl(new_namespace_index, 0, .none);
3361 const new_decl_index = try mod.allocateNewDecl(new_namespace_index, 0);
33703362 const new_decl = mod.declPtr(new_decl_index);
33713363 errdefer @panic("TODO error handling");
33723364
......@@ -3420,9 +3412,18 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
34203412 const struct_ty = sema.getStructType(
34213413 new_decl_index,
34223414 new_namespace_index,
3415 null,
34233416 try mod.intern_pool.trackZir(gpa, file, .main_struct_inst),
34243417 ) catch |err| switch (err) {
34253418 error.OutOfMemory => return error.OutOfMemory,
3419 // The following errors are from resolving capture values, but the root
3420 // struct of a file has no captures.
3421 error.AnalysisFail,
3422 error.NeededSourceLocation,
3423 error.GenericPoison,
3424 error.ComptimeReturn,
3425 error.ComptimeBreak,
3426 => unreachable,
34263427 };
34273428 // TODO: figure out InternPool removals for incremental compilation
34283429 //errdefer ip.remove(struct_ty);
......@@ -3573,7 +3574,6 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !SemaDeclResult {
35733574 .sema = &sema,
35743575 .src_decl = decl_index,
35753576 .namespace = decl.src_namespace,
3576 .wip_capture_scope = try mod.createCaptureScope(decl.src_scope),
35773577 .instructions = .{},
35783578 .inlining = null,
35793579 .is_comptime = true,
......@@ -4205,7 +4205,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void
42054205 );
42064206 const comp = zcu.comp;
42074207 if (!gop.found_existing) {
4208 const new_decl_index = try zcu.allocateNewDecl(namespace_index, decl_node, iter.parent_decl.src_scope);
4208 const new_decl_index = try zcu.allocateNewDecl(namespace_index, decl_node);
42094209 const new_decl = zcu.declPtr(new_decl_index);
42104210 new_decl.kind = kind;
42114211 new_decl.name = decl_name;
......@@ -4438,7 +4438,6 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
44384438 .sema = &sema,
44394439 .src_decl = decl_index,
44404440 .namespace = decl.src_namespace,
4441 .wip_capture_scope = try mod.createCaptureScope(decl.src_scope),
44424441 .instructions = .{},
44434442 .inlining = null,
44444443 .is_comptime = false,
......@@ -4639,7 +4638,6 @@ pub fn allocateNewDecl(
46394638 mod: *Module,
46404639 namespace: Namespace.Index,
46414640 src_node: Ast.Node.Index,
4642 src_scope: CaptureScope.Index,
46434641) !Decl.Index {
46444642 const ip = &mod.intern_pool;
46454643 const gpa = mod.gpa;
......@@ -4657,7 +4655,6 @@ pub fn allocateNewDecl(
46574655 .@"addrspace" = .generic,
46584656 .analysis = .unreferenced,
46594657 .zir_decl_index = .none,
4660 .src_scope = src_scope,
46614658 .is_pub = false,
46624659 .is_exported = false,
46634660 .alive = false,
......@@ -4697,17 +4694,16 @@ pub fn errorSetBits(mod: *Module) u16 {
46974694
46984695pub fn createAnonymousDecl(mod: *Module, block: *Sema.Block, typed_value: TypedValue) !Decl.Index {
46994696 const src_decl = mod.declPtr(block.src_decl);
4700 return mod.createAnonymousDeclFromDecl(src_decl, block.namespace, block.wip_capture_scope, typed_value);
4697 return mod.createAnonymousDeclFromDecl(src_decl, block.namespace, typed_value);
47014698}
47024699
47034700pub fn createAnonymousDeclFromDecl(
47044701 mod: *Module,
47054702 src_decl: *Decl,
47064703 namespace: Namespace.Index,
4707 src_scope: CaptureScope.Index,
47084704 tv: TypedValue,
47094705) !Decl.Index {
4710 const new_decl_index = try mod.allocateNewDecl(namespace, src_decl.src_node, src_scope);
4706 const new_decl_index = try mod.allocateNewDecl(namespace, src_decl.src_node);
47114707 errdefer mod.destroyDecl(new_decl_index);
47124708 const name = try mod.intern_pool.getOrPutStringFmt(mod.gpa, "{}__anon_{d}", .{
47134709 src_decl.name.fmt(&mod.intern_pool), @intFromEnum(new_decl_index),
......@@ -5276,7 +5272,7 @@ pub fn populateTestFunctions(
52765272 .len = test_decl_name.len,
52775273 .child = .u8_type,
52785274 });
5279 const test_name_decl_index = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, .none, .{
5275 const test_name_decl_index = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, .{
52805276 .ty = test_name_decl_ty,
52815277 .val = Value.fromInterned((try mod.intern(.{ .aggregate = .{
52825278 .ty = test_name_decl_ty.toIntern(),
......@@ -5322,7 +5318,7 @@ pub fn populateTestFunctions(
53225318 .child = test_fn_ty.toIntern(),
53235319 .sentinel = .none,
53245320 });
5325 const array_decl_index = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, .none, .{
5321 const array_decl_index = try mod.createAnonymousDeclFromDecl(decl, decl.src_namespace, .{
53265322 .ty = array_decl_ty,
53275323 .val = Value.fromInterned((try mod.intern(.{ .aggregate = .{
53285324 .ty = array_decl_ty.toIntern(),
src/Sema.zig+114-117
......@@ -155,7 +155,6 @@ const Namespace = Module.Namespace;
155155const CompileError = Module.CompileError;
156156const SemaError = Module.SemaError;
157157const Decl = Module.Decl;
158const CaptureScope = Module.CaptureScope;
159158const LazySrcLoc = std.zig.LazySrcLoc;
160159const RangeSet = @import("RangeSet.zig");
161160const target_util = @import("target.zig");
......@@ -331,8 +330,6 @@ pub const Block = struct {
331330 /// used to add a `func_instance` into the `InternPool`.
332331 params: std.MultiArrayList(Param) = .{},
333332
334 wip_capture_scope: CaptureScope.Index,
335
336333 label: ?*Label = null,
337334 inlining: ?*Inlining,
338335 /// If runtime_index is not 0 then one of these is guaranteed to be non null.
......@@ -475,7 +472,6 @@ pub const Block = struct {
475472 .src_decl = parent.src_decl,
476473 .namespace = parent.namespace,
477474 .instructions = .{},
478 .wip_capture_scope = parent.wip_capture_scope,
479475 .label = null,
480476 .inlining = parent.inlining,
481477 .is_comptime = parent.is_comptime,
......@@ -974,12 +970,6 @@ fn analyzeBodyInner(
974970
975971 try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);
976972
977 // Most of the time, we don't need to construct a new capture scope for a
978 // block. However, successive iterations of comptime loops can capture
979 // different values for the same Zir.Inst.Index, so in those cases, we will
980 // have to create nested capture scopes; see the `.repeat` case below.
981 const parent_capture_scope = block.wip_capture_scope;
982
983973 const mod = sema.mod;
984974 const map = &sema.inst_map;
985975 const tags = sema.code.instructions.items(.tag);
......@@ -1028,7 +1018,6 @@ fn analyzeBodyInner(
10281018 .c_import => try sema.zirCImport(block, inst),
10291019 .call => try sema.zirCall(block, inst, .direct),
10301020 .field_call => try sema.zirCall(block, inst, .field),
1031 .closure_get => try sema.zirClosureGet(block, inst),
10321021 .cmp_lt => try sema.zirCmp(block, inst, .lt),
10331022 .cmp_lte => try sema.zirCmp(block, inst, .lte),
10341023 .cmp_eq => try sema.zirCmpEq(block, inst, .eq, Air.Inst.Tag.fromCmpOp(.eq, block.float_mode == .Optimized)),
......@@ -1275,6 +1264,7 @@ fn analyzeBodyInner(
12751264 .work_group_size => try sema.zirWorkItem( block, extended, extended.opcode),
12761265 .work_group_id => try sema.zirWorkItem( block, extended, extended.opcode),
12771266 .in_comptime => try sema.zirInComptime( block),
1267 .closure_get => try sema.zirClosureGet( block, extended),
12781268 // zig fmt: on
12791269
12801270 .fence => {
......@@ -1453,11 +1443,6 @@ fn analyzeBodyInner(
14531443 i += 1;
14541444 continue;
14551445 },
1456 .closure_capture => {
1457 try sema.zirClosureCapture(block, inst);
1458 i += 1;
1459 continue;
1460 },
14611446 .memcpy => {
14621447 try sema.zirMemcpy(block, inst);
14631448 i += 1;
......@@ -1534,11 +1519,6 @@ fn analyzeBodyInner(
15341519 // Send comptime control flow back to the beginning of this block.
15351520 const src = LazySrcLoc.nodeOffset(datas[@intFromEnum(inst)].node);
15361521 try sema.emitBackwardBranch(block, src);
1537
1538 // We need to construct new capture scopes for the next loop iteration so it
1539 // can capture values without clobbering the earlier iteration's captures.
1540 block.wip_capture_scope = try mod.createCaptureScope(parent_capture_scope);
1541
15421522 i = 0;
15431523 continue;
15441524 } else {
......@@ -1552,11 +1532,6 @@ fn analyzeBodyInner(
15521532 // Send comptime control flow back to the beginning of this block.
15531533 const src = LazySrcLoc.nodeOffset(datas[@intFromEnum(inst)].node);
15541534 try sema.emitBackwardBranch(block, src);
1555
1556 // We need to construct new capture scopes for the next loop iteration so it
1557 // can capture values without clobbering the earlier iteration's captures.
1558 block.wip_capture_scope = try mod.createCaptureScope(parent_capture_scope);
1559
15601535 i = 0;
15611536 continue;
15621537 },
......@@ -1855,10 +1830,6 @@ fn analyzeBodyInner(
18551830 map.putAssumeCapacity(inst, air_inst);
18561831 i += 1;
18571832 }
1858
1859 // We may have overwritten the capture scope due to a `repeat` instruction where
1860 // the body had a capture; restore it now.
1861 block.wip_capture_scope = parent_capture_scope;
18621833}
18631834
18641835pub fn resolveInstAllowNone(sema: *Sema, zir_ref: Zir.Inst.Ref) !Air.Inst.Ref {
......@@ -2698,10 +2669,41 @@ fn analyzeAsInt(
26982669 return (try val.getUnsignedIntAdvanced(mod, sema)).?;
26992670}
27002671
2672/// Given a ZIR extra index which points to a list of `Zir.Inst.Capture`,
2673/// resolves this into a list of `Namespace.CaptureValue` allocated by `gpa`.
2674/// Caller owns returned memory.
2675fn getCaptures(sema: *Sema, parent_namespace: ?InternPool.NamespaceIndex, extra_index: usize, captures_len: u32) ![]Namespace.CaptureValue {
2676 const gpa = sema.gpa;
2677 const parent_captures: []const Namespace.CaptureValue = if (parent_namespace) |p| parent: {
2678 break :parent sema.mod.namespacePtr(p).captures;
2679 } else &.{};
2680
2681 const captures = try gpa.alloc(Namespace.CaptureValue, captures_len);
2682 errdefer gpa.free(captures);
2683
2684 for (sema.code.extra[extra_index..][0..captures_len], captures) |raw, *capture| {
2685 const zir_capture: Zir.Inst.Capture = @enumFromInt(raw);
2686 capture.* = switch (zir_capture.unwrap()) {
2687 .inst => |inst| Namespace.CaptureValue.wrap(capture: {
2688 const air_ref = try sema.resolveInst(inst.toRef());
2689 if (try sema.resolveValue(air_ref)) |val| {
2690 break :capture .{ .@"comptime" = val.toIntern() };
2691 }
2692 break :capture .{ .runtime = sema.typeOf(air_ref).toIntern() };
2693 }),
2694 .nested => |parent_idx| parent_captures[parent_idx],
2695 };
2696 }
2697
2698 return captures;
2699}
2700
27012701pub fn getStructType(
27022702 sema: *Sema,
27032703 decl: InternPool.DeclIndex,
27042704 namespace: InternPool.NamespaceIndex,
2705 /// The direct parent Namespace for resolving nested capture values.
2706 parent_namespace: ?InternPool.NamespaceIndex,
27052707 tracked_inst: InternPool.TrackedInst.Index,
27062708) !InternPool.Index {
27072709 const mod = sema.mod;
......@@ -2713,6 +2715,11 @@ pub fn getStructType(
27132715 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
27142716
27152717 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
2718 const captures_len = if (small.has_captures_len) blk: {
2719 const captures_len = sema.code.extra[extra_index];
2720 extra_index += 1;
2721 break :blk captures_len;
2722 } else 0;
27162723 const fields_len = if (small.has_fields_len) blk: {
27172724 const fields_len = sema.code.extra[extra_index];
27182725 extra_index += 1;
......@@ -2724,6 +2731,9 @@ pub fn getStructType(
27242731 break :blk decls_len;
27252732 } else 0;
27262733
2734 mod.namespacePtr(namespace).captures = try sema.getCaptures(parent_namespace, extra_index, captures_len);
2735 extra_index += captures_len;
2736
27272737 if (small.has_backing_int) {
27282738 const backing_int_body_len = sema.code.extra[extra_index];
27292739 extra_index += 1; // backing_int_body_len
......@@ -2791,12 +2801,13 @@ fn zirStructDecl(
27912801 .parent = block.namespace.toOptional(),
27922802 .decl_index = new_decl_index,
27932803 .file_scope = block.getFileScope(mod),
2804 .captures = &.{}, // Will be set by `getStructType`
27942805 });
27952806 errdefer mod.destroyNamespace(new_namespace_index);
27962807
27972808 const struct_ty = ty: {
27982809 const tracked_inst = try ip.trackZir(mod.gpa, block.getFileScope(mod), inst);
2799 const ty = try sema.getStructType(new_decl_index, new_namespace_index, tracked_inst);
2810 const ty = try sema.getStructType(new_decl_index, new_namespace_index, block.namespace, tracked_inst);
28002811 if (sema.builtin_type_target_index != .none) {
28012812 ip.resolveBuiltinType(sema.builtin_type_target_index, ty);
28022813 break :ty sema.builtin_type_target_index;
......@@ -2827,10 +2838,9 @@ fn createAnonymousDeclTypeNamed(
28272838 const ip = &mod.intern_pool;
28282839 const gpa = sema.gpa;
28292840 const namespace = block.namespace;
2830 const src_scope = block.wip_capture_scope;
28312841 const src_decl = mod.declPtr(block.src_decl);
28322842 const src_node = src_decl.relativeToNodeIndex(src.node_offset.x);
2833 const new_decl_index = try mod.allocateNewDecl(namespace, src_node, src_scope);
2843 const new_decl_index = try mod.allocateNewDecl(namespace, src_node);
28342844 errdefer mod.destroyDecl(new_decl_index);
28352845
28362846 switch (name_strategy) {
......@@ -2935,6 +2945,12 @@ fn zirEnumDecl(
29352945 break :blk tag_type_ref;
29362946 } else .none;
29372947
2948 const captures_len = if (small.has_captures_len) blk: {
2949 const captures_len = sema.code.extra[extra_index];
2950 extra_index += 1;
2951 break :blk captures_len;
2952 } else 0;
2953
29382954 const body_len = if (small.has_body_len) blk: {
29392955 const body_len = sema.code.extra[extra_index];
29402956 extra_index += 1;
......@@ -2974,10 +2990,14 @@ fn zirEnumDecl(
29742990 );
29752991 }
29762992
2993 const captures = try sema.getCaptures(block.namespace, extra_index, captures_len);
2994 extra_index += captures_len;
2995
29772996 const new_namespace_index = try mod.createNamespace(.{
29782997 .parent = block.namespace.toOptional(),
29792998 .decl_index = new_decl_index,
29802999 .file_scope = block.getFileScope(mod),
3000 .captures = captures,
29813001 });
29823002 errdefer if (!done) mod.destroyNamespace(new_namespace_index);
29833003
......@@ -3054,7 +3074,6 @@ fn zirEnumDecl(
30543074 .sema = sema,
30553075 .src_decl = new_decl_index,
30563076 .namespace = new_namespace_index,
3057 .wip_capture_scope = try mod.createCaptureScope(new_decl.src_scope),
30583077 .instructions = .{},
30593078 .inlining = null,
30603079 .is_comptime = true,
......@@ -3197,6 +3216,11 @@ fn zirUnionDecl(
31973216 const src = extra.data.src();
31983217
31993218 extra_index += @intFromBool(small.has_tag_type);
3219 const captures_len = if (small.has_captures_len) blk: {
3220 const captures_len = sema.code.extra[extra_index];
3221 extra_index += 1;
3222 break :blk captures_len;
3223 } else 0;
32003224 extra_index += @intFromBool(small.has_body_len);
32013225 const fields_len = if (small.has_fields_len) blk: {
32023226 const fields_len = sema.code.extra[extra_index];
......@@ -3230,10 +3254,14 @@ fn zirUnionDecl(
32303254 );
32313255 }
32323256
3257 const captures = try sema.getCaptures(block.namespace, extra_index, captures_len);
3258 extra_index += captures_len;
3259
32333260 const new_namespace_index = try mod.createNamespace(.{
32343261 .parent = block.namespace.toOptional(),
32353262 .decl_index = new_decl_index,
32363263 .file_scope = block.getFileScope(mod),
3264 .captures = captures,
32373265 });
32383266 errdefer mod.destroyNamespace(new_namespace_index);
32393267
......@@ -3300,6 +3328,12 @@ fn zirOpaqueDecl(
33003328
33013329 const src = extra.data.src();
33023330
3331 const captures_len = if (small.has_captures_len) blk: {
3332 const captures_len = sema.code.extra[extra_index];
3333 extra_index += 1;
3334 break :blk captures_len;
3335 } else 0;
3336
33033337 const decls_len = if (small.has_decls_len) blk: {
33043338 const decls_len = sema.code.extra[extra_index];
33053339 extra_index += 1;
......@@ -3326,10 +3360,14 @@ fn zirOpaqueDecl(
33263360 );
33273361 }
33283362
3363 const captures = try sema.getCaptures(block.namespace, extra_index, captures_len);
3364 extra_index += captures_len;
3365
33293366 const new_namespace_index = try mod.createNamespace(.{
33303367 .parent = block.namespace.toOptional(),
33313368 .decl_index = new_decl_index,
33323369 .file_scope = block.getFileScope(mod),
3370 .captures = captures,
33333371 });
33343372 errdefer mod.destroyNamespace(new_namespace_index);
33353373
......@@ -5780,7 +5818,6 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
57805818 .sema = sema,
57815819 .src_decl = parent_block.src_decl,
57825820 .namespace = parent_block.namespace,
5783 .wip_capture_scope = parent_block.wip_capture_scope,
57845821 .instructions = .{},
57855822 .inlining = parent_block.inlining,
57865823 .is_comptime = true,
......@@ -5900,7 +5937,6 @@ fn zirBlock(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index, force_compt
59005937 .sema = sema,
59015938 .src_decl = parent_block.src_decl,
59025939 .namespace = parent_block.namespace,
5903 .wip_capture_scope = parent_block.wip_capture_scope,
59045940 .instructions = .{},
59055941 .label = &label,
59065942 .inlining = parent_block.inlining,
......@@ -7515,7 +7551,6 @@ fn analyzeCall(
75157551 .sema = sema,
75167552 .src_decl = module_fn.owner_decl,
75177553 .namespace = fn_owner_decl.src_namespace,
7518 .wip_capture_scope = try mod.createCaptureScope(fn_owner_decl.src_scope),
75197554 .instructions = .{},
75207555 .label = null,
75217556 .inlining = &inlining,
......@@ -8036,7 +8071,6 @@ fn instantiateGenericCall(
80368071 .sema = &child_sema,
80378072 .src_decl = generic_owner_func.owner_decl,
80388073 .namespace = namespace_index,
8039 .wip_capture_scope = try mod.createCaptureScope(fn_owner_decl.src_scope),
80408074 .instructions = .{},
80418075 .inlining = null,
80428076 .is_comptime = true,
......@@ -11409,7 +11443,6 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1140911443 .sema = sema,
1141011444 .src_decl = block.src_decl,
1141111445 .namespace = block.namespace,
11412 .wip_capture_scope = block.wip_capture_scope,
1141311446 .instructions = .{},
1141411447 .label = &label,
1141511448 .inlining = block.inlining,
......@@ -12117,7 +12150,6 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1211712150 .sema = sema,
1211812151 .src_decl = block.src_decl,
1211912152 .namespace = block.namespace,
12120 .wip_capture_scope = block.wip_capture_scope,
1212112153 .instructions = .{},
1212212154 .label = &label,
1212312155 .inlining = block.inlining,
......@@ -12281,7 +12313,6 @@ fn analyzeSwitchRuntimeBlock(
1228112313 extra_index += info.body_len;
1228212314
1228312315 case_block.instructions.shrinkRetainingCapacity(0);
12284 case_block.wip_capture_scope = try mod.createCaptureScope(child_block.wip_capture_scope);
1228512316
1228612317 const item = case_vals.items[scalar_i];
1228712318 // `item` is already guaranteed to be constant known.
......@@ -12339,7 +12370,6 @@ fn analyzeSwitchRuntimeBlock(
1233912370 case_val_idx += items_len;
1234012371
1234112372 case_block.instructions.shrinkRetainingCapacity(0);
12342 case_block.wip_capture_scope = child_block.wip_capture_scope;
1234312373
1234412374 // Generate all possible cases as scalar prongs.
1234512375 if (info.is_inline) {
......@@ -12371,7 +12401,6 @@ fn analyzeSwitchRuntimeBlock(
1237112401 const item_ref = Air.internedToRef(item.toIntern());
1237212402
1237312403 case_block.instructions.shrinkRetainingCapacity(0);
12374 case_block.wip_capture_scope = child_block.wip_capture_scope;
1237512404
1237612405 if (emit_bb) sema.emitBackwardBranch(block, .unneeded) catch |err| switch (err) {
1237712406 error.NeededSourceLocation => {
......@@ -12411,7 +12440,6 @@ fn analyzeSwitchRuntimeBlock(
1241112440 cases_len += 1;
1241212441
1241312442 case_block.instructions.shrinkRetainingCapacity(0);
12414 case_block.wip_capture_scope = child_block.wip_capture_scope;
1241512443
1241612444 const analyze_body = if (union_originally) blk: {
1241712445 const item_val = sema.resolveConstDefinedValue(block, .unneeded, item, undefined) catch unreachable;
......@@ -12557,7 +12585,6 @@ fn analyzeSwitchRuntimeBlock(
1255712585 defer gpa.free(cond_body);
1255812586
1255912587 case_block.instructions.shrinkRetainingCapacity(0);
12560 case_block.wip_capture_scope = try mod.createCaptureScope(child_block.wip_capture_scope);
1256112588
1256212589 const body = sema.code.bodySlice(extra_index, info.body_len);
1256312590 extra_index += info.body_len;
......@@ -12618,7 +12645,6 @@ fn analyzeSwitchRuntimeBlock(
1261812645 const item_ref = Air.internedToRef(item_val.toIntern());
1261912646
1262012647 case_block.instructions.shrinkRetainingCapacity(0);
12621 case_block.wip_capture_scope = child_block.wip_capture_scope;
1262212648
1262312649 const analyze_body = if (union_originally) blk: {
1262412650 const field_ty = maybe_union_ty.unionFieldType(item_val, mod).?;
......@@ -12669,7 +12695,6 @@ fn analyzeSwitchRuntimeBlock(
1266912695 const item_ref = Air.internedToRef(item_val);
1267012696
1267112697 case_block.instructions.shrinkRetainingCapacity(0);
12672 case_block.wip_capture_scope = child_block.wip_capture_scope;
1267312698
1267412699 if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
1267512700 emit_bb = true;
......@@ -12700,7 +12725,6 @@ fn analyzeSwitchRuntimeBlock(
1270012725 const item_ref = Air.internedToRef(cur);
1270112726
1270212727 case_block.instructions.shrinkRetainingCapacity(0);
12703 case_block.wip_capture_scope = child_block.wip_capture_scope;
1270412728
1270512729 if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
1270612730 emit_bb = true;
......@@ -12728,7 +12752,6 @@ fn analyzeSwitchRuntimeBlock(
1272812752 cases_len += 1;
1272912753
1273012754 case_block.instructions.shrinkRetainingCapacity(0);
12731 case_block.wip_capture_scope = child_block.wip_capture_scope;
1273212755
1273312756 if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
1273412757 emit_bb = true;
......@@ -12754,7 +12777,6 @@ fn analyzeSwitchRuntimeBlock(
1275412777 cases_len += 1;
1275512778
1275612779 case_block.instructions.shrinkRetainingCapacity(0);
12757 case_block.wip_capture_scope = child_block.wip_capture_scope;
1275812780
1275912781 if (emit_bb) try sema.emitBackwardBranch(block, special_prong_src);
1276012782 emit_bb = true;
......@@ -12783,7 +12805,6 @@ fn analyzeSwitchRuntimeBlock(
1278312805 };
1278412806
1278512807 case_block.instructions.shrinkRetainingCapacity(0);
12786 case_block.wip_capture_scope = try mod.createCaptureScope(child_block.wip_capture_scope);
1278712808
1278812809 if (mod.backendSupportsFeature(.is_named_enum_value) and
1278912810 special.body.len != 0 and block.wantSafety() and
......@@ -17264,49 +17285,16 @@ fn zirThis(
1726417285 return sema.analyzeDeclVal(block, src, this_decl_index);
1726517286}
1726617287
17267fn zirClosureCapture(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
17288fn zirClosureGet(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
1726817289 const mod = sema.mod;
17269 const gpa = sema.gpa;
17270 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
17271 // Closures are not necessarily constant values. For example, the
17272 // code might do something like this:
17273 // fn foo(x: anytype) void { const S = struct {field: @TypeOf(x)}; }
17274 // ...in which case the closure_capture instruction has access to a runtime
17275 // value only. In such case only the type is saved into the scope.
17276 const operand = try sema.resolveInst(inst_data.operand);
17277 const ty = sema.typeOf(operand);
17278 const key: CaptureScope.Key = .{
17279 .zir_index = inst,
17280 .index = block.wip_capture_scope,
17281 };
17282 if (try sema.resolveValue(operand)) |val| {
17283 try mod.comptime_capture_scopes.put(gpa, key, try val.intern(ty, mod));
17284 } else {
17285 try mod.runtime_capture_scopes.put(gpa, key, ty.toIntern());
17286 }
17287}
17290 const captures = mod.namespacePtr(block.namespace).captures;
1728817291
17289fn zirClosureGet(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17290 const mod = sema.mod;
17291 //const ip = &mod.intern_pool;
17292 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].inst_node;
17293 var scope: CaptureScope.Index = mod.declPtr(block.src_decl).src_scope;
17294 assert(scope != .none);
17295 // Note: The target closure must be in this scope list.
17296 // If it's not here, the zir is invalid, or the list is broken.
17297 const capture_ty = while (true) {
17298 // Note: We don't need to add a dependency here, because
17299 // decls always depend on their lexical parents.
17300 const key: CaptureScope.Key = .{
17301 .zir_index = inst_data.inst,
17302 .index = scope,
17303 };
17304 if (mod.comptime_capture_scopes.get(key)) |val|
17305 return Air.internedToRef(val);
17306 if (mod.runtime_capture_scopes.get(key)) |ty|
17307 break ty;
17308 scope = scope.parent(mod);
17309 assert(scope != .none);
17292 const src_node: i32 = @bitCast(extended.operand);
17293 const src = LazySrcLoc.nodeOffset(src_node);
17294
17295 const capture_ty = switch (captures[extended.small].unwrap()) {
17296 .@"comptime" => |index| return Air.internedToRef(index),
17297 .runtime => |index| index,
1731017298 };
1731117299
1731217300 // The comptime case is handled already above. Runtime case below.
......@@ -17322,15 +17310,15 @@ fn zirClosureGet(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1732217310 });
1732317311 break :name null;
1732417312 };
17325 const node = sema.owner_decl.relativeToNodeIndex(inst_data.src_node);
17313 const node = sema.owner_decl.relativeToNodeIndex(src_node);
1732617314 const token = tree.nodes.items(.main_token)[node];
1732717315 break :name tree.tokenSlice(token);
1732817316 };
1732917317
1733017318 const msg = if (name) |some|
17331 try sema.errMsg(block, inst_data.src(), "'{s}' not accessible outside function scope", .{some})
17319 try sema.errMsg(block, src, "'{s}' not accessible outside function scope", .{some})
1733217320 else
17333 try sema.errMsg(block, inst_data.src(), "variable not accessible outside function scope", .{});
17321 try sema.errMsg(block, src, "variable not accessible outside function scope", .{});
1733417322 errdefer msg.destroy(sema.gpa);
1733517323
1733617324 // TODO add "declared here" note
......@@ -17350,15 +17338,15 @@ fn zirClosureGet(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1735017338 });
1735117339 break :name null;
1735217340 };
17353 const node = sema.owner_decl.relativeToNodeIndex(inst_data.src_node);
17341 const node = sema.owner_decl.relativeToNodeIndex(src_node);
1735417342 const token = tree.nodes.items(.main_token)[node];
1735517343 break :name tree.tokenSlice(token);
1735617344 };
1735717345
1735817346 const msg = if (name) |some|
17359 try sema.errMsg(block, inst_data.src(), "'{s}' not accessible from inner function", .{some})
17347 try sema.errMsg(block, src, "'{s}' not accessible from inner function", .{some})
1736017348 else
17361 try sema.errMsg(block, inst_data.src(), "variable not accessible from inner function", .{});
17349 try sema.errMsg(block, src, "variable not accessible from inner function", .{});
1736217350 errdefer msg.destroy(sema.gpa);
1736317351
1736417352 try sema.errNote(block, LazySrcLoc.nodeOffset(0), msg, "crossed function definition here", .{});
......@@ -18631,7 +18619,6 @@ fn zirTypeofBuiltin(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
1863118619 .sema = sema,
1863218620 .src_decl = block.src_decl,
1863318621 .namespace = block.namespace,
18634 .wip_capture_scope = block.wip_capture_scope,
1863518622 .instructions = .{},
1863618623 .inlining = block.inlining,
1863718624 .is_comptime = false,
......@@ -18710,7 +18697,6 @@ fn zirTypeofPeer(
1871018697 .sema = sema,
1871118698 .src_decl = block.src_decl,
1871218699 .namespace = block.namespace,
18713 .wip_capture_scope = block.wip_capture_scope,
1871418700 .instructions = .{},
1871518701 .inlining = block.inlining,
1871618702 .is_comptime = false,
......@@ -19186,7 +19172,6 @@ fn ensurePostHoc(sema: *Sema, block: *Block, dest_block: Zir.Inst.Index) !*Label
1918619172 .sema = sema,
1918719173 .src_decl = block.src_decl,
1918819174 .namespace = block.namespace,
19189 .wip_capture_scope = block.wip_capture_scope,
1919019175 .instructions = .{},
1919119176 .label = &labeled_block.label,
1919219177 .inlining = block.inlining,
......@@ -21462,6 +21447,7 @@ fn zirReify(
2146221447 .parent = block.namespace.toOptional(),
2146321448 .decl_index = new_decl_index,
2146421449 .file_scope = block.getFileScope(mod),
21450 .captures = &.{},
2146521451 });
2146621452 errdefer mod.destroyNamespace(new_namespace_index);
2146721453
......@@ -21670,6 +21656,7 @@ fn zirReify(
2167021656 .parent = block.namespace.toOptional(),
2167121657 .decl_index = new_decl_index,
2167221658 .file_scope = block.getFileScope(mod),
21659 .captures = &.{},
2167321660 });
2167421661 errdefer mod.destroyNamespace(new_namespace_index);
2167521662
......@@ -25919,7 +25906,7 @@ fn zirBuiltinExtern(
2591925906
2592025907 // TODO check duplicate extern
2592125908
25922 const new_decl_index = try mod.allocateNewDecl(sema.owner_decl.src_namespace, sema.owner_decl.src_node, .none);
25909 const new_decl_index = try mod.allocateNewDecl(sema.owner_decl.src_namespace, sema.owner_decl.src_node);
2592325910 errdefer mod.destroyDecl(new_decl_index);
2592425911 const new_decl = mod.declPtr(new_decl_index);
2592525912 new_decl.name = options.name;
......@@ -26515,7 +26502,6 @@ fn addSafetyCheck(
2651526502 .sema = sema,
2651626503 .src_decl = parent_block.src_decl,
2651726504 .namespace = parent_block.namespace,
26518 .wip_capture_scope = parent_block.wip_capture_scope,
2651926505 .instructions = .{},
2652026506 .inlining = parent_block.inlining,
2652126507 .is_comptime = false,
......@@ -26624,7 +26610,6 @@ fn panicUnwrapError(
2662426610 .sema = sema,
2662526611 .src_decl = parent_block.src_decl,
2662626612 .namespace = parent_block.namespace,
26627 .wip_capture_scope = parent_block.wip_capture_scope,
2662826613 .instructions = .{},
2662926614 .inlining = parent_block.inlining,
2663026615 .is_comptime = false,
......@@ -26741,7 +26726,6 @@ fn safetyCheckFormatted(
2674126726 .sema = sema,
2674226727 .src_decl = parent_block.src_decl,
2674326728 .namespace = parent_block.namespace,
26744 .wip_capture_scope = parent_block.wip_capture_scope,
2674526729 .instructions = .{},
2674626730 .inlining = parent_block.inlining,
2674726731 .is_comptime = false,
......@@ -35766,7 +35750,6 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.Key.StructType) Comp
3576635750 .sema = &sema,
3576735751 .src_decl = decl_index,
3576835752 .namespace = struct_type.namespace.unwrap() orelse decl.src_namespace,
35769 .wip_capture_scope = try mod.createCaptureScope(decl.src_scope),
3577035753 .instructions = .{},
3577135754 .inlining = null,
3577235755 .is_comptime = true,
......@@ -35789,9 +35772,16 @@ fn semaBackingIntType(mod: *Module, struct_type: InternPool.Key.StructType) Comp
3578935772
3579035773 if (small.has_backing_int) {
3579135774 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
35775 const captures_len = if (small.has_captures_len) blk: {
35776 const captures_len = zir.extra[extra_index];
35777 extra_index += 1;
35778 break :blk captures_len;
35779 } else 0;
3579235780 extra_index += @intFromBool(small.has_fields_len);
3579335781 extra_index += @intFromBool(small.has_decls_len);
3579435782
35783 extra_index += captures_len;
35784
3579535785 const backing_int_body_len = zir.extra[extra_index];
3579635786 extra_index += 1;
3579735787
......@@ -36500,6 +36490,12 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {
3650036490 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
3650136491 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
3650236492
36493 const captures_len = if (small.has_captures_len) blk: {
36494 const captures_len = zir.extra[extra_index];
36495 extra_index += 1;
36496 break :blk captures_len;
36497 } else 0;
36498
3650336499 const fields_len = if (small.has_fields_len) blk: {
3650436500 const fields_len = zir.extra[extra_index];
3650536501 extra_index += 1;
......@@ -36512,6 +36508,8 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {
3651236508 break :decls_len decls_len;
3651336509 } else 0;
3651436510
36511 extra_index += captures_len;
36512
3651536513 // The backing integer cannot be handled until `resolveStructLayout()`.
3651636514 if (small.has_backing_int) {
3651736515 const backing_int_body_len = zir.extra[extra_index];
......@@ -36584,7 +36582,6 @@ fn semaStructFields(
3658436582 .sema = &sema,
3658536583 .src_decl = decl_index,
3658636584 .namespace = namespace_index,
36587 .wip_capture_scope = try mod.createCaptureScope(decl.src_scope),
3658836585 .instructions = .{},
3658936586 .inlining = null,
3659036587 .is_comptime = true,
......@@ -36842,7 +36839,6 @@ fn semaStructFieldInits(
3684236839 .sema = &sema,
3684336840 .src_decl = decl_index,
3684436841 .namespace = namespace_index,
36845 .wip_capture_scope = try mod.createCaptureScope(decl.src_scope),
3684636842 .instructions = .{},
3684736843 .inlining = null,
3684836844 .is_comptime = true,
......@@ -36974,6 +36970,12 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Key.Un
3697436970 break :blk ty_ref;
3697536971 } else .none;
3697636972
36973 const captures_len = if (small.has_captures_len) blk: {
36974 const captures_len = zir.extra[extra_index];
36975 extra_index += 1;
36976 break :blk captures_len;
36977 } else 0;
36978
3697736979 const body_len = if (small.has_body_len) blk: {
3697836980 const body_len = zir.extra[extra_index];
3697936981 extra_index += 1;
......@@ -36992,8 +36994,8 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Key.Un
3699236994 break :decls_len decls_len;
3699336995 } else 0;
3699436996
36995 // Skip over decls.
36996 extra_index += decls_len;
36997 // Skip over captures and decls.
36998 extra_index += captures_len + decls_len;
3699736999
3699837000 const body = zir.bodySlice(extra_index, body_len);
3699937001 extra_index += body.len;
......@@ -37028,7 +37030,6 @@ fn semaUnionFields(mod: *Module, arena: Allocator, union_type: InternPool.Key.Un
3702837030 .sema = &sema,
3702937031 .src_decl = decl_index,
3703037032 .namespace = union_type.namespace,
37031 .wip_capture_scope = try mod.createCaptureScope(decl.src_scope),
3703237033 .instructions = .{},
3703337034 .inlining = null,
3703437035 .is_comptime = true,
......@@ -37372,7 +37373,7 @@ fn generateUnionTagTypeNumbered(
3737237373 const ip = &mod.intern_pool;
3737337374
3737437375 const src_decl = mod.declPtr(block.src_decl);
37375 const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node, block.wip_capture_scope);
37376 const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node);
3737637377 errdefer mod.destroyDecl(new_decl_index);
3737737378 const fqn = try decl.fullyQualifiedName(mod);
3737837379 const name = try ip.getOrPutStringFmt(gpa, "@typeInfo({}).Union.tag_type.?", .{fqn.fmt(ip)});
......@@ -37425,7 +37426,7 @@ fn generateUnionTagTypeSimple(
3742537426 };
3742637427 const fqn = try mod.declPtr(decl_index).fullyQualifiedName(mod);
3742737428 const src_decl = mod.declPtr(block.src_decl);
37428 const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node, block.wip_capture_scope);
37429 const new_decl_index = try mod.allocateNewDecl(block.namespace, src_decl.src_node);
3742937430 errdefer mod.destroyDecl(new_decl_index);
3743037431 const name = try ip.getOrPutStringFmt(gpa, "@typeInfo({}).Union.tag_type.?", .{fqn.fmt(ip)});
3743137432 try mod.initNewAnonDecl(new_decl_index, src_decl.src_line, .{
......@@ -37460,7 +37461,6 @@ fn generateUnionTagTypeSimple(
3746037461}
3746137462
3746237463fn getBuiltin(sema: *Sema, name: []const u8) CompileError!Air.Inst.Ref {
37463 const mod = sema.mod;
3746437464 const gpa = sema.gpa;
3746537465 const src = LazySrcLoc.nodeOffset(0);
3746637466
......@@ -37469,7 +37469,6 @@ fn getBuiltin(sema: *Sema, name: []const u8) CompileError!Air.Inst.Ref {
3746937469 .sema = sema,
3747037470 .src_decl = sema.owner_decl_index,
3747137471 .namespace = sema.owner_decl.src_namespace,
37472 .wip_capture_scope = try mod.createCaptureScope(sema.owner_decl.src_scope),
3747337472 .instructions = .{},
3747437473 .inlining = null,
3747537474 .is_comptime = true,
......@@ -37510,7 +37509,6 @@ fn getBuiltinDecl(sema: *Sema, block: *Block, name: []const u8) CompileError!Int
3751037509}
3751137510
3751237511fn getBuiltinType(sema: *Sema, name: []const u8) CompileError!Type {
37513 const mod = sema.mod;
3751437512 const ty_inst = try sema.getBuiltin(name);
3751537513
3751637514 var block: Block = .{
......@@ -37518,7 +37516,6 @@ fn getBuiltinType(sema: *Sema, name: []const u8) CompileError!Type {
3751837516 .sema = sema,
3751937517 .src_decl = sema.owner_decl_index,
3752037518 .namespace = sema.owner_decl.src_namespace,
37521 .wip_capture_scope = try mod.createCaptureScope(sema.owner_decl.src_scope),
3752237519 .instructions = .{},
3752337520 .inlining = null,
3752437521 .is_comptime = true,
src/print_zir.zig+96-5
......@@ -282,7 +282,6 @@ const Writer = struct {
282282
283283 .ref,
284284 .ret_implicit,
285 .closure_capture,
286285 .validate_ref_ty,
287286 => try self.writeUnTok(stream, inst),
288287
......@@ -510,8 +509,6 @@ const Writer = struct {
510509
511510 .dbg_stmt => try self.writeDbgStmt(stream, inst),
512511
513 .closure_get => try self.writeInstNode(stream, inst),
514
515512 .@"defer" => try self.writeDefer(stream, inst),
516513 .defer_err_code => try self.writeDeferErrCode(stream, inst),
517514
......@@ -611,6 +608,7 @@ const Writer = struct {
611608 .ptr_cast_no_dest => try self.writePtrCastNoDest(stream, extended),
612609
613610 .restore_err_ret_index => try self.writeRestoreErrRetIndex(stream, extended),
611 .closure_get => try self.writeClosureGet(stream, extended),
614612 }
615613 }
616614
......@@ -1401,6 +1399,12 @@ const Writer = struct {
14011399
14021400 var extra_index: usize = extra.end;
14031401
1402 const captures_len = if (small.has_captures_len) blk: {
1403 const captures_len = self.code.extra[extra_index];
1404 extra_index += 1;
1405 break :blk captures_len;
1406 } else 0;
1407
14041408 const fields_len = if (small.has_fields_len) blk: {
14051409 const fields_len = self.code.extra[extra_index];
14061410 extra_index += 1;
......@@ -1419,12 +1423,26 @@ const Writer = struct {
14191423
14201424 try stream.print("{s}, ", .{@tagName(small.name_strategy)});
14211425
1422 if (small.layout == .Packed and small.has_backing_int) {
1426 if (captures_len == 0) {
1427 try stream.writeAll("{}, ");
1428 } else {
1429 try stream.writeAll("{ ");
1430 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1431 extra_index += 1;
1432 for (1..captures_len) |_| {
1433 try stream.writeAll(", ");
1434 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1435 extra_index += 1;
1436 }
1437 try stream.writeAll(" }, ");
1438 }
1439
1440 if (small.has_backing_int) {
14231441 const backing_int_body_len = self.code.extra[extra_index];
14241442 extra_index += 1;
14251443 try stream.writeAll("Packed(");
14261444 if (backing_int_body_len == 0) {
1427 const backing_int_ref = @as(Zir.Inst.Ref, @enumFromInt(self.code.extra[extra_index]));
1445 const backing_int_ref: Zir.Inst.Ref = @enumFromInt(self.code.extra[extra_index]);
14281446 extra_index += 1;
14291447 try self.writeInstRef(stream, backing_int_ref);
14301448 } else {
......@@ -1601,6 +1619,12 @@ const Writer = struct {
16011619 break :blk tag_type_ref;
16021620 } else .none;
16031621
1622 const captures_len = if (small.has_captures_len) blk: {
1623 const captures_len = self.code.extra[extra_index];
1624 extra_index += 1;
1625 break :blk captures_len;
1626 } else 0;
1627
16041628 const body_len = if (small.has_body_len) blk: {
16051629 const body_len = self.code.extra[extra_index];
16061630 extra_index += 1;
......@@ -1624,6 +1648,20 @@ const Writer = struct {
16241648 });
16251649 try self.writeFlag(stream, "autoenum, ", small.auto_enum_tag);
16261650
1651 if (captures_len == 0) {
1652 try stream.writeAll("{}, ");
1653 } else {
1654 try stream.writeAll("{ ");
1655 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1656 extra_index += 1;
1657 for (1..captures_len) |_| {
1658 try stream.writeAll(", ");
1659 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1660 extra_index += 1;
1661 }
1662 try stream.writeAll(" }, ");
1663 }
1664
16271665 if (decls_len == 0) {
16281666 try stream.writeAll("{}");
16291667 } else {
......@@ -1748,6 +1786,12 @@ const Writer = struct {
17481786 break :blk tag_type_ref;
17491787 } else .none;
17501788
1789 const captures_len = if (small.has_captures_len) blk: {
1790 const captures_len = self.code.extra[extra_index];
1791 extra_index += 1;
1792 break :blk captures_len;
1793 } else 0;
1794
17511795 const body_len = if (small.has_body_len) blk: {
17521796 const body_len = self.code.extra[extra_index];
17531797 extra_index += 1;
......@@ -1769,6 +1813,20 @@ const Writer = struct {
17691813 try stream.print("{s}, ", .{@tagName(small.name_strategy)});
17701814 try self.writeFlag(stream, "nonexhaustive, ", small.nonexhaustive);
17711815
1816 if (captures_len == 0) {
1817 try stream.writeAll("{}, ");
1818 } else {
1819 try stream.writeAll("{ ");
1820 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1821 extra_index += 1;
1822 for (1..captures_len) |_| {
1823 try stream.writeAll(", ");
1824 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1825 extra_index += 1;
1826 }
1827 try stream.writeAll(" }, ");
1828 }
1829
17721830 if (decls_len == 0) {
17731831 try stream.writeAll("{}, ");
17741832 } else {
......@@ -1854,6 +1912,12 @@ const Writer = struct {
18541912 const extra = self.code.extraData(Zir.Inst.OpaqueDecl, extended.operand);
18551913 var extra_index: usize = extra.end;
18561914
1915 const captures_len = if (small.has_captures_len) blk: {
1916 const captures_len = self.code.extra[extra_index];
1917 extra_index += 1;
1918 break :blk captures_len;
1919 } else 0;
1920
18571921 const decls_len = if (small.has_decls_len) blk: {
18581922 const decls_len = self.code.extra[extra_index];
18591923 extra_index += 1;
......@@ -1862,6 +1926,20 @@ const Writer = struct {
18621926
18631927 try stream.print("{s}, ", .{@tagName(small.name_strategy)});
18641928
1929 if (captures_len == 0) {
1930 try stream.writeAll("{}, ");
1931 } else {
1932 try stream.writeAll("{ ");
1933 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1934 extra_index += 1;
1935 for (1..captures_len) |_| {
1936 try stream.writeAll(", ");
1937 try self.writeCapture(stream, @enumFromInt(self.code.extra[extra_index]));
1938 extra_index += 1;
1939 }
1940 try stream.writeAll(" }, ");
1941 }
1942
18651943 if (decls_len == 0) {
18661944 try stream.writeAll("{})");
18671945 } else {
......@@ -2706,6 +2784,12 @@ const Writer = struct {
27062784 try self.writeSrc(stream, inst_data.src());
27072785 }
27082786
2787 fn writeClosureGet(self: *Writer, stream: anytype, extended: Zir.Inst.Extended.InstData) !void {
2788 const src = LazySrcLoc.nodeOffset(@bitCast(extended.operand));
2789 try stream.print("{d})) ", .{extended.small});
2790 try self.writeSrc(stream, src);
2791 }
2792
27092793 fn writeInstRef(self: *Writer, stream: anytype, ref: Zir.Inst.Ref) !void {
27102794 if (ref == .none) {
27112795 return stream.writeAll(".none");
......@@ -2722,6 +2806,13 @@ const Writer = struct {
27222806 return stream.print("%{d}", .{@intFromEnum(inst)});
27232807 }
27242808
2809 fn writeCapture(self: *Writer, stream: anytype, capture: Zir.Inst.Capture) !void {
2810 switch (capture.unwrap()) {
2811 .inst => |inst| return self.writeInstIndex(stream, inst),
2812 .nested => |i| return stream.print("[{d}]", .{i}),
2813 }
2814 }
2815
27252816 fn writeOptionalInstRef(
27262817 self: *Writer,
27272818 stream: anytype,