Compare commits

..

No commits in common. "46560d85410001b26fac3210d73ba0749d35ade7" and "20dfdfec9fd13266866f9b1a87223812131ebcaa" have entirely different histories.

20 changed files with 1439 additions and 2203 deletions

View File

@ -1,60 +1,105 @@
use reid_lib::{ConstValue, Context, InstructionKind, IntPredicate, TerminatorKind, Type}; use reid_lib::{
Context, IntPredicate,
types::{BasicType, IntegerValue, Value},
};
fn main() { pub fn main() {
use ConstValue::*; // Notes from inkwell:
use InstructionKind::*; // - Creating new values should probably just be functions in the context
// - Creating functions should probably be functions from module
// - Builder could well be it's own struct
// - Although, I do like the fact where blocks move the builder by itself..
let context = Context::new(); let context = Context::new();
let mut module = context.module("test"); let module = context.module("testmodule");
let main = module.function("main", Type::I32, Vec::new()); let int_32 = context.type_i32();
let mut m_entry = main.block("entry");
let fibonacci = module.function("fibonacci", Type::I32, vec![Type::I32]); let fibonacci = module.add_function(int_32.function_type(vec![int_32.into()]), "fibonacci");
let mut f_main = fibonacci.block("main");
let arg = m_entry.build(Constant(I32(5))).unwrap(); let param = fibonacci
let fibonacci_call = m_entry .get_param::<IntegerValue>(0, int_32.into())
.build(FunctionCall(fibonacci.value(), vec![arg]))
.unwrap(); .unwrap();
m_entry let mut cmp = f_main
.terminate(TerminatorKind::Ret(fibonacci_call)) .integer_compare(&param, &int_32.from_unsigned(3), &IntPredicate::ULT, "cmp")
.unwrap(); .unwrap();
let mut f_entry = fibonacci.block("entry"); let mut done = fibonacci.block("done");
let mut recurse = fibonacci.block("recurse");
f_main.conditional_br(&cmp, &done, &recurse).unwrap();
let num_3 = f_entry.build(Constant(I32(3))).unwrap(); done.ret(&int_32.from_unsigned(1)).unwrap();
let param_n = f_entry.build(Param(0)).unwrap();
let cond = f_entry let minus_one = recurse
.build(ICmp(IntPredicate::LessThan, param_n, num_3)) .sub(&param, &int_32.from_unsigned(1), "minus_one")
.unwrap();
let minus_two = recurse
.sub(&param, &int_32.from_unsigned(2), "minus_two")
.unwrap();
let one: IntegerValue = recurse
.call(&fibonacci, vec![Value::Integer(minus_one)], "call_one")
.unwrap();
let two = recurse
.call(&fibonacci, vec![Value::Integer(minus_two)], "call_two")
.unwrap(); .unwrap();
let mut then_b = fibonacci.block("then"); let add = recurse.add(&one, &two, "add").unwrap();
let mut else_b = fibonacci.block("else");
f_entry recurse.ret(&add).unwrap();
.terminate(TerminatorKind::CondBr(cond, then_b.value(), else_b.value()))
let main_f = module.add_function(int_32.function_type(Vec::new()), "main");
let mut main_b = main_f.block("main");
let call: IntegerValue = main_b
.call(
&fibonacci,
vec![Value::Integer(int_32.from_unsigned(8))],
"fib_call",
)
.unwrap(); .unwrap();
main_b.ret(&call).unwrap();
let ret_const = then_b.build(Constant(I32(1))).unwrap(); // let secondary = module.add_function(int_32.function_type(&[]), "secondary");
then_b.terminate(TerminatorKind::Ret(ret_const)).unwrap(); // let s_entry = secondary.block("entry");
// s_entry.ret(&int_32.from_signed(54)).unwrap();
let const_1 = else_b.build(Constant(I32(1))).unwrap(); // let function = module.add_function(int_32.function_type(&[]), "main");
let const_2 = else_b.build(Constant(I32(2))).unwrap();
let param_1 = else_b.build(Sub(param_n, const_1)).unwrap();
let param_2 = else_b.build(Sub(param_n, const_2)).unwrap();
let call_1 = else_b
.build(FunctionCall(fibonacci.value(), vec![param_1]))
.unwrap();
let call_2 = else_b
.build(FunctionCall(fibonacci.value(), vec![param_2]))
.unwrap();
let add = else_b.build(Add(call_1, call_2)).unwrap(); // let entry = function.block("entry");
else_b.terminate(TerminatorKind::Ret(add)).unwrap(); // let call = entry.call(&secondary, vec![], "call").unwrap();
// let add = entry.add(&int_32.from_signed(100), &call, "add").unwrap();
// let rhs_cmp = int_32.from_signed(200);
dbg!(&context); // let cond_res = entry
// .integer_compare(&add, &rhs_cmp, &IntPredicate::SLT, "cmp")
// .unwrap();
context.compile(); // let (lhs, rhs) = entry.conditional_br(&cond_res, "lhs", "rhs").unwrap();
// let left = lhs.add(&call, &int_32.from_signed(20), "add").unwrap();
// let right = rhs.add(&call, &int_32.from_signed(30), "add").unwrap();
// let final_block = function.block("final");
// let phi = final_block
// .phi::<IntegerValue>(&int_32, "phi")
// .unwrap()
// .add_incoming(&left, &lhs)
// .add_incoming(&right, &rhs)
// .build();
// lhs.br(&final_block).unwrap();
// rhs.br(&final_block).unwrap();
// let val = final_block
// .add(&phi, &int_32.from_signed(11), "add")
// .unwrap();
// final_block.ret(&val).unwrap();
match module.print_to_string() {
Ok(v) => println!("{}", v),
Err(e) => println!("Err: {:?}", e),
}
} }

View File

@ -1,323 +0,0 @@
use std::{cell::RefCell, rc::Rc};
use crate::{
BlockData, ConstValue, FunctionData, InstructionData, InstructionKind, ModuleData,
TerminatorKind, Type, util::match_types,
};
#[derive(Clone, Hash, Copy, PartialEq, Eq)]
pub struct ModuleValue(pub(crate) usize);
#[derive(Clone, Hash, Copy, PartialEq, Eq)]
pub struct FunctionValue(pub(crate) ModuleValue, pub(crate) usize);
#[derive(Clone, Hash, Copy, PartialEq, Eq)]
pub struct BlockValue(pub(crate) FunctionValue, pub(crate) usize);
#[derive(Clone, Hash, Copy, PartialEq, Eq)]
pub struct InstructionValue(pub(crate) BlockValue, pub(crate) usize);
#[derive(Clone)]
pub struct ModuleHolder {
pub(crate) value: ModuleValue,
pub(crate) data: ModuleData,
pub(crate) functions: Vec<FunctionHolder>,
}
#[derive(Clone)]
pub struct FunctionHolder {
pub(crate) value: FunctionValue,
pub(crate) data: FunctionData,
pub(crate) blocks: Vec<BlockHolder>,
}
#[derive(Clone)]
pub struct BlockHolder {
pub(crate) value: BlockValue,
pub(crate) data: BlockData,
pub(crate) instructions: Vec<InstructionHolder>,
}
#[derive(Clone)]
pub struct InstructionHolder {
pub(crate) value: InstructionValue,
pub(crate) data: InstructionData,
}
#[derive(Debug, Clone)]
pub struct Builder {
modules: Rc<RefCell<Vec<ModuleHolder>>>,
}
impl Builder {
pub fn new() -> Builder {
Builder {
modules: Rc::new(RefCell::new(Vec::new())),
}
}
pub(crate) fn add_module(&self, data: ModuleData) -> ModuleValue {
let value = ModuleValue(self.modules.borrow().len());
self.modules.borrow_mut().push(ModuleHolder {
value,
data,
functions: Vec::new(),
});
value
}
pub(crate) unsafe fn add_function(
&self,
mod_val: &ModuleValue,
data: FunctionData,
) -> FunctionValue {
unsafe {
let mut modules = self.modules.borrow_mut();
let module = modules.get_unchecked_mut(mod_val.0);
let value = FunctionValue(module.value, module.functions.len());
module.functions.push(FunctionHolder {
value,
data,
blocks: Vec::new(),
});
value
}
}
pub(crate) unsafe fn add_block(&self, fun_val: &FunctionValue, data: BlockData) -> BlockValue {
unsafe {
let mut modules = self.modules.borrow_mut();
let module = modules.get_unchecked_mut(fun_val.0.0);
let function = module.functions.get_unchecked_mut(fun_val.1);
let value = BlockValue(function.value, function.blocks.len());
function.blocks.push(BlockHolder {
value,
data,
instructions: Vec::new(),
});
value
}
}
pub(crate) unsafe fn add_instruction(
&self,
block_val: &BlockValue,
data: InstructionData,
) -> Result<InstructionValue, ()> {
unsafe {
let mut modules = self.modules.borrow_mut();
let module = modules.get_unchecked_mut(block_val.0.0.0);
let function = module.functions.get_unchecked_mut(block_val.0.1);
let block = function.blocks.get_unchecked_mut(block_val.1);
let value = InstructionValue(block.value, block.instructions.len());
block.instructions.push(InstructionHolder { value, data });
// Drop modules so that it is no longer mutable borrowed
// (check_instruction requires an immutable borrow).
drop(modules);
self.check_instruction(&value)?;
Ok(value)
}
}
pub(crate) unsafe fn terminate(
&self,
block: &BlockValue,
value: TerminatorKind,
) -> Result<(), ()> {
unsafe {
let mut modules = self.modules.borrow_mut();
let module = modules.get_unchecked_mut(block.0.0.0);
let function = module.functions.get_unchecked_mut(block.0.1);
let block = function.blocks.get_unchecked_mut(block.1);
if let Some(_) = &block.data.terminator {
Err(())
} else {
block.data.terminator = Some(value);
Ok(())
}
}
}
#[allow(dead_code)]
pub(crate) unsafe fn module_data(&self, value: &ModuleValue) -> ModuleData {
unsafe { self.modules.borrow().get_unchecked(value.0).data.clone() }
}
pub(crate) unsafe fn function_data(&self, value: &FunctionValue) -> FunctionData {
unsafe {
self.modules
.borrow()
.get_unchecked(value.0.0)
.functions
.get_unchecked(value.1)
.data
.clone()
}
}
#[allow(dead_code)]
pub(crate) unsafe fn block_data(&self, value: &BlockValue) -> BlockData {
unsafe {
self.modules
.borrow()
.get_unchecked(value.0.0.0)
.functions
.get_unchecked(value.0.1)
.blocks
.get_unchecked(value.1)
.data
.clone()
}
}
pub(crate) unsafe fn instr_data(&self, value: &InstructionValue) -> InstructionData {
unsafe {
self.modules
.borrow()
.get_unchecked(value.0.0.0.0)
.functions
.get_unchecked(value.0.0.1)
.blocks
.get_unchecked(value.0.1)
.instructions
.get_unchecked(value.1)
.data
.clone()
}
}
pub(crate) fn get_modules(&self) -> Rc<RefCell<Vec<ModuleHolder>>> {
self.modules.clone()
}
pub fn check_instruction(&self, instruction: &InstructionValue) -> Result<(), ()> {
use super::InstructionKind::*;
unsafe {
match self.instr_data(&instruction).kind {
Param(_) => Ok(()),
Constant(_) => Ok(()),
Add(lhs, rhs) => match_types(&lhs, &rhs, &self).map(|_| ()),
Sub(lhs, rhs) => match_types(&lhs, &rhs, &self).map(|_| ()),
ICmp(_, lhs, rhs) => {
let t = match_types(&lhs, &rhs, self)?;
if t.comparable() {
Ok(())
} else {
Err(()) // TODO error: Types not comparable
}
}
FunctionCall(fun, params) => {
let param_types = self.function_data(&fun).params;
if param_types.len() != params.len() {
return Err(()); // TODO error: invalid amount of params
}
for (a, b) in param_types.iter().zip(params) {
if *a != b.get_type(&self)? {
return Err(()); // TODO error: params do not match
}
}
Ok(())
}
Phi(vals) => {
let mut iter = vals.iter();
// TODO error: Phi must contain at least one item
let first = iter.next().ok_or(())?;
for item in iter {
match_types(first, item, &self)?;
}
Ok(())
}
}
}
}
}
impl InstructionValue {
pub fn get_type(&self, builder: &Builder) -> Result<Type, ()> {
use InstructionKind::*;
unsafe {
match &builder.instr_data(self).kind {
Param(nth) => builder
.function_data(&self.0.0)
.params
.get(*nth)
.copied()
.ok_or(()),
Constant(c) => Ok(c.get_type()),
Add(lhs, rhs) => match_types(lhs, rhs, &builder),
Sub(lhs, rhs) => match_types(lhs, rhs, &builder),
ICmp(_, _, _) => Ok(Type::Bool),
FunctionCall(function_value, _) => Ok(builder.function_data(function_value).ret),
Phi(values) => values.first().ok_or(()).and_then(|v| v.get_type(&builder)),
}
}
}
}
impl ConstValue {
pub fn get_type(&self) -> Type {
use Type::*;
match self {
ConstValue::I8(_) => I8,
ConstValue::I16(_) => I16,
ConstValue::I32(_) => I32,
ConstValue::I64(_) => I64,
ConstValue::I128(_) => I128,
ConstValue::U8(_) => U8,
ConstValue::U16(_) => U16,
ConstValue::U32(_) => U32,
ConstValue::U64(_) => U64,
ConstValue::U128(_) => U128,
ConstValue::Bool(_) => Bool,
}
}
}
impl Type {
pub fn comparable(&self) -> bool {
match self {
Type::I8 => true,
Type::I16 => true,
Type::I32 => true,
Type::I64 => true,
Type::I128 => true,
Type::U8 => true,
Type::U16 => true,
Type::U32 => true,
Type::U64 => true,
Type::U128 => true,
Type::Bool => true,
Type::Void => false,
}
}
pub fn signed(&self) -> bool {
match self {
Type::I8 => true,
Type::I16 => true,
Type::I32 => true,
Type::I64 => true,
Type::I128 => true,
Type::U8 => false,
Type::U16 => false,
Type::U32 => false,
Type::U64 => false,
Type::U128 => false,
Type::Bool => false,
Type::Void => false,
}
}
}
impl TerminatorKind {
pub fn get_type(&self, builder: &Builder) -> Result<Type, ()> {
use TerminatorKind::*;
match self {
Ret(instr_val) => instr_val.get_type(builder),
Branch(_) => Ok(Type::Void),
CondBr(_, _, _) => Ok(Type::Void),
}
}
}

View File

