/
unified-signatures.ts
630 lines (563 loc) · 18.5 KB
/
unified-signatures.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
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
import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils';
import * as util from '../util';
interface Failure {
unify: Unify;
only2: boolean;
}
type Unify =
| {
kind: 'single-parameter-difference';
p0: TSESTree.Parameter;
p1: TSESTree.Parameter;
}
| {
kind: 'extra-parameter';
extraParameter: TSESTree.Parameter;
otherSignature: SignatureDefinition;
};
/**
* Returns true if typeName is the name of an *outer* type parameter.
* In: `interface I<T> { m<U>(x: U): T }`, only `T` is an outer type parameter.
*/
type IsTypeParameter = (typeName: string) => boolean;
type ScopeNode =
| TSESTree.Program
| TSESTree.TSModuleBlock
| TSESTree.TSInterfaceBody
| TSESTree.ClassBody
| TSESTree.TSTypeLiteral;
type OverloadNode = MethodDefinition | SignatureDefinition;
type ContainingNode =
| TSESTree.ExportNamedDeclaration
| TSESTree.ExportDefaultDeclaration;
type SignatureDefinition =
| TSESTree.FunctionExpression
| TSESTree.TSCallSignatureDeclaration
| TSESTree.TSConstructSignatureDeclaration
| TSESTree.TSDeclareFunction
| TSESTree.TSEmptyBodyFunctionExpression
| TSESTree.TSMethodSignature;
type MethodDefinition =
| TSESTree.MethodDefinition
| TSESTree.TSAbstractMethodDefinition;
type MessageIds =
| 'omittingRestParameter'
| 'omittingSingleParameter'
| 'singleParameterDifference';
type Options = [
{
ignoreDifferentlyNamedParameters?: boolean;
},
];
export default util.createRule<Options, MessageIds>({
name: 'unified-signatures',
meta: {
docs: {
description:
'Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter',
// too opinionated to be recommended
recommended: false,
},
type: 'suggestion',
messages: {
omittingRestParameter: '{{failureStringStart}} with a rest parameter.',
omittingSingleParameter:
'{{failureStringStart}} with an optional parameter.',
singleParameterDifference:
'{{failureStringStart}} taking `{{type1}} | {{type2}}`.',
},
schema: [
{
additionalProperties: false,
properties: {
ignoreDifferentlyNamedParameters: {
type: 'boolean',
},
},
type: 'object',
},
],
},
defaultOptions: [
{
ignoreDifferentlyNamedParameters: false,
},
],
create(context, [{ ignoreDifferentlyNamedParameters }]) {
const sourceCode = context.getSourceCode();
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
function failureStringStart(otherLine?: number): string {
// For only 2 overloads we don't need to specify which is the other one.
const overloads =
otherLine === undefined
? 'These overloads'
: `This overload and the one on line ${otherLine}`;
return `${overloads} can be combined into one signature`;
}
function addFailures(failures: Failure[]): void {
for (const failure of failures) {
const { unify, only2 } = failure;
switch (unify.kind) {
case 'single-parameter-difference': {
const { p0, p1 } = unify;
const lineOfOtherOverload = only2 ? undefined : p0.loc.start.line;
const typeAnnotation0 = isTSParameterProperty(p0)
? p0.parameter.typeAnnotation
: p0.typeAnnotation;
const typeAnnotation1 = isTSParameterProperty(p1)
? p1.parameter.typeAnnotation
: p1.typeAnnotation;
context.report({
loc: p1.loc,
messageId: 'singleParameterDifference',
data: {
failureStringStart: failureStringStart(lineOfOtherOverload),
type1: sourceCode.getText(typeAnnotation0?.typeAnnotation),
type2: sourceCode.getText(typeAnnotation1?.typeAnnotation),
},
node: p1,
});
break;
}
case 'extra-parameter': {
const { extraParameter, otherSignature } = unify;
const lineOfOtherOverload = only2
? undefined
: otherSignature.loc.start.line;
context.report({
loc: extraParameter.loc,
messageId:
extraParameter.type === AST_NODE_TYPES.RestElement
? 'omittingRestParameter'
: 'omittingSingleParameter',
data: {
failureStringStart: failureStringStart(lineOfOtherOverload),
},
node: extraParameter,
});
}
}
}
}
function checkOverloads(
signatures: readonly OverloadNode[][],
typeParameters?: TSESTree.TSTypeParameterDeclaration,
): Failure[] {
const result: Failure[] = [];
const isTypeParameter = getIsTypeParameter(typeParameters);
for (const overloads of signatures) {
forEachPair(overloads, (a, b) => {
const signature0 = (a as MethodDefinition).value || a;
const signature1 = (b as MethodDefinition).value || b;
const unify = compareSignatures(
signature0,
signature1,
isTypeParameter,
);
if (unify !== undefined) {
result.push({ unify, only2: overloads.length === 2 });
}
});
}
return result;
}
function compareSignatures(
a: SignatureDefinition,
b: SignatureDefinition,
isTypeParameter: IsTypeParameter,
): Unify | undefined {
if (!signaturesCanBeUnified(a, b, isTypeParameter)) {
return undefined;
}
return a.params.length === b.params.length
? signaturesDifferBySingleParameter(a.params, b.params)
: signaturesDifferByOptionalOrRestParameter(a, b);
}
function signaturesCanBeUnified(
a: SignatureDefinition,
b: SignatureDefinition,
isTypeParameter: IsTypeParameter,
): boolean {
// Must return the same type.
const aTypeParams =
a.typeParameters !== undefined ? a.typeParameters.params : undefined;
const bTypeParams =
b.typeParameters !== undefined ? b.typeParameters.params : undefined;
if (
ignoreDifferentlyNamedParameters &&
a.params.length === b.params.length
) {
for (let i = 0; i < a.params.length; i += 1) {
if (
a.params[i].type === b.params[i].type &&
getStaticParameterName(a.params[i]) !==
getStaticParameterName(b.params[i])
) {
return false;
}
}
}
return (
typesAreEqual(a.returnType, b.returnType) &&
// Must take the same type parameters.
// If one uses a type parameter (from outside) and the other doesn't, they shouldn't be joined.
util.arraysAreEqual(aTypeParams, bTypeParams, typeParametersAreEqual) &&
signatureUsesTypeParameter(a, isTypeParameter) ===
signatureUsesTypeParameter(b, isTypeParameter)
);
}
/** Detect `a(x: number, y: number, z: number)` and `a(x: number, y: string, z: number)`. */
function signaturesDifferBySingleParameter(
types1: readonly TSESTree.Parameter[],
types2: readonly TSESTree.Parameter[],
): Unify | undefined {
const index = getIndexOfFirstDifference(
types1,
types2,
parametersAreEqual,
);
if (index === undefined) {
return undefined;
}
// If remaining arrays are equal, the signatures differ by just one parameter type
if (
!util.arraysAreEqual(
types1.slice(index + 1),
types2.slice(index + 1),
parametersAreEqual,
)
) {
return undefined;
}
const a = types1[index];
const b = types2[index];
// Can unify `a?: string` and `b?: number`. Can't unify `...args: string[]` and `...args: number[]`.
// See https://github.com/Microsoft/TypeScript/issues/5077
return parametersHaveEqualSigils(a, b) &&
a.type !== AST_NODE_TYPES.RestElement
? { kind: 'single-parameter-difference', p0: a, p1: b }
: undefined;
}
/**
* Detect `a(): void` and `a(x: number): void`.
* Returns the parameter declaration (`x: number` in this example) that should be optional/rest, and overload it's a part of.
*/
function signaturesDifferByOptionalOrRestParameter(
a: SignatureDefinition,
b: SignatureDefinition,
): Unify | undefined {
const sig1 = a.params;
const sig2 = b.params;
const minLength = Math.min(sig1.length, sig2.length);
const longer = sig1.length < sig2.length ? sig2 : sig1;
const shorter = sig1.length < sig2.length ? sig1 : sig2;
const shorterSig = sig1.length < sig2.length ? a : b;
// If one is has 2+ parameters more than the other, they must all be optional/rest.
// Differ by optional parameters: f() and f(x), f() and f(x, ?y, ...z)
// Not allowed: f() and f(x, y)
for (let i = minLength + 1; i < longer.length; i++) {
if (!parameterMayBeMissing(longer[i])) {
return undefined;
}
}
for (let i = 0; i < minLength; i++) {
const sig1i = sig1[i];
const sig2i = sig2[i];
const typeAnnotation1 = isTSParameterProperty(sig1i)
? sig1i.parameter.typeAnnotation
: sig1i.typeAnnotation;
const typeAnnotation2 = isTSParameterProperty(sig2i)
? sig2i.parameter.typeAnnotation
: sig2i.typeAnnotation;
if (!typesAreEqual(typeAnnotation1, typeAnnotation2)) {
return undefined;
}
}
if (
minLength > 0 &&
shorter[minLength - 1].type === AST_NODE_TYPES.RestElement
) {
return undefined;
}
return {
extraParameter: longer[longer.length - 1],
kind: 'extra-parameter',
otherSignature: shorterSig,
};
}
/** Given type parameters, returns a function to test whether a type is one of those parameters. */
function getIsTypeParameter(
typeParameters?: TSESTree.TSTypeParameterDeclaration,
): IsTypeParameter {
if (typeParameters === undefined) {
return (() => false) as IsTypeParameter;
}
const set = new Set<string>();
for (const t of typeParameters.params) {
set.add(t.name.name);
}
return (typeName => set.has(typeName)) as IsTypeParameter;
}
/** True if any of the outer type parameters are used in a signature. */
function signatureUsesTypeParameter(
sig: SignatureDefinition,
isTypeParameter: IsTypeParameter,
): boolean {
return sig.params.some((p: TSESTree.Parameter) =>
typeContainsTypeParameter(
isTSParameterProperty(p)
? p.parameter.typeAnnotation
: p.typeAnnotation,
),
);
function typeContainsTypeParameter(
type?: TSESTree.TSTypeAnnotation | TSESTree.TypeNode,
): boolean {
if (!type) {
return false;
}
if (type.type === AST_NODE_TYPES.TSTypeReference) {
const typeName = type.typeName;
if (isIdentifier(typeName) && isTypeParameter(typeName.name)) {
return true;
}
}
return typeContainsTypeParameter(
(type as TSESTree.TSTypeAnnotation).typeAnnotation ||
(type as TSESTree.TSArrayType).elementType,
);
}
}
function isTSParameterProperty(
node: TSESTree.Node,
): node is TSESTree.TSParameterProperty {
return (
(node as TSESTree.TSParameterProperty).type ===
AST_NODE_TYPES.TSParameterProperty
);
}
function parametersAreEqual(
a: TSESTree.Parameter,
b: TSESTree.Parameter,
): boolean {
const typeAnnotationA = isTSParameterProperty(a)
? a.parameter.typeAnnotation
: a.typeAnnotation;
const typeAnnotationB = isTSParameterProperty(b)
? b.parameter.typeAnnotation
: b.typeAnnotation;
return (
parametersHaveEqualSigils(a, b) &&
typesAreEqual(typeAnnotationA, typeAnnotationB)
);
}
/** True for optional/rest parameters. */
function parameterMayBeMissing(p: TSESTree.Parameter): boolean | undefined {
const optional = isTSParameterProperty(p)
? p.parameter.optional
: p.optional;
return p.type === AST_NODE_TYPES.RestElement || optional;
}
/** False if one is optional and the other isn't, or one is a rest parameter and the other isn't. */
function parametersHaveEqualSigils(
a: TSESTree.Parameter,
b: TSESTree.Parameter,
): boolean {
const optionalA = isTSParameterProperty(a)
? a.parameter.optional
: a.optional;
const optionalB = isTSParameterProperty(b)
? b.parameter.optional
: b.optional;
return (
(a.type === AST_NODE_TYPES.RestElement) ===
(b.type === AST_NODE_TYPES.RestElement) &&
(optionalA !== undefined) === (optionalB !== undefined)
);
}
function typeParametersAreEqual(
a: TSESTree.TSTypeParameter,
b: TSESTree.TSTypeParameter,
): boolean {
return (
a.name.name === b.name.name &&
constraintsAreEqual(a.constraint, b.constraint)
);
}
function typesAreEqual(
a: TSESTree.TSTypeAnnotation | undefined,
b: TSESTree.TSTypeAnnotation | undefined,
): boolean {
return (
a === b ||
(a !== undefined &&
b !== undefined &&
sourceCode.getText(a.typeAnnotation) ===
sourceCode.getText(b.typeAnnotation))
);
}
function constraintsAreEqual(
a: TSESTree.TypeNode | undefined,
b: TSESTree.TypeNode | undefined,
): boolean {
return (
a === b || (a !== undefined && b !== undefined && a.type === b.type)
);
}
/* Returns the first index where `a` and `b` differ. */
function getIndexOfFirstDifference<T>(
a: readonly T[],
b: readonly T[],
equal: util.Equal<T>,
): number | undefined {
for (let i = 0; i < a.length && i < b.length; i++) {
if (!equal(a[i], b[i])) {
return i;
}
}
return undefined;
}
/** Calls `action` for every pair of values in `values`. */
function forEachPair<T>(
values: readonly T[],
action: (a: T, b: T) => void,
): void {
for (let i = 0; i < values.length; i++) {
for (let j = i + 1; j < values.length; j++) {
action(values[i], values[j]);
}
}
}
interface Scope {
overloads: Map<string, OverloadNode[]>;
parent?: ScopeNode;
typeParameters?: TSESTree.TSTypeParameterDeclaration;
}
const scopes: Scope[] = [];
let currentScope: Scope = {
overloads: new Map<string, OverloadNode[]>(),
};
function createScope(
parent: ScopeNode,
typeParameters?: TSESTree.TSTypeParameterDeclaration,
): void {
currentScope && scopes.push(currentScope);
currentScope = {
overloads: new Map<string, OverloadNode[]>(),
parent,
typeParameters,
};
}
function checkScope(): void {
const failures = checkOverloads(
Array.from(currentScope.overloads.values()),
currentScope.typeParameters,
);
addFailures(failures);
currentScope = scopes.pop()!;
}
function addOverload(
signature: OverloadNode,
key?: string,
containingNode?: ContainingNode,
): void {
key = key ?? getOverloadKey(signature);
if (
currentScope &&
(containingNode || signature).parent === currentScope.parent
) {
const overloads = currentScope.overloads.get(key);
if (overloads !== undefined) {
overloads.push(signature);
} else {
currentScope.overloads.set(key, [signature]);
}
}
}
//----------------------------------------------------------------------
// Public
//----------------------------------------------------------------------
return {
Program: createScope,
TSModuleBlock: createScope,
TSInterfaceDeclaration(node): void {
createScope(node.body, node.typeParameters);
},
ClassDeclaration(node): void {
createScope(node.body, node.typeParameters);
},
TSTypeLiteral: createScope,
// collect overloads
TSDeclareFunction(node): void {
const exportingNode = getExportingNode(node);
addOverload(node, node.id?.name ?? exportingNode?.type, exportingNode);
},
TSCallSignatureDeclaration: addOverload,
TSConstructSignatureDeclaration: addOverload,
TSMethodSignature: addOverload,
TSAbstractMethodDefinition(node): void {
if (!node.value.body) {
addOverload(node);
}
},
MethodDefinition(node): void {
if (!node.value.body) {
addOverload(node);
}
},
// validate scopes
'Program:exit': checkScope,
'TSModuleBlock:exit': checkScope,
'TSInterfaceDeclaration:exit': checkScope,
'ClassDeclaration:exit': checkScope,
'TSTypeLiteral:exit': checkScope,
};
},
});
function getExportingNode(
node: TSESTree.TSDeclareFunction,
):
| TSESTree.ExportNamedDeclaration
| TSESTree.ExportDefaultDeclaration
| undefined {
return node.parent &&
(node.parent.type === AST_NODE_TYPES.ExportNamedDeclaration ||
node.parent.type === AST_NODE_TYPES.ExportDefaultDeclaration)
? node.parent
: undefined;
}
function getOverloadKey(node: OverloadNode): string {
const info = getOverloadInfo(node);
return (
((node as MethodDefinition).computed ? '0' : '1') +
((node as MethodDefinition).static ? '0' : '1') +
info
);
}
function getOverloadInfo(node: OverloadNode): string {
switch (node.type) {
case AST_NODE_TYPES.TSConstructSignatureDeclaration:
return 'constructor';
case AST_NODE_TYPES.TSCallSignatureDeclaration:
return '()';
default: {
const { key } = node as MethodDefinition;
return isIdentifier(key) ? key.name : (key as TSESTree.Literal).raw;
}
}
}
function getStaticParameterName(param: TSESTree.Node): string | undefined {
switch (param.type) {
case AST_NODE_TYPES.Identifier:
return param.name;
case AST_NODE_TYPES.RestElement:
return getStaticParameterName(param.argument);
default:
return undefined;
}
}
function isIdentifier(node: TSESTree.Node): node is TSESTree.Identifier {
return node.type === AST_NODE_TYPES.Identifier;
}