Compare commits

..

8 Commits

11 changed files with 779 additions and 364 deletions

View File

@ -5,8 +5,8 @@ impl binop (lhs: u16) + (rhs: u32) -> u32 {
} }
fn main() -> u32 { fn main() -> u32 {
let value = 6; let value = 6 as u16;
let other = 15; let other = 15 as u32;
return value * other + 7 * -value; return value + other;
} }

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

@ -110,8 +110,11 @@ impl ast::Module {
lhs: (lhs.0.clone(), lhs.1 .0.into_mir(module_id)), lhs: (lhs.0.clone(), lhs.1 .0.into_mir(module_id)),
op: op.mir(), op: op.mir(),
rhs: (rhs.0.clone(), rhs.1 .0.into_mir(module_id)), rhs: (rhs.0.clone(), rhs.1 .0.into_mir(module_id)),
return_ty: return_ty.0.into_mir(module_id), return_type: return_ty.0.into_mir(module_id),
block: block.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), meta: signature_range.as_meta(module_id),
}); });
} }

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},
@ -18,7 +18,10 @@ use crate::{
allocator::{Allocator, AllocatorScope}, allocator::{Allocator, AllocatorScope},
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 +80,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,10 +136,6 @@ 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(StackValueKind, TypeKind);
@ -148,39 +185,32 @@ 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, ir: Function<'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 impl<'ctx> StackBinopDefinition<'ctx> {
/// and returns the old block. fn codegen<'a>(
fn swap_block(&mut self, block: Block<'ctx>) -> Block<'ctx> { &self,
let mut old_block = block; lhs: &StackValue,
mem::swap(&mut self.block, &mut old_block); rhs: &StackValue,
old_block scope: &mut Scope<'ctx, 'a>,
} ) -> StackValue {
let (lhs, rhs) = if lhs.1 == self.parameters.0 .1 && rhs.1 == self.parameters.1 .1 {
fn get_typedef(&self, key: &CustomTypeKey) -> Option<&TypeDefinition> { (lhs, rhs)
self.type_values.get(key).and_then(|v| self.types.get(v)) } else {
} (rhs, lhs)
};
fn allocate(&self, name: &String, ty: &TypeKind) -> Option<InstructionValue> { let instr = scope
self.allocator.borrow_mut().allocate(name, ty) .block
.build(Instr::FunctionCall(
self.ir.value(),
vec![lhs.instr(), rhs.instr()],
))
.unwrap();
StackValue(StackValueKind::Immutable(instr), self.return_ty.clone())
} }
} }
@ -327,17 +357,29 @@ impl mir::Module {
), ),
}; };
functions.insert(function.name.clone(), StackFunction { ir: 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 {
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::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 +387,183 @@ 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();
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(),
ir: ir_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 +572,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 +595,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 +609,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(kind) => kind.codegen(scope)?,
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 +760,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 +862,26 @@ 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 {
Some(operation.codegen(&lhs_val, &rhs_val, scope))
} else {
dbg!((lhs_val.1.clone(), rhs_val.1.clone()));
dbg!(&operation.map(|b| &b.return_ty));
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 +898,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),
@ -821,6 +958,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 +988,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 +1036,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 +1045,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 +1448,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

@ -64,9 +64,9 @@ impl Display for BinopDefinition {
write!( write!(
f, f,
"impl binop ({}: {:#}) {} ({}: {:#}) -> {:#} ", "impl binop ({}: {:#}) {} ({}: {:#}) -> {:#} ",
self.lhs.0, self.lhs.1, self.op, self.rhs.0, self.rhs.1, self.return_ty self.lhs.0, self.lhs.1, self.op, self.rhs.0, self.rhs.1, self.return_type
)?; )?;
Display::fmt(&self.block, f) Display::fmt(&self.fn_kind, f)
} }
} }

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,7 +95,7 @@ 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) -> TypeKind {
// TODO make some type of mechanism that allows to binop two values of // TODO make some type of mechanism that allows to binop two values of
// differing types.. // differing types..
// TODO Return None for arrays later // TODO Return None for arrays later
@ -110,9 +110,23 @@ impl TypeKind {
} }
} }
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> {
match op { match op {
BinaryOperator::Add BinaryOperator::Add
| BinaryOperator::Minus | BinaryOperator::Minus
@ -124,6 +138,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,
@ -259,6 +289,40 @@ impl TypeKind {
}, },
} }
} }
pub fn try_collapse_two(
(lhs1, rhs1): (&TypeKind, &TypeKind),
(lhs2, rhs2): (&TypeKind, &TypeKind),
) -> Option<(TypeKind, TypeKind)> {
if lhs1.collapse_into(&lhs2).is_ok() && rhs1.collapse_into(&rhs2).is_ok() {
Some((lhs1.clone(), rhs2.clone()))
} else if lhs1.collapse_into(&rhs2).is_ok() && rhs1.collapse_into(&lhs2).is_ok() {
Some((rhs1.clone(), lhs1.clone()))
} 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)]

View File

