-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
class-methods-use-this.ts
294 lines (274 loc) · 8.02 KB
/
class-methods-use-this.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
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { getSourceCode } from '@typescript-eslint/utils/eslint-utils';
import {
createRule,
getFunctionHeadLoc,
getFunctionNameWithKind,
getStaticStringValue,
} from '../util';
type Options = [
{
exceptMethods?: string[];
enforceForClassFields?: boolean;
ignoreOverrideMethods?: boolean;
ignoreClassesThatImplementAnInterface?: boolean | 'public-fields';
},
];
type MessageIds = 'missingThis';
export default createRule<Options, MessageIds>({
name: 'class-methods-use-this',
meta: {
type: 'suggestion',
docs: {
description: 'Enforce that class methods utilize `this`',
extendsBaseRule: true,
requiresTypeChecking: false,
},
fixable: 'code',
hasSuggestions: false,
schema: [
{
type: 'object',
properties: {
exceptMethods: {
type: 'array',
description:
'Allows specified method names to be ignored with this rule',
items: {
type: 'string',
},
},
enforceForClassFields: {
type: 'boolean',
description:
'Enforces that functions used as instance field initializers utilize `this`',
default: true,
},
ignoreOverrideMethods: {
type: 'boolean',
description: 'Ingore members marked with the `override` modifier',
},
ignoreClassesThatImplementAnInterface: {
oneOf: [
{
type: 'boolean',
description: 'Ignore all classes that implement an interface',
},
{
type: 'string',
enum: ['public-fields'],
description:
'Ignore only the public fields of classes that implement an interface',
},
],
description:
'Ignore classes that specifically implement some interface',
},
},
additionalProperties: false,
},
],
messages: {
missingThis: "Expected 'this' to be used by class {{name}}.",
},
},
defaultOptions: [
{
enforceForClassFields: true,
exceptMethods: [],
ignoreClassesThatImplementAnInterface: false,
ignoreOverrideMethods: false,
},
],
create(
context,
[
{
enforceForClassFields,
exceptMethods: exceptMethodsRaw,
ignoreClassesThatImplementAnInterface,
ignoreOverrideMethods,
},
],
) {
const exceptMethods = new Set(exceptMethodsRaw);
type Stack =
| {
member: null;
class: null;
parent: Stack | undefined;
usesThis: boolean;
}
| {
member: TSESTree.MethodDefinition | TSESTree.PropertyDefinition;
class: TSESTree.ClassDeclaration | TSESTree.ClassExpression;
parent: Stack | undefined;
usesThis: boolean;
};
let stack: Stack | undefined;
const sourceCode = getSourceCode(context);
function pushContext(
member?: TSESTree.MethodDefinition | TSESTree.PropertyDefinition,
): void {
if (member?.parent.type === AST_NODE_TYPES.ClassBody) {
stack = {
member,
class: member.parent.parent as
| TSESTree.ClassDeclaration
| TSESTree.ClassExpression,
usesThis: false,
parent: stack,
};
} else {
stack = {
member: null,
class: null,
usesThis: false,
parent: stack,
};
}
}
function enterFunction(
node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression,
): void {
if (
node.parent.type === AST_NODE_TYPES.MethodDefinition ||
node.parent.type === AST_NODE_TYPES.PropertyDefinition
) {
pushContext(node.parent);
} else {
pushContext();
}
}
/**
* Pop `this` used flag from the stack.
*/
function popContext(): Stack | undefined {
const oldStack = stack;
stack = stack?.parent;
return oldStack;
}
function isPublicField(
accessibility: TSESTree.Accessibility | undefined,
): boolean {
if (!accessibility || accessibility === 'public') {
return true;
}
return false;
}
/**
* Check if the node is an instance method not excluded by config
*/
function isIncludedInstanceMethod(
node: NonNullable<Stack['member']>,
): node is NonNullable<Stack['member']> {
if (
node.static ||
(node.type === AST_NODE_TYPES.MethodDefinition &&
node.kind === 'constructor') ||
(node.type === AST_NODE_TYPES.PropertyDefinition &&
!enforceForClassFields)
) {
return false;
}
if (node.computed || exceptMethods.size === 0) {
return true;
}
const hashIfNeeded =
node.key.type === AST_NODE_TYPES.PrivateIdentifier ? '#' : '';
const name =
node.key.type === AST_NODE_TYPES.Literal
? getStaticStringValue(node.key)
: node.key.name || '';
return !exceptMethods.has(hashIfNeeded + (name ?? ''));
}
/**
* Checks if we are leaving a function that is a method, and reports if 'this' has not been used.
* Static methods and the constructor are exempt.
* Then pops the context off the stack.
*/
function exitFunction(
node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionExpression,
): void {
const stackContext = popContext();
if (
stackContext?.member == null ||
stackContext.usesThis ||
(ignoreOverrideMethods && stackContext.member.override) ||
(ignoreClassesThatImplementAnInterface === true &&
stackContext.class.implements.length > 0) ||
(ignoreClassesThatImplementAnInterface === 'public-fields' &&
stackContext.class.implements.length > 0 &&
isPublicField(stackContext.member.accessibility))
) {
return;
}
if (isIncludedInstanceMethod(stackContext.member)) {
context.report({
node,
loc: getFunctionHeadLoc(node, sourceCode),
messageId: 'missingThis',
data: {
name: getFunctionNameWithKind(node),
},
});
}
}
return {
// function declarations have their own `this` context
FunctionDeclaration(): void {
pushContext();
},
'FunctionDeclaration:exit'(): void {
popContext();
},
FunctionExpression(node): void {
enterFunction(node);
},
'FunctionExpression:exit'(node): void {
exitFunction(node);
},
...(enforceForClassFields
? {
'PropertyDefinition > ArrowFunctionExpression.value'(
node: TSESTree.ArrowFunctionExpression,
): void {
enterFunction(node);
},
'PropertyDefinition > ArrowFunctionExpression.value:exit'(
node: TSESTree.ArrowFunctionExpression,
): void {
exitFunction(node);
},
}
: {}),
/*
* Class field value are implicit functions.
*/
'PropertyDefinition > *.key:exit'(): void {
pushContext();
},
'PropertyDefinition:exit'(): void {
popContext();
},
/*
* Class static blocks are implicit functions. They aren't required to use `this`,
* but we have to push context so that it captures any use of `this` in the static block
* separately from enclosing contexts, because static blocks have their own `this` and it
* shouldn't count as used `this` in enclosing contexts.
*/
StaticBlock(): void {
pushContext();
},
'StaticBlock:exit'(): void {
popContext();
},
'ThisExpression, Super'(): void {
if (stack) {
stack.usesThis = true;
}
},
};
},
});