Debian Codegraph @

src/com/google/javascript/jscomp/AliasKeywords.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.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30
31 /**
32 * <p>Replaces references to aliasable keyword literals (true, false,
33 * null) with variables and statements (throw) with functions declared in the
34 * global scope. When combined with RenameVars, this pass helps to reduce the
35 * number of bytes taken up by references to these keywords by replacing them
36 * with references to variables and functions with shorter names.</p>
37 *
38 */
39 class AliasKeywords implements CompilerPass {
40 /** Callback that finds the nodes that we will alias. */
41 private class FindAliasableNodes extends AbstractPostOrderCallback {
42 @Override
43 public void visit(NodeTraversal t, Node n, Node parent) {
44 final int type = n.getType();
45 if (isAliasableType(type)) {
46 visitAliasableNode(n, parent);
47 } else if (type == Token.NAME) {
48 visitNameNode(n);
49 }
50 }
51
52 /**
53 * Find the AliasSpecification associated with the node, and tell
54 * that AliasSpecification about the new node.
55 */
56 private void visitAliasableNode(Node n, Node parent) {
57 AliasSpecification aliasableNodes = aliasTypes.get(n.getType());
58 aliasableNodes.visit(n, parent);
59 }
60
61 /**
62 * Sanity check that our aliases are not already defined by
63 * someone else.
64 */
65 private void visitNameNode(Node n) {
66 if (isAliasDefinition(n)) {
67 throw new IllegalStateException(
68 "Existing alias definition for " + Token.name(n.getType()));
69 }
70 }
71 }
72
73 /**
74 * An AliasSpecification encapsulates all of the logic to find
75 * aliasable nodes and alias those nodes, for a given alias name. Subclasses
76 * fill in template methods, allowing for various kinds of aliasing.
77 */
78 private abstract static class AliasSpecification {
79
80 /** List of nodes to alias (e.g. all 'null' nodes). */
81 private final Map<Node, Node> nodes = Maps.newHashMap();
82
83 /**
84 * Have we declared the alias (e.g. did we inject var
85 * $$ALIAS_NULL=null; into the parse tree)?
86 */
87 private boolean isAliased = false;
88
89 private String aliasName;
90
91 private int tokenId;
92
93 /**
94 * @param aliasName name being used as alias
95 * @param tokenId type of node being replaced with alias
96 */
97 public AliasSpecification(String aliasName, int tokenId) {
98 this.aliasName = aliasName;
99 this.tokenId = tokenId;
100 }
101
102 public void visit(Node n, Node parent) {
103 nodes.put(n, parent);
104 }
105
106 /**
107 * Insert a node that declares our alias into the parse tree, as a
108 * child of the specified var node. Only do so if we haven't
109 * already and there are enough references to the aliased node to
110 * save bytes.
111 * @return Whether the alias has been inserted.
112 */
113 boolean maybeInsertAliasDeclarationIntoParseTree(Node codeRoot) {
114 if (nodes.size() >= minOccurrencesRequiredToAlias()) {
115 insertAliasDeclaration(codeRoot);
116 isAliased = true;
117 return true;
118 }
119 return false;
120 }
121
122 /**
123 * Update all of the nodes with a reference to the corresponding
124 * alias node.
125 */
126 public void doAlias(AbstractCompiler compiler) {
127 if (isAliased) {
128 for (Map.Entry<Node, Node> entry : nodes.entrySet()) {
129 Node n = entry.getKey();
130 Node parent = entry.getValue();
131 aliasNode(n, parent);
132 compiler.reportCodeChange();
133 }
134 }
135 }
136
137 public int getTokenId() {
138 return tokenId;
139 }
140
141 public String getAliasName() {
142 return aliasName;
143 }
144
145 /**
146 * Returns the minimum number of nodes that should be present for aliasing
147 * to take place.
148 */
149 protected abstract int minOccurrencesRequiredToAlias();
150
151 /**
152 * Creates a node that defines the alias and attaches it to the parse tree.
153 *
154 * @param codeRoot The root of the script. Functions can be attached here,
155 * e.g., <code>function alias(p){throw p;}</code>.
156 */
157 protected abstract void insertAliasDeclaration(Node codeRoot);
158
159 /** Replaces the node n with its alias. */
160 protected abstract void aliasNode(Node n, Node parent);
161 }
162
163 /** Aliases throw statements with a function call. */
164 // TODO(user): Generalize this to work with typeof expressions.
165 private class ThrowAliasSpecification extends AliasSpecification {
166 ThrowAliasSpecification(String aliasName) {
167 super(aliasName, Token.THROW);
168 }
169
170 @Override
171 protected void aliasNode(Node throwNode, Node parent) {
172 Node name = NodeUtil.newName(
173 compiler.getCodingConvention(),
174 getAliasName(), throwNode, getAliasName());
175 Node aliasCall = IR.call( name, throwNode.removeFirstChild());
176 aliasCall.putBooleanProp(Node.FREE_CALL, true);
177 Node exprResult = IR.exprResult(aliasCall);
178 parent.replaceChild(throwNode, exprResult);
179 }
180
181 @Override
182 /**
183 * Adds alias function to codeRoot. See {@link #createAliasFunctionNode}).
184 */
185 protected void insertAliasDeclaration(Node codeRoot) {
186 codeRoot.addChildToFront(createAliasFunctionNode(getAliasName()));
187 }
188
189 @Override
190 protected int minOccurrencesRequiredToAlias() {
191 return MIN_OCCURRENCES_REQUIRED_TO_ALIAS_THROW;
192 }
193 }
194
195 /**
196 * Calculates the minimum number of occurrences of throw needed to alias
197 * throw.
198 */
199 static int estimateMinOccurrencesRequriedToAlias() {
200 // Assuming that the alias function name is two bytes in length, two bytes
201 // will be saved per occurrence of throw:
202 // <code>throw e;</code>, compared to
203 // <code>TT(e);</code>.
204 // However, the alias definition is some length, N, e.g.,
205 // <code>function TT(t){throw t;}</code>
206 // Hence there must be more than N/2 occurrences of throw to reduce
207 // the code size.
208 Node alias = createAliasFunctionNode("TT");
209 return InlineCostEstimator.getCost(alias) / 2 + 1;
210 }
211
212 /**
213 * Creates a function node that takes a single argument, the object to
214 * throw. The function throws the object.
215 */
216 private static Node createAliasFunctionNode(String aliasName) {
217 final String PARAM_NAME = "jscomp_throw_param";
218 return IR.function(
219 IR.name(aliasName),
220 IR.paramList(IR.name(PARAM_NAME)),
221 IR.block(
222 IR.throwNode(IR.name(PARAM_NAME))));
223 }
224
225 /** Aliases literal keywords (e.g., null) with variable names. */
226 private class KeywordAliasSpecification extends AliasSpecification {
227 KeywordAliasSpecification(String aliasName, int tokenId) {
228 super(aliasName, tokenId);
229 }
230
231 @Override
232 protected int minOccurrencesRequiredToAlias() {
233 return MIN_OCCURRENCES_REQUIRED_TO_ALIAS_LITERAL;
234 }
235
236 @Override
237 protected void aliasNode(Node n, Node parent) {
238 Node aliasNode = NodeUtil.newName(
239 compiler.getCodingConvention(), getAliasName(), n, getAliasName());
240 parent.replaceChild(n, aliasNode);
241 }
242
243 @Override
244 /**
245 * Create the alias declaration (e.g. var $$ALIAS_NULL=null;).
246 */
247 protected void insertAliasDeclaration(Node codeRoot) {
248 Node varNode = new Node(Token.VAR);
249 Node value = new Node(getTokenId());
250 Node name = NodeUtil.newName(
251 compiler.getCodingConvention(), getAliasName(),
252 varNode, getAliasName());
253 name.addChildToBack(value);
254 varNode.addChildToBack(name);
255 codeRoot.addChildrenToFront(varNode);
256 }
257 }
258
259 /** Aliases literal keywords (e.g., null) with variable names. */
260 private class VoidKeywordAliasSpecification extends AliasSpecification {
261 VoidKeywordAliasSpecification(String aliasName, int tokenId) {
262 super(aliasName, tokenId);
263 }
264
265 @Override
266 public void visit(Node n, Node parent) {
267 Node value = n.getFirstChild();
268 if (value.isNumber() && value.getDouble() == 0) {
269 super.visit(n, parent);
270 }
271 }
272
273 @Override
274 protected int minOccurrencesRequiredToAlias() {
275 return MIN_OCCURRENCES_REQUIRED_TO_ALIAS_LITERAL;
276 }
277
278 @Override
279 protected void aliasNode(Node n, Node parent) {
280 Node aliasNode = NodeUtil.newName(
281 compiler.getCodingConvention(), getAliasName(), n, getAliasName());
282 parent.replaceChild(n, aliasNode);
283 }
284
285 @Override
286 /**
287 * Create the alias declaration (e.g. var $$ALIAS_VOID=void 0;).
288 */
289 protected void insertAliasDeclaration(Node codeRoot) {
290 Node varNode = new Node(Token.VAR);
291 Node value = IR.voidNode(IR.number(0));
292 Node name = NodeUtil.newName(
293 compiler.getCodingConvention(), getAliasName(),
294 varNode, getAliasName());
295 name.addChildToBack(value);
296 varNode.addChildToBack(name);
297 codeRoot.addChildrenToFront(varNode);
298 }
299 }
300
301
302 static final String ALIAS_NULL = "JSCompiler_alias_NULL";
303 static final String ALIAS_TRUE = "JSCompiler_alias_TRUE";
304 static final String ALIAS_FALSE = "JSCompiler_alias_FALSE";
305 static final String ALIAS_THROW = "JSCompiler_alias_THROW";
306 static final String ALIAS_VOID = "JSCompiler_alias_VOID";
307
308 /**
309 * Don't alias a keyword unless it's referenced at least
310 * MIN_OCCURRENCES_REQUIRED_TO_ALIAS_LITERAL times. Aliasing a keyword has a
311 * cost (e.g. 'var XX=true;' costs 12 bytes). We make up for this
312 * cost by replacing references to the keyword with variables that
313 * have shorter names. If there are only a few references to a
314 * keyword, the cost outweighs the benefit. It is not possible to
315 * determine the exact break-even point without compiling twice
316 * (once with aliasing, another without) and comparing the
317 * post-gzipped size, so we define a minimum number of references
318 * required in order to alias. We choose 6 because the alias cost is
319 * ~7-12 bytes (12 bytes for 'var XX=true;', 7 bytes for a
320 * subsequent declaration that does not require its own 'var ' or
321 * semicolon, e.g. var XX=true,XY=null;), but each reference saves
322 * 2-3 bytes (2 for true and null, 3 for false). Thus, the break
323 * even point is 3 at best, and 6 at worst. We could use a
324 * CostEstimator to be precise, but requiring a constant number of
325 * occurrences is much simpler, and the added precision of a
326 * CostEstimator would save us <10 bytes for some unlikely edge
327 * cases (e.g. where false is referenced exactly 5 times, but does
328 * not get aliased).
329 */
330 static final int MIN_OCCURRENCES_REQUIRED_TO_ALIAS_LITERAL = 6;
331
332 /**
333 * Don't alias throw statements unless throw is used at least
334 * MIN_OCCURRENCES_REQUIRED_TO_ALIAS_THROW times.
335 */
336 static final int MIN_OCCURRENCES_REQUIRED_TO_ALIAS_THROW =
337 estimateMinOccurrencesRequriedToAlias();
338
339 /** Reference to JS Compiler */
340 private final AbstractCompiler compiler;
341
342 /** List of alias specifications, stored in order which transformations
343 * should be applied. See {@link #createAliasSpecifications}.
344 */
345 private final List<AliasSpecification> aliasSpecifications;
346
347 /** Map from rhino nodes to the corresponding AliasSpecification */
348 private final Map<Integer, AliasSpecification> aliasTypes;
349
350 /** Set of alias names. */
351 private final Set<String> aliasNames;
352
353 AliasKeywords(AbstractCompiler compiler) {
354 this.compiler = compiler;
355 aliasSpecifications = createAliasSpecifications();
356 aliasTypes = Maps.newLinkedHashMap();
357 aliasNames = Sets.newLinkedHashSet();
358 for (AliasSpecification specification : aliasSpecifications) {
359 aliasTypes.put(specification.getTokenId(), specification);
360 aliasNames.add(specification.getAliasName());
361 }
362 }
363
364 /**
365 * Do all processing on the root node.
366 */
367 @Override
368 public void process(Node externs, Node root) {
369 // Find candidates to alias.
370 NodeTraversal.traverse(compiler, root, new FindAliasableNodes());
371
372 if (needsAliases()) {
373 // Inject alias nodes for null, true, and false into the global scope.
374 addAliasNodes(compiler.getNodeForCodeInsertion(null));
375
376 // Update references to null/true/false with references to the aliases.
377 for (AliasSpecification spec : aliasSpecifications) {
378 spec.doAlias(compiler);
379 }
380 }
381 }
382
383 private boolean needsAliases() {
384 for (AliasSpecification spec : aliasSpecifications) {
385 if (!spec.nodes.isEmpty()) {
386 return true;
387 }
388 }
389
390 return false;
391 }
392
393 /**
394 * Inject alias nodes into the global scope. e.g.
395 * var $$ALIAS_NULL=null,$$ALIAS_TRUE=true,$$ALIAS_FALSE=false;.
396 */
397 private void addAliasNodes(Node codeRoot) {
398 boolean codeChanged = false;
399
400 for (AliasSpecification spec : aliasSpecifications) {
401 if (spec.maybeInsertAliasDeclarationIntoParseTree(codeRoot)) {
402 codeChanged = true;
403 }
404 }
405
406 if (codeChanged) {
407 compiler.reportCodeChange();
408 }
409 }
410
411 /**
412 * Does the given node define one of our aliases?
413 */
414 private boolean isAliasDefinition(Node n) {
415 if (!n.isName()) {
416 return false;
417 }
418
419 if (!isAliasName(n.getString())) {
420 // The given Node's string contents is not an alias. Skip it.
421 return false;
422 }
423
424 /*
425 * A definition must have a child node (otherwise it's just a
426 * reference to the alias).
427 */
428 return n.getFirstChild() != null;
429 }
430
431 /**
432 * Is this one of the Rhino token types that we're aliasing?
433 */
434 private boolean isAliasableType(int type) {
435 return aliasTypes.containsKey(type);
436 }
437
438 /**
439 * Is this one of our alias names?
440 */
441 private boolean isAliasName(String name) {
442 return aliasNames.contains(name);
443 }
444
445 /**
446 * Create the AliasSpecifications, one for each type we're aliasing. The
447 * order of the elements in the list is significant. Transformations should
448 * be applied in the given order.
449 */
450 private List<AliasSpecification> createAliasSpecifications() {
451 List<AliasSpecification> l = Lists.newArrayList();
452 l.add(new KeywordAliasSpecification(ALIAS_FALSE, Token.FALSE));
453 l.add(new KeywordAliasSpecification(ALIAS_NULL, Token.NULL));
454 l.add(new KeywordAliasSpecification(ALIAS_TRUE, Token.TRUE));
455 l.add(new VoidKeywordAliasSpecification(ALIAS_VOID, Token.VOID));
456 // Process throw nodes after literal keyword nodes. This is important when
457 // a literal keyword is thrown (e.g., throw true;).
458 // KeywordAliasSpecification needs to know what the parent of the node being
459 // replaced with an alias is. Because ThrowAliasSpecification replaces the
460 // parent of the node being aliased, ThrowAliasSpecification invalidates the
461 // record of the node's parent that KeywordAliasSpecification stores.
462 l.add(new ThrowAliasSpecification(ALIAS_THROW));
463 return l;
464 }
465 }