[fine] A wild VM appears!

Untested though
This commit is contained in:
John Doty 2024-01-14 09:28:05 -08:00
parent 53f18e729b
commit 866830b485
8 changed files with 464 additions and 26 deletions

View file

@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::rc::Rc;
use crate::{
parser::{SyntaxTree, Tree, TreeKind, TreeRef},
@ -8,7 +9,7 @@ use crate::{
// TODO: If I were cool this would by actual bytecode.
// But I'm not cool.
#[derive(Debug)]
#[derive(Debug, Clone, Copy)]
pub enum Instruction {
Panic,
@ -32,9 +33,9 @@ pub enum Instruction {
StoreLocal(usize),
StoreModule(usize),
LoadFunction(usize),
LoadExtern(usize),
LoadExternFunction(usize), // NOTE: FUNKY, might want to indirect this index.
Call(usize),
Return,
}
pub enum Export {
@ -43,7 +44,7 @@ pub enum Export {
}
pub struct Module {
pub functions: Vec<Function>, // Functions
pub functions: Vec<Rc<Function>>, // Functions
pub globals: usize, // The number of global variables
pub exports: HashMap<String, Export>, // Exports by name
pub init: usize, // The index of the initialization function
@ -59,7 +60,7 @@ impl Module {
}
}
pub fn functions(&self) -> &[Function] {
pub fn functions(&self) -> &[Rc<Function>] {
&self.functions
}
}
@ -68,7 +69,7 @@ impl Module {
pub struct Function {
name: String,
instructions: Vec<Instruction>,
strings: Vec<String>,
strings: Vec<Rc<str>>,
args: usize, // TODO: Probably type information too?
locals: usize, // TODO: Same?
}
@ -96,7 +97,7 @@ impl Function {
self.locals
}
pub fn strings(&self) -> &[String] {
pub fn strings(&self) -> &[Rc<str>] {
&self.strings
}
@ -105,6 +106,16 @@ impl Function {
}
}
impl std::fmt::Debug for Function {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"fn {} ({} args, {} locals) ...",
self.name, self.args, self.locals
)
}
}
struct Compiler<'a> {
semantics: &'a Semantics<'a>,
syntax: &'a SyntaxTree<'a>,
@ -123,7 +134,7 @@ impl<'a> Compiler<'a> {
fn add_string(&mut self, result: String) -> usize {
let index = self.function.strings.len();
self.function.strings.push(result);
self.function.strings.push(result.into());
index
}
@ -195,7 +206,7 @@ macro_rules! ice {
// ($compiler:expr, $tr:expr, $($t:tt)*) => {{}};
// }
pub fn compile(semantics: &Semantics) -> Module {
pub fn compile(semantics: &Semantics) -> Rc<Module> {
let mut compiler = Compiler {
semantics,
syntax: semantics.tree(),
@ -210,10 +221,10 @@ pub fn compile(semantics: &Semantics) -> Module {
let mut module = compiler.module;
let index = module.functions.len();
module.functions.push(compiler.function);
module.functions.push(Rc::new(compiler.function));
module.init = index;
module
Rc::new(module)
}
fn file(c: &mut Compiler, t: TreeRef) {
@ -565,7 +576,7 @@ fn compile_function_declaration(c: &mut Compiler, t: TreeRef, tree: &Tree, gen_v
compile_expression(c, block);
std::mem::swap(&mut c.function, &mut prev);
c.module.functions.push(prev);
c.module.functions.push(Rc::new(prev));
}
if gen_value {