jetcrab\bytecode/
optimizer.rs

1use crate::vm::instructions::Instruction;
2
3pub struct BytecodeOptimizer;
4
5impl BytecodeOptimizer {
6    pub fn optimize(instructions: Vec<Instruction>) -> Vec<Instruction> {
7        let mut optimized = instructions;
8
9        optimized = Self::remove_dead_code(optimized);
10        optimized = Self::constant_folding(optimized);
11        optimized = Self::peephole_optimization(optimized);
12
13        optimized
14    }
15
16    fn remove_dead_code(instructions: Vec<Instruction>) -> Vec<Instruction> {
17        let mut result = Vec::new();
18        let mut i = 0;
19
20        while i < instructions.len() {
21            let instruction = &instructions[i];
22
23            match instruction {
24                Instruction::Pop => {
25                    if let Some(Instruction::PushConst(_)) = result.last() {
26                        result.pop();
27                    } else {
28                        result.push(instruction.clone());
29                    }
30                }
31                _ => {
32                    result.push(instruction.clone());
33                }
34            }
35
36            i += 1;
37        }
38
39        result
40    }
41
42    fn constant_folding(instructions: Vec<Instruction>) -> Vec<Instruction> {
43        instructions
44    }
45
46    fn peephole_optimization(instructions: Vec<Instruction>) -> Vec<Instruction> {
47        instructions
48    }
49}