Skip to content

Commit

Permalink
Merge pull request #134 from xdufour/xd/bodiless_switch
Browse files Browse the repository at this point in the history
Add support for switch with case statement instead of block statement
  • Loading branch information
laurenthuberdeau authored Feb 19, 2025
2 parents e54d2ce + 263d423 commit bc734b4
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 2 deletions.
8 changes: 7 additions & 1 deletion sh.c
Original file line number Diff line number Diff line change
Expand Up @@ -1866,8 +1866,14 @@ bool comp_switch(ast node) {

node = get_child_(SWITCH_KW, node, 1);

if (node == 0 || get_op(node) != '{') fatal_error("comp_statement: switch without body");
if(get_op(node) == CASE_KW) {
// This is for the edge case where the entire 'statement' part of < switch ( expression ) statement >
// is a single < case constant-expression : statement >
// therefore we wrap the case statement with a block statement to simplify down to the typical syntax
node = new_ast2('{', node, 0);
}

if (node == 0 || get_op(node) != '{') fatal_error("comp_statement: switch without body");
while (get_op(node) == '{') {
statement = get_child_('{', node, 0);
node = get_child_('{', node, 1);
Expand Down
12 changes: 12 additions & 0 deletions tests/_exe/switch.c
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,17 @@ void state_machine_switch() {
}
}

void bodiless_switch() {
switch (123)
case 123:
putchar('E');

switch (456)
case 123:
case 456:
putchar('E');
}

int main() {
empty_switch(); putchar('\n');
no_case_switch(); putchar('\n');
Expand All @@ -229,5 +240,6 @@ int main() {
duff_device_switch(15); putchar('\n');
state_machine_switch();
state_machine_switch(); putchar('\n');
bodiless_switch(); putchar('\n');
return 0;
}
1 change: 1 addition & 0 deletions tests/_exe/switch.golden
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ ABCDE
DT
BCDEFGHABCDEFGH
ABA
EE
12 changes: 12 additions & 0 deletions tests/_sh/switch.c
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,21 @@ void switch_in_while(){
}
}

void bodiless_switch() {
switch (123)
case 123:
putchar('F');

switch (456)
case 123:
case 456:
putchar('E');
}

void main() {
simple_switch();
simple_switch_fall_through();
multiple_labels();
switch_in_while();
bodiless_switch();
}
2 changes: 1 addition & 1 deletion tests/_sh/switch.golden
Original file line number Diff line number Diff line change
@@ -1 +1 @@
BCCBABCDE
BCCBABCDEFE

0 comments on commit bc734b4

Please sign in to comment.