Skip to content

Commit a4ccda5

Browse files
tausbnyoff
andcommitted
Python: Fix pruning of literals in match pattern
Co-authored-by: yoff <[email protected]>
1 parent 95a8881 commit a4ccda5

File tree

1 file changed

+23
-0
lines changed
  • python/extractor/semmle/python/passes

1 file changed

+23
-0
lines changed

python/extractor/semmle/python/passes/pruner.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,25 @@ def visit_Attribute(self, node):
196196
if isinstance(node.value, ast.Name):
197197
self.nodes.add(node.value)
198198

199+
class NotBooleanTestVisitor(ASTVisitor):
200+
"""Visitor that checks if a test is not a boolean test."""
201+
202+
def __init__(self):
203+
self.nodes = set()
204+
205+
def visit_MatchLiteralPattern(self, node):
206+
# MatchLiteralPatterns _look_ like boolean tests, but are not.
207+
# Thus, without this check, we would interpret
208+
#
209+
# match x:
210+
# case False:
211+
# pass
212+
#
213+
# (and similarly for True) as if it was a boolean test. This would cause the true edge
214+
# (leading to pass) to be pruned later on.
215+
if isinstance(node.literal, ast.Name) and node.literal.id in ('True', 'False'):
216+
self.nodes.add(node.literal)
217+
199218
class NonlocalVisitor(ASTVisitor):
200219
def __init__(self):
201220
self.names = set()
@@ -306,6 +325,8 @@ def effective_constants_definitions(bool_const_defns, graph, branching_edges):
306325
def do_pruning(tree, graph):
307326
v = BoolConstVisitor()
308327
v.visit(tree)
328+
not_boolean_test = NotBooleanTestVisitor()
329+
not_boolean_test.visit(tree)
309330
nonlocals = NonlocalVisitor()
310331
nonlocals.visit(tree)
311332
global_vars = GlobalVisitor()
@@ -353,6 +374,8 @@ def do_pruning(tree, graph):
353374
b = const_value(pred.node)
354375
if b is None:
355376
continue
377+
if pred.node in not_boolean_test.nodes:
378+
continue
356379
if b.contradicts(val):
357380
to_be_removed.add((pred, succ))
358381
if not to_be_removed:

0 commit comments

Comments
 (0)