Debian Codegraph @

src/com/google/javascript/jscomp/VariableReferenceCheck.java

raw symbols SCIP
1 /*
2 * Copyright 2008 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.collect.Sets;
20 import com.google.javascript.jscomp.ReferenceCollectingCallback.BasicBlock;
21 import com.google.javascript.jscomp.ReferenceCollectingCallback.Behavior;
22 import com.google.javascript.jscomp.ReferenceCollectingCallback.Reference;
23 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceMap;
24 import com.google.javascript.jscomp.Scope.Var;
25 import com.google.javascript.rhino.Node;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Set;
29
30 /**
31 * Checks variables to see if they are referenced before their declaration, or
32 * if they are redeclared in a way that is suspicious (i.e. not dictated by
33 * control structures). This is a more aggressive version of {@link VarCheck},
34 * but it lacks the cross-module checks.
35 *
36 * @author [email protected] (Kushal Dave)
37 */
38 class VariableReferenceCheck implements HotSwapCompilerPass {
39
40 static final DiagnosticType UNDECLARED_REFERENCE = DiagnosticType.warning(
41 "JSC_REFERENCE_BEFORE_DECLARE",
42 "Variable referenced before declaration: {0}");
43
44 static final DiagnosticType REDECLARED_VARIABLE = DiagnosticType.warning(
45 "JSC_REDECLARED_VARIABLE",
46 "Redeclared variable: {0}");
47
48 static final DiagnosticType AMBIGUOUS_FUNCTION_DECL =
49 DiagnosticType.disabled("AMBIGUOUS_FUNCTION_DECL",
50 "Ambiguous use of a named function: {0}.");
51
52 private final AbstractCompiler compiler;
53 private final CheckLevel checkLevel;
54
55 // NOTE(nicksantos): It's a lot faster to use a shared Set that
56 // we clear after each method call, because the Set never gets too big.
57 private final Set<BasicBlock> blocksWithDeclarations = Sets.newHashSet();
58
59 public VariableReferenceCheck(AbstractCompiler compiler,
60 CheckLevel checkLevel) {
61 this.compiler = compiler;
62 this.checkLevel = checkLevel;
63 }
64
65 @Override
66 public void process(Node externs, Node root) {
67 ReferenceCollectingCallback callback = new ReferenceCollectingCallback(
68 compiler, new ReferenceCheckingBehavior());
69 callback.process(externs, root);
70 }
71
72 @Override
73 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
74 ReferenceCollectingCallback callback = new ReferenceCollectingCallback(
75 compiler, new ReferenceCheckingBehavior());
76 callback.hotSwapScript(scriptRoot, originalRoot);
77 }
78
79 /**
80 * Behavior that checks variables for redeclaration or early references
81 * just after they go out of scope.
82 */
83 private class ReferenceCheckingBehavior implements Behavior {
84
85 @Override
86 public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) {
87 // TODO(bashir) In hot-swap version this means that for global scope we
88 // only go through all global variables accessed in the modified file not
89 // all global variables. This should be fixed.
90
91 // Check all vars after finishing a scope
92 for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
93 Var v = it.next();
94 checkVar(v, referenceMap.getReferences(v).references);
95 }
96 }
97
98 /**
99 * If the variable is declared more than once in a basic block, generate a
100 * warning. Also check if a variable is used in a given scope before it is
101 * declared, which suggest a likely error. Relies on the fact that
102 * references is in parse-tree order.
103 */
104 private void checkVar(Var v, List<Reference> references) {
105 blocksWithDeclarations.clear();
106 boolean isDeclaredInScope = false;
107 boolean isUnhoistedNamedFunction = false;
108 Reference hoistedFn = null;
109
110 // Look for hoisted functions.
111 for (Reference reference : references) {
112 if (reference.isHoistedFunction()) {
113 blocksWithDeclarations.add(reference.getBasicBlock());
114 isDeclaredInScope = true;
115 hoistedFn = reference;
116 break;
117 } else if (NodeUtil.isFunctionDeclaration(
118 reference.getNode().getParent())) {
119 isUnhoistedNamedFunction = true;
120 }
121 }
122
123 for (Reference reference : references) {
124 if (reference == hoistedFn) {
125 continue;
126 }
127
128 BasicBlock basicBlock = reference.getBasicBlock();
129 boolean isDeclaration = reference.isDeclaration();
130
131 boolean allowDupe =
132 SyntacticScopeCreator.hasDuplicateDeclarationSuppression(
133 reference.getNode(), v);
134 if (isDeclaration && !allowDupe) {
135 // Look through all the declarations we've found so far, and
136 // check if any of them are before this block.
137 for (BasicBlock declaredBlock : blocksWithDeclarations) {
138 if (declaredBlock.provablyExecutesBefore(basicBlock)) {
139 // TODO(johnlenz): Fix AST generating clients that so they would
140 // have property StaticSourceFile attached at each node. Or
141 // better yet, make sure the generated code never violates
142 // the requirement to pass aggressive var check!
143 String filename = NodeUtil.getSourceName(reference.getNode());
144 compiler.report(
145 JSError.make(filename,
146 reference.getNode(),
147 checkLevel,
148 REDECLARED_VARIABLE, v.name));
149 break;
150 }
151 }
152 }
153
154 if (isUnhoistedNamedFunction && !isDeclaration && isDeclaredInScope) {
155 // Only allow an unhoisted named function to be used within the
156 // block it is declared.
157 for (BasicBlock declaredBlock : blocksWithDeclarations) {
158 if (!declaredBlock.provablyExecutesBefore(basicBlock)) {
159 String filename = NodeUtil.getSourceName(reference.getNode());
160 compiler.report(
161 JSError.make(filename,
162 reference.getNode(),
163 AMBIGUOUS_FUNCTION_DECL, v.name));
164 break;
165 }
166 }
167 }
168
169 if (!isDeclaration && !isDeclaredInScope) {
170 // Don't check the order of refer in externs files.
171 if (!reference.getNode().isFromExterns()) {
172 // Special case to deal with var goog = goog || {}
173 Node grandparent = reference.getGrandparent();
174 if (grandparent.isName()
175 && grandparent.getString() == v.name) {
176 continue;
177 }
178
179 // Only generate warnings if the scopes do not match in order
180 // to deal with possible forward declarations and recursion
181 if (reference.getScope() == v.scope) {
182 String filename = NodeUtil.getSourceName(reference.getNode());
183 compiler.report(
184 JSError.make(filename,
185 reference.getNode(),
186 checkLevel,
187 UNDECLARED_REFERENCE, v.name));
188 }
189 }
190 }
191
192 if (isDeclaration) {
193 blocksWithDeclarations.add(basicBlock);
194 isDeclaredInScope = true;
195 }
196 }
197 }
198 }
199 }