1use crate::bytecode::optimizer::BytecodeOptimizer;
2use crate::bytecode::BytecodeGenerator;
3
4use crate::parser::Parser;
5use crate::semantic::SemanticAnalyzer;
6use crate::vm::instructions::Instruction;
7
8#[derive(Clone)]
9pub struct Compiler {
10 optimize: bool,
11}
12
13impl Default for Compiler {
14 fn default() -> Self {
15 Self::new()
16 }
17}
18
19impl Compiler {
20 pub fn new() -> Self {
21 Self { optimize: false }
22 }
23
24 pub fn with_optimization(mut self, optimize: bool) -> Self {
25 self.optimize = optimize;
26 self
27 }
28
29 pub fn compile(&mut self, source: &str) -> Result<Vec<Instruction>, String> {
30 let mut parser = Parser::new(source);
31 let ast = parser.parse().map_err(|e| format!("Parser error: {e}"))?;
32
33 let mut analyzer = SemanticAnalyzer::new();
34 analyzer
35 .analyze(&ast)
36 .map_err(|e| format!("Semantic error: {e}"))?;
37
38 let mut generator = BytecodeGenerator::new();
39 let mut instructions = generator.generate(&ast);
40
41 if self.optimize {
42 instructions = BytecodeOptimizer::optimize(instructions);
43 }
44
45 Ok(instructions)
46 }
47
48 pub fn compile_to_bytecode(
49 &mut self,
50 source: &str,
51 ) -> Result<(Vec<Instruction>, Vec<String>), String> {
52 let mut parser = Parser::new(source);
53 let ast = parser.parse().map_err(|e| format!("Parser error: {e}"))?;
54
55 let mut analyzer = SemanticAnalyzer::new();
56 analyzer
57 .analyze(&ast)
58 .map_err(|e| format!("Semantic error: {e}"))?;
59
60 let mut generator = BytecodeGenerator::new();
61 let mut instructions = generator.generate(&ast);
62 let constants = generator.get_constants().clone();
63
64 if self.optimize {
65 instructions = BytecodeOptimizer::optimize(instructions);
66 }
67
68 Ok((instructions, constants))
69 }
70}