forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypeSerializer.ts
More file actions
633 lines (554 loc) · 28.1 KB
/
typeSerializer.ts
File metadata and controls
633 lines (554 loc) · 28.1 KB
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import {
AccessorDeclaration,
ArrayLiteralExpression,
BigIntLiteral,
BinaryExpression,
Block,
CaseBlock,
ClassLikeDeclaration,
ConditionalExpression,
ConditionalTypeNode,
Debug,
EntityName,
Expression,
findAncestor,
FunctionLikeDeclaration,
getAllAccessorDeclarations,
getEffectiveReturnTypeNode,
getEmitScriptTarget,
getFirstConstructorWithBody,
getParseTreeNode,
getRestParameterElementType,
getSetAccessorTypeAnnotationNode,
getStrictOptionValue,
Identifier,
isAsyncFunction,
isBinaryExpression,
isClassLike,
isConditionalExpression,
isConditionalTypeNode,
isFunctionLike,
isGeneratedIdentifier,
isIdentifier,
isLiteralTypeNode,
isNumericLiteral,
isParenthesizedExpression,
isPropertyAccessExpression,
isStringLiteral,
isTypeOfExpression,
isVoidExpression,
JSDocNonNullableType,
JSDocNullableType,
JSDocOptionalType,
LiteralTypeNode,
MethodDeclaration,
ModuleBlock,
Node,
nodeIsPresent,
NumericLiteral,
ParameterDeclaration,
parseNodeFactory,
PrefixUnaryExpression,
PropertyAccessEntityNameExpression,
PropertyDeclaration,
QualifiedName,
ScriptTarget,
setParent,
setTextRange,
SignatureDeclaration,
skipTypeParentheses,
SourceFile,
SyntaxKind,
TransformationContext,
TypeNode,
TypeOperatorNode,
TypePredicateNode,
TypeReferenceNode,
TypeReferenceSerializationKind,
UnionOrIntersectionTypeNode,
VoidExpression,
} from "../_namespaces/ts.js";
/** @internal */
export type SerializedEntityName =
| Identifier // Globals (i.e., `String`, `Number`, etc.)
| PropertyAccessEntityNameExpression // `A.B`
;
/** @internal */
export type SerializedTypeNode =
| SerializedEntityName
| ConditionalExpression // Type Reference or Global fallback
| VoidExpression // `void 0` used for null/undefined/never
;
/** @internal */
export interface RuntimeTypeSerializerContext {
/** Specifies the current lexical block scope */
currentLexicalScope: SourceFile | Block | ModuleBlock | CaseBlock;
/** Specifies the containing `class`, but only when there is no other block scope between the current location and the `class`. */
currentNameScope: ClassLikeDeclaration | undefined;
}
/** @internal */
export interface RuntimeTypeSerializer {
/**
* Serializes a type node for use with decorator type metadata.
*
* Types are serialized in the following fashion:
* - Void types point to "undefined" (e.g. "void 0")
* - Function and Constructor types point to the global "Function" constructor.
* - Interface types with a call or construct signature types point to the global
* "Function" constructor.
* - Array and Tuple types point to the global "Array" constructor.
* - Type predicates and booleans point to the global "Boolean" constructor.
* - String literal types and strings point to the global "String" constructor.
* - Enum and number types point to the global "Number" constructor.
* - Symbol types point to the global "Symbol" constructor.
* - Type references to classes (or class-like variables) point to the constructor for the class.
* - Anything else points to the global "Object" constructor.
*
* @param node The type node to serialize.
*/
serializeTypeNode(serializerContext: RuntimeTypeSerializerContext, node: TypeNode): Expression;
/**
* Serializes the type of a node for use with decorator type metadata.
* @param node The node that should have its type serialized.
*/
serializeTypeOfNode(serializerContext: RuntimeTypeSerializerContext, node: PropertyDeclaration | ParameterDeclaration | AccessorDeclaration | ClassLikeDeclaration | MethodDeclaration, container: ClassLikeDeclaration): Expression;
/**
* Serializes the types of the parameters of a node for use with decorator type metadata.
* @param node The node that should have its parameter types serialized.
*/
serializeParameterTypesOfNode(serializerContext: RuntimeTypeSerializerContext, node: Node, container: ClassLikeDeclaration): ArrayLiteralExpression;
/**
* Serializes the return type of a node for use with decorator type metadata.
* @param node The node that should have its return type serialized.
*/
serializeReturnTypeOfNode(serializerContext: RuntimeTypeSerializerContext, node: Node): SerializedTypeNode;
}
/** @internal */
export function createRuntimeTypeSerializer(context: TransformationContext): RuntimeTypeSerializer {
const {
factory,
hoistVariableDeclaration,
} = context;
const resolver = context.getEmitResolver();
const compilerOptions = context.getCompilerOptions();
const languageVersion = getEmitScriptTarget(compilerOptions);
const strictNullChecks = getStrictOptionValue(compilerOptions, "strictNullChecks");
let currentLexicalScope: SourceFile | CaseBlock | ModuleBlock | Block;
let currentNameScope: ClassLikeDeclaration | undefined;
return {
serializeTypeNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeTypeNode, node),
serializeTypeOfNode: (serializerContext, node, container) => setSerializerContextAnd(serializerContext, serializeTypeOfNode, node, container),
serializeParameterTypesOfNode: (serializerContext, node, container) => setSerializerContextAnd(serializerContext, serializeParameterTypesOfNode, node, container),
serializeReturnTypeOfNode: (serializerContext, node) => setSerializerContextAnd(serializerContext, serializeReturnTypeOfNode, node),
};
function setSerializerContextAnd<TNode extends Node | undefined, R>(serializerContext: RuntimeTypeSerializerContext, cb: (node: TNode) => R, node: TNode): R;
function setSerializerContextAnd<TNode extends Node | undefined, T, R>(serializerContext: RuntimeTypeSerializerContext, cb: (node: TNode, arg: T) => R, node: TNode, arg: T): R;
function setSerializerContextAnd<TNode extends Node | undefined, T, R>(serializerContext: RuntimeTypeSerializerContext, cb: (node: TNode, arg?: T) => R, node: TNode, arg?: T) {
const savedCurrentLexicalScope = currentLexicalScope;
const savedCurrentNameScope = currentNameScope;
currentLexicalScope = serializerContext.currentLexicalScope;
currentNameScope = serializerContext.currentNameScope;
const result = arg === undefined ? cb(node) : cb(node, arg);
currentLexicalScope = savedCurrentLexicalScope;
currentNameScope = savedCurrentNameScope;
return result;
}
function getAccessorTypeNode(node: AccessorDeclaration, container: ClassLikeDeclaration) {
const accessors = getAllAccessorDeclarations(container.members, node);
return accessors.setAccessor && getSetAccessorTypeAnnotationNode(accessors.setAccessor)
|| accessors.getAccessor && getEffectiveReturnTypeNode(accessors.getAccessor);
}
/**
* Serializes the type of a node for use with decorator type metadata.
* @param node The node that should have its type serialized.
*/
function serializeTypeOfNode(node: PropertyDeclaration | ParameterDeclaration | AccessorDeclaration | ClassLikeDeclaration | MethodDeclaration, container: ClassLikeDeclaration): SerializedTypeNode {
switch (node.kind) {
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.Parameter:
return serializeTypeNode(node.type);
case SyntaxKind.SetAccessor:
case SyntaxKind.GetAccessor:
return serializeTypeNode(getAccessorTypeNode(node, container));
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.MethodDeclaration:
return factory.createIdentifier("Function");
default:
return factory.createVoidZero();
}
}
/**
* Serializes the type of a node for use with decorator type metadata.
* @param node The node that should have its type serialized.
*/
function serializeParameterTypesOfNode(node: Node, container: ClassLikeDeclaration): ArrayLiteralExpression {
const valueDeclaration = isClassLike(node)
? getFirstConstructorWithBody(node)
: isFunctionLike(node) && nodeIsPresent((node as FunctionLikeDeclaration).body)
? node
: undefined;
const expressions: SerializedTypeNode[] = [];
if (valueDeclaration) {
const parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
const numParameters = parameters.length;
for (let i = 0; i < numParameters; i++) {
const parameter = parameters[i];
if (i === 0 && isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
continue;
}
if (parameter.dotDotDotToken) {
expressions.push(serializeTypeNode(getRestParameterElementType(parameter.type)));
}
else {
expressions.push(serializeTypeOfNode(parameter, container));
}
}
}
return factory.createArrayLiteralExpression(expressions);
}
function getParametersOfDecoratedDeclaration(node: SignatureDeclaration, container: ClassLikeDeclaration) {
if (container && node.kind === SyntaxKind.GetAccessor) {
const { setAccessor } = getAllAccessorDeclarations(container.members, node as AccessorDeclaration);
if (setAccessor) {
return setAccessor.parameters;
}
}
return node.parameters;
}
/**
* Serializes the return type of a node for use with decorator type metadata.
* @param node The node that should have its return type serialized.
*/
function serializeReturnTypeOfNode(node: Node): SerializedTypeNode {
if (isFunctionLike(node) && node.type) {
return serializeTypeNode(node.type);
}
else if (isAsyncFunction(node)) {
return factory.createIdentifier("Promise");
}
return factory.createVoidZero();
}
/**
* Serializes a type node for use with decorator type metadata.
*
* Types are serialized in the following fashion:
* - Void types point to "undefined" (e.g. "void 0")
* - Function and Constructor types point to the global "Function" constructor.
* - Interface types with a call or construct signature types point to the global
* "Function" constructor.
* - Array and Tuple types point to the global "Array" constructor.
* - Type predicates and booleans point to the global "Boolean" constructor.
* - String literal types and strings point to the global "String" constructor.
* - Enum and number types point to the global "Number" constructor.
* - Symbol types point to the global "Symbol" constructor.
* - Type references to classes (or class-like variables) point to the constructor for the class.
* - Anything else points to the global "Object" constructor.
*
* @param node The type node to serialize.
*/
function serializeTypeNode(node: TypeNode | undefined): SerializedTypeNode {
if (node === undefined) {
return factory.createIdentifier("Object");
}
node = skipTypeParentheses(node);
switch (node.kind) {
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NeverKeyword:
return factory.createVoidZero();
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return factory.createIdentifier("Function");
case SyntaxKind.ArrayType:
case SyntaxKind.TupleType:
return factory.createIdentifier("Array");
case SyntaxKind.TypePredicate:
return (node as TypePredicateNode).assertsModifier ?
factory.createVoidZero() :
factory.createIdentifier("Boolean");
case SyntaxKind.BooleanKeyword:
return factory.createIdentifier("Boolean");
case SyntaxKind.TemplateLiteralType:
case SyntaxKind.StringKeyword:
return factory.createIdentifier("String");
case SyntaxKind.ObjectKeyword:
return factory.createIdentifier("Object");
case SyntaxKind.LiteralType:
return serializeLiteralOfLiteralTypeNode((node as LiteralTypeNode).literal);
case SyntaxKind.NumberKeyword:
return factory.createIdentifier("Number");
case SyntaxKind.BigIntKeyword:
return getGlobalConstructor("BigInt", ScriptTarget.ES2020);
case SyntaxKind.SymbolKeyword:
return getGlobalConstructor("Symbol", ScriptTarget.ES2015);
case SyntaxKind.TypeReference:
return serializeTypeReferenceNode(node as TypeReferenceNode);
case SyntaxKind.IntersectionType:
return serializeUnionOrIntersectionConstituents((node as UnionOrIntersectionTypeNode).types, /*isIntersection*/ true);
case SyntaxKind.UnionType:
return serializeUnionOrIntersectionConstituents((node as UnionOrIntersectionTypeNode).types, /*isIntersection*/ false);
case SyntaxKind.ConditionalType:
return serializeUnionOrIntersectionConstituents([(node as ConditionalTypeNode).trueType, (node as ConditionalTypeNode).falseType], /*isIntersection*/ false);
case SyntaxKind.TypeOperator:
if ((node as TypeOperatorNode).operator === SyntaxKind.ReadonlyKeyword) {
return serializeTypeNode((node as TypeOperatorNode).type);
}
break;
case SyntaxKind.TypeQuery:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.MappedType:
case SyntaxKind.TypeLiteral:
case SyntaxKind.AnyKeyword:
case SyntaxKind.UnknownKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.ImportType:
break;
// handle JSDoc types from an invalid parse
case SyntaxKind.JSDocAllType:
case SyntaxKind.JSDocUnknownType:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.JSDocVariadicType:
case SyntaxKind.JSDocNamepathType:
break;
case SyntaxKind.JSDocNullableType:
case SyntaxKind.JSDocNonNullableType:
case SyntaxKind.JSDocOptionalType:
return serializeTypeNode((node as JSDocNullableType | JSDocNonNullableType | JSDocOptionalType).type);
default:
return Debug.failBadSyntaxKind(node);
}
return factory.createIdentifier("Object");
}
function serializeLiteralOfLiteralTypeNode(node: LiteralTypeNode["literal"]): SerializedTypeNode {
switch (node.kind) {
case SyntaxKind.StringLiteral:
case SyntaxKind.NoSubstitutionTemplateLiteral:
return factory.createIdentifier("String");
case SyntaxKind.PrefixUnaryExpression: {
const operand = (node as PrefixUnaryExpression).operand;
switch (operand.kind) {
case SyntaxKind.NumericLiteral:
case SyntaxKind.BigIntLiteral:
return serializeLiteralOfLiteralTypeNode(operand as NumericLiteral | BigIntLiteral);
default:
return Debug.failBadSyntaxKind(operand);
}
}
case SyntaxKind.NumericLiteral:
return factory.createIdentifier("Number");
case SyntaxKind.BigIntLiteral:
return getGlobalConstructor("BigInt", ScriptTarget.ES2020);
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
return factory.createIdentifier("Boolean");
case SyntaxKind.NullKeyword:
return factory.createVoidZero();
default:
return Debug.failBadSyntaxKind(node);
}
}
function serializeUnionOrIntersectionConstituents(types: readonly TypeNode[], isIntersection: boolean): SerializedTypeNode {
// Note when updating logic here also update `getEntityNameForDecoratorMetadata` in checker.ts so that aliases can be marked as referenced
let serializedType: SerializedTypeNode | undefined;
for (let typeNode of types) {
typeNode = skipTypeParentheses(typeNode);
if (typeNode.kind === SyntaxKind.NeverKeyword) {
if (isIntersection) return factory.createVoidZero(); // Reduce to `never` in an intersection
continue; // Elide `never` in a union
}
if (typeNode.kind === SyntaxKind.UnknownKeyword) {
if (!isIntersection) return factory.createIdentifier("Object"); // Reduce to `unknown` in a union
continue; // Elide `unknown` in an intersection
}
if (typeNode.kind === SyntaxKind.AnyKeyword) {
return factory.createIdentifier("Object"); // Reduce to `any` in a union or intersection
}
if (!strictNullChecks && ((isLiteralTypeNode(typeNode) && typeNode.literal.kind === SyntaxKind.NullKeyword) || typeNode.kind === SyntaxKind.UndefinedKeyword)) {
continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
}
const serializedConstituent = serializeTypeNode(typeNode);
if (isIdentifier(serializedConstituent) && serializedConstituent.escapedText === "Object") {
// One of the individual is global object, return immediately
return serializedConstituent;
}
// If there exists union that is not `void 0` expression, check if the the common type is identifier.
// anything more complex and we will just default to Object
if (serializedType) {
// Different types
if (!equateSerializedTypeNodes(serializedType, serializedConstituent)) {
return factory.createIdentifier("Object");
}
}
else {
// Initialize the union type
serializedType = serializedConstituent;
}
}
// If we were able to find common type, use it
return serializedType ?? (factory.createVoidZero()); // Fallback is only hit if all union constituents are null/undefined/never
}
function equateSerializedTypeNodes(left: Expression, right: Expression): boolean {
return (
// temp vars used in fallback
isGeneratedIdentifier(left) ? isGeneratedIdentifier(right) :
// entity names
isIdentifier(left) ? isIdentifier(right)
&& left.escapedText === right.escapedText :
isPropertyAccessExpression(left) ? isPropertyAccessExpression(right)
&& equateSerializedTypeNodes(left.expression, right.expression)
&& equateSerializedTypeNodes(left.name, right.name) :
// `void 0`
isVoidExpression(left) ? isVoidExpression(right)
&& isNumericLiteral(left.expression) && left.expression.text === "0"
&& isNumericLiteral(right.expression) && right.expression.text === "0" :
// `"undefined"` or `"function"` in `typeof` checks
isStringLiteral(left) ? isStringLiteral(right)
&& left.text === right.text :
// used in `typeof` checks for fallback
isTypeOfExpression(left) ? isTypeOfExpression(right)
&& equateSerializedTypeNodes(left.expression, right.expression) :
// parens in `typeof` checks with temps
isParenthesizedExpression(left) ? isParenthesizedExpression(right)
&& equateSerializedTypeNodes(left.expression, right.expression) :
// conditionals used in fallback
isConditionalExpression(left) ? isConditionalExpression(right)
&& equateSerializedTypeNodes(left.condition, right.condition)
&& equateSerializedTypeNodes(left.whenTrue, right.whenTrue)
&& equateSerializedTypeNodes(left.whenFalse, right.whenFalse) :
// logical binary and assignments used in fallback
isBinaryExpression(left) ? isBinaryExpression(right)
&& left.operatorToken.kind === right.operatorToken.kind
&& equateSerializedTypeNodes(left.left, right.left)
&& equateSerializedTypeNodes(left.right, right.right) :
false
);
}
/**
* Serializes a TypeReferenceNode to an appropriate JS constructor value for use with decorator type metadata.
* @param node The type reference node.
*/
function serializeTypeReferenceNode(node: TypeReferenceNode): SerializedTypeNode {
const kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope ?? currentLexicalScope);
switch (kind) {
case TypeReferenceSerializationKind.Unknown:
// From conditional type type reference that cannot be resolved is Similar to any or unknown
if (findAncestor(node, n => n.parent && isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n))) {
return factory.createIdentifier("Object");
}
const serialized = serializeEntityNameAsExpressionFallback(node.typeName);
const temp = factory.createTempVariable(hoistVariableDeclaration);
return factory.createConditionalExpression(
factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"),
/*questionToken*/ undefined,
temp,
/*colonToken*/ undefined,
factory.createIdentifier("Object"),
);
case TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
return serializeEntityNameAsExpression(node.typeName);
case TypeReferenceSerializationKind.VoidNullableOrNeverType:
return factory.createVoidZero();
case TypeReferenceSerializationKind.BigIntLikeType:
return getGlobalConstructor("BigInt", ScriptTarget.ES2020);
case TypeReferenceSerializationKind.BooleanType:
return factory.createIdentifier("Boolean");
case TypeReferenceSerializationKind.NumberLikeType:
return factory.createIdentifier("Number");
case TypeReferenceSerializationKind.StringLikeType:
return factory.createIdentifier("String");
case TypeReferenceSerializationKind.ArrayLikeType:
return factory.createIdentifier("Array");
case TypeReferenceSerializationKind.ESSymbolType:
return getGlobalConstructor("Symbol", ScriptTarget.ES2015);
case TypeReferenceSerializationKind.TypeWithCallSignature:
return factory.createIdentifier("Function");
case TypeReferenceSerializationKind.Promise:
return factory.createIdentifier("Promise");
case TypeReferenceSerializationKind.ObjectType:
return factory.createIdentifier("Object");
default:
return Debug.assertNever(kind);
}
}
/**
* Produces an expression that results in `right` if `left` is not undefined at runtime:
*
* ```
* typeof left !== "undefined" && right
* ```
*
* We use `typeof L !== "undefined"` (rather than `L !== undefined`) since `L` may not be declared.
* It's acceptable for this expression to result in `false` at runtime, as the result is intended to be
* further checked by any containing expression.
*/
function createCheckedValue(left: Expression, right: Expression) {
return factory.createLogicalAnd(
factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")),
right,
);
}
/**
* Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
* @param node The entity name to serialize.
*/
function serializeEntityNameAsExpressionFallback(node: EntityName): BinaryExpression {
if (node.kind === SyntaxKind.Identifier) {
// A -> typeof A !== "undefined" && A
const copied = serializeEntityNameAsExpression(node);
return createCheckedValue(copied, copied);
}
if (node.left.kind === SyntaxKind.Identifier) {
// A.B -> typeof A !== "undefined" && A.B
return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
}
// A.B.C -> typeof A !== "undefined" && (_a = A.B) !== void 0 && _a.C
const left = serializeEntityNameAsExpressionFallback(node.left);
const temp = factory.createTempVariable(hoistVariableDeclaration);
return factory.createLogicalAnd(
factory.createLogicalAnd(
left.left,
factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero()),
),
factory.createPropertyAccessExpression(temp, node.right),
);
}
/**
* Serializes an entity name as an expression for decorator type metadata.
* @param node The entity name to serialize.
*/
function serializeEntityNameAsExpression(node: EntityName): SerializedEntityName {
switch (node.kind) {
case SyntaxKind.Identifier:
// Create a clone of the name with a new parent, and treat it as if it were
// a source tree node for the purposes of the checker.
const name = setParent(setTextRange(parseNodeFactory.cloneNode(node), node), node.parent);
name.original = undefined;
setParent(name, getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node.
return name;
case SyntaxKind.QualifiedName:
return serializeQualifiedNameAsExpression(node);
}
}
/**
* Serializes an qualified name as an expression for decorator type metadata.
* @param node The qualified name to serialize.
*/
function serializeQualifiedNameAsExpression(node: QualifiedName): SerializedEntityName {
return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right) as PropertyAccessEntityNameExpression;
}
function getGlobalConstructorWithFallback(name: string) {
return factory.createConditionalExpression(
factory.createTypeCheck(factory.createIdentifier(name), "function"),
/*questionToken*/ undefined,
factory.createIdentifier(name),
/*colonToken*/ undefined,
factory.createIdentifier("Object"),
);
}
function getGlobalConstructor(name: string, minLanguageVersion: ScriptTarget): SerializedTypeNode {
return languageVersion < minLanguageVersion ?
getGlobalConstructorWithFallback(name) :
factory.createIdentifier(name);
}
}