Skip to content

Commit 8e155b6

Browse files
authored
Fix redeclaration (#6)
1 parent 798dfa8 commit 8e155b6

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

semantic_listener.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,13 @@ def __init__(self):
4848

4949
def enterForLoop(self, ctx: MyParser.ForLoopContext):
5050
self.nested_loop_counter += 1
51-
self.variables[ctx.getChild(1).getText()] = Type.INT
51+
var = ctx.getChild(1).getText()
52+
if var in self.variables:
53+
ctx.parser.notifyErrorListeners(
54+
f"Variable {var} already declared", ctx.getChild(2).getSymbol()
55+
)
56+
else:
57+
self.variables[var] = Type.INT
5258

5359
def exitForLoop(self, ctx: MyParser.ForLoopContext):
5460
self.nested_loop_counter -= 1
@@ -99,8 +105,15 @@ def exitSimpleAssignment(self, ctx: MyParser.SimpleAssignmentContext):
99105
ctx.getChild(1).getSymbol(),
100106
)
101107
self.variables[var] = None
108+
self.expr_type[ctx.getChild(0)] = None
102109
else:
103110
self.variables[var] = self.expr_type[ctx.getChild(2)]
111+
self.expr_type[ctx.getChild(0)] = self.expr_type[ctx.getChild(2)]
112+
113+
elif self.expr_type[ctx.getChild(0)] != self.expr_type[ctx.getChild(2)]:
114+
ctx.parser.notifyErrorListeners(
115+
"Incompatible types in an assignment", ctx.getChild(1).getSymbol()
116+
)
104117

105118
def exitCompoundAssignment(self, ctx: MyParser.CompoundAssignmentContext):
106119
type_1 = self.expr_type[ctx.getChild(0)]

test_main.py

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ def test_ast(n: int):
4747
("comparisons", [7, 9], "comparison"),
4848
("compound_assignments", [10, 11, 12], "assignment"),
4949
("ranges", [9], "range"),
50+
("redeclaration", [3, 12], ""),
5051
],
5152
)
5253
def test_sem_errors(name: str, line_numbers: list[int], additional: str):
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
i = 0;
2+
3+
for i = 1:5
4+
print i;
5+
6+
print i;
7+
8+
i = 3;
9+
10+
print i;
11+
12+
i = 2.0;
13+
14+
print i;

0 commit comments

Comments
 (0)