authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-07-08 23:39:37-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-07-18 19:02:05-07:00
logf3dc53f6b53e8493b341f82cb06a56e33e80e6b7
treea5c5c93af8ea6661214790e54e22fd5af3e0d6d6
parent55e89255e18163bcc153138a4883ec8d85e0d517

compiler: rework inferred error sets

* move inferred error sets into InternPool. - they are now represented by pointing directly at the corresponding function body value. * inferred error set working memory is now in Sema and expires after the Sema for the function corresponding to the inferred error set is finished having its body analyzed. * error sets use a InternPool.Index.Slice rather than an actual slice to avoid lifetime issues.

7 files changed, 1037 insertions(+), 739 deletions(-)

lib/std/array_hash_map.zig+6-4
......@@ -1669,8 +1669,9 @@ pub fn ArrayHashMapUnmanaged(
16691669
16701670 inline fn checkedHash(ctx: anytype, key: anytype) u32 {
16711671 comptime std.hash_map.verifyContext(@TypeOf(ctx), @TypeOf(key), K, u32, true);
1672 // If you get a compile error on the next line, it means that
1673 const hash = ctx.hash(key); // your generic hash function doesn't accept your key
1672 // If you get a compile error on the next line, it means that your
1673 // generic hash function doesn't accept your key.
1674 const hash = ctx.hash(key);
16741675 if (@TypeOf(hash) != u32) {
16751676 @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic hash function that returns the wrong type!\n" ++
16761677 @typeName(u32) ++ " was expected, but found " ++ @typeName(@TypeOf(hash)));
......@@ -1679,8 +1680,9 @@ pub fn ArrayHashMapUnmanaged(
16791680 }
16801681 inline fn checkedEql(ctx: anytype, a: anytype, b: K, b_index: usize) bool {
16811682 comptime std.hash_map.verifyContext(@TypeOf(ctx), @TypeOf(a), K, u32, true);
1682 // If you get a compile error on the next line, it means that
1683 const eql = ctx.eql(a, b, b_index); // your generic eql function doesn't accept (self, adapt key, K, index)
1683 // If you get a compile error on the next line, it means that your
1684 // generic eql function doesn't accept (self, adapt key, K, index).
1685 const eql = ctx.eql(a, b, b_index);
16841686 if (@TypeOf(eql) != bool) {
16851687 @compileError("Context " ++ @typeName(@TypeOf(ctx)) ++ " has a generic eql function that returns the wrong type!\n" ++
16861688 @typeName(bool) ++ " was expected, but found " ++ @typeName(@TypeOf(eql)));
src/InternPool.zig+510-204
......@@ -53,14 +53,6 @@ allocated_unions: std.SegmentedList(Module.Union, 0) = .{},
5353/// When a Union object is freed from `allocated_unions`, it is pushed into this stack.
5454unions_free_list: std.ArrayListUnmanaged(Module.Union.Index) = .{},
5555
56/// InferredErrorSet objects are stored in this data structure because:
57/// * They contain pointers such as the errors map and the set of other inferred error sets.
58/// * They need to be mutated after creation.
59allocated_inferred_error_sets: std.SegmentedList(Module.InferredErrorSet, 0) = .{},
60/// When a Struct object is freed from `allocated_inferred_error_sets`, it is
61/// pushed into this stack.
62inferred_error_sets_free_list: std.ArrayListUnmanaged(Module.InferredErrorSet.Index) = .{},
63
6456/// Some types such as enums, structs, and unions need to store mappings from field names
6557/// to field index, or value to field index. In such cases, they will store the underlying
6658/// field names and values directly, relying on one of these maps, stored separately,
......@@ -143,12 +135,24 @@ pub const NullTerminatedString = enum(u32) {
143135 empty = 0,
144136 _,
145137
138 /// An array of `NullTerminatedString` existing within the `extra` array.
139 /// This type exists to provide a struct with lifetime that is
140 /// not invalidated when items are added to the `InternPool`.
141 pub const Slice = struct {
142 start: u32,
143 len: u32,
144
145 pub fn get(slice: Slice, ip: *const InternPool) []NullTerminatedString {
146 return @ptrCast(ip.extra.items[slice.start..][0..slice.len]);
147 }
148 };
149
146150 pub fn toString(self: NullTerminatedString) String {
147 return @as(String, @enumFromInt(@intFromEnum(self)));
151 return @enumFromInt(@intFromEnum(self));
148152 }
149153
150154 pub fn toOptional(self: NullTerminatedString) OptionalNullTerminatedString {
151 return @as(OptionalNullTerminatedString, @enumFromInt(@intFromEnum(self)));
155 return @enumFromInt(@intFromEnum(self));
152156 }
153157
154158 const Adapter = struct {
......@@ -238,7 +242,8 @@ pub const Key = union(enum) {
238242 enum_type: EnumType,
239243 func_type: FuncType,
240244 error_set_type: ErrorSetType,
241 inferred_error_set_type: Module.InferredErrorSet.Index,
245 /// The payload is the function body, either a `func_decl` or `func_instance`.
246 inferred_error_set_type: Index,
242247
243248 /// Typed `undefined`. This will never be `none`; untyped `undefined` is represented
244249 /// via `simple_value` and has a named `Index` tag for it.
......@@ -287,14 +292,14 @@ pub const Key = union(enum) {
287292
288293 pub const ErrorSetType = struct {
289294 /// Set of error names, sorted by null terminated string index.
290 names: []const NullTerminatedString,
295 names: NullTerminatedString.Slice,
291296 /// This is ignored by `get` but will always be provided by `indexToKey`.
292297 names_map: OptionalMapIndex = .none,
293298
294299 /// Look up field index based on field name.
295300 pub fn nameIndex(self: ErrorSetType, ip: *const InternPool, name: NullTerminatedString) ?u32 {
296301 const map = &ip.maps.items[@intFromEnum(self.names_map.unwrap().?)];
297 const adapter: NullTerminatedString.Adapter = .{ .strings = self.names };
302 const adapter: NullTerminatedString.Adapter = .{ .strings = self.names.get(ip) };
298303 const field_index = map.getIndexAdapted(name, adapter) orelse return null;
299304 return @as(u32, @intCast(field_index));
300305 }
......@@ -565,6 +570,9 @@ pub const Key = union(enum) {
565570 /// Index into extra array of the `zir_body_inst` corresponding to this function.
566571 /// Used for mutating that data.
567572 zir_body_inst_extra_index: u32,
573 /// Index into extra array of the resolved inferred error set for this function.
574 /// Used for mutating that data.
575 resolved_error_set_extra_index: u32,
568576 /// When a generic function is instantiated, branch_quota is inherited from the
569577 /// active Sema context. Importantly, this value is also updated when an existing
570578 /// generic function instantiation is found and called.
......@@ -603,13 +611,21 @@ pub const Key = union(enum) {
603611 return @ptrCast(&ip.extra.items[func.analysis_extra_index]);
604612 }
605613
614 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
606615 pub fn zirBodyInst(func: *const Func, ip: *const InternPool) *Zir.Inst.Index {
607616 return @ptrCast(&ip.extra.items[func.zir_body_inst_extra_index]);
608617 }
609618
619 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
610620 pub fn branchQuota(func: *const Func, ip: *const InternPool) *u32 {
611621 return &ip.extra.items[func.zir_body_inst_extra_index];
612622 }
623
624 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
625 pub fn resolvedErrorSet(func: *const Func, ip: *const InternPool) *Index {
626 assert(func.analysis(ip).inferred_error_set);
627 return @ptrCast(&ip.extra.items[func.resolved_error_set_extra_index]);
628 }
613629 };
614630
615631 pub const Int = struct {
......@@ -750,7 +766,7 @@ pub const Key = union(enum) {
750766 };
751767
752768 pub fn hash32(key: Key, ip: *const InternPool) u32 {
753 return @as(u32, @truncate(key.hash64(ip)));
769 return @truncate(key.hash64(ip));
754770 }
755771
756772 pub fn hash64(key: Key, ip: *const InternPool) u64 {
......@@ -914,11 +930,7 @@ pub const Key = union(enum) {
914930 return hasher.final();
915931 },
916932
917 .error_set_type => |error_set_type| {
918 var hasher = Hash.init(seed);
919 for (error_set_type.names) |elem| std.hash.autoHash(&hasher, elem);
920 return hasher.final();
921 },
933 .error_set_type => |x| Hash.hash(seed, std.mem.sliceAsBytes(x.names.get(ip))),
922934
923935 .anon_struct_type => |anon_struct_type| {
924936 var hasher = Hash.init(seed);
......@@ -1225,7 +1237,7 @@ pub const Key = union(enum) {
12251237 },
12261238 .error_set_type => |a_info| {
12271239 const b_info = b.error_set_type;
1228 return std.mem.eql(NullTerminatedString, a_info.names, b_info.names);
1240 return std.mem.eql(NullTerminatedString, a_info.names.get(ip), b_info.names.get(ip));
12291241 },
12301242 .inferred_error_set_type => |a_info| {
12311243 const b_info = b.inferred_error_set_type;
......@@ -1518,13 +1530,14 @@ pub const Index = enum(u32) {
15181530 type_optional: DataIsIndex,
15191531 type_anyframe: DataIsIndex,
15201532 type_error_union: struct { data: *Key.ErrorUnionType },
1533 type_anyerror_union: DataIsIndex,
15211534 type_error_set: struct {
15221535 const @"data.names_len" = opaque {};
15231536 data: *Tag.ErrorSet,
15241537 @"trailing.names.len": *@"data.names_len",
15251538 trailing: struct { names: []NullTerminatedString },
15261539 },
1527 type_inferred_error_set: struct { data: Module.InferredErrorSet.Index },
1540 type_inferred_error_set: DataIsIndex,
15281541 type_enum_auto: struct {
15291542 const @"data.fields_len" = opaque {};
15301543 data: *EnumAuto,
......@@ -1916,11 +1929,14 @@ pub const Tag = enum(u8) {
19161929 /// An error union type.
19171930 /// data is payload to `Key.ErrorUnionType`.
19181931 type_error_union,
1932 /// An error union type of the form `anyerror!T`.
1933 /// data is `Index` of payload type.
1934 type_anyerror_union,
19191935 /// An error set type.
19201936 /// data is payload to `ErrorSet`.
19211937 type_error_set,
19221938 /// The inferred error set type of a function.
1923 /// data is `Module.InferredErrorSet.Index`.
1939 /// data is `Index` of a `func_decl` or `func_instance`.
19241940 type_inferred_error_set,
19251941 /// An enum type with auto-numbered tag values.
19261942 /// The enum is exhaustive.
......@@ -2156,6 +2172,7 @@ pub const Tag = enum(u8) {
21562172 .type_optional => unreachable,
21572173 .type_anyframe => unreachable,
21582174 .type_error_union => ErrorUnionType,
2175 .type_anyerror_union => unreachable,
21592176 .type_error_set => ErrorSet,
21602177 .type_inferred_error_set => unreachable,
21612178 .type_enum_auto => EnumAuto,
......@@ -2251,6 +2268,10 @@ pub const Tag = enum(u8) {
22512268 ty: Index,
22522269 };
22532270
2271 /// Trailing:
2272 /// 0. If `analysis.inferred_error_set` is `true`, `Index` of an `error_set` which
2273 /// is a regular error set corresponding to the finished inferred error set.
2274 /// A `none` value marks that the inferred error set is not resolved yet.
22542275 pub const FuncDecl = struct {
22552276 analysis: FuncAnalysis,
22562277 owner_decl: Module.Decl.Index,
......@@ -2263,10 +2284,10 @@ pub const Tag = enum(u8) {
22632284 };
22642285
22652286 /// Trailing:
2266 /// 0. For each parameter of generic_owner: Index
2267 /// - comptime parameter: the comptime-known value
2268 /// - anytype parameter: the type of the runtime-known value
2269 /// - otherwise: `none`
2287 /// 0. If `analysis.inferred_error_set` is `true`, `Index` of an `error_set` which
2288 /// is a regular error set corresponding to the finished inferred error set.
2289 /// A `none` value marks that the inferred error set is not resolved yet.
2290 /// 1. For each parameter of generic_owner: `Index` if comptime, otherwise `none`
22702291 pub const FuncInstance = struct {
22712292 analysis: FuncAnalysis,
22722293 // Needed by the linker for codegen. Not part of hashing or equality.
......@@ -2312,14 +2333,19 @@ pub const Tag = enum(u8) {
23122333};
23132334
23142335/// State that is mutable during semantic analysis. This data is not used for
2315/// equality or hashing.
2336/// equality or hashing, except for `inferred_error_set` which is considered
2337/// to be part of the type of the function.
23162338pub const FuncAnalysis = packed struct(u32) {
23172339 state: State,
23182340 is_cold: bool,
23192341 is_noinline: bool,
23202342 calls_or_awaits_errorable_fn: bool,
23212343 stack_alignment: Alignment,
2322 _: u15 = 0,
2344
2345 /// True if this function has an inferred error set.
2346 inferred_error_set: bool,
2347
2348 _: u14 = 0,
23232349
23242350 pub const State = enum(u8) {
23252351 /// This function has not yet undergone analysis, because we have not
......@@ -2710,9 +2736,6 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
27102736 ip.unions_free_list.deinit(gpa);
27112737 ip.allocated_unions.deinit(gpa);
27122738
2713 ip.inferred_error_sets_free_list.deinit(gpa);
2714 ip.allocated_inferred_error_sets.deinit(gpa);
2715
27162739 ip.decls_free_list.deinit(gpa);
27172740 ip.allocated_decls.deinit(gpa);
27182741
......@@ -2780,19 +2803,15 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
27802803 return .{ .ptr_type = ptr_info };
27812804 },
27822805
2783 .type_optional => .{ .opt_type = @as(Index, @enumFromInt(data)) },
2784 .type_anyframe => .{ .anyframe_type = @as(Index, @enumFromInt(data)) },
2806 .type_optional => .{ .opt_type = @enumFromInt(data) },
2807 .type_anyframe => .{ .anyframe_type = @enumFromInt(data) },
27852808
27862809 .type_error_union => .{ .error_union_type = ip.extraData(Key.ErrorUnionType, data) },
2787 .type_error_set => {
2788 const error_set = ip.extraDataTrail(Tag.ErrorSet, data);
2789 const names_len = error_set.data.names_len;
2790 const names = ip.extra.items[error_set.end..][0..names_len];
2791 return .{ .error_set_type = .{
2792 .names = @ptrCast(names),
2793 .names_map = error_set.data.names_map.toOptional(),
2794 } };
2795 },
2810 .type_anyerror_union => .{ .error_union_type = .{
2811 .error_set_type = .anyerror_type,
2812 .payload_type = @enumFromInt(data),
2813 } },
2814 .type_error_set => ip.indexToKeyErrorSetType(data),
27962815 .type_inferred_error_set => .{
27972816 .inferred_error_set_type = @enumFromInt(data),
27982817 },
......@@ -2870,7 +2889,7 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
28702889 },
28712890 .type_enum_explicit => ip.indexToKeyEnum(data, .explicit),
28722891 .type_enum_nonexhaustive => ip.indexToKeyEnum(data, .nonexhaustive),
2873 .type_function => .{ .func_type = ip.indexToKeyFuncType(data) },
2892 .type_function => .{ .func_type = ip.extraFuncType(data) },
28742893
28752894 .undef => .{ .undef = @as(Index, @enumFromInt(data)) },
28762895 .runtime_value => .{ .runtime_value = ip.extraData(Tag.TypeValue, data) },
......@@ -3117,12 +3136,8 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
31173136 } };
31183137 },
31193138 .extern_func => .{ .extern_func = ip.extraData(Tag.ExternFunc, data) },
3120 .func_instance => {
3121 @panic("TODO");
3122 },
3123 .func_decl => {
3124 @panic("TODO");
3125 },
3139 .func_instance => .{ .func = ip.indexToKeyFuncInstance(data) },
3140 .func_decl => .{ .func = ip.indexToKeyFuncDecl(data) },
31263141 .only_possible_value => {
31273142 const ty = @as(Index, @enumFromInt(data));
31283143 const ty_item = ip.items.get(@intFromEnum(ty));
......@@ -3227,8 +3242,19 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
32273242 };
32283243}
32293244
3230fn indexToKeyFuncType(ip: *const InternPool, data: u32) Key.FuncType {
3231 const type_function = ip.extraDataTrail(Tag.TypeFunction, data);
3245fn indexToKeyErrorSetType(ip: *const InternPool, data: u32) Key {
3246 const error_set = ip.extraDataTrail(Tag.ErrorSet, data);
3247 return .{ .error_set_type = .{
3248 .names = .{
3249 .start = @intCast(error_set.end),
3250 .len = error_set.data.names_len,
3251 },
3252 .names_map = error_set.data.names_map.toOptional(),
3253 } };
3254}
3255
3256fn extraFuncType(ip: *const InternPool, extra_index: u32) Key.FuncType {
3257 const type_function = ip.extraDataTrail(Tag.TypeFunction, extra_index);
32323258 var index: usize = type_function.end;
32333259 const comptime_bits: u32 = if (!type_function.data.flags.has_comptime_bits) 0 else b: {
32343260 const x = ip.extra.items[index];
......@@ -3256,14 +3282,22 @@ fn indexToKeyFuncType(ip: *const InternPool, data: u32) Key.FuncType {
32563282 .cc_is_generic = type_function.data.flags.cc_is_generic,
32573283 .section_is_generic = type_function.data.flags.section_is_generic,
32583284 .addrspace_is_generic = type_function.data.flags.addrspace_is_generic,
3259 .is_generic = comptime_bits != 0 or
3260 type_function.data.flags.align_is_generic or
3261 type_function.data.flags.cc_is_generic or
3262 type_function.data.flags.section_is_generic or
3263 type_function.data.flags.addrspace_is_generic,
3285 .is_generic = type_function.data.flags.is_generic,
32643286 };
32653287}
32663288
3289fn indexToKeyFuncDecl(ip: *const InternPool, data: u32) Key.Func {
3290 _ = ip;
3291 _ = data;
3292 @panic("TODO");
3293}
3294
3295fn indexToKeyFuncInstance(ip: *const InternPool, data: u32) Key.Func {
3296 _ = ip;
3297 _ = data;
3298 @panic("TODO");
3299}
3300
32673301fn indexToKeyEnum(ip: *const InternPool, data: u32, tag_mode: Key.EnumType.TagMode) Key {
32683302 const enum_explicit = ip.extraDataTrail(EnumExplicit, data);
32693303 const names = @as(
......@@ -3301,7 +3335,7 @@ fn indexToKeyBigInt(ip: *const InternPool, limb_index: u32, positive: bool) Key
33013335pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
33023336 const adapter: KeyAdapter = .{ .intern_pool = ip };
33033337 const gop = try ip.map.getOrPutAdapted(gpa, key, adapter);
3304 if (gop.found_existing) return @as(Index, @enumFromInt(gop.index));
3338 if (gop.found_existing) return @enumFromInt(gop.index);
33053339 try ip.items.ensureUnusedCapacity(gpa, 1);
33063340 switch (key) {
33073341 .int_type => |int_type| {
......@@ -3392,17 +3426,20 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
33923426 });
33933427 },
33943428 .error_union_type => |error_union_type| {
3395 ip.items.appendAssumeCapacity(.{
3429 ip.items.appendAssumeCapacity(if (error_union_type.error_set_type == .anyerror_type) .{
3430 .tag = .type_anyerror_union,
3431 .data = @intFromEnum(error_union_type.payload_type),
3432 } else .{
33963433 .tag = .type_error_union,
33973434 .data = try ip.addExtra(gpa, error_union_type),
33983435 });
33993436 },
34003437 .error_set_type => |error_set_type| {
34013438 assert(error_set_type.names_map == .none);
3402 assert(std.sort.isSorted(NullTerminatedString, error_set_type.names, {}, NullTerminatedString.indexLessThan));
3439 assert(std.sort.isSorted(NullTerminatedString, error_set_type.names.get(ip), {}, NullTerminatedString.indexLessThan));
34033440 const names_map = try ip.addMap(gpa);
3404 try addStringsToMap(ip, gpa, names_map, error_set_type.names);
3405 const names_len = @as(u32, @intCast(error_set_type.names.len));
3441 try addStringsToMap(ip, gpa, names_map, error_set_type.names.get(ip));
3442 const names_len = error_set_type.names.len;
34063443 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.ErrorSet).Struct.fields.len + names_len);
34073444 ip.items.appendAssumeCapacity(.{
34083445 .tag = .type_error_set,
......@@ -3411,7 +3448,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
34113448 .names_map = names_map,
34123449 }),
34133450 });
3414 ip.extra.appendSliceAssumeCapacity(@as([]const u32, @ptrCast(error_set_type.names)));
3451 ip.extra.appendSliceAssumeCapacity(@ptrCast(error_set_type.names.get(ip)));
34153452 },
34163453 .inferred_error_set_type => |ies_index| {
34173454 ip.items.appendAssumeCapacity(.{
......@@ -4207,7 +4244,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
42074244 ip.extra.appendSliceAssumeCapacity(@as([]const u32, @ptrCast(memoized_call.arg_values)));
42084245 },
42094246 }
4210 return @as(Index, @enumFromInt(ip.items.len - 1));
4247 return @enumFromInt(ip.items.len - 1);
42114248}
42124249
42134250/// This is equivalent to `Key.FuncType` but adjusted to have a slice for `param_types`.
......@@ -4216,13 +4253,13 @@ pub const GetFuncTypeKey = struct {
42164253 return_type: Index,
42174254 comptime_bits: u32,
42184255 noalias_bits: u32,
4219 alignment: Alignment,
4220 cc: std.builtin.CallingConvention,
4256 /// `null` means generic.
4257 alignment: ?Alignment,
4258 /// `null` means generic.
4259 cc: ?std.builtin.CallingConvention,
42214260 is_var_args: bool,
42224261 is_generic: bool,
42234262 is_noinline: bool,
4224 align_is_generic: bool,
4225 cc_is_generic: bool,
42264263 section_is_generic: bool,
42274264 addrspace_is_generic: bool,
42284265};
......@@ -4244,40 +4281,42 @@ pub fn getFuncType(ip: *InternPool, gpa: Allocator, key: GetFuncTypeKey) Allocat
42444281 params_len);
42454282 try ip.items.ensureUnusedCapacity(gpa, 1);
42464283
4247 ip.items.appendAssumeCapacity(.{
4248 .tag = .type_function,
4249 .data = ip.addExtraAssumeCapacity(Tag.TypeFunction{
4250 .params_len = params_len,
4251 .return_type = key.return_type,
4252 .flags = .{
4253 .alignment = key.alignment,
4254 .cc = key.cc,
4255 .is_var_args = key.is_var_args,
4256 .has_comptime_bits = key.comptime_bits != 0,
4257 .has_noalias_bits = key.noalias_bits != 0,
4258 .is_generic = key.is_generic,
4259 .is_noinline = key.is_noinline,
4260 .align_is_generic = key.align_is_generic,
4261 .cc_is_generic = key.cc_is_generic,
4262 .section_is_generic = key.section_is_generic,
4263 .addrspace_is_generic = key.addrspace_is_generic,
4264 },
4265 }),
4284 const func_type_extra_index = ip.addExtraAssumeCapacity(Tag.TypeFunction{
4285 .params_len = params_len,
4286 .return_type = key.return_type,
4287 .flags = .{
4288 .alignment = key.alignment orelse .none,
4289 .cc = key.cc orelse .Unspecified,
4290 .is_var_args = key.is_var_args,
4291 .has_comptime_bits = key.comptime_bits != 0,
4292 .has_noalias_bits = key.noalias_bits != 0,
4293 .is_generic = key.is_generic,
4294 .is_noinline = key.is_noinline,
4295 .align_is_generic = key.alignment == null,
4296 .cc_is_generic = key.cc == null,
4297 .section_is_generic = key.section_is_generic,
4298 .addrspace_is_generic = key.addrspace_is_generic,
4299 },
42664300 });
4301
42674302 if (key.comptime_bits != 0) ip.extra.appendAssumeCapacity(key.comptime_bits);
42684303 if (key.noalias_bits != 0) ip.extra.appendAssumeCapacity(key.noalias_bits);
42694304 ip.extra.appendSliceAssumeCapacity(@ptrCast(key.param_types));
42704305
42714306 const adapter: KeyAdapter = .{ .intern_pool = ip };
42724307 const gop = try ip.map.getOrPutAdapted(gpa, Key{
4273 .func_type = indexToKeyFuncType(ip, @intCast(ip.items.len - 1)),
4308 .func_type = extraFuncType(ip, func_type_extra_index),
42744309 }, adapter);
4275 if (!gop.found_existing) return @enumFromInt(ip.items.len - 1);
4310 if (gop.found_existing) {
4311 ip.extra.items.len = prev_extra_len;
4312 return @enumFromInt(gop.index);
4313 }
42764314
4277 // An existing function type was found; undo the additions to our two arrays.
4278 ip.items.len -= 1;
4279 ip.extra.items.len = prev_extra_len;
4280 return @enumFromInt(gop.index);
4315 ip.items.appendAssumeCapacity(.{
4316 .tag = .type_function,
4317 .data = func_type_extra_index,
4318 });
4319 return @enumFromInt(ip.items.len - 1);
42814320}
42824321
42834322pub const GetExternFuncKey = struct {
......@@ -4299,19 +4338,71 @@ pub fn getExternFunc(ip: *InternPool, gpa: Allocator, key: GetExternFuncKey) All
42994338}
43004339
43014340pub const GetFuncDeclKey = struct {
4302 fn_owner_decl: Module.Decl.Index,
4303 param_types: []const Index,
4341 owner_decl: Module.Decl.Index,
4342 ty: Index,
4343 zir_body_inst: Zir.Inst.Index,
4344 lbrace_line: u32,
4345 rbrace_line: u32,
4346 lbrace_column: u32,
4347 rbrace_column: u32,
4348 cc: ?std.builtin.CallingConvention,
4349 is_noinline: bool,
4350};
4351
4352pub fn getFuncDecl(ip: *InternPool, gpa: Allocator, key: GetFuncDeclKey) Allocator.Error!Index {
4353 // The strategy here is to add the function type unconditionally, then to
4354 // ask if it already exists, and if so, revert the lengths of the mutated
4355 // arrays. This is similar to what `getOrPutTrailingString` does.
4356 const prev_extra_len = ip.extra.items.len;
4357
4358 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncDecl).Struct.fields.len);
4359 try ip.items.ensureUnusedCapacity(gpa, 1);
4360
4361 ip.items.appendAssumeCapacity(.{
4362 .tag = .func_decl,
4363 .data = ip.addExtraAssumeCapacity(Tag.FuncDecl{
4364 .analysis = .{
4365 .state = if (key.cc == .Inline) .inline_only else .none,
4366 .is_cold = false,
4367 .is_noinline = key.is_noinline,
4368 .calls_or_awaits_errorable_fn = false,
4369 .stack_alignment = .none,
4370 .inferred_error_set = false,
4371 },
4372 .owner_decl = key.owner_decl,
4373 .ty = key.ty,
4374 .zir_body_inst = key.zir_body_inst,
4375 .lbrace_line = key.lbrace_line,
4376 .rbrace_line = key.rbrace_line,
4377 .lbrace_column = key.lbrace_column,
4378 .rbrace_column = key.rbrace_column,
4379 }),
4380 });
4381
4382 const adapter: KeyAdapter = .{ .intern_pool = ip };
4383 const gop = try ip.map.getOrPutAdapted(gpa, Key{
4384 .func = indexToKeyFuncDecl(ip, @intCast(ip.items.len - 1)),
4385 }, adapter);
4386 if (!gop.found_existing) return @enumFromInt(ip.items.len - 1);
4387
4388 // An existing function type was found; undo the additions to our two arrays.
4389 ip.items.len -= 1;
4390 ip.extra.items.len = prev_extra_len;
4391 return @enumFromInt(gop.index);
4392}
4393
4394pub const GetFuncDeclIesKey = struct {
4395 owner_decl: Module.Decl.Index,
4396 param_types: []Index,
43044397 noalias_bits: u32,
43054398 comptime_bits: u32,
4306 return_type: Index,
4307 inferred_error_set: bool,
4399 bare_return_type: Index,
43084400 /// null means generic.
43094401 cc: ?std.builtin.CallingConvention,
43104402 /// null means generic.
43114403 alignment: ?Alignment,
4312 section: Section,
4313 /// null means generic
4314 address_space: ?std.builtin.AddressSpace,
4404 section_is_generic: bool,
4405 addrspace_is_generic: bool,
43154406 is_var_args: bool,
43164407 is_generic: bool,
43174408 is_noinline: bool,
......@@ -4320,63 +4411,258 @@ pub const GetFuncDeclKey = struct {
43204411 rbrace_line: u32,
43214412 lbrace_column: u32,
43224413 rbrace_column: u32,
4323
4324 pub const Section = union(enum) {
4325 generic,
4326 default,
4327 explicit: InternPool.NullTerminatedString,
4328 };
43294414};
43304415
4331pub fn getFuncDecl(ip: *InternPool, gpa: Allocator, key: GetFuncDeclKey) Allocator.Error!Index {
4332 const fn_owner_decl = ip.declPtr(key.fn_owner_decl);
4333 const decl_index = try ip.createDecl(gpa, .{
4334 .name = undefined,
4335 .src_namespace = fn_owner_decl.src_namespace,
4336 .src_node = fn_owner_decl.src_node,
4337 .src_line = fn_owner_decl.src_line,
4338 .has_tv = true,
4339 .owns_tv = true,
4340 .ty = @panic("TODO"),
4341 .val = @panic("TODO"),
4342 .alignment = .none,
4343 .@"linksection" = fn_owner_decl.@"linksection",
4344 .@"addrspace" = fn_owner_decl.@"addrspace",
4345 .analysis = .complete,
4346 .deletion_flag = false,
4347 .zir_decl_index = fn_owner_decl.zir_decl_index,
4348 .src_scope = fn_owner_decl.src_scope,
4349 .generation = 0,
4350 .is_pub = fn_owner_decl.is_pub,
4351 .is_exported = fn_owner_decl.is_exported,
4352 .has_linksection_or_addrspace = fn_owner_decl.has_linksection_or_addrspace,
4353 .has_align = fn_owner_decl.has_align,
4354 .alive = true,
4355 .kind = .anon,
4416pub fn getFuncDeclIes(ip: *InternPool, gpa: Allocator, key: GetFuncDeclIesKey) Allocator.Error!Index {
4417 // Validate input parameters.
4418 assert(key.bare_return_type != .none);
4419 for (key.param_types) |param_type| assert(param_type != .none);
4420
4421 // The strategy here is to add the function decl unconditionally, then to
4422 // ask if it already exists, and if so, revert the lengths of the mutated
4423 // arrays. This is similar to what `getOrPutTrailingString` does.
4424 const prev_extra_len = ip.extra.items.len;
4425 const params_len: u32 = @intCast(key.param_types.len);
4426
4427 try ip.map.ensureUnusedCapacity(gpa, 4);
4428 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncDecl).Struct.fields.len +
4429 1 + // inferred_error_set
4430 @typeInfo(Tag.ErrorUnionType).Struct.fields.len +
4431 @typeInfo(Tag.TypeFunction).Struct.fields.len +
4432 @intFromBool(key.comptime_bits != 0) +
4433 @intFromBool(key.noalias_bits != 0) +
4434 params_len);
4435 try ip.items.ensureUnusedCapacity(gpa, 4);
4436
4437 ip.items.appendAssumeCapacity(.{
4438 .tag = .func_decl,
4439 .data = ip.addExtraAssumeCapacity(Tag.FuncDecl{
4440 .analysis = .{
4441 .state = if (key.cc == .Inline) .inline_only else .none,
4442 .is_cold = false,
4443 .is_noinline = key.is_noinline,
4444 .calls_or_awaits_errorable_fn = false,
4445 .stack_alignment = .none,
4446 .inferred_error_set = true,
4447 },
4448 .owner_decl = key.owner_decl,
4449 .ty = @enumFromInt(ip.items.len + 1),
4450 .zir_body_inst = key.zir_body_inst,
4451 .lbrace_line = key.lbrace_line,
4452 .rbrace_line = key.rbrace_line,
4453 .lbrace_column = key.lbrace_column,
4454 .rbrace_column = key.rbrace_column,
4455 }),
4456 });
4457 ip.extra.appendAssumeCapacity(@intFromEnum(Index.none));
4458
4459 ip.items.appendAssumeCapacity(.{
4460 .tag = .type_error_union,
4461 .data = ip.addExtraAssumeCapacity(Tag.ErrorUnionType{
4462 .error_set_type = @enumFromInt(ip.items.len + 1),
4463 .payload_type = key.bare_return_type,
4464 }),
43564465 });
4357 // TODO better names for generic function instantiations
4358 const decl_name = try ip.getOrPutStringFmt(gpa, "{}__anon_{d}", .{
4359 fn_owner_decl.name.fmt(ip), @intFromEnum(decl_index),
4466
4467 ip.items.appendAssumeCapacity(.{
4468 .tag = .type_inferred_error_set,
4469 .data = @intCast(ip.items.len - 2),
43604470 });
4361 ip.declPtr(decl_index).name = decl_name;
4362 @panic("TODO");
4471
4472 const func_type_extra_index = ip.addExtraAssumeCapacity(Tag.TypeFunction{
4473 .params_len = params_len,
4474 .return_type = @enumFromInt(ip.items.len - 2),
4475 .flags = .{
4476 .alignment = key.alignment orelse .none,
4477 .cc = key.cc orelse .Unspecified,
4478 .is_var_args = key.is_var_args,
4479 .has_comptime_bits = key.comptime_bits != 0,
4480 .has_noalias_bits = key.noalias_bits != 0,
4481 .is_generic = key.is_generic,
4482 .is_noinline = key.is_noinline,
4483 .align_is_generic = key.alignment == null,
4484 .cc_is_generic = key.cc == null,
4485 .section_is_generic = key.section_is_generic,
4486 .addrspace_is_generic = key.addrspace_is_generic,
4487 },
4488 });
4489 if (key.comptime_bits != 0) ip.extra.appendAssumeCapacity(key.comptime_bits);
4490 if (key.noalias_bits != 0) ip.extra.appendAssumeCapacity(key.noalias_bits);
4491 ip.extra.appendSliceAssumeCapacity(@ptrCast(key.param_types));
4492
4493 ip.items.appendAssumeCapacity(.{
4494 .tag = .type_function,
4495 .data = func_type_extra_index,
4496 });
4497
4498 const adapter: KeyAdapter = .{ .intern_pool = ip };
4499 const gop = ip.map.getOrPutAssumeCapacityAdapted(Key{
4500 .func = indexToKeyFuncDecl(ip, @intCast(ip.items.len - 4)),
4501 }, adapter);
4502 if (!gop.found_existing) {
4503 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{ .error_union_type = .{
4504 .error_set_type = @enumFromInt(ip.items.len - 2),
4505 .payload_type = key.bare_return_type,
4506 } }, adapter).found_existing);
4507 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
4508 .inferred_error_set_type = @enumFromInt(ip.items.len - 4),
4509 }, adapter).found_existing);
4510 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
4511 .func_type = extraFuncType(ip, func_type_extra_index),
4512 }, adapter).found_existing);
4513 return @enumFromInt(ip.items.len - 4);
4514 }
4515
4516 // An existing function type was found; undo the additions to our two arrays.
4517 ip.items.len -= 4;
4518 ip.extra.items.len = prev_extra_len;
4519 return @enumFromInt(gop.index);
4520}
4521
4522pub fn getErrorSetType(
4523 ip: *InternPool,
4524 gpa: Allocator,
4525 names: []const NullTerminatedString,
4526) Allocator.Error!Index {
4527 assert(std.sort.isSorted(NullTerminatedString, names, {}, NullTerminatedString.indexLessThan));
4528
4529 // The strategy here is to add the type unconditionally, then to ask if it
4530 // already exists, and if so, revert the lengths of the mutated arrays.
4531 // This is similar to what `getOrPutTrailingString` does.
4532 const prev_extra_len = ip.extra.items.len;
4533
4534 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.ErrorSet).Struct.fields.len + names.len);
4535 try ip.items.ensureUnusedCapacity(gpa, 1);
4536
4537 ip.items.appendAssumeCapacity(.{
4538 .tag = .type_error_set,
4539 .data = ip.addExtraAssumeCapacity(Tag.ErrorSet{
4540 .names_len = @intCast(names.len),
4541 .names_map = @enumFromInt(ip.maps.items.len),
4542 }),
4543 });
4544 ip.extra.appendSliceAssumeCapacity(@ptrCast(names));
4545
4546 const adapter: KeyAdapter = .{ .intern_pool = ip };
4547 const key = indexToKeyErrorSetType(ip, @intCast(ip.items.len - 1));
4548 const gop = try ip.map.getOrPutAdapted(gpa, key, adapter);
4549 if (!gop.found_existing) {
4550 _ = ip.addMap(gpa) catch {
4551 ip.items.len -= 1;
4552 ip.extra.items.len = prev_extra_len;
4553 };
4554 return @enumFromInt(ip.items.len - 1);
4555 }
4556
4557 // An existing function type was found; undo the additions to our two arrays.
4558 ip.items.len -= 1;
4559 ip.extra.items.len = prev_extra_len;
4560 return @enumFromInt(gop.index);
43634561}
43644562
43654563pub const GetFuncInstanceKey = struct {
4366 param_types: []const Index,
4564 param_types: []Index,
43674565 noalias_bits: u32,
4368 return_type: Index,
4566 bare_return_type: Index,
43694567 cc: std.builtin.CallingConvention,
43704568 alignment: Alignment,
43714569 is_noinline: bool,
43724570 generic_owner: Index,
4571 inferred_error_set: bool,
43734572};
43744573
4375pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, key: GetFuncInstanceKey) Allocator.Error!Index {
4574pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey) Allocator.Error!Index {
43764575 _ = ip;
43774576 _ = gpa;
4378 _ = key;
4577 _ = arg;
43794578 @panic("TODO");
4579 //const func_ty = try ip.getFuncType(gpa, .{
4580 // .param_types = arg.param_types,
4581 // .bare_return_type = arg.bare_return_type,
4582 // .comptime_bits = arg.comptime_bits,
4583 // .noalias_bits = arg.noalias_bits,
4584 // .alignment = arg.alignment,
4585 // .cc = arg.cc,
4586 // .is_var_args = arg.is_var_args,
4587 // .is_generic = arg.is_generic,
4588 // .is_noinline = arg.is_noinline,
4589 // .section_is_generic = arg.section_is_generic,
4590 // .addrspace_is_generic = arg.addrspace_is_generic,
4591 // .inferred_error_set = arg.inferred_error_set,
4592 //});
4593
4594 //const fn_owner_decl = ip.declPtr(arg.fn_owner_decl);
4595 //const decl_index = try ip.createDecl(gpa, .{
4596 // .name = undefined,
4597 // .src_namespace = fn_owner_decl.src_namespace,
4598 // .src_node = fn_owner_decl.src_node,
4599 // .src_line = fn_owner_decl.src_line,
4600 // .has_tv = true,
4601 // .owns_tv = true,
4602 // .ty = func_ty,
4603 // .val = undefined,
4604 // .alignment = .none,
4605 // .@"linksection" = fn_owner_decl.@"linksection",
4606 // .@"addrspace" = fn_owner_decl.@"addrspace",
4607 // .analysis = .complete,
4608 // .deletion_flag = false,
4609 // .zir_decl_index = fn_owner_decl.zir_decl_index,
4610 // .src_scope = fn_owner_decl.src_scope,
4611 // .generation = arg.generation,
4612 // .is_pub = fn_owner_decl.is_pub,
4613 // .is_exported = fn_owner_decl.is_exported,
4614 // .has_linksection_or_addrspace = fn_owner_decl.has_linksection_or_addrspace,
4615 // .has_align = fn_owner_decl.has_align,
4616 // .alive = true,
4617 // .kind = .anon,
4618 //});
4619 //// TODO: improve this name
4620 //const decl = ip.declPtr(decl_index);
4621 //decl.name = try ip.getOrPutStringFmt(gpa, "{}__anon_{d}", .{
4622 // fn_owner_decl.name.fmt(ip), @intFromEnum(decl_index),
4623 //});
4624
4625 //const gop = try ip.map.getOrPutAdapted(gpa, Key{
4626 // .func = .{
4627 // .ty = func_ty,
4628 // .generic_owner = .none,
4629 // .owner_decl = decl_index,
4630 // // Only the above fields will be read for hashing/equality.
4631 // .analysis_extra_index = undefined,
4632 // .zir_body_inst_extra_index = undefined,
4633 // .branch_quota_extra_index = undefined,
4634 // .resolved_error_set_extra_index = undefined,
4635 // .zir_body_inst = undefined,
4636 // .lbrace_line = undefined,
4637 // .rbrace_line = undefined,
4638 // .lbrace_column = undefined,
4639 // .rbrace_column = undefined,
4640 // .comptime_args = undefined,
4641 // },
4642 //}, KeyAdapter{ .intern_pool = ip });
4643 //if (gop.found_existing) return @enumFromInt(gop.index);
4644 //try ip.items.append(gpa, .{
4645 // .tag = .func_decl,
4646 // .data = try ip.addExtra(gpa, .{
4647 // .analysis = .{
4648 // .state = if (arg.cc == .Inline) .inline_only else .none,
4649 // .is_cold = false,
4650 // .is_noinline = arg.is_noinline,
4651 // .calls_or_awaits_errorable_fn = false,
4652 // .stack_alignment = .none,
4653 // },
4654 // .owner_decl = arg.owner_decl,
4655 // .ty = func_ty,
4656 // .zir_body_inst = arg.zir_body_inst,
4657 // .lbrace_line = arg.lbrace_line,
4658 // .rbrace_line = arg.rbrace_line,
4659 // .lbrace_column = arg.lbrace_column,
4660 // .rbrace_column = arg.rbrace_column,
4661 // }),
4662 //});
4663 //const func_index: InternPool.Index = @enumFromInt(ip.items.len - 1);
4664 //decl.val = func_index.toValue();
4665 //return func_index;
43804666}
43814667
43824668/// Provides API for completing an enum type after calling `getIncompleteEnum`.
......@@ -4576,15 +4862,15 @@ pub fn finishGetEnum(
45764862 .values_map = values_map,
45774863 }),
45784864 });
4579 ip.extra.appendSliceAssumeCapacity(@as([]const u32, @ptrCast(enum_type.names)));
4580 ip.extra.appendSliceAssumeCapacity(@as([]const u32, @ptrCast(enum_type.values)));
4581 return @as(Index, @enumFromInt(ip.items.len - 1));
4865 ip.extra.appendSliceAssumeCapacity(@ptrCast(enum_type.names));
4866 ip.extra.appendSliceAssumeCapacity(@ptrCast(enum_type.values));
4867 return @enumFromInt(ip.items.len - 1);
45824868}
45834869
45844870pub fn getIfExists(ip: *const InternPool, key: Key) ?Index {
45854871 const adapter: KeyAdapter = .{ .intern_pool = ip };
45864872 const index = ip.map.getIndexAdapted(key, adapter) orelse return null;
4587 return @as(Index, @enumFromInt(index));
4873 return @enumFromInt(index);
45884874}
45894875
45904876pub fn getAssumeExists(ip: *const InternPool, key: Key) Index {
......@@ -4622,7 +4908,7 @@ fn addIndexesToMap(
46224908fn addMap(ip: *InternPool, gpa: Allocator) Allocator.Error!MapIndex {
46234909 const ptr = try ip.maps.addOne(gpa);
46244910 ptr.* = .{};
4625 return @as(MapIndex, @enumFromInt(ip.maps.items.len - 1));
4911 return @enumFromInt(ip.maps.items.len - 1);
46264912}
46274913
46284914/// This operation only happens under compile error conditions.
......@@ -4653,23 +4939,28 @@ fn addExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
46534939 const result = @as(u32, @intCast(ip.extra.items.len));
46544940 inline for (@typeInfo(@TypeOf(extra)).Struct.fields) |field| {
46554941 ip.extra.appendAssumeCapacity(switch (field.type) {
4656 u32 => @field(extra, field.name),
4657 Index => @intFromEnum(@field(extra, field.name)),
4658 Module.Decl.Index => @intFromEnum(@field(extra, field.name)),
4659 Module.Namespace.Index => @intFromEnum(@field(extra, field.name)),
4660 Module.Namespace.OptionalIndex => @intFromEnum(@field(extra, field.name)),
4661 MapIndex => @intFromEnum(@field(extra, field.name)),
4662 OptionalMapIndex => @intFromEnum(@field(extra, field.name)),
4663 RuntimeIndex => @intFromEnum(@field(extra, field.name)),
4664 String => @intFromEnum(@field(extra, field.name)),
4665 NullTerminatedString => @intFromEnum(@field(extra, field.name)),
4666 OptionalNullTerminatedString => @intFromEnum(@field(extra, field.name)),
4667 i32 => @as(u32, @bitCast(@field(extra, field.name))),
4668 Tag.TypePointer.Flags => @as(u32, @bitCast(@field(extra, field.name))),
4669 Tag.TypeFunction.Flags => @as(u32, @bitCast(@field(extra, field.name))),
4670 Tag.TypePointer.PackedOffset => @as(u32, @bitCast(@field(extra, field.name))),
4671 Tag.TypePointer.VectorIndex => @intFromEnum(@field(extra, field.name)),
4672 Tag.Variable.Flags => @as(u32, @bitCast(@field(extra, field.name))),
4942 Index,
4943 Module.Decl.Index,
4944 Module.Namespace.Index,
4945 Module.Namespace.OptionalIndex,
4946 MapIndex,
4947 OptionalMapIndex,
4948 RuntimeIndex,
4949 String,
4950 NullTerminatedString,
4951 OptionalNullTerminatedString,
4952 Tag.TypePointer.VectorIndex,
4953 => @intFromEnum(@field(extra, field.name)),
4954
4955 u32,
4956 i32,
4957 FuncAnalysis,
4958 Tag.TypePointer.Flags,
4959 Tag.TypeFunction.Flags,
4960 Tag.TypePointer.PackedOffset,
4961 Tag.Variable.Flags,
4962 => @bitCast(@field(extra, field.name)),
4963
46734964 else => @compileError("bad field type: " ++ @typeName(field.type)),
46744965 });
46754966 }
......@@ -4720,8 +5011,6 @@ fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct
47205011 inline for (fields, 0..) |field, i| {
47215012 const int32 = ip.extra.items[i + index];
47225013 @field(result, field.name) = switch (field.type) {
4723 u32 => int32,
4724
47255014 Index,
47265015 Module.Decl.Index,
47275016 Module.Namespace.Index,
......@@ -4735,6 +5024,7 @@ fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct
47355024 Tag.TypePointer.VectorIndex,
47365025 => @enumFromInt(int32),
47375026
5027 u32,
47385028 i32,
47395029 Tag.TypePointer.Flags,
47405030 Tag.TypeFunction.Flags,
......@@ -5200,19 +5490,11 @@ pub fn indexToFuncType(ip: *const InternPool, val: Index) ?Key.FuncType {
52005490 const tags = ip.items.items(.tag);
52015491 const datas = ip.items.items(.data);
52025492 switch (tags[@intFromEnum(val)]) {
5203 .type_function => return indexToKeyFuncType(ip, datas[@intFromEnum(val)]),
5493 .type_function => return extraFuncType(ip, datas[@intFromEnum(val)]),
52045494 else => return null,
52055495 }
52065496}
52075497
5208pub fn indexToInferredErrorSetType(ip: *const InternPool, val: Index) Module.InferredErrorSet.OptionalIndex {
5209 assert(val != .none);
5210 const tags = ip.items.items(.tag);
5211 if (tags[@intFromEnum(val)] != .type_inferred_error_set) return .none;
5212 const datas = ip.items.items(.data);
5213 return @as(Module.InferredErrorSet.Index, @enumFromInt(datas[@intFromEnum(val)])).toOptional();
5214}
5215
52165498/// includes .comptime_int_type
52175499pub fn isIntegerType(ip: *const InternPool, ty: Index) bool {
52185500 return switch (ty) {
......@@ -5284,6 +5566,10 @@ pub fn isAggregateType(ip: *const InternPool, ty: Index) bool {
52845566 };
52855567}
52865568
5569pub fn errorUnionSet(ip: *const InternPool, ty: Index) Index {
5570 return ip.indexToKey(ty).error_union_type.error_set_type;
5571}
5572
52875573/// The is only legal because the initializer is not part of the hash.
52885574pub fn mutateVarInit(ip: *InternPool, index: Index, init_index: Index) void {
52895575 const item = ip.items.get(@intFromEnum(index));
......@@ -5354,11 +5640,12 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
53545640 .type_optional => 0,
53555641 .type_anyframe => 0,
53565642 .type_error_union => @sizeOf(Key.ErrorUnionType),
5643 .type_anyerror_union => 0,
53575644 .type_error_set => b: {
53585645 const info = ip.extraData(Tag.ErrorSet, data);
53595646 break :b @sizeOf(Tag.ErrorSet) + (@sizeOf(u32) * info.names_len);
53605647 },
5361 .type_inferred_error_set => @sizeOf(Module.InferredErrorSet),
5648 .type_inferred_error_set => 0,
53625649 .type_enum_explicit, .type_enum_nonexhaustive => @sizeOf(EnumExplicit),
53635650 .type_enum_auto => @sizeOf(EnumAuto),
53645651 .type_opaque => @sizeOf(Key.OpaqueType),
......@@ -5506,6 +5793,7 @@ fn dumpAllFallible(ip: *const InternPool) anyerror!void {
55065793 .type_optional,
55075794 .type_anyframe,
55085795 .type_error_union,
5796 .type_anyerror_union,
55095797 .type_error_set,
55105798 .type_inferred_error_set,
55115799 .type_enum_explicit,
......@@ -5598,14 +5886,6 @@ pub fn unionPtrConst(ip: *const InternPool, index: Module.Union.Index) *const Mo
55985886 return ip.allocated_unions.at(@intFromEnum(index));
55995887}
56005888
5601pub fn inferredErrorSetPtr(ip: *InternPool, index: Module.InferredErrorSet.Index) *Module.InferredErrorSet {
5602 return ip.allocated_inferred_error_sets.at(@intFromEnum(index));
5603}
5604
5605pub fn inferredErrorSetPtrConst(ip: *const InternPool, index: Module.InferredErrorSet.Index) *const Module.InferredErrorSet {
5606 return ip.allocated_inferred_error_sets.at(@intFromEnum(index));
5607}
5608
56095889pub fn declPtr(ip: *InternPool, index: Module.Decl.Index) *Module.Decl {
56105890 return ip.allocated_decls.at(@intFromEnum(index));
56115891}
......@@ -5658,28 +5938,6 @@ pub fn destroyUnion(ip: *InternPool, gpa: Allocator, index: Module.Union.Index)
56585938 };
56595939}
56605940
5661pub fn createInferredErrorSet(
5662 ip: *InternPool,
5663 gpa: Allocator,
5664 initialization: Module.InferredErrorSet,
5665) Allocator.Error!Module.InferredErrorSet.Index {
5666 if (ip.inferred_error_sets_free_list.popOrNull()) |index| {
5667 ip.allocated_inferred_error_sets.at(@intFromEnum(index)).* = initialization;
5668 return index;
5669 }
5670 const ptr = try ip.allocated_inferred_error_sets.addOne(gpa);
5671 ptr.* = initialization;
5672 return @as(Module.InferredErrorSet.Index, @enumFromInt(ip.allocated_inferred_error_sets.len - 1));
5673}
5674
5675pub fn destroyInferredErrorSet(ip: *InternPool, gpa: Allocator, index: Module.InferredErrorSet.Index) void {
5676 ip.inferredErrorSetPtr(index).* = undefined;
5677 ip.inferred_error_sets_free_list.append(gpa, index) catch {
5678 // In order to keep `destroyInferredErrorSet` a non-fallible function, we ignore memory
5679 // allocation failures here, instead leaking the InferredErrorSet until garbage collection.
5680 };
5681}
5682
56835941pub fn createDecl(
56845942 ip: *InternPool,
56855943 gpa: Allocator,
......@@ -5912,6 +6170,7 @@ pub fn typeOf(ip: *const InternPool, index: Index) Index {
59126170 .type_optional,
59136171 .type_anyframe,
59146172 .type_error_union,
6173 .type_anyerror_union,
59156174 .type_error_set,
59166175 .type_inferred_error_set,
59176176 .type_enum_auto,
......@@ -6236,7 +6495,10 @@ pub fn zigTypeTagOrPoison(ip: *const InternPool, index: Index) error{GenericPois
62366495
62376496 .type_optional => .Optional,
62386497 .type_anyframe => .AnyFrame,
6239 .type_error_union => .ErrorUnion,
6498
6499 .type_error_union,
6500 .type_anyerror_union,
6501 => .ErrorUnion,
62406502
62416503 .type_error_set,
62426504 .type_inferred_error_set,
......@@ -6340,6 +6602,10 @@ pub fn funcAnalysis(ip: *const InternPool, i: Index) *FuncAnalysis {
63406602 return @ptrCast(&ip.extra.items[extra_index]);
63416603}
63426604
6605pub fn funcHasInferredErrorSet(ip: *const InternPool, i: Index) bool {
6606 return funcAnalysis(ip, i).inferred_error_set;
6607}
6608
63436609pub fn funcZirBodyInst(ip: *const InternPool, i: Index) Zir.Inst.Index {
63446610 assert(i != .none);
63456611 const item = ip.items.get(@intFromEnum(i));
......@@ -6356,3 +6622,43 @@ pub fn funcZirBodyInst(ip: *const InternPool, i: Index) Zir.Inst.Index {
63566622 };
63576623 return ip.extra.items[extra_index];
63586624}
6625
6626pub fn iesFuncIndex(ip: *const InternPool, ies_index: InternPool.Index) InternPool.Index {
6627 assert(ies_index != .none);
6628 const tags = ip.items.items(.tag);
6629 assert(tags[@intFromEnum(ies_index)] == .type_inferred_error_set);
6630 const func_index = ip.items.items(.data)[@intFromEnum(ies_index)];
6631 switch (tags[func_index]) {
6632 .func_decl, .func_instance => {},
6633 else => unreachable, // assertion failed
6634 }
6635 return @enumFromInt(func_index);
6636}
6637
6638/// Returns a mutable pointer to the resolved error set type of an inferred
6639/// error set function. The returned pointer is invalidated when anything is
6640/// added to `ip`.
6641pub fn iesResolved(ip: *const InternPool, ies_index: InternPool.Index) *InternPool.Index {
6642 assert(ies_index != .none);
6643 const tags = ip.items.items(.tag);
6644 const datas = ip.items.items(.data);
6645 assert(tags[@intFromEnum(ies_index)] == .type_inferred_error_set);
6646 const func_index = datas[@intFromEnum(ies_index)];
6647 return funcIesResolved(ip, func_index);
6648}
6649
6650/// Returns a mutable pointer to the resolved error set type of an inferred
6651/// error set function. The returned pointer is invalidated when anything is
6652/// added to `ip`.
6653pub fn funcIesResolved(ip: *const InternPool, func_index: InternPool.Index) *InternPool.Index {
6654 const tags = ip.items.items(.tag);
6655 const datas = ip.items.items(.data);
6656 assert(funcHasInferredErrorSet(ip, func_index));
6657 const func_start = datas[@intFromEnum(func_index)];
6658 const extra_index = switch (tags[@intFromEnum(func_index)]) {
6659 .func_decl => func_start + @typeInfo(Tag.FuncDecl).Struct.fields.len,
6660 .func_instance => func_start + @typeInfo(Tag.FuncInstance).Struct.fields.len,
6661 else => unreachable,
6662 };
6663 return @ptrCast(&ip.extra.items[extra_index]);
6664}
src/Module.zig+18-126
......@@ -1297,98 +1297,6 @@ pub const Union = struct {
12971297 }
12981298};
12991299
1300/// Some extern function struct memory is owned by the Decl's TypedValue.Managed
1301/// arena allocator.
1302pub const ExternFn = struct {
1303 /// The Decl that corresponds to the function itself.
1304 owner_decl: Decl.Index,
1305 /// Library name if specified.
1306 /// For example `extern "c" fn write(...) usize` would have 'c' as library name.
1307 /// Allocated with Module's allocator; outlives the ZIR code.
1308 lib_name: ?[*:0]const u8,
1309
1310 pub fn deinit(extern_fn: *ExternFn, gpa: Allocator) void {
1311 if (extern_fn.lib_name) |lib_name| {
1312 gpa.free(mem.sliceTo(lib_name, 0));
1313 }
1314 }
1315};
1316
1317/// This struct is used to keep track of any dependencies related to functions instances
1318/// that return inferred error sets. Note that a function may be associated to
1319/// multiple different error sets, for example an inferred error set which
1320/// this function returns, but also any inferred error sets of called inline
1321/// or comptime functions.
1322pub const InferredErrorSet = struct {
1323 /// The function from which this error set originates.
1324 func: InternPool.Index,
1325
1326 /// All currently known errors that this error set contains. This includes
1327 /// direct additions via `return error.Foo;`, and possibly also errors that
1328 /// are returned from any dependent functions. When the inferred error set is
1329 /// fully resolved, this map contains all the errors that the function might return.
1330 errors: NameMap = .{},
1331
1332 /// Other inferred error sets which this inferred error set should include.
1333 inferred_error_sets: std.AutoArrayHashMapUnmanaged(InferredErrorSet.Index, void) = .{},
1334
1335 /// Whether the function returned anyerror. This is true if either of
1336 /// the dependent functions returns anyerror.
1337 is_anyerror: bool = false,
1338
1339 /// Whether this error set is already fully resolved. If true, resolving
1340 /// can skip resolving any dependents of this inferred error set.
1341 is_resolved: bool = false,
1342
1343 pub const NameMap = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void);
1344
1345 pub const Index = enum(u32) {
1346 _,
1347
1348 pub fn toOptional(i: InferredErrorSet.Index) InferredErrorSet.OptionalIndex {
1349 return @as(InferredErrorSet.OptionalIndex, @enumFromInt(@intFromEnum(i)));
1350 }
1351 };
1352
1353 pub const OptionalIndex = enum(u32) {
1354 none = std.math.maxInt(u32),
1355 _,
1356
1357 pub fn init(oi: ?InferredErrorSet.Index) InferredErrorSet.OptionalIndex {
1358 return @as(InferredErrorSet.OptionalIndex, @enumFromInt(@intFromEnum(oi orelse return .none)));
1359 }
1360
1361 pub fn unwrap(oi: InferredErrorSet.OptionalIndex) ?InferredErrorSet.Index {
1362 if (oi == .none) return null;
1363 return @as(InferredErrorSet.Index, @enumFromInt(@intFromEnum(oi)));
1364 }
1365 };
1366
1367 pub fn addErrorSet(
1368 self: *InferredErrorSet,
1369 err_set_ty: Type,
1370 ip: *InternPool,
1371 gpa: Allocator,
1372 ) !void {
1373 switch (err_set_ty.toIntern()) {
1374 .anyerror_type => {
1375 self.is_anyerror = true;
1376 },
1377 else => switch (ip.indexToKey(err_set_ty.toIntern())) {
1378 .error_set_type => |error_set_type| {
1379 for (error_set_type.names) |name| {
1380 try self.errors.put(gpa, name, {});
1381 }
1382 },
1383 .inferred_error_set_type => |ies_index| {
1384 try self.inferred_error_sets.put(gpa, ies_index, {});
1385 },
1386 else => unreachable,
1387 },
1388 }
1389 }
1390};
1391
13921300pub const DeclAdapter = struct {
13931301 mod: *Module,
13941302
......@@ -3220,10 +3128,6 @@ pub fn structPtr(mod: *Module, index: Struct.Index) *Struct {
32203128 return mod.intern_pool.structPtr(index);
32213129}
32223130
3223pub fn inferredErrorSetPtr(mod: *Module, index: InferredErrorSet.Index) *InferredErrorSet {
3224 return mod.intern_pool.inferredErrorSetPtr(index);
3225}
3226
32273131pub fn namespacePtrUnwrap(mod: *Module, index: Namespace.OptionalIndex) ?*Namespace {
32283132 return mod.namespacePtr(index.unwrap() orelse return null);
32293133}
......@@ -4261,6 +4165,7 @@ pub fn semaFile(mod: *Module, file: *File) SemaError!void {
42614165 .owner_decl_index = new_decl_index,
42624166 .func_index = .none,
42634167 .fn_ret_ty = Type.void,
4168 .fn_ret_ty_ies = null,
42644169 .owner_func_index = .none,
42654170 .comptime_mutable_decls = &comptime_mutable_decls,
42664171 };
......@@ -4342,6 +4247,7 @@ fn semaDecl(mod: *Module, decl_index: Decl.Index) !bool {
43424247 .owner_decl_index = decl_index,
43434248 .func_index = .none,
43444249 .fn_ret_ty = Type.void,
4250 .fn_ret_ty_ies = null,
43454251 .owner_func_index = .none,
43464252 .comptime_mutable_decls = &comptime_mutable_decls,
43474253 };
......@@ -5289,12 +5195,19 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
52895195 .owner_decl_index = decl_index,
52905196 .func_index = func_index,
52915197 .fn_ret_ty = fn_ty_info.return_type.toType(),
5198 .fn_ret_ty_ies = null,
52925199 .owner_func_index = func_index,
52935200 .branch_quota = @max(func.branchQuota(ip).*, Sema.default_branch_quota),
52945201 .comptime_mutable_decls = &comptime_mutable_decls,
52955202 };
52965203 defer sema.deinit();
52975204
5205 if (func.analysis(ip).inferred_error_set) {
5206 const ies = try arena.create(Sema.InferredErrorSet);
5207 ies.* = .{ .func = func_index };
5208 sema.fn_ret_ty_ies = ies;
5209 }
5210
52985211 // reset in case calls to errorable functions are removed.
52995212 func.analysis(ip).calls_or_awaits_errorable_fn = false;
53005213
......@@ -5433,7 +5346,7 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
54335346 try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
54345347 inner_block.instructions.items.len);
54355348 const main_block_index = sema.addExtraAssumeCapacity(Air.Block{
5436 .body_len = @as(u32, @intCast(inner_block.instructions.items.len)),
5349 .body_len = @intCast(inner_block.instructions.items.len),
54375350 });
54385351 sema.air_extra.appendSliceAssumeCapacity(inner_block.instructions.items);
54395352 sema.air_extra.items[@intFromEnum(Air.ExtraIndex.main_block)] = main_block_index;
......@@ -5445,7 +5358,7 @@ pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocato
54455358 // Crucially, this happens *after* we set the function state to success above,
54465359 // so that dependencies on the function body will now be satisfied rather than
54475360 // result in circular dependency errors.
5448 sema.resolveFnTypes(fn_ty) catch |err| switch (err) {
5361 sema.resolveFnTypes(&inner_block, LazySrcLoc.nodeOffset(0), fn_ty) catch |err| switch (err) {
54495362 error.NeededSourceLocation => unreachable,
54505363 error.GenericPoison => unreachable,
54515364 error.ComptimeReturn => unreachable,
......@@ -6595,7 +6508,8 @@ pub fn errorUnionType(mod: *Module, error_set_ty: Type, payload_ty: Type) Alloca
65956508
65966509pub fn singleErrorSetType(mod: *Module, name: InternPool.NullTerminatedString) Allocator.Error!Type {
65976510 const names: *const [1]InternPool.NullTerminatedString = &name;
6598 return (try mod.intern_pool.get(mod.gpa, .{ .error_set_type = .{ .names = names } })).toType();
6511 const new_ty = try mod.intern_pool.getErrorSetType(mod.gpa, names);
6512 return new_ty.toType();
65996513}
66006514
66016515/// Sorts `names` in place.
......@@ -6609,7 +6523,7 @@ pub fn errorSetFromUnsortedNames(
66096523 {},
66106524 InternPool.NullTerminatedString.indexLessThan,
66116525 );
6612 const new_ty = try mod.intern(.{ .error_set_type = .{ .names = names } });
6526 const new_ty = try mod.intern_pool.getErrorSetType(mod.gpa, names);
66136527 return new_ty.toType();
66146528}
66156529
......@@ -6956,16 +6870,6 @@ pub fn typeToFunc(mod: *Module, ty: Type) ?InternPool.Key.FuncType {
69566870 return mod.intern_pool.indexToFuncType(ty.toIntern());
69576871}
69586872
6959pub fn typeToInferredErrorSet(mod: *Module, ty: Type) ?*InferredErrorSet {
6960 const index = typeToInferredErrorSetIndex(mod, ty).unwrap() orelse return null;
6961 return mod.inferredErrorSetPtr(index);
6962}
6963
6964pub fn typeToInferredErrorSetIndex(mod: *Module, ty: Type) InferredErrorSet.OptionalIndex {
6965 if (ty.ip_index == .none) return .none;
6966 return mod.intern_pool.indexToInferredErrorSetType(ty.toIntern());
6967}
6968
69696873pub fn funcOwnerDeclPtr(mod: *Module, func_index: InternPool.Index) *Decl {
69706874 return mod.declPtr(mod.funcOwnerDeclIndex(func_index));
69716875}
......@@ -6974,6 +6878,10 @@ pub fn funcOwnerDeclIndex(mod: *Module, func_index: InternPool.Index) Decl.Index
69746878 return mod.funcInfo(func_index).owner_decl;
69756879}
69766880
6881pub fn iesFuncIndex(mod: *const Module, ies_index: InternPool.Index) InternPool.Index {
6882 return mod.intern_pool.iesFuncIndex(ies_index);
6883}
6884
69776885pub fn funcInfo(mod: *Module, func_index: InternPool.Index) InternPool.Key.Func {
69786886 return mod.intern_pool.indexToKey(func_index).func;
69796887}
......@@ -7040,19 +6948,3 @@ pub fn getParamName(mod: *Module, func_index: InternPool.Index, index: u32) [:0]
70406948 else => unreachable,
70416949 };
70426950}
7043
7044pub fn hasInferredErrorSet(mod: *Module, func: InternPool.Key.Func) bool {
7045 const owner_decl = mod.declPtr(func.owner_decl);
7046 const zir = owner_decl.getFileScope(mod).zir;
7047 const zir_tags = zir.instructions.items(.tag);
7048 switch (zir_tags[func.zir_body_inst]) {
7049 .func => return false,
7050 .func_inferred => return true,
7051 .func_fancy => {
7052 const inst_data = zir.instructions.items(.data)[func.zir_body_inst].pl_node;
7053 const extra = zir.extraData(Zir.Inst.FuncFancy, inst_data.payload_index);
7054 return extra.data.bits.is_inferred_error;
7055 },
7056 else => unreachable,
7057 }
7058}
src/Sema.zig+435-324
......@@ -38,6 +38,10 @@ error_return_trace_index_on_fn_entry: Air.Inst.Ref = .none,
3838/// generic function which uses a type expression for the return type.
3939/// The type will be `void` in the case that `func` is `null`.
4040fn_ret_ty: Type,
41/// In case of the return type being an error union with an inferred error
42/// set, this is the inferred error set. `null` otherwise. Allocated with
43/// `Sema.arena`.
44fn_ret_ty_ies: ?*InferredErrorSet,
4145branch_quota: u32 = default_branch_quota,
4246branch_count: u32 = 0,
4347/// Populated when returning `error.ComptimeBreak`. Used to communicate the
......@@ -128,6 +132,46 @@ const Alignment = InternPool.Alignment;
128132pub const default_branch_quota = 1000;
129133pub const default_reference_trace_len = 2;
130134
135pub const InferredErrorSet = struct {
136 /// The function body from which this error set originates.
137 func: InternPool.Index,
138
139 /// All currently known errors that this error set contains. This includes
140 /// direct additions via `return error.Foo;`, and possibly also errors that
141 /// are returned from any dependent functions. When the inferred error set is
142 /// fully resolved, this map contains all the errors that the function might return.
143 errors: NameMap = .{},
144
145 /// Other inferred error sets which this inferred error set should include.
146 inferred_error_sets: std.AutoArrayHashMapUnmanaged(InternPool.Index, void) = .{},
147
148 pub const NameMap = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void);
149
150 pub fn addErrorSet(
151 self: *InferredErrorSet,
152 err_set_ty: Type,
153 ip: *InternPool,
154 arena: Allocator,
155 ) !void {
156 switch (err_set_ty.toIntern()) {
157 .anyerror_type => {
158 ip.funcIesResolved(self.func).* = .anyerror_type;
159 },
160 else => switch (ip.indexToKey(err_set_ty.toIntern())) {
161 .error_set_type => |error_set_type| {
162 for (error_set_type.names.get(ip)) |name| {
163 try self.errors.put(arena, name, {});
164 }
165 },
166 .inferred_error_set_type => {
167 try self.inferred_error_sets.put(arena, err_set_ty.toIntern(), {});
168 },
169 else => unreachable,
170 },
171 }
172 }
173};
174
131175/// Stores the mapping from `Zir.Inst.Index -> Air.Inst.Ref`, which is used by sema to resolve
132176/// instructions during analysis.
133177/// Instead of a hash table approach, InstMap is simply a slice that is indexed into using the
......@@ -1120,7 +1164,7 @@ fn analyzeBodyInner(
11201164 .shl_sat => try sema.zirShl(block, inst, .shl_sat),
11211165
11221166 .ret_ptr => try sema.zirRetPtr(block),
1123 .ret_type => try sema.addType(sema.fn_ret_ty),
1167 .ret_type => Air.internedToRef(sema.fn_ret_ty.toIntern()),
11241168
11251169 // Instructions that we know to *always* be noreturn based solely on their tag.
11261170 // These functions match the return type of analyzeBody so that we can
......@@ -3392,7 +3436,7 @@ fn zirErrorSetDecl(
33923436 const src = inst_data.src();
33933437 const extra = sema.code.extraData(Zir.Inst.ErrorSetDecl, inst_data.payload_index);
33943438
3395 var names: Module.InferredErrorSet.NameMap = .{};
3439 var names: InferredErrorSet.NameMap = .{};
33963440 try names.ensureUnusedCapacity(sema.arena, extra.data.fields_len);
33973441
33983442 var extra_index = @as(u32, @intCast(extra.end));
......@@ -6933,12 +6977,10 @@ fn analyzeCall(
69336977 .return_type = owner_info.return_type,
69346978 .comptime_bits = 0,
69356979 .noalias_bits = owner_info.noalias_bits,
6936 .alignment = owner_info.alignment,
6937 .cc = owner_info.cc,
6980 .alignment = if (owner_info.align_is_generic) null else owner_info.alignment,
6981 .cc = if (owner_info.cc_is_generic) null else owner_info.cc,
69386982 .is_var_args = owner_info.is_var_args,
69396983 .is_noinline = owner_info.is_noinline,
6940 .align_is_generic = owner_info.align_is_generic,
6941 .cc_is_generic = owner_info.cc_is_generic,
69426984 .section_is_generic = owner_info.section_is_generic,
69436985 .addrspace_is_generic = owner_info.addrspace_is_generic,
69446986 .is_generic = owner_info.is_generic,
......@@ -7001,21 +7043,25 @@ fn analyzeCall(
70017043 try sema.resolveInst(fn_info.ret_ty_ref);
70027044 const ret_ty_src: LazySrcLoc = .{ .node_offset_fn_type_ret_ty = 0 };
70037045 const bare_return_type = try sema.analyzeAsType(&child_block, ret_ty_src, ret_ty_inst);
7004 // Create a fresh inferred error set type for inline/comptime calls.
7005 const fn_ret_ty = blk: {
7006 if (mod.hasInferredErrorSet(module_fn)) {
7007 const ies_index = try mod.intern_pool.createInferredErrorSet(gpa, .{
7008 .func = module_fn_index,
7009 });
7010 const error_set_ty = try mod.intern(.{ .inferred_error_set_type = ies_index });
7011 break :blk try mod.errorUnionType(error_set_ty.toType(), bare_return_type);
7012 }
7013 break :blk bare_return_type;
7014 };
7015 new_fn_info.return_type = fn_ret_ty.toIntern();
70167046 const parent_fn_ret_ty = sema.fn_ret_ty;
7017 sema.fn_ret_ty = fn_ret_ty;
7047 const parent_fn_ret_ty_ies = sema.fn_ret_ty_ies;
7048 sema.fn_ret_ty = bare_return_type;
7049 sema.fn_ret_ty_ies = null;
70187050 defer sema.fn_ret_ty = parent_fn_ret_ty;
7051 defer sema.fn_ret_ty_ies = parent_fn_ret_ty_ies;
7052
7053 if (module_fn.analysis(ip).inferred_error_set) {
7054 // Create a fresh inferred error set type for inline/comptime calls.
7055 const error_set_ty = try mod.intern(.{ .inferred_error_set_type = module_fn_index });
7056 const ies = try sema.arena.create(InferredErrorSet);
7057 ies.* = .{ .func = module_fn_index };
7058 sema.fn_ret_ty_ies = ies;
7059 sema.fn_ret_ty = (try ip.get(gpa, .{ .error_union_type = .{
7060 .error_set_type = error_set_ty,
7061 .payload_type = bare_return_type.toIntern(),
7062 } })).toType();
7063 ip.funcIesResolved(module_fn_index).* = .none;
7064 }
70197065
70207066 // This `res2` is here instead of directly breaking from `res` due to a stage1
70217067 // bug generating invalid LLVM IR.
......@@ -7059,7 +7105,7 @@ fn analyzeCall(
70597105 }
70607106
70617107 if (is_comptime_call and ensure_result_used) {
7062 try sema.ensureResultUsed(block, fn_ret_ty, call_src);
7108 try sema.ensureResultUsed(block, sema.fn_ret_ty, call_src);
70637109 }
70647110
70657111 const result = result: {
......@@ -7089,7 +7135,7 @@ fn analyzeCall(
70897135
70907136 if (should_memoize and is_comptime_call) {
70917137 const result_val = try sema.resolveConstMaybeUndefVal(block, .unneeded, result, "");
7092 const result_interned = try result_val.intern(fn_ret_ty, mod);
7138 const result_interned = try result_val.intern(sema.fn_ret_ty, mod);
70937139
70947140 // TODO: check whether any external comptime memory was mutated by the
70957141 // comptime function call. If so, then do not memoize the call here.
......@@ -7114,7 +7160,7 @@ fn analyzeCall(
71147160 if (i < fn_params_len) {
71157161 const opts: CoerceOpts = .{ .param_src = .{
71167162 .func_inst = func,
7117 .param_i = @as(u32, @intCast(i)),
7163 .param_i = @intCast(i),
71187164 } };
71197165 const param_ty = func_ty_info.param_types.get(ip)[i].toType();
71207166 args[i] = sema.analyzeCallArg(
......@@ -7433,6 +7479,7 @@ fn instantiateGenericCall(
74337479 .owner_decl_index = sema.owner_decl_index,
74347480 .func_index = sema.owner_func_index,
74357481 .fn_ret_ty = Type.void,
7482 .fn_ret_ty_ies = null,
74367483 .owner_func_index = .none,
74377484 .comptime_args = comptime_args,
74387485 .generic_owner = generic_owner,
......@@ -7769,6 +7816,7 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
77697816 defer tracy.end();
77707817
77717818 const mod = sema.mod;
7819 const ip = &mod.intern_pool;
77727820 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
77737821 const src = LazySrcLoc.nodeOffset(extra.node);
77747822 const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = extra.node };
......@@ -7779,7 +7827,7 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
77797827 if (val.isUndef(mod)) {
77807828 return sema.addConstUndef(Type.err_int);
77817829 }
7782 const err_name = mod.intern_pool.indexToKey(val.toIntern()).err.name;
7830 const err_name = ip.indexToKey(val.toIntern()).err.name;
77837831 return sema.addConstant(try mod.intValue(
77847832 Type.err_int,
77857833 try mod.getErrorValue(err_name),
......@@ -7787,17 +7835,19 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
77877835 }
77887836
77897837 const op_ty = sema.typeOf(uncasted_operand);
7790 try sema.resolveInferredErrorSetTy(block, src, op_ty);
7791 if (!op_ty.isAnyError(mod)) {
7792 const names = op_ty.errorSetNames(mod);
7793 switch (names.len) {
7794 0 => return sema.addConstant(try mod.intValue(Type.err_int, 0)),
7795 1 => {
7796 const int = @as(Module.ErrorInt, @intCast(mod.global_error_set.getIndex(names[0]).?));
7797 return sema.addIntUnsigned(Type.err_int, int);
7798 },
7799 else => {},
7800 }
7838 switch (try sema.resolveInferredErrorSetTy(block, src, op_ty.toIntern())) {
7839 .anyerror_type => {},
7840 else => |err_set_ty_index| {
7841 const names = ip.indexToKey(err_set_ty_index).error_set_type.names;
7842 switch (names.len) {
7843 0 => return sema.addConstant(try mod.intValue(Type.err_int, 0)),
7844 1 => {
7845 const int: Module.ErrorInt = @intCast(mod.global_error_set.getIndex(names.get(ip)[0]).?);
7846 return sema.addIntUnsigned(Type.err_int, int);
7847 },
7848 else => {},
7849 }
7850 },
78017851 }
78027852
78037853 try sema.requireRuntimeBlock(block, src, operand_src);
......@@ -7846,6 +7896,7 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
78467896 defer tracy.end();
78477897
78487898 const mod = sema.mod;
7899 const ip = &mod.intern_pool;
78497900 const inst_data = sema.code.instructions.items(.data)[inst].pl_node;
78507901 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
78517902 const src: LazySrcLoc = .{ .node_offset_bin_op = inst_data.src_node };
......@@ -7874,23 +7925,25 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
78747925 return Air.Inst.Ref.anyerror_type;
78757926 }
78767927
7877 if (mod.typeToInferredErrorSetIndex(lhs_ty).unwrap()) |ies_index| {
7878 try sema.resolveInferredErrorSet(block, src, ies_index);
7879 // isAnyError might have changed from a false negative to a true positive after resolution.
7880 if (lhs_ty.isAnyError(mod)) {
7881 return Air.Inst.Ref.anyerror_type;
7928 if (ip.isInferredErrorSetType(lhs_ty.toIntern())) {
7929 switch (try sema.resolveInferredErrorSet(block, src, lhs_ty.toIntern())) {
7930 // isAnyError might have changed from a false negative to a true
7931 // positive after resolution.
7932 .anyerror_type => return .anyerror_type,
7933 else => {},
78827934 }
78837935 }
7884 if (mod.typeToInferredErrorSetIndex(rhs_ty).unwrap()) |ies_index| {
7885 try sema.resolveInferredErrorSet(block, src, ies_index);
7886 // isAnyError might have changed from a false negative to a true positive after resolution.
7887 if (rhs_ty.isAnyError(mod)) {
7888 return Air.Inst.Ref.anyerror_type;
7936 if (ip.isInferredErrorSetType(rhs_ty.toIntern())) {
7937 switch (try sema.resolveInferredErrorSet(block, src, rhs_ty.toIntern())) {
7938 // isAnyError might have changed from a false negative to a true
7939 // positive after resolution.
7940 .anyerror_type => return .anyerror_type,
7941 else => {},
78897942 }
78907943 }
78917944
78927945 const err_set_ty = try sema.errorSetMerge(lhs_ty, rhs_ty);
7893 return sema.addType(err_set_ty);
7946 return Air.internedToRef(err_set_ty.toIntern());
78947947}
78957948
78967949fn zirEnumLiteral(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -8569,6 +8622,12 @@ fn checkCallConvSupportsVarArgs(sema: *Sema, block: *Block, src: LazySrcLoc, cc:
85698622 }
85708623}
85718624
8625const Section = union(enum) {
8626 generic,
8627 default,
8628 explicit: InternPool.NullTerminatedString,
8629};
8630
85728631fn funcCommon(
85738632 sema: *Sema,
85748633 block: *Block,
......@@ -8578,7 +8637,7 @@ fn funcCommon(
85788637 alignment: ?Alignment,
85798638 /// null means generic poison
85808639 address_space: ?std.builtin.AddressSpace,
8581 section: InternPool.GetFuncDeclKey.Section,
8640 section: Section,
85828641 /// null means generic poison
85838642 cc: ?std.builtin.CallingConvention,
85848643 /// this might be Type.generic_poison
......@@ -8709,6 +8768,36 @@ fn funcCommon(
87098768 const param_types = block.params.items(.ty);
87108769
87118770 const opt_func_index: InternPool.Index = i: {
8771 if (!is_source_decl) {
8772 assert(has_body);
8773 assert(!is_generic);
8774 assert(comptime_bits == 0);
8775 assert(cc != null);
8776 assert(section != .generic);
8777 assert(address_space != null);
8778 assert(!var_args);
8779 break :i try ip.getFuncInstance(gpa, .{
8780 .param_types = param_types,
8781 .noalias_bits = noalias_bits,
8782 .bare_return_type = bare_return_type.toIntern(),
8783 .cc = cc_resolved,
8784 .alignment = alignment.?,
8785 .is_noinline = is_noinline,
8786 .inferred_error_set = inferred_error_set,
8787 .generic_owner = sema.generic_owner,
8788 });
8789 }
8790
8791 // extern_func and func_decl functions take ownership of `sema.owner_decl`.
8792
8793 sema.owner_decl.@"linksection" = switch (section) {
8794 .generic => .none,
8795 .default => .none,
8796 .explicit => |section_name| section_name.toOptional(),
8797 };
8798 sema.owner_decl.alignment = alignment orelse .none;
8799 sema.owner_decl.@"addrspace" = address_space orelse .generic;
8800
87128801 if (is_extern) {
87138802 assert(comptime_bits == 0);
87148803 assert(cc != null);
......@@ -8734,26 +8823,19 @@ fn funcCommon(
87348823
87358824 if (!has_body) break :i .none;
87368825
8737 if (is_source_decl) {
8738 if (inferred_error_set)
8739 try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
8740
8741 const fn_owner_decl = if (sema.generic_owner != .none)
8742 mod.funcOwnerDeclIndex(sema.generic_owner)
8743 else
8744 sema.owner_decl_index;
8826 if (inferred_error_set) {
8827 try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
8828 break :i try ip.getFuncDeclIes(gpa, .{
8829 .owner_decl = sema.owner_decl_index,
87458830
8746 break :i try ip.getFuncDecl(gpa, .{
8747 .fn_owner_decl = fn_owner_decl,
87488831 .param_types = param_types,
87498832 .noalias_bits = noalias_bits,
87508833 .comptime_bits = comptime_bits,
8751 .return_type = bare_return_type.toIntern(),
8752 .inferred_error_set = inferred_error_set,
8834 .bare_return_type = bare_return_type.toIntern(),
87538835 .cc = cc,
87548836 .alignment = alignment,
8755 .section = section,
8756 .address_space = address_space,
8837 .section_is_generic = section == .generic,
8838 .addrspace_is_generic = address_space == null,
87578839 .is_var_args = var_args,
87588840 .is_generic = final_is_generic,
87598841 .is_noinline = is_noinline,
......@@ -8766,22 +8848,30 @@ fn funcCommon(
87668848 });
87678849 }
87688850
8769 assert(!is_generic);
8770 assert(comptime_bits == 0);
8771 assert(cc != null);
8772 assert(section != .generic);
8773 assert(address_space != null);
8774 assert(!var_args);
8775
8776 break :i try ip.getFuncInstance(gpa, .{
8851 const func_ty = try ip.getFuncType(gpa, .{
87778852 .param_types = param_types,
87788853 .noalias_bits = noalias_bits,
8854 .comptime_bits = comptime_bits,
87798855 .return_type = bare_return_type.toIntern(),
8780 .cc = cc_resolved,
8781 .alignment = alignment.?,
8856 .cc = cc,
8857 .alignment = alignment,
8858 .section_is_generic = section == .generic,
8859 .addrspace_is_generic = address_space == null,
8860 .is_var_args = var_args,
8861 .is_generic = final_is_generic,
87828862 .is_noinline = is_noinline,
8863 });
87838864
8784 .generic_owner = sema.generic_owner,
8865 break :i try ip.getFuncDecl(gpa, .{
8866 .owner_decl = sema.owner_decl_index,
8867 .ty = func_ty,
8868 .cc = cc,
8869 .is_noinline = is_noinline,
8870 .zir_body_inst = func_inst,
8871 .lbrace_line = src_locs.lbrace_line,
8872 .rbrace_line = src_locs.rbrace_line,
8873 .lbrace_column = @as(u16, @truncate(src_locs.columns)),
8874 .rbrace_column = @as(u16, @truncate(src_locs.columns >> 16)),
87858875 });
87868876 };
87878877
......@@ -8913,10 +9003,8 @@ fn funcCommon(
89139003 .noalias_bits = noalias_bits,
89149004 .comptime_bits = comptime_bits,
89159005 .return_type = return_type.toIntern(),
8916 .cc = cc_resolved,
8917 .cc_is_generic = cc == null,
8918 .alignment = alignment orelse .none,
8919 .align_is_generic = alignment == null,
9006 .cc = cc,
9007 .alignment = alignment,
89209008 .section_is_generic = section == .generic,
89219009 .addrspace_is_generic = address_space == null,
89229010 .is_var_args = var_args,
......@@ -10254,7 +10342,7 @@ const SwitchProngAnalysis = struct {
1025410342 return sema.bitCast(block, item_ty, spa.operand, operand_src, null);
1025510343 }
1025610344
10257 var names: Module.InferredErrorSet.NameMap = .{};
10345 var names: InferredErrorSet.NameMap = .{};
1025810346 try names.ensureUnusedCapacity(sema.arena, case_vals.len);
1025910347 for (case_vals) |err| {
1026010348 const err_val = sema.resolveConstValue(block, .unneeded, err, "") catch unreachable;
......@@ -10622,97 +10710,100 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1062210710 }
1062310711 }
1062410712
10625 try sema.resolveInferredErrorSetTy(block, src, operand_ty);
10626
10627 if (operand_ty.isAnyError(mod)) {
10628 if (special_prong != .@"else") {
10629 return sema.fail(
10630 block,
10631 src,
10632 "else prong required when switching on type 'anyerror'",
10633 .{},
10634 );
10635 }
10636 else_error_ty = Type.anyerror;
10637 } else else_validation: {
10638 var maybe_msg: ?*Module.ErrorMsg = null;
10639 errdefer if (maybe_msg) |msg| msg.destroy(sema.gpa);
10713 switch (try sema.resolveInferredErrorSetTy(block, src, operand_ty.toIntern())) {
10714 .anyerror_type => {
10715 if (special_prong != .@"else") {
10716 return sema.fail(
10717 block,
10718 src,
10719 "else prong required when switching on type 'anyerror'",
10720 .{},
10721 );
10722 }
10723 else_error_ty = Type.anyerror;
10724 },
10725 else => |err_set_ty_index| else_validation: {
10726 const error_names = ip.indexToKey(err_set_ty_index).error_set_type.names;
10727 var maybe_msg: ?*Module.ErrorMsg = null;
10728 errdefer if (maybe_msg) |msg| msg.destroy(sema.gpa);
10729
10730 for (error_names.get(ip)) |error_name| {
10731 if (!seen_errors.contains(error_name) and special_prong != .@"else") {
10732 const msg = maybe_msg orelse blk: {
10733 maybe_msg = try sema.errMsg(
10734 block,
10735 src,
10736 "switch must handle all possibilities",
10737 .{},
10738 );
10739 break :blk maybe_msg.?;
10740 };
1064010741
10641 for (operand_ty.errorSetNames(mod)) |error_name| {
10642 if (!seen_errors.contains(error_name) and special_prong != .@"else") {
10643 const msg = maybe_msg orelse blk: {
10644 maybe_msg = try sema.errMsg(
10742 try sema.errNote(
1064510743 block,
1064610744 src,
10647 "switch must handle all possibilities",
10648 .{},
10745 msg,
10746 "unhandled error value: 'error.{}'",
10747 .{error_name.fmt(ip)},
1064910748 );
10650 break :blk maybe_msg.?;
10651 };
10652
10653 try sema.errNote(
10654 block,
10655 src,
10656 msg,
10657 "unhandled error value: 'error.{}'",
10658 .{error_name.fmt(ip)},
10659 );
10749 }
1066010750 }
10661 }
1066210751
10663 if (maybe_msg) |msg| {
10664 maybe_msg = null;
10665 try sema.addDeclaredHereNote(msg, operand_ty);
10666 return sema.failWithOwnedErrorMsg(msg);
10667 }
10752 if (maybe_msg) |msg| {
10753 maybe_msg = null;
10754 try sema.addDeclaredHereNote(msg, operand_ty);
10755 return sema.failWithOwnedErrorMsg(msg);
10756 }
1066810757
10669 if (special_prong == .@"else" and seen_errors.count() == operand_ty.errorSetNames(mod).len) {
10670 // In order to enable common patterns for generic code allow simple else bodies
10671 // else => unreachable,
10672 // else => return,
10673 // else => |e| return e,
10674 // even if all the possible errors were already handled.
10675 const tags = sema.code.instructions.items(.tag);
10676 for (special.body) |else_inst| switch (tags[else_inst]) {
10677 .dbg_block_begin,
10678 .dbg_block_end,
10679 .dbg_stmt,
10680 .dbg_var_val,
10681 .ret_type,
10682 .as_node,
10683 .ret_node,
10684 .@"unreachable",
10685 .@"defer",
10686 .defer_err_code,
10687 .err_union_code,
10688 .ret_err_value_code,
10689 .restore_err_ret_index,
10690 .is_non_err,
10691 .ret_is_non_err,
10692 .condbr,
10693 => {},
10694 else => break,
10695 } else break :else_validation;
10758 if (special_prong == .@"else" and
10759 seen_errors.count() == error_names.len)
10760 {
10761 // In order to enable common patterns for generic code allow simple else bodies
10762 // else => unreachable,
10763 // else => return,
10764 // else => |e| return e,
10765 // even if all the possible errors were already handled.
10766 const tags = sema.code.instructions.items(.tag);
10767 for (special.body) |else_inst| switch (tags[else_inst]) {
10768 .dbg_block_begin,
10769 .dbg_block_end,
10770 .dbg_stmt,
10771 .dbg_var_val,
10772 .ret_type,
10773 .as_node,
10774 .ret_node,
10775 .@"unreachable",
10776 .@"defer",
10777 .defer_err_code,
10778 .err_union_code,
10779 .ret_err_value_code,
10780 .restore_err_ret_index,
10781 .is_non_err,
10782 .ret_is_non_err,
10783 .condbr,
10784 => {},
10785 else => break,
10786 } else break :else_validation;
1069610787
10697 return sema.fail(
10698 block,
10699 special_prong_src,
10700 "unreachable else prong; all cases already handled",
10701 .{},
10702 );
10703 }
10788 return sema.fail(
10789 block,
10790 special_prong_src,
10791 "unreachable else prong; all cases already handled",
10792 .{},
10793 );
10794 }
1070410795
10705 const error_names = operand_ty.errorSetNames(mod);
10706 var names: Module.InferredErrorSet.NameMap = .{};
10707 try names.ensureUnusedCapacity(sema.arena, error_names.len);
10708 for (error_names) |error_name| {
10709 if (seen_errors.contains(error_name)) continue;
10796 var names: InferredErrorSet.NameMap = .{};
10797 try names.ensureUnusedCapacity(sema.arena, error_names.len);
10798 for (error_names.get(ip)) |error_name| {
10799 if (seen_errors.contains(error_name)) continue;
1071010800
10711 names.putAssumeCapacityNoClobber(error_name, {});
10712 }
10713 // No need to keep the hash map metadata correct; here we
10714 // extract the (sorted) keys only.
10715 else_error_ty = try mod.errorSetFromUnsortedNames(names.keys());
10801 names.putAssumeCapacityNoClobber(error_name, {});
10802 }
10803 // No need to keep the hash map metadata correct; here we
10804 // extract the (sorted) keys only.
10805 else_error_ty = try mod.errorSetFromUnsortedNames(names.keys());
10806 },
1071610807 }
1071710808 },
1071810809 .Int, .ComptimeInt => {
......@@ -16444,50 +16535,51 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1644416535
1644516536 try sema.queueFullTypeResolution(error_field_ty);
1644616537
16447 // If the error set is inferred it must be resolved at this point
16448 try sema.resolveInferredErrorSetTy(block, src, ty);
16449
1645016538 // Build our list of Error values
1645116539 // Optional value is only null if anyerror
1645216540 // Value can be zero-length slice otherwise
16453 const error_field_vals = if (ty.isAnyError(mod)) null else blk: {
16454 const vals = try sema.arena.alloc(InternPool.Index, ty.errorSetNames(mod).len);
16455 for (vals, 0..) |*field_val, i| {
16456 // TODO: write something like getCoercedInts to avoid needing to dupe
16457 const name = try sema.arena.dupe(u8, ip.stringToSlice(ty.errorSetNames(mod)[i]));
16458 const name_val = v: {
16459 var anon_decl = try block.startAnonDecl();
16460 defer anon_decl.deinit();
16461 const new_decl_ty = try mod.arrayType(.{
16462 .len = name.len,
16463 .child = .u8_type,
16464 });
16465 const new_decl = try anon_decl.finish(
16466 new_decl_ty,
16467 (try mod.intern(.{ .aggregate = .{
16468 .ty = new_decl_ty.toIntern(),
16469 .storage = .{ .bytes = name },
16470 } })).toValue(),
16471 .none, // default alignment
16472 );
16473 break :v try mod.intern(.{ .ptr = .{
16474 .ty = .slice_const_u8_type,
16475 .addr = .{ .decl = new_decl },
16476 .len = (try mod.intValue(Type.usize, name.len)).toIntern(),
16477 } });
16478 };
16541 const error_field_vals = switch (try sema.resolveInferredErrorSetTy(block, src, ty.toIntern())) {
16542 .anyerror_type => null,
16543 else => |err_set_ty_index| blk: {
16544 const names = ip.indexToKey(err_set_ty_index).error_set_type.names;
16545 const vals = try sema.arena.alloc(InternPool.Index, names.len);
16546 for (vals, 0..) |*field_val, i| {
16547 // TODO: write something like getCoercedInts to avoid needing to dupe
16548 const name = try sema.arena.dupe(u8, ip.stringToSlice(names.get(ip)[i]));
16549 const name_val = v: {
16550 var anon_decl = try block.startAnonDecl();
16551 defer anon_decl.deinit();
16552 const new_decl_ty = try mod.arrayType(.{
16553 .len = name.len,
16554 .child = .u8_type,
16555 });
16556 const new_decl = try anon_decl.finish(
16557 new_decl_ty,
16558 (try mod.intern(.{ .aggregate = .{
16559 .ty = new_decl_ty.toIntern(),
16560 .storage = .{ .bytes = name },
16561 } })).toValue(),
16562 .none, // default alignment
16563 );
16564 break :v try mod.intern(.{ .ptr = .{
16565 .ty = .slice_const_u8_type,
16566 .addr = .{ .decl = new_decl },
16567 .len = (try mod.intValue(Type.usize, name.len)).toIntern(),
16568 } });
16569 };
1647916570
16480 const error_field_fields = .{
16481 // name: []const u8,
16482 name_val,
16483 };
16484 field_val.* = try mod.intern(.{ .aggregate = .{
16485 .ty = error_field_ty.toIntern(),
16486 .storage = .{ .elems = &error_field_fields },
16487 } });
16488 }
16571 const error_field_fields = .{
16572 // name: []const u8,
16573 name_val,
16574 };
16575 field_val.* = try mod.intern(.{ .aggregate = .{
16576 .ty = error_field_ty.toIntern(),
16577 .storage = .{ .elems = &error_field_fields },
16578 } });
16579 }
1648916580
16490 break :blk vals;
16581 break :blk vals;
16582 },
1649116583 };
1649216584
1649316585 // Build our ?[]const Error value
......@@ -18055,7 +18147,9 @@ fn addToInferredErrorSet(sema: *Sema, uncasted_operand: Air.Inst.Ref) !void {
1805518147 const ip = &mod.intern_pool;
1805618148 assert(sema.fn_ret_ty.zigTypeTag(mod) == .ErrorUnion);
1805718149
18058 if (mod.typeToInferredErrorSet(sema.fn_ret_ty.errorUnionSet(mod))) |ies| {
18150 if (ip.isInferredErrorSetType(sema.fn_ret_ty.errorUnionSet(mod).toIntern())) {
18151 const ies = sema.fn_ret_ty_ies.?;
18152 assert(ies.func == sema.func_index);
1805918153 const op_ty = sema.typeOf(uncasted_operand);
1806018154 switch (op_ty.zigTypeTag(mod)) {
1806118155 .ErrorSet => try ies.addErrorSet(op_ty, ip, gpa),
......@@ -19508,7 +19602,7 @@ fn zirReify(
1950819602 return sema.addType(Type.anyerror);
1950919603
1951019604 const len = try sema.usizeCast(block, src, payload_val.sliceLen(mod));
19511 var names: Module.InferredErrorSet.NameMap = .{};
19605 var names: InferredErrorSet.NameMap = .{};
1951219606 try names.ensureUnusedCapacity(sema.arena, len);
1951319607 for (0..len) |i| {
1951419608 const elem_val = try payload_val.elemValue(mod, i);
......@@ -20019,8 +20113,6 @@ fn zirReify(
2001920113 .is_var_args = is_var_args,
2002020114 .is_generic = false,
2002120115 .is_noinline = false,
20022 .align_is_generic = false,
20023 .cc_is_generic = false,
2002420116 .section_is_generic = false,
2002520117 .addrspace_is_generic = false,
2002620118 });
......@@ -20524,8 +20616,8 @@ fn zirErrSetCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstDat
2052420616 break :disjoint true;
2052520617 }
2052620618
20527 try sema.resolveInferredErrorSetTy(block, src, dest_ty);
20528 try sema.resolveInferredErrorSetTy(block, operand_src, operand_ty);
20619 _ = try sema.resolveInferredErrorSetTy(block, src, dest_ty.toIntern());
20620 _ = try sema.resolveInferredErrorSetTy(block, operand_src, operand_ty.toIntern());
2052920621 for (dest_ty.errorSetNames(mod)) |dest_err_name| {
2053020622 if (Type.errorSetHasFieldIp(ip, operand_ty.toIntern(), dest_err_name))
2053120623 break :disjoint false;
......@@ -23505,7 +23597,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2350523597 break :blk mod.toEnum(std.builtin.AddressSpace, addrspace_tv.val);
2350623598 } else target_util.defaultAddressSpace(target, .function);
2350723599
23508 const section: InternPool.GetFuncDeclKey.Section = if (extra.data.bits.has_section_body) blk: {
23600 const section: Section = if (extra.data.bits.has_section_body) blk: {
2350923601 const body_len = sema.code.extra[extra_index];
2351023602 extra_index += 1;
2351123603 const body = sema.code.extra[extra_index..][0..body_len];
......@@ -27750,42 +27842,22 @@ fn coerceInMemoryAllowedErrorSets(
2775027842 return .ok;
2775127843 }
2775227844
27753 if (mod.typeToInferredErrorSetIndex(dest_ty).unwrap()) |dst_ies_index| {
27754 const dst_ies = mod.inferredErrorSetPtr(dst_ies_index);
27755 // We will make an effort to return `ok` without resolving either error set, to
27756 // avoid unnecessary "unable to resolve error set" dependency loop errors.
27757 switch (src_ty.toIntern()) {
27758 .anyerror_type => {},
27759 else => switch (ip.indexToKey(src_ty.toIntern())) {
27760 .inferred_error_set_type => |src_index| {
27761 // If both are inferred error sets of functions, and
27762 // the dest includes the source function, the coercion is OK.
27763 // This check is important because it works without forcing a full resolution
27764 // of inferred error sets.
27765 if (dst_ies.inferred_error_sets.contains(src_index)) {
27766 return .ok;
27767 }
27768 },
27769 .error_set_type => |error_set_type| {
27770 for (error_set_type.names) |name| {
27771 if (!dst_ies.errors.contains(name)) break;
27772 } else return .ok;
27773 },
27774 else => unreachable,
27775 },
27776 }
27777
27778 if (dst_ies.func == sema.owner_func_index) {
27779 // We are trying to coerce an error set to the current function's
27780 // inferred error set.
27781 try dst_ies.addErrorSet(src_ty, ip, gpa);
27782 return .ok;
27845 if (ip.isInferredErrorSetType(dest_ty.toIntern())) {
27846 const dst_ies_func_index = ip.iesFuncIndex(dest_ty.toIntern());
27847 if (sema.fn_ret_ty_ies) |dst_ies| {
27848 if (dst_ies.func == dst_ies_func_index) {
27849 // We are trying to coerce an error set to the current function's
27850 // inferred error set.
27851 try dst_ies.addErrorSet(src_ty, ip, gpa);
27852 return .ok;
27853 }
2778327854 }
2778427855
27785 try sema.resolveInferredErrorSet(block, dest_src, dst_ies_index);
27786 // isAnyError might have changed from a false negative to a true positive after resolution.
27787 if (dest_ty.isAnyError(mod)) {
27788 return .ok;
27856 switch (try sema.resolveInferredErrorSet(block, dest_src, dest_ty.toIntern())) {
27857 // isAnyError might have changed from a false negative to a true
27858 // positive after resolution.
27859 .anyerror_type => return .ok,
27860 else => {},
2778927861 }
2779027862 }
2779127863
......@@ -27800,17 +27872,15 @@ fn coerceInMemoryAllowedErrorSets(
2780027872 },
2780127873
2780227874 else => switch (ip.indexToKey(src_ty.toIntern())) {
27803 .inferred_error_set_type => |src_index| {
27804 const src_data = mod.inferredErrorSetPtr(src_index);
27805
27806 try sema.resolveInferredErrorSet(block, src_src, src_index);
27875 .inferred_error_set_type => {
27876 const resolved_src_ty = try sema.resolveInferredErrorSet(block, src_src, src_ty.toIntern());
2780727877 // src anyerror status might have changed after the resolution.
27808 if (src_ty.isAnyError(mod)) {
27878 if (resolved_src_ty == .anyerror_type) {
2780927879 // dest_ty.isAnyError(mod) == true is already checked for at this point.
2781027880 return .from_anyerror;
2781127881 }
2781227882
27813 for (src_data.errors.keys()) |key| {
27883 for (ip.indexToKey(resolved_src_ty).error_set_type.names.get(ip)) |key| {
2781427884 if (!Type.errorSetHasFieldIp(ip, dest_ty.toIntern(), key)) {
2781527885 try missing_error_buf.append(key);
2781627886 }
......@@ -27825,7 +27895,7 @@ fn coerceInMemoryAllowedErrorSets(
2782527895 return .ok;
2782627896 },
2782727897 .error_set_type => |error_set_type| {
27828 for (error_set_type.names) |name| {
27898 for (error_set_type.names.get(ip)) |name| {
2782927899 if (!Type.errorSetHasFieldIp(ip, dest_ty.toIntern(), name)) {
2783027900 try missing_error_buf.append(name);
2783127901 }
......@@ -30341,73 +30411,72 @@ fn analyzeIsNonErrComptimeOnly(
3034130411 operand: Air.Inst.Ref,
3034230412) CompileError!Air.Inst.Ref {
3034330413 const mod = sema.mod;
30414 const ip = &mod.intern_pool;
3034430415 const operand_ty = sema.typeOf(operand);
3034530416 const ot = operand_ty.zigTypeTag(mod);
30346 if (ot != .ErrorSet and ot != .ErrorUnion) return Air.Inst.Ref.bool_true;
30347 if (ot == .ErrorSet) return Air.Inst.Ref.bool_false;
30417 if (ot != .ErrorSet and ot != .ErrorUnion) return .bool_true;
30418 if (ot == .ErrorSet) return .bool_false;
3034830419 assert(ot == .ErrorUnion);
3034930420
3035030421 const payload_ty = operand_ty.errorUnionPayload(mod);
3035130422 if (payload_ty.zigTypeTag(mod) == .NoReturn) {
30352 return Air.Inst.Ref.bool_false;
30423 return .bool_false;
3035330424 }
3035430425
3035530426 if (Air.refToIndex(operand)) |operand_inst| {
3035630427 switch (sema.air_instructions.items(.tag)[operand_inst]) {
30357 .wrap_errunion_payload => return Air.Inst.Ref.bool_true,
30358 .wrap_errunion_err => return Air.Inst.Ref.bool_false,
30428 .wrap_errunion_payload => return .bool_true,
30429 .wrap_errunion_err => return .bool_false,
3035930430 else => {},
3036030431 }
3036130432 } else if (operand == .undef) {
3036230433 return sema.addConstUndef(Type.bool);
3036330434 } else if (@intFromEnum(operand) < InternPool.static_len) {
3036430435 // None of the ref tags can be errors.
30365 return Air.Inst.Ref.bool_true;
30436 return .bool_true;
3036630437 }
3036730438
3036830439 const maybe_operand_val = try sema.resolveMaybeUndefVal(operand);
3036930440
3037030441 // exception if the error union error set is known to be empty,
3037130442 // we allow the comparison but always make it comptime-known.
30372 const set_ty = operand_ty.errorUnionSet(mod);
30373 switch (set_ty.toIntern()) {
30443 const set_ty = ip.errorUnionSet(operand_ty.toIntern());
30444 switch (set_ty) {
3037430445 .anyerror_type => {},
30375 else => switch (mod.intern_pool.indexToKey(set_ty.toIntern())) {
30446 else => switch (ip.indexToKey(set_ty)) {
3037630447 .error_set_type => |error_set_type| {
30377 if (error_set_type.names.len == 0) return Air.Inst.Ref.bool_true;
30448 if (error_set_type.names.len == 0) return .bool_true;
3037830449 },
30379 .inferred_error_set_type => |ies_index| blk: {
30450 .inferred_error_set_type => |func_index| blk: {
3038030451 // If the error set is empty, we must return a comptime true or false.
3038130452 // However we want to avoid unnecessarily resolving an inferred error set
3038230453 // in case it is already non-empty.
30383 const ies = mod.inferredErrorSetPtr(ies_index);
30384 if (ies.is_anyerror) break :blk;
30385 if (ies.errors.count() != 0) break :blk;
30454 switch (ip.funcIesResolved(func_index).*) {
30455 .anyerror_type => break :blk,
30456 .none => {},
30457 else => |i| if (ip.indexToKey(i).error_set_type.names.len != 0) break :blk,
30458 }
3038630459 if (maybe_operand_val == null) {
30387 // Try to avoid resolving inferred error set if possible.
30388 if (ies.errors.count() != 0) break :blk;
30389 if (ies.is_anyerror) break :blk;
30390 for (ies.inferred_error_sets.keys()) |other_ies_index| {
30391 if (ies_index == other_ies_index) continue;
30392 try sema.resolveInferredErrorSet(block, src, other_ies_index);
30393 const other_ies = mod.inferredErrorSetPtr(other_ies_index);
30394 if (other_ies.is_anyerror) {
30395 ies.is_anyerror = true;
30396 ies.is_resolved = true;
30397 break :blk;
30460 if (sema.fn_ret_ty_ies) |ies| if (ies.func == func_index) {
30461 // Try to avoid resolving inferred error set if possible.
30462 for (ies.inferred_error_sets.keys()) |other_ies_index| {
30463 if (set_ty == other_ies_index) continue;
30464 const other_resolved =
30465 try sema.resolveInferredErrorSet(block, src, other_ies_index);
30466 if (other_resolved == .anyerror_type) {
30467 ip.funcIesResolved(func_index).* = .anyerror_type;
30468 break :blk;
30469 }
30470 if (ip.indexToKey(other_resolved).error_set_type.names.len != 0)
30471 break :blk;
3039830472 }
30399
30400 if (other_ies.errors.count() != 0) break :blk;
30401 }
30402 if (ies.func == sema.owner_func_index) {
30403 // We're checking the inferred errorset of the current function and none of
30404 // its child inferred error sets contained any errors meaning that any value
30405 // so far with this type can't contain errors either.
30406 return Air.Inst.Ref.bool_true;
30407 }
30408 try sema.resolveInferredErrorSet(block, src, ies_index);
30409 if (ies.is_anyerror) break :blk;
30410 if (ies.errors.count() == 0) return Air.Inst.Ref.bool_true;
30473 return .bool_true;
30474 };
30475 const resolved_ty = try sema.resolveInferredErrorSet(block, src, set_ty);
30476 if (resolved_ty == .anyerror_type)
30477 break :blk;
30478 if (ip.indexToKey(resolved_ty).error_set_type.names.len == 0)
30479 return .bool_true;
3041130480 }
3041230481 },
3041330482 else => unreachable,
......@@ -30419,12 +30488,12 @@ fn analyzeIsNonErrComptimeOnly(
3041930488 return sema.addConstUndef(Type.bool);
3042030489 }
3042130490 if (err_union.getErrorName(mod) == .none) {
30422 return Air.Inst.Ref.bool_true;
30491 return .bool_true;
3042330492 } else {
30424 return Air.Inst.Ref.bool_false;
30493 return .bool_false;
3042530494 }
3042630495 }
30427 return Air.Inst.Ref.none;
30496 return .none;
3042830497}
3042930498
3043030499fn analyzeIsNonErr(
......@@ -31365,16 +31434,19 @@ fn wrapErrorUnionSet(
3136531434 if (error_set_type.nameIndex(ip, expected_name) != null) break :ok;
3136631435 return sema.failWithErrorSetCodeMissing(block, inst_src, dest_err_set_ty, inst_ty);
3136731436 },
31368 .inferred_error_set_type => |ies_index| ok: {
31369 const ies = mod.inferredErrorSetPtr(ies_index);
31370 const expected_name = mod.intern_pool.indexToKey(val.toIntern()).err.name;
31371
31437 .inferred_error_set_type => |func_index| ok: {
3137231438 // We carefully do this in an order that avoids unnecessarily
3137331439 // resolving the destination error set type.
31374 if (ies.is_anyerror) break :ok;
31375
31376 if (ies.errors.contains(expected_name)) break :ok;
31377 if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, dest_err_set_ty, inst_ty, inst_src, inst_src)) break :ok;
31440 const expected_name = mod.intern_pool.indexToKey(val.toIntern()).err.name;
31441 switch (ip.funcIesResolved(func_index).*) {
31442 .anyerror_type => break :ok,
31443 .none => if (.ok == try sema.coerceInMemoryAllowedErrorSets(block, dest_err_set_ty, inst_ty, inst_src, inst_src)) {
31444 break :ok;
31445 },
31446 else => |i| if (ip.indexToKey(i).error_set_type.nameIndex(ip, expected_name) != null) {
31447 break :ok;
31448 },
31449 }
3137831450
3137931451 return sema.failWithErrorSetCodeMissing(block, inst_src, dest_err_set_ty, inst_ty);
3138031452 },
......@@ -32862,10 +32934,13 @@ fn typeIsArrayLike(sema: *Sema, ty: Type) ?ArrayLike {
3286232934 };
3286332935}
3286432936
32865pub fn resolveFnTypes(sema: *Sema, fn_ty: Type) CompileError!void {
32937pub fn resolveFnTypes(sema: *Sema, block: *Block, src: LazySrcLoc, fn_ty: Type) CompileError!void {
3286632938 const mod = sema.mod;
3286732939 const ip = &mod.intern_pool;
3286832940 const fn_ty_info = mod.typeToFunc(fn_ty).?;
32941
32942 if (sema.fn_ret_ty_ies) |ies| try sema.resolveInferredErrorSetPtr(block, src, ies);
32943
3286932944 try sema.resolveTypeFully(fn_ty_info.return_type.toType());
3287032945
3287132946 if (mod.comp.bin_file.options.error_return_tracing and fn_ty_info.return_type.toType().isError(mod)) {
......@@ -33173,6 +33248,7 @@ fn semaBackingIntType(mod: *Module, struct_obj: *Module.Struct) CompileError!voi
3317333248 .owner_decl_index = decl_index,
3317433249 .func_index = .none,
3317533250 .fn_ret_ty = Type.void,
33251 .fn_ret_ty_ies = null,
3317633252 .owner_func_index = .none,
3317733253 .comptime_mutable_decls = &comptime_mutable_decls,
3317833254 };
......@@ -33223,6 +33299,7 @@ fn semaBackingIntType(mod: *Module, struct_obj: *Module.Struct) CompileError!voi
3322333299 .owner_decl_index = decl_index,
3322433300 .func_index = .none,
3322533301 .fn_ret_ty = Type.void,
33302 .fn_ret_ty_ies = null,
3322633303 .owner_func_index = .none,
3322733304 .comptime_mutable_decls = undefined,
3322833305 };
......@@ -33797,30 +33874,31 @@ fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_obj: *Module.Union) Compi
3379733874 union_obj.status = .have_field_types;
3379833875}
3379933876
33877/// Returns a normal error set corresponding to the fully populated inferred
33878/// error set.
3380033879fn resolveInferredErrorSet(
3380133880 sema: *Sema,
3380233881 block: *Block,
3380333882 src: LazySrcLoc,
33804 ies_index: Module.InferredErrorSet.Index,
33805) CompileError!void {
33883 ies_index: InternPool.Index,
33884) CompileError!InternPool.Index {
3380633885 const mod = sema.mod;
3380733886 const ip = &mod.intern_pool;
33808 const ies = mod.inferredErrorSetPtr(ies_index);
33809
33810 if (ies.is_resolved) return;
33811
33812 const func = mod.funcInfo(ies.func);
33813 if (func.analysis(ip).state == .in_progress) {
33887 const func_index = ip.iesFuncIndex(ies_index);
33888 const func = mod.funcInfo(func_index);
33889 const resolved_ty = func.resolvedErrorSet(ip).*;
33890 if (resolved_ty != .none) return resolved_ty;
33891 if (func.analysis(ip).state == .in_progress)
3381433892 return sema.fail(block, src, "unable to resolve inferred error set", .{});
33815 }
3381633893
33817 // In order to ensure that all dependencies are properly added to the set, we
33818 // need to ensure the function body is analyzed of the inferred error set.
33819 // However, in the case of comptime/inline function calls with inferred error sets,
33820 // each call gets a new InferredErrorSet object, which contains the same
33821 // `InternPool.Index`. Not only is the function not relevant to the inferred error set
33822 // in this case, it may be a generic function which would cause an assertion failure
33823 // if we called `ensureFuncBodyAnalyzed` on it here.
33894 // In order to ensure that all dependencies are properly added to the set,
33895 // we need to ensure the function body is analyzed of the inferred error
33896 // set. However, in the case of comptime/inline function calls with
33897 // inferred error sets, each call gets a new InferredErrorSet object, which
33898 // contains the `InternPool.Index` of the callee. Not only is the function
33899 // not relevant to the inferred error set in this case, it may be a generic
33900 // function which would cause an assertion failure if we called
33901 // `ensureFuncBodyAnalyzed` on it here.
3382433902 const ies_func_owner_decl = mod.declPtr(func.owner_decl);
3382533903 const ies_func_info = mod.typeToFunc(ies_func_owner_decl.ty).?;
3382633904 // if ies declared by a inline function with generic return type, the return_type should be generic_poison,
......@@ -33828,7 +33906,7 @@ fn resolveInferredErrorSet(
3382833906 // so here we can simply skip this case.
3382933907 if (ies_func_info.return_type == .generic_poison_type) {
3383033908 assert(ies_func_info.cc == .Inline);
33831 } else if (mod.typeToInferredErrorSet(ies_func_info.return_type.toType().errorUnionSet(mod)).? == ies) {
33909 } else if (ip.errorUnionSet(ies_func_info.return_type) == ies_index) {
3383233910 if (ies_func_info.is_generic) {
3383333911 const msg = msg: {
3383433912 const msg = try sema.errMsg(block, src, "unable to resolve inferred error set of generic function", .{});
......@@ -33841,33 +33919,62 @@ fn resolveInferredErrorSet(
3384133919 }
3384233920 // In this case we are dealing with the actual InferredErrorSet object that
3384333921 // corresponds to the function, not one created to track an inline/comptime call.
33844 try sema.ensureFuncBodyAnalyzed(ies.func);
33922 try sema.ensureFuncBodyAnalyzed(func_index);
3384533923 }
3384633924
33847 ies.is_resolved = true;
33925 // This will now have been resolved by the logic at the end of `Module.analyzeFnBody`
33926 // which calls `resolveInferredErrorSetPtr`.
33927 const final_resolved_ty = func.resolvedErrorSet(ip).*;
33928 assert(final_resolved_ty != .none);
33929 return final_resolved_ty;
33930}
33931
33932fn resolveInferredErrorSetPtr(
33933 sema: *Sema,
33934 block: *Block,
33935 src: LazySrcLoc,
33936 ies: *InferredErrorSet,
33937) CompileError!void {
33938 const mod = sema.mod;
33939 const ip = &mod.intern_pool;
33940
33941 const func = mod.funcInfo(ies.func);
33942 if (func.resolvedErrorSet(ip).* != .none) return;
33943
33944 const ies_index = ip.errorUnionSet(sema.fn_ret_ty.toIntern());
3384833945
3384933946 for (ies.inferred_error_sets.keys()) |other_ies_index| {
3385033947 if (ies_index == other_ies_index) continue;
33851 try sema.resolveInferredErrorSet(block, src, other_ies_index);
33852
33853 const other_ies = mod.inferredErrorSetPtr(other_ies_index);
33854 for (other_ies.errors.keys()) |key| {
33855 try ies.errors.put(sema.gpa, key, {});
33948 switch (try sema.resolveInferredErrorSet(block, src, other_ies_index)) {
33949 .anyerror_type => {
33950 func.resolvedErrorSet(ip).* = .anyerror_type;
33951 return;
33952 },
33953 else => |error_set_ty_index| {
33954 const names = ip.indexToKey(error_set_ty_index).error_set_type.names;
33955 for (names.get(ip)) |name| {
33956 try ies.errors.put(sema.arena, name, {});
33957 }
33958 },
3385633959 }
33857 if (other_ies.is_anyerror)
33858 ies.is_anyerror = true;
3385933960 }
33961
33962 const resolved_error_set_ty = try mod.errorSetFromUnsortedNames(ies.errors.keys());
33963 func.resolvedErrorSet(ip).* = resolved_error_set_ty.toIntern();
3386033964}
3386133965
3386233966fn resolveInferredErrorSetTy(
3386333967 sema: *Sema,
3386433968 block: *Block,
3386533969 src: LazySrcLoc,
33866 ty: Type,
33867) CompileError!void {
33970 ty: InternPool.Index,
33971) CompileError!InternPool.Index {
3386833972 const mod = sema.mod;
33869 if (mod.typeToInferredErrorSetIndex(ty).unwrap()) |ies_index| {
33870 try sema.resolveInferredErrorSet(block, src, ies_index);
33973 const ip = &mod.intern_pool;
33974 switch (ip.indexToKey(ty)) {
33975 .error_set_type => return ty,
33976 .inferred_error_set_type => return sema.resolveInferredErrorSet(block, src, ty),
33977 else => unreachable,
3387133978 }
3387233979}
3387333980
......@@ -33937,6 +34044,7 @@ fn semaStructFields(mod: *Module, struct_obj: *Module.Struct) CompileError!void
3393734044 .owner_decl_index = decl_index,
3393834045 .func_index = .none,
3393934046 .fn_ret_ty = Type.void,
34047 .fn_ret_ty_ies = null,
3394034048 .owner_func_index = .none,
3394134049 .comptime_mutable_decls = &comptime_mutable_decls,
3394234050 };
......@@ -34282,6 +34390,7 @@ fn semaUnionFields(mod: *Module, union_obj: *Module.Union) CompileError!void {
3428234390 .owner_decl_index = decl_index,
3428334391 .func_index = .none,
3428434392 .fn_ret_ty = Type.void,
34393 .fn_ret_ty_ies = null,
3428534394 .owner_func_index = .none,
3428634395 .comptime_mutable_decls = &comptime_mutable_decls,
3428734396 };
......@@ -34893,6 +35002,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3489335002 .var_args_param_type,
3489435003 .none,
3489535004 => unreachable,
35005
3489635006 _ => switch (mod.intern_pool.items.items(.tag)[@intFromEnum(ty.toIntern())]) {
3489735007 .type_int_signed, // i0 handled above
3489835008 .type_int_unsigned, // u0 handled above
......@@ -34901,6 +35011,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3490135011 .type_optional, // ?noreturn handled above
3490235012 .type_anyframe,
3490335013 .type_error_union,
35014 .type_anyerror_union,
3490435015 .type_error_set,
3490535016 .type_inferred_error_set,
3490635017 .type_opaque,
......@@ -36354,7 +36465,7 @@ fn errorSetMerge(sema: *Sema, lhs: Type, rhs: Type) !Type {
3635436465 const arena = sema.arena;
3635536466 const lhs_names = lhs.errorSetNames(mod);
3635636467 const rhs_names = rhs.errorSetNames(mod);
36357 var names: Module.InferredErrorSet.NameMap = .{};
36468 var names: InferredErrorSet.NameMap = .{};
3635836469 try names.ensureUnusedCapacity(arena, lhs_names.len);
3635936470
3636036471 for (lhs_names) |name| {
src/codegen/llvm.zig+12-13
......@@ -6061,8 +6061,6 @@ pub const FuncGen = struct {
60616061 .is_var_args = false,
60626062 .is_generic = false,
60636063 .is_noinline = false,
6064 .align_is_generic = false,
6065 .cc_is_generic = false,
60666064 .section_is_generic = false,
60676065 .addrspace_is_generic = false,
60686066 });
......@@ -10657,30 +10655,31 @@ fn llvmField(ty: Type, field_index: usize, mod: *Module) ?LlvmField {
1065710655}
1065810656
1065910657fn firstParamSRet(fn_info: InternPool.Key.FuncType, mod: *Module) bool {
10660 if (!fn_info.return_type.toType().hasRuntimeBitsIgnoreComptime(mod)) return false;
10658 const return_type = fn_info.return_type.toType();
10659 if (!return_type.hasRuntimeBitsIgnoreComptime(mod)) return false;
1066110660
1066210661 const target = mod.getTarget();
1066310662 switch (fn_info.cc) {
10664 .Unspecified, .Inline => return isByRef(fn_info.return_type.toType(), mod),
10663 .Unspecified, .Inline => return isByRef(return_type, mod),
1066510664 .C => switch (target.cpu.arch) {
1066610665 .mips, .mipsel => return false,
1066710666 .x86_64 => switch (target.os.tag) {
10668 .windows => return x86_64_abi.classifyWindows(fn_info.return_type.toType(), mod) == .memory,
10669 else => return firstParamSRetSystemV(fn_info.return_type.toType(), mod),
10667 .windows => return x86_64_abi.classifyWindows(return_type, mod) == .memory,
10668 else => return firstParamSRetSystemV(return_type, mod),
1067010669 },
10671 .wasm32 => return wasm_c_abi.classifyType(fn_info.return_type.toType(), mod)[0] == .indirect,
10672 .aarch64, .aarch64_be => return aarch64_c_abi.classifyType(fn_info.return_type.toType(), mod) == .memory,
10673 .arm, .armeb => switch (arm_c_abi.classifyType(fn_info.return_type.toType(), mod, .ret)) {
10670 .wasm32 => return wasm_c_abi.classifyType(return_type, mod)[0] == .indirect,
10671 .aarch64, .aarch64_be => return aarch64_c_abi.classifyType(return_type, mod) == .memory,
10672 .arm, .armeb => switch (arm_c_abi.classifyType(return_type, mod, .ret)) {
1067410673 .memory, .i64_array => return true,
1067510674 .i32_array => |size| return size != 1,
1067610675 .byval => return false,
1067710676 },
10678 .riscv32, .riscv64 => return riscv_c_abi.classifyType(fn_info.return_type.toType(), mod) == .memory,
10677 .riscv32, .riscv64 => return riscv_c_abi.classifyType(return_type, mod) == .memory,
1067910678 else => return false, // TODO investigate C ABI for other architectures
1068010679 },
10681 .SysV => return firstParamSRetSystemV(fn_info.return_type.toType(), mod),
10682 .Win64 => return x86_64_abi.classifyWindows(fn_info.return_type.toType(), mod) == .memory,
10683 .Stdcall => return !isScalar(mod, fn_info.return_type.toType()),
10680 .SysV => return firstParamSRetSystemV(return_type, mod),
10681 .Win64 => return x86_64_abi.classifyWindows(return_type, mod) == .memory,
10682 .Stdcall => return !isScalar(mod, return_type),
1068410683 else => return false,
1068510684 }
1068610685}
src/link/Dwarf.zig+23-34
......@@ -1043,6 +1043,7 @@ pub fn commitDeclState(
10431043 var dbg_line_buffer = &decl_state.dbg_line;
10441044 var dbg_info_buffer = &decl_state.dbg_info;
10451045 const decl = mod.declPtr(decl_index);
1046 const ip = &mod.intern_pool;
10461047
10471048 const target_endian = self.target.cpu.arch.endian();
10481049
......@@ -1241,20 +1242,9 @@ pub fn commitDeclState(
12411242 while (sym_index < decl_state.abbrev_table.items.len) : (sym_index += 1) {
12421243 const symbol = &decl_state.abbrev_table.items[sym_index];
12431244 const ty = symbol.type;
1244 const deferred: bool = blk: {
1245 if (ty.isAnyError(mod)) break :blk true;
1246 switch (mod.intern_pool.indexToKey(ty.ip_index)) {
1247 .inferred_error_set_type => |ies_index| {
1248 const ies = mod.inferredErrorSetPtr(ies_index);
1249 if (!ies.is_resolved) break :blk true;
1250 },
1251 else => {},
1252 }
1253 break :blk false;
1254 };
1255 if (deferred) continue;
1245 if (ip.isErrorSetType(ty.toIntern())) continue;
12561246
1257 symbol.offset = @as(u32, @intCast(dbg_info_buffer.items.len));
1247 symbol.offset = @intCast(dbg_info_buffer.items.len);
12581248 try decl_state.addDbgInfoType(mod, di_atom_index, ty);
12591249 }
12601250 }
......@@ -1265,18 +1255,7 @@ pub fn commitDeclState(
12651255 if (reloc.target) |target| {
12661256 const symbol = decl_state.abbrev_table.items[target];
12671257 const ty = symbol.type;
1268 const deferred: bool = blk: {
1269 if (ty.isAnyError(mod)) break :blk true;
1270 switch (mod.intern_pool.indexToKey(ty.ip_index)) {
1271 .inferred_error_set_type => |ies_index| {
1272 const ies = mod.inferredErrorSetPtr(ies_index);
1273 if (!ies.is_resolved) break :blk true;
1274 },
1275 else => {},
1276 }
1277 break :blk false;
1278 };
1279 if (deferred) {
1258 if (ip.isErrorSetType(ty.toIntern())) {
12801259 log.debug("resolving %{d} deferred until flush", .{target});
12811260 try self.global_abbrev_relocs.append(gpa, .{
12821261 .target = null,
......@@ -2505,18 +2484,18 @@ pub fn flushModule(self: *Dwarf, module: *Module) !void {
25052484 defer arena_alloc.deinit();
25062485 const arena = arena_alloc.allocator();
25072486
2508 // TODO: don't create a zig type for this, just make the dwarf info
2509 // without touching the zig type system.
2510 const names = try arena.dupe(InternPool.NullTerminatedString, module.global_error_set.keys());
2511 std.mem.sort(InternPool.NullTerminatedString, names, {}, InternPool.NullTerminatedString.indexLessThan);
2512
2513 const error_ty = try module.intern(.{ .error_set_type = .{ .names = names } });
25142487 var dbg_info_buffer = std.ArrayList(u8).init(arena);
2515 try addDbgInfoErrorSet(module, error_ty.toType(), self.target, &dbg_info_buffer);
2488 try addDbgInfoErrorSetNames(
2489 module,
2490 Type.anyerror,
2491 module.global_error_set.keys(),
2492 self.target,
2493 &dbg_info_buffer,
2494 );
25162495
25172496 const di_atom_index = try self.createAtom(.di_atom);
25182497 log.debug("updateDeclDebugInfoAllocation in flushModule", .{});
2519 try self.updateDeclDebugInfoAllocation(di_atom_index, @as(u32, @intCast(dbg_info_buffer.items.len)));
2498 try self.updateDeclDebugInfoAllocation(di_atom_index, @intCast(dbg_info_buffer.items.len));
25202499 log.debug("writeDeclDebugInfo in flushModule", .{});
25212500 try self.writeDeclDebugInfo(di_atom_index, dbg_info_buffer.items);
25222501
......@@ -2633,6 +2612,17 @@ fn addDbgInfoErrorSet(
26332612 ty: Type,
26342613 target: std.Target,
26352614 dbg_info_buffer: *std.ArrayList(u8),
2615) !void {
2616 return addDbgInfoErrorSetNames(mod, ty, ty.errorSetNames(mod), target, dbg_info_buffer);
2617}
2618
2619fn addDbgInfoErrorSetNames(
2620 mod: *Module,
2621 /// Used for printing the type name only.
2622 ty: Type,
2623 error_names: []const InternPool.NullTerminatedString,
2624 target: std.Target,
2625 dbg_info_buffer: *std.ArrayList(u8),
26362626) !void {
26372627 const target_endian = target.cpu.arch.endian();
26382628
......@@ -2655,7 +2645,6 @@ fn addDbgInfoErrorSet(
26552645 // DW.AT.const_value, DW.FORM.data8
26562646 mem.writeInt(u64, dbg_info_buffer.addManyAsArrayAssumeCapacity(8), 0, target_endian);
26572647
2658 const error_names = ty.errorSetNames(mod);
26592648 for (error_names) |error_name_ip| {
26602649 const int = try mod.getErrorValue(error_name_ip);
26612650 const error_name = mod.intern_pool.stringToSlice(error_name_ip);
src/type.zig+33-34
......@@ -251,20 +251,19 @@ pub const Type = struct {
251251 return;
252252 },
253253 .inferred_error_set_type => |index| {
254 const ies = mod.inferredErrorSetPtr(index);
255 const func = ies.func;
256
254 const func = mod.iesFuncIndex(index);
257255 try writer.writeAll("@typeInfo(@typeInfo(@TypeOf(");
258256 const owner_decl = mod.funcOwnerDeclPtr(func);
259257 try owner_decl.renderFullyQualifiedName(mod, writer);
260258 try writer.writeAll(")).Fn.return_type.?).ErrorUnion.error_set");
261259 },
262260 .error_set_type => |error_set_type| {
261 const ip = &mod.intern_pool;
263262 const names = error_set_type.names;
264263 try writer.writeAll("error{");
265 for (names, 0..) |name, i| {
264 for (names.get(ip), 0..) |name, i| {
266265 if (i != 0) try writer.writeByte(',');
267 try writer.print("{}", .{name.fmt(&mod.intern_pool)});
266 try writer.print("{}", .{name.fmt(ip)});
268267 }
269268 try writer.writeAll("}");
270269 },
......@@ -2051,21 +2050,19 @@ pub const Type = struct {
20512050
20522051 /// Asserts that the type is an error union.
20532052 pub fn errorUnionSet(ty: Type, mod: *Module) Type {
2054 return mod.intern_pool.indexToKey(ty.toIntern()).error_union_type.error_set_type.toType();
2053 return mod.intern_pool.errorUnionSet(ty.toIntern()).toType();
20552054 }
20562055
20572056 /// Returns false for unresolved inferred error sets.
20582057 pub fn errorSetIsEmpty(ty: Type, mod: *Module) bool {
2058 const ip = &mod.intern_pool;
20592059 return switch (ty.toIntern()) {
20602060 .anyerror_type => false,
2061 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2061 else => switch (ip.indexToKey(ty.toIntern())) {
20622062 .error_set_type => |error_set_type| error_set_type.names.len == 0,
2063 .inferred_error_set_type => |index| {
2064 const inferred_error_set = mod.inferredErrorSetPtr(index);
2065 // Can't know for sure.
2066 if (!inferred_error_set.is_resolved) return false;
2067 if (inferred_error_set.is_anyerror) return false;
2068 return inferred_error_set.errors.count() == 0;
2063 .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
2064 .none, .anyerror_type => false,
2065 else => |t| ip.indexToKey(t).error_set_type.names.len == 0,
20692066 },
20702067 else => unreachable,
20712068 },
......@@ -2076,10 +2073,11 @@ pub const Type = struct {
20762073 /// Note that the result may be a false negative if the type did not get error set
20772074 /// resolution prior to this call.
20782075 pub fn isAnyError(ty: Type, mod: *Module) bool {
2076 const ip = &mod.intern_pool;
20792077 return switch (ty.toIntern()) {
20802078 .anyerror_type => true,
20812079 else => switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2082 .inferred_error_set_type => |i| mod.inferredErrorSetPtr(i).is_anyerror,
2080 .inferred_error_set_type => |i| ip.funcIesResolved(i).* == .anyerror_type,
20832081 else => false,
20842082 },
20852083 };
......@@ -2103,13 +2101,11 @@ pub const Type = struct {
21032101 return switch (ty) {
21042102 .anyerror_type => true,
21052103 else => switch (ip.indexToKey(ty)) {
2106 .error_set_type => |error_set_type| {
2107 return error_set_type.nameIndex(ip, name) != null;
2108 },
2109 .inferred_error_set_type => |index| {
2110 const ies = ip.inferredErrorSetPtrConst(index);
2111 if (ies.is_anyerror) return true;
2112 return ies.errors.contains(name);
2104 .error_set_type => |error_set_type| error_set_type.nameIndex(ip, name) != null,
2105 .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
2106 .anyerror_type => true,
2107 .none => false,
2108 else => |t| ip.indexToKey(t).error_set_type.nameIndex(ip, name) != null,
21132109 },
21142110 else => unreachable,
21152111 },
......@@ -2129,12 +2125,14 @@ pub const Type = struct {
21292125 const field_name_interned = ip.getString(name).unwrap() orelse return false;
21302126 return error_set_type.nameIndex(ip, field_name_interned) != null;
21312127 },
2132 .inferred_error_set_type => |index| {
2133 const ies = ip.inferredErrorSetPtr(index);
2134 if (ies.is_anyerror) return true;
2135 // If the string is not interned, then the field certainly is not present.
2136 const field_name_interned = ip.getString(name).unwrap() orelse return false;
2137 return ies.errors.contains(field_name_interned);
2128 .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
2129 .anyerror_type => true,
2130 .none => false,
2131 else => |t| {
2132 // If the string is not interned, then the field certainly is not present.
2133 const field_name_interned = ip.getString(name).unwrap() orelse return false;
2134 return ip.indexToKey(t).error_set_type.nameIndex(ip, field_name_interned) != null;
2135 },
21382136 },
21392137 else => unreachable,
21402138 },
......@@ -2943,14 +2941,15 @@ pub const Type = struct {
29432941 }
29442942
29452943 // Asserts that `ty` is an error set and not `anyerror`.
2944 // Asserts that `ty` is resolved if it is an inferred error set.
29462945 pub fn errorSetNames(ty: Type, mod: *Module) []const InternPool.NullTerminatedString {
2947 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
2948 .error_set_type => |x| x.names,
2949 .inferred_error_set_type => |index| {
2950 const inferred_error_set = mod.inferredErrorSetPtr(index);
2951 assert(inferred_error_set.is_resolved);
2952 assert(!inferred_error_set.is_anyerror);
2953 return inferred_error_set.errors.keys();
2946 const ip = &mod.intern_pool;
2947 return switch (ip.indexToKey(ty.toIntern())) {
2948 .error_set_type => |x| x.names.get(ip),
2949 .inferred_error_set_type => |i| switch (ip.funcIesResolved(i).*) {
2950 .none => unreachable, // unresolved inferred error set
2951 .anyerror_type => unreachable,
2952 else => |t| ip.indexToKey(t).error_set_type.names.get(ip),
29542953 },
29552954 else => unreachable,
29562955 };