Compare commits

..

6 Commits

Author SHA1 Message Date
1b1a5934f5 Implement lexical scopes 2025-07-28 18:40:42 +03:00
726251e39c Fix warnings, cleanup 2025-07-28 18:22:51 +03:00
61d3ea61ee Fix debug info 2025-07-28 18:20:00 +03:00
d0e1082029 Refactor scopes a little bit 2025-07-28 18:05:19 +03:00
60860498df Possibly fix binop type inference infinite recursion 2025-07-28 17:31:18 +03:00
7ca8949e8c Start adding lexical scopes 2025-07-28 16:11:20 +03:00
17 changed files with 368 additions and 321 deletions

6
examples/a.reid Normal file
View File

@ -0,0 +1,6 @@
pub fn main() -> u32 {
let b = 4;
let c = b + 4;
return c;
}

View File

@ -7,7 +7,7 @@ use crate::{
Block, BlockData, CompileResult, CustomTypeKind, ErrorKind, FunctionData, Instr, InstructionData, ModuleData,
NamedStruct, TerminatorKind, Type, TypeCategory, TypeData,
debug_information::{
DebugInformation, DebugLocationValue, DebugMetadataValue, DebugProgramValue, InstructionDebugRecordData,
DebugInformation, DebugLocationValue, DebugMetadataValue, DebugScopeValue, InstructionDebugRecordData,
},
util::match_types,
};
@ -47,6 +47,8 @@ pub struct FunctionHolder {
pub(crate) value: FunctionValue,
pub(crate) data: FunctionData,
pub(crate) blocks: Vec<BlockHolder>,
/// Debug scope value of this current function
pub(crate) debug_info: Option<DebugScopeValue>,
}
#[derive(Clone)]
@ -117,6 +119,7 @@ impl Builder {
value,
data,
blocks: Vec::new(),
debug_info: None,
});
value
}
@ -198,12 +201,12 @@ impl Builder {
}
}
pub(crate) unsafe fn set_debug_subprogram(&self, value: &FunctionValue, subprogram: DebugProgramValue) {
pub(crate) unsafe fn set_debug_subprogram(&self, value: &FunctionValue, subprogram: DebugScopeValue) {
unsafe {
let mut modules = self.modules.borrow_mut();
let module = modules.get_unchecked_mut(value.0.0);
let function = module.functions.get_unchecked_mut(value.1);
function.data.debug = Some(subprogram)
function.debug_info = Some(subprogram)
}
}

View File

@ -3,6 +3,7 @@
//! with the LLVM API.
use std::{
cell::Ref,
collections::HashMap,
ptr::{null, null_mut},
};
@ -206,12 +207,11 @@ impl<'a> Drop for LLVMModule<'a> {
}
pub struct LLVMDebugInformation<'a> {
debug: &'a DebugInformation,
info: &'a DebugInformation,
builder: LLVMDIBuilderRef,
file_ref: LLVMMetadataRef,
// scopes: &'a HashMap<DebugScopeValue, LLVMMetadataRef>,
scopes: &'a mut HashMap<DebugScopeValue, LLVMMetadataRef>,
types: &'a mut HashMap<DebugTypeValue, LLVMMetadataRef>,
programs: &'a mut HashMap<DebugProgramValue, LLVMMetadataRef>,
metadata: &'a mut HashMap<DebugMetadataValue, LLVMMetadataRef>,
locations: &'a mut HashMap<DebugLocationValue, LLVMMetadataRef>,
}
@ -238,7 +238,7 @@ impl ModuleHolder {
let mut types = HashMap::new();
let mut metadata = HashMap::new();
let mut programs = HashMap::new();
let mut scopes = HashMap::new();
let mut locations = HashMap::new();
let mut debug = if let Some(debug) = &self.debug_information {
@ -294,19 +294,19 @@ impl ModuleHolder {
// }
// dbg!("after!");
programs.insert(DebugProgramValue(0), compile_unit);
scopes.insert(DebugScopeValue(Vec::new()), compile_unit);
let debug = LLVMDebugInformation {
builder: di_builder,
debug: debug,
info: debug,
file_ref,
types: &mut types,
metadata: &mut metadata,
programs: &mut programs,
scopes: &mut scopes,
locations: &mut locations,
};
for ty in debug.debug.get_types().borrow().iter() {
for ty in debug.info.get_types().borrow().iter() {
let meta_ref = ty.compile_debug(&debug);
debug.types.insert(ty.value.clone(), meta_ref);
}
@ -322,23 +322,28 @@ impl ModuleHolder {
let mut functions = HashMap::new();
for function in &self.functions {
let func = function.compile_signature(context, module_ref, &types, &debug);
let func = function.compile_signature(context, module_ref, &types, &mut debug);
functions.insert(function.value, func);
if let Some(debug) = &mut debug {
if let Some(program_value) = function.data.debug {
debug.programs.insert(program_value, func.metadata.unwrap());
if let (Some(debug), Some(debug_info)) = (&mut debug, &function.debug_info) {
let scope_refcell = debug.info.get_scope();
let mut scope = scope_refcell.borrow();
for i in &debug_info.0 {
scope = Ref::map(scope, |v| v.inner_scopes.get_unchecked(*i));
}
for scope in &scope.inner_scopes {
scope.compile_scope(func.metadata.unwrap(), debug.file_ref, debug.scopes, debug.builder);
}
}
}
if let Some(debug) = &mut debug {
for location in debug.debug.get_locations().borrow().iter() {
for location in debug.info.get_locations().borrow().iter() {
let location_ref = location.compile(context, &debug);
debug.locations.insert(location.value, location_ref);
debug.locations.insert(location.value.clone(), location_ref);
}
for meta in debug.debug.get_metadatas().borrow().iter() {
for meta in debug.info.get_metadatas().borrow().iter() {
let meta_ref = meta.compile(&debug);
debug.metadata.insert(meta.value.clone(), meta_ref);
}
@ -376,7 +381,7 @@ impl DebugLocationHolder {
context.context_ref,
self.location.pos.line,
self.location.pos.column,
*debug.programs.get(&self.program).unwrap(),
*debug.scopes.get(&self.scope).unwrap(),
null_mut(),
)
}
@ -392,10 +397,16 @@ impl DebugScopeHolder {
di_builder: LLVMDIBuilderRef,
) {
unsafe {
let scope = if let Some(location) = &self.location {
LLVMDIBuilderCreateLexicalBlock(di_builder, parent, file, location.pos.line, location.pos.column)
} else {
LLVMDIBuilderCreateLexicalBlockFile(di_builder, parent, file, 0)
let scope = match &self.data.kind {
DebugScopeKind::CodegenContext => panic!(),
DebugScopeKind::LexicalScope(data) => LLVMDIBuilderCreateLexicalBlock(
di_builder,
parent,
file,
data.location.pos.line,
data.location.pos.column,
),
DebugScopeKind::Subprogram(_) => panic!(),
};
for inner in &self.inner_scopes {
@ -413,7 +424,7 @@ impl DebugMetadataHolder {
match &self.data {
DebugMetadata::ParamVar(param) => LLVMDIBuilderCreateParameterVariable(
debug.builder,
*debug.programs.get(&self.location.scope).unwrap(),
*debug.scopes.get(&self.location.scope).unwrap(),
into_cstring(param.name.clone()).as_ptr(),
param.name.len(),
param.arg_idx + 1,
@ -425,7 +436,7 @@ impl DebugMetadataHolder {
),
DebugMetadata::LocalVar(var) => LLVMDIBuilderCreateAutoVariable(
debug.builder,
*debug.programs.get(&self.location.scope).unwrap(),
*debug.scopes.get(&self.location.scope).unwrap(),
into_cstring(var.name.clone()).as_ptr(),
var.name.len(),
debug.file_ref,
@ -495,7 +506,7 @@ impl DebugTypeHolder {
.map(|field| {
LLVMDIBuilderCreateMemberType(
debug.builder,
*debug.programs.get(&st.scope).unwrap(),
*debug.scopes.get(&st.scope).unwrap(),
into_cstring(field.name.clone()).as_ptr(),
field.name.len(),
debug.file_ref,
@ -510,7 +521,7 @@ impl DebugTypeHolder {
.collect::<Vec<_>>();
LLVMDIBuilderCreateStructType(
debug.builder,
*debug.programs.get(&st.scope).unwrap(),
*debug.scopes.get(&st.scope).unwrap(),
into_cstring(st.name.clone()).as_ptr(),
st.name.len(),
debug.file_ref,
@ -563,7 +574,7 @@ impl FunctionHolder {
context: &LLVMContext,
module_ref: LLVMModuleRef,
types: &HashMap<TypeValue, LLVMTypeRef>,
debug: &Option<LLVMDebugInformation>,
debug: &mut Option<LLVMDebugInformation>,
) -> LLVMFunction {
unsafe {
let ret_type = self.data.ret.as_llvm(context.context_ref, types);
@ -586,30 +597,37 @@ impl FunctionHolder {
}
let metadata = if let Some(debug) = debug {
if let Some(value) = &self.data.debug {
let subprogram = debug.debug.get_subprogram_data_unchecked(&value);
if let Some(scope_value) = &self.debug_info {
let scope_data = debug.info.get_scope_data(scope_value).unwrap();
dbg!(&debug.info.get_scope());
let mangled_length_ptr = &mut 0;
let mangled_name = LLVMGetValueName2(function_ref, mangled_length_ptr);
let mangled_length = *mangled_length_ptr;
let subprogram = LLVMDIBuilderCreateFunction(
debug.builder,
*debug.programs.get(&subprogram.outer_scope).unwrap(),
into_cstring(subprogram.name.clone()).as_ptr(),
subprogram.name.clone().len(),
mangled_name,
mangled_length,
debug.file_ref,
subprogram.location.pos.line,
*debug.types.get(&subprogram.ty).unwrap(),
subprogram.opts.is_local as i32,
subprogram.opts.is_definition as i32,
subprogram.opts.scope_line,
subprogram.opts.flags.as_llvm(),
subprogram.opts.is_optimized as i32,
);
let subprogram = match scope_data.kind {
DebugScopeKind::CodegenContext => panic!(),
DebugScopeKind::LexicalScope(_) => panic!(),
DebugScopeKind::Subprogram(subprogram) => LLVMDIBuilderCreateFunction(
debug.builder,
*debug.scopes.get(&scope_data.parent.unwrap()).unwrap(),
into_cstring(subprogram.name.clone()).as_ptr(),
subprogram.name.clone().len(),
mangled_name,
mangled_length,
debug.file_ref,
subprogram.location.pos.line,
*debug.types.get(&subprogram.ty).unwrap(),
subprogram.opts.is_local as i32,
subprogram.opts.is_definition as i32,
subprogram.opts.scope_line,
subprogram.opts.flags.as_llvm(),
subprogram.opts.is_optimized as i32,
),
};
LLVMSetSubprogram(function_ref, subprogram);
debug.scopes.insert(scope_value.clone(), subprogram);
Some(subprogram)
} else {
None
@ -1013,7 +1031,7 @@ impl InstructionHolder {
module.context_ref,
record.location.pos.line,
record.location.pos.column,
*debug.programs.get(&record.scope).unwrap(),
*debug.scopes.get(&record.scope).unwrap(),
null_mut(),
);

View File

@ -1,12 +1,16 @@
use std::{cell::RefCell, rc::Rc};
use std::{
cell::{Ref, RefCell, RefMut},
rc::Rc,
};
use crate::builder::InstructionValue;
/// Represents 1. the compilation context, 2. subprogram or 3. a lexical scope
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct DebugScopeValue(pub Vec<usize>);
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct DebugLocationValue(pub DebugProgramValue, pub usize);
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct DebugLocationValue(pub DebugScopeValue, pub usize);
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct DebugTypeValue(pub usize);
@ -14,10 +18,6 @@ pub struct DebugTypeValue(pub usize);
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct DebugMetadataValue(pub usize);
/// Represents either a subprogram, or the compilation context
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct DebugProgramValue(pub usize);
#[derive(Debug, Clone)]
pub struct DebugFileData {
pub name: String,
@ -27,9 +27,8 @@ pub struct DebugFileData {
#[derive(Debug, Clone)]
pub(crate) struct DebugScopeHolder {
pub(crate) value: DebugScopeValue,
pub(crate) location: Option<DebugLocation>,
pub(crate) data: DebugScopeData,
pub(crate) inner_scopes: Vec<DebugScopeHolder>,
pub(crate) locations: Vec<DebugLocationHolder>,
}
#[derive(Debug, Clone)]
@ -45,15 +44,9 @@ pub struct DebugTypeHolder {
pub(crate) data: DebugTypeData,
}
#[derive(Debug, Clone)]
pub struct DebugSubprogramHolder {
pub(crate) _value: DebugProgramValue,
pub(crate) data: DebugSubprogramData,
}
#[derive(Debug, Clone)]
pub(crate) struct DebugLocationHolder {
pub(crate) program: DebugProgramValue,
pub(crate) scope: DebugScopeValue,
pub(crate) value: DebugLocationValue,
pub(crate) location: DebugLocation,
}
@ -61,68 +54,38 @@ pub(crate) struct DebugLocationHolder {
#[derive(Debug, Clone)]
pub struct DebugInformation {
pub file: DebugFileData,
// scope: Rc<RefCell<DebugScopeHolder>>,
scope: Rc<RefCell<DebugScopeHolder>>,
locations: Rc<RefCell<Vec<DebugLocationHolder>>>,
programs: Rc<RefCell<Vec<DebugSubprogramHolder>>>,
metadata: Rc<RefCell<Vec<DebugMetadataHolder>>>,
types: Rc<RefCell<Vec<DebugTypeHolder>>>,
}
impl DebugInformation {
pub fn from_file(file: DebugFileData) -> (DebugInformation, DebugProgramValue) {
pub fn from_file(file: DebugFileData) -> (DebugInformation, DebugScopeValue) {
let scope_value = DebugScopeValue(Vec::new());
(
DebugInformation {
file,
// scope: Rc::new(RefCell::new(DebugScopeHolder {
// value: scope_value.clone(),
// inner_scopes: Vec::new(),
// locations: Vec::new(),
// location: None,
// })),
scope: Rc::new(RefCell::new(DebugScopeHolder {
value: scope_value.clone(),
inner_scopes: Vec::new(),
data: DebugScopeData {
parent: None,
kind: DebugScopeKind::CodegenContext,
},
})),
locations: Rc::new(RefCell::new(Vec::new())),
metadata: Rc::new(RefCell::new(Vec::new())),
programs: Rc::new(RefCell::new(Vec::new())),
types: Rc::new(RefCell::new(Vec::new())),
},
DebugProgramValue(0),
scope_value,
)
}
// pub fn inner_scope(
// &self,
// parent: &DebugScopeValue,
// location: DebugLocation,
// ) -> DebugScopeValue {
// unsafe {
// let mut outer_scope = RefMut::map(self.scope.borrow_mut(), |mut v| {
// for i in &parent.0 {
// v = v.inner_scopes.get_unchecked_mut(*i);
// }
// v
// });
// let mut arr = parent.0.clone();
// arr.push(parent.0.len());
// let value = DebugScopeValue(arr);
// outer_scope.inner_scopes.push(DebugScopeHolder {
// value: value.clone(),
// inner_scopes: Vec::new(),
// locations: Vec::new(),
// location: Some(location),
// });
// value
// }
// }
pub fn location(
&self,
program_value: &DebugProgramValue,
location: DebugLocation,
) -> DebugLocationValue {
let value = DebugLocationValue(program_value.clone(), self.locations.borrow().len());
pub fn location(&self, scope_value: &DebugScopeValue, location: DebugLocation) -> DebugLocationValue {
let value = DebugLocationValue(scope_value.clone(), self.locations.borrow().len());
let location = DebugLocationHolder {
program: *program_value,
scope: scope_value.clone(),
value: value.clone(),
location,
};
@ -144,21 +107,60 @@ impl DebugInformation {
let mut metadata = self.metadata.borrow_mut();
let value = DebugMetadataValue(metadata.len());
metadata.push(DebugMetadataHolder {
location: *location,
location: location.clone(),
value: value.clone(),
data: kind,
});
value
}
pub fn subprogram(&self, kind: DebugSubprogramData) -> DebugProgramValue {
let mut subprogram = self.programs.borrow_mut();
let value = DebugProgramValue(subprogram.len() + 1);
subprogram.push(DebugSubprogramHolder {
_value: value.clone(),
data: kind,
});
value
pub fn subprogram(&self, parent: DebugScopeValue, kind: DebugSubprogramData) -> DebugScopeValue {
unsafe {
let mut outer_scope = RefMut::map(self.scope.borrow_mut(), |mut v| {
for i in &parent.0 {
v = v.inner_scopes.get_unchecked_mut(*i);
}
v
});
let mut arr = parent.0.clone();
arr.push(outer_scope.inner_scopes.len());
let value = DebugScopeValue(arr);
outer_scope.inner_scopes.push(DebugScopeHolder {
value: value.clone(),
inner_scopes: Vec::new(),
data: DebugScopeData {
parent: Some(parent.clone()),
kind: DebugScopeKind::Subprogram(kind),
},
});
value
}
}
pub fn lexical_scope(&self, parent: &DebugScopeValue, data: DebugLexicalScope) -> DebugScopeValue {
unsafe {
let mut outer_scope = RefMut::map(self.scope.borrow_mut(), |mut v| {
for i in &parent.0 {
v = v.inner_scopes.get_unchecked_mut(*i);
}
v
});
let mut arr = parent.0.clone();
arr.push(outer_scope.inner_scopes.len());
let value = DebugScopeValue(arr);
outer_scope.inner_scopes.push(DebugScopeHolder {
value: value.clone(),
inner_scopes: Vec::new(),
data: DebugScopeData {
parent: Some(parent.clone()),
kind: DebugScopeKind::LexicalScope(data),
},
});
value
}
}
pub fn get_metadata(&self, value: DebugMetadataValue) -> DebugMetadata {
@ -166,14 +168,24 @@ impl DebugInformation {
}
pub fn get_metadata_location(&self, value: DebugMetadataValue) -> DebugLocation {
unsafe { self.metadata.borrow().get_unchecked(value.0).location }
unsafe { self.metadata.borrow().get_unchecked(value.0).location.clone() }
}
pub fn get_subprogram_data(&self, value: DebugProgramValue) -> Option<DebugSubprogramData> {
if value.0 == 0 {
None
pub fn get_scope_data(&self, value: &DebugScopeValue) -> Option<DebugScopeData> {
let scope = Ref::filter_map(self.scope.borrow(), |v: &DebugScopeHolder| {
let mut opt = Some(v);
for i in &value.0 {
if let Some(inner) = opt {
opt = inner.inner_scopes.get(*i);
}
}
opt
});
if let Ok(scope) = scope {
Some(scope.data.clone())
} else {
Some(self.get_subprogram_data_unchecked(&value))
None
}
}
@ -181,26 +193,16 @@ impl DebugInformation {
unsafe { self.types.borrow().get_unchecked(value.0).data.clone() }
}
pub fn get_location(&self, value: DebugLocationValue) -> DebugLocation {
unsafe {
self.locations
.borrow()
.get_unchecked(value.1)
.location
.clone()
}
pub fn get_location(&self, value: &DebugLocationValue) -> DebugLocation {
unsafe { self.locations.borrow().get_unchecked(value.1).location.clone() }
}
pub fn get_metadatas(&self) -> Rc<RefCell<Vec<DebugMetadataHolder>>> {
self.metadata.clone()
}
// pub fn get_scopes(&self) -> Rc<RefCell<DebugScopeHolder>> {
// self.scope.clone()
// }
pub fn get_subprograms(&self) -> Rc<RefCell<Vec<DebugSubprogramHolder>>> {
self.programs.clone()
pub(crate) fn get_scope(&self) -> Rc<RefCell<DebugScopeHolder>> {
self.scope.clone()
}
pub fn get_types(&self) -> Rc<RefCell<Vec<DebugTypeHolder>>> {
@ -210,21 +212,11 @@ impl DebugInformation {
pub(crate) fn get_locations(&self) -> Rc<RefCell<Vec<DebugLocationHolder>>> {
self.locations.clone()
}
pub fn get_subprogram_data_unchecked(&self, value: &DebugProgramValue) -> DebugSubprogramData {
unsafe {
self.programs
.borrow()
.get_unchecked(value.0 - 1)
.data
.clone()
}
}
}
#[derive(Clone, Copy)]
#[derive(Clone)]
pub struct DebugLocation {
pub scope: DebugProgramValue,
pub scope: DebugScopeValue,
pub pos: DebugPosition,
}
@ -315,7 +307,7 @@ pub struct DebugPointerType {
#[derive(Clone)]
pub struct DebugStructType {
pub name: String,
pub scope: DebugProgramValue,
pub scope: DebugScopeValue,
pub pos: Option<DebugPosition>,
pub size_bits: u64,
pub flags: DwarfFlags,
@ -325,7 +317,7 @@ pub struct DebugStructType {
#[derive(Clone)]
pub struct DebugFieldType {
pub name: String,
pub scope: DebugProgramValue,
pub scope: DebugScopeValue,
pub pos: Option<DebugPosition>,
pub size_bits: u64,
pub offset: u64,
@ -350,11 +342,29 @@ pub enum DwarfEncoding {
UnsignedChar = 8,
}
#[derive(Debug, Clone)]
pub struct DebugScopeData {
pub parent: Option<DebugScopeValue>,
pub kind: DebugScopeKind,
}
#[derive(Debug, Clone)]
pub enum DebugScopeKind {
CodegenContext,
LexicalScope(DebugLexicalScope),
Subprogram(DebugSubprogramData),
}
#[derive(Debug, Clone)]
pub struct DebugLexicalScope {
pub location: DebugLocation,
}
#[derive(Debug, Clone)]
pub struct DebugSubprogramData {
/// Function name.
pub name: String,
pub outer_scope: DebugProgramValue,
pub outer_scope: DebugScopeValue,
/// Used for line number.
pub location: DebugLocation,
/// Function type.
@ -376,7 +386,7 @@ pub struct DebugSubprogramOptionals {
#[derive(Clone)]
pub struct InstructionDebugRecordData {
pub scope: DebugProgramValue,
pub scope: DebugScopeValue,
pub variable: DebugMetadataValue,
pub location: DebugLocation,
pub kind: DebugRecordKind,

View File

@ -11,8 +11,8 @@ use crate::{
debug_information::{
DebugArrayType, DebugBasicType, DebugFieldType, DebugInformation, DebugLocalVariable, DebugLocation,
DebugLocationValue, DebugMetadata, DebugMetadataValue, DebugParamVariable, DebugPointerType, DebugPosition,
DebugProgramValue, DebugRecordKind, DebugScopeValue, DebugStructType, DebugSubprogramType, DebugTypeData,
DebugTypeHolder, DebugTypeValue,
DebugRecordKind, DebugScopeValue, DebugStructType, DebugSubprogramType, DebugTypeData, DebugTypeHolder,
DebugTypeValue,
},
pad_adapter::PadAdapter,
};
@ -74,7 +74,7 @@ impl FunctionHolder {
let mut state = Default::default();
let mut inner = PadAdapter::wrap(f, &mut state);
writeln!(inner, "(Value = {:?}) ", self.value)?;
if let Some(debug) = self.data.debug {
if let Some(debug) = &self.debug_info {
writeln!(inner, "(Debug = {:?})", debug)?;
}
@ -111,7 +111,7 @@ impl BlockHolder {
if let Some(terminator) = &self.data.terminator {
terminator.builder_fmt(&mut inner, builder, debug)?;
}
if let Some(location) = self.data.terminator_location {
if let Some(location) = &self.data.terminator_location {
writeln!(inner, " ^ (At {}) ", debug.as_ref().unwrap().get_location(location))?;
}
@ -142,7 +142,7 @@ impl InstructionHolder {
}
writeln!(f, "{:?} ({}) = {:?} ", self.value, self.name, self.data.kind)?;
if let Some(debug) = debug {
if let Some(location) = self.data.location {
if let Some(location) = &self.data.location {
writeln!(f, " ^ (At {}) ", debug.get_location(location))?;
}
if let Some(meta) = self.data.meta {
@ -261,7 +261,7 @@ impl Debug for InstructionHolder {
impl Debug for InstructionData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.kind.fmt(f)?;
if let Some(location) = self.location {
if let Some(location) = &self.location {
write!(f, " ({:?})", location)?;
}
Ok(())
@ -574,12 +574,6 @@ impl Debug for DebugTypeValue {
}
}
impl Debug for DebugProgramValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Subprogram[{}]", self.0)
}
}
impl Debug for DebugLocationValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Value[{:?}][{}]", self.0, self.1)

View File

@ -5,9 +5,11 @@
use std::{fmt::Debug, marker::PhantomData};
use builder::{BlockValue, Builder, FunctionValue, InstructionValue, ModuleValue, TypeValue};
use debug_information::{DebugFileData, DebugInformation, DebugLocationValue, DebugMetadataValue, DebugProgramValue};
use debug_information::{DebugFileData, DebugInformation, DebugLocationValue, DebugMetadataValue};
use fmt::PrintableModule;
use crate::debug_information::DebugScopeValue;
pub mod builder;
pub mod compile;
pub mod debug_information;
@ -76,7 +78,6 @@ impl<'ctx> Module<'ctx> {
ret,
params,
flags,
debug: None,
},
),
}
@ -103,10 +104,10 @@ impl<'ctx> Module<'ctx> {
}
}
pub fn create_debug_info(&mut self, file: DebugFileData) -> (DebugInformation, DebugProgramValue) {
let (debug_info, program_value) = DebugInformation::from_file(file);
pub fn create_debug_info(&mut self, file: DebugFileData) -> (DebugInformation, DebugScopeValue) {
let (debug_info, scope_value) = DebugInformation::from_file(file);
self.debug_info = Some(debug_info.clone());
(debug_info, program_value)
(debug_info, scope_value)
}
pub fn get_debug_info(&self) -> &Option<DebugInformation> {
@ -128,7 +129,6 @@ pub struct FunctionData {
ret: Type,
params: Vec<Type>,
flags: FunctionFlags,
debug: Option<DebugProgramValue>,
}
#[derive(Debug, Clone, Copy, Hash)]
@ -184,7 +184,7 @@ impl<'ctx> Function<'ctx> {
}
}
pub fn set_debug(&self, subprogram: DebugProgramValue) {
pub fn set_debug(&self, subprogram: DebugScopeValue) {
unsafe {
self.builder.set_debug_subprogram(&self.value, subprogram);
}
@ -546,7 +546,7 @@ impl ConstValue {
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
enum TypeCategory {
pub enum TypeCategory {
SignedInteger,
UnsignedInteger,
Void,

View File

@ -122,8 +122,8 @@ pub enum BinaryOperator {
And,
Or,
Xor,
BWAnd,
BWOr,
BitAnd,
BitOr,
LT,
LE,
GT,
@ -141,9 +141,8 @@ impl BinaryOperator {
Mult => 15,
Div => 20,
Mod => 20,
BWAnd => 90,
BWOr => 90,
BWXor => 90,
BitAnd => 90,
BitOr => 90,
BitshiftLeft => 100,
BitshiftRight => 100,
And => 150,

View File

@ -518,8 +518,8 @@ impl Parse for BinaryOperator {
}
(Some(Token::Hat), _) => BinaryOperator::Xor,
(Some(Token::Et), _) => BinaryOperator::BWAnd,
(Some(Token::Pipe), _) => BinaryOperator::BWOr,
(Some(Token::Et), _) => BinaryOperator::BitAnd,
(Some(Token::Pipe), _) => BinaryOperator::BitOr,
(Some(Token::LessThan), _) => BinaryOperator::LT,
(Some(Token::GreaterThan), _) => BinaryOperator::GT,

View File

@ -459,8 +459,8 @@ impl ast::BinaryOperator {
ast::BinaryOperator::BitshiftRight => mir::BinaryOperator::BitshiftRight,
ast::BinaryOperator::BitshiftLeft => mir::BinaryOperator::BitshiftLeft,
ast::BinaryOperator::Xor => mir::BinaryOperator::Xor,
ast::BinaryOperator::BWAnd => mir::BinaryOperator::BitAnd,
ast::BinaryOperator::BWOr => mir::BinaryOperator::BitOr,
ast::BinaryOperator::BitAnd => mir::BinaryOperator::BitAnd,
ast::BinaryOperator::BitOr => mir::BinaryOperator::BitOr,
}
}
}

View File

@ -1,5 +1,3 @@
use std::ops::BitAnd;
use reid_lib::{builder::InstructionValue, CmpPredicate, ConstValue, Instr, Type};
use crate::{

View File

@ -5,8 +5,9 @@ use intrinsics::*;
use reid_lib::{
compile::CompiledModule,
debug_information::{
DebugFileData, DebugLocalVariable, DebugLocation, DebugMetadata, DebugRecordKind, DebugSubprogramData,
DebugSubprogramOptionals, DebugSubprogramType, DebugTypeData, DwarfFlags, InstructionDebugRecordData,
DebugFileData, DebugLexicalScope, DebugLocalVariable, DebugLocation, DebugMetadata, DebugRecordKind,
DebugSubprogramData, DebugSubprogramOptionals, DebugSubprogramType, DebugTypeData, DwarfFlags,
InstructionDebugRecordData,
},
CmpPredicate, ConstValue, Context, CustomTypeKind, Function, FunctionFlags, Instr, Module, NamedStruct,
TerminatorKind as Term, Type,
@ -124,7 +125,7 @@ impl mir::Module {
debug_types.insert(
$kind.clone(),
$kind.get_debug_type_hard(
compile_unit,
&compile_unit,
&debug,
&debug_types,
&type_values,
@ -279,7 +280,6 @@ impl mir::Module {
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,
is_pub: binop.exported,
is_imported: binop.exported,
..Default::default()
@ -311,7 +311,7 @@ impl mir::Module {
stack_values: HashMap::new(),
debug: Some(Debug {
info: &debug,
scope: compile_unit,
scope: compile_unit.clone(),
types: &debug_types,
}),
binops: &binops,
@ -328,7 +328,9 @@ impl mir::Module {
&binop.return_type,
&ir_function,
match &binop.fn_kind {
FunctionDefinitionKind::Local(_, meta) => meta.into_debug(tokens, compile_unit),
FunctionDefinitionKind::Local(_, meta) => {
meta.into_debug(tokens, &compile_unit)
}
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
},
@ -383,7 +385,7 @@ impl mir::Module {
stack_values: HashMap::new(),
debug: Some(Debug {
info: &debug,
scope: compile_unit,
scope: compile_unit.clone(),
types: &debug_types,
}),
binops: &binops,
@ -401,7 +403,7 @@ impl mir::Module {
&function,
match &mir_function.kind {
FunctionDefinitionKind::Local(..) => {
mir_function.signature().into_debug(tokens, compile_unit)
mir_function.signature().into_debug(tokens, &compile_unit)
}
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
@ -442,7 +444,7 @@ impl mir::Module {
stack_values: HashMap::new(),
debug: Some(Debug {
info: &debug,
scope: compile_unit,
scope: compile_unit.clone(),
types: &debug_types,
}),
binops: &binops,
@ -460,7 +462,7 @@ impl mir::Module {
&function,
match &mir_function.kind {
FunctionDefinitionKind::Local(..) => {
mir_function.signature().into_debug(tokens, compile_unit)
mir_function.signature().into_debug(tokens, &compile_unit)
}
FunctionDefinitionKind::Extern(_) => None,
FunctionDefinitionKind::Intrinsic(_) => None,
@ -499,22 +501,25 @@ impl FunctionDefinitionKind {
flags: DwarfFlags,
}));
let subprogram = debug.info.subprogram(DebugSubprogramData {
name: name.clone(),
outer_scope: debug.scope.clone(),
location,
ty: debug_ty,
opts: DebugSubprogramOptionals {
is_local: !is_pub,
is_definition: true,
..DebugSubprogramOptionals::default()
let subprogram = debug.info.subprogram(
debug.scope.clone(),
DebugSubprogramData {
name: name.clone(),
outer_scope: debug.scope.clone(),
location,
ty: debug_ty,
opts: DebugSubprogramOptionals {
is_local: !is_pub,
is_definition: true,
..DebugSubprogramOptionals::default()
},
},
});
);
ir_function.set_debug(subprogram);
ir_function.set_debug(subprogram.clone());
scope.debug = Some(Debug {
info: debug.info,
scope: subprogram,
scope: subprogram.clone(),
types: debug.types,
});
}
@ -542,36 +547,10 @@ impl FunctionDefinitionKind {
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)? {
if let Some(ret) = block.codegen(scope, &state, false)? {
scope.block.terminate(Term::Ret(ret.instr())).unwrap();
} else {
if !scope.block.delete_if_unused().unwrap() {
@ -582,8 +561,8 @@ impl FunctionDefinitionKind {
}
if let Some(debug) = &scope.debug {
if let Some(location) = &block.return_meta().into_debug(scope.tokens, debug.scope) {
let location = debug.info.location(&debug.scope, *location);
if let Some(location) = &block.return_meta().into_debug(scope.tokens, &debug.scope) {
let location = debug.info.location(&debug.scope, location.clone());
scope.block.set_terminator_location(location).unwrap();
}
}
@ -600,18 +579,31 @@ impl mir::Block {
&self,
mut scope: &mut Scope<'ctx, 'a>,
state: &State,
create_debug_scope: bool,
) -> Result<Option<StackValue>, ErrorKind> {
let parent_scope = if let Some(debug) = &mut scope.debug {
let parent_scope = debug.scope.clone();
if create_debug_scope {
let location = self.meta.into_debug(scope.tokens, &debug.scope).unwrap();
let scope = debug.info.lexical_scope(&debug.scope, DebugLexicalScope { location });
debug.scope = scope;
}
Some(parent_scope)
} else {
None
};
for stmt in &self.statements {
stmt.codegen(&mut scope, state)?.map(|s| {
if let Some(debug) = &scope.debug {
let location = stmt.1.into_debug(scope.tokens, debug.scope).unwrap();
let location = stmt.1.into_debug(scope.tokens, &debug.scope).unwrap();
let loc_val = debug.info.location(&debug.scope, location);
s.instr().with_location(&mut scope.block, loc_val);
}
});
}
if let Some((kind, expr)) = &self.return_expression {
let return_value = if let Some((kind, expr)) = &self.return_expression {
if let Some(expr) = expr {
let ret = expr.codegen(&mut scope, &mut state.load(true))?;
match kind {
@ -634,14 +626,20 @@ impl mir::Block {
}
} else {
Ok(None)
};
if let Some(parent_scope) = parent_scope {
scope.debug.as_mut().unwrap().scope = parent_scope;
}
return_value
}
}
impl mir::Statement {
fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>, state: &State) -> Result<Option<StackValue>, ErrorKind> {
let location = scope.debug.clone().map(|d| {
let location = self.1.into_debug(scope.tokens, d.scope).unwrap();
let location = self.1.into_debug(scope.tokens, &d.scope).unwrap();
d.info.location(&d.scope, location)
});
@ -652,7 +650,7 @@ impl mir::Statement {
let alloca = scope
.allocate(name, &value.1)
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
let store = scope
.block
@ -670,7 +668,7 @@ impl mir::Statement {
StackValue(stack_value, TypeKind::CodegenPtr(Box::new(value.clone().1))),
);
if let Some(debug) = &scope.debug {
let location = self.1.into_debug(scope.tokens, debug.scope).unwrap();
let location = self.1.into_debug(scope.tokens, &debug.scope).unwrap();
let var = debug.info.metadata(
&location,
DebugMetadata::LocalVar(DebugLocalVariable {
@ -686,7 +684,7 @@ impl mir::Statement {
variable: var,
location,
kind: DebugRecordKind::Declare(alloca),
scope: debug.scope,
scope: debug.scope.clone(),
},
);
}
@ -755,7 +753,7 @@ impl mir::Statement {
.unwrap();
let mut condition_true_scope = scope.with_block(condition_true_block);
block.codegen(&mut condition_true_scope, state)?;
block.codegen(&mut condition_true_scope, state, true)?;
condition_true_scope
.block
@ -777,7 +775,7 @@ impl mir::Expression {
Some(
debug
.info
.location(&debug.scope, self.1.into_debug(scope.tokens, debug.scope).unwrap()),
.location(&debug.scope, self.1.into_debug(scope.tokens, &debug.scope).unwrap()),
)
} else {
None
@ -851,12 +849,12 @@ impl mir::Expression {
.block
.build(Instr::UDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Mod, true, false) => {
@ -864,12 +862,12 @@ impl mir::Expression {
.block
.build(Instr::SDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Mod, _, true) => {
@ -877,12 +875,12 @@ impl mir::Expression {
.block
.build(Instr::FDiv(lhs, rhs))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
let mul = scope
.block
.build(Instr::Mul(rhs, div))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
Instr::Sub(lhs, mul)
}
(mir::BinaryOperator::Or, true, true) => todo!(),
@ -916,7 +914,7 @@ impl mir::Expression {
.block
.build(instr)
.unwrap()
.maybe_location(&mut scope.block, location),
.maybe_location(&mut scope.block, location.clone()),
),
return_ty.clone(),
))
@ -929,7 +927,7 @@ impl mir::Expression {
scope.block.terminate(Term::Br(inner.value())).unwrap();
let mut inner_scope = scope.with_block(inner);
let ret = if let Some(ret) = block.codegen(&mut inner_scope, state)? {
let ret = if let Some(ret) = block.codegen(&mut inner_scope, state, true)? {
Some(ret)
} else {
None
@ -962,7 +960,7 @@ impl mir::Expression {
.block
.build_named(format!("gep"), Instr::GetElemPtr(loaded, vec![idx]))
.unwrap()
.maybe_location(&mut scope.block, location),
.maybe_location(&mut scope.block, location.clone()),
*further_inner,
)
} else if let TypeKind::CodegenPtr(further_inner) = *inner.clone() {
@ -975,7 +973,7 @@ impl mir::Expression {
.block
.build_named(format!("array.gep"), Instr::GetElemPtr(kind.instr(), vec![idx]))
.unwrap()
.maybe_location(&mut scope.block, location),
.maybe_location(&mut scope.block, location.clone()),
val_t.clone(),
)
} else {
@ -992,7 +990,7 @@ impl mir::Expression {
.block
.build_named(format!("array.gep"), Instr::GetElemPtr(kind.instr(), vec![first, idx]))
.unwrap()
.maybe_location(&mut scope.block, location),
.maybe_location(&mut scope.block, location.clone()),
val_t.clone(),
)
};
@ -1004,7 +1002,7 @@ impl mir::Expression {
.block
.build_named("array.load", Instr::Load(ptr, contained_ty.get_type(scope.type_values)))
.unwrap()
.maybe_location(&mut scope.block, location),
.maybe_location(&mut scope.block, location.clone()),
),
contained_ty,
))
@ -1042,7 +1040,7 @@ impl mir::Expression {
.block
.build_named(&array_name, Instr::Alloca(array_ty.clone()))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
for (index, instr) in instr_list.iter().enumerate() {
let gep_n = format!("{}.{}.gep", array_name, index);
@ -1060,19 +1058,19 @@ impl mir::Expression {
.block
.build_named(gep_n, Instr::GetElemPtr(array, vec![first, index_expr]))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
scope
.block
.build_named(store_n, Instr::Store(ptr, *instr))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
}
let array_val = scope
.block
.build_named(load_n, Instr::Load(array, array_ty))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
Some(StackValue(
StackValueKind::Literal(array_val),
@ -1140,7 +1138,7 @@ impl mir::Expression {
.block
.build_named(name, Instr::Alloca(ty.clone()))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
for (field_n, exp) in items {
let gep_n = format!("{}.{}.gep", name, field_n);
@ -1151,13 +1149,13 @@ impl mir::Expression {
.block
.build_named(gep_n, Instr::GetStructElemPtr(struct_ptr, i as u32))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
if let Some(val) = exp.codegen(scope, state)? {
scope
.block
.build_named(store_n, Instr::Store(elem_ptr, val.instr()))
.unwrap()
.maybe_location(&mut scope.block, location);
.maybe_location(&mut scope.block, location.clone());
}
}
@ -1277,7 +1275,7 @@ impl mir::Expression {
mir::ExprKind::AssociatedFunctionCall(ty, call) => codegen_function_call(Some(ty), call, scope, state)?,
};
if let Some(value) = &value {
value.instr().maybe_location(&mut scope.block, location);
value.instr().maybe_location(&mut scope.block, location.clone());
}
Ok(value)
}
@ -1310,7 +1308,7 @@ fn codegen_function_call<'ctx, 'a>(
.collect::<Vec<_>>();
let location = if let Some(debug) = &scope.debug {
call.meta.into_debug(scope.tokens, debug.scope)
call.meta.into_debug(scope.tokens, &debug.scope)
} else {
None
};
@ -1393,16 +1391,16 @@ impl mir::IfExpression {
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();
let before_location = self.0 .1.into_debug(scope.tokens, &debug.scope).unwrap();
let before_v = debug.info.location(&debug.scope, before_location);
scope.block.set_terminator_location(before_v).ok();
let then_location = self.1 .1.into_debug(scope.tokens, debug.scope).unwrap();
let then_v = debug.info.location(&debug.scope, then_location);
let then_location = self.1 .1.into_debug(scope.tokens, &debug.scope).unwrap();
let then_v = debug.info.location(&debug.scope, then_location.clone());
then_b.set_terminator_location(then_v).unwrap();
let else_location = if let Some(else_expr) = self.2.as_ref() {
else_expr.1.into_debug(scope.tokens, debug.scope).unwrap()
else_expr.1.into_debug(scope.tokens, &debug.scope).unwrap()
} else {
then_location
};

View File

@ -2,7 +2,7 @@ use std::{cell::RefCell, collections::HashMap, mem, rc::Rc};
use reid_lib::{
builder::{InstructionValue, TypeValue},
debug_information::{DebugInformation, DebugLocation, DebugProgramValue, DebugTypeValue},
debug_information::{DebugInformation, DebugLocation, DebugScopeValue, DebugTypeValue},
Block, Context, Function, Instr, Module,
};
@ -75,7 +75,7 @@ impl<'ctx, 'a> Scope<'ctx, 'a> {
#[derive(Debug, Clone)]
pub struct Debug<'ctx> {
pub(super) info: &'ctx DebugInformation,
pub(super) scope: DebugProgramValue,
pub(super) scope: DebugScopeValue,
pub(super) types: &'ctx HashMap<TypeKind, DebugTypeValue>,
}

View File

@ -3,19 +3,15 @@ use std::collections::HashMap;
use reid_lib::{
builder::{InstructionValue, TypeValue},
debug_information::{
DebugArrayType, DebugBasicType, DebugFieldType, DebugInformation, DebugLocation,
DebugPointerType, DebugPosition, DebugProgramValue, DebugStructType, DebugTypeData,
DebugTypeValue, DwarfEncoding, DwarfFlags,
DebugArrayType, DebugBasicType, DebugFieldType, DebugInformation, DebugLocation, DebugPointerType,
DebugPosition, DebugScopeValue, DebugStructType, DebugTypeData, DebugTypeValue, DwarfEncoding, DwarfFlags,
},
Block, CmpPredicate, ConstValue, Instr, Type,
};
use crate::{
lexer::{FullToken, Position},
mir::{
self, CustomTypeKey, Metadata, SourceModuleId, TypeDefinition, TypeDefinitionKind,
TypeKind, VagueLiteral,
},
mir::{self, CustomTypeKey, Metadata, SourceModuleId, TypeDefinition, TypeDefinitionKind, TypeKind, VagueLiteral},
};
use super::{
@ -38,9 +34,7 @@ impl mir::CmpOperator {
impl mir::Literal {
pub(super) fn as_const(&self, block: &mut Block) -> InstructionValue {
block
.build_named(format!("{}", self), self.as_const_kind())
.unwrap()
block.build_named(format!("{}", self), self.as_const_kind()).unwrap()
}
pub(super) fn as_const_kind(&self) -> Instr {
@ -110,7 +104,7 @@ impl TypeKind {
impl TypeKind {
pub(super) fn get_debug_type(&self, debug: &Debug, scope: &Scope) -> DebugTypeValue {
self.get_debug_type_hard(
debug.scope,
&debug.scope,
debug.info,
debug.types,
scope.type_values,
@ -123,7 +117,7 @@ impl TypeKind {
pub(super) fn get_debug_type_hard(
&self,
scope: DebugProgramValue,
scope: &DebugScopeValue,
debug_info: &DebugInformation,
debug_types: &HashMap<TypeKind, DebugTypeValue>,
type_values: &HashMap<CustomTypeKey, TypeValue>,
@ -184,11 +178,11 @@ impl TypeKind {
let location = if typedef.source_module != local_mod {
None
} else {
field.2.into_debug(&tokens, scope)
field.2.into_debug(&tokens, &scope)
};
fields.push(DebugFieldType {
name: field.0.clone(),
scope,
scope: scope.clone(),
pos: location.map(|l| l.pos),
size_bits: field.1.size_of(),
offset: size_bits,
@ -214,7 +208,7 @@ impl TypeKind {
};
DebugTypeData::Struct(DebugStructType {
name: key.0.clone(),
scope,
scope: scope.clone(),
pos: location.map(|l| l.pos),
size_bits,
flags: DwarfFlags,
@ -231,12 +225,8 @@ impl TypeKind {
TypeKind::Bool => DwarfEncoding::Boolean,
TypeKind::I8 => DwarfEncoding::SignedChar,
TypeKind::U8 => DwarfEncoding::UnsignedChar,
TypeKind::I16 | TypeKind::I32 | TypeKind::I64 | TypeKind::I128 => {
DwarfEncoding::Signed
}
TypeKind::U16 | TypeKind::U32 | TypeKind::U64 | TypeKind::U128 => {
DwarfEncoding::Unsigned
}
TypeKind::I16 | TypeKind::I32 | TypeKind::I64 | TypeKind::I128 => DwarfEncoding::Signed,
TypeKind::U16 | TypeKind::U32 | TypeKind::U64 | TypeKind::U128 => DwarfEncoding::Unsigned,
TypeKind::F16
| TypeKind::F32
| TypeKind::F32B
@ -258,13 +248,9 @@ impl TypeKind {
}
impl Metadata {
pub(super) fn into_debug(
&self,
tokens: &Vec<FullToken>,
scope: DebugProgramValue,
) -> Option<DebugLocation> {
pub(super) fn into_debug(&self, tokens: &Vec<FullToken>, scope: &DebugScopeValue) -> Option<DebugLocation> {
if let Some((start, _)) = self.into_positions(tokens) {
Some(start.debug(scope))
Some(start.debug(scope.clone()))
} else {
None
}
@ -272,7 +258,7 @@ impl Metadata {
}
impl Position {
pub(super) fn debug(self, scope: DebugProgramValue) -> DebugLocation {
pub(super) fn debug(self, scope: DebugScopeValue) -> DebugLocation {
DebugLocation {
pos: DebugPosition {
line: self.1,

View File

@ -1,3 +1,5 @@
use std::collections::HashSet;
use crate::mir::VagueType as Vague;
use crate::mir::*;
use typecheck::ErrorTypedefKind;
@ -291,7 +293,7 @@ impl TypeKind {
pub(super) fn resolve_weak(&self, refs: &TypeRefs) -> TypeKind {
match self {
TypeKind::Vague(Vague::TypeRef(idx)) => refs.retrieve_wide_type(*idx).unwrap(),
TypeKind::Vague(Vague::TypeRef(idx)) => refs.retrieve_wide_type(*idx, &mut HashSet::new()).unwrap(),
_ => self.clone(),
}
}

View File

@ -1,6 +1,6 @@
//! This module contains code relevant to doing a type checking pass on the MIR.
//! During typechecking relevant types are also coerced if possible.
use std::{collections::HashSet, convert::Infallible, hint, iter};
use std::{collections::HashSet, convert::Infallible, iter};
use crate::{mir::*, util::try_all};
use VagueType as Vague;
@ -415,7 +415,6 @@ impl Expression {
// First find unfiltered parameters to binop
let lhs_res = lhs.typecheck(state, &typerefs, HintKind::None);
let rhs_res = rhs.typecheck(state, &typerefs, HintKind::None);
dbg!(&lhs_res, &rhs_res, &ret_ty);
let lhs_type = state.or_else(lhs_res, TypeKind::Vague(Vague::Unknown), lhs.1);
let rhs_type = state.or_else(rhs_res, TypeKind::Vague(Vague::Unknown), rhs.1);
@ -433,8 +432,6 @@ impl Expression {
operator: *op,
});
dbg!(&binops);
// dbg!(&lhs_type, &rhs_type, &binops, &ret_ty, &expected_return_ty);
if let Some(binop) = binops
.iter()
.filter(|f| f.1.return_ty.narrow_into(&expected_return_ty).is_ok())
@ -753,9 +750,7 @@ impl Expression {
.into_iter()
.chain(iter::repeat(TypeKind::Vague(Vague::Unknown)));
for (i, (param, true_param_t)) in
function_call.parameters.iter_mut().zip(true_params_iter).enumerate()
{
for (param, true_param_t) in function_call.parameters.iter_mut().zip(true_params_iter) {
// Typecheck every param separately
let param_res = param.typecheck(state, &typerefs, HintKind::Coerce(true_param_t.clone()));
let param_t = state.or_else(param_res, TypeKind::Vague(Vague::Unknown), param.1);

View File

@ -285,7 +285,7 @@ impl Block {
let rhs_ref = state.ok(rhs_infer, rhs.1);
// Try to narrow the lhs with rhs
if let (Some(mut lhs_ref), Some(mut rhs_ref)) = (lhs_ref, rhs_ref) {
if let (Some(lhs_ref), Some(mut rhs_ref)) = (lhs_ref, rhs_ref) {
rhs_ref.narrow(&lhs_ref);
}
}

View File

@ -15,7 +15,7 @@ impl<'scope> TypeRef<'scope> {
/// Resolve current type in a weak manner, not resolving any Arrays or
/// further inner types
pub fn resolve_weak(&self) -> Option<TypeKind> {
Some(self.1.types.retrieve_wide_type(*self.0.borrow())?)
Some(self.1.types.retrieve_wide_type(*self.0.borrow(), &mut HashSet::new())?)
}
/// Resolve type deeply, trying to resolve any inner types as well.
@ -62,17 +62,16 @@ pub enum TypeRefKind {
}
impl TypeRefKind {
pub fn widen(&self, types: &TypeRefs) -> TypeKind {
pub fn widen(&self, types: &TypeRefs, seen: &mut HashSet<usize>) -> TypeKind {
match self {
TypeRefKind::BinOp(op, lhs, rhs) => {
let lhs_resolved = types.cut_recursion(lhs, seen).resolve_ref(types);
let rhs_resolved = types.cut_recursion(rhs, seen).resolve_ref(types);
let mut binops = types
.binop_types
.iter()
.filter(|b| b.1.operator == *op)
.map(|b| {
b.1.narrow(&lhs.resolve_ref(types), &rhs.resolve_ref(types))
.map(|b| b.2)
})
.map(|b| b.1.narrow(&lhs_resolved, &rhs_resolved).map(|b| b.2))
.filter_map(|s| s);
if let Some(mut ty) = binops.next() {
while let Some(other) = binops.next() {
@ -84,7 +83,7 @@ impl TypeRefKind {
}
}
TypeRefKind::Direct(ty) => match ty {
TypeKind::Vague(VagueType::TypeRef(id)) => types.retrieve_wide_type(*id).unwrap(),
TypeKind::Vague(VagueType::TypeRef(id)) => types.retrieve_wide_type(*id, seen).unwrap(),
_ => ty.clone(),
},
}
@ -110,7 +109,7 @@ impl std::fmt::Display for TypeRefs {
i,
unsafe { *self.recurse_type_ref(idx).borrow() },
self.retrieve_typeref(idx),
self.retrieve_wide_type(idx),
self.retrieve_wide_type(idx, &mut HashSet::new()),
)?;
}
Ok(())
@ -182,8 +181,35 @@ impl TypeRefs {
self.hints.borrow().get(inner_idx).cloned()
}
pub fn retrieve_wide_type(&self, idx: usize) -> Option<TypeKind> {
self.retrieve_typeref(idx).map(|t| t.widen(self))
pub fn retrieve_wide_type(&self, idx: usize, seen: &mut HashSet<usize>) -> Option<TypeKind> {
self.retrieve_typeref(idx).map(|t| t.widen(self, seen))
}
pub fn cut_recursion_weak<'s>(&self, idx: usize, seen: &mut HashSet<usize>) -> Option<TypeRefKind> {
if seen.insert(idx) {
self.retrieve_typeref(idx)
} else {
None
}
}
pub(super) fn cut_recursion(&self, kind: &TypeKind, seen: &mut HashSet<usize>) -> TypeKind {
match kind {
TypeKind::Array(type_kind, len) => TypeKind::Array(Box::new(self.cut_recursion(&type_kind, seen)), *len),
TypeKind::Borrow(type_kind, mutable) => {
TypeKind::Borrow(Box::new(self.cut_recursion(&type_kind, seen)), *mutable)
}
TypeKind::UserPtr(type_kind) => TypeKind::UserPtr(Box::new(self.cut_recursion(&type_kind, seen))),
TypeKind::CodegenPtr(type_kind) => TypeKind::CodegenPtr(Box::new(self.cut_recursion(&type_kind, seen))),
TypeKind::Vague(VagueType::TypeRef(idx)) => {
if let Some(tyref) = self.cut_recursion_weak(*idx, seen) {
tyref.widen(self, seen)
} else {
TypeKind::Vague(VagueType::Unknown)
}
}
_ => kind.clone(),
}
}
}
@ -329,7 +355,7 @@ impl<'outer> ScopeTypeRefs<'outer> {
.borrow()
.get_unchecked(*hint2.0.borrow())
.clone()
.widen(self.types);
.widen(self.types, &mut HashSet::new());
self.narrow_to_type(&hint1, &ty)?;
let hint1_typeref = self.types.retrieve_typeref(*hint1.0.borrow()).unwrap();
let hint2_typeref = self.types.retrieve_typeref(*hint2.0.borrow()).unwrap();
@ -357,10 +383,22 @@ impl<'outer> ScopeTypeRefs<'outer> {
}
}
(TypeRefKind::BinOp(_, lhs1, rhs1), TypeRefKind::BinOp(_, lhs2, rhs2)) => {
let mut lhs_ref = self.from_type(&lhs1).unwrap();
let mut rhs_ref = self.from_type(&rhs1).unwrap();
lhs_ref.narrow(&self.from_type(&lhs2).unwrap());
rhs_ref.narrow(&self.from_type(&rhs2).unwrap());
let mut lhs_ref = self
.from_type(&self.types.cut_recursion(lhs1, &mut HashSet::new()))
.unwrap();
let mut rhs_ref = self
.from_type(&self.types.cut_recursion(rhs1, &mut HashSet::new()))
.unwrap();
lhs_ref.narrow(
&self
.from_type(&self.types.cut_recursion(lhs2, &mut HashSet::new()))
.unwrap(),
);
rhs_ref.narrow(
&self
.from_type(&self.types.cut_recursion(rhs2, &mut HashSet::new()))
.unwrap(),
);
}
_ => {}
}