@ -1,405 +0,0 @@
use std::{collections::HashMap, ffi::CString, ptr::null_mut};
use llvm_sys::{
LLVMIntPredicate,
analysis::LLVMVerifyModule,
core::*,
prelude::*,
target::{
LLVM_InitializeAllAsmParsers, LLVM_InitializeAllAsmPrinters, LLVM_InitializeAllTargetInfos,
LLVM_InitializeAllTargetMCs, LLVM_InitializeAllTargets, LLVMSetModuleDataLayout,
},
target_machine::{
LLVMCodeGenFileType, LLVMCreateTargetDataLayout, LLVMCreateTargetMachine,
LLVMGetDefaultTargetTriple, LLVMGetTargetFromTriple, LLVMTargetMachineEmitToFile,
},
};
use crate::util::{ErrorMessageHolder, from_cstring, into_cstring};
use super::{
ConstValue, Context, IntPredicate, TerminatorKind, Type,
builder::{
BlockHolder, BlockValue, Builder, FunctionHolder, FunctionValue, InstructionHolder,
InstructionValue, ModuleHolder,
},
};
pub struct LLVMContext {
context_ref: LLVMContextRef,
builder_ref: LLVMBuilderRef,
}
impl Context {
pub fn compile(&self) {
unsafe {
let context_ref = LLVMContextCreate();
let context = LLVMContext {
context_ref,
builder_ref: LLVMCreateBuilderInContext(context_ref),
};
for holder in self.builder.get_modules().borrow().iter() {
holder.compile(&context, &self.builder);
}
LLVMDisposeBuilder(context.builder_ref);
LLVMContextDispose(context.context_ref);
}
}
}
pub struct LLVMModule<'a> {
builder: &'a Builder,
context_ref: LLVMContextRef,
builder_ref: LLVMBuilderRef,
#[allow(dead_code)]
module_ref: LLVMModuleRef,
functions: HashMap<FunctionValue, LLVMFunction>,
blocks: HashMap<BlockValue, LLVMBasicBlockRef>,
values: HashMap<InstructionValue, LLVMValue>,
}
#[derive(Clone, Copy)]
pub struct LLVMFunction {
type_ref: LLVMTypeRef,
value_ref: LLVMValueRef,
}
pub struct LLVMValue {
_ty: Type,
value_ref: LLVMValueRef,
}
impl ModuleHolder {
fn compile(&self, context: &LLVMContext, builder: &Builder) {
unsafe {
let module_ref = LLVMModuleCreateWithNameInContext(
into_cstring(&self.data.name).as_ptr(),
context.context_ref,
);
// Compile the contents
let mut functions = HashMap::new();
for function in &self.functions {
functions.insert(
function.value,
function.compile_signature(context, module_ref),
);
}
let mut module = LLVMModule {
builder,
context_ref: context.context_ref,
builder_ref: context.builder_ref,
module_ref,
functions,
blocks: HashMap::new(),
values: HashMap::new(),
};
for function in &self.functions {
function.compile(&mut module);
}
LLVM_InitializeAllTargets();
LLVM_InitializeAllTargetInfos();
LLVM_InitializeAllTargetMCs();
LLVM_InitializeAllAsmParsers();
LLVM_InitializeAllAsmPrinters();
let triple = LLVMGetDefaultTargetTriple();
let mut target: _ = null_mut();
let mut err = ErrorMessageHolder::null();
LLVMGetTargetFromTriple(triple, &mut target, err.borrow_mut());
println!("{:?}, {:?}", from_cstring(triple), target);
err.into_result().unwrap();
let target_machine = LLVMCreateTargetMachine(
target,
triple,
c"generic".as_ptr(),
c"".as_ptr(),
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
);
let data_layout = LLVMCreateTargetDataLayout(target_machine);
LLVMSetTarget(module_ref, triple);
LLVMSetModuleDataLayout(module_ref, data_layout);
let mut err = ErrorMessageHolder::null();
LLVMVerifyModule(
module_ref,
llvm_sys::analysis::LLVMVerifierFailureAction::LLVMPrintMessageAction,
err.borrow_mut(),
);
err.into_result().unwrap();
let mut err = ErrorMessageHolder::null();
LLVMTargetMachineEmitToFile(
target_machine,
module_ref,
CString::new("hello.asm").unwrap().into_raw(),
LLVMCodeGenFileType::LLVMAssemblyFile,
err.borrow_mut(),
);
err.into_result().unwrap();
let mut err = ErrorMessageHolder::null();
LLVMTargetMachineEmitToFile(
target_machine,
module_ref,
CString::new("hello.o").unwrap().into_raw(),
LLVMCodeGenFileType::LLVMObjectFile,
err.borrow_mut(),
);
err.into_result().unwrap();
let module_str = from_cstring(LLVMPrintModuleToString(module_ref));
println!("{}", module_str.unwrap());
}
}
}
impl FunctionHolder {
unsafe fn compile_signature(
&self,
context: &LLVMContext,
module_ref: LLVMModuleRef,
) -> LLVMFunction {
unsafe {
let ret_type = self.data.ret.as_llvm(context.context_ref);
let mut param_types: Vec<LLVMTypeRef> = self
.data
.params
.iter()
.map(|t| t.as_llvm(context.context_ref))
.collect();
let param_ptr = param_types.as_mut_ptr();
let param_len = param_types.len();
let fn_type = LLVMFunctionType(ret_type, param_ptr, param_len as u32, 0);
let function_ref =
LLVMAddFunction(module_ref, into_cstring(&self.data.name).as_ptr(), fn_type);
LLVMFunction {
type_ref: fn_type,
value_ref: function_ref,
}
}
}
unsafe fn compile(&self, module: &mut LLVMModule) {
unsafe {
let own_function = *module.functions.get(&self.value).unwrap();
for block in &self.blocks {
let block_ref = LLVMCreateBasicBlockInContext(
module.context_ref,
into_cstring(&self.data.name).as_ptr(),
);
LLVMAppendExistingBasicBlock(own_function.value_ref, block_ref);
module.blocks.insert(block.value, block_ref);
}
for block in &self.blocks {
block.compile(module, &own_function);
}
}
}
}
impl BlockHolder {
unsafe fn compile(&self, module: &mut LLVMModule, function: &LLVMFunction) {
unsafe {
let block_ref = *module.blocks.get(&self.value).unwrap();
LLVMPositionBuilderAtEnd(module.builder_ref, block_ref);
for instruction in &self.instructions {
let key = instruction.value;
let ret = instruction.compile(module, function, block_ref);
module.values.insert(key, ret);
}
self.data
.terminator
.clone()
.expect(&format!(
"Block {} does not have a terminator!",
self.data.name
))
.compile(module, function, block_ref);
}
}
}
impl InstructionHolder {
unsafe fn compile(
&self,
module: &LLVMModule,
function: &LLVMFunction,
_block: LLVMBasicBlockRef,
) -> LLVMValue {
let _ty = self.value.get_type(module.builder).unwrap();
let val = unsafe {
use super::InstructionKind::*;
match &self.data.kind {
Param(nth) => LLVMGetParam(function.value_ref, *nth as u32),
Constant(val) => val.as_llvm(module.context_ref),
Add(lhs, rhs) => {
let lhs_val = module.values.get(&lhs).unwrap().value_ref;
let rhs_val = module.values.get(&rhs).unwrap().value_ref;
LLVMBuildAdd(module.builder_ref, lhs_val, rhs_val, c"add".as_ptr())
}
Sub(lhs, rhs) => {
let lhs_val = module.values.get(&lhs).unwrap().value_ref;
let rhs_val = module.values.get(&rhs).unwrap().value_ref;
LLVMBuildSub(module.builder_ref, lhs_val, rhs_val, c"sub".as_ptr())
}
ICmp(pred, lhs, rhs) => {
let lhs = module.values.get(&lhs).unwrap();
let rhs_val = module.values.get(&rhs).unwrap().value_ref;
LLVMBuildICmp(
module.builder_ref,
// Signedness from LHS
pred.as_llvm(lhs._ty.signed()),
lhs.value_ref,
rhs_val,
c"icmp".as_ptr(),
)
}
FunctionCall(function_value, instruction_values) => {
let fun = module.functions.get(&function_value).unwrap();
let mut param_list: Vec<LLVMValueRef> = instruction_values
.iter()
.map(|i| module.values.get(i).unwrap().value_ref)
.collect();
LLVMBuildCall2(
module.builder_ref,
fun.type_ref,
fun.value_ref,
param_list.as_mut_ptr(),
param_list.len() as u32,
c"call".as_ptr(),
)
}
Phi(values) => {
let mut inc_values = Vec::new();
let mut inc_blocks = Vec::new();
for item in values {
inc_values.push(module.values.get(&item).unwrap().value_ref);
inc_blocks.push(*module.blocks.get(&item.0).unwrap());
}
let phi = LLVMBuildPhi(
module.builder_ref,
_ty.as_llvm(module.context_ref),
c"phi".as_ptr(),
);
LLVMAddIncoming(
phi,
inc_values.as_mut_ptr(),
inc_blocks.as_mut_ptr(),
values.len() as u32,
);
phi
}
}
};
LLVMValue {
_ty,
value_ref: val,
}
}
}
impl TerminatorKind {
fn compile(
&self,
module: &LLVMModule,
_function: &LLVMFunction,
_block: LLVMBasicBlockRef,
) -> LLVMValue {
let _ty = self.get_type(module.builder).unwrap();
let val = unsafe {
match self {
TerminatorKind::Ret(val) => {
let value = module.values.get(val).unwrap();
LLVMBuildRet(module.builder_ref, value.value_ref)
}
TerminatorKind::Branch(block_value) => {
let dest = *module.blocks.get(block_value).unwrap();
LLVMBuildBr(module.builder_ref, dest)
}
TerminatorKind::CondBr(cond, then_b, else_b) => {
let cond_val = module.values.get(cond).unwrap().value_ref;
let then_bb = *module.blocks.get(then_b).unwrap();
let else_bb = *module.blocks.get(else_b).unwrap();
LLVMBuildCondBr(module.builder_ref, cond_val, then_bb, else_bb)
}
}
};
LLVMValue {
_ty,
value_ref: val,
}
}
}
impl IntPredicate {
fn as_llvm(&self, signed: bool) -> LLVMIntPredicate {
use IntPredicate::*;
use LLVMIntPredicate::*;
match (self, signed) {
(LessThan, true) => LLVMIntSLT,
(GreaterThan, true) => LLVMIntSGT,
(LessThan, false) => LLVMIntULT,
(GreaterThan, false) => LLVMIntUGT,
}
}
}
impl ConstValue {
fn as_llvm(&self, context: LLVMContextRef) -> LLVMValueRef {
unsafe {
let t = self.get_type().as_llvm(context);
match *self {
ConstValue::Bool(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::I8(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::I16(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::I32(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::I64(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::I128(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::U8(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::U16(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::U32(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::U64(val) => LLVMConstInt(t, val as u64, 1),
ConstValue::U128(val) => LLVMConstInt(t, val as u64, 1),
}
}
}
}
impl Type {
fn as_llvm(&self, context: LLVMContextRef) -> LLVMTypeRef {
use Type::*;
unsafe {
match self {
I8 | U8 => LLVMInt8TypeInContext(context),
I16 | U16 => LLVMInt16TypeInContext(context),
I32 | U32 => LLVMInt32TypeInContext(context),
I64 | U64 => LLVMInt64TypeInContext(context),
I128 | U128 => LLVMInt128TypeInContext(context),
Bool => LLVMInt1TypeInContext(context),
Void => LLVMVoidType(),
}
}
}
}

View File

@ -1,106 +0,0 @@
use std::fmt::Debug;
use crate::{InstructionData, InstructionKind, IntPredicate, TerminatorKind, builder::*};
impl Debug for ModuleHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(&format!("Module({})", self.data.name))
.field(&self.value)
.field(&self.functions)
.finish()
}
}
impl Debug for FunctionHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(&format!(
"{}({:?}) -> {:?}",
self.data.name, self.data.params, self.data.ret
))
.field(&self.blocks)
.finish()
}
}
impl Debug for BlockHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(&format!("Block({})", self.data.name))
.field(&self.value)
.field(&self.instructions)
.field(&self.data.terminator)
.finish()
}
}
impl Debug for InstructionHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?} = {:?}", &self.value, &self.data)
}
}
impl Debug for InstructionData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.kind.fmt(f)
}
}
impl Debug for ModuleValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "M[{}]", &self.0)
}
}
impl Debug for FunctionValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "F[{}, {}]", &self.0.0, &self.1,)
}
}
impl Debug for BlockValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "B[{}, {}, {}]", &self.0.0.0, &self.0.1, self.1)
}
}
impl Debug for InstructionValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"I<{}-{}-{}-{}>",
&self.0.0.0.0, &self.0.0.1, &self.0.1, self.1
)
}
}
impl Debug for InstructionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Param(nth) => write!(f, "Param({})", &nth),
Self::Constant(c) => write!(f, "{:?}", &c),
Self::Add(lhs, rhs) => write!(f, "{:?} + {:?}", &lhs, &rhs),
Self::Sub(lhs, rhs) => write!(f, "{:?} + {:?}", &lhs, &rhs),
Self::Phi(val) => write!(f, "Phi: {:?}", &val),
Self::ICmp(cmp, lhs, rhs) => write!(f, "{:?} {:?} {:?}", &lhs, &cmp, &rhs),
Self::FunctionCall(fun, params) => write!(f, "{:?}({:?})", &fun, &params),
}
}
}
impl Debug for IntPredicate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::LessThan => write!(f, "<"),
Self::GreaterThan => write!(f, ">"),
}
}
}
impl Debug for TerminatorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Ret(val) => write!(f, "Ret {:?}", &val),
Self::Branch(val) => write!(f, "Br {:?}", &val),
Self::CondBr(cond, b1, b2) => write!(f, "CondBr {:?} ? {:?} : {:?}", &cond, &b1, &b2),
}
}
}

View File

