| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.google.javascript.jscomp; |
| 18 |
|
| 19 |
import com.google.common.base.Preconditions; |
| 20 |
import com.google.common.collect.Lists; |
| 21 |
import com.google.javascript.rhino.IR; |
| 22 |
import com.google.javascript.rhino.Node; |
| 23 |
import com.google.javascript.rhino.Token; |
| 24 |
|
| 25 |
import java.util.List; |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
class AstChangeProxy { |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
interface ChangeListener { |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
void nodeRemoved(Node node); |
| 44 |
} |
| 45 |
|
| 46 |
private final List<ChangeListener> listeners; |
| 47 |
|
| 48 |
AstChangeProxy() { |
| 49 |
listeners = Lists.newArrayList(); |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
final void registerListener(ChangeListener listener) { |
| 56 |
listeners.add(listener); |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
final void unregisterListener(ChangeListener listener) { |
| 63 |
listeners.remove(listener); |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
private void notifyOfRemoval(Node node) { |
| 70 |
for (ChangeListener listener : listeners) { |
| 71 |
listener.nodeRemoved(node); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
final void removeChild(Node parent, Node node) { |
| 79 |
parent.removeChild(node); |
| 80 |
|
| 81 |
notifyOfRemoval(node); |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
final void replaceWith(Node parent, Node node, Node replacement) { |
| 88 |
replaceWith(parent, node, Lists.newArrayList(replacement)); |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
final void replaceWith(Node parent, Node node, List<Node> replacements) { |
| 95 |
Preconditions.checkNotNull(replacements, "\"replacements\" is null."); |
| 96 |
|
| 97 |
int size = replacements.size(); |
| 98 |
|
| 99 |
if ((size == 1) && node.isEquivalentTo(replacements.get(0))) { |
| 100 |
|
| 101 |
return; |
| 102 |
} |
| 103 |
|
| 104 |
int parentType = parent.getType(); |
| 105 |
|
| 106 |
Preconditions.checkState(size == 1 || |
| 107 |
parentType == Token.BLOCK || |
| 108 |
parentType == Token.SCRIPT || |
| 109 |
parentType == Token.LABEL); |
| 110 |
|
| 111 |
if (parentType == Token.LABEL && size != 1) { |
| 112 |
Node block = IR.block(); |
| 113 |
for (Node newChild : replacements) { |
| 114 |
newChild.copyInformationFrom(node); |
| 115 |
block.addChildToBack(newChild); |
| 116 |
} |
| 117 |
parent.replaceChild(node, block); |
| 118 |
} else { |
| 119 |
for (Node newChild : replacements) { |
| 120 |
newChild.copyInformationFrom(node); |
| 121 |
parent.addChildBefore(newChild, node); |
| 122 |
} |
| 123 |
parent.removeChild(node); |
| 124 |
} |
| 125 |
notifyOfRemoval(node); |
| 126 |
} |
| 127 |
} |