From bfd7d85d9c5570b8085d62297669e7526a4cc9bc Mon Sep 17 00:00:00 2001 From: MilkeeyCat Date: Mon, 3 Jun 2024 13:31:56 +0300 Subject: [PATCH] feat(type): `castable` method --- src/parser/expr/expr.rs | 12 +++++++++--- src/parser/type_.rs | 10 ++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/parser/expr/expr.rs b/src/parser/expr/expr.rs index 65e2553..8eafde4 100644 --- a/src/parser/expr/expr.rs +++ b/src/parser/expr/expr.rs @@ -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), } } } @@ -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 { + 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())) + } } } diff --git a/src/parser/type_.rs b/src/parser/type_.rs index 7e3fcf6..372d100 100644 --- a/src/parser/type_.rs +++ b/src/parser/type_.rs @@ -4,6 +4,7 @@ use std::fmt::Display; pub enum TypeError { Promotion(Type, Type), IdentNotFound(String), + Cast(Type, Type), } impl Display for TypeError { @@ -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), } } } @@ -94,4 +96,12 @@ impl Type { false } + + pub fn castable(&self, type_: &Self) -> bool { + if self.int() && type_.int() { + return true; + } + + false + } }