@typeonce/oxlint-plugin-ritmo 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +88 -22
  3. package/dist/index.js +13 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/internal/ast.d.ts +43 -0
  6. package/dist/internal/ast.d.ts.map +1 -1
  7. package/dist/internal/ast.js +127 -0
  8. package/dist/internal/ast.js.map +1 -1
  9. package/dist/rules/handle-runtime-result.d.ts.map +1 -1
  10. package/dist/rules/handle-runtime-result.js +82 -10
  11. package/dist/rules/handle-runtime-result.js.map +1 -1
  12. package/dist/rules/keep-simulation-headless.d.ts +3 -3
  13. package/dist/rules/keep-simulation-headless.d.ts.map +1 -1
  14. package/dist/rules/keep-simulation-headless.js +30 -15
  15. package/dist/rules/keep-simulation-headless.js.map +1 -1
  16. package/dist/rules/no-float-timers.d.ts +2 -2
  17. package/dist/rules/no-float-timers.d.ts.map +1 -1
  18. package/dist/rules/no-float-timers.js +133 -20
  19. package/dist/rules/no-float-timers.js.map +1 -1
  20. package/dist/rules/no-infinity-in-simulation-data.d.ts.map +1 -1
  21. package/dist/rules/no-infinity-in-simulation-data.js +134 -10
  22. package/dist/rules/no-infinity-in-simulation-data.js.map +1 -1
  23. package/dist/rules/no-kept-query-values.d.ts +9 -0
  24. package/dist/rules/no-kept-query-values.d.ts.map +1 -0
  25. package/dist/rules/no-kept-query-values.js +375 -0
  26. package/dist/rules/no-kept-query-values.js.map +1 -0
  27. package/dist/rules/no-state-spread.d.ts.map +1 -1
  28. package/dist/rules/no-state-spread.js +137 -14
  29. package/dist/rules/no-state-spread.js.map +1 -1
  30. package/dist/rules/use-clock-for-time.d.ts.map +1 -1
  31. package/dist/rules/use-clock-for-time.js +31 -15
  32. package/dist/rules/use-clock-for-time.js.map +1 -1
  33. package/dist/rules/use-keyboard-for-game-keys.d.ts +9 -0
  34. package/dist/rules/use-keyboard-for-game-keys.d.ts.map +1 -0
  35. package/dist/rules/use-keyboard-for-game-keys.js +81 -0
  36. package/dist/rules/use-keyboard-for-game-keys.js.map +1 -0
  37. package/dist/rules/use-ops-for-math.d.ts.map +1 -1
  38. package/dist/rules/use-ops-for-math.js +11 -7
  39. package/dist/rules/use-ops-for-math.js.map +1 -1
  40. package/dist/rules/use-random-for-randomness.d.ts.map +1 -1
  41. package/dist/rules/use-random-for-randomness.js +11 -13
  42. package/dist/rules/use-random-for-randomness.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/index.ts +13 -6
  45. package/src/internal/ast.ts +125 -0
  46. package/src/rules/handle-runtime-result.ts +86 -8
  47. package/src/rules/keep-simulation-headless.ts +32 -12
  48. package/src/rules/no-float-timers.ts +124 -19
  49. package/src/rules/no-infinity-in-simulation-data.ts +133 -10
  50. package/src/rules/no-kept-query-values.ts +353 -0
  51. package/src/rules/no-state-spread.ts +140 -12
  52. package/src/rules/use-clock-for-time.ts +31 -14
  53. package/src/rules/use-keyboard-for-game-keys.ts +85 -0
  54. package/src/rules/use-ops-for-math.ts +10 -10
  55. package/src/rules/use-random-for-randomness.ts +9 -11
@@ -1,19 +1,46 @@
1
1
  import { defineRule } from "@oxlint/plugins"
2
2
  import type { Context, ESTree } from "@oxlint/plugins"
3
3
 
4
- import { docsUrl, globalMember, isGlobalIdentifier } from "../internal/ast.ts"
4
+ import { docsUrl, globalMember, globalPath, isGlobalIdentifier } from "../internal/ast.ts"
5
5
 
