|
| 1 | +/** |
| 2 | + * @name Useless comparison test |
| 3 | + * @description A comparison that always evaluates to true or always evaluates to false may |
| 4 | + * indicate faulty logic and dead code. |
| 5 | + * @kind problem |
| 6 | + * @problem.severity warning |
| 7 | + * @id js/useless-comparison-test |
| 8 | + * @tags correctness |
| 9 | + * @precision high |
| 10 | + */ |
| 11 | + |
| 12 | +import javascript |
| 13 | + |
| 14 | +/** |
| 15 | + * Holds if there are any contradictory guard nodes in `container`. |
| 16 | + * |
| 17 | + * We use this to restrict reachability analysis to a small set of containers. |
| 18 | + */ |
| 19 | +predicate hasContradictoryGuardNodes(StmtContainer container) { |
| 20 | + exists (ConditionGuardNode guard | |
| 21 | + RangeAnalysis::isContradictoryGuardNode(guard) and |
| 22 | + container = guard.getContainer()) |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Holds if `block` is reachable and is in a container with contradictory guard nodes. |
| 27 | + */ |
| 28 | +predicate isReachable(BasicBlock block) { |
| 29 | + exists (StmtContainer container | |
| 30 | + hasContradictoryGuardNodes(container) and |
| 31 | + block = container.getEntryBB()) |
| 32 | + or |
| 33 | + isReachable(block.getAPredecessor()) and |
| 34 | + not RangeAnalysis::isContradictoryGuardNode(block.getANode()) |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Holds if `block` is unreachable, but could be reached if `guard` was not contradictory. |
| 39 | + */ |
| 40 | +predicate isBlockedByContradictoryGuardNodes(BasicBlock block, ConditionGuardNode guard) { |
| 41 | + RangeAnalysis::isContradictoryGuardNode(guard) and |
| 42 | + isReachable(block.getAPredecessor()) and // the guard itself is reachable |
| 43 | + block = guard.getBasicBlock() |
| 44 | + or |
| 45 | + isBlockedByContradictoryGuardNodes(block.getAPredecessor(), guard) and |
| 46 | + not isReachable(block) |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Holds if the given guard node is contradictory and causes an expression or statement to be unreachable. |
| 51 | + */ |
| 52 | +predicate isGuardNodeWithDeadCode(ConditionGuardNode guard) { |
| 53 | + exists (BasicBlock block | |
| 54 | + isBlockedByContradictoryGuardNodes(block, guard) and |
| 55 | + block.getANode() instanceof ExprOrStmt) |
| 56 | +} |
| 57 | + |
| 58 | +from ConditionGuardNode guard |
| 59 | +where isGuardNodeWithDeadCode(guard) |
| 60 | +select guard.getTest(), "The condition '" + guard.getTest() + "' is always " + guard.getOutcome().booleanNot() + "." |
0 commit comments