~starkingdoms/starkingdoms

ref: 426c4c005ea227b6953945c8bacb92575f5e392d starkingdoms/kabel/src/codegen.rs -rw-r--r-- 12.2 KiB
426c4c00 — ghostly_zsh basic break and continue but it doesn't quite work 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
use crate::{ast::{ASTType, BinOp, Lit, Name, UnOp, AST}, codegen_binary, codegen_unary, extension::Extension, opcodes::OpCode, vm::{Value, VM}};

pub struct Codegen {
    pub vm: VM,
    pub scopes: Vec<usize>, // number of variables declared in the scope
    break_stack: Vec<Vec<usize>>,
    continue_stack: Vec<Vec<usize>>,
}

impl Codegen {
    pub fn new(text: String) -> Self {
        Codegen {
            vm: VM::new(Vec::new(), Vec::new(),
                Vec::new(), text),
            scopes: vec![0],
            break_stack: Vec::new(),
            continue_stack: Vec::new(),
        }
    }
    pub fn visit(&mut self, ast: AST) {
        use crate::ast::ASTType::*;
        match ast.ast_type {
            Program(asts) => {
                for ast in asts {
                    self.visit(ast);
                }
            }
            While(condition, block) => {
                self.visit_while(*condition, *block);
            }
            Break => {
                self.visit_break(&ast);
            }
            Continue => {
                self.visit_continue(&ast);
            }
            If(condition, block, else_expr) => {
                self.visit_if(*condition, *block, *else_expr);
            }
            Block(ref stmts) => {
                self.visit_block(&ast, stmts.clone());
            }
            Decl(ref name, ref expr) => {
                self.visit_decl(&ast, name.clone(), *expr.clone());
            }
            Expr(ref expr) => {
                self.visit_expr_stmt(&ast, *expr.clone());
            }
            // REMOVE LATER
            Print(ref expr) => {
                self.visit_print(&ast, *expr.clone());
            }
            Assign(ref name, ref expr) => {
                self.visit_assign(&ast, name.clone(), *expr.clone());
            }
            Binary(left, oper, right) => {
                self.visit_binary(*left, oper, *right);
            }
            Unary(oper, right) => {
                self.visit_unary(oper, *right);
            }
            Lit(ref lit) => {
                self.visit_lit(&ast, lit.clone());
            }
            _ => {}
        }
    }
    pub fn visit_while(&mut self, condition: AST, block: AST) {
        self.break_stack.push(Vec::new());
        self.continue_stack.push(Vec::new());

        let end_jmp = self.vm.chunk.len();
        self.visit(condition.clone());
        self.vm.chunk.push(OpCode::JNE.into());
        self.vm.chunk.push(0xFF); // placeholder
        self.vm.chunk.push(0xFF); // placeholder
        let start_jmp_loc = self.vm.chunk.len()-2;
        if self.vm.lines.last().unwrap().0 != condition.end_line {
            self.vm.lines.push((condition.end_line, 3));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 3;
        }
        self.visit(block.clone());
        self.vm.chunk.push(OpCode::JMP_UP.into());
        let current = self.vm.chunk.len()+2;
        let current_to_start = current - end_jmp;
        self.vm.chunk.push(((current_to_start >> 8) & 0xFF) as u8);
        self.vm.chunk.push((current_to_start & 0xFF) as u8);
        if self.vm.lines.last().unwrap().0 != block.end_line {
            self.vm.lines.push((block.end_line, 3));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 3;
        }
        self.patch_jump(start_jmp_loc);

        let breaks = self.break_stack.pop().expect("break stack empty on pop");
        for loc in breaks {
            self.patch_jump(loc);
        }
        let continues = self.continue_stack.pop().expect("continue stack empty on pop");
        for loc in continues {
            let jump = loc - end_jmp - 2;
            self.vm.chunk[loc] = ((jump >> 8) & 0xFF) as u8;
            self.vm.chunk[loc + 1] = (jump & 0xFF) as u8;
        }
    }
    pub fn visit_break(&mut self, ast: &AST) {
        self.vm.chunk.push(OpCode::JMP.into());
        self.vm.chunk.push(0xFF);
        self.vm.chunk.push(0xFF);
        if self.vm.lines.last().unwrap().0 != ast.end_line {
            self.vm.lines.push((ast.end_line, 3));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 3;
        }
        self.break_stack.last_mut().expect("break not in a loop").push(self.vm.chunk.len()-2);
    }
    pub fn visit_continue(&mut self, ast: &AST) {
        self.vm.chunk.push(OpCode::JMP_UP.into());
        self.vm.chunk.push(0xFF);
        self.vm.chunk.push(0xFF);
        if self.vm.lines.last().unwrap().0 != ast.end_line {
            self.vm.lines.push((ast.end_line, 3));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 3;
        }
        self.continue_stack.last_mut().expect("continue not in a loop").push(self.vm.chunk.len()-2);
    }
    pub fn visit_if(&mut self, condition: AST, block: AST, else_expr: Option<AST>) {
        self.visit(condition.clone());
        self.vm.chunk.push(OpCode::JNE.into());
        self.vm.chunk.push(0xFF); // placeholder
        self.vm.chunk.push(0xFF); // placeholder
        let start_jmp_loc = self.vm.chunk.len()-2;
        if self.vm.lines.last().unwrap().0 != condition.end_line {
            self.vm.lines.push((condition.end_line, 3));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 3;
        }
        self.visit(block);
        if let Some(ast) = else_expr {
            match ast.ast_type {
                ASTType::If(_, _, _) => {
                    self.vm.chunk.push(OpCode::JMP.into());
                    self.vm.chunk.push(0xFF); // placeholder
                    self.vm.chunk.push(0xFF); // placeholder
                    let end_jmp_loc = self.vm.chunk.len()-2;
                    if self.vm.lines.last().unwrap().0 != ast.end_line {
                        self.vm.lines.push((ast.end_line, 3));
                    } else {
                        self.vm.lines.last_mut().unwrap().1 += 3;
                    }
                    
                    self.patch_jump(start_jmp_loc);
                    self.visit(ast);
                    self.patch_jump(end_jmp_loc);
                }
                ASTType::Block(_) => {

                    self.vm.chunk.push(OpCode::JMP.into());
                    self.vm.chunk.push(0xFF); // placeholder
                    self.vm.chunk.push(0xFF); // placeholder
                    if self.vm.lines.last().unwrap().0 != ast.end_line {
                        self.vm.lines.push((ast.end_line, 3));
                    } else {
                        self.vm.lines.last_mut().unwrap().1 += 3;
                    }
                    
                    let end_jmp_loc = self.vm.chunk.len()-2;
                    self.patch_jump(start_jmp_loc); // jmp to else
                    self.visit(ast);
                    self.patch_jump(end_jmp_loc); // jmp to after else
                }
                _ => { println!("unimplemented"); }
            }
        } else {
            self.patch_jump(start_jmp_loc);
        }
    }
    pub fn visit_block(&mut self, ast: &AST, stmts: Vec<AST>) {
        self.scopes.push(0);
        for stmt in stmts {
            self.visit(stmt);
        }
        let variables = self.scopes.pop().expect("popped scope in block");
        for _ in 0..variables {
            self.vm.chunk.push(OpCode::POP.into());
            if self.vm.lines.last().unwrap().0 != ast.end_line {
                self.vm.lines.push((ast.end_line, 1));
            } else {
                self.vm.lines.last_mut().unwrap().1 += 1;
            }
        }
    }
    pub fn visit_decl(&mut self, ast: &AST, _name: Name, expr: AST) {
        self.visit(expr);
        #[allow(irrefutable_let_patterns)]
        if let Extension::Resolution(_scope, _ptr) = ast.extensions[0] {
            *self.scopes.last_mut().expect("codegen scopes vec was empty") += 1;
        }
    }
    pub fn visit_expr_stmt(&mut self, ast: &AST, expr: AST) {
        self.visit(expr);
        self.vm.chunk.push(OpCode::POP.into());
        if self.vm.lines.last().unwrap().0 != ast.end_line {
            self.vm.lines.push((ast.end_line, 1));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 1;
        }
    }
    // REMOVE LATER
    pub fn visit_print(&mut self, ast: &AST, expr: AST) {
        self.visit(expr);
        self.vm.chunk.push(OpCode::PRINT.into());
        if self.vm.lines.last().unwrap().0 != ast.end_line {
            self.vm.lines.push((ast.end_line, 1));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 1;
        }
    }
    pub fn visit_assign(&mut self, ast: &AST, _name: Name, expr: AST) {
        self.visit(expr);
        // pop stack to get value. then find variable in stack. set variable to value.
        self.vm.chunk.push(OpCode::ASSIGN.into());
        #[allow(irrefutable_let_patterns)]
        if let Extension::Resolution(_scope, ptr) = ast.extensions[0] {
            self.vm.chunk.push(ptr as u8);
            if self.vm.lines.last().unwrap().0 != ast.end_line {
                self.vm.lines.push((ast.end_line, 1));
            } else {
                self.vm.lines.last_mut().unwrap().1 += 1;
            }
        }
        if self.vm.lines.last().unwrap().0 != ast.end_line {
            self.vm.lines.push((ast.end_line, 1));
        } else {
            self.vm.lines.last_mut().unwrap().1 += 1;
        }
    }
    pub fn visit_binary(&mut self, left: AST, oper: BinOp, right: AST) {
        use crate::ast::BinOp::*;
        codegen_binary!(self, left, right, oper, Add, ADD, Sub, SUB, Mul, MUL,
            Div, DIV, Mod, MOD, BitAnd, BITAND, BitXor, BITXOR, BitOr, BITOR,
            Eq, EQ, Ne, NE, Gr, GR, Ge, GE, Ls, LS, Le, LE, Or, OR, And, AND);
    }
    pub fn visit_unary(&mut self, oper: UnOp, right: AST) {
        use crate::ast::UnOp::*;
        codegen_unary!(self, right, oper, Not, NOT, Neg, NEG);
    }
    pub fn visit_lit(&mut self, ast: &AST, lit: Lit) {
        match lit {
            Lit::Num(value) => {
                self.vm.pool.push(Value::Num(value));
                self.vm.chunk.push(OpCode::LOAD.into());
                self.vm.chunk.push((self.vm.pool.len()-1) as u8);
                if self.vm.lines.len() == 0 || self.vm.lines.last().unwrap().0 != ast.end_line {
                    self.vm.lines.push((ast.end_line, 2));
                } else {
                    self.vm.lines.last_mut().unwrap().1 += 2;
                }
            }
            Lit::Str(value) => {
                self.vm.pool.push(Value::Str(value.into()));
                self.vm.chunk.push(OpCode::LOAD.into());
                self.vm.chunk.push((self.vm.pool.len()-1) as u8);
                if self.vm.lines.len() == 0 || self.vm.lines.last().unwrap().0 != ast.end_line {
                    self.vm.lines.push((ast.end_line, 2));
                } else {
                    self.vm.lines.last_mut().unwrap().1 += 2;
                }
            }
            Lit::Bool(value) => {
                self.vm.pool.push(Value::Bool(value));
                self.vm.chunk.push(OpCode::LOAD.into());
                self.vm.chunk.push((self.vm.pool.len()-1) as u8);
                if self.vm.lines.len() == 0 || self.vm.lines.last().unwrap().0 != ast.end_line {
                    self.vm.lines.push((ast.end_line, 2));
                } else {
                    self.vm.lines.last_mut().unwrap().1 += 2;
                }
            }
            Lit::Ident(_name) => {
                self.vm.chunk.push(OpCode::VAR.into());
                #[allow(irrefutable_let_patterns)]
                if let Extension::Resolution(_scope, ptr) = ast.extensions[0] {
                    /*println!("line: {} ptr: {} locals: {:?}", ast.end_line, ptr, self.locals);
                    let (_scope, slot) = self.locals.get(ptr).unwrap();
                    println!("slot: {}", *slot);
                    self.vm.chunk.push(*slot);*/
                    self.vm.chunk.push(ptr as u8);
                    if self.vm.lines.len() == 0 || self.vm.lines.last().unwrap().0 != ast.end_line {
                        self.vm.lines.push((ast.end_line, 2));
                    } else {
                        self.vm.lines.last_mut().unwrap().1 += 2;
                    }
                }
            }
            _ => {}
        }
    }
    pub fn patch_jump(&mut self, loc: usize) {
        let jump = self.vm.chunk.len() - loc - 2;

        self.vm.chunk[loc] = ((jump >> 8) & 0xFF) as u8;
        self.vm.chunk[loc + 1] = (jump & 0xFF) as u8;
    }
}