udem-dlteam / pnut

🥜 A Self-Compiling C Transpiler Targeting Human-Readable POSIX Shell
https://pnut.sh
BSD 2-Clause "Simplified" License
424 stars 14 forks source link

Simplify shell switch code #102

Closed laurenthuberdeau closed 2 months ago

laurenthuberdeau commented 2 months ago

Context

The comp_statement and comp_switch_block_statement functions overlapped and it seemed like a good opportunity to reduce the code size while making the code more maintainable. This PR:

  1. Refactors comp_statement to make it shorter and reuse code for loops (while, do_while, for)
  2. Fixes the buggy empty-block detection logic. Since loops all uses the same function, it reduces the complexity of the code and is more correct
  3. Finally with the simplified comp_statement function, it was merged with comp_switch_block_statement by making comp_statement and other similar functions return whether or not the statement always returns/breaks.

Size comparison

Main

########## pnut-sh ##########
By file:
    3254   10565   81486 pnut.c
    2566   12447  101364 sh.c
     922    4010   36979 sh-runtime.c
    6742   27022  219829 total
By file (without comments or blank lines):
    2447    7670   63850 build/measure/pnut.c
    1997    8807   79394 build/measure/sh.c
     865    3808   35540 build/measure/sh-runtime.c
    5309   20285  178784 total
Expanded includes:
    6742   27018  219791 build/measure/pnut-sh.c
    7218   31490  232088 build/measure/pnut-sh.sh
Ratio (Original): 7218/6742 = 1.070
Ratio (Cleaned):  7218/5309 = 1.359

This branch

########## pnut-sh ##########
By file:
    3254   10565   81486 pnut.c
    2585   12722  102762 sh.c
     922    4010   36979 sh-runtime.c
    6761   27297  221227 total
By file (without comments or blank lines):
    2447    7670   63850 build/measure/pnut.c
    1983    8718   78727 build/measure/sh.c
     865    3808   35540 build/measure/sh-runtime.c
    5295   20196  178117 total
Expanded includes:
    6761   27293  221189 build/measure/pnut-sh.c
    7189   31394  231608 build/measure/pnut-sh.sh
Ratio (Original): 7189/6761 = 1.063
Ratio (Cleaned):  7189/5295 = 1.357