Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2010 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.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.CompilerOptions.AliasTransformation;
24 import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler;
25 import com.google.javascript.jscomp.Scope.Var;
26 import com.google.javascript.rhino.JSDocInfo;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.SourcePosition;
29 import com.google.javascript.rhino.Token;
30
31 import java.util.Collection;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35
36 import javax.annotation.Nullable;
37
38 /**
39 * Process aliases in goog.scope blocks.
40 *
41 * goog.scope(function() {
42 * var dom = goog.dom;
43 * var DIV = dom.TagName.DIV;
44 *
45 * dom.createElement(DIV);
46 * });
47 *
48 * should become
49 *
50 * goog.dom.createElement(goog.dom.TagName.DIV);
51 *
52 * @author [email protected] (Robby Walker)
53 */
54 class ScopedAliases implements HotSwapCompilerPass {
55 /** Name used to denote an scoped function block used for aliasing. */
56 static final String SCOPING_METHOD_NAME = "goog.scope";
57
58 private final AbstractCompiler compiler;
59 private final PreprocessorSymbolTable preprocessorSymbolTable;
60 private final AliasTransformationHandler transformationHandler;
61
62 // Errors
63 static final DiagnosticType GOOG_SCOPE_USED_IMPROPERLY = DiagnosticType.error(
64 "JSC_GOOG_SCOPE_USED_IMPROPERLY",
65 "The call to goog.scope must be alone in a single statement.");
66
67 static final DiagnosticType GOOG_SCOPE_HAS_BAD_PARAMETERS =
68 DiagnosticType.error(
69 "JSC_GOOG_SCOPE_HAS_BAD_PARAMETERS",
70 "The call to goog.scope must take only a single parameter. It must" +
71 " be an anonymous function that itself takes no parameters.");
72
73 static final DiagnosticType GOOG_SCOPE_REFERENCES_THIS = DiagnosticType.error(
74 "JSC_GOOG_SCOPE_REFERENCES_THIS",
75 "The body of a goog.scope function cannot reference 'this'.");
76
77 static final DiagnosticType GOOG_SCOPE_USES_RETURN = DiagnosticType.error(
78 "JSC_GOOG_SCOPE_USES_RETURN",
79 "The body of a goog.scope function cannot use 'return'.");
80
81 static final DiagnosticType GOOG_SCOPE_USES_THROW = DiagnosticType.error(
82 "JSC_GOOG_SCOPE_USES_THROW",
83 "The body of a goog.scope function cannot use 'throw'.");
84
85 static final DiagnosticType GOOG_SCOPE_ALIAS_REDEFINED = DiagnosticType.error(
86 "JSC_GOOG_SCOPE_ALIAS_REDEFINED",
87 "The alias {0} is assigned a value more than once.");
88
89 static final DiagnosticType GOOG_SCOPE_NON_ALIAS_LOCAL = DiagnosticType.error(
90 "JSC_GOOG_SCOPE_NON_ALIAS_LOCAL",
91 "The local variable {0} is in a goog.scope and is not an alias.");
92
93 ScopedAliases(AbstractCompiler compiler,
94 @Nullable PreprocessorSymbolTable preprocessorSymbolTable,
95 AliasTransformationHandler transformationHandler) {
96 this.compiler = compiler;
97 this.preprocessorSymbolTable = preprocessorSymbolTable;
98 this.transformationHandler = transformationHandler;
99 }
100
101 @Override
102 public void process(Node externs, Node root) {
103 hotSwapScript(root, null);
104 }
105
106 @Override
107 public void hotSwapScript(Node root, Node originalRoot) {
108 Traversal traversal = new Traversal();
109 NodeTraversal.traverse(compiler, root, traversal);
110
111 if (!traversal.hasErrors()) {
112
113 // Apply the aliases.
114 for (AliasUsage aliasUsage : traversal.getAliasUsages()) {
115 aliasUsage.applyAlias();
116 }
117
118 // Remove the alias definitions.
119 for (Node aliasDefinition : traversal.getAliasDefinitionsInOrder()) {
120 if (aliasDefinition.getParent().isVar() &&
121 aliasDefinition.getParent().hasOneChild()) {
122 aliasDefinition.getParent().detachFromParent();
123 } else {
124 aliasDefinition.detachFromParent();
125 }
126 }
127
128 // Collapse the scopes.
129 for (Node scopeCall : traversal.getScopeCalls()) {
130 Node expressionWithScopeCall = scopeCall.getParent();
131 Node scopeClosureBlock = scopeCall.getLastChild().getLastChild();
132 scopeClosureBlock.detachFromParent();
133 expressionWithScopeCall.getParent().replaceChild(
134 expressionWithScopeCall,
135 scopeClosureBlock);
136 NodeUtil.tryMergeBlock(scopeClosureBlock);
137 }
138
139 if (traversal.getAliasUsages().size() > 0 ||
140 traversal.getAliasDefinitionsInOrder().size() > 0 ||
141 traversal.getScopeCalls().size() > 0) {
142 compiler.reportCodeChange();
143 }
144 }
145 }
146
147 private interface AliasUsage {
148 public void applyAlias();
149 }
150
151 private class AliasedNode implements AliasUsage {
152 private final Node aliasReference;
153
154 private final Node aliasDefinition;
155
156 AliasedNode(Node aliasReference, Node aliasDefinition) {
157 this.aliasReference = aliasReference;
158 this.aliasDefinition = aliasDefinition;
159 }
160
161 @Override
162 public void applyAlias() {
163 aliasReference.getParent().replaceChild(
164 aliasReference, aliasDefinition.cloneTree());
165 }
166 }
167
168 private class AliasedTypeNode implements AliasUsage {
169 private final Node typeReference;
170 private final Node aliasDefinition;
171 private final String aliasName;
172
173 AliasedTypeNode(Node typeReference, Node aliasDefinition,
174 String aliasName) {
175 this.typeReference = typeReference;
176 this.aliasDefinition = aliasDefinition;
177 this.aliasName = aliasName;
178 }
179
180 @Override
181 public void applyAlias() {
182 String typeName = typeReference.getString();
183 String aliasExpanded =
184 Preconditions.checkNotNull(aliasDefinition.getQualifiedName());
185 Preconditions.checkState(typeName.startsWith(aliasName));
186 typeReference.setString(typeName.replaceFirst(aliasName, aliasExpanded));
187 }
188 }
189
190
191 private class Traversal implements NodeTraversal.ScopedCallback {
192 // The job of this class is to collect these three data sets.
193
194 // The order of this list determines the order that aliases are applied.
195 private final List<Node> aliasDefinitionsInOrder = Lists.newArrayList();
196
197 private final List<Node> scopeCalls = Lists.newArrayList();
198
199 private final List<AliasUsage> aliasUsages = Lists.newArrayList();
200
201 // This map is temporary and cleared for each scope.
202 private final Map<String, Var> aliases = Maps.newHashMap();
203
204 // Suppose you create an alias.
205 // var x = goog.x;
206 // As a side-effect, this means you can shadow the namespace 'goog'
207 // in inner scopes. When we inline the namespaces, we have to rename
208 // these shadows.
209 //
210 // Fortunately, we already have a name uniquifier that runs during tree
211 // normalization (before optimizations). We run it here on a limited
212 // set of variables, but only as a last resort (because this will screw
213 // up warning messages downstream).
214 private final Set<String> forbiddenLocals = Sets.newHashSet();
215 private boolean hasNamespaceShadows = false;
216
217 private boolean hasErrors = false;
218
219 private AliasTransformation transformation = null;
220
221 Collection<Node> getAliasDefinitionsInOrder() {
222 return aliasDefinitionsInOrder;
223 }
224
225 private List<AliasUsage> getAliasUsages() {
226 return aliasUsages;
227 }
228
229 List<Node> getScopeCalls() {
230 return scopeCalls;
231 }
232
233 boolean hasErrors() {
234 return hasErrors;
235 }
236
237 private boolean isCallToScopeMethod(Node n) {
238 return n.isCall() &&
239 SCOPING_METHOD_NAME.equals(n.getFirstChild().getQualifiedName());
240 }
241
242 @Override
243 public void enterScope(NodeTraversal t) {
244 Node n = t.getCurrentNode().getParent();
245 if (n != null && isCallToScopeMethod(n)) {
246 transformation = transformationHandler.logAliasTransformation(
247 n.getSourceFileName(), getSourceRegion(n));
248 findAliases(t);
249 }
250 }
251
252 @Override
253 public void exitScope(NodeTraversal t) {
254 if (t.getScopeDepth() > 2) {
255 findNamespaceShadows(t);
256 }
257
258 if (t.getScopeDepth() == 2) {
259 renameNamespaceShadows(t);
260 aliases.clear();
261 forbiddenLocals.clear();
262 transformation = null;
263 hasNamespaceShadows = false;
264 }
265 }
266
267 @Override
268 public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
269 if (n.isFunction() && t.inGlobalScope()) {
270 // Do not traverse in to functions except for goog.scope functions.
271 if (parent == null || !isCallToScopeMethod(parent)) {
272 return false;
273 }
274 }
275 return true;
276 }
277
278 private SourcePosition<AliasTransformation> getSourceRegion(Node n) {
279 Node testNode = n;
280 Node next = null;
281 for (; next != null || testNode.isScript();) {
282 next = testNode.getNext();
283 testNode = testNode.getParent();
284 }
285
286 int endLine = next == null ? Integer.MAX_VALUE : next.getLineno();
287 int endChar = next == null ? Integer.MAX_VALUE : next.getCharno();
288 SourcePosition<AliasTransformation> pos =
289 new SourcePosition<AliasTransformation>() {};
290 pos.setPositionInformation(
291 n.getLineno(), n.getCharno(), endLine, endChar);
292 return pos;
293 }
294
295 private void report(NodeTraversal t, Node n, DiagnosticType error,
296 String... arguments) {
297 compiler.report(t.makeError(n, error, arguments));
298 hasErrors = true;
299 }
300
301 private void findAliases(NodeTraversal t) {
302 Scope scope = t.getScope();
303 for (Var v : scope.getVarIterable()) {
304 Node n = v.getNode();
305 Node parent = n.getParent();
306 if (parent.isVar() &&
307 n.hasChildren() && n.getFirstChild().isQualifiedName()) {
308 String name = n.getString();
309 Var aliasVar = scope.getVar(name);
310 aliases.put(name, aliasVar);
311
312 String qualifiedName =
313 aliasVar.getInitialValue().getQualifiedName();
314 transformation.addAlias(name, qualifiedName);
315
316 int rootIndex = qualifiedName.indexOf(".");
317 if (rootIndex != -1) {
318 String qNameRoot = qualifiedName.substring(0, rootIndex);
319 if (!aliases.containsKey(qNameRoot)) {
320 forbiddenLocals.add(qNameRoot);
321 }
322 }
323 } else if (v.isBleedingFunction()) {
324 // Bleeding functions already get a BAD_PARAMETERS error, so just
325 // do nothing.
326 } else if (parent.getType() == Token.LP) {
327 // Parameters of the scope function also get a BAD_PARAMETERS
328 // error.
329 } else {
330 // TODO(robbyw): Support using locals for private variables.
331 report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
332 }
333 }
334 }
335
336 /** Find out if there are any local shadows of namespaces. */
337 private void findNamespaceShadows(NodeTraversal t) {
338 if (hasNamespaceShadows) {
339 return;
340 }
341
342 Scope scope = t.getScope();
343 for (Var v : scope.getVarIterable()) {
344 if (forbiddenLocals.contains(v.getName())) {
345 hasNamespaceShadows = true;
346 return;
347 }
348 }
349 }
350
351 /**
352 * Rename any local shadows of namespaces.
353 * This should be a very rare occurrence, so only do this traversal
354 * if we know that we need it.
355 */
356 private void renameNamespaceShadows(NodeTraversal t) {
357 if (hasNamespaceShadows) {
358 MakeDeclaredNamesUnique.Renamer renamer =
359 new MakeDeclaredNamesUnique.WhitelistedRenamer(
360 new MakeDeclaredNamesUnique.ContextualRenamer(),
361 forbiddenLocals);
362 for (String s : forbiddenLocals) {
363 renamer.addDeclaredName(s);
364 }
365 MakeDeclaredNamesUnique uniquifier =
366 new MakeDeclaredNamesUnique(renamer);
367 NodeTraversal.traverse(compiler, t.getScopeRoot(), uniquifier);
368 }
369 }
370
371 private void validateScopeCall(NodeTraversal t, Node n, Node parent) {
372 if (preprocessorSymbolTable != null) {
373 preprocessorSymbolTable.addReference(n.getFirstChild());
374 }
375 if (!parent.isExprResult()) {
376 report(t, n, GOOG_SCOPE_USED_IMPROPERLY);
377 }
378 if (n.getChildCount() != 2) {
379 // The goog.scope call should have exactly 1 parameter. The first
380 // child is the "goog.scope" and the second should be the parameter.
381 report(t, n, GOOG_SCOPE_HAS_BAD_PARAMETERS);
382 } else {
383 Node anonymousFnNode = n.getChildAtIndex(1);
384 if (!anonymousFnNode.isFunction() ||
385 NodeUtil.getFunctionName(anonymousFnNode) != null ||
386 NodeUtil.getFunctionParameters(anonymousFnNode).hasChildren()) {
387 report(t, anonymousFnNode, GOOG_SCOPE_HAS_BAD_PARAMETERS);
388 } else {
389 scopeCalls.add(n);
390 }
391 }
392 }
393
394 @Override
395 public void visit(NodeTraversal t, Node n, Node parent) {
396 if (isCallToScopeMethod(n)) {
397 validateScopeCall(t, n, n.getParent());
398 }
399
400 if (t.getScopeDepth() < 2) {
401 return;
402 }
403
404 int type = n.getType();
405 Var aliasVar = null;
406 if (type == Token.NAME) {
407 String name = n.getString();
408 Var lexicalVar = t.getScope().getVar(n.getString());
409 if (lexicalVar != null && lexicalVar == aliases.get(name)) {
410 aliasVar = lexicalVar;
411 }
412 }
413
414 // Validate the top-level of the goog.scope block.
415 if (t.getScopeDepth() == 2) {
416 if (aliasVar != null && NodeUtil.isLValue(n)) {
417 if (aliasVar.getNode() == n) {
418 aliasDefinitionsInOrder.add(n);
419
420 // Return early, to ensure that we don't record a definition
421 // twice.
422 return;
423 } else {
424 report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString());
425 }
426 }
427
428 if (type == Token.RETURN) {
429 report(t, n, GOOG_SCOPE_USES_RETURN);
430 } else if (type == Token.THIS) {
431 report(t, n, GOOG_SCOPE_REFERENCES_THIS);
432 } else if (type == Token.THROW) {
433 report(t, n, GOOG_SCOPE_USES_THROW);
434 }
435 }
436
437 // Validate all descendent scopes of the goog.scope block.
438 if (t.getScopeDepth() >= 2) {
439 // Check if this name points to an alias.
440 if (aliasVar != null) {
441 // Note, to support the transitive case, it's important we don't
442 // clone aliasedNode here. For example,
443 // var g = goog; var d = g.dom; d.createElement('DIV');
444 // The node in aliasedNode (which is "g") will be replaced in the
445 // changes pass above with "goog". If we cloned here, we'd end up
446 // with <code>g.dom.createElement('DIV')</code>.
447 Node aliasedNode = aliasVar.getInitialValue();
448 aliasUsages.add(new AliasedNode(n, aliasedNode));
449 }
450
451 JSDocInfo info = n.getJSDocInfo();
452 if (info != null) {
453 for (Node node : info.getTypeNodes()) {
454 fixTypeNode(node);
455 }
456 }
457
458 // TODO(robbyw): Error for goog.scope not at root.
459 }
460 }
461
462 private void fixTypeNode(Node typeNode) {
463 if (typeNode.isString()) {
464 String name = typeNode.getString();
465 int endIndex = name.indexOf('.');
466 if (endIndex == -1) {
467 endIndex = name.length();
468 }
469 String baseName = name.substring(0, endIndex);
470 Var aliasVar = aliases.get(baseName);
471 if (aliasVar != null) {
472 Node aliasedNode = aliasVar.getInitialValue();
473 aliasUsages.add(new AliasedTypeNode(typeNode, aliasedNode, baseName));
474 }
475 }
476
477 for (Node child = typeNode.getFirstChild(); child != null;
478 child = child.getNext()) {
479 fixTypeNode(child);
480 }
481 }
482 }
483 }