Skip to content

Commit

Permalink
feat(type): castable method
Browse files Browse the repository at this point in the history
  • Loading branch information
MilkeeyCat committed Jun 3, 2024
1 parent 0fdc786 commit bfd7d85
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/parser/expr/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl Expr {
{
Symbol::GlobalVar(global_var) => Ok(global_var.type_.clone()),
},
Self::Cast(cast) => Ok(cast.type_()),
Self::Cast(cast) => cast.type_(symtable),
}
}
}
Expand Down Expand Up @@ -170,7 +170,13 @@ impl ExprCast {
Self { type_, expr }
}

pub fn type_(&self) -> Type {
self.type_.to_owned()
pub fn type_(&self, symbtable: &SymbolTable) -> Result<Type, TypeError> {
let expr_type = self.expr.type_(symbtable)?;

if expr_type.castable(&self.type_) {
Ok(self.type_.clone())
} else {
Err(TypeError::Cast(expr_type, self.type_.clone()))
}
}
}
10 changes: 10 additions & 0 deletions src/parser/type_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fmt::Display;
pub enum TypeError {
Promotion(Type, Type),
IdentNotFound(String),
Cast(Type, Type),
}

impl Display for TypeError {
Expand All @@ -13,6 +14,7 @@ impl Display for TypeError {
Self::Promotion(lhs, rhs) => {
write!(f, "Operation between {} and {} are not allowed", lhs, rhs)
}
Self::Cast(from, to) => write!(f, "Cant cast {} into {}", from, to),
}
}
}
Expand Down Expand Up @@ -94,4 +96,12 @@ impl Type {

false
}

pub fn castable(&self, type_: &Self) -> bool {
if self.int() && type_.int() {
return true;
}

false
}
}

0 comments on commit bfd7d85

Please sign in to comment.