-
-
Notifications
You must be signed in to change notification settings - Fork 649
/
ts-ast.js
496 lines (479 loc) · 14.9 KB
/
ts-ast.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
const { findVariable } = require('@eslint-community/eslint-utils')
const { inferRuntimeTypeFromTypeNode } = require('./ts-types')
/**
* @typedef {import('@typescript-eslint/types').TSESTree.TypeNode} TSESTreeTypeNode
* @typedef {import('@typescript-eslint/types').TSESTree.TSInterfaceBody} TSESTreeTSInterfaceBody
* @typedef {import('@typescript-eslint/types').TSESTree.TSTypeLiteral} TSESTreeTSTypeLiteral
* @typedef {import('@typescript-eslint/types').TSESTree.TSFunctionType} TSESTreeTSFunctionType
* @typedef {import('@typescript-eslint/types').TSESTree.Parameter} TSESTreeParameter
* @typedef {import('@typescript-eslint/types').TSESTree.Node} TSESTreeNode
*
*/
/**
* @typedef {import('../index').ComponentTypeProp} ComponentTypeProp
* @typedef {import('../index').ComponentTypeEmit} ComponentTypeEmit
*/
const noop = Function.prototype
module.exports = {
isTypeNode,
flattenTypeNodes,
isTSInterfaceBody,
isTSTypeLiteral,
isTSTypeLiteralOrTSFunctionType,
extractRuntimeProps,
extractRuntimeEmits
}
/**
* @param {ASTNode} node
* @returns {node is TypeNode}
*/
function isTypeNode(node) {
if (
node.type === 'TSAbstractKeyword' ||
node.type === 'TSAnyKeyword' ||
node.type === 'TSAsyncKeyword' ||
node.type === 'TSArrayType' ||
node.type === 'TSBigIntKeyword' ||
node.type === 'TSBooleanKeyword' ||
node.type === 'TSConditionalType' ||
node.type === 'TSConstructorType' ||
node.type === 'TSDeclareKeyword' ||
node.type === 'TSExportKeyword' ||
node.type === 'TSFunctionType' ||
node.type === 'TSImportType' ||
node.type === 'TSIndexedAccessType' ||
node.type === 'TSInferType' ||
node.type === 'TSIntersectionType' ||
node.type === 'TSIntrinsicKeyword' ||
node.type === 'TSLiteralType' ||
node.type === 'TSMappedType' ||
node.type === 'TSNamedTupleMember' ||
node.type === 'TSNeverKeyword' ||
node.type === 'TSNullKeyword' ||
node.type === 'TSNumberKeyword' ||
node.type === 'TSObjectKeyword' ||
node.type === 'TSOptionalType' ||
node.type === 'TSQualifiedName' ||
node.type === 'TSPrivateKeyword' ||
node.type === 'TSProtectedKeyword' ||
node.type === 'TSPublicKeyword' ||
node.type === 'TSReadonlyKeyword' ||
node.type === 'TSRestType' ||
node.type === 'TSStaticKeyword' ||
node.type === 'TSStringKeyword' ||
node.type === 'TSSymbolKeyword' ||
node.type === 'TSTemplateLiteralType' ||
node.type === 'TSThisType' ||
node.type === 'TSTupleType' ||
node.type === 'TSTypeLiteral' ||
node.type === 'TSTypeOperator' ||
node.type === 'TSTypePredicate' ||
node.type === 'TSTypeQuery' ||
node.type === 'TSTypeReference' ||
node.type === 'TSUndefinedKeyword' ||
node.type === 'TSUnionType' ||
node.type === 'TSUnknownKeyword' ||
node.type === 'TSVoidKeyword'
) {
/** @type {TypeNode['type']} for type check */
const type = node.type
noop(type)
return true
}
/** @type {Exclude<ASTNode['type'], TypeNode['type']>} for type check */
const type = node.type
noop(type)
return false
}
/**
* @param {TSESTreeTypeNode|TSESTreeTSInterfaceBody} node
* @returns {node is TSESTreeTSInterfaceBody}
*/
function isTSInterfaceBody(node) {
return node.type === 'TSInterfaceBody'
}
/**
* @param {TSESTreeTypeNode} node
* @returns {node is TSESTreeTSTypeLiteral}
*/
function isTSTypeLiteral(node) {
return node.type === 'TSTypeLiteral'
}
/**
* @param {TSESTreeTypeNode} node
* @returns {node is TSESTreeTSFunctionType}
*/
function isTSFunctionType(node) {
return node.type === 'TSFunctionType'
}
/**
* @param {TSESTreeTypeNode} node
* @returns {node is TSESTreeTSTypeLiteral | TSESTreeTSFunctionType}
*/
function isTSTypeLiteralOrTSFunctionType(node) {
return isTSTypeLiteral(node) || isTSFunctionType(node)
}
/**
* @see https://github.com/vuejs/vue-next/blob/253ca2729d808fc051215876aa4af986e4caa43c/packages/compiler-sfc/src/compileScript.ts#L1512
* @param {RuleContext} context The ESLint rule context object.
* @param {TSESTreeTSTypeLiteral | TSESTreeTSInterfaceBody} node
* @returns {IterableIterator<ComponentTypeProp>}
*/
function* extractRuntimeProps(context, node) {
const members = node.type === 'TSTypeLiteral' ? node.members : node.body
for (const m of members) {
if (
(m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
(m.key.type === 'Identifier' || m.key.type === 'Literal')
) {
/** @type {string[]|undefined} */
let types
if (m.type === 'TSMethodSignature') {
types = ['Function']
} else if (m.typeAnnotation) {
types = inferRuntimeType(context, m.typeAnnotation.typeAnnotation)
}
yield {
type: 'type',
key: /** @type {Identifier | Literal} */ (m.key),
propName: m.key.type === 'Identifier' ? m.key.name : `${m.key.value}`,
node: /** @type {TSPropertySignature | TSMethodSignature} */ (m),
required: !m.optional,
types: types || [`null`]
}
}
}
}
/**
* @see https://github.com/vuejs/vue-next/blob/348c3b01e56383ffa70b180d1376fdf4ac12e274/packages/compiler-sfc/src/compileScript.ts#L1632
* @param {TSESTreeTSTypeLiteral | TSESTreeTSInterfaceBody | TSESTreeTSFunctionType} node
* @returns {IterableIterator<ComponentTypeEmit>}
*/
function* extractRuntimeEmits(node) {
if (node.type === 'TSTypeLiteral' || node.type === 'TSInterfaceBody') {
const members = node.type === 'TSTypeLiteral' ? node.members : node.body
for (const t of members) {
if (t.type === 'TSCallSignatureDeclaration') {
yield* extractEventNames(
t.params[0],
/** @type {TSCallSignatureDeclaration} */ (t)
)
}
}
return
} else {
yield* extractEventNames(
node.params[0],
/** @type {TSFunctionType} */ (node)
)
}
}
/**
* @param {TSESTreeParameter} eventName
* @param {TSCallSignatureDeclaration | TSFunctionType} member
* @returns {IterableIterator<ComponentTypeEmit>}
*/
function* extractEventNames(eventName, member) {
if (
eventName &&
eventName.type === 'Identifier' &&
eventName.typeAnnotation &&
eventName.typeAnnotation.type === 'TSTypeAnnotation'
) {
const typeNode = eventName.typeAnnotation.typeAnnotation
if (
typeNode.type === 'TSLiteralType' &&
typeNode.literal.type === 'Literal'
) {
const emitName = String(typeNode.literal.value)
yield {
type: 'type',
key: /** @type {TSLiteralType} */ (typeNode),
emitName,
node: member
}
} else if (typeNode.type === 'TSUnionType') {
for (const t of typeNode.types) {
if (t.type === 'TSLiteralType' && t.literal.type === 'Literal') {
const emitName = String(t.literal.value)
yield {
type: 'type',
key: /** @type {TSLiteralType} */ (t),
emitName,
node: member
}
}
}
}
}
}
/**
* @param {RuleContext} context The ESLint rule context object.
* @param {TSESTreeTypeNode} node
* @returns {(TSESTreeTypeNode|TSESTreeTSInterfaceBody)[]}
*/
function flattenTypeNodes(context, node) {
/**
* @typedef {object} TraversedData
* @property {Set<TSESTreeTypeNode|TSESTreeTSInterfaceBody>} nodes
* @property {boolean} finished
*/
/** @type {Map<TSESTreeTypeNode,TraversedData>} */
const traversed = new Map()
return [...flattenImpl(node)]
/**
* @param {TSESTreeTypeNode} node
* @returns {Iterable<TSESTreeTypeNode|TSESTreeTSInterfaceBody>}
*/
function* flattenImpl(node) {
if (node.type === 'TSUnionType' || node.type === 'TSIntersectionType') {
for (const typeNode of node.types) {
yield* flattenImpl(typeNode)
}
return
}
if (
node.type === 'TSTypeReference' &&
node.typeName.type === 'Identifier'
) {
const refName = node.typeName.name
const variable = findVariable(context.getScope(), refName)
if (variable && variable.defs.length === 1) {
const defNode = /** @type {TSESTreeNode} */ (variable.defs[0].node)
if (defNode.type === 'TSInterfaceDeclaration') {
yield defNode.body
return
} else if (defNode.type === 'TSTypeAliasDeclaration') {
const typeAnnotation = defNode.typeAnnotation
let traversedData = traversed.get(typeAnnotation)
if (traversedData) {
const copy = [...traversedData.nodes]
yield* copy
if (!traversedData.finished) {
// Include the node because it will probably be referenced recursively.
yield typeAnnotation
}
return
}
traversedData = { nodes: new Set(), finished: false }
traversed.set(typeAnnotation, traversedData)
for (const e of flattenImpl(typeAnnotation)) {
traversedData.nodes.add(e)
}
traversedData.finished = true
yield* traversedData.nodes
return
}
}
}
yield node
}
}
/**
* @param {RuleContext} context The ESLint rule context object.
* @param {TSESTreeTypeNode} node
* @param {Set<TSESTreeTypeNode>} [checked]
* @returns {string[]}
*/
function inferRuntimeType(context, node, checked = new Set()) {
switch (node.type) {
case 'TSStringKeyword':
case 'TSTemplateLiteralType':
return ['String']
case 'TSNumberKeyword':
return ['Number']
case 'TSBooleanKeyword':
return ['Boolean']
case 'TSObjectKeyword':
return ['Object']
case 'TSTypeLiteral':
return inferTypeLiteralType(node)
case 'TSFunctionType':
return ['Function']
case 'TSArrayType':
case 'TSTupleType':
return ['Array']
case 'TSSymbolKeyword':
return ['Symbol']
case 'TSLiteralType':
if (node.literal.type === 'Literal') {
switch (typeof node.literal.value) {
case 'boolean':
return ['Boolean']
case 'string':
return ['String']
case 'number':
case 'bigint':
return ['Number']
}
if (node.literal.value instanceof RegExp) {
return ['RegExp']
}
}
return inferRuntimeTypeFromTypeNode(
context,
/** @type {TypeNode} */ (node)
)
case 'TSTypeReference':
if (node.typeName.type === 'Identifier') {
const variable = findVariable(context.getScope(), node.typeName.name)
if (variable && variable.defs.length === 1) {
const defNode = /** @type {TSESTreeNode} */ (variable.defs[0].node)
if (defNode.type === 'TSInterfaceDeclaration') {
return [`Object`]
}
if (defNode.type === 'TSTypeAliasDeclaration') {
const typeAnnotation = defNode.typeAnnotation
if (!checked.has(typeAnnotation)) {
checked.add(typeAnnotation)
return inferRuntimeType(context, typeAnnotation, checked)
}
}
if (defNode.type === 'TSEnumDeclaration') {
return inferEnumType(context, defNode)
}
}
for (const name of [
node.typeName.name,
...(node.typeName.name.startsWith('Readonly')
? [node.typeName.name.slice(8)]
: [])
]) {
switch (name) {
case 'Array':
case 'Function':
case 'Object':
case 'Set':
case 'Map':
case 'WeakSet':
case 'WeakMap':
case 'Date':
return [name]
}
}
switch (node.typeName.name) {
case 'Record':
case 'Partial':
case 'Readonly':
case 'Pick':
case 'Omit':
case 'Required':
case 'InstanceType':
return ['Object']
case 'Uppercase':
case 'Lowercase':
case 'Capitalize':
case 'Uncapitalize':
return ['String']
case 'Parameters':
case 'ConstructorParameters':
return ['Array']
case 'NonNullable':
if (node.typeParameters && node.typeParameters.params[0]) {
return inferRuntimeType(
context,
node.typeParameters.params[0],
checked
).filter((t) => t !== 'null')
}
break
case 'Extract':
if (node.typeParameters && node.typeParameters.params[1]) {
return inferRuntimeType(
context,
node.typeParameters.params[1],
checked
)
}
break
case 'Exclude':
case 'OmitThisParameter':
if (node.typeParameters && node.typeParameters.params[0]) {
return inferRuntimeType(
context,
node.typeParameters.params[0],
checked
)
}
break
}
}
return inferRuntimeTypeFromTypeNode(
context,
/** @type {TypeNode} */ (node)
)
case 'TSUnionType':
case 'TSIntersectionType':
return inferUnionType(node)
default:
return inferRuntimeTypeFromTypeNode(
context,
/** @type {TypeNode} */ (node)
)
}
/**
* @param {import('@typescript-eslint/types').TSESTree.TSUnionType|import('@typescript-eslint/types').TSESTree.TSIntersectionType} node
* @returns {string[]}
*/
function inferUnionType(node) {
const types = new Set()
for (const t of node.types) {
for (const tt of inferRuntimeType(context, t, checked)) {
types.add(tt)
}
}
return [...types]
}
}
/**
* @param {import('@typescript-eslint/types').TSESTree.TSTypeLiteral} node
* @returns {string[]}
*/
function inferTypeLiteralType(node) {
const types = new Set()
for (const m of node.members) {
switch (m.type) {
case 'TSCallSignatureDeclaration':
case 'TSConstructSignatureDeclaration':
types.add('Function')
break
default:
types.add('Object')
}
}
return types.size > 0 ? [...types] : ['Object']
}
/**
* @param {RuleContext} context The ESLint rule context object.
* @param {import('@typescript-eslint/types').TSESTree.TSEnumDeclaration} node
* @returns {string[]}
*/
function inferEnumType(context, node) {
const types = new Set()
for (const m of node.members) {
if (m.initializer) {
if (m.initializer.type === 'Literal') {
switch (typeof m.initializer.value) {
case 'string':
types.add('String')
break
case 'number':
case 'bigint': // Now it's a syntax error.
types.add('Number')
break
case 'boolean': // Now it's a syntax error.
types.add('Boolean')
break
}
} else {
for (const type of inferRuntimeTypeFromTypeNode(
context,
/** @type {Expression} */ (m.initializer)
)) {
types.add(type)
}
}
}
}
return types.size > 0 ? [...types] : ['Number']
}