/
get-type-annotation.js
615 lines (559 loc) · 18.1 KB
/
get-type-annotation.js
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
/**
* External dependencies
*/
// See https://babeljs.io/docs/en/babel-types.
const { types: babelTypes } = require( '@babel/core' );
/* eslint-disable jsdoc/valid-types */
/** @typedef {ReturnType<import('comment-parser').parse>[0]} CommentBlock */
/** @typedef {CommentBlock['tags'][0]} CommentTag */
/** @typedef {babelTypes.TSType} TypeAnnotation */
/** @typedef {babelTypes.TSCallSignatureDeclaration | babelTypes.TSFunctionType | babelTypes.TSConstructSignatureDeclaration} ExtendedTypeAnnotation */
/** @typedef {import('@babel/core').Node} ASTNode */
/* eslint-enable jsdoc/valid-types */
/**
* @param {ExtendedTypeAnnotation} typeAnnotation
* @param {' => ' | ': '} returnIndicator The return indicator to use. Allows using the same function for function annotations and object call properties.
*/
function getFunctionTypeAnnotation( typeAnnotation, returnIndicator ) {
const nonRestParams = typeAnnotation.parameters
.filter( ( p ) => babelTypes.isIdentifier( p ) )
.map(
( p ) =>
`${ p.name }: ${ getTypeAnnotation(
p.typeAnnotation.typeAnnotation
) }`
)
.join( ', ' );
let params = nonRestParams;
const restParam = typeAnnotation.parameters.find(
babelTypes.isRestElement
);
if ( restParam ) {
const paramName = restParam.argument.name;
const paramType = getTypeAnnotation(
restParam.typeAnnotation.typeAnnotation
);
params += `, ...${ paramName }: ${ paramType }`;
}
const returnType = getTypeAnnotation(
typeAnnotation.returnType ||
typeAnnotation.typeAnnotation.typeAnnotation
);
const paramsWithParens = params.length ? `( ${ params } )` : `()`;
return `${ paramsWithParens }${ returnIndicator }${ returnType }`;
}
/**
* @param {babelTypes.TSTypeLiteral} typeAnnotation
*/
function getTypeLiteralCallSignatureDeclarationTypeAnnotations(
typeAnnotation
) {
const callProperties = typeAnnotation.members
.filter( ( m ) => babelTypes.isTSCallSignatureDeclaration( m ) )
.map( ( callProperty ) => {
return getFunctionTypeAnnotation( callProperty, ': ' );
} );
if ( callProperties.length ) {
return `${ callProperties.join( '; ' ) }; `;
}
return '';
}
/**
* @param {babelTypes.TSTypeLiteral} typeAnnotation
*/
function getTypeLiteralIndexSignatureTypeAnnotations( typeAnnotation ) {
const indexers = typeAnnotation.members
.filter( ( m ) => babelTypes.isTSIndexSignature( m ) )
.map( ( indexer ) => {
const parameter = indexer.parameters[ 0 ];
return `[ ${ parameter.name }: ${ getTypeAnnotation(
parameter.typeAnnotation.typeAnnotation
) } ]: ${ getTypeAnnotation(
indexer.typeAnnotation.typeAnnotation
) }`;
} );
if ( indexers.length ) {
return `${ indexers.join( '; ' ) }; `;
}
return '';
}
/**
* @param {babelTypes.TSTypeLiteral} typeAnnotation
*/
function getTypeLiteralPropertyTypeAnnotations( typeAnnotation ) {
const properties = typeAnnotation.members
.filter( ( m ) => babelTypes.isTSPropertySignature( m ) )
.map( ( prop ) => {
return `${ prop.key.name }${
prop.optional ? '?' : ''
}: ${ getTypeAnnotation( prop.typeAnnotation.typeAnnotation ) }`;
} );
if ( properties.length ) {
return `${ properties.join( '; ' ) }; `;
}
return '';
}
/**
* @param {babelTypes.TSTypeLiteral} typeAnnotation
*/
function getTypeLiteralTypeAnnotation( typeAnnotation ) {
const callProperties =
getTypeLiteralCallSignatureDeclarationTypeAnnotations( typeAnnotation );
const indexers =
getTypeLiteralIndexSignatureTypeAnnotations( typeAnnotation );
const properties = getTypeLiteralPropertyTypeAnnotations( typeAnnotation );
return `{ ${ callProperties }${ properties }${ indexers }}`;
}
/**
* @param {babelTypes.TSUnionType} typeAnnotation
*/
function getUnionTypeAnnotation( typeAnnotation ) {
return typeAnnotation.types.map( getTypeAnnotation ).join( ' | ' );
}
/**
* @param {babelTypes.TSIntersectionType} typeAnnotation
*/
function getIntersectionTypeAnnotation( typeAnnotation ) {
return typeAnnotation.types.map( getTypeAnnotation ).join( ' & ' );
}
/**
* @param {babelTypes.TSArrayType} typeAnnotation
* @return {string} The type annotation
*/
function getArrayTypeAnnotation( typeAnnotation ) {
return `${ getTypeAnnotation( typeAnnotation.elementType ) }[]`;
}
/**
* @param {babelTypes.TSTupleType} typeAnnotation
*/
function getTupleTypeAnnotation( typeAnnotation ) {
const types = typeAnnotation.elementTypes
.map( getTypeAnnotation )
.join( ', ' );
if ( types.length ) {
return `[ ${ types } ]`;
}
return '[]';
}
/**
* @param {babelTypes.TSQualifiedName} qualifiedName
*/
function unifyQualifiedName( qualifiedName ) {
if ( ! qualifiedName.right ) {
if ( ! qualifiedName.left ) {
return qualifiedName.name;
}
return qualifiedName.left.name;
}
return `${ unifyQualifiedName( qualifiedName.left ) }.${
qualifiedName.right.name
}`;
}
/**
* @param {babelTypes.TSImportType} typeAnnotation
*/
function getImportTypeAnnotation( typeAnnotation ) {
// Should this just return the unqualified name (i.e., typeAnnotation.name || typeAnnotation.right.name)?
return `import( '${
typeAnnotation.argument.value
}' ).${ unifyQualifiedName( typeAnnotation.qualifier ) }`;
}
/**
*
* @param {babelTypes.TSType} objectType
*/
function getIndexedAccessTypeAnnotationObjectName( objectType ) {
if ( babelTypes.isTSImportType( objectType ) ) {
return getImportTypeAnnotation( objectType );
}
return objectType.typeName.name;
}
/**
* @param {babelTypes.TSIndexedAccessType} typeAnnotation
*/
function getIndexedAccessTypeAnnotation( typeAnnotation ) {
const objName = getIndexedAccessTypeAnnotationObjectName(
typeAnnotation.objectType
);
const index = typeAnnotation.indexType.literal.value;
return `${ objName }[ '${ index }' ]`;
}
/**
*
* @param {babelTypes.TSLiteralType} typeAnnotation
*/
function getLiteralTypeAnnotation( typeAnnotation ) {
switch ( typeAnnotation.literal.type ) {
case 'BigIntLiteral': {
return `${ typeAnnotation.literal.value }n`;
}
case 'NumericLiteral':
case 'BooleanLiteral': {
return typeAnnotation.literal.value.toString();
}
case 'StringLiteral': {
return `'${ typeAnnotation.literal.value }'`;
}
}
}
/**
* @param {babelTypes.TSMappedType} typeAnnotation
*/
function getMappedTypeAnnotation( typeAnnotation ) {
const typeParam = typeAnnotation.typeParameter.name;
const constraintOperator = typeAnnotation.typeParameter.constraint.operator;
const constraintAnnotation = getTypeAnnotation(
typeAnnotation.typeParameter.constraint.typeAnnotation
);
const mappedValue = getTypeAnnotation( typeAnnotation.typeAnnotation );
return `[ ${ typeParam } in ${ constraintOperator } ${ constraintAnnotation } ]: ${ mappedValue }`;
}
/**
* @param {babelTypes.TSTypeReference} typeAnnotation
*/
function getTypeReferenceTypeAnnotation( typeAnnotation ) {
if ( ! typeAnnotation.typeParameters ) {
if ( babelTypes.isTSQualifiedName( typeAnnotation.typeName ) ) {
return unifyQualifiedName( typeAnnotation.typeName );
}
return typeAnnotation.typeName.name;
}
const typeParams = typeAnnotation.typeParameters.params
.map( getTypeAnnotation )
.join( ', ' );
return `${ typeAnnotation.typeName.name }< ${ typeParams } >`;
}
/**
* @param {TypeAnnotation} typeAnnotation
* @return {string | null} The type or null if not an identifiable type.
*/
function getTypeAnnotation( typeAnnotation ) {
switch ( typeAnnotation.type ) {
case 'TSAnyKeyword': {
return 'any';
}
case 'TSArrayType': {
return getArrayTypeAnnotation( typeAnnotation );
}
case 'TSBigIntKeyword': {
return 'BigInt';
}
case 'TSBooleanKeyword': {
return 'boolean';
}
case 'TSConditionalType': {
// Unsure what this is.
return '';
}
case 'TSConstructorType': {
return `new ${ getFunctionTypeAnnotation( typeAnnotation, ': ' ) }`;
}
case 'TSExpressionWithTypeArguments': {
// Unsure with this is.
return '';
}
case 'TSFunctionType': {
return getFunctionTypeAnnotation( typeAnnotation, ' => ' );
}
case 'TSImportType': {
return getImportTypeAnnotation( typeAnnotation );
}
case 'TSIndexedAccessType': {
return getIndexedAccessTypeAnnotation( typeAnnotation );
}
case 'TSIntersectionType': {
return getIntersectionTypeAnnotation( typeAnnotation );
}
case 'TSLiteralType': {
return getLiteralTypeAnnotation( typeAnnotation );
}
case 'TSMappedType': {
return getMappedTypeAnnotation( typeAnnotation );
}
case 'TSNeverKeyword': {
return 'never';
}
case 'TSNullKeyword': {
return 'null';
}
case 'TSNumberKeyword': {
return 'number';
}
case 'TSObjectKeyword': {
return 'object';
}
case 'TSOptionalType': {
return `${ getTypeAnnotation( typeAnnotation.typeAnnotation ) }?`;
}
case 'TSParenthesizedType': {
return `( ${ getTypeAnnotation(
typeAnnotation.typeAnnotation
) } )`;
}
case 'TSRestType': {
return `...${ getTypeAnnotation( typeAnnotation.typeAnnotation ) }`;
}
case 'TSStringKeyword': {
return 'string';
}
case 'TSSymbolKeyword': {
return 'symbol';
}
case 'TSThisType': {
return 'this';
}
case 'TSTupleType': {
return getTupleTypeAnnotation( typeAnnotation );
}
case 'TSTypeLiteral': {
return getTypeLiteralTypeAnnotation( typeAnnotation );
}
case 'TSTypeOperator': {
return `${ typeAnnotation.operator } ${ getTypeAnnotation(
typeAnnotation.typeAnnotation
) }`;
}
case 'TSTypePredicate': {
return `${
typeAnnotation.parameterName.name
} is ${ getTypeAnnotation(
typeAnnotation.typeAnnotation.typeAnnotation
) }`;
}
case 'TSTypeQuery': {
// Unsure what this is.
return '';
}
case 'TSTypeReference': {
return getTypeReferenceTypeAnnotation( typeAnnotation );
}
case 'TSUndefinedKeyword': {
return 'undefined';
}
case 'TSUnionType': {
return getUnionTypeAnnotation( typeAnnotation );
}
case 'TSUnknownKeyword': {
return 'unknown';
}
case 'TSVoidKeyword': {
return 'void';
}
default: {
return '';
}
}
}
/**
* Extract wrapped selector functions to reach inside for parameter types.
*
* This function wasn't necessary until we started introducing more TypeScript code into
* the project. With parameter types fully in the JSDoc comments we always have a direct
* match between parameter name and the type. However, when working in TypeScript where
* we rely on the type annotations for the types we introduce a mismatch when wrapping
* functions.
*
* Example:
* export const getThings = createSelector( ( state ) => state.things, ( state ) => state.version );
*
* In this example we would document `state` but its type is buried inside of `createSelector`.
* Because this kind of scenario is tricky to properly parse without asking TypeScript directly
* to give us the actual type of `getThings` we're going to special-case the known instances
* of selector-wrapping to extract the inner function and re-connect the parameter types
* with their descriptions in the JSDoc comments.
*
* If we find more wrapper functions on selectors we should add them below following the
* example of `createSelector` and `createRegsitrySelector`.
*
* @param {ASTNode} token Contains either a function or a call to a function-wrapper.
*
* TODO: Remove the special-casing here once we're able to infer the types from TypeScript itself.
*/
function unwrapWrappedSelectors( token ) {
if ( babelTypes.isFunctionDeclaration( token ) ) {
return token;
}
if ( babelTypes.isArrowFunctionExpression( token ) ) {
return token;
}
if ( babelTypes.isCallExpression( token ) ) {
// createSelector( ( state, queryId ) => state.queries[ queryId ] );
// \--------------------------------------------/ CallExpression.arguments[0]
if ( token.callee.name === 'createSelector' ) {
return token.arguments[ 0 ];
}
// createRegistrySelector( ( selector ) => ( state, queryId ) => select( 'core/queries' ).get( queryId ) );
// \-----------------------------------------------------------/ CallExpression.arguments[0].body
// \---------------------------------------------------------------------------/ CallExpression.arguments[0]
if ( token.callee.name === 'createRegistrySelector' ) {
return token.arguments[ 0 ].body;
}
}
}
/**
* @param {ASTNode} token
* @return {babelTypes.ArrowFunctionExpression | babelTypes.FunctionDeclaration} The function token.
*/
function getFunctionToken( token ) {
let resolvedToken = token;
if ( babelTypes.isExportDefaultDeclaration( resolvedToken ) ) {
resolvedToken = resolvedToken.declaration;
}
if ( babelTypes.isExportNamedDeclaration( resolvedToken ) ) {
resolvedToken = resolvedToken.declaration;
}
if ( babelTypes.isVariableDeclaration( resolvedToken ) ) {
// Ignore multiple variable declarations.
resolvedToken = resolvedToken.declarations[ 0 ].init;
}
return unwrapWrappedSelectors( resolvedToken );
}
function getFunctionNameForError( declarationToken ) {
let namedFunctionToken = declarationToken;
if (
babelTypes.isExportNamedDeclaration( declarationToken ) ||
babelTypes.isExportDefaultDeclaration( declarationToken )
) {
namedFunctionToken = declarationToken.declaration;
}
if ( babelTypes.isVariableDeclaration( namedFunctionToken ) ) {
namedFunctionToken = namedFunctionToken.declarations[ 0 ];
}
return namedFunctionToken.id.name;
}
function getArrayTagNamePosition( tag ) {
return parseInt( tag.name.split( '.' ).slice( -1 )[ 0 ], 0 );
}
function getQualifiedArrayPatternTypeAnnotation( tag, paramType ) {
if ( babelTypes.isTSArrayType( paramType ) ) {
if ( babelTypes.isTSTypeReference( paramType.elementType ) ) {
// Just get the element type for the array.
return paramType.elementType.typeName.name;
}
return getTypeAnnotation( paramType.elementType.typeAnnotation );
} else if ( babelTypes.isTSTupleType( paramType ) ) {
return getTypeAnnotation(
paramType.elementTypes[ getArrayTagNamePosition( tag ) ]
);
}
// Anything else, `Alias[ position ]`.
return `( ${ getTypeAnnotation( paramType ) } )[ ${ getArrayTagNamePosition(
tag
) } ]`;
}
function getQualifiedObjectPatternTypeAnnotation( tag, paramType ) {
const memberName = tag.name.split( '.' ).slice( -1 )[ 0 ];
if ( babelTypes.isTSTypeLiteral( paramType ) ) {
// If it's a type literal we can try to find the member on the type.
const member = paramType.members.find(
( m ) => m.key.name === memberName
);
if ( member !== undefined ) {
return getTypeAnnotation( member.typeAnnotation.typeAnnotation );
}
}
// If we couldn't find a specific member for the type then we'll just return something like `Type[ memberName ]` to indicate the parameter is a member of that type.
const typeAnnotation = getTypeAnnotation( paramType );
return `${ typeAnnotation }[ '${ memberName }' ]`;
}
/**
* @param {CommentTag} tag The documented parameter.
* @param {ASTNode} declarationToken The function the parameter is documented on.
* @param {number} paramIndex The parameter index.
* @return {string?} The parameter's type annotation.
*/
function getParamTypeAnnotation( tag, declarationToken, paramIndex ) {
const functionToken = getFunctionToken( declarationToken );
// Otherwise find the corresponding parameter token for the documented parameter.
let paramToken = functionToken.params[ paramIndex ];
// This shouldn't happen due to our ESLint enforcing correctly documented parameter names but just in case
// we'll give a descriptive error so that it's easy to diagnose the issue.
if ( ! paramToken ) {
throw new Error(
`Could not find corresponding parameter token for documented parameter '${
tag.name
}' in function '${ getFunctionNameForError( declarationToken ) }'.`
);
}
if ( babelTypes.isAssignmentPattern( paramToken ) ) {
paramToken = paramToken.left;
}
if (
! paramToken.typeAnnotation ||
! paramToken.typeAnnotation.typeAnnotation
) {
return;
}
const paramType = paramToken.typeAnnotation.typeAnnotation;
const isQualifiedName = tag.name.includes( '.' );
if (
babelTypes.isIdentifier( paramToken ) ||
babelTypes.isRestElement( paramToken ) ||
( ( babelTypes.isArrayPattern( paramToken ) ||
babelTypes.isObjectPattern( paramToken ) ) &&
! isQualifiedName )
) {
return getTypeAnnotation( paramType );
} else if ( babelTypes.isArrayPattern( paramToken ) ) {
return getQualifiedArrayPatternTypeAnnotation( tag, paramType );
} else if ( babelTypes.isObjectPattern( paramToken ) ) {
return getQualifiedObjectPatternTypeAnnotation( tag, paramType );
}
}
/**
* @param {ASTNode} declarationToken A function token.
* @return {string?} The function's return type annotation.
*/
function getReturnTypeAnnotation( declarationToken ) {
const functionToken = getFunctionToken( declarationToken );
if ( ! functionToken.returnType ) {
return;
}
return getTypeAnnotation( functionToken.returnType.typeAnnotation );
}
/**
* @param {ASTNode} declarationToken
* @return {string?} The type annotation for the variable.
*/
function getVariableTypeAnnotation( declarationToken ) {
let resolvedToken = declarationToken;
if ( babelTypes.isExportNamedDeclaration( resolvedToken ) ) {
resolvedToken = resolvedToken.declaration;
}
if ( babelTypes.isClassDeclaration( resolvedToken ) ) {
// Just use the classname if we're exporting a class.
return resolvedToken.id.name;
}
if ( babelTypes.isVariableDeclaration( resolvedToken ) ) {
resolvedToken = resolvedToken.declarations[ 0 ].id;
}
try {
return getTypeAnnotation( resolvedToken.typeAnnotation.typeAnnotation );
} catch ( e ) {
// Assume it's a fully undocumented variable, there's nothing we can do about that but fail silently.
}
}
module.exports =
/**
* @param {CommentTag} tag A comment tag.
* @param {ASTNode} token A function token.
* @param {number | null} index The index of the parameter or `null` if not a param tag.
* @return {[string]} The type annotation for the given tag or null if the tag has no type annotation.
*/
function ( tag, token, index ) {
// If the file is using JSDoc type annotations, use the JSDoc.
if ( tag.type ) {
return tag.type;
}
switch ( tag.tag ) {
case 'param': {
return getParamTypeAnnotation( tag, token, index );
}
case 'return': {
return getReturnTypeAnnotation( token );
}
case 'type': {
return getVariableTypeAnnotation( token );
}
}
};