-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathExprs.qll
More file actions
695 lines (564 loc) · 20.8 KB
/
Exprs.qll
File metadata and controls
695 lines (564 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
private import python
private import semmle.python.internal.CachedStages
/** An expression */
class Expr extends Expr_, AstNode {
/** Gets the scope of this expression */
override Scope getScope() { py_scopes(this, result) }
/** Gets a textual representation of this element. */
cached
override string toString() {
Stages::AST::ref() and
result = "Expression"
}
/** Gets the module in which this expression occurs */
Module getEnclosingModule() { result = this.getScope().getEnclosingModule() }
/**
* Whether this expression defines variable `v`
* If doing dataflow, then consider using SsaVariable.getDefinition() for more precision.
*/
predicate defines(Variable v) { this.getASubExpression().defines(v) }
/** Whether this expression may have a side effect (as determined purely from its syntax) */
predicate hasSideEffects() {
/* If an exception raised by this expression handled, count that as a side effect */
this.getAFlowNode().getASuccessor().getNode() instanceof ExceptStmt
or
this.getASubExpression().hasSideEffects()
}
/** Whether this expression is a constant */
predicate isConstant() { not this.isVariable() }
/** Whether the parenthesized property of this expression is true. */
predicate isParenthesized() { Expr_.super.isParenthesised() }
private predicate isVariable() {
this.hasSideEffects()
or
this instanceof Name
or
exists(Expr e | e = this.getASubExpression() and e.isVariable())
}
override Location getLocation() { result = Expr_.super.getLocation() }
/** Gets an immediate (non-nested) sub-expression of this expression */
Expr getASubExpression() { none() }
override AstNode getAChildNode() { result = this.getASubExpression() }
}
/** An assignment expression, such as `x := y` */
class AssignExpr extends AssignExpr_ {
override Expr getASubExpression() {
result = this.getValue() or
result = this.getTarget()
}
}
/** An attribute expression, such as `value.attr` */
class Attribute extends Attribute_ {
/* syntax: Expr.name */
override Expr getASubExpression() { result = this.getObject() }
override AttrNode getAFlowNode() { result = super.getAFlowNode() }
/** Gets the name of this attribute. That is the `name` in `obj.name` */
string getName() { result = Attribute_.super.getAttr() }
/** Gets the object of this attribute. That is the `obj` in `obj.name` */
Expr getObject() { result = Attribute_.super.getValue() }
/**
* Gets the expression corresponding to the object of the attribute, if the name of the attribute is `name`.
* Equivalent to `this.getObject() and this.getName() = name`.
*/
Expr getObject(string name) {
result = Attribute_.super.getValue() and
name = Attribute_.super.getAttr()
}
}
/** A subscript expression, such as `value[slice]` */
class Subscript extends Subscript_ {
/* syntax: Expr[Expr] */
override Expr getASubExpression() {
result = this.getIndex()
or
result = this.getObject()
}
Expr getObject() { result = Subscript_.super.getValue() }
override SubscriptNode getAFlowNode() { result = super.getAFlowNode() }
}
/** A call expression, such as `func(...)` */
class Call extends Call_ {
/* syntax: Expr(...) */
override Expr getASubExpression() {
result = this.getAPositionalArg() or
result = this.getAKeyword().getValue() or
result = this.getFunc()
}
override predicate hasSideEffects() { any() }
override string toString() { result = this.getFunc().toString() + "()" }
override CallNode getAFlowNode() { result = super.getAFlowNode() }
/** Gets a tuple (*) argument of this call. */
Expr getStarargs() { result = this.getAPositionalArg().(Starred).getValue() }
/** Gets a dictionary (**) argument of this call. */
Expr getKwargs() { result = this.getANamedArg().(DictUnpacking).getValue() }
/* Backwards compatibility */
/**
* Gets the nth keyword argument of this call expression, provided it is not preceded by a double-starred argument.
* This exists primarily for backwards compatibility. You are recommended to use
* Call.getNamedArg(index) instead.
*/
Keyword getKeyword(int index) {
result = this.getNamedArg(index) and
(
not exists(this.getMinimumUnpackingIndex())
or
index <= this.getMinimumUnpackingIndex()
)
}
/** Gets the minimum index (if any) at which a dictionary unpacking (`**foo`) occurs in this call. */
private int getMinimumUnpackingIndex() {
result = min(int i | this.getNamedArg(i) instanceof DictUnpacking)
}
/**
* Gets a keyword argument of this call expression, provided it is not preceded by a double-starred argument.
* This exists primarily for backwards compatibility. You are recommended to use
* Call.getANamedArg() instead.
*/
Keyword getAKeyword() { result = this.getKeyword(_) }
/**
* Gets the positional argument at `index`, provided it is not preceded by a starred argument.
* This exists primarily for backwards compatibility. You are recommended to use
* Call.getPositionalArg(index) instead.
*/
Expr getArg(int index) {
result = this.getPositionalArg(index) and
not result instanceof Starred and
not exists(Starred s, int lower | s = this.getPositionalArg(lower) and lower < index)
}
/**
* Gets a positional argument, provided it is not preceded by a starred argument.
* This exists primarily for backwards compatibility. You are recommended to use
* Call.getAPositionalArg() instead.
*/
Expr getAnArg() { result = this.getArg(_) }
override AstNode getAChildNode() {
result = this.getAPositionalArg() or
result = this.getANamedArg() or
result = this.getFunc()
}
/** Gets the name of a named argument, including those passed in dict literals. */
string getANamedArgumentName() {
result = this.getAKeyword().getArg()
or
result = this.getKwargs().(Dict).getAKey().(StringLiteral).getText()
}
/** Gets the positional argument count of this call, provided there is no more than one tuple (*) argument. */
int getPositionalArgumentCount() {
count(this.getStarargs()) < 2 and
result = count(Expr arg | arg = this.getAPositionalArg() and not arg instanceof Starred)
}
/** Gets the first tuple (*) argument of this call, if any. */
Expr getStarArg() {
exists(int firstStarArgIndex |
firstStarArgIndex = min(int i | this.getPositionalArg(i) instanceof Starred | i) and
result = this.getPositionalArg(firstStarArgIndex).(Starred).getValue()
)
}
}
/** A conditional expression such as, `body if test else orelse` */
class IfExp extends IfExp_ {
/* syntax: Expr if Expr else Expr */
override Expr getASubExpression() {
result = this.getTest() or result = this.getBody() or result = this.getOrelse()
}
override IfExprNode getAFlowNode() { result = super.getAFlowNode() }
}
/** A starred expression, such as the `*rest` in the assignment `first, *rest = seq` */
class Starred extends Starred_ {
/* syntax: *Expr */
override Expr getASubExpression() { result = this.getValue() }
}
/** A yield expression, such as `yield value` */
class Yield extends Yield_ {
/* syntax: yield Expr */
override Expr getASubExpression() { result = this.getValue() }
override predicate hasSideEffects() { any() }
}
/** A yield expression, such as `yield from value` */
class YieldFrom extends YieldFrom_ {
/* syntax: yield from Expr */
override Expr getASubExpression() { result = this.getValue() }
override predicate hasSideEffects() { any() }
}
/** A repr (backticks) expression, such as `` `value` `` */
class Repr extends Repr_ {
/* syntax: `Expr` */
override Expr getASubExpression() { result = this.getValue() }
override predicate hasSideEffects() { any() }
}
/* Constants */
/**
* A bytes constant, such as `b'ascii'`. Note that unadorned string constants such as
* `"hello"` are treated as Bytes for Python2, but Unicode for Python3.
*/
class Bytes extends StringLiteral {
/* syntax: b"hello" */
Bytes() { not this.isUnicode() }
/**
* The extractor puts quotes into the name of each string (to prevent "0" clashing with 0).
* The following predicate help us match up a string/byte literals in the source
* which the equivalent object.
*/
string quotedString() {
exists(string b_unquoted | b_unquoted = this.getS() | result = "b'" + b_unquoted + "'")
}
}
/** An ellipsis expression, such as `...` */
class Ellipsis extends Ellipsis_ {
/* syntax: ... */
override Expr getASubExpression() { none() }
}
/**
* An immutable literal expression (except tuples).
* Consists of string (both unicode and byte) literals and numeric literals.
*/
abstract class ImmutableLiteral extends Expr {
abstract boolean booleanValue();
}
/** A numerical constant expression, such as `7` or `4.2` */
abstract class Num extends Num_, ImmutableLiteral {
override Expr getASubExpression() { none() }
/* We want to declare this abstract, but currently we cannot. */
override string toString() { result = "Num with missing toString" }
}
/** An integer numeric constant, such as `7` or `0x9` */
class IntegerLiteral extends Num {
/* syntax: 4 */
IntegerLiteral() { not this instanceof FloatLiteral and not this instanceof ImaginaryLiteral }
/**
* Gets the (integer) value of this constant. Will not return a result if the value does not fit into
* a 32 bit signed value
*/
int getValue() { result = this.getN().toInt() }
override string toString() { result = "IntegerLiteral" }
override boolean booleanValue() {
this.getValue() = 0 and result = false
or
this.getValue() != 0 and result = true
}
}
/** A floating point numeric constant, such as `0.4` or `4e3` */
class FloatLiteral extends Num {
/* syntax: 4.2 */
FloatLiteral() {
not this instanceof ImaginaryLiteral and
this.getN().regexpMatch(".*[.eE].*")
}
float getValue() { result = this.getN().toFloat() }
override string toString() { result = "FloatLiteral" }
override boolean booleanValue() {
this.getValue() = 0.0 and result = false
or
// In QL 0.0 != -0.0
this.getValue() = -0.0 and result = false
or
this.getValue() != 0.0 and this.getValue() != -0.0 and result = true
}
}
/** An imaginary numeric constant, such as `3j` */
class ImaginaryLiteral extends Num {
private float value;
/* syntax: 1.0j */
ImaginaryLiteral() { value = this.getN().regexpCapture("(.+)j.*", 1).toFloat() }
/** Gets the value of this constant as a floating point value */
float getValue() { result = value }
override string toString() { result = "ImaginaryLiteral" }
override boolean booleanValue() {
this.getValue() = 0.0 and result = false
or
// In QL 0.0 != -0.0
this.getValue() = -0.0 and result = false
or
this.getValue() != 0.0 and this.getValue() != -0.0 and result = true
}
}
class NegativeIntegerLiteral extends ImmutableLiteral, UnaryExpr {
NegativeIntegerLiteral() {
this.getOp() instanceof USub and
this.getOperand() instanceof IntegerLiteral
}
override boolean booleanValue() { result = this.getOperand().(IntegerLiteral).booleanValue() }
/**
* Gets the (integer) value of this constant. Will not return a result if the value does not fit into
* a 32 bit signed value
*/
int getValue() { result = -this.getOperand().(IntegerLiteral).getValue() }
}
/**
* A unicode string expression, such as `u"\u20ac"`. Note that unadorned string constants such as
* "hello" are treated as Bytes for Python2, but Unicode for Python3.
*/
class Unicode extends StringLiteral {
/* syntax: "hello" */
Unicode() { this.isUnicode() }
/**
* Gets the quoted representation fo this string.
*
* The extractor puts quotes into the name of each string (to prevent "0" clashing with 0).
* The following predicate help us match up a string/byte literals in the source
* which the equivalent object.
*/
string quotedString() {
exists(string u_unquoted | u_unquoted = this.getS() | result = "u'" + u_unquoted + "'")
}
}
/* Compound Values */
/** A dictionary expression, such as `{'key':'value'}` */
class Dict extends Dict_ {
/* syntax: {Expr: Expr, ...} */
/** Gets the value of an item of this dict display */
Expr getAValue() { result = this.getAnItem().(DictDisplayItem).getValue() }
/**
* Gets the key of an item of this dict display, for those items that have keys
* E.g, in {'a':1, **b} this returns only 'a'
*/
Expr getAKey() { result = this.getAnItem().(KeyValuePair).getKey() }
override Expr getASubExpression() { result = this.getAValue() or result = this.getAKey() }
override AstNode getAChildNode() { result = this.getAnItem() }
}
/** A list expression, such as `[ 1, 3, 5, 7, 9 ]` */
class List extends List_ {
/* syntax: [Expr, ...] */
override Expr getASubExpression() { result = this.getAnElt() }
}
/** A set expression such as `{ 1, 3, 5, 7, 9 }` */
class Set extends Set_ {
/* syntax: {Expr, ...} */
override Expr getASubExpression() { result = this.getAnElt() }
}
class PlaceHolder extends PlaceHolder_ {
string getId() { result = this.getVariable().getId() }
override Expr getASubExpression() { none() }
override string toString() { result = "$" + this.getId() }
override NameNode getAFlowNode() { result = super.getAFlowNode() }
}
/** A tuple expression such as `( 1, 3, 5, 7, 9 )` */
class Tuple extends Tuple_ {
/* syntax: (Expr, ...) */
override Expr getASubExpression() { result = this.getAnElt() }
}
/**
* A (plain variable) name expression, such as `var`.
* `None`, `True` and `False` are excluded.
*/
class Name extends Name_ {
/* syntax: name */
string getId() { result = this.getVariable().getId() }
/** Whether this expression is a definition */
predicate isDefinition() {
py_expr_contexts(_, 5, this)
or
/* Treat Param as a definition (which it is) */
py_expr_contexts(_, 4, this)
or
/* The target in an augmented assignment is also a definition (and a use) */
exists(AugAssign aa | aa.getTarget() = this)
}
/**
* Whether this expression defines variable `v`
* If doing dataflow, then consider using SsaVariable.getDefinition() for more precision.
*/
override predicate defines(Variable v) {
this.isDefinition() and
v = this.getVariable()
}
/** Whether this expression is a deletion */
predicate isDeletion() { py_expr_contexts(_, 2, this) }
/**
* Whether this expression deletes variable `v`.
* If doing dataflow, then consider using SsaVariable.getDefinition() for more precision.
*/
predicate deletes(Variable v) {
this.isDeletion() and
v = this.getVariable()
}
/** Whether this expression is a use */
predicate isUse() { py_expr_contexts(_, 3, this) }
/**
* Whether this expression is a use of variable `v`
* If doing dataflow, then consider using SsaVariable.getAUse() for more precision.
*/
predicate uses(Variable v) {
this.isUse() and
v = this.getVariable()
}
override predicate isConstant() { none() }
override Expr getASubExpression() { none() }
override string toString() { result = this.getId() }
override NameNode getAFlowNode() { result = super.getAFlowNode() }
override predicate isArtificial() {
/* Artificial variable names in comprehensions all start with "." */
this.getId().charAt(0) = "."
}
}
class Filter extends Filter_ {
override Expr getASubExpression() {
result = this.getFilter()
or
result = this.getValue()
}
}
/** A slice. E.g `0:1` in the expression `x[0:1]` */
class Slice extends Slice_ {
override Expr getASubExpression() {
result = this.getStart() or
result = this.getStop() or
result = this.getStep()
}
}
/**
* Returns all string prefixes in the database that are explicitly marked as Unicode strings.
*
* Helper predicate for `StringLiteral::isUnicode`.
*/
pragma[nomagic]
private string unicode_prefix() {
result = any(Str_ s).getPrefix() and
result.charAt(_) in ["u", "U"]
}
/**
* Returns all string prefixes in the database that are _not_ explicitly marked as bytestrings.
*
* Helper predicate for `StringLiteral::isUnicode`.
*/
pragma[nomagic]
private string non_byte_prefix() {
result = any(Str_ s).getPrefix() and
not result.charAt(_) in ["b", "B"]
}
/** DEPRECATED. Use `StringLiteral` instead. */
deprecated class Str = StringLiteral;
/** DEPRECATED. Use `StringLiteral` instead. */
deprecated class StrConst = StringLiteral;
/** A string constant. */
class StringLiteral extends Str_, ImmutableLiteral {
/* syntax: "hello" */
/**
* Holds if this string is a unicode string, either by default (e.g. if Python 3), or with an
* explicit prefix.
*/
predicate isUnicode() {
this.getPrefix() = unicode_prefix()
or
this.getPrefix() = non_byte_prefix() and
(
major_version() = 3
or
this.getEnclosingModule().hasFromFuture("unicode_literals")
)
}
override Expr getASubExpression() { none() }
override AstNode getAChildNode() { result = this.getAnImplicitlyConcatenatedPart() }
/** Gets the text of this str constant */
string getText() { result = this.getS() }
/** Whether this is a docstring */
predicate isDocString() { exists(Scope s | s.getDocString() = this) }
override boolean booleanValue() {
this.getText() = "" and result = false
or
this.getText() != "" and result = true
}
override string toString() { result = "StringLiteral" }
}
/** Holds if `n` is a named constant (`True`, `False`, or `None`) with name `id`. */
predicate name_consts(Name_ n, string id) {
exists(Variable v | py_variables(v, n) and id = v.getId() |
id = "True" or id = "False" or id = "None"
)
}
/** A named constant, one of `None`, `True` or `False` */
abstract class NameConstant extends Name, ImmutableLiteral {
NameConstant() { name_consts(this, _) }
override Expr getASubExpression() { none() }
override string toString() { name_consts(this, result) }
override predicate isConstant() { any() }
override NameConstantNode getAFlowNode() { result = Name.super.getAFlowNode() }
override predicate isArtificial() { none() }
}
/** A boolean named constant, either `True` or `False` */
abstract class BooleanLiteral extends NameConstant { }
/** The boolean named constant `True` */
class True extends BooleanLiteral {
/* syntax: True */
True() { name_consts(this, "True") }
override boolean booleanValue() { result = true }
}
/** The boolean named constant `False` */
class False extends BooleanLiteral {
/* syntax: False */
False() { name_consts(this, "False") }
override boolean booleanValue() { result = false }
}
/** The `None` constant. */
class None extends NameConstant {
/* syntax: None */
None() { name_consts(this, "None") }
override boolean booleanValue() { result = false }
}
/** An await expression such as `await coro`. */
class Await extends Await_ {
/* syntax: await Expr */
override Expr getASubExpression() { result = this.getValue() }
}
/** A formatted string literal expression, such as `f'hello {world!s}'` */
class Fstring extends Fstring_ {
/* syntax: f"Yes!" */
override Expr getASubExpression() { result = this.getAValue() }
}
/**
* A formatted value (within a formatted string literal).
* For example, in the string `f'hello {world!s}'` the formatted value is `world!s`.
*/
class FormattedValue extends FormattedValue_ {
override Expr getASubExpression() {
result = this.getValue() or
result = this.getFormatSpec()
}
}
/** A guard in a case statement */
class Guard extends Guard_ {
/* syntax: if Expr */
override Expr getASubExpression() { result = this.getTest() }
}
/** An annotation, such as the `int` part of `x: int` */
class Annotation extends Expr {
Annotation() {
this = any(AnnAssign a).getAnnotation()
or
exists(Arguments args |
this in [
args.getAnAnnotation(),
args.getAKwAnnotation(),
args.getKwargannotation(),
args.getVarargannotation()
]
)
or
this = any(FunctionExpr f).getReturns()
}
/** Gets the expression that this annotation annotates. */
Expr getAnnotatedExpression() {
result = any(AnnAssign a | a.getAnnotation() = this).getTarget()
or
result = any(Parameter p | p.getAnnotation() = this)
or
exists(FunctionExpr f, Return r |
this = f.getReturns() and r.getScope() = f.getInnerScope() and result = r.getValue()
)
}
}
/* Expression Contexts */
/** A context in which an expression used */
class ExprContext extends ExprContext_ { }
/** The load context, the context of var in len(var) */
class Load extends Load_ { }
/** The store context, the context of var in var = 0 */
class Store extends Store_ { }
/** The delete context, the context of var in del var */
class Del extends Del_ { }
/** The context of an augmented load. This is an artifact of the Python grammar which includes an AugLoad context, even though it is never used. */
class AugLoad extends AugLoad_ { }
/** The augmented store context, the context of var in var += 1 */
class AugStore extends AugStore_ { }
/** The parameter context, the context of var in def f(var): pass */
class Param extends Param_ { }