Skip to content

Commit

Permalink
feat: check type when assign value to a variable
Browse files Browse the repository at this point in the history
closes #9
  • Loading branch information
MilkeeyCat committed Jun 2, 2024
1 parent 977d25c commit f7fdf8d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
23 changes: 18 additions & 5 deletions src/parser/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,24 @@ impl Parser {
let token = self.cur_token.clone();
self.next_token();

Expr::Binary(ExprBinary::new(
BinOp::from(&token),
Box::new(left),
Box::new(self.expr(token.precedence())),
))
let left = Box::new(left);
let right = Box::new(self.expr(token.precedence()));
let op = BinOp::from(&token);

if op == BinOp::Assign {
if !left
.type_(&self.symtable)
.assignable(&right.type_(&self.symtable))
{
panic!(
"Cant assign {:?} to {:?}",
right.type_(&self.symtable),
left.type_(&self.symtable)
);
}
}

Expr::Binary(ExprBinary::new(op, left, right))
}

fn unary_expr(&mut self) -> Expr {
Expand Down
14 changes: 14 additions & 0 deletions src/parser/type_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,18 @@ impl Type {

right
}

pub fn assignable(&self, type_: &Self) -> bool {
if self.int() && type_.int() {
if (self.signed() && !type_.signed()) || (!self.signed() && type_.signed()) {
return false;
}

if self >= type_ {
return true;
}
}

false
}
}

0 comments on commit f7fdf8d

Please sign in to comment.