-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
switch-exhaustiveness-check.ts
180 lines (160 loc) · 5.46 KB
/
switch-exhaustiveness-check.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
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { getSourceCode } from '@typescript-eslint/utils/eslint-utils';
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';
import {
createRule,
getConstrainedTypeAtLocation,
getParserServices,
isClosingBraceToken,
isOpeningBraceToken,
requiresQuoting,
} from '../util';
export default createRule({
name: 'switch-exhaustiveness-check',
meta: {
type: 'suggestion',
docs: {
description:
'Require switch-case statements to be exhaustive with union types and enums',
requiresTypeChecking: true,
},
hasSuggestions: true,
schema: [],
messages: {
switchIsNotExhaustive:
'Switch is not exhaustive. Cases not matched: {{missingBranches}}',
addMissingCases: 'Add branches for missing cases.',
},
},
defaultOptions: [],
create(context) {
const sourceCode = getSourceCode(context);
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
function fixSwitch(
fixer: TSESLint.RuleFixer,
node: TSESTree.SwitchStatement,
missingBranchTypes: ts.Type[],
symbolName?: string,
): TSESLint.RuleFix | null {
const lastCase =
node.cases.length > 0 ? node.cases[node.cases.length - 1] : null;
const caseIndent = lastCase
? ' '.repeat(lastCase.loc.start.column)
: // if there are no cases, use indentation of the switch statement
// and leave it to user to format it correctly
' '.repeat(node.loc.start.column);
const missingCases = [];
for (const missingBranchType of missingBranchTypes) {
// While running this rule on checker.ts of TypeScript project
// the fix introduced a compiler error due to:
//
// type __String = (string & {
// __escapedIdentifier: void;
// }) | (void & {
// __escapedIdentifier: void;
// }) | InternalSymbolName;
//
// The following check fixes it.
if (missingBranchType.isIntersection()) {
continue;
}
const missingBranchName = missingBranchType.getSymbol()?.escapedName;
let caseTest = checker.typeToString(missingBranchType);
if (
symbolName &&
(missingBranchName || missingBranchName === '') &&
requiresQuoting(missingBranchName.toString(), compilerOptions.target)
) {
const escapedBranchName = missingBranchName
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
caseTest = `${symbolName}['${escapedBranchName}']`;
}
const errorMessage = `Not implemented yet: ${caseTest} case`;
const escapedErrorMessage = errorMessage.replace(/'/g, "\\'");
missingCases.push(
`case ${caseTest}: { throw new Error('${escapedErrorMessage}') }`,
);
}
const fixString = missingCases
.map(code => `${caseIndent}${code}`)
.join('\n');
if (lastCase) {
return fixer.insertTextAfter(lastCase, `\n${fixString}`);
}
// there were no existing cases
const openingBrace = sourceCode.getTokenAfter(
node.discriminant,
isOpeningBraceToken,
)!;
const closingBrace = sourceCode.getTokenAfter(
node.discriminant,
isClosingBraceToken,
)!;
return fixer.replaceTextRange(
[openingBrace.range[0], closingBrace.range[1]],
['{', fixString, `${caseIndent}}`].join('\n'),
);
}
function checkSwitchExhaustive(node: TSESTree.SwitchStatement): void {
const discriminantType = getConstrainedTypeAtLocation(
services,
node.discriminant,
);
const symbolName = discriminantType.getSymbol()?.escapedName;
if (discriminantType.isUnion()) {
const unionTypes = tsutils.unionTypeParts(discriminantType);
const caseTypes = new Set<ts.Type>();
for (const switchCase of node.cases) {
if (switchCase.test == null) {
// Switch has 'default' branch - do nothing.
return;
}
caseTypes.add(
getConstrainedTypeAtLocation(services, switchCase.test),
);
}
const missingBranchTypes = unionTypes.filter(
unionType => !caseTypes.has(unionType),
);
if (missingBranchTypes.length === 0) {
// All cases matched - do nothing.
return;
}
context.report({
node: node.discriminant,
messageId: 'switchIsNotExhaustive',
data: {
missingBranches: missingBranchTypes
.map(missingType =>
tsutils.isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike)
? `typeof ${missingType.getSymbol()?.escapedName as string}`
: checker.typeToString(missingType),
)
.join(' | '),
},
suggest: [
{
messageId: 'addMissingCases',
fix(fixer): TSESLint.RuleFix | null {
return fixSwitch(
fixer,
node,
missingBranchTypes,
symbolName?.toString(),
);
},
},
],
});
}
}
return {
SwitchStatement: checkSwitchExhaustive,
};
},
});