Skip to content

Commit 5ed0584

Browse files
committed
Implement break and continue
1 parent dc1b821 commit 5ed0584

File tree

3 files changed

+47
-4
lines changed

3 files changed

+47
-4
lines changed

interpreter.py

+19-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66
from utils.memory import MemoryStack
77
from utils.values import Int, Float, String, Vector
88

9+
class Break(Exception):
10+
pass
11+
12+
class Continue(Exception):
13+
pass
914

1015
class Interpreter(MyParserVisitor):
1116
def __init__(self):
@@ -36,7 +41,12 @@ def visitForLoop(self, ctx: MyParser.ForLoopContext):
3641
while a <= b:
3742
self.memory_stack.put(variable, Int(a))
3843
a = a + 1 # to increment enumerateor and disregard changes inside the loop
39-
self.visit(ctx.statement())
44+
try:
45+
self.visit(ctx.statement())
46+
except Continue:
47+
continue
48+
except Break:
49+
break
4050

4151
def visitRange(self, ctx: MyParser.RangeContext):
4252
a = self.visit(ctx.expression(0))
@@ -47,7 +57,12 @@ def visitRange(self, ctx: MyParser.RangeContext):
4757

4858
def visitWhileLoop(self, ctx: MyParser.WhileLoopContext):
4959
while self.visit(ctx.comparison()):
50-
self.visit(ctx.statement())
60+
try:
61+
self.visit(ctx.statement())
62+
except Continue:
63+
continue
64+
except Break:
65+
break
5166

5267
def visitComparison(self, ctx: MyParser.ComparisonContext):
5368
a = self.visit(ctx.expression(0))
@@ -153,10 +168,10 @@ def visitSpecialMatrixFunction(self, ctx: MyParser.SpecialMatrixFunctionContext)
153168
return vector
154169

155170
def visitBreak(self, ctx: MyParser.BreakContext):
156-
return self.visitChildren(ctx) # todo
171+
raise Break()
157172

158173
def visitContinue(self, ctx: MyParser.ContinueContext):
159-
return self.visitChildren(ctx) # todo
174+
raise Continue()
160175

161176
def visitVector(self, ctx: MyParser.VectorContext):
162177
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)