@ -1,195 +1,454 @@
use std::ffi::CString;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::net::Incoming;
use std::ptr::null_mut;
use builder::{BlockValue, Builder, FunctionValue, InstructionValue, ModuleValue}; use llvm_sys::analysis::LLVMVerifyModule;
use llvm_sys::target::{
LLVM_InitializeAllAsmParsers, LLVM_InitializeAllAsmPrinters, LLVM_InitializeAllTargetInfos,
LLVM_InitializeAllTargetMCs, LLVM_InitializeAllTargets, LLVMSetModuleDataLayout,
};
use llvm_sys::target_machine::{
LLVMCodeGenFileType, LLVMCreateTargetDataLayout, LLVMCreateTargetMachine,
LLVMGetDefaultTargetTriple, LLVMGetTargetFromTriple, LLVMTargetMachineEmitToFile,
};
use llvm_sys::{LLVMBuilder, LLVMContext, LLVMIntPredicate, core::*, prelude::*};
use types::{BasicType, BasicValue, FunctionType, IntegerType, Value};
use util::{ErrorMessageHolder, from_cstring, into_cstring};
pub mod builder; pub mod types;
pub mod compile;
mod debug;
mod util; mod util;
// pub struct InstructionValue(BlockValue, usize); pub enum IntPredicate {
SLT,
SGT,
ULT,
UGT,
}
impl IntPredicate {
pub fn as_llvm(&self) -> LLVMIntPredicate {
match *self {
Self::SLT => LLVMIntPredicate::LLVMIntSLT,
Self::SGT => LLVMIntPredicate::LLVMIntSGT,
Self::ULT => LLVMIntPredicate::LLVMIntULT,
Self::UGT => LLVMIntPredicate::LLVMIntUGT,
}
}
}
#[derive(Debug)]
pub struct Context { pub struct Context {
builder: Builder, pub(crate) context_ref: *mut LLVMContext,
pub(crate) builder_ref: *mut LLVMBuilder,
} }
impl Context { impl Context {
pub fn new() -> Context { pub fn new() -> Context {
unsafe {
// Set up a context, module and builder in that context.
let context = LLVMContextCreate();
let builder = LLVMCreateBuilderInContext(context);
Context { Context {
builder: Builder::new(), context_ref: context,
builder_ref: builder,
}
} }
} }
pub fn module<'ctx>(&'ctx self, name: &str) -> Module<'ctx> { pub fn type_i1<'a>(&'a self) -> IntegerType<'a> {
let value = self.builder.add_module(ModuleData { IntegerType::in_context(&self, 1)
name: name.to_owned(),
});
Module {
phantom: PhantomData,
builder: self.builder.clone(),
value,
} }
pub fn type_i8<'a>(&'a self) -> IntegerType<'a> {
IntegerType::in_context(&self, 8)
}
pub fn type_i16<'a>(&'a self) -> IntegerType<'a> {
IntegerType::in_context(&self, 16)
}
pub fn type_i32<'a>(&'a self) -> IntegerType<'a> {
IntegerType::in_context(&self, 32)
}
pub fn module(&self, name: &str) -> Module {
Module::with_name(self, name)
} }
} }
#[derive(Debug, Clone, Hash)] impl Drop for Context {
pub struct ModuleData { fn drop(&mut self) {
name: String, // Clean up. Values created in the context mostly get cleaned up there.
unsafe {
LLVMDisposeBuilder(self.builder_ref);
LLVMContextDispose(self.context_ref);
}
}
} }
pub struct Module<'ctx> { pub struct Module<'ctx> {
phantom: PhantomData<&'ctx ()>, context: &'ctx Context,
builder: Builder, module_ref: LLVMModuleRef,
value: ModuleValue, name: CString,
} }
impl<'ctx> Module<'ctx> { impl<'ctx> Module<'ctx> {
pub fn function(&mut self, name: &str, ret: Type, params: Vec<Type>) -> Function<'ctx> { fn with_name(context: &'ctx Context, name: &str) -> Module<'ctx> {
unsafe { unsafe {
let cstring_name = into_cstring(name);
let module_ref =
LLVMModuleCreateWithNameInContext(cstring_name.as_ptr(), context.context_ref);
Module {
context,
module_ref,
name: cstring_name,
}
}
}
pub fn add_function(&'ctx self, fn_type: FunctionType<'ctx>, name: &str) -> Function<'ctx> {
unsafe {
let name_cstring = into_cstring(name);
let function_ref =
LLVMAddFunction(self.module_ref, name_cstring.as_ptr(), fn_type.llvm_type());
Function { Function {
phantom: PhantomData, module: self,
builder: self.builder.clone(), fn_type,
value: self.builder.add_function( name: name_cstring,
&self.value, fn_ref: function_ref,
FunctionData {
name: name.to_owned(),
ret,
params,
},
),
} }
} }
} }
pub fn value(&self) -> ModuleValue { pub fn print_to_string(&self) -> Result<String, String> {
self.value unsafe {
LLVM_InitializeAllTargets();
LLVM_InitializeAllTargetInfos();
LLVM_InitializeAllTargetMCs();
LLVM_InitializeAllAsmParsers();
LLVM_InitializeAllAsmPrinters();
let triple = LLVMGetDefaultTargetTriple();
let mut target: _ = null_mut();
let mut err = ErrorMessageHolder::null();
LLVMGetTargetFromTriple(triple, &mut target, err.borrow_mut());
println!("{:?}, {:?}", from_cstring(triple), target);
err.into_result().unwrap();
let target_machine = LLVMCreateTargetMachine(
target,
triple,
c"generic".as_ptr(),
c"".as_ptr(),
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
);
let data_layout = LLVMCreateTargetDataLayout(target_machine);
LLVMSetTarget(self.module_ref, triple);
LLVMSetModuleDataLayout(self.module_ref, data_layout);
let mut err = ErrorMessageHolder::null();
LLVMVerifyModule(
self.module_ref,
llvm_sys::analysis::LLVMVerifierFailureAction::LLVMPrintMessageAction,
err.borrow_mut(),
);
err.into_result().unwrap();
let mut err = ErrorMessageHolder::null();
LLVMTargetMachineEmitToFile(
target_machine,
self.module_ref,
CString::new("hello.asm").unwrap().into_raw(),
LLVMCodeGenFileType::LLVMAssemblyFile,
err.borrow_mut(),
);
err.into_result().unwrap();
let mut err = ErrorMessageHolder::null();
LLVMTargetMachineEmitToFile(
target_machine,
self.module_ref,
CString::new("hello.o").unwrap().into_raw(),
LLVMCodeGenFileType::LLVMObjectFile,
err.borrow_mut(),
);
err.into_result().unwrap();
from_cstring(LLVMPrintModuleToString(self.module_ref)).ok_or("UTF-8 error".to_owned())
}
} }
} }
#[derive(Debug, Clone, Hash)] impl<'a> Drop for Module<'a> {
pub struct FunctionData { fn drop(&mut self) {
name: String, // Clean up. Values created in the context mostly get cleaned up there.
ret: Type, unsafe {
params: Vec<Type>, LLVMDisposeModule(self.module_ref);
}
}
} }
#[derive(Clone)]
pub struct Function<'ctx> { pub struct Function<'ctx> {
phantom: PhantomData<&'ctx ()>, module: &'ctx Module<'ctx>,
builder: Builder, name: CString,
value: FunctionValue, fn_type: FunctionType<'ctx>,
fn_ref: LLVMValueRef,
} }
impl<'ctx> Function<'ctx> { impl<'ctx> Function<'ctx> {
pub fn block(&self, name: &str) -> Block<'ctx> { pub fn block<T: Into<String>>(&'ctx self, name: T) -> BasicBlock<'ctx> {
unsafe { BasicBlock::in_function(&self, name.into())
Block {
phantom: PhantomData,
builder: self.builder.clone(),
value: self.builder.add_block(
&self.value,
BlockData {
name: name.to_owned(),
terminator: None,
},
),
}
}
} }
pub fn value(&self) -> FunctionValue { pub fn get_param<T: BasicValue<'ctx>>(
self.value &'ctx self,
nth: usize,
param_type: T::BaseType,
) -> Result<T, String> {
if let Some(actual_type) = self.fn_type.param_types.iter().nth(nth) {
if param_type.llvm_type() != *actual_type {
return Err(String::from("Wrong type"));
}
} else {
return Err(String::from("nth too large"));
}
unsafe { Ok(T::from_llvm(LLVMGetParam(self.fn_ref, nth as u32))) }
} }
} }
#[derive(Debug, Clone, Hash)] pub struct BasicBlock<'ctx> {
pub struct BlockData { function: &'ctx Function<'ctx>,
builder_ref: LLVMBuilderRef,
name: String, name: String,
terminator: Option<TerminatorKind>, blockref: LLVMBasicBlockRef,
inserted: bool,
} }
pub struct Block<'builder> { impl<'ctx> BasicBlock<'ctx> {
phantom: PhantomData<&'builder ()>, fn in_function(function: &'ctx Function<'ctx>, name: String) -> BasicBlock<'ctx> {
builder: Builder,
value: BlockValue,
}
impl<'builder> Block<'builder> {
pub fn build(&mut self, instruction: InstructionKind) -> Result<InstructionValue, ()> {
unsafe { unsafe {
self.builder let block_name = into_cstring(name.clone());
.add_instruction(&self.value, InstructionData { kind: instruction }) let block_ref = LLVMCreateBasicBlockInContext(
function.module.context.context_ref,
block_name.as_ptr(),
);
LLVMAppendExistingBasicBlock(function.fn_ref, block_ref);
BasicBlock {
function: function,
builder_ref: function.module.context.builder_ref,
name,
blockref: block_ref,
inserted: false,
}
} }
} }
pub fn terminate(&mut self, instruction: TerminatorKind) -> Result<(), ()> { #[must_use]
unsafe { self.builder.terminate(&self.value, instruction) } pub fn integer_compare<T: BasicValue<'ctx>>(
&self,
lhs: &T,
rhs: &T,
comparison: &IntPredicate,
name: &str,
) -> Result<T, ()> {
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
let value = LLVMBuildICmp(
self.builder_ref,
comparison.as_llvm(),
lhs.llvm_value(),
rhs.llvm_value(),
into_cstring(name).as_ptr(),
);
Ok(T::from_llvm(value))
}
} }
pub fn value(&self) -> BlockValue { #[must_use]
self.value pub fn call<T: BasicValue<'ctx>>(
&self,
callee: &Function<'ctx>,
params: Vec<Value<'ctx>>,
name: &str,
) -> Result<T, ()> {
if params.len() != callee.fn_type.param_types.len() {
return Err(()); // TODO invalid amount of parameters
}
for (t1, t2) in callee.fn_type.param_types.iter().zip(&params) {
if t1 != &t2.llvm_type() {
return Err(()); // TODO wrong types in parameters
}
}
if !T::BaseType::is_type(callee.fn_type.return_type) {
return Err(()); // TODO wrong return type
}
unsafe {
let mut param_list: Vec<LLVMValueRef> = params.iter().map(|p| p.llvm_value()).collect();
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
let ret_val = LLVMBuildCall2(
self.builder_ref,
callee.fn_type.llvm_type(),
callee.fn_ref,
param_list.as_mut_ptr(),
param_list.len() as u32,
into_cstring(name).as_ptr(),
);
Ok(T::from_llvm(ret_val))
}
}
#[must_use]
pub fn add<T: BasicValue<'ctx>>(&self, lhs: &T, rhs: &T, name: &str) -> Result<T, ()> {
if lhs.llvm_type() != rhs.llvm_type() {
return Err(()); // TODO error
}
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
let add_value_ref = LLVMBuildAdd(
self.builder_ref,
lhs.llvm_value(),
rhs.llvm_value(),
into_cstring(name).as_ptr(),
);
Ok(T::from_llvm(add_value_ref))
}
}
#[must_use]
pub fn sub<T: BasicValue<'ctx>>(&self, lhs: &T, rhs: &T, name: &str) -> Result<T, ()> {
dbg!(lhs, rhs);
dbg!(lhs.llvm_type(), rhs.llvm_type());
if lhs.llvm_type() != rhs.llvm_type() {
return Err(()); // TODO error
}
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
let add_value_ref = LLVMBuildSub(
self.builder_ref,
lhs.llvm_value(),
rhs.llvm_value(),
into_cstring(name).as_ptr(),
);
Ok(T::from_llvm(add_value_ref))
}
}
#[must_use]
pub fn phi<PhiValue: BasicValue<'ctx>>(
&self,
phi_type: &PhiValue::BaseType,
name: &str,
) -> Result<PhiBuilder<'ctx, PhiValue>, ()> {
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
let phi_node = LLVMBuildPhi(
self.builder_ref,
phi_type.llvm_type(),
into_cstring(name).as_ptr(),
);
Ok(PhiBuilder::new(phi_node))
}
}
#[must_use]
pub fn br(&mut self, into: &BasicBlock<'ctx>) -> Result<(), ()> {
self.try_insert()?;
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
LLVMBuildBr(self.builder_ref, into.blockref);
Ok(())
}
}
#[must_use]
pub fn conditional_br<T: BasicValue<'ctx>>(
&mut self,
condition: &T,
lhs: &BasicBlock<'ctx>,
rhs: &BasicBlock<'ctx>,
) -> Result<(), ()> {
self.try_insert()?;
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
LLVMBuildCondBr(
self.builder_ref,
condition.llvm_value(),
lhs.blockref,
rhs.blockref,
);
Ok(())
}
}
#[must_use]
pub fn ret<T: BasicValue<'ctx>>(&mut self, return_value: &T) -> Result<(), ()> {
if self.function.fn_type.return_type != return_value.llvm_type() {
return Err(());
}
self.try_insert()?;
unsafe {
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
LLVMBuildRet(self.builder_ref, return_value.llvm_value());
Ok(())
}
}
fn try_insert(&mut self) -> Result<(), ()> {
if self.inserted {
return Err(());
}
self.inserted = true;
Ok(())
} }
} }
#[derive(Clone, Hash)] impl<'ctx> Drop for BasicBlock<'ctx> {
pub struct InstructionData { fn drop(&mut self) {
kind: InstructionKind, if !self.inserted {
unsafe {
LLVMDeleteBasicBlock(self.blockref);
}
}
}
} }
#[derive(Clone, Copy, Hash)] pub struct PhiBuilder<'ctx, PhiValue: BasicValue<'ctx>> {
pub enum IntPredicate { phi_node: LLVMValueRef,
LessThan, phantom: PhantomData<&'ctx PhiValue>,
GreaterThan,
} }
#[derive(Clone, Hash)] impl<'ctx, PhiValue: BasicValue<'ctx>> PhiBuilder<'ctx, PhiValue> {
pub enum InstructionKind { fn new(phi_node: LLVMValueRef) -> PhiBuilder<'ctx, PhiValue> {
Param(usize), PhiBuilder {
Constant(ConstValue), phi_node,
Add(InstructionValue, InstructionValue), phantom: PhantomData,
Sub(InstructionValue, InstructionValue), }
Phi(Vec<InstructionValue>), }
/// Integer Comparison pub fn add_incoming(&self, value: &PhiValue, block: &BasicBlock<'ctx>) -> &Self {
ICmp(IntPredicate, InstructionValue, InstructionValue), let mut values = vec![value.llvm_value()];
let mut blocks = vec![block.blockref];
unsafe {
LLVMAddIncoming(
self.phi_node,
values.as_mut_ptr(),
blocks.as_mut_ptr(),
values.len() as u32,
);
self
}
}
FunctionCall(FunctionValue, Vec<InstructionValue>), pub fn build(&self) -> PhiValue {
} unsafe { PhiValue::from_llvm(self.phi_node) }
}
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum Type {
I8,
I16,
I32,
I64,
I128,
U8,
U16,
U32,
U64,
U128,
Bool,
Void,
}
#[derive(Debug, Clone, Hash)]
pub enum ConstValue {
I8(i8),
I16(i16),
I32(i32),
I64(i64),
I128(i128),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
Bool(bool),
}
#[derive(Clone, Hash)]
pub enum TerminatorKind {
Ret(InstructionValue),
Branch(BlockValue),
CondBr(InstructionValue, BlockValue, BlockValue),
} }

336
reid-llvm-lib/src/types.rs Normal file
View File

@ -0,0 +1,336 @@
use std::{any::Any, marker::PhantomData, ptr::null_mut};
use llvm_sys::{
LLVMTypeKind,
core::*,
prelude::{LLVMTypeRef, LLVMValueRef},
};
use crate::{BasicBlock, Context, PhiBuilder};
pub trait BasicType<'ctx> {
fn llvm_type(&self) -> LLVMTypeRef;
fn is_type(llvm_type: LLVMTypeRef) -> bool
where
Self: Sized;
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
where
Self: Sized;
fn function_type(&self, params: Vec<TypeEnum>) -> FunctionType<'ctx> {
unsafe {
let mut typerefs: Vec<LLVMTypeRef> = params.iter().map(|b| b.llvm_type()).collect();
let param_ptr = typerefs.as_mut_ptr();
let param_len = typerefs.len();
FunctionType {
phantom: PhantomData,
return_type: self.llvm_type(),
param_types: typerefs,
type_ref: LLVMFunctionType(self.llvm_type(), param_ptr, param_len as u32, 0),
}
}
}
fn array_type(&'ctx self, length: u32) -> ArrayType<'ctx>
where
Self: Sized,
{
ArrayType {
phantom: PhantomData,
element_type: self.llvm_type(),
length,
type_ref: unsafe { LLVMArrayType(self.llvm_type(), length) },
}
}
}
impl<'ctx> PartialEq for &dyn BasicType<'ctx> {
fn eq(&self, other: &Self) -> bool {
self.llvm_type() == other.llvm_type()
}
}
impl<'ctx> PartialEq<LLVMTypeRef> for &dyn BasicType<'ctx> {
fn eq(&self, other: &LLVMTypeRef) -> bool {
self.llvm_type() == *other
}
}
#[derive(Clone, Copy)]
pub struct IntegerType<'ctx> {
context: &'ctx Context,
type_ref: LLVMTypeRef,
}
impl<'ctx> BasicType<'ctx> for IntegerType<'ctx> {
fn llvm_type(&self) -> LLVMTypeRef {
self.type_ref
}
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
where
Self: Sized,
{
IntegerType {
context,
type_ref: llvm_type,
}
}
fn is_type(llvm_type: LLVMTypeRef) -> bool {
unsafe { LLVMGetTypeKind(llvm_type) == LLVMTypeKind::LLVMIntegerTypeKind }
}
}
impl<'ctx> IntegerType<'ctx> {
pub(crate) fn in_context(context: &Context, width: u32) -> IntegerType {
let type_ref = unsafe {
match width {
128 => LLVMInt128TypeInContext(context.context_ref),
64 => LLVMInt64TypeInContext(context.context_ref),
32 => LLVMInt32TypeInContext(context.context_ref),
16 => LLVMInt16TypeInContext(context.context_ref),
8 => LLVMInt8TypeInContext(context.context_ref),
1 => LLVMInt1TypeInContext(context.context_ref),
_ => LLVMIntTypeInContext(context.context_ref, width),
}
};
IntegerType { context, type_ref }
}
pub fn from_signed(&self, value: i64) -> IntegerValue<'ctx> {
self.from_const(value as u64, true)
}
pub fn from_unsigned(&self, value: i64) -> IntegerValue<'ctx> {
self.from_const(value as u64, false)
}
fn from_const(&self, value: u64, sign: bool) -> IntegerValue<'ctx> {
unsafe {
IntegerValue::from_llvm(LLVMConstInt(
self.type_ref,
value,
match sign {
true => 1,
false => 0,
},
))
}
}
}
#[derive(Clone)]
pub struct FunctionType<'ctx> {
phantom: PhantomData<&'ctx ()>,
pub(crate) return_type: LLVMTypeRef,
pub(crate) param_types: Vec<LLVMTypeRef>,
type_ref: LLVMTypeRef,
}
impl<'ctx> BasicType<'ctx> for FunctionType<'ctx> {
fn llvm_type(&self) -> LLVMTypeRef {
self.type_ref
}
unsafe fn from_llvm(_context: &'ctx Context, fn_type: LLVMTypeRef) -> Self
where
Self: Sized,
{
unsafe {
let param_count = LLVMCountParamTypes(fn_type);
let param_types_ptr: *mut LLVMTypeRef = null_mut();
LLVMGetParamTypes(fn_type, param_types_ptr);
let param_types: Vec<LLVMTypeRef> =
std::slice::from_raw_parts(param_types_ptr, param_count as usize)
.iter()
.map(|t| *t)
.collect();
FunctionType {
phantom: PhantomData,
return_type: LLVMGetReturnType(fn_type),
param_types,
type_ref: fn_type,
}
}
}
fn is_type(llvm_type: LLVMTypeRef) -> bool {
unsafe { LLVMGetTypeKind(llvm_type) == LLVMTypeKind::LLVMFunctionTypeKind }
}
}
#[derive(Clone, Copy)]
pub struct ArrayType<'ctx> {
phantom: PhantomData<&'ctx ()>,
element_type: LLVMTypeRef,
length: u32,
type_ref: LLVMTypeRef,
}
impl<'ctx> BasicType<'ctx> for ArrayType<'ctx> {
fn llvm_type(&self) -> LLVMTypeRef {
self.type_ref
}
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
where
Self: Sized,
{
unsafe {
let length = LLVMGetArrayLength(llvm_type);
todo!()
}
}
fn is_type(llvm_type: LLVMTypeRef) -> bool {
unsafe { LLVMGetTypeKind(llvm_type) == LLVMTypeKind::LLVMArrayTypeKind }
}
}
#[derive(Clone)]
pub enum TypeEnum<'ctx> {
Integer(IntegerType<'ctx>),
Array(ArrayType<'ctx>),
Function(FunctionType<'ctx>),
}
impl<'ctx> From<IntegerType<'ctx>> for TypeEnum<'ctx> {
fn from(int: IntegerType<'ctx>) -> Self {
TypeEnum::Integer(int)
}
}
impl<'ctx> From<ArrayType<'ctx>> for TypeEnum<'ctx> {
fn from(arr: ArrayType<'ctx>) -> Self {
TypeEnum::Array(arr)
}
}
impl<'ctx> From<FunctionType<'ctx>> for TypeEnum<'ctx> {
fn from(func: FunctionType<'ctx>) -> Self {
TypeEnum::Function(func)
}
}
impl<'ctx> TypeEnum<'ctx> {
fn inner_basic(&'ctx self) -> &'ctx dyn BasicType<'ctx> {
match self {
TypeEnum::Integer(integer_type) => integer_type,
TypeEnum::Array(array_type) => array_type,
TypeEnum::Function(function_type) => function_type,
}
}
}
impl<'ctx> BasicType<'ctx> for TypeEnum<'ctx> {
fn llvm_type(&self) -> LLVMTypeRef {
self.inner_basic().llvm_type()
}
fn is_type(llvm_type: LLVMTypeRef) -> bool
where
Self: Sized,
{
true
}
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
where
Self: Sized,
{
unsafe {
match LLVMGetTypeKind(llvm_type) {
LLVMTypeKind::LLVMIntegerTypeKind => {
TypeEnum::Integer(IntegerType::from_llvm(context, llvm_type))
}
LLVMTypeKind::LLVMArrayTypeKind => {
TypeEnum::Array(ArrayType::from_llvm(context, llvm_type))
}
LLVMTypeKind::LLVMFunctionTypeKind => {
TypeEnum::Function(FunctionType::from_llvm(context, llvm_type))
}
_ => todo!(),
}
}
}
}
pub trait BasicValue<'ctx>: std::fmt::Debug {
type BaseType: BasicType<'ctx>;
unsafe fn from_llvm(value: LLVMValueRef) -> Self
where
Self: Sized;
fn llvm_value(&self) -> LLVMValueRef;
fn llvm_type(&self) -> LLVMTypeRef;
}
#[derive(Clone, Debug)]
pub struct IntegerValue<'ctx> {
phantom: PhantomData<&'ctx ()>,
pub(crate) value_ref: LLVMValueRef,
}
impl<'ctx> BasicValue<'ctx> for IntegerValue<'ctx> {
type BaseType = IntegerType<'ctx>;
unsafe fn from_llvm(value: LLVMValueRef) -> Self {
IntegerValue {
phantom: PhantomData,
value_ref: value,
}
}
fn llvm_value(&self) -> LLVMValueRef {
self.value_ref
}
fn llvm_type(&self) -> LLVMTypeRef {
unsafe { LLVMTypeOf(self.value_ref) }
}
}
#[derive(Clone, Debug)]
pub enum Value<'ctx> {
Integer(IntegerValue<'ctx>),
}
impl<'ctx> BasicValue<'ctx> for Value<'ctx> {
type BaseType = TypeEnum<'ctx>;
unsafe fn from_llvm(value: LLVMValueRef) -> Self
where
Self: Sized,
{
unsafe {
use LLVMTypeKind::*;
let llvm_type = LLVMTypeOf(value);
let type_kind = LLVMGetTypeKind(llvm_type);
match type_kind {
LLVMIntegerTypeKind => Value::Integer(IntegerValue::from_llvm(value)),
_ => panic!("asd"),
}
}
}
fn llvm_value(&self) -> LLVMValueRef {
match self {
Self::Integer(i) => i.llvm_value(),
}
}
fn llvm_type(&self) -> LLVMTypeRef {
match self {
Self::Integer(i) => i.llvm_type(),
}
}
}
impl<'ctx> From<IntegerValue<'ctx>> for Value<'ctx> {
fn from(value: IntegerValue<'ctx>) -> Self {
Value::Integer(value)
}
}

View File

@ -5,11 +5,6 @@ use std::{
use llvm_sys::error::LLVMDisposeErrorMessage; use llvm_sys::error::LLVMDisposeErrorMessage;
use crate::{
Type,
builder::{Builder, InstructionValue},
};
pub fn into_cstring<T: Into<String>>(value: T) -> CString { pub fn into_cstring<T: Into<String>>(value: T) -> CString {
let string = value.into(); let string = value.into();
unsafe { CString::from_vec_with_nul_unchecked((string + "\0").into_bytes()) } unsafe { CString::from_vec_with_nul_unchecked((string + "\0").into_bytes()) }
@ -54,17 +49,3 @@ impl Drop for ErrorMessageHolder {
} }
} }
} }
pub fn match_types(
lhs: &InstructionValue,
rhs: &InstructionValue,
builder: &Builder,
) -> Result<Type, ()> {
let lhs_type = lhs.get_type(&builder);
let rhs_type = rhs.get_type(&builder);
if let (Ok(lhs_t), Ok(rhs_t)) = (lhs_type, rhs_type) {
if lhs_t == rhs_t { Ok(lhs_t) } else { Err(()) }
} else {
Err(())
}
}

View File

@ -1,13 +1,12 @@
// Main // Main
fn main() -> u8 { fn main() {
let a = fibonacci(3); return fibonacci(10);
return a;
} }
// Fibonacci // Fibonacci
fn fibonacci(value: u8) -> u8 { fn fibonacci(value: i32) -> i32 {
if value < 3 { if value < 3 {
return 1; return 1;
} }
return 5 + fibonacci(value - 2); return fibonacci(value - 1) + fibonacci(value - 2);
} }

View File

