Skip to content

Commit 9face19

Browse files
Fix continue statement
1 parent 53bcd04 commit 9face19

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

tests/snippets/control_flow.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# break from a nested for loop
2+
13
def foo():
24
sum = 0
35
for i in range(10):
@@ -8,3 +10,24 @@ def foo():
810
return sum
911

1012
assert foo() == 45
13+
14+
15+
# continue statement
16+
17+
def primes(limit):
18+
"""Finds all the primes from 2 up to a given number using the Sieve of Eratosthenes."""
19+
sieve = [False] * (limit + 1)
20+
for i in range(2, limit + 1):
21+
if sieve[i]:
22+
continue
23+
yield i
24+
25+
for j in range(2 * i, limit + 1, i):
26+
sieve[j] = True
27+
28+
29+
assert list(primes(1)) == []
30+
assert list(primes(2)) == [2]
31+
assert list(primes(10)) == [2, 3, 5, 7]
32+
assert list(primes(13)) == [2, 3, 5, 7, 11, 13]
33+

vm/src/frame.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -542,7 +542,10 @@ impl Frame {
542542
bytecode::Instruction::Break => {
543543
let block = self.unwind_loop(vm);
544544
if let BlockType::Loop { end, .. } = block.typ {
545+
self.pop_block();
545546
self.jump(end);
547+
} else {
548+
unreachable!()
546549
}
547550
Ok(None)
548551
}
@@ -555,7 +558,7 @@ impl Frame {
555558
if let BlockType::Loop { start, .. } = block.typ {
556559
self.jump(start);
557560
} else {
558-
assert!(false);
561+
unreachable!();
559562
}
560563
Ok(None)
561564
}
@@ -745,7 +748,7 @@ impl Frame {
745748

746749
fn unwind_loop(&mut self, vm: &mut VirtualMachine) -> Block {
747750
loop {
748-
let block = self.pop_block().expect("not in a loop");
751+
let block = self.current_block().cloned().expect("not in a loop");
749752
match block.typ {
750753
BlockType::Loop { .. } => break block,
751754
BlockType::TryExcept { .. } => {
@@ -760,6 +763,8 @@ impl Frame {
760763
}
761764
},
762765
}
766+
767+
self.pop_block();
763768
}
764769
}
765770

@@ -1080,6 +1085,10 @@ impl Frame {
10801085
Some(block)
10811086
}
10821087

1088+
fn current_block(&self) -> Option<&Block> {
1089+
self.blocks.last()
1090+
}
1091+
10831092
pub fn push_value(&mut self, obj: PyObjectRef) {
10841093
self.stack.push(obj);
10851094
}

0 commit comments

Comments
 (0)