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
//! Provides a compiler for executing a program
//! and running in the virtual machine.
//!
//! Example for emitting bytecode for the program `print('Hello World')`:
//! ```
//! use haru::ast;
//! use haru::vmbindings::vm::{Vm, VmOpcode};
//! use haru::compiler::Compiler;
//! let mut c = Compiler::new();
//! let prog = ast::grammar::start("print('Hello World')\n").unwrap();
//! for stmt in prog {
//!     stmt.emit(&mut c);
//! }
//! c.vm.code.push(VmOpcode::OP_HALT);
//! ```

use crate::vmbindings::carray::CArray;
use crate::vmbindings::vm::{Vm, VmOpcode};

use std::collections::HashMap;


struct Scope {
    vars: Vec<String>,
}
impl Scope {
    fn new() -> Scope {
        Scope { vars: Vec::new() }
    }
}

struct LoopStatement {
    pub fill_continue: Vec<usize>,
    pub fill_break: Vec<usize>,
}

/// Indexed range for a stream of source code or bytecode.
pub type ArrayIndexRange = (usize, usize);
/// Mapping for a source code range to bytecode range.
pub struct SourceMap {
    pub file: ArrayIndexRange,
    pub bytecode: ArrayIndexRange,
    pub fileno: usize,
}

/// Compiler for processing AST nodes and
/// executing generated bytecode in a virtual machine.
pub struct Compiler {
    scopes: Vec<Scope>,
    loop_stmts: Vec<LoopStatement>,
    pub smap: Vec<SourceMap>,
    pub files: Vec<String>,
    pub modules_loaded: std::collections::HashSet<std::path::PathBuf>,
    pub symbol: HashMap<usize, String>,
    pub sources: Vec<String>,
    pub vm: Vm,
}
impl Compiler {
    pub fn new() -> Compiler {
        Compiler {
            scopes: Vec::new(),
            loop_stmts: Vec::new(),
            smap: Vec::new(),
            files: Vec::new(),
            modules_loaded: std::collections::HashSet::new(),
            symbol: HashMap::new(),
            sources: Vec::new(),
            vm: Vm::new(),
        }
    }

    // constructor for execution ctx
    pub unsafe fn new_append_vm(vm: &mut Vm) -> Compiler {
        Compiler {
            scopes: Vec::new(),
            loop_stmts: Vec::new(),
            smap: Vec::new(),
            files: Vec::new(),
            modules_loaded: std::collections::HashSet::new(),
            symbol: HashMap::new(),
            sources: Vec::new(),
            vm: {
                let mut vm_ = Vm::new_nil();
                vm_.code = vm.code.deref();
                vm_
            },
        }
    }

    pub fn deref_vm_code(mut self) -> CArray<VmOpcode> {
        self.vm.code.deref()
    }

    // scopes
    pub fn is_in_function(&self) -> bool {
        !self.scopes.is_empty()
    }

    // local
    fn get_local(&self, var: &String) -> Option<(u16, u16)> {
        let mut relascope: u16 = 0;
        for scope in self.scopes.iter().rev() {
            if let Some(slot) = scope.vars.iter().position(|x| *x == *var) {
                return Some((slot as u16, relascope));
            }
            relascope += 1;
        }
        None
    }

    pub fn set_local(&mut self, var: String) -> Option<(u16, u16)> {
        if let Some(last) = self.scopes.last_mut() {
            last.vars.push(var);
            let idx = last.vars.len() - 1;
            return Some((idx as u16, 0));
        }
        None
    }

