Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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.HashMultimap;
21 import com.google.common.collect.Multimap;
22 import com.google.javascript.jscomp.NameReferenceGraph.Name;
23 import com.google.javascript.jscomp.NameReferenceGraph.Reference;
24 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
25 import com.google.javascript.jscomp.Scope.Var;
26 import com.google.javascript.jscomp.graph.GraphNode;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29 import com.google.javascript.rhino.jstype.FunctionType;
30 import com.google.javascript.rhino.jstype.JSType;
31 import com.google.javascript.rhino.jstype.JSTypeNative;
32 import com.google.javascript.rhino.jstype.ObjectType;
33
34 import java.util.ArrayList;
35 import java.util.Collection;
36
37 import javax.annotation.Nullable;
38
39 /**
40 * Constructs a name reference graph.
41 *
42 * @see NameReferenceGraph
43 *
44 */
45 class NameReferenceGraphConstruction implements CompilerPass {
46
47 private final AbstractCompiler compiler;
48 private final NameReferenceGraph graph;
49
50 // Maps "foo" -> (curFuncName, unknownObject.foo) if we have no idea what
51 // the unknown object is. After we finish one pass, we must go through all
52 // the nodes that might have a name foo and connect that to the curFuncName.
53 // The accuracy of the analysis will depend heavily on eliminating the need
54 // to resort to this map.
55 private final Multimap<String, NameUse> unknownNameUse =
56 HashMultimap.create();
57
58 // Should we continue even if we found a type checker bug.
59 private static final boolean CONSERVATIVE = false;
60
61 // The symbol for the current function so we can quickly create a reference
62 // edge when we see a call: Example when this symbol is foo() and we see
63 // bar(), we connect foo -> bar.
64 private final ArrayList<Name> currentFunctionStack = new ArrayList<Name>();
65
66 NameReferenceGraphConstruction(AbstractCompiler compiler) {
67 this.compiler = compiler;
68 this.graph = new NameReferenceGraph(compiler);
69 }
70
71 NameReferenceGraph getNameReferenceGraph() {
72 return this.graph;
73 }
74
75 @Override
76 public void process(Node externs, Node root) {
77 // Use the MemoizedScopeCreator instance from TypeCheck if available
78 // as FunctionTypeBuilder warns about existing types if TypedScopeCreator is
79 // ran a second time.
80 ScopeCreator scopeCreator = compiler.getTypedScopeCreator();
81 if (scopeCreator == null) {
82 // The TypedScopeCreator gives us correct handling of namespaces,
83 // while the default NodeTraversal only gives us a
84 // SyntacticScopeCreator.
85 scopeCreator = new MemoizedScopeCreator(new TypedScopeCreator(compiler));
86 }
87 NodeTraversal externsTraversal = new NodeTraversal(compiler,
88 new Traversal(true), scopeCreator);
89 NodeTraversal codeTraversal = new NodeTraversal(compiler,
90 new Traversal(false), scopeCreator);
91 Scope topScope = compiler.getTopScope();
92 if (topScope != null) {
93 externsTraversal.traverseWithScope(externs, topScope);
94 codeTraversal.traverseWithScope(root, topScope);
95 } else {
96 externsTraversal.traverse(externs);
97 codeTraversal.traverse(root);
98 }
99 connectUnknowns();
100 }
101
102 private class Traversal implements ScopedCallback {
103
104 final boolean isExtern;
105
106 private Traversal(boolean isExtern) {
107 this.isExtern = isExtern;
108 pushContainingFunction(graph.MAIN);
109 }
110
111 @Override
112 public void enterScope(NodeTraversal t) {
113 Node root = t.getScopeRoot();
114 Node parent = root.getParent();
115
116 // When we are not in a {{GLOBAL MAIN}}, we need to determine what the
117 // current function is.
118 if (!t.inGlobalScope()) {
119
120 // TODO(user): A global function foo() is treated as the same
121 // function as a inner function named foo(). We should use some clever
122 // naming scheme to avoid this lost of precision.
123 String name = NodeUtil.getFunctionName(root);
124
125 if (name == null) {
126 // When the name is null, we have a function that is presumably not
127 // reference-able again and should not be modeled in the name graph.
128 // A common example would be (function() { ... })();
129 pushContainingFunction(graph.UNKNOWN);
130 return;
131 }
132
133 // If we've done type analysis, then we should be able to get the
134 // correct JSFunctionType for the containing function. If not,
135 // we're probably going to get an unknown type here.
136 JSType type = getType(root);
137
138 if (parent.isAssign() &&
139 NodeUtil.isPrototypeProperty(parent.getFirstChild())) {
140 pushContainingFunction(
141 recordPrototypePropDefinition(parent.getFirstChild(), type, parent));
142 } else {
143 pushContainingFunction(
144 recordStaticNameDefinition(
145 name, type, root, root.getLastChild()));
146 }
147 }
148 }
149
150 @Override
151 public void exitScope(NodeTraversal t) {
152 if (!t.inGlobalScope()) {
153 popContainingFunction();
154 }
155 }
156
157 @Override
158 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
159 return true;
160 }
161
162 @SuppressWarnings("fallthrough")
163 @Override
164 public void visit(NodeTraversal t, Node n, Node parent) {
165 switch (n.getType()) {
166 case Token.NAME:
167 case Token.GETPROP:
168 if (parent.isGetProp()) {
169 // We will resolve this when we visit parent later in the traversal.
170 return;
171 } else if (parent.isFunction()) {
172 // Function declarations have been taken care of in enterScope();
173 return;
174 } else if (parent.isAssign()) {
175 // Handled below.
176 return;
177 }
178
179 if (isLocalNameReference(t, n)) {
180 // Ignore all local variable references unless is creates a closure.
181 return;
182 }
183
184 if (isPrototypeNameReference(n)) {
185 recordPrototypePropUse(n, parent);
186 } else if (isStaticNameReference(n, t.getScope())) {
187 recordStaticNameUse(n, parent);
188 } else {
189 recordUnknownUse(n, parent);
190 }
191 break;
192
193 case Token.ASSIGN:
194 Node lhs = n.getFirstChild();
195 Node rhs = n.getLastChild();
196 if (rhs.isFunction()) {
197 // These are recorded when entering the scope.
198 return;
199 }
200 if (lhs.isName() ||
201 lhs.isGetProp() ||
202 rhs.isGetProp()) {
203 if (NodeUtil.isPrototypeProperty(lhs)) {
204 Name name = recordPrototypePropDefinition(
205 lhs, getType(rhs), n);
206 name.setAliased(true);
207 }
208 }
209 maybeAliasNamesOnAssign(lhs, rhs);
210 break;
211
212 case Token.VAR:
213 // var foo = bar;
214 Node varName = n.getFirstChild();
215 Node assignedValue = varName.getFirstChild();
216 if (assignedValue == null) {
217 return;
218 }
219 maybeAliasNamesOnAssign(varName, assignedValue);
220 break;
221
222 case Token.CALL:
223 Node param = n.getFirstChild();
224 // We need to alias every name that is passed as a parameter because
225 // they have different names inside the function's scope.
226 while ((param = param.getNext()) != null) {
227 if (param.isName() || param.isGetProp()) {
228 safeAlias(param);
229 }
230 }
231
232 maybeRecordExport(n);
233 break;
234 }
235 }
236
237 private boolean containsName(Node n) {
238 return NodeUtil.containsType(n, Token.NAME) ||
239 NodeUtil.containsType(n, Token.GETELEM) ||
240 NodeUtil.containsType(n, Token.GETPROP);
241 }
242
243 /**
244 * Given a node, this alias all the names in the node that need aliasing.
245 * This is safer than just calling getQualifiedName() because it can return
246 * null it several situations.
247 * @param n node to alias
248 */
249 private void safeAlias(Node n) {
250 if (n.isName() || n.isGetProp()) {
251 String name = n.getQualifiedName();
252 // getQualifiedName can return null in cases like bar[0].baz
253 if (name != null) {
254 defineAndAlias(name);
255 return;
256 }
257 }
258
259 if (n.isGetProp()) {
260 // var foo = bar[0].baz;
261 defineAndAlias(n.getLastChild().getString());
262 } else if (n.isAssign()) {
263 // In case of nested assignment, we only consider the name of the
264 // immediate neighbor.
265 safeAlias(n.getFirstChild());
266 } else if (n.hasChildren()) {
267 Node cur = n.getFirstChild();
268 do {
269 safeAlias(cur);
270 } while ((cur = cur.getNext()) != null);
271 } else {
272 // No name to alias
273 }
274 }
275
276 private void maybeAliasNamesOnAssign(Node lhs, Node rhs) {
277 if ((lhs.isName() || lhs.isGetProp()) &&
278 containsName(rhs) &&
279 !rhs.isFunction() &&
280 !rhs.isNew()) {
281 safeAlias(lhs);
282 safeAlias(rhs);
283 }
284 }
285
286 private void defineAndAlias(String name) {
287 graph.defineNameIfNotExists(name, isExtern).setAliased(true);
288 }
289
290 private void maybeRecordExport(Node call) {
291 Preconditions.checkArgument(call.isCall());
292 Node getProp = call.getFirstChild();
293 if (!getProp.isGetProp()) {
294 return;
295 }
296
297 String propQName = getProp.getQualifiedName();
298
299 if (propQName == null) {
300 return;
301 }
302
303 // Keep track of calls to "call" and "apply" because they mess up the name
304 // graph.
305 if (propQName.endsWith(".call") || propQName.endsWith(".apply")) {
306 graph.defineNameIfNotExists(getProp.getFirstChild().getQualifiedName(),
307 isExtern).markExposedToCallOrApply();
308 }
309
310 if (!"goog.exportSymbol".equals(propQName)) {
311 return;
312 }
313
314 Node symbol = getProp.getNext();
315 if (!symbol.isString()) {
316 return;
317 }
318
319 Node obj = symbol.getNext();
320 String qName = obj.getQualifiedName();
321
322 if (qName == null || obj.getNext() != null) {
323 return;
324 }
325
326 graph.defineNameIfNotExists(qName, false).markExported();
327 }
328
329 /**
330 * @return true if n MUST be a local name reference.
331 */
332 private boolean isLocalNameReference(NodeTraversal t, Node n) {
333 // TODO(user): What happen if it is a reference to an outer local
334 // variable (closures)?
335 if (n.isName()) {
336 Var v = t.getScope().getVar(n.getString());
337 return v != null && v.isLocal();
338 }
339 return false;
340 }
341
342 /**
343 * @return true if n MUST be a static name reference.
344 */
345 private boolean isStaticNameReference(Node n, Scope scope) {
346 Preconditions.checkArgument(n.isName() || n.isGetProp());
347 if (n.isName()) {
348 return true;
349 }
350 String qName = n.getQualifiedName();
351 if (qName == null) {
352 return false;
353 }
354 // TODO(user): This does not always work due to type system bugs.
355 return scope.isDeclared(qName, true);
356 }
357
358 /**
359 * @return true if n MUST be a prototype name reference.
360 */
361 private boolean isPrototypeNameReference(Node n) {
362 if (!n.isGetProp()) {
363 return false;
364 }
365 JSType type = getType(n.getFirstChild());
366 if (type.isUnknownType() || type.isUnionType()) {
367 return false;
368 }
369 return (type.isInstanceType() || type.autoboxesTo() != null);
370 }
371
372 private Name recordStaticNameDefinition(String name, JSType type,
373 Node n, Node rValue) {
374 if (getNamedContainingFunction() != graph.MAIN) {
375 // TODO(user): if A.B() defines A.C(), there is a dependence from
376 // A.C() -> A.B(). However, this is not important in module code motion
377 // and will be ignored (for now).
378 }
379 if (type.isConstructor()) {
380 return recordClassConstructorOrInterface(
381 name, type.toMaybeFunctionType(),
382 n, rValue);
383 } else {
384 Name symbol = graph.defineNameIfNotExists(name, isExtern);
385 symbol.setType(type);
386 if (n.isAssign()) {
387 symbol.addAssignmentDeclaration(n);
388 } else {
389 symbol.addFunctionDeclaration(n);
390 }
391 return symbol;
392 }
393 }
394
395 /**
396 * @param assign The assignment node, null if it is just a "forward"
397 * declaration for recording the rValue's type.
398 */
399 private Name recordPrototypePropDefinition(
400 Node qName, JSType type, @Nullable Node assign) {
401 JSType constructor = getType(NodeUtil.getPrototypeClassName(qName));
402 FunctionType classType = null;
403 String className = null;
404
405 if (constructor != null && constructor.isConstructor()) {
406 // Case where the class has been properly declared with @constructor
407 classType = constructor.toMaybeFunctionType();
408 className = classType.getReferenceName();
409 } else {
410 // We'll guess it is a constructor even if it didn't have @constructor
411 classType = compiler.getTypeRegistry().getNativeFunctionType(
412 JSTypeNative.U2U_CONSTRUCTOR_TYPE);
413 className = NodeUtil.getPrototypeClassName(qName).getQualifiedName();
414 }
415 // In case we haven't seen the function yet.
416 recordClassConstructorOrInterface(
417 className, classType, null, null);
418
419 String qNameStr = className + ".prototype." +
420 NodeUtil.getPrototypePropertyName(qName);
421 Name prototypeProp = graph.defineNameIfNotExists(qNameStr, isExtern);
422 Preconditions.checkNotNull(prototypeProp,
423 "%s should be in the name graph as a node.", qNameStr);
424 if (assign != null) {
425 prototypeProp.addAssignmentDeclaration(assign);
426 }
427 prototypeProp.setType(type);
428 return prototypeProp;
429 }
430
431 private Reference recordStaticNameUse(
432 Node n, Node parent) {
433 if (isExtern) {
434 // Don't count reference in extern as a use.
435 return null;
436 } else {
437 Reference reference = new Reference(n, parent);
438 Name name = graph.defineNameIfNotExists(n.getQualifiedName(), isExtern);
439 name.setType(getType(n));
440 graph.connect(getNamedContainingFunction(), reference, name);
441 return reference;
442 }
443 }
444
445 private void recordPrototypePropUse(Node n, Node parent) {
446 Preconditions.checkArgument(n.isGetProp());
447 Node instance = n.getFirstChild();
448 JSType instanceType = getType(instance);
449 JSType boxedType = instanceType.autoboxesTo();
450 instanceType = boxedType != null ? boxedType : instanceType;
451
452 // Retrieves the property.
453 ObjectType objType = instanceType.toObjectType();
454 Preconditions.checkState(objType != null);
455
456 if (!isExtern) {
457 // Don't count reference in extern as a use.
458 Reference ref = new Reference(n, parent);
459
460 FunctionType constructor = objType.getConstructor();
461 if (constructor != null) {
462 String propName = n.getLastChild().getString();
463 if (!constructor.getPrototype().hasOwnProperty(propName)) {
464 recordSuperClassPrototypePropUse(constructor, propName, ref);
465 }
466
467 // TODO(user): TightenType can help a whole lot here.
468 recordSubclassPrototypePropUse(constructor, propName, ref);
469 } else {
470 recordUnknownUse(n, parent);
471 }
472 }
473 }
474
475 /**
476 * Look for the super class implementation up the tree.
477 */
478 private void recordSuperClassPrototypePropUse(
479 FunctionType classType, String prop, Reference ref) {
480 FunctionType superClass = classType.getSuperClassConstructor();
481 while (superClass != null) {
482 if (superClass.getPrototype().hasOwnProperty(prop)) {
483 graph.connect(getNamedContainingFunction(), ref,
484 graph.defineNameIfNotExists(
485 superClass.getReferenceName() + ".prototype." + prop, false));
486 return;
487 } else {
488 superClass = superClass.getSuperClassConstructor();
489 }
490 }
491 }
492
493 /**
494 * Conservatively assumes that all subclass implementation of this property
495 * might be called.
496 */
497 private void recordSubclassPrototypePropUse(
498 FunctionType classType, String prop, Reference ref) {
499 if (classType.getPrototype().hasOwnProperty(prop)) {
500 graph.connect(getNamedContainingFunction(), ref,
501 graph.defineNameIfNotExists(
502 classType.getReferenceName() + ".prototype." + prop, false));
503 }
504 if (classType.getSubTypes() != null) {
505 for (FunctionType subclass : classType.getSubTypes()) {
506 recordSubclassPrototypePropUse(subclass, prop, ref);
507 }
508 }
509 }
510
511 private void recordUnknownUse(Node n, Node parent) {
512 if (isExtern) {
513 // Don't count reference in extern as a use.
514 return;
515 } else {
516 Preconditions.checkArgument(n.isGetProp());
517 Reference ref = new Reference(n, parent);
518 ref.setUnknown(true);
519 unknownNameUse.put(n.getLastChild().getString(),
520 new NameUse(getNamedContainingFunction(), ref));
521 }
522 }
523
524 /**
525 * Creates the name in the graph if it does not already exist. Also puts all
526 * the properties and prototype properties of this name in the graph.
527 */
528 private Name recordClassConstructorOrInterface(
529 String name, FunctionType type, @Nullable Node n, @Nullable Node rhs) {
530 Preconditions.checkArgument(type.isConstructor() || type.isInterface());
531 Name symbol = graph.defineNameIfNotExists(name, isExtern);
532 if (rhs != null) {
533 // TODO(user): record the definition.
534 symbol.setType(getType(rhs));
535 if (n.isAssign()) {
536 symbol.addAssignmentDeclaration(n);
537 } else {
538 symbol.addFunctionDeclaration(n);
539 }
540 }
541 ObjectType prototype = type.getPrototype();
542 for (String prop : prototype.getOwnPropertyNames()) {
543 graph.defineNameIfNotExists(
544 name + ".prototype." + prop, isExtern);
545 }
546 return symbol;
547 }
548 }
549
550 private void connectUnknowns() {
551 for (GraphNode<Name, Reference> node : graph.getNodes()) {
552 Name name = node.getValue();
553 String propName = name.getPropertyName();
554 if (propName == null) {
555 continue;
556 }
557 Collection<NameUse> uses = unknownNameUse.get(propName);
558 if (uses != null) {
559 for (NameUse use : uses) {
560 graph.connect(use.name, use.reference, name);
561 }
562 }
563 }
564 }
565
566 /**
567 * A helper to retrieve the type of a node.
568 */
569 private JSType getType(Node n) {
570 JSType type = n.getJSType();
571 if (type == null) {
572 if (CONSERVATIVE) {
573 throw new RuntimeException("Type system failed us :(");
574 } else {
575 return compiler.getTypeRegistry().getNativeType(
576 JSTypeNative.UNKNOWN_TYPE);
577 }
578 }
579 // Null-ability does not affect the name graph's result.
580 return type.restrictByNotNullOrUndefined();
581 }
582
583 /**
584 * Mark the provided node as the current function that we are analyzing.
585 * and add it to the stack of scopes we are inside.
586 *
587 * @param functionNode node representing current function.
588 */
589 private void pushContainingFunction(Name functionNode) {
590 currentFunctionStack.add(functionNode);
591 }
592
593 /**
594 * Remove the top item off the containing function stack, and restore the
595 * previous containing scope to the be the current containing function.
596 */
597 private void popContainingFunction() {
598 currentFunctionStack.remove(currentFunctionStack.size() - 1);
599 }
600
601 /**
602 * Find the first containing function that's not an function expression
603 * closure.
604 */
605 private Name getNamedContainingFunction() {
606 Name containingFn = null;
607 int pos;
608 for (pos = currentFunctionStack.size() - 1; pos >= 0; pos = pos - 1) {
609 Name cf = currentFunctionStack.get(pos);
610 if (cf != graph.UNKNOWN) {
611 containingFn = cf;
612 break;
613 }
614 }
615 Preconditions.checkNotNull(containingFn);
616 return containingFn;
617 }
618
619 private static class NameUse {
620 private final Name name;
621 private final Reference reference;
622
623 private NameUse(Name name, Reference reference) {
624 this.name = name;
625 this.reference = reference;
626 }
627 }
628 }