authorgravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-10-16 23:11:35+03:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2020-10-30 15:58:13+02:00
log4155d2ae242d18c0bc280aa22f733bf7dcb6e1f0
treef63b33a1ebb55b9c74f90bfd230b55104d9da473
parent3c96d799531dbfaf4127ed2fcaa0e69658f90e23
signaturelock-open Commit is signed but in an unrecognized format.

stage2: switch ranges and multi item prongs


5 files changed, 189 insertions(+), 94 deletions(-)

src/astgen.zig+140-91
......@@ -1561,6 +1561,17 @@ fn forExpr(mod: *Module, scope: *Scope, rl: ResultLoc, for_node: *ast.Node.For)
15611561 return &for_block.base;
15621562}
15631563
1564fn getRangeNode(node: *ast.Node) ?*ast.Node.SimpleInfixOp {
1565 var cur = node;
1566 while (true) {
1567 switch (cur.tag) {
1568 .Range => return @fieldParentPtr(ast.Node.SimpleInfixOp, "base", cur),
1569 .GroupedExpression => cur = @fieldParentPtr(ast.Node.GroupedExpression, "base", cur).expr,
1570 else => return null,
1571 }
1572 }
1573}
1574
15641575fn switchExpr(mod: *Module, scope: *Scope, rl: ResultLoc, switch_node: *ast.Node.Switch) InnerError!*zir.Inst {
15651576 var block_scope: Scope.GenZIR = .{
15661577 .parent = scope,
......@@ -1581,6 +1592,7 @@ fn switchExpr(mod: *Module, scope: *Scope, rl: ResultLoc, switch_node: *ast.Node
15811592 const tree = scope.tree();
15821593 const switch_src = tree.token_locs[switch_node.switch_token].start;
15831594 const target_ptr = try expr(mod, &block_scope.base, .ref, switch_node.expr);
1595 const target = try addZIRUnOp(mod, &block_scope.base, target_ptr.src, .deref, target_ptr);
15841596 // Add the switch instruction here so that it comes before any range checks.
15851597 const switch_inst = (try addZIRInst(mod, &block_scope.base, switch_src, zir.Inst.SwitchBr, .{
15861598 .target_ptr = target_ptr,
......@@ -1593,24 +1605,51 @@ fn switchExpr(mod: *Module, scope: *Scope, rl: ResultLoc, switch_node: *ast.Node
15931605 var cases = std.ArrayList(zir.Inst.SwitchBr.Case).init(mod.gpa);
15941606 defer cases.deinit();
15951607
1608 // Add comptime block containing all prong items first,
1609 const item_block = try addZIRInstBlock(mod, scope, switch_src, .block_comptime_flat, .{
1610 .instructions = undefined, // populated below
1611 });
1612 // then add block containing the switch.
1613 const block = try addZIRInstBlock(mod, scope, switch_src, .block, .{
1614 .instructions = undefined, // populated below
1615 });
1616
1617 // Most result location types can be forwarded directly; however
1618 // if we need to write to a pointer which has an inferred type,
1619 // proper type inference requires peer type resolution on the switch case.
1620 const case_rl: ResultLoc = switch (rl) {
1621 .discard, .none, .ty, .ptr, .ref => rl,
1622 .inferred_ptr, .bitcasted_ptr, .block_ptr => .{ .block_ptr = block },
1623 };
1624
1625 var case_scope: Scope.GenZIR = .{
1626 .parent = scope,
1627 .decl = block_scope.decl,
1628 .arena = block_scope.arena,
1629 .instructions = .{},
1630 };
1631 defer case_scope.instructions.deinit(mod.gpa);
1632
15961633 // first we gather all the switch items and check else/'_' prongs
15971634 var else_src: ?usize = null;
15981635 var underscore_src: ?usize = null;
1599 var range_inst: ?*zir.Inst = null;
1636 var first_range: ?*zir.Inst = null;
1637 var special_case: ?*ast.Node.SwitchCase = null;
16001638 for (switch_node.cases()) |uncasted_case| {
16011639 const case = uncasted_case.castTag(.SwitchCase).?;
16021640 const case_src = tree.token_locs[case.firstToken()].start;
1641 // reset without freeing to reduce allocations.
1642 case_scope.instructions.items.len = 0;
1643 assert(case.items_len != 0);
16031644
1604 if (case.payload != null) {
1605 return mod.fail(scope, case_src, "TODO switch case payload capture", .{});
1606 }
1607
1645 // Check for else/_ prong, those are handled last.
16081646 if (case.items_len == 1 and case.items()[0].tag == .SwitchElse) {
16091647 if (else_src) |src| {
16101648 return mod.fail(scope, case_src, "multiple else prongs in switch expression", .{});
16111649 // TODO notes "previous else prong is here"
16121650 }
16131651 else_src = case_src;
1652 special_case = case;
16141653 continue;
16151654 } else if (case.items_len == 1 and case.items()[0].tag == .Identifier and
16161655 mem.eql(u8, tree.tokenSlice(case.items()[0].firstToken()), "_"))
......@@ -1620,6 +1659,7 @@ fn switchExpr(mod: *Module, scope: *Scope, rl: ResultLoc, switch_node: *ast.Node
16201659 // TODO notes "previous '_' prong is here"
16211660 }
16221661 underscore_src = case_src;
1662 special_case = case;
16231663 continue;
16241664 }
16251665
......@@ -1631,103 +1671,107 @@ fn switchExpr(mod: *Module, scope: *Scope, rl: ResultLoc, switch_node: *ast.Node
16311671 }
16321672 }
16331673
1634 // TODO and not range
1635 if (case.items_len == 1) {
1674 // If this is a simple one item prong then it is handled by the switchbr.
1675 if (case.items_len == 1 and getRangeNode(case.items()[0]) == null) {
16361676 const item = try expr(mod, &item_scope.base, .none, case.items()[0]);
1677 try items.append(item);
1678 try switchCaseExpr(mod, &case_scope.base, case_rl, block, case);
1679
16371680 try cases.append(.{
16381681 .item = item,
1639 .body = undefined, // populated below
1682 .body = .{ .instructions = try scope.arena().dupe(*zir.Inst, case_scope.instructions.items) },
16401683 });
16411684 continue;
16421685 }
1643 return mod.fail(scope, case_src, "TODO switch ranges", .{});
1644 }
16451686
1646 // Actually populate switch instruction values.
1647 if (else_src != null) switch_inst.kw_args.special_prong = .@"else";
1648 if (underscore_src != null) switch_inst.kw_args.special_prong = .underscore;
1649 switch_inst.positionals.cases = try block_scope.arena.dupe(zir.Inst.SwitchBr.Case, cases.items);
1650 switch_inst.positionals.items = try block_scope.arena.dupe(*zir.Inst, items.items);
1651 switch_inst.kw_args.range = range_inst;
1687 // TODO if the case has few items and no ranges it might be better
1688 // to just handle them as switch prongs.
1689
1690 // Check if the target matches any of the items.
1691 // 1, 2, 3..6 will result in
1692 // target == 1 or target == 2 or (target >= 3 and target <= 6)
1693 var any_ok: ?*zir.Inst = null;
1694 for (case.items()) |item| {
1695 if (getRangeNode(item)) |range| {
1696 const start = try expr(mod, &item_scope.base, .none, range.lhs);
1697 const end = try expr(mod, &item_scope.base, .none, range.rhs);
1698 const range_src = tree.token_locs[range.op_token].start;
1699 const range_inst = try addZIRBinOp(mod, &item_scope.base, range_src, .switch_range, start, end);
1700 try items.append(range_inst);
1701 if (first_range == null) first_range = range_inst;
1702
1703 // target >= start and target <= end
1704 const range_start_ok = try addZIRBinOp(mod, &block_scope.base, range_src, .cmp_gte, target, start);
1705 const range_end_ok = try addZIRBinOp(mod, &block_scope.base, range_src, .cmp_lte, target, end);
1706 const range_ok = try addZIRBinOp(mod, &block_scope.base, range_src, .booland, range_start_ok, range_end_ok);
1707
1708 if (any_ok) |some| {
1709 any_ok = try addZIRBinOp(mod, &block_scope.base, range_src, .boolor, some, range_ok);
1710 } else {
1711 any_ok = range_ok;
1712 }
1713 continue;
1714 }
16521715
1653 // Add comptime block containing all prong items first,
1654 _ = try addZIRInstBlock(mod, scope, switch_src, .block_comptime_flat, .{
1655 .instructions = try block_scope.arena.dupe(*zir.Inst, item_scope.instructions.items),
1656 });
1657 // then add block containing the switch.
1658 const block = try addZIRInstBlock(mod, scope, switch_src, .block, .{
1659 .instructions = undefined, // populated below
1660 });
1716 const item_inst = try expr(mod, &item_scope.base, .none, item);
1717 try items.append(item_inst);
1718 const cpm_ok = try addZIRBinOp(mod, &block_scope.base, item_inst.src, .cmp_eq, target, item_inst);
16611719
1662 // Most result location types can be forwarded directly; however
1663 // if we need to write to a pointer which has an inferred type,
1664 // proper type inference requires peer type resolution on the switch case.
1665 const case_rl: ResultLoc = switch (rl) {
1666 .discard, .none, .ty, .ptr, .ref => rl,
1667 .inferred_ptr, .bitcasted_ptr, .block_ptr => .{ .block_ptr = block },
1668 };
1720 if (any_ok) |some| {
1721 any_ok = try addZIRBinOp(mod, &block_scope.base, item_inst.src, .boolor, some, cpm_ok);
1722 } else {
1723 any_ok = cpm_ok;
1724 }
1725 }
16691726
1670 var case_scope: Scope.GenZIR = .{
1671 .parent = scope,
1672 .decl = block_scope.decl,
1673 .arena = block_scope.arena,
1674 .instructions = .{},
1675 };
1676 defer case_scope.instructions.deinit(mod.gpa);
1727 const condbr = try addZIRInstSpecial(mod, &block_scope.base, case_src, zir.Inst.CondBr, .{
1728 .condition = any_ok.?,
1729 .then_body = undefined, // populated below
1730 .else_body = undefined, // populated below
1731 }, .{});
16771732
1678 // And finally we fill generate the bodies of each case.
1679 var case_index: usize = 0;
1680 var special_case: ?*ast.Node.SwitchCase = null;
1681 for (switch_node.cases()) |uncasted_case| {
1682 const case = uncasted_case.castTag(.SwitchCase).?;
1683 const case_src = tree.token_locs[case.firstToken()].start;
1684 // reset without freeing to reduce allocations.
1685 defer case_scope.instructions.items.len = 0;
1733 try switchCaseExpr(mod, &case_scope.base, case_rl, block, case);
1734 condbr.positionals.then_body = .{
1735 .instructions = try scope.arena().dupe(*zir.Inst, case_scope.instructions.items),
1736 };
16861737
1687 if (case.items_len == 1 and case.items()[0].tag == .SwitchElse) {
1688 // validated earlier
1689 special_case = case;
1690 continue;
1691 } else if (case.items_len == 1 and case.items()[0].tag == .Identifier and
1692 mem.eql(u8, tree.tokenSlice(case.items()[0].firstToken()), "_"))
1693 {
1694 // validated earlier
1695 special_case = case;
1696 continue;
1697 }
1738 // reset to add the empty block
1739 case_scope.instructions.items.len = 0;
1740 const empty_block = try addZIRInstBlock(mod, &case_scope.base, case_src, .block, .{
1741 .instructions = undefined, // populated below
1742 });
1743 condbr.positionals.else_body = .{
1744 .instructions = try scope.arena().dupe(*zir.Inst, case_scope.instructions.items),
1745 };
16981746
1699 if (case.items_len == 1) {
1700 // Generate the body of this case.
1701 const case_body = try expr(mod, &case_scope.base, case_rl, case.expr);
1702 if (!case_body.tag.isNoReturn()) {
1703 _ = try addZIRInst(mod, &case_scope.base, case_src, zir.Inst.Break, .{
1704 .block = block,
1705 .operand = case_body,
1706 }, .{});
1707 }
1708 switch_inst.positionals.cases[case_index].body = .{
1709 .instructions = try scope.arena().dupe(*zir.Inst, case_scope.instructions.items),
1710 };
1711 case_index += 1;
1712 continue;
1713 }
1714 return mod.fail(scope, case_src, "TODO switch ranges", .{});
1747 // reset to add a break to the empty block
1748 case_scope.instructions.items.len = 0;
1749 _ = try addZIRInst(mod, &case_scope.base, case_src, zir.Inst.BreakVoid, .{
1750 .block = empty_block,
1751 }, .{});
1752 empty_block.positionals.body = .{
1753 .instructions = try scope.arena().dupe(*zir.Inst, case_scope.instructions.items),
1754 };
17151755 }
17161756
1757 // All items have been generated, add the instructions to the comptime block.
1758 item_block.positionals.body = .{
1759 .instructions = try block_scope.arena.dupe(*zir.Inst, item_scope.instructions.items),
1760 };
1761
1762 // Actually populate switch instruction values.
1763 if (else_src != null) switch_inst.kw_args.special_prong = .@"else";
1764 if (underscore_src != null) switch_inst.kw_args.special_prong = .underscore;
1765 switch_inst.positionals.cases = try block_scope.arena.dupe(zir.Inst.SwitchBr.Case, cases.items);
1766 switch_inst.positionals.items = try block_scope.arena.dupe(*zir.Inst, items.items);
1767 switch_inst.kw_args.range = first_range;
1768
17171769 // Generate else block or a break last to finish the block.
17181770 if (special_case) |case| {
1719 const case_src = tree.token_locs[case.firstToken()].start;
1720 const case_body = try expr(mod, &block_scope.base, case_rl, case.expr);
1721 if (!case_body.tag.isNoReturn()) {
1722 _ = try addZIRInst(mod, &block_scope.base, case_src, zir.Inst.Break, .{
1723 .block = block,
1724 .operand = case_body,
1725 }, .{});
1726 }
1771 try switchCaseExpr(mod, &block_scope.base, case_rl, block, case);
17271772 } else {
1728 _ = try addZIRInst(mod, &block_scope.base, switch_src, zir.Inst.BreakVoid, .{
1729 .block = block,
1730 }, .{});
1773 // Not handling all possible cases is a compile error.
1774 _ = try addZIRNoOp(mod, &block_scope.base, switch_src, .unreach_nocheck);
17311775 }
17321776
17331777 // Set block instructions now that it is finished.
......@@ -1737,15 +1781,20 @@ fn switchExpr(mod: *Module, scope: *Scope, rl: ResultLoc, switch_node: *ast.Node
17371781 return &block.base;
17381782}
17391783
1740/// Only used for `a...b` in switches.
1741fn switchRange(mod: *Module, scope: *Scope, node: *ast.Node.SimpleInfixOp) InnerError!*zir.Inst {
1784fn switchCaseExpr(mod: *Module, scope: *Scope, rl: ResultLoc, block: *zir.Inst.Block, case: *ast.Node.SwitchCase) !void {
17421785 const tree = scope.tree();
1743 const src = tree.token_locs[node.op_token].start;
1744
1745 const start = try expr(mod, scope, .none, node.lhs);
1746 const end = try expr(mod, scope, .none, node.rhs);
1786 const case_src = tree.token_locs[case.firstToken()].start;
1787 if (case.payload != null) {
1788 return mod.fail(scope, case_src, "TODO switch case payload capture", .{});
1789 }
17471790
1748 return try addZIRBinOp(mod, scope, src, .switch_range, start, end);
1791 const case_body = try expr(mod, scope, rl, case.expr);
1792 if (!case_body.tag.isNoReturn()) {
1793 _ = try addZIRInst(mod, scope, case_src, zir.Inst.Break, .{
1794 .block = block,
1795 .operand = case_body,
1796 }, .{});
1797 }
17491798}
17501799
17511800fn ret(mod: *Module, scope: *Scope, cfe: *ast.Node.ControlFlowExpression) InnerError!*zir.Inst {
src/codegen.zig+9-1
......@@ -758,6 +758,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
758758 .br => return self.genBr(inst.castTag(.br).?),
759759 .breakpoint => return self.genBreakpoint(inst.src),
760760 .brvoid => return self.genBrVoid(inst.castTag(.brvoid).?),
761 .booland => return self.genBoolOp(inst.castTag(.booland).?),
762 .boolor => return self.genBoolOp(inst.castTag(.boolor).?),
761763 .call => return self.genCall(inst.castTag(.call).?),
762764 .cmp_lt => return self.genCmp(inst.castTag(.cmp_lt).?, .lt),
763765 .cmp_lte => return self.genCmp(inst.castTag(.cmp_lte).?, .lte),
......@@ -782,11 +784,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
782784 .retvoid => return self.genRetVoid(inst.castTag(.retvoid).?),
783785 .store => return self.genStore(inst.castTag(.store).?),
784786 .sub => return self.genSub(inst.castTag(.sub).?),
787 .switchbr => return self.genSwitch(inst.castTag(.switchbr).?),
785788 .unreach => return MCValue{ .unreach = {} },
786789 .unwrap_optional => return self.genUnwrapOptional(inst.castTag(.unwrap_optional).?),
787790 .wrap_optional => return self.genWrapOptional(inst.castTag(.wrap_optional).?),
788791 .varptr => return self.genVarPtr(inst.castTag(.varptr).?),
789 .switchbr => return self.genSwitch(inst.castTag(.switchbr).?),
790792 }
791793 }
792794
......@@ -2030,6 +2032,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
20302032 return self.brVoid(inst.base.src, inst.block);
20312033 }
20322034
2035 fn genBoolOp(self: *Self, inst: *ir.Inst.BinOp) !MCValue {
2036 switch (arch) {
2037 else => return self.fail(inst.base.src, "TODO genBoolOp for {}", .{self.target.cpu.arch}),
2038 }
2039 }
2040
20332041 fn brVoid(self: *Self, src: usize, block: *ir.Inst.Block) !MCValue {
20342042 // Emit a jump with a relocation. It will be patched up after the block ends.
20352043 try block.codegen.relocs.ensureCapacity(self.gpa, block.codegen.relocs.items.len + 1);
src/ir.zig+4
......@@ -74,6 +74,8 @@ pub const Inst = struct {
7474 isnonnull,
7575 isnull,
7676 iserr,
77 booland,
78 boolor,
7779 /// Read a value from a pointer.
7880 load,
7981 loop,
......@@ -126,6 +128,8 @@ pub const Inst = struct {
126128 .cmp_gt,
127129 .cmp_neq,
128130 .store,
131 .booland,
132 .boolor,
129133 => BinOp,
130134
131135 .arg => Arg,
src/zir.zig+11-1
......@@ -85,8 +85,12 @@ pub const Inst = struct {
8585 block_comptime,
8686 /// Same as `block_flat` but additionally makes the inner instructions execute at comptime.
8787 block_comptime_flat,
88 /// Boolean AND. See also `bitand`.
89 booland,
8890 /// Boolean NOT. See also `bitnot`.
8991 boolnot,
92 /// Boolean OR. See also `bitor`.
93 boolor,
9094 /// Return a value from a `Block`.
9195 @"break",
9296 breakpoint,
......@@ -333,6 +337,8 @@ pub const Inst = struct {
333337 .array_type,
334338 .bitand,
335339 .bitor,
340 .booland,
341 .boolor,
336342 .div,
337343 .mod_rem,
338344 .mul,
......@@ -425,6 +431,8 @@ pub const Inst = struct {
425431 .block_comptime,
426432 .block_comptime_flat,
427433 .boolnot,
434 .booland,
435 .boolor,
428436 .breakpoint,
429437 .call,
430438 .cmp_lt,
......@@ -502,6 +510,7 @@ pub const Inst = struct {
502510 .slice_start,
503511 .import,
504512 .switchbr,
513 .switch_range,
505514 => false,
506515
507516 .@"break",
......@@ -513,7 +522,6 @@ pub const Inst = struct {
513522 .unreach_nocheck,
514523 .@"unreachable",
515524 .loop,
516 .switch_range,
517525 => true,
518526 };
519527 }
......@@ -2320,6 +2328,8 @@ const EmitZIR = struct {
23202328 .cmp_gte => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_gte).?, .cmp_gte),
23212329 .cmp_gt => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_gt).?, .cmp_gt),
23222330 .cmp_neq => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_neq).?, .cmp_neq),
2331 .booland => try self.emitBinOp(inst.src, new_body, inst.castTag(.booland).?, .booland),
2332 .boolor => try self.emitBinOp(inst.src, new_body, inst.castTag(.boolor).?, .boolor),
23232333
23242334 .bitcast => try self.emitCast(inst.src, new_body, inst.castTag(.bitcast).?, .bitcast),
23252335 .intcast => try self.emitCast(inst.src, new_body, inst.castTag(.intcast).?, .intcast),
src/zir_sema.zig+25-1
......@@ -137,6 +137,8 @@ pub fn analyzeInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!
137137 .import => return analyzeInstImport(mod, scope, old_inst.castTag(.import).?),
138138 .switchbr => return analyzeInstSwitchBr(mod, scope, old_inst.castTag(.switchbr).?),
139139 .switch_range => return analyzeInstSwitchRange(mod, scope, old_inst.castTag(.switch_range).?),
140 .booland => return analyzeInstBoolOp(mod, scope, old_inst.castTag(.booland).?),
141 .boolor => return analyzeInstBoolOp(mod, scope, old_inst.castTag(.boolor).?),
140142 }
141143}
142144
......@@ -1224,7 +1226,7 @@ fn analyzeInstSwitchRange(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) In
12241226 if (start.value()) |start_val| {
12251227 if (end.value()) |end_val| {
12261228 if (start_val.compare(.gte, end_val)) {
1227 return mod.fail(scope, inst.base.src, "range start value is greater than the end value", .{});
1229 return mod.fail(scope, inst.base.src, "range start value must be smaller than the end value", .{});
12281230 }
12291231 }
12301232 }
......@@ -1609,6 +1611,28 @@ fn analyzeInstBoolNot(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerEr
16091611 return mod.addUnOp(b, inst.base.src, bool_type, .not, operand);
16101612}
16111613
1614fn analyzeInstBoolOp(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
1615 const bool_type = Type.initTag(.bool);
1616 const uncasted_lhs = try resolveInst(mod, scope, inst.positionals.lhs);
1617 const lhs = try mod.coerce(scope, bool_type, uncasted_lhs);
1618 const uncasted_rhs = try resolveInst(mod, scope, inst.positionals.rhs);
1619 const rhs = try mod.coerce(scope, bool_type, uncasted_rhs);
1620
1621 const is_bool_or = inst.base.tag == .boolor;
1622
1623 if (lhs.value()) |lhs_val| {
1624 if (rhs.value()) |rhs_val| {
1625 if (is_bool_or) {
1626 return mod.constBool(scope, inst.base.src, lhs_val.toBool() or rhs_val.toBool());
1627 } else {
1628 return mod.constBool(scope, inst.base.src, lhs_val.toBool() and rhs_val.toBool());
1629 }
1630 }
1631 }
1632 const b = try mod.requireRuntimeBlock(scope, inst.base.src);
1633 return mod.addBinOp(b, inst.base.src, bool_type, if (is_bool_or) .boolor else .booland, lhs, rhs);
1634}
1635
16121636fn analyzeInstIsNonNull(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp, invert_logic: bool) InnerError!*Inst {
16131637 const operand = try resolveInst(mod, scope, inst.positionals.operand);
16141638 return mod.analyzeIsNull(scope, inst.base.src, operand, invert_logic);