Compare commits
No commits in common. "f6425fc37e6b661788f871796f32e4149a412e82" and "89002f34e4ae2d7cfe9eb53fbb0ba2c774f60501" have entirely different histories.
f6425fc37e
...
89002f34e4
@ -1,12 +0,0 @@
|
|||||||
// 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;
|
|
||||||
}
|
|
@ -21,5 +21,5 @@ fn main() -> u8 {
|
|||||||
|
|
||||||
free_string(&test);
|
free_string(&test);
|
||||||
|
|
||||||
return 8;
|
return addition(5, 3);
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use llvm_sys::{
|
use llvm_sys::{
|
||||||
LLVMAttributeIndex, LLVMIntPredicate, LLVMLinkage, LLVMRealPredicate, LLVMValueKind,
|
LLVMIntPredicate, LLVMLinkage, LLVMRealPredicate, LLVMValueKind,
|
||||||
analysis::LLVMVerifyModule,
|
analysis::LLVMVerifyModule,
|
||||||
core::*,
|
core::*,
|
||||||
debuginfo::*,
|
debuginfo::*,
|
||||||
@ -86,7 +86,7 @@ impl CompiledModule {
|
|||||||
triple,
|
triple,
|
||||||
c"generic".as_ptr(),
|
c"generic".as_ptr(),
|
||||||
c"".as_ptr(),
|
c"".as_ptr(),
|
||||||
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelLess,
|
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
|
||||||
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
|
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
|
||||||
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
|
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
|
||||||
);
|
);
|
||||||
@ -601,15 +601,6 @@ impl FunctionHolder {
|
|||||||
let function_ref =
|
let function_ref =
|
||||||
LLVMAddFunction(module_ref, into_cstring(&self.data.name).as_ptr(), fn_type);
|
LLVMAddFunction(module_ref, into_cstring(&self.data.name).as_ptr(), fn_type);
|
||||||
|
|
||||||
if self.data.flags.inline {
|
|
||||||
let attribute = LLVMCreateEnumAttribute(
|
|
||||||
context.context_ref,
|
|
||||||
LLVMEnumAttribute::AlwaysInline as u32,
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
LLVMAddAttributeAtIndex(function_ref, 0, attribute);
|
|
||||||
}
|
|
||||||
|
|
||||||
let metadata = if let Some(debug) = debug {
|
let metadata = if let Some(debug) = debug {
|
||||||
if let Some(value) = &self.data.debug {
|
if let Some(value) = &self.data.debug {
|
||||||
let subprogram = debug.debug.get_subprogram_data_unchecked(&value);
|
let subprogram = debug.debug.get_subprogram_data_unchecked(&value);
|
||||||
@ -1224,7 +1215,3 @@ impl Type {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum LLVMEnumAttribute {
|
|
||||||
AlwaysInline = 3,
|
|
||||||
}
|
|
||||||
|
@ -148,7 +148,6 @@ pub struct FunctionFlags {
|
|||||||
pub is_main: bool,
|
pub is_main: bool,
|
||||||
pub is_pub: bool,
|
pub is_pub: bool,
|
||||||
pub is_imported: bool,
|
pub is_imported: bool,
|
||||||
pub inline: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for FunctionFlags {
|
impl Default for FunctionFlags {
|
||||||
@ -158,7 +157,6 @@ impl Default for FunctionFlags {
|
|||||||
is_main: false,
|
is_main: false,
|
||||||
is_pub: false,
|
is_pub: false,
|
||||||
is_imported: false,
|
is_imported: false,
|
||||||
inline: false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,8 +6,8 @@ use reid_lib::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use crate::mir::{
|
use crate::mir::{
|
||||||
self, CustomTypeKey, FunctionCall, FunctionDefinition, FunctionDefinitionKind, IfExpression,
|
self, CustomTypeKey, FunctionCall, FunctionDefinition, IfExpression, SourceModuleId,
|
||||||
SourceModuleId, TypeDefinition, TypeKind, WhileStatement,
|
TypeDefinition, TypeKind, WhileStatement,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -28,12 +28,8 @@ impl Allocator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from(
|
pub fn from(func: &FunctionDefinition, scope: &mut AllocatorScope) -> Allocator {
|
||||||
func: &FunctionDefinitionKind,
|
func.allocate(scope)
|
||||||
params: &Vec<(String, TypeKind)>,
|
|
||||||
scope: &mut AllocatorScope,
|
|
||||||
) -> Allocator {
|
|
||||||
func.allocate(scope, params)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn allocate(&mut self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
|
pub fn allocate(&mut self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
|
||||||
@ -49,16 +45,12 @@ impl Allocator {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Allocation(String, TypeKind, InstructionValue);
|
pub struct Allocation(String, TypeKind, InstructionValue);
|
||||||
|
|
||||||
impl mir::FunctionDefinitionKind {
|
impl mir::FunctionDefinition {
|
||||||
fn allocate<'ctx, 'a>(
|
fn allocate<'ctx, 'a>(&self, scope: &mut AllocatorScope<'ctx, 'a>) -> Allocator {
|
||||||
&self,
|
|
||||||
scope: &mut AllocatorScope<'ctx, 'a>,
|
|
||||||
parameters: &Vec<(String, TypeKind)>,
|
|
||||||
) -> Allocator {
|
|
||||||
let mut allocated = Vec::new();
|
let mut allocated = Vec::new();
|
||||||
match &self {
|
match &self.kind {
|
||||||
mir::FunctionDefinitionKind::Local(block, _) => {
|
mir::FunctionDefinitionKind::Local(block, _) => {
|
||||||
for param in parameters {
|
for param in &self.parameters {
|
||||||
let allocation = scope
|
let allocation = scope
|
||||||
.block
|
.block
|
||||||
.build_named(
|
.build_named(
|
||||||
|
@ -207,17 +207,6 @@ pub enum TopLevelStatement {
|
|||||||
ExternFunction(FunctionSignature),
|
ExternFunction(FunctionSignature),
|
||||||
FunctionDefinition(FunctionDefinition),
|
FunctionDefinition(FunctionDefinition),
|
||||||
TypeDefinition(TypeDefinition),
|
TypeDefinition(TypeDefinition),
|
||||||
BinopDefinition(BinopDefinition),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct BinopDefinition {
|
|
||||||
pub lhs: (String, Type),
|
|
||||||
pub op: BinaryOperator,
|
|
||||||
pub rhs: (String, Type),
|
|
||||||
pub return_ty: Type,
|
|
||||||
pub block: Block,
|
|
||||||
pub signature_range: TokenRange,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
@ -314,7 +314,7 @@ fn parse_binop_rhs(
|
|||||||
|
|
||||||
lhs = Expression(
|
lhs = Expression(
|
||||||
ExpressionKind::Binop(op, Box::new(lhs), Box::new(rhs)),
|
ExpressionKind::Binop(op, Box::new(lhs), Box::new(rhs)),
|
||||||
stream.get_range_prev().unwrap(),
|
stream.get_range().unwrap(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -554,11 +554,7 @@ impl Parse for Block {
|
|||||||
statements.push(statement);
|
statements.push(statement);
|
||||||
}
|
}
|
||||||
stream.expect(Token::BraceClose)?;
|
stream.expect(Token::BraceClose)?;
|
||||||
Ok(Block(
|
Ok(Block(statements, return_stmt, stream.get_range().unwrap()))
|
||||||
statements,
|
|
||||||
return_stmt,
|
|
||||||
stream.get_range_prev().unwrap(),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -789,46 +785,7 @@ impl Parse for TopLevelStatement {
|
|||||||
range,
|
range,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Some(Token::Impl) => Stmt::BinopDefinition(stream.parse()?),
|
|
||||||
_ => Err(stream.expecting_err("import or fn")?)?,
|
_ => Err(stream.expecting_err("import or fn")?)?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Parse for BinopDefinition {
|
|
||||||
fn parse(mut stream: TokenStream) -> Result<Self, Error> {
|
|
||||||
stream.expect(Token::Impl)?;
|
|
||||||
stream.expect(Token::Binop)?;
|
|
||||||
|
|
||||||
stream.expect(Token::ParenOpen)?;
|
|
||||||
let Some(Token::Identifier(lhs_name)) = stream.next() else {
|
|
||||||
return Err(stream.expected_err("lhs name")?);
|
|
||||||
};
|
|
||||||
stream.expect(Token::Colon)?;
|
|
||||||
let lhs_type = stream.parse()?;
|
|
||||||
stream.expect(Token::ParenClose)?;
|
|
||||||
|
|
||||||
let operator = stream.parse()?;
|
|
||||||
|
|
||||||
stream.expect(Token::ParenOpen)?;
|
|
||||||
let Some(Token::Identifier(rhs_name)) = stream.next() else {
|
|
||||||
return Err(stream.expected_err("rhs name")?);
|
|
||||||
};
|
|
||||||
stream.expect(Token::Colon)?;
|
|
||||||
let rhs_type = stream.parse()?;
|
|
||||||
stream.expect(Token::ParenClose)?;
|
|
||||||
|
|
||||||
let signature_range = stream.get_range().unwrap();
|
|
||||||
|
|
||||||
stream.expect(Token::Arrow)?;
|
|
||||||
|
|
||||||
Ok(BinopDefinition {
|
|
||||||
lhs: (lhs_name, lhs_type),
|
|
||||||
op: operator,
|
|
||||||
rhs: (rhs_name, rhs_type),
|
|
||||||
return_ty: stream.parse()?,
|
|
||||||
block: stream.parse()?,
|
|
||||||
signature_range,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -23,7 +23,6 @@ impl ast::Module {
|
|||||||
let mut imports = Vec::new();
|
let mut imports = Vec::new();
|
||||||
let mut functions = Vec::new();
|
let mut functions = Vec::new();
|
||||||
let mut typedefs = Vec::new();
|
let mut typedefs = Vec::new();
|
||||||
let mut binops = Vec::new();
|
|
||||||
|
|
||||||
use ast::TopLevelStatement::*;
|
use ast::TopLevelStatement::*;
|
||||||
for stmt in &self.top_level_statements {
|
for stmt in &self.top_level_statements {
|
||||||
@ -98,33 +97,12 @@ impl ast::Module {
|
|||||||
};
|
};
|
||||||
typedefs.push(def);
|
typedefs.push(def);
|
||||||
}
|
}
|
||||||
BinopDefinition(ast::BinopDefinition {
|
|
||||||
lhs,
|
|
||||||
op,
|
|
||||||
rhs,
|
|
||||||
return_ty,
|
|
||||||
block,
|
|
||||||
signature_range,
|
|
||||||
}) => {
|
|
||||||
binops.push(mir::BinopDefinition {
|
|
||||||
lhs: (lhs.0.clone(), lhs.1 .0.into_mir(module_id)),
|
|
||||||
op: op.mir(),
|
|
||||||
rhs: (rhs.0.clone(), rhs.1 .0.into_mir(module_id)),
|
|
||||||
return_type: return_ty.0.into_mir(module_id),
|
|
||||||
fn_kind: mir::FunctionDefinitionKind::Local(
|
|
||||||
block.into_mir(module_id),
|
|
||||||
block.2.as_meta(module_id),
|
|
||||||
),
|
|
||||||
meta: signature_range.as_meta(module_id),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mir::Module {
|
mir::Module {
|
||||||
name: self.name.clone(),
|
name: self.name.clone(),
|
||||||
module_id: module_id,
|
module_id: module_id,
|
||||||
binop_defs: binops,
|
|
||||||
imports,
|
imports,
|
||||||
functions,
|
functions,
|
||||||
path: self.path.clone(),
|
path: self.path.clone(),
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use std::{cell::RefCell, collections::HashMap, hash::Hash, mem, rc::Rc};
|
use std::{cell::RefCell, collections::HashMap, mem, rc::Rc};
|
||||||
|
|
||||||
use reid_lib::{
|
use reid_lib::{
|
||||||
builder::{InstructionValue, TypeValue},
|
builder::{InstructionValue, TypeValue},
|
||||||
@ -16,13 +16,9 @@ use reid_lib::{
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
allocator::{Allocator, AllocatorScope},
|
allocator::{Allocator, AllocatorScope},
|
||||||
intrinsics::IntrinsicFunction,
|
|
||||||
lexer::{FullToken, Position},
|
lexer::{FullToken, Position},
|
||||||
mir::{
|
mir::{
|
||||||
self,
|
self, implement::TypeCategory, CustomTypeKey, Metadata, NamedVariableRef, SourceModuleId,
|
||||||
implement::TypeCategory,
|
|
||||||
pass::{ScopeBinopDef, ScopeBinopKey},
|
|
||||||
CustomTypeKey, FunctionDefinitionKind, Metadata, NamedVariableRef, SourceModuleId,
|
|
||||||
StructField, StructType, TypeDefinition, TypeDefinitionKind, TypeKind, VagueLiteral,
|
StructField, StructType, TypeDefinition, TypeDefinitionKind, TypeKind, VagueLiteral,
|
||||||
WhileStatement,
|
WhileStatement,
|
||||||
},
|
},
|
||||||
@ -81,55 +77,17 @@ pub struct Scope<'ctx, 'scope> {
|
|||||||
modules: &'scope HashMap<SourceModuleId, ModuleCodegen<'ctx>>,
|
modules: &'scope HashMap<SourceModuleId, ModuleCodegen<'ctx>>,
|
||||||
tokens: &'ctx Vec<FullToken>,
|
tokens: &'ctx Vec<FullToken>,
|
||||||
module: &'ctx Module<'ctx>,
|
module: &'ctx Module<'ctx>,
|
||||||
module_id: SourceModuleId,
|
pub(super) module_id: SourceModuleId,
|
||||||
function: &'ctx Function<'ctx>,
|
function: &'ctx StackFunction<'ctx>,
|
||||||
pub(super) block: Block<'ctx>,
|
pub(super) block: Block<'ctx>,
|
||||||
types: &'scope HashMap<TypeValue, TypeDefinition>,
|
pub(super) types: &'scope HashMap<TypeValue, TypeDefinition>,
|
||||||
type_values: &'scope HashMap<CustomTypeKey, TypeValue>,
|
pub(super) type_values: &'scope HashMap<CustomTypeKey, TypeValue>,
|
||||||
functions: &'scope HashMap<String, Function<'ctx>>,
|
functions: &'scope HashMap<String, StackFunction<'ctx>>,
|
||||||
binops: &'scope HashMap<ScopeBinopKey, StackBinopDefinition<'ctx>>,
|
|
||||||
stack_values: HashMap<String, StackValue>,
|
stack_values: HashMap<String, StackValue>,
|
||||||
debug: Option<Debug<'ctx>>,
|
debug: Option<Debug<'ctx>>,
|
||||||
allocator: Rc<RefCell<Allocator>>,
|
allocator: Rc<RefCell<Allocator>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx, 'a> Scope<'ctx, 'a> {
|
|
||||||
fn with_block(&self, block: Block<'ctx>) -> Scope<'ctx, 'a> {
|
|
||||||
Scope {
|
|
||||||
block,
|
|
||||||
modules: self.modules,
|
|
||||||
tokens: self.tokens,
|
|
||||||
function: self.function,
|
|
||||||
context: self.context,
|
|
||||||
module: self.module,
|
|
||||||
module_id: self.module_id,
|
|
||||||
functions: self.functions,
|
|
||||||
types: self.types,
|
|
||||||
type_values: self.type_values,
|
|
||||||
stack_values: self.stack_values.clone(),
|
|
||||||
debug: self.debug.clone(),
|
|
||||||
allocator: self.allocator.clone(),
|
|
||||||
binops: self.binops,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Takes the block out from this scope, swaps the given block in it's place
|
|
||||||
/// and returns the old block.
|
|
||||||
fn swap_block(&mut self, block: Block<'ctx>) -> Block<'ctx> {
|
|
||||||
let mut old_block = block;
|
|
||||||
mem::swap(&mut self.block, &mut old_block);
|
|
||||||
old_block
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_typedef(&self, key: &CustomTypeKey) -> Option<&TypeDefinition> {
|
|
||||||
self.type_values.get(key).and_then(|v| self.types.get(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn allocate(&self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
|
|
||||||
self.allocator.borrow_mut().allocate(name, ty)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Debug<'ctx> {
|
pub struct Debug<'ctx> {
|
||||||
info: &'ctx DebugInformation,
|
info: &'ctx DebugInformation,
|
||||||
@ -137,8 +95,12 @@ pub struct Debug<'ctx> {
|
|||||||
types: &'ctx HashMap<TypeKind, DebugTypeValue>,
|
types: &'ctx HashMap<TypeKind, DebugTypeValue>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct StackFunction<'ctx> {
|
||||||
|
ir: Function<'ctx>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct StackValue(pub(super) StackValueKind, pub(super) TypeKind);
|
pub struct StackValue(StackValueKind, TypeKind);
|
||||||
|
|
||||||
impl StackValue {
|
impl StackValue {
|
||||||
fn instr(&self) -> InstructionValue {
|
fn instr(&self) -> InstructionValue {
|
||||||
@ -186,47 +148,39 @@ impl StackValueKind {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct StackBinopDefinition<'ctx> {
|
impl<'ctx, 'a> Scope<'ctx, 'a> {
|
||||||
parameters: ((String, TypeKind), (String, TypeKind)),
|
fn with_block(&self, block: Block<'ctx>) -> Scope<'ctx, 'a> {
|
||||||
return_ty: TypeKind,
|
Scope {
|
||||||
kind: StackBinopFunctionKind<'ctx>,
|
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 enum StackBinopFunctionKind<'ctx> {
|
/// Takes the block out from this scope, swaps the given block in it's place
|
||||||
UserGenerated(Function<'ctx>),
|
/// and returns the old block.
|
||||||
Intrinsic(&'ctx Box<dyn IntrinsicFunction>),
|
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
|
||||||
|
}
|
||||||
|
|
||||||
impl<'ctx> StackBinopDefinition<'ctx> {
|
fn get_typedef(&self, key: &CustomTypeKey) -> Option<&TypeDefinition> {
|
||||||
fn codegen<'a>(
|
self.type_values.get(key).and_then(|v| self.types.get(v))
|
||||||
&self,
|
|
||||||
lhs: &StackValue,
|
|
||||||
rhs: &StackValue,
|
|
||||||
scope: &mut Scope<'ctx, 'a>,
|
|
||||||
) -> Result<StackValue, ErrorKind> {
|
|
||||||
let (lhs, rhs) = if lhs.1 == self.parameters.0 .1 && rhs.1 == self.parameters.1 .1 {
|
|
||||||
(lhs, rhs)
|
|
||||||
} else {
|
|
||||||
(rhs, lhs)
|
|
||||||
};
|
|
||||||
match &self.kind {
|
|
||||||
StackBinopFunctionKind::UserGenerated(ir) => {
|
|
||||||
let instr = scope
|
|
||||||
.block
|
|
||||||
.build(Instr::FunctionCall(
|
|
||||||
ir.value(),
|
|
||||||
vec![lhs.instr(), rhs.instr()],
|
|
||||||
))
|
|
||||||
.unwrap();
|
|
||||||
Ok(StackValue(
|
|
||||||
StackValueKind::Immutable(instr),
|
|
||||||
self.return_ty.clone(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
StackBinopFunctionKind::Intrinsic(fun) => {
|
|
||||||
fun.codegen(scope, &[lhs.instr(), rhs.instr()])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn allocate(&self, name: &String, ty: &TypeKind) -> Option<InstructionValue> {
|
||||||
|
self.allocator.borrow_mut().allocate(name, ty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -342,7 +296,7 @@ impl mir::Module {
|
|||||||
|
|
||||||
let is_main = self.is_main && function.name == "main";
|
let is_main = self.is_main && function.name == "main";
|
||||||
let func = match &function.kind {
|
let func = match &function.kind {
|
||||||
mir::FunctionDefinitionKind::Local(_, _) => Some(module.function(
|
mir::FunctionDefinitionKind::Local(_, _) => module.function(
|
||||||
&function.name,
|
&function.name,
|
||||||
function.return_type.get_type(&type_values),
|
function.return_type.get_type(&type_values),
|
||||||
param_types,
|
param_types,
|
||||||
@ -352,8 +306,8 @@ impl mir::Module {
|
|||||||
is_imported: function.is_imported,
|
is_imported: function.is_imported,
|
||||||
..FunctionFlags::default()
|
..FunctionFlags::default()
|
||||||
},
|
},
|
||||||
)),
|
),
|
||||||
mir::FunctionDefinitionKind::Extern(imported) => Some(module.function(
|
mir::FunctionDefinitionKind::Extern(imported) => module.function(
|
||||||
&function.name,
|
&function.name,
|
||||||
function.return_type.get_type(&type_values),
|
function.return_type.get_type(&type_values),
|
||||||
param_types,
|
param_types,
|
||||||
@ -362,113 +316,28 @@ impl mir::Module {
|
|||||||
is_imported: *imported,
|
is_imported: *imported,
|
||||||
..FunctionFlags::default()
|
..FunctionFlags::default()
|
||||||
},
|
},
|
||||||
)),
|
),
|
||||||
mir::FunctionDefinitionKind::Intrinsic(_) => None,
|
mir::FunctionDefinitionKind::Intrinsic(_) => module.function(
|
||||||
};
|
&function.name,
|
||||||
|
function.return_type.get_type(&type_values),
|
||||||
if let Some(func) = func {
|
param_types,
|
||||||
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 {
|
FunctionFlags {
|
||||||
inline: true,
|
..FunctionFlags::default()
|
||||||
..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
|
functions.insert(function.name.clone(), StackFunction { ir: func });
|
||||||
.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 {
|
for mir_function in &self.functions {
|
||||||
let function = functions.get(&mir_function.name).unwrap();
|
let function = functions.get(&mir_function.name).unwrap();
|
||||||
let mut entry = function.block("entry");
|
|
||||||
|
|
||||||
let allocator = Allocator::from(
|
match &mir_function.kind {
|
||||||
&mir_function.kind,
|
mir::FunctionDefinitionKind::Local(block, _) => {
|
||||||
&mir_function.parameters,
|
let mut entry = function.ir.block("entry");
|
||||||
|
let mut allocator = Allocator::from(
|
||||||
|
mir_function,
|
||||||
&mut AllocatorScope {
|
&mut AllocatorScope {
|
||||||
block: &mut entry,
|
block: &mut entry,
|
||||||
module_id: self.module_id,
|
module_id: self.module_id,
|
||||||
@ -476,116 +345,63 @@ impl mir::Module {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
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
|
// Insert debug information
|
||||||
if let Some(debug) = &scope.debug {
|
let debug_scope = if let Some(location) =
|
||||||
if let Some(location) = debug_location {
|
mir_function.signature().into_debug(tokens, compile_unit)
|
||||||
|
{
|
||||||
// let debug_scope = debug.inner_scope(&outer_scope, location);
|
// let debug_scope = debug.inner_scope(&outer_scope, location);
|
||||||
|
|
||||||
let fn_param_ty = &return_type.get_debug_type(&debug, scope);
|
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 debug_ty =
|
let debug_ty =
|
||||||
debug
|
debug.debug_type(DebugTypeData::Subprogram(DebugSubprogramType {
|
||||||
.info
|
|
||||||
.debug_type(DebugTypeData::Subprogram(DebugSubprogramType {
|
|
||||||
parameters: vec![*fn_param_ty],
|
parameters: vec![*fn_param_ty],
|
||||||
flags: DwarfFlags,
|
flags: DwarfFlags,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let subprogram = debug.info.subprogram(DebugSubprogramData {
|
let subprogram = debug.subprogram(DebugSubprogramData {
|
||||||
name: name.clone(),
|
name: mir_function.name.clone(),
|
||||||
outer_scope: debug.scope.clone(),
|
outer_scope: compile_unit.clone(),
|
||||||
location,
|
location,
|
||||||
ty: debug_ty,
|
ty: debug_ty,
|
||||||
opts: DebugSubprogramOptionals {
|
opts: DebugSubprogramOptionals {
|
||||||
is_local: !is_pub,
|
is_local: !mir_function.is_pub,
|
||||||
is_definition: true,
|
is_definition: true,
|
||||||
..DebugSubprogramOptionals::default()
|
..DebugSubprogramOptionals::default()
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
ir_function.set_debug(subprogram);
|
function.ir.set_debug(subprogram);
|
||||||
scope.debug = Some(Debug {
|
|
||||||
info: debug.info,
|
Some(subprogram)
|
||||||
scope: subprogram,
|
} else {
|
||||||
types: debug.types,
|
None
|
||||||
});
|
};
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Compile actual IR part
|
// Compile actual IR part
|
||||||
for (i, (p_name, p_ty)) in parameters.iter().enumerate() {
|
let mut stack_values = HashMap::new();
|
||||||
|
for (i, (p_name, p_ty)) in mir_function.parameters.iter().enumerate() {
|
||||||
// Codegen actual parameters
|
// Codegen actual parameters
|
||||||
let arg_name = format!("arg.{}", p_name);
|
let arg_name = format!("arg.{}", p_name);
|
||||||
let param = scope
|
let param = entry
|
||||||
.block
|
|
||||||
.build_named(format!("{}.get", arg_name), Instr::Param(i))
|
.build_named(format!("{}.get", arg_name), Instr::Param(i))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let alloca = scope.allocate(&p_name, &p_ty).unwrap();
|
let alloca = allocator.allocate(&p_name, &p_ty).unwrap();
|
||||||
|
|
||||||
scope
|
entry
|
||||||
.block
|
|
||||||
.build_named(format!("{}.store", arg_name), Instr::Store(alloca, param))
|
.build_named(format!("{}.store", arg_name), Instr::Store(alloca, param))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
scope.stack_values.insert(
|
stack_values.insert(
|
||||||
p_name.clone(),
|
p_name.clone(),
|
||||||
StackValue(
|
StackValue(
|
||||||
StackValueKind::mutable(p_ty.is_mutable(), alloca),
|
StackValueKind::mutable(p_ty.is_mutable(), alloca),
|
||||||
@ -594,10 +410,10 @@ impl FunctionDefinitionKind {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Generate debug info
|
// Generate debug info
|
||||||
// if let (Some(debug_scope), Some(location)) = (
|
if let (Some(debug_scope), Some(location)) = (
|
||||||
// &debug_scope,
|
&debug_scope,
|
||||||
// mir_function.signature().into_debug(tokens, compile_unit),
|
mir_function.signature().into_debug(tokens, compile_unit),
|
||||||
// ) {
|
) {
|
||||||
// debug.metadata(
|
// debug.metadata(
|
||||||
// &location,
|
// &location,
|
||||||
// DebugMetadata::ParamVar(DebugParamVariable {
|
// DebugMetadata::ParamVar(DebugParamVariable {
|
||||||
@ -617,11 +433,33 @@ impl FunctionDefinitionKind {
|
|||||||
// flags: DwarfFlags,
|
// flags: DwarfFlags,
|
||||||
// }),
|
// }),
|
||||||
// );
|
// );
|
||||||
// }
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut scope = Scope {
|
||||||
|
context,
|
||||||
|
modules: &modules,
|
||||||
|
tokens,
|
||||||
|
module: &module,
|
||||||
|
module_id: self.module_id,
|
||||||
|
function,
|
||||||
|
block: entry,
|
||||||
|
functions: &functions,
|
||||||
|
types: &types,
|
||||||
|
type_values: &type_values,
|
||||||
|
stack_values,
|
||||||
|
debug: debug_scope.and_then(|scope| {
|
||||||
|
Some(Debug {
|
||||||
|
info: &debug,
|
||||||
|
scope,
|
||||||
|
types: &debug_types,
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
allocator: Rc::new(RefCell::new(allocator)),
|
||||||
|
};
|
||||||
|
|
||||||
let state = State::default();
|
let state = State::default();
|
||||||
if let Some(ret) = block.codegen(scope, &state)? {
|
if let Some(ret) = block.codegen(&mut scope, &state)? {
|
||||||
scope.block.terminate(Term::Ret(ret.instr())).unwrap();
|
scope.block.terminate(Term::Ret(ret.instr())).unwrap();
|
||||||
} else {
|
} else {
|
||||||
if !scope.block.delete_if_unused().unwrap() {
|
if !scope.block.delete_if_unused().unwrap() {
|
||||||
@ -631,19 +469,38 @@ impl FunctionDefinitionKind {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(debug) = &scope.debug {
|
if let Some(debug) = scope.debug {
|
||||||
let location = &block
|
let location =
|
||||||
.return_meta()
|
&block.return_meta().into_debug(tokens, debug.scope).unwrap();
|
||||||
.into_debug(scope.tokens, debug.scope)
|
|
||||||
.unwrap();
|
|
||||||
let location = debug.info.location(&debug.scope, *location);
|
let location = debug.info.location(&debug.scope, *location);
|
||||||
scope.block.set_terminator_location(location).unwrap();
|
scope.block.set_terminator_location(location).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mir::FunctionDefinitionKind::Extern(_) => {}
|
mir::FunctionDefinitionKind::Extern(_) => {}
|
||||||
mir::FunctionDefinitionKind::Intrinsic(_) => {}
|
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())),
|
||||||
};
|
};
|
||||||
Ok(())
|
|
||||||
|
kind.codegen(&mut scope)?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ModuleCodegen { module })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -782,9 +639,9 @@ impl mir::Statement {
|
|||||||
mir::StmtKind::While(WhileStatement {
|
mir::StmtKind::While(WhileStatement {
|
||||||
condition, block, ..
|
condition, block, ..
|
||||||
}) => {
|
}) => {
|
||||||
let condition_block = scope.function.block("while.cond");
|
let condition_block = scope.function.ir.block("while.cond");
|
||||||
let condition_true_block = scope.function.block("while.body");
|
let condition_true_block = scope.function.ir.block("while.body");
|
||||||
let condition_failed_block = scope.function.block("while.end");
|
let condition_failed_block = scope.function.ir.block("while.end");
|
||||||
|
|
||||||
scope
|
scope
|
||||||
.block
|
.block
|
||||||
@ -884,24 +741,14 @@ impl mir::Expression {
|
|||||||
lit.as_type(),
|
lit.as_type(),
|
||||||
)),
|
)),
|
||||||
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
|
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
|
||||||
let lhs_val = lhs_exp
|
let lhs = lhs_exp
|
||||||
.codegen(scope, state)?
|
.codegen(scope, state)?
|
||||||
.expect("lhs has no return value");
|
.expect("lhs has no return value")
|
||||||
let rhs_val = rhs_exp
|
.instr();
|
||||||
|
let rhs = rhs_exp
|
||||||
.codegen(scope, state)?
|
.codegen(scope, state)?
|
||||||
.expect("rhs has no return value");
|
.expect("rhs has no return value")
|
||||||
let lhs = lhs_val.instr();
|
.instr();
|
||||||
let rhs = rhs_val.instr();
|
|
||||||
|
|
||||||
let operation = scope.binops.get(&ScopeBinopKey {
|
|
||||||
params: (lhs_val.1.clone(), rhs_val.1.clone()),
|
|
||||||
operator: *binop,
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Some(operation) = operation {
|
|
||||||
let a = operation.codegen(&lhs_val, &rhs_val, scope)?;
|
|
||||||
Some(a)
|
|
||||||
} else {
|
|
||||||
let lhs_type = lhs_exp
|
let lhs_type = lhs_exp
|
||||||
.return_type(&Default::default(), scope.module_id)
|
.return_type(&Default::default(), scope.module_id)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@ -918,12 +765,8 @@ impl mir::Expression {
|
|||||||
(mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs),
|
(mir::BinaryOperator::Mult, _, false) => Instr::Mul(lhs, rhs),
|
||||||
(mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs),
|
(mir::BinaryOperator::Mult, _, true) => Instr::FMul(lhs, rhs),
|
||||||
(mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs),
|
(mir::BinaryOperator::And, _, _) => Instr::And(lhs, rhs),
|
||||||
(mir::BinaryOperator::Cmp(i), _, false) => {
|
(mir::BinaryOperator::Cmp(i), _, false) => Instr::ICmp(i.predicate(), lhs, rhs),
|
||||||
Instr::ICmp(i.predicate(), lhs, rhs)
|
(mir::BinaryOperator::Cmp(i), _, true) => Instr::FCmp(i.predicate(), lhs, rhs),
|
||||||
}
|
|
||||||
(mir::BinaryOperator::Cmp(i), _, true) => {
|
|
||||||
Instr::FCmp(i.predicate(), lhs, rhs)
|
|
||||||
}
|
|
||||||
(mir::BinaryOperator::Div, false, false) => Instr::UDiv(lhs, rhs),
|
(mir::BinaryOperator::Div, false, false) => Instr::UDiv(lhs, rhs),
|
||||||
(mir::BinaryOperator::Div, true, false) => Instr::SDiv(lhs, rhs),
|
(mir::BinaryOperator::Div, true, false) => Instr::SDiv(lhs, rhs),
|
||||||
(mir::BinaryOperator::Div, _, true) => Instr::FDiv(lhs, rhs),
|
(mir::BinaryOperator::Div, _, true) => Instr::FDiv(lhs, rhs),
|
||||||
@ -967,7 +810,6 @@ impl mir::Expression {
|
|||||||
Instr::Sub(lhs, mul)
|
Instr::Sub(lhs, mul)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
dbg!(&instr);
|
|
||||||
Some(StackValue(
|
Some(StackValue(
|
||||||
StackValueKind::Immutable(
|
StackValueKind::Immutable(
|
||||||
scope
|
scope
|
||||||
@ -979,7 +821,6 @@ impl mir::Expression {
|
|||||||
lhs_type,
|
lhs_type,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
|
||||||
mir::ExprKind::FunctionCall(call) => {
|
mir::ExprKind::FunctionCall(call) => {
|
||||||
let ret_type_kind = call
|
let ret_type_kind = call
|
||||||
.return_type
|
.return_type
|
||||||
@ -1009,7 +850,7 @@ impl mir::Expression {
|
|||||||
.block
|
.block
|
||||||
.build_named(
|
.build_named(
|
||||||
call.name.clone(),
|
call.name.clone(),
|
||||||
Instr::FunctionCall(callee.value(), param_instrs),
|
Instr::FunctionCall(callee.ir.value(), param_instrs),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@ -1057,7 +898,7 @@ impl mir::Expression {
|
|||||||
}
|
}
|
||||||
mir::ExprKind::If(if_expression) => if_expression.codegen(scope, state)?,
|
mir::ExprKind::If(if_expression) => if_expression.codegen(scope, state)?,
|
||||||
mir::ExprKind::Block(block) => {
|
mir::ExprKind::Block(block) => {
|
||||||
let inner = scope.function.block("inner");
|
let inner = scope.function.ir.block("inner");
|
||||||
scope.block.terminate(Term::Br(inner.value())).unwrap();
|
scope.block.terminate(Term::Br(inner.value())).unwrap();
|
||||||
|
|
||||||
let mut inner_scope = scope.with_block(inner);
|
let mut inner_scope = scope.with_block(inner);
|
||||||
@ -1066,7 +907,7 @@ impl mir::Expression {
|
|||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let outer = scope.function.block("outer");
|
let outer = scope.function.ir.block("outer");
|
||||||
inner_scope.block.terminate(Term::Br(outer.value())).ok();
|
inner_scope.block.terminate(Term::Br(outer.value())).ok();
|
||||||
scope.swap_block(outer);
|
scope.swap_block(outer);
|
||||||
ret
|
ret
|
||||||
@ -1469,9 +1310,9 @@ impl mir::IfExpression {
|
|||||||
let condition = self.0.codegen(scope, state)?.unwrap();
|
let condition = self.0.codegen(scope, state)?.unwrap();
|
||||||
|
|
||||||
// Create blocks
|
// Create blocks
|
||||||
let mut then_b = scope.function.block("then");
|
let mut then_b = scope.function.ir.block("then");
|
||||||
let mut else_b = scope.function.block("else");
|
let mut else_b = scope.function.ir.block("else");
|
||||||
let after_b = scope.function.block("after");
|
let after_b = scope.function.ir.block("after");
|
||||||
|
|
||||||
if let Some(debug) = &scope.debug {
|
if let Some(debug) = &scope.debug {
|
||||||
let before_location = self.0 .1.into_debug(scope.tokens, debug.scope).unwrap();
|
let before_location = self.0 .1.into_debug(scope.tokens, debug.scope).unwrap();
|
||||||
|
@ -1,15 +1,20 @@
|
|||||||
use reid_lib::{builder::InstructionValue, Instr};
|
use reid_lib::Instr;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
codegen::{ErrorKind, Scope, StackValue, StackValueKind},
|
codegen::{ErrorKind, Scope},
|
||||||
mir::{BinaryOperator, BinopDefinition, FunctionDefinition, FunctionDefinitionKind, TypeKind},
|
mir::{FunctionDefinition, FunctionDefinitionKind, TypeKind},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum InstrinsicKind {
|
||||||
|
IAdd,
|
||||||
|
}
|
||||||
|
|
||||||
fn intrinsic(
|
fn intrinsic(
|
||||||
name: &str,
|
name: &str,
|
||||||
ret_ty: TypeKind,
|
ret_ty: TypeKind,
|
||||||
params: Vec<(&str, TypeKind)>,
|
params: Vec<(&str, TypeKind)>,
|
||||||
fun: impl IntrinsicFunction + 'static,
|
kind: InstrinsicKind,
|
||||||
) -> FunctionDefinition {
|
) -> FunctionDefinition {
|
||||||
FunctionDefinition {
|
FunctionDefinition {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
@ -17,93 +22,36 @@ fn intrinsic(
|
|||||||
is_imported: false,
|
is_imported: false,
|
||||||
return_type: ret_ty,
|
return_type: ret_ty,
|
||||||
parameters: params.into_iter().map(|(n, ty)| (n.into(), ty)).collect(),
|
parameters: params.into_iter().map(|(n, ty)| (n.into(), ty)).collect(),
|
||||||
kind: FunctionDefinitionKind::Intrinsic(Box::new(fun)),
|
kind: FunctionDefinitionKind::Intrinsic(kind),
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn intrinsic_binop(
|
|
||||||
op: BinaryOperator,
|
|
||||||
lhs: TypeKind,
|
|
||||||
rhs: TypeKind,
|
|
||||||
ret_ty: TypeKind,
|
|
||||||
fun: impl IntrinsicFunction + 'static,
|
|
||||||
) -> BinopDefinition {
|
|
||||||
BinopDefinition {
|
|
||||||
lhs: ("lhs".to_string(), lhs),
|
|
||||||
op,
|
|
||||||
rhs: ("rhs".to_owned(), rhs),
|
|
||||||
return_type: ret_ty,
|
|
||||||
fn_kind: FunctionDefinitionKind::Intrinsic(Box::new(fun)),
|
|
||||||
meta: Default::default(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn form_intrinsics() -> Vec<FunctionDefinition> {
|
pub fn form_intrinsics() -> Vec<FunctionDefinition> {
|
||||||
let intrinsics = Vec::new();
|
|
||||||
|
|
||||||
intrinsics
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn form_intrinsic_binops() -> Vec<BinopDefinition> {
|
|
||||||
let mut intrinsics = Vec::new();
|
let mut intrinsics = Vec::new();
|
||||||
|
|
||||||
|
intrinsics.push(intrinsic(
|
||||||
|
"addition",
|
||||||
|
TypeKind::U8,
|
||||||
|
vec![("lhs".into(), TypeKind::U8), ("rhs".into(), TypeKind::U8)],
|
||||||
|
InstrinsicKind::IAdd,
|
||||||
|
));
|
||||||
|
|
||||||
intrinsics
|
intrinsics
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait IntrinsicFunction: std::fmt::Debug {
|
impl InstrinsicKind {
|
||||||
fn codegen<'ctx, 'a>(
|
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Result<(), ErrorKind> {
|
||||||
&self,
|
match self {
|
||||||
scope: &mut Scope<'ctx, 'a>,
|
InstrinsicKind::IAdd => {
|
||||||
params: &[InstructionValue],
|
let lhs = scope.block.build(Instr::Param(0)).unwrap();
|
||||||
) -> Result<StackValue, ErrorKind>;
|
let rhs = scope.block.build(Instr::Param(1)).unwrap();
|
||||||
}
|
let add = scope.block.build(Instr::Add(lhs, rhs)).unwrap();
|
||||||
|
scope
|
||||||
#[derive(Debug, Clone)]
|
.block
|
||||||
pub struct IntrinsicIAdd(TypeKind);
|
.terminate(reid_lib::TerminatorKind::Ret(add))
|
||||||
|
.unwrap()
|
||||||
impl IntrinsicFunction for IntrinsicIAdd {
|
}
|
||||||
fn codegen<'ctx, 'a>(
|
}
|
||||||
&self,
|
Ok(())
|
||||||
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()))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -46,12 +46,8 @@ pub enum Token {
|
|||||||
While,
|
While,
|
||||||
/// `for`
|
/// `for`
|
||||||
For,
|
For,
|
||||||
/// `in`
|
/// `In`
|
||||||
In,
|
In,
|
||||||
/// `impl`
|
|
||||||
Impl,
|
|
||||||
/// `binop`
|
|
||||||
Binop,
|
|
||||||
|
|
||||||
// Symbols
|
// Symbols
|
||||||
/// `;`
|
/// `;`
|
||||||
@ -149,8 +145,6 @@ impl ToString for Token {
|
|||||||
Token::For => String::from("for"),
|
Token::For => String::from("for"),
|
||||||
Token::In => String::from("in"),
|
Token::In => String::from("in"),
|
||||||
Token::While => String::from("while"),
|
Token::While => String::from("while"),
|
||||||
Token::Impl => String::from("impl"),
|
|
||||||
Token::Binop => String::from("binop"),
|
|
||||||
Token::Semi => String::from(';'),
|
Token::Semi => String::from(';'),
|
||||||
Token::Equals => String::from('='),
|
Token::Equals => String::from('='),
|
||||||
Token::Colon => String::from(':'),
|
Token::Colon => String::from(':'),
|
||||||
@ -340,8 +334,6 @@ pub fn tokenize<T: Into<String>>(to_tokenize: T) -> Result<Vec<FullToken>, Error
|
|||||||
"for" => Token::For,
|
"for" => Token::For,
|
||||||
"while" => Token::While,
|
"while" => Token::While,
|
||||||
"in" => Token::In,
|
"in" => Token::In,
|
||||||
"impl" => Token::Impl,
|
|
||||||
"binop" => Token::Binop,
|
|
||||||
_ => Token::Identifier(value),
|
_ => Token::Identifier(value),
|
||||||
};
|
};
|
||||||
variant
|
variant
|
||||||
|
@ -44,7 +44,7 @@
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use error_raporting::{ErrorKind as ErrorRapKind, ErrorModules, ReidError};
|
use error_raporting::{ErrorKind as ErrorRapKind, ErrorModules, ReidError};
|
||||||
use intrinsics::{form_intrinsic_binops, form_intrinsics};
|
use intrinsics::form_intrinsics;
|
||||||
use lexer::FullToken;
|
use lexer::FullToken;
|
||||||
use mir::{
|
use mir::{
|
||||||
linker::LinkerPass, typecheck::TypeCheck, typeinference::TypeInference, typerefs::TypeRefs,
|
linker::LinkerPass, typecheck::TypeCheck, typeinference::TypeInference, typerefs::TypeRefs,
|
||||||
@ -128,12 +128,6 @@ pub fn perform_all_passes<'map>(
|
|||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
dbg!(&context);
|
dbg!(&context);
|
||||||
|
|
||||||
for module in &mut context.modules {
|
|
||||||
for intrinsic in form_intrinsic_binops() {
|
|
||||||
module.1.binop_defs.insert(0, intrinsic);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for module in &mut context.modules {
|
for module in &mut context.modules {
|
||||||
for intrinsic in form_intrinsics() {
|
for intrinsic in form_intrinsics() {
|
||||||
module.1.functions.insert(0, intrinsic);
|
module.1.functions.insert(0, intrinsic);
|
||||||
|
@ -40,9 +40,6 @@ impl Display for Module {
|
|||||||
for import in &self.imports {
|
for import in &self.imports {
|
||||||
writeln!(inner_f, "{}", import)?;
|
writeln!(inner_f, "{}", import)?;
|
||||||
}
|
}
|
||||||
for binop in &self.binop_defs {
|
|
||||||
writeln!(inner_f, "{}", binop)?;
|
|
||||||
}
|
|
||||||
for typedef in &self.typedefs {
|
for typedef in &self.typedefs {
|
||||||
writeln!(inner_f, "{}", typedef)?;
|
writeln!(inner_f, "{}", typedef)?;
|
||||||
}
|
}
|
||||||
@ -59,17 +56,6 @@ impl Display for Import {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for BinopDefinition {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(
|
|
||||||
f,
|
|
||||||
"impl binop ({}: {:#}) {} ({}: {:#}) -> {:#} ",
|
|
||||||
self.lhs.0, self.lhs.1, self.op, self.rhs.0, self.rhs.1, self.return_type
|
|
||||||
)?;
|
|
||||||
Display::fmt(&self.fn_kind, f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for TypeDefinition {
|
impl Display for TypeDefinition {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(f, "type {} = ", self.name)?;
|
write!(f, "type {} = ", self.name)?;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use super::{pass::ScopeBinopDef, typecheck::ErrorKind, typerefs::TypeRefs, VagueType as Vague, *};
|
use super::{typecheck::ErrorKind, typerefs::TypeRefs, VagueType as Vague, *};
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum ReturnTypeOther {
|
pub enum ReturnTypeOther {
|
||||||
@ -95,11 +95,11 @@ impl TypeKind {
|
|||||||
|
|
||||||
/// Return the type that is the result of a binary operator between two
|
/// Return the type that is the result of a binary operator between two
|
||||||
/// values of this type
|
/// values of this type
|
||||||
pub fn simple_binop_type(&self, op: &BinaryOperator) -> Option<TypeKind> {
|
pub fn binop_type(&self, op: &BinaryOperator) -> TypeKind {
|
||||||
if !self.category().is_simple_maths() {
|
// TODO make some type of mechanism that allows to binop two values of
|
||||||
return None;
|
// differing types..
|
||||||
}
|
// TODO Return None for arrays later
|
||||||
Some(match op {
|
match op {
|
||||||
BinaryOperator::Add => self.clone(),
|
BinaryOperator::Add => self.clone(),
|
||||||
BinaryOperator::Minus => self.clone(),
|
BinaryOperator::Minus => self.clone(),
|
||||||
BinaryOperator::Mult => self.clone(),
|
BinaryOperator::Mult => self.clone(),
|
||||||
@ -107,29 +107,12 @@ impl TypeKind {
|
|||||||
BinaryOperator::Cmp(_) => TypeKind::Bool,
|
BinaryOperator::Cmp(_) => TypeKind::Bool,
|
||||||
BinaryOperator::Div => self.clone(),
|
BinaryOperator::Div => self.clone(),
|
||||||
BinaryOperator::Mod => self.clone(),
|
BinaryOperator::Mod => self.clone(),
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn binop_type(
|
|
||||||
lhs: &TypeKind,
|
|
||||||
rhs: &TypeKind,
|
|
||||||
binop: &ScopeBinopDef,
|
|
||||||
) -> Option<(TypeKind, TypeKind, TypeKind)> {
|
|
||||||
let lhs_ty = lhs.collapse_into(&binop.hands.0);
|
|
||||||
let rhs_ty = rhs.collapse_into(&binop.hands.1);
|
|
||||||
if let (Ok(lhs_ty), Ok(rhs_ty)) = (lhs_ty, rhs_ty) {
|
|
||||||
Some((lhs_ty, rhs_ty, binop.return_ty.clone()))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reverse of binop_type, where the given hint is the known required output
|
/// Reverse of binop_type, where the given hint is the known required output
|
||||||
/// type of the binop, and the output is the hint for the lhs/rhs type.
|
/// type of the binop, and the output is the hint for the lhs/rhs type.
|
||||||
pub fn simple_binop_hint(&self, op: &BinaryOperator) -> Option<TypeKind> {
|
pub fn binop_hint(&self, op: &BinaryOperator) -> Option<TypeKind> {
|
||||||
if !self.category().is_simple_maths() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
match op {
|
match op {
|
||||||
BinaryOperator::Add
|
BinaryOperator::Add
|
||||||
| BinaryOperator::Minus
|
| BinaryOperator::Minus
|
||||||
@ -141,22 +124,6 @@ impl TypeKind {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn binop_hint(
|
|
||||||
&self,
|
|
||||||
lhs: &TypeKind,
|
|
||||||
rhs: &TypeKind,
|
|
||||||
binop: &ScopeBinopDef,
|
|
||||||
) -> Option<(TypeKind, TypeKind)> {
|
|
||||||
self.collapse_into(&binop.return_ty).ok()?;
|
|
||||||
let lhs_ty = lhs.collapse_into(&binop.hands.0);
|
|
||||||
let rhs_ty = rhs.collapse_into(&binop.hands.1);
|
|
||||||
if let (Ok(lhs_ty), Ok(rhs_ty)) = (lhs_ty, rhs_ty) {
|
|
||||||
Some((lhs_ty, rhs_ty))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn signed(&self) -> bool {
|
pub fn signed(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
TypeKind::Bool => false,
|
TypeKind::Bool => false,
|
||||||
@ -278,7 +245,7 @@ impl TypeKind {
|
|||||||
| TypeKind::F80
|
| TypeKind::F80
|
||||||
| TypeKind::F128PPC => TypeCategory::Real,
|
| TypeKind::F128PPC => TypeCategory::Real,
|
||||||
TypeKind::Void => TypeCategory::Other,
|
TypeKind::Void => TypeCategory::Other,
|
||||||
TypeKind::Bool => TypeCategory::Bool,
|
TypeKind::Bool => TypeCategory::Other,
|
||||||
TypeKind::Array(_, _) => TypeCategory::Other,
|
TypeKind::Array(_, _) => TypeCategory::Other,
|
||||||
TypeKind::CustomType(..) => TypeCategory::Other,
|
TypeKind::CustomType(..) => TypeCategory::Other,
|
||||||
TypeKind::Borrow(_, _) => TypeCategory::Other,
|
TypeKind::Borrow(_, _) => TypeCategory::Other,
|
||||||
@ -292,63 +259,16 @@ impl TypeKind {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn try_collapse_two(
|
|
||||||
(lhs1, rhs1): (&TypeKind, &TypeKind),
|
|
||||||
(lhs2, rhs2): (&TypeKind, &TypeKind),
|
|
||||||
) -> Option<(TypeKind, TypeKind)> {
|
|
||||||
if let (Ok(lhs), Ok(rhs)) = (lhs1.collapse_into(&lhs2), rhs1.collapse_into(&rhs2)) {
|
|
||||||
Some((lhs, rhs))
|
|
||||||
} else if let (Ok(lhs), Ok(rhs)) = (lhs1.collapse_into(&rhs2), rhs1.collapse_into(&lhs2)) {
|
|
||||||
Some((rhs, lhs))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BinaryOperator {
|
|
||||||
pub fn is_commutative(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
BinaryOperator::Add => true,
|
|
||||||
BinaryOperator::Minus => false,
|
|
||||||
BinaryOperator::Mult => true,
|
|
||||||
BinaryOperator::Div => false,
|
|
||||||
BinaryOperator::Mod => false,
|
|
||||||
BinaryOperator::And => true,
|
|
||||||
BinaryOperator::Cmp(cmp_operator) => match cmp_operator {
|
|
||||||
CmpOperator::LT => false,
|
|
||||||
CmpOperator::LE => false,
|
|
||||||
CmpOperator::GT => false,
|
|
||||||
CmpOperator::GE => false,
|
|
||||||
CmpOperator::EQ => true,
|
|
||||||
CmpOperator::NE => true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum TypeCategory {
|
pub enum TypeCategory {
|
||||||
Integer,
|
Integer,
|
||||||
Real,
|
Real,
|
||||||
Bool,
|
|
||||||
Other,
|
Other,
|
||||||
TypeRef,
|
TypeRef,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TypeCategory {
|
|
||||||
pub fn is_simple_maths(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
TypeCategory::Integer => true,
|
|
||||||
TypeCategory::Real => true,
|
|
||||||
TypeCategory::Other => false,
|
|
||||||
TypeCategory::TypeRef => false,
|
|
||||||
TypeCategory::Bool => true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StructType {
|
impl StructType {
|
||||||
pub fn get_field_ty(&self, name: &String) -> Option<&TypeKind> {
|
pub fn get_field_ty(&self, name: &String) -> Option<&TypeKind> {
|
||||||
self.0
|
self.0
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf};
|
use std::{collections::HashMap, path::PathBuf};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
intrinsics::IntrinsicFunction,
|
intrinsics::InstrinsicKind,
|
||||||
lexer::{FullToken, Position},
|
lexer::{FullToken, Position},
|
||||||
token_stream::TokenRange,
|
token_stream::TokenRange,
|
||||||
};
|
};
|
||||||
@ -214,7 +214,7 @@ impl VagueLiteral {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum BinaryOperator {
|
pub enum BinaryOperator {
|
||||||
Add,
|
Add,
|
||||||
Minus,
|
Minus,
|
||||||
@ -226,7 +226,7 @@ pub enum BinaryOperator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Specifically the operators that LLVM likes to take in as "icmp" parameters
|
/// Specifically the operators that LLVM likes to take in as "icmp" parameters
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum CmpOperator {
|
pub enum CmpOperator {
|
||||||
LT,
|
LT,
|
||||||
LE,
|
LE,
|
||||||
@ -303,7 +303,7 @@ pub enum FunctionDefinitionKind {
|
|||||||
/// True = imported from other module, False = Is user defined extern
|
/// True = imported from other module, False = Is user defined extern
|
||||||
Extern(bool),
|
Extern(bool),
|
||||||
/// Intrinsic definition, defined within the compiler
|
/// Intrinsic definition, defined within the compiler
|
||||||
Intrinsic(Box<dyn IntrinsicFunction>),
|
Intrinsic(InstrinsicKind),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FunctionDefinition {
|
impl FunctionDefinition {
|
||||||
@ -365,30 +365,6 @@ pub enum TypeDefinitionKind {
|
|||||||
Struct(StructType),
|
Struct(StructType),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct BinopDefinition {
|
|
||||||
pub lhs: (String, TypeKind),
|
|
||||||
pub op: BinaryOperator,
|
|
||||||
pub rhs: (String, TypeKind),
|
|
||||||
pub return_type: TypeKind,
|
|
||||||
pub fn_kind: FunctionDefinitionKind,
|
|
||||||
pub meta: Metadata,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BinopDefinition {
|
|
||||||
pub fn block_meta(&self) -> Option<Metadata> {
|
|
||||||
match &self.fn_kind {
|
|
||||||
FunctionDefinitionKind::Local(block, _) => Some(block.meta),
|
|
||||||
FunctionDefinitionKind::Extern(_) => None,
|
|
||||||
FunctionDefinitionKind::Intrinsic(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn signature(&self) -> Metadata {
|
|
||||||
self.meta
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Module {
|
pub struct Module {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@ -396,7 +372,6 @@ pub struct Module {
|
|||||||
pub imports: Vec<Import>,
|
pub imports: Vec<Import>,
|
||||||
pub functions: Vec<FunctionDefinition>,
|
pub functions: Vec<FunctionDefinition>,
|
||||||
pub typedefs: Vec<TypeDefinition>,
|
pub typedefs: Vec<TypeDefinition>,
|
||||||
pub binop_defs: Vec<BinopDefinition>,
|
|
||||||
pub path: Option<PathBuf>,
|
pub path: Option<PathBuf>,
|
||||||
pub tokens: Vec<FullToken>,
|
pub tokens: Vec<FullToken>,
|
||||||
pub is_main: bool,
|
pub is_main: bool,
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
//! This module contains relevant code for [`Pass`] and shared code between
|
//! This module contains relevant code for [`Pass`] and shared code between
|
||||||
//! passes. Passes can be performed on Reid MIR to e.g. typecheck the code.
|
//! passes. Passes can be performed on Reid MIR to e.g. typecheck the code.
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::HashMap;
|
||||||
use std::convert::Infallible;
|
use std::convert::Infallible;
|
||||||
use std::error::Error as STDError;
|
use std::error::Error as STDError;
|
||||||
|
|
||||||
@ -111,19 +111,10 @@ impl<Key: std::hash::Hash + Eq, T: Clone + std::fmt::Debug> Storage<Key, T> {
|
|||||||
pub fn get(&self, key: &Key) -> Option<&T> {
|
pub fn get(&self, key: &Key) -> Option<&T> {
|
||||||
self.0.get(key)
|
self.0.get(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn iter(&self) -> impl Iterator<Item = (&Key, &T)> {
|
|
||||||
self.0.iter()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find(&self, key: &Key) -> Option<(&Key, &T)> {
|
|
||||||
self.0.iter().find(|(k, _)| *k == key)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Default, Debug)]
|
#[derive(Clone, Default, Debug)]
|
||||||
pub struct Scope<Data: Clone + Default> {
|
pub struct Scope<Data: Clone + Default> {
|
||||||
pub binops: Storage<ScopeBinopKey, ScopeBinopDef>,
|
|
||||||
pub function_returns: Storage<String, ScopeFunction>,
|
pub function_returns: Storage<String, ScopeFunction>,
|
||||||
pub variables: Storage<String, ScopeVariable>,
|
pub variables: Storage<String, ScopeVariable>,
|
||||||
pub types: Storage<CustomTypeKey, TypeDefinition>,
|
pub types: Storage<CustomTypeKey, TypeDefinition>,
|
||||||
@ -137,7 +128,6 @@ impl<Data: Clone + Default> Scope<Data> {
|
|||||||
Scope {
|
Scope {
|
||||||
function_returns: self.function_returns.clone(),
|
function_returns: self.function_returns.clone(),
|
||||||
variables: self.variables.clone(),
|
variables: self.variables.clone(),
|
||||||
binops: self.binops.clone(),
|
|
||||||
types: self.types.clone(),
|
types: self.types.clone(),
|
||||||
return_type_hint: self.return_type_hint.clone(),
|
return_type_hint: self.return_type_hint.clone(),
|
||||||
data: self.data.clone(),
|
data: self.data.clone(),
|
||||||
@ -172,57 +162,6 @@ pub struct ScopeVariable {
|
|||||||
pub mutable: bool,
|
pub mutable: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq)]
|
|
||||||
pub struct ScopeBinopKey {
|
|
||||||
pub params: (TypeKind, TypeKind),
|
|
||||||
pub operator: BinaryOperator,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
|
|
||||||
pub enum CommutativeKind {
|
|
||||||
True,
|
|
||||||
False,
|
|
||||||
Any,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for ScopeBinopKey {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
if self.operator != other.operator {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if self.operator.is_commutative() != other.operator.is_commutative() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let operators_eq = self.params == other.params;
|
|
||||||
let swapped_ops_eq = (self.params.1.clone(), self.params.0.clone()) == other.params;
|
|
||||||
if self.operator.is_commutative() {
|
|
||||||
operators_eq || swapped_ops_eq
|
|
||||||
} else {
|
|
||||||
operators_eq
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::hash::Hash for ScopeBinopKey {
|
|
||||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
if self.operator.is_commutative() {
|
|
||||||
let mut sorted = vec![&self.params.0, &self.params.1];
|
|
||||||
sorted.sort();
|
|
||||||
sorted.hash(state);
|
|
||||||
self.operator.hash(state);
|
|
||||||
} else {
|
|
||||||
self.params.hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct ScopeBinopDef {
|
|
||||||
pub hands: (TypeKind, TypeKind),
|
|
||||||
pub operator: BinaryOperator,
|
|
||||||
pub return_ty: TypeKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PassState<'st, 'sc, Data: Clone + Default, TError: STDError + Clone> {
|
pub struct PassState<'st, 'sc, Data: Clone + Default, TError: STDError + Clone> {
|
||||||
state: &'st mut State<TError>,
|
state: &'st mut State<TError>,
|
||||||
pub scope: &'sc mut Scope<Data>,
|
pub scope: &'sc mut Scope<Data>,
|
||||||
@ -362,23 +301,6 @@ impl Module {
|
|||||||
.ok();
|
.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
for binop in &self.binop_defs {
|
|
||||||
scope
|
|
||||||
.binops
|
|
||||||
.set(
|
|
||||||
ScopeBinopKey {
|
|
||||||
params: (binop.lhs.1.clone(), binop.rhs.1.clone()),
|
|
||||||
operator: binop.op,
|
|
||||||
},
|
|
||||||
ScopeBinopDef {
|
|
||||||
hands: (binop.lhs.1.clone(), binop.rhs.1.clone()),
|
|
||||||
operator: binop.op,
|
|
||||||
return_ty: binop.return_type.clone(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
for function in &self.functions {
|
for function in &self.functions {
|
||||||
scope
|
scope
|
||||||
.function_returns
|
.function_returns
|
||||||
|
@ -64,16 +64,12 @@ pub enum ErrorKind {
|
|||||||
ImpossibleMutableBorrow(String),
|
ImpossibleMutableBorrow(String),
|
||||||
#[error("Cannot declare variable {0} as mutable, when it's type is immutable")]
|
#[error("Cannot declare variable {0} as mutable, when it's type is immutable")]
|
||||||
ImpossibleMutLet(String),
|
ImpossibleMutLet(String),
|
||||||
#[error("Cannot produce a negative unsigned value of type {0}")]
|
#[error("Cannot produce a negative unsigned value of type {0}!")]
|
||||||
NegativeUnsignedValue(TypeKind),
|
NegativeUnsignedValue(TypeKind),
|
||||||
#[error("Cannot cast type {0} into type {1}")]
|
#[error("Cannot cast type {0} into type {1}!")]
|
||||||
NotCastableTo(TypeKind, TypeKind),
|
NotCastableTo(TypeKind, TypeKind),
|
||||||
#[error("Cannot divide by zero")]
|
#[error("Cannot divide by zero")]
|
||||||
DivideZero,
|
DivideZero,
|
||||||
#[error("Binary operation {0} between {1} and {2} is already defined")]
|
|
||||||
BinaryOpAlreadyDefined(BinaryOperator, TypeKind, TypeKind),
|
|
||||||
#[error("Binary operation {0} between {1} and {2} is not defined")]
|
|
||||||
InvalidBinop(BinaryOperator, TypeKind, TypeKind),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Struct used to implement a type-checking pass that can be performed on the
|
/// Struct used to implement a type-checking pass that can be performed on the
|
||||||
@ -136,11 +132,6 @@ impl<'t> Pass for TypeCheck<'t> {
|
|||||||
check_typedefs_for_recursion(&defmap, typedef, HashSet::new(), &mut state);
|
check_typedefs_for_recursion(&defmap, typedef, HashSet::new(), &mut state);
|
||||||
}
|
}
|
||||||
|
|
||||||
for binop in &mut module.binop_defs {
|
|
||||||
let res = binop.typecheck(&self.refs, &mut state.inner());
|
|
||||||
state.ok(res, binop.block_meta().unwrap_or(binop.signature()));
|
|
||||||
}
|
|
||||||
|
|
||||||
for function in &mut module.functions {
|
for function in &mut module.functions {
|
||||||
let res = function.typecheck(&self.refs, &mut state.inner());
|
let res = function.typecheck(&self.refs, &mut state.inner());
|
||||||
state.ok(res, function.block_meta());
|
state.ok(res, function.block_meta());
|
||||||
@ -179,52 +170,6 @@ fn check_typedefs_for_recursion<'a, 'b>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BinopDefinition {
|
|
||||||
fn typecheck(
|
|
||||||
&mut self,
|
|
||||||
typerefs: &TypeRefs,
|
|
||||||
state: &mut TypecheckPassState,
|
|
||||||
) -> Result<TypeKind, ErrorKind> {
|
|
||||||
for param in vec![&self.lhs, &self.rhs] {
|
|
||||||
let param_t = state.or_else(
|
|
||||||
param.1.assert_known(typerefs, state),
|
|
||||||
TypeKind::Vague(Vague::Unknown),
|
|
||||||
self.signature(),
|
|
||||||
);
|
|
||||||
let res = state
|
|
||||||
.scope
|
|
||||||
.variables
|
|
||||||
.set(
|
|
||||||
param.0.clone(),
|
|
||||||
ScopeVariable {
|
|
||||||
ty: param_t.clone(),
|
|
||||||
mutable: param_t.is_mutable(),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
|
|
||||||
state.ok(res, self.signature());
|
|
||||||
}
|
|
||||||
|
|
||||||
let return_type = self.return_type.clone().assert_known(typerefs, state)?;
|
|
||||||
|
|
||||||
state.scope.return_type_hint = Some(self.return_type.clone());
|
|
||||||
let inferred =
|
|
||||||
self.fn_kind
|
|
||||||
.typecheck(&typerefs, &mut state.inner(), Some(return_type.clone()));
|
|
||||||
|
|
||||||
match inferred {
|
|
||||||
Ok(t) => return_type
|
|
||||||
.collapse_into(&t.1)
|
|
||||||
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
|
|
||||||
Err(e) => Ok(state.or_else(
|
|
||||||
Err(e),
|
|
||||||
return_type,
|
|
||||||
self.block_meta().unwrap_or(self.signature()),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FunctionDefinition {
|
impl FunctionDefinition {
|
||||||
fn typecheck(
|
fn typecheck(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -252,30 +197,10 @@ impl FunctionDefinition {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let return_type = self.return_type.clone().assert_known(typerefs, state)?;
|
let return_type = self.return_type.clone().assert_known(typerefs, state)?;
|
||||||
let inferred = self
|
let inferred = match &mut self.kind {
|
||||||
.kind
|
|
||||||
.typecheck(typerefs, state, Some(self.return_type.clone()));
|
|
||||||
|
|
||||||
match inferred {
|
|
||||||
Ok(t) => return_type
|
|
||||||
.collapse_into(&t.1)
|
|
||||||
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
|
|
||||||
Err(e) => Ok(state.or_else(Err(e), return_type, self.block_meta())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FunctionDefinitionKind {
|
|
||||||
fn typecheck(
|
|
||||||
&mut self,
|
|
||||||
typerefs: &TypeRefs,
|
|
||||||
state: &mut TypecheckPassState,
|
|
||||||
hint: Option<TypeKind>,
|
|
||||||
) -> Result<(ReturnKind, TypeKind), ErrorKind> {
|
|
||||||
match self {
|
|
||||||
FunctionDefinitionKind::Local(block, _) => {
|
FunctionDefinitionKind::Local(block, _) => {
|
||||||
state.scope.return_type_hint = hint.clone();
|
state.scope.return_type_hint = Some(self.return_type.clone());
|
||||||
block.typecheck(&mut state.inner(), &typerefs, hint.as_ref())
|
block.typecheck(&mut state.inner(), &typerefs, Some(&return_type))
|
||||||
}
|
}
|
||||||
FunctionDefinitionKind::Extern(_) => {
|
FunctionDefinitionKind::Extern(_) => {
|
||||||
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
|
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
|
||||||
@ -283,6 +208,13 @@ impl FunctionDefinitionKind {
|
|||||||
FunctionDefinitionKind::Intrinsic(..) => {
|
FunctionDefinitionKind::Intrinsic(..) => {
|
||||||
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
|
Ok((ReturnKind::Soft, TypeKind::Vague(Vague::Unknown)))
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match inferred {
|
||||||
|
Ok(t) => return_type
|
||||||
|
.collapse_into(&t.1)
|
||||||
|
.or(Err(ErrorKind::ReturnTypeMismatch(return_type, t.1))),
|
||||||
|
Err(e) => Ok(state.or_else(Err(e), return_type, self.block_meta())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -510,71 +442,16 @@ impl Expression {
|
|||||||
Ok(literal.as_type())
|
Ok(literal.as_type())
|
||||||
}
|
}
|
||||||
ExprKind::BinOp(op, lhs, rhs) => {
|
ExprKind::BinOp(op, lhs, rhs) => {
|
||||||
// First find unfiltered parameters to binop
|
// TODO make sure lhs and rhs can actually do this binary
|
||||||
let lhs_res = lhs.typecheck(state, &typerefs, None);
|
// operation once relevant
|
||||||
let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
|
|
||||||
let rhs_res = rhs.typecheck(state, &typerefs, None);
|
|
||||||
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
|
|
||||||
|
|
||||||
let cloned = state.scope.binops.clone();
|
|
||||||
let mut iter = cloned.iter();
|
|
||||||
let operator = loop {
|
|
||||||
let Some((_, binop)) = iter.next() else {
|
|
||||||
break None;
|
|
||||||
};
|
|
||||||
if binop.operator != *op {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if let Some(hint_t) = hint_t {
|
|
||||||
if binop.return_ty == *hint_t {
|
|
||||||
if let Some(_) = TypeKind::binop_type(&lhs_type, &rhs_type, binop) {
|
|
||||||
break Some(binop);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(_) = TypeKind::binop_type(&lhs_type, &rhs_type, binop) {
|
|
||||||
break Some(binop);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some(operator) = operator {
|
|
||||||
// Re-typecheck with found operator hints
|
|
||||||
let (lhs_ty, rhs_ty) = TypeKind::try_collapse_two(
|
|
||||||
(&lhs_type, &rhs_type),
|
|
||||||
(&operator.hands.0, &operator.hands.1),
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let lhs_res = lhs.typecheck(state, &typerefs, Some(&lhs_ty));
|
|
||||||
let rhs_res = rhs.typecheck(state, &typerefs, Some(&rhs_ty));
|
|
||||||
state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
|
|
||||||
state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
|
|
||||||
Ok(operator.return_ty.clone())
|
|
||||||
} else {
|
|
||||||
// Re-typecheck with typical everyday binop
|
|
||||||
let lhs_res = lhs.typecheck(
|
let lhs_res = lhs.typecheck(
|
||||||
state,
|
state,
|
||||||
&typerefs,
|
&typerefs,
|
||||||
hint_t.and_then(|t| t.simple_binop_hint(op)).as_ref(),
|
hint_t.and_then(|t| t.binop_hint(op)).as_ref(),
|
||||||
);
|
);
|
||||||
let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
|
let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
|
||||||
let rhs_res = rhs.typecheck(state, &typerefs, Some(&lhs_type));
|
let rhs_res = rhs.typecheck(state, &typerefs, Some(&lhs_type));
|
||||||
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
|
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
|
||||||
dbg!(&op, &hint_t);
|
|
||||||
dbg!(&lhs_type);
|
|
||||||
dbg!(&rhs_type);
|
|
||||||
|
|
||||||
let both_t = lhs_type.collapse_into(&rhs_type)?;
|
|
||||||
|
|
||||||
if *op == BinaryOperator::Minus && !lhs_type.signed() {
|
|
||||||
if let (Some(lhs_val), Some(rhs_val)) = (lhs.num_value()?, rhs.num_value()?)
|
|
||||||
{
|
|
||||||
if lhs_val < rhs_val {
|
|
||||||
return Err(ErrorKind::NegativeUnsignedValue(lhs_type));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) {
|
if let Some(collapsed) = state.ok(rhs_type.collapse_into(&rhs_type), self.1) {
|
||||||
// Try to coerce both sides again with collapsed type
|
// Try to coerce both sides again with collapsed type
|
||||||
@ -582,11 +459,18 @@ impl Expression {
|
|||||||
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
|
rhs.typecheck(state, &typerefs, Some(&collapsed)).ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
both_t
|
let both_t = lhs_type.collapse_into(&rhs_type)?;
|
||||||
.simple_binop_type(op)
|
|
||||||
.ok_or(ErrorKind::InvalidBinop(*op, lhs_type, 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))
|
||||||
|
}
|
||||||
ExprKind::FunctionCall(function_call) => {
|
ExprKind::FunctionCall(function_call) => {
|
||||||
let true_function = state
|
let true_function = state
|
||||||
.scope
|
.scope
|
||||||
@ -864,7 +748,7 @@ impl Expression {
|
|||||||
Ok(*inner)
|
Ok(*inner)
|
||||||
}
|
}
|
||||||
ExprKind::CastTo(expression, type_kind) => {
|
ExprKind::CastTo(expression, type_kind) => {
|
||||||
let expr = expression.typecheck(state, typerefs, Some(&type_kind))?;
|
let expr = expression.typecheck(state, typerefs, None)?;
|
||||||
expr.resolve_ref(typerefs).cast_into(type_kind)
|
expr.resolve_ref(typerefs).cast_into(type_kind)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,20 +4,16 @@
|
|||||||
//! must then be passed through TypeCheck with the same [`TypeRefs`] in order to
|
//! must then be passed through TypeCheck with the same [`TypeRefs`] in order to
|
||||||
//! place the correct types from the IDs and check that there are no issues.
|
//! place the correct types from the IDs and check that there are no issues.
|
||||||
|
|
||||||
use std::{
|
use std::{collections::HashMap, convert::Infallible, iter};
|
||||||
collections::{HashMap, HashSet},
|
|
||||||
convert::Infallible,
|
|
||||||
iter,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{mir::TypeKind, util::try_all};
|
use crate::{mir::TypeKind, util::try_all};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
pass::{self, Pass, PassResult, PassState, ScopeBinopDef, ScopeBinopKey},
|
pass::{Pass, PassResult, PassState},
|
||||||
typecheck::{ErrorKind, ErrorTypedefKind},
|
typecheck::{ErrorKind, ErrorTypedefKind},
|
||||||
typerefs::{ScopeTypeRefs, TypeRef, TypeRefs},
|
typerefs::{ScopeTypeRefs, TypeRef, TypeRefs},
|
||||||
BinopDefinition, Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition,
|
Block, CustomTypeKey, ExprKind, Expression, FunctionDefinition, FunctionDefinitionKind,
|
||||||
FunctionDefinitionKind, IfExpression, Module, ReturnKind, StmtKind,
|
IfExpression, Module, ReturnKind, StmtKind,
|
||||||
TypeKind::*,
|
TypeKind::*,
|
||||||
VagueType::*,
|
VagueType::*,
|
||||||
WhileStatement,
|
WhileStatement,
|
||||||
@ -59,33 +55,6 @@ impl<'t> Pass for TypeInference<'t> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut seen_binops = HashSet::new();
|
|
||||||
for binop in &module.binop_defs {
|
|
||||||
let binop_key = ScopeBinopKey {
|
|
||||||
params: (binop.lhs.1.clone(), binop.rhs.1.clone()),
|
|
||||||
operator: binop.op,
|
|
||||||
};
|
|
||||||
if seen_binops.contains(&binop_key)
|
|
||||||
|| (binop.lhs == binop.rhs && binop.lhs.1.category().is_simple_maths())
|
|
||||||
{
|
|
||||||
state.note_errors(
|
|
||||||
&vec![ErrorKind::BinaryOpAlreadyDefined(
|
|
||||||
binop.op,
|
|
||||||
binop.lhs.1.clone(),
|
|
||||||
binop.rhs.1.clone(),
|
|
||||||
)],
|
|
||||||
binop.signature(),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
seen_binops.insert(binop_key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for binop in &mut module.binop_defs {
|
|
||||||
let res = binop.infer_types(&self.refs, &mut state.inner());
|
|
||||||
state.ok(res, binop.block_meta().unwrap_or(binop.signature()));
|
|
||||||
}
|
|
||||||
|
|
||||||
for function in &mut module.functions {
|
for function in &mut module.functions {
|
||||||
let res = function.infer_types(&self.refs, &mut state.inner());
|
let res = function.infer_types(&self.refs, &mut state.inner());
|
||||||
state.ok(res, function.block_meta());
|
state.ok(res, function.block_meta());
|
||||||
@ -94,60 +63,16 @@ impl<'t> Pass for TypeInference<'t> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BinopDefinition {
|
|
||||||
fn infer_types(
|
|
||||||
&mut self,
|
|
||||||
type_refs: &TypeRefs,
|
|
||||||
state: &mut TypeInferencePassState,
|
|
||||||
) -> Result<(), ErrorKind> {
|
|
||||||
let scope_hints = ScopeTypeRefs::from(type_refs);
|
|
||||||
|
|
||||||
let lhs_ty = state.or_else(
|
|
||||||
self.lhs.1.assert_unvague(),
|
|
||||||
Vague(Unknown),
|
|
||||||
self.signature(),
|
|
||||||
);
|
|
||||||
state.ok(
|
|
||||||
scope_hints
|
|
||||||
.new_var(self.lhs.0.clone(), false, &lhs_ty)
|
|
||||||
.or(Err(ErrorKind::VariableAlreadyDefined(self.lhs.0.clone()))),
|
|
||||||
self.signature(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let rhs_ty = state.or_else(
|
|
||||||
self.rhs.1.assert_unvague(),
|
|
||||||
Vague(Unknown),
|
|
||||||
self.signature(),
|
|
||||||
);
|
|
||||||
|
|
||||||
state.ok(
|
|
||||||
scope_hints
|
|
||||||
.new_var(self.rhs.0.clone(), false, &rhs_ty)
|
|
||||||
.or(Err(ErrorKind::VariableAlreadyDefined(self.rhs.0.clone()))),
|
|
||||||
self.signature(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let ret_ty =
|
|
||||||
self.fn_kind
|
|
||||||
.infer_types(state, &scope_hints, Some(self.return_type.clone()))?;
|
|
||||||
if let Some(mut ret_ty) = ret_ty {
|
|
||||||
ret_ty.narrow(&scope_hints.from_type(&self.return_type).unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FunctionDefinition {
|
impl FunctionDefinition {
|
||||||
fn infer_types(
|
fn infer_types(
|
||||||
&mut self,
|
&mut self,
|
||||||
type_refs: &TypeRefs,
|
type_refs: &TypeRefs,
|
||||||
state: &mut TypeInferencePassState,
|
state: &mut TypeInferencePassState,
|
||||||
) -> Result<(), ErrorKind> {
|
) -> Result<(), ErrorKind> {
|
||||||
let scope_refs = ScopeTypeRefs::from(type_refs);
|
let scope_hints = ScopeTypeRefs::from(type_refs);
|
||||||
for param in &self.parameters {
|
for param in &self.parameters {
|
||||||
let param_t = state.or_else(param.1.assert_unvague(), Vague(Unknown), self.signature());
|
let param_t = state.or_else(param.1.assert_unvague(), Vague(Unknown), self.signature());
|
||||||
let res = scope_refs
|
let res = scope_hints
|
||||||
.new_var(param.0.clone(), false, ¶m_t)
|
.new_var(param.0.clone(), false, ¶m_t)
|
||||||
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
|
.or(Err(ErrorKind::VariableAlreadyDefined(param.0.clone())));
|
||||||
state.ok(res, self.signature());
|
state.ok(res, self.signature());
|
||||||
@ -158,51 +83,21 @@ impl FunctionDefinition {
|
|||||||
state.scope.return_type_hint = Some(self.return_type.clone());
|
state.scope.return_type_hint = Some(self.return_type.clone());
|
||||||
|
|
||||||
// Infer block return type
|
// Infer block return type
|
||||||
let ret_res = block.infer_types(state, &scope_refs);
|
let ret_res = block.infer_types(state, &scope_hints);
|
||||||
|
|
||||||
// Narrow block type to declared function type
|
// Narrow block type to declared function type
|
||||||
if let Some(mut ret_ty) = state.ok(ret_res.map(|(_, ty)| ty), self.block_meta()) {
|
if let Some(mut ret_ty) = state.ok(ret_res.map(|(_, ty)| ty), self.block_meta()) {
|
||||||
ret_ty.narrow(&scope_refs.from_type(&self.return_type).unwrap());
|
ret_ty.narrow(&scope_hints.from_type(&self.return_type).unwrap());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
FunctionDefinitionKind::Extern(_) => {}
|
FunctionDefinitionKind::Extern(_) => {}
|
||||||
FunctionDefinitionKind::Intrinsic(_) => {}
|
FunctionDefinitionKind::Intrinsic(_) => {}
|
||||||
};
|
};
|
||||||
let return_ty = self
|
|
||||||
.kind
|
|
||||||
.infer_types(state, &scope_refs, Some(self.return_type.clone()));
|
|
||||||
|
|
||||||
if let Some(Some(mut ret_ty)) = state.ok(return_ty, self.block_meta()) {
|
|
||||||
ret_ty.narrow(&scope_refs.from_type(&self.return_type).unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FunctionDefinitionKind {
|
|
||||||
fn infer_types<'s>(
|
|
||||||
&mut self,
|
|
||||||
state: &mut TypeInferencePassState,
|
|
||||||
scope_refs: &'s ScopeTypeRefs,
|
|
||||||
hint: Option<TypeKind>,
|
|
||||||
) -> Result<Option<TypeRef<'s>>, ErrorKind> {
|
|
||||||
Ok(match self {
|
|
||||||
FunctionDefinitionKind::Local(block, _) => {
|
|
||||||
state.scope.return_type_hint = hint;
|
|
||||||
|
|
||||||
// Infer block return type
|
|
||||||
let ret_res = block.infer_types(state, &scope_refs);
|
|
||||||
|
|
||||||
// Narrow block type to declared function type
|
|
||||||
Some(ret_res.map(|(_, ty)| ty)?)
|
|
||||||
}
|
|
||||||
FunctionDefinitionKind::Extern(_) => None,
|
|
||||||
FunctionDefinitionKind::Intrinsic(_) => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Block {
|
impl Block {
|
||||||
fn infer_types<'s>(
|
fn infer_types<'s>(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -314,31 +209,12 @@ impl Expression {
|
|||||||
// Infer LHS and RHS, and return binop type
|
// Infer LHS and RHS, and return binop type
|
||||||
let mut lhs_ref = lhs.infer_types(state, type_refs)?;
|
let mut lhs_ref = lhs.infer_types(state, type_refs)?;
|
||||||
let mut rhs_ref = rhs.infer_types(state, type_refs)?;
|
let mut rhs_ref = rhs.infer_types(state, type_refs)?;
|
||||||
|
type_refs
|
||||||
if let Ok(binop) = type_refs
|
.binop(op, &mut lhs_ref, &mut rhs_ref)
|
||||||
.binop(op, &mut lhs_ref, &mut rhs_ref, &state.scope.binops)
|
|
||||||
.ok_or(ErrorKind::TypesIncompatible(
|
.ok_or(ErrorKind::TypesIncompatible(
|
||||||
lhs_ref.resolve_deep().unwrap(),
|
lhs_ref.resolve_deep().unwrap(),
|
||||||
rhs_ref.resolve_deep().unwrap(),
|
rhs_ref.resolve_deep().unwrap(),
|
||||||
))
|
))
|
||||||
{
|
|
||||||
Ok(binop)
|
|
||||||
} else {
|
|
||||||
let typeref = lhs_ref.narrow(&rhs_ref).unwrap();
|
|
||||||
Ok(type_refs
|
|
||||||
.from_type(
|
|
||||||
&typeref
|
|
||||||
.resolve_deep()
|
|
||||||
.unwrap()
|
|
||||||
.simple_binop_type(op)
|
|
||||||
.ok_or(ErrorKind::InvalidBinop(
|
|
||||||
*op,
|
|
||||||
lhs_ref.resolve_deep().unwrap(),
|
|
||||||
rhs_ref.resolve_deep().unwrap(),
|
|
||||||
))?,
|
|
||||||
)
|
|
||||||
.unwrap())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
ExprKind::FunctionCall(function_call) => {
|
ExprKind::FunctionCall(function_call) => {
|
||||||
// Get function definition and types
|
// Get function definition and types
|
||||||
|
@ -6,11 +6,7 @@ use std::{
|
|||||||
|
|
||||||
use crate::mir::VagueType;
|
use crate::mir::VagueType;
|
||||||
|
|
||||||
use super::{
|
use super::{typecheck::ErrorKind, BinaryOperator, TypeKind};
|
||||||
pass::{ScopeBinopDef, ScopeBinopKey, Storage},
|
|
||||||
typecheck::ErrorKind,
|
|
||||||
BinaryOperator, TypeKind,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct TypeRef<'scope>(
|
pub struct TypeRef<'scope>(
|
||||||
@ -231,39 +227,8 @@ impl<'outer> ScopeTypeRefs<'outer> {
|
|||||||
op: &BinaryOperator,
|
op: &BinaryOperator,
|
||||||
lhs: &mut TypeRef<'outer>,
|
lhs: &mut TypeRef<'outer>,
|
||||||
rhs: &mut TypeRef<'outer>,
|
rhs: &mut TypeRef<'outer>,
|
||||||
binops: &Storage<ScopeBinopKey, ScopeBinopDef>,
|
|
||||||
) -> Option<TypeRef<'outer>> {
|
) -> Option<TypeRef<'outer>> {
|
||||||
if lhs.resolve_deep().unwrap().known().is_err()
|
let ty = lhs.narrow(rhs)?;
|
||||||
&& rhs.resolve_deep().unwrap().known().is_err()
|
self.from_type(&ty.as_type().binop_type(op))
|
||||||
{
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
Loading…
Reference in New Issue
Block a user