Debian Codegraph @

src/com/google/javascript/jscomp/CrossModuleCodeMotion.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
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
21 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
22 import com.google.javascript.jscomp.Scope.Var;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.Token;
25
26 import java.util.ArrayDeque;
27 import java.util.Deque;
28 import java.util.Iterator;
29 import java.util.LinkedHashMap;
30 import java.util.HashMap;
31 import java.util.Map;
32 import java.util.logging.Logger;
33
34 /**
35 * A {@link Compiler} pass for moving code to a deeper module if possible.
36 * - currently it only moves functions + variables
37 *
38 */
39 class CrossModuleCodeMotion extends AbstractPostOrderCallback
40 implements CompilerPass {
41
42 private static final Logger logger =
43 Logger.getLogger(CrossModuleCodeMotion.class.getName());
44
45 private final AbstractCompiler compiler;
46 private final JSModuleGraph graph;
47
48 /**
49 * Map from module to the node in that module that should parent any string
50 * variable declarations that have to be moved into that module
51 */
52 private final Map<JSModule, Node> moduleVarParentMap =
53 new HashMap<JSModule, Node>();
54
55 /*
56 * NOTE - I made this a LinkedHashMap to make testing easier. With a regular
57 * HashMap, the variables may not output in a consistent order
58 */
59 private final Map<Scope.Var, NamedInfo> namedInfo =
60 new LinkedHashMap<Var, NamedInfo>();
61
62 /**
63 * Creates an instance.
64 *
65 * @param compiler The compiler
66 */
67 CrossModuleCodeMotion(AbstractCompiler compiler, JSModuleGraph graph) {
68 this.compiler = compiler;
69 this.graph = graph;
70 }
71
72 @Override
73 public void process(Node externs, Node root) {
74 logger.fine("Moving functions + variable into deeper modules");
75
76 // If there are <2 modules, then we will never move anything, so we're done
77 if (graph != null && graph.getModuleCount() > 1) {
78
79 // Traverse the tree and find the modules where a var is declared + used
80 NodeTraversal.traverse(compiler, root, this);
81
82 // Move the functions + variables to a deeper module [if possible]
83 moveCode();
84 }
85 }
86
87 /** move the code accordingly */
88 private void moveCode() {
89 for (NamedInfo info : namedInfo.values()) {
90 JSModule deepestDependency = info.deepestModule;
91
92 // Only move if all are true:
93 // a) allowMove is true
94 // b) it was used + declared somewhere [if not, then it will be removed
95 // as dead or invalid code elsewhere]
96 // c) the new dependency depends on the declModule
97 if (info.allowMove && deepestDependency != null) {
98 Iterator<Declaration> it = info.declarationIterator();
99 JSModuleGraph moduleGraph = compiler.getModuleGraph();
100 while (it.hasNext()) {
101 Declaration decl = it.next();
102 if (decl.module != null &&
103 moduleGraph.dependsOn(deepestDependency,
104 decl.module)) {
105
106 // Find the appropriate spot to move it to
107 Node destParent = moduleVarParentMap.get(deepestDependency);
108 if (destParent == null) {
109 destParent = compiler.getNodeForCodeInsertion(deepestDependency);
110 moduleVarParentMap.put(deepestDependency, destParent);
111 }
112
113 // VAR Nodes are normalized to have only one child.
114 Node declParent = decl.node.getParent();
115 Preconditions.checkState(
116 !declParent.isVar() || declParent.hasOneChild(),
117 "AST not normalized.");
118
119 // Remove it
120 declParent.detachFromParent();
121
122 // Add it to the new spot
123 destParent.addChildToFront(declParent);
124
125 compiler.reportCodeChange();
126 }
127 }
128 }
129 }
130 }
131
132 /** useful information for each variable candidate */
133 private class NamedInfo {
134 boolean allowMove = true;
135
136 // The deepest module where the variable is used. Starts at null
137 private JSModule deepestModule = null;
138
139 // The module where declarations appear
140 private JSModule declModule = null;
141
142 // information on the spot where the item was declared
143 private final Deque<Declaration> declarations =
144 new ArrayDeque<Declaration>();
145
146 // Add a Module where it is used
147 void addUsedModule(JSModule m) {
148 // If we are not allowed to move it, all bets are off
149 if (!allowMove) {
150 return;
151 }
152
153 // If we have no deepest module yet, set this one
154 if (deepestModule == null) {
155 deepestModule = m;
156 } else {
157 // Find the deepest common dependency
158 deepestModule =
159 graph.getDeepestCommonDependencyInclusive(m, deepestModule);
160 }
161 }
162
163 /**
164 * Add a declaration for this name.
165 * @return Whether this is a valid declaration. If this returns false,
166 * this should be added as a reference.
167 */
168 boolean addDeclaration(Declaration d) {
169 // all declarations must appear in the same module.
170 if (declModule != null && d.module != declModule) {
171 return false;
172 }
173 declarations.push(d);
174 declModule = d.module;
175 return true;
176 }
177
178 /**
179 * Returns an iterator over the declarations, in the order that they were
180 * declared.
181 */
182 Iterator<Declaration> declarationIterator() {
183 return declarations.iterator();
184 }
185 }
186
187 private class Declaration {
188 final JSModule module;
189 final Node node;
190
191 Declaration(JSModule module, Node node) {
192 this.module = module;
193 this.node = node;
194 }
195 }
196
197 /**
198 * return true if the node has any form of conditional in its ancestry
199 * TODO(nicksantos) keep track of the conditionals in the ancestry, so
200 * that we don't have to recrawl it.
201 */
202 private boolean hasConditionalAncestor(Node n) {
203 for (Node ancestor : n.getAncestors()) {
204 switch (ancestor.getType()) {
205 case Token.DO:
206 case Token.FOR:
207 case Token.HOOK:
208 case Token.IF:
209 case Token.SWITCH:
210 case Token.WHILE:
211 case Token.FUNCTION:
212 return true;
213 }
214 }
215 return false;
216 }
217
218 /**
219 * get the information on a variable
220 */
221 private NamedInfo getNamedInfo(Var v) {
222 NamedInfo info = namedInfo.get(v);
223 if (info == null) {
224 info = new NamedInfo();
225 namedInfo.put(v, info);
226 }
227 return info;
228 }
229
230 /**
231 * Process the references to named variables
232 */
233 private void processReference(NodeTraversal t, NamedInfo info, String name) {
234 // A name is recursively defined if:
235 // 1: It is calling itself.
236 // 2: One of its property calls itself.
237 // Recursive definition should not block movement.
238
239 boolean recursive = false;
240 Node rootNode = t.getScope().getRootNode();
241 if (rootNode.isFunction()) {
242
243 // CASE #1:
244 String scopeFuncName = rootNode.getFirstChild().getString();
245 Node scopeFuncParent = rootNode.getParent();
246 if (scopeFuncName.equals(name)) {
247 recursive = true;
248 } else if (scopeFuncParent.isName() &&
249 scopeFuncParent.getString().equals(name)) {
250 recursive = true;
251 } else {
252 // CASE #2:
253 // Suppose name is Foo, we keep look up the scope stack to look for
254 // a scope with "Foo.prototype.bar = function() { ..... "
255 for (Scope s = t.getScope();
256 s.getParent() != null; s = s.getParent()) {
257 Node curRoot = s.getRootNode();
258 if (curRoot.getParent().isAssign()) {
259 Node owner = curRoot.getParent().getFirstChild();
260 while (owner.isGetProp()) {
261 owner = owner.getFirstChild();
262 }
263 if (owner.isName() &&
264 owner.getString().equals(name)) {
265 recursive = true;
266 break;
267 }
268 }
269 }
270 }
271 }
272
273 if (!recursive) {
274 info.addUsedModule(t.getModule());
275 }
276 }
277
278 @Override
279 public void visit(NodeTraversal t, Node n, Node parent) {
280 if (!n.isName()) {
281 return;
282 }
283
284 // Skip empty and exported names
285 String name = n.getString();
286 if (name.isEmpty() || compiler.getCodingConvention().isExported(name)) {
287 return;
288 }
289
290 // If the JSCompiler can't find a Var for this string, then all
291 // bets are off. This sometimes occurs with closures. Alternately, we skip
292 // non-global variables
293 Var v = t.getScope().getVar(name);
294 if (v == null || !v.isGlobal()) {
295 return;
296 }
297
298 NamedInfo info = getNamedInfo(v);
299 if (info.allowMove) {
300 if (maybeProcessDeclaration(t, n, parent, info)) {
301 // Check to see if the declaration is conditional starting at the
302 // grandparent of the name node. Since a function declaration
303 // is considered conditional (the function might not be called)
304 // we would need to skip the parent in this check as the name could
305 // just be a function itself.
306 if (hasConditionalAncestor(parent.getParent())) {
307 info.allowMove = false;
308 }
309 } else {
310 // Otherwise, it's a reference
311 processReference(t, info, name);
312 }
313 }
314 }
315
316 /**
317 * Determines whether the given NAME node belongs to a declaration that
318 * can be moved across modules. If it is, registers it properly.
319 *
320 * There are four types of movable declarations:
321 * 1) var NAME = [movable object];
322 * 2) function NAME() {}
323 * 3) NAME = [movable object];
324 * NAME.prop = [movable object];
325 * NAME.prop.prop2 = [movable object];
326 * etc.
327 * 4) Class-defining function calls, like "inherits" and "mixin".
328 * NAME.inherits([some other name]);
329 * where "movable object" is a literal or a function.
330 */
331 private boolean maybeProcessDeclaration(NodeTraversal t, Node name,
332 Node parent, NamedInfo info) {
333 Node gramps = parent.getParent();
334 switch (parent.getType()) {
335 case Token.VAR:
336 if (canMoveValue(name.getFirstChild())) {
337 return info.addDeclaration(
338 new Declaration(t.getModule(), name));
339 }
340 return false;
341
342 case Token.FUNCTION:
343 if (NodeUtil.isFunctionDeclaration(parent)) {
344 return info.addDeclaration(
345 new Declaration(t.getModule(), name));
346 }
347 return false;
348
349 case Token.ASSIGN:
350 case Token.GETPROP:
351 Node child = name;
352
353 // Look for assignment expressions where the name is the root
354 // of a qualified name on the left hand side of the assignment.
355 for (Node current : name.getAncestors()) {
356 if (current.isGetProp()) {
357 // fallthrough
358 } else if (current.isAssign() &&
359 current.getFirstChild() == child) {
360 Node currentParent = current.getParent();
361 if (currentParent.isExprResult() &&
362 canMoveValue(current.getLastChild())) {
363 return info.addDeclaration(
364 new Declaration(t.getModule(), current));
365 }
366 } else {
367 return false;
368 }
369
370 child = current;
371 }
372 return false;
373
374 case Token.CALL:
375 if (NodeUtil.isExprCall(gramps)) {
376 SubclassRelationship relationship =
377 compiler.getCodingConvention().getClassesDefinedByCall(parent);
378 if (relationship != null &&
379 name.getString().equals(relationship.subclassName)) {
380 return info.addDeclaration(
381 new Declaration(t.getModule(), parent));
382 }
383 }
384 return false;
385
386 default:
387 return false;
388 }
389 }
390
391 /**
392 * Determines whether the given value is eligible to be moved across modules.
393 */
394 private boolean canMoveValue(Node n) {
395 // the value is only movable if it's
396 // a) nothing,
397 // b) a constant literal,
398 // c) a function, or
399 // d) an array/object literal of movable values.
400 // e) a function stub generated by CrossModuleMethodMotion.
401 if (n == null || NodeUtil.isLiteralValue(n, true) ||
402 n.isFunction()) {
403 return true;
404 } else if (n.isCall()) {
405 Node functionName = n.getFirstChild();
406 return functionName.isName() &&
407 (functionName.getString().equals(
408 CrossModuleMethodMotion.STUB_METHOD_NAME) ||
409 functionName.getString().equals(
410 CrossModuleMethodMotion.UNSTUB_METHOD_NAME));
411 } else if (n.isArrayLit() || n.isObjectLit()) {
412 boolean isObjectLit = n.isObjectLit();
413 for (Node child = n.getFirstChild(); child != null;
414 child = child.getNext()) {
415 if (!canMoveValue(isObjectLit ? child.getFirstChild() : child)) {
416 return false;
417 }
418 }
419
420 return true;
421 }
422
423 return false;
424 }
425 }