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);
return addition(5, 3);
return 8;
}

View File

@ -8,7 +8,7 @@ use std::{
};
use llvm_sys::{
LLVMIntPredicate, LLVMLinkage, LLVMRealPredicate, LLVMValueKind,
LLVMAttributeIndex, LLVMIntPredicate, LLVMLinkage, LLVMRealPredicate, LLVMValueKind,
analysis::LLVMVerifyModule,
core::*,
debuginfo::*,
@ -86,7 +86,7 @@ impl CompiledModule {
triple,
c"generic".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::LLVMCodeModel::LLVMCodeModelDefault,
);
@ -601,6 +601,15 @@ impl FunctionHolder {
let function_ref =
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 {
if let Some(value) = &self.data.debug {
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_pub: bool,
pub is_imported: bool,
pub inline: bool,
}
impl Default for FunctionFlags {
@ -157,6 +158,7 @@ impl Default for FunctionFlags {
is_main: false,
is_pub: false,
is_imported: false,
inline: false,
}
}
}

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

@ -207,6 +207,17 @@ pub enum TopLevelStatement {
ExternFunction(FunctionSignature),
FunctionDefinition(FunctionDefinition),
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)]

View File

@ -314,7 +314,7 @@ fn parse_binop_rhs(
lhs = Expression(
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);
}
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,
})
}
Some(Token::Impl) => Stmt::BinopDefinition(stream.parse()?),
_ => 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 functions = Vec::new();
let mut typedefs = Vec::new();
let mut binops = Vec::new();
use ast::TopLevelStatement::*;
for stmt in &self.top_level_statements {
@ -97,12 +98,33 @@ impl ast::Module {
};
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 {
name: self.name.clone(),
module_id: module_id,
binop_defs: binops,
imports,
functions,
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::{
builder::{InstructionValue, TypeValue},
@ -16,9 +16,13 @@ use reid_lib::{
use crate::{
allocator::{Allocator, AllocatorScope},
intrinsics::IntrinsicFunction,
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 +81,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,12 +137,8 @@ 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);
pub struct StackValue(pub(super) StackValueKind, pub(super) TypeKind);
impl StackValue {
fn instr(&self) -> InstructionValue {
@ -148,40 +186,48 @@ 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,
kind: StackBinopFunctionKind<'ctx>,
}
pub enum StackBinopFunctionKind<'ctx> {
UserGenerated(Function<'ctx>),
Intrinsic(&'ctx Box<dyn IntrinsicFunction>),
}
impl<'ctx> StackBinopDefinition<'ctx> {
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()])
}
}
}
/// 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, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
@ -296,7 +342,7 @@ impl mir::Module {
let is_main = self.is_main && function.name == "main";
let func = match &function.kind {
mir::FunctionDefinitionKind::Local(_, _) => module.function(
mir::FunctionDefinitionKind::Local(_, _) => Some(module.function(
&function.name,
function.return_type.get_type(&type_values),
param_types,
@ -306,8 +352,8 @@ impl mir::Module {
is_imported: function.is_imported,
..FunctionFlags::default()
},
),
mir::FunctionDefinitionKind::Extern(imported) => module.function(
)),
mir::FunctionDefinitionKind::Extern(imported) => Some(module.function(
&function.name,
function.return_type.get_type(&type_values),
param_types,
@ -316,191 +362,288 @@ impl mir::Module {
is_imported: *imported,
..FunctionFlags::default()
},
),
mir::FunctionDefinitionKind::Intrinsic(_) => module.function(
&function.name,
function.return_type.get_type(&type_values),
param_types,
FunctionFlags {
..FunctionFlags::default()
},
),
)),
mir::FunctionDefinitionKind::Intrinsic(_) => None,
};
functions.insert(function.name.clone(), StackFunction { ir: func });
if let Some(func) = func {
functions.insert(function.name.clone(), func);
}
}
let mut binops = HashMap::new();
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");
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();
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");
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(_) => {}
};
Ok(())
}
}
@ -639,9 +782,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 +884,101 @@ 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 {
let a = operation.codegen(&lhs_val, &rhs_val, scope)?;
Some(a)
} else {
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)
}
};
dbg!(&instr);
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 +1009,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 +1057,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 +1066,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 +1469,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

