Debian Codegraph @

src/com/google/javascript/jscomp/StripCode.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 javax.annotation.Nullable;
20 import com.google.common.collect.Sets;
21 import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
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.Set;
28
29 /**
30 * A pass for stripping a list of provided JavaScript object types.
31 *
32 * The stripping strategy is as follows:
33 * - Provide: 1) a list of types that should be stripped, and 2) a list of
34 * suffixes of field/variable names that should be stripped.
35 * - Remove declarations of variables that are initialized using static
36 * methods of strip types (e.g. var x = goog.debug.Logger.getLogger(...);).
37 * - Remove all references to variables that are stripped.
38 * - Remove all object literal keys with strip names.
39 * - Remove all assignments to 1) field names that are strip names and
40 * 2) qualified names that begin with strip types.
41 * - Remove all statements containing calls to static methods of strip types.
42 *
43 */
44 class StripCode implements CompilerPass {
45
46 // TODO(user): Try eliminating the need for a list of strip names by instead
47 // recording which field names are assigned to debug types in each JS input.
48 private final AbstractCompiler compiler;
49 private final Set<String> stripTypes;
50 private final Set<String> stripNameSuffixes;
51 private final Set<String> stripTypePrefixes;
52 private final Set<String> stripNamePrefixes;
53 private final Set<Scope.Var> varsToRemove;
54
55 static final DiagnosticType STRIP_TYPE_INHERIT_ERROR = DiagnosticType.error(
56 "JSC_STRIP_TYPE_INHERIT_ERROR",
57 "Non-strip type {0} cannot inherit from strip type {1}");
58
59 static final DiagnosticType STRIP_ASSIGNMENT_ERROR = DiagnosticType.error(
60 "JSC_STRIP_ASSIGNMENT_ERROR",
61 "Unable to strip assignment to {0}");
62
63 /**
64 * Creates an instance.
65 *
66 * @param compiler The compiler
67 */
68 StripCode(AbstractCompiler compiler,
69 Set<String> stripTypes,
70 Set<String> stripNameSuffixes,
71 Set<String> stripTypePrefixes,
72 Set<String> stripNamePrefixes) {
73
74 this.compiler = compiler;
75 this.stripTypes = Sets.newHashSet(stripTypes);
76 this.stripNameSuffixes = Sets.newHashSet(stripNameSuffixes);
77 this.stripTypePrefixes = Sets.newHashSet(stripTypePrefixes);
78 this.stripNamePrefixes = Sets.newHashSet(stripNamePrefixes);
79 this.varsToRemove = Sets.newHashSet();
80 }
81
82 /**
83 * Enables stripping of goog.tweak functions.
84 */
85 public void enableTweakStripping() {
86 stripTypes.add("goog.tweak");
87 }
88
89 @Override
90 public void process(Node externs, Node root) {
91 NodeTraversal.traverse(compiler, root, new Strip());
92 }
93
94 // -------------------------------------------------------------------------
95
96 /**
97 * A callback that strips debug code from a JavaScript parse tree.
98 */
99 private class Strip extends AbstractPostOrderCallback {
100
101 @Override
102 public void visit(NodeTraversal t, Node n, Node parent) {
103 switch (n.getType()) {
104 case Token.VAR:
105 removeVarDeclarationsByNameOrRvalue(t, n, parent);
106 break;
107
108 case Token.NAME:
109 maybeRemoveReferenceToRemovedVariable(t, n, parent);
110 break;
111
112 case Token.ASSIGN:
113 case Token.ASSIGN_BITOR:
114 case Token.ASSIGN_BITXOR:
115 case Token.ASSIGN_BITAND:
116 case Token.ASSIGN_LSH:
117 case Token.ASSIGN_RSH:
118 case Token.ASSIGN_URSH:
119 case Token.ASSIGN_ADD:
120 case Token.ASSIGN_SUB:
121 case Token.ASSIGN_MUL:
122 case Token.ASSIGN_DIV:
123 case Token.ASSIGN_MOD:
124 maybeEliminateAssignmentByLvalueName(t, n, parent);
125 break;
126
127 case Token.CALL:
128 case Token.NEW:
129 maybeRemoveCall(t, n, parent);
130 break;
131
132 case Token.OBJECTLIT:
133 eliminateKeysWithStripNamesFromObjLit(t, n);
134 break;
135
136 case Token.EXPR_RESULT:
137 maybeEliminateExpressionByName(t, n, parent);
138 break;
139 }
140 }
141
142 /**
143 * Removes declarations of any variables whose names are strip names or
144 * whose whose r-values are static method calls on strip types. Builds a set
145 * of removed variables so that all references to them can be removed.
146 *
147 * @param t The traversal
148 * @param n A VAR node
149 * @param parent {@code n}'s parent
150 */
151 void removeVarDeclarationsByNameOrRvalue(NodeTraversal t, Node n,
152 Node parent) {
153 for (Node nameNode = n.getFirstChild(); nameNode != null;
154 nameNode = nameNode.getNext()) {
155 String name = nameNode.getString();
156 if (isStripName(name) ||
157 isCallWhoseReturnValueShouldBeStripped(nameNode.getFirstChild())) {
158 // Remove the NAME.
159 Scope scope = t.getScope();
160 varsToRemove.add(scope.getVar(name));
161 n.removeChild(nameNode);
162 compiler.reportCodeChange();
163 }
164 }
165 if (!n.hasChildren()) {
166 // Must also remove the VAR.
167 replaceWithEmpty(n, parent);
168 compiler.reportCodeChange();
169 }
170 }
171
172 /**
173 * Removes a reference if it is a reference to a removed variable.
174 *
175 * @param t The traversal
176 * @param n A NAME node
177 * @param parent {@code n}'s parent
178 */
179 void maybeRemoveReferenceToRemovedVariable(NodeTraversal t, Node n,
180 Node parent) {
181 switch (parent.getType()) {
182 case Token.VAR:
183 // This is a variable declaration, not a reference.
184 break;
185
186 case Token.GETPROP:
187 // GETPROP
188 // NAME
189 // STRING (property name)
190 case Token.GETELEM:
191 // GETELEM
192 // NAME
193 // NUMBER|STRING|NAME|...
194 if (parent.getFirstChild() == n && isReferenceToRemovedVar(t, n)) {
195 replaceHighestNestedCallWithNull(parent, parent.getParent());
196 }
197 break;
198
199 case Token.ASSIGN:
200 case Token.ASSIGN_BITOR:
201 case Token.ASSIGN_BITXOR:
202 case Token.ASSIGN_BITAND:
203 case Token.ASSIGN_LSH:
204 case Token.ASSIGN_RSH:
205 case Token.ASSIGN_URSH:
206 case Token.ASSIGN_ADD:
207 case Token.ASSIGN_SUB:
208 case Token.ASSIGN_MUL:
209 case Token.ASSIGN_DIV:
210 case Token.ASSIGN_MOD:
211 if (isReferenceToRemovedVar(t, n)) {
212 if (parent.getFirstChild() == n) {
213 Node gramps = parent.getParent();
214 if (gramps.isExprResult()) {
215 // Remove the assignment.
216 Node greatGramps = gramps.getParent();
217 replaceWithEmpty(gramps, greatGramps);
218 compiler.reportCodeChange();
219 } else {
220 // Substitute the r-value for the assignment.
221 Node rvalue = n.getNext();
222 parent.removeChild(rvalue);
223 gramps.replaceChild(parent, rvalue);
224 compiler.reportCodeChange();
225 }
226 } else {
227 // The var reference is the r-value. Replace it with null.
228 replaceWithNull(n, parent);
229 compiler.reportCodeChange();
230 }
231 }
232 break;
233
234 default:
235 if (isReferenceToRemovedVar(t, n)) {
236 replaceWithNull(n, parent);
237 compiler.reportCodeChange();
238 }
239 break;
240 }
241 }
242
243 /**
244 * Use a while loop to get up out of any nested calls. For example,
245 * if we have just detected that we need to remove the a.b() call
246 * in a.b().c().d(), we'll have to remove all of the calls, and it
247 * will take a few iterations through this loop to get up to d().
248 */
249 void replaceHighestNestedCallWithNull(Node node, Node parent) {
250 Node ancestor = parent;
251 Node ancestorChild = node;
252 while (true) {
253 if (ancestor.getFirstChild() != ancestorChild) {
254 replaceWithNull(ancestorChild, ancestor);
255 break;
256 }
257 if (ancestor.isExprResult()) {
258 // Remove the entire expression statement.
259 Node ancParent = ancestor.getParent();
260 replaceWithEmpty(ancestor, ancParent);
261 break;
262 }
263 int type = ancestor.getType();
264 if (type != Token.GETPROP &&
265 type != Token.GETELEM &&
266 type != Token.CALL) {
267 replaceWithNull(ancestorChild, ancestor);
268 break;
269 }
270 ancestorChild = ancestor;
271 ancestor = ancestor.getParent();
272 }
273 compiler.reportCodeChange();
274 }
275
276 /**
277 * Eliminates an assignment if the l-value is:
278 * - A field name that's a strip name
279 * - A qualified name that begins with a strip type
280 *
281 * @param t The traversal
282 * @param n An ASSIGN node
283 * @param parent {@code n}'s parent
284 */
285 void maybeEliminateAssignmentByLvalueName(NodeTraversal t, Node n,
286 Node parent) {
287 // ASSIGN
288 // l-value
289 // r-value
290 Node lvalue = n.getFirstChild();
291 if (nameEndsWithFieldNameToStrip(lvalue) ||
292 qualifiedNameBeginsWithStripType(lvalue)) {
293
294 // Limit to EXPR_RESULT because it is not
295 // safe to eliminate assignment in complex expressions,
296 // e.g. in ((x = 7) + 8)
297 if (parent.isExprResult()) {
298 Node gramps = parent.getParent();
299 replaceWithEmpty(parent, gramps);
300 compiler.reportCodeChange();
301 } else {
302 t.report(n, STRIP_ASSIGNMENT_ERROR, lvalue.getQualifiedName());
303 }
304 }
305 }
306
307 /**
308 * Eliminates an expression if it refers to:
309 * - A field name that's a strip name
310 * - A qualified name that begins with a strip type
311 * This gets rid of construct like:
312 * a.prototype.logger; (used instead of a.prototype.logger = null;)
313 * This expression is not an assignment and so will not be caught by
314 * maybeEliminateAssignmentByLvalueName.
315 * @param t The traversal
316 * @param n An EXPR_RESULT node
317 * @param parent {@code n}'s parent
318 */
319 void maybeEliminateExpressionByName(NodeTraversal t, Node n,
320 Node parent) {
321 // EXPR_RESULT
322 // expression
323 Node expression = n.getFirstChild();
324 if (nameEndsWithFieldNameToStrip(expression) ||
325 qualifiedNameBeginsWithStripType(expression)) {
326 if (parent.isExprResult()) {
327 Node gramps = parent.getParent();
328 replaceWithEmpty(parent, gramps);
329 } else {
330 replaceWithEmpty(n, parent);
331 }
332 compiler.reportCodeChange();
333 }
334 }
335
336 /**
337 * Removes a method call if {@link #isMethodOrCtorCallThatTriggersRemoval}
338 * indicates that it should be removed.
339 *
340 * @param t The traversal
341 * @param n A CALL node
342 * @param parent {@code n}'s parent
343 */
344 void maybeRemoveCall(NodeTraversal t, Node n, Node parent) {
345 // CALL/NEW
346 // function
347 // arguments
348 if (isMethodOrCtorCallThatTriggersRemoval(t, n, parent)) {
349 replaceHighestNestedCallWithNull(n, parent);
350 }
351 }
352
353 /**
354 * Eliminates any object literal keys in an object literal declaration that
355 * have strip names.
356 *
357 * @param t The traversal
358 * @param n An OBJLIT node
359 */
360 void eliminateKeysWithStripNamesFromObjLit(NodeTraversal t, Node n) {
361 // OBJLIT
362 // key1
363 // value1
364 // key2
365 // ...
366 Node key = n.getFirstChild();
367 while (key != null) {
368 if (isStripName(key.getString())) {
369 Node next = key.getNext();
370 n.removeChild(key);
371 key = next;
372 compiler.reportCodeChange();
373 } else {
374 key = key.getNext();
375 }
376 }
377 }
378
379 /**
380 * Gets whether a node is a CALL node whose return value should be
381 * stripped. A call's return value should be stripped if the function
382 * getting called is a static method in a class that gets stripped. For
383 * example, if "goog.debug.Logger" is a strip name, then this function
384 * returns true for a call such as "goog.debug.Logger.getLogger(...)". It
385 * may also simply be a function that is getting stripped. For example,
386 * if "getLogger" is a strip name, but not "goog.debug.Logger", this will
387 * still return true.
388 *
389 * @param n A node (typically a CALL node)
390 * @return Whether the call's return value should be stripped
391 */
392 boolean isCallWhoseReturnValueShouldBeStripped(@Nullable Node n) {
393 return n != null &&
394 (n.isCall() ||
395 n.isNew()) &&
396 n.hasChildren() &&
397 (qualifiedNameBeginsWithStripType(n.getFirstChild()) ||
398 nameEndsWithFieldNameToStrip(n.getFirstChild()));
399 }
400
401 /**
402 * Gets whether a qualified name begins with a strip name. The names
403 * "goog.debug", "goog.debug.Logger", and "goog.debug.Logger.Level" are
404 * examples of strip names that would result in this function returning
405 * true for a node representing the name "goog.debug.Logger.Level".
406 *
407 * @param n A node (typically a NAME or GETPROP node)
408 * @return Whether the name begins with a strip name
409 */
410 boolean qualifiedNameBeginsWithStripType(Node n) {
411 String name = n.getQualifiedName();
412 return qualifiedNameBeginsWithStripType(name);
413 }
414
415 /**
416 * Gets whether a qualified name begins with a strip name. The names
417 * "goog.debug", "goog.debug.Logger", and "goog.debug.Logger.Level" are
418 * examples of strip names that would result in this function returning
419 * true for a node representing the name "goog.debug.Logger.Level".
420 *
421 * @param name A qualified class name
422 * @return Whether the name begins with a strip name
423 */
424 boolean qualifiedNameBeginsWithStripType(String name) {
425 if (name != null) {
426 for (String type : stripTypes) {
427 if (name.equals(type) || name.startsWith(type + ".")) {
428 return true;
429 }
430 }
431 for (String type : stripTypePrefixes) {
432 if (name.startsWith(type)) {
433 return true;
434 }
435 }
436 }
437 return false;
438 }
439
440 /**
441 * Determines whether a NAME node represents a reference to a variable that
442 * has been removed.
443 *
444 * @param t The traversal
445 * @param n A NAME node
446 * @return Whether the variable was removed
447 */
448 boolean isReferenceToRemovedVar(NodeTraversal t, Node n) {
449 String name = n.getString();
450 Scope scope = t.getScope();
451 Scope.Var var = scope.getVar(name);
452 return varsToRemove.contains(var);
453 }
454
455 /**
456 * Gets whether a CALL node triggers statement removal, based on the name
457 * of the object whose method is being called, or the name of the method.
458 * Checks whether the name begins with a strip type, ends with a field name
459 * that's a strip name, or belongs to the set of global class-defining
460 * functions (e.g. goog.inherits).
461 *
462 * @param t The traversal
463 * @param n A CALL node
464 * @return Whether the node triggers statement removal
465 */
466 boolean isMethodOrCtorCallThatTriggersRemoval(
467 NodeTraversal t, Node n, Node parent) {
468 // CALL/NEW
469 // GETPROP (function) <-- we're interested in this, the function
470 // GETPROP (callee object) <-- or the object on which it is called
471 // ...
472 // STRING (field name)
473 // STRING (method name)
474 // ... (arguments)
475
476 Node function = n.getFirstChild();
477 if (function == null || !function.isGetProp()) {
478 // We are only interested in calls on object references that are
479 // properties. We don't need to eliminate method calls on variables
480 // that are getting removed, since that's already done by the code
481 // that removes all references to those variables.
482 return false;
483 }
484
485 if (parent != null && parent.isName()) {
486 Node gramps = parent.getParent();
487 if (gramps != null && gramps.isVar()) {
488 // The call's return value is being used to initialize a newly
489 // declared variable. We should leave the call intact for now.
490 // That way, when the traversal reaches the variable declaration,
491 // we'll recognize that the variable and all references to it need
492 // to be eliminated.
493 return false;
494 }
495 }
496
497 Node callee = function.getFirstChild();
498 return nameEndsWithFieldNameToStrip(callee) ||
499 nameEndsWithFieldNameToStrip(function) ||
500 qualifiedNameBeginsWithStripType(function) ||
501 actsOnStripType(t, n);
502 }
503
504 /**
505 * Gets whether a name ends with a field name that should be stripped. For
506 * example, this function would return true when passed "this.logger" or
507 * "a.b.c.myLogger" if "logger" is a strip name.
508 *
509 * @param n A node (typically a GETPROP node)
510 * @return Whether the name ends with a field name that should be stripped
511 */
512 boolean nameEndsWithFieldNameToStrip(@Nullable Node n) {
513 if (n != null && n.isGetProp()) {
514 Node propNode = n.getLastChild();
515 return propNode != null && propNode.isString() &&
516 isStripName(propNode.getString());
517 }
518 return false;
519 }
520
521 /**
522 * Determines whether the given node helps to define a
523 * strip type. For example, goog.inherits(stripType, Object)
524 * would be such a call.
525 *
526 * Also reports an error if a non-strip type inherits from a strip type.
527 *
528 * @param t The current traversal
529 * @param callNode The CALL node
530 */
531 private boolean actsOnStripType(NodeTraversal t, Node callNode) {
532 SubclassRelationship classes =
533 compiler.getCodingConvention().getClassesDefinedByCall(callNode);
534 if (classes != null) {
535 // It's okay to strip a type that inherits from a non-stripped type
536 // e.g. goog.inherits(goog.debug.Logger, Object)
537 if (qualifiedNameBeginsWithStripType(classes.subclassName)) {
538 return true;
539 }
540
541 // report an error if a non-strip type inherits from a
542 // strip type.
543 if (qualifiedNameBeginsWithStripType(classes.superclassName)) {
544 t.report(callNode, STRIP_TYPE_INHERIT_ERROR,
545 classes.subclassName, classes.superclassName);
546 }
547 }
548
549 return false;
550 }
551
552 /**
553 * Gets whether a JavaScript identifier is the name of a variable or
554 * property that should be stripped.
555 *
556 * @param name A JavaScript identifier
557 * @return Whether {@code name} is a name that triggers removal
558 */
559 boolean isStripName(String name) {
560 if (stripNameSuffixes.contains(name) ||
561 stripNamePrefixes.contains(name)) {
562 return true;
563 }
564
565 if ((name.length() == 0) || Character.isUpperCase(name.charAt(0))) {
566 return false;
567 }
568
569 String lcName = name.toLowerCase();
570 for (String stripName : stripNamePrefixes) {
571 if (lcName.startsWith(stripName.toLowerCase())) {
572 return true;
573 }
574 }
575
576 for (String stripName : stripNameSuffixes) {
577 if (lcName.endsWith(stripName.toLowerCase())) {
578 return true;
579 }
580 }
581
582 return false;
583 }
584
585 /**
586 * Replaces a node with a NULL node. This is useful where a value is
587 * expected.
588 *
589 * @param n A node
590 * @param parent {@code n}'s parent
591 */
592 void replaceWithNull(Node n, Node parent) {
593 parent.replaceChild(n, IR.nullNode());
594 }
595
596 /**
597 * Replaces a node with an EMPTY node. This is useful where a statement is
598 * expected.
599 *
600 * @param n A node
601 * @param parent {@code n}'s parent
602 */
603 void replaceWithEmpty(Node n, Node parent) {
604 NodeUtil.removeChild(parent, n);
605 }
606 }
607 }