Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.collect.ImmutableMap;
21 import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.Token;
25 import com.google.javascript.rhino.TokenStream;
26
27 import java.util.Arrays;
28 import java.util.Comparator;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Iterator;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.SortedSet;
35 import java.util.TreeSet;
36
37 import javax.annotation.Nullable;
38
39 /**
40 * RenamePrototypes renames custom properties (including methods) of custom
41 * prototypes and object literals. Externed property names are never renamed.
42 *
43 * To ensure that a prototype property or object literal property gets renamed,
44 * end it with an underscore.
45 *
46 * To ensure that a prototype property is not renamed, give it a leading
47 * underscore.
48 *
49 * For custom prototype property names that lack leading and trailing
50 * underscores:
51 * - To always rename these, use aggressive renaming.
52 * - If aggressive renaming is off, we use a heuristic to decide whether to
53 * rename (to avoid most built-in JS methods). We rename if the original name
54 * contains at least one character that is not a lowercase letter.
55 *
56 * When a property name is used both in a prototype definition and as an object
57 * literal key, we rename it only if it satisfies both renaming policies.
58 *
59 */
60 class RenamePrototypes implements CompilerPass {
61
62 private final AbstractCompiler compiler;
63 private final boolean aggressiveRenaming;
64 private final char[] reservedCharacters;
65
66 /** Previously used prototype renaming map. */
67 private final VariableMap prevUsedRenameMap;
68
69 /**
70 * The Property class encapsulates the information needed for renaming
71 * a method or member.
72 */
73 private class Property {
74 String oldName;
75 String newName;
76 int prototypeCount;
77 int objLitCount;
78 int refCount;
79
80 Property(String name) {
81 this.oldName = name;
82 this.newName = null;
83 this.prototypeCount = 0;
84 this.objLitCount = 0;
85 this.refCount = 0;
86 }
87
88 int count() {
89 return prototypeCount + objLitCount + refCount;
90 }
91
92 boolean canRename() {
93 if (this.prototypeCount > 0 && this.objLitCount == 0) {
94 return canRenamePrototypeProperty();
95 }
96 if (this.objLitCount > 0 && this.prototypeCount == 0) {
97 return canRenameObjLitProperty();
98 }
99 // We're not sure what kind of property this is, so we're conservative.
100 // Note that we still want to try renaming the property even when both
101 // counts are zero. It may be a property added to an object at runtime,
102 // like: o.newProp = x;
103 return canRenamePrototypeProperty() && canRenameObjLitProperty();
104 }
105
106 private boolean canRenamePrototypeProperty() {
107 if (compiler.getCodingConvention().isExported(oldName)) {
108 // an externally visible name should not be renamed.
109 return false;
110 }
111
112 if (compiler.getCodingConvention().isPrivate(oldName)) {
113 // private names can be safely renamed. Rename!
114 return true;
115 }
116
117 if (aggressiveRenaming) {
118 return true;
119 }
120
121 for (int i = 0, n = oldName.length(); i < n; i++) {
122 char ch = oldName.charAt(i);
123
124 if (Character.isUpperCase(ch) || !Character.isLetter(ch)) {
125 return true;
126 }
127 }
128 return false;
129 }
130
131 private boolean canRenameObjLitProperty() {
132 if (compiler.getCodingConvention().isExported(oldName)) {
133 // an externally visible name should not be renamed.
134 return false;
135 }
136
137 if (compiler.getCodingConvention().isPrivate(oldName)) {
138 // private names can be safely renamed. Rename!
139 return true;
140 }
141
142 // NOTE(user): We should probably have more aggressive options, like
143 // renaming all obj lit properties that are not quoted.
144 return false;
145 }
146 }
147
148 /**
149 * Sorts Property objects by their count, breaking ties alphabetically to
150 * ensure a deterministic total ordering.
151 */
152 private static final Comparator<Property> FREQUENCY_COMPARATOR =
153 new Comparator<Property>() {
154 @Override
155 public int compare(Property a1, Property a2) {
156 int n1 = a1.count();
157 int n2 = a2.count();
158 if (n1 != n2) {
159 return n2 - n1;
160 }
161 return a1.oldName.compareTo(a2.oldName);
162 }
163 };
164
165
166 // Set of String nodes to rename
167 private final Set<Node> stringNodes = new HashSet<Node>();
168
169 // Mapping of property names to Property objects
170 private final Map<String, Property> properties =
171 new HashMap<String, Property>();
172
173 // Set of names not to rename. Externed properties/methods are added later.
174 private final Set<String> reservedNames =
175 new HashSet<String>(Arrays.asList(
176 "indexOf", "lastIndexOf", "toString", "valueOf"));
177
178 // Set of OBJLIT nodes that are assigned to prototypes
179 private final Set<Node> prototypeObjLits = new HashSet<Node>();
180
181 /**
182 * Creates an instance.
183 *
184 * @param compiler The JSCompiler
185 * @param aggressiveRenaming Whether to rename aggressively
186 * @param reservedCharacters If specified these characters won't be used in
187 * generated names
188 * @param prevUsedRenameMap The rename map used in the previous compilation
189 */
190 RenamePrototypes(AbstractCompiler compiler, boolean aggressiveRenaming,
191 @Nullable char[] reservedCharacters,
192 @Nullable VariableMap prevUsedRenameMap) {
193 this.compiler = compiler;
194 this.aggressiveRenaming = aggressiveRenaming;
195 this.reservedCharacters = reservedCharacters;
196 this.prevUsedRenameMap = prevUsedRenameMap;
197 }
198
199 /**
200 * Does property/method renaming.
201 *
202 * @param externs The root of the externs parse tree
203 * @param root The root of the main code parse tree
204 */
205 @Override
206 public void process(Node externs, Node root) {
207 Preconditions.checkState(compiler.getLifeCycleStage().isNormalized());
208
209 NodeTraversal.traverse(compiler, externs,
210 new ProcessExternedProperties());
211 NodeTraversal.traverse(compiler, root, new ProcessProperties());
212
213 // Gather the properties to rename, sorted by count.
214 SortedSet<Property> propsByFrequency =
215 new TreeSet<Property>(FREQUENCY_COMPARATOR);
216
217 for (Iterator<Map.Entry<String, Property>> it =
218 properties.entrySet().iterator(); it.hasNext(); ) {
219 Property a = it.next().getValue();
220 if (a.canRename() && !reservedNames.contains(a.oldName)) {
221 propsByFrequency.add(a);
222 } else {
223 it.remove();
224
225 // If we're not renaming this, make sure we don't name something
226 // else to this name.
227 reservedNames.add(a.oldName);
228 }
229 }
230
231 // Try and reuse as many names from the previous compilation as possible.
232 if (prevUsedRenameMap != null) {
233 reusePrototypeNames(propsByFrequency);
234 }
235
236 // Generate new names.
237 NameGenerator nameGen = new NameGenerator(reservedNames, "",
238 reservedCharacters);
239 StringBuilder debug = new StringBuilder();
240 for (Property a : propsByFrequency) {
241 if (a.newName == null) {
242 a.newName = nameGen.generateNextName();
243 reservedNames.add(a.newName);
244 }
245
246 debug.append(a.oldName).append(" => ").append(a.newName).append('\n');
247 }
248
249 compiler.addToDebugLog("JS property assignments:\n" + debug);
250
251 // Update the string nodes.
252 boolean changed = false;
253 for (Node n : stringNodes) {
254 String oldName = n.getString();
255 Property a = properties.get(oldName);
256 if (a != null && a.newName != null) {
257 n.setString(a.newName);
258 changed = changed || !a.newName.equals(oldName);
259 }
260 }
261
262 if (changed) {
263 compiler.reportCodeChange();
264 }
265
266 compiler.setLifeCycleStage(LifeCycleStage.NORMALIZED_OBFUSCATED);
267 }
268
269 /**
270 * Runs through the list of properties and tries to rename as many as possible
271 * with names that were used for them in the previous compilation.
272 * {@code reservedNames} is updated with the set of reused names.
273 * @param properties The set of properties to attempt to rename.
274 */
275 private void reusePrototypeNames(Set<Property> properties) {
276 for (Property prop : properties) {
277 String prevName = prevUsedRenameMap.lookupNewName(prop.oldName);
278 if (prevName != null) {
279 if (reservedNames.contains(prevName)) {
280 continue;
281 }
282
283 prop.newName = prevName;
284 reservedNames.add(prevName);
285 }
286 }
287 }
288
289 /**
290 * Iterate through the nodes, collect all of the STRING nodes that are
291 * children of GETPROP or GETELEM and mark them as externs.
292 */
293 private class ProcessExternedProperties extends AbstractPostOrderCallback {
294
295 @Override
296 public void visit(NodeTraversal t, Node n, Node parent) {
297 switch (n.getType()) {
298 case Token.GETPROP:
299 case Token.GETELEM:
300 Node dest = n.getFirstChild().getNext();
301 if (dest.isString()) {
302 reservedNames.add(dest.getString());
303 }
304 }
305 }
306 }
307
308 /**
309 * Iterate through the nodes, collect all of the STRING nodes that are
310 * children of GETPROP, GETELEM, or OBJLIT, and also count the number of
311 * times each STRING is referenced.
312 *
313 * Also collects OBJLIT assignments of prototypes as candidates for renaming.
314 */
315 private class ProcessProperties extends AbstractPostOrderCallback {
316
317 @Override
318 public void visit(NodeTraversal t, Node n, Node parent) {
319 switch (n.getType()) {
320 case Token.GETPROP:
321 case Token.GETELEM:
322 Node dest = n.getFirstChild().getNext();
323 if (dest.isString()) {
324 String s = dest.getString();
325 if (s.equals("prototype")) {
326 processPrototypeParent(parent, t.getInput());
327 } else {
328 markPropertyAccessCandidate(dest, t.getInput());
329 }
330 }
331 break;
332 case Token.OBJECTLIT:
333 if (!prototypeObjLits.contains(n)) {
334 // Object literals have their property name/value pairs as a flat
335 // list as their children. We want every other node in order to get
336 // only the property names.
337 for (Node child = n.getFirstChild();
338 child != null;
339 child = child.getNext()) {
340
341 if (TokenStream.isJSIdentifier(child.getString())) {
342 markObjLitPropertyCandidate(child, t.getInput());
343 }
344 }
345 }
346 break;
347 }
348 }
349
350 /**
351 * Processes the parent of a GETPROP prototype, which can either be
352 * another GETPROP (in the case of Foo.prototype.bar), or can be
353 * an assignment (in the case of Foo.prototype = ...).
354 */
355 private void processPrototypeParent(Node n, CompilerInput input) {
356 switch (n.getType()) {
357 // Foo.prototype.getBar = function() { ... }
358 case Token.GETPROP:
359 case Token.GETELEM:
360 Node dest = n.getFirstChild().getNext();
361 if (dest.isString()) {
362 markPrototypePropertyCandidate(dest, input);
363 }
364 break;
365
366 // Foo.prototype = { "getBar" : function() { ... } }
367 case Token.ASSIGN:
368 case Token.CALL:
369 Node map;
370 if (n.isAssign()) {
371 map = n.getFirstChild().getNext();
372 } else {
373 map = n.getLastChild();
374 }
375 if (map.isObjectLit()) {
376 // Remember this node so that we can avoid processing it again when
377 // the traversal reaches it.
378 prototypeObjLits.add(map);
379
380 for (Node key = map.getFirstChild();
381 key != null; key = key.getNext()) {
382 if (TokenStream.isJSIdentifier(key.getString())) {
383 // May be STRING, GET, or SET
384 markPrototypePropertyCandidate(key, input);
385 }
386 }
387 }
388 break;
389 }
390 }
391
392 /**
393 * Remembers the given String node and increments the property name's
394 * access count.
395 *
396 * @param n A STRING node
397 * @param input The Input that the node came from
398 */
399 private void markPrototypePropertyCandidate(Node n, CompilerInput input) {
400 stringNodes.add(n);
401 getProperty(n.getString()).prototypeCount++;
402 }
403
404 /**
405 * Remembers the given String node and increments the property name's
406 * access count.
407 *
408 * @param n A STRING node
409 * @param input The Input that the node came from
410 */
411 private void markObjLitPropertyCandidate(Node n, CompilerInput input) {
412 stringNodes.add(n);
413 getProperty(n.getString()).objLitCount++;
414 }
415
416 /**
417 * Remembers the given String node and increments the property name's
418 * access count.
419 *
420 * @param n A STRING node
421 * @param input The Input that the node came from
422 */
423 private void markPropertyAccessCandidate(Node n, CompilerInput input) {
424 stringNodes.add(n);
425 getProperty(n.getString()).refCount++;
426 }
427
428 /**
429 * Gets the current property for the given name, creating a new one if
430 * none exists.
431 */
432 private Property getProperty(String name) {
433 Property prop = properties.get(name);
434 if (prop == null) {
435 prop = new Property(name);
436 properties.put(name, prop);
437 }
438 return prop;
439 }
440 }
441
442 /**
443 * Gets the property renaming map.
444 *
445 * @return A mapping from original names to new names
446 */
447 VariableMap getPropertyMap() {
448 ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
449 for (Property p : properties.values()) {
450 if (p.newName != null) {
451 map.put(p.oldName, p.newName);
452 }
453 }
454 return new VariableMap(map.build());
455 }
456 }