@ -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,
@ -370,14 +370,18 @@ pub struct BinopDefinition {
pub lhs: (String, TypeKind), pub lhs: (String, TypeKind),
pub op: BinaryOperator, pub op: BinaryOperator,
pub rhs: (String, TypeKind), pub rhs: (String, TypeKind),
pub return_ty: TypeKind, pub return_type: TypeKind,
pub block: Block, pub fn_kind: FunctionDefinitionKind,
pub meta: Metadata, pub meta: Metadata,
} }
impl BinopDefinition { impl BinopDefinition {
pub fn block_meta(&self) -> Metadata { pub fn block_meta(&self) -> Option<Metadata> {
self.block.meta match &self.fn_kind {
FunctionDefinitionKind::Local(block, _) => Some(block.meta),
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
}
} }
pub fn signature(&self) -> Metadata { pub fn signature(&self) -> Metadata {

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,15 @@ 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()
}
} }
#[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 +133,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 +168,58 @@ 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 commutative: bool,
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 +359,24 @@ 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,
commutative: true,
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

@ -70,6 +70,8 @@ pub enum ErrorKind {
NotCastableTo(TypeKind, TypeKind), NotCastableTo(TypeKind, TypeKind),
#[error("Cannot divide by zero")] #[error("Cannot divide by zero")]
DivideZero, DivideZero,
#[error("Binary operation between {0} and {1} is already defined!")]
BinaryOpAlreadyDefined(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
@ -134,7 +136,7 @@ impl<'t> Pass for TypeCheck<'t> {
for binop in &mut module.binop_defs { for binop in &mut module.binop_defs {
let res = binop.typecheck(&self.refs, &mut state.inner()); let res = binop.typecheck(&self.refs, &mut state.inner());
state.ok(res, binop.block_meta()); state.ok(res, binop.block_meta().unwrap_or(binop.signature()));
} }
for function in &mut module.functions { for function in &mut module.functions {
@ -201,18 +203,22 @@ impl BinopDefinition {
state.ok(res, self.signature()); state.ok(res, self.signature());
} }
let return_type = self.return_ty.clone().assert_known(typerefs, state)?; let return_type = self.return_type.clone().assert_known(typerefs, state)?;
state.scope.return_type_hint = Some(self.return_ty.clone()); state.scope.return_type_hint = Some(self.return_type.clone());
let inferred = self let inferred =
.block self.fn_kind
.typecheck(&mut state.inner(), &typerefs, Some(&return_type)); .typecheck(&typerefs, &mut state.inner(), Some(return_type.clone()));
match inferred { match inferred {
Ok(t) => return_type Ok(t) => return_type
.collapse_into(&t.1) .collapse_into(&t.1)
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))), .or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
Err(e) => Ok(state.or_else(Err(e), return_type, self.block_meta())), Err(e) => Ok(state.or_else(
Err(e),
return_type,
self.block_meta().unwrap_or(self.signature()),
)),
} }
} }
} }
@ -244,10 +250,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)))
@ -255,13 +281,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())),
} }
} }
} }
@ -489,35 +508,64 @@ 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 operator = state
.scope
.binops
.get(&pass::ScopeBinopKey {
params: (lhs_type.clone(), rhs_type.clone()),
operator: *op,
})
.cloned();
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)
} 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);
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
lhs.typecheck(state, &typerefs, Some(&collapsed)).ok(); lhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok(); rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
} }
let both_t = lhs_type.collapse_into(&rhs_type)?; Ok(both_t.simple_binop_type(op))
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));
} }
} }
}
Ok(both_t.binop_type(op))
}
ExprKind::FunctionCall(function_call) => { ExprKind::FunctionCall(function_call) => {
let true_function = state let true_function = state
.scope .scope
@ -795,7 +843,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,12 +4,16 @@
//! 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},
BinopDefinition, Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition, BinopDefinition, Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition,
@ -55,9 +59,28 @@ 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) {
state.note_errors(
&vec![ErrorKind::BinaryOpAlreadyDefined(
binop.lhs.1.clone(),
binop.rhs.1.clone(),
)],
binop.signature(),
);
} else {
seen_binops.insert(binop_key);
}
}
for binop in &mut module.binop_defs { for binop in &mut module.binop_defs {
let res = binop.infer_types(&self.refs, &mut state.inner()); let res = binop.infer_types(&self.refs, &mut state.inner());
state.ok(res, binop.block_meta()); state.ok(res, binop.block_meta().unwrap_or(binop.signature()));
} }
for function in &mut module.functions { for function in &mut module.functions {
@ -101,18 +124,12 @@ impl BinopDefinition {
self.signature(), self.signature(),
); );
state.scope.return_type_hint = Some(self.return_ty.clone()); let ret_ty =
let ret_res = self.block.infer_types(state, &scope_hints); self.fn_kind
let (_, mut ret_ty) = state.or_else( .infer_types(state, &scope_hints, Some(self.return_type.clone()))?;
ret_res, if let Some(mut ret_ty) = ret_ty {
( ret_ty.narrow(&scope_hints.from_type(&self.return_type).unwrap());
ReturnKind::Soft, }
scope_hints.from_type(&Vague(Unknown)).unwrap(),
),
self.block_meta(),
);
ret_ty.narrow(&scope_hints.from_type(&self.return_ty).unwrap());
Ok(()) Ok(())
} }
@ -124,10 +141,10 @@ impl FunctionDefinition {
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());
@ -138,21 +155,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,
@ -265,7 +312,7 @@ impl Expression {
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 type_refs
.binop(op, &mut lhs_ref, &mut rhs_ref) .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(),

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,31 @@ 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>> {
for (_, binop) in binops.iter() {
if let Some(ret) = try_binop(lhs, rhs, binop) {
return Some(ret);
}
if binop.commutative {
if let Some(ret) = try_binop(rhs, lhs, binop) {
return Some(ret);
}
}
}
let ty = lhs.narrow(rhs)?; let ty = lhs.narrow(rhs)?;
self.from_type(&ty.as_type().binop_type(op)) self.from_type(&ty.as_type().simple_binop_type(op))
} }
} }
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)
}