| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
package com.google.javascript.jscomp; |
| 17 |
|
| 18 |
import com.google.common.base.Preconditions; |
| 19 |
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; |
| 20 |
import com.google.javascript.rhino.Node; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
class CollapseAnonymousFunctions implements CompilerPass { |
| 39 |
private final AbstractCompiler compiler; |
| 40 |
|
| 41 |
public CollapseAnonymousFunctions(AbstractCompiler compiler) { |
| 42 |
Preconditions.checkArgument(compiler.getLifeCycleStage().isNormalized()); |
| 43 |
this.compiler = compiler; |
| 44 |
} |
| 45 |
|
| 46 |
@Override |
| 47 |
public void process(Node externs, Node root) { |
| 48 |
NodeTraversal.traverse(compiler, root, new Callback()); |
| 49 |
} |
| 50 |
|
| 51 |
private class Callback extends AbstractPostOrderCallback { |
| 52 |
@Override |
| 53 |
public void visit(NodeTraversal t, Node n, Node parent) { |
| 54 |
if (!n.isVar()) { |
| 55 |
return; |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
Node grandparent = parent.getParent(); |
| 65 |
if (!(parent.isScript() || |
| 66 |
grandparent != null && |
| 67 |
grandparent.isFunction() && |
| 68 |
parent.isBlock())) { |
| 69 |
return; |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
Preconditions.checkState(n.hasOneChild()); |
| 75 |
Node name = n.getFirstChild(); |
| 76 |
Node value = name.getFirstChild(); |
| 77 |
if (value != null && |
| 78 |
value.isFunction() && |
| 79 |
!isRecursiveFunction(value)) { |
| 80 |
Node fnName = value.getFirstChild(); |
| 81 |
fnName.setString(name.getString()); |
| 82 |
NodeUtil.copyNameAnnotations(name, fnName); |
| 83 |
name.removeChild(value); |
| 84 |
parent.replaceChild(n, value); |
| 85 |
|
| 86 |
|
| 87 |
if (!t.inGlobalScope() && |
| 88 |
NodeUtil.isHoistedFunctionDeclaration(value)) { |
| 89 |
parent.addChildToFront(value.detachFromParent()); |
| 90 |
} |
| 91 |
|
| 92 |
compiler.reportCodeChange(); |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
private boolean isRecursiveFunction(Node function) { |
| 97 |
Node name = function.getFirstChild(); |
| 98 |
if (name.getString().isEmpty()) { |
| 99 |
return false; |
| 100 |
} |
| 101 |
Node args = name.getNext(); |
| 102 |
Node body = args.getNext(); |
| 103 |
return containsName(body, name.getString()); |
| 104 |
} |
| 105 |
|
| 106 |
private boolean containsName(Node n, String name) { |
| 107 |
if (n.isName() && n.getString().equals(name)) { |
| 108 |
return true; |
| 109 |
} |
| 110 |
|
| 111 |
for (Node child : n.children()) { |
| 112 |
if (containsName(child, name)) { |
| 113 |
return true; |
| 114 |
} |
| 115 |
} |
| 116 |
return false; |
| 117 |
} |
| 118 |
} |
| 119 |
} |