Removal of duplicate code when several switch clauses contain the same code
- Dominant language
- C++
- Stars
- 8.6k
- Forks
- 1k
- PR merge metrics
- No merged PRs in 30d
Description
When multiple clauses in a switch statement contain the same code, we can (at certain circumstances) merge the clauses together.
## Input
Consider the following C source code:
```c
#include
int main() {
int ch;
scanf("%d", &ch);
switch (ch) {
case 0:
case 1:
case 2:
case 3:
printf("d\n");
case 4:
printf("e\n");
case 5:
printf("f\n");
case 6:
printf("g\n"); break;
case 17:
printf("17\n"); break;
case 18:
printf("18\n"); break;
case 19:
printf("19\n"); break;
case 20:
printf("20\n"); break;
case 25:
printf("25\n"); break;
default:
printf("default\n"); break;
}
printf("after switch");
return 0;
}
```
Compile it with mingw32-x86-pe (`-O1`) to get [switch.exe](https://github.com/avast-tl/retdec/files/1706955/switch.zip).
## Run
Decompile `switch.exe`:
```sh
$ retdec-decompiler switch.exe
```
## Output
Slightly abridged:
```c
int32_t v1 = 0; // bp-20
scanf("%d", &v1);
switch (v1) {
default: {
puts("default");
break;
}
case 0: {
puts("d");
puts("e");
puts("f");
puts("g");
break;
}
case 1: {
puts("d");
puts("e");
puts("f");
puts("g");
break;
}
case 2: {
puts("d");
puts("e");
puts("f");
puts("g");
break;
}
case 3: {
puts("d");
}
...
```
## Expected output
Although the code is correct, it would be better if the duplicate code could be removed so it looks like the original code:
```c
switch (ch) {
case 0:
case 1:
case 2:
case 3:
printf("d\n");
case 4:
printf("e\n");
case 5:
printf("f\n");
case 6:
printf("g\n"); break;
...
```
Contributor guide
No contributing guide indexed for this repository
Research direction
Reproduce the issue with the supplied switch.exe using retdec-decompiler and compare its output with the expected fall-through switch. Trace the switch reconstruction path responsible for emitting repeated clauses. Done means equivalent adjacent clauses are represented without duplicate code while preserving fall-through behavior and the shown output shape.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, cpp
- Domain
- compilers, reverse-engineering
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100