Debian Codegraph @

src/com/google/javascript/jscomp/Normalize.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 package com.google.javascript.jscomp;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
23 import com.google.javascript.jscomp.MakeDeclaredNamesUnique.BoilerplateRenamer;
24 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
25 import com.google.javascript.jscomp.NodeTraversal.Callback;
26 import com.google.javascript.jscomp.Scope.Var;
27 import com.google.javascript.rhino.IR;
28 import com.google.javascript.rhino.JSDocInfo;
29 import com.google.javascript.rhino.Node;
30 import com.google.javascript.rhino.Token;
31
32 import java.util.Map;
33 import java.util.Set;
34
35 /**
36 * The goal with this pass is to simplify the other passes,
37 * by making less complex statements.
38 *
39 * Starting with statements like:
40 * var a = 0, b = foo();
41 *
42 * Which become:
43 * var a = 0;
44 * var b = foo();
45 *
46 * The key here is only to break down things that help the other passes
47 * and can be put back together in a form that is at least as small when
48 * all is said and done.
49 *
50 * This pass currently does the following:
51 * 1) Simplifies the AST by splitting var statements, moving initializers
52 * out of for loops, and converting whiles to fors.
53 * 2) Moves hoisted functions to the top of function scopes.
54 * 3) Rewrites unhoisted named function declarations to be var declarations.
55 * 4) Makes all variable names globally unique (extern or otherwise) so that
56 * no value is ever shadowed (note: "arguments" may require special
57 * handling).
58 * 5) Removes duplicate variable declarations.
59 * 6) Marks constants with the IS_CONSTANT_NAME annotation.
60 * 7) Finds properties marked @expose, and rewrites them in [] notation.
61 *
62 * @author [email protected] (johnlenz)
63 */
64 // public for ReplaceDebugStringsTest
65 class Normalize implements CompilerPass {
66
67 private final AbstractCompiler compiler;
68 private final boolean assertOnChange;
69 private static final boolean CONVERT_WHILE_TO_FOR = true;
70 static final boolean MAKE_LOCAL_NAMES_UNIQUE = true;
71
72 public static final DiagnosticType CATCH_BLOCK_VAR_ERROR =
73 DiagnosticType.error(
74 "JSC_CATCH_BLOCK_VAR_ERROR",
75 "The use of scope variable {0} is not allowed within a catch block " +
76 "with a catch exception of the same name.");
77
78
79 Normalize(AbstractCompiler compiler, boolean assertOnChange) {
80 this.compiler = compiler;
81 this.assertOnChange = assertOnChange;
82
83 // TODO(nicksantos): assertOnChange should only be true if the tree
84 // is normalized.
85 }
86
87 static Node parseAndNormalizeSyntheticCode(
88 AbstractCompiler compiler, String code, String prefix) {
89 Node js = compiler.parseSyntheticCode(code);
90 NodeTraversal.traverse(compiler, js,
91 new Normalize.NormalizeStatements(compiler, false));
92 NodeTraversal.traverse(
93 compiler, js,
94 new MakeDeclaredNamesUnique(
95 new BoilerplateRenamer(
96 compiler.getCodingConvention(),
97 compiler.getUniqueNameIdSupplier(),
98 prefix)));
99 return js;
100 }
101
102 static Node parseAndNormalizeTestCode(
103 AbstractCompiler compiler, String code) {
104 Node js = compiler.parseTestCode(code);
105 NodeTraversal.traverse(compiler, js,
106 new Normalize.NormalizeStatements(compiler, false));
107 NodeTraversal.traverse(
108 compiler, js,
109 new MakeDeclaredNamesUnique());
110 return js;
111 }
112
113 private void reportCodeChange(String changeDescription) {
114 if (assertOnChange) {
115 throw new IllegalStateException(
116 "Normalize constraints violated:\n" + changeDescription);
117 }
118 compiler.reportCodeChange();
119 }
120
121 @Override
122 public void process(Node externs, Node root) {
123 new NodeTraversal(
124 compiler, new NormalizeStatements(compiler, assertOnChange))
125 .traverseRoots(externs, root);
126 if (MAKE_LOCAL_NAMES_UNIQUE) {
127 MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();
128 NodeTraversal t = new NodeTraversal(compiler, renamer);
129 t.traverseRoots(externs, root);
130 }
131 // It is important that removeDuplicateDeclarations runs after
132 // MakeDeclaredNamesUnique in order for catch block exception names to be
133 // handled properly. Specifically, catch block exception names are
134 // only valid within the catch block, but our current Scope logic
135 // has no concept of this and includes it in the containing function
136 // (or global scope). MakeDeclaredNamesUnique makes the catch exception
137 // names unique so that removeDuplicateDeclarations() will properly handle
138 // cases where a function scope variable conflict with a exception name:
139 // function f() {
140 // try {throw 0;} catch(e) {e; /* catch scope 'e'*/}
141 // var e = 1; // f scope 'e'
142 // }
143 // otherwise 'var e = 1' would be rewritten as 'e = 1'.
144 // TODO(johnlenz): Introduce a separate scope for catch nodes.
145 removeDuplicateDeclarations(externs, root);
146 new PropagateConstantAnnotationsOverVars(compiler, assertOnChange)
147 .process(externs, root);
148
149 FindExposeAnnotations findExposeAnnotations = new FindExposeAnnotations();
150 NodeTraversal.traverse(compiler, root, findExposeAnnotations);
151 if (!findExposeAnnotations.exposedProperties.isEmpty()) {
152 NodeTraversal.traverse(compiler, root,
153 new RewriteExposedProperties(
154 findExposeAnnotations.exposedProperties));
155 }
156
157 if (!compiler.getLifeCycleStage().isNormalized()) {
158 compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED);
159 }
160 }
161
162 /**
163 * Find all the @expose annotations.
164 */
165 private static class FindExposeAnnotations extends AbstractPostOrderCallback {
166 private final Set<String> exposedProperties = Sets.newHashSet();
167
168 @Override public void visit(NodeTraversal t, Node n, Node parent) {
169 if (NodeUtil.isExprAssign(n)) {
170 Node assign = n.getFirstChild();
171 Node lhs = assign.getFirstChild();
172 if (lhs.isGetProp() && isMarkedExpose(assign)) {
173 exposedProperties.add(lhs.getLastChild().getString());
174 }
175 } else if (n.isStringKey() && isMarkedExpose(n)) {
176 exposedProperties.add(n.getString());
177 } else if (n.isGetProp() && n.getParent().isExprResult()
178 && isMarkedExpose(n)) {
179 exposedProperties.add(n.getLastChild().getString());
180 }
181 }
182
183 private boolean isMarkedExpose(Node n) {
184 JSDocInfo info = n.getJSDocInfo();
185 return info != null && info.isExpose();
186 }
187 }
188
189 /**
190 * Rewrite all exposed properties in [] form.
191 */
192 private class RewriteExposedProperties
193 extends AbstractPostOrderCallback {
194 private final Set<String> exposedProperties;
195
196 RewriteExposedProperties(Set<String> exposedProperties) {
197 this.exposedProperties = exposedProperties;
198 }
199
200 @Override public void visit(NodeTraversal t, Node n, Node parent) {
201 if (n.isGetProp()) {
202 String propName = n.getLastChild().getString();
203 if (exposedProperties.contains(propName)) {
204 Node obj = n.removeFirstChild();
205 Node prop = n.removeFirstChild();
206 n.getParent().replaceChild(n, IR.getelem(obj, prop));
207 compiler.reportCodeChange();
208 }
209 } else if (n.isStringKey()) {
210 String propName = n.getString();
211 if (exposedProperties.contains(propName)) {
212 n.setQuotedString();
213 compiler.reportCodeChange();
214 }
215 }
216 }
217 }
218
219 /**
220 * Propagate constant annotations over the Var graph.
221 */
222 static class PropagateConstantAnnotationsOverVars
223 extends AbstractPostOrderCallback
224 implements CompilerPass {
225 private final AbstractCompiler compiler;
226 private final boolean assertOnChange;
227
228 PropagateConstantAnnotationsOverVars(
229 AbstractCompiler compiler, boolean forbidChanges) {
230 this.compiler = compiler;
231 this.assertOnChange = forbidChanges;
232 }
233
234 @Override
235 public void process(Node externs, Node root) {
236 new NodeTraversal(compiler, this).traverseRoots(externs, root);
237 }
238
239 @Override
240 public void visit(NodeTraversal t, Node n, Node parent) {
241 // Note: Constant properties annotations are not propagated.
242 if (n.isName()) {
243 if (n.getString().isEmpty()) {
244 return;
245 }
246
247 JSDocInfo info = null;
248 // Find the JSDocInfo for a top-level variable.
249 Var var = t.getScope().getVar(n.getString());
250 if (var != null) {
251 info = var.getJSDocInfo();
252 }
253
254 boolean shouldBeConstant =
255 (info != null && info.isConstant()) ||
256 NodeUtil.isConstantByConvention(
257 compiler.getCodingConvention(), n, parent);
258 boolean isMarkedConstant = n.getBooleanProp(Node.IS_CONSTANT_NAME);
259 if (shouldBeConstant && !isMarkedConstant) {
260 if (assertOnChange) {
261 String name = n.getString();
262 throw new IllegalStateException(
263 "Unexpected const change.\n" +
264 " name: "+ name + "\n" +
265 " parent:" + n.getParent().toStringTree());
266 }
267 n.putBooleanProp(Node.IS_CONSTANT_NAME, true);
268 }
269 }
270 }
271 }
272
273 /**
274 * Walk the AST tree and verify that constant names are used consistently.
275 */
276 static class VerifyConstants extends AbstractPostOrderCallback
277 implements CompilerPass {
278
279 final private AbstractCompiler compiler;
280 final private boolean checkUserDeclarations;
281
282 VerifyConstants(AbstractCompiler compiler, boolean checkUserDeclarations) {
283 this.compiler = compiler;
284 this.checkUserDeclarations = checkUserDeclarations;
285 }
286
287 @Override
288 public void process(Node externs, Node root) {
289 Node externsAndJs = root.getParent();
290 Preconditions.checkState(externsAndJs != null);
291 Preconditions.checkState(externsAndJs.hasChild(externs));
292
293 NodeTraversal.traverseRoots(
294 compiler, Lists.newArrayList(externs, root), this);
295 }
296
297 private Map<String, Boolean> constantMap = Maps.newHashMap();
298
299 @Override
300 public void visit(NodeTraversal t, Node n, Node parent) {
301 if (n.isName()) {
302 String name = n.getString();
303 if (n.getString().isEmpty()) {
304 return;
305 }
306
307 boolean isConst = n.getBooleanProp(Node.IS_CONSTANT_NAME);
308 if (checkUserDeclarations) {
309 boolean expectedConst = false;
310 CodingConvention convention = compiler.getCodingConvention();
311 if (NodeUtil.isConstantName(n)
312 || NodeUtil.isConstantByConvention(convention, n, parent)) {
313 expectedConst = true;
314 } else {
315 expectedConst = false;
316
317 JSDocInfo info = null;
318 Var var = t.getScope().getVar(n.getString());
319 if (var != null) {
320 info = var.getJSDocInfo();
321 }
322
323 if (info != null && info.isConstant()) {
324 expectedConst = true;
325 } else {
326 expectedConst = false;
327 }
328 }
329
330 if (expectedConst) {
331 Preconditions.checkState(expectedConst == isConst,
332 "The name %s is not annotated as constant.", name);
333 } else {
334 Preconditions.checkState(expectedConst == isConst,
335 "The name %s should not be annotated as constant.", name);
336 }
337 }
338
339 Boolean value = constantMap.get(name);
340 if (value == null) {
341 constantMap.put(name, isConst);
342 } else {
343 Preconditions.checkState(value.booleanValue() == isConst,
344 "The name %s is not consistently annotated as constant.", name);
345 }
346 }
347 }
348 }
349
350 /**
351 * Simplify the AST:
352 * - VAR declarations split, so they represent exactly one child
353 * declaration.
354 * - WHILEs are converted to FORs
355 * - FOR loop are initializers are moved out of the FOR structure
356 * - LABEL node of children other than LABEL, BLOCK, WHILE, FOR, or DO are
357 * moved into a block.
358 * - Add constant annotations based on coding convention.
359 */
360 static class NormalizeStatements implements Callback {
361 private final AbstractCompiler compiler;
362 private final boolean assertOnChange;
363
364 NormalizeStatements(AbstractCompiler compiler, boolean assertOnChange) {
365 this.compiler = compiler;
366 this.assertOnChange = assertOnChange;
367 }
368
369 private void reportCodeChange(String changeDescription) {
370 if (assertOnChange) {
371 throw new IllegalStateException(
372 "Normalize constraints violated:\n" + changeDescription);
373 }
374 compiler.reportCodeChange();
375 }
376
377 @Override
378 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
379 doStatementNormalizations(n);
380
381 return true;
382 }
383
384 @Override
385 public void visit(NodeTraversal t, Node n, Node parent) {
386 switch (n.getType()) {
387 case Token.WHILE:
388 if (CONVERT_WHILE_TO_FOR) {
389 Node expr = n.getFirstChild();
390 n.setType(Token.FOR);
391 Node empty = IR.empty();
392 empty.copyInformationFrom(n);
393 n.addChildBefore(empty, expr);
394 n.addChildAfter(empty.cloneNode(), expr);
395 reportCodeChange("WHILE node");
396 }
397 break;
398
399 case Token.FUNCTION:
400 normalizeFunctionDeclaration(n);
401 break;
402
403 case Token.NAME:
404 case Token.STRING:
405 case Token.STRING_KEY:
406 case Token.GETTER_DEF:
407 case Token.SETTER_DEF:
408 if (!compiler.getLifeCycleStage().isNormalizedObfuscated()) {
409 annotateConstantsByConvention(n, parent);
410 }
411 break;
412
413 case Token.CAST:
414 parent.replaceChild(n, n.removeFirstChild());
415 break;
416 }
417 }
418
419 /**
420 * Mark names and properties that are constants by convention.
421 */
422 private void annotateConstantsByConvention(Node n, Node parent) {
423 Preconditions.checkState(
424 n.isName()
425 || n.isString()
426 || n.isStringKey()
427 || n.isGetterDef()
428 || n.isSetterDef());
429
430 // There are only two cases where a string token
431 // may be a variable reference: The right side of a GETPROP
432 // or an OBJECTLIT key.
433 boolean isObjLitKey = NodeUtil.isObjectLitKey(n);
434 boolean isProperty = isObjLitKey ||
435 (parent.isGetProp() &&
436 parent.getLastChild() == n);
437 if (n.isName() || isProperty) {
438 boolean isMarkedConstant = n.getBooleanProp(Node.IS_CONSTANT_NAME);
439 if (!isMarkedConstant &&
440 NodeUtil.isConstantByConvention(
441 compiler.getCodingConvention(), n, parent)) {
442 if (assertOnChange) {
443 String name = n.getString();
444 throw new IllegalStateException(
445 "Unexpected const change.\n" +
446 " name: "+ name + "\n" +
447 " parent:" + n.getParent().toStringTree());
448 }
449 n.putBooleanProp(Node.IS_CONSTANT_NAME, true);
450 }
451 }
452 }
453
454 /**
455 * Rewrite named unhoisted functions declarations to a known
456 * consistent behavior so we don't to different logic paths for the same
457 * code. From:
458 * function f() {}
459 * to:
460 * var f = function () {};
461 */
462 private void normalizeFunctionDeclaration(Node n) {
463 Preconditions.checkState(n.isFunction());
464 if (!NodeUtil.isFunctionExpression(n)
465 && !NodeUtil.isHoistedFunctionDeclaration(n)) {
466 rewriteFunctionDeclaration(n);
467 }
468 }
469
470 /**
471 * Rewrite the function declaration from:
472 * function x() {}
473 * FUNCTION
474 * NAME
475 * LP
476 * BLOCK
477 * to:
478 * var x = function() {};
479 * VAR
480 * NAME
481 * FUNCTION
482 * NAME (w/ empty string)
483 * LP
484 * BLOCK
485 */
486 private void rewriteFunctionDeclaration(Node n) {
487 // Prepare a spot for the function.
488 Node oldNameNode = n.getFirstChild();
489 Node fnNameNode = oldNameNode.cloneNode();
490 Node var = IR.var(fnNameNode).srcref(n);
491
492 // Prepare the function
493 oldNameNode.setString("");
494
495 // Move the function
496 Node parent = n.getParent();
497 parent.replaceChild(n, var);
498 fnNameNode.addChildToFront(n);
499
500 reportCodeChange("Function declaration");
501 }
502
503 /**
504 * Do normalizations that introduce new siblings or parents.
505 */
506 private void doStatementNormalizations(Node n) {
507 if (n.isLabel()) {
508 normalizeLabels(n);
509 }
510
511 // Only inspect the children of SCRIPTs, BLOCKs and LABELs, as all these
512 // are the only legal place for VARs and FOR statements.
513 if (NodeUtil.isStatementBlock(n) || n.isLabel()) {
514 extractForInitializer(n, null, null);
515 }
516
517 // Only inspect the children of SCRIPTs, BLOCKs, as all these
518 // are the only legal place for VARs.
519 if (NodeUtil.isStatementBlock(n)) {
520 splitVarDeclarations(n);
521 }
522
523 if (n.isFunction()) {
524 moveNamedFunctions(n.getLastChild());
525 }
526 }
527
528 // TODO(johnlenz): Move this to NodeTypeNormalizer once the unit tests are
529 // fixed.
530 /**
531 * Limit the number of special cases where LABELs need to be handled. Only
532 * BLOCK and loops are allowed to be labeled. Loop labels must remain in
533 * place as the named continues are not allowed for labeled blocks.
534 */
535 private void normalizeLabels(Node n) {
536 Preconditions.checkArgument(n.isLabel());
537
538 Node last = n.getLastChild();
539 switch (last.getType()) {
540 case Token.LABEL:
541 case Token.BLOCK:
542 case Token.FOR:
543 case Token.WHILE:
544 case Token.DO:
545 return;
546 default:
547 Node block = IR.block();
548 block.copyInformationFrom(last);
549 n.replaceChild(last, block);
550 block.addChildToFront(last);
551 reportCodeChange("LABEL normalization");
552 return;
553 }
554 }
555
556 /**
557 * Bring the initializers out of FOR loops. These need to be placed
558 * before any associated LABEL nodes. This needs to be done from the top
559 * level label first so this is called as a pre-order callback (from
560 * shouldTraverse).
561 *
562 * @param n The node to inspect.
563 * @param before The node to insert the initializer before.
564 * @param beforeParent The parent of the node before which the initializer
565 * will be inserted.
566 */
567 private void extractForInitializer(
568 Node n, Node before, Node beforeParent) {
569
570 for (Node next, c = n.getFirstChild(); c != null; c = next) {
571 next = c.getNext();
572 Node insertBefore = (before == null) ? c : before;
573 Node insertBeforeParent = (before == null) ? n : beforeParent;
574 switch (c.getType()) {
575 case Token.LABEL:
576 extractForInitializer(c, insertBefore, insertBeforeParent);
577 break;
578 case Token.FOR:
579 if (NodeUtil.isForIn(c)) {
580 Node first = c.getFirstChild();
581 if (first.isVar()) {
582 // Transform:
583 // for (var a = 1 in b) {}
584 // to:
585 // var a = 1; for (a in b) {};
586 Node newStatement = first;
587 // Clone just the node, to remove any initialization.
588 Node name = newStatement.getFirstChild().cloneNode();
589 first.getParent().replaceChild(first, name);
590 insertBeforeParent.addChildBefore(newStatement, insertBefore);
591 reportCodeChange("FOR-IN var declaration");
592 }
593 } else if (!c.getFirstChild().isEmpty()) {
594 Node init = c.getFirstChild();
595 Node empty = IR.empty();
596 empty.copyInformationFrom(c);
597 c.replaceChild(init, empty);
598
599 Node newStatement;
600 // Only VAR statements, and expressions are allowed,
601 // but are handled differently.
602 if (init.isVar()) {
603 newStatement = init;
604 } else {
605 newStatement = NodeUtil.newExpr(init);
606 }
607
608 insertBeforeParent.addChildBefore(newStatement, insertBefore);
609 reportCodeChange("FOR initializer");
610 }
611 break;
612 }
613 }
614 }
615
616 /**
617 * Split a var node such as:
618 * var a, b;
619 * into individual statements:
620 * var a;
621 * var b;
622 * @param n The whose children we should inspect.
623 */
624 private void splitVarDeclarations(Node n) {
625 for (Node next, c = n.getFirstChild(); c != null; c = next) {
626 next = c.getNext();
627 if (c.isVar()) {
628 if (assertOnChange && !c.hasChildren()) {
629 throw new IllegalStateException("Empty VAR node.");
630 }
631
632 while (c.getFirstChild() != c.getLastChild()) {
633 Node name = c.getFirstChild();
634 c.removeChild(name);
635 Node newVar = IR.var(name).srcref(n);
636 n.addChildBefore(newVar, c);
637 reportCodeChange("VAR with multiple children");
638 }
639 }
640 }
641 }
642
643 /**
644 * Move all the functions that are valid at the execution of the first
645 * statement of the function to the beginning of the function definition.
646 */
647 private void moveNamedFunctions(Node functionBody) {
648 Preconditions.checkState(
649 functionBody.getParent().isFunction());
650 Node previous = null;
651 Node current = functionBody.getFirstChild();
652 // Skip any declarations at the beginning of the function body, they
653 // are already in the right place.
654 while (current != null && NodeUtil.isFunctionDeclaration(current)) {
655 previous = current;
656 current = current.getNext();
657 }
658
659 // Find any remaining declarations and move them.
660 Node insertAfter = previous;
661 while (current != null) {
662 // Save off the next node as the current node maybe removed.
663 Node next = current.getNext();
664 if (NodeUtil.isFunctionDeclaration(current)) {
665 // Remove the declaration from the body.
666 Preconditions.checkNotNull(previous);
667 functionBody.removeChildAfter(previous);
668
669 // Read the function at the top of the function body (after any
670 // previous declarations).
671 insertAfter = addToFront(functionBody, current, insertAfter);
672 reportCodeChange("Move function declaration not at top of function");
673 } else {
674 // Update the previous only if the current node hasn't been moved.
675 previous = current;
676 }
677 current = next;
678 }
679 }
680
681 /**
682 * @param after The child node to insert the newChild after, or null if
683 * newChild should be added to the front of parent's child list.
684 * @return The inserted child node.
685 */
686 private Node addToFront(Node parent, Node newChild, Node after) {
687 if (after == null) {
688 parent.addChildToFront(newChild);
689 } else {
690 parent.addChildAfter(newChild, after);
691 }
692 return newChild;
693 }
694 }
695
696 /**
697 * Remove duplicate VAR declarations.
698 */
699 private void removeDuplicateDeclarations(Node externs, Node root) {
700 Callback tickler = new ScopeTicklingCallback();
701 ScopeCreator scopeCreator = new SyntacticScopeCreator(
702 compiler, new DuplicateDeclarationHandler());
703 NodeTraversal t = new NodeTraversal(compiler, tickler, scopeCreator);
704 t.traverseRoots(externs, root);
705 }
706
707 /**
708 * ScopeCreator duplicate declaration handler.
709 */
710 private final class DuplicateDeclarationHandler implements
711 SyntacticScopeCreator.RedeclarationHandler {
712
713 private Set<Var> hasOkDuplicateDeclaration = Sets.newHashSet();
714
715 /**
716 * Remove duplicate VAR declarations encountered discovered during
717 * scope creation.
718 */
719 @Override
720 public void onRedeclaration(
721 Scope s, String name, Node n, CompilerInput input) {
722 Preconditions.checkState(n.isName());
723 Node parent = n.getParent();
724 Var v = s.getVar(name);
725
726 if (v != null && s.isGlobal()) {
727 // We allow variables to be duplicate declared if one
728 // declaration appears in source and the other in externs.
729 // This deals with issues where a browser built-in is declared
730 // in one browser but not in another.
731 if (v.isExtern() && !input.isExtern()) {
732 if (hasOkDuplicateDeclaration.add(v)) {
733 return;
734 }
735 }
736 }
737
738 // If name is "arguments", Var maybe null.
739 if (v != null && v.getParentNode().isCatch()) {
740 // Redeclaration of a catch expression variable is hard to model
741 // without support for "with" expressions.
742 // The ECMAScript spec (section 12.14), declares that a catch
743 // "catch (e) {}" is handled like "with ({'e': e}) {}" so that
744 // "var e" would refer to the scope variable, but any following
745 // reference would still refer to "e" of the catch expression.
746 // Until we have support for this disallow it.
747 // Currently the Scope object adds the catch expression to the
748 // function scope, which is technically not true but a good
749 // approximation for most uses.
750
751 // TODO(johnlenz): Consider improving how scope handles catch
752 // expression.
753
754 // Use the name of the var before it was made unique.
755 name = MakeDeclaredNamesUnique.ContextualRenameInverter.getOrginalName(
756 name);
757 compiler.report(
758 JSError.make(
759 input.getName(), n,
760 CATCH_BLOCK_VAR_ERROR, name));
761 } else if (v != null && parent.isFunction()) {
762 if (v.getParentNode().isVar()) {
763 s.undeclare(v);
764 s.declare(name, n, n.getJSType(), v.input);
765 replaceVarWithAssignment(v.getNameNode(), v.getParentNode(),
766 v.getParentNode().getParent());
767 }
768 } else if (parent.isVar()) {
769 Preconditions.checkState(parent.hasOneChild());
770
771 replaceVarWithAssignment(n, parent, parent.getParent());
772 }
773 }
774
775 /**
776 * Remove the parent VAR. There are three cases that need to be handled:
777 * 1) "var a = b;" which is replaced with "a = b"
778 * 2) "label:var a;" which is replaced with "label:;". Ideally, the
779 * label itself would be removed but that is not possible in the
780 * context in which "onRedeclaration" is called.
781 * 3) "for (var a in b) ..." which is replaced with "for (a in b)..."
782 * Cases we don't need to handle are VARs with multiple children,
783 * which have already been split into separate declarations, so there
784 * is no need to handle that here, and "for (var a;;);", which has
785 * been moved out of the loop.
786 * The result of this is that in each case the parent node is replaced
787 * which is generally dangerous in a traversal but is fine here with
788 * the scope creator, as the next node of interest is the parent's
789 * next sibling.
790 */
791 private void replaceVarWithAssignment(Node n, Node parent, Node gramps) {
792 if (n.hasChildren()) {
793 // The * is being initialize, preserve the new value.
794 parent.removeChild(n);
795 // Convert "var name = value" to "name = value"
796 Node value = n.getFirstChild();
797 n.removeChild(value);
798 Node replacement = IR.assign(n, value);
799 replacement.copyInformationFrom(parent);
800 gramps.replaceChild(parent, NodeUtil.newExpr(replacement));
801 } else {
802 // It is an empty reference remove it.
803 if (NodeUtil.isStatementBlock(gramps)) {
804 gramps.removeChild(parent);
805 } else if (gramps.isFor()) {
806 // This is the "for (var a in b)..." case. We don't need to worry
807 // about initializers in "for (var a;;)..." as those are moved out
808 // as part of the other normalizations.
809 parent.removeChild(n);
810 gramps.replaceChild(parent, n);
811 } else {
812 Preconditions.checkState(gramps.isLabel());
813 // We should never get here. LABELs with a single VAR statement should
814 // already have been normalized to have a BLOCK.
815 throw new IllegalStateException("Unexpected LABEL");
816 }
817 }
818 reportCodeChange("Duplicate VAR declaration");
819 }
820 }
821
822 /**
823 * A simple class that causes scope to be created.
824 */
825 private final class ScopeTicklingCallback
826 implements NodeTraversal.ScopedCallback {
827 @Override
828 public void enterScope(NodeTraversal t) {
829 // Cause the scope to be created, which will cause duplicate
830 // to be found.
831 t.getScope();
832 }
833
834 @Override
835 public void exitScope(NodeTraversal t) {
836 // Nothing to do.
837 }
838
839 @Override
840 public boolean shouldTraverse(
841 NodeTraversal nodeTraversal, Node n, Node parent) {
842 return true;
843 }
844
845 @Override
846 public void visit(NodeTraversal t, Node n, Node parent) {
847 // Nothing to do.
848 }
849 }
850 }