authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-03-28 19:38:19-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-03-28 19:40:21-07:00
log8f469c11275e60f5f1a8ae08fc7596ba366eda16
tree0d6d8894eeb6f6ce42d7994d92c5df278ba436d9
parent0005b346375f1fbe7bc42c22d658e3218bbd599d

stage2: fix error sets


7 files changed, 217 insertions(+), 236 deletions(-)

src/AstGen.zig+54-46
......@@ -197,7 +197,7 @@ pub fn typeExpr(gz: *GenZir, scope: *Scope, type_node: ast.Node.Index) InnerErro
197197}
198198
199199fn lvalExpr(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!zir.Inst.Ref {
200 const tree = scope.tree();
200 const tree = gz.tree();
201201 const node_tags = tree.nodes.items(.tag);
202202 const main_tokens = tree.nodes.items(.main_token);
203203 switch (node_tags[node]) {
......@@ -392,7 +392,7 @@ fn lvalExpr(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!zir.Ins
392392/// it must otherwise not be used.
393393pub fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!zir.Inst.Ref {
394394 const mod = gz.astgen.mod;
395 const tree = scope.tree();
395 const tree = gz.tree();
396396 const main_tokens = tree.nodes.items(.main_token);
397397 const token_tags = tree.tokens.items(.tag);
398398 const node_datas = tree.nodes.items(.data);
......@@ -925,7 +925,7 @@ pub fn blockExpr(
925925 const tracy = trace(@src());
926926 defer tracy.end();
927927
928 const tree = scope.tree();
928 const tree = gz.tree();
929929 const main_tokens = tree.nodes.items(.main_token);
930930 const token_tags = tree.tokens.items(.tag);
931931
......@@ -996,7 +996,7 @@ fn labeledBlockExpr(
996996 assert(zir_tag == .block);
997997
998998 const mod = gz.astgen.mod;
999 const tree = parent_scope.tree();
999 const tree = gz.tree();
10001000 const main_tokens = tree.nodes.items(.main_token);
10011001 const token_tags = tree.tokens.items(.tag);
10021002
......@@ -1074,7 +1074,7 @@ fn blockExprStmts(
10741074 node: ast.Node.Index,
10751075 statements: []const ast.Node.Index,
10761076) !void {
1077 const tree = parent_scope.tree();
1077 const tree = gz.tree();
10781078 const main_tokens = tree.nodes.items(.main_token);
10791079 const node_tags = tree.nodes.items(.tag);
10801080
......@@ -1235,7 +1235,6 @@ fn blockExprStmts(
12351235 .merge_error_sets,
12361236 .error_union_type,
12371237 .bit_not,
1238 .error_set,
12391238 .error_value,
12401239 .error_to_int,
12411240 .int_to_error,
......@@ -1305,7 +1304,7 @@ fn varDecl(
13051304 return mod.failNode(scope, var_decl.ast.align_node, "TODO implement alignment on locals", .{});
13061305 }
13071306 const astgen = gz.astgen;
1308 const tree = scope.tree();
1307 const tree = gz.tree();
13091308 const token_tags = tree.tokens.items(.tag);
13101309
13111310 const name_token = var_decl.ast.mut_token + 1;
......@@ -1365,7 +1364,7 @@ fn varDecl(
13651364 // Depending on the type of AST the initialization expression is, we may need an lvalue
13661365 // or an rvalue as a result location. If it is an rvalue, we can use the instruction as
13671366 // the variable, no memory location needed.
1368 if (!nodeMayNeedMemoryLocation(scope, var_decl.ast.init_node)) {
1367 if (!nodeMayNeedMemoryLocation(tree, var_decl.ast.init_node)) {
13691368 const result_loc: ResultLoc = if (var_decl.ast.type_node != 0) .{
13701369 .ty = try typeExpr(gz, scope, var_decl.ast.type_node),
13711370 } else .none;
......@@ -1502,7 +1501,7 @@ fn varDecl(
15021501}
15031502
15041503fn assign(gz: *GenZir, scope: *Scope, infix_node: ast.Node.Index) InnerError!void {
1505 const tree = scope.tree();
1504 const tree = gz.tree();
15061505 const node_datas = tree.nodes.items(.data);
15071506 const main_tokens = tree.nodes.items(.main_token);
15081507 const node_tags = tree.nodes.items(.tag);
......@@ -1527,7 +1526,7 @@ fn assignOp(
15271526 infix_node: ast.Node.Index,
15281527 op_inst_tag: zir.Inst.Tag,
15291528) InnerError!void {
1530 const tree = scope.tree();
1529 const tree = gz.tree();
15311530 const node_datas = tree.nodes.items(.data);
15321531
15331532 const lhs_ptr = try lvalExpr(gz, scope, node_datas[infix_node].lhs);
......@@ -1543,7 +1542,7 @@ fn assignOp(
15431542}
15441543
15451544fn boolNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!zir.Inst.Ref {
1546 const tree = scope.tree();
1545 const tree = gz.tree();
15471546 const node_datas = tree.nodes.items(.data);
15481547
15491548 const operand = try expr(gz, scope, .{ .ty = .bool_type }, node_datas[node].lhs);
......@@ -1552,7 +1551,7 @@ fn boolNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) Inne
15521551}
15531552
15541553fn bitNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!zir.Inst.Ref {
1555 const tree = scope.tree();
1554 const tree = gz.tree();
15561555 const node_datas = tree.nodes.items(.data);
15571556
15581557 const operand = try expr(gz, scope, .none, node_datas[node].lhs);
......@@ -1567,7 +1566,7 @@ fn negation(
15671566 node: ast.Node.Index,
15681567 tag: zir.Inst.Tag,
15691568) InnerError!zir.Inst.Ref {
1570 const tree = scope.tree();
1569 const tree = gz.tree();
15711570 const node_datas = tree.nodes.items(.data);
15721571
15731572 const operand = try expr(gz, scope, .none, node_datas[node].lhs);
......@@ -1582,7 +1581,7 @@ fn ptrType(
15821581 node: ast.Node.Index,
15831582 ptr_info: ast.full.PtrType,
15841583) InnerError!zir.Inst.Ref {
1585 const tree = scope.tree();
1584 const tree = gz.tree();
15861585
15871586 const elem_type = try typeExpr(gz, scope, ptr_info.ast.child_type);
15881587
......@@ -1664,7 +1663,7 @@ fn ptrType(
16641663}
16651664
16661665fn arrayType(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !zir.Inst.Ref {
1667 const tree = scope.tree();
1666 const tree = gz.tree();
16681667 const node_datas = tree.nodes.items(.data);
16691668
16701669 // TODO check for [_]T
......@@ -1676,7 +1675,7 @@ fn arrayType(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !z
16761675}
16771676
16781677fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !zir.Inst.Ref {
1679 const tree = scope.tree();
1678 const tree = gz.tree();
16801679 const node_datas = tree.nodes.items(.data);
16811680 const extra = tree.extraData(node_datas[node].rhs, ast.Node.ArrayTypeSentinel);
16821681
......@@ -1704,10 +1703,11 @@ fn errorSetDecl(
17041703 rl: ResultLoc,
17051704 node: ast.Node.Index,
17061705) InnerError!zir.Inst.Ref {
1707 if (true) @panic("TODO update for zir-memory-layout branch");
1706 const mod = gz.astgen.mod;
17081707 const tree = gz.tree();
17091708 const main_tokens = tree.nodes.items(.main_token);
17101709 const token_tags = tree.tokens.items(.tag);
1710 const arena = gz.astgen.arena;
17111711
17121712 // Count how many fields there are.
17131713 const error_token = main_tokens[node];
......@@ -1724,7 +1724,7 @@ fn errorSetDecl(
17241724 } else unreachable; // TODO should not need else unreachable here
17251725 };
17261726
1727 const fields = try scope.arena().alloc([]const u8, count);
1727 const fields = try arena.alloc([]const u8, count);
17281728 {
17291729 var tok_i = error_token + 2;
17301730 var field_i: usize = 0;
......@@ -1740,8 +1740,21 @@ fn errorSetDecl(
17401740 }
17411741 }
17421742 }
1743 const result = try addZIRInst(mod, scope, src, zir.Inst.ErrorSet, .{ .fields = fields }, .{});
1744 return rvalue(gz, scope, rl, result);
1743 const error_set = try arena.create(Module.ErrorSet);
1744 error_set.* = .{
1745 .owner_decl = gz.astgen.decl,
1746 .node_offset = gz.astgen.decl.nodeIndexToRelative(node),
1747 .names_ptr = fields.ptr,
1748 .names_len = @intCast(u32, fields.len),
1749 };
1750 const error_set_ty = try Type.Tag.error_set.create(arena, error_set);
1751 const typed_value = try arena.create(TypedValue);
1752 typed_value.* = .{
1753 .ty = Type.initTag(.type),
1754 .val = try Value.Tag.ty.create(arena, error_set_ty),
1755 };
1756 const result = try gz.addConst(typed_value);
1757 return rvalue(gz, scope, rl, result, node);
17451758}
17461759
17471760fn orelseCatchExpr(
......@@ -2518,13 +2531,12 @@ fn getRangeNode(
25182531}
25192532
25202533fn switchExpr(
2521 gz: *GenZir,
2534 parent_gz: *GenZir,
25222535 scope: *Scope,
25232536 rl: ResultLoc,
25242537 switch_node: ast.Node.Index,
25252538) InnerError!zir.Inst.Ref {
25262539 if (true) @panic("TODO update for zir-memory-layout");
2527 const parent_gz = scope.getGenZir();
25282540 const tree = parent_gz.tree();
25292541 const node_datas = tree.nodes.items(.data);
25302542 const main_tokens = tree.nodes.items(.main_token);
......@@ -2541,7 +2553,7 @@ fn switchExpr(
25412553 var block_scope: GenZir = .{
25422554 .parent = scope,
25432555 .decl = scope.ownerDecl().?,
2544 .arena = scope.arena(),
2556 .arena = parent_gz.astgen.arena,
25452557 .force_comptime = parent_gz.force_comptime,
25462558 .instructions = .{},
25472559 };
......@@ -2727,7 +2739,7 @@ fn switchExpr(
27272739
27282740 cases[case_index] = .{
27292741 .item = item,
2730 .body = .{ .instructions = try scope.arena().dupe(zir.Inst.Ref, case_scope.instructions.items) },
2742 .body = .{ .instructions = try parent_gz.astgen.arena.dupe(zir.Inst.Ref, case_scope.instructions.items) },
27312743 };
27322744 case_index += 1;
27332745 continue;
......@@ -2774,14 +2786,14 @@ fn switchExpr(
27742786 .else_body = undefined, // populated below
27752787 }, .{});
27762788 const cond_block = try addZIRInstBlock(mod, &else_scope.base, case_src, .block, .{
2777 .instructions = try scope.arena().dupe(zir.Inst.Ref, case_scope.instructions.items),
2789 .instructions = try parent_gz.astgen.arena.dupe(zir.Inst.Ref, case_scope.instructions.items),
27782790 });
27792791
27802792 // reset cond_scope for then_body
27812793 case_scope.instructions.items.len = 0;
27822794 try switchCaseExpr(mod, &case_scope.base, block_scope.break_result_loc, block, case, target);
27832795 condbr.positionals.then_body = .{
2784 .instructions = try scope.arena().dupe(zir.Inst.Ref, case_scope.instructions.items),
2796 .instructions = try parent_gz.astgen.arena.dupe(zir.Inst.Ref, case_scope.instructions.items),
27852797 };
27862798
27872799 // reset cond_scope for else_body
......@@ -2790,7 +2802,7 @@ fn switchExpr(
27902802 .block = cond_block,
27912803 }, .{});
27922804 condbr.positionals.else_body = .{
2793 .instructions = try scope.arena().dupe(zir.Inst.Ref, case_scope.instructions.items),
2805 .instructions = try parent_gz.astgen.arena.dupe(zir.Inst.Ref, case_scope.instructions.items),
27942806 };
27952807 }
27962808
......@@ -2816,7 +2828,7 @@ fn switchCaseExpr(
28162828 case: ast.full.SwitchCase,
28172829 target: zir.Inst.Ref,
28182830) !void {
2819 const tree = scope.tree();
2831 const tree = gz.tree();
28202832 const node_datas = tree.nodes.items(.data);
28212833 const main_tokens = tree.nodes.items(.main_token);
28222834 const token_tags = tree.tokens.items(.tag);
......@@ -2849,13 +2861,13 @@ fn switchCaseExpr(
28492861}
28502862
28512863fn ret(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!zir.Inst.Ref {
2852 const tree = scope.tree();
2864 const tree = gz.tree();
28532865 const node_datas = tree.nodes.items(.data);
28542866 const main_tokens = tree.nodes.items(.main_token);
28552867
28562868 const operand_node = node_datas[node].lhs;
28572869 const operand: zir.Inst.Ref = if (operand_node != 0) operand: {
2858 const rl: ResultLoc = if (nodeMayNeedMemoryLocation(scope, operand_node)) .{
2870 const rl: ResultLoc = if (nodeMayNeedMemoryLocation(tree, operand_node)) .{
28592871 .ptr = try gz.addNode(.ret_ptr, node),
28602872 } else .{
28612873 .ty = try gz.addNode(.ret_type, node),
......@@ -2876,7 +2888,7 @@ fn identifier(
28762888 defer tracy.end();
28772889
28782890 const mod = gz.astgen.mod;
2879 const tree = scope.tree();
2891 const tree = gz.tree();
28802892 const main_tokens = tree.nodes.items(.main_token);
28812893
28822894 const ident_token = main_tokens[ident];
......@@ -2961,7 +2973,7 @@ fn stringLiteral(
29612973 rl: ResultLoc,
29622974 node: ast.Node.Index,
29632975) InnerError!zir.Inst.Ref {
2964 const tree = scope.tree();
2976 const tree = gz.tree();
29652977 const main_tokens = tree.nodes.items(.main_token);
29662978 const string_bytes = &gz.astgen.string_bytes;
29672979 const str_index = string_bytes.items.len;
......@@ -3048,7 +3060,7 @@ fn integerLiteral(
30483060 rl: ResultLoc,
30493061 node: ast.Node.Index,
30503062) InnerError!zir.Inst.Ref {
3051 const tree = scope.tree();
3063 const tree = gz.tree();
30523064 const main_tokens = tree.nodes.items(.main_token);
30533065 const int_token = main_tokens[node];
30543066 const prefixed_bytes = tree.tokenSlice(int_token);
......@@ -3070,8 +3082,8 @@ fn floatLiteral(
30703082 rl: ResultLoc,
30713083 node: ast.Node.Index,
30723084) InnerError!zir.Inst.Ref {
3073 const arena = scope.arena();
3074 const tree = scope.tree();
3085 const arena = gz.astgen.arena;
3086 const tree = gz.tree();
30753087 const main_tokens = tree.nodes.items(.main_token);
30763088
30773089 const main_token = main_tokens[node];
......@@ -3088,10 +3100,7 @@ fn floatLiteral(
30883100 .ty = Type.initTag(.comptime_float),
30893101 .val = try Value.Tag.float_128.create(arena, float_number),
30903102 };
3091 const result = try gz.add(.{
3092 .tag = .@"const",
3093 .data = .{ .@"const" = typed_value },
3094 });
3103 const result = try gz.addConst(typed_value);
30953104 return rvalue(gz, scope, rl, result, node);
30963105}
30973106
......@@ -3103,8 +3112,8 @@ fn asmExpr(
31033112 full: ast.full.Asm,
31043113) InnerError!zir.Inst.Ref {
31053114 const mod = gz.astgen.mod;
3106 const arena = scope.arena();
3107 const tree = scope.tree();
3115 const arena = gz.astgen.arena;
3116 const tree = gz.tree();
31083117 const main_tokens = tree.nodes.items(.main_token);
31093118 const node_datas = tree.nodes.items(.data);
31103119
......@@ -3289,7 +3298,7 @@ fn typeOf(
32893298 const result = try gz.addUnTok(.typeof, try expr(gz, scope, .none, params[0]), node);
32903299 return rvalue(gz, scope, rl, result, node);
32913300 }
3292 const arena = scope.arena();
3301 const arena = gz.astgen.arena;
32933302 var items = try arena.alloc(zir.Inst.Ref, params.len);
32943303 for (params) |param, param_i| {
32953304 items[param_i] = try expr(gz, scope, .none, param);
......@@ -3311,7 +3320,7 @@ fn builtinCall(
33113320 params: []const ast.Node.Index,
33123321) InnerError!zir.Inst.Ref {
33133322 const mod = gz.astgen.mod;
3314 const tree = scope.tree();
3323 const tree = gz.tree();
33153324 const main_tokens = tree.nodes.items(.main_token);
33163325
33173326 const builtin_token = main_tokens[node];
......@@ -3608,8 +3617,7 @@ pub const simple_types = std.ComptimeStringMap(zir.Inst.Ref, .{
36083617 .{ "false", .bool_false },
36093618});
36103619
3611fn nodeMayNeedMemoryLocation(scope: *Scope, start_node: ast.Node.Index) bool {
3612 const tree = scope.tree();
3620fn nodeMayNeedMemoryLocation(tree: *const ast.Tree, start_node: ast.Node.Index) bool {
36133621 const node_tags = tree.nodes.items(.tag);
36143622 const node_datas = tree.nodes.items(.data);
36153623 const main_tokens = tree.nodes.items(.main_token);
......@@ -3842,7 +3850,7 @@ fn rvalue(
38423850 },
38433851 .ref => {
38443852 // We need a pointer but we have a value.
3845 const tree = scope.tree();
3853 const tree = gz.tree();
38463854 const src_token = tree.firstToken(src_node);
38473855 return gz.addUnTok(.ref, result, src_token);
38483856 },
src/Module.zig+29-7
......@@ -78,9 +78,11 @@ next_anon_name_index: usize = 0,
7878deletion_set: ArrayListUnmanaged(*Decl) = .{},
7979
8080/// Error tags and their values, tag names are duped with mod.gpa.
81global_error_set: std.StringHashMapUnmanaged(u16) = .{},
81/// Corresponds with `error_name_list`.
82global_error_set: std.StringHashMapUnmanaged(ErrorInt) = .{},
8283
83/// error u16 -> []const u8 for fast lookups for @intToError at comptime
84/// ErrorInt -> []const u8 for fast lookups for @intToError at comptime
85/// Corresponds with `global_error_set`.
8486error_name_list: ArrayListUnmanaged([]const u8) = .{},
8587
8688/// Keys are fully qualified paths
......@@ -108,6 +110,8 @@ emit_h: ?Compilation.EmitLoc,
108110
109111compile_log_text: ArrayListUnmanaged(u8) = .{},
110112
113pub const ErrorInt = u32;
114
111115pub const Export = struct {
112116 options: std.builtin.ExportOptions,
113117 src: LazySrcLoc,
......@@ -341,6 +345,17 @@ pub const EmitH = struct {
341345 fwd_decl: ArrayListUnmanaged(u8) = .{},
342346};
343347
348/// Represents the data that an explicit error set syntax provides.
349pub const ErrorSet = struct {
350 owner_decl: *Decl,
351 /// Offset from Decl node index, points to the error set AST node.
352 node_offset: i32,
353 names_len: u32,
354 /// The string bytes are stored in the owner Decl arena.
355 /// They are in the same order they appear in the AST.
356 names_ptr: [*]const []const u8,
357};
358
344359/// Some Fn struct memory is owned by the Decl's TypedValue.Managed arena allocator.
345360/// Extern functions do not have this data structure; they are represented by
346361/// the `Decl` only, with a `Value` tag of `extern_fn`.
......@@ -1363,6 +1378,13 @@ pub const Scope = struct {
13631378 return new_index;
13641379 }
13651380
1381 pub fn addConst(gz: *GenZir, typed_value: *TypedValue) !zir.Inst.Ref {
1382 return gz.add(.{
1383 .tag = .@"const",
1384 .data = .{ .@"const" = typed_value },
1385 });
1386 }
1387
13661388 pub fn add(gz: *GenZir, inst: zir.Inst) !zir.Inst.Ref {
13671389 return gz.astgen.indexToRef(try gz.addAsIndex(inst));
13681390 }
......@@ -3362,7 +3384,7 @@ fn createNewDecl(
33623384}
33633385
33643386/// Get error value for error tag `name`.
3365pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(u16).Entry {
3387pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged(ErrorInt).Entry {
33663388 const gop = try mod.global_error_set.getOrPut(mod.gpa, name);
33673389 if (gop.found_existing)
33683390 return gop.entry.*;
......@@ -3370,7 +3392,7 @@ pub fn getErrorValue(mod: *Module, name: []const u8) !std.StringHashMapUnmanaged
33703392 errdefer mod.global_error_set.removeAssertDiscard(name);
33713393 try mod.error_name_list.ensureCapacity(mod.gpa, mod.error_name_list.items.len + 1);
33723394 gop.entry.key = try mod.gpa.dupe(u8, name);
3373 gop.entry.value = @intCast(u16, mod.error_name_list.items.len);
3395 gop.entry.value = @intCast(ErrorInt, mod.error_name_list.items.len);
33743396 mod.error_name_list.appendAssumeCapacity(gop.entry.key);
33753397 return gop.entry.*;
33763398}
......@@ -3580,9 +3602,9 @@ pub fn createAnonymousDecl(
35803602 new_decl.analysis = .complete;
35813603 new_decl.generation = mod.generation;
35823604
3583 // TODO: This generates the Decl into the machine code file if it is of a type that is non-zero size.
3584 // We should be able to further improve the compiler to not omit Decls which are only referenced at
3585 // compile-time and not runtime.
3605 // TODO: This generates the Decl into the machine code file if it is of a
3606 // type that is non-zero size. We should be able to further improve the
3607 // compiler to omit Decls which are only referenced at compile-time and not runtime.
35863608 if (typed_value.ty.hasCodeGenBits()) {
35873609 try mod.comp.bin_file.allocateDeclIndexes(new_decl);
35883610 try mod.comp.work_queue.writeItem(.{ .codegen_decl = new_decl });
src/Sema.zig+77-92
......@@ -174,7 +174,6 @@ pub fn analyzeBody(
174174 .err_union_payload_safe_ptr => try sema.zirErrUnionPayloadPtr(block, inst, true),
175175 .err_union_payload_unsafe => try sema.zirErrUnionPayload(block, inst, false),
176176 .err_union_payload_unsafe_ptr => try sema.zirErrUnionPayloadPtr(block, inst, false),
177 .error_set => try sema.zirErrorSet(block, inst),
178177 .error_union_type => try sema.zirErrorUnionType(block, inst),
179178 .error_value => try sema.zirErrorValue(block, inst),
180179 .error_to_int => try sema.zirErrorToInt(block, inst),
......@@ -1409,41 +1408,6 @@ fn zirErrorUnionType(sema: *Sema, block: *Scope.Block, inst: zir.Inst.Index) Inn
14091408 return sema.mod.constType(sema.arena, src, err_union_ty);
14101409}
14111410
1412fn zirErrorSet(sema: *Sema, block: *Scope.Block, inst: zir.Inst.Index) InnerError!*Inst {
1413 const tracy = trace(@src());
1414 defer tracy.end();
1415
1416 if (true) @panic("TODO update for zir-memory-layout branch");
1417
1418 // The owner Decl arena will store the hashmap.
1419 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
1420 errdefer new_decl_arena.deinit();
1421
1422 const payload = try new_decl_arena.allocator.create(Value.Payload.ErrorSet);
1423 payload.* = .{
1424 .base = .{ .tag = .error_set },
1425 .data = .{
1426 .fields = .{},
1427 .decl = undefined, // populated below
1428 },
1429 };
1430 try payload.data.fields.ensureCapacity(&new_decl_arena.allocator, @intCast(u32, inst.positionals.fields.len));
1431
1432 for (inst.positionals.fields) |field_name| {
1433 const entry = try sema.mod.getErrorValue(field_name);
1434 if (payload.data.fields.fetchPutAssumeCapacity(entry.key, {})) |_| {
1435 return sema.mod.fail(&block.base, inst.base.src, "duplicate error: '{s}'", .{field_name});
1436 }
1437 }
1438 // TODO create name in format "error:line:column"
1439 const new_decl = try sema.mod.createAnonymousDecl(&block.base, &new_decl_arena, .{
1440 .ty = Type.initTag(.type),
1441 .val = Value.initPayload(&payload.base),
1442 });
1443 payload.data.decl = new_decl;
1444 return sema.analyzeDeclVal(block, inst.base.src, new_decl);
1445}
1446
14471411fn zirErrorValue(sema: *Sema, block: *Scope.Block, inst: zir.Inst.Index) InnerError!*Inst {
14481412 const tracy = trace(@src());
14491413 defer tracy.end();
......@@ -1537,71 +1501,67 @@ fn zirMergeErrorSets(sema: *Sema, block: *Scope.Block, inst: zir.Inst.Index) Inn
15371501 if (lhs_ty.zigTypeTag() != .ErrorSet)
15381502 return sema.mod.fail(&block.base, lhs_src, "expected error set type, found {}", .{lhs_ty});
15391503
1540 // anything merged with anyerror is anyerror
1541 if (lhs_ty.tag() == .anyerror or rhs_ty.tag() == .anyerror)
1504 // Anything merged with anyerror is anyerror.
1505 if (lhs_ty.tag() == .anyerror or rhs_ty.tag() == .anyerror) {
15421506 return sema.mod.constInst(sema.arena, src, .{
15431507 .ty = Type.initTag(.type),
15441508 .val = Value.initTag(.anyerror_type),
15451509 });
1546 // The declarations arena will store the hashmap.
1547 var new_decl_arena = std.heap.ArenaAllocator.init(sema.gpa);
1548 errdefer new_decl_arena.deinit();
1549
1550 const payload = try new_decl_arena.allocator.create(Value.Payload.ErrorSet);
1551 payload.* = .{
1552 .base = .{ .tag = .error_set },
1553 .data = .{
1554 .fields = .{},
1555 .decl = undefined, // populated below
1556 },
1557 };
1558 try payload.data.fields.ensureCapacity(&new_decl_arena.allocator, @intCast(u32, switch (rhs_ty.tag()) {
1559 .error_set_single => 1,
1560 .error_set => rhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields.size,
1561 else => unreachable,
1562 } + switch (lhs_ty.tag()) {
1563 .error_set_single => 1,
1564 .error_set => lhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields.size,
1565 else => unreachable,
1566 }));
1510 }
1511 // When we support inferred error sets, we'll want to use a data structure that can
1512 // represent a merged set of errors without forcing them to be resolved here. Until then
1513 // we re-use the same data structure that is used for explicit error set declarations.
1514 var set: std.StringHashMapUnmanaged(void) = .{};
1515 defer set.deinit(sema.gpa);
15671516
15681517 switch (lhs_ty.tag()) {
15691518 .error_set_single => {
15701519 const name = lhs_ty.castTag(.error_set_single).?.data;
1571 payload.data.fields.putAssumeCapacity(name, {});
1520 try set.put(sema.gpa, name, {});
15721521 },
15731522 .error_set => {
1574 var multiple = lhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields;
1575 var it = multiple.iterator();
1576 while (it.next()) |entry| {
1577 payload.data.fields.putAssumeCapacity(entry.key, entry.value);
1523 const lhs_set = lhs_ty.castTag(.error_set).?.data;
1524 try set.ensureCapacity(sema.gpa, set.count() + lhs_set.names_len);
1525 for (lhs_set.names_ptr[0..lhs_set.names_len]) |name| {
1526 set.putAssumeCapacityNoClobber(name, {});
15781527 }
15791528 },
15801529 else => unreachable,
15811530 }
1582
15831531 switch (rhs_ty.tag()) {
15841532 .error_set_single => {
15851533 const name = rhs_ty.castTag(.error_set_single).?.data;
1586 payload.data.fields.putAssumeCapacity(name, {});
1534 try set.put(sema.gpa, name, {});
15871535 },
15881536 .error_set => {
1589 var multiple = rhs_ty.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields;
1590 var it = multiple.iterator();
1591 while (it.next()) |entry| {
1592 payload.data.fields.putAssumeCapacity(entry.key, entry.value);
1537 const rhs_set = rhs_ty.castTag(.error_set).?.data;
1538 try set.ensureCapacity(sema.gpa, set.count() + rhs_set.names_len);
1539 for (rhs_set.names_ptr[0..rhs_set.names_len]) |name| {
1540 set.putAssumeCapacity(name, {});
15931541 }
15941542 },
15951543 else => unreachable,
15961544 }
1597 // TODO create name in format "error:line:column"
1598 const new_decl = try sema.mod.createAnonymousDecl(&block.base, &new_decl_arena, .{
1545
1546 const new_names = try sema.arena.alloc([]const u8, set.count());
1547 var it = set.iterator();
1548 var i: usize = 0;
1549 while (it.next()) |entry| : (i += 1) {
1550 new_names[i] = entry.key;
1551 }
1552
1553 const new_error_set = try sema.arena.create(Module.ErrorSet);
1554 new_error_set.* = .{
1555 .owner_decl = sema.owner_decl,
1556 .node_offset = inst_data.src_node,
1557 .names_ptr = new_names.ptr,
1558 .names_len = @intCast(u32, new_names.len),
1559 };
1560 const error_set_ty = try Type.Tag.error_set.create(sema.arena, new_error_set);
1561 return sema.mod.constInst(sema.arena, src, .{
15991562 .ty = Type.initTag(.type),
1600 .val = Value.initPayload(&payload.base),
1563 .val = try Value.Tag.ty.create(sema.arena, error_set_ty),
16011564 });
1602 payload.data.decl = new_decl;
1603
1604 return sema.analyzeDeclVal(block, src, new_decl);
16051565}
16061566
16071567fn zirEnumLiteral(sema: *Sema, block: *Scope.Block, inst: zir.Inst.Index) InnerError!*Inst {
......@@ -3441,20 +3401,25 @@ fn namedFieldPtr(
34413401 const child_type = try val.toType(sema.arena);
34423402 switch (child_type.zigTypeTag()) {
34433403 .ErrorSet => {
3444 var name: []const u8 = undefined;
34453404 // TODO resolve inferred error sets
3446 if (val.castTag(.error_set)) |payload|
3447 name = (payload.data.fields.getEntry(field_name) orelse return sema.mod.fail(&block.base, src, "no error named '{s}' in '{}'", .{ field_name, child_type })).key
3448 else
3449 name = (try sema.mod.getErrorValue(field_name)).key;
3450
3451 const result_type = if (child_type.tag() == .anyerror)
3452 try Type.Tag.error_set_single.create(sema.arena, name)
3453 else
3454 child_type;
3405 const name: []const u8 = if (child_type.castTag(.error_set)) |payload| blk: {
3406 const error_set = payload.data;
3407 // TODO this is O(N). I'm putting off solving this until we solve inferred
3408 // error sets at the same time.
3409 const names = error_set.names_ptr[0..error_set.names_len];
3410 for (names) |name| {
3411 if (mem.eql(u8, field_name, name)) {
3412 break :blk name;
3413 }
3414 }
3415 return sema.mod.fail(&block.base, src, "no error named '{s}' in '{}'", .{
3416 field_name,
3417 child_type,
3418 });
3419 } else (try sema.mod.getErrorValue(field_name)).key;
34553420
34563421 return sema.mod.constInst(sema.arena, src, .{
3457 .ty = try sema.mod.simplePtrType(sema.arena, result_type, false, .One),
3422 .ty = try sema.mod.simplePtrType(sema.arena, child_type, false, .One),
34583423 .val = try Value.Tag.ref_val.create(
34593424 sema.arena,
34603425 try Value.Tag.@"error".create(sema.arena, .{
......@@ -4201,15 +4166,35 @@ fn wrapErrorUnion(sema: *Sema, block: *Scope.Block, dest_type: Type, inst: *Inst
42014166 } else switch (err_union.data.error_set.tag()) {
42024167 .anyerror => val,
42034168 .error_set_single => blk: {
4169 const expected_name = val.castTag(.@"error").?.data.name;
42044170 const n = err_union.data.error_set.castTag(.error_set_single).?.data;
4205 if (!mem.eql(u8, val.castTag(.@"error").?.data.name, n))
4206 return sema.mod.fail(&block.base, inst.src, "expected type '{}', found type '{}'", .{ err_union.data.error_set, inst.ty });
4171 if (!mem.eql(u8, expected_name, n)) {
4172 return sema.mod.fail(
4173 &block.base,
4174 inst.src,
4175 "expected type '{}', found type '{}'",
4176 .{ err_union.data.error_set, inst.ty },
4177 );
4178 }
42074179 break :blk val;
42084180 },
42094181 .error_set => blk: {
4210 const f = err_union.data.error_set.castTag(.error_set).?.data.typed_value.most_recent.typed_value.val.castTag(.error_set).?.data.fields;
4211 if (f.get(val.castTag(.@"error").?.data.name) == null)
4212 return sema.mod.fail(&block.base, inst.src, "expected type '{}', found type '{}'", .{ err_union.data.error_set, inst.ty });
4182 const expected_name = val.castTag(.@"error").?.data.name;
4183 const error_set = err_union.data.error_set.castTag(.error_set).?.data;
4184 const names = error_set.names_ptr[0..error_set.names_len];
4185 // TODO this is O(N). I'm putting off solving this until we solve inferred
4186 // error sets at the same time.
4187 const found = for (names) |name| {
4188 if (mem.eql(u8, expected_name, name)) break true;
4189 } else false;
4190 if (!found) {
4191 return sema.mod.fail(
4192 &block.base,
4193 inst.src,
4194 "expected type '{}', found type '{}'",
4195 .{ err_union.data.error_set, inst.ty },
4196 );
4197 }
42134198 break :blk val;
42144199 },
42154200 else => unreachable,
src/type.zig+11-4
......@@ -606,7 +606,7 @@ pub const Type = extern union {
606606 .payload = try payload.payload.copy(allocator),
607607 });
608608 },
609 .error_set => return self.copyPayloadShallow(allocator, Payload.Decl),
609 .error_set => return self.copyPayloadShallow(allocator, Payload.ErrorSet),
610610 .error_set_single => return self.copyPayloadShallow(allocator, Payload.Name),
611611 .empty_struct => return self.copyPayloadShallow(allocator, Payload.ContainerScope),
612612
......@@ -831,8 +831,8 @@ pub const Type = extern union {
831831 continue;
832832 },
833833 .error_set => {
834 const decl = ty.castTag(.error_set).?.data;
835 return out_stream.writeAll(std.mem.spanZ(decl.name));
834 const error_set = ty.castTag(.error_set).?.data;
835 return out_stream.writeAll(std.mem.spanZ(error_set.owner_decl.name));
836836 },
837837 .error_set_single => {
838838 const name = ty.castTag(.error_set_single).?.data;
......@@ -3464,7 +3464,7 @@ pub const Type = extern union {
34643464 .int_unsigned,
34653465 => Payload.Bits,
34663466
3467 .error_set => Payload.Decl,
3467 .error_set => Payload.ErrorSet,
34683468
34693469 .array => Payload.Array,
34703470 .array_sentinel => Payload.ArraySentinel,
......@@ -3548,6 +3548,13 @@ pub const Type = extern union {
35483548 },
35493549 };
35503550
3551 pub const ErrorSet = struct {
3552 pub const base_tag = Tag.error_set;
3553
3554 base: Payload = Payload{ .tag = base_tag },
3555 data: *Module.ErrorSet,
3556 };
3557
35513558 pub const Pointer = struct {
35523559 pub const base_tag = Tag.pointer;
35533560
src/value.zig+1-46
......@@ -102,7 +102,6 @@ pub const Value = extern union {
102102 float_64,
103103 float_128,
104104 enum_literal,
105 error_set,
106105 @"error",
107106 error_union,
108107 /// This is a special value that tracks a set of types that have been stored
......@@ -196,7 +195,6 @@ pub const Value = extern union {
196195 .float_32 => Payload.Float_32,
197196 .float_64 => Payload.Float_64,
198197 .float_128 => Payload.Float_128,
199 .error_set => Payload.ErrorSet,
200198 .@"error" => Payload.Error,
201199 .inferred_alloc => Payload.InferredAlloc,
202200 };
......@@ -404,7 +402,6 @@ pub const Value = extern union {
404402 return Value{ .ptr_otherwise = &new_payload.base };
405403 },
406404
407 .error_set => return self.copyPayloadShallow(allocator, Payload.ErrorSet),
408405 .inferred_alloc => unreachable,
409406 }
410407 }
......@@ -515,15 +512,6 @@ pub const Value = extern union {
515512 .float_32 => return out_stream.print("{}", .{val.castTag(.float_32).?.data}),
516513 .float_64 => return out_stream.print("{}", .{val.castTag(.float_64).?.data}),
517514 .float_128 => return out_stream.print("{}", .{val.castTag(.float_128).?.data}),
518 .error_set => {
519 const error_set = val.castTag(.error_set).?.data;
520 try out_stream.writeAll("error{");
521 var it = error_set.fields.iterator();
522 while (it.next()) |entry| {
523 try out_stream.print("{},", .{entry.value});
524 }
525 return out_stream.writeAll("}");
526 },
527515 .@"error" => return out_stream.print("error.{s}", .{val.castTag(.@"error").?.data.name}),
528516 // TODO to print this it should be error{ Set, Items }!T(val), but we need the type for that
529517 .error_union => return out_stream.print("error_union_val({})", .{val.castTag(.error_union).?.data}),
......@@ -608,10 +596,6 @@ pub const Value = extern union {
608596 };
609597 return Type.initPayload(&new.base);
610598 },
611 .error_set => {
612 const payload = self.castTag(.error_set).?.data;
613 return Type.Tag.error_set.create(allocator, payload.decl);
614 },
615599
616600 .undef,
617601 .zero,
......@@ -711,7 +695,6 @@ pub const Value = extern union {
711695 .unreachable_value,
712696 .empty_array,
713697 .enum_literal,
714 .error_set,
715698 .error_union,
716699 .@"error",
717700 .empty_struct_value,
......@@ -799,7 +782,6 @@ pub const Value = extern union {
799782 .unreachable_value,
800783 .empty_array,
801784 .enum_literal,
802 .error_set,
803785 .@"error",
804786 .error_union,
805787 .empty_struct_value,
......@@ -887,7 +869,6 @@ pub const Value = extern union {
887869 .unreachable_value,
888870 .empty_array,
889871 .enum_literal,
890 .error_set,
891872 .@"error",
892873 .error_union,
893874 .empty_struct_value,
......@@ -1003,7 +984,6 @@ pub const Value = extern union {
1003984 .unreachable_value,
1004985 .empty_array,
1005986 .enum_literal,
1006 .error_set,
1007987 .@"error",
1008988 .error_union,
1009989 .empty_struct_value,
......@@ -1095,7 +1075,6 @@ pub const Value = extern union {
10951075 .unreachable_value,
10961076 .empty_array,
10971077 .enum_literal,
1098 .error_set,
10991078 .@"error",
11001079 .error_union,
11011080 .empty_struct_value,
......@@ -1256,7 +1235,6 @@ pub const Value = extern union {
12561235 .void_value,
12571236 .unreachable_value,
12581237 .enum_literal,
1259 .error_set,
12601238 .@"error",
12611239 .error_union,
12621240 .empty_struct_value,
......@@ -1335,7 +1313,6 @@ pub const Value = extern union {
13351313 .unreachable_value,
13361314 .empty_array,
13371315 .enum_literal,
1338 .error_set,
13391316 .@"error",
13401317 .error_union,
13411318 .empty_struct_value,
......@@ -1476,15 +1453,10 @@ pub const Value = extern union {
14761453 .enum_literal_type,
14771454 .ty,
14781455 => {
1479 // Directly return Type.hash, toType can only fail for .int_type and .error_set.
1456 // Directly return Type.hash, toType can only fail for .int_type.
14801457 var allocator = std.heap.FixedBufferAllocator.init(&[_]u8{});
14811458 return (self.toType(&allocator.allocator) catch unreachable).hash();
14821459 },
1483 .error_set => {
1484 // Payload.decl should be same for all instances of the type.
1485 const payload = self.castTag(.error_set).?.data;
1486 std.hash.autoHash(&hasher, payload.decl);
1487 },
14881460 .int_type => {
14891461 const payload = self.castTag(.int_type).?.data;
14901462 var int_payload = Type.Payload.Bits{
......@@ -1656,7 +1628,6 @@ pub const Value = extern union {
16561628 .unreachable_value,
16571629 .empty_array,
16581630 .enum_literal,
1659 .error_set,
16601631 .@"error",
16611632 .error_union,
16621633 .empty_struct_value,
......@@ -1744,7 +1715,6 @@ pub const Value = extern union {
17441715 .void_value,
17451716 .unreachable_value,
17461717 .enum_literal,
1747 .error_set,
17481718 .@"error",
17491719 .error_union,
17501720 .empty_struct_value,
......@@ -1849,7 +1819,6 @@ pub const Value = extern union {
18491819 .float_128,
18501820 .void_value,
18511821 .enum_literal,
1852 .error_set,
18531822 .@"error",
18541823 .error_union,
18551824 .empty_struct_value,
......@@ -1933,7 +1902,6 @@ pub const Value = extern union {
19331902 .float_128,
19341903 .void_value,
19351904 .enum_literal,
1936 .error_set,
19371905 .empty_struct_value,
19381906 => null,
19391907
......@@ -2012,7 +1980,6 @@ pub const Value = extern union {
20121980 .single_const_pointer_to_comptime_int_type,
20131981 .const_slice_u8_type,
20141982 .enum_literal_type,
2015 .error_set,
20161983 => true,
20171984
20181985 .zero,
......@@ -2156,18 +2123,6 @@ pub const Value = extern union {
21562123 data: f128,
21572124 };
21582125
2159 /// TODO move to type.zig
2160 pub const ErrorSet = struct {
2161 pub const base_tag = Tag.error_set;
2162
2163 base: Payload = .{ .tag = base_tag },
2164 data: struct {
2165 /// TODO revisit this when we have the concept of the error tag type
2166 fields: std.StringHashMapUnmanaged(void),
2167 decl: *Module.Decl,
2168 },
2169 };
2170
21712126 pub const Error = struct {
21722127 base: Payload = .{ .tag = .@"error" },
21732128 data: struct {
src/zir.zig+13-9
......@@ -314,11 +314,6 @@ pub const Inst = struct {
314314 /// Create a `E!T` type.
315315 /// Uses the `pl_node` field with `Bin` payload.
316316 error_union_type,
317 /// Create an error set. TODO can't we just do this in astgen? reconsider
318 /// memory layout of error sets. if astgen wants to make Sema do the work,
319 /// this ZIR instruction could just be an AST node index. If astgen wants to
320 /// do the work, it could use a const instruction.
321 error_set,
322317 /// `error.Foo` syntax. Uses the `str_tok` field of the Data union.
323318 error_value,
324319 /// Given a pointer to a struct or object that contains virtual fields, returns a pointer
......@@ -742,7 +737,6 @@ pub const Inst = struct {
742737 .merge_error_sets,
743738 .error_union_type,
744739 .bit_not,
745 .error_set,
746740 .error_value,
747741 .slice_start,
748742 .slice_end,
......@@ -1459,8 +1453,6 @@ const Writer = struct {
14591453 .asm_volatile,
14601454 .elem_ptr_node,
14611455 .elem_val_node,
1462 .field_ptr,
1463 .field_val,
14641456 .field_ptr_named,
14651457 .field_val_named,
14661458 .floatcast,
......@@ -1519,6 +1511,10 @@ const Writer = struct {
15191511 .decl_val,
15201512 => try self.writePlNodeDecl(stream, inst),
15211513
1514 .field_ptr,
1515 .field_val,
1516 => try self.writePlNodeField(stream, inst),
1517
15221518 .as_node => try self.writeAs(stream, inst),
15231519
15241520 .breakpoint,
......@@ -1544,7 +1540,6 @@ const Writer = struct {
15441540 .bitcast,
15451541 .bitcast_ref,
15461542 .bitcast_result_ptr,
1547 .error_set,
15481543 .store_to_inferred_ptr,
15491544 => try stream.writeAll("TODO)"),
15501545 }
......@@ -1733,6 +1728,15 @@ const Writer = struct {
17331728 try self.writeSrc(stream, inst_data.src());
17341729 }
17351730
1731 fn writePlNodeField(self: *Writer, stream: anytype, inst: Inst.Index) !void {
1732 const inst_data = self.code.instructions.items(.data)[inst].pl_node;
1733 const extra = self.code.extraData(Inst.Field, inst_data.payload_index).data;
1734 const name = self.code.nullTerminatedString(extra.field_name_start);
1735 try self.writeInstRef(stream, extra.lhs);
1736 try stream.print(", \"{}\") ", .{std.zig.fmtEscapes(name)});
1737 try self.writeSrc(stream, inst_data.src());
1738 }
1739
17361740 fn writeAs(self: *Writer, stream: anytype, inst: Inst.Index) !void {
17371741 const inst_data = self.code.instructions.items(.data)[inst].pl_node;
17381742 const extra = self.code.extraData(Inst.As, inst_data.payload_index).data;
test/stage2/test.zig+32-32
......@@ -1565,37 +1565,37 @@ pub fn addCases(ctx: *TestContext) !void {
15651565 \\}
15661566 , "");
15671567 }
1568 //{
1569 // var case = ctx.exe("merge error sets", linux_x64);
1568 {
1569 var case = ctx.exe("merge error sets", linux_x64);
15701570
1571 // case.addCompareOutput(
1572 // \\export fn _start() noreturn {
1573 // \\ const E = error{ A, B, D } || error { A, B, C };
1574 // \\ const a = E.A;
1575 // \\ const b = E.B;
1576 // \\ const c = E.C;
1577 // \\ const d = E.D;
1578 // \\ const E2 = error { X, Y } || @TypeOf(error.Z);
1579 // \\ const x = E2.X;
1580 // \\ const y = E2.Y;
1581 // \\ const z = E2.Z;
1582 // \\ assert(anyerror || error { Z } == anyerror);
1583 // \\ exit();
1584 // \\}
1585 // \\fn assert(b: bool) void {
1586 // \\ if (!b) unreachable;
1587 // \\}
1588 // \\fn exit() noreturn {
1589 // \\ asm volatile ("syscall"
1590 // \\ :
1591 // \\ : [number] "{rax}" (231),
1592 // \\ [arg1] "{rdi}" (0)
1593 // \\ : "rcx", "r11", "memory"
1594 // \\ );
1595 // \\ unreachable;
1596 // \\}
1597 // ,
1598 // "",
1599 // );
1600 //}
1571 case.addCompareOutput(
1572 \\export fn _start() noreturn {
1573 \\ const E = error{ A, B, D } || error { A, B, C };
1574 \\ const a = E.A;
1575 \\ const b = E.B;
1576 \\ const c = E.C;
1577 \\ const d = E.D;
1578 \\ const E2 = error { X, Y } || @TypeOf(error.Z);
1579 \\ const x = E2.X;
1580 \\ const y = E2.Y;
1581 \\ const z = E2.Z;
1582 \\ assert(anyerror || error { Z } == anyerror);
1583 \\ exit();
1584 \\}
1585 \\fn assert(b: bool) void {
1586 \\ if (!b) unreachable;
1587 \\}
1588 \\fn exit() noreturn {
1589 \\ asm volatile ("syscall"
1590 \\ :
1591 \\ : [number] "{rax}" (231),
1592 \\ [arg1] "{rdi}" (0)
1593 \\ : "rcx", "r11", "memory"
1594 \\ );
1595 \\ unreachable;
1596 \\}
1597 ,
1598 "",
1599 );
1600 }
16011601}