-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathinfinite-reactive-loop.ts
383 lines (359 loc) · 11.1 KB
/
infinite-reactive-loop.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
import type { TSESTree } from "@typescript-eslint/types"
import type { AST } from "svelte-eslint-parser"
import { createRule } from "../utils"
import type { RuleContext } from "../types"
import { findVariable } from "../utils/ast-utils"
import { traverseNodes } from "svelte-eslint-parser"
import { extractSvelteLifeCycleReferences } from "./reference-helpers/svelte-lifecycle"
import { extractTaskReferences } from "./reference-helpers/microtask"
/**
* If `node` is inside of `maybeAncestorNode`, return true.
*/
function isChildNode(
maybeAncestorNode: TSESTree.Node | AST.SvelteNode,
node: TSESTree.Node,
): boolean {
let parent = node.parent
while (parent) {
if (parent === maybeAncestorNode) return true
parent = parent.parent
}
return false
}
/**
* Return true if `node` is a function call.
*/
function isFunctionCall(node: TSESTree.Node): boolean {
if (node.type !== "Identifier") return false
const { parent } = node
if (parent?.type !== "CallExpression") return false
return parent.callee.type === "Identifier" && parent.callee.name === node.name
}
/**
* Return true if `node` is a reactive variable.
*/
function isReactiveVariableNode(
reactiveVariableReferences: TSESTree.Identifier[],
node: TSESTree.Node,
): node is TSESTree.Identifier {
if (node.type !== "Identifier") return false
return reactiveVariableReferences.includes(node)
}
/**
* e.g. foo.bar = baz + 1
* If node is `foo`, return true.
* Otherwise, return false.
*/
function isNodeForAssign(node: TSESTree.Identifier): boolean {
const { parent } = node
if (parent?.type === "AssignmentExpression") {
return parent.left.type === "Identifier" && parent.left.name === node.name
}
return (
parent?.type === "MemberExpression" &&
parent.parent?.type === "AssignmentExpression" &&
parent.parent.left.type === "MemberExpression" &&
parent.parent.left.object.type === "Identifier" &&
parent.parent.left.object.name === node.name
)
}
/**
* Return true if `node` is inside of `then` or `catch`.
*/
function isPromiseThenOrCatchBody(node: TSESTree.Node): boolean {
if (!getDeclarationBody(node)) return false
const { parent } = node
if (
parent?.type !== "CallExpression" ||
parent?.callee?.type !== "MemberExpression"
) {
return false
}
const { property } = parent.callee
if (property?.type !== "Identifier") return false
return ["then", "catch"].includes(property.name)
}
/**
* Get all reactive variable reference.
*/
function getReactiveVariableReferences(context: RuleContext) {
const scopeManager = context.getSourceCode().scopeManager
// Find the top-level (module or global) scope.
// Any variable defined at the top-level (module scope or global scope) can be made reactive.
const toplevelScope =
scopeManager.globalScope?.childScopes.find(
(scope) => scope.type === "module",
) || scopeManager.globalScope
if (!toplevelScope) {
return []
}
// Extracts all reactive references to variables defined in the top-level scope.
const reactiveVariableNodes: TSESTree.Identifier[] = []
for (const variable of toplevelScope.variables) {
for (const reference of variable.references) {
if (
reference.identifier.type === "Identifier" &&
!isFunctionCall(reference.identifier)
) {
reactiveVariableNodes.push(reference.identifier)
}
}
}
return reactiveVariableNodes
}
/**
* Get all tracked reactive variables.
*/
function getTrackedVariableNodes(
reactiveVariableReferences: TSESTree.Identifier[],
ast: AST.SvelteReactiveStatement,
) {
const reactiveVariableNodes: Set<TSESTree.Identifier> = new Set()
for (const identifier of reactiveVariableReferences) {
if (
// If the identifier is within the reactive statement range,
// it is used within the reactive statement.
ast.range[0] <= identifier.range[0] &&
identifier.range[1] <= ast.range[1]
) {
reactiveVariableNodes.add(identifier)
}
}
return reactiveVariableNodes
}
/** */
function getDeclarationBody(
node: TSESTree.Node,
functionName?: string,
): TSESTree.BlockStatement | TSESTree.Expression | null {
if (
node.type === "VariableDeclarator" &&
node.id.type === "Identifier" &&
(!functionName || node.id.name === functionName)
) {
if (
node.init?.type === "ArrowFunctionExpression" ||
node.init?.type === "FunctionExpression"
) {
return node.init.body
}
} else if (
node.type === "FunctionDeclaration" &&
node.id?.type === "Identifier" &&
(!functionName || node.id?.name === functionName)
) {
return node.body
} else if (!functionName && node.type === "ArrowFunctionExpression") {
return node.body
}
return null
}
/** */
function getFunctionDeclarationNode(
context: RuleContext,
functionCall: TSESTree.Identifier,
): TSESTree.BlockStatement | TSESTree.Expression | null {
const variable = findVariable(context, functionCall)
if (!variable) {
return null
}
for (const def of variable.defs) {
if (def.type === "FunctionName") {
if (def.node.type === "FunctionDeclaration") {
return def.node.body
}
}
if (def.type === "Variable") {
if (
def.node.init &&
(def.node.init.type === "FunctionExpression" ||
def.node.init.type === "ArrowFunctionExpression")
) {
return def.node.init.body
}
}
}
return null
}
/**
* If the node is inside of a function, return true.
*
* e.g. `$: await foo()`
* if `node` is `foo`, return false because reactive statement is not function.
*
* e.g. `const bar = () => foo()`
* if `node` is `foo`, return true.
*
*/
function isInsideOfFunction(node: TSESTree.Node) {
let parent: TSESTree.Node | AST.SvelteReactiveStatement | null = node
while (parent) {
parent = parent.parent as TSESTree.Node | AST.SvelteReactiveStatement | null
if (!parent) break
if (parent.type === "FunctionDeclaration" && parent.async) return true
if (
parent.type === "VariableDeclarator" &&
(parent.init?.type === "FunctionExpression" ||
parent.init?.type === "ArrowFunctionExpression") &&
parent.init?.async
) {
return true
}
}
return false
}
/** Let's lint! */
function doLint(
context: RuleContext,
ast: TSESTree.Node,
callFuncIdentifiers: TSESTree.Identifier[],
tickCallExpressions: { node: TSESTree.CallExpression; name: string }[],
taskReferences: {
node: TSESTree.CallExpression
name: string
}[],
reactiveVariableNames: string[],
reactiveVariableReferences: TSESTree.Identifier[],
pIsSameTask: boolean,
) {
const processed = new Set<TSESTree.Node>()
verifyInternal(ast, callFuncIdentifiers, pIsSameTask)
/** verify for node */
function verifyInternal(
ast: TSESTree.Node,
callFuncIdentifiers: TSESTree.Identifier[],
pIsSameTask: boolean,
) {
if (processed.has(ast)) {
// Avoid infinite recursion with recursive references.
return
}
processed.add(ast)
let isSameMicroTask = pIsSameTask
const differentMicroTaskEnterNodes: TSESTree.Node[] = []
traverseNodes(ast, {
enterNode(node) {
// Promise.then() or Promise.catch() is called.
if (isPromiseThenOrCatchBody(node)) {
differentMicroTaskEnterNodes.push(node)
isSameMicroTask = false
}
// `tick`, `setTimeout`, `setInterval` , `queueMicrotask` is called
for (const { node: callExpression } of [
...tickCallExpressions,
...taskReferences,
]) {
if (isChildNode(callExpression, node)) {
differentMicroTaskEnterNodes.push(node)
isSameMicroTask = false
}
}
// left side of await block
if (
node.parent?.type === "AssignmentExpression" &&
node.parent?.right.type === "AwaitExpression" &&
node.parent?.left === node
) {
differentMicroTaskEnterNodes.push(node)
isSameMicroTask = false
}
if (node.type === "Identifier" && isFunctionCall(node)) {
// traverse used functions body
const functionDeclarationNode = getFunctionDeclarationNode(
context,
node,
)
if (functionDeclarationNode) {
verifyInternal(
functionDeclarationNode,
[...callFuncIdentifiers, node],
isSameMicroTask,
)
}
}
if (!isSameMicroTask) {
if (
isReactiveVariableNode(reactiveVariableReferences, node) &&
reactiveVariableNames.includes(node.name) &&
isNodeForAssign(node)
) {
context.report({
node,
loc: node.loc,
messageId: "unexpected",
})
callFuncIdentifiers.forEach((callFuncIdentifier) => {
context.report({
node: callFuncIdentifier,
loc: callFuncIdentifier.loc,
messageId: "unexpectedCall",
data: {
variableName: node.name,
},
})
})
}
}
},
leaveNode(node) {
if (node.type === "AwaitExpression") {
if ((ast.parent?.type as string) === "SvelteReactiveStatement") {
// MEMO: It checks that `await` is used in reactive statement directly or not.
// If `await` is used in inner function of a reactive statement, result of `isInsideOfFunction` will be `true`.
if (!isInsideOfFunction(node)) {
isSameMicroTask = false
}
} else {
isSameMicroTask = false
}
}
if (differentMicroTaskEnterNodes.includes(node)) {
isSameMicroTask = true
}
},
})
}
}
export default createRule("infinite-reactive-loop", {
meta: {
docs: {
description:
"Svelte runtime prevents calling the same reactive statement twice in a microtask. But between different microtask, it doesn't prevent.",
category: "Possible Errors",
// TODO Switch to recommended in the major version.
recommended: false,
},
schema: [],
messages: {
unexpected: "Possibly it may occur an infinite reactive loop.",
unexpectedCall:
"Possibly it may occur an infinite reactive loop because this function may update `{{variableName}}`.",
},
type: "suggestion",
},
create(context) {
const tickCallExpressions = Array.from(
extractSvelteLifeCycleReferences(context, ["tick"]),
)
const taskReferences = Array.from(extractTaskReferences(context))
const reactiveVariableReferences = getReactiveVariableReferences(context)
return {
["SvelteReactiveStatement"]: (ast: AST.SvelteReactiveStatement) => {
const trackedVariableNodes = getTrackedVariableNodes(
reactiveVariableReferences,
ast,
)
doLint(
context,
ast.body,
[],
tickCallExpressions,
taskReferences,
Array.from(trackedVariableNodes).map((node) => node.name),
reactiveVariableReferences,
true,
)
},
}
},
})