-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
VariableReferenceCheck.java
457 lines (409 loc) · 17.6 KB
/
VariableReferenceCheck.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
import com.google.javascript.jscomp.ReferenceCollectingCallback.Behavior;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Checks variables to see if they are referenced before their declaration, or
* if they are redeclared in a way that is suspicious (i.e. not dictated by
* control structures). This is a more aggressive version of {@link VarCheck},
* but it lacks the cross-module checks.
*
* @author kushal@google.com (Kushal Dave)
*/
class VariableReferenceCheck implements HotSwapCompilerPass {
static final DiagnosticType EARLY_REFERENCE =
DiagnosticType.warning(
"JSC_REFERENCE_BEFORE_DECLARE", "Variable referenced before declaration: {0}");
static final DiagnosticType REDECLARED_VARIABLE =
DiagnosticType.warning("JSC_REDECLARED_VARIABLE", "Redeclared variable: {0}");
static final DiagnosticType EARLY_REFERENCE_ERROR =
DiagnosticType.error(
"JSC_REFERENCE_BEFORE_DECLARE_ERROR",
"Illegal variable reference before declaration: {0}");
static final DiagnosticType REASSIGNED_CONSTANT =
DiagnosticType.error("JSC_REASSIGNED_CONSTANT", "Constant reassigned: {0}");
static final DiagnosticType REDECLARED_VARIABLE_ERROR =
DiagnosticType.error("JSC_REDECLARED_VARIABLE_ERROR", "Illegal redeclared variable: {0}");
static final DiagnosticType DECLARATION_NOT_DIRECTLY_IN_BLOCK =
DiagnosticType.error(
"JSC_DECLARATION_NOT_DIRECTLY_IN_BLOCK",
"Block-scoped declaration not directly within block: {0}");
static final DiagnosticType UNUSED_LOCAL_ASSIGNMENT =
DiagnosticType.disabled(
"JSC_UNUSED_LOCAL_ASSIGNMENT", "Value assigned to local variable {0} is never read");
private final AbstractCompiler compiler;
// If true, the pass will only check code that is at least ES6. Certain errors in block-scoped
// variable declarations will prevent correct transpilation, so this pass must be run.
private final boolean forTranspileOnly;
private final boolean checkUnusedLocals;
// NOTE(nicksantos): It's a lot faster to use a shared Set that
// we clear after each method call, because the Set never gets too big.
private final Set<BasicBlock> blocksWithDeclarations = new HashSet<>();
// These types do not permit a block-scoped declaration inside them without an explicit block.
// e.g. if (b) let x;
private static final ImmutableSet<Token> BLOCKLESS_DECLARATION_FORBIDDEN_STATEMENTS =
Sets.immutableEnumSet(Token.IF, Token.FOR, Token.FOR_IN, Token.FOR_OF, Token.WHILE);
public VariableReferenceCheck(AbstractCompiler compiler) {
this(compiler, false);
}
VariableReferenceCheck(AbstractCompiler compiler, boolean forTranspileOnly) {
this.compiler = compiler;
this.forTranspileOnly = forTranspileOnly;
this.checkUnusedLocals = compiler.getOptions().enables(DiagnosticGroups.UNUSED_LOCAL_VARIABLE);
}
private boolean shouldProcess(Node root) {
if (!forTranspileOnly) {
return true;
}
if (compiler.getOptions().getLanguageIn().toFeatureSet().contains(FeatureSet.ES6)) {
for (Node singleRoot : root.children()) {
if (TranspilationPasses.isScriptEs6ImplOrHigher(singleRoot)) {
return true;
}
}
}
return false;
}
@Override
public void process(Node externs, Node root) {
if (shouldProcess(root)) {
new ReferenceCollectingCallback(
compiler, new ReferenceCheckingBehavior(), new Es6SyntacticScopeCreator(compiler))
.process(externs, root);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
if (!forTranspileOnly
|| (compiler.getOptions().getLanguageIn().toFeatureSet().contains(FeatureSet.ES6)
&& TranspilationPasses.isScriptEs6ImplOrHigher(scriptRoot))) {
new ReferenceCollectingCallback(
compiler, new ReferenceCheckingBehavior(), new Es6SyntacticScopeCreator(compiler))
.hotSwapScript(scriptRoot, originalRoot);
}
}
/**
* Behavior that checks variables for redeclaration or early references
* just after they go out of scope.
*/
private class ReferenceCheckingBehavior implements Behavior {
private Set<String> varsInFunctionBody;
private ReferenceCheckingBehavior() {
varsInFunctionBody = new HashSet<>();
}
@Override
public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) {
// TODO(bashir) In hot-swap version this means that for global scope we
// only go through all global variables accessed in the modified file not
// all global variables. This should be fixed.
// Check all vars after finishing a scope
Scope scope = t.getScope();
if (scope.isFunctionBlockScope()) {
varsInFunctionBody.clear();
for (Var v : scope.getVarIterable()) {
varsInFunctionBody.add(v.name);
}
}
for (Var v : scope.getVarIterable()) {
ReferenceCollection referenceCollection = referenceMap.getReferences(v);
// TODO(moz): Figure out why this could be null
if (referenceCollection != null) {
if (scope.getRootNode().isFunction() && v.isDefaultParam()) {
checkDefaultParam(v, scope, varsInFunctionBody);
}
if (scope.getRootNode().isFunction()) {
checkShadowParam(v, scope, referenceCollection.references);
}
checkVar(v, referenceCollection.references);
}
}
}
private void checkDefaultParam(
Var param, final Scope scope, final Set<String> varsInFunctionBody) {
NodeTraversal.traverseEs6(
compiler,
param.getParentNode().getSecondChild(),
/**
* Do a shallow check since cases like:
* function f(y = () => x, x = 5) { return y(); }
* is legal. We are going to miss cases like:
* function f(y = (() => x)(), x = 5) { return y(); }
* but this should be rare.
*/
new AbstractShallowCallback() {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (!NodeUtil.isReferenceName(n)) {
return;
}
String refName = n.getString();
if (varsInFunctionBody.contains(refName) && !scope.isDeclared(refName, true)) {
compiler.report(JSError.make(n, EARLY_REFERENCE_ERROR, refName));
}
}
});
}
private void checkShadowParam(Var v, Scope functionScope, List<Reference> references) {
Var maybeParam = functionScope.getVar(v.getName());
if (maybeParam != null && maybeParam.isParam() && maybeParam.getScope() == functionScope) {
for (Reference r : references) {
if ((r.isVarDeclaration() || r.isHoistedFunction())
&& r.getNode() != v.getNameNode()) {
compiler.report(JSError.make(r.getNode(), REDECLARED_VARIABLE, v.name));
}
}
}
}
/**
* If the variable is declared more than once in a basic block, generate a
* warning. Also check if a variable is used in a given scope before it is
* declared, which suggest a likely error. Relies on the fact that
* references is in parse-tree order.
*/
private void checkVar(Var v, List<Reference> references) {
blocksWithDeclarations.clear();
boolean hasSeenDeclaration = false;
boolean hasErrors = false;
boolean isRead = false;
Reference unusedAssignment = null;
Reference hoistedFn = lookForHoistedFunction(references);
if (hoistedFn != null) {
hasSeenDeclaration = true;
}
for (Reference reference : references) {
if (reference == hoistedFn) {
continue;
}
Node referenceNode = reference.getNode();
BasicBlock basicBlock = reference.getBasicBlock();
boolean isDeclaration = reference.isDeclaration();
boolean isAssignment = isDeclaration || reference.isLvalue();
if (isDeclaration) {
// Checks for declarations
hasSeenDeclaration = true;
hasErrors = checkRedeclaration(v, reference, referenceNode, hoistedFn, basicBlock);
// Add the current basic block after checking redeclarations
blocksWithDeclarations.add(basicBlock);
checkBlocklessDeclaration(v, reference, referenceNode);
} else {
// Checks for references
if (!hasSeenDeclaration) {
hasErrors = checkEarlyReference(v, reference, referenceNode);
}
if (!hasErrors && v.isConst() && reference.isLvalue()) {
compiler.report(JSError.make(referenceNode, REASSIGNED_CONSTANT, v.name));
}
// Check for temporal dead zone of let / const declarations in for-in and for-of loops
if ((v.isLet() || v.isConst()) && v.getScope() == reference.getScope()
&& NodeUtil.isEnhancedFor(reference.getScope().getRootNode())) {
compiler.report(JSError.make(referenceNode, EARLY_REFERENCE_ERROR, v.name));
}
}
if (isAssignment) {
Reference decl = references.get(0);
Node declNode = decl.getNode();
Node gp = declNode.getGrandparent();
boolean lhsOfForInLoop = gp.isForIn() && gp.getFirstFirstChild() == declNode;
if (decl.getScope().isLocal()
&& (decl.isVarDeclaration() || decl.isLetDeclaration() || decl.isConstDeclaration())
&& !decl.getNode().isFromExterns()
&& !lhsOfForInLoop) {
unusedAssignment = reference;
}
if ((reference.getParent().isDec() || reference.getParent().isInc()
|| NodeUtil.isCompoundAssignmentOp(reference.getParent()))
&& NodeUtil.isExpressionResultUsed(reference.getNode())) {
isRead = true;
}
} else {
isRead = true;
}
}
if (checkUnusedLocals && unusedAssignment != null && !isRead && !hasErrors) {
checkForUnusedLocalVar(v, unusedAssignment);
}
}
}
/**
* @return The reference to the hoisted function, if the variable is one
*/
private Reference lookForHoistedFunction(List<Reference> references) {
for (Reference reference : references) {
if (reference.isHoistedFunction()) {
blocksWithDeclarations.add(reference.getBasicBlock());
return reference;
}
}
return null;
}
private void checkBlocklessDeclaration(Var v, Reference reference, Node referenceNode) {
if (!reference.isVarDeclaration() && reference.getGrandparent().isAddedBlock()
&& BLOCKLESS_DECLARATION_FORBIDDEN_STATEMENTS.contains(
reference.getGrandparent().getParent().getToken())) {
compiler.report(JSError.make(referenceNode, DECLARATION_NOT_DIRECTLY_IN_BLOCK, v.name));
}
}
/**
* @return If a redeclaration error has been found
*/
private boolean checkRedeclaration(
Var v, Reference reference, Node referenceNode, Reference hoistedFn, BasicBlock basicBlock) {
boolean allowDupe = VarCheck.hasDuplicateDeclarationSuppression(referenceNode, v);
boolean letConstShadowsVar = v.getParentNode().isVar()
&& (reference.isLetDeclaration() || reference.isConstDeclaration());
boolean isVarNodeSameAsReferenceNode = v.getNode() == reference.getNode();
// We disallow redeclaration of caught exceptions
boolean shadowCatchVar = v.getParentNode().isCatch() && !isVarNodeSameAsReferenceNode;
boolean shadowParam = v.isParam() && NodeUtil.isBlockScopedDeclaration(referenceNode)
&& v.getScope() == reference.getScope().getParent();
boolean shadowDetected = false;
if (!allowDupe) {
// Look through all the declarations we've found so far, and
// check if any of them are before this block.
for (BasicBlock declaredBlock : blocksWithDeclarations) {
if (declaredBlock.provablyExecutesBefore(basicBlock)) {
shadowDetected = true;
DiagnosticType diagnosticType;
Node warningNode = referenceNode;
if (v.isLet() || v.isConst() || v.isClass() || letConstShadowsVar || shadowCatchVar
|| shadowParam) {
// These cases are all hard errors that violate ES6 semantics
diagnosticType = REDECLARED_VARIABLE_ERROR;
} else if (reference.getNode().getParent().isCatch() || allowDupe) {
return false;
} else {
// These diagnostics are for valid, but suspicious, code, and are suppressible.
// For vars defined in the global scope, give the same error as VarCheck
diagnosticType =
v.getScope().isGlobal()
? VarCheck.VAR_MULTIPLY_DECLARED_ERROR
: REDECLARED_VARIABLE;
// Since we skip hoisted functions, we would have the wrong warning node in cases
// where the redeclaration is a function declaration. Check for that case.
if (isVarNodeSameAsReferenceNode
&& hoistedFn != null
&& v.name.equals(hoistedFn.getNode().getString())) {
warningNode = hoistedFn.getNode();
}
}
compiler.report(
JSError.make(
warningNode,
diagnosticType,
v.name,
v.input != null ? v.input.getName() : "??"));
return true;
}
}
}
if (!shadowDetected && (letConstShadowsVar || shadowCatchVar)
&& v.getScope() == reference.getScope()) {
compiler.report(JSError.make(referenceNode, REDECLARED_VARIABLE_ERROR, v.name));
return true;
}
return false;
}
/**
* @return If an early reference has been found
*/
private boolean checkEarlyReference(Var v, Reference reference, Node referenceNode) {
// Don't check the order of refer in externs files.
if (!referenceNode.isFromExterns()) {
// Special case to deal with var goog = goog || {}. Note that
// let x = x || {} is illegal, just like var y = x || {}; let x = y;
if (v.isVar()) {
Node curr = reference.getParent();
while (curr.isOr() && curr.getParent().getFirstChild() == curr) {
curr = curr.getParent();
}
if (curr.isName() && curr.getString().equals(v.name)) {
return false;
}
}
// Only generate warnings if the scopes do not match in order
// to deal with possible forward declarations and recursion
// TODO(moz): See if we can remove the bypass for "goog"
if (reference.getScope() == v.scope && !v.getName().equals("goog")) {
compiler.report(
JSError.make(
reference.getNode(),
(v.isLet() || v.isConst() || v.isClass() || v.isParam())
? EARLY_REFERENCE_ERROR
: EARLY_REFERENCE,
v.name));
return true;
}
}
return false;
}
// Only check for unused local if not in a goog.scope function.
// TODO(tbreisacher): Consider moving UNUSED_LOCAL_ASSIGNMENT into its own check pass, so
// that we can run it after goog.scope processing, and get rid of the inGoogScope check.
private void checkForUnusedLocalVar(Var v, Reference unusedAssignment) {
if (!v.isLocal()) {
return;
}
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(unusedAssignment.getNode());
if (jsDoc != null && jsDoc.hasTypedefType()) {
return;
}
boolean inGoogScope = false;
Scope s = v.getScope();
Node function = null;
if (s.isFunctionBlockScope()) {
function = s.getRootNode().getParent();
} else if (s.isFunctionScope()) {
// TODO(tbreisacher): Remove this branch when everything is switched to
// Es6SyntacticScopeCreator.
function = s.getRootNode();
}
if (function != null) {
Node callee = function.getPrevious();
inGoogScope = callee != null && callee.matchesQualifiedName("goog.scope");
}
if (inGoogScope) {
// No warning.
return;
}
if (s.isModuleScope()) {
Node statement = NodeUtil.getEnclosingStatement(v.getNode());
if (NodeUtil.isNameDeclaration(statement)) {
Node lhs = statement.getFirstChild();
Node rhs = lhs.getFirstChild();
if (rhs != null
&& (NodeUtil.isCallTo(rhs, "goog.forwardDeclare")
|| NodeUtil.isCallTo(rhs, "goog.require")
|| rhs.isQualifiedName())) {
// No warning. goog.{require,forwardDeclare} will be caught by the unused-require check,
// and if the right side is a qualified name then this is likely an alias used in type
// annotations.
return;
}
}
}
compiler.report(JSError.make(unusedAssignment.getNode(), UNUSED_LOCAL_ASSIGNMENT, v.name));
}
}