Compare commits

..

18 Commits

20 changed files with 1208 additions and 400 deletions

0
.rustfmt.toml Normal file
View File

View File

@ -0,0 +1,12 @@
// Arithmetic, function calls and imports!
impl binop (lhs: u16) + (rhs: u32) -> u32 {
return (lhs as u32) + rhs;
}
fn main() -> u32 {
let value = 6 as u16;
let other = 15 as u32;
return value + other;
}

View File

@ -21,5 +21,5 @@ fn main() -> u8 {
free_string(&test); free_string(&test);
return addition(5, 3); return 8;
} }

View File

@ -8,7 +8,7 @@ use std::{
}; };
use llvm_sys::{ use llvm_sys::{
LLVMIntPredicate, LLVMLinkage, LLVMRealPredicate, LLVMValueKind, LLVMAttributeIndex, LLVMIntPredicate, LLVMLinkage, LLVMRealPredicate, LLVMValueKind,
analysis::LLVMVerifyModule, analysis::LLVMVerifyModule,
core::*, core::*,
debuginfo::*, debuginfo::*,
@ -86,7 +86,7 @@ impl CompiledModule {
triple, triple,
c"generic".as_ptr(), c"generic".as_ptr(),
c"".as_ptr(), c"".as_ptr(),
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone, llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelLess,
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault, llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault, llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
); );
@ -601,6 +601,15 @@ impl FunctionHolder {
let function_ref = let function_ref =
LLVMAddFunction(module_ref, into_cstring(&self.data.name).as_ptr(), fn_type); LLVMAddFunction(module_ref, into_cstring(&self.data.name).as_ptr(), fn_type);
if self.data.flags.inline {
let attribute = LLVMCreateEnumAttribute(
context.context_ref,
LLVMEnumAttribute::AlwaysInline as u32,
0,
);
LLVMAddAttributeAtIndex(function_ref, 0, attribute);
}
let metadata = if let Some(debug) = debug { let metadata = if let Some(debug) = debug {
if let Some(value) = &self.data.debug { if let Some(value) = &self.data.debug {
let subprogram = debug.debug.get_subprogram_data_unchecked(&value); let subprogram = debug.debug.get_subprogram_data_unchecked(&value);
@ -1215,3 +1224,7 @@ impl Type {
} }
} }
} }
pub enum LLVMEnumAttribute {
AlwaysInline = 3,
}

View File

@ -148,6 +148,7 @@ pub struct FunctionFlags {
pub is_main: bool, pub is_main: bool,
pub is_pub: bool, pub is_pub: bool,
pub is_imported: bool, pub is_imported: bool,
pub inline: bool,
} }
impl Default for FunctionFlags { impl Default for FunctionFlags {
@ -157,6 +158,7 @@ impl Default for FunctionFlags {
is_main: false, is_main: false,
is_pub: false, is_pub: false,
is_imported: false, is_imported: false,
inline: false,
} }
} }
} }

View File

@ -6,8 +6,8 @@ use reid_lib::{
}; };
use crate::mir::{ use crate::mir::{
self, CustomTypeKey, FunctionCall, FunctionDefinition, IfExpression, SourceModuleId, self, CustomTypeKey, FunctionCall, FunctionDefinition, FunctionDefinitionKind, IfExpression,
TypeDefinition, TypeKind, WhileStatement, SourceModuleId, TypeDefinition, TypeKind, WhileStatement,
}; };
#[derive(Debug)] #[derive(Debug)]
@ -28,8 +28,12 @@ impl Allocator {
} }
} }
pub fn from(func: &FunctionDefinition, scope: &mut AllocatorScope) -> Allocator { pub fn from(
func.allocate(scope) func: &FunctionDefinitionKind,
params: &Vec<(String, TypeKind)>,
scope: &mut AllocatorScope,
) -> Allocator {
func.allocate(scope, params)
} }
pub fn allocate(&mut self, name: &String, ty: &TypeKind) -> Option<InstructionValue> { pub fn allocate(&mut self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
@ -45,12 +49,16 @@ impl Allocator {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Allocation(String, TypeKind, InstructionValue); pub struct Allocation(String, TypeKind, InstructionValue);
impl mir::FunctionDefinition { impl mir::FunctionDefinitionKind {
fn allocate<'ctx, 'a>(&self, scope: &mut AllocatorScope<'ctx, 'a>) -> Allocator { fn allocate<'ctx, 'a>(
&self,
scope: &mut AllocatorScope<'ctx, 'a>,
parameters: &Vec<(String, TypeKind)>,
) -> Allocator {
let mut allocated = Vec::new(); let mut allocated = Vec::new();
match &self.kind { match &self {
mir::FunctionDefinitionKind::Local(block, _) => { mir::FunctionDefinitionKind::Local(block, _) => {
for param in &self.parameters { for param in parameters {
let allocation = scope let allocation = scope
.block .block
.build_named( .build_named(

View File

@ -207,6 +207,17 @@ pub enum TopLevelStatement {
ExternFunction(FunctionSignature), ExternFunction(FunctionSignature),
FunctionDefinition(FunctionDefinition), FunctionDefinition(FunctionDefinition),
TypeDefinition(TypeDefinition), TypeDefinition(TypeDefinition),
BinopDefinition(BinopDefinition),
}
#[derive(Debug)]
pub struct BinopDefinition {
pub lhs: (String, Type),
pub op: BinaryOperator,
pub rhs: (String, Type),
pub return_ty: Type,
pub block: Block,
pub signature_range: TokenRange,
} }
#[derive(Debug)] #[derive(Debug)]

View File

@ -314,7 +314,7 @@ fn parse_binop_rhs(
lhs = Expression( lhs = Expression(
ExpressionKind::Binop(op, Box::new(lhs), Box::new(rhs)), ExpressionKind::Binop(op, Box::new(lhs), Box::new(rhs)),
stream.get_range().unwrap(), stream.get_range_prev().unwrap(),
); );
} }
@ -554,7 +554,11 @@ impl Parse for Block {
statements.push(statement); statements.push(statement);
} }
stream.expect(Token::BraceClose)?; stream.expect(Token::BraceClose)?;
Ok(Block(statements, return_stmt, stream.get_range().unwrap())) Ok(Block(
statements,
return_stmt,
stream.get_range_prev().unwrap(),
))
} }
} }
@ -785,7 +789,46 @@ impl Parse for TopLevelStatement {
range, range,
}) })
} }
Some(Token::Impl) => Stmt::BinopDefinition(stream.parse()?),
_ => Err(stream.expecting_err("import or fn")?)?, _ => Err(stream.expecting_err("import or fn")?)?,
}) })
} }
} }
impl Parse for BinopDefinition {
fn parse(mut stream: TokenStream) -> Result<Self, Error> {
stream.expect(Token::Impl)?;
stream.expect(Token::Binop)?;
stream.expect(Token::ParenOpen)?;
let Some(Token::Identifier(lhs_name)) = stream.next() else {
return Err(stream.expected_err("lhs name")?);
};
stream.expect(Token::Colon)?;
let lhs_type = stream.parse()?;
stream.expect(Token::ParenClose)?;
let operator = stream.parse()?;
stream.expect(Token::ParenOpen)?;
let Some(Token::Identifier(rhs_name)) = stream.next() else {
return Err(stream.expected_err("rhs name")?);
};
stream.expect(Token::Colon)?;
let rhs_type = stream.parse()?;
stream.expect(Token::ParenClose)?;
let signature_range = stream.get_range().unwrap();
stream.expect(Token::Arrow)?;
Ok(BinopDefinition {
lhs: (lhs_name, lhs_type),
op: operator,
rhs: (rhs_name, rhs_type),
return_ty: stream.parse()?,
block: stream.parse()?,
signature_range,
})
}
}

View File

