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

Convert switch to if-else conditions #127

Merged
merged 7 commits into from
Jul 27, 2023
Merged

Convert switch to if-else conditions #127

merged 7 commits into from
Jul 27, 2023

Conversation

milenaaluisa
Copy link
Contributor

Added the TransformSwitchToIf class which converts a switch statement like this:

int num = 1, a;

switch (num) {
    case 1:
        a = 10;
    default:
        a = 80;
        break;
    case 2:
        a = 20;
        break;
    case 3 ... 7:
        a = 30;
}

Into this:

int num = 1, a;

if (num == 1) 
    goto case_1;
else if (num == 2) 
    goto case_2;
else if (num >= 3 && num <= 7) 
    goto case_3_7;
else 
    goto case_default;

case_1:
    a = 10;
case_default:
    a = 80;
    goto switch_exit;
case_2:
    a = 20;
    goto switch_exit;
case_3_7:
    a = 30;
    
switch_exit:
;

Note:

  • To avoid adding duplicate labels to the AST when dealing with multiple switch statements, the label name of the switch exit and case statement actually contains its astId (e.g: switch_exit_0x14fb5a5b0b8, case_0x14fb5a5b120)
  • Since the switch statement of the given example is the last child of its parent node, an empty statement was inserted after the switch_exit label:
// ...

switch_exit:
;   // the empty statement

@joaobispo joaobispo merged commit 7b45c5d into staging Jul 27, 2023
2 checks passed
@joaobispo joaobispo deleted the switch-to-if branch July 27, 2023 19:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants