Skip to content

Commit

Permalink
add type check
Browse files Browse the repository at this point in the history
  • Loading branch information
jackparsonss committed Jun 28, 2024
1 parent f736464 commit f436493
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions include/ast/passes/type_check.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class TypeCheck : public Pass {
public:
explicit TypeCheck();
void visit_declaration(shared_ptr<ast::Declaration>) override;
void visit_assignment(shared_ptr<ast::Assignment>) override;
void visit_function(shared_ptr<ast::Function>) override;
void visit_call(shared_ptr<ast::Call>) override;
void visit_return(shared_ptr<ast::Return>) override;
Expand Down
13 changes: 13 additions & 0 deletions src/ast/passes/type_check.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,19 @@ void TypeCheck::visit_declaration(shared_ptr<ast::Declaration> node) {
}
}

void TypeCheck::visit_assignment(shared_ptr<ast::Assignment> node) {
visit(node->var);
visit(node->expr);

Type var = *node->var->get_type();
Type expr = *node->expr->get_type();
if (var != expr) {
throw TypeError(node->token->getLine(),
"mismatched lhs(" + var.get_name() + ") and rhs(" +
expr.get_name() + ") types on assignment");
}
}

void TypeCheck::visit_function(shared_ptr<ast::Function> node) {
for (const auto& param : node->params) {
visit(param);
Expand Down
6 changes: 6 additions & 0 deletions tests/input/errors/type/assignment.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fn main(): i32 {
let x: i32 = 5;
x = 'a';

return 0;
}
1 change: 1 addition & 0 deletions tests/output/errors/type/assignment.out
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
TypeError on Line 3

0 comments on commit f436493

Please sign in to comment.