@ -23,6 +23,7 @@ impl ast::Module {
let mut imports = Vec::new(); let mut imports = Vec::new();
let mut functions = Vec::new(); let mut functions = Vec::new();
let mut typedefs = Vec::new(); let mut typedefs = Vec::new();
let mut binops = Vec::new();
use ast::TopLevelStatement::*; use ast::TopLevelStatement::*;
for stmt in &self.top_level_statements { for stmt in &self.top_level_statements {
@ -97,12 +98,33 @@ impl ast::Module {
}; };
typedefs.push(def); typedefs.push(def);
} }
BinopDefinition(ast::BinopDefinition {
lhs,
op,
rhs,
return_ty,
block,
signature_range,
}) => {
binops.push(mir::BinopDefinition {
lhs: (lhs.0.clone(), lhs.1 .0.into_mir(module_id)),
op: op.mir(),
rhs: (rhs.0.clone(), rhs.1 .0.into_mir(module_id)),
return_type: return_ty.0.into_mir(module_id),
fn_kind: mir::FunctionDefinitionKind::Local(
block.into_mir(module_id),
block.2.as_meta(module_id),
),
meta: signature_range.as_meta(module_id),
});
}
} }
} }
mir::Module { mir::Module {
name: self.name.clone(), name: self.name.clone(),
module_id: module_id, module_id: module_id,
binop_defs: binops,
imports, imports,
functions, functions,
path: self.path.clone(), path: self.path.clone(),

View File

@ -1,4 +1,4 @@
use std::{cell::RefCell, collections::HashMap, mem, rc::Rc}; use std::{cell::RefCell, collections::HashMap, hash::Hash, mem, rc::Rc};
use reid_lib::{ use reid_lib::{
builder::{InstructionValue, TypeValue}, builder::{InstructionValue, TypeValue},
@ -16,9 +16,13 @@ use reid_lib::{
use crate::{ use crate::{
allocator::{Allocator, AllocatorScope}, allocator::{Allocator, AllocatorScope},
intrinsics::IntrinsicFunction,
lexer::{FullToken, Position}, lexer::{FullToken, Position},
mir::{ mir::{
self, implement::TypeCategory, CustomTypeKey, Metadata, NamedVariableRef, SourceModuleId, self,
implement::TypeCategory,
pass::{ScopeBinopDef, ScopeBinopKey},
CustomTypeKey, FunctionDefinitionKind, Metadata, NamedVariableRef, SourceModuleId,
StructField, StructType, TypeDefinition, TypeDefinitionKind, TypeKind, VagueLiteral, StructField, StructType, TypeDefinition, TypeDefinitionKind, TypeKind, VagueLiteral,
WhileStatement, WhileStatement,
}, },
@ -77,17 +81,55 @@ pub struct Scope<'ctx, 'scope> {
modules: &'scope HashMap<SourceModuleId, ModuleCodegen<'ctx>>, modules: &'scope HashMap<SourceModuleId, ModuleCodegen<'ctx>>,
tokens: &'ctx Vec<FullToken>, tokens: &'ctx Vec<FullToken>,
module: &'ctx Module<'ctx>, module: &'ctx Module<'ctx>,
pub(super) module_id: SourceModuleId, module_id: SourceModuleId,
function: &'ctx StackFunction<'ctx>, function: &'ctx Function<'ctx>,
pub(super) block: Block<'ctx>, pub(super) block: Block<'ctx>,
pub(super) types: &'scope HashMap<TypeValue, TypeDefinition>, types: &'scope HashMap<TypeValue, TypeDefinition>,
pub(super) type_values: &'scope HashMap<CustomTypeKey, TypeValue>, type_values: &'scope HashMap<CustomTypeKey, TypeValue>,
functions: &'scope HashMap<String, StackFunction<'ctx>>, functions: &'scope HashMap<String, Function<'ctx>>,
binops: &'scope HashMap<ScopeBinopKey, StackBinopDefinition<'ctx>>,
stack_values: HashMap<String, StackValue>, stack_values: HashMap<String, StackValue>,
debug: Option<Debug<'ctx>>, debug: Option<Debug<'ctx>>,
allocator: Rc<RefCell<Allocator>>, allocator: Rc<RefCell<Allocator>>,
} }
impl<'ctx, 'a> Scope<'ctx, 'a> {
fn with_block(&self, block: Block<'ctx>) -> Scope<'ctx, 'a> {
Scope {
block,
modules: self.modules,
tokens: self.tokens,
function: self.function,
context: self.context,
module: self.module,
module_id: self.module_id,
functions: self.functions,
types: self.types,
type_values: self.type_values,
stack_values: self.stack_values.clone(),
debug: self.debug.clone(),
allocator: self.allocator.clone(),
binops: self.binops,
}
}
/// Takes the block out from this scope, swaps the given block in it's place
/// and returns the old block.
fn swap_block(&mut self, block: Block<'ctx>) -> Block<'ctx> {
let mut old_block = block;
mem::swap(&mut self.block, &mut old_block);
old_block
}
fn get_typedef(&self, key: &CustomTypeKey) -> Option<&TypeDefinition> {
self.type_values.get(key).and_then(|v| self.types.get(v))
}
fn allocate(&self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
self.allocator.borrow_mut().allocate(name, ty)
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Debug<'ctx> { pub struct Debug<'ctx> {
info: &'ctx DebugInformation, info: &'ctx DebugInformation,
@ -95,12 +137,8 @@ pub struct Debug<'ctx> {
types: &'ctx HashMap<TypeKind, DebugTypeValue>, types: &'ctx HashMap<TypeKind, DebugTypeValue>,
} }
pub struct StackFunction<'ctx> {
ir: Function<'ctx>,
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackValue(StackValueKind, TypeKind); pub struct StackValue(pub(super) StackValueKind, pub(super) TypeKind);
impl StackValue { impl StackValue {
fn instr(&self) -> InstructionValue { fn instr(&self) -> InstructionValue {
@ -148,39 +186,47 @@ impl StackValueKind {
} }
} }
impl<'ctx, 'a> Scope<'ctx, 'a> { pub struct StackBinopDefinition<'ctx> {
fn with_block(&self, block: Block<'ctx>) -> Scope<'ctx, 'a> { parameters: ((String, TypeKind), (String, TypeKind)),
Scope { return_ty: TypeKind,
block, kind: StackBinopFunctionKind<'ctx>,
modules: self.modules,
tokens: self.tokens,
function: self.function,
context: self.context,
module: self.module,
module_id: self.module_id,
functions: self.functions,
types: self.types,
type_values: self.type_values,
stack_values: self.stack_values.clone(),
debug: self.debug.clone(),
allocator: self.allocator.clone(),
}
} }
/// Takes the block out from this scope, swaps the given block in it's place pub enum StackBinopFunctionKind<'ctx> {
/// and returns the old block. UserGenerated(Function<'ctx>),
fn swap_block(&mut self, block: Block<'ctx>) -> Block<'ctx> { Intrinsic(&'ctx Box<dyn IntrinsicFunction>),
let mut old_block = block;
mem::swap(&mut self.block, &mut old_block);
old_block
} }
fn get_typedef(&self, key: &CustomTypeKey) -> Option<&TypeDefinition> { impl<'ctx> StackBinopDefinition<'ctx> {
self.type_values.get(key).and_then(|v| self.types.get(v)) fn codegen<'a>(
&self,
lhs: &StackValue,
rhs: &StackValue,
scope: &mut Scope<'ctx, 'a>,
) -> Result<StackValue, ErrorKind> {
let (lhs, rhs) = if lhs.1 == self.parameters.0 .1 && rhs.1 == self.parameters.1 .1 {
(lhs, rhs)
} else {
(rhs, lhs)
};
match &self.kind {
StackBinopFunctionKind::UserGenerated(ir) => {
let instr = scope
.block
.build(Instr::FunctionCall(
ir.value(),
vec![lhs.instr(), rhs.instr()],
))
.unwrap();
Ok(StackValue(
StackValueKind::Immutable(instr),
self.return_ty.clone(),
))
}
StackBinopFunctionKind::Intrinsic(fun) => {
fun.codegen(scope, &[lhs.instr(), rhs.instr()])
}
} }
fn allocate(&self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
self.allocator.borrow_mut().allocate(name, ty)
} }
} }
@ -296,7 +342,7 @@ impl mir::Module {
let is_main = self.is_main && function.name == "main"; let is_main = self.is_main && function.name == "main";
let func = match &function.kind { let func = match &function.kind {
mir::FunctionDefinitionKind::Local(_, _) => module.function( mir::FunctionDefinitionKind::Local(_, _) => Some(module.function(
&function.name, &function.name,
function.return_type.get_type(&type_values), function.return_type.get_type(&type_values),
param_types, param_types,
@ -306,8 +352,8 @@ impl mir::Module {
is_imported: function.is_imported, is_imported: function.is_imported,
..FunctionFlags::default() ..FunctionFlags::default()
}, },
), )),
mir::FunctionDefinitionKind::Extern(imported) => module.function( mir::FunctionDefinitionKind::Extern(imported) => Some(module.function(
&function.name, &function.name,
function.return_type.get_type(&type_values), function.return_type.get_type(&type_values),
param_types, param_types,
@ -316,28 +362,48 @@ impl mir::Module {
is_imported: *imported, is_imported: *imported,
..FunctionFlags::default() ..FunctionFlags::default()
}, },
), )),
mir::FunctionDefinitionKind::Intrinsic(_) => module.function( mir::FunctionDefinitionKind::Intrinsic(_) => None,
&function.name,
function.return_type.get_type(&type_values),
param_types,
FunctionFlags {
..FunctionFlags::default()
},
),
}; };
functions.insert(function.name.clone(), StackFunction { ir: func }); if let Some(func) = func {
functions.insert(function.name.clone(), func);
}
} }
for mir_function in &self.functions { let mut binops = HashMap::new();
let function = functions.get(&mir_function.name).unwrap(); for binop in &self.binop_defs {
binops.insert(
ScopeBinopKey {
params: (binop.lhs.1.clone(), binop.rhs.1.clone()),
operator: binop.op,
},
StackBinopDefinition {
parameters: (binop.lhs.clone(), binop.rhs.clone()),
return_ty: binop.return_type.clone(),
kind: match &binop.fn_kind {
FunctionDefinitionKind::Local(block, metadata) => {
let binop_fn_name = format!(
"binop.{}.{:?}.{}.{}",
binop.lhs.1, binop.op, binop.rhs.1, binop.return_type
);
let ir_function = module.function(
&binop_fn_name,
binop.return_type.get_type(&type_values),
vec![
binop.lhs.1.get_type(&type_values),
binop.rhs.1.get_type(&type_values),
],
FunctionFlags {
inline: true,
..Default::default()
},
);
let mut entry = ir_function.block("entry");
match &mir_function.kind { let allocator = Allocator::from(
mir::FunctionDefinitionKind::Local(block, _) => { &binop.fn_kind,
let mut entry = function.ir.block("entry"); &vec![binop.lhs.clone(), binop.rhs.clone()],
let mut allocator = Allocator::from(
mir_function,
&mut AllocatorScope { &mut AllocatorScope {
block: &mut entry, block: &mut entry,
module_id: self.module_id, module_id: self.module_id,
@ -345,63 +411,181 @@ impl mir::Module {
}, },
); );
// Insert debug information let mut scope = Scope {
let debug_scope = if let Some(location) = context,
mir_function.signature().into_debug(tokens, compile_unit) modules: &modules,
{ tokens,
// let debug_scope = debug.inner_scope(&outer_scope, location); module: &module,
module_id: self.module_id,
function: &ir_function,
block: entry,
functions: &functions,
types: &types,
type_values: &type_values,
stack_values: HashMap::new(),
debug: Some(Debug {
info: &debug,
scope: compile_unit,
types: &debug_types,
}),
binops: &binops,
allocator: Rc::new(RefCell::new(allocator)),
};
let fn_param_ty = &mir_function.return_type.get_debug_type_hard( binop
compile_unit, .fn_kind
&debug, .codegen(
&debug_types, binop_fn_name.clone(),
&type_values, false,
&types, &mut scope,
self.module_id, &vec![binop.lhs.clone(), binop.rhs.clone()],
&self.tokens, &binop.return_type,
&modules, &ir_function,
match &binop.fn_kind {
FunctionDefinitionKind::Local(_, meta) => {
meta.into_debug(tokens, compile_unit)
}
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
},
)
.unwrap();
StackBinopFunctionKind::UserGenerated(ir_function)
}
FunctionDefinitionKind::Extern(_) => todo!(),
FunctionDefinitionKind::Intrinsic(intrinsic_function) => {
StackBinopFunctionKind::Intrinsic(intrinsic_function)
}
},
},
);
}
for mir_function in &self.functions {
let function = functions.get(&mir_function.name).unwrap();
let mut entry = function.block("entry");
let allocator = Allocator::from(
&mir_function.kind,
&mir_function.parameters,
&mut AllocatorScope {
block: &mut entry,
module_id: self.module_id,
type_values: &type_values,
},
); );
let mut scope = Scope {
context,
modules: &modules,
tokens,
module: &module,
module_id: self.module_id,
function,
block: entry,
functions: &functions,
types: &types,
type_values: &type_values,
stack_values: HashMap::new(),
debug: Some(Debug {
info: &debug,
scope: compile_unit,
types: &debug_types,
}),
binops: &binops,
allocator: Rc::new(RefCell::new(allocator)),
};
mir_function
.kind
.codegen(
mir_function.name.clone(),
mir_function.is_pub,
&mut scope,
&mir_function.parameters,
&mir_function.return_type,
&function,
match &mir_function.kind {
FunctionDefinitionKind::Local(..) => {
mir_function.signature().into_debug(tokens, compile_unit)
}
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
},
)
.unwrap();
}
Ok(ModuleCodegen { module })
}
}
impl FunctionDefinitionKind {
fn codegen<'ctx, 'scope>(
&self,
name: String,
is_pub: bool,
scope: &mut Scope,
parameters: &Vec<(String, TypeKind)>,
return_type: &TypeKind,
ir_function: &Function,
debug_location: Option<DebugLocation>,
) -> Result<(), ErrorKind> {
match &self {
mir::FunctionDefinitionKind::Local(block, _) => {
// Insert debug information
if let Some(debug) = &scope.debug {
if let Some(location) = debug_location {
// let debug_scope = debug.inner_scope(&outer_scope, location);
let fn_param_ty = &return_type.get_debug_type(&debug, scope);
let debug_ty = let debug_ty =
debug.debug_type(DebugTypeData::Subprogram(DebugSubprogramType { debug
.info
.debug_type(DebugTypeData::Subprogram(DebugSubprogramType {
parameters: vec![*fn_param_ty], parameters: vec![*fn_param_ty],
flags: DwarfFlags, flags: DwarfFlags,
})); }));
let subprogram = debug.subprogram(DebugSubprogramData { let subprogram = debug.info.subprogram(DebugSubprogramData {
name: mir_function.name.clone(), name: name.clone(),
outer_scope: compile_unit.clone(), outer_scope: debug.scope.clone(),
location, location,
ty: debug_ty, ty: debug_ty,
opts: DebugSubprogramOptionals { opts: DebugSubprogramOptionals {
is_local: !mir_function.is_pub, is_local: !is_pub,
is_definition: true, is_definition: true,
..DebugSubprogramOptionals::default() ..DebugSubprogramOptionals::default()
}, },
}); });
function.ir.set_debug(subprogram); ir_function.set_debug(subprogram);
scope.debug = Some(Debug {
Some(subprogram) info: debug.info,
} else { scope: subprogram,
None types: debug.types,
}; });
}
}
// Compile actual IR part // Compile actual IR part
let mut stack_values = HashMap::new(); for (i, (p_name, p_ty)) in parameters.iter().enumerate() {
for (i, (p_name, p_ty)) in mir_function.parameters.iter().enumerate() {
// Codegen actual parameters // Codegen actual parameters
let arg_name = format!("arg.{}", p_name); let arg_name = format!("arg.{}", p_name);
let param = entry let param = scope
.block
.build_named(format!("{}.get", arg_name), Instr::Param(i)) .build_named(format!("{}.get", arg_name), Instr::Param(i))
.unwrap(); .unwrap();
let alloca = allocator.allocate(&p_name, &p_ty).unwrap(); let alloca = scope.allocate(&p_name, &p_ty).unwrap();
entry scope
.block
.build_named(format!("{}.store", arg_name), Instr::Store(alloca, param)) .build_named(format!("{}.store", arg_name), Instr::Store(alloca, param))
.unwrap(); .unwrap();
stack_values.insert( scope.stack_values.insert(
p_name.clone(), p_name.clone(),
StackValue( StackValue(
StackValueKind::mutable(p_ty.is_mutable(), alloca), StackValueKind::mutable(p_ty.is_mutable(), alloca),
@ -410,10 +594,10 @@ impl mir::Module {
); );
// Generate debug info // Generate debug info
if let (Some(debug_scope), Some(location)) = ( // if let (Some(debug_scope), Some(location)) = (
&debug_scope, // &debug_scope,
mir_function.signature().into_debug(tokens, compile_unit), // mir_function.signature().into_debug(tokens, compile_unit),
) { // ) {
// debug.metadata( // debug.metadata(
// &location, // &location,
// DebugMetadata::ParamVar(DebugParamVariable { // DebugMetadata::ParamVar(DebugParamVariable {
@ -433,33 +617,11 @@ impl mir::Module {
// flags: DwarfFlags, // flags: DwarfFlags,
// }), // }),
// ); // );
// }
} }
}
let mut scope = Scope {
context,
modules: &modules,
tokens,
module: &module,
module_id: self.module_id,
function,
block: entry,
functions: &functions,
types: &types,
type_values: &type_values,
stack_values,
debug: debug_scope.and_then(|scope| {
Some(Debug {
info: &debug,
scope,
types: &debug_types,
})
}),
allocator: Rc::new(RefCell::new(allocator)),
};
let state = State::default(); let state = State::default();
if let Some(ret) = block.codegen(&mut scope, &state)? { if let Some(ret) = block.codegen(scope, &state)? {
scope.block.terminate(Term::Ret(ret.instr())).unwrap(); scope.block.terminate(Term::Ret(ret.instr())).unwrap();
} else { } else {
if !scope.block.delete_if_unused().unwrap() { if !scope.block.delete_if_unused().unwrap() {
@ -469,38 +631,19 @@ impl mir::Module {
} }
} }
if let Some(debug) = scope.debug { if let Some(debug) = &scope.debug {
let location = let location = &block
&block.return_meta().into_debug(tokens, debug.scope).unwrap(); .return_meta()
.into_debug(scope.tokens, debug.scope)
.unwrap();
let location = debug.info.location(&debug.scope, *location); let location = debug.info.location(&debug.scope, *location);
scope.block.set_terminator_location(location).unwrap(); scope.block.set_terminator_location(location).unwrap();
} }
} }
mir::FunctionDefinitionKind::Extern(_) => {} mir::FunctionDefinitionKind::Extern(_) => {}
mir::FunctionDefinitionKind::Intrinsic(kind) => { mir::FunctionDefinitionKind::Intrinsic(_) => {}
let entry = function.ir.block("entry");
let mut scope = Scope {
context,
modules: &modules,
tokens,
module: &module,
module_id: self.module_id,
function,
block: entry,
functions: &functions,
types: &types,
type_values: &type_values,
stack_values: Default::default(),
debug: None,
allocator: Rc::new(RefCell::new(Allocator::empty())),
}; };
Ok(())
kind.codegen(&mut scope)?
}
}
}
Ok(ModuleCodegen { module })
} }
} }
@ -639,9 +782,9 @@ impl mir::Statement {
mir::StmtKind::While(WhileStatement { mir::StmtKind::While(WhileStatement {
condition, block, .. condition, block, ..
}) => { }) => {
let condition_block = scope.function.ir.block("while.cond"); let condition_block = scope.function.block("while.cond");
let condition_true_block = scope.function.ir.block("while.body"); let condition_true_block = scope.function.block("while.body");
let condition_failed_block = scope.function.ir.block("while.end"); let condition_failed_block = scope.function.block("while.end");
scope scope
.block .block
@ -741,14 +884,24 @@ impl mir::Expression {
lit.as_type(), lit.as_type(),
)), )),
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => { mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
let lhs = lhs_exp let lhs_val = lhs_exp
.codegen(scope, state)? .codegen(scope, state)?
.expect("lhs has no return value") .expect("lhs has no return value");
.instr(); let rhs_val = rhs_exp
let rhs = rhs_exp
.codegen(scope, state)? .codegen(scope, state)?
.expect("rhs has no return value") .expect("rhs has no return value");
.instr(); let lhs = lhs_val.instr();
let rhs = rhs_val.instr();
let operation = scope.binops.get(&ScopeBinopKey {
params: (lhs_val.1.clone(), rhs_val.1.clone()),
operator: *binop,
});
if let Some(operation) = operation {
let a = operation.codegen(&lhs_val, &rhs_val, scope)?;
Some(a)
} else {
let lhs_type = lhs_exp let lhs_type = lhs_exp
.return_type(&Default::default(), scope.module_id) .return_type(&Default::default(), scope.module_id)
.unwrap() .unwrap()
@ -765,8 +918,12 @@ impl mir::Expression {
(mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs), (mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs),
(mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs), (mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs),
(mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs), (mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs),
(mir::BinaryOperator::Cmp(i), _, false) => Instr::ICmp(i.predicate(), lhs, rhs), (mir::BinaryOperator::Cmp(i), _, false) => {
(mir::BinaryOperator::Cmp(i), _, true) => Instr::FCmp(i.predicate(), lhs, rhs), Instr::ICmp(i.predicate(), lhs, rhs)
}
(mir::BinaryOperator::Cmp(i), _, true) => {
Instr::FCmp(i.predicate(), lhs, rhs)
}
(mir::BinaryOperator::Div, false, false) => Instr::UDiv(lhs, rhs), (mir::BinaryOperator::Div, false, false) => Instr::UDiv(lhs, rhs),
(mir::BinaryOperator::Div, true, false) => Instr::SDiv(lhs, rhs), (mir::BinaryOperator::Div, true, false) => Instr::SDiv(lhs, rhs),
(mir::BinaryOperator::Div, _, true) => Instr::FDiv(lhs, rhs), (mir::BinaryOperator::Div, _, true) => Instr::FDiv(lhs, rhs),
@ -810,6 +967,7 @@ impl mir::Expression {
Instr::Sub(lhs, mul) Instr::Sub(lhs, mul)
} }
}; };
dbg!(&instr);
Some(StackValue( Some(StackValue(
StackValueKind::Immutable( StackValueKind::Immutable(
scope scope
@ -821,6 +979,7 @@ impl mir::Expression {
lhs_type, lhs_type,
)) ))
} }
}
mir::ExprKind::FunctionCall(call) => { mir::ExprKind::FunctionCall(call) => {
let ret_type_kind = call let ret_type_kind = call
.return_type .return_type
@ -850,7 +1009,7 @@ impl mir::Expression {
.block .block
.build_named( .build_named(
call.name.clone(), call.name.clone(),
Instr::FunctionCall(callee.ir.value(), param_instrs), Instr::FunctionCall(callee.value(), param_instrs),
) )
.unwrap(); .unwrap();
@ -898,7 +1057,7 @@ impl mir::Expression {
} }
mir::ExprKind::If(if_expression) => if_expression.codegen(scope, state)?, mir::ExprKind::If(if_expression) => if_expression.codegen(scope, state)?,
mir::ExprKind::Block(block) => { mir::ExprKind::Block(block) => {
let inner = scope.function.ir.block("inner"); let inner = scope.function.block("inner");
scope.block.terminate(Term::Br(inner.value())).unwrap(); scope.block.terminate(Term::Br(inner.value())).unwrap();
let mut inner_scope = scope.with_block(inner); let mut inner_scope = scope.with_block(inner);
@ -907,7 +1066,7 @@ impl mir::Expression {
} else { } else {
None None
}; };
let outer = scope.function.ir.block("outer"); let outer = scope.function.block("outer");
inner_scope.block.terminate(Term::Br(outer.value())).ok(); inner_scope.block.terminate(Term::Br(outer.value())).ok();
scope.swap_block(outer); scope.swap_block(outer);
ret ret
@ -1310,9 +1469,9 @@ impl mir::IfExpression {
let condition = self.0.codegen(scope, state)?.unwrap(); let condition = self.0.codegen(scope, state)?.unwrap();
// Create blocks // Create blocks
let mut then_b = scope.function.ir.block("then"); let mut then_b = scope.function.block("then");
let mut else_b = scope.function.ir.block("else"); let mut else_b = scope.function.block("else");
let after_b = scope.function.ir.block("after"); let after_b = scope.function.block("after");
if let Some(debug) = &scope.debug { if let Some(debug) = &scope.debug {
let before_location = self.0 .1.into_debug(scope.tokens, debug.scope).unwrap(); let before_location = self.0 .1.into_debug(scope.tokens, debug.scope).unwrap();

View File

@ -1,20 +1,15 @@
use reid_lib::Instr; use reid_lib::{builder::InstructionValue, Instr};
use crate::{ use crate::{
codegen::{ErrorKind, Scope}, codegen::{ErrorKind, Scope, StackValue, StackValueKind},
mir::{FunctionDefinition, FunctionDefinitionKind, TypeKind}, mir::{BinaryOperator, BinopDefinition, FunctionDefinition, FunctionDefinitionKind, TypeKind},
}; };
#[derive(Debug, Clone, Copy)]
pub enum InstrinsicKind {
IAdd,
}
fn intrinsic( fn intrinsic(
name: &str, name: &str,
ret_ty: TypeKind, ret_ty: TypeKind,
params: Vec<(&str, TypeKind)>, params: Vec<(&str, TypeKind)>,
kind: InstrinsicKind, fun: impl IntrinsicFunction + 'static,
) -> FunctionDefinition { ) -> FunctionDefinition {
FunctionDefinition { FunctionDefinition {
name: name.into(), name: name.into(),
@ -22,36 +17,93 @@ fn intrinsic(
is_imported: false, is_imported: false,
return_type: ret_ty, return_type: ret_ty,
parameters: params.into_iter().map(|(n, ty)| (n.into(), ty)).collect(), parameters: params.into_iter().map(|(n, ty)| (n.into(), ty)).collect(),
kind: FunctionDefinitionKind::Intrinsic(kind), kind: FunctionDefinitionKind::Intrinsic(Box::new(fun)),
}
}
fn intrinsic_binop(
op: BinaryOperator,
lhs: TypeKind,
rhs: TypeKind,
ret_ty: TypeKind,
fun: impl IntrinsicFunction + 'static,
) -> BinopDefinition {
BinopDefinition {
lhs: ("lhs".to_string(), lhs),
op,
rhs: ("rhs".to_owned(), rhs),
return_type: ret_ty,
fn_kind: FunctionDefinitionKind::Intrinsic(Box::new(fun)),
meta: Default::default(),
} }
} }
pub fn form_intrinsics() -> Vec<FunctionDefinition> { pub fn form_intrinsics() -> Vec<FunctionDefinition> {
let mut intrinsics = Vec::new(); let intrinsics = Vec::new();
intrinsics.push(intrinsic(
"addition",
TypeKind::U8,
vec![("lhs".into(), TypeKind::U8), ("rhs".into(), TypeKind::U8)],
InstrinsicKind::IAdd,
));
intrinsics intrinsics
} }
impl InstrinsicKind { pub fn form_intrinsic_binops() -> Vec<BinopDefinition> {
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Result<(), ErrorKind> { let mut intrinsics = Vec::new();
match self {
InstrinsicKind::IAdd => { intrinsics
let lhs = scope.block.build(Instr::Param(0)).unwrap(); }
let rhs = scope.block.build(Instr::Param(1)).unwrap();
let add = scope.block.build(Instr::Add(lhs, rhs)).unwrap(); pub trait IntrinsicFunction: std::fmt::Debug {
scope fn codegen<'ctx, 'a>(
.block &self,
.terminate(reid_lib::TerminatorKind::Ret(add)) scope: &mut Scope<'ctx, 'a>,
.unwrap() params: &[InstructionValue],
) -> Result<StackValue, ErrorKind>;
}
#[derive(Debug, Clone)]
pub struct IntrinsicIAdd(TypeKind);
impl IntrinsicFunction for IntrinsicIAdd {
fn codegen<'ctx, 'a>(
&self,
scope: &mut Scope<'ctx, 'a>,
params: &[InstructionValue],
) -> Result<StackValue, ErrorKind> {
let lhs = params.get(0).unwrap();
let rhs = params.get(1).unwrap();
let add = scope.block.build(Instr::Add(*lhs, *rhs)).unwrap();
Ok(StackValue(StackValueKind::Literal(add), self.0.clone()))
} }
} }
Ok(())
#[derive(Debug, Clone)]
pub struct IntrinsicUDiv(TypeKind);
impl IntrinsicFunction for IntrinsicUDiv {
fn codegen<'ctx, 'a>(
&self,
scope: &mut Scope<'ctx, 'a>,
params: &[InstructionValue],
) -> Result<StackValue, ErrorKind> {
let lhs = params.get(0).unwrap();
let rhs = params.get(1).unwrap();
let add = scope.block.build(Instr::UDiv(*lhs, *rhs)).unwrap();
Ok(StackValue(StackValueKind::Literal(add), self.0.clone()))
}
}
#[derive(Debug, Clone)]
pub struct IntrinsicUMod(TypeKind);
impl IntrinsicFunction for IntrinsicUMod {
fn codegen<'ctx, 'a>(
&self,
scope: &mut Scope<'ctx, 'a>,
params: &[InstructionValue],
) -> Result<StackValue, ErrorKind> {
let lhs = params.get(0).unwrap();
let rhs = params.get(1).unwrap();
let div = scope.block.build(Instr::UDiv(*lhs, *rhs)).unwrap();
let mul = scope.block.build(Instr::Mul(*rhs, div)).unwrap();
let sub = scope.block.build(Instr::Sub(*lhs, mul)).unwrap();
Ok(StackValue(StackValueKind::Literal(sub), self.0.clone()))
} }
} }

View File

@ -46,8 +46,12 @@ pub enum Token {
While, While,
/// `for` /// `for`
For, For,
/// `In` /// `in`
In, In,
/// `impl`
Impl,
/// `binop`
Binop,
// Symbols // Symbols
/// `;` /// `;`
@ -145,6 +149,8 @@ impl ToString for Token {
Token::For => String::from("for"), Token::For => String::from("for"),
Token::In => String::from("in"), Token::In => String::from("in"),
Token::While => String::from("while"), Token::While => String::from("while"),
Token::Impl => String::from("impl"),
Token::Binop => String::from("binop"),
Token::Semi => String::from(';'), Token::Semi => String::from(';'),
Token::Equals => String::from('='), Token::Equals => String::from('='),
Token::Colon => String::from(':'), Token::Colon => String::from(':'),
@ -334,6 +340,8 @@ pub fn tokenize<T: Into<String>>(to_tokenize: T) -> Result<Vec<FullToken>, Error
"for" => Token::For, "for" => Token::For,
"while" => Token::While, "while" => Token::While,
"in" => Token::In, "in" => Token::In,
"impl" => Token::Impl,
"binop" => Token::Binop,
_ => Token::Identifier(value), _ => Token::Identifier(value),
}; };
variant variant

View File

@ -44,7 +44,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use error_raporting::{ErrorKind as ErrorRapKind, ErrorModules, ReidError}; use error_raporting::{ErrorKind as ErrorRapKind, ErrorModules, ReidError};
use intrinsics::form_intrinsics; use intrinsics::{form_intrinsic_binops, form_intrinsics};
use lexer::FullToken; use lexer::FullToken;
use mir::{ use mir::{
linker::LinkerPass, typecheck::TypeCheck, typeinference::TypeInference, typerefs::TypeRefs, linker::LinkerPass, typecheck::TypeCheck, typeinference::TypeInference, typerefs::TypeRefs,
@ -128,6 +128,12 @@ pub fn perform_all_passes<'map>(
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
dbg!(&context); dbg!(&context);
for module in &mut context.modules {
for intrinsic in form_intrinsic_binops() {
module.1.binop_defs.insert(0, intrinsic);
}
}
for module in &mut context.modules { for module in &mut context.modules {
for intrinsic in form_intrinsics() { for intrinsic in form_intrinsics() {
module.1.functions.insert(0, intrinsic); module.1.functions.insert(0, intrinsic);

View File

@ -40,6 +40,9 @@ impl Display for Module {
for import in &self.imports { for import in &self.imports {
writeln!(inner_f, "{}", import)?; writeln!(inner_f, "{}", import)?;
} }
for binop in &self.binop_defs {
writeln!(inner_f, "{}", binop)?;
}
for typedef in &self.typedefs { for typedef in &self.typedefs {
writeln!(inner_f, "{}", typedef)?; writeln!(inner_f, "{}", typedef)?;
} }
@ -56,6 +59,17 @@ impl Display for Import {
} }
} }
impl Display for BinopDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"impl binop ({}: {:#}) {} ({}: {:#}) -> {:#} ",
self.lhs.0, self.lhs.1, self.op, self.rhs.0, self.rhs.1, self.return_type
)?;
Display::fmt(&self.fn_kind, f)
}
}
impl Display for TypeDefinition { impl Display for TypeDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "type {} = ", self.name)?; write!(f, "type {} = ", self.name)?;

View File

@ -1,4 +1,4 @@
use super::{typecheck::ErrorKind, typerefs::TypeRefs, VagueType as Vague, *}; use super::{pass::ScopeBinopDef, typecheck::ErrorKind, typerefs::TypeRefs, VagueType as Vague, *};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ReturnTypeOther { pub enum ReturnTypeOther {
@ -95,11 +95,11 @@ impl TypeKind {
/// Return the type that is the result of a binary operator between two /// Return the type that is the result of a binary operator between two
/// values of this type /// values of this type
pub fn binop_type(&self, op: &BinaryOperator) -> TypeKind { pub fn simple_binop_type(&self, op: &BinaryOperator) -> Option<TypeKind> {
// TODO make some type of mechanism that allows to binop two values of if !self.category().is_simple_maths() {
// differing types.. return None;
// TODO Return None for arrays later }
match op { Some(match op {
BinaryOperator::Add => self.clone(), BinaryOperator::Add => self.clone(),
BinaryOperator::Minus => self.clone(), BinaryOperator::Minus => self.clone(),
BinaryOperator::Mult => self.clone(), BinaryOperator::Mult => self.clone(),
@ -107,12 +107,29 @@ impl TypeKind {
BinaryOperator::Cmp(_) => TypeKind::Bool, BinaryOperator::Cmp(_) => TypeKind::Bool,
BinaryOperator::Div => self.clone(), BinaryOperator::Div => self.clone(),
BinaryOperator::Mod => self.clone(), BinaryOperator::Mod => self.clone(),
})
}
pub fn binop_type(
lhs: &TypeKind,
rhs: &TypeKind,
binop: &ScopeBinopDef,
) -> Option<(TypeKind, TypeKind, TypeKind)> {
let lhs_ty = lhs.collapse_into(&binop.hands.0);
let rhs_ty = rhs.collapse_into(&binop.hands.1);
if let (Ok(lhs_ty), Ok(rhs_ty)) = (lhs_ty, rhs_ty) {
Some((lhs_ty, rhs_ty, binop.return_ty.clone()))
} else {
None
} }
} }
/// Reverse of binop_type, where the given hint is the known required output /// Reverse of binop_type, where the given hint is the known required output
/// type of the binop, and the output is the hint for the lhs/rhs type. /// type of the binop, and the output is the hint for the lhs/rhs type.
pub fn binop_hint(&self, op: &BinaryOperator) -> Option<TypeKind> { pub fn simple_binop_hint(&self, op: &BinaryOperator) -> Option<TypeKind> {
if !self.category().is_simple_maths() {
return None;
}
match op { match op {
BinaryOperator::Add BinaryOperator::Add
| BinaryOperator::Minus | BinaryOperator::Minus
@ -124,6 +141,22 @@ impl TypeKind {
} }
} }
pub fn binop_hint(
&self,
lhs: &TypeKind,
rhs: &TypeKind,
binop: &ScopeBinopDef,
) -> Option<(TypeKind, TypeKind)> {
self.collapse_into(&binop.return_ty).ok()?;
let lhs_ty = lhs.collapse_into(&binop.hands.0);
let rhs_ty = rhs.collapse_into(&binop.hands.1);
if let (Ok(lhs_ty), Ok(rhs_ty)) = (lhs_ty, rhs_ty) {
Some((lhs_ty, rhs_ty))
} else {
None
}
}
pub fn signed(&self) -> bool { pub fn signed(&self) -> bool {
match self { match self {
TypeKind::Bool => false, TypeKind::Bool => false,
@ -245,7 +278,7 @@ impl TypeKind {
| TypeKind::F80 | TypeKind::F80
| TypeKind::F128PPC => TypeCategory::Real, | TypeKind::F128PPC => TypeCategory::Real,
TypeKind::Void => TypeCategory::Other, TypeKind::Void => TypeCategory::Other,
TypeKind::Bool => TypeCategory::Other, TypeKind::Bool => TypeCategory::Bool,
TypeKind::Array(_, _) => TypeCategory::Other, TypeKind::Array(_, _) => TypeCategory::Other,
TypeKind::CustomType(..) => TypeCategory::Other, TypeKind::CustomType(..) => TypeCategory::Other,
TypeKind::Borrow(_, _) => TypeCategory::Other, TypeKind::Borrow(_, _) => TypeCategory::Other,
@ -259,16 +292,63 @@ impl TypeKind {
}, },
} }
} }
pub fn try_collapse_two(
(lhs1, rhs1): (&TypeKind, &TypeKind),
(lhs2, rhs2): (&TypeKind, &TypeKind),
) -> Option<(TypeKind, TypeKind)> {
if let (Ok(lhs), Ok(rhs)) = (lhs1.collapse_into(&lhs2), rhs1.collapse_into(&rhs2)) {
Some((lhs, rhs))
} else if let (Ok(lhs), Ok(rhs)) = (lhs1.collapse_into(&rhs2), rhs1.collapse_into(&lhs2)) {
Some((rhs, lhs))
} else {
None
}
}
}
impl BinaryOperator {
pub fn is_commutative(&self) -> bool {
match self {
BinaryOperator::Add => true,
BinaryOperator::Minus => false,
BinaryOperator::Mult => true,
BinaryOperator::Div => false,
BinaryOperator::Mod => false,
BinaryOperator::And => true,
BinaryOperator::Cmp(cmp_operator) => match cmp_operator {
CmpOperator::LT => false,
CmpOperator::LE => false,
CmpOperator::GT => false,
CmpOperator::GE => false,
CmpOperator::EQ => true,
CmpOperator::NE => true,
},
}
}
} }
#[derive(PartialEq, Eq, PartialOrd, Ord)] #[derive(PartialEq, Eq, PartialOrd, Ord)]
pub enum TypeCategory { pub enum TypeCategory {
Integer, Integer,
Real, Real,
Bool,
Other, Other,
TypeRef, TypeRef,
} }
impl TypeCategory {
pub fn is_simple_maths(&self) -> bool {
match self {
TypeCategory::Integer => true,
TypeCategory::Real => true,
TypeCategory::Other => false,
TypeCategory::TypeRef => false,
TypeCategory::Bool => true,
}
}
}
impl StructType { impl StructType {
pub fn get_field_ty(&self, name: &String) -> Option<&TypeKind> { pub fn get_field_ty(&self, name: &String) -> Option<&TypeKind> {
self.0 self.0

View File

@ -5,7 +5,7 @@
use std::{collections::HashMap, path::PathBuf}; use std::{collections::HashMap, path::PathBuf};
use crate::{ use crate::{
intrinsics::InstrinsicKind, intrinsics::IntrinsicFunction,
lexer::{FullToken, Position}, lexer::{FullToken, Position},
token_stream::TokenRange, token_stream::TokenRange,
}; };
@ -214,7 +214,7 @@ impl VagueLiteral {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BinaryOperator { pub enum BinaryOperator {
Add, Add,
Minus, Minus,
@ -226,7 +226,7 @@ pub enum BinaryOperator {
} }
/// Specifically the operators that LLVM likes to take in as "icmp" parameters /// Specifically the operators that LLVM likes to take in as "icmp" parameters
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CmpOperator { pub enum CmpOperator {
LT, LT,
LE, LE,
@ -303,7 +303,7 @@ pub enum FunctionDefinitionKind {
/// True = imported from other module, False = Is user defined extern /// True = imported from other module, False = Is user defined extern
Extern(bool), Extern(bool),
/// Intrinsic definition, defined within the compiler /// Intrinsic definition, defined within the compiler
Intrinsic(InstrinsicKind), Intrinsic(Box<dyn IntrinsicFunction>),
} }
impl FunctionDefinition { impl FunctionDefinition {
@ -365,6 +365,30 @@ pub enum TypeDefinitionKind {
Struct(StructType), Struct(StructType),
} }
#[derive(Debug)]
pub struct BinopDefinition {
pub lhs: (String, TypeKind),
pub op: BinaryOperator,
pub rhs: (String, TypeKind),
pub return_type: TypeKind,
pub fn_kind: FunctionDefinitionKind,
pub meta: Metadata,
}
impl BinopDefinition {
pub fn block_meta(&self) -> Option<Metadata> {
match &self.fn_kind {
FunctionDefinitionKind::Local(block, _) => Some(block.meta),
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
}
}
pub fn signature(&self) -> Metadata {
self.meta
}
}
#[derive(Debug)] #[derive(Debug)]
pub struct Module { pub struct Module {
pub name: String, pub name: String,
@ -372,6 +396,7 @@ pub struct Module {
pub imports: Vec<Import>, pub imports: Vec<Import>,
pub functions: Vec<FunctionDefinition>, pub functions: Vec<FunctionDefinition>,
pub typedefs: Vec<TypeDefinition>, pub typedefs: Vec<TypeDefinition>,
pub binop_defs: Vec<BinopDefinition>,
pub path: Option<PathBuf>, pub path: Option<PathBuf>,
pub tokens: Vec<FullToken>, pub tokens: Vec<FullToken>,
pub is_main: bool, pub is_main: bool,

View File

@ -1,7 +1,7 @@
//! This module contains relevant code for [`Pass`] and shared code between //! This module contains relevant code for [`Pass`] and shared code between
//! passes. Passes can be performed on Reid MIR to e.g. typecheck the code. //! passes. Passes can be performed on Reid MIR to e.g. typecheck the code.
use std::collections::HashMap; use std::collections::{HashMap, HashSet};
use std::convert::Infallible; use std::convert::Infallible;
use std::error::Error as STDError; use std::error::Error as STDError;
@ -111,10 +111,19 @@ impl<Key: std::hash::Hash + Eq, T: Clone + std::fmt::Debug> Storage<Key, T> {
pub fn get(&self, key: &Key) -> Option<&T> { pub fn get(&self, key: &Key) -> Option<&T> {
self.0.get(key) self.0.get(key)
} }
pub fn iter(&self) -> impl Iterator<Item = (&Key, &T)> {
self.0.iter()
}
pub fn find(&self, key: &Key) -> Option<(&Key, &T)> {
self.0.iter().find(|(k, _)| *k == key)
}
} }
#[derive(Clone, Default, Debug)] #[derive(Clone, Default, Debug)]
pub struct Scope<Data: Clone + Default> { pub struct Scope<Data: Clone + Default> {
pub binops: Storage<ScopeBinopKey, ScopeBinopDef>,
pub function_returns: Storage<String, ScopeFunction>, pub function_returns: Storage<String, ScopeFunction>,
pub variables: Storage<String, ScopeVariable>, pub variables: Storage<String, ScopeVariable>,
pub types: Storage<CustomTypeKey, TypeDefinition>, pub types: Storage<CustomTypeKey, TypeDefinition>,
@ -128,6 +137,7 @@ impl<Data: Clone + Default> Scope<Data> {
Scope { Scope {
function_returns: self.function_returns.clone(), function_returns: self.function_returns.clone(),
variables: self.variables.clone(), variables: self.variables.clone(),
binops: self.binops.clone(),
types: self.types.clone(), types: self.types.clone(),
return_type_hint: self.return_type_hint.clone(), return_type_hint: self.return_type_hint.clone(),
data: self.data.clone(), data: self.data.clone(),
@ -162,6 +172,57 @@ pub struct ScopeVariable {
pub mutable: bool, pub mutable: bool,
} }
#[derive(Clone, Debug, Eq)]
pub struct ScopeBinopKey {
pub params: (TypeKind, TypeKind),
pub operator: BinaryOperator,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum CommutativeKind {
True,
False,
Any,
}
impl PartialEq for ScopeBinopKey {
fn eq(&self, other: &Self) -> bool {
if self.operator != other.operator {
return false;
}
if self.operator.is_commutative() != other.operator.is_commutative() {
return false;
}
let operators_eq = self.params == other.params;
let swapped_ops_eq = (self.params.1.clone(), self.params.0.clone()) == other.params;
if self.operator.is_commutative() {
operators_eq || swapped_ops_eq
} else {
operators_eq
}
}
}
impl std::hash::Hash for ScopeBinopKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
if self.operator.is_commutative() {
let mut sorted = vec![&self.params.0, &self.params.1];
sorted.sort();
sorted.hash(state);
self.operator.hash(state);
} else {
self.params.hash(state);
}
}
}
#[derive(Clone, Debug)]
pub struct ScopeBinopDef {
pub hands: (TypeKind, TypeKind),
pub operator: BinaryOperator,
pub return_ty: TypeKind,
}
pub struct PassState<'st, 'sc, Data: Clone + Default, TError: STDError + Clone> { pub struct PassState<'st, 'sc, Data: Clone + Default, TError: STDError + Clone> {
state: &'st mut State<TError>, state: &'st mut State<TError>,
pub scope: &'sc mut Scope<Data>, pub scope: &'sc mut Scope<Data>,
@ -301,6 +362,23 @@ impl Module {
.ok(); .ok();
} }
for binop in &self.binop_defs {
scope
.binops
.set(
ScopeBinopKey {
params: (binop.lhs.1.clone(), binop.rhs.1.clone()),
operator: binop.op,
},
ScopeBinopDef {
hands: (binop.lhs.1.clone(), binop.rhs.1.clone()),
operator: binop.op,
return_ty: binop.return_type.clone(),
},
)
.ok();
}
for function in &self.functions { for function in &self.functions {
scope scope
.function_returns .function_returns

View File

@ -64,12 +64,16 @@ pub enum ErrorKind {
ImpossibleMutableBorrow(String), ImpossibleMutableBorrow(String),
#[error("Cannot declare variable {0} as mutable, when it's type is immutable")] #[error("Cannot declare variable {0} as mutable, when it's type is immutable")]
ImpossibleMutLet(String), ImpossibleMutLet(String),
#[error("Cannot produce a negative unsigned value of type {0}!")] #[error("Cannot produce a negative unsigned value of type {0}")]
NegativeUnsignedValue(TypeKind), NegativeUnsignedValue(TypeKind),
#[error("Cannot cast type {0} into type {1}!")] #[error("Cannot cast type {0} into type {1}")]
NotCastableTo(TypeKind, TypeKind), NotCastableTo(TypeKind, TypeKind),
#[error("Cannot divide by zero")] #[error("Cannot divide by zero")]
DivideZero, DivideZero,
#[error("Binary operation {0} between {1} and {2} is already defined")]
BinaryOpAlreadyDefined(BinaryOperator, TypeKind, TypeKind),
#[error("Binary operation {0} between {1} and {2} is not defined")]
InvalidBinop(BinaryOperator, TypeKind, TypeKind),
} }
/// Struct used to implement a type-checking pass that can be performed on the /// Struct used to implement a type-checking pass that can be performed on the
@ -132,6 +136,11 @@ impl<'t> Pass for TypeCheck<'t> {
check_typedefs_for_recursion(&defmap, typedef, HashSet::new(), &mut state); check_typedefs_for_recursion(&defmap, typedef, HashSet::new(), &mut state);
} }
for binop in &mut module.binop_defs {
let res = binop.typecheck(&self.refs, &mut state.inner());
state.ok(res, binop.block_meta().unwrap_or(binop.signature()));
}
for function in &mut module.functions { for function in &mut module.functions {
let res = function.typecheck(&self.refs, &mut state.inner()); let res = function.typecheck(&self.refs, &mut state.inner());
state.ok(res, function.block_meta()); state.ok(res, function.block_meta());
@ -170,6 +179,52 @@ fn check_typedefs_for_recursion<'a, 'b>(
} }
} }
impl BinopDefinition {
fn typecheck(
&mut self,
typerefs: &TypeRefs,
state: &mut TypecheckPassState,
) -> Result<TypeKind, ErrorKind> {
for param in vec![&self.lhs, &self.rhs] {
let param_t = state.or_else(
param.1.assert_known(typerefs, state),
TypeKind::Vague(Vague::Unknown),
self.signature(),
);
let res = state
.scope
.variables
.set(
param.0.clone(),
ScopeVariable {
ty: param_t.clone(),
mutable: param_t.is_mutable(),
},
)
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
state.ok(res, self.signature());
}
let return_type = self.return_type.clone().assert_known(typerefs, state)?;
state.scope.return_type_hint = Some(self.return_type.clone());
let inferred =
self.fn_kind
.typecheck(&typerefs, &mut state.inner(), Some(return_type.clone()));
match inferred {
Ok(t) => return_type
.collapse_into(&t.1)
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
Err(e) => Ok(state.or_else(
Err(e),
return_type,
self.block_meta().unwrap_or(self.signature()),
)),
}
}
}
impl FunctionDefinition { impl FunctionDefinition {
fn typecheck( fn typecheck(
&mut self, &mut self,
@ -197,10 +252,30 @@ impl FunctionDefinition {
} }
let return_type = self.return_type.clone().assert_known(typerefs, state)?; let return_type = self.return_type.clone().assert_known(typerefs, state)?;
let inferred = match &mut self.kind { let inferred = self
.kind
.typecheck(typerefs, state, Some(self.return_type.clone()));
match inferred {
Ok(t) => return_type
.collapse_into(&t.1)
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
Err(e) => Ok(state.or_else(Err(e), return_type, self.block_meta())),
}
}
}
impl FunctionDefinitionKind {
fn typecheck(
&mut self,
typerefs: &TypeRefs,
state: &mut TypecheckPassState,
hint: Option<TypeKind>,
) -> Result<(ReturnKind, TypeKind), ErrorKind> {
match self {
FunctionDefinitionKind::Local(block, _) => { FunctionDefinitionKind::Local(block, _) => {
state.scope.return_type_hint = Some(self.return_type.clone()); state.scope.return_type_hint = hint.clone();
block.typecheck(&mut state.inner(), &typerefs, Some(&return_type)) block.typecheck(&mut state.inner(), &typerefs, hint.as_ref())
} }
FunctionDefinitionKind::Extern(_) => { FunctionDefinitionKind::Extern(_) => {
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown))) Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
@ -208,13 +283,6 @@ impl FunctionDefinition {
FunctionDefinitionKind::Intrinsic(..) => { FunctionDefinitionKind::Intrinsic(..) => {
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown))) Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
} }
};
match inferred {
Ok(t) => return_type
.collapse_into(&t.1)
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
Err(e) => Ok(state.or_else(Err(e), return_type, self.block_meta())),
} }
} }
} }
@ -442,16 +510,71 @@ impl Expression {
Ok(literal.as_type()) Ok(literal.as_type())
} }
ExprKind::BinOp(op, lhs, rhs) => { ExprKind::BinOp(op, lhs, rhs) => {
// TODO make sure lhs and rhs can actually do this binary // First find unfiltered parameters to binop
// operation once relevant let lhs_res = lhs.typecheck(state, &typerefs, None);
let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
let rhs_res = rhs.typecheck(state, &typerefs, None);
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
let cloned = state.scope.binops.clone();
let mut iter = cloned.iter();
let operator = loop {
let Some((_, binop)) = iter.next() else {
break None;
};
if binop.operator != *op {
continue;
}
if let Some(hint_t) = hint_t {
if binop.return_ty == *hint_t {
if let Some(_) = TypeKind::binop_type(&lhs_type, &rhs_type, binop) {
break Some(binop);
}
} else {
continue;
}
}
if let Some(_) = TypeKind::binop_type(&lhs_type, &rhs_type, binop) {
break Some(binop);
}
};
if let Some(operator) = operator {
// Re-typecheck with found operator hints
let (lhs_ty, rhs_ty) = TypeKind::try_collapse_two(
(&lhs_type, &rhs_type),
(&operator.hands.0, &operator.hands.1),
)
.unwrap();
let lhs_res = lhs.typecheck(state, &typerefs, Some(&lhs_ty));
let rhs_res = rhs.typecheck(state, &typerefs, Some(&rhs_ty));
state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
Ok(operator.return_ty.clone())
} else {
// Re-typecheck with typical everyday binop
let lhs_res = lhs.typecheck( let lhs_res = lhs.typecheck(
state, state,
&typerefs, &typerefs,
hint_t.and_then(|t| t.binop_hint(op)).as_ref(), hint_t.and_then(|t| t.simple_binop_hint(op)).as_ref(),
); );
let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1); let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
let rhs_res = rhs.typecheck(state, &typerefs, Some(&lhs_type)); let rhs_res = rhs.typecheck(state, &typerefs, Some(&lhs_type));
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1); let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
dbg!(&op, &hint_t);
dbg!(&lhs_type);
dbg!(&rhs_type);
let both_t = lhs_type.collapse_into(&rhs_type)?;
if *op == BinaryOperator::Minus && !lhs_type.signed() {
if let (Some(lhs_val), Some(rhs_val)) = (lhs.num_value()?, rhs.num_value()?)
{
if lhs_val < rhs_val {
return Err(ErrorKind::NegativeUnsignedValue(lhs_type));
}
}
}
if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) { if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) {
// Try to coerce both sides again with collapsed type // Try to coerce both sides again with collapsed type
@ -459,18 +582,11 @@ impl Expression {
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok(); rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
} }
let both_t = lhs_type.collapse_into(&rhs_type)?; both_t
.simple_binop_type(op)
if *op == BinaryOperator::Minus && !lhs_type.signed() { .ok_or(ErrorKind::InvalidBinop(*op, lhs_type, rhs_type))
if let (Some(lhs_val), Some(rhs_val)) = (lhs.num_value()?, rhs.num_value()?) {
if lhs_val < rhs_val {
return Err(ErrorKind::NegativeUnsignedValue(lhs_type));
} }
} }
}
Ok(both_t.binop_type(op))
}
ExprKind::FunctionCall(function_call) => { ExprKind::FunctionCall(function_call) => {
let true_function = state let true_function = state
.scope .scope
@ -748,7 +864,7 @@ impl Expression {
Ok(*inner) Ok(*inner)
} }
ExprKind::CastTo(expression, type_kind) => { ExprKind::CastTo(expression, type_kind) => {
let expr = expression.typecheck(state, typerefs, None)?; let expr = expression.typecheck(state, typerefs, Some(&type_kind))?;
expr.resolve_ref(typerefs).cast_into(type_kind) expr.resolve_ref(typerefs).cast_into(type_kind)
} }
} }

View File

@ -4,16 +4,20 @@
//! must then be passed through TypeCheck with the same [`TypeRefs`] in order to //! must then be passed through TypeCheck with the same [`TypeRefs`] in order to
//! place the correct types from the IDs and check that there are no issues. //! place the correct types from the IDs and check that there are no issues.
use std::{collections::HashMap, convert::Infallible, iter}; use std::{
collections::{HashMap, HashSet},
convert::Infallible,
iter,
};
use crate::{mir::TypeKind, util::try_all}; use crate::{mir::TypeKind, util::try_all};
use super::{ use super::{
pass::{Pass, PassResult, PassState}, pass::{self, Pass, PassResult, PassState, ScopeBinopDef, ScopeBinopKey},
typecheck::{ErrorKind, ErrorTypedefKind}, typecheck::{ErrorKind, ErrorTypedefKind},
typerefs::{ScopeTypeRefs, TypeRef, TypeRefs}, typerefs::{ScopeTypeRefs, TypeRef, TypeRefs},
Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition, FunctionDefinitionKind, BinopDefinition, Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition,
IfExpression, Module, ReturnKind, StmtKind, FunctionDefinitionKind, IfExpression, Module, ReturnKind, StmtKind,
TypeKind::*, TypeKind::*,
VagueType::*, VagueType::*,
WhileStatement, WhileStatement,
@ -55,6 +59,33 @@ impl<'t> Pass for TypeInference<'t> {
} }
} }
let mut seen_binops = HashSet::new();
for binop in &module.binop_defs {
let binop_key = ScopeBinopKey {
params: (binop.lhs.1.clone(), binop.rhs.1.clone()),
operator: binop.op,
};
if seen_binops.contains(&binop_key)
|| (binop.lhs == binop.rhs && binop.lhs.1.category().is_simple_maths())
{
state.note_errors(
&vec![ErrorKind::BinaryOpAlreadyDefined(
binop.op,
binop.lhs.1.clone(),
binop.rhs.1.clone(),
)],
binop.signature(),
);
} else {
seen_binops.insert(binop_key);
}
}
for binop in &mut module.binop_defs {
let res = binop.infer_types(&self.refs, &mut state.inner());
state.ok(res, binop.block_meta().unwrap_or(binop.signature()));
}
for function in &mut module.functions { for function in &mut module.functions {
let res = function.infer_types(&self.refs, &mut state.inner()); let res = function.infer_types(&self.refs, &mut state.inner());
state.ok(res, function.block_meta()); state.ok(res, function.block_meta());
@ -63,16 +94,60 @@ impl<'t> Pass for TypeInference<'t> {
} }
} }
impl BinopDefinition {
fn infer_types(
&mut self,
type_refs: &TypeRefs,
state: &mut TypeInferencePassState,
) -> Result<(), ErrorKind> {
let scope_hints = ScopeTypeRefs::from(type_refs);
let lhs_ty = state.or_else(
self.lhs.1.assert_unvague(),
Vague(Unknown),
self.signature(),
);
state.ok(
scope_hints
.new_var(self.lhs.0.clone(), false, &lhs_ty)
.or(Err(ErrorKind::VariableAlreadyDefined(self.lhs.0.clone()))),
self.signature(),
);
let rhs_ty = state.or_else(
self.rhs.1.assert_unvague(),
Vague(Unknown),
self.signature(),
);
state.ok(
scope_hints
.new_var(self.rhs.0.clone(), false, &rhs_ty)
.or(Err(ErrorKind::VariableAlreadyDefined(self.rhs.0.clone()))),
self.signature(),
);
let ret_ty =
self.fn_kind
.infer_types(state, &scope_hints, Some(self.return_type.clone()))?;
if let Some(mut ret_ty) = ret_ty {
ret_ty.narrow(&scope_hints.from_type(&self.return_type).unwrap());
}
Ok(())
}
}
impl FunctionDefinition { impl FunctionDefinition {
fn infer_types( fn infer_types(
&mut self, &mut self,
type_refs: &TypeRefs, type_refs: &TypeRefs,
state: &mut TypeInferencePassState, state: &mut TypeInferencePassState,
) -> Result<(), ErrorKind> { ) -> Result<(), ErrorKind> {
let scope_hints = ScopeTypeRefs::from(type_refs); let scope_refs = ScopeTypeRefs::from(type_refs);
for param in &self.parameters { for param in &self.parameters {
let param_t = state.or_else(param.1.assert_unvague(), Vague(Unknown), self.signature()); let param_t = state.or_else(param.1.assert_unvague(), Vague(Unknown), self.signature());
let res = scope_hints let res = scope_refs
.new_var(param.0.clone(), false, &param_t) .new_var(param.0.clone(), false, &param_t)
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone()))); .or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
state.ok(res, self.signature()); state.ok(res, self.signature());
@ -83,21 +158,51 @@ impl FunctionDefinition {
state.scope.return_type_hint = Some(self.return_type.clone()); state.scope.return_type_hint = Some(self.return_type.clone());
// Infer block return type // Infer block return type
let ret_res = block.infer_types(state, &scope_hints); let ret_res = block.infer_types(state, &scope_refs);
// Narrow block type to declared function type // Narrow block type to declared function type
if let Some(mut ret_ty) = state.ok(ret_res.map(|(_, ty)| ty), self.block_meta()) { if let Some(mut ret_ty) = state.ok(ret_res.map(|(_, ty)| ty), self.block_meta()) {
ret_ty.narrow(&scope_hints.from_type(&self.return_type).unwrap()); ret_ty.narrow(&scope_refs.from_type(&self.return_type).unwrap());
} }
} }
FunctionDefinitionKind::Extern(_) => {} FunctionDefinitionKind::Extern(_) => {}
FunctionDefinitionKind::Intrinsic(_) => {} FunctionDefinitionKind::Intrinsic(_) => {}
}; };
let return_ty = self
.kind
.infer_types(state, &scope_refs, Some(self.return_type.clone()));
if let Some(Some(mut ret_ty)) = state.ok(return_ty, self.block_meta()) {
ret_ty.narrow(&scope_refs.from_type(&self.return_type).unwrap());
}
Ok(()) Ok(())
} }
} }
impl FunctionDefinitionKind {
fn infer_types<'s>(
&mut self,
state: &mut TypeInferencePassState,
scope_refs: &'s ScopeTypeRefs,
hint: Option<TypeKind>,
) -> Result<Option<TypeRef<'s>>, ErrorKind> {
Ok(match self {
FunctionDefinitionKind::Local(block, _) => {
state.scope.return_type_hint = hint;
// Infer block return type
let ret_res = block.infer_types(state, &scope_refs);
// Narrow block type to declared function type
Some(ret_res.map(|(_, ty)| ty)?)
}
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
})
}
}
impl Block { impl Block {
fn infer_types<'s>( fn infer_types<'s>(
&mut self, &mut self,
@ -209,12 +314,31 @@ impl Expression {
// Infer LHS and RHS, and return binop type // Infer LHS and RHS, and return binop type
let mut lhs_ref = lhs.infer_types(state, type_refs)?; let mut lhs_ref = lhs.infer_types(state, type_refs)?;
let mut rhs_ref = rhs.infer_types(state, type_refs)?; let mut rhs_ref = rhs.infer_types(state, type_refs)?;
type_refs
.binop(op, &mut lhs_ref, &mut rhs_ref) if let Ok(binop) = type_refs
.binop(op, &mut lhs_ref, &mut rhs_ref, &state.scope.binops)
.ok_or(ErrorKind::TypesIncompatible( .ok_or(ErrorKind::TypesIncompatible(
lhs_ref.resolve_deep().unwrap(), lhs_ref.resolve_deep().unwrap(),
rhs_ref.resolve_deep().unwrap(), rhs_ref.resolve_deep().unwrap(),
)) ))
{
Ok(binop)
} else {
let typeref = lhs_ref.narrow(&rhs_ref).unwrap();
Ok(type_refs
.from_type(
&typeref
.resolve_deep()
.unwrap()
.simple_binop_type(op)
.ok_or(ErrorKind::InvalidBinop(
*op,
lhs_ref.resolve_deep().unwrap(),
rhs_ref.resolve_deep().unwrap(),
))?,
)
.unwrap())
}
} }
ExprKind::FunctionCall(function_call) => { ExprKind::FunctionCall(function_call) => {
// Get function definition and types // Get function definition and types

View File

@ -6,7 +6,11 @@ use std::{
use crate::mir::VagueType; use crate::mir::VagueType;
use super::{typecheck::ErrorKind, BinaryOperator, TypeKind}; use super::{
pass::{ScopeBinopDef, ScopeBinopKey, Storage},
typecheck::ErrorKind,
BinaryOperator, TypeKind,
};
#[derive(Clone)] #[derive(Clone)]
pub struct TypeRef<'scope>( pub struct TypeRef<'scope>(
@ -227,8 +231,39 @@ impl<'outer> ScopeTypeRefs<'outer> {
op: &BinaryOperator, op: &BinaryOperator,
lhs: &mut TypeRef<'outer>, lhs: &mut TypeRef<'outer>,
rhs: &mut TypeRef<'outer>, rhs: &mut TypeRef<'outer>,
binops: &Storage<ScopeBinopKey, ScopeBinopDef>,
) -> Option<TypeRef<'outer>> { ) -> Option<TypeRef<'outer>> {
let ty = lhs.narrow(rhs)?; if lhs.resolve_deep().unwrap().known().is_err()
self.from_type(&ty.as_type().binop_type(op)) && rhs.resolve_deep().unwrap().known().is_err()
{
return self.from_type(&TypeKind::Vague(VagueType::Unknown));
}
let mut iter = binops.iter();
loop {
let Some((_, binop)) = iter.next() else {
break None;
};
if let Some(ret) = try_binop(lhs, rhs, binop) {
break Some(ret);
}
if binop.operator.is_commutative() {
if let Some(ret) = try_binop(rhs, lhs, binop) {
return Some(ret);
} }
} }
}
}
}
fn try_binop<'o>(
lhs: &mut TypeRef<'o>,
rhs: &mut TypeRef<'o>,
binop: &ScopeBinopDef,
) -> Option<TypeRef<'o>> {
let (lhs_ty, rhs_ty, ret_ty) =
TypeKind::binop_type(&lhs.resolve_deep()?, &rhs.resolve_deep()?, binop)?;
lhs.narrow(&lhs.1.from_type(&lhs_ty).unwrap()).unwrap();
rhs.narrow(&rhs.1.from_type(&rhs_ty).unwrap()).unwrap();
lhs.1.from_type(&ret_ty)
}