From 59bc1d272120bd860cc3cd1f894a2a4e08fc1f3f Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Wed, 29 Jan 2020 19:08:15 +0100 Subject: [PATCH] Fix edge case in switch with single else ir_gen_switch_expr doesn't set the switch_br field at all if there are zero cases, detect this situation and handle it gracefully. Closes #4322 --- src/ir.cpp | 4 +++- test/stage1/behavior/switch.zig | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/ir.cpp b/src/ir.cpp index fb7613cf90..149c8fbdc9 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -22768,7 +22768,9 @@ static IrInstGen *ir_analyze_instruction_switch_else_var(IrAnalyze *ira, } // Make note of the errors handled by other cases ErrorTableEntry **errors = allocate(ira->codegen->errors_by_index.length); - for (size_t case_i = 0; case_i < instruction->switch_br->case_count; case_i += 1) { + // We may not have any case in the switch if this is a lone else + const size_t switch_cases = instruction->switch_br ? instruction->switch_br->case_count : 0; + for (size_t case_i = 0; case_i < switch_cases; case_i += 1) { IrInstSrcSwitchBrCase *br_case = &instruction->switch_br->cases[case_i]; IrInstGen *case_expr = br_case->value->child; if (case_expr->value->type->id == ZigTypeIdErrorSet) { diff --git a/test/stage1/behavior/switch.zig b/test/stage1/behavior/switch.zig index 3cfab63f86..4e33d6505f 100644 --- a/test/stage1/behavior/switch.zig +++ b/test/stage1/behavior/switch.zig @@ -479,3 +479,17 @@ test "switch on pointer type" { comptime expect(2 == S.doTheTest(S.P2)); comptime expect(3 == S.doTheTest(S.P3)); } + +test "switch on error set with single else" { + const S = struct { + fn doTheTest() void { + var some: error{Foo} = error.Foo; + expect(switch (some) { + else => |a| true, + }); + } + }; + + S.doTheTest(); + comptime S.doTheTest(); +}