|
| 1 | +/** |
| 2 | + * @name Unreachable code |
| 3 | + * @description Code that cannot be reached should be deleted. |
| 4 | + * @kind problem |
| 5 | + * @problem.severity recommendation |
| 6 | + * @precision medium |
| 7 | + * @id rust/dead-code |
| 8 | + * @tags maintainability |
| 9 | + */ |
| 10 | + |
| 11 | +import rust |
| 12 | +import codeql.rust.controlflow.ControlFlowGraph |
| 13 | +import codeql.rust.controlflow.internal.ControlFlowGraphImpl as ControlFlowGraphImpl |
| 14 | + |
| 15 | +/** |
| 16 | + * Holds if `n` is an AST node that's unreachable. |
| 17 | + */ |
| 18 | +private predicate unreachable(AstNode n) { |
| 19 | + not n = any(CfgNode cfn).getAstNode() and // reachable nodes |
| 20 | + exists(ControlFlowGraphImpl::ControlFlowTree cft | |
| 21 | + // nodes intended to be part of the CFG |
| 22 | + cft.succ(n, _, _) |
| 23 | + or |
| 24 | + cft.succ(_, n, _) |
| 25 | + ) |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Holds if `n` is an AST node that's unreachable, and is not the successor |
| 30 | + * of an unreachable node (which would be a duplicate result). |
| 31 | + */ |
| 32 | +private predicate firstUnreachable(AstNode n) { |
| 33 | + unreachable(n) and |
| 34 | + ( |
| 35 | + // no predecessor -> we are the first unreachable node. |
| 36 | + not ControlFlowGraphImpl::succ(_, n, _) |
| 37 | + or |
| 38 | + // reachable predecessor -> we are the first unreachable node. |
| 39 | + exists(AstNode pred | |
| 40 | + ControlFlowGraphImpl::succ(pred, n, _) and |
| 41 | + not unreachable(pred) |
| 42 | + ) |
| 43 | + ) |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Gets a node we'd prefer not to report as unreachable. |
| 48 | + */ |
| 49 | +predicate skipNode(AstNode n) { |
| 50 | + n instanceof ControlFlowGraphImpl::PostOrderTree or // location is counter-intuitive |
| 51 | + not n instanceof ControlFlowGraphImpl::ControlFlowTree // not expected to be reachable |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Gets the `ControlFlowTree` successor of a node we'd prefer not to report. |
| 56 | + */ |
| 57 | +AstNode skipSuccessor(AstNode n) { |
| 58 | + skipNode(n) and |
| 59 | + ControlFlowGraphImpl::succ(n, result, _) |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Gets the node `n`, skipping past any nodes we'd prefer not to report. |
| 64 | + */ |
| 65 | +AstNode skipSuccessors(AstNode n) { |
| 66 | + result = skipSuccessor*(n) and |
| 67 | + not skipNode(result) |
| 68 | +} |
| 69 | + |
| 70 | +from AstNode first, AstNode report |
| 71 | +where |
| 72 | + firstUnreachable(first) and |
| 73 | + report = skipSuccessors(first) and |
| 74 | + exists(report.getFile().getRelativePath()) // in source |
| 75 | +select report, "This code is never reached." |
0 commit comments