Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2007 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.Maps;
20 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
21 import com.google.javascript.rhino.IR;
22 import com.google.javascript.rhino.Node;
23 import com.google.javascript.rhino.Token;
24
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.LinkedHashSet;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32 import java.util.SortedMap;
33 import java.util.logging.Logger;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import java.util.zip.CRC32;
37
38 /**
39 * A {@link Compiler} pass for aliasing strings. String declarations
40 * contribute to garbage collection, which becomes a problem in large
41 * applications. Strings that should be aliased occur many times in the code,
42 * or occur on codepaths that get executed frequently.
43 *
44 */
45 class AliasStrings extends AbstractPostOrderCallback
46 implements CompilerPass {
47
48 private static final Logger logger =
49 Logger.getLogger(AliasStrings.class.getName());
50
51 /** Prefix for variable names for the aliased strings */
52 private static final String STRING_ALIAS_PREFIX = "$$S_";
53
54 private final AbstractCompiler compiler;
55
56 private final JSModuleGraph moduleGraph;
57
58 // Regular expression matcher for a blacklisting strings in aliasing.
59 private Matcher blacklist = null;
60
61 /**
62 * Strings that can be aliased, or null if all strings except 'undefined'
63 * should be aliased
64 */
65 private final Set<String> aliasableStrings;
66
67 private final boolean outputStringUsage;
68
69 private final SortedMap<String, StringInfo> stringInfoMap = Maps.newTreeMap();
70
71 private final Set<String> usedHashedAliases = new LinkedHashSet<String>();
72
73 /**
74 * Map from module to the node in that module that should parent any string
75 * variable declarations that have to be moved into that module
76 */
77 private final Map<JSModule, Node> moduleVarParentMap =
78 new HashMap<JSModule, Node>();
79
80 /** package private. This value is AND-ed with the hash function to allow
81 * unit tests to reduce the range of hash values to test collision cases */
82 long unitTestHashReductionMask = ~0L;
83
84 /**
85 * Creates an instance.
86 *
87 * @param compiler The compiler
88 * @param moduleGraph The module graph, or null if there are no modules
89 * @param strings Set of strings to be aliased. If null, all strings except
90 * 'undefined' will be aliased.
91 * @param blacklistRegex The regex to blacklist words in aliasing strings.
92 * @param outputStringUsage Outputs all strings and the number of times they
93 * were used in the application to the server log.
94 */
95 AliasStrings(AbstractCompiler compiler,
96 JSModuleGraph moduleGraph,
97 Set<String> strings,
98 String blacklistRegex,
99 boolean outputStringUsage) {
100 this.compiler = compiler;
101 this.moduleGraph = moduleGraph;
102 this.aliasableStrings = strings;
103 if (blacklistRegex.length() != 0) {
104 this.blacklist = Pattern.compile(blacklistRegex).matcher("");
105 } else {
106 this.blacklist = null;
107 }
108 this.outputStringUsage = outputStringUsage;
109 }
110
111 @Override
112 public void process(Node externs, Node root) {
113 logger.fine("Aliasing common strings");
114
115 // Traverse the tree and collect strings
116 NodeTraversal.traverse(compiler, root, this);
117
118 // 1st edit pass: replace some strings with aliases
119 replaceStringsWithAliases();
120
121 // 2nd edit pass: add variable declarations for aliased strings.
122 addAliasDeclarationNodes();
123
124 if (outputStringUsage) {
125 outputStringUsage();
126 }
127 }
128
129 @Override
130 public void visit(NodeTraversal t, Node n, Node parent) {
131 if (n.isString() &&
132 !parent.isGetProp() &&
133 !parent.isRegExp()) {
134
135 String str = n.getString();
136
137 // "undefined" is special-cased, since it needs to be used when JS code
138 // is unloading and therefore variable references aren't available.
139 // This is because of a bug in Firefox.
140 if ("undefined".equals(str)) {
141 return;
142 }
143
144 if (blacklist != null && blacklist.reset(str).find()) {
145 return;
146 }
147
148 if (aliasableStrings == null || aliasableStrings.contains(str)) {
149 StringOccurrence occurrence = new StringOccurrence(n, parent);
150 StringInfo info = getOrCreateStringInfo(str);
151
152 info.occurrences.add(occurrence);
153 info.numOccurrences++;
154
155 if (t.inGlobalScope() || isInThrowExpression(n)) {
156 info.numOccurrencesInfrequentlyExecuted++;
157 }
158
159 // The current module.
160 JSModule module = t.getModule();
161 if (info.numOccurrences != 1) {
162 // Check whether the current module depends on the module containing
163 // the declaration.
164 if (module != null &&
165 info.moduleToContainDecl != null &&
166 module != info.moduleToContainDecl &&
167 !moduleGraph.dependsOn(module, info.moduleToContainDecl)) {
168 // We need to declare this string in the deepest module in the
169 // module dependency graph that both of these modules depend on.
170 module = moduleGraph.getDeepestCommonDependency(
171 module, info.moduleToContainDecl);
172 } else {
173 // use the previously saved insertion location.
174 return;
175 }
176 }
177 Node varParent = moduleVarParentMap.get(module);
178 if (varParent == null) {
179 varParent = compiler.getNodeForCodeInsertion(module);
180 moduleVarParentMap.put(module, varParent);
181 }
182 info.moduleToContainDecl = module;
183 info.parentForNewVarDecl = varParent;
184 info.siblingToInsertVarDeclBefore = varParent.getFirstChild();
185 }
186 }
187 }
188
189 /**
190 * Looks up the {@link StringInfo} object for a JavaScript string. Creates
191 * it if necessary.
192 */
193 private StringInfo getOrCreateStringInfo(String string) {
194 StringInfo info = stringInfoMap.get(string);
195 if (info == null) {
196 info = new StringInfo(stringInfoMap.size());
197 stringInfoMap.put(string, info);
198 }
199 return info;
200 }
201
202 /**
203 * Is the {@link Node} currently within a 'throw' expression?
204 */
205 private static boolean isInThrowExpression(Node n) {
206 // Look up the traversal stack to find a THROW node
207 for (Node ancestor : n.getAncestors()) {
208 switch (ancestor.getType()) {
209 case Token.THROW:
210 return true;
211 case Token.IF:
212 case Token.WHILE:
213 case Token.DO:
214 case Token.FOR:
215 case Token.SWITCH:
216 case Token.CASE:
217 case Token.DEFAULT_CASE:
218 case Token.BLOCK:
219 case Token.SCRIPT:
220 case Token.FUNCTION:
221 case Token.TRY:
222 case Token.CATCH:
223 case Token.RETURN:
224 case Token.EXPR_RESULT:
225 // early exit - these nodes types can't be within a THROW
226 return false;
227 }
228 }
229 return false;
230 }
231
232 /**
233 * Replace strings with references to alias variables.
234 */
235 private void replaceStringsWithAliases() {
236 for (Entry<String, StringInfo> entry : stringInfoMap.entrySet()) {
237 String literal = entry.getKey();
238 StringInfo info = entry.getValue();
239 if (shouldReplaceWithAlias(literal, info)) {
240 for (StringOccurrence occurrence : info.occurrences) {
241 replaceStringWithAliasName(
242 occurrence, info.getVariableName(literal), info);
243 }
244 }
245 }
246 }
247
248 /**
249 * Creates a var declaration for each aliased string. Var declarations are
250 * inserted as close to the first use of the string as possible.
251 */
252 private void addAliasDeclarationNodes() {
253 for (Entry<String, StringInfo> entry : stringInfoMap.entrySet()) {
254 StringInfo info = entry.getValue();
255 if (!info.isAliased) {
256 continue;
257 }
258 String alias = info.getVariableName(entry.getKey());
259 Node var = IR.var(IR.name(alias), IR.string(entry.getKey()));
260 if (info.siblingToInsertVarDeclBefore == null) {
261 info.parentForNewVarDecl.addChildToFront(var);
262 } else {
263 info.parentForNewVarDecl.addChildBefore(
264 var, info.siblingToInsertVarDeclBefore);
265 }
266 compiler.reportCodeChange();
267 }
268 }
269
270 /**
271 * Dictates the policy for replacing a string with an alias.
272 *
273 * @param str The string literal
274 * @param info Accumulated information about a string
275 */
276 private static boolean shouldReplaceWithAlias(String str, StringInfo info) {
277 // Optimize for application performance. If there are any uses of the
278 // string that are not 'infrequent uses', assume they are frequent and
279 // create an alias.
280 if (info.numOccurrences > info.numOccurrencesInfrequentlyExecuted) {
281 return true;
282 }
283
284 // Optimize for code size. Are aliases smaller than strings?
285 //
286 // This logic optimizes for the size of uncompressed code, but it tends to
287 // get good results for the size of the gzipped code too.
288 //
289 // gzip actually prefers that strings are not aliased - it compresses N
290 // string literals better than 1 string literal and N+1 short variable
291 // names, provided each string is within 32k of the previous copy. We
292 // follow the uncompressed logic as insurance against there being multiple
293 // strings more than 32k apart.
294
295 int sizeOfLiteral = 2 + str.length();
296 int sizeOfStrings = info.numOccurrences * sizeOfLiteral;
297 int sizeOfVariable = 3;
298 // '6' comes from: 'var =;' in var XXX="...";
299 int sizeOfAliases = 6 + sizeOfVariable + sizeOfLiteral // declaration
300 + info.numOccurrences * sizeOfVariable; // + uses
301
302 return sizeOfAliases < sizeOfStrings;
303 }
304
305 /**
306 * Replaces a string literal with a reference to the string's alias variable.
307 */
308 private void replaceStringWithAliasName(StringOccurrence occurrence,
309 String name,
310 StringInfo info) {
311 occurrence.parent.replaceChild(occurrence.node,
312 IR.name(name));
313 info.isAliased = true;
314 compiler.reportCodeChange();
315 }
316
317 /**
318 * Outputs a log of all strings used more than once in the code.
319 */
320 private void outputStringUsage() {
321 StringBuilder sb = new StringBuilder("Strings used more than once:\n");
322 for (Entry<String, StringInfo> stringInfoEntry : stringInfoMap.entrySet()) {
323 StringInfo info = stringInfoEntry.getValue();
324 if (info.numOccurrences > 1) {
325 sb.append(info.numOccurrences);
326 sb.append(": ");
327 sb.append(stringInfoEntry.getKey());
328 sb.append('\n');
329 }
330 }
331 // TODO(user): Make this save to file OR output to the application
332 logger.fine(sb.toString());
333 }
334
335 // -------------------------------------------------------------------------
336
337 /**
338 * A class that holds the location of a single JavaScript string literal
339 */
340 private static final class StringOccurrence {
341 final Node node;
342 final Node parent;
343
344 StringOccurrence(Node node, Node parent) {
345 this.node = node;
346 this.parent = parent;
347 }
348 }
349
350 /**
351 * A class that holds information about a JavaScript string that might become
352 * aliased.
353 */
354 private final class StringInfo {
355 final int id;
356
357 boolean isAliased; // set to 'true' when reference to alias created
358
359 final List<StringOccurrence> occurrences;
360 int numOccurrences;
361 int numOccurrencesInfrequentlyExecuted;
362
363 JSModule moduleToContainDecl;
364 Node parentForNewVarDecl;
365 Node siblingToInsertVarDeclBefore;
366
367 String aliasName;
368
369 StringInfo(int id) {
370 this.id = id;
371 this.occurrences = new ArrayList<StringOccurrence>();
372 this.isAliased = false;
373 }
374
375 /** Returns the JS variable name to be substituted for this string. */
376 String getVariableName(String stringLiteral) {
377 if (aliasName == null) {
378 aliasName =
379 encodeStringAsIdentifier(STRING_ALIAS_PREFIX, stringLiteral);
380 }
381 return aliasName;
382 }
383
384 /**
385 * Returns a legal identifier that uniquely characterizes string 's'.
386 *
387 * We want the identifier to be a function of the string value because that
388 * makes the identifiers stable as the program is changed.
389 *
390 * The digits of a good hash function would be adequate, but for short
391 * strings the following algorithm is easier to work with for unit tests.
392 *
393 * ASCII alphanumerics are mapped to themselves. Other characters are
394 * mapped to $XXX or $XXX_ where XXX is a variable number of hex digits.
395 * The underscore is inserted as necessary to avoid ambiguity when the
396 * character following is a hex digit. E.g. '\n1' maps to '$a_1',
397 * distinguished by the underscore from '\u00A1' which maps to '$a1'.
398 *
399 * If the string is short enough, this is sufficient. Longer strings are
400 * truncated after encoding an initial prefix and appended with a hash
401 * value.
402 */
403 String encodeStringAsIdentifier(String prefix, String s) {
404 // Limit to avoid generating very long identifiers
405 final int MAX_LIMIT = 20;
406 final int length = s.length();
407 final int limit = Math.min(length, MAX_LIMIT);
408
409 StringBuilder sb = new StringBuilder();
410 sb.append(prefix);
411 boolean protectHex = false;
412
413 for (int i = 0; i < limit; i++) {
414 char ch = s.charAt(i);
415
416 if (protectHex) {
417 if ((ch >= '0' && ch <= '9') ||
418 (ch >= 'a' && ch <= 'f')) { // toHexString generate lowercase
419 sb.append('_');
420 }
421 protectHex = false;
422 }
423
424 if ((ch >= '0' && ch <= '9') ||
425 (ch >= 'A' && ch <= 'Z') ||
426 (ch >= 'a' && ch <= 'z')) {
427 sb.append(ch);
428 } else {
429 sb.append('$');
430 sb.append(Integer.toHexString(ch));
431 protectHex = true;
432 }
433 }
434
435 if (length == limit) {
436 return sb.toString();
437 }
438
439 // The identifier is not unique because we omitted part, so add a
440 // checksum as a hashcode.
441 CRC32 crc32 = new CRC32();
442 crc32.update(s.getBytes());
443 long hash = crc32.getValue() & unitTestHashReductionMask;
444 sb.append('_');
445 sb.append(Long.toHexString(hash));
446 String encoded = sb.toString();
447 if (!usedHashedAliases.add(encoded)) {
448 // A collision has been detected (which is very rare). Use the sequence
449 // id to break the tie. This means that the name is no longer invariant
450 // across source code changes and recompilations.
451 encoded += "_" + id;
452 }
453 return encoded;
454 }
455 }
456 }