Debian Codegraph @

src/com/google/javascript/jscomp/RescopeGlobalSymbols.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.collect.ImmutableSet;
19 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
20 import com.google.javascript.jscomp.NodeTraversal.AbstractShallowStatementCallback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Set;
26
27 /**
28 * Finds all references to global symbols and rewrites them to be property
29 * accesses to a special object with the same name as the global symbol.
30 *
31 * Given the name of the global object is NS
32 * <pre> var a = 1; function b() { return a }</pre>
33 * becomes
34 * <pre> NS.a = 1; NS.b = function b() { return NS.a }</pre>
35 *
36 * This allows splitting code into modules that depend on each other's
37 * global symbols, without using polluting JavaScript's global scope with those
38 * symbols.
39 *
40 * <p>This compile step requires moveFunctionDeclarations to be turned on
41 * to guarantee semantics.
42 *
43 * <p>For lots of examples, see the unit test.
44 *
45 *
46 */
47 class RescopeGlobalSymbols implements CompilerPass {
48
49 // Appended to variables names that conflict with globalSymbolNamespace.
50 private static final String DISAMBIGUATION_SUFFIX = "$";
51 private static final String WINDOW = "window";
52 private static final Set<String> SPECIAL_EXTERNS =
53 ImmutableSet.of(WINDOW, "eval", "arguments");
54
55 private final AbstractCompiler compiler;
56 private final String globalSymbolNamespace;
57 private final boolean addExtern;
58
59 RescopeGlobalSymbols(AbstractCompiler compiler, String globalSymbolNamespace,
60 boolean addExtern) {
61 this.compiler = compiler;
62 this.globalSymbolNamespace = globalSymbolNamespace;
63 this.addExtern = addExtern;
64 }
65
66 RescopeGlobalSymbols(AbstractCompiler compiler,
67 String globalSymbolNamespace) {
68 this(compiler, globalSymbolNamespace, true);
69 }
70
71 private void addExternForGlobalSymbolNamespace() {
72 Node varNode = IR.var(IR.name(globalSymbolNamespace));
73 CompilerInput input = compiler.newExternInput(
74 "{RescopeGlobalSymbolsNamespaceVar}");
75 input.getAstRoot(compiler).addChildrenToBack(varNode);
76 compiler.reportCodeChange();
77 }
78
79 @Override
80 public void process(Node externs, Node root) {
81 // Make the name of the globalSymbolNamespace an extern.
82 if (addExtern) {
83 addExternForGlobalSymbolNamespace();
84 }
85 // Rewrite all references to global symbols to properties of a
86 // single symbol by:
87 // (If necessary the 3 traversals could be combined. They are left
88 // separate for readability reasons.)
89 // 1. turning global named function statements into var assignments.
90 NodeTraversal.traverse(compiler, root,
91 new RewriteGlobalFunctionStatementsToVarAssignmentsCallback());
92 // 2. rewriting all references to be property accesses of the single symbol.
93 NodeTraversal.traverse(compiler, root, new RewriteScopeCallback());
94 // 3. removing the var from every statement in global scope.
95 NodeTraversal.traverse(compiler, root, new RemoveGlobalVarCallback());
96
97 // Extra pass which makes all extern global symbols reference window
98 // explicitly.
99 NodeTraversal.traverse(compiler, root,
100 new MakeExternsReferenceWindowExplicitly());
101 }
102
103 /**
104 * Rewrites function statements to var statements + assignment.
105 *
106 * <pre>function test(){}</pre>
107 * becomes
108 * <pre>var test = function (){}</pre>
109 *
110 * After this traversal, the special case of global function statements
111 * can be ignored.
112 */
113 private class RewriteGlobalFunctionStatementsToVarAssignmentsCallback
114 extends AbstractShallowStatementCallback {
115 @Override
116 public void visit(NodeTraversal t, Node n, Node parent) {
117 if (NodeUtil.isFunctionDeclaration(n)) {
118 String name = NodeUtil.getFunctionName(n);
119 n.getFirstChild().setString("");
120 Node prev = parent.getChildBefore(n);
121 n.detachFromParent();
122 Node var = NodeUtil.newVarNode(name, n);
123 if (prev == null) {
124 parent.addChildToFront(var);
125 } else {
126 parent.addChildAfter(var, prev);
127 }
128 compiler.reportCodeChange();
129 }
130 }
131 }
132
133 /**
134 * Visits each NAME token and checks whether it refers to a global variable.
135 * If yes, rewrites the name to be a property access on the
136 * "globalSymbolNamespace".
137 *
138 * <pre>var a = 1, b = 2, c = 3;</pre>
139 * becomes
140 * <pre>var NS.a = 1, NS.b = 2, NS.c = 4</pre>
141 * (The var token is removed in a later traversal.)
142 *
143 * <pre>a + b</pre>
144 * becomes
145 * <pre>NS.a + NS.b</pre>
146 *
147 * <pre>a()</pre>
148 * becomes
149 * <pre>(0,NS.a)()</pre>
150 * Notice the special syntax here to preserve the *this* semantics in the
151 * function call.
152 */
153 private class RewriteScopeCallback extends AbstractPostOrderCallback {
154 @Override
155 public void visit(NodeTraversal t, Node n, Node parent) {
156 if (!n.isName()) {
157 return;
158 }
159 String name = n.getString();
160 // Ignore anonymous functions
161 if (parent.isFunction() && name.length() == 0) {
162 return;
163 }
164 Scope.Var var = t.getScope().getVar(name);
165 if (var == null) {
166 return;
167 }
168 // Don't touch externs.
169 if (var.isExtern()) {
170 return;
171 }
172 // When the globalSymbolNamespace is used as a local variable name
173 // add suffix to avoid shadowing the namespace. Also add a suffix
174 // if a name starts with the name of the globalSymbolNamespace and
175 // the suffix.
176 if (!var.isExtern() && (name.equals(globalSymbolNamespace) ||
177 name.indexOf(globalSymbolNamespace + DISAMBIGUATION_SUFFIX) == 0)) {
178 n.setString(name + DISAMBIGUATION_SUFFIX);
179 compiler.reportCodeChange();
180 }
181 // We only care about global vars.
182 if (!var.isGlobal()) {
183 return;
184 }
185 Node nameNode = var.getNameNode();
186 // The exception variable (e in try{}catch(e){}) should not be rewritten.
187 if (nameNode != null && nameNode.getParent() != null &&
188 nameNode.getParent().isCatch()) {
189 return;
190 }
191 replaceSymbol(n, name);
192 }
193
194 private void replaceSymbol(Node node, String name) {
195 Node parent = node.getParent();
196 Node replacement = IR.getprop(
197 IR.name(globalSymbolNamespace).srcref(node),
198 IR.string(name).srcref(node));
199 replacement.srcref(node);
200 if (node.hasChildren()) {
201 // var declaration list: var a = 1, b = 2;
202 Node assign = IR.assign(replacement,
203 node.removeFirstChild());
204 parent.replaceChild(node, assign);
205 } else {
206 parent.replaceChild(node, replacement);
207 }
208 compiler.reportCodeChange();
209 }
210 }
211
212 /**
213 * Removes every occurrence of var that declares a global variable.
214 *
215 * <pre>var NS.a = 1, NS.b = 2;</pre>
216 * becomes
217 * <pre>NS.a = 1; NS.b = 2;</pre>
218 *
219 * <pre>for (var a = 0, b = 0;;)</pre>
220 * becomes
221 * <pre>for (NS.a = 0, NS.b = 0;;)</pre>
222 *
223 * Declarations without assignments are optimized away:
224 * <pre>var a = 1, b;</pre>
225 * becomes
226 * <pre>NS.a = 1</pre>
227 */
228 private class RemoveGlobalVarCallback extends
229 AbstractShallowStatementCallback {
230 @Override
231 public void visit(NodeTraversal t, Node n, Node parent) {
232 if (!n.isVar()) {
233 return;
234 }
235 List<Node> commas = new ArrayList<Node>();
236 List<Node> interestingChildren = new ArrayList<Node>();
237 // Filter out declarations without assignments.
238 // As opposed to regular var nodes, there are always assignments
239 // because the previous traversal in RewriteScopeCallback creates
240 // them.
241 for (Node c : n.children()) {
242 if (c.isAssign() ||
243 parent.isFor()) {
244 interestingChildren.add(c);
245 }
246 }
247 for (Node c : interestingChildren) {
248 if (parent.isFor() && parent.getFirstChild() == n) {
249 commas.add(c.cloneTree());
250 } else {
251 // Var statement outside of for-loop.
252 Node expr = IR.exprResult(c.cloneTree()).srcref(c);
253 parent.addChildBefore(expr, n);
254 }
255 }
256 if (commas.size() > 0) {
257 Node comma = joinOnComma(commas, n);
258 parent.addChildBefore(comma, n);
259 }
260 // Remove the var node.
261 parent.removeChild(n);
262 compiler.reportCodeChange();
263 }
264
265 private Node joinOnComma(List<Node> commas, Node source) {
266 Node comma = commas.get(0);
267 for (int i = 1; i < commas.size(); i++) {
268 Node nextComma = IR.comma(comma, commas.get(i));
269 nextComma.copyInformationFrom(source);
270 comma = nextComma;
271 }
272 return comma;
273 }
274 }
275
276 /**
277 * Rewrites extern names to be explicit children of window instead of only
278 * implicitly referencing it.
279 * This enables injecting window into a scope and make all global symbol
280 * depend on the injected object.
281 */
282 private class MakeExternsReferenceWindowExplicitly extends
283 AbstractPostOrderCallback {
284
285 @Override
286 public void visit(NodeTraversal t, Node n, Node parent) {
287 if (!n.isName()) {
288 return;
289 }
290 String name = n.getString();
291 Scope.Var var = t.getScope().getVar(name);
292 if (name.length() > 0 && (var == null || var.isExtern()) &&
293 !globalSymbolNamespace.equals(name) &&
294 !SPECIAL_EXTERNS.contains(name)) {
295 parent.replaceChild(n, IR.getprop(IR.name(WINDOW), IR.string(name))
296 .srcrefTree(n));
297 compiler.reportCodeChange();
298 }
299 }
300
301 }
302 }