Debian Codegraph @

src/com/google/javascript/jscomp/PeepholeCollectPropertyAssignments.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.javascript.rhino.IR;
21 import com.google.javascript.rhino.Token;
22 import com.google.javascript.rhino.Node;
23
24 /**
25 * A pass that looks for assignments to properties of an object or array
26 * immediately following its creation using the abbreviated syntax.
27 * <p>
28 * E.g. {@code var a = [];a[0] = 0} is optimized to {@code var a = [0]} and
29 * similarly for the object constructor.
30 *
31 */
32 public class PeepholeCollectPropertyAssignments
33 extends AbstractPeepholeOptimization {
34
35 @Override
36 Node optimizeSubtree(Node subtree) {
37 if (!subtree.isScript() && !subtree.isBlock()) {
38 return subtree;
39 }
40
41 boolean codeChanged = false;
42
43 // Look for variable declarations or simple assignments
44 // and start processing there.
45 for (Node child = subtree.getFirstChild();
46 child != null; child = child.getNext()) {
47 if (!child.isVar() && !NodeUtil.isExprAssign(child)) {
48 continue;
49 }
50 if (!isPropertyAssignmentToName(child.getNext())) {
51 // Quick check to see if there's anything to collapse.
52 continue;
53 }
54
55 Preconditions.checkState(child.hasOneChild());
56 Node name = getName(child);
57 if (!name.isName()) {
58 // The assignment target is not a simple name.
59 continue;
60 }
61 Node value = getValue(child);
62 if (value == null || !isInterestingValue(value)) {
63 // No initializer or not an Object or Array literal.
64 continue;
65 }
66
67 Node propertyCandidate;
68 while ((propertyCandidate = child.getNext()) != null) {
69 // This does not infinitely loop because collectProperty always
70 // removes propertyCandidate from its parent when it returns true.
71 if (!collectProperty(propertyCandidate, name.getString(), value)) {
72 break;
73 }
74 codeChanged = true;
75 }
76 }
77
78 if (codeChanged) {
79 reportCodeChange();
80 }
81 return subtree;
82 }
83
84 private Node getName(Node n) {
85 if (n.isVar()) {
86 return n.getFirstChild();
87 } else if (NodeUtil.isExprAssign(n)) {
88 return n.getFirstChild().getFirstChild();
89 }
90 throw new IllegalStateException();
91 }
92
93 private Node getValue(Node n) {
94 if (n.isVar()) {
95 return n.getFirstChild().getFirstChild();
96 } else if (NodeUtil.isExprAssign(n)) {
97 return n.getFirstChild().getLastChild();
98 }
99 throw new IllegalStateException();
100 }
101
102 boolean isInterestingValue(Node n) {
103 return n.isObjectLit() || n.isArrayLit();
104 }
105
106 private boolean isPropertyAssignmentToName(Node propertyCandidate) {
107 if (propertyCandidate == null) { return false; }
108 // Must be an assignment...
109 if (!NodeUtil.isExprAssign(propertyCandidate)) {
110 return false;
111 }
112
113 Node expr = propertyCandidate.getFirstChild();
114
115 // to a property...
116 Node lhs = expr.getFirstChild();
117 if (!NodeUtil.isGet(lhs)) {
118 return false;
119 }
120
121 // of a variable.
122 Node obj = lhs.getFirstChild();
123 if (!obj.isName()) {
124 return false;
125 }
126
127 return true;
128 }
129
130 private boolean collectProperty(
131 Node propertyCandidate, String name, Node value) {
132 if (!isPropertyAssignmentToName(propertyCandidate)) {
133 return false;
134 }
135
136 Node lhs = propertyCandidate.getFirstChild().getFirstChild();
137 // Must be an assignment to the recent variable...
138 if (!name.equals(lhs.getFirstChild().getString())) {
139 return false;
140 }
141
142 Node rhs = lhs.getNext();
143 // with a value that cannot change the values of the variables,
144 if (mayHaveSideEffects(rhs)
145 || NodeUtil.canBeSideEffected(rhs)) {
146 return false;
147 }
148 // and does not have a reference to a variable initialized after it.
149 if (!NodeUtil.isLiteralValue(rhs, true)
150 && mightContainForwardReference(rhs, name)) {
151 return false;
152 }
153
154 switch (value.getType()) {
155 case Token.ARRAYLIT:
156 if (!collectArrayProperty(value, propertyCandidate)) {
157 return false;
158 }
159 break;
160 case Token.OBJECTLIT:
161 if (!collectObjectProperty(value, propertyCandidate)) {
162 return false;
163 }
164 break;
165 default:
166 throw new IllegalStateException();
167 }
168 return true;
169 }
170
171
172 private boolean collectArrayProperty(
173 Node arrayLiteral, Node propertyCandidate) {
174 Node assignment = propertyCandidate.getFirstChild();
175 final int sizeOfArrayAtStart = arrayLiteral.getChildCount();
176 int maxIndexAssigned = sizeOfArrayAtStart - 1;
177
178 Node lhs = assignment.getFirstChild();
179 Node rhs = lhs.getNext();
180 if (!lhs.isGetElem()) {
181 return false;
182 }
183 Node obj = lhs.getFirstChild();
184 Node property = obj.getNext();
185 // The left hand side must have a numeric index
186 if (!property.isNumber()) {
187 return false;
188 }
189 // that is a valid array index
190 double dindex = property.getDouble();
191 if (!(dindex >= 0) // Handles NaN and negatives.
192 || Double.isInfinite(dindex) || dindex > 0x7fffffffL) {
193 return false;
194 }
195 int index = (int) dindex;
196 if (dindex != index) {
197 return false;
198 }
199 // that would not make the array so sparse that they take more space
200 // when rendered than x[9]=1.
201 if (maxIndexAssigned + 4 < index) {
202 return false;
203 }
204 if (index > maxIndexAssigned) {
205 while (maxIndexAssigned < index - 1) {
206 // Pad the array if it is sparse.
207 // So if array is [0] and integer 3 is assigned at index is 2, then
208 // we want to produce [0,,2].
209 Node emptyNode = IR.empty().srcref(arrayLiteral);
210 arrayLiteral.addChildToBack(emptyNode);
211 ++maxIndexAssigned;
212 }
213 arrayLiteral.addChildToBack(rhs.detachFromParent());
214 } else {
215 // An out of order assignment. Allow it if it's a hole.
216 Node currentValue = arrayLiteral.getChildAtIndex(index);
217 if (!currentValue.isEmpty()) {
218 // We've already collected a value for this index.
219 return false;
220 }
221 arrayLiteral.replaceChild(currentValue, rhs.detachFromParent());
222 }
223
224 propertyCandidate.detachFromParent();
225 return true;
226 }
227
228 private boolean collectObjectProperty(
229 Node objectLiteral, Node propertyCandidate) {
230 Node assignment = propertyCandidate.getFirstChild();
231 Node lhs = assignment.getFirstChild(), rhs = lhs.getNext();
232 Node obj = lhs.getFirstChild();
233 Node property = obj.getNext();
234
235 // The property must be statically known.
236 if (lhs.isGetElem()
237 && (!property.isString()
238 && !property.isNumber())) {
239 return false;
240 }
241
242 String propertyName;
243 if (property.isNumber()) {
244 propertyName = NodeUtil.getStringValue(property);
245 } else {
246 propertyName = property.getString();
247 }
248
249 Node newProperty = IR.stringKey(propertyName)
250 .copyInformationFrom(property);
251 // Preserve the quotedness of a property reference
252 if (lhs.isGetElem()) {
253 newProperty.setQuotedString();
254 }
255 Node newValue = rhs.detachFromParent();
256 newProperty.addChildToBack(newValue);
257 objectLiteral.addChildToBack(newProperty);
258
259 propertyCandidate.detachFromParent();
260 return true;
261 }
262
263
264 private static boolean mightContainForwardReference(
265 Node node, String varName) {
266 if (node.isName()) {
267 return varName.equals(node.getString());
268 }
269 for (Node child = node.getFirstChild(); child != null;
270 child = child.getNext()) {
271 if (mightContainForwardReference(child, varName)) {
272 return true;
273 }
274 }
275 return false;
276 }
277
278 }