Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for switch with case statement instead of block statement #134

Merged
merged 6 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading