JavaScript: Teach Unused{Variable,Parameter} to ignore variables with leading underscore.

This commit is contained in:
Max Schaefer
2018-12-11 08:49:17 +00:00
parent a4b3b1e8c8
commit 4d186e0edc
7 changed files with 26 additions and 5 deletions

View File

@@ -9,7 +9,7 @@
*/
import javascript
import UnusedParameter // local library
import UnusedParameter
from Parameter p
where isAnAccidentallyUnusedParameter(p)

View File

@@ -46,7 +46,9 @@ predicate isUnused(Function f, Parameter p, Variable pv, int i) {
// functions without a body cannot use their parameters
f.hasBody() and
// field parameters are used to initialize a field
not p instanceof FieldParameter
not p instanceof FieldParameter and
// common convention: parameters with leading underscore are intentionally unused
pv.getName().charAt(0) != "_"
}
/**

View File

@@ -22,7 +22,9 @@ class UnusedLocal extends LocalVariable {
not exists(FunctionExpr fe | this = fe.getVariable()) and
not exists(ClassExpr ce | this = ce.getVariable()) and
not exists(ExportDeclaration ed | ed.exportsAs(this, _)) and
not exists(LocalVarTypeAccess type | type.getVariable() = this)
not exists(LocalVarTypeAccess type | type.getVariable() = this) and
// common convention: variables with leading underscore are intentionally unused
getName().charAt(0) != "_"
}
}

View File

@@ -33,4 +33,8 @@ var g = f3;
// OK
define(function (require, exports, module) {
module.x = 23;
});
});
// OK: starts with underscore
function f(_p) {
}

View File

@@ -9,5 +9,7 @@
| multi-imports.js:2:1:2:42 | import ... om 'x'; | Unused imports alphabetically, ordered. |
| require-react-in-other-scope.js:2:9:2:13 | React | Unused variable React. |
| typeoftype.ts:9:7:9:7 | y | Unused variable y. |
| underscore.js:6:7:6:7 | e | Unused variable e. |
| underscore.js:7:7:7:7 | f | Unused variable f. |
| unusedShadowed.ts:1:1:1:26 | import ... where'; | Unused import T. |
| unusedShadowed.ts:2:1:2:31 | import ... where'; | Unused import object. |

View File

@@ -0,0 +1,10 @@
function f(a) {
const [a, // OK: used
_, // OK: starts with underscore
_c, // OK: starts with underscore
d, // OK: used
e, // NOT OK
f] // NOT OK
= a;
return a + d;
}