Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.base.Preconditions;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26
27 import java.util.Set;
28
29 /**
30 * Checks that all variables are declared, that file-private variables are
31 * accessed only in the file that declares them, and that any var references
32 * that cross module boundaries respect declared module dependencies.
33 *
34 */
35 class VarCheck extends AbstractPostOrderCallback implements
36 HotSwapCompilerPass {
37
38 static final DiagnosticType UNDEFINED_VAR_ERROR = DiagnosticType.error(
39 "JSC_UNDEFINED_VARIABLE",
40 "variable {0} is undeclared");
41
42 static final DiagnosticType VIOLATED_MODULE_DEP_ERROR = DiagnosticType.error(
43 "JSC_VIOLATED_MODULE_DEPENDENCY",
44 "module {0} cannot reference {2}, defined in " +
45 "module {1}, since {1} loads after {0}");
46
47 static final DiagnosticType MISSING_MODULE_DEP_ERROR = DiagnosticType.warning(
48 "JSC_MISSING_MODULE_DEPENDENCY",
49 "missing module dependency; module {0} should depend " +
50 "on module {1} because it references {2}");
51
52 static final DiagnosticType STRICT_MODULE_DEP_ERROR = DiagnosticType.disabled(
53 "JSC_STRICT_MODULE_DEPENDENCY",
54 "module {0} cannot reference {2}, defined in " +
55 "module {1}");
56
57 static final DiagnosticType NAME_REFERENCE_IN_EXTERNS_ERROR =
58 DiagnosticType.warning(
59 "JSC_NAME_REFERENCE_IN_EXTERNS",
60 "accessing name {0} in externs has no effect");
61
62 static final DiagnosticType UNDEFINED_EXTERN_VAR_ERROR =
63 DiagnosticType.warning(
64 "JSC_UNDEFINED_EXTERN_VAR_ERROR",
65 "name {0} is not undefined in the externs.");
66
67 private Node synthesizedExternsRoot = null;
68
69 // Vars that still need to be declared in externs. These will be declared
70 // at the end of the pass, or when we see the equivalent var declared
71 // in the normal code.
72 private final Set<String> varsToDeclareInExterns = Sets.newHashSet();
73
74 private final AbstractCompiler compiler;
75
76 // Whether this is the post-processing sanity check.
77 private final boolean sanityCheck;
78
79 // Whether extern checks emit error.
80 private final boolean strictExternCheck;
81
82 VarCheck(AbstractCompiler compiler) {
83 this(compiler, false);
84 }
85
86 VarCheck(AbstractCompiler compiler, boolean sanityCheck) {
87 this.compiler = compiler;
88 this.strictExternCheck = compiler.getErrorLevel(
89 JSError.make("", 0, 0, UNDEFINED_EXTERN_VAR_ERROR)) == CheckLevel.ERROR;
90 this.sanityCheck = sanityCheck;
91 }
92
93 @Override
94 public void process(Node externs, Node root) {
95 // Don't run externs-checking in sanity check mode. Normalization will
96 // remove duplicate VAR declarations, which will make
97 // externs look like they have assigns.
98 if (!sanityCheck) {
99 NodeTraversal.traverse(compiler, externs, new NameRefInExternsCheck());
100 }
101
102 NodeTraversal.traverseRoots(
103 compiler, Lists.newArrayList(externs, root), this);
104 for (String varName : varsToDeclareInExterns) {
105 createSynthesizedExternVar(varName);
106 }
107 }
108
109 @Override
110 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
111 Preconditions.checkState(scriptRoot.isScript());
112 NodeTraversal t = new NodeTraversal(compiler, this);
113 // Note we use the global scope to prevent wrong "undefined-var errors" on
114 // variables that are defined in other JS files.
115 t.traverseWithScope(scriptRoot,
116 SyntacticScopeCreator.generateUntypedTopScope(compiler));
117 // TODO(bashir) Check if we need to createSynthesizedExternVar like process.
118 }
119
120 @Override
121 public void visit(NodeTraversal t, Node n, Node parent) {
122 if (!n.isName()) {
123 return;
124 }
125
126 String varName = n.getString();
127
128 // Only a function can have an empty name.
129 if (varName.isEmpty()) {
130 Preconditions.checkState(parent.isFunction());
131 Preconditions.checkState(NodeUtil.isFunctionExpression(parent));
132 return;
133 }
134
135 // Check if this is a declaration for a var that has been declared
136 // elsewhere. If so, mark it as a duplicate.
137 if ((parent.isVar() ||
138 NodeUtil.isFunctionDeclaration(parent)) &&
139 varsToDeclareInExterns.contains(varName)) {
140 createSynthesizedExternVar(varName);
141
142 n.addSuppression("duplicate");
143 }
144
145 // Check that the var has been declared.
146 Scope scope = t.getScope();
147 Scope.Var var = scope.getVar(varName);
148 if (var == null) {
149 if (NodeUtil.isFunctionExpression(parent)) {
150 // e.g. [ function foo() {} ], it's okay if "foo" isn't defined in the
151 // current scope.
152 } else {
153 // The extern checks are stricter, don't report a second error.
154 if (!strictExternCheck || !t.getInput().isExtern()) {
155 t.report(n, UNDEFINED_VAR_ERROR, varName);
156 }
157
158 if (sanityCheck) {
159 throw new IllegalStateException("Unexpected variable " + varName);
160 } else {
161 createSynthesizedExternVar(varName);
162 scope.getGlobalScope().declare(varName, n,
163 null, getSynthesizedExternsInput());
164 }
165 }
166 return;
167 }
168
169 CompilerInput currInput = t.getInput();
170 CompilerInput varInput = var.input;
171 if (currInput == varInput || currInput == null || varInput == null) {
172 // The variable was defined in the same file. This is fine.
173 return;
174 }
175
176 // Check module dependencies.
177 JSModule currModule = currInput.getModule();
178 JSModule varModule = varInput.getModule();
179 JSModuleGraph moduleGraph = compiler.getModuleGraph();
180 if (!sanityCheck &&
181 varModule != currModule && varModule != null && currModule != null) {
182 if (moduleGraph.dependsOn(currModule, varModule)) {
183 // The module dependency was properly declared.
184 } else {
185 if (scope.isGlobal()) {
186 if (moduleGraph.dependsOn(varModule, currModule)) {
187 // The variable reference violates a declared module dependency.
188 t.report(n, VIOLATED_MODULE_DEP_ERROR,
189 currModule.getName(), varModule.getName(), varName);
190 } else {
191 // The variable reference is between two modules that have no
192 // dependency relationship. This should probably be considered an
193 // error, but just issue a warning for now.
194 t.report(n, MISSING_MODULE_DEP_ERROR,
195 currModule.getName(), varModule.getName(), varName);
196 }
197 } else {
198 t.report(n, STRICT_MODULE_DEP_ERROR,
199 currModule.getName(), varModule.getName(), varName);
200 }
201 }
202 }
203 }
204
205 /**
206 * Create a new variable in a synthetic script. This will prevent
207 * subsequent compiler passes from crashing.
208 */
209 private void createSynthesizedExternVar(String varName) {
210 Node nameNode = IR.name(varName);
211
212 // Mark the variable as constant if it matches the coding convention
213 // for constant vars.
214 // NOTE(nicksantos): honestly, I'm not sure how much this matters.
215 // AFAIK, all people who use the CONST coding convention also
216 // compile with undeclaredVars as errors. We have some test
217 // cases for this configuration though, and it makes them happier.
218 if (compiler.getCodingConvention().isConstant(varName)) {
219 nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true);
220 }
221
222 getSynthesizedExternsRoot().addChildToBack(
223 IR.var(nameNode));
224 varsToDeclareInExterns.remove(varName);
225 compiler.reportCodeChange();
226 }
227
228 /**
229 * A check for name references in the externs inputs. These used to prevent
230 * a variable from getting renamed, but no longer have any effect.
231 */
232 private class NameRefInExternsCheck extends AbstractPostOrderCallback {
233 @Override
234 public void visit(NodeTraversal t, Node n, Node parent) {
235 if (n.isName()) {
236 switch (parent.getType()) {
237 case Token.VAR:
238 case Token.FUNCTION:
239 case Token.PARAM_LIST:
240 // These are okay.
241 break;
242 case Token.GETPROP:
243 if (n == parent.getFirstChild()) {
244 Scope scope = t.getScope();
245 Scope.Var var = scope.getVar(n.getString());
246 if (var == null) {
247 t.report(n, UNDEFINED_EXTERN_VAR_ERROR, n.getString());
248 varsToDeclareInExterns.add(n.getString());
249 }
250 }
251 break;
252 default:
253 t.report(n, NAME_REFERENCE_IN_EXTERNS_ERROR, n.getString());
254
255 Scope scope = t.getScope();
256 Scope.Var var = scope.getVar(n.getString());
257 if (var == null) {
258 varsToDeclareInExterns.add(n.getString());
259 }
260 break;
261 }
262 }
263 }
264 }
265
266 /** Lazily create a "new" externs input for undeclared variables. */
267 private CompilerInput getSynthesizedExternsInput() {
268 return compiler.getSynthesizedExternsInput();
269 }
270
271 /** Lazily create a "new" externs root for undeclared variables. */
272 private Node getSynthesizedExternsRoot() {
273 if (synthesizedExternsRoot == null) {
274 CompilerInput synthesizedExterns = getSynthesizedExternsInput();
275 synthesizedExternsRoot = synthesizedExterns.getAstRoot(compiler);
276 }
277 return synthesizedExternsRoot;
278 }
279 }