jetcrab\bytecode/
generator.rs

1use crate::ast::node::Node;
2use crate::bytecode::expressions::{
3    ArithmeticCore, ArithmeticGenerator, AssignmentCore, AssignmentGenerator, ComparisonCore,
4    ComparisonGenerator, LogicalCore, LogicalGenerator, UnaryCore, UnaryGenerator,
5};
6use crate::bytecode::literals::{
7    ArrayCore, ArrayGenerator, FunctionLiteralCore, ObjectCore, ObjectGenerator,
8};
9use crate::bytecode::scope::{ConstantCore, ConstantManager, ScopeCore, ScopeManager};
10use crate::bytecode::statements::{
11    ClassCore, ClassGenerator, ControlFlowCore, ControlFlowGenerator, FunctionCore,
12    FunctionGenerator, VariableCore, VariableGenerator,
13};
14use crate::vm::instructions::Instruction;
15use crate::vm::types::{CodeAddress, ConstantIndex, LocalIndex};
16use std::collections::HashMap;
17
18pub struct BytecodeGenerator {
19    constants: Vec<String>,
20    constant_map: HashMap<String, ConstantIndex>,
21    instructions: Vec<Instruction>,
22    local_vars: HashMap<String, LocalIndex>,
23    next_local: usize,
24    loop_labels: Vec<CodeAddress>,
25    statement_labels: HashMap<String, CodeAddress>,
26    current_labels: Vec<String>,
27}
28
29impl BytecodeGenerator {
30    pub fn new() -> Self {
31        Self {
32            constants: Vec::new(),
33            constant_map: HashMap::new(),
34            instructions: Vec::new(),
35            local_vars: HashMap::new(),
36            next_local: 0,
37            loop_labels: Vec::new(),
38            statement_labels: HashMap::new(),
39            current_labels: Vec::new(),
40        }
41    }
42}
43
44impl Default for BytecodeGenerator {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl BytecodeGenerator {
51    pub fn generate(&mut self, ast: &Node) -> Vec<Instruction> {
52        self.visit_node(ast);
53        self.instructions.clone()
54    }
55
56    pub fn get_constants(&self) -> &Vec<String> {
57        <Self as ConstantManager>::get_constants(self)
58    }
59
60    fn visit_node(&mut self, node: &Node) {
61        match node {
62            Node::Program(program) => {
63                for stmt in &program.body {
64                    self.visit_node(stmt);
65                }
66            }
67            Node::VariableDeclaration(_decl) => {
68                <Self as VariableGenerator>::generate_variable_declaration(self, node);
69            }
70            Node::FunctionDeclaration(_decl) => {
71                <Self as FunctionGenerator>::generate_function_declaration(self, node);
72            }
73            Node::ClassDeclaration(_decl) => {
74                <Self as ClassGenerator>::generate_class_declaration(self, node);
75            }
76            Node::ImportDeclaration(_stmt) => {
77                <Self as ControlFlowGenerator>::generate_import_declaration(self, node);
78            }
79            Node::ExportDeclaration(_stmt) => {
80                <Self as ControlFlowGenerator>::generate_export_declaration(self, node);
81            }
82            Node::ClassExpression(_expr) => {
83                <Self as ClassGenerator>::generate_class_expression(self, node);
84            }
85            Node::YieldExpression(expr) => {
86                if let Some(arg) = &expr.argument {
87                    self.visit_node(arg);
88                }
89                self.instructions.push(Instruction::Yield);
90            }
91            Node::AwaitExpression(expr) => {
92                self.visit_node(&expr.argument);
93                self.instructions.push(Instruction::Await);
94            }
95            Node::SwitchStatement(_stmt) => {
96                <Self as ControlFlowGenerator>::generate_switch_statement(self, node);
97            }
98            Node::TryStatement(_stmt) => {
99                <Self as ControlFlowGenerator>::generate_try_statement(self, node);
100            }
101            Node::CatchClause(_clause) => {
102                <Self as ControlFlowGenerator>::generate_catch_clause(self, node);
103            }
104            Node::ThrowStatement(_stmt) => {
105                <Self as ControlFlowGenerator>::generate_throw_statement(self, node);
106            }
107            Node::ReturnStatement(_stmt) => {
108                <Self as ControlFlowGenerator>::generate_return_statement(self, node);
109            }
110            Node::BreakStatement(_) => {
111                <Self as ControlFlowGenerator>::generate_break_statement(self, node);
112            }
113            Node::ContinueStatement(_) => {
114                <Self as ControlFlowGenerator>::generate_continue_statement(self, node);
115            }
116            Node::LabeledStatement(_stmt) => {
117                <Self as ControlFlowGenerator>::generate_labeled_statement(self, node);
118            }
119            Node::WithStatement(stmt) => {
120                self.visit_node(&stmt.object);
121                self.visit_node(&stmt.body);
122            }
123            Node::DebuggerStatement(_) => {}
124            Node::TemplateLiteral(lit) => {
125                for expr in &lit.expressions {
126                    self.visit_node(expr);
127                }
128            }
129            Node::TaggedTemplateExpression(expr) => {
130                self.visit_node(&expr.tag);
131                self.visit_node(&expr.quasi);
132            }
133            Node::Super(_) => {
134                self.instructions
135                    .push(Instruction::LoadLocal(LocalIndex::new(0)));
136            }
137            Node::MetaProperty(prop) => {
138                self.visit_node(&prop.meta);
139                self.visit_node(&prop.property);
140
141                self.instructions.push(Instruction::LoadThisFunction);
142            }
143            Node::SpreadElement(elem) => {
144                self.visit_node(&elem.argument);
145                self.instructions.push(Instruction::Spread);
146            }
147            Node::RegExp(re) => {
148                let constant_id = <Self as ConstantManager>::add_constant(self, re.pattern.clone());
149                self.instructions.push(Instruction::PushConst(constant_id));
150            }
151            Node::BigInt(val) => {
152                let constant_id = <Self as ConstantManager>::add_constant(self, val.clone());
153                self.instructions.push(Instruction::PushBigInt(constant_id));
154            }
155            Node::BinaryExpression(expr) => {
156                // Use ComparisonGenerator for comparison operators
157                match expr.operator.as_str() {
158                    "==" | "!=" | "===" | "!==" | "<" | ">" | "<=" | ">=" => {
159                        <Self as ComparisonGenerator>::generate_comparison_expression(self, node);
160                    }
161                    // Use ArithmeticGenerator for arithmetic operators
162                    "+" | "-" | "*" | "/" | "%" | "**" => {
163                        <Self as ArithmeticGenerator>::generate_binary_expression(self, node);
164                    }
165                    // Use LogicalGenerator for logical operators
166                    "&&" | "||" | "??" => {
167                        <Self as LogicalGenerator>::generate_logical_expression(self, node);
168                    }
169                    // Default to arithmetic for unknown operators
170                    _ => {
171                        <Self as ArithmeticGenerator>::generate_binary_expression(self, node);
172                    }
173                }
174            }
175            Node::UnaryExpression(_expr) => {
176                <Self as UnaryGenerator>::generate_unary_expression(self, node);
177            }
178            Node::CallExpression(_expr) => {
179                <Self as AssignmentGenerator>::generate_call_expression(self, node);
180            }
181            Node::NewExpression(_expr) => {
182                <Self as AssignmentGenerator>::generate_new_expression(self, node);
183            }
184            Node::MemberExpression(_expr) => {
185                <Self as AssignmentGenerator>::generate_member_expression(self, node);
186            }
187            Node::AssignmentExpression(_expr) => {
188                <Self as AssignmentGenerator>::generate_assignment_expression(self, node);
189            }
190            Node::ConditionalExpression(_expr) => {
191                <Self as AssignmentGenerator>::generate_conditional_expression(self, node);
192            }
193            Node::LogicalExpression(_expr) => {
194                <Self as LogicalGenerator>::generate_logical_expression(self, node);
195            }
196            Node::UpdateExpression(_expr) => {
197                <Self as UnaryGenerator>::generate_update_expression(self, node);
198            }
199            Node::ArrowFunctionExpression(expr) => {
200                for param in &expr.params {
201                    self.visit_node(param);
202                }
203                self.visit_node(&expr.body);
204            }
205            Node::FunctionExpression(_expr) => {
206                <Self as FunctionGenerator>::generate_function_expression(self, node);
207            }
208            Node::BlockStatement(stmt) => {
209                for node in &stmt.body {
210                    self.visit_node(node);
211                }
212            }
213            Node::IfStatement(_stmt) => {
214                <Self as ControlFlowGenerator>::generate_if_statement(self, node);
215            }
216            Node::ForStatement(_stmt) => {
217                <Self as ControlFlowGenerator>::generate_for_statement(self, node);
218            }
219            Node::ForInStatement(_stmt) => {
220                <Self as ControlFlowGenerator>::generate_for_in_statement(self, node);
221            }
222            Node::ForOfStatement(_stmt) => {
223                <Self as ControlFlowGenerator>::generate_for_of_statement(self, node);
224            }
225            Node::WhileStatement(_stmt) => {
226                <Self as ControlFlowGenerator>::generate_while_statement(self, node);
227            }
228            Node::DoWhileStatement(_stmt) => {
229                <Self as ControlFlowGenerator>::generate_do_while_statement(self, node);
230            }
231            Node::ExpressionStatement(stmt) => {
232                self.visit_node(&stmt.expression);
233            }
234            Node::ArrayLiteral(_lit) => {
235                <Self as ArrayGenerator>::generate_array_literal(self, node);
236            }
237            Node::ObjectLiteral(_lit) => {
238                <Self as ObjectGenerator>::generate_object_literal(self, node);
239            }
240            Node::Property(prop) => {
241                self.visit_node(&prop.key);
242                self.visit_node(&prop.value);
243            }
244            Node::RestElement(elem) => {
245                self.visit_node(&elem.argument);
246            }
247            Node::Identifier(name) => {
248                if let Some(&local_idx) = <Self as ScopeManager>::get_local(self, name) {
249                    self.instructions.push(Instruction::LoadLocal(local_idx));
250                } else {
251                    let constant_id = <Self as ConstantManager>::add_constant(self, name.clone());
252                    self.instructions.push(Instruction::PushConst(constant_id));
253                }
254            }
255            Node::Number(n) => {
256                let constant_id = <Self as ConstantManager>::add_constant(self, n.to_string());
257                self.instructions.push(Instruction::PushConst(constant_id));
258            }
259            Node::String(s) => {
260                // Store string literals with quotes to distinguish from numbers
261                let quoted_string = format!("\"{}\"", s);
262                let constant_id = <Self as ConstantManager>::add_constant(self, quoted_string);
263                self.instructions.push(Instruction::PushConst(constant_id));
264            }
265            Node::Boolean(b) => {
266                if *b {
267                    self.instructions.push(Instruction::PushTrue);
268                } else {
269                    self.instructions.push(Instruction::PushFalse);
270                }
271            }
272            Node::Null => {
273                self.instructions.push(Instruction::PushNull);
274            }
275            Node::Undefined => {
276                self.instructions.push(Instruction::PushUndefined);
277            }
278            Node::This => {
279                self.instructions.push(Instruction::LoadThis);
280            }
281        }
282    }
283}
284
285impl ConstantCore for BytecodeGenerator {
286    fn constants(&self) -> &Vec<String> {
287        &self.constants
288    }
289
290    fn constant_map(&self) -> &HashMap<String, ConstantIndex> {
291        &self.constant_map
292    }
293
294    fn constants_mut(&mut self) -> &mut Vec<String> {
295        &mut self.constants
296    }
297
298    fn constant_map_mut(&mut self) -> &mut HashMap<String, ConstantIndex> {
299        &mut self.constant_map
300    }
301}
302
303impl ScopeCore for BytecodeGenerator {
304    fn local_vars(&self) -> &HashMap<String, LocalIndex> {
305        &self.local_vars
306    }
307
308    fn local_vars_mut(&mut self) -> &mut HashMap<String, LocalIndex> {
309        &mut self.local_vars
310    }
311
312    fn next_local(&self) -> usize {
313        self.next_local
314    }
315
316    fn set_next_local(&mut self, next: usize) {
317        self.next_local = next;
318    }
319}
320
321impl VariableCore for BytecodeGenerator {
322    fn instructions(&mut self) -> &mut Vec<Instruction> {
323        &mut self.instructions
324    }
325
326    fn visit_node(&mut self, node: &Node) {
327        BytecodeGenerator::visit_node(self, node)
328    }
329}
330
331
332
333
334
335impl ClassCore for BytecodeGenerator {
336    fn instructions(&mut self) -> &mut Vec<Instruction> {
337        &mut self.instructions
338    }
339
340    fn visit_node(&mut self, node: &Node) {
341        BytecodeGenerator::visit_node(self, node)
342    }
343}
344
345impl ControlFlowCore for BytecodeGenerator {
346    fn instructions(&mut self) -> &mut Vec<Instruction> {
347        &mut self.instructions
348    }
349
350    fn visit_node(&mut self, node: &Node) {
351        BytecodeGenerator::visit_node(self, node)
352    }
353
354    fn push_loop_label(&mut self, break_address: CodeAddress) {
355        self.loop_labels.push(break_address);
356    }
357
358    fn pop_loop_label(&mut self) {
359        self.loop_labels.pop();
360    }
361
362    fn get_current_break_address(&self) -> Option<CodeAddress> {
363        self.loop_labels.last().copied()
364    }
365}
366
367impl crate::bytecode::statements::control_flow::LabelManager for BytecodeGenerator {
368    fn add_label(&mut self, name: String, address: CodeAddress) {
369        self.statement_labels.insert(name, address);
370    }
371
372    fn get_label_address(&self, name: &str) -> Option<CodeAddress> {
373        self.statement_labels.get(name).copied()
374    }
375
376    fn get_label_start_address(&self, label_name: &str) -> Option<CodeAddress> {
377        self.statement_labels.get(&format!("{}_start", label_name)).copied()
378    }
379
380    fn get_label_end_address(&self, label_name: &str) -> Option<CodeAddress> {
381        self.statement_labels.get(&format!("{}_end", label_name)).copied()
382    }
383
384    fn push_current_label(&mut self, name: String) {
385        self.current_labels.push(name);
386    }
387
388    fn pop_current_label(&mut self) {
389        self.current_labels.pop();
390    }
391
392    fn get_current_labels(&self) -> &[String] {
393        &self.current_labels
394    }
395}
396
397impl ArithmeticCore for BytecodeGenerator {
398    fn instructions(&mut self) -> &mut Vec<Instruction> {
399        &mut self.instructions
400    }
401
402    fn visit_node(&mut self, node: &Node) {
403        BytecodeGenerator::visit_node(self, node)
404    }
405}
406
407impl ComparisonCore for BytecodeGenerator {
408    fn instructions(&mut self) -> &mut Vec<Instruction> {
409        &mut self.instructions
410    }
411
412    fn visit_node(&mut self, node: &Node) {
413        BytecodeGenerator::visit_node(self, node)
414    }
415}
416
417impl LogicalCore for BytecodeGenerator {
418    fn instructions(&mut self) -> &mut Vec<Instruction> {
419        &mut self.instructions
420    }
421
422    fn visit_node(&mut self, node: &Node) {
423        BytecodeGenerator::visit_node(self, node)
424    }
425}
426
427impl UnaryCore for BytecodeGenerator {
428    fn instructions(&mut self) -> &mut Vec<Instruction> {
429        &mut self.instructions
430    }
431
432    fn visit_node(&mut self, node: &Node) {
433        BytecodeGenerator::visit_node(self, node)
434    }
435}
436
437impl AssignmentCore for BytecodeGenerator {
438    fn instructions(&mut self) -> &mut Vec<Instruction> {
439        &mut self.instructions
440    }
441
442    fn visit_node(&mut self, node: &Node) {
443        BytecodeGenerator::visit_node(self, node)
444    }
445}
446
447impl ObjectCore for BytecodeGenerator {
448    fn instructions(&mut self) -> &mut Vec<Instruction> {
449        &mut self.instructions
450    }
451
452    fn visit_node(&mut self, node: &Node) {
453        BytecodeGenerator::visit_node(self, node)
454    }
455}
456
457impl ArrayCore for BytecodeGenerator {
458    fn instructions(&mut self) -> &mut Vec<Instruction> {
459        &mut self.instructions
460    }
461
462    fn visit_node(&mut self, node: &Node) {
463        BytecodeGenerator::visit_node(self, node)
464    }
465}
466
467impl FunctionLiteralCore for BytecodeGenerator {
468    fn instructions(&mut self) -> &mut Vec<Instruction> {
469        &mut self.instructions
470    }
471
472    fn visit_node(&mut self, node: &Node) {
473        BytecodeGenerator::visit_node(self, node)
474    }
475}
476
477impl FunctionCore for BytecodeGenerator {
478    fn instructions(&mut self) -> &mut Vec<Instruction> {
479        &mut self.instructions
480    }
481
482    fn visit_node(&mut self, node: &Node) {
483        BytecodeGenerator::visit_node(self, node)
484    }
485}