|
| 1 | +/** |
| 2 | + * Provides a predicate for identifying unused index variables in loops. |
| 3 | + */ |
| 4 | + |
| 5 | +import javascript |
| 6 | + |
| 7 | +/** |
| 8 | + * Holds if `arr` is of the form `base[idx]` and is nested inside loop `fs`. |
| 9 | + */ |
| 10 | +private predicate arrayIndexInLoop(IndexExpr arr, Variable base, Expr idx, ForStmt fs) { |
| 11 | + arr.getEnclosingStmt().getParentStmt*() = fs.getBody() and |
| 12 | + arr.getBase() = base.getAnAccess() and |
| 13 | + arr.getIndex() = idx |
| 14 | +} |
| 15 | + |
| 16 | +/** |
| 17 | + * Gets `e` or a sub-expression `s` resulting from `e` by peeling off unary and binary |
| 18 | + * operators, increments, decrements, type assertions, parentheses, sequence expressions, |
| 19 | + * and assignments. |
| 20 | + */ |
| 21 | +private Expr unwrap(Expr e) { |
| 22 | + result = e or |
| 23 | + result = unwrap(e.(UpdateExpr).getOperand()) or |
| 24 | + result = unwrap(e.(UnaryExpr).getOperand()) or |
| 25 | + result = unwrap(e.(BinaryExpr).getAnOperand()) or |
| 26 | + result = unwrap(e.getUnderlyingValue()) |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * Holds if `rel` is a for-loop condition of the form `idx <= v.length`, but all array |
| 31 | + * indices `v[c]` inside the loop body (of which there must be at least one) use a constant |
| 32 | + * index `c` instead of an index based on `idx`. |
| 33 | + */ |
| 34 | +predicate unusedIndexVariable(RelationalComparison rel, Variable idx, Variable v) { |
| 35 | + exists(ForStmt fs | fs.getTest() = rel | |
| 36 | + unwrap(rel.getLesserOperand()) = idx.getAnAccess() and |
| 37 | + rel.getGreaterOperand().(PropAccess).accesses(v.getAnAccess(), "length") and |
| 38 | + forex(IndexExpr arr, Expr e | arrayIndexInLoop(arr, v, e, fs) | exists(e.getIntValue())) |
| 39 | + ) |
| 40 | +} |
0 commit comments