Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2006 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.javascript.rhino.InputId;
21 import com.google.javascript.rhino.JSDocInfo;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24
25
26 /**
27 * <p>The syntactic scope creator scans the parse tree to create a Scope object
28 * containing all the variable declarations in that scope.</p>
29 *
30 * <p>This implementation is not thread-safe.</p>
31 *
32 */
33 class SyntacticScopeCreator implements ScopeCreator {
34 private final AbstractCompiler compiler;
35 private Scope scope;
36 private InputId inputId;
37 private final RedeclarationHandler redeclarationHandler;
38
39 // The arguments variable is special, in that it's declared in every local
40 // scope, but not explicitly declared.
41 private static final String ARGUMENTS = "arguments";
42
43 public static final DiagnosticType VAR_MULTIPLY_DECLARED_ERROR =
44 DiagnosticType.error(
45 "JSC_VAR_MULTIPLY_DECLARED_ERROR",
46 "Variable {0} first declared in {1}");
47
48 public static final DiagnosticType VAR_ARGUMENTS_SHADOWED_ERROR =
49 DiagnosticType.error(
50 "JSC_VAR_ARGUMENTS_SHADOWED_ERROR",
51 "Shadowing \"arguments\" is not allowed");
52
53 /**
54 * Creates a ScopeCreator.
55 */
56 SyntacticScopeCreator(AbstractCompiler compiler) {
57 this.compiler = compiler;
58 this.redeclarationHandler = new DefaultRedeclarationHandler();
59 }
60
61 SyntacticScopeCreator(
62 AbstractCompiler compiler, RedeclarationHandler redeclarationHandler) {
63 this.compiler = compiler;
64 this.redeclarationHandler = redeclarationHandler;
65 }
66
67 @Override
68 public Scope createScope(Node n, Scope parent) {
69 inputId = null;
70 if (parent == null) {
71 scope = Scope.createGlobalScope(n);
72 } else {
73 scope = new Scope(parent, n);
74 }
75
76 scanRoot(n);
77
78 inputId = null;
79 Scope returnedScope = scope;
80 scope = null;
81 return returnedScope;
82 }
83
84 private void scanRoot(Node n) {
85 if (n.isFunction()) {
86 if (inputId == null) {
87 inputId = NodeUtil.getInputId(n);
88 // TODO(johnlenz): inputId maybe null if the FUNCTION node is detached
89 // from the AST.
90 // Is it meaningful to build a scope for detached FUNCTION node?
91 }
92
93 final Node fnNameNode = n.getFirstChild();
94 final Node args = fnNameNode.getNext();
95 final Node body = args.getNext();
96
97 // Bleed the function name into the scope, if it hasn't
98 // been declared in the outer scope.
99 String fnName = fnNameNode.getString();
100 if (!fnName.isEmpty() && NodeUtil.isFunctionExpression(n)) {
101 declareVar(fnNameNode);
102 }
103
104 // Args: Declare function variables
105 Preconditions.checkState(args.isParamList());
106 for (Node a = args.getFirstChild(); a != null;
107 a = a.getNext()) {
108 Preconditions.checkState(a.isName());
109 declareVar(a);
110 }
111
112 // Body
113 scanVars(body);
114 } else {
115 // It's the global block
116 Preconditions.checkState(scope.getParent() == null);
117 scanVars(n);
118 }
119 }
120
121 /**
122 * Scans and gather variables declarations under a Node
123 */
124 private void scanVars(Node n) {
125 switch (n.getType()) {
126 case Token.VAR:
127 // Declare all variables. e.g. var x = 1, y, z;
128 for (Node child = n.getFirstChild();
129 child != null;) {
130 Node next = child.getNext();
131 declareVar(child);
132 child = next;
133 }
134 return;
135
136 case Token.FUNCTION:
137 if (NodeUtil.isFunctionExpression(n)) {
138 return;
139 }
140
141 String fnName = n.getFirstChild().getString();
142 if (fnName.isEmpty()) {
143 // This is invalid, but allow it so the checks can catch it.
144 return;
145 }
146 declareVar(n.getFirstChild());
147 return; // should not examine function's children
148
149 case Token.CATCH:
150 Preconditions.checkState(n.getChildCount() == 2);
151 Preconditions.checkState(n.getFirstChild().isName());
152 // the first child is the catch var and the third child
153 // is the code block
154
155 final Node var = n.getFirstChild();
156 final Node block = var.getNext();
157
158 declareVar(var);
159 scanVars(block);
160 return; // only one child to scan
161
162 case Token.SCRIPT:
163 inputId = n.getInputId();
164 Preconditions.checkNotNull(inputId);
165 break;
166 }
167
168 // Variables can only occur in statement-level nodes, so
169 // we only need to traverse children in a couple special cases.
170 if (NodeUtil.isControlStructure(n) || NodeUtil.isStatementBlock(n)) {
171 for (Node child = n.getFirstChild();
172 child != null;) {
173 Node next = child.getNext();
174 scanVars(child);
175 child = next;
176 }
177 }
178 }
179
180 /**
181 * Interface for injectable duplicate handling.
182 */
183 interface RedeclarationHandler {
184 void onRedeclaration(
185 Scope s, String name, Node n, CompilerInput input);
186 }
187
188 /**
189 * The default handler for duplicate declarations.
190 */
191 private class DefaultRedeclarationHandler implements RedeclarationHandler {
192 @Override
193 public void onRedeclaration(
194 Scope s, String name, Node n, CompilerInput input) {
195 Node parent = n.getParent();
196
197 // Don't allow multiple variables to be declared at the top-level scope
198 if (scope.isGlobal()) {
199 Scope.Var origVar = scope.getVar(name);
200 Node origParent = origVar.getParentNode();
201 if (origParent.isCatch() &&
202 parent.isCatch()) {
203 // Okay, both are 'catch(x)' variables.
204 return;
205 }
206
207 boolean allowDupe = hasDuplicateDeclarationSuppression(n, origVar);
208
209 if (!allowDupe) {
210 compiler.report(
211 JSError.make(NodeUtil.getSourceName(n), n,
212 VAR_MULTIPLY_DECLARED_ERROR,
213 name,
214 (origVar.input != null
215 ? origVar.input.getName()
216 : "??")));
217 }
218 } else if (name.equals(ARGUMENTS) && !NodeUtil.isVarDeclaration(n)) {
219 // Disallow shadowing "arguments" as we can't handle with our current
220 // scope modeling.
221 compiler.report(
222 JSError.make(NodeUtil.getSourceName(n), n,
223 VAR_ARGUMENTS_SHADOWED_ERROR));
224 }
225 }
226 }
227
228 /**
229 * Declares a variable.
230 *
231 * @param n The node corresponding to the variable name.
232 */
233 private void declareVar(Node n) {
234 Preconditions.checkState(n.isName());
235
236 CompilerInput input = compiler.getInput(inputId);
237 String name = n.getString();
238 if (scope.isDeclared(name, false)
239 || (scope.isLocal() && name.equals(ARGUMENTS))) {
240 redeclarationHandler.onRedeclaration(
241 scope, name, n, input);
242 } else {
243 scope.declare(name, n, null, input);
244 }
245 }
246
247
248 /**
249 * @param n The name node to check.
250 * @param origVar The associated Var.
251 * @return Whether duplicated declarations warnings should be suppressed
252 * for the given node.
253 */
254 static boolean hasDuplicateDeclarationSuppression(Node n, Scope.Var origVar) {
255 Preconditions.checkState(n.isName());
256 Node parent = n.getParent();
257 Node origParent = origVar.getParentNode();
258
259 JSDocInfo info = n.getJSDocInfo();
260 if (info == null) {
261 info = parent.getJSDocInfo();
262 }
263 if (info != null && info.getSuppressions().contains("duplicate")) {
264 return true;
265 }
266
267 info = origVar.nameNode.getJSDocInfo();
268 if (info == null) {
269 info = origParent.getJSDocInfo();
270 }
271 return (info != null && info.getSuppressions().contains("duplicate"));
272 }
273
274 /**
275 * Generates an untyped global scope from the root of AST of compiler (which
276 * includes externs).
277 *
278 * @param compiler The compiler for which the scope is generated.
279 * @return The new untyped global scope generated as a result of this call.
280 */
281 static Scope generateUntypedTopScope(AbstractCompiler compiler) {
282 return new SyntacticScopeCreator(compiler).createScope(compiler.getRoot(),
283 null);
284 }
285
286
287 }