Debian Codegraph @

src/com/google/javascript/jscomp/CrossModuleMethodMotion.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.javascript.jscomp.AnalyzePrototypeProperties.NameInfo;
20 import com.google.javascript.jscomp.AnalyzePrototypeProperties.Property;
21 import com.google.javascript.jscomp.AnalyzePrototypeProperties.Symbol;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.Node;
24 import java.io.Serializable;
25 import java.util.Collection;
26 import java.util.Iterator;
27
28 /**
29 * Move prototype methods into later modules.
30 *
31 * @author [email protected] (Nick Santos)
32 */
33 class CrossModuleMethodMotion implements CompilerPass {
34
35 // Internal errors
36 static final DiagnosticType NULL_COMMON_MODULE_ERROR = DiagnosticType.error(
37 "JSC_INTERNAL_ERROR_MODULE_DEPEND",
38 "null deepest common module");
39
40 private final AbstractCompiler compiler;
41 private final IdGenerator idGenerator;
42 private final AnalyzePrototypeProperties analyzer;
43 private final JSModuleGraph moduleGraph;
44
45 static final String STUB_METHOD_NAME = "JSCompiler_stubMethod";
46 static final String UNSTUB_METHOD_NAME = "JSCompiler_unstubMethod";
47
48 // Visible for testing
49 static final String STUB_DECLARATIONS =
50 "var JSCompiler_stubMap = [];" +
51 "function JSCompiler_stubMethod(JSCompiler_stubMethod_id) {" +
52 " return function() {" +
53 " return JSCompiler_stubMap[JSCompiler_stubMethod_id].apply(" +
54 " this, arguments);" +
55 " };" +
56 "}" +
57 "function JSCompiler_unstubMethod(" +
58 " JSCompiler_unstubMethod_id, JSCompiler_unstubMethod_body) {" +
59 " return JSCompiler_stubMap[JSCompiler_unstubMethod_id] = " +
60 " JSCompiler_unstubMethod_body;" +
61 "}";
62
63 /**
64 * Creates a new pass for moving prototype properties.
65 * @param compiler The compiler.
66 * @param idGenerator An id generator for method stubs.
67 * @param canModifyExterns If true, then we can move prototype
68 * properties that are declared in the externs file.
69 */
70 CrossModuleMethodMotion(AbstractCompiler compiler, IdGenerator idGenerator,
71 boolean canModifyExterns) {
72 this.compiler = compiler;
73 this.idGenerator = idGenerator;
74 this.moduleGraph = compiler.getModuleGraph();
75 this.analyzer = new AnalyzePrototypeProperties(compiler, moduleGraph,
76 canModifyExterns, false);
77 }
78
79 @Override
80 public void process(Node externRoot, Node root) {
81 // If there are < 2 modules, then we will never move anything,
82 // so we're done.
83 if (moduleGraph != null && moduleGraph.getModuleCount() > 1) {
84 analyzer.process(externRoot, root);
85 moveMethods(analyzer.getAllNameInfo());
86 }
87 }
88
89 /**
90 * Move methods deeper in the module graph when possible.
91 */
92 private void moveMethods(Collection<NameInfo> allNameInfo) {
93 boolean hasStubDeclaration = idGenerator.hasGeneratedAnyIds();
94 for (NameInfo nameInfo : allNameInfo) {
95 if (!nameInfo.isReferenced()) {
96 // The code below can't do anything with unreferenced name
97 // infos. They should be skipped to avoid NPE since their
98 // deepestCommonModuleRef is null.
99 continue;
100 }
101
102 if (nameInfo.readsClosureVariables()) {
103 continue;
104 }
105
106 JSModule deepestCommonModuleRef = nameInfo.getDeepestCommonModuleRef();
107 if (deepestCommonModuleRef == null) {
108 compiler.report(JSError.make(NULL_COMMON_MODULE_ERROR));
109 continue;
110 }
111
112 Iterator<Symbol> declarations =
113 nameInfo.getDeclarations().descendingIterator();
114 while (declarations.hasNext()) {
115 Symbol symbol = declarations.next();
116 if (!(symbol instanceof Property)) {
117 continue;
118 }
119 Property prop = (Property) symbol;
120
121 // We should only move a property across modules if:
122 // 1) We can move it deeper in the module graph, and
123 // 2) it's a function, and
124 // 3) it is not a GETTER_DEF or a SETTER_DEF, and
125 // 4) the class is available in the global scope.
126 //
127 // #1 should be obvious. #2 is more subtle. It's possible
128 // to copy off of a prototype, as in the code:
129 // for (var k in Foo.prototype) {
130 // doSomethingWith(Foo.prototype[k]);
131 // }
132 // This is a common way to implement pseudo-multiple inheritance in JS.
133 //
134 // So if we move a prototype method into a deeper module, we must
135 // replace it with a stub function so that it preserves its original
136 // behavior.
137 if (prop.getRootVar() == null || !prop.getRootVar().isGlobal()) {
138 continue;
139 }
140
141 Node value = prop.getValue();
142 if (moduleGraph.dependsOn(deepestCommonModuleRef, prop.getModule()) &&
143 value.isFunction()) {
144 Node valueParent = value.getParent();
145 if (valueParent.isGetterDef()
146 || valueParent.isSetterDef()) {
147 // TODO(johnlenz): a GET or SET can't be deferred like a normal
148 // FUNCTION property definition as a mix-in would get the result
149 // of a GET instead of the function itself.
150 continue;
151 }
152 Node proto = prop.getPrototype();
153 int stubId = idGenerator.newId();
154
155 // example: JSCompiler_stubMethod(id);
156 Node stubCall = IR.call(
157 IR.name(STUB_METHOD_NAME),
158 IR.number(stubId))
159 .copyInformationFromForTree(value);
160 stubCall.putBooleanProp(Node.FREE_CALL, true);
161
162 // stub out the method in the original module
163 // A.prototype.b = JSCompiler_stubMethod(id);
164 valueParent.replaceChild(value, stubCall);
165
166 // unstub the function body in the deeper module
167 Node unstubParent = compiler.getNodeForCodeInsertion(
168 deepestCommonModuleRef);
169 Node unstubCall = IR.call(
170 IR.name(UNSTUB_METHOD_NAME),
171 IR.number(stubId),
172 value);
173 unstubCall.putBooleanProp(Node.FREE_CALL, true);
174 unstubParent.addChildToFront(
175 // A.prototype.b = JSCompiler_unstubMethod(id, body);
176 IR.exprResult(
177 IR.assign(
178 IR.getprop(
179 proto.cloneTree(),
180 IR.string(nameInfo.name)),
181 unstubCall))
182 .copyInformationFromForTree(value));
183
184 compiler.reportCodeChange();
185 }
186 }
187 }
188
189 if (!hasStubDeclaration && idGenerator.hasGeneratedAnyIds()) {
190 // Declare stub functions in the top-most module.
191 Node declarations = compiler.parseSyntheticCode(STUB_DECLARATIONS);
192 compiler.getNodeForCodeInsertion(null).addChildrenToFront(
193 declarations.removeChildren());
194 }
195 }
196
197 static class IdGenerator implements Serializable {
198 private static final long serialVersionUID = 0L;
199
200 /**
201 * Ids for cross-module method stubbing, so that each method has
202 * a unique id.
203 */
204 private int currentId = 0;
205
206 /**
207 * Returns whether we've generated any new ids.
208 */
209 boolean hasGeneratedAnyIds() {
210 return currentId != 0;
211 }
212
213 /**
214 * Creates a new id for stubbing a method.
215 */
216 int newId() {
217 return currentId++;
218 }
219 }
220 }