-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PrototypeObjectType.java
565 lines (502 loc) · 17.6 KB
/
PrototypeObjectType.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/*
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bob Jervis
* Google Inc.
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package com.google.javascript.rhino.jstype;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.ImmutableList;
import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/**
* The object type represents instances of JavaScript objects such as
* {@code Object}, {@code Date}, {@code Function}.<p>
*
* Objects in JavaScript are unordered collections of properties.
* Each property consists of a name, a value and a set of attributes.<p>
*
* Each instance has an implicit prototype property ({@code [[Prototype]]})
* pointing to an object instance, which itself has an implicit property, thus
* forming a chain.<p>
*
* A class begins life with no name. Later, a name may be provided once it
* can be inferred. Note that the name in this case is strictly for
* debugging purposes. Looking up type name references goes through the
* {@link JSTypeRegistry}.<p>
*/
public class PrototypeObjectType extends ObjectType {
private static final long serialVersionUID = 1L;
private final String className;
private final PropertyMap properties;
private final boolean nativeType;
private final boolean anonymousType;
// NOTE(nicksantos): The implicit prototype can change over time.
// Modeling this is a bear. Always call getImplicitPrototype(), because
// some subclasses override this to do special resolution handling.
private ObjectType implicitPrototypeFallback;
// If this is a function prototype, then this is the owner.
// A PrototypeObjectType can only be the prototype of one function. If we try
// to do this for multiple functions, then we'll have to create a new one.
private FunctionType ownerFunction = null;
// Whether the toString representation of this should be pretty-printed,
// by printing all properties.
private boolean prettyPrint = false;
private static final int MAX_PRETTY_PRINTED_PROPERTIES = 10;
/**
* Creates an object type.
*
* @param className the name of the class. May be {@code null} to
* denote an anonymous class.
*
* @param implicitPrototype the implicit prototype
* (a.k.a. {@code [[Prototype]]}) as defined by ECMA-262. If the
* implicit prototype is {@code null} the implicit prototype will be
* set to the {@link JSTypeNative#OBJECT_TYPE}.
*/
PrototypeObjectType(JSTypeRegistry registry, String className,
ObjectType implicitPrototype) {
this(
registry,
className,
implicitPrototype,
false /* nativeType */,
null /* templateTypeMap */,
false /* anonymousType */);
}
/**
* Creates an object type.
*
* @param className the name of the class. May be {@code null} to
* denote an anonymous class.
*
* @param implicitPrototype the implicit prototype
* (a.k.a. {@code [[Prototype]]}) as defined by ECMA-262. If the
* implicit prototype is {@code null} the implicit prototype will be
* set to the {@link JSTypeNative#OBJECT_TYPE}.
* @param anonymousType True if the class is intended to be anonymous.
*/
PrototypeObjectType(JSTypeRegistry registry, String className,
ObjectType implicitPrototype, boolean anonymousType) {
this(
registry,
className,
implicitPrototype,
false /* nativeType */,
null /* templateTypeMap */,
anonymousType);
}
/**
* Creates an object type, allowing specification of the implicit prototype,
* whether the object is native, and any templatized types.
*/
PrototypeObjectType(JSTypeRegistry registry, String className,
ObjectType implicitPrototype, boolean nativeType,
TemplateTypeMap templateTypeMap) {
this(
registry,
className,
implicitPrototype,
nativeType,
templateTypeMap,
false /* anonymousType */);
}
/**
* Creates an object type, allowing specification of the implicit prototype,
* whether the object is native, and any templatized types.
*/
private PrototypeObjectType(JSTypeRegistry registry, String className,
ObjectType implicitPrototype, boolean nativeType,
TemplateTypeMap templateTypeMap, boolean anonymousType) {
super(registry, templateTypeMap);
this.properties = new PropertyMap();
this.properties.setParentSource(this);
this.className = className;
this.nativeType = nativeType;
this.anonymousType = anonymousType;
if (nativeType || implicitPrototype != null) {
setImplicitPrototype(implicitPrototype);
} else {
setImplicitPrototype(registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE));
}
}
@Override
PropertyMap getPropertyMap() {
return properties;
}
@Override
boolean defineProperty(String name, JSType type, boolean inferred,
Node propertyNode) {
if (hasOwnDeclaredProperty(name)) {
return false;
}
Property newProp = new Property(
name, type, inferred, propertyNode);
properties.putProperty(name, newProp);
return true;
}
@Override
public boolean removeProperty(String name) {
return properties.removeProperty(name);
}
@Override
public void setPropertyJSDocInfo(String propertyName, JSDocInfo info) {
if (info != null) {
if (properties.getOwnProperty(propertyName) == null) {
// If docInfo was attached, but the type of the property
// was not defined anywhere, then we consider this an explicit
// declaration of the property.
defineInferredProperty(propertyName, getPropertyType(propertyName),
null);
}
// The prototype property is not represented as a normal Property.
// We probably don't want to attach any JSDoc to it anyway.
Property property = properties.getOwnProperty(propertyName);
if (property != null) {
property.setJSDocInfo(info);
}
}
}
@Override
public void setPropertyNode(String propertyName, Node defSite) {
Property property = properties.getOwnProperty(propertyName);
if (property != null) {
property.setNode(defSite);
}
}
@Override
public boolean matchesNumberContext() {
return isNumberObjectType() || isDateType() || isBooleanObjectType()
|| isStringObjectType() || hasOverriddenNativeProperty("valueOf");
}
@Override
public boolean matchesStringContext() {
return isTheObjectType() || isStringObjectType() || isDateType()
|| isRegexpType() || isArrayType() || isNumberObjectType()
|| isBooleanObjectType() || hasOverriddenNativeProperty("toString");
}
@Override
public boolean matchesSymbolContext() {
return isSymbolObjectType();
}
/**
* Given the name of a native object property, checks whether the property is
* present on the object and different from the native one.
*/
private boolean hasOverriddenNativeProperty(String propertyName) {
if (isNativeObjectType()) {
return false;
}
JSType propertyType = getPropertyType(propertyName);
ObjectType nativeType =
isFunctionType()
? registry.getNativeObjectType(JSTypeNative.FUNCTION_PROTOTYPE)
: registry.getNativeObjectType(JSTypeNative.OBJECT_PROTOTYPE);
JSType nativePropertyType = nativeType.getPropertyType(propertyName);
return propertyType != nativePropertyType;
}
@Override
public final JSType unboxesTo() {
if (isStringObjectType()) {
return getNativeType(JSTypeNative.STRING_TYPE);
} else if (isBooleanObjectType()) {
return getNativeType(JSTypeNative.BOOLEAN_TYPE);
} else if (isNumberObjectType()) {
return getNativeType(JSTypeNative.NUMBER_TYPE);
} else if (isSymbolObjectType()) {
return getNativeType(JSTypeNative.SYMBOL_TYPE);
} else {
return super.unboxesTo();
}
}
@Override
public boolean matchesObjectContext() {
return true;
}
@Override
StringBuilder appendTo(StringBuilder sb, boolean forAnnotations) {
if (hasReferenceName()) {
return sb.append(forAnnotations ? getNormalizedReferenceName() : getReferenceName());
}
if (!prettyPrint) {
return sb.append(forAnnotations ? "?" : "{...}");
}
// Don't pretty print recursively.
prettyPrint = false;
// Use a tree set so that the properties are sorted.
Set<String> propertyNames = new TreeSet<>();
for (ObjectType current = this;
current != null && !current.isNativeObjectType()
&& propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES;
current = current.getImplicitPrototype()) {
propertyNames.addAll(current.getOwnPropertyNames());
}
sb.append("{");
boolean useNewlines = !forAnnotations && propertyNames.size() > 2;
int i = 0;
for (String property : propertyNames) {
if (i > 0) {
sb.append(",");
}
if (useNewlines) {
sb.append("\n ");
} else if (i > 0) {
sb.append(" ");
}
sb.append(property).append(": ");
getPropertyType(property).appendAsNonNull(sb, forAnnotations);
++i;
if (!forAnnotations && i == MAX_PRETTY_PRINTED_PROPERTIES) {
sb.append(", ...");
break;
}
}
if (useNewlines) {
sb.append("\n");
}
sb.append("}");
prettyPrint = true;
return sb;
}
void setPrettyPrint(boolean prettyPrint) {
this.prettyPrint = prettyPrint;
}
boolean isPrettyPrint() {
return prettyPrint;
}
@Override
public FunctionType getConstructor() {
return null;
}
@Override
public ObjectType getImplicitPrototype() {
return implicitPrototypeFallback;
}
/**
* This should only be reset on the FunctionPrototypeType, only to fix an
* incorrectly established prototype chain due to the user having a mismatch
* in super class declaration, and only before properties on that type are
* processed.
*/
final void setImplicitPrototype(ObjectType implicitPrototype) {
checkState(!hasCachedValues());
this.implicitPrototypeFallback = implicitPrototype;
}
@Override
public String getReferenceName() {
if (className != null) {
return className;
} else if (ownerFunction != null) {
return ownerFunction.getReferenceName() + ".prototype";
} else {
return null;
}
}
@Override
public boolean hasReferenceName() {
return className != null || ownerFunction != null;
}
public boolean isAnonymous() {
return anonymousType;
}
@Override
public boolean isSubtype(JSType that) {
return isSubtype(that, ImplCache.create(), SubtypingMode.NORMAL);
}
@Override
protected boolean isSubtype(JSType that,
ImplCache implicitImplCache, SubtypingMode subtypingMode) {
if (JSType.isSubtypeHelper(this, that, implicitImplCache, subtypingMode)) {
return true;
}
// Union types
if (that.isUnionType()) {
// The static {@code JSType.isSubtype} check already decomposed
// union types, so we don't need to check those again.
return false;
}
// record types
if (that.isRecordType()) {
return PrototypeObjectType.isSubtype(
this, that.toMaybeRecordType(), implicitImplCache, subtypingMode);
}
// Interfaces
// Find all the interfaces implemented by this class and compare each one
// to the interface instance.
ObjectType thatObj = that.toObjectType();
FunctionType thatCtor = thatObj == null ? null : thatObj.getConstructor();
if (getConstructor() != null && getConstructor().isInterface()) {
for (ObjectType thisInterface : getCtorExtendedInterfaces()) {
if (thisInterface.isSubtype(that, implicitImplCache, subtypingMode)) {
return true;
}
}
} else if (thatCtor != null && thatCtor.isInterface()) {
Iterable<ObjectType> thisInterfaces = getCtorImplementedInterfaces();
for (ObjectType thisInterface : thisInterfaces) {
if (thisInterface.isSubtype(that, implicitImplCache, subtypingMode)) {
return true;
}
}
}
// other prototype based objects
if (isUnknownType()) {
// If unsure, say 'yes', to avoid spurious warnings.
return true;
}
return thatObj != null && isImplicitPrototype(thatObj);
}
/** Determines if typeA is a subtype of typeB */
private static boolean isSubtype(ObjectType typeA, RecordType typeB,
ImplCache implicitImplCache, SubtypingMode subtypingMode) {
// typeA is a subtype of record type typeB iff:
// 1) typeA has all the properties declared in typeB.
// 2) And for each property of typeB, its type must be
// a super type of the corresponding property of typeA.
for (String property : typeB.getOwnPropertyNames()) {
if (!typeA.hasProperty(property)) {
return false;
}
JSType propA = typeA.getPropertyType(property);
JSType propB = typeB.getPropertyType(property);
if (!propA.isSubtype(propB, implicitImplCache, subtypingMode)) {
return false;
}
}
return true;
}
@Override
public boolean hasCachedValues() {
return super.hasCachedValues();
}
/** Whether this is a built-in object. */
@Override
public boolean isNativeObjectType() {
return nativeType;
}
@Override
void setOwnerFunction(FunctionType type) {
checkState(ownerFunction == null || type == null);
ownerFunction = type;
}
@Override
public FunctionType getOwnerFunction() {
return ownerFunction;
}
@Override
public Iterable<ObjectType> getCtorImplementedInterfaces() {
return isFunctionPrototypeType()
? getOwnerFunction().getImplementedInterfaces()
: ImmutableList.<ObjectType>of();
}
@Override
public Iterable<ObjectType> getCtorExtendedInterfaces() {
return isFunctionPrototypeType()
? getOwnerFunction().getExtendedInterfaces()
: ImmutableList.<ObjectType>of();
}
@Override
JSType resolveInternal(ErrorReporter reporter) {
setResolvedTypeInternal(this);
ObjectType implicitPrototype = getImplicitPrototype();
if (implicitPrototype != null) {
implicitPrototypeFallback =
(ObjectType) implicitPrototype.resolve(reporter);
FunctionType ctor = getConstructor();
if (ctor != null) {
FunctionType superCtor = ctor.getSuperClassConstructor();
if (superCtor != null) {
// If the super ctor of this prototype object was not known before resolution, then the
// subTypes would not have been set. Update them.
superCtor.addSubTypeIfNotPresent(ctor);
}
}
}
for (Property prop : properties.values()) {
prop.setType(safeResolve(prop.getType(), reporter));
}
return this;
}
@Override
public void matchConstraint(JSType constraint) {
// We only want to match constraints on anonymous types.
if (hasReferenceName()) {
return;
}
// Handle the case where the constraint object is a record type.
//
// param constraint {{prop: (number|undefined)}}
// function f(constraint) {}
// f({});
//
// We want to modify the object literal to match the constraint, by
// taking any each property on the record and trying to match
// properties on this object.
if (constraint.isRecordType()) {
matchRecordTypeConstraint(constraint.toObjectType());
} else if (constraint.isUnionType()) {
for (JSType alt : constraint.toMaybeUnionType().getAlternates()) {
if (alt.isRecordType()) {
matchRecordTypeConstraint(alt.toObjectType());
}
}
}
}
public void matchRecordTypeConstraint(ObjectType constraintObj) {
for (String prop : constraintObj.getOwnPropertyNames()) {
JSType propType = constraintObj.getPropertyType(prop);
if (!isPropertyTypeDeclared(prop)) {
JSType typeToInfer = propType;
if (!hasProperty(prop)) {
typeToInfer = getNativeType(JSTypeNative.VOID_TYPE)
.getLeastSupertype(propType);
}
defineInferredProperty(prop, typeToInfer, null);
}
}
}
@Override
public int hashCode() {
if (isStructuralType()) {
return Objects.hash(className, properties);
} else {
return System.identityHashCode(this);
}
}
}