@ -1,4 +1,4 @@
use reid::mir::{self, *}; use reid::mir::*;
use reid_lib::Context; use reid_lib::Context;
fn main() { fn main() {
@ -7,7 +7,6 @@ fn main() {
let fibonacci = FunctionDefinition { let fibonacci = FunctionDefinition {
name: fibonacci_name.clone(), name: fibonacci_name.clone(),
return_type: TypeKind::I32,
parameters: vec![(fibonacci_n.clone(), TypeKind::I32)], parameters: vec![(fibonacci_n.clone(), TypeKind::I32)],
kind: FunctionDefinitionKind::Local( kind: FunctionDefinitionKind::Local(
Block { Block {
@ -127,7 +126,6 @@ fn main() {
let main = FunctionDefinition { let main = FunctionDefinition {
name: "main".to_owned(), name: "main".to_owned(),
return_type: TypeKind::I32,
parameters: vec![], parameters: vec![],
kind: FunctionDefinitionKind::Local( kind: FunctionDefinitionKind::Local(
Block { Block {
@ -152,24 +150,22 @@ fn main() {
), ),
}; };
let mir_context = mir::Context { println!("test1");
modules: vec![Module {
let module = Module {
name: "test module".to_owned(), name: "test module".to_owned(),
imports: vec![], imports: vec![],
functions: vec![fibonacci, main], functions: vec![fibonacci, main],
}],
}; };
println!("test1");
let context = Context::new();
let codegen = mir_context.codegen(&context);
println!("test2"); println!("test2");
let context = Context::new();
let codegen_module = module.codegen(&context);
codegen.compile();
println!("test3"); println!("test3");
// match codegen_module.module.print_to_string() { match codegen_module.module.print_to_string() {
// Ok(v) => println!("{}", v), Ok(v) => println!("{}", v),
// Err(e) => println!("Err: {:?}", e), Err(e) => println!("Err: {:?}", e),
// } }
} }

View File

@ -8,22 +8,12 @@ pub struct Type(pub TypeKind, pub TokenRange);
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum TypeKind { pub enum TypeKind {
Bool,
I8,
I16,
I32, I32,
I64,
I128,
U8,
U16,
U32,
U64,
U128,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Literal { pub enum Literal {
Number(u64), I32(i32),
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -63,22 +53,13 @@ impl BinaryOperator {
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FunctionCallExpression( pub struct FunctionCallExpression(pub String, pub Vec<Expression>, pub TokenRange);
pub String,
pub Vec<Expression>,
#[allow(dead_code)] pub TokenRange,
);
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct IfExpression( pub struct IfExpression(pub Expression, pub Block, pub Option<Block>, pub TokenRange);
pub Expression,
pub Block,
pub Option<Block>,
#[allow(dead_code)] pub TokenRange,
);
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct LetStatement(pub String, pub Option<Type>, pub Expression, pub TokenRange); pub struct LetStatement(pub String, pub Expression, pub TokenRange);
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ImportStatement(Vec<String>, pub TokenRange); pub struct ImportStatement(Vec<String>, pub TokenRange);
@ -91,7 +72,6 @@ pub struct FunctionSignature {
pub name: String, pub name: String,
pub args: Vec<(String, Type)>, pub args: Vec<(String, Type)>,
pub return_type: Option<Type>, pub return_type: Option<Type>,
#[allow(dead_code)]
pub range: TokenRange, pub range: TokenRange,
} }
@ -111,7 +91,7 @@ pub struct Block(
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum BlockLevelStatement { pub enum BlockLevelStatement {
Let(LetStatement), Let(LetStatement),
Import { _i: ImportStatement }, Import(ImportStatement),
Expression(Expression), Expression(Expression),
Return(ReturnType, Expression), Return(ReturnType, Expression),
} }

View File

@ -1,7 +1,7 @@
use crate::ast::*; use crate::ast::*;
use crate::{ use crate::{
lexer::Token, lexer::Token,
token_stream::{Error, TokenStream}, token_stream::{Error, TokenRange, TokenStream},
}; };
pub trait Parse pub trait Parse
@ -15,17 +15,7 @@ impl Parse for Type {
fn parse(mut stream: TokenStream) -> Result<Self, Error> { fn parse(mut stream: TokenStream) -> Result<Self, Error> {
let kind = if let Some(Token::Identifier(ident)) = stream.next() { let kind = if let Some(Token::Identifier(ident)) = stream.next() {
Ok(match &*ident { Ok(match &*ident {
"bool" => TypeKind::Bool,
"i8" => TypeKind::I8,
"i16" => TypeKind::I16,
"i32" => TypeKind::I32, "i32" => TypeKind::I32,
"i64" => TypeKind::I64,
"i128" => TypeKind::I128,
"u8" => TypeKind::U8,
"u16" => TypeKind::U16,
"u32" => TypeKind::U32,
"u64" => TypeKind::U64,
"u128" => TypeKind::U128,
_ => panic!("asd"), _ => panic!("asd"),
}) })
} else { } else {
@ -38,37 +28,36 @@ impl Parse for Type {
impl Parse for Expression { impl Parse for Expression {
fn parse(mut stream: TokenStream) -> Result<Expression, Error> { fn parse(mut stream: TokenStream) -> Result<Expression, Error> {
let lhs = stream.parse::<PrimaryExpression>()?.0; let lhs = parse_primary_expression(&mut stream)?;
parse_binop_rhs(&mut stream, lhs, None) parse_binop_rhs(&mut stream, lhs, None)
} }
} }
#[derive(Debug)] fn parse_primary_expression(stream: &mut TokenStream) -> Result<Expression, Error> {
pub struct PrimaryExpression(Expression);
impl Parse for PrimaryExpression {
fn parse(mut stream: TokenStream) -> Result<Self, Error> {
use ExpressionKind as Kind; use ExpressionKind as Kind;
let expr = if let Ok(exp) = stream.parse() { if let Ok(exp) = stream.parse() {
Expression( Ok(Expression(
Kind::FunctionCall(Box::new(exp)), Kind::FunctionCall(Box::new(exp)),
stream.get_range().unwrap(), stream.get_range().unwrap(),
) ))
} else if let Ok(block) = stream.parse() { } else if let Ok(block) = stream.parse() {
Expression( Ok(Expression(
Kind::BlockExpr(Box::new(block)), Kind::BlockExpr(Box::new(block)),
stream.get_range().unwrap(), stream.get_range().unwrap(),
) ))
} else if let Ok(ifexpr) = stream.parse() { } else if let Ok(ifexpr) = stream.parse() {
Expression(Kind::IfExpr(Box::new(ifexpr)), stream.get_range().unwrap()) Ok(Expression(
Kind::IfExpr(Box::new(ifexpr)),
stream.get_range().unwrap(),
))
} else if let Some(token) = stream.next() { } else if let Some(token) = stream.next() {
match &token { Ok(match &token {
Token::Identifier(v) => { Token::Identifier(v) => {
Expression(Kind::VariableName(v.clone()), stream.get_range().unwrap()) Expression(Kind::VariableName(v.clone()), stream.get_range().unwrap())
} }
Token::DecimalValue(v) => Expression( Token::DecimalValue(v) => Expression(
Kind::Literal(Literal::Number(v.parse().unwrap())), Kind::Literal(Literal::I32(v.parse().unwrap())),
stream.get_range().unwrap(), stream.get_range().unwrap(),
), ),
Token::ParenOpen => { Token::ParenOpen => {
@ -77,11 +66,9 @@ impl Parse for PrimaryExpression {
exp exp
} }
_ => Err(stream.expected_err("identifier, constant or parentheses")?)?, _ => Err(stream.expected_err("identifier, constant or parentheses")?)?,
} })
} else { } else {
Err(stream.expected_err("expression")?)? Err(stream.expected_err("expression")?)?
};
Ok(PrimaryExpression(expr))
} }
} }
@ -108,7 +95,7 @@ fn parse_binop_rhs(
stream.parse_if::<BinaryOperator, _>(|b| b.get_precedence() >= expr_precedence) stream.parse_if::<BinaryOperator, _>(|b| b.get_precedence() >= expr_precedence)
{ {
let curr_token_prec = op.get_precedence(); let curr_token_prec = op.get_precedence();
let mut rhs = stream.parse::<PrimaryExpression>()?.0; let mut rhs = parse_primary_expression(stream)?;
if let Ok(next_op) = stream.parse_peek::<BinaryOperator>() { if let Ok(next_op) = stream.parse_peek::<BinaryOperator>() {
let next_prec = next_op.get_precedence(); let next_prec = next_op.get_precedence();
@ -198,7 +185,6 @@ impl Parse for LetStatement {
stream.expect(Token::Semi)?; stream.expect(Token::Semi)?;
Ok(LetStatement( Ok(LetStatement(
variable, variable,
None, // TODO add possibility to name type
expression, expression,
stream.get_range().unwrap(), stream.get_range().unwrap(),
)) ))
@ -318,9 +304,7 @@ impl Parse for BlockLevelStatement {
use BlockLevelStatement as Stmt; use BlockLevelStatement as Stmt;
Ok(match stream.peek() { Ok(match stream.peek() {
Some(Token::LetKeyword) => Stmt::Let(stream.parse()?), Some(Token::LetKeyword) => Stmt::Let(stream.parse()?),
Some(Token::ImportKeyword) => Stmt::Import { Some(Token::ImportKeyword) => Stmt::Import(stream.parse()?),
_i: stream.parse()?,
},
Some(Token::ReturnKeyword) => { Some(Token::ReturnKeyword) => {
stream.next(); stream.next();
let exp = stream.parse()?; let exp = stream.parse()?;

View File

@ -1,18 +1,257 @@
use std::collections::HashMap;
use crate::{ use crate::{
ast::{self}, ast,
mir::{self, StmtKind, VariableReference}, mir::{self, StmtKind, VariableReference},
token_stream::TokenRange,
}; };
impl mir::Context { #[derive(Clone)]
pub fn from(modules: Vec<ast::Module>) -> mir::Context { pub enum InferredType {
mir::Context { FromVariable(String, TokenRange),
modules: modules.iter().map(|m| m.process()).collect(), FunctionReturn(String, TokenRange),
Static(mir::TypeKind, TokenRange),
OneOf(Vec<InferredType>),
Void(TokenRange),
DownstreamError(IntoMIRError, TokenRange),
}
fn all_ok<T, E>(result: Vec<Result<T, E>>) -> Option<Vec<T>> {
let mut res = Vec::with_capacity(result.len());
for item in result {
if let Ok(item) = item {
res.push(item);
} else {
return None;
}
}
Some(res)
}
impl InferredType {
fn collapse(
&self,
state: &mut State,
scope: &VirtualScope,
) -> Result<mir::TypeKind, IntoMIRError> {
match self {
InferredType::FromVariable(name, token_range) => {
if let Some(inferred) = scope.get_var(name) {
let temp = inferred.collapse(state, scope);
state.note(temp)
} else {
state.err(IntoMIRError::VariableNotDefined(name.clone(), *token_range))
}
}
InferredType::FunctionReturn(name, token_range) => {
if let Some(type_kind) = scope.get_return_type(name) {
Ok(*type_kind)
} else {
state.err(IntoMIRError::VariableNotDefined(name.clone(), *token_range))
}
}
InferredType::Static(type_kind, _) => Ok(*type_kind),
InferredType::OneOf(inferred_types) => {
let collapsed = all_ok(
inferred_types
.iter()
.map(|t| {
let temp = t.collapse(state, scope);
state.note(temp)
})
.collect(),
);
if let Some(list) = collapsed {
if let Some(first) = list.first() {
if list.iter().all(|i| i == first) {
Ok((*first).into())
} else {
state.err(IntoMIRError::ConflictingType(self.get_range()))
}
} else {
state.err(IntoMIRError::VoidType(self.get_range()))
}
} else {
state.err(IntoMIRError::DownstreamError(self.get_range()))
}
}
InferredType::Void(token_range) => state.err(IntoMIRError::VoidType(*token_range)),
InferredType::DownstreamError(e, _) => state.err(e.clone()),
}
}
fn get_range(&self) -> TokenRange {
match &self {
InferredType::FromVariable(_, token_range) => *token_range,
InferredType::FunctionReturn(_, token_range) => *token_range,
InferredType::Static(_, token_range) => *token_range,
InferredType::OneOf(inferred_types) => {
inferred_types.iter().map(|i| i.get_range()).sum()
}
InferredType::Void(token_range) => *token_range,
InferredType::DownstreamError(_, range) => *range,
}
}
}
pub struct VirtualVariable {
name: String,
inferred: InferredType,
meta: mir::Metadata,
}
pub struct VirtualFunctionSignature {
name: String,
return_type: mir::TypeKind,
parameter_types: Vec<mir::TypeKind>,
metadata: mir::Metadata,
}
pub enum VirtualStorageError {
KeyAlreadyExists(String),
}
pub struct VirtualStorage<T> {
storage: HashMap<String, Vec<T>>,
}
impl<T> VirtualStorage<T> {
fn set(&mut self, name: String, value: T) -> Result<(), VirtualStorageError> {
let result = if let Some(list) = self.storage.get_mut(&name) {
list.push(value);
Err(VirtualStorageError::KeyAlreadyExists(name.clone()))
} else {
self.storage.insert(name, vec![value]);
Ok(())
};
result
}
fn get(&self, name: &String) -> Option<&T> {
if let Some(list) = self.storage.get(name) {
list.first()
} else {
None
}
}
}
impl<T> Default for VirtualStorage<T> {
fn default() -> Self {
Self {
storage: Default::default(),
}
}
}
#[derive(Clone, Debug)]
pub enum IntoMIRError {
DuplicateVariable(String, TokenRange),
DuplicateFunction(String, TokenRange),
VariableNotDefined(String, TokenRange),
FunctionNotDefined(String, TokenRange),
DownstreamError(TokenRange),
ConflictingType(TokenRange),
VoidType(TokenRange),
}
pub struct VirtualScope {
variables: VirtualStorage<VirtualVariable>,
functions: VirtualStorage<VirtualFunctionSignature>,
}
impl VirtualScope {
pub fn set_var(&mut self, variable: VirtualVariable) -> Result<(), IntoMIRError> {
let range = variable.meta.range;
match self.variables.set(variable.name.clone(), variable) {
Ok(_) => Ok(()),
Err(VirtualStorageError::KeyAlreadyExists(n)) => {
Err(IntoMIRError::DuplicateVariable(n, range))
}
}
}
pub fn set_fun(&mut self, function: VirtualFunctionSignature) -> Result<(), IntoMIRError> {
let range = function.metadata.range;
match self.functions.set(function.name.clone(), function) {
Ok(_) => Ok(()),
Err(VirtualStorageError::KeyAlreadyExists(n)) => {
Err(IntoMIRError::DuplicateVariable(n, range))
}
}
}
pub fn get_var(&self, name: &String) -> Option<&InferredType> {
self.variables.get(name).map(|v| &v.inferred)
}
pub fn get_return_type(&self, name: &String) -> Option<&mir::TypeKind> {
self.functions.get(name).map(|v| &v.return_type)
}
}
impl Default for VirtualScope {
fn default() -> Self {
Self {
variables: Default::default(),
functions: Default::default(),
}
}
}
#[derive(Debug)]
pub struct State {
errors: Vec<IntoMIRError>,
fatal: bool,
}
impl State {
fn note<T: std::fmt::Debug>(
&mut self,
value: Result<T, IntoMIRError>,
) -> Result<T, IntoMIRError> {
dbg!(&value);
if let Err(e) = &value {
self.errors.push(e.clone());
}
value
}
fn err<T>(&mut self, error: IntoMIRError) -> Result<T, IntoMIRError> {
self.errors.push(error.clone());
Err(error)
}
}
impl Default for State {
fn default() -> Self {
Self {
errors: Default::default(),
fatal: false,
} }
} }
} }
impl ast::Module { impl ast::Module {
fn process(&self) -> mir::Module { pub fn process(&self) -> mir::Module {
let mut state = State::default();
let mut scope = VirtualScope::default();
for stmt in &self.top_level_statements {
match stmt {
FunctionDefinition(ast::FunctionDefinition(signature, _, range)) => {
state.note(scope.set_fun(VirtualFunctionSignature {
name: signature.name.clone(),
return_type: signature.return_type.into(),
parameter_types: signature.args.iter().map(|p| p.1.into()).collect(),
metadata: (*range).into(),
}));
}
_ => {}
}
}
let mut imports = Vec::new(); let mut imports = Vec::new();
let mut functions = Vec::new(); let mut functions = Vec::new();
@ -25,24 +264,34 @@ impl ast::Module {
} }
} }
FunctionDefinition(ast::FunctionDefinition(signature, block, range)) => { FunctionDefinition(ast::FunctionDefinition(signature, block, range)) => {
for (name, ptype) in &signature.args {
state.note(scope.set_var(VirtualVariable {
name: name.clone(),
inferred: InferredType::Static((*ptype).into(), *range),
meta: ptype.1.into(),
}));
}
dbg!(&signature);
if let Some(mir_block) = block.process(&mut state, &mut scope) {
let def = mir::FunctionDefinition { let def = mir::FunctionDefinition {
name: signature.name.clone(), name: signature.name.clone(),
return_type: signature
.return_type
.map(|r| r.0.into())
.unwrap_or(mir::TypeKind::Void),
parameters: signature parameters: signature
.args .args
.iter() .iter()
.cloned() .cloned()
.map(|p| (p.0, p.1.into())) .map(|p| (p.0, p.1.into()))
.collect(), .collect(),
kind: mir::FunctionDefinitionKind::Local(block.into_mir(), (*range).into()), kind: mir::FunctionDefinitionKind::Local(mir_block, (*range).into()),
}; };
functions.push(def); functions.push(def);
} }
} }
} }
}
dbg!(&state);
// TODO do something with state here // TODO do something with state here
@ -55,44 +304,79 @@ impl ast::Module {
} }
impl ast::Block { impl ast::Block {
pub fn into_mir(&self) -> mir::Block { pub fn process(&self, state: &mut State, scope: &mut VirtualScope) -> Option<mir::Block> {
let mut mir_statements = Vec::new(); let mut mir_statements = Vec::new();
for statement in &self.0 { for statement in &self.0 {
let (kind, range) = match statement { let (kind, range): (Option<mir::StmtKind>, TokenRange) = match statement {
ast::BlockLevelStatement::Let(s_let) => ( ast::BlockLevelStatement::Let(s_let) => {
let res = s_let.1.infer_return_type().collapse(state, scope);
let collapsed = state.note(res);
let inferred = match &collapsed {
Ok(t) => InferredType::Static(*t, s_let.2),
Err(e) => InferredType::DownstreamError(e.clone(), s_let.2),
};
state
.note(scope.set_var(VirtualVariable {
name: s_let.0.clone(),
inferred,
meta: s_let.2.into(),
}))
.ok();
(
collapsed.ok().and_then(|t| {
s_let.1.process(state, scope).map(|e| {
mir::StmtKind::Let( mir::StmtKind::Let(
mir::VariableReference( mir::VariableReference(t, s_let.0.clone(), s_let.2.into()),
s_let e,
.1 )
.map(|t| t.0.into()) })
.unwrap_or(mir::TypeKind::Vague(mir::VagueType::Unknown)), }),
s_let.0.clone(), s_let.2,
s_let.3.into(), )
}
ast::BlockLevelStatement::Import(_) => todo!(),
ast::BlockLevelStatement::Expression(e) => (
e.process(state, scope).map(|e| StmtKind::Expression(e)),
e.1,
), ),
s_let.2.process(), ast::BlockLevelStatement::Return(_, e) => (
e.process(state, scope).map(|e| StmtKind::Expression(e)),
e.1,
), ),
s_let.3,
),
ast::BlockLevelStatement::Import { _i } => todo!(),
ast::BlockLevelStatement::Expression(e) => (StmtKind::Expression(e.process()), e.1),
ast::BlockLevelStatement::Return(_, e) => (StmtKind::Expression(e.process()), e.1),
}; };
if let Some(kind) = kind {
mir_statements.push(mir::Statement(kind, range.into())); mir_statements.push(mir::Statement(kind, range.into()));
} else {
state.fatal = true;
}
} }
let return_expression = if let Some(r) = &self.1 { let return_expression = if let Some(r) = &self.1 {
Some((r.0.into(), Box::new(r.1.process()))) if let Some(expr) = r.1.process(state, scope) {
Some((r.0.into(), Box::new(expr)))
} else {
state.fatal = true;
None?
}
} else { } else {
None None
}; };
mir::Block { Some(mir::Block {
statements: mir_statements, statements: mir_statements,
return_expression, return_expression,
meta: self.2.into(), meta: self.2.into(),
})
} }
fn infer_return_type(&self) -> InferredType {
self.1
.as_ref()
.map(|(_, expr)| expr.infer_return_type())
.unwrap_or(InferredType::Void(self.2))
} }
} }
@ -106,40 +390,111 @@ impl From<ast::ReturnType> for mir::ReturnKind {
} }
impl ast::Expression { impl ast::Expression {
fn process(&self) -> mir::Expression { fn process(&self, state: &mut State, scope: &mut VirtualScope) -> Option<mir::Expression> {
let kind = match &self.0 { let kind = match &self.0 {
ast::ExpressionKind::VariableName(name) => mir::ExprKind::Variable(VariableReference( ast::ExpressionKind::VariableName(name) => {
mir::TypeKind::Vague(mir::VagueType::Unknown), let ty = scope.get_var(name);
if let Some(ty) = ty {
let res = ty.collapse(state, scope);
state
.note(res)
.map(|result| {
mir::ExprKind::Variable(VariableReference(
result,
name.clone(), name.clone(),
self.1.into(), self.1.into(),
)), ))
ast::ExpressionKind::Literal(literal) => mir::ExprKind::Literal(literal.mir()),
ast::ExpressionKind::Binop(binary_operator, lhs, rhs) => mir::ExprKind::BinOp(
binary_operator.mir(),
Box::new(lhs.process()),
Box::new(rhs.process()),
),
ast::ExpressionKind::FunctionCall(fn_call_expr) => {
mir::ExprKind::FunctionCall(mir::FunctionCall {
name: fn_call_expr.0.clone(),
return_type: mir::TypeKind::Vague(mir::VagueType::Unknown),
parameters: fn_call_expr.1.iter().map(|e| e.process()).collect(),
}) })
.ok()
} else {
state
.err(IntoMIRError::VariableNotDefined(
name.clone(),
self.1.into(),
))
.ok()
}
}
ast::ExpressionKind::Literal(literal) => Some(mir::ExprKind::Literal(literal.mir())),
ast::ExpressionKind::Binop(binary_operator, lhs, rhs) => {
let mir_lhs = lhs.process(state, scope);
let mir_rhs = rhs.process(state, scope);
Some(mir::ExprKind::BinOp(
binary_operator.mir(),
Box::new(mir_lhs?),
Box::new(mir_rhs?),
))
}
ast::ExpressionKind::FunctionCall(fn_call_expr) => {
if let Some(fn_type) = scope.get_return_type(&fn_call_expr.0).cloned() {
let parameters = all_ok(
fn_call_expr
.1
.iter()
.map(|e| {
e.process(state, scope)
.ok_or(IntoMIRError::DownstreamError(self.1.into()))
})
.collect(),
);
if let Some(parameters) = parameters {
Some(mir::ExprKind::FunctionCall(mir::FunctionCall {
name: fn_call_expr.0.clone(),
return_type: fn_type,
parameters,
}))
} else {
None
}
} else {
state
.err(IntoMIRError::FunctionNotDefined(
fn_call_expr.0.clone(),
self.1,
))
.ok()
}
}
ast::ExpressionKind::BlockExpr(block) => {
block.process(state, scope).map(|b| mir::ExprKind::Block(b))
} }
ast::ExpressionKind::BlockExpr(block) => mir::ExprKind::Block(block.into_mir()),
ast::ExpressionKind::IfExpr(if_expression) => { ast::ExpressionKind::IfExpr(if_expression) => {
let cond = if_expression.0.process(); let cond = if_expression.0.process(state, scope);
let then_block = if_expression.1.into_mir(); let then_block = if_expression.1.process(state, scope);
let else_block = if let Some(el) = &if_expression.2 { let else_block = if let Some(el) = &if_expression.2 {
Some(el.into_mir()) Some(el.process(state, scope)?)
} else { } else {
None None
}; };
mir::ExprKind::If(mir::IfExpression(Box::new(cond), then_block, else_block)) Some(mir::ExprKind::If(mir::IfExpression(
Box::new(cond?),
then_block?,
else_block,
)))
} }
}; };
mir::Expression(kind, self.1.into()) kind.map(|k| mir::Expression(k, self.1.into()))
}
fn infer_return_type(&self) -> InferredType {
use ast::ExpressionKind::*;
match &self.0 {
VariableName(name) => InferredType::FromVariable(name.clone(), self.1),
Literal(lit) => InferredType::Static(lit.mir().as_type(), self.1),
Binop(_, lhs, rhs) => {
InferredType::OneOf(vec![lhs.infer_return_type(), rhs.infer_return_type()])
}
FunctionCall(fncall) => InferredType::FunctionReturn(fncall.0.clone(), self.1),
BlockExpr(block) => block.infer_return_type(),
IfExpr(exp) => {
let mut types = vec![exp.1.infer_return_type()];
if let Some(e) = &exp.2 {
types.push(e.infer_return_type())
}
InferredType::OneOf(types)
}
}
} }
} }
@ -160,7 +515,7 @@ impl ast::BinaryOperator {
impl ast::Literal { impl ast::Literal {
fn mir(&self) -> mir::Literal { fn mir(&self) -> mir::Literal {
match *self { match *self {
ast::Literal::Number(v) => mir::Literal::Vague(mir::VagueLiteral::Number(v)), ast::Literal::I32(v) => mir::Literal::I32(v),
} }
} }
} }
@ -168,17 +523,7 @@ impl ast::Literal {
impl From<ast::TypeKind> for mir::TypeKind { impl From<ast::TypeKind> for mir::TypeKind {
fn from(value: ast::TypeKind) -> Self { fn from(value: ast::TypeKind) -> Self {
match value { match value {
ast::TypeKind::Bool => mir::TypeKind::Bool,
ast::TypeKind::I8 => mir::TypeKind::I8,
ast::TypeKind::I16 => mir::TypeKind::I16,
ast::TypeKind::I32 => mir::TypeKind::I32, ast::TypeKind::I32 => mir::TypeKind::I32,
ast::TypeKind::I64 => mir::TypeKind::I64,
ast::TypeKind::I128 => mir::TypeKind::I128,
ast::TypeKind::U8 => mir::TypeKind::U8,
ast::TypeKind::U16 => mir::TypeKind::U16,
ast::TypeKind::U32 => mir::TypeKind::U32,
ast::TypeKind::U64 => mir::TypeKind::U64,
ast::TypeKind::U128 => mir::TypeKind::U128,
} }
} }
} }
@ -188,3 +533,12 @@ impl From<ast::Type> for mir::TypeKind {
value.0.into() value.0.into()
} }
} }
impl From<Option<ast::Type>> for mir::TypeKind {
fn from(value: Option<ast::Type>) -> Self {
match value {
Some(v) => v.into(),
None => mir::TypeKind::Void,
}
}
}

View File

@ -1,77 +1,49 @@
use std::{collections::HashMap, mem}; use std::{collections::HashMap, mem, ops::Deref};
use reid_lib::{
builder::InstructionValue, Block, ConstValue, Context, Function, InstructionKind, IntPredicate,
Module, TerminatorKind, Type,
};
use crate::mir::{self, types::ReturnType, TypeKind, VariableReference}; use crate::mir::{self, types::ReturnType, TypeKind, VariableReference};
use reid_lib::{
#[derive(Debug)] types::{BasicType, BasicValue, IntegerValue, TypeEnum, Value},
pub struct CodegenContext<'ctx> { BasicBlock, Context, Function, IntPredicate, Module,
pub modules: Vec<ModuleCodegen<'ctx>>, };
}
impl<'ctx> CodegenContext<'ctx> {
pub fn compile(&self) {
for module in &self.modules {
module.context.compile();
}
}
}
impl mir::Context {
pub fn codegen<'ctx>(&self, context: &'ctx Context) -> CodegenContext<'ctx> {
let mut modules = Vec::new();
for module in &self.modules {
modules.push(module.codegen(context));
}
CodegenContext { modules }
}
}
pub struct ModuleCodegen<'ctx> { pub struct ModuleCodegen<'ctx> {
pub context: &'ctx Context, context: &'ctx Context,
pub module: Module<'ctx>, pub module: Module<'ctx>,
} }
impl<'ctx> std::fmt::Debug for ModuleCodegen<'ctx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.context.fmt(f)
}
}
impl mir::Module { impl mir::Module {
fn codegen<'ctx>(&self, context: &'ctx Context) -> ModuleCodegen<'ctx> { pub fn codegen<'ctx>(&self, context: &'ctx Context) -> ModuleCodegen<'ctx> {
let mut module = context.module(&self.name); let module = context.module(&self.name);
let mut functions = HashMap::new(); let mut functions = HashMap::new();
for function in &self.functions { for function in &self.functions {
let param_types: Vec<Type> = function let ret_type = function.return_type().unwrap().get_type(&context);
let fn_type = ret_type.function_type(
function
.parameters .parameters
.iter() .iter()
.map(|(_, p)| p.get_type()) .map(|(_, p)| p.get_type(&context))
.collect(); .collect(),
);
let func = match &function.kind { let func = match &function.kind {
mir::FunctionDefinitionKind::Local(_, _) => { mir::FunctionDefinitionKind::Local(_, _) => {
module.function(&function.name, function.return_type.get_type(), param_types) module.add_function(fn_type, &function.name)
} }
mir::FunctionDefinitionKind::Extern => todo!(), mir::FunctionDefinitionKind::Extern(_) => todo!(),
}; };
functions.insert(function.name.clone(), func); functions.insert(function.name.clone(), func);
} }
for mir_function in &self.functions { for mir_function in &self.functions {
let function = functions.get(&mir_function.name).unwrap(); let function = functions.get(&mir_function.name).unwrap();
let mut entry = function.block("entry");
let mut stack_values = HashMap::new(); let mut stack_values = HashMap::new();
for (i, (p_name, _)) in mir_function.parameters.iter().enumerate() { for (i, (p_name, p_type)) in mir_function.parameters.iter().enumerate() {
stack_values.insert( stack_values.insert(
p_name.clone(), p_name.clone(),
entry.build(InstructionKind::Param(i)).unwrap(), function.get_param(i, p_type.get_type(&context)).unwrap(),
); );
} }
@ -79,17 +51,17 @@ impl mir::Module {
context, context,
module: &module, module: &module,
function, function,
block: entry, block: function.block("entry"),
functions: &functions, functions: functions.clone(),
stack_values, stack_values,
}; };
match &mir_function.kind { match &mir_function.kind {
mir::FunctionDefinitionKind::Local(block, _) => { mir::FunctionDefinitionKind::Local(block, _) => {
if let Some(ret) = block.codegen(&mut scope) { if let Some(ret) = block.codegen(&mut scope) {
scope.block.terminate(TerminatorKind::Ret(ret)).unwrap(); scope.block.ret(&ret).unwrap();
} }
} }
mir::FunctionDefinitionKind::Extern => {} mir::FunctionDefinitionKind::Extern(_) => {}
} }
} }
@ -97,30 +69,30 @@ impl mir::Module {
} }
} }
pub struct Scope<'ctx, 'a> { pub struct Scope<'ctx> {
context: &'ctx Context, context: &'ctx Context,
module: &'ctx Module<'ctx>, module: &'ctx Module<'ctx>,
function: &'ctx Function<'ctx>, function: &'ctx Function<'ctx>,
block: Block<'ctx>, block: BasicBlock<'ctx>,
functions: &'a HashMap<String, Function<'ctx>>, functions: HashMap<String, Function<'ctx>>,
stack_values: HashMap<String, InstructionValue>, stack_values: HashMap<String, Value<'ctx>>,
} }
impl<'ctx, 'a> Scope<'ctx, 'a> { impl<'ctx> Scope<'ctx> {
pub fn with_block(&self, block: Block<'ctx>) -> Scope<'ctx, 'a> { pub fn with_block(&self, block: BasicBlock<'ctx>) -> Scope<'ctx> {
Scope { Scope {
block, block,
function: self.function,
context: self.context, context: self.context,
function: self.function,
module: self.module, module: self.module,
functions: self.functions, functions: self.functions.clone(),
stack_values: self.stack_values.clone(), stack_values: self.stack_values.clone(),
} }
} }
/// Takes the block out from this scope, swaps the given block in it's place /// Takes the block out from this scope, swaps the given block in it's place
/// and returns the old block. /// and returns the old block.
pub fn swap_block(&mut self, block: Block<'ctx>) -> Block<'ctx> { pub fn swap_block(&mut self, block: BasicBlock<'ctx>) -> BasicBlock<'ctx> {
let mut old_block = block; let mut old_block = block;
mem::swap(&mut self.block, &mut old_block); mem::swap(&mut self.block, &mut old_block);
old_block old_block
@ -128,7 +100,7 @@ impl<'ctx, 'a> Scope<'ctx, 'a> {
} }
impl mir::Statement { impl mir::Statement {
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> { pub fn codegen<'ctx>(&self, scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
match &self.0 { match &self.0 {
mir::StmtKind::Let(VariableReference(_, name, _), expression) => { mir::StmtKind::Let(VariableReference(_, name, _), expression) => {
let value = expression.codegen(scope).unwrap(); let value = expression.codegen(scope).unwrap();
@ -143,7 +115,7 @@ impl mir::Statement {
} }
impl mir::IfExpression { impl mir::IfExpression {
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> { pub fn codegen<'ctx>(&self, scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
let condition = self.0.codegen(scope).unwrap(); let condition = self.0.codegen(scope).unwrap();
// Create blocks // Create blocks
@ -153,106 +125,82 @@ impl mir::IfExpression {
let mut then_scope = scope.with_block(then_bb); let mut then_scope = scope.with_block(then_bb);
let then_res = self.1.codegen(&mut then_scope); let then_res = self.1.codegen(&mut then_scope);
then_scope then_scope.block.br(&scope.block).ok();
.block
.terminate(TerminatorKind::Branch(scope.block.value()))
.ok();
let else_bb = scope.function.block("else"); let else_bb = scope.function.block("else");
let mut else_scope = scope.with_block(else_bb); let mut else_scope = scope.with_block(else_bb);
let else_res = if let Some(else_block) = &self.2 { let else_opt = if let Some(else_block) = &self.2 {
before_bb before_bb
.terminate(TerminatorKind::CondBr( .conditional_br(&condition, &then_scope.block, &else_scope.block)
condition,
then_scope.block.value(),
else_scope.block.value(),
))
.unwrap(); .unwrap();
let opt = else_block.codegen(&mut else_scope); let opt = else_block.codegen(&mut else_scope);
if let Some(ret) = opt { if let Some(ret) = opt {
else_scope else_scope.block.br(&scope.block).ok();
.block Some((else_scope.block, ret))
.terminate(TerminatorKind::Branch(scope.block.value()))
.ok();
Some(ret)
} else { } else {
None None
} }
} else { } else {
else_scope else_scope.block.br(&scope.block).unwrap();
.block
.terminate(TerminatorKind::Branch(scope.block.value()))
.unwrap();
before_bb before_bb
.terminate(TerminatorKind::CondBr( .conditional_br(&condition, &then_scope.block, &scope.block)
condition,
then_scope.block.value(),
scope.block.value(),
))
.unwrap(); .unwrap();
None None
}; };
if then_res.is_none() && else_res.is_none() { if then_res.is_none() && else_opt.is_none() {
None None
} else { } else if let Ok(ret_type) = self.1.return_type() {
let mut inc = Vec::from(then_res.as_slice()); let phi = scope
inc.extend(else_res); .block
.phi(&ret_type.get_type(scope.context), "phi")
.unwrap();
if let Some(then_ret) = then_res {
phi.add_incoming(&then_ret, &then_scope.block);
}
if let Some((else_bb, else_ret)) = else_opt {
phi.add_incoming(&else_ret, &else_bb);
}
Some(scope.block.build(InstructionKind::Phi(vec![])).unwrap()) Some(phi.build())
} else {
None
} }
} }
} }
impl mir::Expression { impl mir::Expression {
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> { pub fn codegen<'ctx>(&self, scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
match &self.0 { match &self.0 {
mir::ExprKind::Variable(varref) => { mir::ExprKind::Variable(varref) => {
varref.0.is_known().expect("variable type unknown");
let v = scope let v = scope
.stack_values .stack_values
.get(&varref.1) .get(&varref.1)
.expect("Variable reference not found?!"); .expect("Variable reference not found?!");
Some(v.clone()) Some(v.clone())
} }
mir::ExprKind::Literal(lit) => Some(lit.as_const(&mut scope.block)), mir::ExprKind::Literal(lit) => Some(lit.codegen(scope.context)),
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => { mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
lhs_exp
.return_type()
.expect("No ret type in lhs?")
.is_known()
.expect("lhs ret type is unknown");
rhs_exp
.return_type()
.expect("No ret type in rhs?")
.is_known()
.expect("rhs ret type is unknown");
let lhs = lhs_exp.codegen(scope).expect("lhs has no return value"); let lhs = lhs_exp.codegen(scope).expect("lhs has no return value");
let rhs = rhs_exp.codegen(scope).expect("rhs has no return value"); let rhs = rhs_exp.codegen(scope).expect("rhs has no return value");
Some(match binop { Some(match binop {
mir::BinaryOperator::Add => { mir::BinaryOperator::Add => scope.block.add(&lhs, &rhs, "add").unwrap(),
scope.block.build(InstructionKind::Add(lhs, rhs)).unwrap() mir::BinaryOperator::Minus => scope.block.sub(&lhs, &rhs, "sub").unwrap(),
}
mir::BinaryOperator::Minus => {
scope.block.build(InstructionKind::Sub(lhs, rhs)).unwrap()
}
mir::BinaryOperator::Mult => todo!(), mir::BinaryOperator::Mult => todo!(),
mir::BinaryOperator::And => todo!(), mir::BinaryOperator::And => todo!(),
mir::BinaryOperator::Logic(l) => scope mir::BinaryOperator::Logic(l) => {
let ret_type = lhs_exp.return_type().expect("No ret type in lhs?");
scope
.block .block
.build(InstructionKind::ICmp(l.int_predicate(), lhs, rhs)) .integer_compare(&lhs, &rhs, &l.int_predicate(ret_type.signed()), "cmp")
.unwrap(), .unwrap()
}
}) })
} }
mir::ExprKind::FunctionCall(call) => { mir::ExprKind::FunctionCall(call) => {
call.return_type
.is_known()
.expect("function return type unknown");
let params = call let params = call
.parameters .parameters
.iter() .iter()
@ -262,21 +210,13 @@ impl mir::Expression {
.functions .functions
.get(&call.name) .get(&call.name)
.expect("function not found!"); .expect("function not found!");
Some( Some(scope.block.call(callee, params, "call").unwrap())
scope
.block
.build(InstructionKind::FunctionCall(callee.value(), params))
.unwrap(),
)
} }
mir::ExprKind::If(if_expression) => if_expression.codegen(scope), mir::ExprKind::If(if_expression) => if_expression.codegen(scope),
mir::ExprKind::Block(block) => { mir::ExprKind::Block(block) => {
let mut inner_scope = scope.with_block(scope.function.block("inner")); let mut inner_scope = scope.with_block(scope.function.block("inner"));
if let Some(ret) = block.codegen(&mut inner_scope) { if let Some(ret) = block.codegen(&mut inner_scope) {
inner_scope inner_scope.block.br(&scope.block);
.block
.terminate(TerminatorKind::Branch(scope.block.value()))
.unwrap();
Some(ret) Some(ret)
} else { } else {
None None
@ -287,16 +227,18 @@ impl mir::Expression {
} }
impl mir::LogicOperator { impl mir::LogicOperator {
fn int_predicate(&self) -> IntPredicate { fn int_predicate(&self, signed: bool) -> IntPredicate {
match self { match (self, signed) {
mir::LogicOperator::LessThan => IntPredicate::LessThan, (mir::LogicOperator::LessThan, true) => IntPredicate::SLT,
mir::LogicOperator::GreaterThan => IntPredicate::GreaterThan, (mir::LogicOperator::GreaterThan, true) => IntPredicate::SGT,
(mir::LogicOperator::LessThan, false) => IntPredicate::ULT,
(mir::LogicOperator::GreaterThan, false) => IntPredicate::UGT,
} }
} }
} }
impl mir::Block { impl mir::Block {
pub fn codegen<'ctx, 'a>(&self, mut scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> { pub fn codegen<'ctx>(&self, mut scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
for stmt in &self.statements { for stmt in &self.statements {
stmt.codegen(&mut scope); stmt.codegen(&mut scope);
} }
@ -305,7 +247,7 @@ impl mir::Block {
let ret = expr.codegen(&mut scope).unwrap(); let ret = expr.codegen(&mut scope).unwrap();
match kind { match kind {
mir::ReturnKind::Hard => { mir::ReturnKind::Hard => {
scope.block.terminate(TerminatorKind::Ret(ret)).unwrap(); scope.block.ret(&ret).unwrap();
None None
} }
mir::ReturnKind::Soft => Some(ret), mir::ReturnKind::Soft => Some(ret),
@ -317,43 +259,21 @@ impl mir::Block {
} }
impl mir::Literal { impl mir::Literal {
pub fn as_const(&self, block: &mut Block) -> InstructionValue { pub fn codegen<'ctx>(&self, context: &'ctx Context) -> Value<'ctx> {
block.build(self.as_const_kind()).unwrap() let val: IntegerValue<'ctx> = match *self {
} mir::Literal::I32(val) => context.type_i32().from_signed(val as i64),
mir::Literal::I16(val) => context.type_i16().from_signed(val as i64),
pub fn as_const_kind(&self) -> InstructionKind { };
InstructionKind::Constant(match *self { Value::Integer(val)
mir::Literal::I8(val) => ConstValue::I8(val),
mir::Literal::I16(val) => ConstValue::I16(val),
mir::Literal::I32(val) => ConstValue::I32(val),
mir::Literal::I64(val) => ConstValue::I64(val),
mir::Literal::I128(val) => ConstValue::I128(val),
mir::Literal::U8(val) => ConstValue::U8(val),
mir::Literal::U16(val) => ConstValue::U16(val),
mir::Literal::U32(val) => ConstValue::U32(val),
mir::Literal::U64(val) => ConstValue::U64(val),
mir::Literal::U128(val) => ConstValue::U128(val),
mir::Literal::Vague(_) => panic!("Got vague literal!"),
})
} }
} }
impl TypeKind { impl TypeKind {
fn get_type(&self) -> Type { fn get_type<'ctx>(&self, context: &'ctx Context) -> TypeEnum<'ctx> {
match &self { match &self {
TypeKind::I8 => Type::I8, TypeKind::I32 => TypeEnum::Integer(context.type_i32()),
TypeKind::I16 => Type::I16, TypeKind::I16 => TypeEnum::Integer(context.type_i16()),
TypeKind::I32 => Type::I32,
TypeKind::I64 => Type::I64,
TypeKind::I128 => Type::I128,
TypeKind::U8 => Type::U8,
TypeKind::U16 => Type::U16,
TypeKind::U32 => Type::U32,
TypeKind::U64 => Type::U64,
TypeKind::U128 => Type::U128,
TypeKind::Bool => Type::Bool,
TypeKind::Void => panic!("Void not a supported type"), TypeKind::Void => panic!("Void not a supported type"),
TypeKind::Vague(_) => panic!("Tried to compile a vague type!"),
} }
} }
} }

View File

@ -1,4 +1,3 @@
use mir::typecheck::TypeCheck;
use reid_lib::Context; use reid_lib::Context;
use crate::{ast::TopLevelStatement, lexer::Token, token_stream::TokenStream}; use crate::{ast::TopLevelStatement, lexer::Token, token_stream::TokenStream};
@ -8,7 +7,6 @@ mod codegen;
mod lexer; mod lexer;
pub mod mir; pub mod mir;
mod token_stream; mod token_stream;
mod util;
// TODO: // TODO:
// 1. Make it so that TopLevelStatement can only be import or function def // 1. Make it so that TopLevelStatement can only be import or function def
@ -22,8 +20,6 @@ pub enum ReidError {
LexerError(#[from] lexer::Error), LexerError(#[from] lexer::Error),
#[error(transparent)] #[error(transparent)]
ParserError(#[from] token_stream::Error), ParserError(#[from] token_stream::Error),
#[error("Errors during typecheck: {0:?}")]
TypeCheckErrors(Vec<mir::pass::Error<mir::typecheck::ErrorKind>>),
// #[error(transparent)] // #[error(transparent)]
// CodegenError(#[from] codegen::Error), // CodegenError(#[from] codegen::Error),
} }
@ -49,29 +45,15 @@ pub fn compile(source: &str) -> Result<String, ReidError> {
}; };
dbg!(&ast_module); dbg!(&ast_module);
let mut mir_context = mir::Context::from(vec![ast_module]); let mir_module = ast_module.process();
dbg!(&mir_context); dbg!(&mir_module);
let state = mir_context.pass(&mut TypeCheck {});
dbg!(&mir_context);
dbg!(&state);
if !state.errors.is_empty() {
return Err(ReidError::TypeCheckErrors(state.errors));
}
dbg!(&mir_context);
let mut context = Context::new(); let mut context = Context::new();
let codegen_modules = mir_context.codegen(&mut context); let cogegen_module = mir_module.codegen(&mut context);
dbg!(&codegen_modules); Ok(match cogegen_module.module.print_to_string() {
codegen_modules.compile(); Ok(v) => v,
Err(e) => panic!("Err: {:?}", e),
Ok(String::new()) })
// Ok(match cogegen_module.module.print_to_string() {
// Ok(v) => v,
// Err(e) => panic!("Err: {:?}", e),
// })
} }

View File

@ -3,158 +3,53 @@
/// type-checked beforehand. /// type-checked beforehand.
use crate::token_stream::TokenRange; use crate::token_stream::TokenRange;
pub mod pass;
pub mod typecheck;
pub mod types; pub mod types;
#[derive(Default, Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct Metadata { pub struct Metadata {
pub range: TokenRange, pub range: TokenRange,
} }
impl std::fmt::Display for Metadata {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.range)
}
}
impl std::ops::Add for Metadata {
type Output = Metadata;
fn add(self, rhs: Self) -> Self::Output {
Metadata {
range: self.range + rhs.range,
}
}
}
impl From<TokenRange> for Metadata { impl From<TokenRange> for Metadata {
fn from(value: TokenRange) -> Self { fn from(value: TokenRange) -> Self {
Metadata { range: value } Metadata { range: value }
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] impl Default for Metadata {
fn default() -> Self {
Metadata {
range: Default::default(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TypeKind { pub enum TypeKind {
#[error("bool")]
Bool,
#[error("i8")]
I8,
#[error("i16")]
I16,
#[error("i32")]
I32, I32,
#[error("i64")] I16,
I64,
#[error("i128")]
I128,
#[error("u8")]
U8,
#[error("u16")]
U16,
#[error("u32")]
U32,
#[error("u64")]
U64,
#[error("u128")]
U128,
#[error("void")]
Void, Void,
#[error(transparent)]
Vague(#[from] VagueType),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum VagueType {
#[error("Unknown")]
Unknown,
#[error("Number")]
Number,
}
impl TypeKind {
pub fn is_known(&self) -> Result<TypeKind, VagueType> {
if let TypeKind::Vague(vague) = self {
Err(*vague)
} else {
Ok(*self)
}
}
} }
impl TypeKind { impl TypeKind {
pub fn signed(&self) -> bool { pub fn signed(&self) -> bool {
match self { match self {
TypeKind::Void => false, _ => true,
TypeKind::Vague(_) => false,
TypeKind::Bool => false,
TypeKind::I8 => false,
TypeKind::I16 => false,
TypeKind::I32 => false,
TypeKind::I64 => false,
TypeKind::I128 => false,
TypeKind::U8 => false,
TypeKind::U16 => false,
TypeKind::U32 => false,
TypeKind::U64 => false,
TypeKind::U128 => false,
}
}
pub fn is_maths(&self) -> bool {
use TypeKind::*;
match &self {
I8 => true,
I16 => true,
I32 => true,
I64 => true,
I128 => true,
U8 => true,
U16 => true,
U32 => true,
U64 => true,
U128 => true,
Bool => true,
Vague(_) => false,
Void => false,
} }
} }
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum Literal { pub enum Literal {
I8(i8),
I16(i16),
I32(i32), I32(i32),
I64(i64), I16(i16),
I128(i128),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
Vague(VagueLiteral),
}
#[derive(Debug, Clone, Copy)]
pub enum VagueLiteral {
Number(u64),
} }
impl Literal { impl Literal {
pub fn as_type(self: &Literal) -> TypeKind { pub fn as_type(self: &Literal) -> TypeKind {
match self { match self {
Literal::I8(_) => TypeKind::I8,
Literal::I16(_) => TypeKind::I16,
Literal::I32(_) => TypeKind::I32, Literal::I32(_) => TypeKind::I32,
Literal::I64(_) => TypeKind::I64, Literal::I16(_) => TypeKind::I16,
Literal::I128(_) => TypeKind::I128,
Literal::U8(_) => TypeKind::U8,
Literal::U16(_) => TypeKind::U16,
Literal::U32(_) => TypeKind::U32,
Literal::U64(_) => TypeKind::U64,
Literal::U128(_) => TypeKind::U128,
Literal::Vague(VagueLiteral::Number(_)) => TypeKind::Vague(VagueType::Number),
} }
} }
} }
@ -213,7 +108,6 @@ pub struct FunctionCall {
#[derive(Debug)] #[derive(Debug)]
pub struct FunctionDefinition { pub struct FunctionDefinition {
pub name: String, pub name: String,
pub return_type: TypeKind,
pub parameters: Vec<(String, TypeKind)>, pub parameters: Vec<(String, TypeKind)>,
pub kind: FunctionDefinitionKind, pub kind: FunctionDefinitionKind,
} }
@ -222,23 +116,8 @@ pub struct FunctionDefinition {
pub enum FunctionDefinitionKind { pub enum FunctionDefinitionKind {
/// Actual definition block and surrounding signature range /// Actual definition block and surrounding signature range
Local(Block, Metadata), Local(Block, Metadata),
Extern, /// Return Type
} Extern(TypeKind),
impl FunctionDefinition {
fn block_meta(&self) -> Metadata {
match &self.kind {
FunctionDefinitionKind::Local(block, _) => block.meta,
FunctionDefinitionKind::Extern => Metadata::default(),
}
}
fn signature(&self) -> Metadata {
match &self.kind {
FunctionDefinitionKind::Local(_, metadata) => *metadata,
FunctionDefinitionKind::Extern => Metadata::default(),
}
}
} }
#[derive(Debug)] #[derive(Debug)]
@ -266,8 +145,3 @@ pub struct Module {
pub imports: Vec<Import>, pub imports: Vec<Import>,
pub functions: Vec<FunctionDefinition>, pub functions: Vec<FunctionDefinition>,
} }
#[derive(Debug)]
pub struct Context {
pub modules: Vec<Module>,
}

View File

@ -1,279 +0,0 @@
use std::collections::HashMap;
use std::error::Error as STDError;
use super::*;
#[derive(thiserror::Error, Debug, Clone)]
pub enum SimplePassError {
#[error("Function not defined: {0}")]
FunctionAlreadyDefined(String),
#[error("Variable not defined: {0}")]
VariableAlreadyDefined(String),
}
#[derive(Debug, Clone)]
pub struct Error<TErr: STDError> {
metadata: Metadata,
kind: TErr,
}
impl<TErr: STDError> std::fmt::Display for Error<TErr> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Error at {}: {}", self.metadata, self.kind)
}
}
impl<TErr: STDError> STDError for Error<TErr> {
fn source(&self) -> Option<&(dyn STDError + 'static)> {
self.kind.source()
}
}
#[derive(Clone, Debug)]
pub struct Storage<T: std::fmt::Debug>(HashMap<String, T>);
#[derive(Debug)]
pub struct State<TErr: STDError> {
pub errors: Vec<Error<TErr>>,
}
impl<TErr: STDError> State<TErr> {
fn new() -> State<TErr> {
State {
errors: Default::default(),
}
}
fn or_else<U, T: Into<Metadata> + Clone + Copy>(
&mut self,
result: Result<U, TErr>,
default: U,
meta: T,
) -> U {
match result {
Ok(t) => t,
Err(e) => {
self.errors.push(Error {
metadata: meta.into(),
kind: e,
});
default
}
}
}
fn ok<T: Into<Metadata> + Clone + Copy, U>(
&mut self,
result: Result<U, TErr>,
meta: T,
) -> Option<U> {
match result {
Ok(v) => Some(v),
Err(e) => {
self.errors.push(Error {
metadata: meta.into(),
kind: e,
});
None
}
}
}
}
impl<T: std::fmt::Debug> Default for Storage<T> {
fn default() -> Self {
Self(Default::default())
}
}
impl<T: Clone + std::fmt::Debug> Storage<T> {
pub fn set(&mut self, key: String, value: T) -> Result<T, ()> {
if let Some(_) = self.0.get(&key) {
Err(())
} else {
self.0.insert(key, value.clone());
Ok(value)
}
}
pub fn get(&self, key: &String) -> Option<&T> {
self.0.get(key)
}
}
#[derive(Clone, Default, Debug)]
pub struct Scope {
pub function_returns: Storage<ScopeFunction>,
pub variables: Storage<TypeKind>,
/// Hard Return type of this scope, if inside a function
pub return_type_hint: Option<TypeKind>,
}
#[derive(Clone, Debug)]
pub struct ScopeFunction {
pub ret: TypeKind,
pub params: Vec<TypeKind>,
}
impl Scope {
pub fn inner(&self) -> Scope {
Scope {
function_returns: self.function_returns.clone(),
variables: self.variables.clone(),
return_type_hint: self.return_type_hint,
}
}
}
pub struct PassState<'st, 'sc, TError: STDError + Clone> {
state: &'st mut State<TError>,
pub scope: &'sc mut Scope,
inner: Vec<Scope>,
}
impl<'st, 'sc, TError: STDError + Clone> PassState<'st, 'sc, TError> {
fn from(state: &'st mut State<TError>, scope: &'sc mut Scope) -> Self {
PassState {
state,
scope,
inner: Vec::new(),
}
}
pub fn or_else<U, TMeta: Into<Metadata> + Clone + Copy>(
&mut self,
result: Result<U, TError>,
default: U,
meta: TMeta,
) -> U {
self.state.or_else(result, default, meta)
}
pub fn ok<TMeta: Into<Metadata> + Clone + Copy, U>(
&mut self,
result: Result<U, TError>,
meta: TMeta,
) -> Option<U> {
self.state.ok(result, meta)
}
pub fn inner(&mut self) -> PassState<TError> {
self.inner.push(self.scope.inner());
let scope = self.inner.last_mut().unwrap();
PassState {
state: self.state,
scope,
inner: Vec::new(),
}
}
}
pub trait Pass {
type TError: STDError + Clone;
fn module(&mut self, _module: &mut Module, mut _state: PassState<Self::TError>) {}
fn function(
&mut self,
_function: &mut FunctionDefinition,
mut _state: PassState<Self::TError>,
) {
}
fn block(&mut self, _block: &mut Block, mut _state: PassState<Self::TError>) {}
fn stmt(&mut self, _stmt: &mut Statement, mut _state: PassState<Self::TError>) {}
fn expr(&mut self, _expr: &mut Expression, mut _state: PassState<Self::TError>) {}
}
impl Context {
pub fn pass<T: Pass>(&mut self, pass: &mut T) -> State<T::TError> {
let mut state = State::new();
let mut scope = Scope::default();
for module in &mut self.modules {
module.pass(pass, &mut state, &mut scope);
}
state
}
}
impl Module {
fn pass<T: Pass>(&mut self, pass: &mut T, state: &mut State<T::TError>, scope: &mut Scope) {
for function in &self.functions {
scope
.function_returns
.set(
function.name.clone(),
ScopeFunction {
ret: function.return_type,
params: function.parameters.iter().map(|v| v.1).collect(),
},
)
.ok();
}
pass.module(self, PassState::from(state, scope));
for function in &mut self.functions {
function.pass(pass, state, scope);
}
}
}
impl FunctionDefinition {
fn pass<T: Pass>(&mut self, pass: &mut T, state: &mut State<T::TError>, scope: &mut Scope) {
for param in &self.parameters {
scope.variables.set(param.0.clone(), param.1).ok();
}
pass.function(self, PassState::from(state, scope));
match &mut self.kind {
FunctionDefinitionKind::Local(block, _) => {
scope.return_type_hint = Some(self.return_type);
block.pass(pass, state, scope);
}
FunctionDefinitionKind::Extern => {}
};
}
}
impl Block {
fn pass<T: Pass>(&mut self, pass: &mut T, state: &mut State<T::TError>, scope: &mut Scope) {
let mut scope = scope.inner();
for statement in &mut self.statements {
statement.pass(pass, state, &mut scope);
}
pass.block(self, PassState::from(state, &mut scope));
}
}
impl Statement {
fn pass<T: Pass>(&mut self, pass: &mut T, state: &mut State<T::TError>, scope: &mut Scope) {
match &mut self.0 {
StmtKind::Let(_, expression) => {
expression.pass(pass, state, scope);
}
StmtKind::Import(_) => todo!(),
StmtKind::Expression(expression) => {
expression.pass(pass, state, scope);
}
}
pass.stmt(self, PassState::from(state, scope));
match &mut self.0 {
StmtKind::Let(variable_reference, _) => scope
.variables
.set(variable_reference.1.clone(), variable_reference.0)
.ok(),
StmtKind::Import(_) => todo!(),
StmtKind::Expression(_) => None,
};
}
}
impl Expression {
fn pass<T: Pass>(&mut self, pass: &mut T, state: &mut State<T::TError>, scope: &mut Scope) {
pass.expr(self, PassState::from(state, scope));
}
}

View File

@ -1,352 +0,0 @@
use std::{convert::Infallible, iter};
/// This module contains code relevant to doing a type checking pass on the MIR.
use crate::{mir::*, util::try_all};
use TypeKind::*;
use VagueType::*;
use super::pass::{Pass, PassState, ScopeFunction};
#[derive(thiserror::Error, Debug, Clone)]
pub enum ErrorKind {
#[error("NULL error, should never occur!")]
Null,
#[error("Type is vague: {0}")]
TypeIsVague(VagueType),
#[error("Can not coerce {0} to vague type {1}")]
HintIsVague(TypeKind, VagueType),
#[error("Types {0} and {1} are incompatible")]
TypesIncompatible(TypeKind, TypeKind),
#[error("Variable not defined: {0}")]
VariableNotDefined(String),
#[error("Function not defined: {0}")]
FunctionNotDefined(String),
#[error("Type is vague: {0}")]
ReturnTypeMismatch(TypeKind, TypeKind),
#[error("Function not defined: {0}")]
FunctionAlreadyDefined(String),
#[error("Variable not defined: {0}")]
VariableAlreadyDefined(String),
}
pub struct TypeCheck {}
impl Pass for TypeCheck {
type TError = ErrorKind;
fn module(&mut self, module: &mut Module, mut state: PassState<ErrorKind>) {
for function in &mut module.functions {
let res = function.typecheck(&mut state);
state.ok(res, function.block_meta());
}
}
}
impl FunctionDefinition {
fn typecheck(&mut self, state: &mut PassState<ErrorKind>) -> Result<TypeKind, ErrorKind> {
for param in &self.parameters {
let param_t = state.or_else(param.1.assert_known(), Vague(Unknown), self.signature());
let res = state
.scope
.variables
.set(param.0.clone(), param_t)
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
state.ok(res, self.signature());
}
let return_type = self.return_type.clone();
let inferred = match &mut self.kind {
FunctionDefinitionKind::Local(block, _) => {
state.scope.return_type_hint = Some(self.return_type);
block.typecheck(state, Some(return_type))
}
FunctionDefinitionKind::Extern => Ok(Vague(Unknown)),
};
match inferred {
Ok(t) => try_collapse(&return_type, &t)
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t))),
Err(e) => Ok(state.or_else(Err(e), return_type, self.block_meta())),
}
}
}
impl Block {
fn typecheck(
&mut self,
state: &mut PassState<ErrorKind>,
hint_t: Option<TypeKind>,
) -> Result<TypeKind, ErrorKind> {
let mut state = state.inner();
for statement in &mut self.statements {
match &mut statement.0 {
StmtKind::Let(variable_reference, expression) => {
let res = expression.typecheck(&mut state, Some(variable_reference.0));
// If expression resolution itself was erronous, resolve as
// Unknown.
let res = state.or_else(res, Vague(Unknown), expression.1);
// Make sure the expression and variable type really is the same
let res_t = state.or_else(
res.collapse_into(&variable_reference.0),
Vague(Unknown),
variable_reference.2 + expression.1,
);
// Make sure expression/variable type is NOT vague anymore
let res_t =
state.or_else(res_t.or_default(), Vague(Unknown), variable_reference.2);
// Update typing to be more accurate
variable_reference.0 = res_t;
// Variable might already be defined, note error
let res = state
.scope
.variables
.set(variable_reference.1.clone(), variable_reference.0)
.or(Err(ErrorKind::VariableAlreadyDefined(
variable_reference.1.clone(),
)));
state.ok(res, variable_reference.2);
}
StmtKind::Import(_) => todo!(),
StmtKind::Expression(expression) => {
let res = expression.typecheck(&mut state, None);
state.ok(res, expression.1);
}
}
}
if let Some((return_kind, expr)) = &mut self.return_expression {
let ret_hint_t = match return_kind {
ReturnKind::Hard => state.scope.return_type_hint,
ReturnKind::Soft => hint_t,
};
let res = expr.typecheck(&mut state, ret_hint_t);
Ok(state.or_else(res, Vague(Unknown), expr.1))
} else {
Ok(Void)
}
}
}
impl Expression {
fn typecheck(
&mut self,
state: &mut PassState<ErrorKind>,
hint_t: Option<TypeKind>,
) -> Result<TypeKind, ErrorKind> {
match &mut self.0 {
ExprKind::Variable(var_ref) => {
dbg!(&state.scope);
let existing = state.or_else(
state
.scope
.variables
.get(&var_ref.1)
.copied()
.ok_or(ErrorKind::VariableNotDefined(var_ref.1.clone())),
Vague(Unknown),
var_ref.2,
);
// Update typing to be more accurate
var_ref.0 = state.or_else(
var_ref.0.collapse_into(&existing),
Vague(Unknown),
var_ref.2,
);
Ok(var_ref.0)
}
ExprKind::Literal(literal) => {
*literal = literal.try_coerce(hint_t)?;
Ok(literal.as_type())
}
ExprKind::BinOp(op, lhs, rhs) => {
// TODO make sure lhs and rhs can actually do this binary
// operation once relevant
let lhs_res = lhs.typecheck(state, None); // TODO
let lhs_type = state.or_else(lhs_res, Vague(Unknown), lhs.1);
let rhs_res = rhs.typecheck(state, Some(lhs_type)); // TODO
let rhs_type = state.or_else(rhs_res, Vague(Unknown), rhs.1);
if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) {
// Try to coerce both sides again with collapsed type
lhs.typecheck(state, Some(collapsed)).ok();
rhs.typecheck(state, Some(collapsed)).ok();
}
let res = lhs_type.binop_type(&op, &rhs_type)?;
Ok(res)
}
ExprKind::FunctionCall(function_call) => {
let true_function = state
.scope
.function_returns
.get(&function_call.name)
.cloned()
.ok_or(ErrorKind::FunctionNotDefined(function_call.name.clone()));
if let Ok(f) = true_function {
if function_call.parameters.len() != f.params.len() {
state.ok::<_, Infallible>(Err(ErrorKind::Null), self.1);
}
let true_params_iter = f.params.into_iter().chain(iter::repeat(Vague(Unknown)));
for (param, true_param_t) in
function_call.parameters.iter_mut().zip(true_params_iter)
{
let param_res = param.typecheck(state, Some(true_param_t));
let param_t = state.or_else(param_res, Vague(Unknown), param.1);
state.ok(param_t.collapse_into(&true_param_t), param.1);
}
// Make sure function return type is the same as the claimed
// return type
let ret_t = try_collapse(&f.ret, &function_call.return_type)?;
// Update typing to be more accurate
function_call.return_type = ret_t;
Ok(ret_t)
} else {
Ok(function_call.return_type)
}
}
ExprKind::If(IfExpression(cond, lhs, rhs)) => {
// TODO make sure cond_res is Boolean here
let cond_res = cond.typecheck(state, Some(Bool));
let cond_t = state.or_else(cond_res, Vague(Unknown), cond.1);
state.ok(cond_t.collapse_into(&Bool), cond.1);
let lhs_res = lhs.typecheck(state, hint_t);
let lhs_type = state.or_else(lhs_res, Vague(Unknown), lhs.meta);
let rhs_type = if let Some(rhs) = rhs {
let res = rhs.typecheck(state, hint_t);
state.or_else(res, Vague(Unknown), rhs.meta)
} else {
Vague(Unknown)
};
lhs_type.collapse_into(&rhs_type)
}
ExprKind::Block(block) => block.typecheck(state, hint_t),
}
}
}
impl Literal {
fn try_coerce(self, hint: Option<TypeKind>) -> Result<Self, ErrorKind> {
if let Some(hint) = hint {
use Literal as L;
use VagueLiteral as VagueL;
Ok(match (self, hint) {
(L::I8(_), I8) => self,
(L::I16(_), I16) => self,
(L::I32(_), I32) => self,
(L::I64(_), I64) => self,
(L::I128(_), I128) => self,
(L::U8(_), U8) => self,
(L::U16(_), U16) => self,
(L::U32(_), U32) => self,
(L::U64(_), U64) => self,
(L::U128(_), U128) => self,
(L::Vague(VagueL::Number(v)), I8) => L::I8(v as i8),
(L::Vague(VagueL::Number(v)), I16) => L::I16(v as i16),
(L::Vague(VagueL::Number(v)), I32) => L::I32(v as i32),
(L::Vague(VagueL::Number(v)), I64) => L::I64(v as i64),
(L::Vague(VagueL::Number(v)), I128) => L::I128(v as i128),
(L::Vague(VagueL::Number(v)), U8) => L::U8(v as u8),
(L::Vague(VagueL::Number(v)), U16) => L::U16(v as u16),
(L::Vague(VagueL::Number(v)), U32) => L::U32(v as u32),
(L::Vague(VagueL::Number(v)), U64) => L::U64(v as u64),
(L::Vague(VagueL::Number(v)), U128) => L::U128(v as u128),
// Default type for number literal if unable to find true type.
(L::Vague(VagueL::Number(v)), Vague(Number)) => L::I32(v as i32),
(_, Vague(_)) => self,
_ => Err(ErrorKind::TypesIncompatible(self.as_type(), hint))?,
})
} else {
Ok(self)
}
}
}
impl TypeKind {
/// Assert that a type is already known and not vague. Return said type or
/// error.
fn assert_known(&self) -> Result<TypeKind, ErrorKind> {
self.is_known().map_err(ErrorKind::TypeIsVague)
}
/// Try to collapse a type on itself producing a default type if one exists,
/// Error if not.
fn or_default(&self) -> Result<TypeKind, ErrorKind> {
match self {
Vague(vague_type) => match vague_type {
Unknown => Err(ErrorKind::TypeIsVague(*vague_type)),
Number => Ok(TypeKind::I32),
},
_ => Ok(*self),
}
}
fn binop_type(&self, op: &BinaryOperator, other: &TypeKind) -> Result<TypeKind, ErrorKind> {
let res = self.collapse_into(other)?;
Ok(match op {
BinaryOperator::Add => res,
BinaryOperator::Minus => res,
BinaryOperator::Mult => res,
BinaryOperator::And => res,
BinaryOperator::Logic(_) => Bool,
})
}
}
fn try_collapse(lhs: &TypeKind, rhs: &TypeKind) -> Result<TypeKind, ErrorKind> {
lhs.collapse_into(rhs)
.or(rhs.collapse_into(lhs))
.or(Err(ErrorKind::TypesIncompatible(*lhs, *rhs)))
}
pub trait Collapsable: Sized + Clone {
fn collapse_into(&self, other: &Self) -> Result<Self, ErrorKind>;
}
impl Collapsable for TypeKind {
fn collapse_into(&self, other: &TypeKind) -> Result<TypeKind, ErrorKind> {
if self == other {
return Ok(self.clone());
}
match (self, other) {
(Vague(Number), other) | (other, Vague(Number)) => match other {
Vague(Unknown) => Ok(Vague(Number)),
Vague(Number) => Ok(Vague(Number)),
I8 | I16 | I32 | I64 | I128 | U8 | U16 | U32 | U64 | U128 => Ok(*other),
_ => Err(ErrorKind::TypesIncompatible(*self, *other)),
},
(Vague(Unknown), other) | (other, Vague(Unknown)) => Ok(other.clone()),
_ => Err(ErrorKind::TypesIncompatible(*self, *other)),
}
}
}
impl Collapsable for ScopeFunction {
fn collapse_into(&self, other: &ScopeFunction) -> Result<ScopeFunction, ErrorKind> {
Ok(ScopeFunction {
ret: self.ret.collapse_into(&other.ret)?,
params: try_all(
self.params
.iter()
.zip(&other.params)
.map(|(p1, p2)| p1.collapse_into(&p2))
.collect(),
)
.map_err(|e| e.first().unwrap().clone())?,
})
}
}

View File

@ -54,21 +54,21 @@ impl ReturnType for IfExpression {
impl ReturnType for VariableReference { impl ReturnType for VariableReference {
fn return_type(&self) -> Result<TypeKind, ReturnTypeOther> { fn return_type(&self) -> Result<TypeKind, ReturnTypeOther> {
Ok(self.0.clone()) Ok(self.0)
} }
} }
impl ReturnType for FunctionCall { impl ReturnType for FunctionCall {
fn return_type(&self) -> Result<TypeKind, ReturnTypeOther> { fn return_type(&self) -> Result<TypeKind, ReturnTypeOther> {
Ok(self.return_type.clone()) Ok(self.return_type)
} }
} }
// impl ReturnType for FunctionDefinition { impl ReturnType for FunctionDefinition {
// fn return_type(&self) -> Result<TypeKind, ReturnTypeOther> { fn return_type(&self) -> Result<TypeKind, ReturnTypeOther> {
// match &self.kind { match &self.kind {
// FunctionDefinitionKind::Local(block, _) => block.return_type(), FunctionDefinitionKind::Local(block, _) => block.return_type(),
// FunctionDefinitionKind::Extern(type_kind) => Ok(type_kind.clone()), FunctionDefinitionKind::Extern(type_kind) => Ok(*type_kind),
// } }
// } }
// } }

View File

@ -76,7 +76,6 @@ impl<'a, 'b> TokenStream<'a, 'b> {
/// Parse the next item with Parse-trait, also mapping it with the given /// Parse the next item with Parse-trait, also mapping it with the given
/// function. The token-stream is only consumed, if the inner function /// function. The token-stream is only consumed, if the inner function
/// retuns an Ok. /// retuns an Ok.
#[allow(dead_code)]
pub fn parse_map<T: Parse + std::fmt::Debug, F, O>(&mut self, inner: F) -> Result<O, Error> pub fn parse_map<T: Parse + std::fmt::Debug, F, O>(&mut self, inner: F) -> Result<O, Error>
where where
F: Fn(T) -> Result<O, Error>, F: Fn(T) -> Result<O, Error>,
@ -157,7 +156,7 @@ impl Drop for TokenStream<'_, '_> {
} }
} }
#[derive(Default, Clone, Copy)] #[derive(Clone, Copy)]
pub struct TokenRange { pub struct TokenRange {
pub start: usize, pub start: usize,
pub end: usize, pub end: usize,
@ -169,6 +168,15 @@ impl std::fmt::Debug for TokenRange {
} }
} }
impl Default for TokenRange {
fn default() -> Self {
Self {
start: Default::default(),
end: Default::default(),
}
}
}
impl std::ops::Add for TokenRange { impl std::ops::Add for TokenRange {
type Output = TokenRange; type Output = TokenRange;

View File

@ -1,17 +0,0 @@
pub fn try_all<U, E>(list: Vec<Result<U, E>>) -> Result<Vec<U>, Vec<E>> {
let mut successes = Vec::with_capacity(list.len());
let mut failures = Vec::with_capacity(list.len());
for item in list {
match item {
Ok(s) => successes.push(s),
Err(e) => failures.push(e),
}
}
if failures.len() > 0 {
Err(failures)
} else {
Ok(successes)
}
}