Skip to content

Commit b23f661

Browse files
authored
Merge pull request #370 from namannimmo10/annassign
Raise error for a type mismatch in annassign
2 parents 4a0e5cf + 575fcd0 commit b23f661

5 files changed

+41
-0
lines changed

src/lpython/semantics/python_ast_to_asr.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1736,6 +1736,18 @@ class BodyVisitor : public CommonVisitor<BodyVisitor> {
17361736
this->visit_expr(*x.m_value);
17371737
value = ASRUtils::EXPR(tmp);
17381738
value = cast_helper(type, value, true);
1739+
if (!ASRUtils::check_equal_type(type, ASRUtils::expr_type(value))) {
1740+
std::string ltype = ASRUtils::type_to_str(type);
1741+
std::string rtype = ASRUtils::type_to_str(ASRUtils::expr_type(value));
1742+
diag.add(diag::Diagnostic(
1743+
"Type mismatch in annotation-assignment, the types must be compatible",
1744+
diag::Level::Error, diag::Stage::Semantic, {
1745+
diag::Label("type mismatch (" + ltype + " and " + rtype + ")",
1746+
{x.m_target->base.loc, value->base.loc})
1747+
})
1748+
);
1749+
throw SemanticAbort();
1750+
}
17391751
}
17401752
ASR::expr_t *init_expr = nullptr;
17411753
ASR::intentType s_intent = ASRUtils::intent_local;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from ltypes import i32
2+
3+
def f():
4+
x: i32[4] = [1, 2, 3, 4]
5+
print(a)
6+
7+
f()
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"basename": "asr-test_annassign_type_mismatch-7dac7be",
3+
"cmd": "lpython --show-asr --no-color {infile} -o {outfile}",
4+
"infile": "tests/errors/test_annassign_type_mismatch.py",
5+
"infile_hash": "5dacc11ffb3bc47fb14e508f454836ce4b196598d1943237cba9c86c",
6+
"outfile": null,
7+
"outfile_hash": null,
8+
"stdout": null,
9+
"stdout_hash": null,
10+
"stderr": "asr-test_annassign_type_mismatch-7dac7be.stderr",
11+
"stderr_hash": "26b687e0b4a187c139b077ec970580df391288fce1d13bde3770ce3b",
12+
"returncode": 2
13+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
semantic error: Type mismatch in annotation-assignment, the types must be compatible
2+
--> tests/errors/test_annassign_type_mismatch.py:4:5
3+
|
4+
4 | x: i32[4] = [1, 2, 3, 4]
5+
| ^ ^^^^^^^^^^^^ type mismatch (integer and list)

tests/tests.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,10 @@ asr = true
283283
filename = "errors/test_str_slicing.py"
284284
asr = true
285285

286+
[[test]]
287+
filename = "errors/test_annassign_type_mismatch.py"
288+
asr = true
289+
286290
[[test]]
287291
filename = "errors/test_append_type_mismatch.py"
288292
asr = true

0 commit comments

Comments
 (0)