1from .constant_folding import constant_folding_term
2from .constant_propogation import constant_propogation_term
3from .dead_code_elimination import dead_code_elimination_term
4from .syntax import Program
5
6
7def optimize_program_step(
8 program: Program,
9) -> tuple[Program, bool]:
10 propagated = Program(
11 parameters=program.parameters,
12 body=constant_propogation_term(program.body, {}),
13 )
14 folded = Program(
15 parameters=propagated.parameters,
16 body=constant_folding_term(propagated.body, {}),
17 )
18 eliminated = Program(
19 parameters=folded.parameters,
20 body=dead_code_elimination_term(folded.body, {}),
21 )
22 return eliminated, eliminated != program
23
24
25def optimize_program(
26 program: Program,
27) -> Program:
28 current = program
29 while True:
30 current, changed = optimize_program_step(current)
31 if not changed:
32 return current