From ce10c140c6b6975c5d543b8e6a5bac5bdd6a6939 Mon Sep 17 00:00:00 2001 From: Denys Smirnov Date: Sat, 9 Nov 2024 14:48:59 +0200 Subject: [PATCH] cxgo: Fix panic in switch with unreachable stmt. Fixes #80. --- c_stmt.go | 7 ++++++- parse_test.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/c_stmt.go b/c_stmt.go index 7723679..474fdec 100644 --- a/c_stmt.go +++ b/c_stmt.go @@ -358,7 +358,12 @@ func (s *CSwitchStmt) addStmts(stmts []CStmt) { s.addStmts(sub) } } else { - last := s.Cases[len(s.Cases)-1] + ci := len(s.Cases) - 1 + if ci < 0 { + // statement before any cases - ignore + continue + } + last := s.Cases[ci] last.Stmts = append(last.Stmts, st) } } diff --git a/parse_test.go b/parse_test.go index b364ae6..cf59f5c 100644 --- a/parse_test.go +++ b/parse_test.go @@ -150,6 +150,62 @@ func foo(a int32) { foo(6) } } +`, + }, + { + name: "switch unreachable", + src: ` +void foo(int a) { + switch (a) { + a++; + case 1: + foo(1); + break; + a++; + case 2: + foo(2); + default: + foo(0); + case 3: + foo(3); + break; + case 4: + case 5: + foo(5); + return; + a++; + case 6: + foo(6); + } +} +`, + exp: ` +func foo(a int32) { + switch a { + case 1: + foo(1) + break + a++ + fallthrough + case 2: + foo(2) + fallthrough + default: + foo(0) + fallthrough + case 3: + foo(3) + case 4: + fallthrough + case 5: + foo(5) + return + a++ + fallthrough + case 6: + foo(6) + } +} `, }, {