Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2011 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 package com.google.javascript.jscomp;
17
18 import java.util.Iterator;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.collect.Iterators;
21 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.Node;
24
25 /**
26 * Rewrites an AMD module https://github.com/amdjs/amdjs-api/wiki/AMD to a
27 * CommonJS module. See {@link ProcessCommonJSModules} for follow up processing
28 * step.
29 */
30 class TransformAMDToCJSModule implements CompilerPass {
31
32 @VisibleForTesting
33 final static DiagnosticType UNSUPPORTED_DEFINE_SIGNATURE_ERROR =
34 DiagnosticType.error(
35 "UNSUPPORTED_DEFINE_SIGNATURE",
36 "Only define(function() ...), define(OBJECT_LITERAL) and define("
37 + "['dep', 'dep1'], function(d0, d2, [exports, module]) ...) forms "
38 + "are currently supported.");
39 final static DiagnosticType NON_TOP_LEVEL_STATEMENT_DEFINE_ERROR =
40 DiagnosticType.error(
41 "NON_TOP_LEVEL_STATEMENT_DEFINE",
42 "The define function must be called as a top-level statement.");
43 final static DiagnosticType REQUIREJS_PLUGINS_NOT_SUPPORTED_WARNING =
44 DiagnosticType.warning(
45 "REQUIREJS_PLUGINS_NOT_SUPPORTED",
46 "Plugins in define requirements are not supported: {0}");
47
48 final static String VAR_RENAME_SUFFIX = "__alias";
49
50
51 private final AbstractCompiler compiler;
52 private int renameIndex = 0;
53
54 TransformAMDToCJSModule(AbstractCompiler compiler) {
55 this.compiler = compiler;
56 }
57
58 @Override
59 public void process(Node externs, Node root) {
60 NodeTraversal.traverse(compiler, root, new TransformAMDModulesCallback());
61 }
62
63 private void unsupportedDefineError(NodeTraversal t, Node n) {
64 t.report(n, UNSUPPORTED_DEFINE_SIGNATURE_ERROR);
65 }
66
67 /**
68 * The modules "exports", "require" and "module" are virtual in terms of
69 * existing implicitly in CommonJS.
70 */
71 private boolean isVirtualModuleName(String moduleName) {
72 return "exports".equals(moduleName) || "require".equals(moduleName) ||
73 "module".equals(moduleName);
74 }
75
76 /**
77 * Rewrites calls to define which has to be in void context just below the
78 * current script node.
79 */
80 private class TransformAMDModulesCallback extends AbstractPostOrderCallback {
81
82 @Override
83 public void visit(NodeTraversal t, Node n, Node parent) {
84 if (n.isCall() && n.getFirstChild() != null &&
85 n.getFirstChild().isName() &&
86 "define".equals(n.getFirstChild().getString())) {
87 Scope.Var define = t.getScope().getVar(n.getFirstChild().
88 getString());
89 if (define != null && !define.isGlobal()) {
90 // Ignore non-global define.
91 return;
92 }
93 if (!(parent.isExprResult() && parent.getParent().isScript())) {
94 t.report(n, NON_TOP_LEVEL_STATEMENT_DEFINE_ERROR);
95 return;
96 }
97 Node script = parent.getParent();
98 Node requiresNode = null;
99 Node callback = null;
100 int defineArity = n.getChildCount() - 1;
101 if (defineArity == 0) {
102 unsupportedDefineError(t, n);
103 return;
104 } else if (defineArity == 1) {
105 callback = n.getChildAtIndex(1);
106 if (callback.isObjectLit()) {
107 handleDefineObjectLiteral(parent, callback, script);
108 return;
109 }
110 } else if (defineArity == 2) {
111 requiresNode = n.getChildAtIndex(1);
112 callback = n.getChildAtIndex(2);
113 } else if (defineArity >= 3) {
114 unsupportedDefineError(t, n);
115 return;
116 }
117
118 if (!callback.isFunction() ||
119 (requiresNode != null && !requiresNode.isArrayLit())) {
120 unsupportedDefineError(t, n);
121 return;
122 }
123
124 handleRequiresAndParamList(t, n, script, requiresNode, callback);
125
126 Node callbackBlock = callback.getChildAtIndex(2);
127 NodeTraversal.traverse(compiler, callbackBlock,
128 new DefineCallbackReturnCallback());
129
130 moveCallbackContentToTopLevel(parent, script, callbackBlock);
131 compiler.reportCodeChange();
132 }
133 }
134
135 /**
136 * When define is called with an object literal, assign it to exports and
137 * we're done.
138 */
139 private void handleDefineObjectLiteral(Node parent, Node onlyExport,
140 Node script) {
141 onlyExport.getParent().removeChild(onlyExport);
142 script.replaceChild(parent,
143 IR.exprResult(IR.assign(IR.name("exports"), onlyExport))
144 .copyInformationFromForTree(onlyExport));
145 compiler.reportCodeChange();
146 }
147
148 /**
149 * Rewrites the required modules to
150 * <code>var nameInParamList = require("nameFromRequireList");</code>
151 */
152 private void handleRequiresAndParamList(NodeTraversal t, Node defineNode,
153 Node script, Node requiresNode, Node callback) {
154 Iterator<Node> paramList = callback.getChildAtIndex(1).children().
155 iterator();
156 Iterator<Node> requires = requiresNode != null ?
157 requiresNode.children().iterator() : Iterators.<Node>emptyIterator();
158 while (paramList.hasNext() || requires.hasNext()) {
159 Node aliasNode = paramList.hasNext() ? paramList.next() : null;
160 Node modNode = requires.hasNext() ? requires.next() : null;
161 handleRequire(t, defineNode, script, callback, aliasNode, modNode);
162 }
163 }
164
165 /**
166 * Rewrite a single require call.
167 */
168 private void handleRequire(NodeTraversal t, Node defineNode, Node script,
169 Node callback, Node aliasNode, Node modNode) {
170 String moduleName = null;
171 if (modNode != null) {
172 moduleName = handlePlugins(t, script, modNode.getString(), modNode);
173 }
174
175 if (isVirtualModuleName(moduleName)) {
176 return;
177 }
178
179 String aliasName = aliasNode != null ? aliasNode.getString() : null;
180 Scope globalScope = t.getScope();
181 if (aliasName != null &&
182 globalScope.isDeclared(aliasName, true)) {
183 while (true) {
184 String renamed = aliasName + VAR_RENAME_SUFFIX + renameIndex;
185 if (!globalScope.isDeclared(renamed, true)) {
186 NodeTraversal.traverse(compiler, callback,
187 new RenameCallback(aliasName, renamed));
188 aliasName = renamed;
189 break;
190 }
191 renameIndex++;
192 }
193 }
194
195 Node requireNode;
196 if (moduleName != null) {
197 Node call = IR.call(IR.name("require"), IR.string(moduleName));
198 call.putBooleanProp(Node.FREE_CALL, true);
199 if (aliasName != null) {
200 requireNode = IR.var(IR.name(aliasName), call)
201 .copyInformationFromForTree(aliasNode);
202 } else {
203 requireNode = IR.exprResult(call).
204 copyInformationFromForTree(modNode);
205 }
206 } else {
207 // ignore exports, require and module (because they are implicit
208 // in CommonJS);
209 if (isVirtualModuleName(aliasName)) {
210 return;
211 }
212 requireNode = IR.var(IR.name(aliasName), IR.nullNode())
213 .copyInformationFromForTree(aliasNode);
214 }
215
216 script.addChildBefore(requireNode,
217 defineNode.getParent());
218 }
219
220 /**
221 * Require.js supports a range of plugins that are hard to support
222 * statically. Generally none are supported right now with the
223 * exception of a simple hack to support condition loading. This
224 * was added to make compilation of Dojo work better but will
225 * probably break, so just don't use them :)
226 */
227 private String handlePlugins(NodeTraversal t, Node script,
228 String moduleName, Node modNode) {
229 if (moduleName.contains("!")) {
230 t.report(modNode, REQUIREJS_PLUGINS_NOT_SUPPORTED_WARNING, moduleName);
231 int condition = moduleName.indexOf('?');
232 if (condition > 0) {
233 if (moduleName.contains(":")) {
234 return null;
235 }
236 return handlePlugins(t, script, moduleName.substring(condition + 1),
237 modNode);
238 }
239 moduleName = null;
240 }
241 return moduleName;
242 }
243
244 /**
245 * Moves the statements in the callback to be direct children of the
246 * current script.
247 */
248 private void moveCallbackContentToTopLevel(Node defineParent, Node script,
249 Node callbackBlock) {
250 int curIndex = script.getIndexOfChild(defineParent);
251 script.removeChild(defineParent);
252 callbackBlock.getParent().removeChild(callbackBlock);
253 Node before = script.getChildAtIndex(curIndex);
254 if (before != null) {
255 script.addChildBefore(callbackBlock, before);
256 }
257 script.addChildToBack(callbackBlock);
258 NodeUtil.tryMergeBlock(callbackBlock);
259 }
260 }
261
262 /**
263 * Rewrites the return statement of the callback to be an assignment to
264 * module.exports.
265 */
266 private class DefineCallbackReturnCallback extends
267 NodeTraversal.AbstractShallowStatementCallback {
268 @Override
269 public void visit(NodeTraversal t, Node n, Node parent) {
270 if (n.isReturn() && n.hasChildren()) {
271 Node retVal = n.getFirstChild();
272 n.removeChild(retVal);
273 parent.replaceChild(n, IR.exprResult(
274 IR.assign(
275 IR.getprop(IR.name("module"), IR.string("exports")), retVal))
276 .useSourceInfoFromForTree(n));
277 }
278 }
279 }
280
281 /**
282 * Renames names;
283 */
284 private class RenameCallback extends AbstractPostOrderCallback {
285
286 private final String from;
287 private final String to;
288
289 public RenameCallback(String from, String to) {
290 this.from = from;
291 this.to = to;
292 }
293
294 @Override
295 public void visit(NodeTraversal t, Node n, Node parent) {
296 if (n.isName() && from.equals(n.getString())) {
297 n.setString(to);
298 n.putProp(Node.ORIGINALNAME_PROP, from);
299 }
300 }
301 }
302 }