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

View File

@ -110,8 +110,11 @@ impl ast::Module {
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_ty: return_ty.0.into_mir(module_id),
block: block.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),
});
}

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::{
builder::{InstructionValue, TypeValue},
@ -18,7 +18,10 @@ use crate::{
allocator::{Allocator, AllocatorScope},
lexer::{FullToken, Position},
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,
WhileStatement,
},
@ -77,17 +80,55 @@ pub struct Scope<'ctx, 'scope> {
modules: &'scope HashMap<SourceModuleId, ModuleCodegen<'ctx>>,
tokens: &'ctx Vec<FullToken>,
module: &'ctx Module<'ctx>,
pub(super) module_id: SourceModuleId,
function: &'ctx StackFunction<'ctx>,
module_id: SourceModuleId,
function: &'ctx Function<'ctx>,
pub(super) block: Block<'ctx>,
pub(super) types: &'scope HashMap<TypeValue, TypeDefinition>,
pub(super) type_values: &'scope HashMap<CustomTypeKey, TypeValue>,
functions: &'scope HashMap<String, StackFunction<'ctx>>,
types: &'scope HashMap<TypeValue, TypeDefinition>,
type_values: &'scope HashMap<CustomTypeKey, TypeValue>,
functions: &'scope HashMap<String, Function<'ctx>>,
binops: &'scope HashMap<ScopeBinopKey, StackBinopDefinition<'ctx>>,
stack_values: HashMap<String, StackValue>,
debug: Option<Debug<'ctx>>,
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)]
pub struct Debug<'ctx> {
info: &'ctx DebugInformation,
@ -95,10 +136,6 @@ pub struct Debug<'ctx> {
types: &'ctx HashMap<TypeKind, DebugTypeValue>,
}
pub struct StackFunction<'ctx> {
ir: Function<'ctx>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StackValue(StackValueKind, TypeKind);
@ -148,39 +185,32 @@ impl StackValueKind {
}
}
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(),
}
}
pub struct StackBinopDefinition<'ctx> {
parameters: ((String, TypeKind), (String, TypeKind)),
return_ty: TypeKind,
ir: Function<'ctx>,
}
/// 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)
impl<'ctx> StackBinopDefinition<'ctx> {
fn codegen<'a>(
&self,
lhs: &StackValue,
rhs: &StackValue,
scope: &mut Scope<'ctx, 'a>,
) -> StackValue {
let (lhs, rhs) = if lhs.1 == self.parameters.0 .1 && rhs.1 == self.parameters.1 .1 {
(lhs, rhs)
} else {
(rhs, lhs)
};
let instr = scope
.block
.build(Instr::FunctionCall(
self.ir.value(),
vec![lhs.instr(), rhs.instr()],
))
.unwrap();
StackValue(StackValueKind::Immutable(instr), self.return_ty.clone())
}
}
@ -327,180 +357,271 @@ impl mir::Module {
),
};
functions.insert(function.name.clone(), StackFunction { ir: func });
functions.insert(function.name.clone(), func);
}
let mut binops = HashMap::new();
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");
let allocator = Allocator::from(
&binop.fn_kind,
&vec![binop.lhs.clone(), binop.rhs.clone()],
&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: &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)),
};
binop
.fn_kind
.codegen(
binop_fn_name.clone(),
false,
&mut scope,
&vec![binop.lhs.clone(), binop.rhs.clone()],
&binop.return_type,
&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");
match &mir_function.kind {
mir::FunctionDefinitionKind::Local(block, _) => {
let mut entry = function.ir.block("entry");
let mut allocator = Allocator::from(
mir_function,
&mut AllocatorScope {
block: &mut entry,
module_id: self.module_id,
type_values: &type_values,
},
);
let allocator = Allocator::from(
&mir_function.kind,
&mir_function.parameters,
&mut AllocatorScope {
block: &mut entry,
module_id: self.module_id,
type_values: &type_values,
},
);
// Insert debug information
let debug_scope = if let Some(location) =
mir_function.signature().into_debug(tokens, compile_unit)
{
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 = &mir_function.return_type.get_debug_type_hard(
compile_unit,
&debug,
&debug_types,
&type_values,
&types,
self.module_id,
&self.tokens,
&modules,
);
let fn_param_ty = &return_type.get_debug_type(&debug, scope);
let debug_ty =
debug.debug_type(DebugTypeData::Subprogram(DebugSubprogramType {
parameters: vec![*fn_param_ty],
flags: DwarfFlags,
}));
debug
.info
.debug_type(DebugTypeData::Subprogram(DebugSubprogramType {
parameters: vec![*fn_param_ty],
flags: DwarfFlags,
}));
let subprogram = debug.subprogram(DebugSubprogramData {
name: mir_function.name.clone(),
outer_scope: compile_unit.clone(),
let subprogram = debug.info.subprogram(DebugSubprogramData {
name: name.clone(),
outer_scope: debug.scope.clone(),
location,
ty: debug_ty,
opts: DebugSubprogramOptionals {
is_local: !mir_function.is_pub,
is_local: !is_pub,
is_definition: true,
..DebugSubprogramOptionals::default()
},
});
function.ir.set_debug(subprogram);
Some(subprogram)
} else {
None
};
// Compile actual IR part
let mut stack_values = HashMap::new();
for (i, (p_name, p_ty)) in mir_function.parameters.iter().enumerate() {
// Codegen actual parameters
let arg_name = format!("arg.{}", p_name);
let param = entry
.build_named(format!("{}.get", arg_name), Instr::Param(i))
.unwrap();
let alloca = allocator.allocate(&p_name, &p_ty).unwrap();
entry
.build_named(format!("{}.store", arg_name), Instr::Store(alloca, param))
.unwrap();
stack_values.insert(
p_name.clone(),
StackValue(
StackValueKind::mutable(p_ty.is_mutable(), alloca),
TypeKind::CodegenPtr(Box::new(p_ty.clone())),
),
);
// Generate debug info
if let (Some(debug_scope), Some(location)) = (
&debug_scope,
mir_function.signature().into_debug(tokens, compile_unit),
) {
// debug.metadata(
// &location,
// DebugMetadata::ParamVar(DebugParamVariable {
// name: p_name.clone(),
// arg_idx: i as u32,
// ty: p_ty.get_debug_type_hard(
// *debug_scope,
// &debug,
// &debug_types,
// &type_values,
// &types,
// self.module_id,
// &self.tokens,
// &modules,
// ),
// always_preserve: true,
// 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();
if let Some(ret) = block.codegen(&mut scope, &state)? {
scope.block.terminate(Term::Ret(ret.instr())).unwrap();
} else {
if !scope.block.delete_if_unused().unwrap() {
// Add a void return just in case if the block
// wasn't unused but didn't have a terminator yet
scope.block.terminate(Term::RetVoid).ok();
}
}
if let Some(debug) = scope.debug {
let location =
&block.return_meta().into_debug(tokens, debug.scope).unwrap();
let location = debug.info.location(&debug.scope, *location);
scope.block.set_terminator_location(location).unwrap();
ir_function.set_debug(subprogram);
scope.debug = Some(Debug {
info: debug.info,
scope: subprogram,
types: debug.types,
});
}
}
mir::FunctionDefinitionKind::Extern(_) => {}
mir::FunctionDefinitionKind::Intrinsic(kind) => {
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())),
};
kind.codegen(&mut scope)?
// Compile actual IR part
for (i, (p_name, p_ty)) in parameters.iter().enumerate() {
// Codegen actual parameters
let arg_name = format!("arg.{}", p_name);
let param = scope
.block
.build_named(format!("{}.get", arg_name), Instr::Param(i))
.unwrap();
let alloca = scope.allocate(&p_name, &p_ty).unwrap();
scope
.block
.build_named(format!("{}.store", arg_name), Instr::Store(alloca, param))
.unwrap();
scope.stack_values.insert(
p_name.clone(),
StackValue(
StackValueKind::mutable(p_ty.is_mutable(), alloca),
TypeKind::CodegenPtr(Box::new(p_ty.clone())),
),
);
// Generate debug info
// if let (Some(debug_scope), Some(location)) = (
// &debug_scope,
// mir_function.signature().into_debug(tokens, compile_unit),
// ) {
// debug.metadata(
// &location,
// DebugMetadata::ParamVar(DebugParamVariable {
// name: p_name.clone(),
// arg_idx: i as u32,
// ty: p_ty.get_debug_type_hard(
// *debug_scope,
// &debug,
// &debug_types,
// &type_values,
// &types,
// self.module_id,
// &self.tokens,
// &modules,
// ),
// always_preserve: true,
// flags: DwarfFlags,
// }),
// );
// }
}
let state = State::default();
if let Some(ret) = block.codegen(scope, &state)? {
scope.block.terminate(Term::Ret(ret.instr())).unwrap();
} else {
if !scope.block.delete_if_unused().unwrap() {
// Add a void return just in case if the block
// wasn't unused but didn't have a terminator yet
scope.block.terminate(Term::RetVoid).ok();
}
}
if let Some(debug) = &scope.debug {
let location = &block
.return_meta()
.into_debug(scope.tokens, debug.scope)
.unwrap();
let location = debug.info.location(&debug.scope, *location);
scope.block.set_terminator_location(location).unwrap();
}
}
}
Ok(ModuleCodegen { module })
mir::FunctionDefinitionKind::Extern(_) => {}
mir::FunctionDefinitionKind::Intrinsic(kind) => kind.codegen(scope)?,
};
Ok(())
}
}
@ -639,9 +760,9 @@ impl mir::Statement {
mir::StmtKind::While(WhileStatement {
condition, block, ..
}) => {
let condition_block = scope.function.ir.block("while.cond");
let condition_true_block = scope.function.ir.block("while.body");
let condition_failed_block = scope.function.ir.block("while.end");
let condition_block = scope.function.block("while.cond");
let condition_true_block = scope.function.block("while.body");
let condition_failed_block = scope.function.block("while.end");
scope
.block
@ -741,85 +862,102 @@ impl mir::Expression {
lit.as_type(),
)),
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
let lhs = lhs_exp
let lhs_val = lhs_exp
.codegen(scope, state)?
.expect("lhs has no return value")
.instr();
let rhs = rhs_exp
.expect("lhs has no return value");
let rhs_val = rhs_exp
.codegen(scope, state)?
.expect("rhs has no return value")
.instr();
let lhs_type = lhs_exp
.return_type(&Default::default(), scope.module_id)
.unwrap()
.1;
let instr = match (
binop,
lhs_type.signed(),
lhs_type.category() == TypeCategory::Real,
) {
(mir::BinaryOperator::Add, _, false) => Instr::Add(lhs, rhs),
(mir::BinaryOperator::Add, _, true) => Instr::FAdd(lhs, rhs),
(mir::BinaryOperator::Minus, _, false) => Instr::Sub(lhs, rhs),
(mir::BinaryOperator::Minus, _, true) => Instr::FSub(lhs, rhs),
(mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs),
(mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs),
(mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs),
(mir::BinaryOperator::Cmp(i), _, false) => 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, true, false) => Instr::SDiv(lhs, rhs),
(mir::BinaryOperator::Div, _, true) => Instr::FDiv(lhs, rhs),
(mir::BinaryOperator::Mod, false, false) => {
let div = scope
.block
.build(Instr::UDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Mod, true, false) => {
let div = scope
.block
.build(Instr::SDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Mod, _, true) => {
let div = scope
.block
.build(Instr::FDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
Instr::Sub(lhs, mul)
}
};
Some(StackValue(
StackValueKind::Immutable(
scope
.block
.build(instr)
.unwrap()
.maybe_location(&mut scope.block, location),
),
lhs_type,
))
.expect("rhs has no return value");
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
.return_type(&Default::default(), scope.module_id)
.unwrap()
.1;
let instr = match (
binop,
lhs_type.signed(),
lhs_type.category() == TypeCategory::Real,
) {
(mir::BinaryOperator::Add, _, false) => Instr::Add(lhs, rhs),
(mir::BinaryOperator::Add, _, true) => Instr::FAdd(lhs, rhs),
(mir::BinaryOperator::Minus, _, false) => Instr::Sub(lhs, rhs),
(mir::BinaryOperator::Minus, _, true) => Instr::FSub(lhs, rhs),
(mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs),
(mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs),
(mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs),
(mir::BinaryOperator::Cmp(i), _, false) => {
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, true, false) => Instr::SDiv(lhs, rhs),
(mir::BinaryOperator::Div, _, true) => Instr::FDiv(lhs, rhs),
(mir::BinaryOperator::Mod, false, false) => {
let div = scope
.block
.build(Instr::UDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Mod, true, false) => {
let div = scope
.block
.build(Instr::SDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Mod, _, true) => {
let div = scope
.block
.build(Instr::FDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
Instr::Sub(lhs, mul)
}
};
Some(StackValue(
StackValueKind::Immutable(
scope
.block
.build(instr)
.unwrap()
.maybe_location(&mut scope.block, location),
),
lhs_type,
))
}
}
mir::ExprKind::FunctionCall(call) => {
let ret_type_kind = call
@ -850,7 +988,7 @@ impl mir::Expression {
.block
.build_named(
call.name.clone(),
Instr::FunctionCall(callee.ir.value(), param_instrs),
Instr::FunctionCall(callee.value(), param_instrs),
)
.unwrap();
@ -898,7 +1036,7 @@ impl mir::Expression {
}
mir::ExprKind::If(if_expression) => if_expression.codegen(scope, state)?,
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();
let mut inner_scope = scope.with_block(inner);
@ -907,7 +1045,7 @@ impl mir::Expression {
} else {
None
};
let outer = scope.function.ir.block("outer");
let outer = scope.function.block("outer");
inner_scope.block.terminate(Term::Br(outer.value())).ok();
scope.swap_block(outer);
ret
@ -1310,9 +1448,9 @@ impl mir::IfExpression {
let condition = self.0.codegen(scope, state)?.unwrap();
// Create blocks
let mut then_b = scope.function.ir.block("then");
let mut else_b = scope.function.ir.block("else");
let after_b = scope.function.ir.block("after");
let mut then_b = scope.function.block("then");
let mut else_b = scope.function.block("else");
let after_b = scope.function.block("after");
if let Some(debug) = &scope.debug {
let before_location = self.0 .1.into_debug(scope.tokens, debug.scope).unwrap();

View File

@ -64,9 +64,9 @@ impl Display for BinopDefinition {
write!(
f,
"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)]
pub enum ReturnTypeOther {
@ -95,7 +95,7 @@ impl TypeKind {
/// Return the type that is the result of a binary operator between two
/// 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
// differing types..
// 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
/// 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 {
BinaryOperator::Add
| 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 {
match self {
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)]

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 {
Add,
Minus,
@ -226,7 +226,7 @@ pub enum BinaryOperator {
}
/// 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 {
LT,
LE,
@ -370,14 +370,18 @@ pub struct BinopDefinition {
pub lhs: (String, TypeKind),
pub op: BinaryOperator,
pub rhs: (String, TypeKind),
pub return_ty: TypeKind,
pub block: Block,
pub return_type: TypeKind,
pub fn_kind: FunctionDefinitionKind,
pub meta: Metadata,
}
impl BinopDefinition {
pub fn block_meta(&self) -> Metadata {
self.block.meta
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 {

View File

@ -1,7 +1,7 @@
//! 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.
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::convert::Infallible;
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> {
self.0.get(key)
}
pub fn iter(&self) -> impl Iterator<Item = (&Key, &T)> {
self.0.iter()
}
}
#[derive(Clone, Default, Debug)]
pub struct Scope<Data: Clone + Default> {
pub binops: Storage<ScopeBinopKey, ScopeBinopDef>,
pub function_returns: Storage<String, ScopeFunction>,
pub variables: Storage<String, ScopeVariable>,
pub types: Storage<CustomTypeKey, TypeDefinition>,
@ -128,6 +133,7 @@ impl<Data: Clone + Default> Scope<Data> {
Scope {
function_returns: self.function_returns.clone(),
variables: self.variables.clone(),
binops: self.binops.clone(),
types: self.types.clone(),
return_type_hint: self.return_type_hint.clone(),
data: self.data.clone(),
@ -162,6 +168,58 @@ pub struct ScopeVariable {
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> {
state: &'st mut State<TError>,
pub scope: &'sc mut Scope<Data>,
@ -301,6 +359,24 @@ impl Module {
.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 {
scope
.function_returns

View File

@ -70,6 +70,8 @@ pub enum ErrorKind {
NotCastableTo(TypeKind, TypeKind),
#[error("Cannot divide by zero")]
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
@ -134,7 +136,7 @@ impl<'t> Pass for TypeCheck<'t> {
for binop in &mut module.binop_defs {
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 {
@ -201,18 +203,22 @@ impl BinopDefinition {
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());
let inferred = self
.block
.typecheck(&mut state.inner(), &typerefs, Some(&return_type));
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())),
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 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, _) => {
state.scope.return_type_hint = Some(self.return_type.clone());
block.typecheck(&mut state.inner(), &typerefs, Some(&return_type))
state.scope.return_type_hint = hint.clone();
block.typecheck(&mut state.inner(), &typerefs, hint.as_ref())
}
FunctionDefinitionKind::Extern(_) => {
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
@ -255,13 +281,6 @@ impl FunctionDefinition {
FunctionDefinitionKind::Intrinsic(..) => {
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,34 +508,63 @@ impl Expression {
Ok(literal.as_type())
}
ExprKind::BinOp(op, lhs, rhs) => {
// TODO make sure lhs and rhs can actually do this binary
// operation once relevant
let lhs_res = lhs.typecheck(
state,
&typerefs,
hint_t.and_then(|t| t.binop_hint(op)).as_ref(),
);
// First find unfiltered parameters to binop
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, Some(&lhs_type));
let rhs_res = rhs.typecheck(state, &typerefs, None);
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) {
// Try to coerce both sides again with collapsed type
lhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
}
let operator = state
.scope
.binops
.get(&pass::ScopeBinopKey {
params: (lhs_type.clone(), rhs_type.clone()),
operator: *op,
})
.cloned();
let both_t = lhs_type.collapse_into(&rhs_type)?;
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(
state,
&typerefs,
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 rhs_res = rhs.typecheck(state, &typerefs, Some(&lhs_type));
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
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));
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));
}
}
}
}
Ok(both_t.binop_type(op))
if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) {
// Try to coerce both sides again with collapsed type
lhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
}
Ok(both_t.simple_binop_type(op))
}
}
ExprKind::FunctionCall(function_call) => {
let true_function = state
@ -795,7 +843,7 @@ impl Expression {
Ok(*inner)
}
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)
}
}

View File

@ -4,12 +4,16 @@
//! 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.
use std::{collections::HashMap, convert::Infallible, iter};
use std::{
collections::{HashMap, HashSet},
convert::Infallible,
iter,
};
use crate::{mir::TypeKind, util::try_all};
use super::{
pass::{Pass, PassResult, PassState},
pass::{self, Pass, PassResult, PassState, ScopeBinopDef, ScopeBinopKey},
typecheck::{ErrorKind, ErrorTypedefKind},
typerefs::{ScopeTypeRefs, TypeRef, TypeRefs},
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 {
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 {
@ -101,18 +124,12 @@ impl BinopDefinition {
self.signature(),
);
state.scope.return_type_hint = Some(self.return_ty.clone());
let ret_res = self.block.infer_types(state, &scope_hints);
let (_, mut ret_ty) = state.or_else(
ret_res,
(
ReturnKind::Soft,
scope_hints.from_type(&Vague(Unknown)).unwrap(),
),
self.block_meta(),
);
ret_ty.narrow(&scope_hints.from_type(&self.return_ty).unwrap());
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(())
}
@ -124,10 +141,10 @@ impl FunctionDefinition {
type_refs: &TypeRefs,
state: &mut TypeInferencePassState,
) -> Result<(), ErrorKind> {
let scope_hints = ScopeTypeRefs::from(type_refs);
let scope_refs = ScopeTypeRefs::from(type_refs);
for param in &self.parameters {
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)
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
state.ok(res, self.signature());
@ -138,21 +155,51 @@ impl FunctionDefinition {
state.scope.return_type_hint = Some(self.return_type.clone());
// 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
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::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(())
}
}
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 {
fn infer_types<'s>(
&mut self,
@ -265,7 +312,7 @@ impl Expression {
let mut lhs_ref = lhs.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)
.binop(op, &mut lhs_ref, &mut rhs_ref, &state.scope.binops)
.ok_or(ErrorKind::TypesIncompatible(
lhs_ref.resolve_deep().unwrap(),
rhs_ref.resolve_deep().unwrap(),

View File

@ -6,7 +6,11 @@ use std::{
use crate::mir::VagueType;
use super::{typecheck::ErrorKind, BinaryOperator, TypeKind};
use super::{
pass::{ScopeBinopDef, ScopeBinopKey, Storage},
typecheck::ErrorKind,
BinaryOperator, TypeKind,
};
#[derive(Clone)]
pub struct TypeRef<'scope>(
@ -227,8 +231,31 @@ impl<'outer> ScopeTypeRefs<'outer> {
op: &BinaryOperator,
lhs: &mut TypeRef<'outer>,
rhs: &mut TypeRef<'outer>,
binops: &Storage<ScopeBinopKey, ScopeBinopDef>,
) -> 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)?;
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)
}