Add support for both '_' and 'else' prongs at the same time in switch statements

If both are used, 'else' handles named members and '_' handles
unnamed members. In this case the 'else' prong will be unrolled
to an explicit case containing all remaining named values.
This commit is contained in:
Justus Klausecker 2025-07-10 01:58:02 +02:00
parent 1d9b1c0212
commit ba549a7d67
11 changed files with 770 additions and 364 deletions

View File

@ -2877,24 +2877,6 @@ pub const full = struct {
arrow_token: TokenIndex, arrow_token: TokenIndex,
target_expr: Node.Index, target_expr: Node.Index,
}; };
/// Returns:
/// `null` if case is not special
/// `.none` if case is else prong
/// Index of underscore otherwise
pub fn isSpecial(case: *const SwitchCase, tree: *const Ast) ?Node.OptionalIndex {
if (case.ast.values.len == 0) {
return .none;
}
for (case.ast.values) |val| {
if (tree.nodeTag(val) == .identifier and
mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(val)), "_"))
{
return val.toOptional();
}
}
return null;
}
}; };
pub const Asm = struct { pub const Asm = struct {

View File

@ -7662,11 +7662,12 @@ fn switchExpr(
var scalar_cases_len: u32 = 0; var scalar_cases_len: u32 = 0;
var multi_cases_len: u32 = 0; var multi_cases_len: u32 = 0;
var inline_cases_len: u32 = 0; var inline_cases_len: u32 = 0;
var special_prong: Zir.SpecialProng = .none; var else_case_node: Ast.Node.OptionalIndex = .none;
var special_node: Ast.Node.OptionalIndex = .none;
var else_src: ?Ast.TokenIndex = null; var else_src: ?Ast.TokenIndex = null;
var underscore_src: ?Ast.TokenIndex = null; var underscore_case_node: Ast.Node.OptionalIndex = .none;
var underscore_node: Ast.Node.OptionalIndex = .none; var underscore_node: Ast.Node.OptionalIndex = .none;
var underscore_src: ?Ast.TokenIndex = null;
var underscore_additional_items: Zir.SpecialProngs.AdditionalItems = .none;
for (case_nodes) |case_node| { for (case_nodes) |case_node| {
const case = tree.fullSwitchCase(case_node).?; const case = tree.fullSwitchCase(case_node).?;
if (case.payload_token) |payload_token| { if (case.payload_token) |payload_token| {
@ -7687,6 +7688,7 @@ fn switchExpr(
any_non_inline_capture = true; any_non_inline_capture = true;
} }
} }
// Check for else prong. // Check for else prong.
if (case.ast.values.len == 0) { if (case.ast.values.len == 0) {
const case_src = case.ast.arrow_token - 1; const case_src = case.ast.arrow_token - 1;
@ -7703,40 +7705,21 @@ fn switchExpr(
), ),
}, },
); );
} else if (underscore_src) |some_underscore| {
return astgen.failNodeNotes(
node,
"else and '_' prong in switch expression",
.{},
&[_]u32{
try astgen.errNoteTok(
case_src,
"else prong here",
.{},
),
try astgen.errNoteTok(
some_underscore,
"'_' prong here",
.{},
),
},
);
} }
special_node = case_node.toOptional(); else_case_node = case_node.toOptional();
special_prong = .@"else";
else_src = case_src; else_src = case_src;
continue; continue;
} }
// Check for '_' prong. // Check for '_' prong.
var found_underscore = false; var case_has_underscore = false;
for (case.ast.values) |val| { for (case.ast.values) |val| {
switch (tree.nodeTag(val)) { switch (tree.nodeTag(val)) {
.identifier => if (mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(val)), "_")) { .identifier => if (mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(val)), "_")) {
const case_src = case.ast.arrow_token - 1; const val_src = tree.nodeMainToken(val);
if (underscore_src) |src| { if (underscore_src) |src| {
return astgen.failTokNotes( return astgen.failTokNotes(
case_src, val_src,
"multiple '_' prongs in switch expression", "multiple '_' prongs in switch expression",
.{}, .{},
&[_]u32{ &[_]u32{
@ -7747,39 +7730,26 @@ fn switchExpr(
), ),
}, },
); );
} else if (else_src) |some_else| {
return astgen.failNodeNotes(
node,
"else and '_' prong in switch expression",
.{},
&[_]u32{
try astgen.errNoteTok(
some_else,
"else prong here",
.{},
),
try astgen.errNoteTok(
case_src,
"'_' prong here",
.{},
),
},
);
} }
if (case.inline_token != null) { if (case.inline_token != null) {
return astgen.failTok(case_src, "cannot inline '_' prong", .{}); return astgen.failTok(val_src, "cannot inline '_' prong", .{});
} }
special_node = case_node.toOptional(); underscore_case_node = case_node.toOptional();
special_prong = if (case.ast.values.len == 1) .under else .absorbing_under; underscore_src = val_src;
underscore_src = case_src;
underscore_node = val.toOptional(); underscore_node = val.toOptional();
found_underscore = true; underscore_additional_items = switch (case.ast.values.len) {
0 => unreachable,
1 => .none,
2 => .one,
else => .many,
};
case_has_underscore = true;
}, },
.string_literal => return astgen.failNode(val, "cannot switch on strings", .{}), .string_literal => return astgen.failNode(val, "cannot switch on strings", .{}),
else => {}, else => {},
} }
} }
if (found_underscore) continue; if (case_has_underscore) continue;
if (case.ast.values.len == 1 and tree.nodeTag(case.ast.values[0]) != .switch_range) { if (case.ast.values.len == 1 and tree.nodeTag(case.ast.values[0]) != .switch_range) {
scalar_cases_len += 1; scalar_cases_len += 1;
@ -7791,6 +7761,14 @@ fn switchExpr(
} }
} }
const special_prongs: Zir.SpecialProngs = .init(
else_src != null,
underscore_src != null,
underscore_additional_items,
);
const has_else = special_prongs.hasElse();
const has_under = special_prongs.hasUnder();
const operand_ri: ResultInfo = .{ .rl = if (any_payload_is_ref) .ref else .none }; const operand_ri: ResultInfo = .{ .rl = if (any_payload_is_ref) .ref else .none };
astgen.advanceSourceCursorToNode(operand_node); astgen.advanceSourceCursorToNode(operand_node);
@ -7811,7 +7789,9 @@ fn switchExpr(
const payloads = &astgen.scratch; const payloads = &astgen.scratch;
const scratch_top = astgen.scratch.items.len; const scratch_top = astgen.scratch.items.len;
const case_table_start = scratch_top; const case_table_start = scratch_top;
const scalar_case_table = case_table_start + @intFromBool(special_prong != .none); const else_case_index = if (has_else) case_table_start else undefined;
const under_case_index = if (has_under) case_table_start + @intFromBool(has_else) else undefined;
const scalar_case_table = case_table_start + @intFromBool(has_else) + @intFromBool(has_under);
const multi_case_table = scalar_case_table + scalar_cases_len; const multi_case_table = scalar_case_table + scalar_cases_len;
const case_table_end = multi_case_table + multi_cases_len; const case_table_end = multi_case_table + multi_cases_len;
try astgen.scratch.resize(gpa, case_table_end); try astgen.scratch.resize(gpa, case_table_end);
@ -7943,9 +7923,19 @@ fn switchExpr(
const header_index: u32 = @intCast(payloads.items.len); const header_index: u32 = @intCast(payloads.items.len);
const body_len_index = if (is_multi_case) blk: { const body_len_index = if (is_multi_case) blk: {
if (case_node.toOptional() == special_node) { if (case_node.toOptional() == underscore_case_node) {
assert(special_prong == .absorbing_under); payloads.items[under_case_index] = header_index;
payloads.items[case_table_start] = header_index; if (special_prongs.hasOneAdditionalItem()) {
try payloads.resize(gpa, header_index + 2); // item, body_len
const maybe_item_node = case.ast.values[0];
const item_node = if (maybe_item_node.toOptional() == underscore_node)
case.ast.values[1]
else
maybe_item_node;
const item_inst = try comptimeExpr(parent_gz, scope, item_ri, item_node, .switch_item);
payloads.items[header_index] = @intFromEnum(item_inst);
break :blk header_index + 1;
}
} else { } else {
payloads.items[multi_case_table + multi_case_index] = header_index; payloads.items[multi_case_table + multi_case_index] = header_index;
multi_case_index += 1; multi_case_index += 1;
@ -7985,9 +7975,13 @@ fn switchExpr(
payloads.items[header_index] = items_len; payloads.items[header_index] = items_len;
payloads.items[header_index + 1] = ranges_len; payloads.items[header_index + 1] = ranges_len;
break :blk header_index + 2; break :blk header_index + 2;
} else if (case_node.toOptional() == special_node) blk: { } else if (case_node.toOptional() == else_case_node) blk: {
assert(special_prong != .absorbing_under); payloads.items[else_case_index] = header_index;
payloads.items[case_table_start] = header_index; try payloads.resize(gpa, header_index + 1); // body_len
break :blk header_index;
} else if (case_node.toOptional() == underscore_case_node) blk: {
assert(!special_prongs.hasAdditionalItems());
payloads.items[under_case_index] = header_index;
try payloads.resize(gpa, header_index + 1); // body_len try payloads.resize(gpa, header_index + 1); // body_len
break :blk header_index; break :blk header_index;
} else blk: { } else blk: {
@ -8048,7 +8042,7 @@ fn switchExpr(
.operand = raw_operand, .operand = raw_operand,
.bits = Zir.Inst.SwitchBlock.Bits{ .bits = Zir.Inst.SwitchBlock.Bits{
.has_multi_cases = multi_cases_len != 0, .has_multi_cases = multi_cases_len != 0,
.special_prong = special_prong, .special_prongs = special_prongs,
.any_has_tag_capture = any_has_tag_capture, .any_has_tag_capture = any_has_tag_capture,
.any_non_inline_capture = any_non_inline_capture, .any_non_inline_capture = any_non_inline_capture,
.has_continue = switch_full.label_token != null and block_scope.label.?.used_for_continue, .has_continue = switch_full.label_token != null and block_scope.label.?.used_for_continue,
@ -8067,29 +8061,40 @@ fn switchExpr(
const zir_datas = astgen.instructions.items(.data); const zir_datas = astgen.instructions.items(.data);
zir_datas[@intFromEnum(switch_block)].pl_node.payload_index = payload_index; zir_datas[@intFromEnum(switch_block)].pl_node.payload_index = payload_index;
var normal_case_table_start = case_table_start; if (has_else) {
if (special_prong != .none) { const start_index = payloads.items[else_case_index];
normal_case_table_start += 1; var end_index = start_index + 1;
const prong_info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(payloads.items[start_index]);
const start_index = payloads.items[case_table_start]; end_index += prong_info.body_len;
astgen.extra.appendSliceAssumeCapacity(payloads.items[start_index..end_index]);
}
if (has_under) {
const start_index = payloads.items[under_case_index];
var body_len_index = start_index; var body_len_index = start_index;
var end_index = start_index; var end_index = start_index;
if (special_prong == .absorbing_under) { switch (underscore_additional_items) {
body_len_index += 2; .none => {
const items_len = payloads.items[start_index]; end_index += 1;
const ranges_len = payloads.items[start_index + 1]; },
end_index += 3 + items_len + 2 * ranges_len; .one => {
} else { body_len_index += 1;
end_index += 1; end_index += 2;
},
.many => {
body_len_index += 2;
const items_len = payloads.items[start_index];
const ranges_len = payloads.items[start_index + 1];
end_index += 3 + items_len + 2 * ranges_len;
},
} }
const prong_info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(payloads.items[body_len_index]); const prong_info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(payloads.items[body_len_index]);
end_index += prong_info.body_len; end_index += prong_info.body_len;
astgen.extra.appendSliceAssumeCapacity(payloads.items[start_index..end_index]); astgen.extra.appendSliceAssumeCapacity(payloads.items[start_index..end_index]);
} }
for (payloads.items[normal_case_table_start..case_table_end], 0..) |start_index, i| { for (payloads.items[scalar_case_table..case_table_end], 0..) |start_index, i| {
var body_len_index = start_index; var body_len_index = start_index;
var end_index = start_index; var end_index = start_index;
const table_index = normal_case_table_start + i; const table_index = scalar_case_table + i;
if (table_index < multi_case_table) { if (table_index < multi_case_table) {
body_len_index += 1; body_len_index += 1;
end_index += 2; end_index += 2;

View File

@ -3226,9 +3226,14 @@ pub const Inst = struct {
/// 0. multi_cases_len: u32 // If has_multi_cases is set. /// 0. multi_cases_len: u32 // If has_multi_cases is set.
/// 1. tag_capture_inst: u32 // If any_has_tag_capture is set. Index of instruction prongs use to refer to the inline tag capture. /// 1. tag_capture_inst: u32 // If any_has_tag_capture is set. Index of instruction prongs use to refer to the inline tag capture.
/// 2. else_body { // If special_prong != .none /// 2. else_body { // If special_prong.hasElse() is set.
/// items_len: u32, // If special_prong == .absorbing_under /// info: ProngInfo,
/// ranges_len: u32, // If special_prong == .absorbing_under /// body member Index for every info.body_len
/// }
/// 3. under_body { // If special_prong.hasUnder() is set.
/// item: Ref, // If special_prong.hasOneAdditionalItem() is set.
/// items_len: u32, // If special_prong.hasManyAdditionalItems() is set.
/// ranges_len: u32, // If special_prong.hasManyAdditionalItems() is set.
/// info: ProngInfo, /// info: ProngInfo,
/// item: Ref, // for every items_len /// item: Ref, // for every items_len
/// ranges: { // for every ranges_len /// ranges: { // for every ranges_len
@ -3237,12 +3242,12 @@ pub const Inst = struct {
/// } /// }
/// body member Index for every info.body_len /// body member Index for every info.body_len
/// } /// }
/// 3. scalar_cases: { // for every scalar_cases_len /// 4. scalar_cases: { // for every scalar_cases_len
/// item: Ref, /// item: Ref,
/// info: ProngInfo, /// info: ProngInfo,
/// body member Index for every info.body_len /// body member Index for every info.body_len
/// } /// }
/// 4. multi_cases: { // for every multi_cases_len /// 5. multi_cases: { // for every multi_cases_len
/// items_len: u32, /// items_len: u32,
/// ranges_len: u32, /// ranges_len: u32,
/// info: ProngInfo, /// info: ProngInfo,
@ -3283,16 +3288,17 @@ pub const Inst = struct {
/// If true, one or more prongs have multiple items. /// If true, one or more prongs have multiple items.
has_multi_cases: bool, has_multi_cases: bool,
/// Information about the special prong. /// Information about the special prong.
special_prong: SpecialProng, special_prongs: SpecialProngs,
/// If true, at least one prong has an inline tag capture. /// If true, at least one prong has an inline tag capture.
any_has_tag_capture: bool, any_has_tag_capture: bool,
/// If true, at least one prong has a capture which may not /// If true, at least one prong has a capture which may not
/// be comptime-known via `inline`. /// be comptime-known via `inline`.
any_non_inline_capture: bool, any_non_inline_capture: bool,
/// If true, at least one prong contains a `continue`.
has_continue: bool, has_continue: bool,
scalar_cases_len: ScalarCasesLen, scalar_cases_len: ScalarCasesLen,
pub const ScalarCasesLen = u26; pub const ScalarCasesLen = u25;
}; };
pub const MultiProng = struct { pub const MultiProng = struct {
@ -3868,17 +3874,67 @@ pub const Inst = struct {
}; };
}; };
pub const SpecialProng = enum(u2) { pub const SpecialProngs = enum(u3) {
none, none = 0b000,
/// Simple else prong. /// Simple `else` prong.
/// `else => {}` /// `else => {},`
@"else", @"else" = 0b001,
/// Simple '_' prong. /// Simple `_` prong.
/// `_ => {}` /// `_ => {},`
under, under = 0b010,
/// '_' prong with additional items. /// Both an `else` and a `_` prong.
/// `a, _, b => {}` /// `else => {},`
absorbing_under, /// `_ => {},`
under_and_else = 0b011,
/// `_` prong with 1 additional item.
/// `a, _ => {},`
under_one_item = 0b100,
/// Both an `else` and a `_` prong with 1 additional item.
/// `else => {},`
/// `a, _ => {},`
under_one_item_and_else = 0b101,
/// `_` prong with >1 additional items.
/// `a, _, b => {},`
under_many_items = 0b110,
/// Both an `else` and a `_` prong with >1 additional items.
/// `else => {},`
/// `a, _, b => {},`
under_many_items_and_else = 0b111,
pub const AdditionalItems = enum(u3) {
none = @intFromEnum(SpecialProngs.under),
one = @intFromEnum(SpecialProngs.under_one_item),
many = @intFromEnum(SpecialProngs.under_many_items),
};
pub fn init(has_else: bool, has_under: bool, additional_items: AdditionalItems) SpecialProngs {
const else_bit: u3 = @intFromBool(has_else);
const under_bits: u3 = if (has_under)
@intFromEnum(additional_items)
else
@intFromEnum(SpecialProngs.none);
return @enumFromInt(else_bit | under_bits);
}
pub fn hasElse(special_prongs: SpecialProngs) bool {
return (@intFromEnum(special_prongs) & 0b001) != 0;
}
pub fn hasUnder(special_prongs: SpecialProngs) bool {
return (@intFromEnum(special_prongs) & 0b110) != 0;
}
pub fn hasAdditionalItems(special_prongs: SpecialProngs) bool {
return (@intFromEnum(special_prongs) & 0b100) != 0;
}
pub fn hasOneAdditionalItem(special_prongs: SpecialProngs) bool {
return (@intFromEnum(special_prongs) & 0b110) == @intFromEnum(SpecialProngs.under_one_item);
}
pub fn hasManyAdditionalItems(special_prongs: SpecialProngs) bool {
return (@intFromEnum(special_prongs) & 0b110) == @intFromEnum(SpecialProngs.under_many_items);
}
}; };
pub const DeclIterator = struct { pub const DeclIterator = struct {
@ -4723,7 +4779,7 @@ fn findTrackableSwitch(
} }
const has_special = switch (kind) { const has_special = switch (kind) {
.normal => extra.data.bits.special_prong != .none, .normal => extra.data.bits.special_prongs != .none,
.err_union => has_special: { .err_union => has_special: {
// Handle `non_err_body` first. // Handle `non_err_body` first.
const prong_info: Inst.SwitchBlock.ProngInfo = @bitCast(zir.extra[extra_index]); const prong_info: Inst.SwitchBlock.ProngInfo = @bitCast(zir.extra[extra_index]);
@ -4738,29 +4794,40 @@ fn findTrackableSwitch(
}; };
if (has_special) { if (has_special) {
const has_else = if (kind == .normal)
extra.data.bits.special_prongs.hasElse()
else
true;
if (has_else) {
const prong_info: Inst.SwitchBlock.ProngInfo = @bitCast(zir.extra[extra_index]);
extra_index += 1;
const body = zir.bodySlice(extra_index, prong_info.body_len);
extra_index += body.len;
try zir.findTrackableBody(gpa, contents, defers, body);
}
if (kind == .normal) { if (kind == .normal) {
if (extra.data.bits.special_prong == .absorbing_under) { const special_prongs = extra.data.bits.special_prongs;
const items_len = zir.extra[extra_index];
extra_index += 1;
const ranges_len = zir.extra[extra_index];
extra_index += 1;
const prong_info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(zir.extra[extra_index]);
extra_index += 1;
extra_index += items_len + ranges_len * 2;
if (special_prongs.hasUnder()) {
var trailing_items_len: u32 = 0;
if (special_prongs.hasOneAdditionalItem()) {
extra_index += 1;
} else if (special_prongs.hasManyAdditionalItems()) {
const items_len = zir.extra[extra_index];
extra_index += 1;
const ranges_len = zir.extra[extra_index];
extra_index += 1;
trailing_items_len = items_len + ranges_len * 2;
}
const prong_info: Inst.SwitchBlock.ProngInfo = @bitCast(zir.extra[extra_index]);
extra_index += 1 + trailing_items_len;
const body = zir.bodySlice(extra_index, prong_info.body_len); const body = zir.bodySlice(extra_index, prong_info.body_len);
extra_index += body.len; extra_index += body.len;
try zir.findTrackableBody(gpa, contents, defers, body); try zir.findTrackableBody(gpa, contents, defers, body);
} }
} }
const prong_info: Inst.SwitchBlock.ProngInfo = @bitCast(zir.extra[extra_index]);
extra_index += 1;
const body = zir.bodySlice(extra_index, prong_info.body_len);
extra_index += body.len;
try zir.findTrackableBody(gpa, contents, defers, body);
} }
{ {

File diff suppressed because it is too large Load Diff

View File

@ -1677,19 +1677,36 @@ pub const SrcLoc = struct {
return tree.nodeToSpan(condition); return tree.nodeToSpan(condition);
}, },
.node_offset_switch_special_prong => |node_off| { .node_offset_switch_else_prong => |node_off| {
const tree = try src_loc.file_scope.getTree(zcu); const tree = try src_loc.file_scope.getTree(zcu);
const switch_node = node_off.toAbsolute(src_loc.base_node); const switch_node = node_off.toAbsolute(src_loc.base_node);
_, const extra_index = tree.nodeData(switch_node).node_and_extra; _, const extra_index = tree.nodeData(switch_node).node_and_extra;
const case_nodes = tree.extraDataSlice(tree.extraData(extra_index, Ast.Node.SubRange), Ast.Node.Index); const case_nodes = tree.extraDataSlice(tree.extraData(extra_index, Ast.Node.SubRange), Ast.Node.Index);
for (case_nodes) |case_node| { for (case_nodes) |case_node| {
const case = tree.fullSwitchCase(case_node).?; const case = tree.fullSwitchCase(case_node).?;
if (case.isSpecial(tree)) |special_node| { if (case.ast.values.len == 0) {
return tree.tokensToSpan( return tree.nodeToSpan(case_node);
tree.firstToken(case_node), }
tree.lastToken(case_node), } else unreachable;
tree.nodeMainToken(special_node.unwrap() orelse case_node), },
);
.node_offset_switch_under_prong => |node_off| {
const tree = try src_loc.file_scope.getTree(zcu);
const switch_node = node_off.toAbsolute(src_loc.base_node);
_, const extra_index = tree.nodeData(switch_node).node_and_extra;
const case_nodes = tree.extraDataSlice(tree.extraData(extra_index, Ast.Node.SubRange), Ast.Node.Index);
for (case_nodes) |case_node| {
const case = tree.fullSwitchCase(case_node).?;
for (case.ast.values) |val| {
if (tree.nodeTag(val) == .identifier and
mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(val)), "_"))
{
return tree.tokensToSpan(
tree.firstToken(case_node),
tree.lastToken(case_node),
tree.nodeMainToken(val),
);
}
} }
} else unreachable; } else unreachable;
}, },
@ -1701,10 +1718,6 @@ pub const SrcLoc = struct {
const case_nodes = tree.extraDataSlice(tree.extraData(extra_index, Ast.Node.SubRange), Ast.Node.Index); const case_nodes = tree.extraDataSlice(tree.extraData(extra_index, Ast.Node.SubRange), Ast.Node.Index);
for (case_nodes) |case_node| { for (case_nodes) |case_node| {
const case = tree.fullSwitchCase(case_node).?; const case = tree.fullSwitchCase(case_node).?;
if (case.isSpecial(tree)) |maybe_else| {
if (maybe_else == .none) continue;
}
for (case.ast.values) |item_node| { for (case.ast.values) |item_node| {
if (tree.nodeTag(item_node) == .switch_range) { if (tree.nodeTag(item_node) == .switch_range) {
return tree.nodeToSpan(item_node); return tree.nodeToSpan(item_node);
@ -2109,32 +2122,35 @@ pub const SrcLoc = struct {
var multi_i: u32 = 0; var multi_i: u32 = 0;
var scalar_i: u32 = 0; var scalar_i: u32 = 0;
var found_special = false;
var underscore_node: Ast.Node.OptionalIndex = .none; var underscore_node: Ast.Node.OptionalIndex = .none;
const case = for (case_nodes) |case_node| { const case = case: for (case_nodes) |case_node| {
const case = tree.fullSwitchCase(case_node).?; const case = tree.fullSwitchCase(case_node).?;
const is_special = special: { if (case.ast.values.len == 0) {
if (found_special) break :special false; if (want_case_idx == LazySrcLoc.Offset.SwitchCaseIndex.special_else) {
if (case.isSpecial(tree)) |special_node| { break :case case;
underscore_node = special_node;
found_special = true;
break :special true;
} }
break :special false; continue :case;
};
if (is_special) {
if (want_case_idx == LazySrcLoc.Offset.SwitchCaseIndex.special) {
break case;
}
continue;
} }
if (underscore_node == .none) for (case.ast.values) |val_node| {
if (tree.nodeTag(val_node) == .identifier and
mem.eql(u8, tree.tokenSlice(tree.nodeMainToken(val_node)), "_"))
{
underscore_node = val_node.toOptional();
if (want_case_idx == LazySrcLoc.Offset.SwitchCaseIndex.special_under) {
break :case case;
}
continue :case;
}
};
const is_multi = case.ast.values.len != 1 or const is_multi = case.ast.values.len != 1 or
tree.nodeTag(case.ast.values[0]) == .switch_range; tree.nodeTag(case.ast.values[0]) == .switch_range;
switch (want_case_idx.kind) { switch (want_case_idx.kind) {
.scalar => if (!is_multi and want_case_idx.index == scalar_i) break case, .scalar => if (!is_multi and want_case_idx.index == scalar_i)
.multi => if (is_multi and want_case_idx.index == multi_i) break case, break :case case,
.multi => if (is_multi and want_case_idx.index == multi_i)
break :case case,
} }
if (is_multi) { if (is_multi) {
@ -2148,7 +2164,10 @@ pub const SrcLoc = struct {
.switch_case_item, .switch_case_item,
.switch_case_item_range_first, .switch_case_item_range_first,
.switch_case_item_range_last, .switch_case_item_range_last,
=> |x| x.item_idx, => |x| item_idx: {
assert(want_case_idx != LazySrcLoc.Offset.SwitchCaseIndex.special_else);
break :item_idx x.item_idx;
},
.switch_capture, .switch_tag_capture => { .switch_capture, .switch_tag_capture => {
const start = switch (src_loc.lazy) { const start = switch (src_loc.lazy) {
.switch_capture => case.payload_token.?, .switch_capture => case.payload_token.?,
@ -2369,10 +2388,14 @@ pub const LazySrcLoc = struct {
/// by taking this AST node index offset from the containing base node, /// by taking this AST node index offset from the containing base node,
/// which points to a switch expression AST node. Next, navigate to the operand. /// which points to a switch expression AST node. Next, navigate to the operand.
node_offset_switch_operand: Ast.Node.Offset, node_offset_switch_operand: Ast.Node.Offset,
/// The source location points to the else/`_` prong of a switch expression, found /// The source location points to the else prong of a switch expression, found
/// by taking this AST node index offset from the containing base node, /// by taking this AST node index offset from the containing base node,
/// which points to a switch expression AST node. Next, navigate to the else/`_` prong. /// which points to a switch expression AST node. Next, navigate to the else prong.
node_offset_switch_special_prong: Ast.Node.Offset, node_offset_switch_else_prong: Ast.Node.Offset,
/// The source location points to the `_` prong of a switch expression, found
/// by taking this AST node index offset from the containing base node,
/// which points to a switch expression AST node. Next, navigate to the `_` prong.
node_offset_switch_under_prong: Ast.Node.Offset,
/// The source location points to all the ranges of a switch expression, found /// The source location points to all the ranges of a switch expression, found
/// by taking this AST node index offset from the containing base node, /// by taking this AST node index offset from the containing base node,
/// which points to a switch expression AST node. Next, navigate to any of the /// which points to a switch expression AST node. Next, navigate to any of the
@ -2568,7 +2591,8 @@ pub const LazySrcLoc = struct {
kind: enum(u1) { scalar, multi }, kind: enum(u1) { scalar, multi },
index: u31, index: u31,
pub const special: SwitchCaseIndex = @bitCast(@as(u32, std.math.maxInt(u32))); pub const special_else: SwitchCaseIndex = @bitCast(@as(u32, std.math.maxInt(u32)));
pub const special_under: SwitchCaseIndex = @bitCast(@as(u32, std.math.maxInt(u32) - 1));
}; };
pub const SwitchItemIndex = packed struct(u32) { pub const SwitchItemIndex = packed struct(u32) {

View File

@ -2087,19 +2087,40 @@ const Writer = struct {
self.indent += 2; self.indent += 2;
else_prong: { const special_prongs = extra.data.bits.special_prongs;
const special_prong = extra.data.bits.special_prong;
if (special_prong == .none) break :else_prong;
if (special_prongs.hasElse()) {
const info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(self.code.extra[extra_index]);
const capture_text = switch (info.capture) {
.none => "",
.by_val => "by_val ",
.by_ref => "by_ref ",
};
const inline_text = if (info.is_inline) "inline " else "";
extra_index += 1;
const body = self.code.bodySlice(extra_index, info.body_len);
extra_index += body.len;
try stream.writeAll(",\n");
try stream.splatByteAll(' ', self.indent);
try stream.print("{s}{s}else => ", .{ capture_text, inline_text });
try self.writeBracedBody(stream, body);
}
if (special_prongs.hasUnder()) {
var single_item_ref: Zir.Inst.Ref = .none;
var items_len: u32 = 0; var items_len: u32 = 0;
var ranges_len: u32 = 0; var ranges_len: u32 = 0;
if (special_prong == .absorbing_under) { if (special_prongs.hasOneAdditionalItem()) {
single_item_ref = @enumFromInt(self.code.extra[extra_index]);
extra_index += 1;
} else if (special_prongs.hasManyAdditionalItems()) {
items_len = self.code.extra[extra_index]; items_len = self.code.extra[extra_index];
extra_index += 1; extra_index += 1;
ranges_len = self.code.extra[extra_index]; ranges_len = self.code.extra[extra_index];
extra_index += 1; extra_index += 1;
} }
const info = @as(Zir.Inst.SwitchBlock.ProngInfo, @bitCast(self.code.extra[extra_index])); const info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
const items = self.code.refSlice(extra_index, items_len); const items = self.code.refSlice(extra_index, items_len);
extra_index += items_len; extra_index += items_len;
@ -2112,12 +2133,12 @@ const Writer = struct {
.by_ref => try stream.writeAll("by_ref "), .by_ref => try stream.writeAll("by_ref "),
} }
if (info.is_inline) try stream.writeAll("inline "); if (info.is_inline) try stream.writeAll("inline ");
switch (special_prong) {
.@"else" => try stream.writeAll("else"),
.under, .absorbing_under => try stream.writeAll("_"),
.none => unreachable,
}
try stream.writeAll("_");
if (single_item_ref != .none) {
try stream.writeAll(", ");
try self.writeInstRef(stream, single_item_ref);
}
for (items) |item_ref| { for (items) |item_ref| {
try stream.writeAll(", "); try stream.writeAll(", ");
try self.writeInstRef(stream, item_ref); try self.writeInstRef(stream, item_ref);
@ -2125,9 +2146,9 @@ const Writer = struct {
var range_i: usize = 0; var range_i: usize = 0;
while (range_i < ranges_len) : (range_i += 1) { while (range_i < ranges_len) : (range_i += 1) {
const item_first = @as(Zir.Inst.Ref, @enumFromInt(self.code.extra[extra_index])); const item_first: Zir.Inst.Ref = @enumFromInt(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
const item_last = @as(Zir.Inst.Ref, @enumFromInt(self.code.extra[extra_index])); const item_last: Zir.Inst.Ref = @enumFromInt(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
try stream.writeAll(", "); try stream.writeAll(", ");
@ -2146,9 +2167,9 @@ const Writer = struct {
const scalar_cases_len = extra.data.bits.scalar_cases_len; const scalar_cases_len = extra.data.bits.scalar_cases_len;
var scalar_i: usize = 0; var scalar_i: usize = 0;
while (scalar_i < scalar_cases_len) : (scalar_i += 1) { while (scalar_i < scalar_cases_len) : (scalar_i += 1) {
const item_ref = @as(Zir.Inst.Ref, @enumFromInt(self.code.extra[extra_index])); const item_ref: Zir.Inst.Ref = @enumFromInt(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
const info = @as(Zir.Inst.SwitchBlock.ProngInfo, @bitCast(self.code.extra[extra_index])); const info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
const body = self.code.bodySlice(extra_index, info.body_len); const body = self.code.bodySlice(extra_index, info.body_len);
extra_index += info.body_len; extra_index += info.body_len;
@ -2173,7 +2194,7 @@ const Writer = struct {
extra_index += 1; extra_index += 1;
const ranges_len = self.code.extra[extra_index]; const ranges_len = self.code.extra[extra_index];
extra_index += 1; extra_index += 1;
const info = @as(Zir.Inst.SwitchBlock.ProngInfo, @bitCast(self.code.extra[extra_index])); const info: Zir.Inst.SwitchBlock.ProngInfo = @bitCast(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
const items = self.code.refSlice(extra_index, items_len); const items = self.code.refSlice(extra_index, items_len);
extra_index += items_len; extra_index += items_len;
@ -2194,9 +2215,9 @@ const Writer = struct {
var range_i: usize = 0; var range_i: usize = 0;
while (range_i < ranges_len) : (range_i += 1) { while (range_i < ranges_len) : (range_i += 1) {
const item_first = @as(Zir.Inst.Ref, @enumFromInt(self.code.extra[extra_index])); const item_first: Zir.Inst.Ref = @enumFromInt(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
const item_last = @as(Zir.Inst.Ref, @enumFromInt(self.code.extra[extra_index])); const item_last: Zir.Inst.Ref = @enumFromInt(self.code.extra[extra_index]);
extra_index += 1; extra_index += 1;
if (range_i != 0 or items.len != 0) { if (range_i != 0 or items.len != 0) {

View File

@ -1075,26 +1075,50 @@ test "switch on 8-bit mod result" {
} }
test "switch on non-exhaustive enum" { test "switch on non-exhaustive enum" {
const E = enum(u32) { if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest; // TODO
const E = enum(u4) {
a, a,
b, b,
c, c,
_, _,
fn doTheTest(e: @This()) !void {
switch (e) {
.a, .b => {},
else => return error.TestFailed,
}
switch (e) {
.a, .b => {},
.c => return error.TestFailed,
_ => return error.TestFailed,
}
switch (e) {
.a, .b => {},
.c, _ => return error.TestFailed,
}
switch (e) {
.a => {},
.b, .c, _ => return error.TestFailed,
}
switch (e) {
.b => return error.TestFailed,
else => {},
_ => return error.TestFailed,
}
switch (e) {
else => {},
_ => return error.TestFailed,
}
switch (e) {
inline else => {},
_ => return error.TestFailed,
}
}
}; };
var e: E = .a; var e: E = .a;
_ = &e; _ = &e;
switch (e) { try E.doTheTest(e);
.a, .b => {}, try comptime E.doTheTest(.a);
else => return error.TestFailed,
}
switch (e) {
.a, .b => {},
.c => return error.TestFailed,
_ => return error.TestFailed,
}
switch (e) {
.a, .b => {},
.c, _ => return error.TestFailed,
}
} }

View File

@ -249,3 +249,27 @@ test "switch loop on larger than pointer integer" {
} }
try expect(entry == 3); try expect(entry == 3);
} }
test "switch loop on non-exhaustive enum" {
if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
if (builtin.zig_backend == .stage2_spirv) return error.SkipZigTest; // TODO
const S = struct {
const E = enum(u8) { a, b, c, _ };
fn doTheTest() !void {
var start: E = undefined;
start = .a;
const result: u32 = s: switch (start) {
.a => continue :s .c,
else => continue :s @enumFromInt(123),
.b, _ => |x| break :s @intFromEnum(x),
};
try expect(result == 123);
}
};
try S.doTheTest();
try comptime S.doTheTest();
}

View File

@ -0,0 +1,27 @@
const E = enum(u8) {
a,
b,
_,
};
export fn f(e: E) void {
switch (e) {
.a => {},
inline _ => {},
}
}
export fn g(e: E) void {
switch (e) {
.a => {},
else => {},
inline _ => {},
}
}
// error
// backend=stage2
// target=native
//
// :10:16: error: cannot inline '_' prong
// :18:16: error: cannot inline '_' prong

View File

@ -0,0 +1,18 @@
const E = enum(u8) {
a,
b,
_,
};
export fn f(e: E) void {
switch (e) {
.a, .b, _ => {},
else => {},
}
}
// error
// backend=stage2
// target=native
//
// :10:14: error: unreachable else prong; all explicit cases already handled

View File

@ -37,7 +37,7 @@ pub export fn entry3() void {
// :12:5: error: switch must handle all possibilities // :12:5: error: switch must handle all possibilities
// :3:5: note: unhandled enumeration value: 'b' // :3:5: note: unhandled enumeration value: 'b'
// :1:11: note: enum 'tmp.E' declared here // :1:11: note: enum 'tmp.E' declared here
// :19:5: error: switch on non-exhaustive enum must include 'else' or '_' prong // :19:5: error: switch on non-exhaustive enum must include 'else' or '_' prong or both
// :26:5: error: '_' prong only allowed when switching on non-exhaustive enums // :26:5: error: '_' prong only allowed when switching on non-exhaustive enums
// :29:9: note: '_' prong here // :29:9: note: '_' prong here
// :26:5: note: consider using 'else' // :26:5: note: consider using 'else'