6
- /** Whether `node` is Infinity, -Infinity, NaN, or Number's names for them. */
7
- const nonFinite = (context: Context, node: ESTree.Node): boolean => {
6
+ /** `node` without the wrappers that keep its value (`x as number`, `x!`, `(x)`). */
7
+ const unwrap = (node: ESTree.Node): ESTree.Node =>
8
+ node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression" || node.type === "ParenthesizedExpression"
9
+ ? unwrap(node.expression)
10
+ : node
11
+
12
+ const isNumber = (node: ESTree.Node): boolean => {
13
+ const value = unwrap(node)
14
+ if (value.type === "UnaryExpression" && (value.operator === "-" || value.operator === "+")) return isNumber(value.argument)
15
+ return value.type === "Literal" && typeof value.value === "number"
16
+ }
17
+
18
+ /** Whether `node` is Infinity, -Infinity, NaN, Number's names for them, `1 / 0`, or `Math.min()` / `Math.max()` of nothing. */
19
+ const nonFinite = (context: Context, raw: ESTree.Node): boolean => {
20
+ const node = unwrap(raw)
8
21
  if (node.type === "UnaryExpression" && (node.operator === "-" || node.operator === "+")) return nonFinite(context, node.argument)
9
22
  if (isGlobalIdentifier(context, node, "Infinity") || isGlobalIdentifier(context, node, "NaN")) return true
10
23
  if (node.type === "MemberExpression") {
11
24
  const name = globalMember(context, node, "Number")
12
25
  return name === "POSITIVE_INFINITY" || name === "NEGATIVE_INFINITY" || name === "NaN"
13
26
  }
27
+ if (node.type === "BinaryExpression" && node.operator === "/") {
28
+ const divisor = unwrap(node.right)
29
+ return isNumber(node.left) && divisor.type === "Literal" && divisor.value === 0
30
+ }
31
+ if (node.type === "CallExpression" && node.arguments.length === 0) {
32
+ const path = globalPath(context, node.callee)
33
+ return path === "Math.min" || path === "Math.max"
34
+ }
14
35
  return false
15
36
  }
16
37
 
38
+ const comparisons = new Set(["<", "<=", ">", ">=", "===", "!==", "==", "!="])
39
+ const finiteChecks = new Set(["isFinite", "isNaN", "Number.isFinite", "Number.isNaN"])
40
+
41
+ /** Whether `node` is an operand of a comparison: `hit.time < limit`. */
42
+ const isCompared = (node: ESTree.Node): boolean => node.parent?.type === "BinaryExpression" && comparisons.has(node.parent.operator)
43
+
17
44
  /**
18
45
  * Simulation data stays finite: Infinity and NaN cannot be saved, so a world
19
46
  * holding them no longer loads.
@@ -27,19 +54,115 @@ export default defineRule({
27
54
  },
28
55
  messages: {
29
56
  nonFinite:
30
- "`{{key}}: {{value}}` cannot be saved: JSON turns it into null and a number schema rejects it, so the save no longer loads (and devtools warns `non-finite-value`). Use `null` for \"never\" or \"no limit\": type the field `number | null` and give it a nullable number schema. For a value that only some entities have (a timer on a non-permanent pool), make that part optional: `timer: { remaining: number; duration: number } | null`."
57
+ "`{{text}}` puts Infinity or NaN in data, which cannot be saved: JSON turns it into null and a number schema rejects it, so the save no longer loads (and devtools warns `non-finite-value`). Use `null` for \"never\" or \"no limit\": type the field `number | null` and give it a nullable number schema. For a value that only some entities have (a timer on a non-permanent pool), make that part optional: `timer: { remaining: number; duration: number } | null`.",
58
+ seed:
59
+ "`{{text}}` stores `{{name}}`, which starts as `{{value}}` and keeps it when nothing replaces it (a search that finds nothing). Infinity and NaN cannot be saved: JSON turns them into null and a number schema rejects it, so the save no longer loads (and devtools warns `non-finite-value`). Check it before storing it: `Number.isFinite({{name}}) ? {{name}} : null`, with a nullable number schema, or store what the search found instead."
31
60
  },
32
61
  schema: []
33
62
  },
34
63
  create(context) {
64
+ const text = (node: ESTree.Node): string => context.sourceCode.getText(node)
65
+
66
+ /** The variable `node` names, if a declaration in the file binds it. */
67
+ const variableOf = (node: ESTree.Node) =>
68
+ context.sourceCode.getScope(node).references.find((reference) => reference.identifier === node)?.resolved ?? undefined
69
+
70
+ /** Whether every use of a `const` reads a field of it to compare (`hit.time < limit`), and there is one. */
71
+ const onlyCompared = (declarator: ESTree.VariableDeclarator): boolean => {
72
+ const [variable] = context.sourceCode.getDeclaredVariables(declarator)
73
+ const uses = variable?.references.filter((reference) => reference.identifier !== declarator.id) ?? []
74
+ return uses.length > 0 && uses.every((reference) => {
75
+ const read = reference.identifier.parent
76
+ return read?.type === "MemberExpression" && read.object === reference.identifier && isCompared(read)
77
+ })
78
+ }
79
+
80
+ /**
81
+ * Whether a literal is local scratch, never stored: a search seed in a
82
+ * `let` (overwritten before anything is stored), a fallback in a function
83
+ * only compared (`(sweep ?? { time: Infinity }).time < limit`), values a
84
+ * `for...of` tries one by one, or a part of one of these.
85
+ */
86
+ const isScratch = (literal: ESTree.Node): boolean => {
87
+ let node = literal
88
+ let parent = node.parent
89
+ while (
90
+ parent !== null &&
91
+ ((parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression" || parent.type === "TSSatisfiesExpression" || parent.type === "ParenthesizedExpression") ||
92
+ (parent.type === "LogicalExpression" && parent.right === node) ||
93
+ (parent.type === "ConditionalExpression" && parent.test !== node))
94
+ ) {
95
+ node = parent
96
+ parent = node.parent
97
+ }
98
+ if (parent === null) return false
99
+ if (parent.type === "Property" && parent.value === node && parent.parent.type === "ObjectExpression") return isScratch(parent.parent)
100
+ if (parent.type === "ArrayExpression") return isScratch(parent)
101
+ if (parent.type === "MemberExpression" && parent.object === node) return isCompared(parent)
102
+ // `for (const size of [0, Infinity])`: values tried one by one, a local each time.
103
+ if (parent.type === "ForOfStatement" && parent.right === node) return true
104
+ if (parent.type !== "VariableDeclarator" || parent.init !== node || parent.id.type !== "Identifier") return false
105
+ const declaration = parent.parent
106
+ if (declaration.type !== "VariableDeclaration") return false
107
+ if (declaration.kind === "let") return true
108
+ return declaration.kind === "const" && context.sourceCode.getScope(parent).variableScope.type !== "module" && onlyCompared(parent)
109
+ }
110
+
111
+ /** The non-finite value a variable is declared with (`let best = Infinity`, `const LIMIT = Infinity`), if it is. */
112
+ const declaredAs = (node: ESTree.Node): { readonly value: string; readonly kind: string } | undefined => {
113
+ const variable = variableOf(node)
114
+ const definition = variable?.defs.length === 1 ? variable.defs[0] : undefined
115
+ if (definition?.type !== "Variable" || definition.node.type !== "VariableDeclarator" || definition.node.id.type !== "Identifier") return undefined
116
+ const init = definition.node.init
117
+ if (init === null || init === undefined || !nonFinite(context, init) || definition.parent?.type !== "VariableDeclaration") return undefined
118
+ return { value: text(init), kind: definition.parent.kind }
119
+ }
120
+
121
+ /** Whether the code checks a variable against Infinity or NaN before relying on it (`best === Infinity`, `Number.isFinite(best)`). */
122
+ const isChecked = (node: ESTree.Node): boolean =>
123
+ variableOf(node)?.references.some((reference) => {
124
+ const use = reference.identifier
125
+ const parent = use.parent
126
+ if (parent?.type === "BinaryExpression" && comparisons.has(parent.operator)) {
127
+ return nonFinite(context, parent.left === use ? parent.right : parent.left)
128
+ }
129
+ if (parent?.type === "CallExpression" && parent.arguments.some((argument) => argument === use)) return finiteChecks.has(globalPath(context, parent.callee) ?? "")
130
+ return false
131
+ }) ?? false
132
+
133
+ /** Reports a value stored in a literal (`at` is the property or the element) that holds Infinity or NaN. */
134
+ const check = (value: ESTree.Node, at: ESTree.Node): void => {
135
+ const node = unwrap(value)
136
+ if (nonFinite(context, node)) {
137
+ context.report({ node: at, messageId: "nonFinite", data: { text: text(at) } })
138
+ return
139
+ }
140
+ // `make(Infinity)`: whatever it builds from Infinity is stored. Math and Number give back numbers.
141
+ if (node.type === "CallExpression" && node.arguments.some((argument) => nonFinite(context, argument))) {
142
+ const path = globalPath(context, node.callee)
143
+ if (path === undefined || !(path.startsWith("Math.") || path.startsWith("Number."))) {
144
+ context.report({ node: at, messageId: "nonFinite", data: { text: text(at) } })
145
+ }
146
+ return
147
+ }
148
+ if (node.type !== "Identifier") return
149
+ const declared = declaredAs(node)
150
+ if (declared === undefined) return
151
+ // `const LIMIT = Infinity` is Infinity; `let best = Infinity` is a seed the search may replace, so a check before storing it is enough.
152
+ if (declared.kind === "const") context.report({ node: at, messageId: "nonFinite", data: { text: text(at) } })
153
+ else if (!isChecked(node)) context.report({ node: at, messageId: "seed", data: { text: text(at), name: node.name, value: declared.value } })
154
+ }
155
+
35
156
  return {
36
157
  Property(node) {
37
- if (node.kind !== "init" || !nonFinite(context, node.value)) return
38
- context.report({
39
- node,
40
- messageId: "nonFinite",
41
- data: { key: context.sourceCode.getText(node.key), value: context.sourceCode.getText(node.value) }
42
- })
158
+ if (node.kind !== "init" || node.parent.type !== "ObjectExpression" || isScratch(node.parent)) return
159
+ check(node.value, node)
160
+ },
161
+ ArrayExpression(node) {
162
+ if (isScratch(node)) return
163
+ for (const element of node.elements) {
164
+ if (element !== null && element.type !== "SpreadElement") check(element, element)
165
+ }
43
166
  }
44
167
  }
45
168
  }
@@ -0,0 +1,353 @@
1
+ import { defineRule } from "@oxlint/plugins"
2
+ import type { ESTree } from "@oxlint/plugins"
3
+
4
+ import { calledMethod, docsUrl, globalPath, propertyKey, propertyName } from "../internal/ast.ts"
5
+
6
+ type Kind = "entity" | "data"
7
+
8
+ /** Array methods whose callback's first parameter is one entity of the array they are called on. */
9
+ const callbacks = new Set(["map", "forEach", "filter", "find", "findLast", "some", "every", "flatMap"])
10
+ /** Array methods that return one entity, or entities, of the array they are called on. */
11
+ const picks = new Set(["find", "findLast", "at", "filter", "slice", "toSorted", "toReversed"])
12
+ /** Array methods that return what their callback returns, for each entity. */
13
+ const maps = new Set(["map", "flatMap"])
14
+ /** Collection methods that keep their argument. */
15
+ const keeps = new Set(["push", "unshift", "add", "set"])
16
+
17
+ /** `queries.x.each()` */
18
+ const isEach = (node: ESTree.Node): boolean =>
19
+ node.type === "CallExpression" && calledMethod(node) === "each" && node.arguments.length === 0
20
+
21
+ /** Unwraps what passes a value through unchanged: `x!`, `(x)`, `x as T`, `a?.b`. */
22
+ const unwrap = (node: ESTree.Node): ESTree.Node => {
23
+ let current = node
24
+ while (
25
+ current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression" ||
26
+ current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "ChainExpression"
27
+ ) current = current.expression
28
+ return current
29
+ }
30
+
31
+ /** The root of a member chain: `local` in `local.cache.targets`. */
32
+ const rootOf = (node: ESTree.Node): ESTree.Node => {
33
+ let current = unwrap(node)
34
+ while (current.type === "MemberExpression") current = unwrap(current.object)
35
+ return current
36
+ }
37
+
38
+ const isFunction = (node: ESTree.Node | null | undefined): node is ESTree.ArrowFunctionExpression | ESTree.Function =>
39
+ node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "FunctionDeclaration"
40
+
41
+ /** Whether `call` is `Game.System(...)` or `Game.Inspector(...)`. */
42
+ const isSystemCall = (call: ESTree.Node | null | undefined): call is ESTree.CallExpression => {
43
+ if (call?.type !== "CallExpression") return false
44
+ const method = calledMethod(call)
45
+ return method === "System" || method === "Inspector"
46
+ }
47
+
48
+ /** The expressions a function returns: its expression body, or the `return`s of its body's own statements. */
49
+ const returnedBy = (fn: ESTree.Node): ReadonlyArray<ESTree.Node> => {
50
+ if (!isFunction(fn) || fn.body === null) return []
51
+ if (fn.body.type !== "BlockStatement") return [fn.body]
52
+ const found: Array<ESTree.Node> = []
53
+ const visit = (statement: ESTree.Node | null | undefined): void => {
54
+ if (statement === null || statement === undefined) return
55
+ if (statement.type === "ReturnStatement" && statement.argument !== null) found.push(statement.argument)
56
+ if (statement.type === "BlockStatement") statement.body.forEach(visit)
57
+ if (statement.type === "IfStatement") {
58
+ visit(statement.consequent)
59
+ visit(statement.alternate)
60
+ }
61
+ }
62
+ fn.body.body.forEach(visit)
63
+ return found
64
+ }
65
+
66
+ const inside = (node: ESTree.Node, outer: ESTree.Node): boolean => node.range[0] >= outer.range[0] && node.range[1] <= outer.range[1]
67
+
68
+ /**
69
+ * An entity from `queries.x.each()` or the system's `queries.x.data` lives for
70
+ * one run. Kept in `local` state or in a variable outside the system, the data
71
+ * throws in the next run, and the entity keeps reading after it left the
72
+ * query: keep the id, or read the values into plain rows.
73
+ */
74
+ export default defineRule({
75
+ meta: {
76
+ type: "problem",
77
+ docs: {
78
+ description: "Keep an entity's id or plain values past a run, not the entity from queries.x.each() or queries.x.data.",
79
+ url: docsUrl("no-kept-query-values")
80
+ },
81
+ messages: {
82
+ entity:
83
+ "`{{name}}` is an entity from a query, kept past the run: in a later run it is not checked against the query again, so a runtime without `debug` reads it after it left (`without`, `with`), and a debug runtime throws. Keep {{id}} and resolve it with `queries.x.get(id)` in each run, which is fallible.",
84
+ data:
85
+ "`{{name}}` is a query's `data`, kept past the run: it throws when used in a later run. Read `queries.x.data` again in each run, or keep plain values from `queries.x.rows()`."
86
+ },
87
+ schema: []
88
+ },
89
+ create(context) {
90
+ const kinds = new Map<unknown, Kind>()
91
+ const text = (node: ESTree.Node): string => context.sourceCode.getText(node)
92
+
93
+ const variableOf = (node: ESTree.Node) =>
94
+ context.sourceCode.getScope(node).references.find((reference) => reference.identifier === node)?.resolved ?? undefined
95
+
96
+ /** Functions declared apart and passed to `Game.System(...)` by name (`Game.System(name, spec, run)`). */
97
+ let named: Set<ESTree.Node> | undefined
98
+ const namedSystems = (): Set<ESTree.Node> => {
99
+ if (named !== undefined) return named
100
+ named = new Set()
101
+ for (const scope of context.sourceCode.scopeManager.scopes) {
102
+ for (const reference of scope.references) {
103
+ const call = reference.identifier.parent
104
+ if (!isSystemCall(call) || !call.arguments.some((argument) => argument === reference.identifier)) continue
105
+ for (const definition of reference.resolved?.defs ?? []) {
106
+ if (definition.type === "FunctionName") named.add(definition.node)
107
+ if (definition.type === "Variable" && definition.node.type === "VariableDeclarator" && isFunction(definition.node.init)) named.add(definition.node.init)
108
+ }
109
+ }
110
+ }
111
+ return named
112
+ }
113
+
114
+ /** Whether `fn` is a system's or an inspector's run: passed to `Game.System(...)` inline or by name. */
115
+ const isSystem = (fn: ESTree.Node): boolean =>
116
+ isFunction(fn) && ((isSystemCall(fn.parent) && fn.parent.arguments.some((argument) => argument === fn)) || namedSystems().has(fn))
117
+
118
+ /** The system function that holds `node`, if any. */
119
+ const systemOf = (node: ESTree.Node): ESTree.Node | undefined => {
120
+ for (let current = node.parent; current; current = current.parent) if (isSystem(current)) return current
121
+ return undefined
122
+ }
123
+
124
+ /** The keys from the top of a destructuring `pattern` down to `binding` in it (`["queries", "x"]` for `x` in `{ queries: { x } }`). */
125
+ const keysTo = (binding: ESTree.Node, pattern: ESTree.Node): ReadonlyArray<string> | undefined => {
126
+ const keys: Array<string> = []
127
+ let current = binding
128
+ while (current !== pattern) {
129
+ const parent = current.parent
130
+ if (parent === null) return undefined
131
+ if (parent.type === "AssignmentPattern" && parent.left === current) {
132
+ current = parent
133
+ continue
134
+ }
135
+ if (parent.type !== "Property" || parent.value !== current || parent.parent.type !== "ObjectPattern") return undefined
136
+ const key = propertyKey(parent)
137
+ if (key === undefined) return undefined
138
+ keys.unshift(key)
139
+ current = parent.parent
140
+ }
141
+ return keys
142
+ }
143
+
144
+ /**
145
+ * The part of the system's context an expression reads, as keys
146
+ * (`["queries", "x"]` for `queries.x`, `q.x` after `({ queries: q })`,
147
+ * `x` after `({ queries: { x } })`, and `ctx.queries.x`), when it reads
148
+ * one. A name `queries` or `local` that resolves to nothing else is read
149
+ * as that part.
150
+ */
151
+ const contextPath = (expression: ESTree.Node): ReadonlyArray<string> | undefined => {
152
+ const node = unwrap(expression)
153
+ if (node.type === "MemberExpression") {
154
+ const name = propertyName(node)
155
+ const object = name === undefined ? undefined : contextPath(node.object)
156
+ return object === undefined || name === undefined ? undefined : [...object, name]
157
+ }
158
+ if (node.type !== "Identifier") return undefined
159
+ const fallback = node.name === "queries" || node.name === "local" ? [node.name] : undefined
160
+ const definition = variableOf(node)?.defs[0]
161
+ if (definition === undefined) return fallback
162
+ if (definition.type === "Parameter" && isSystem(definition.node)) {
163
+ const param = (definition.node as ESTree.ArrowFunctionExpression | ESTree.Function).params[0]
164
+ return param === undefined ? fallback : keysTo(definition.name, param) ?? fallback
165
+ }
166
+ if (definition.type === "Variable" && definition.node.type === "VariableDeclarator" && definition.node.init !== null && definition.node.init !== undefined) {
167
+ const keys = keysTo(definition.name, definition.node.id)
168
+ const from = keys === undefined ? undefined : contextPath(definition.node.init)
169
+ return from === undefined || keys === undefined ? fallback : [...from, ...keys]
170
+ }
171
+ return fallback
172
+ }
173
+
174
+ /** `queries.x.data`, however the context was destructured. */
175
+ const isData = (node: ESTree.Node): boolean => {
176
+ const path = contextPath(node)
177
+ return path?.length === 3 && path[0] === "queries" && path[2] === "data"
178
+ }
179
+
180
+ /** Marks the variables `declaration` declares under `names` (a declarator, a function's parameters). */
181
+ const mark = (declaration: ESTree.Node, names: ReadonlyArray<string>, kind: Kind): void => {
182
+ for (const variable of context.sourceCode.getDeclaredVariables(declaration)) {
183
+ if (names.includes(variable.name)) kinds.set(variable, kind)
184
+ }
185
+ }
186
+ /** The names a binding declares for the value itself or its elements: `entity`, or `first` and `rest` in `[first, ...rest]`. */
187
+ const namesIn = (pattern: ESTree.Node): ReadonlyArray<string> => {
188
+ if (pattern.type === "Identifier") return [pattern.name]
189
+ if (pattern.type === "AssignmentPattern") return namesIn(pattern.left)
190
+ if (pattern.type === "RestElement") return namesIn(pattern.argument)
191
+ if (pattern.type === "ArrayPattern") return pattern.elements.flatMap((element) => (element === null ? [] : namesIn(element)))
192
+ return []
193
+ }
194
+ /** Marks the `index`th parameter of a callback over entities as an entity. */
195
+ const markCallback = (callback: ESTree.Node | undefined, index: number): void => {
196
+ if (callback === undefined || !isFunction(callback)) return
197
+ const param = callback.params[index]
198
+ if (param !== undefined) mark(callback, namesIn(param), "entity")
199
+ }
200
+ /** What a callback over entities returns: an entity, data, or neither (`(entity) => entity.id`). */
201
+ const returnKind = (callback: ESTree.Node | undefined): Kind | undefined => {
202
+ if (callback === undefined) return undefined
203
+ for (const returned of returnedBy(callback)) {
204
+ const found = keptIn(returned)
205
+ if (found) return found.kind
206
+ }
207
+ return undefined
208
+ }
209
+
210
+ /** What a value is, when it is plainly one of the run's entities or data. */
211
+ const kindOf = (expression: ESTree.Node): Kind | undefined => {
212
+ const node = unwrap(expression)
213
+ if (isData(node)) return "data"
214
+ if (isEach(node)) return "entity"
215
+ if (node.type === "Identifier") return kinds.get(variableOf(node))
216
+ // `queries.x.each()[0]`, `.find(...)`, `.at(...)`, `.filter(...)` of entities.
217
+ if (node.type === "MemberExpression" && node.computed) return kindOf(node.object) === "entity" ? "entity" : undefined
218
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression") {
219
+ const method = calledMethod(node) ?? ""
220
+ // `Array.from(queries.x.each())`, or what its map returns.
221
+ if (globalPath(context, node.callee) === "Array.from") {
222
+ const [source, map] = node.arguments
223
+ if (source === undefined || source.type === "SpreadElement" || kindOf(source) !== "entity") return undefined
224
+ if (map === undefined) return "entity"
225
+ markCallback(map, 0)
226
+ return returnKind(map)
227
+ }
228
+ if (kindOf(node.callee.object) !== "entity") return undefined
229
+ if (picks.has(method)) return "entity"
230
+ // `.map((entity) => entity)`: whatever the callback returns for each entity.
231
+ if (maps.has(method)) {
232
+ markCallback(node.arguments[0], 0)
233
+ return returnKind(node.arguments[0])
234
+ }
235
+ // `.reduce((best, entity) => ...)`: what the callback returns, or the initial value.
236
+ if (method === "reduce" || method === "reduceRight") {
237
+ const [reducer, initial] = node.arguments
238
+ markCallback(reducer, 1)
239
+ return returnKind(reducer) ?? (initial === undefined || initial.type === "SpreadElement" ? undefined : kindOf(initial))
240
+ }
241
+ return undefined
242
+ }
243
+ if (node.type === "LogicalExpression") return kindOf(node.left) ?? kindOf(node.right)
244
+ if (node.type === "ConditionalExpression") return kindOf(node.consequent) ?? kindOf(node.alternate)
245
+ return undefined
246
+ }
247
+
248
+ /** The entity or data a kept value holds: itself, a field or element of a literal, or what a closure captures. */
249
+ const keptIn = (expression: ESTree.Node): { readonly node: ESTree.Node; readonly kind: Kind } | undefined => {
250
+ const node = unwrap(expression)
251
+ const kind = kindOf(node)
252
+ if (kind !== undefined) return { node, kind }
253
+ if (node.type === "ObjectExpression") {
254
+ for (const property of node.properties) {
255
+ const found = property.type === "Property" ? keptIn(property.value) : keptIn(property.argument)
256
+ if (found) return found
257
+ }
258
+ }
259
+ if (node.type === "ArrayExpression") {
260
+ for (const element of node.elements) {
261
+ const found = element === null ? undefined : keptIn(element.type === "SpreadElement" ? element.argument : element)
262
+ if (found) return found
263
+ }
264
+ }
265
+ if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") {
266
+ for (const scope of context.sourceCode.scopeManager.scopes) {
267
+ if (scope.block !== node) continue
268
+ for (const reference of scope.through) {
269
+ const captured = kinds.get(reference.resolved) ?? (isData(reference.identifier) ? "data" : undefined)
270
+ if (captured !== undefined) return { node: reference.identifier, kind: captured }
271
+ }
272
+ }
273
+ }
274
+ return undefined
275
+ }
276
+
277
+ const report = (found: { readonly node: ESTree.Node; readonly kind: Kind }): void => {
278
+ const name = text(found.node)
279
+ const id = found.node.type === "Identifier" ? `\`${name}.id\`` : "its `id`"
280
+ context.report({ node: found.node, messageId: found.kind, data: found.kind === "entity" ? { name, id } : { name } })
281
+ }
282
+
283
+ /** Whether an expression is the system's `local` state (`whole`), or a part of it (`local.x`, `targets` after `const { targets } = local`). */
284
+ const isLocal = (node: ESTree.Node, whole = false): boolean => {
285
+ // `local.byId[key]` has no static path: its object `local.byId` does.
286
+ for (let current = unwrap(node), depth = 0; ; current = unwrap(current.object), depth += 1) {
287
+ const path = contextPath(current)
288
+ if (path !== undefined) return path[0] === "local" && (whole || path.length + depth >= 2)
289
+ if (current.type !== "MemberExpression") return false
290
+ }
291
+ }
292
+
293
+ /** Whether writing to `target` keeps the value past the run: `local` state, or a variable outside the system. */
294
+ const outlivesRun = (target: ESTree.Node, at: ESTree.Node): boolean => {
295
+ if (isLocal(target)) return true
296
+ const root = rootOf(target)
297
+ if (root.type !== "Identifier") return false
298
+ const system = systemOf(at)
299
+ const variable = variableOf(root)
300
+ const declared = variable?.defs[0]?.node
301
+ return system !== undefined && declared !== undefined && !inside(declared, system)
302
+ }
303
+
304
+ return {
305
+ VariableDeclarator(node) {
306
+ if (node.init === null || node.init === undefined) return
307
+ // `const [first] = queries.x.each()`
308
+ const kind = kindOf(node.init)
309
+ if (kind !== undefined) mark(node, namesIn(node.id), kind)
310
+ },
311
+ ForOfStatement(node) {
312
+ if (kindOf(node.right) === "entity" && node.left.type === "VariableDeclaration") {
313
+ for (const declaration of node.left.declarations) mark(declaration, namesIn(declaration.id), "entity")
314
+ }
315
+ },
316
+ CallExpression(node) {
317
+ // `Object.assign(local, { target: entity })`
318
+ if (globalPath(context, node.callee) === "Object.assign") {
319
+ const [target, ...sources] = node.arguments
320
+ if (target === undefined || target.type === "SpreadElement" || !(isLocal(target, true) || outlivesRun(target, node))) return
321
+ for (const source of sources) {
322
+ const found = source.type === "SpreadElement" ? undefined : keptIn(source)
323
+ if (found) report(found)
324
+ }
325
+ return
326
+ }
327
+ const method = calledMethod(node)
328
+ if (method === undefined || node.callee.type !== "MemberExpression") return
329
+ // `queries.x.each().map((entity) => ...)`
330
+ if (callbacks.has(method) && kindOf(node.callee.object) === "entity") {
331
+ markCallback(node.arguments[0], 0)
332
+ return
333
+ }
334
+ if ((method === "reduce" || method === "reduceRight") && kindOf(node.callee.object) === "entity") {
335
+ markCallback(node.arguments[0], 1)
336
+ return
337
+ }
338
+ // `local.targets.push(entity)`, `local.byId.set(id, entity)`
339
+ if (keeps.has(method) && outlivesRun(node.callee.object, node)) {
340
+ for (const argument of node.arguments) {
341
+ const found = argument.type === "SpreadElement" ? undefined : keptIn(argument)
342
+ if (found) report(found)
343
+ }
344
+ }
345
+ },
346
+ AssignmentExpression(node) {
347
+ if (!outlivesRun(node.left, node)) return
348
+ const found = keptIn(node.right)
349
+ if (found) report(found)
350
+ }
351
+ }
352
+ }
353
+ })