Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2012 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 package com.google.javascript.jscomp;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Sets;
21 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
22 import com.google.javascript.jscomp.TypeValidator.TypeMismatch;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.JSDocInfo;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.jstype.FunctionType;
27 import com.google.javascript.rhino.jstype.JSType;
28 import com.google.javascript.rhino.jstype.JSTypeNative;
29 import com.google.javascript.rhino.jstype.JSTypeRegistry;
30 import com.google.javascript.rhino.jstype.ObjectType;
31
32 import java.util.Map;
33 import java.util.Set;
34
35
36 /**
37 * InlineProperties attempts to find references to properties that are known to
38 * be constants and inline the known value.
39 *
40 * This pass relies on type information to find these property references and
41 * properties are assumed to be constant if either:
42 * - the property is assigned unconditionally in the instance constructor
43 * - the property is assigned unconditionally to the type's prototype
44 *
45 * The current implementation only inlines immutable values (as defined by
46 * NodeUtil.isImmutableValue).
47 *
48 * @author [email protected] (John Lenz)
49 */
50 public class InlineProperties implements CompilerPass {
51
52 private final AbstractCompiler compiler;
53
54 static class PropertyInfo {
55 PropertyInfo(JSType type, Node value) {
56 this.type = type;
57 this.value = value;
58 }
59 final JSType type;
60 final Node value;
61 }
62
63 private static final PropertyInfo INVALIDATED = new PropertyInfo(
64 null, null);
65
66 private final Map<String, PropertyInfo> props = Maps.newHashMap();
67
68 private Set<JSType> invalidatingTypes;
69
70 InlineProperties(AbstractCompiler compiler) {
71 this.compiler = compiler;
72 buildInvalidatingTypeSet();
73 }
74
75 // TODO(johnlenz): this is a direct copy of the invalidation code
76 // from AmbiguateProperties, if in the end we don't need to modify it
77 // we should move it to a common location.
78 private void buildInvalidatingTypeSet() {
79 JSTypeRegistry registry = compiler.getTypeRegistry();
80 invalidatingTypes = Sets.newHashSet(
81 registry.getNativeType(JSTypeNative.ALL_TYPE),
82 registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE),
83 registry.getNativeType(JSTypeNative.NO_TYPE),
84 registry.getNativeType(JSTypeNative.NULL_TYPE),
85 registry.getNativeType(JSTypeNative.VOID_TYPE),
86 registry.getNativeType(JSTypeNative.FUNCTION_FUNCTION_TYPE),
87 registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE),
88 registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE),
89 registry.getNativeType(JSTypeNative.GLOBAL_THIS),
90 registry.getNativeType(JSTypeNative.OBJECT_TYPE),
91 registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE),
92 registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE),
93 registry.getNativeType(JSTypeNative.TOP_LEVEL_PROTOTYPE),
94 registry.getNativeType(JSTypeNative.UNKNOWN_TYPE));
95
96 for (TypeMismatch mis : compiler.getTypeValidator().getMismatches()) {
97 addInvalidatingType(mis.typeA);
98 addInvalidatingType(mis.typeB);
99 }
100 }
101
102 /**
103 * Invalidates the given type, so that no properties on it will be renamed.
104 */
105 private void addInvalidatingType(JSType type) {
106 type = type.restrictByNotNullOrUndefined();
107 if (type.isUnionType()) {
108 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
109 addInvalidatingType(alt);
110 }
111 }
112
113 invalidatingTypes.add(type);
114 ObjectType objType = ObjectType.cast(type);
115 if (objType != null && objType.isInstanceType()) {
116 invalidatingTypes.add(objType.getImplicitPrototype());
117 }
118 }
119
120 /** Returns true if properties on this type should not be renamed. */
121 private boolean isInvalidatingType(JSType type) {
122 if (type.isUnionType()) {
123 type = type.restrictByNotNullOrUndefined();
124 if (type.isUnionType()) {
125 for (JSType alt : type.toMaybeUnionType().getAlternates()) {
126 if (isInvalidatingType(alt)) {
127 return true;
128 }
129 }
130 return false;
131 }
132 }
133 ObjectType objType = ObjectType.cast(type);
134 return objType == null
135 || invalidatingTypes.contains(objType)
136 || !objType.hasReferenceName()
137 || objType.isUnknownType()
138 || objType.isEmptyType() /* unresolved types */
139 || objType.isEnumType()
140 || objType.autoboxesTo() != null;
141 }
142
143 /**
144 * This method gets the JSType from the Node argument and verifies that it is
145 * present.
146 */
147 private JSType getJSType(Node n) {
148 JSType jsType = n.getJSType();
149 if (jsType == null) {
150 return compiler.getTypeRegistry().getNativeType(
151 JSTypeNative.UNKNOWN_TYPE);
152 } else {
153 return jsType;
154 }
155 }
156
157 @Override
158 public void process(Node externs, Node root) {
159 NodeTraversal.traverseRoots(
160 compiler, new GatherCandidates(), externs, root);
161 NodeTraversal.traverseRoots(
162 compiler, new ReplaceCandidates(), externs, root);
163 }
164
165 class GatherCandidates extends AbstractPostOrderCallback {
166
167 @Override
168 public void visit(NodeTraversal t, Node n, Node parent) {
169 boolean invalidatingPropRef = false;
170 String propName = null;
171 if (n.isGetProp()) {
172 propName = n.getLastChild().getString();
173 if (t.getInput().isExtern()) {
174 // Any extern reference invalidates
175 invalidatingPropRef = true;
176 } else if (parent.isAssign()) {
177 invalidatingPropRef = !maybeCandidateDefinition(t, n, parent);
178 } else if (NodeUtil.isLValue(n)) {
179 // Other LValue references invalidate
180 invalidatingPropRef = true;
181 } else if (parent.isDelProp()) {
182 // Deletes invalidate
183 invalidatingPropRef = true;
184 } else {
185 // A property read doesn't invalidate
186 invalidatingPropRef = false;
187 }
188 } else if (n.isStringKey()) {
189 propName = n.getString();
190 if (t.getInput().isExtern()) {
191 // Any extern reference invalidates
192 invalidatingPropRef = true;
193 } else {
194 // For now, any object literal key invalidates
195 // TODO(johnlenz): support prototype properties like:
196 // foo.prototype = { a: 1, b: 2 };
197 invalidatingPropRef = true;
198 }
199 }
200
201 if (invalidatingPropRef) {
202 Preconditions.checkNotNull(propName);
203 invalidateProperty(propName);
204 }
205 }
206
207 /**
208 * @return Whether this is a valid definition for a candidate property.
209 */
210 private boolean maybeCandidateDefinition(
211 NodeTraversal t, Node n, Node parent) {
212 Preconditions.checkState(n.isGetProp() && parent.isAssign());
213 boolean isCandidate = false;
214 Node src = n.getFirstChild();
215 String propName = n.getLastChild().getString();
216
217 Node value = parent.getLastChild();
218 if (src.isThis()) {
219 // This is a simple assignment like:
220 // this.foo = 1;
221 if (inContructor(t)) {
222 // This maybe a valid assignment.
223 isCandidate = maybeStoreCandidateValue(
224 getJSType(src), propName, value);
225 }
226 } else if (t.inGlobalScope()
227 && src.isGetProp()
228 && src.getLastChild().getString().equals("prototype")) {
229 // This is a prototype assignment like:
230 // x.prototype.foo = 1;
231 JSType instanceType = maybeGetInstanceTypeFromPrototypeRef(src);
232 if (instanceType != null) {
233 isCandidate = maybeStoreCandidateValue(
234 instanceType, propName, value);
235 }
236 }
237 return isCandidate;
238 }
239
240 private JSType maybeGetInstanceTypeFromPrototypeRef(Node src) {
241 JSType ownerType = getJSType(src.getFirstChild());
242 if (ownerType.isFunctionType() && ownerType.isConstructor()) {
243 FunctionType functionType = ((FunctionType) ownerType);
244 return functionType.getInstanceType();
245 }
246 return null;
247 }
248
249 private void invalidateProperty(String propName) {
250 props.put(propName, INVALIDATED);
251 }
252
253 private boolean maybeStoreCandidateValue(
254 JSType type, String propName, Node value) {
255 Preconditions.checkNotNull(value);
256 if (!props.containsKey(propName)
257 && !isInvalidatingType(type)
258 && NodeUtil.isImmutableValue(value)
259 && NodeUtil.isExecutedExactlyOnce(value)) {
260 props.put(propName, new PropertyInfo(type, value));
261 return true;
262 }
263 return false;
264 }
265
266 private boolean inContructor(NodeTraversal t) {
267 Node root = t.getScopeRoot();
268 JSDocInfo info = NodeUtil.getBestJSDocInfo(root);
269 return info != null && info.isConstructor();
270 }
271 }
272
273 class ReplaceCandidates extends AbstractPostOrderCallback {
274 @Override
275 public void visit(NodeTraversal t, Node n, Node parent) {
276 if (n.isGetProp() && !NodeUtil.isLValue(n)) {
277 Node target = n.getFirstChild();
278 String propName = n.getLastChild().getString();
279 PropertyInfo info = props.get(propName);
280 if (info != null
281 && info != INVALIDATED
282 && isMatchingType(target, info.type)) {
283 Node replacement = info.value.cloneTree();
284 if (NodeUtil.mayHaveSideEffects(n.getFirstChild(), compiler)) {
285 replacement = IR.comma(n.removeFirstChild(), replacement).srcref(n);
286 }
287 parent.replaceChild(n, replacement);
288 compiler.reportCodeChange();
289 }
290 }
291 }
292
293 private boolean isMatchingType(Node n, JSType src) {
294 src = src.restrictByNotNullOrUndefined();
295 JSType dest = getJSType(n).restrictByNotNullOrUndefined();
296 if (!isInvalidatingType(dest)
297 && dest.isSubtype(src)) {
298 return true;
299 }
300 return false;
301 }
302 }
303 }