Skip to content

Commit

Permalink
fix: show error when recursive type occurs
Browse files Browse the repository at this point in the history
closes #24
  • Loading branch information
MilkeeyCat committed Sep 8, 2024
1 parent 16570df commit 3036c73
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/passes/type_checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use super::Pass;
use crate::{
parser::{Block, Expr, Expression, ParserError, Stmt, UnOp},
scope::Scope,
type_table as tt,
type_table::TypeTable,
types::{Type, TypeError},
};
use std::collections::HashSet;
Expand All @@ -13,6 +15,7 @@ impl Pass for TypeChecker {
type Output = Result<()>;

fn proccess(stmts: &mut Vec<Stmt>, scope: &mut Scope) -> Self::Output {
Self::check_type_table(scope.type_table(), scope)?;
for stmt in stmts {
Self::check_stmt(stmt, scope)?;
}
Expand All @@ -24,6 +27,7 @@ impl Pass for TypeChecker {
impl TypeChecker {
fn check_block(block: &Block, scope: &mut Scope) -> Result<()> {
scope.enter(block.scope.clone());
Self::check_type_table(scope.type_table(), scope)?;
for stmt in &block.statements {
Self::check_stmt(stmt, scope)?;
}
Expand Down Expand Up @@ -175,4 +179,21 @@ impl TypeChecker {
_ => {}
})
}

fn check_type_table(type_table: &TypeTable, scope: &Scope) -> Result<()> {
for type_ in &type_table.0 {
match type_ {
tt::Type::Struct(type_struct) => {
for (_, type_) in &type_struct.fields {
Self::check_type(type_, scope)?;
if type_ == &Type::Struct(type_struct.name.clone()) {
panic!("Recursize type {type_} has infinite size");
}
}
}
}
}

Ok(())
}
}
4 changes: 4 additions & 0 deletions src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ impl Scope {
&mut self.0.last_mut().unwrap().symbol_table
}

pub fn type_table(&self) -> &TypeTable {
&self.0.last().unwrap().type_table
}

pub fn type_table_mut(&mut self) -> &mut TypeTable {
&mut self.0.last_mut().unwrap().type_table
}
Expand Down
2 changes: 1 addition & 1 deletion src/type_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl TypeStruct {
}

#[derive(Debug, Clone, PartialEq)]
pub struct TypeTable(Vec<Type>);
pub struct TypeTable(pub Vec<Type>);

impl TypeTable {
pub fn new() -> Self {
Expand Down

0 comments on commit 3036c73

Please sign in to comment.