-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
InlineProperties.java
317 lines (290 loc) · 11.2 KB
/
InlineProperties.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
* Copyright 2012 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.TypeI;
import com.google.javascript.rhino.TypeIRegistry;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.ObjectType;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* InlineProperties attempts to find references to properties that are known to
* be constants and inline the known value.
*
* This pass relies on type information to find these property references and
* properties are assumed to be constant if either:
* - the property is assigned unconditionally in the instance constructor
* - the property is assigned unconditionally to the type's prototype
*
* The current implementation only inlines immutable values (as defined by
* NodeUtil.isImmutableValue).
*
* @author johnlenz@google.com (John Lenz)
*/
final class InlineProperties implements CompilerPass {
private final AbstractCompiler compiler;
static class PropertyInfo {
PropertyInfo(JSType type, Node value) {
this.type = type;
this.value = value;
}
final JSType type;
final Node value;
}
private static final PropertyInfo INVALIDATED = new PropertyInfo(
null, null);
private final Map<String, PropertyInfo> props = new HashMap<>();
private Set<TypeI> invalidatingTypes;
InlineProperties(AbstractCompiler compiler) {
this.compiler = compiler;
buildInvalidatingTypeSet();
invalidateExternProperties();
}
// TODO(johnlenz): this is a direct copy of the invalidation code
// from AmbiguateProperties, if in the end we don't need to modify it
// we should move it to a common location.
private void buildInvalidatingTypeSet() {
TypeIRegistry registry = compiler.getTypeIRegistry();
invalidatingTypes = new HashSet<>(ImmutableSet.<TypeI>of(
(JSType) registry.getNativeType(JSTypeNative.ALL_TYPE),
(JSType) registry.getNativeType(JSTypeNative.NO_OBJECT_TYPE),
(JSType) registry.getNativeType(JSTypeNative.NO_TYPE),
(JSType) registry.getNativeType(JSTypeNative.NULL_TYPE),
(JSType) registry.getNativeType(JSTypeNative.VOID_TYPE),
(JSType) registry.getNativeType(JSTypeNative.FUNCTION_FUNCTION_TYPE),
(JSType) registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE),
(JSType) registry.getNativeType(JSTypeNative.FUNCTION_PROTOTYPE),
(JSType) registry.getNativeType(JSTypeNative.GLOBAL_THIS),
(JSType) registry.getNativeType(JSTypeNative.OBJECT_TYPE),
(JSType) registry.getNativeType(JSTypeNative.OBJECT_PROTOTYPE),
(JSType) registry.getNativeType(JSTypeNative.OBJECT_FUNCTION_TYPE),
(JSType) registry.getNativeType(JSTypeNative.TOP_LEVEL_PROTOTYPE),
(JSType) registry.getNativeType(JSTypeNative.UNKNOWN_TYPE)));
for (TypeMismatch mis : compiler.getTypeMismatches()) {
addInvalidatingType(mis.typeA);
addInvalidatingType(mis.typeB);
}
}
private void invalidateExternProperties() {
// Invalidate properties defined in externs.
for (String name : compiler.getExternProperties()) {
props.put(name, INVALIDATED);
}
}
/**
* Invalidates the given type, so that no properties on it will be renamed.
*/
private void addInvalidatingType(TypeI type) {
type = type.restrictByNotNullOrUndefined();
if (type.isUnionType()) {
for (TypeI alt : type.getUnionMembers()) {
addInvalidatingType(alt);
}
}
invalidatingTypes.add(type);
ObjectType objType = (ObjectType) type.toMaybeObjectType();
if (objType != null && objType.isInstanceType()) {
invalidatingTypes.add(objType.getImplicitPrototype());
}
}
/** Returns true if properties on this type should not be renamed. */
private boolean isInvalidatingType(JSType type) {
if (type.isUnionType()) {
type = type.restrictByNotNullOrUndefined();
if (type.isUnionType()) {
for (JSType alt : type.toMaybeUnionType().getAlternatesWithoutStructuralTyping()) {
if (isInvalidatingType(alt)) {
return true;
}
}
return false;
}
}
ObjectType objType = ObjectType.cast(type);
return objType == null
|| invalidatingTypes.contains(objType)
|| !objType.hasReferenceName()
|| objType.isUnknownType()
|| objType.isEmptyType() /* unresolved types */
|| objType.isEnumType()
|| objType.autoboxesTo() != null;
}
/**
* This method gets the JSType from the Node argument and verifies that it is
* present.
*/
private JSType getJSType(Node n) {
JSType jsType = n.getJSType();
if (jsType == null) {
return compiler.getTypeIRegistry().getNativeType(JSTypeNative.UNKNOWN_TYPE);
} else {
return jsType;
}
}
@Override
public void process(Node externs, Node root) {
// Find and replace the properties in non-extern AST.
NodeTraversal.traverseEs6(compiler, root, new GatherCandidates());
NodeTraversal.traverseEs6(compiler, root, new ReplaceCandidates());
}
class GatherCandidates extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
boolean invalidatingPropRef = false;
String propName = null;
if (n.isGetProp()) {
propName = n.getLastChild().getString();
if (parent.isAssign()) {
invalidatingPropRef = !maybeCandidateDefinition(t, n, parent);
} else if (NodeUtil.isLValue(n)) {
// Other LValue references invalidate
invalidatingPropRef = true;
} else if (parent.isDelProp()) {
// Deletes invalidate
invalidatingPropRef = true;
} else {
// A property read doesn't invalidate
invalidatingPropRef = false;
}
} else if (n.isStringKey()) {
propName = n.getString();
// For now, any object literal key invalidates
// TODO(johnlenz): support prototype properties like:
// foo.prototype = { a: 1, b: 2 };
// TODO(johnlenz): Object.create(), Object.createProperty
invalidatingPropRef = true;
}
if (invalidatingPropRef) {
Preconditions.checkNotNull(propName);
invalidateProperty(propName);
}
}
/**
* @return Whether this is a valid definition for a candidate property.
*/
private boolean maybeCandidateDefinition(
NodeTraversal t, Node n, Node parent) {
Preconditions.checkState(n.isGetProp() && parent.isAssign(), n);
boolean isCandidate = false;
Node src = n.getFirstChild();
String propName = n.getLastChild().getString();
Node value = parent.getLastChild();
if (src.isThis()) {
// This is a simple assignment like:
// this.foo = 1;
if (inConstructor(t)) {
// This maybe a valid assignment.
isCandidate = maybeStoreCandidateValue(
getJSType(src), propName, value);
}
} else if (t.inGlobalHoistScope()
&& src.isGetProp()
&& src.getLastChild().getString().equals("prototype")) {
// This is a prototype assignment like:
// x.prototype.foo = 1;
JSType instanceType = maybeGetInstanceTypeFromPrototypeRef(src);
if (instanceType != null) {
isCandidate = maybeStoreCandidateValue(
instanceType, propName, value);
}
} else if (t.inGlobalHoistScope()) {
JSType targetType = getJSType(src);
if (targetType != null && targetType.isConstructor()) {
isCandidate = maybeStoreCandidateValue(targetType, propName, value);
}
}
return isCandidate;
}
private JSType maybeGetInstanceTypeFromPrototypeRef(Node src) {
JSType ownerType = getJSType(src.getFirstChild());
if (ownerType.isFunctionType() && ownerType.isConstructor()) {
FunctionType functionType = ((FunctionType) ownerType);
return functionType.getInstanceType();
}
return null;
}
private void invalidateProperty(String propName) {
props.put(propName, INVALIDATED);
}
private boolean maybeStoreCandidateValue(
JSType type, String propName, Node value) {
Preconditions.checkNotNull(value);
if (!props.containsKey(propName)
&& !isInvalidatingType(type)
&& NodeUtil.isImmutableValue(value)
&& NodeUtil.isExecutedExactlyOnce(value)) {
props.put(propName, new PropertyInfo(type, value));
return true;
}
return false;
}
private boolean inConstructor(NodeTraversal t) {
Node root = t.getEnclosingFunction();
if (root == null) {
return false;
}
JSDocInfo info = NodeUtil.getBestJSDocInfo(root);
return info != null && info.isConstructor();
}
}
class ReplaceCandidates extends AbstractPostOrderCallback {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isGetProp() && !NodeUtil.isLValue(n)) {
Node target = n.getFirstChild();
String propName = n.getLastChild().getString();
PropertyInfo info = props.get(propName);
if (info != null
&& info != INVALIDATED
&& isMatchingType(target, info.type)) {
Node replacement = info.value.cloneTree();
if (NodeUtil.mayHaveSideEffects(n.getFirstChild(), compiler)) {
replacement = IR.comma(n.removeFirstChild(), replacement).srcref(n);
}
parent.replaceChild(n, replacement);
compiler.reportCodeChange();
}
}
}
private boolean isMatchingType(Node n, JSType src) {
src = src.restrictByNotNullOrUndefined();
JSType dest = getJSType(n).restrictByNotNullOrUndefined();
if (!isInvalidatingType(dest)) {
if (dest.isConstructor()) {
// Don't inline constructor properties referenced from
// subclass constructor references. This would be appropriate
// for ES6 class with Class-side inheritence but not
// traditional Closure classes from which subclass constructor
// don't inherit the super-classes constructor properties.
return dest.isEquivalentTo(src);
} else {
return dest.isSubtype(src);
}
}
return false;
}
}
}