Skip to content

Commit

Permalink
fix(type_checker): does not allow passing const to a nonconst, allow …
Browse files Browse the repository at this point in the history
…passing nonconst to a const
  • Loading branch information
JaDogg committed May 25, 2024
1 parent 28cac98 commit 637e9be
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions compiler/src/compiler/type_checker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,7 @@ void type_checker::visit_const_stmt(const_stmt *obj) {
auto match = type_match(obj->data_type_->args_[0], expression_dt, true);
if (match.matched_) {
placeholder = expression_data;
placeholder.datatype_ = obj->data_type_; // Set the correct data type
} else {
std::stringstream message{};
message << "Constant '" << name << "' data type mismatch. ";
Expand Down Expand Up @@ -1150,6 +1151,10 @@ type_match_result type_checker::type_match(ykdatatype *required_datatype,
required_datatype->auto_cast(provided_datatype, dt_pool_, false, true);
if (castable != nullptr) { return type_match_result{"", true, true}; }
}
// Pass a Type to a Const[Type] is allowed (becomes more restrictive)
if (primitive_or_obj && is_identical_type(required_datatype->const_unwrap(), provided_datatype)) {
return type_match_result{"", true, false};
}
std::stringstream message{};
message << "data type mismatch. Expected: ";
message << required_datatype->as_string_simplified();
Expand Down
22 changes: 22 additions & 0 deletions compiler/tests/test_type_checker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,28 @@ TEST_CASE(
" return 0",
"Variable argument: 5 mismatches. Expected: int Provided: i64");
}
TEST_CASE("type checker: pass in a non constant structure to a const") {
test_typechecker_snippet_full_ok(
"class A:\n"
" a: int\n"
"def afunc(a: Const[A]) -> None:\n"
" pass\n"
"def main() -> int:\n"
" myobj = A{a: 1}\n"
" afunc(myobj)\n"
" return 0");
}
TEST_CASE("type checker: pass in a constant structure object to a non const") {
test_typechecker_snippet_full(
"class A:\n"
" a: int\n"
"def afunc(a: A) -> None:\n"
" pass\n"
"def main() -> int:\n"
" myobj: Const[A] = A{a: 1}\n"
" afunc(myobj)\n"
" return 0", "Parameter & argument 1 mismatches. Expected: A Provided: Const[A]");
}
TEST_CASE("type checker: func ptr call parameter and argument mismatches") {
test_typechecker_snippet_full_ok("def fnc(a: int, b: int) -> None:\n"
" pass\n"
Expand Down

0 comments on commit 637e9be

Please sign in to comment.