Merge pull request #557 from esben-semmle/js/unused-react-variable

Approved by xiemaisi
This commit is contained in:
semmle-qlci
2018-11-30 09:35:36 +00:00
committed by GitHub
8 changed files with 54 additions and 16 deletions

View File

@@ -49,24 +49,29 @@ predicate isPropertyFilter(UnusedLocal v) {
)
}
predicate hasJsxInScope(UnusedLocal v) {
any(JSXNode n).getParent+() = v.getScope().getScopeElement()
}
/**
* Holds if `v` is an import of React, and there is a JSX element that implicitly
* references it.
*/
predicate isReactImportForJSX(UnusedLocal v) {
exists (ImportSpecifier is |
is.getLocal() = v.getADeclaration() and
exists (JSXNode jsx | jsx.getTopLevel() = is.getTopLevel())
|
* Holds if `v` is a "React" variable that is implicitly used by a JSX element.
*/
predicate isReactForJSX(UnusedLocal v) {
hasJsxInScope(v) and
(
v.getName() = "React"
or
// legacy `@jsx` pragmas
exists (JSXPragma p | p.getTopLevel() = is.getTopLevel() | p.getDOMName() = v.getName())
or
// JSX pragma from a .babelrc file
exists (Babel::TransformReactJsxConfig plugin |
plugin.appliesTo(is.getTopLevel()) and
plugin.getJsxFactoryVariableName() = v.getName())
exists(TopLevel tl |
tl = v.getADeclaration().getTopLevel() |
// legacy `@jsx` pragmas
exists(JSXPragma p | p.getTopLevel() = tl | p.getDOMName() = v.getName())
or
// JSX pragma from a .babelrc file
exists(Babel::TransformReactJsxConfig plugin |
plugin.appliesTo(tl) and
plugin.getJsxFactoryVariableName() = v.getName()
)
)
)
}
@@ -150,7 +155,7 @@ predicate whitelisted(UnusedLocal v) {
// exclude variables used to filter out unwanted properties
isPropertyFilter(v) or
// exclude imports of React that are implicitly referenced by JSX
isReactImportForJSX(v) or
isReactForJSX(v) or
// exclude names that are used as types
exists (VarDecl vd |
v = vd.getVariable() |

View File

@@ -7,6 +7,7 @@
| importWithoutPragma.jsx:1:1:1:27 | import ... react'; | Unused import h. |
| multi-imports.js:1:1:1:29 | import ... om 'x'; | Unused imports a, b, d. |
| 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. |
| 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,2 @@
var React = x; // OK
(<e/>);

View File

@@ -0,0 +1,2 @@
var React = require("probably-react"); // OK
(<e/>);

View File

@@ -0,0 +1,2 @@
var { React } = { React: require("probably-react") }; // OK
(<e/>);

View File

@@ -0,0 +1,2 @@
var { React } = require("probably-react"); // OK
(<e/>);

View File

@@ -0,0 +1,6 @@
(function() {
var React = require("probably-react"); // NOT OK
})
(function() {
(<e/>);
})