Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2011 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.ImmutableSet;
21 import com.google.common.collect.Lists;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
24 import com.google.javascript.jscomp.Scope.Var;
25 import com.google.javascript.rhino.IR;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.Token;
28
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Set;
32 import java.util.logging.Logger;
33
34 /**
35 * Replace known jQuery aliases and methods with standard
36 * conventions so that the compiler recognizes them. Expected
37 * replacements include:
38 * - jQuery.fn -> jQuery.prototype
39 * - jQuery.extend -> expanded into direct object assignments
40 * - jQuery.expandedEach -> expand into direct assignments
41 *
42 * @author [email protected] (Chad Killingsworth)
43 */
44 class ExpandJqueryAliases extends AbstractPostOrderCallback
45 implements CompilerPass {
46 private final AbstractCompiler compiler;
47 private final CodingConvention convention;
48 private static final Logger logger =
49 Logger.getLogger(ExpandJqueryAliases.class.getName());
50
51 static final DiagnosticType JQUERY_UNABLE_TO_EXPAND_INVALID_LIT_ERROR =
52 DiagnosticType.warning("JSC_JQUERY_UNABLE_TO_EXPAND_INVALID_LIT",
53 "jQuery.expandedEach call cannot be expanded because the first " +
54 "argument must be an object literal or an array of strings " +
55 "literal.");
56
57 static final DiagnosticType JQUERY_UNABLE_TO_EXPAND_INVALID_NAME_ERROR =
58 DiagnosticType.error("JSC_JQUERY_UNABLE_TO_EXPAND_INVALID_NAME",
59 "jQuery.expandedEach expansion would result in the invalid " +
60 "property name \"{0}\".");
61
62 static final DiagnosticType JQUERY_USELESS_EACH_EXPANSION =
63 DiagnosticType.warning("JSC_JQUERY_USELESS_EACH_EXPANSION",
64 "jQuery.expandedEach was not expanded as no valid property " +
65 "assignments were encountered. Consider using jQuery.each instead.");
66
67 private static final Set<String> JQUERY_EXTEND_NAMES = ImmutableSet.of(
68 "jQuery.extend", "jQuery.fn.extend", "jQuery.prototype.extend");
69
70 private static final String JQUERY_EXPANDED_EACH_NAME =
71 "jQuery.expandedEach";
72
73 private final PeepholeOptimizationsPass peepholePasses;
74
75 ExpandJqueryAliases(AbstractCompiler compiler) {
76 this.compiler = compiler;
77 this.convention = compiler.getCodingConvention();
78
79 // All of the "early" peephole optimizations.
80 // These passes should make the code easier to analyze.
81 // Passes, such as StatementFusion, are omitted for this reason.
82 final boolean late = false;
83 this.peepholePasses = new PeepholeOptimizationsPass(compiler,
84 new PeepholeSubstituteAlternateSyntax(late),
85 new PeepholeReplaceKnownMethods(late),
86 new PeepholeRemoveDeadCode(),
87 new PeepholeFoldConstants(late),
88 new PeepholeCollectPropertyAssignments());
89 }
90
91 /**
92 * Check that Node n is a call to one of the jQuery.extend methods that we
93 * can expand. Valid calls are single argument calls where the first argument
94 * is an object literal or two argument calls where the first argument
95 * is a name and the second argument is an object literal.
96 */
97 public static boolean isJqueryExtendCall(Node n, String qname,
98 AbstractCompiler compiler) {
99 if (JQUERY_EXTEND_NAMES.contains(qname)) {
100 Node firstArgument = n.getNext();
101 if (firstArgument == null) {
102 return false;
103 }
104
105 Node secondArgument = firstArgument.getNext();
106 if ((firstArgument.isObjectLit() && secondArgument == null) ||
107 (firstArgument.isName() || NodeUtil.isGet(firstArgument) &&
108 !NodeUtil.mayHaveSideEffects(firstArgument, compiler) &&
109 secondArgument != null && secondArgument.isObjectLit() &&
110 secondArgument.getNext() == null)) {
111 return true;
112 }
113 }
114 return false;
115 }
116
117 public boolean isJqueryExpandedEachCall(Node call, String qName) {
118 Preconditions.checkArgument(call.isCall());
119 if (call.getFirstChild() != null &&
120 JQUERY_EXPANDED_EACH_NAME.equals(qName)) {
121 return true;
122 }
123 return false;
124 }
125
126 @Override
127 public void visit(NodeTraversal t, Node n, Node parent) {
128 if (n.isGetProp() && convention.isPrototypeAlias(n)) {
129 maybeReplaceJqueryPrototypeAlias(n);
130
131 } else if (n.isCall()) {
132 Node callTarget = n.getFirstChild();
133 String qName = callTarget.getQualifiedName();
134
135 if (isJqueryExtendCall(callTarget, qName, this.compiler)) {
136 maybeExpandJqueryExtendCall(n);
137
138 } else if (isJqueryExpandedEachCall(n, qName)) {
139 maybeExpandJqueryEachCall(t, n);
140 }
141 }
142 }
143
144 @Override
145 public void process(Node externs, Node root) {
146 logger.fine("Expanding Jquery Aliases");
147
148 NodeTraversal.traverse(compiler, root, this);
149 }
150
151 private void maybeReplaceJqueryPrototypeAlias(Node n) {
152 // Check to see if this is the assignment of the original alias.
153 // If so, leave it intact.
154 if(NodeUtil.isLValue(n)) {
155 Node maybeAssign = n.getParent();
156 while (!NodeUtil.isStatement(maybeAssign) && !maybeAssign.isAssign()) {
157 maybeAssign = maybeAssign.getParent();
158 }
159
160 if (maybeAssign.isAssign()) {
161 maybeAssign = maybeAssign.getParent();
162 if (maybeAssign.isBlock() || maybeAssign.isScript() ||
163 NodeUtil.isStatement(maybeAssign)) {
164 return;
165 }
166 }
167 }
168
169 Node fn = n.getLastChild();
170 if (fn != null) {
171 n.replaceChild(fn, IR.string("prototype"));
172 compiler.reportCodeChange();
173 }
174 }
175
176 /**
177 * Expand jQuery.extend (and derivative) calls into direct object assignments
178 * Example: jQuery.extend(obj1, {prop1: val1, prop2: val2}) ->
179 * obj1.prop1 = val1;
180 * obj1.prop2 = val2;
181 */
182 private void maybeExpandJqueryExtendCall(Node n) {
183 Node callTarget = n.getFirstChild();
184 Node objectToExtend = callTarget.getNext(); // first argument
185 Node extendArg = objectToExtend.getNext(); // second argument
186 boolean ensureObjectDefined = true;
187
188 if (extendArg == null) {
189 // Only one argument was specified, so extend jQuery namespace
190 extendArg = objectToExtend;
191 objectToExtend = callTarget.getFirstChild();
192 ensureObjectDefined = false;
193 } else if (objectToExtend.isGetProp() &&
194 (objectToExtend.getLastChild().getString().equals("prototype") ||
195 convention.isPrototypeAlias(objectToExtend))) {
196 ensureObjectDefined = false;
197 }
198
199 // Check for an empty object literal
200 if (!extendArg.hasChildren()) {
201 return;
202 }
203
204 // Since we are expanding jQuery.extend calls into multiple statements,
205 // encapsulate the new statements in a new block.
206 Node fncBlock = IR.block().srcref(n);
207
208 if (ensureObjectDefined) {
209 Node assignVal = IR.or(objectToExtend.cloneTree(),
210 IR.objectlit().srcref(n)).srcref(n);
211 Node assign = IR.assign(objectToExtend.cloneTree(), assignVal).srcref(n);
212 fncBlock.addChildrenToFront(IR.exprResult(assign).srcref(n));
213 }
214
215 while (extendArg.hasChildren()) {
216 Node currentProp = extendArg.removeFirstChild();
217 currentProp.setType(Token.STRING);
218
219 Node propValue = currentProp.removeFirstChild();
220
221 Node newProp;
222 if(currentProp.isQuotedString()) {
223 newProp = IR.getelem(objectToExtend.cloneTree(),
224 currentProp).srcref(currentProp);
225 } else {
226 newProp = IR.getprop(objectToExtend.cloneTree(),
227 currentProp).srcref(currentProp);
228 }
229
230 Node assignNode = IR.assign(newProp, propValue).srcref(currentProp);
231 fncBlock.addChildToBack(IR.exprResult(assignNode).srcref(currentProp));
232 }
233
234 // Check to see if the return value is used. If not, replace the original
235 // call with new block. Otherwise, wrap the statements in an
236 // immediately-called anonymous function.
237 if (n.getParent().isExprResult()) {
238 Node parent = n.getParent();
239 parent.getParent().replaceChild(parent, fncBlock);
240 } else {
241 Node targetVal;
242 if ("jQuery.prototype".equals(objectToExtend.getQualifiedName())) {
243 // When extending the jQuery prototype, return the jQuery namespace.
244 // This is not commonly used.
245 targetVal = objectToExtend.removeFirstChild();
246 } else {
247 targetVal = objectToExtend.detachFromParent();
248 }
249 fncBlock.addChildToBack(IR.returnNode(targetVal).srcref(targetVal));
250
251 Node fnc = IR.function(IR.name("").srcref(n),
252 IR.paramList().srcref(n),
253 fncBlock);
254 n.replaceChild(callTarget, fnc);
255 n.putBooleanProp(Node.FREE_CALL, true);
256
257 // remove any other pre-existing call arguments
258 while(fnc.getNext() != null) {
259 n.removeChildAfter(fnc);
260 }
261 }
262 compiler.reportCodeChange();
263 }
264
265 /**
266 * Expand a jQuery.expandedEach call
267 *
268 * Expanded jQuery.expandedEach calls will replace the GETELEM nodes of a
269 * property assignment with GETPROP nodes to allow for renaming.
270 */
271 private void maybeExpandJqueryEachCall(NodeTraversal t, Node n) {
272 Node objectToLoopOver = n.getChildAtIndex(1);
273
274 if (objectToLoopOver == null) {
275 return;
276 }
277
278 Node callbackFunction = objectToLoopOver.getNext();
279 if (callbackFunction == null || !callbackFunction.isFunction()) {
280 return;
281 }
282
283 // Run the peephole optimizations on the first argument to handle
284 // cases like ("a " + "b").split(" ")
285 peepholePasses.process(null, n.getChildAtIndex(1));
286
287 // Create a reference tree
288 Node nClone = n.cloneTree();
289
290 objectToLoopOver = nClone.getChildAtIndex(1);
291
292 // Check to see if the first argument is something we recognize and can
293 // expand.
294 if (!objectToLoopOver.isObjectLit() &&
295 !(objectToLoopOver.isArrayLit() &&
296 isArrayLitValidForExpansion(objectToLoopOver))) {
297 t.report(n, JQUERY_UNABLE_TO_EXPAND_INVALID_LIT_ERROR, (String)null);
298 return;
299 }
300
301 // Find all references to the callback function arguments
302 List<Node> keyNodeReferences = Lists.newArrayList();
303 List<Node> valueNodeReferences = Lists.newArrayList();
304
305 NodeTraversal.traverse(compiler,
306 NodeUtil.getFunctionBody(callbackFunction),
307 new FindCallbackArgumentReferences(callbackFunction,
308 keyNodeReferences, valueNodeReferences,
309 objectToLoopOver.isArrayLit()));
310
311 if(keyNodeReferences.size() == 0) {
312 // We didn't do anything useful ...
313 t.report(n, JQUERY_USELESS_EACH_EXPANSION, (String)null);
314 return;
315 }
316
317 Node fncBlock = tryExpandJqueryEachCall(t, nClone, callbackFunction,
318 keyNodeReferences, valueNodeReferences);
319
320 if (fncBlock != null && fncBlock.hasChildren()) {
321 replaceOriginalJqueryEachCall(n, fncBlock);
322 } else {
323 // We didn't do anything useful ...
324 t.report(n, JQUERY_USELESS_EACH_EXPANSION, (String)null);
325 }
326 }
327
328 private Node tryExpandJqueryEachCall(NodeTraversal t, Node n,
329 Node callbackFunction, List<Node> keyNodes, List<Node> valueNodes) {
330
331 Node callTarget = n.getFirstChild();
332 Node objectToLoopOver = callTarget.getNext();
333
334 // New block to contain the expanded statements
335 Node fncBlock = IR.block().srcref(callTarget);
336
337 boolean isValidExpansion = true;
338
339 // Expand the jQuery.expandedEach call
340 Node key = objectToLoopOver.getFirstChild(), val = null;
341 for(int i = 0; key != null; key = key.getNext(), i++) {
342 if (key != null) {
343 if (objectToLoopOver.isArrayLit()) {
344 // Arrays have a value of their index number
345 val = IR.number(i).srcref(key);
346 } else {
347 val = key.getFirstChild();
348 }
349 }
350
351 // Keep track of the replaced nodes so we can reset the tree
352 List<Node> newKeys = Lists.newArrayList();
353 List<Node> newValues = Lists.newArrayList();
354 List<Node> origGetElems = Lists.newArrayList();
355 List<Node> newGetProps = Lists.newArrayList();
356
357 // Replace all of the key nodes with the prop name
358 for (int j = 0; j < keyNodes.size(); j++) {
359 Node origNode = keyNodes.get(j);
360 Node ancestor = origNode.getParent();
361
362 Node newNode = IR.string(key.getString()).srcref(key);
363 newKeys.add(newNode);
364 ancestor.replaceChild(origNode, newNode);
365
366 // Walk up the tree to see if the key is used in a GETELEM
367 // assignment
368 while (ancestor != null && !NodeUtil.isStatement(ancestor) &&
369 !ancestor.isGetElem()) {
370 ancestor = ancestor.getParent();
371 }
372
373 // Convert GETELEM nodes to GETPROP nodes so that they can be
374 // renamed or removed.
375 if (ancestor != null && ancestor.isGetElem()) {
376
377 Node propObject = ancestor;
378 while (propObject.isGetProp() || propObject.isGetElem()) {
379 propObject = propObject.getFirstChild();
380 }
381
382 Node ancestorClone = ancestor.cloneTree();
383 // Run the peephole passes to handle cases such as
384 // obj['lit' + key] = val;
385 peepholePasses.process(null, ancestorClone.getChildAtIndex(1));
386 Node prop = ancestorClone.getChildAtIndex(1);
387
388 if (prop.isString() &&
389 NodeUtil.isValidPropertyName(prop.getString())) {
390 Node target = ancestorClone.getFirstChild();
391 Node newGetProp = IR.getprop(target.detachFromParent(),
392 prop.detachFromParent());
393 newGetProps.add(newGetProp);
394 origGetElems.add(ancestor);
395 ancestor.getParent().replaceChild(ancestor, newGetProp);
396 } else {
397 if (prop.isString() &&
398 !NodeUtil.isValidPropertyName(prop.getString())) {
399 t.report(n,
400 JQUERY_UNABLE_TO_EXPAND_INVALID_NAME_ERROR,
401 prop.getString());
402 }
403 isValidExpansion = false;
404 }
405 }
406 }
407
408 if (isValidExpansion) {
409 // Replace all of the value nodes with the prop value
410 for (int j = 0; val != null && j < valueNodes.size(); j++) {
411 Node origNode = valueNodes.get(j);
412 Node newNode = val.cloneTree();
413 newValues.add(newNode);
414 origNode.getParent().replaceChild(origNode, newNode);
415 }
416
417 // Wrap the new tree in an anonymous function call
418 Node fnc = IR.function(IR.name("").srcref(key),
419 IR.paramList().srcref(key),
420 callbackFunction.getChildAtIndex(2).cloneTree()).srcref(key);
421 Node call = IR.call(fnc).srcref(key);
422 call.putBooleanProp(Node.FREE_CALL, true);
423 fncBlock.addChildToBack(IR.exprResult(call).srcref(call));
424 }
425
426 // Reset the source tree
427 for (int j = 0; j < newGetProps.size(); j++) {
428 newGetProps.get(j).getParent().replaceChild(newGetProps.get(j),
429 origGetElems.get(j));
430 }
431 for (int j = 0; j < newKeys.size(); j++) {
432 newKeys.get(j).getParent().replaceChild(newKeys.get(j),
433 keyNodes.get(j));
434 }
435 for (int j = 0; j < newValues.size(); j++) {
436 newValues.get(j).getParent().replaceChild(newValues.get(j),
437 valueNodes.get(j));
438 }
439
440 if (!isValidExpansion) {
441 return null;
442 }
443 }
444 return fncBlock;
445 }
446
447 private void replaceOriginalJqueryEachCall(Node n, Node expandedBlock) {
448 // Check to see if the return value of the original jQuery.expandedEach
449 // call is used. If so, we need to wrap each loop expansion in an anonymous
450 // function and return the original objectToLoopOver.
451 if (n.getParent().isExprResult()) {
452 Node parent = n.getParent();
453 Node grandparent = parent.getParent();
454 Node insertAfter = parent;
455 while (expandedBlock.hasChildren()) {
456 Node child = expandedBlock.getFirstChild().detachFromParent();
457 grandparent.addChildAfter(child, insertAfter);
458 insertAfter = child;
459 }
460 grandparent.removeChild(parent);
461 } else {
462 // Return the original object
463 Node callTarget = n.getFirstChild();
464 Node objectToLoopOver = callTarget.getNext();
465
466 objectToLoopOver.detachFromParent();
467 Node ret = IR.returnNode(objectToLoopOver).srcref(callTarget);
468 expandedBlock.addChildToBack(ret);
469
470 // Wrap all of the expanded loop calls in a new anonymous function
471 Node fnc = IR.function(IR.name("").srcref(callTarget),
472 IR.paramList().srcref(callTarget),
473 expandedBlock);
474 n.replaceChild(callTarget, fnc);
475 n.putBooleanProp(Node.FREE_CALL, true);
476
477 // remove any other pre-existing call arguments
478 while(fnc.getNext() != null) {
479 n.removeChildAfter(fnc);
480 }
481 }
482 compiler.reportCodeChange();
483 }
484
485 private boolean isArrayLitValidForExpansion(Node n) {
486 Iterator<Node> iter = n.children().iterator();
487 while (iter.hasNext()) {
488 Node child = iter.next();
489 if (!child.isString()) {
490 return false;
491 }
492 }
493 return true;
494 }
495
496 /**
497 * Given a jQuery.expandedEach callback function, traverse it and collect any
498 * references to its parameter names.
499 */
500 class FindCallbackArgumentReferences extends AbstractPostOrderCallback
501 implements ScopedCallback {
502
503 private final String keyName;
504 private final String valueName;
505 private Scope startingScope;
506 private List<Node> keyReferences;
507 private List<Node> valueReferences;
508
509 FindCallbackArgumentReferences(Node functionRoot, List<Node> keyReferences,
510 List<Node> valueReferences, boolean useArrayMode) {
511 Preconditions.checkState(functionRoot.isFunction());
512
513 String keyString = null, valueString = null;
514 Node callbackParams = NodeUtil.getFunctionParameters(functionRoot);
515 Node param = callbackParams.getFirstChild();
516 if (param != null) {
517 Preconditions.checkState(param.isName());
518 keyString = param.getString();
519
520 param = param.getNext();
521 if (param != null) {
522 Preconditions.checkState(param.isName());
523 valueString = param.getString();
524 }
525 }
526
527 this.keyName = keyString;
528 this.valueName = valueString;
529
530 // For arrays, the keyString is the index number of the element.
531 // We're interested in the value of the element instead
532 if (useArrayMode) {
533 this.keyReferences = valueReferences;
534 this.valueReferences = keyReferences;
535 } else {
536 this.keyReferences = keyReferences;
537 this.valueReferences = valueReferences;
538 }
539
540 this.startingScope = null;
541 }
542
543 private boolean isShadowed(String name, Scope scope) {
544 Var nameVar = scope.getVar(name);
545 return nameVar != null &&
546 nameVar.getScope() != this.startingScope;
547 }
548
549 @Override
550 public void visit(NodeTraversal t, Node n, Node parent) {
551 // In the top scope, "this" is a reference to "value"
552 boolean isThis = false;
553 if (t.getScope() == this.startingScope) {
554 isThis = n.isThis();
555 }
556
557 if (isThis || n.isName() && !isShadowed(n.getString(), t.getScope())) {
558 String nodeValue = isThis ? null : n.getString();
559 if (!isThis && keyName != null && nodeValue.equals(keyName)) {
560 keyReferences.add(n);
561 } else if (isThis || (valueName != null &&
562 nodeValue.equals(valueName))) {
563 valueReferences.add(n);
564 }
565 }
566 }
567
568 /**
569 * As we enter each scope, make sure that the scope doesn't define
570 * a local variable with the same name as our original callback method
571 * parameter names.
572 */
573 @Override
574 public void enterScope(NodeTraversal t) {
575 if (this.startingScope == null) {
576 this.startingScope = t.getScope();
577 }
578 }
579
580 @Override
581 public void exitScope(NodeTraversal t) { }
582 }
583 }