Debian Codegraph @

src/com/google/javascript/jscomp/NameReferenceGraph.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.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Multimap;
24 import com.google.javascript.jscomp.DefinitionsRemover.AssignmentDefinition;
25 import com.google.javascript.jscomp.DefinitionsRemover.Definition;
26 import com.google.javascript.jscomp.DefinitionsRemover.NamedFunctionDefinition;
27 import com.google.javascript.jscomp.graph.GraphNode;
28 import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
29 import com.google.javascript.rhino.Node;
30 import com.google.javascript.rhino.jstype.JSType;
31 import com.google.javascript.rhino.jstype.JSTypeNative;
32
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
36 import java.util.Map;
37
38 /**
39 * A graph represents all the referencing of global names in the program. In
40 * other words, it is a call and variable-name graph.
41 *
42 * <p>The NameReferenceGraph G for a program P is a directed graph G = (V, E)
43 * where:
44 *
45 * <P>V ({@link Name}) represents all global names in P and E = (v, v'), v and
46 * v' in V ({@link Reference} represents a reference use or definition from the
47 * name v to v' in P.
48 *
49 * <p>There are two core results we are trying to compute. The first being able
50 * to precisely identify the function body at any given call site with
51 * {@link #getReferencesAt(Node)}.
52 *
53 * <p>The second result come directly from the previous one. The directed edge
54 * provides us with dependency information. If A->B, B might be needed (in this
55 * module) if A is needed (in this module). The converse of the this result is
56 * more useful. B is not needed if A is not needed.
57 *
58 */
59 class NameReferenceGraph extends
60 LinkedDirectedGraph<NameReferenceGraph.Name, NameReferenceGraph.Reference>
61 implements DefinitionProvider {
62
63 // This is the key result of the name graph. Given a node in the AST, this map
64 // will give us the Reference edges. For example a CALL node will map to a
65 // list of possible call edge destinations.
66 private final Multimap<Node, Name>
67 referenceMap = HashMultimap.create();
68
69 // Given a qualified name, provides the Name object.
70 private Map<String, Name> nameMap = Maps.newHashMap();
71
72 // The following are some implicit nodes of the graph.
73
74 // If we have a call site that we absolutely have no idea what variable it
75 // it calls or reference, we'd point it to UNKNOWN.
76 final Name UNKNOWN;
77
78 // Represents the "main" global block as well as externs.
79 final Name MAIN;
80
81 // The implicit "window" object.
82 final Name WINDOW;
83
84 final AbstractCompiler compiler;
85
86 public NameReferenceGraph(AbstractCompiler compiler) {
87 super(true, true);
88 this.compiler = compiler;
89
90 // Initialize builtins.
91 UNKNOWN = new Name("{UNKNOWN}", true);
92 UNKNOWN.isAliased = true;
93 UNKNOWN.type = compiler.getTypeRegistry().getNativeType(
94 JSTypeNative.NO_TYPE);
95 this.createNode(UNKNOWN);
96
97 MAIN = new Name("{Global Main}", true);
98 this.createNode(MAIN);
99
100 WINDOW = new Name("window", true);
101 this.createNode(WINDOW);
102 }
103
104 public Name defineNameIfNotExists(String name, boolean isExtern) {
105 Name symbol = null;
106 if (nameMap.containsKey(name)) {
107 // This is a re-declaration.
108 symbol = nameMap.get(name);
109 } else {
110 symbol = new Name(name, isExtern);
111 nameMap.put(name, symbol);
112 createNode(symbol);
113 }
114 return symbol;
115 }
116
117 /**
118 * Retrieves a list of all possible Names that this site is referring to.
119 */
120 public List<Name> getReferencesAt(Node site) {
121 Preconditions.checkArgument(
122 site.isGetProp() || site.isName());
123 List<Name> result = new ArrayList<Name>();
124 for (Name target : referenceMap.get(site)) {
125 result.add(target);
126 }
127 return result;
128 }
129
130 @Override
131 public Collection<Definition> getDefinitionsReferencedAt(Node useSite) {
132 List<Name> nameRefs = getReferencesAt(useSite);
133 if (nameRefs.isEmpty()) {
134 return null;
135 }
136
137 List<Definition> result = Lists.newArrayList();
138 for (Name nameRef : nameRefs) {
139 List<Definition> decls = nameRef.getDeclarations();
140 if (!decls.isEmpty()) {
141 result.addAll(decls);
142 }
143 }
144
145 if (!result.isEmpty()) {
146 return result;
147 } else {
148 return null;
149 }
150 }
151
152 public Name getSymbol(String name) {
153 return nameMap.get(name);
154 }
155
156 @Override
157 public GraphNode<Name, Reference> createNode(Name value) {
158 nameMap.put(value.qName, value);
159 return super.createNode(value);
160 }
161
162 @Override
163 public void connect(Name src, Reference ref, Name dest) {
164 super.connect(src, ref, dest);
165 referenceMap.put(ref.site, dest);
166 }
167
168 /**
169 * Represents function or variable names that can be referenced globally.
170 */
171 class Name {
172 // Full name
173 private final String qName;
174
175 private JSType type;
176
177 // A list (re)declarations
178 private List<Definition> declarations = Lists.newLinkedList();
179
180 final boolean isExtern;
181
182 private boolean isExported = false;
183
184 private boolean isAliased = false;
185
186 // Function invocations that use ".call" and ".apply" syntax may prevent
187 // several of the possible optimizations. We keep track of all functions
188 // invoked in this way so those passes can exclude them.
189 // Ex:
190 // some_func.call(some_obj, 1, 2 , 3);
191 // The name graph does not currently recognize this as a call to some_func.
192 // This Set is meant to keep track of such occurrence until the name graph
193 // becomes aware of those cases.
194 private boolean exposedToCallOrApply = false;
195
196 public Name(String qName, boolean isExtern) {
197 this.qName = qName;
198 this.isExtern = isExtern;
199 int lastDot = qName.lastIndexOf('.');
200 String name = (lastDot == -1) ? qName : qName.substring(lastDot + 1);
201 this.isExported = compiler.getCodingConvention().isExported(name);
202 this.type = compiler.getTypeRegistry().getNativeType(
203 JSTypeNative.UNKNOWN_TYPE);
204 }
205
206 public JSType getType() {
207 return type;
208 }
209
210 public void setType(JSType type) {
211 this.type = type;
212 }
213
214 public List<Definition> getDeclarations() {
215 return declarations;
216 }
217
218 public void addAssignmentDeclaration(Node node) {
219 declarations.add(new AssignmentDefinition(node, isExtern));
220 }
221
222 public void addFunctionDeclaration(Node node) {
223 declarations.add(new NamedFunctionDefinition(node, isExtern));
224 }
225
226 public boolean isExtern() {
227 return isExtern;
228 }
229
230 public void markExported() {
231 this.isExported = true;
232 }
233
234 public boolean isExported() {
235 return isExported;
236 }
237
238 /** Removes all of the declarations of this name. */
239 public final void remove() {
240 for (Definition declaration : getDeclarations()) {
241 declaration.remove();
242 }
243 }
244
245 /**
246 * @return {@code} True if this name has been dereferenced. Removing from
247 * the program or the module is no longer safe unless further analysis
248 * can prove otherwise.
249 */
250 public boolean isAliased() {
251 return isAliased;
252 }
253
254 public void setAliased(boolean isAliased) {
255 this.isAliased = isAliased;
256 }
257
258 public boolean hasSideEffect() {
259 return isCallable();
260 }
261
262 public String getQualifiedName() {
263 return qName;
264 }
265
266 /**
267 * @return The short property name of this object if it is a property, else
268 * {@code null}.
269 */
270 public String getPropertyName() {
271 int lastIndexOfDot = qName.lastIndexOf('.');
272 if (lastIndexOfDot == -1) {
273 return null;
274 } else {
275 return qName.substring(lastIndexOfDot + 1);
276 }
277 }
278
279 public boolean isCallable() {
280 return type.canBeCalled();
281 }
282
283 public boolean exposedToCallOrApply() {
284 return exposedToCallOrApply;
285 }
286
287 public void markExposedToCallOrApply() {
288 exposedToCallOrApply = true;
289 }
290
291 @Override
292 public String toString() {
293 return qName + " : " + type;
294 }
295
296 @Override
297 public int hashCode() {
298 return qName.hashCode();
299 }
300
301 /**
302 * Return true if it's safe to change the signature of the function
303 * references by this name. It is safe to change the signature if the Name
304 * is:
305 * <ul>
306 * <li>callable</li>
307 * <li>not an extern</li>
308 * <li>not been aliased</li>
309 * <li>not been exported</li>
310 * <li>Referred by call or apply functions</li>
311 * <li>The function uses the arguments property</li>
312 * </ul>
313 *
314 * @return true if it's safe to change the signature of the name.
315 */
316 public boolean canChangeSignature() {
317 // Ignore anything that is extern as they should not be changed.
318 // Also skip over any non-function names. Finally if a function has been
319 // alias, we don't know all of its callers and should not optimize.
320 //
321 // Also, if the function is called using .call or .apply, we don't try to
322 // optimize those call because the name graph does not give us enough
323 // information on the parameters.
324
325 // TODO(user) We'll be able to remove the check for call or apply once
326 // the name graph handles those call. The issue for now is that those
327 // calls aren't edges in the graph, so we don't have enough information to
328 // know if it's safe to change the method's signature.
329 return !(isExtern() ||
330 !isCallable() ||
331 isAliased() ||
332 isExported() ||
333 exposedToCallOrApply() ||
334 nameUsesArgumentsProperty());
335 }
336
337 /**
338 * Returns true if the the arguments property is used in any of the function
339 * definition.
340 * Ex. function foo(a,b,c) {return arguments.size;};
341 * @return True is arguments is present in one of the definitions.
342 */
343 private boolean nameUsesArgumentsProperty() {
344 for (Definition definition : getDeclarations()) {
345 if (NodeUtil.isVarArgsFunction(definition.getRValue())) {
346 return true;
347 }
348 }
349 return false;
350 }
351 }
352
353 /**
354 * A reference site for a function or a variable reference. It can be a
355 * reference use or an assignment to that name.
356 */
357 static class Reference {
358 // The node that references the name.
359 public final Node site;
360
361 // Parent pointer.
362 public final Node parent;
363
364 private JSModule module = null;
365
366 // A reference is unknown because we don't know the object's type.
367 // If A.x->B.y in the name graph and the edge is unknown. It implies
368 // A.x() reference to someObject.y and B.y MAY be the site.
369 private boolean isUnknown = false;
370
371 public Reference(Node site, Node parent) {
372 this.site = site;
373 this.parent = parent;
374 }
375
376 public boolean isUnknown() {
377 return isUnknown;
378 }
379
380 public void setUnknown(boolean isUnknown) {
381 this.isUnknown = isUnknown;
382 }
383
384 public JSModule getModule() {
385 return module;
386 }
387
388 public void setModule(JSModule module) {
389 this.module = module;
390 }
391
392 boolean isCall() {
393 return site.isCall();
394 }
395
396 /**
397 * Get accessor for retrieving the actual node corresponding to the
398 * reference.
399 *
400 * @return node representing the access/reference/call site
401 */
402 public Node getSite() {
403 return site;
404 }
405 }
406 }