Debian Codegraph @

src/com/google/javascript/jscomp/ProcessClosurePrimitives.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.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
24 import com.google.javascript.rhino.IR;
25 import com.google.javascript.rhino.JSDocInfo;
26 import com.google.javascript.rhino.JSDocInfoBuilder;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33
34 import javax.annotation.Nullable;
35
36 /**
37 * Replaces goog.provide calls, removes goog.require calls, verifies that
38 * goog.require has a corresponding goog.provide and some closure specific
39 * simplifications.
40 *
41 */
42 class ProcessClosurePrimitives extends AbstractPostOrderCallback
43 implements HotSwapCompilerPass {
44
45 static final DiagnosticType NULL_ARGUMENT_ERROR = DiagnosticType.error(
46 "JSC_NULL_ARGUMENT_ERROR",
47 "method \"{0}\" called without an argument");
48
49 static final DiagnosticType EXPECTED_OBJECTLIT_ERROR = DiagnosticType.error(
50 "JSC_EXPECTED_OBJECTLIT_ERROR",
51 "method \"{0}\" expected an object literal argument");
52
53 static final DiagnosticType EXPECTED_STRING_ERROR = DiagnosticType.error(
54 "JSC_EXPECTED_STRING_ERROR",
55 "method \"{0}\" expected an object string argument");
56
57 static final DiagnosticType INVALID_ARGUMENT_ERROR = DiagnosticType.error(
58 "JSC_INVALID_ARGUMENT_ERROR",
59 "method \"{0}\" called with invalid argument");
60
61 static final DiagnosticType INVALID_STYLE_ERROR = DiagnosticType.error(
62 "JSC_INVALID_CSS_NAME_MAP_STYLE_ERROR",
63 "Invalid CSS name map style {0}");
64
65 static final DiagnosticType TOO_MANY_ARGUMENTS_ERROR = DiagnosticType.error(
66 "JSC_TOO_MANY_ARGUMENTS_ERROR",
67 "method \"{0}\" called with more than one argument");
68
69 static final DiagnosticType DUPLICATE_NAMESPACE_ERROR = DiagnosticType.error(
70 "JSC_DUPLICATE_NAMESPACE_ERROR",
71 "namespace \"{0}\" cannot be provided twice");
72
73 static final DiagnosticType FUNCTION_NAMESPACE_ERROR = DiagnosticType.error(
74 "JSC_FUNCTION_NAMESPACE_ERROR",
75 "\"{0}\" cannot be both provided and declared as a function");
76
77 static final DiagnosticType MISSING_PROVIDE_ERROR = DiagnosticType.error(
78 "JSC_MISSING_PROVIDE_ERROR",
79 "required \"{0}\" namespace never provided");
80
81 static final DiagnosticType LATE_PROVIDE_ERROR = DiagnosticType.error(
82 "JSC_LATE_PROVIDE_ERROR",
83 "required \"{0}\" namespace not provided yet");
84
85 static final DiagnosticType INVALID_PROVIDE_ERROR = DiagnosticType.error(
86 "JSC_INVALID_PROVIDE_ERROR",
87 "\"{0}\" is not a valid JS property name");
88
89 static final DiagnosticType XMODULE_REQUIRE_ERROR = DiagnosticType.warning(
90 "JSC_XMODULE_REQUIRE_ERROR",
91 "namespace \"{0}\" provided in module {1} " +
92 "but required in module {2}");
93
94 static final DiagnosticType NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR =
95 DiagnosticType.error(
96 "JSC_NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR",
97 "goog.setCssNameMapping only takes an object literal with string values");
98
99 static final DiagnosticType INVALID_CSS_RENAMING_MAP = DiagnosticType.warning(
100 "INVALID_CSS_RENAMING_MAP",
101 "Invalid entries in css renaming map: {0}");
102
103 static final DiagnosticType BASE_CLASS_ERROR = DiagnosticType.error(
104 "JSC_BASE_CLASS_ERROR",
105 "incorrect use of goog.base: {0}");
106
107 /** The root Closure namespace */
108 static final String GOOG = "goog";
109
110 private final AbstractCompiler compiler;
111 private final JSModuleGraph moduleGraph;
112
113 // The goog.provides must be processed in a deterministic order.
114 private final Map<String, ProvidedName> providedNames =
115 Maps.newLinkedHashMap();
116
117 private final List<UnrecognizedRequire> unrecognizedRequires =
118 Lists.newArrayList();
119 private final Set<String> exportedVariables = Sets.newHashSet();
120 private final CheckLevel requiresLevel;
121 private final PreprocessorSymbolTable preprocessorSymbolTable;
122
123 ProcessClosurePrimitives(AbstractCompiler compiler,
124 @Nullable PreprocessorSymbolTable preprocessorSymbolTable,
125 CheckLevel requiresLevel) {
126 this.compiler = compiler;
127 this.preprocessorSymbolTable = preprocessorSymbolTable;
128 this.moduleGraph = compiler.getModuleGraph();
129 this.requiresLevel = requiresLevel;
130
131 // goog is special-cased because it is provided in Closure's base library.
132 providedNames.put(GOOG,
133 new ProvidedName(GOOG, null, null, false /* implicit */));
134 }
135
136 Set<String> getExportedVariableNames() {
137 return exportedVariables;
138 }
139
140 @Override
141 public void process(Node externs, Node root) {
142 new NodeTraversal(compiler, this).traverse(root);
143
144 for (ProvidedName pn : providedNames.values()) {
145 pn.replace();
146 }
147
148 if (requiresLevel.isOn()) {
149 for (UnrecognizedRequire r : unrecognizedRequires) {
150 DiagnosticType error;
151 ProvidedName expectedName = providedNames.get(r.namespace);
152 if (expectedName != null && expectedName.firstNode != null) {
153 // The namespace ended up getting provided after it was required.
154 error = LATE_PROVIDE_ERROR;
155 } else {
156 error = MISSING_PROVIDE_ERROR;
157 }
158
159 compiler.report(JSError.make(
160 r.inputName, r.requireNode, requiresLevel, error, r.namespace));
161 }
162 }
163 }
164
165 @Override
166 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
167 // TODO(bashir): Implement a real hot-swap version instead and make it fully
168 // consistent with the full version.
169 this.compiler.process(this);
170 }
171
172 @Override
173 public void visit(NodeTraversal t, Node n, Node parent) {
174 switch (n.getType()) {
175 case Token.CALL:
176 boolean isExpr = parent.isExprResult();
177 Node left = n.getFirstChild();
178 if (left.isGetProp()) {
179 Node name = left.getFirstChild();
180 if (name.isName() &&
181 GOOG.equals(name.getString())) {
182 // For the sake of simplicity, we report code changes
183 // when we see a provides/requires, and don't worry about
184 // reporting the change when we actually do the replacement.
185 String methodName = name.getNext().getString();
186 if ("base".equals(methodName)) {
187 processBaseClassCall(t, n);
188 } else if (!isExpr) {
189 // All other methods must be called in an EXPR.
190 break;
191 } else if ("require".equals(methodName)) {
192 processRequireCall(t, n, parent);
193 } else if ("provide".equals(methodName)) {
194 processProvideCall(t, n, parent);
195 } else if ("exportSymbol".equals(methodName)) {
196 Node arg = left.getNext();
197 if (arg.isString()) {
198 int dot = arg.getString().indexOf('.');
199 if (dot == -1) {
200 exportedVariables.add(arg.getString());
201 } else {
202 exportedVariables.add(arg.getString().substring(0, dot));
203 }
204 }
205 } else if ("addDependency".equals(methodName)) {
206 CodingConvention convention = compiler.getCodingConvention();
207 List<String> typeDecls =
208 convention.identifyTypeDeclarationCall(n);
209 if (typeDecls != null) {
210 for (String typeDecl : typeDecls) {
211 compiler.getTypeRegistry().forwardDeclareType(typeDecl);
212 }
213 }
214
215 // We can't modify parent, so just create a node that will
216 // get compiled out.
217 parent.replaceChild(n, IR.number(0));
218 compiler.reportCodeChange();
219 } else if ("setCssNameMapping".equals(methodName)) {
220 processSetCssNameMapping(t, n, parent);
221 }
222 }
223 }
224 break;
225
226 case Token.ASSIGN:
227 case Token.NAME:
228 // If this is an assignment to a provided name, remove the provided
229 // object.
230 handleCandidateProvideDefinition(t, n, parent);
231 break;
232
233 case Token.EXPR_RESULT:
234 handleTypedefDefinition(t, n);
235 break;
236
237 case Token.FUNCTION:
238 // If this is a declaration of a provided named function, this is an
239 // error. Hoisted functions will explode if they're provided.
240 if (t.inGlobalScope() &&
241 !NodeUtil.isFunctionExpression(n)) {
242 String name = n.getFirstChild().getString();
243 ProvidedName pn = providedNames.get(name);
244 if (pn != null) {
245 compiler.report(t.makeError(n, FUNCTION_NAMESPACE_ERROR, name));
246 }
247 }
248 break;
249
250 case Token.GETPROP:
251 if (n.getFirstChild().isName() &&
252 !parent.isCall() &&
253 !parent.isAssign() &&
254 "goog.base".equals(n.getQualifiedName())) {
255 reportBadBaseClassUse(t, n, "May only be called directly.");
256 }
257 break;
258 }
259 }
260
261 /**
262 * Handles a goog.require call.
263 */
264 private void processRequireCall(NodeTraversal t, Node n, Node parent) {
265 Node left = n.getFirstChild();
266 Node arg = left.getNext();
267 if (verifyArgument(t, left, arg)) {
268 String ns = arg.getString();
269 ProvidedName provided = providedNames.get(ns);
270 if (provided == null || !provided.isExplicitlyProvided()) {
271 unrecognizedRequires.add(
272 new UnrecognizedRequire(n, ns, t.getSourceName()));
273 } else {
274 JSModule providedModule = provided.explicitModule;
275
276 // This must be non-null, because there was an explicit provide.
277 Preconditions.checkNotNull(providedModule);
278
279 JSModule module = t.getModule();
280 if (moduleGraph != null &&
281 module != providedModule &&
282 !moduleGraph.dependsOn(module, providedModule)) {
283 compiler.report(
284 t.makeError(n, XMODULE_REQUIRE_ERROR, ns,
285 providedModule.getName(),
286 module.getName()));
287 }
288 }
289
290 maybeAddToSymbolTable(left);
291 maybeAddStringNodeToSymbolTable(arg);
292
293 // Requires should be removed before runtime. The one
294 // exception is if the type has not been provided yet and
295 // errors for broken requires are turned off, in which case,
296 // we will be doing a later pass that may error, so we can
297 // leave this here this time and let it error next time if it
298 // is still not provided.
299 if (provided != null || requiresLevel.isOn()) {
300 parent.detachFromParent();
301 compiler.reportCodeChange();
302 }
303 }
304 }
305
306 /**
307 * Handles a goog.provide call.
308 */
309 private void processProvideCall(NodeTraversal t, Node n, Node parent) {
310 Node left = n.getFirstChild();
311 Node arg = left.getNext();
312 if (verifyProvide(t, left, arg)) {
313 String ns = arg.getString();
314
315 maybeAddToSymbolTable(left);
316 maybeAddStringNodeToSymbolTable(arg);
317
318 if (providedNames.containsKey(ns)) {
319 ProvidedName previouslyProvided = providedNames.get(ns);
320 if (!previouslyProvided.isExplicitlyProvided()) {
321 previouslyProvided.addProvide(parent, t.getModule(), true);
322 } else {
323 compiler.report(
324 t.makeError(n, DUPLICATE_NAMESPACE_ERROR, ns));
325 }
326 } else {
327 registerAnyProvidedPrefixes(ns, parent, t.getModule());
328 providedNames.put(
329 ns, new ProvidedName(ns, parent, t.getModule(), true));
330 }
331 }
332 }
333
334 /**
335 * Handles a typedef definition for a goog.provided name.
336 * @param n EXPR_RESULT node.
337 */
338 private void handleTypedefDefinition(
339 NodeTraversal t, Node n) {
340 JSDocInfo info = n.getFirstChild().getJSDocInfo();
341 if (t.inGlobalScope() && info != null && info.hasTypedefType()) {
342 String name = n.getFirstChild().getQualifiedName();
343 if (name != null) {
344 ProvidedName pn = providedNames.get(name);
345 if (pn != null) {
346 pn.addDefinition(n, t.getModule());
347 }
348 }
349 }
350 }
351
352 /**
353 * Handles a candidate definition for a goog.provided name.
354 */
355 private void handleCandidateProvideDefinition(
356 NodeTraversal t, Node n, Node parent) {
357 if (t.inGlobalScope()) {
358 String name = null;
359 if (n.isName() && parent.isVar()) {
360 name = n.getString();
361 } else if (n.isAssign() &&
362 parent.isExprResult()) {
363 name = n.getFirstChild().getQualifiedName();
364 }
365
366 if (name != null) {
367 if (parent.getBooleanProp(Node.IS_NAMESPACE)) {
368 processProvideFromPreviousPass(t, name, parent);
369 } else {
370 ProvidedName pn = providedNames.get(name);
371 if (pn != null) {
372 pn.addDefinition(parent, t.getModule());
373 }
374 }
375 }
376 }
377 }
378
379 /**
380 * Processes the base class call.
381 */
382 private void processBaseClassCall(NodeTraversal t, Node n) {
383 // Two things must hold for every goog.base call:
384 // 1) We must be calling it on "this".
385 // 2) We must be calling it on a prototype method of the same name as
386 // the one we're in, OR we must be calling it from a constructor.
387 // If both of those things are true, then we can rewrite:
388 // <pre>
389 // function Foo() {
390 // goog.base(this);
391 // }
392 // goog.inherits(Foo, BaseFoo);
393 // Foo.prototype.bar = function() {
394 // goog.base(this, 'bar', 1);
395 // };
396 // </pre>
397 // as the easy-to-optimize:
398 // <pre>
399 // function Foo() {
400 // BaseFoo.call(this);
401 // }
402 // goog.inherits(Foo, BaseFoo);
403 // Foo.prototype.bar = function() {
404 // Foo.superClass_.bar.call(this, 1);
405 // };
406 //
407 // Most of the logic here is just to make sure the AST's
408 // structure is what we expect it to be.
409
410 Node callee = n.getFirstChild();
411 Node thisArg = callee.getNext();
412 if (thisArg == null || !thisArg.isThis()) {
413 reportBadBaseClassUse(t, n, "First argument must be 'this'.");
414 return;
415 }
416
417 Node enclosingFnNameNode = getEnclosingDeclNameNode(t);
418 if (enclosingFnNameNode == null) {
419 reportBadBaseClassUse(t, n, "Could not find enclosing method.");
420 return;
421 }
422
423 String enclosingQname = enclosingFnNameNode.getQualifiedName();
424 if (enclosingQname.indexOf(".prototype.") == -1) {
425 // Handle constructors.
426 Node enclosingParent = enclosingFnNameNode.getParent();
427 Node maybeInheritsExpr = (enclosingParent.isAssign() ?
428 enclosingParent.getParent() : enclosingParent).getNext();
429 Node baseClassNode = null;
430 if (maybeInheritsExpr != null &&
431 maybeInheritsExpr.isExprResult() &&
432 maybeInheritsExpr.getFirstChild().isCall()) {
433 Node callNode = maybeInheritsExpr.getFirstChild();
434 if ("goog.inherits".equals(
435 callNode.getFirstChild().getQualifiedName()) &&
436 callNode.getLastChild().isQualifiedName()) {
437 baseClassNode = callNode.getLastChild();
438 }
439 }
440
441 if (baseClassNode == null) {
442 reportBadBaseClassUse(
443 t, n, "Could not find goog.inherits for base class");
444 return;
445 }
446
447 // We're good to go.
448 n.replaceChild(
449 callee,
450 NodeUtil.newQualifiedNameNode(
451 compiler.getCodingConvention(),
452 String.format("%s.call", baseClassNode.getQualifiedName()),
453 callee, "goog.base"));
454 compiler.reportCodeChange();
455 } else {
456 // Handle methods.
457 Node methodNameNode = thisArg.getNext();
458 if (methodNameNode == null || !methodNameNode.isString()) {
459 reportBadBaseClassUse(t, n, "Second argument must name a method.");
460 return;
461 }
462
463 String methodName = methodNameNode.getString();
464 String ending = ".prototype." + methodName;
465 if (enclosingQname == null ||
466 !enclosingQname.endsWith(ending)) {
467 reportBadBaseClassUse(
468 t, n, "Enclosing method does not match " + methodName);
469 return;
470 }
471
472 // We're good to go.
473 Node className =
474 enclosingFnNameNode.getFirstChild().getFirstChild();
475 n.replaceChild(
476 callee,
477 NodeUtil.newQualifiedNameNode(
478 compiler.getCodingConvention(),
479 String.format("%s.superClass_.%s.call",
480 className.getQualifiedName(), methodName),
481 callee, "goog.base"));
482 n.removeChild(methodNameNode);
483 compiler.reportCodeChange();
484 }
485 }
486
487 /**
488 * Returns the qualified name node of the function whose scope we're in,
489 * or null if it cannot be found.
490 */
491 private Node getEnclosingDeclNameNode(NodeTraversal t) {
492 Node scopeRoot = t.getScopeRoot();
493 if (NodeUtil.isFunctionDeclaration(scopeRoot)) {
494 // function x() {...}
495 return scopeRoot.getFirstChild();
496 } else {
497 Node parent = scopeRoot.getParent();
498 if (parent != null) {
499 if (parent.isAssign() ||
500 parent.getLastChild() == scopeRoot &&
501 parent.getFirstChild().isQualifiedName()) {
502 // x.y.z = function() {...};
503 return parent.getFirstChild();
504 } else if (parent.isName()) {
505 // var x = function() {...};
506 return parent;
507 }
508 }
509 }
510
511 return null;
512 }
513
514 /** Reports an incorrect use of super-method calling. */
515 private void reportBadBaseClassUse(
516 NodeTraversal t, Node n, String extraMessage) {
517 compiler.report(t.makeError(n, BASE_CLASS_ERROR, extraMessage));
518 }
519
520 /**
521 * Processes the output of processed-provide from a previous pass. This will
522 * update our data structures in the same manner as if the provide had been
523 * processed in this pass.
524 */
525 private void processProvideFromPreviousPass(
526 NodeTraversal t, String name, Node parent) {
527 if (!providedNames.containsKey(name)) {
528 // Record this provide created on a previous pass, and create a dummy
529 // EXPR node as a placeholder to simulate an explicit provide.
530 Node expr = new Node(Token.EXPR_RESULT);
531 expr.copyInformationFromForTree(parent);
532 parent.getParent().addChildBefore(expr, parent);
533 compiler.reportCodeChange();
534
535 JSModule module = t.getModule();
536 registerAnyProvidedPrefixes(name, expr, module);
537
538 ProvidedName provided = new ProvidedName(name, expr, module, true);
539 providedNames.put(name, provided);
540 provided.addDefinition(parent, module);
541 } else {
542 // Remove this provide if it came from a previous pass since we have an
543 // replacement already.
544 if (isNamespacePlaceholder(parent)) {
545 parent.getParent().removeChild(parent);
546 compiler.reportCodeChange();
547 }
548 }
549 }
550
551 /**
552 * Processes a call to goog.setCssNameMapping(). Either the argument to
553 * goog.setCssNameMapping() is valid, in which case it will be used to create
554 * a CssRenamingMap for the compiler of this CompilerPass, or it is invalid
555 * and a JSCompiler error will be reported.
556 * @see #visit(NodeTraversal, Node, Node)
557 */
558 private void processSetCssNameMapping(NodeTraversal t, Node n, Node parent) {
559 Node left = n.getFirstChild();
560 Node arg = left.getNext();
561 if (verifySetCssNameMapping(t, left, arg)) {
562 // Translate OBJECTLIT into SubstitutionMap. All keys and
563 // values must be strings, or an error will be thrown.
564 final Map<String, String> cssNames = Maps.newHashMap();
565
566 for (Node key = arg.getFirstChild(); key != null;
567 key = key.getNext()) {
568 Node value = key.getFirstChild();
569 if (!key.isStringKey()
570 || value == null
571 || !value.isString()) {
572 compiler.report(
573 t.makeError(n,
574 NON_STRING_PASSED_TO_SET_CSS_NAME_MAPPING_ERROR));
575 return;
576 }
577 cssNames.put(key.getString(), value.getString());
578 }
579
580 String styleStr = "BY_PART";
581 if (arg.getNext() != null) {
582 styleStr = arg.getNext().getString();
583 }
584
585 final CssRenamingMap.Style style;
586 try {
587 style = CssRenamingMap.Style.valueOf(styleStr);
588 } catch (IllegalArgumentException e) {
589 compiler.report(
590 t.makeError(n, INVALID_STYLE_ERROR, styleStr));
591 return;
592 }
593
594 if (style == CssRenamingMap.Style.BY_PART) {
595 // Make sure that no keys contain -'s
596 List<String> errors = Lists.newArrayList();
597 for (String key : cssNames.keySet()) {
598 if (key.contains("-")) {
599 errors.add(key);
600 }
601 }
602 if (errors.size() != 0) {
603 compiler.report(
604 t.makeError(n, INVALID_CSS_RENAMING_MAP, errors.toString()));
605 }
606 } else if (style == CssRenamingMap.Style.BY_WHOLE) {
607 // Verifying things is a lot trickier here. We just do a quick
608 // n^2 check over the map which makes sure that if "a-b" in
609 // the map, then map(a-b) = map(a)-map(b).
610 // To speed things up, only consider cases where len(b) <= 10
611 List<String> errors = Lists.newArrayList();
612 for (Map.Entry<String, String> b : cssNames.entrySet()) {
613 if (b.getKey().length() > 10) continue;
614 for (Map.Entry<String, String> a : cssNames.entrySet()) {
615 String combined = cssNames.get(a.getKey() + "-" + b.getKey());
616 if (combined != null &&
617 !combined.equals(a.getValue() + "-" + b.getValue())) {
618 errors.add("map(" + a.getKey() + "-" + b.getKey() +") != map(" +
619 a.getKey() + ")-map(" + b.getKey() +")");
620 }
621 }
622 }
623 if (errors.size() != 0) {
624 compiler.report(
625 t.makeError(n, INVALID_CSS_RENAMING_MAP, errors.toString()));
626 }
627 }
628
629 CssRenamingMap cssRenamingMap = new CssRenamingMap() {
630 @Override
631 public String get(String value) {
632 if (cssNames.containsKey(value)) {
633 return cssNames.get(value);
634 } else {
635 return value;
636 }
637 }
638
639 @Override
640 public CssRenamingMap.Style getStyle() {
641 return style;
642 }
643 };
644 compiler.setCssRenamingMap(cssRenamingMap);
645 parent.getParent().removeChild(parent);
646 compiler.reportCodeChange();
647 }
648 }
649
650 /**
651 * Verifies that a provide method call has exactly one argument,
652 * and that it's a string literal and that the contents of the string are
653 * valid JS tokens. Reports a compile error if it doesn't.
654 *
655 * @return Whether the argument checked out okay
656 */
657 private boolean verifyProvide(NodeTraversal t, Node methodName, Node arg) {
658 if (!verifyArgument(t, methodName, arg)) {
659 return false;
660 }
661
662 for (String part : arg.getString().split("\\.")) {
663 if (!NodeUtil.isValidPropertyName(part)) {
664 compiler.report(t.makeError(arg, INVALID_PROVIDE_ERROR, part));
665 return false;
666 }
667 }
668 return true;
669 }
670
671 /**
672 * Verifies that a method call has exactly one argument, and that it's a
673 * string literal. Reports a compile error if it doesn't.
674 *
675 * @return Whether the argument checked out okay
676 */
677 private boolean verifyArgument(NodeTraversal t, Node methodName, Node arg) {
678 return verifyArgument(t, methodName, arg, Token.STRING);
679 }
680
681 /**
682 * Verifies that a method call has exactly one argument, and that it is of the
683 * desired type. Reports a compile error if it doesn't.
684 *
685 * @return Whether the argument checked out okay
686 */
687 private boolean verifyArgument(NodeTraversal t, Node methodName, Node arg,
688 int desiredType) {
689 DiagnosticType diagnostic = null;
690 if (arg == null) {
691 diagnostic = NULL_ARGUMENT_ERROR;
692 } else if (arg.getType() != desiredType) {
693 diagnostic = INVALID_ARGUMENT_ERROR;
694 } else if (arg.getNext() != null) {
695 diagnostic = TOO_MANY_ARGUMENTS_ERROR;
696 }
697 if (diagnostic != null) {
698 compiler.report(
699 t.makeError(methodName,
700 diagnostic, methodName.getQualifiedName()));
701 return false;
702 }
703 return true;
704 }
705
706 /**
707 * Verifies that setCssNameMapping is called with the correct methods.
708 *
709 * @return Whether the arguments checked out okay
710 */
711 private boolean verifySetCssNameMapping(NodeTraversal t, Node methodName,
712 Node firstArg) {
713 DiagnosticType diagnostic = null;
714 if (firstArg == null) {
715 diagnostic = NULL_ARGUMENT_ERROR;
716 } else if (!firstArg.isObjectLit()) {
717 diagnostic = EXPECTED_OBJECTLIT_ERROR;
718 } else if (firstArg.getNext() != null) {
719 Node secondArg = firstArg.getNext();
720 if (!secondArg.isString()) {
721 diagnostic = EXPECTED_STRING_ERROR;
722 } else if (secondArg.getNext() != null) {
723 diagnostic = TOO_MANY_ARGUMENTS_ERROR;
724 }
725 }
726 if (diagnostic != null) {
727 compiler.report(
728 t.makeError(methodName,
729 diagnostic, methodName.getQualifiedName()));
730 return false;
731 }
732 return true;
733 }
734
735 /**
736 * Registers ProvidedNames for prefix namespaces if they haven't
737 * already been defined. The prefix namespaces must be registered in
738 * order from shortest to longest.
739 *
740 * @param ns The namespace whose prefixes may need to be provided.
741 * @param node The EXPR of the provide call.
742 * @param module The current module.
743 */
744 private void registerAnyProvidedPrefixes(
745 String ns, Node node, JSModule module) {
746 int pos = ns.indexOf('.');
747 while (pos != -1) {
748 String prefixNs = ns.substring(0, pos);
749 pos = ns.indexOf('.', pos + 1);
750 if (providedNames.containsKey(prefixNs)) {
751 providedNames.get(prefixNs).addProvide(
752 node, module, false /* implicit */);
753 } else {
754 providedNames.put(
755 prefixNs,
756 new ProvidedName(prefixNs, node, module, false /* implicit */));
757 }
758 }
759 }
760
761 // -------------------------------------------------------------------------
762
763 /**
764 * Information required to replace a goog.provide call later in the traversal.
765 */
766 private class ProvidedName {
767 private final String namespace;
768
769 // The node and module where the call was explicitly or implicitly
770 // goog.provided.
771 private final Node firstNode;
772 private final JSModule firstModule;
773
774 // The node where the call was explicitly goog.provided. May be null
775 // if the namespace is always provided implicitly.
776 private Node explicitNode = null;
777 private JSModule explicitModule = null;
778
779 // The candidate definition.
780 private Node candidateDefinition = null;
781
782 // The minimum module where the provide must appear.
783 private JSModule minimumModule = null;
784
785 // The replacement declaration.
786 private Node replacementNode = null;
787
788 ProvidedName(String namespace, Node node, JSModule module,
789 boolean explicit) {
790 Preconditions.checkArgument(
791 node == null /* The base case */ ||
792 node.isExprResult());
793 this.namespace = namespace;
794 this.firstNode = node;
795 this.firstModule = module;
796
797 addProvide(node, module, explicit);
798 }
799
800 /**
801 * Add an implicit or explicit provide.
802 */
803 void addProvide(Node node, JSModule module, boolean explicit) {
804 if (explicit) {
805 Preconditions.checkState(explicitNode == null);
806 Preconditions.checkArgument(node.isExprResult());
807 explicitNode = node;
808 explicitModule = module;
809 }
810 updateMinimumModule(module);
811 }
812
813 boolean isExplicitlyProvided() {
814 return explicitNode != null;
815 }
816
817 /**
818 * Record function declaration, variable declaration or assignment that
819 * refers to the same name as the provide statement. Give preference to
820 * declarations; if no declaration exists, record a reference to an
821 * assignment so it repurposed later.
822 */
823 void addDefinition(Node node, JSModule module) {
824 Preconditions.checkArgument(node.isExprResult() || // assign
825 node.isFunction() ||
826 node.isVar());
827 Preconditions.checkArgument(explicitNode != node);
828 if ((candidateDefinition == null) || !node.isExprResult()) {
829 candidateDefinition = node;
830 updateMinimumModule(module);
831 }
832 }
833
834 private void updateMinimumModule(JSModule newModule) {
835 if (minimumModule == null) {
836 minimumModule = newModule;
837 } else if (moduleGraph != null) {
838 minimumModule = moduleGraph.getDeepestCommonDependencyInclusive(
839 minimumModule, newModule);
840 } else {
841 // If there is no module graph, then there must be exactly one
842 // module in the program.
843 Preconditions.checkState(newModule == minimumModule,
844 "Missing module graph");
845 }
846 }
847
848 /**
849 * Replace the provide statement.
850 *
851 * If we're providing a name with no definition, then create one.
852 * If we're providing a name with a duplicate definition, then make sure
853 * that definition becomes a declaration.
854 */
855 void replace() {
856 if (firstNode == null) {
857 // Don't touch the base case ('goog').
858 replacementNode = candidateDefinition;
859 return;
860 }
861
862 // Handle the case where there is a duplicate definition for an explicitly
863 // provided symbol.
864 if (candidateDefinition != null && explicitNode != null) {
865 explicitNode.detachFromParent();
866 compiler.reportCodeChange();
867
868 // Does this need a VAR keyword?
869 replacementNode = candidateDefinition;
870 if (candidateDefinition.isExprResult() &&
871 !candidateDefinition.getFirstChild().isQualifiedName()) {
872 candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true);
873 Node assignNode = candidateDefinition.getFirstChild();
874 Node nameNode = assignNode.getFirstChild();
875 if (nameNode.isName()) {
876 // Need to convert this assign to a var declaration.
877 Node valueNode = nameNode.getNext();
878 assignNode.removeChild(nameNode);
879 assignNode.removeChild(valueNode);
880 nameNode.addChildToFront(valueNode);
881 Node varNode = IR.var(nameNode);
882 varNode.copyInformationFrom(candidateDefinition);
883 candidateDefinition.getParent().replaceChild(
884 candidateDefinition, varNode);
885 nameNode.setJSDocInfo(assignNode.getJSDocInfo());
886 compiler.reportCodeChange();
887 replacementNode = varNode;
888 }
889 }
890 } else {
891 // Handle the case where there's not a duplicate definition.
892 replacementNode = createDeclarationNode();
893 if (firstModule == minimumModule) {
894 firstNode.getParent().addChildBefore(replacementNode, firstNode);
895 } else {
896 // In this case, the name was implicitly provided by two independent
897 // modules. We need to move this code up to a common module.
898 int indexOfDot = namespace.lastIndexOf('.');
899 if (indexOfDot == -1) {
900 // Any old place is fine.
901 compiler.getNodeForCodeInsertion(minimumModule)
902 .addChildToBack(replacementNode);
903 } else {
904 // Add it after the parent namespace.
905 ProvidedName parentName =
906 providedNames.get(namespace.substring(0, indexOfDot));
907 Preconditions.checkNotNull(parentName);
908 Preconditions.checkNotNull(parentName.replacementNode);
909 parentName.replacementNode.getParent().addChildAfter(
910 replacementNode, parentName.replacementNode);
911 }
912 }
913 if (explicitNode != null) {
914 explicitNode.detachFromParent();
915 }
916 compiler.reportCodeChange();
917 }
918 }
919
920 /**
921 * Create the declaration node for this name, without inserting it
922 * into the AST.
923 */
924 private Node createDeclarationNode() {
925 if (namespace.indexOf('.') == -1) {
926 return makeVarDeclNode();
927 } else {
928 return makeAssignmentExprNode();
929 }
930 }
931
932 /**
933 * Creates a simple namespace variable declaration
934 * (e.g. <code>var foo = {};</code>).
935 */
936 private Node makeVarDeclNode() {
937 Node name = IR.name(namespace);
938 name.addChildToFront(createNamespaceLiteral());
939
940 Node decl = IR.var(name);
941 decl.putBooleanProp(Node.IS_NAMESPACE, true);
942
943 // TODO(nicksantos): ew ew ew. Create a mutator package.
944 if (compiler.getCodingConvention().isConstant(namespace)) {
945 name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
946 }
947 if (candidateDefinition == null) {
948 name.setJSDocInfo(createConstantJsDoc());
949 }
950
951 Preconditions.checkState(isNamespacePlaceholder(decl));
952 setSourceInfo(decl);
953 return decl;
954 }
955
956 /**
957 * There are some special cases where clients of the compiler
958 * do not run TypedScopeCreator after running this pass.
959 * So always give the namespace literal a type.
960 */
961 private Node createNamespaceLiteral() {
962 Node objlit = IR.objectlit();
963 objlit.setJSType(
964 compiler.getTypeRegistry().createAnonymousObjectType(null));
965 return objlit;
966 }
967
968 /**
969 * Creates a dotted namespace assignment expression
970 * (e.g. <code>foo.bar = {};</code>).
971 */
972 private Node makeAssignmentExprNode() {
973 Node decl = IR.exprResult(
974 IR.assign(
975 NodeUtil.newQualifiedNameNode(
976 compiler.getCodingConvention(), namespace,
977 firstNode /* real source info will be filled in below */,
978 namespace),
979 createNamespaceLiteral()));
980 decl.putBooleanProp(Node.IS_NAMESPACE, true);
981 if (candidateDefinition == null) {
982 decl.getFirstChild().setJSDocInfo(createConstantJsDoc());
983 }
984 Preconditions.checkState(isNamespacePlaceholder(decl));
985 setSourceInfo(decl);
986 return decl;
987 }
988
989 private JSDocInfo createConstantJsDoc() {
990 JSDocInfoBuilder builder = new JSDocInfoBuilder(false);
991 builder.recordConstancy();
992 return builder.build(null);
993 }
994
995 /**
996 * Copy source info to the new node.
997 */
998 private void setSourceInfo(Node newNode) {
999 Node provideStringNode = getProvideStringNode();
1000 int offset = getSourceInfoOffset(provideStringNode);
1001 Node sourceInfoNode = provideStringNode == null
1002 ? firstNode : provideStringNode;
1003 newNode.copyInformationFromForTree(sourceInfoNode);
1004 if (offset != 0) {
1005 newNode.setSourceEncodedPositionForTree(
1006 sourceInfoNode.getSourcePosition() + offset);
1007 }
1008 }
1009
1010 /**
1011 * Get the offset into the provide node where the symbol appears.
1012 */
1013 private int getSourceInfoOffset(Node provideStringNode) {
1014 if (provideStringNode == null) {
1015 return 0;
1016 }
1017
1018 int indexOfLastDot = namespace.lastIndexOf('.');
1019
1020 // +1 for the opening quote
1021 // +1 for the dot
1022 // if there's no dot, then the -1 index cancels it out
1023 // so elegant!
1024 return 2 + indexOfLastDot;
1025 }
1026
1027 private Node getProvideStringNode() {
1028 return (firstNode.getFirstChild() != null &&
1029 NodeUtil.isExprCall(firstNode)) ?
1030 firstNode.getFirstChild().getLastChild() :
1031 null;
1032 }
1033 }
1034
1035 /**
1036 * @return Whether the node is namespace placeholder.
1037 */
1038 private static boolean isNamespacePlaceholder(Node n) {
1039 if (!n.getBooleanProp(Node.IS_NAMESPACE)) {
1040 return false;
1041 }
1042
1043 Node value = null;
1044 if (n.isExprResult()) {
1045 Node assign = n.getFirstChild();
1046 value = assign.getLastChild();
1047 } else if (n.isVar()) {
1048 Node name = n.getFirstChild();
1049 value = name.getFirstChild();
1050 }
1051
1052 return value != null
1053 && value.isObjectLit()
1054 && !value.hasChildren();
1055 }
1056
1057 /**
1058 * The string in {@code n} is a reference name. Create a synthetic
1059 * node for it with all the proper source info, and add it to the symbol
1060 * table.
1061 */
1062 private void maybeAddStringNodeToSymbolTable(Node n) {
1063 if (preprocessorSymbolTable == null) {
1064 return;
1065 }
1066
1067 String name = n.getString();
1068 Node syntheticRef = NodeUtil.newQualifiedNameNode(
1069 compiler.getCodingConvention(), name,
1070 n /* real source offsets will be filled in below */,
1071 name);
1072
1073 // Offsets to add to source. Named for documentation purposes.
1074 final int FOR_QUOTE = 1;
1075 final int FOR_DOT = 1;
1076
1077 Node current = null;
1078 for (current = syntheticRef;
1079 current.isGetProp();
1080 current = current.getFirstChild()) {
1081 int fullLen = current.getQualifiedName().length();
1082 int namespaceLen = current.getFirstChild().getQualifiedName().length();
1083
1084 current.setSourceEncodedPosition(n.getSourcePosition() + FOR_QUOTE);
1085 current.setLength(fullLen);
1086
1087 current.getLastChild().setSourceEncodedPosition(
1088 n.getSourcePosition() + namespaceLen + FOR_QUOTE + FOR_DOT);
1089 current.getLastChild().setLength(
1090 current.getLastChild().getString().length());
1091 }
1092
1093 current.setSourceEncodedPosition(n.getSourcePosition() + FOR_QUOTE);
1094 current.setLength(current.getString().length());
1095
1096 maybeAddToSymbolTable(syntheticRef);
1097 }
1098
1099 /**
1100 * Add the given qualified name node to the symbol table.
1101 */
1102 private void maybeAddToSymbolTable(Node n) {
1103 if (preprocessorSymbolTable != null) {
1104 preprocessorSymbolTable.addReference(n);
1105 }
1106 }
1107
1108 // -------------------------------------------------------------------------
1109
1110 /**
1111 * Information required to create a {@code MISSING_PROVIDE_ERROR} warning.
1112 */
1113 private class UnrecognizedRequire {
1114 final Node requireNode;
1115 final String namespace;
1116 final String inputName;
1117
1118 UnrecognizedRequire(Node requireNode, String namespace, String inputName) {
1119 this.requireNode = requireNode;
1120 this.namespace = namespace;
1121 this.inputName = inputName;
1122 }
1123 }
1124 }