|
| 1 | +/** |
| 2 | + * Provides classes and predicates to represent constant integer expressions. |
| 3 | + */ |
| 4 | + |
| 5 | +private import csharp |
| 6 | +private import Ssa |
| 7 | + |
| 8 | +/** |
| 9 | + * Holds if property `p` matches `property` in `baseClass` or any overrides. |
| 10 | + */ |
| 11 | +predicate propertyOverrides(Property p, string baseClass, string property) { |
| 12 | + exists(Property p2 | |
| 13 | + p2.getSourceDeclaration().getDeclaringType().hasQualifiedName(baseClass) and |
| 14 | + p2.hasName(property) |
| 15 | + | |
| 16 | + p.overridesOrImplementsOrEquals(p2) |
| 17 | + ) |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Holds if expression `e` is either |
| 22 | + * - a compile time constant with integer value `val`, or |
| 23 | + * - a read of a compile time constant with integer value `val`, or |
| 24 | + * - a read of the `Length` of an array with `val` lengths. |
| 25 | + */ |
| 26 | +private predicate constantIntegerExpr(Expr e, int val) { |
| 27 | + e.getValue().toInt() = val |
| 28 | + or |
| 29 | + exists(ExplicitDefinition v, Expr src | |
| 30 | + e = v.getARead() and |
| 31 | + src = v.getADefinition().getSource() and |
| 32 | + constantIntegerExpr(src, val) |
| 33 | + ) |
| 34 | + or |
| 35 | + isArrayLengthAccess(e, val) |
| 36 | +} |
| 37 | + |
| 38 | +private int getArrayLength(ArrayCreation arrCreation, int index) { |
| 39 | + constantIntegerExpr(arrCreation.getLengthArgument(index), result) |
| 40 | +} |
| 41 | + |
| 42 | +private int getArrayLengthRec(ArrayCreation arrCreation, int index) { |
| 43 | + index = 0 and result = getArrayLength(arrCreation, 0) |
| 44 | + or |
| 45 | + index > 0 and |
| 46 | + result = getArrayLength(arrCreation, index) * getArrayLengthRec(arrCreation, index - 1) |
| 47 | +} |
| 48 | + |
| 49 | +private predicate isArrayLengthAccess(PropertyAccess pa, int length) { |
| 50 | + propertyOverrides(pa.getTarget(), "System.Array", "Length") and |
| 51 | + exists(ExplicitDefinition arr, ArrayCreation arrCreation | |
| 52 | + getArrayLengthRec(arrCreation, arrCreation.getNumberOfLengthArguments() - 1) = length and |
| 53 | + arrCreation = arr.getADefinition().getSource() and |
| 54 | + pa.getQualifier() = arr.getARead() |
| 55 | + ) |
| 56 | +} |
| 57 | + |
| 58 | +/** An expression that always has the same integer value. */ |
| 59 | +class ConstantIntegerExpr extends Expr { |
| 60 | + ConstantIntegerExpr() { constantIntegerExpr(this, _) } |
| 61 | + |
| 62 | + /** Gets the integer value of this expression. */ |
| 63 | + int getIntValue() { constantIntegerExpr(this, result) } |
| 64 | +} |
0 commit comments