use ux::{i48, u56};
use crate::{
ast2::Expr,
bytecode::{Bytecode, PrettyOp},
const_table::ConstTable,
};
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Type {
Int,
Float,
String,
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Slot {
index: usize,
}
impl From<Slot> for u8 {
fn from(slot: Slot) -> Self {
slot.index as u8
}
}
pub struct Slots {
next_index: usize,
next_named: usize,
named_slots: std::collections::HashMap<String, Slot>,
free_list: Vec<Slot>,
types: std::collections::HashMap<usize, Option<Type>>,
}
impl Slots {
pub fn new() -> Self {
Slots {
next_index: 0,
next_named: 0,
named_slots: std::collections::HashMap::new(),
free_list: Vec::new(),
types: std::collections::HashMap::new(),
}
}
pub fn free(&mut self, slot: Slot) {
if slot.index < self.next_named {
return;
}
self.free_list.push(slot);
}
pub fn allocate(&mut self, r#type: Option<Type>) -> Slot {
let slot = {
if let Some(slot) = self.free_list.pop() {
return slot;
}
let slot = Slot {
index: self.next_index,
};
self.next_index += 1;
slot
};
self.types.insert(slot.index, r#type);
slot
}
fn allocate_named(&mut self, name: &str, r#type: Option<Type>) -> Slot {
if let Some(&slot) = self.named_slots.get(name) {
if let Some(existing_type) = self.type_of(slot) {
if let Some(new_type) = r#type {
assert_eq!(existing_type, new_type, "Type mismatch for named slot");
}
} else if let Some(new_type) = r#type {
self.set_type(slot, new_type);
}
return slot;
} else {
let slot = Slot {
index: self.next_named,
};
self.next_named += 1;
self.types.insert(slot.index, r#type);
self.named_slots.insert(name.to_string(), slot);
slot
}
}
fn type_of(&self, slot: Slot) -> Option<Type> {
self.types.get(&slot.index).copied().flatten()
}
fn set_type(&mut self, slot: Slot, r#type: Type) {
assert!(
!matches!(self.types.get(&slot.index), Some(Some(_))),
"Type already set for slot"
);
self.types.insert(slot.index, Some(r#type));
}
}
#[derive(Clone, Debug)]
pub struct CompiledCode {
pub bytecode: Vec<u8>,
pub consts: ConstTable,
}
struct GenCtx {
slots: Slots,
code: Bytecode,
consts: ConstTable,
}
pub fn generate_bytecode(expr: &Expr) -> CompiledCode {
let mut ctx = GenCtx {
slots: Slots::new(),
code: Bytecode::new(),
consts: ConstTable::new(),
};
let decls = count_decls(expr);
ctx.slots.next_index += decls;
gen_expr(expr, &mut ctx, None);
ctx.code.emit(PrettyOp::Halt);
let bytes = ctx.code.into_bytes();
let slots_max = ctx.slots.next_index;
let alloc = PrettyOp::Alloc {
n: u56::new(slots_max as u64),
}
.into_slice();
let mut final_code = Vec::with_capacity(bytes.len() + alloc.len());
final_code.extend_from_slice(&alloc);
final_code.extend_from_slice(&bytes);
CompiledCode {
bytecode: final_code,
consts: ctx.consts,
}
}
fn count_decls(expr: &Expr) -> usize {
match expr {
Expr::Decl { name: _, value } => 1 + count_decls(value),
Expr::Block(exprs) => exprs.iter().map(count_decls).sum(),
Expr::Add(expr, expr1)
| Expr::Sub(expr, expr1)
| Expr::Mul(expr, expr1)
| Expr::Div(expr, expr1)
| Expr::Mod(expr, expr1)
| Expr::LogicOr(expr, expr1)
| Expr::LogicAnd(expr, expr1)
| Expr::Cond(expr, _, expr1) => count_decls(expr) + count_decls(expr1),
Expr::Negation(expr) | Expr::Inversion(expr) | Expr::GroupedExpr(expr) => count_decls(expr),
Expr::Assign { left: _, right } => count_decls(right),
Expr::FuncCall { name: _, args } => args.iter().map(count_decls).sum(),
Expr::Int(_) | Expr::Float(_) | Expr::String(_) | Expr::Var(_) => 0,
}
}
pub fn gen_expr(expr: &Expr, ctx: &mut GenCtx, result_slot: Option<Slot>) -> (Slot, Type) {
println!("Expr: {:?}", expr);
println!("Slots: {:?} Types: {:?}", ctx.slots.named_slots, ctx.slots.types);
match expr {
Expr::Int(i) => {
let slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(Type::Int)));
if *i > i64::from(i48::MAX) || *i < i64::from(i48::MIN) {
todo!("loadci");
}
ctx.code.emit(PrettyOp::Loadi {
i: slot.into(),
val: i48::new(*i),
});
(slot, Type::Int)
}
Expr::Float(f) => {
let slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(Type::Float)));
let ci = ctx.consts.add_float(*f);
ctx.code.emit(PrettyOp::LoadCf {
i: slot.into(),
c: ci,
});
(slot, Type::Float)
}
Expr::String(s) => todo!(),
Expr::FuncCall { name, args } => todo!(),
Expr::Add(expr, expr1) => {
let (left_slot, left_type) = gen_expr(expr, ctx, None);
let (right_slot, right_type) = gen_expr(expr1, ctx, None);
assert_eq!(left_type, right_type);
let result_slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(left_type)));
match left_type {
Type::Int => ctx.code.emit(PrettyOp::Addi {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::Float => ctx.code.emit(PrettyOp::Addf {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::String => unreachable!("Cannot add strings"),
}
ctx.slots.free(left_slot);
ctx.slots.free(right_slot);
(result_slot, left_type)
}
Expr::Sub(expr, expr1) => {
let (left_slot, left_type) = gen_expr(expr, ctx, None);
let (right_slot, right_type) = gen_expr(expr1, ctx, None);
assert_eq!(left_type, right_type);
let result_slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(left_type)));
match left_type {
Type::Int => ctx.code.emit(PrettyOp::Subi {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::Float => ctx.code.emit(PrettyOp::Subf {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::String => unreachable!("Cannot sub strings"),
}
ctx.slots.free(left_slot);
ctx.slots.free(right_slot);
(result_slot, left_type)
}
Expr::Mul(expr, expr1) => {
let (left_slot, left_type) = gen_expr(expr, ctx, None);
let (right_slot, right_type) = gen_expr(expr1, ctx, None);
assert_eq!(left_type, right_type);
let result_slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(left_type)));
match left_type {
Type::Int => ctx.code.emit(PrettyOp::Muli {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::Float => ctx.code.emit(PrettyOp::Mulf {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::String => unreachable!("Cannot mul strings"),
}
ctx.slots.free(left_slot);
ctx.slots.free(right_slot);
(result_slot, left_type)
}
Expr::Div(expr, expr1) => {
let (left_slot, left_type) = gen_expr(expr, ctx, None);
let (right_slot, right_type) = gen_expr(expr1, ctx, None);
assert_eq!(left_type, right_type);
let result_slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(left_type)));
match left_type {
Type::Int => ctx.code.emit(PrettyOp::Divi {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::Float => ctx.code.emit(PrettyOp::Divf {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::String => unreachable!("Cannot div strings"),
}
ctx.slots.free(left_slot);
ctx.slots.free(right_slot);
(result_slot, left_type)
}
Expr::Mod(expr, expr1) => {
let (left_slot, left_type) = gen_expr(expr, ctx, None);
let (right_slot, right_type) = gen_expr(expr1, ctx, None);
assert_eq!(left_type, right_type);
let result_slot = result_slot.unwrap_or_else(|| ctx.slots.allocate(Some(left_type)));
match left_type {
Type::Int => ctx.code.emit(PrettyOp::Addi {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::Float => ctx.code.emit(PrettyOp::Addf {
r: result_slot.into(),
i: left_slot.into(),
k: right_slot.into(),
}),
Type::String => unreachable!("Cannot add strings"),
}
ctx.slots.free(left_slot);
ctx.slots.free(right_slot);
(result_slot, left_type)
}
Expr::Assign { left, right } => {
if !matches!(**left, Expr::Var(_)) {
panic!("Left side of assignment must be a variable");
}
let (left_slot, left_type) = gen_expr(left, ctx, None);
let (_right_slot, right_type) = gen_expr(right, ctx, Some(left_slot));
assert_eq!(
left_type,
right_type,
"Type mismatch in assignment"
);
(left_slot, right_type)
}
Expr::Decl { name, value } => {
let hint = ctx.slots.allocate_named(name, None);
let expr = gen_expr(value, ctx, Some(hint));
ctx.slots.set_type(hint, expr.1);
expr
}
Expr::LogicOr(expr, expr1) => todo!(),
Expr::LogicAnd(expr, expr1) => todo!(),
Expr::Cond(expr, cond_op, expr1) => todo!(),
Expr::Negation(expr) => todo!(),
Expr::Inversion(expr) => todo!(),
Expr::Var(name) => {
let slot = ctx.slots.allocate_named(name, None);
let ty = ctx.slots.type_of(slot).expect("Variable used before declaration");
(slot, ty)
}
Expr::GroupedExpr(expr) => todo!(),
Expr::Block(exprs) => {
let mut last_slot = None;
let mut last_type = None;
let mut used_slots = Vec::new();
for expr in exprs {
let (slot, ty) = gen_expr(expr, ctx, None);
used_slots.push(slot);
last_slot = Some(slot);
last_type = Some(ty);
}
used_slots.retain(|&s| Some(s) != last_slot);
for slot in used_slots {
ctx.slots.free(slot);
}
(
last_slot.unwrap_or(Slot { index: 0 }),
last_type.unwrap_or(Type::Int),
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_named_allocation() {
let mut slots = Slots::new();
let slot1 = slots.allocate_named("x", Some(Type::Int));
let slot2 = slots.allocate_named("x", Some(Type::Int));
let slot3 = slots.allocate_named("x", None);
assert_eq!(slot1.index, slot2.index);
assert_eq!(slot2.index, slot3.index);
assert_eq!(slots.type_of(slot1), Some(Type::Int));
let slot3 = slots.allocate_named("y", None);
assert_ne!(slot1.index, slot3.index);
assert_eq!(slots.type_of(slot3), None);
slots.set_type(slot3, Type::Float);
assert_eq!(slots.type_of(slot3), Some(Type::Float));
}
#[test]
#[should_panic]
fn test_set_type_twice() {
let mut slots = Slots::new();
let _slot = slots.allocate_named("y", Some(Type::Float));
slots.allocate_named("y", Some(Type::Int));
}
}