Skip to content

Commit c1d0547

Browse files
committed
Implement break and continue
1 parent dc1b821 commit c1d0547

File tree

3 files changed

+50
-4
lines changed

3 files changed

+50
-4
lines changed

interpreter.py

+22-4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@
77
from utils.values import Int, Float, String, Vector
88

99

10+
class Break(Exception):
11+
pass
12+
13+
14+
class Continue(Exception):
15+
pass
16+
17+
1018
class Interpreter(MyParserVisitor):
1119
def __init__(self):
1220
self.memory_stack = MemoryStack()
@@ -36,7 +44,12 @@ def visitForLoop(self, ctx: MyParser.ForLoopContext):
3644
while a <= b:
3745
self.memory_stack.put(variable, Int(a))
3846
a = a + 1 # to increment enumerateor and disregard changes inside the loop
39-
self.visit(ctx.statement())
47+
try:
48+
self.visit(ctx.statement())
49+
except Continue:
50+
continue
51+
except Break:
52+
break
4053

4154
def visitRange(self, ctx: MyParser.RangeContext):
4255
a = self.visit(ctx.expression(0))
@@ -47,7 +60,12 @@ def visitRange(self, ctx: MyParser.RangeContext):
4760

4861
def visitWhileLoop(self, ctx: MyParser.WhileLoopContext):
4962
while self.visit(ctx.comparison()):
50-
self.visit(ctx.statement())
63+
try:
64+
self.visit(ctx.statement())
65+
except Continue:
66+
continue
67+
except Break:
68+
break
5169

5270
def visitComparison(self, ctx: MyParser.ComparisonContext):
5371
a = self.visit(ctx.expression(0))
@@ -153,10 +171,10 @@ def visitSpecialMatrixFunction(self, ctx: MyParser.SpecialMatrixFunctionContext)
153171
return vector
154172

155173
def visitBreak(self, ctx: MyParser.BreakContext):
156-
return self.visitChildren(ctx) # todo
174+
raise Break()
157175

158176
def visitContinue(self, ctx: MyParser.ContinueContext):
159-
return self.visitChildren(ctx) # todo
177+
raise Continue()
160178

161179
def visitVector(self, ctx: MyParser.VectorContext):
162180
elements = [

test_main.py

+1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ def test_sem_errors(name: str, line_numbers: list[int], additional: str):
8484
("variables", [2, 1, 3, "OK", 6]),
8585
("while", [4, 3, 2, 1, 0]),
8686
("for", [1, 10, 2, 10, 3, 10, 4, 10]),
87+
("break_continue", [1, 2, 1, 2, 4] * 2),
8788
],
8889
)
8990
def test_interpreter(name: str, output: str):

tests/interpreter/break_continue.txt

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
for i = 1:4 {
2+
if (i == 3)
3+
break;
4+
print i;
5+
}
6+
7+
for i = 1:4 {
8+
if (i == 3)
9+
continue;
10+
print i;
11+
}
12+
13+
i = 0;
14+
while (i < 4) {
15+
i += 1;
16+
if (i == 3)
17+
break;
18+
print i;
19+
}
20+
21+
i = 0;
22+
while (i < 4) {
23+
i += 1;
24+
if (i == 3)
25+
continue;
26+
print i;
27+
}

0 commit comments

Comments
 (0)