108 lines
2.3 KiB
Rust
108 lines
2.3 KiB
Rust
#[derive(Debug)]
|
|
pub enum Instruction {
|
|
Duplicate,
|
|
Pop,
|
|
|
|
Jump(usize),
|
|
JumpIf(usize),
|
|
Call,
|
|
Return,
|
|
|
|
LoadLocal(usize),
|
|
StoreLocal(usize),
|
|
|
|
HeapLoad,
|
|
HeapStore,
|
|
HeapAlloc,
|
|
|
|
PushUnit,
|
|
PushInt(i64),
|
|
PushFloat(f64),
|
|
PushString(String),
|
|
PushBool(bool),
|
|
PushFunctionReference(usize),
|
|
|
|
Not,
|
|
Negate,
|
|
|
|
Add,
|
|
Subtract,
|
|
Multiply,
|
|
Divide,
|
|
Modulo,
|
|
Exponentiate,
|
|
LT,
|
|
LTE,
|
|
GT,
|
|
GTE,
|
|
Equal,
|
|
Inequal,
|
|
And,
|
|
Or,
|
|
In,
|
|
NotIn,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Module {
|
|
pub functions: Vec<Function>,
|
|
pub entry_function: usize,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum Function {
|
|
BuiltIn {
|
|
arguments: usize,
|
|
},
|
|
UserDefined {
|
|
instructions: Vec<Instruction>,
|
|
arguments: usize,
|
|
locals_reserve: usize,
|
|
},
|
|
}
|
|
|
|
impl Module {
|
|
pub fn fancy_string(&self) -> String {
|
|
format!(
|
|
"Module\n{}",
|
|
self.functions
|
|
.iter()
|
|
.map(|f| f.fancy_string())
|
|
.reduce(|mut acc, v| {
|
|
acc.push_str(&v);
|
|
acc
|
|
})
|
|
.unwrap_or("".to_string())
|
|
)
|
|
}
|
|
}
|
|
|
|
impl Function {
|
|
pub fn instructions(&self) -> &Vec<Instruction> {
|
|
match self {
|
|
Self::UserDefined { instructions, .. } => instructions,
|
|
_ => panic!("expected user defined function"),
|
|
}
|
|
}
|
|
pub fn arguments(&self) -> usize {
|
|
match self {
|
|
Self::BuiltIn { arguments } |
|
|
Self::UserDefined { arguments, .. } => *arguments,
|
|
}
|
|
}
|
|
pub fn locals_reserve(&self) -> usize {
|
|
match self {
|
|
Self::UserDefined { locals_reserve, .. } => *locals_reserve,
|
|
_ => panic!("expected user defined function"),
|
|
}
|
|
}
|
|
|
|
pub fn fancy_string(&self) -> String {
|
|
match self {
|
|
Self::BuiltIn { arguments } => format!(" - BuiltIn Function\n arguments: {}", arguments),
|
|
Self::UserDefined { instructions, arguments, locals_reserve } =>
|
|
format!(" - Function\n arguments: {}\n locals_reserve: {}\n instructions:\n{}", arguments, locals_reserve, instructions.iter().map(|i| format!(" - {:?}\n", i)).reduce(|mut acc, v|{acc.push_str(&v); acc}).unwrap_or("".to_string()))
|
|
}
|
|
}
|
|
}
|