Debian Codegraph @

src/com/google/javascript/jscomp/ProcessCommonJSModules.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 com.google.common.base.Preconditions;
19 import com.google.common.collect.Sets;
20 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.util.Set;
27 import java.util.regex.Pattern;
28
29 /**
30 * Rewrites a CommonJS module http://wiki.commonjs.org/wiki/Modules/1.1.1
31 * into a form that can be safely concatenated.
32 * Does not add a function around the module body but instead adds suffixes
33 * to global variables to avoid conflicts.
34 * Calls to require are changed to reference the required module directly.
35 * goog.provide and goog.require are emitted for closure compiler automatic
36 * ordering.
37 */
38 public class ProcessCommonJSModules implements CompilerPass {
39 // According to the spec, the forward slash should be the delimite on
40 // all platforms.
41 private static final String MODULE_SLASH = "/";
42
43 public static final String DEFAULT_FILENAME_PREFIX = "." + MODULE_SLASH;
44
45 private static final String MODULE_NAME_SEPARATOR = "\\$";
46 private static final String MODULE_NAME_PREFIX = "module$";
47
48 private final AbstractCompiler compiler;
49 private final String filenamePrefix;
50 private final boolean reportDependencies;
51 private JSModule module;
52
53 ProcessCommonJSModules(AbstractCompiler compiler, String filenamePrefix) {
54 this(compiler, filenamePrefix, true);
55 }
56
57 ProcessCommonJSModules(AbstractCompiler compiler, String filenamePrefix,
58 boolean reportDependencies) {
59 this.compiler = compiler;
60 this.filenamePrefix = filenamePrefix.endsWith(MODULE_SLASH) ?
61 filenamePrefix : filenamePrefix + MODULE_SLASH;
62 this.reportDependencies = reportDependencies;
63 }
64
65 @Override
66 public void process(Node externs, Node root) {
67 NodeTraversal
68 .traverse(compiler, root, new ProcessCommonJsModulesCallback());
69 }
70
71 String guessCJSModuleName(String filename) {
72 return toModuleName(normalizeSourceName(filename));
73 }
74
75 /**
76 * For every file that is being processed this returns the module that
77 * created for it.
78 */
79 JSModule getModule() {
80 return module;
81 }
82
83 /**
84 * Turns a filename into a JS identifier that is used for moduleNames in
85 * rewritten code. Removes leading ./, replaces / with $, removes trailing .js
86 * and replaces - with _. All moduleNames get a "module$" prefix.
87 */
88 public static String toModuleName(String filename) {
89 return MODULE_NAME_PREFIX +
90 filename.replaceAll("^\\." + Pattern.quote(MODULE_SLASH), "")
91 .replaceAll(Pattern.quote(MODULE_SLASH), MODULE_NAME_SEPARATOR)
92 .replaceAll("\\.js$", "").replaceAll("-", "_");
93 }
94
95 /**
96 * Turn a filename into a moduleName with support for relative addressing
97 * with ./ and ../ based on currentFilename;
98 */
99 public static String toModuleName(String requiredFilename,
100 String currentFilename) {
101 requiredFilename = requiredFilename.replaceAll("\\.js$", "");
102 currentFilename = currentFilename.replaceAll("\\.js$", "");
103
104 if (requiredFilename.startsWith("." + MODULE_SLASH) ||
105 requiredFilename.startsWith(".." + MODULE_SLASH)) {
106 try {
107 requiredFilename = (new URI(currentFilename)).resolve(new URI(requiredFilename))
108 .toString();
109 } catch (URISyntaxException e) {
110 throw new RuntimeException(e);
111 }
112 }
113 return toModuleName(requiredFilename);
114 }
115
116 private String normalizeSourceName(String filename) {
117 // The DOS command shell will normalize "/" to "\", so we have to
118 // wrestle it back.
119 filename = filename.replace("\\", "/");
120
121 if (filename.indexOf(filenamePrefix) == 0) {
122 filename = filename.substring(filenamePrefix.length());
123 }
124
125 return filename;
126 }
127
128 /**
129 * Visits require, every "script" and special module.exports assignments.
130 */
131 private class ProcessCommonJsModulesCallback extends
132 AbstractPostOrderCallback {
133
134 private int scriptNodeCount = 0;
135 private Set<String> modulesWithExports = Sets.newHashSet();
136
137 @Override
138 public void visit(NodeTraversal t, Node n, Node parent) {
139 if (n.isCall() && n.getChildCount() == 2 &&
140 "require".equals(n.getFirstChild().getQualifiedName()) &&
141 n.getChildAtIndex(1).isString()) {
142 visitRequireCall(t, n, parent);
143 }
144
145 if (n.isScript()) {
146 scriptNodeCount++;
147 visitScript(t, n);
148 }
149
150 if (n.isGetProp() &&
151 "module.exports".equals(n.getQualifiedName())) {
152 visitModuleExports(n);
153 }
154 }
155
156 /**
157 * Visit require calls. Emit corresponding goog.require and rewrite require
158 * to be a direct reference to name of require module.
159 */
160 private void visitRequireCall(NodeTraversal t, Node require, Node parent) {
161 String moduleName = toModuleName(require.getChildAtIndex(1).getString(),
162 normalizeSourceName(t.getSourceName()));
163 Node moduleRef = IR.name(moduleName).srcref(require);
164 parent.replaceChild(require, moduleRef);
165 Node script = getCurrentScriptNode(parent);
166 if (reportDependencies) {
167 t.getInput().addRequire(moduleName);
168 }
169 // Rewrite require("name").
170 script.addChildToFront(IR.exprResult(
171 IR.call(IR.getprop(IR.name("goog"), IR.string("require")),
172 IR.string(moduleName))).copyInformationFromForTree(require));
173 compiler.reportCodeChange();
174 }
175
176 /**
177 * Emit goog.provide and add suffix to all global vars to avoid conflicts
178 * with other modules.
179 */
180 private void visitScript(NodeTraversal t, Node script) {
181 Preconditions.checkArgument(scriptNodeCount == 1,
182 "ProcessCommonJSModules supports only one invocation per " +
183 "CompilerInput / script node");
184 String moduleName = guessCJSModuleName(script.getSourceFileName());
185 script.addChildToFront(IR.var(IR.name(moduleName), IR.objectlit())
186 .copyInformationFromForTree(script));
187 if (reportDependencies) {
188 CompilerInput ci = t.getInput();
189 ci.addProvide(moduleName);
190 JSModule m = new JSModule(moduleName);
191 m.addAndOverrideModule(ci);
192 module = m;
193 }
194 script.addChildToFront(IR.exprResult(
195 IR.call(IR.getprop(IR.name("goog"), IR.string("provide")),
196 IR.string(moduleName))).copyInformationFromForTree(script));
197
198 emitOptionalModuleExportsOverride(script, moduleName);
199
200 // Rename vars to not conflict in global scope.
201 NodeTraversal.traverse(compiler, script, new SuffixVarsCallback(
202 moduleName));
203
204 compiler.reportCodeChange();
205 }
206
207 /**
208 * Emit <code>if (moduleName.module$exports) {
209 * moduleName = moduleName.module$export;
210 * }</code> at end of file.
211 */
212 private void emitOptionalModuleExportsOverride(Node script,
213 String moduleName) {
214 if (!modulesWithExports.contains(moduleName)) {
215 return;
216 }
217
218 Node moduleExportsProp = IR.getprop(IR.name(moduleName),
219 IR.string("module$exports"));
220 script.addChildToBack(IR.ifNode(
221 moduleExportsProp,
222 IR.block(IR.exprResult(IR.assign(IR.name(moduleName),
223 moduleExportsProp.cloneTree())))).copyInformationFromForTree(
224 script));
225 }
226
227 /**
228 * Rewrite module.exports to moduleName.module$exports.
229 */
230 private void visitModuleExports(Node prop) {
231 String moduleName = guessCJSModuleName(prop.getSourceFileName());
232 Node module = prop.getChildAtIndex(0);
233 module.putProp(Node.ORIGINALNAME_PROP, "module");
234 module.setString(moduleName);
235 Node exports = prop.getChildAtIndex(1);
236 exports.putProp(Node.ORIGINALNAME_PROP, "exports");
237 exports.setString("module$exports");
238 modulesWithExports.add(moduleName);
239 }
240
241 /**
242 * Returns next script node in parents.
243 */
244 private Node getCurrentScriptNode(Node n) {
245 while (true) {
246 if (n.isScript()) {
247 return n;
248 }
249 n = n.getParent();
250 }
251 }
252 }
253
254 /**
255 * Traverses a node tree and appends a suffix to all global variable names.
256 */
257 private class SuffixVarsCallback extends AbstractPostOrderCallback {
258
259 private static final String EXPORTS = "exports";
260
261 private final String suffix;
262
263 SuffixVarsCallback(String suffix) {
264 this.suffix = suffix;
265 }
266
267 @Override
268 public void visit(NodeTraversal t, Node n, Node parent) {
269 if (n.isName()) {
270 String name = n.getString();
271 if (suffix.equals(name)) {
272 return;
273 }
274 if (EXPORTS.equals(name)) {
275 n.setString(suffix);
276 n.putProp(Node.ORIGINALNAME_PROP, EXPORTS);
277 } else {
278 Scope.Var var = t.getScope().getVar(name);
279 if (var != null && var.isGlobal()) {
280 n.setString(name + "$$" + suffix);
281 n.putProp(Node.ORIGINALNAME_PROP, name);
282 }
283 }
284 }
285 }
286 }
287 }