/
no-unused-state.js
338 lines (301 loc) · 9.89 KB
/
no-unused-state.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
/**
* @fileoverview Attempts to discover all state fields in a React component and
* warn if any of them are never read.
*
* State field definitions are collected from `this.state = {}` assignments in
* the constructor, objects passed to `this.setState()`, and `state = {}` class
* property assignments.
*/
'use strict';
var Components = require('../util/Components');
// Descend through all wrapping TypeCastExpressions and return the expression
// that was cast.
function uncast(node) {
while (node.type === 'TypeCastExpression') {
node = node.expression;
}
return node;
}
// Return the name of an identifier or the string value of a literal. Useful
// anywhere that a literal may be used as a key (e.g., member expressions,
// method definitions, ObjectExpression property keys).
function getName(node) {
node = uncast(node);
if (node.type === 'Identifier') {
return node.name;
} else if (node.type === 'Literal') {
return String(node.value);
}
return null;
}
function isThisExpression(node) {
return uncast(node).type === 'ThisExpression';
}
function getInitialClassInfo() {
return {
// Set of nodes where state fields were defined.
stateFields: [],
// Set of names of state fields that we've seen used.
usedStateFields: [],
// Names of local variables that may be pointing to this.state. To
// track this properly, we would need to keep track of all locals,
// shadowing, assignments, etc. To keep things simple, we only
// maintain one set of aliases per method and accept that it will
// produce some false negatives.
aliases: null
};
}
module.exports = {
meta: {
docs: {
description: 'Prevent definition of unused state fields',
category: 'Best Practices',
recommended: false
},
schema: []
},
create: Components.detect(function(context, components, utils) {
// Non-null when we are inside a React component ClassDeclaration and we have
// not yet encountered any use of this.state which we have chosen not to
// analyze. If we encounter any such usage (like this.state being spread as
// JSX attributes), then this is again set to null.
var classInfo = null;
// Returns true if the given node is possibly a reference to `this.state`.
function isStateReference(node) {
node = uncast(node);
var isDirectStateReference =
node.type === 'MemberExpression' &&
isThisExpression(node.object) &&
node.property.name === 'state';
var isAliasedStateReference =
node.type === 'Identifier' &&
classInfo.aliases &&
classInfo.aliases.indexOf(node.name) >= 0;
return isDirectStateReference || isAliasedStateReference;
}
// Takes an ObjectExpression node and adds all named Property nodes to the
// current set of state fields.
function addStateFields(node) {
node.properties.forEach(function(prop) {
if (prop.type === 'Property' && getName(prop.key) !== null) {
classInfo.stateFields.push(prop);
}
});
}
// Adds the name of the given node as a used state field if the node is an
// Identifier or a Literal. Other node types are ignored.
function addUsedStateField(node) {
var name = getName(node);
if (name) {
classInfo.usedStateFields.push(name);
}
}
// Records used state fields and new aliases for an ObjectPattern which
// destructures `this.state`.
function handleStateDestructuring(node) {
node.properties.forEach(function(prop) {
if (prop.type === 'Property') {
addUsedStateField(prop.key);
} else if (
prop.type === 'ExperimentalRestProperty' &&
classInfo.aliases
) {
classInfo.aliases.push(getName(prop.argument));
}
});
}
// Used to record used state fields and new aliases for both
// AssignmentExpressions and VariableDeclarators.
function handleAssignment(left, right) {
switch (left.type) {
case 'Identifier':
if (isStateReference(right) && classInfo.aliases) {
classInfo.aliases.push(left.name);
}
break;
case 'ObjectPattern':
if (isStateReference(right)) {
handleStateDestructuring(left);
} else if (isThisExpression(right) && classInfo.aliases) {
left.properties.forEach(function(prop) {
if (prop.type === 'Property' && getName(prop.key) === 'state') {
var name = getName(prop.value);
if (name) {
classInfo.aliases.push(name);
} else if (prop.value.type === 'ObjectPattern') {
handleStateDestructuring(prop.value);
}
}
});
}
break;
default:
// pass
}
}
function reportUnusedFields() {
// Report all unused state fields.
classInfo.stateFields.forEach(function(node) {
var name = getName(node.key);
if (classInfo.usedStateFields.indexOf(name) < 0) {
context.report(node, 'Unused state field: \'' + name + '\'');
}
});
}
return {
ClassDeclaration: function(node) {
if (utils.isES6Component(node)) {
classInfo = getInitialClassInfo();
}
},
ObjectExpression: function(node) {
if (utils.isES5Component(node)) {
classInfo = getInitialClassInfo();
}
},
'ObjectExpression:exit': function(node) {
if (!classInfo) {
return;
}
if (utils.isES5Component(node)) {
reportUnusedFields();
classInfo = null;
}
},
'ClassDeclaration:exit': function() {
if (!classInfo) {
return;
}
reportUnusedFields();
classInfo = null;
},
CallExpression: function(node) {
if (!classInfo) {
return;
}
// If we're looking at a `this.setState({})` invocation, record all the
// properties as state fields.
if (
node.callee.type === 'MemberExpression' &&
isThisExpression(node.callee.object) &&
getName(node.callee.property) === 'setState' &&
node.arguments.length > 0 &&
node.arguments[0].type === 'ObjectExpression'
) {
addStateFields(node.arguments[0]);
}
},
ClassProperty: function(node) {
if (!classInfo) {
return;
}
// If we see state being assigned as a class property using an object
// expression, record all the fields of that object as state fields.
if (
getName(node.key) === 'state' &&
!node.static &&
node.value &&
node.value.type === 'ObjectExpression'
) {
addStateFields(node.value);
}
},
MethodDefinition: function() {
if (!classInfo) {
return;
}
// Create a new set for this.state aliases local to this method.
classInfo.aliases = [];
},
'MethodDefinition:exit': function() {
if (!classInfo) {
return;
}
// Forget our set of local aliases.
classInfo.aliases = null;
},
FunctionExpression: function(node) {
if (!classInfo) {
return;
}
var parent = node.parent;
if (!utils.isES5Component(parent.parent)) {
return;
}
if (parent.key.name === 'getInitialState') {
var body = node.body.body;
var lastBodyNode = body[body.length - 1];
if (
lastBodyNode.type === 'ReturnStatement' &&
lastBodyNode.argument.type === 'ObjectExpression'
) {
addStateFields(lastBodyNode.argument);
}
} else {
// Create a new set for this.state aliases local to this method.
classInfo.aliases = [];
}
},
AssignmentExpression: function(node) {
if (!classInfo) {
return;
}
// Check for assignments like `this.state = {}`
if (
node.left.type === 'MemberExpression' &&
isThisExpression(node.left.object) &&
getName(node.left.property) === 'state' &&
node.right.type === 'ObjectExpression'
) {
// Find the nearest function expression containing this assignment.
var fn = node;
while (fn.type !== 'FunctionExpression' && fn.parent) {
fn = fn.parent;
}
// If the nearest containing function is the constructor, then we want
// to record all the assigned properties as state fields.
if (
fn.parent &&
fn.parent.type === 'MethodDefinition' &&
fn.parent.kind === 'constructor'
) {
addStateFields(node.right);
}
} else {
// Check for assignments like `alias = this.state` and record the alias.
handleAssignment(node.left, node.right);
}
},
VariableDeclarator: function(node) {
if (!classInfo || !node.init) {
return;
}
handleAssignment(node.id, node.init);
},
MemberExpression: function(node) {
if (!classInfo) {
return;
}
if (isStateReference(node.object)) {
// If we see this.state[foo] access, give up.
if (node.computed && node.property.type !== 'Literal') {
classInfo = null;
return;
}
// Otherwise, record that we saw this property being accessed.
addUsedStateField(node.property);
}
},
JSXSpreadAttribute: function(node) {
if (classInfo && isStateReference(node.argument)) {
classInfo = null;
}
},
ExperimentalSpreadProperty: function(node) {
if (classInfo && isStateReference(node.argument)) {
classInfo = null;
}
}
};
})
};