forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexpressionToTypeNode.ts
496 lines (476 loc) · 23.3 KB
/
expressionToTypeNode.ts
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
import {
AccessorDeclaration,
AllAccessorDeclarations,
ArrayLiteralExpression,
ArrowFunction,
AsExpression,
BinaryExpression,
BindingElement,
ClassExpression,
CompilerOptions,
Debug,
ElementAccessExpression,
ExportAssignment,
Expression,
forEachReturnStatement,
FunctionExpression,
FunctionFlags,
FunctionLikeDeclaration,
GetAccessorDeclaration,
getEffectiveReturnTypeNode,
getEffectiveTypeAnnotationNode,
getFunctionFlags,
getJSDocTypeAssertionType,
getStrictOptionValue,
HasInferredType,
Identifier,
IntersectionTypeNode,
isBlock,
isConstTypeReference,
isDeclarationReadonly,
isGetAccessor,
isIdentifier,
isJSDocTypeAssertion,
isKeyword,
isPrimitiveLiteralValue,
isShorthandPropertyAssignment,
isSpreadAssignment,
isValueSignatureDeclaration,
isVarConstLike,
JSDocSignature,
MethodDeclaration,
Node,
NodeArray,
NodeFlags,
nodeIsMissing,
ObjectLiteralExpression,
ParameterDeclaration,
ParenthesizedExpression,
ParenthesizedTypeNode,
PrefixUnaryExpression,
PropertyAccessExpression,
PropertyAssignment,
PropertyDeclaration,
PropertyName,
PropertySignature,
SetAccessorDeclaration,
SignatureDeclaration,
SyntacticTypeNodeBuilderContext,
SyntacticTypeNodeBuilderResolver,
SyntaxKind,
TypeAssertion,
TypeNode,
TypeParameterDeclaration,
UnionTypeNode,
VariableDeclaration,
} from "./_namespaces/ts.js";
/** @internal */
export function createSyntacticTypeNodeBuilder(options: CompilerOptions, resolver: SyntacticTypeNodeBuilderResolver) {
const strictNullChecks = getStrictOptionValue(options, "strictNullChecks");
return {
typeFromExpression,
serializeTypeOfDeclaration,
serializeReturnTypeForSignature,
serializeTypeOfExpression,
};
function serializeExistingTypeAnnotation(type: TypeNode | undefined, addUndefined?: boolean) {
return type !== undefined && (!addUndefined || (type && canAddUndefined(type))) ? true : undefined;
}
function serializeTypeOfExpression(expr: Expression, context: SyntacticTypeNodeBuilderContext, addUndefined?: boolean, preserveLiterals?: boolean) {
return typeFromExpression(expr, context, /*isConstContext*/ false, addUndefined, preserveLiterals) ?? inferExpressionType(expr, context);
}
function serializeTypeOfDeclaration(node: HasInferredType, context: SyntacticTypeNodeBuilderContext) {
switch (node.kind) {
case SyntaxKind.PropertySignature:
return serializeExistingTypeAnnotation(getEffectiveTypeAnnotationNode(node));
case SyntaxKind.Parameter:
return typeFromParameter(node, context);
case SyntaxKind.VariableDeclaration:
return typeFromVariable(node, context);
case SyntaxKind.PropertyDeclaration:
return typeFromProperty(node, context);
case SyntaxKind.BindingElement:
return inferTypeOfDeclaration(node, context);
case SyntaxKind.ExportAssignment:
return serializeTypeOfExpression(node.expression, context, /*addUndefined*/ undefined, /*preserveLiterals*/ true);
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.BinaryExpression:
return serializeExistingTypeAnnotation(getEffectiveTypeAnnotationNode(node)) || inferTypeOfDeclaration(node, context);
case SyntaxKind.PropertyAssignment:
return typeFromExpression(node.initializer, context) || inferTypeOfDeclaration(node, context);
default:
Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind((node as Node).kind)}`);
}
}
function serializeReturnTypeForSignature(node: SignatureDeclaration | JSDocSignature, context: SyntacticTypeNodeBuilderContext): boolean | undefined {
switch (node.kind) {
case SyntaxKind.GetAccessor:
return typeFromAccessor(node, context);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ConstructSignature:
case SyntaxKind.MethodSignature:
case SyntaxKind.CallSignature:
case SyntaxKind.Constructor:
case SyntaxKind.SetAccessor:
case SyntaxKind.IndexSignature:
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.JSDocSignature:
return createReturnFromSignature(node, context);
default:
Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind((node as Node).kind)}`);
}
}
function getTypeAnnotationFromAccessor(accessor: AccessorDeclaration): TypeNode | undefined {
if (accessor) {
return accessor.kind === SyntaxKind.GetAccessor
? getEffectiveReturnTypeNode(accessor) // Getter - return type
: accessor.parameters.length > 0
? getEffectiveTypeAnnotationNode(accessor.parameters[0]) // Setter parameter type
: undefined;
}
}
function getTypeAnnotationFromAllAccessorDeclarations(node: AccessorDeclaration, accessors: AllAccessorDeclarations) {
let accessorType = getTypeAnnotationFromAccessor(node);
if (!accessorType && node !== accessors.firstAccessor) {
accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
}
if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
}
return accessorType;
}
function typeFromAccessor(node: AccessorDeclaration, context: SyntacticTypeNodeBuilderContext) {
const accessorDeclarations = resolver.getAllAccessorDeclarations(node);
const accessorType = getTypeAnnotationFromAllAccessorDeclarations(node, accessorDeclarations);
if (accessorType) {
return serializeExistingTypeAnnotation(accessorType);
}
if (accessorDeclarations.getAccessor) {
return createReturnFromSignature(accessorDeclarations.getAccessor, context);
}
return false;
}
function typeFromVariable(node: VariableDeclaration, context: SyntacticTypeNodeBuilderContext) {
const declaredType = getEffectiveTypeAnnotationNode(node);
if (declaredType) {
return serializeExistingTypeAnnotation(declaredType);
}
let resultType;
if (node.initializer) {
if (!resolver.isExpandoFunctionDeclaration(node)) {
resultType = typeFromExpression(node.initializer, context, /*isConstContext*/ undefined, /*requiresAddingUndefined*/ undefined, isVarConstLike(node));
}
}
return resultType ?? inferTypeOfDeclaration(node, context);
}
function typeFromParameter(node: ParameterDeclaration, context: SyntacticTypeNodeBuilderContext) {
const parent = node.parent;
if (parent.kind === SyntaxKind.SetAccessor) {
return typeFromAccessor(parent, context);
}
const declaredType = getEffectiveTypeAnnotationNode(node);
const addUndefined = resolver.requiresAddingImplicitUndefined(node);
let resultType;
if (declaredType) {
resultType = serializeExistingTypeAnnotation(declaredType, addUndefined);
}
else {
if (node.initializer && isIdentifier(node.name)) {
resultType = typeFromExpression(node.initializer, context, /*isConstContext*/ undefined, addUndefined);
}
}
return resultType ?? inferTypeOfDeclaration(node, context);
}
function typeFromProperty(node: PropertyDeclaration, context: SyntacticTypeNodeBuilderContext) {
const declaredType = getEffectiveTypeAnnotationNode(node);
if (declaredType) {
return serializeExistingTypeAnnotation(declaredType);
}
let resultType;
if (node.initializer) {
const isReadonly = isDeclarationReadonly(node);
resultType = typeFromExpression(node.initializer, context, /*isConstContext*/ undefined, /*requiresAddingUndefined*/ undefined, isReadonly);
}
return resultType ?? inferTypeOfDeclaration(node, context);
}
function inferTypeOfDeclaration(
node: PropertyAssignment | PropertyAccessExpression | BinaryExpression | ElementAccessExpression | VariableDeclaration | ParameterDeclaration | BindingElement | PropertyDeclaration | PropertySignature | ExportAssignment,
context: SyntacticTypeNodeBuilderContext,
) {
context.tracker.reportInferenceFallback(node);
return false;
}
function inferExpressionType(node: Expression, context: SyntacticTypeNodeBuilderContext) {
context.tracker.reportInferenceFallback(node);
return false;
}
function inferReturnTypeOfSignatureSignature(node: SignatureDeclaration | JSDocSignature, context: SyntacticTypeNodeBuilderContext) {
context.tracker.reportInferenceFallback(node);
return false;
}
function inferAccessorType(node: GetAccessorDeclaration | SetAccessorDeclaration, allAccessors: AllAccessorDeclarations, context: SyntacticTypeNodeBuilderContext) {
if (node.kind === SyntaxKind.GetAccessor) {
return createReturnFromSignature(node, context);
}
else {
context.tracker.reportInferenceFallback(node);
return false;
}
}
function typeFromTypeAssertion(expression: Expression, type: TypeNode, context: SyntacticTypeNodeBuilderContext, requiresAddingUndefined: boolean) {
if (isConstTypeReference(type)) {
return typeFromExpression(expression, context, /*isConstContext*/ true, requiresAddingUndefined);
}
if (requiresAddingUndefined && !canAddUndefined(type)) {
context.tracker.reportInferenceFallback(type);
}
return serializeExistingTypeAnnotation(type);
}
function typeFromExpression(node: Expression, context: SyntacticTypeNodeBuilderContext, isConstContext = false, requiresAddingUndefined = false, preserveLiterals = false): boolean | undefined {
switch (node.kind) {
case SyntaxKind.ParenthesizedExpression:
if (isJSDocTypeAssertion(node)) {
return typeFromTypeAssertion(node.expression, getJSDocTypeAssertionType(node), context, requiresAddingUndefined);
}
return typeFromExpression((node as ParenthesizedExpression).expression, context, isConstContext, requiresAddingUndefined);
case SyntaxKind.Identifier:
if (resolver.isUndefinedIdentifierExpression(node as Identifier)) {
return true;
}
break;
case SyntaxKind.NullKeyword:
return true;
case SyntaxKind.ArrowFunction:
case SyntaxKind.FunctionExpression:
return typeFromFunctionLikeExpression(node as ArrowFunction | FunctionExpression, context);
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
const asExpression = node as AsExpression | TypeAssertion;
return typeFromTypeAssertion(asExpression.expression, asExpression.type, context, requiresAddingUndefined);
case SyntaxKind.PrefixUnaryExpression:
const unaryExpression = node as PrefixUnaryExpression;
if (isPrimitiveLiteralValue(unaryExpression)) {
if (unaryExpression.operand.kind === SyntaxKind.BigIntLiteral) {
return typeFromPrimitiveLiteral();
}
if (unaryExpression.operand.kind === SyntaxKind.NumericLiteral) {
return typeFromPrimitiveLiteral();
}
}
break;
case SyntaxKind.NumericLiteral:
return typeFromPrimitiveLiteral();
case SyntaxKind.TemplateExpression:
if (!isConstContext && !preserveLiterals) {
return true;
}
break;
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.StringLiteral:
return typeFromPrimitiveLiteral();
case SyntaxKind.BigIntLiteral:
return typeFromPrimitiveLiteral();
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
return typeFromPrimitiveLiteral();
case SyntaxKind.ArrayLiteralExpression:
return typeFromArrayLiteral(node as ArrayLiteralExpression, context, isConstContext);
case SyntaxKind.ObjectLiteralExpression:
return typeFromObjectLiteral(node as ObjectLiteralExpression, context, isConstContext);
case SyntaxKind.ClassExpression:
return inferExpressionType(node as ClassExpression, context);
}
return undefined;
}
function typeFromFunctionLikeExpression(fnNode: FunctionExpression | ArrowFunction, context: SyntacticTypeNodeBuilderContext) {
const returnType = serializeExistingTypeAnnotation(fnNode.type) ?? createReturnFromSignature(fnNode, context);
const typeParameters = reuseTypeParameters(fnNode.typeParameters);
const parameters = fnNode.parameters.every(p => ensureParameter(p, context));
return returnType && typeParameters && parameters;
}
function canGetTypeFromArrayLiteral(arrayLiteral: ArrayLiteralExpression, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) {
if (!isConstContext) {
context.tracker.reportInferenceFallback(arrayLiteral);
return false;
}
for (const element of arrayLiteral.elements) {
if (element.kind === SyntaxKind.SpreadElement) {
context.tracker.reportInferenceFallback(element);
return false;
}
}
return true;
}
function typeFromArrayLiteral(arrayLiteral: ArrayLiteralExpression, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) {
if (!canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext)) {
return false;
}
let canInferArray = true;
for (const element of arrayLiteral.elements) {
Debug.assert(element.kind !== SyntaxKind.SpreadElement);
if (element.kind !== SyntaxKind.OmittedExpression) {
canInferArray = (typeFromExpression(element, context, isConstContext) ?? inferExpressionType(element, context)) && canInferArray;
}
}
return true;
}
function canGetTypeFromObjectLiteral(objectLiteral: ObjectLiteralExpression, context: SyntacticTypeNodeBuilderContext) {
let result = true;
for (const prop of objectLiteral.properties) {
if (prop.flags & NodeFlags.ThisNodeHasError) {
result = false;
break; // Bail if parse errors
}
if (prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.SpreadAssignment) {
context.tracker.reportInferenceFallback(prop);
result = false;
}
else if (prop.name.flags & NodeFlags.ThisNodeHasError) {
result = false;
break; // Bail if parse errors
}
else if (prop.name.kind === SyntaxKind.PrivateIdentifier) {
// Not valid in object literals but the compiler will complain about this, we just ignore it here.
result = false;
}
else if (prop.name.kind === SyntaxKind.ComputedPropertyName) {
const expression = prop.name.expression;
if (!isPrimitiveLiteralValue(expression, /*includeBigInt*/ false) && !resolver.isDefinitelyReferenceToGlobalSymbolObject(expression)) {
context.tracker.reportInferenceFallback(prop.name);
result = false;
}
}
}
return result;
}
function typeFromObjectLiteral(objectLiteral: ObjectLiteralExpression, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean): boolean {
if (!canGetTypeFromObjectLiteral(objectLiteral, context)) return false;
let canInferObjectLiteral = true;
for (const prop of objectLiteral.properties) {
Debug.assert(!isShorthandPropertyAssignment(prop) && !isSpreadAssignment(prop));
const name = prop.name;
switch (prop.kind) {
case SyntaxKind.MethodDeclaration:
canInferObjectLiteral = !!typeFromObjectLiteralMethod(prop, name, context) && canInferObjectLiteral;
break;
case SyntaxKind.PropertyAssignment:
canInferObjectLiteral = !!typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext) && canInferObjectLiteral;
break;
case SyntaxKind.SetAccessor:
case SyntaxKind.GetAccessor:
canInferObjectLiteral = !!typeFromObjectLiteralAccessor(prop, name, context) && canInferObjectLiteral;
break;
}
}
return canInferObjectLiteral;
}
function typeFromObjectLiteralPropertyAssignment(prop: PropertyAssignment, name: PropertyName, context: SyntacticTypeNodeBuilderContext, isConstContext: boolean) {
return typeFromExpression(prop.initializer, context, isConstContext) ?? inferTypeOfDeclaration(prop, context);
}
function ensureParameter(p: ParameterDeclaration, context: SyntacticTypeNodeBuilderContext) {
return typeFromParameter(p, context);
}
function reuseTypeParameters(typeParameters: NodeArray<TypeParameterDeclaration> | undefined) {
// TODO: We will probably need to add a fake scopes for the signature (to hold the type parameters and the parameter)
// For now this is good enough since the new serialization is used for Nodes in the same context.
return typeParameters?.every(tp =>
serializeExistingTypeAnnotation(tp.constraint) &&
serializeExistingTypeAnnotation(tp.default)
) ?? true;
}
function typeFromObjectLiteralMethod(method: MethodDeclaration, name: PropertyName, context: SyntacticTypeNodeBuilderContext): boolean {
const returnType = createReturnFromSignature(method, context);
const typeParameters = reuseTypeParameters(method.typeParameters);
const parameters = method.parameters.every(p => ensureParameter(p, context));
return returnType && typeParameters && parameters;
}
function typeFromObjectLiteralAccessor(accessor: GetAccessorDeclaration | SetAccessorDeclaration, name: PropertyName, context: SyntacticTypeNodeBuilderContext) {
const allAccessors = resolver.getAllAccessorDeclarations(accessor);
const getAccessorType = allAccessors.getAccessor && getTypeAnnotationFromAccessor(allAccessors.getAccessor);
const setAccessorType = allAccessors.setAccessor && getTypeAnnotationFromAccessor(allAccessors.setAccessor);
// We have types for both accessors, we can't know if they are the same type so we keep both accessors
if (getAccessorType !== undefined && setAccessorType !== undefined) {
const parameters = accessor.parameters.every(p => ensureParameter(p, context));
if (isGetAccessor(accessor)) {
return parameters && serializeExistingTypeAnnotation(getAccessorType);
}
else {
return parameters;
}
}
else if (allAccessors.firstAccessor === accessor) {
const foundType = getAccessorType ?? setAccessorType;
const propertyType = foundType ? serializeExistingTypeAnnotation(foundType) : inferAccessorType(accessor, allAccessors, context);
return propertyType;
}
return false;
}
function typeFromPrimitiveLiteral() {
return true;
}
function canAddUndefined(node: TypeNode): boolean {
if (!strictNullChecks) return true;
if (
isKeyword(node.kind)
|| node.kind === SyntaxKind.LiteralType
|| node.kind === SyntaxKind.FunctionType
|| node.kind === SyntaxKind.ConstructorType
|| node.kind === SyntaxKind.ArrayType
|| node.kind === SyntaxKind.TupleType
|| node.kind === SyntaxKind.TypeLiteral
|| node.kind === SyntaxKind.TemplateLiteralType
|| node.kind === SyntaxKind.ThisType
) {
return true;
}
if (node.kind === SyntaxKind.ParenthesizedType) {
return canAddUndefined((node as ParenthesizedTypeNode).type);
}
if (node.kind === SyntaxKind.UnionType || node.kind === SyntaxKind.IntersectionType) {
return (node as UnionTypeNode | IntersectionTypeNode).types.every(canAddUndefined);
}
return false;
}
function createReturnFromSignature(fn: SignatureDeclaration | JSDocSignature, context: SyntacticTypeNodeBuilderContext) {
let returnType;
const returnTypeNode = getEffectiveReturnTypeNode(fn);
if (returnTypeNode) {
returnType = serializeExistingTypeAnnotation(returnTypeNode);
}
if (!returnType && isValueSignatureDeclaration(fn)) {
returnType = typeFromSingleReturnExpression(fn, context);
}
return returnType ?? inferReturnTypeOfSignatureSignature(fn, context);
}
function typeFromSingleReturnExpression(declaration: FunctionLikeDeclaration | undefined, context: SyntacticTypeNodeBuilderContext): boolean | undefined {
let candidateExpr: Expression | undefined;
if (declaration && !nodeIsMissing(declaration.body)) {
if (getFunctionFlags(declaration) & FunctionFlags.AsyncGenerator) return undefined;
const body = declaration.body;
if (body && isBlock(body)) {
forEachReturnStatement(body, s => {
if (!candidateExpr) {
candidateExpr = s.expression;
}
else {
candidateExpr = undefined;
return true;
}
});
}
else {
candidateExpr = body;
}
}
if (candidateExpr) {
return typeFromExpression(candidateExpr, context);
}
return undefined;
}
}