Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2010 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.base.Preconditions;
20 import com.google.common.base.Predicate;
21 import com.google.common.collect.HashMultimap;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import com.google.common.collect.ImmutableSet;
25 import com.google.common.collect.Iterables;
26 import com.google.common.collect.Lists;
27 import com.google.common.collect.Maps;
28 import com.google.common.collect.Multimap;
29 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
30 import com.google.javascript.rhino.IR;
31 import com.google.javascript.rhino.Node;
32 import com.google.javascript.rhino.Token;
33 import com.google.javascript.rhino.jstype.JSType;
34 import com.google.javascript.rhino.jstype.JSTypeRegistry;
35
36 import java.util.Collection;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40
41 /**
42 * Replaces JavaScript strings in the list of supplied methods with shortened
43 * forms. Useful for replacing debug message such as: throw new
44 * Error("Something bad happened"); with generated codes like: throw new
45 * Error("a"); This makes the compiled JavaScript smaller and prevents us from
46 * leaking details about the source code.
47 *
48 * Based in concept on the work by Jared Jacobs.
49 */
50 class ReplaceStrings extends AbstractPostOrderCallback
51 implements CompilerPass {
52 static final DiagnosticType BAD_REPLACEMENT_CONFIGURATION =
53 DiagnosticType.warning(
54 "JSC_BAD_REPLACEMENT_CONFIGURATION",
55 "Bad replacement configuration.");
56
57 private final String DEFAULT_PLACEHOLDER_TOKEN = "`";
58 private final String placeholderToken;
59 private static final String REPLACE_ONE_MARKER = "?";
60 private static final String REPLACE_ALL_MARKER = "*";
61
62 private final AbstractCompiler compiler;
63 private final JSTypeRegistry registry;
64
65 //
66 private final Map<String, Config> functions = Maps.newHashMap();
67 private final Multimap<String, String> methods = HashMultimap.create();
68 private final NameGenerator nameGenerator;
69 private final Map<String, Result> results = Maps.newLinkedHashMap();
70
71 /**
72 * Describes a function to look for a which parameters to replace.
73 */
74 private class Config {
75 // TODO(johnlenz): Support name "groups" so that unrelated strings can
76 // reuse strings. For example, event-id can reuse the names used for logger
77 // classes.
78 final String name;
79 final int parameter;
80 static final int REPLACE_ALL_VALUE = 0;
81
82 Config(String name, int parameter) {
83 this.name = name;
84 this.parameter = parameter;
85 }
86 }
87
88 /**
89 * Describes a replacement that occurred.
90 */
91 class Result {
92 // The original message with non-static content replaced with
93 // {@code placeholderToken}.
94 public final String original;
95 public final String replacement;
96 public final List<Location> replacementLocations = Lists.newLinkedList();
97
98 Result(String original, String replacement) {
99 this.original = original;
100 this.replacement = replacement;
101 }
102
103 void addLocation(Node n) {
104 replacementLocations.add(new Location(
105 n.getSourceFileName(),
106 n.getLineno(), n.getCharno()));
107 }
108 }
109
110 /** Represent a source location where a replacement occurred. */
111 class Location {
112 public final String sourceFile;
113 public final int line;
114 public final int column;
115 Location(String sourceFile, int line, int column) {
116 this.sourceFile = sourceFile;
117 this.line = line;
118 this.column = column;
119 }
120 }
121
122 /**
123 * @param placeholderToken Separator to use between string parts. Used to replace
124 * non-static string content.
125 * @param functionsToInspect A list of function configurations in the form of
126 * function($,,,)
127 * or
128 * class.prototype.method($,,,)
129 * @param blacklisted A set of names that should not be used as replacement
130 * strings. Useful to prevent unwanted strings for appearing in the
131 * final output.
132 * where '$' is used to indicate which parameter should be replaced.
133 */
134 ReplaceStrings(
135 AbstractCompiler compiler, String placeholderToken,
136 List<String> functionsToInspect,
137 Set<String> blacklisted,
138 VariableMap previousMappings) {
139 this.compiler = compiler;
140 this.placeholderToken = placeholderToken.isEmpty()
141 ? DEFAULT_PLACEHOLDER_TOKEN : placeholderToken;
142 this.registry = compiler.getTypeRegistry();
143
144 Iterable<String> reservedNames = blacklisted;
145 if (previousMappings != null) {
146 Set<String> previous =
147 previousMappings.getOriginalNameToNewNameMap().keySet();
148 reservedNames = Iterables.concat(blacklisted, previous);
149 initMapping(previousMappings, blacklisted);
150 }
151 this.nameGenerator = createNameGenerator(reservedNames);
152
153 // Initialize the map of functions to inspect for renaming candidates.
154 parseConfiguration(functionsToInspect);
155 }
156
157 private void initMapping(
158 VariableMap previousVarMap, Set<String> reservedNames) {
159 Map<String,String> previous = previousVarMap.getOriginalNameToNewNameMap();
160 for (Map.Entry<String,String> entry : previous.entrySet()) {
161 String key = entry.getKey();
162 if (!reservedNames.contains(key)) {
163 String value = entry.getValue();
164 results.put(value, new Result(value, key));
165 }
166 }
167 }
168
169 static final Predicate<Result> USED_RESULTS = new Predicate<Result>() {
170 @Override
171 public boolean apply(Result result) {
172 // The list of locations may be empty if the map
173 // was pre-populated from a previous map.
174 return !result.replacementLocations.isEmpty();
175 }
176 };
177
178 // Get the list of all replacements performed.
179 List<Result> getResult() {
180 return ImmutableList.copyOf(
181 Iterables.filter(results.values(), USED_RESULTS));
182 }
183
184 // Get the list of replaces as a VariableMap
185 VariableMap getStringMap() {
186 ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
187 for (Result result : Iterables.filter(results.values(), USED_RESULTS)) {
188 map.put(result.replacement, result.original);
189 }
190
191 VariableMap stringMap = new VariableMap(map.build());
192 return stringMap;
193 }
194
195 @Override
196 public void process(Node externs, Node root) {
197 NodeTraversal.traverse(compiler, root, this);
198 }
199
200 @Override
201 public void visit(NodeTraversal t, Node n, Node parent) {
202 // TODO(johnlenz): Determine if it is necessary to support ".call" or
203 // ".apply".
204 switch (n.getType()) {
205 case Token.NEW: // e.g. new Error('msg');
206 case Token.CALL: // e.g. Error('msg');
207 Node calledFn = n.getFirstChild();
208
209 // Look for calls to static functions.
210 String name = calledFn.getQualifiedName();
211 if (name != null) {
212 Config config = findMatching(name);
213 if (config != null) {
214 doSubstitutions(t, config, n);
215 return;
216 }
217 }
218
219 // Look for calls to class methods.
220 if (NodeUtil.isGet(calledFn)) {
221 Node rhs = calledFn.getLastChild();
222 if (rhs.isName() || rhs.isString()) {
223 String methodName = rhs.getString();
224 Collection<String> classes = methods.get(methodName);
225 if (classes != null) {
226 Node lhs = calledFn.getFirstChild();
227 if (lhs.getJSType() != null) {
228 JSType type = lhs.getJSType().restrictByNotNullOrUndefined();
229 Config config = findMatchingClass(type, classes);
230 if (config != null) {
231 doSubstitutions(t, config, n);
232 return;
233 }
234 }
235 }
236 }
237 }
238 break;
239 }
240 }
241
242 /**
243 * @param name The function name to find.
244 * @return The Config object for the name or null if no match was found.
245 */
246 private Config findMatching(String name) {
247 Config config = functions.get(name);
248 if (config == null) {
249 name = name.replace('$', '.');
250 config = functions.get(name);
251 }
252 return config;
253 }
254
255 /**
256 * @return The Config object for the class match the specified type or null
257 * if no match was found.
258 */
259 private Config findMatchingClass(
260 JSType callClassType, Collection<String> declarationNames) {
261 if (!callClassType.isNoObjectType() && !callClassType.isUnknownType()) {
262 for (String declarationName : declarationNames) {
263 String className = getClassFromDeclarationName(declarationName);
264 JSType methodClassType = registry.getType(className);
265 if (methodClassType != null
266 && callClassType.isSubtype(methodClassType)) {
267 return functions.get(declarationName);
268 }
269 }
270 }
271 return null;
272 }
273
274 /**
275 * Replace the parameters specified in the config, if possible.
276 */
277 private void doSubstitutions(NodeTraversal t, Config config, Node n) {
278 Preconditions.checkState(
279 n.isNew() || n.isCall());
280
281 if (config.parameter != Config.REPLACE_ALL_VALUE) {
282 // Note: the first child is the function, but the parameter id is 1 based.
283 Node arg = n.getChildAtIndex(config.parameter);
284 if (arg != null) {
285 replaceExpression(t, arg, n);
286 }
287 } else {
288 // Replace all parameters.
289 Node firstParam = n.getFirstChild().getNext();
290 for (Node arg = firstParam; arg != null; arg = arg.getNext()) {
291 arg = replaceExpression(t, arg, n);
292 }
293 }
294 }
295
296 /**
297 * Replaces a string expression with a short encoded string expression.
298 *
299 * @param t The traversal
300 * @param expr The expression node
301 * @param parent The expression node's parent
302 * @return The replacement node (or the original expression if no replacement
303 * is made)
304 */
305 private Node replaceExpression(NodeTraversal t, Node expr, Node parent) {
306 Node replacement;
307 String key = null;
308 String replacementString;
309 switch (expr.getType()) {
310 case Token.STRING:
311 key = expr.getString();
312 replacementString = getReplacement(key);
313 replacement = IR.string(replacementString);
314 break;
315 case Token.ADD:
316 StringBuilder keyBuilder = new StringBuilder();
317 Node keyNode = IR.string("");
318 replacement = buildReplacement(expr, keyNode, keyBuilder);
319 key = keyBuilder.toString();
320 replacementString = getReplacement(key);
321 keyNode.setString(replacementString);
322 break;
323 case Token.NAME:
324 // If the referenced variable is a constant, use its value.
325 Scope.Var var = t.getScope().getVar(expr.getString());
326 if (var != null && var.isConst()) {
327 Node value = var.getInitialValue();
328 if (value != null && value.isString()) {
329 key = value.getString();
330 replacementString = getReplacement(key);
331 replacement = IR.string(replacementString);
332 break;
333 }
334 }
335 return expr;
336 default:
337 // This may be a function call or a variable reference. We don't
338 // replace these.
339 return expr;
340 }
341
342 Preconditions.checkNotNull(key);
343 Preconditions.checkNotNull(replacementString);
344 recordReplacement(expr, key);
345
346 parent.replaceChild(expr, replacement);
347 compiler.reportCodeChange();
348 return replacement;
349 }
350
351 /**
352 * Get a replacement string for the provide key text.
353 */
354 private String getReplacement(String key) {
355 Result result = results.get(key);
356 if (result != null) {
357 return result.replacement;
358 }
359
360 String replacement = nameGenerator.generateNextName();
361 result = new Result(key, replacement);
362 results.put(key, result);
363 return replacement;
364 }
365
366 /**
367 * Record the location the replacement was made.
368 */
369 private void recordReplacement(Node n, String key) {
370 Result result = results.get(key);
371 Preconditions.checkState(result != null);
372
373 result.addLocation(n);
374 }
375
376 /**
377 * Builds a replacement abstract syntax tree for the string expression {@code
378 * expr}. Appends any string literal values that are encountered to
379 * {@code keyBuilder}, to build the expression's replacement key.
380 *
381 * @param expr A JS expression that evaluates to a string value
382 * @param prefix The JS expression to which {@code expr}'s replacement is
383 * logically being concatenated. It is a partial solution to the
384 * problem at hand and will either be this method's return value or a
385 * descendant of it.
386 * @param keyBuilder A builder of the string expression's replacement key
387 * @return The abstract syntax tree that should replace {@code expr}
388 */
389 private Node buildReplacement(
390 Node expr, Node prefix, StringBuilder keyBuilder) {
391 switch (expr.getType()) {
392 case Token.ADD:
393 Node left = expr.getFirstChild();
394 Node right = left.getNext();
395 prefix = buildReplacement(left, prefix, keyBuilder);
396 return buildReplacement(right, prefix, keyBuilder);
397 case Token.STRING:
398 keyBuilder.append(expr.getString());
399 return prefix;
400 default:
401 keyBuilder.append(placeholderToken);
402 prefix = IR.add(prefix, IR.string(placeholderToken));
403 return IR.add(prefix, expr.cloneTree());
404 }
405 }
406
407 /**
408 * From a provide name extract the method name.
409 */
410 private String getMethodFromDeclarationName(String fullDeclarationName) {
411 String[] parts = fullDeclarationName.split("\\.prototype\\.");
412 Preconditions.checkState(parts.length == 1 || parts.length == 2);
413 if (parts.length == 2) {
414 return parts[1];
415 }
416 return null;
417 }
418
419 /**
420 * From a provide name extract the class name.
421 */
422 private String getClassFromDeclarationName(String fullDeclarationName) {
423 String[] parts = fullDeclarationName.split("\\.prototype\\.");
424 Preconditions.checkState(parts.length == 1 || parts.length == 2);
425 if (parts.length == 2) {
426 return parts[0];
427 }
428 return null;
429 }
430
431 /**
432 * Build the data structures need by this pass from the provided
433 * list of functions and methods.
434 */
435 private void parseConfiguration(List<String> functionsToInspect) {
436 for (String function : functionsToInspect) {
437 Config config = parseConfiguration(function);
438 functions.put(config.name, config);
439
440 String method = getMethodFromDeclarationName(config.name);
441 if (method != null) {
442 methods.put(method, config.name);
443 }
444 }
445 }
446
447 /**
448 * Convert the provide string into a Config. The string can be a static function:
449 * foo(,,?)
450 * foo.bar(?)
451 * or a class method:
452 * foo.prototype.bar(?)
453 * And is allowed to either replace all parameters using "*" or one parameter "?".
454 * "," is used as a placeholder for ignored parameters.
455 */
456 private Config parseConfiguration(String function) {
457 // Looks like this function_name(,$,)
458 int first = function.indexOf('(');
459 int last = function.indexOf(')');
460
461 // TODO(johnlenz): Make parsing precondition checks JSErrors reports.
462 Preconditions.checkState(first != -1 && last != -1);
463
464 String name = function.substring(0, first);
465 String params = function.substring(first+1, last);
466
467 int paramCount = 0;
468 int replacementParameter = -1;
469 String[] parts = params.split(",");
470 for (String param : parts) {
471 paramCount++;
472 if (param.equals(REPLACE_ALL_MARKER)) {
473 Preconditions.checkState(paramCount == 1 && parts.length == 1);
474 replacementParameter = Config.REPLACE_ALL_VALUE;
475 } else if (param.equals(REPLACE_ONE_MARKER)) {
476 // TODO(johnlenz): Support multiple.
477 Preconditions.checkState(replacementParameter == -1);
478 replacementParameter = paramCount;
479 } else {
480 // TODO(johnlenz): report an error.
481 Preconditions.checkState(param.isEmpty(), "Unknown marker", param);
482 }
483 }
484
485 Preconditions.checkState(replacementParameter != -1);
486 return new Config(name, replacementParameter);
487 }
488
489 /**
490 * Use a name generate to create names so the names overlap with the names
491 * used for variable and properties.
492 */
493 private static NameGenerator createNameGenerator(Iterable<String> reserved) {
494 final String namePrefix = "";
495 final char[] reservedChars = new char[0];
496 return new NameGenerator(
497 ImmutableSet.copyOf(reserved), namePrefix, reservedChars);
498 }
499 }