Skip to content

Commit 9fda4ab

Browse files
committed
Python: Fix false positive in py/non-iterator-in-for-loop
Should fix #1833, #2137, and #2187. Internally, comprehensions are (at present) elaborated into local functions and iterators as described in [PEP-289](https://www.python.org/dev/peps/pep-0289/). That is, something like: ``` g = (x**2 for x in range(10)) ``` becomes something akin to ``` def __gen(exp): for x in exp: yield x**2 g = __gen(iter(range(10))) ``` In the context of the top-level of a class, this means `__gen` looks as if it is a method of the class, and in particular `exp` looks like it's the `self` argument of this method, which leads the points-to analysis to think that `exp` is an instance of the surrounding class itself. The fix in this case is pretty simple: we look for occurrences of `exp` (in fact called `.0` internally -- carefully chosen to _not_ be a valid Python identifier) and explicitly exclude this parameter from being classified as a `self` parameter.
1 parent 77c869f commit 9fda4ab

File tree

3 files changed

+3
-3
lines changed

3 files changed

+3
-3
lines changed

python/ql/src/semmle/python/objects/TObject.qll

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,9 +367,10 @@ predicate receiver(AttrNode instantiation, PointsToContext context, ObjectIntern
367367
pragma [noinline]
368368
private predicate self_parameter(ParameterDefinition def, PointsToContext context, PythonClassObjectInternal cls) {
369369
def.isSelf() and
370+
/* Exclude the special parameter name `.0` which is used for unfolded comprehensions. */
371+
def.getName() != ".0" and
370372
exists(Function scope |
371373
def.getScope() = scope and
372-
def.isSelf() and
373374
context.isRuntime() and context.appliesToScope(scope) and
374375
scope.getScope() = cls.getScope() and
375376
concrete_class(cls) and
Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
| test.py:50:1:50:23 | For | $@ of class '$@' may be used in for-loop. | test.py:50:10:50:22 | ControlFlowNode for NonIterator() | Non-iterator | test.py:45:1:45:26 | class NonIterator | NonIterator |
2-
| test.py:170:10:170:22 | For | $@ of class '$@' may be used in for-loop. | test.py:170:10:170:22 | ControlFlowNode for .0 | Non-iterator | test.py:169:1:169:21 | class false_positive | false_positive |

python/ql/test/query-tests/Statements/general/test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def no_with():
165165
def assert_ok(seq):
166166
assert all(isinstance(element, (str, unicode)) for element in seq)
167167

168-
# False positive. ODASA-8042
168+
# False positive. ODASA-8042. Fixed in PR #2401.
169169
class false_positive:
170170
e = (x for x in [])
171171

0 commit comments

Comments
 (0)