@ -1,20 +1,15 @@
use reid_lib::Instr;
use reid_lib::{builder::InstructionValue, Instr};
use crate::{
codegen::{ErrorKind, Scope},
mir::{FunctionDefinition, FunctionDefinitionKind, TypeKind},
codegen::{ErrorKind, Scope, StackValue, StackValueKind},
mir::{BinaryOperator, BinopDefinition, FunctionDefinition, FunctionDefinitionKind, TypeKind},
};
#[derive(Debug, Clone, Copy)]
pub enum InstrinsicKind {
IAdd,
}
fn intrinsic(
name: &str,
ret_ty: TypeKind,
params: Vec<(&str, TypeKind)>,
kind: InstrinsicKind,
fun: impl IntrinsicFunction + 'static,
) -> FunctionDefinition {
FunctionDefinition {
name: name.into(),
@ -22,36 +17,93 @@ fn intrinsic(
is_imported: false,
return_type: ret_ty,
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> {
let mut intrinsics = Vec::new();
intrinsics.push(intrinsic(
"addition",
TypeKind::U8,
vec![("lhs".into(), TypeKind::U8), ("rhs".into(), TypeKind::U8)],
InstrinsicKind::IAdd,
));
let intrinsics = Vec::new();
intrinsics
}
impl InstrinsicKind {
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Result<(), ErrorKind> {
match self {
InstrinsicKind::IAdd => {
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();
scope
.block
.terminate(reid_lib::TerminatorKind::Ret(add))
.unwrap()
}
}
Ok(())
pub fn form_intrinsic_binops() -> Vec<BinopDefinition> {
let mut intrinsics = Vec::new();
intrinsics
}
pub trait IntrinsicFunction: std::fmt::Debug {
fn codegen<'ctx, 'a>(
&self,
scope: &mut Scope<'ctx, 'a>,
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()))
}
}
#[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,
/// `for`
For,
/// `In`
/// `in`
In,
/// `impl`
Impl,
/// `binop`
Binop,
// Symbols
/// `;`
@ -145,6 +149,8 @@ impl ToString for Token {
Token::For => String::from("for"),
Token::In => String::from("in"),
Token::While => String::from("while"),
Token::Impl => String::from("impl"),
Token::Binop => String::from("binop"),
Token::Semi => String::from(';'),
Token::Equals => 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,
"while" => Token::While,
"in" => Token::In,
"impl" => Token::Impl,
"binop" => Token::Binop,
_ => Token::Identifier(value),
};
variant

View File

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

View File

@ -40,6 +40,9 @@ impl Display for Module {
for import in &self.imports {
writeln!(inner_f, "{}", import)?;
}
for binop in &self.binop_defs {
writeln!(inner_f, "{}", binop)?;
}
for typedef in &self.typedefs {
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 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
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)]
pub enum ReturnTypeOther {
@ -95,11 +95,11 @@ 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 {
// TODO make some type of mechanism that allows to binop two values of
// differing types..
// TODO Return None for arrays later
match op {
pub fn simple_binop_type(&self, op: &BinaryOperator) -> Option<TypeKind> {
if !self.category().is_simple_maths() {
return None;
}
Some(match op {
BinaryOperator::Add => self.clone(),
BinaryOperator::Minus => self.clone(),
BinaryOperator::Mult => self.clone(),
@ -107,12 +107,29 @@ impl TypeKind {
BinaryOperator::Cmp(_) => TypeKind::Bool,
BinaryOperator::Div => 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
/// 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 {
BinaryOperator::Add
| 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 {
match self {
TypeKind::Bool => false,
@ -245,7 +278,7 @@ impl TypeKind {
| TypeKind::F80
| TypeKind::F128PPC => TypeCategory::Real,
TypeKind::Void => TypeCategory::Other,
TypeKind::Bool => TypeCategory::Other,
TypeKind::Bool => TypeCategory::Bool,
TypeKind::Array(_, _) => TypeCategory::Other,
TypeKind::CustomType(..) => 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)]
pub enum TypeCategory {
Integer,
Real,
Bool,
Other,
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 {
pub fn get_field_ty(&self, name: &String) -> Option<&TypeKind> {
self.0

View File

@ -5,7 +5,7 @@
use std::{collections::HashMap, path::PathBuf};
use crate::{
intrinsics::InstrinsicKind,
intrinsics::IntrinsicFunction,
lexer::{FullToken, Position},
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 {
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,
@ -303,7 +303,7 @@ pub enum FunctionDefinitionKind {
/// True = imported from other module, False = Is user defined extern
Extern(bool),
/// Intrinsic definition, defined within the compiler
Intrinsic(InstrinsicKind),
Intrinsic(Box<dyn IntrinsicFunction>),
}
impl FunctionDefinition {
@ -365,6 +365,30 @@ pub enum TypeDefinitionKind {
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)]
pub struct Module {
pub name: String,
@ -372,6 +396,7 @@ pub struct Module {
pub imports: Vec<Import>,
pub functions: Vec<FunctionDefinition>,
pub typedefs: Vec<TypeDefinition>,
pub binop_defs: Vec<BinopDefinition>,
pub path: Option<PathBuf>,
pub tokens: Vec<FullToken>,
pub is_main: bool,

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,19 @@ 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()
}
pub fn find(&self, key: &Key) -> Option<(&Key, &T)> {
self.0.iter().find(|(k, _)| *k == key)
}
}
#[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 +137,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 +172,57 @@ 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 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 +362,23 @@ 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,
return_ty: binop.return_type.clone(),
},
)
.ok();
}
for function in &self.functions {
scope
.function_returns

View File

@ -64,12 +64,16 @@ pub enum ErrorKind {
ImpossibleMutableBorrow(String),
#[error("Cannot declare variable {0} as mutable, when it's type is immutable")]
ImpossibleMutLet(String),
#[error("Cannot produce a negative unsigned value of type {0}!")]
#[error("Cannot produce a negative unsigned value of type {0}")]
NegativeUnsignedValue(TypeKind),
#[error("Cannot cast type {0} into type {1}!")]
#[error("Cannot cast type {0} into type {1}")]
NotCastableTo(TypeKind, TypeKind),
#[error("Cannot divide by zero")]
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
@ -132,6 +136,11 @@ impl<'t> Pass for TypeCheck<'t> {
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 {
let res = function.typecheck(&self.refs, &mut state.inner());
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 {
fn typecheck(
&mut self,
@ -197,10 +252,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)))
@ -208,13 +283,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())),
}
}
}
@ -442,34 +510,82 @@ 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 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));
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);
}
};
Ok(both_t.binop_type(op))
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(
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);
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) {
// Try to coerce both sides again with collapsed type
lhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
}
both_t
.simple_binop_type(op)
.ok_or(ErrorKind::InvalidBinop(*op, lhs_type, rhs_type))
}
}
ExprKind::FunctionCall(function_call) => {
let true_function = state
@ -748,7 +864,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,16 +4,20 @@
//! 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},
Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition, FunctionDefinitionKind,
IfExpression, Module, ReturnKind, StmtKind,
BinopDefinition, Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition,
FunctionDefinitionKind, IfExpression, Module, ReturnKind, StmtKind,
TypeKind::*,
VagueType::*,
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 {
let res = function.infer_types(&self.refs, &mut state.inner());
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 {
fn infer_types(
&mut self,
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());
@ -83,21 +158,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,
@ -209,12 +314,31 @@ impl Expression {
// Infer LHS and RHS, and return binop type
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)
if let Ok(binop) = type_refs
.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(),
))
{
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) => {
// Get function definition and types

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,39 @@ impl<'outer> ScopeTypeRefs<'outer> {
op: &BinaryOperator,
lhs: &mut TypeRef<'outer>,
rhs: &mut TypeRef<'outer>,
binops: &Storage<ScopeBinopKey, ScopeBinopDef>,
) -> Option<TypeRef<'outer>> {
let ty = lhs.narrow(rhs)?;
self.from_type(&ty.as_type().binop_type(op))
if lhs.resolve_deep().unwrap().known().is_err()
&& 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)
}