reid-llvm/src/codegen.rs

221 lines
6.9 KiB
Rust
Raw Normal View History

2023-08-02 17:29:20 +02:00
use std::collections::{hash_map, HashMap};
2023-08-02 17:19:30 +02:00
use crate::{
2023-08-02 23:53:39 +02:00
ast::{
2023-08-03 19:08:20 +02:00
BinaryOperator, Block, BlockLevelStatement, Expression, FunctionCallExpression,
FunctionDefinition, FunctionSignature, ReturnType, TopLevelStatement,
2023-08-02 23:53:39 +02:00
},
llvm_ir::{self, IRBlock, IRFunction, IRModule, IRValue, IRValueType},
2023-08-02 17:19:30 +02:00
};
2023-08-02 23:53:39 +02:00
#[derive(Clone)]
pub struct ScopeData {
2023-08-02 17:43:47 +02:00
named_vars: HashMap<String, IRValue>,
2023-08-02 23:53:39 +02:00
defined_functions: HashMap<String, (FunctionSignature, Option<IRFunction>)>,
2023-08-02 17:29:20 +02:00
}
2023-08-02 23:53:39 +02:00
impl ScopeData {
2023-08-03 19:08:20 +02:00
pub fn inner<'a, 'b>(&self, block: &'b mut IRBlock<'a>) -> Scope<'a, 'b> {
Scope {
block,
data: self.clone(),
}
2023-08-02 17:29:20 +02:00
}
2023-08-02 23:53:39 +02:00
pub fn var(&self, name: &String) -> Option<&IRValue> {
2023-08-02 17:29:20 +02:00
self.named_vars.get(name)
}
2023-08-02 23:53:39 +02:00
pub fn set_var(&mut self, name: &str, val: IRValue) -> Result<(), Error> {
2023-08-02 17:38:38 +02:00
if let hash_map::Entry::Vacant(e) = self.named_vars.entry(name.to_owned()) {
2023-08-02 17:29:20 +02:00
e.insert(val);
Ok(())
} else {
2023-08-02 19:17:06 +02:00
Err(Error::VariableAlreadyDefined(name.to_owned()))
2023-08-02 17:29:20 +02:00
}
}
2023-08-02 23:53:39 +02:00
pub fn function(
&mut self,
name: &String,
) -> Option<&mut (FunctionSignature, Option<IRFunction>)> {
self.defined_functions.get_mut(name)
}
pub fn set_function_signature(
&mut self,
name: &str,
sig: FunctionSignature,
ir: IRFunction,
) -> Result<(), Error> {
if let hash_map::Entry::Vacant(e) = self.defined_functions.entry(name.to_owned()) {
e.insert((sig, Some(ir)));
Ok(())
} else {
Err(Error::VariableAlreadyDefined(name.to_owned()))
}
}
}
pub struct Scope<'a, 'b> {
2023-08-03 19:08:20 +02:00
pub block: &'b mut IRBlock<'a>,
pub data: ScopeData,
}
impl<'a, 'b> Scope<'a, 'b> {
pub fn inner<'c>(&'c mut self) -> Scope<'a, 'c> {
Scope {
block: self.block,
data: self.data.clone(),
}
}
2023-08-02 23:53:39 +02:00
}
pub fn codegen_from_statements(statements: Vec<TopLevelStatement>) -> Result<IRModule, Error> {
let mut module = IRModule::new("testmod");
let mut scope = ScopeData {
defined_functions: HashMap::new(),
named_vars: HashMap::new(),
};
for statement in &statements {
match statement {
TopLevelStatement::FunctionDefinition(FunctionDefinition(sig, _)) => {
let function = module.create_func(&sig.name, IRValueType::I32);
scope.set_function_signature(&sig.name.clone(), sig.clone(), function)?;
}
TopLevelStatement::Import(_) => {}
}
}
for statement in &statements {
statement.codegen(&mut module, &mut scope)?;
}
Ok(module)
2023-08-02 17:29:20 +02:00
}
2023-08-02 17:37:31 +02:00
impl TopLevelStatement {
2023-08-02 23:53:39 +02:00
pub fn codegen(&self, module: &mut IRModule, root_data: &mut ScopeData) -> Result<(), Error> {
2023-08-02 17:37:31 +02:00
match self {
2023-08-02 17:19:30 +02:00
TopLevelStatement::FunctionDefinition(FunctionDefinition(sig, block)) => {
2023-08-02 23:53:39 +02:00
if let Some((_, ir)) = root_data.function(&sig.name) {
2023-08-03 19:08:20 +02:00
if let Some(ir_function) = ir.take() {
let mut ir_block = module.create_block();
let mut scope = root_data.inner(&mut ir_block);
2023-08-02 17:19:30 +02:00
2023-08-03 19:08:20 +02:00
let (_, value) = match block.codegen(&mut scope)? {
Some(v) => v,
None => panic!("Void-return type function not yet implemented!"),
2023-08-02 23:53:39 +02:00
};
2023-08-03 19:08:20 +02:00
ir_function.add_definition(value, ir_block);
2023-08-02 23:53:39 +02:00
} else {
Err(Error::FunctionAlreadyDefined(sig.name.clone()))?
}
2023-08-02 17:19:30 +02:00
} else {
2023-08-02 23:53:39 +02:00
panic!("Function was not declared before it's definition")
}
2023-08-02 16:03:06 +02:00
}
2023-08-02 17:19:30 +02:00
TopLevelStatement::Import(_) => {}
}
2023-08-02 19:17:06 +02:00
Ok(())
}
}
2023-08-03 19:08:20 +02:00
impl Block {
pub fn codegen(&self, scope: &mut Scope) -> Result<Option<(ReturnType, IRValue)>, Error> {
for statement in &self.0 {
statement.codegen(scope)?;
}
let value = if let Some((rt, exp)) = &self.1 {
Some((*rt, exp.codegen(scope)?))
} else {
None
};
Ok(value)
}
}
2023-08-02 17:37:31 +02:00
impl BlockLevelStatement {
2023-08-02 19:17:06 +02:00
pub fn codegen(&self, scope: &mut Scope) -> Result<(), Error> {
2023-08-02 17:37:31 +02:00
match self {
BlockLevelStatement::Let(let_statement) => {
2023-08-02 19:17:06 +02:00
let val = let_statement.1.codegen(scope)?;
2023-08-02 23:53:39 +02:00
scope.data.set_var(&let_statement.0, val)?;
2023-08-02 19:17:06 +02:00
Ok(())
2023-08-02 16:03:06 +02:00
}
2023-08-02 19:22:10 +02:00
BlockLevelStatement::Return(_) => panic!("Should never happen"),
2023-08-03 19:10:12 +02:00
BlockLevelStatement::Import(_) => Ok(()), // TODO: To implement
BlockLevelStatement::Expression(e) => {
let _value = e.codegen(scope)?;
Ok(())
}
2023-08-02 17:37:31 +02:00
}
}
}
impl Expression {
2023-08-02 19:17:06 +02:00
pub fn codegen(&self, scope: &mut Scope) -> Result<IRValue, Error> {
2023-08-02 17:37:31 +02:00
use Expression::*;
match self {
Binop(op, lhs, rhs) => match op {
BinaryOperator::Add => {
2023-08-02 19:17:06 +02:00
let lhs = lhs.codegen(scope)?;
let rhs = rhs.codegen(scope)?;
Ok(scope.block.add(lhs, rhs)?)
2023-08-02 17:37:31 +02:00
}
2023-08-02 23:53:39 +02:00
BinaryOperator::Mult => {
let lhs = lhs.codegen(scope)?;
let rhs = rhs.codegen(scope)?;
Ok(scope.block.mul(lhs, rhs)?)
}
2023-08-02 17:37:31 +02:00
},
2023-08-03 19:08:20 +02:00
BlockExpr(block) => {
let mut inner = scope.inner();
Ok(match block.codegen(&mut inner)? {
Some((r_type, value)) => match r_type {
ReturnType::Soft => value,
ReturnType::Hard => {
panic!("Hard returns in inner blocks not supported yet")
}
},
None => panic!("Void-return type block not yet implemented!"),
})
}
2023-08-02 23:53:39 +02:00
FunctionCall(fc) => {
let FunctionCallExpression(name, _) = &**fc;
if let Some((sig, _)) = scope.data.function(name) {
Ok(scope.block.function_call(sig)?)
} else {
Err(Error::UndefinedFunction(name.clone()))?
}
}
2023-08-02 19:22:10 +02:00
VariableName(name) => scope
2023-08-02 23:53:39 +02:00
.data
.var(name)
2023-08-02 19:17:06 +02:00
.cloned()
2023-08-02 19:22:10 +02:00
.ok_or(Error::UndefinedVariable(name.clone())),
2023-08-02 19:17:06 +02:00
Literal(lit) => Ok(scope.block.get_const(lit)),
2023-08-02 17:37:31 +02:00
}
2023-08-02 16:03:06 +02:00
}
}
2023-08-02 19:17:06 +02:00
#[derive(thiserror::Error, Debug)]
pub enum Error {
2023-08-02 19:22:10 +02:00
#[error("Variable '{0}' already defined")]
2023-08-02 19:17:06 +02:00
VariableAlreadyDefined(String),
2023-08-02 19:22:10 +02:00
#[error("Variable '{0}' not yet defined")]
2023-08-02 19:17:06 +02:00
UndefinedVariable(String),
2023-08-02 23:53:39 +02:00
#[error("Function '{0}' not defined")]
UndefinedFunction(String),
#[error("Function '{0}' already defined")]
FunctionAlreadyDefined(String),
2023-08-02 19:17:06 +02:00
#[error(transparent)]
Deeper(#[from] llvm_ir::Error),
}