You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Translate switch with default case in the middle (#30)
This PR handles code as:
```cpp
// tests/unit/switch_default_middle.cpp
int default_middle(int x) {
int r = 0;
switch (x) {
case 1:
r = 1;
break;
default:
r = 99;
break;
case 2:
r = 2;
break;
}
return r;
}
```
In rust, the default arm has to be the last arm, otherwise, arms
following the default one will be ignored, making this assertion fail
`assert(default_middle(2) == 2)`. Hence, the rust translation becomes:
```rs
match x {
v if v == 1 => {
r = 1;
}
v if v == 2 => {
r = 2;
}
_ => {
r = 99;
}
}
```
This is achieved by iterating over all top-level case statements in
VisitSwitchStmt and deferring the translation of the default arm until
every othter arm is translated. A top-level case statement is defined
as:
```cpp
switch (x) {
case TOP_LEVEL_STMT_1:
case NOT_TOP_LEVEL_STMT_1:
default: // not top level as well
...
break;
case TOP_LEVEL_STMT_2:
case NOT_TOP_LEVEL_STMT_2:
...
break
}
```
Furthermore, chains of case statements that contain a default statement
are reduced to default, effectively making the above code translate as:
```rs
match x {
v if v == TOP_LEVEL_STMT_2 || v == NOT_TOP_LEVEL_STMT_2 => {}
_ => {} // TOP_LEVEL_STMT_1, NOT_TOP_LEVEL_STMT_1, default was reduced to default
}
```
0 commit comments