Skip to content

Commit 381cc20

Browse files
authored
Merge pull request #18703 from github/tausbn/python-robustly-handle-loop-constructs
Python: Handle loop constructs outside of loops
2 parents aca70cd + 131ec8d commit 381cc20

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

python/extractor/semmle/python/passes/flow.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -909,14 +909,22 @@ def _walk_slice(self, node, predecessors):
909909
def _walk_break(self, node, predecessors):
910910
#A break statement counts as an exit to the enclosing loop statement
911911
predecessors = self.add_successor(predecessors, node)
912-
self.scope.breaking_stack.add(predecessors)
912+
# In well formed code, there should always be an element in the breaking stack, but because
913+
# our parser accepts code where `break` appears outside of a loop, we must check for this
914+
# case.
915+
if self.scope.breaking_stack:
916+
self.scope.breaking_stack.add(predecessors)
913917
#Provide no predecessors to following statement
914918
return EMPTY
915919

916920
def _walk_continue(self, node, predecessors):
917921
#A continue statement counts as an exit to the following orelse
918922
predecessors = self.add_successor(predecessors, node)
919-
self.scope.continuing_stack.add(predecessors)
923+
# In well formed code, there should always be an element in the continuing stack, but
924+
# because our parser accepts code where `continue` appears outside of a loop, we must check
925+
# for this case.
926+
if self.scope.continuing_stack:
927+
self.scope.continuing_stack.add(predecessors)
920928
#Provide no predecessors to following statement
921929
return EMPTY
922930

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
category: fix
3+
---
4+
5+
- Using the `break` and `continue` keywords outside of a loop, which is a syntax error but is accepted by our parser, would cause the control-flow construction to fail. This is now no longer the case.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# The following constructs are syntax errors in Python, as they are not inside a loop.
2+
# However, our parser does not consider this code to be syntactically incorrect.
3+
# Thus, this test is really observing that allowing these constructs does not break any other parts
4+
# of the extractor.
5+
6+
if True:
7+
break
8+
9+
if True:
10+
continue

0 commit comments

Comments
 (0)