    // emit set var
    pub fn emit_set_var(&mut self, var: String) {
        if var.starts_with("$") || self.scopes.len() == 0 {
            // set global
            self.vm.code.push(VmOpcode::OP_SET_GLOBAL);
            self.vm.cpushs(if var.starts_with("$") {
                &var[1..]
            } else {
                var.as_str()
            });
        } else if let Some(local) = self.get_local(&var) {
            // set existing local
            let mut slot = local.0;
            let relascope = local.1;
            if relascope != 0 {
                let local = self.set_local(var.clone()).unwrap();
                slot = local.0;
            }
            self.vm.code.push(VmOpcode::OP_SET_LOCAL);
            self.vm.cpush16(slot);
        } else {
            let local = self.set_local(var.clone()).unwrap();
            let slot = local.0;
            self.vm.code.push(VmOpcode::OP_SET_LOCAL);
            self.vm.cpush16(slot);
        }
    }
    pub fn emit_set_var_fn(&mut self, var: String) {
        if var.starts_with("$") || self.scopes.len() == 0 {
            // set global
            self.vm.code.push(VmOpcode::OP_SET_GLOBAL);
            self.vm.cpushs(if var.starts_with("$") {
                &var[1..]
            } else {
                var.as_str()
            });
        } else if let Some(local) = self.get_local(&var) {
            // set existing local
            let mut slot = local.0;
            let relascope = local.1;
            if relascope != 0 {
                let local = self.set_local(var.clone()).unwrap();
                slot = local.0;
            }
            self.vm.code.push(VmOpcode::OP_SET_LOCAL_FUNCTION_DEF);
            self.vm.cpush16(slot);
        } else {
            let local = self.set_local(var.clone()).unwrap();
            let slot = local.0;
            self.vm.code.push(VmOpcode::OP_SET_LOCAL_FUNCTION_DEF);
            self.vm.cpush16(slot);
        }
    }

    pub fn emit_get_var(&mut self, var: String) {
        let local = self.get_local(&var);
        if var.starts_with("$") || !local.is_some() {
            // set global
            self.vm.code.push(VmOpcode::OP_GET_GLOBAL);
            self.vm.cpushs(if var.starts_with("$") {
                &var[1..]
            } else {
                var.as_str()
            });
        } else {
            let local = local.unwrap();
            let slot = local.0;
            let relascope = local.1;
            if relascope == 0 {
                self.vm.code.push(VmOpcode::OP_GET_LOCAL);
                self.vm.cpush16(slot);
            } else {
                self.vm.code.push(VmOpcode::OP_GET_LOCAL_UP);
                self.vm.cpush16(slot);
                self.vm.cpush16(relascope);
            }
        }
    }

    // labels
    pub fn reserve_label(&mut self) -> usize {
        let pos = self.vm.code.len();
        self.vm.cpush32(0xdeadbeef);
        pos
    }
    pub fn reserve_label16(&mut self) -> usize {
        let pos = self.vm.code.len();
        self.vm.cpush16(0);
        pos
    }
    pub fn fill_label16(&mut self, pos: usize, label: u16) {
        self.vm.cfill_label16(pos, label);
    }

    // scopes
    pub fn scope(&mut self) {
        self.scopes.push(Scope::new());
    }
    pub fn unscope(&mut self) -> u16 {
        let size = self.scopes.pop().unwrap().vars.len();
        size as u16
    }

    // loops
    pub fn loop_start(&mut self) {
        self.loop_stmts.push(LoopStatement {
            fill_continue: Vec::new(),
            fill_break: Vec::new(),
        });
    }
    pub fn loop_continue(&mut self) {
        let label = self.reserve_label();
        let ls = self.loop_stmts.last_mut().unwrap();
        ls.fill_continue.push(label);
    }
    pub fn loop_break(&mut self) {
        let label = self.reserve_label();
        let ls = self.loop_stmts.last_mut().unwrap();
        ls.fill_break.push(label);
    }
    pub fn loop_end(&mut self, next_it_pos: usize, end_pos: usize) {
        let ls = self.loop_stmts.pop().unwrap();
        for label in ls.fill_continue {
            self.fill_label16(label, (next_it_pos - label) as u16);
        }
        for label in ls.fill_break {
            self.fill_label16(label, (end_pos - label) as u16);
        }
    }

    // source map
    pub fn lookup_smap(&self, bc_idx: usize) -> Option<&SourceMap> {
        // TODO: fix this and maybe use binary search?
        let mut last_found: Option<&SourceMap> = None;
        for smap in self.smap.iter() {
            if (smap.bytecode.0..=smap.bytecode.1).contains(&bc_idx) {
                // this is so that the lookup gets more "specific"
                last_found = Some(smap);
            }
        }
        if last_found.is_some() {
            last_found
        } else {
            None
        }
    }
}