@typeonce/oxlint-plugin-ritmo 0.22.0 → 0.23.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.
- package/CHANGELOG.md +70 -0
- package/README.md +61 -21
- package/dist/index.js +10 -6
- package/dist/index.js.map +1 -1
- package/dist/internal/ast.d.ts +43 -0
- package/dist/internal/ast.d.ts.map +1 -1
- package/dist/internal/ast.js +127 -0
- package/dist/internal/ast.js.map +1 -1
- package/dist/rules/handle-runtime-result.d.ts.map +1 -1
- package/dist/rules/handle-runtime-result.js +82 -10
- package/dist/rules/handle-runtime-result.js.map +1 -1
- package/dist/rules/keep-simulation-headless.d.ts +3 -3
- package/dist/rules/keep-simulation-headless.d.ts.map +1 -1
- package/dist/rules/keep-simulation-headless.js +30 -15
- package/dist/rules/keep-simulation-headless.js.map +1 -1
- package/dist/rules/no-float-timers.d.ts +2 -2
- package/dist/rules/no-float-timers.d.ts.map +1 -1
- package/dist/rules/no-float-timers.js +133 -20
- package/dist/rules/no-float-timers.js.map +1 -1
- package/dist/rules/no-infinity-in-simulation-data.d.ts.map +1 -1
- package/dist/rules/no-infinity-in-simulation-data.js +134 -10
- package/dist/rules/no-infinity-in-simulation-data.js.map +1 -1
- package/dist/rules/no-kept-query-values.d.ts +9 -0
- package/dist/rules/no-kept-query-values.d.ts.map +1 -0
- package/dist/rules/no-kept-query-values.js +375 -0
- package/dist/rules/no-kept-query-values.js.map +1 -0
- package/dist/rules/no-state-spread.d.ts.map +1 -1
- package/dist/rules/no-state-spread.js +137 -14
- package/dist/rules/no-state-spread.js.map +1 -1
- package/dist/rules/use-clock-for-time.d.ts.map +1 -1
- package/dist/rules/use-clock-for-time.js +31 -15
- package/dist/rules/use-clock-for-time.js.map +1 -1
- package/dist/rules/use-ops-for-math.d.ts.map +1 -1
- package/dist/rules/use-ops-for-math.js +11 -7
- package/dist/rules/use-ops-for-math.js.map +1 -1
- package/dist/rules/use-random-for-randomness.d.ts.map +1 -1
- package/dist/rules/use-random-for-randomness.js +11 -13
- package/dist/rules/use-random-for-randomness.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +10 -6
- package/src/internal/ast.ts +125 -0
- package/src/rules/handle-runtime-result.ts +86 -8
- package/src/rules/keep-simulation-headless.ts +32 -12
- package/src/rules/no-float-timers.ts +124 -19
- package/src/rules/no-infinity-in-simulation-data.ts +133 -10
- package/src/rules/no-kept-query-values.ts +353 -0
- package/src/rules/no-state-spread.ts +140 -12
- package/src/rules/use-clock-for-time.ts +31 -14
- package/src/rules/use-ops-for-math.ts +10 -10
- package/src/rules/use-random-for-randomness.ts +9 -11
package/src/internal/ast.ts
CHANGED
|
@@ -36,6 +36,131 @@ export const globalMember = (context: Context, node: ESTree.MemberExpression, ob
|
|
|
36
36
|
return propertyName(node)
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/** Objects whose members are the globals themselves: `globalThis.Math` is `Math`. */
|
|
40
|
+
const globalObjects = new Set(["globalThis", "self", "window"])
|
|
41
|
+
|
|
42
|
+
/** Where the type checker reads a name as a type: these never run. */
|
|
43
|
+
export const typePositions = new Set(["TSTypeQuery", "TSQualifiedName", "TSTypeReference", "TSClassImplements", "TSInterfaceHeritage"])
|
|
44
|
+
|
|
45
|
+
/** The static name of an object pattern or literal property (`a`, `"a"`), if it has one. */
|
|
46
|
+
export const propertyKey = (node: ESTree.ObjectProperty | ESTree.AssignmentTargetProperty | ESTree.BindingProperty): string | undefined =>
|
|
47
|
+
!node.computed && node.key.type === "Identifier" ? node.key.name : stringValue(node.key)
|
|
48
|
+
|
|
49
|
+
/** The path of member `name` of the global at `object`: a member of `globalThis`, `self`, or `window` is the global itself. */
|
|
50
|
+
const memberOf = (object: string, name: string): string => (globalObjects.has(object) ? name : `${object}.${name}`)
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The global `node` refers to, as a path (`Math`, `Math.random`,
|
|
54
|
+
* `Temporal.Now`), or `undefined` when it refers to anything else. It
|
|
55
|
+
* resolves:
|
|
56
|
+
* - a global name that no local, parameter, or import shadows (`Math`;
|
|
57
|
+
* `globalThis`, `self`, and `window` give their own name);
|
|
58
|
+
* - a static member of one (`Math.random`, `Math["random"]`), where a member
|
|
59
|
+
* of `globalThis`, `self`, or `window` is that global (`globalThis.Math`
|
|
60
|
+
* and `self.window.Math` give `Math`);
|
|
61
|
+
* - a `const` that holds one (`const M = Math` makes `M` give `Math`), or a
|
|
62
|
+
* property destructured from one in a `const` (`const { now: n } = Date`
|
|
63
|
+
* makes `n` give `Date.now`).
|
|
64
|
+
*
|
|
65
|
+
* A name in a type (`let at: Date`, `typeof Math`) runs nothing and gives
|
|
66
|
+
* `undefined`. Values passed through functions or other modules are not
|
|
67
|
+
* followed.
|
|
68
|
+
*/
|
|
69
|
+
export const globalPath = (context: Context, node: ESTree.Node, seen = new Set<ESTree.Node>()): string | undefined => {
|
|
70
|
+
// `const a = b, b = a` refers to nothing.
|
|
71
|
+
if (seen.has(node)) return undefined
|
|
72
|
+
seen.add(node)
|
|
73
|
+
if (node.type === "MemberExpression") {
|
|
74
|
+
const name = propertyName(node)
|
|
75
|
+
const object = name === undefined ? undefined : globalPath(context, node.object, seen)
|
|
76
|
+
return object === undefined || name === undefined ? undefined : memberOf(object, name)
|
|
77
|
+
}
|
|
78
|
+
if (node.type !== "Identifier" || typePositions.has(node.parent.type)) return undefined
|
|
79
|
+
const reference = context.sourceCode.getScope(node).references.find((candidate) => candidate.identifier === node)
|
|
80
|
+
if (reference === undefined) return undefined
|
|
81
|
+
const variable = reference.resolved
|
|
82
|
+
if (variable === null || variable.defs.length === 0) return node.name
|
|
83
|
+
const [definition] = variable.defs
|
|
84
|
+
if (variable.defs.length !== 1 || definition?.type !== "Variable") return undefined
|
|
85
|
+
if (definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const") return undefined
|
|
86
|
+
return bindingPath(context, definition.name, seen)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The global a `const` binding holds: the whole value (`M` in `const M = Math`) or a property destructured from it. */
|
|
90
|
+
const bindingPath = (context: Context, binding: ESTree.Node, seen: Set<ESTree.Node>): string | undefined => {
|
|
91
|
+
const parent = binding.parent
|
|
92
|
+
if (parent === null) return undefined
|
|
93
|
+
if (parent.type === "VariableDeclarator" && parent.id === binding) return parent.init === null ? undefined : globalPath(context, parent.init, seen)
|
|
94
|
+
if (parent.type === "Property" && parent.value === binding) return propertyPath(context, parent, seen)
|
|
95
|
+
if (parent.type === "AssignmentPattern" && parent.left === binding && parent.parent.type === "Property") return propertyPath(context, parent.parent, seen)
|
|
96
|
+
// `const { ...rest } = Math`: the rest holds Math's other members.
|
|
97
|
+
if (parent.type === "RestElement" && parent.parent.type === "ObjectPattern") return patternPath(context, parent.parent, seen)
|
|
98
|
+
return undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The global an object pattern destructures (`Date` in `const { now } = Date`), also when nested in another pattern. */
|
|
102
|
+
const patternPath = (context: Context, pattern: ESTree.Node, seen: Set<ESTree.Node>): string | undefined => {
|
|
103
|
+
const parent = pattern.parent
|
|
104
|
+
if (parent === null) return undefined
|
|
105
|
+
if (parent.type === "VariableDeclarator" && parent.id === pattern) return parent.init === null ? undefined : globalPath(context, parent.init, seen)
|
|
106
|
+
if (parent.type === "AssignmentExpression" && parent.left === pattern) return globalPath(context, parent.right, seen)
|
|
107
|
+
if (parent.type === "Property" && parent.value === pattern) return propertyPath(context, parent, seen)
|
|
108
|
+
if (parent.type === "AssignmentPattern" && parent.left === pattern && parent.parent.type === "Property") return propertyPath(context, parent.parent, seen)
|
|
109
|
+
return undefined
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The global a property of an object pattern reads (`Date.now` for `now` in `const { now } = Date`). */
|
|
113
|
+
const propertyPath = (context: Context, property: ESTree.Node, seen: Set<ESTree.Node>): string | undefined => {
|
|
114
|
+
if (property.type !== "Property" || property.parent.type !== "ObjectPattern") return undefined
|
|
115
|
+
const key = propertyKey(property)
|
|
116
|
+
const object = key === undefined ? undefined : patternPath(context, property.parent, seen)
|
|
117
|
+
return object === undefined || key === undefined ? undefined : memberOf(object, key)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A global read at one spot: its path (see `globalPath`), and the path of the global it is a member of. */
|
|
121
|
+
export interface GlobalRead {
|
|
122
|
+
readonly path: string
|
|
123
|
+
/** The global the read takes a member of (`window` for `window.innerWidth`); none for a bare name. */
|
|
124
|
+
readonly from?: string
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The global `node` reads where it stands: a member of one
|
|
129
|
+
* (`globalThis.Date.now`, `M.random` after `const M = Math`), a property
|
|
130
|
+
* destructured from one (`now` in `const { now } = Date`), or a global name
|
|
131
|
+
* itself (`setTimeout`). A `const` holding a global (`M`, or `n` after
|
|
132
|
+
* `const { now: n } = Date`) gives `undefined`: the global was read where the
|
|
133
|
+
* `const` was declared, and a rule reports it there.
|
|
134
|
+
*/
|
|
135
|
+
export const globalRead = (context: Context, node: ESTree.Node): GlobalRead | undefined => {
|
|
136
|
+
if (node.type === "MemberExpression") {
|
|
137
|
+
const name = propertyName(node)
|
|
138
|
+
const from = name === undefined ? undefined : globalPath(context, node.object)
|
|
139
|
+
return from === undefined || name === undefined ? undefined : { path: memberOf(from, name), from }
|
|
140
|
+
}
|
|
141
|
+
if (node.type === "Property") {
|
|
142
|
+
const key = node.parent.type === "ObjectPattern" ? propertyKey(node) : undefined
|
|
143
|
+
const from = key === undefined ? undefined : patternPath(context, node.parent, new Set())
|
|
144
|
+
return from === undefined || key === undefined ? undefined : { path: memberOf(from, key), from }
|
|
145
|
+
}
|
|
146
|
+
if (node.type === "Identifier" && !typePositions.has(node.parent.type) && isGlobalReference(context, node)) return { path: node.name }
|
|
147
|
+
return undefined
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The value of the `const` `node` names (`value` in `const x = value`), when
|
|
152
|
+
* a declaration in the file binds it to the whole value. A `let`, a
|
|
153
|
+
* parameter, and a destructured name give `undefined`.
|
|
154
|
+
*/
|
|
155
|
+
export const constValue = (context: Context, node: ESTree.Node): ESTree.Node | undefined => {
|
|
156
|
+
if (node.type !== "Identifier") return undefined
|
|
157
|
+
const variable = context.sourceCode.getScope(node).references.find((reference) => reference.identifier === node)?.resolved
|
|
158
|
+
const definition = variable?.defs.length === 1 ? variable.defs[0] : undefined
|
|
159
|
+
if (definition?.type !== "Variable" || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const") return undefined
|
|
160
|
+
const declarator = definition.node
|
|
161
|
+
return declarator.type === "VariableDeclarator" && declarator.id.type === "Identifier" ? declarator.init ?? undefined : undefined
|
|
162
|
+
}
|
|
163
|
+
|
|
39
164
|
/** Whether `node` names the global `name` (not a local binding, property key, or type). */
|
|
40
165
|
export const isGlobalIdentifier = (context: Context, node: ESTree.Node, name: string): boolean =>
|
|
41
166
|
node.type === "Identifier" && node.name === name && isGlobalReference(context, node)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { defineRule } from "@oxlint/plugins"
|
|
2
2
|
import type { ESTree } from "@oxlint/plugins"
|
|
3
3
|
|
|
4
|
-
import { calledMethod, docsUrl, receiverName } from "../internal/ast.ts"
|
|
4
|
+
import { calledMethod, constValue, docsUrl, globalPath, propertyKey, propertyName, receiverName } from "../internal/ast.ts"
|
|
5
5
|
|
|
6
6
|
interface Options {
|
|
7
7
|
readonly runtimePattern?: string
|
|
@@ -38,6 +38,18 @@ const unchecked = new Set(["CallExpression", "NewExpression", "TemplateLiteral",
|
|
|
38
38
|
*/
|
|
39
39
|
const sinks = new Set(["JSON.stringify", "String", "console.log", "console.info", "console.warn", "console.error", "console.debug"])
|
|
40
40
|
|
|
41
|
+
/** Functions that call back and drop what the callback returns: `forEach`, timers, event listeners. */
|
|
42
|
+
const droppingMethods = new Set(["forEach", "addEventListener"])
|
|
43
|
+
const droppingGlobals = new Set(["requestAnimationFrame", "requestIdleCallback", "setTimeout", "setInterval", "setImmediate", "queueMicrotask"])
|
|
44
|
+
|
|
45
|
+
/** Statements whose `test` is read as a boolean. */
|
|
46
|
+
const tests = new Set(["IfStatement", "WhileStatement", "DoWhileStatement", "ForStatement"])
|
|
47
|
+
|
|
48
|
+
const unwrap = (node: ESTree.Node): ESTree.Node =>
|
|
49
|
+
node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression" || node.type === "ParenthesizedExpression"
|
|
50
|
+
? unwrap(node.expression)
|
|
51
|
+
: node
|
|
52
|
+
|
|
41
53
|
const calleeName = (node: ESTree.Node): string | undefined => {
|
|
42
54
|
if (node.type === "Identifier") return node.name
|
|
43
55
|
if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && node.property.type === "Identifier") {
|
|
@@ -69,6 +81,8 @@ export default defineRule({
|
|
|
69
81
|
"The result of `{{call}}(...)` is dropped. A checkpoint the runtime let go of (older than its window, or taken before a rewind to an older one or a restore) changes nothing, so the ticks run next are run on top of the present instead of again, unnoticed. Check it: `const rewound = {{call}}(checkpoint); if (!rewound.ok) ...` (`rewound.error` says why), and resynchronize, for example by loading a peer's save. Write `void {{call}}(...)` to ignore it on purpose.",
|
|
70
82
|
dropped:
|
|
71
83
|
"The result of `{{call}}()` is dropped, so the call does nothing. Read it: `const saved = {{call}}(); if (saved.ok) ...`.",
|
|
84
|
+
truthy:
|
|
85
|
+
"`{{call}}(...)` returns a `Result`, an object, so as a condition it is always true and a failure goes unnoticed. Test its `.ok`: `if (!{{call}}(...).ok) ...`, or name it to read `.error` too: `const result = {{call}}(...); if (!result.ok) ...`.",
|
|
72
86
|
unchecked:
|
|
73
87
|
"`{{call}}(...)` returns a `Result`, and it is passed on unchecked: code that accepts any value (a save, a log, `JSON.stringify`) gets the `{ ok, value }` wrapper instead of the value, and a failure goes unnoticed. Check it first: `const result = {{call}}(...); if (result.ok) use(result.value)`. A helper that takes the `Result` itself gets it once it is named: `const result = {{call}}(...); helper(result)`."
|
|
74
88
|
},
|
|
@@ -88,29 +102,93 @@ export default defineRule({
|
|
|
88
102
|
create(context) {
|
|
89
103
|
const options = (context.options[0] ?? {}) as Options
|
|
90
104
|
const runtime = new RegExp(options.runtimePattern ?? "runtime$", "i")
|
|
105
|
+
|
|
106
|
+
/** Whether `node` is a `Game.Runtime.make(...)` call (`Runtime.make(...)` too), or a `const` that holds one. */
|
|
107
|
+
const isMake = (raw: ESTree.Node): boolean => {
|
|
108
|
+
const node = unwrap(raw)
|
|
109
|
+
const value = constValue(context, node)
|
|
110
|
+
if (value !== undefined) return isMake(value)
|
|
111
|
+
return node.type === "CallExpression" && calledMethod(node) === "make" && node.callee.type === "MemberExpression" && receiverName(node.callee.object) === "Runtime"
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Whether `node` is a runtime: named like one, or the `.value` of a `Game.Runtime.make(...)` in the file, also through a `const`. */
|
|
115
|
+
const isRuntime = (raw: ESTree.Node): boolean => {
|
|
116
|
+
const node = unwrap(raw)
|
|
117
|
+
const name = receiverName(node)
|
|
118
|
+
if (name !== undefined && runtime.test(name)) return true
|
|
119
|
+
const value = constValue(context, node)
|
|
120
|
+
if (value !== undefined) return isRuntime(value)
|
|
121
|
+
return node.type === "MemberExpression" && propertyName(node) === "value" && isMake(node.object)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The runtime method a call invokes: `runtime.tick(...)`, or `tick(...)` after `const { tick } = runtime`. */
|
|
125
|
+
const methodOf = (call: ESTree.CallExpression): string | undefined => {
|
|
126
|
+
if (call.callee.type === "MemberExpression") return isRuntime(call.callee.object) ? calledMethod(call) : undefined
|
|
127
|
+
if (call.callee.type !== "Identifier") return undefined
|
|
128
|
+
const variable = context.sourceCode.getScope(call.callee).references.find((reference) => reference.identifier === call.callee)?.resolved
|
|
129
|
+
const definition = variable?.defs.length === 1 ? variable.defs[0] : undefined
|
|
130
|
+
if (definition?.type !== "Variable" || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const") return undefined
|
|
131
|
+
const binding = definition.name.parent
|
|
132
|
+
const property = binding?.type === "AssignmentPattern" ? binding.parent : binding
|
|
133
|
+
if (property?.type !== "Property" || property.parent.type !== "ObjectPattern") return undefined
|
|
134
|
+
const declarator = property.parent.parent
|
|
135
|
+
if (declarator.type !== "VariableDeclarator" || declarator.init === null || !isRuntime(declarator.init)) return undefined
|
|
136
|
+
return propertyKey(property)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Whether a function's caller drops what it returns: `forEach`, a timer, an event listener. */
|
|
140
|
+
const dropsReturn = (callback: ESTree.Node): boolean => {
|
|
141
|
+
const call = callback.parent
|
|
142
|
+
if (call?.type !== "CallExpression" || !call.arguments.some((argument) => argument === callback)) return false
|
|
143
|
+
const method = calledMethod(call)
|
|
144
|
+
if (method !== undefined && droppingMethods.has(method)) return true
|
|
145
|
+
const path = globalPath(context, call.callee)
|
|
146
|
+
return path !== undefined && droppingGlobals.has(path)
|
|
147
|
+
}
|
|
148
|
+
|
|
91
149
|
return {
|
|
92
150
|
CallExpression(call) {
|
|
93
|
-
|
|
94
|
-
const method = calledMethod(call)
|
|
151
|
+
const method = methodOf(call)
|
|
95
152
|
const takes = method === undefined ? undefined : methods.get(method)
|
|
96
153
|
if (takes === undefined) return
|
|
97
154
|
// `run.tick()` and `replay.rewind()` without arguments are other libraries' methods.
|
|
98
155
|
if (takes === "arguments" && call.arguments.length === 0) return
|
|
99
156
|
if (takes === "none" && call.arguments.length > 0) return
|
|
100
|
-
const receiver = receiverName(call.callee.object)
|
|
101
|
-
if (receiver === undefined || !runtime.test(receiver)) return
|
|
102
157
|
const data = { call: context.sourceCode.getText(call.callee) }
|
|
158
|
+
const drop = (node: ESTree.Node) =>
|
|
159
|
+
context.report({ node, messageId: takes === "none" ? "dropped" : method === "restore" || method === "rewind" ? method : "tick", data })
|
|
103
160
|
|
|
104
161
|
let node: ESTree.Node = call
|
|
105
162
|
let parent: ESTree.Node | null | undefined = node.parent
|
|
106
|
-
|
|
163
|
+
// A Result is an object: a condition on it is always true.
|
|
164
|
+
const tested = (): boolean =>
|
|
165
|
+
parent != null && (
|
|
166
|
+
(parent.type === "UnaryExpression" && parent.operator === "!") ||
|
|
167
|
+
(parent.type === "ConditionalExpression" && parent.test === node) ||
|
|
168
|
+
(parent.type === "LogicalExpression" && parent.operator !== "??" && parent.left === node) ||
|
|
169
|
+
(tests.has(parent.type) && "test" in parent && parent.test === node)
|
|
170
|
+
)
|
|
171
|
+
while (parent != null && passesThrough.has(parent.type) && !tested()) {
|
|
107
172
|
node = parent
|
|
108
173
|
parent = node.parent
|
|
109
174
|
}
|
|
110
175
|
if (parent == null) return
|
|
176
|
+
if (tested()) {
|
|
177
|
+
context.report({ node: call, messageId: "truthy", data })
|
|
178
|
+
return
|
|
179
|
+
}
|
|
111
180
|
if (parent.type === "ExpressionStatement") {
|
|
112
|
-
|
|
113
|
-
|
|
181
|
+
drop(parent)
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
// `runtime.tick(update), draw()`: a sequence keeps only its last value.
|
|
185
|
+
if (parent.type === "SequenceExpression" && parent.expressions.at(-1) !== node) {
|
|
186
|
+
drop(call)
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
// `updates.forEach((u) => runtime.tick(u))`: the arrow returns the Result to a caller that drops it.
|
|
190
|
+
if (parent.type === "ArrowFunctionExpression" && parent.body === node && dropsReturn(parent)) {
|
|
191
|
+
drop(call)
|
|
114
192
|
return
|
|
115
193
|
}
|
|
116
194
|
if (!unchecked.has(parent.type)) return
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { defineRule } from "@oxlint/plugins"
|
|
2
2
|
import type { ESTree } from "@oxlint/plugins"
|
|
3
3
|
|
|
4
|
-
import { docsUrl,
|
|
4
|
+
import { docsUrl, globalRead, importsOnlyTypes, stringValue } from "../internal/ast.ts"
|
|
5
5
|
|
|
6
6
|
/** Globals that are the page: input and layout. */
|
|
7
7
|
const page = new Set([
|
|
@@ -17,6 +17,13 @@ const io = new Set([
|
|
|
17
17
|
/** Globals that connect to other peers: what online play goes through a netcode session for. */
|
|
18
18
|
const network = new Set(["WebSocket", "RTCPeerConnection", "RTCDataChannel"])
|
|
19
19
|
|
|
20
|
+
/** Globals that play sound. */
|
|
21
|
+
const audio = new Set(["Audio", "AudioContext"])
|
|
22
|
+
|
|
23
|
+
/** The report a listed global gets. */
|
|
24
|
+
const kindOf = (name: string): "page" | "io" | "network" | "audio" | undefined =>
|
|
25
|
+
page.has(name) ? "page" : io.has(name) ? "io" : network.has(name) ? "network" : audio.has(name) ? "audio" : undefined
|
|
26
|
+
|
|
20
27
|
/** Renderer and UI packages, by exact name. */
|
|
21
28
|
const renderers = new Set([
|
|
22
29
|
"@typeonce/ritmo-render", "@typeonce/ritmo-pixi", "pixi.js", "three", "react", "react-dom", "preact",
|
|
@@ -32,15 +39,15 @@ interface Options {
|
|
|
32
39
|
|
|
33
40
|
/**
|
|
34
41
|
* Simulation code runs headless (tests, bots, replays, servers): it never
|
|
35
|
-
* touches the page, does host I/O, or imports a renderer, not
|
|
36
|
-
* so another renderer can replace the current one. The host
|
|
37
|
-
* and data, and render code draws it.
|
|
42
|
+
* touches the page, does host I/O, plays sound, or imports a renderer, not
|
|
43
|
+
* even a type, so another renderer can replace the current one. The host
|
|
44
|
+
* feeds it input and data, and render code draws it and plays its sound.
|
|
38
45
|
*/
|
|
39
46
|
export default defineRule({
|
|
40
47
|
meta: {
|
|
41
48
|
type: "problem",
|
|
42
49
|
docs: {
|
|
43
|
-
description: "Keep simulation code headless: no page globals, host I/O, or renderer imports.",
|
|
50
|
+
description: "Keep simulation code headless: no page globals, host I/O, audio, or renderer imports.",
|
|
44
51
|
url: docsUrl("keep-simulation-headless")
|
|
45
52
|
},
|
|
46
53
|
messages: {
|
|
@@ -50,6 +57,8 @@ export default defineRule({
|
|
|
50
57
|
"`{{name}}` is host I/O, which tests, bots, and replays do not have and cannot reproduce. Do the I/O in host code and pass the result in with `runtime.send(...)` or a resource; save and load the world in host code with `runtime.snapshot()` and `runtime.restore(...)`.",
|
|
51
58
|
network:
|
|
52
59
|
"`{{name}}` is a connection to other peers, which tests, bots, and replays do not have. For other players' input, run the simulation under a session of `@typeonce/ritmo-netcode` (`Netcode.rollback` or `Netcode.lockstep`): host code opens the connection and wraps it in a link (`WebSocketNetworkLink`, `WebRtcNetworkLink`), and remote input reaches the simulation through `Netcode.seats`, never `runtime.send(...)`, which a rollback would read on the wrong tick.",
|
|
60
|
+
audio:
|
|
61
|
+
"`{{name}}` plays sound from the simulation, which tests, bots, and servers do not have, and a replay or a rollback that runs the system again plays it again. Publish what happened as an event (`Game.System.writeEvent(Hit)`), and play the sound from a render or host system that reads it (`Game.System.readEvent(Hit)`) and requests the game's audio as a service (`Game.System.service(Audio)`), so a headless test can provide one that records. Under a `@typeonce/ritmo-netcode` session, play it from `session.events(Hit)` instead, so a rolled-back tick does not play it twice.",
|
|
53
62
|
renderer:
|
|
54
63
|
"The simulation imports `{{source}}`, a renderer or UI package, so it no longer runs headless. Draw from a render schedule in render code: mirror entities into nodes with `RenderSync` and a `NodeRegistry` from `@typeonce/ritmo-render`, and declare its services (a node registry) there. Renderer nodes stay in the registry, never in components.",
|
|
55
64
|
rendererType:
|
|
@@ -79,6 +88,19 @@ export default defineRule({
|
|
|
79
88
|
const checkSource = (node: ESTree.Node, source: string | undefined, onlyTypes = false): void => {
|
|
80
89
|
if (source !== undefined && isRenderer(source)) context.report({ node, messageId: onlyTypes ? "rendererType" : "renderer", data: { source } })
|
|
81
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* Reports a listed global read here: by name (`localStorage`), as a member
|
|
93
|
+
* of a global object (`globalThis.localStorage`, `self.innerWidth`), or
|
|
94
|
+
* destructured (`const { innerWidth } = self`). A member of a listed
|
|
95
|
+
* global (`window.innerWidth`) is left to the report on that global.
|
|
96
|
+
*/
|
|
97
|
+
const check = (node: ESTree.Node): void => {
|
|
98
|
+
const read = globalRead(context, node)
|
|
99
|
+
const kind = read === undefined ? undefined : kindOf(read.path)
|
|
100
|
+
if (read === undefined || kind === undefined) return
|
|
101
|
+
if (read.from !== undefined && kindOf(read.from) !== undefined) return
|
|
102
|
+
context.report({ node, messageId: kind, data: { name: read.path } })
|
|
103
|
+
}
|
|
82
104
|
return {
|
|
83
105
|
ImportDeclaration(node) {
|
|
84
106
|
checkSource(node, node.source.value, importsOnlyTypes(node))
|
|
@@ -93,13 +115,11 @@ export default defineRule({
|
|
|
93
115
|
checkSource(node, stringValue(node.source))
|
|
94
116
|
},
|
|
95
117
|
Identifier(node) {
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
context.report({ node, messageId: kind, data: { name: node.name } })
|
|
102
|
-
}
|
|
118
|
+
if (kindOf(node.name) !== undefined) check(node)
|
|
119
|
+
},
|
|
120
|
+
MemberExpression: check,
|
|
121
|
+
Property: check
|
|
122
|
+
|
|
103
123
|
}
|
|
104
124
|
}
|
|
105
125
|
})
|
|
@@ -1,37 +1,135 @@
|
|
|
1
1
|
import { defineRule } from "@oxlint/plugins"
|
|
2
|
-
import type { ESTree } from "@oxlint/plugins"
|
|
2
|
+
import type { Context, ESTree } from "@oxlint/plugins"
|
|
3
3
|
|
|
4
|
-
import { calledMethod, docsUrl, propertyName } from "../internal/ast.ts"
|
|
4
|
+
import { calledMethod, constValue, docsUrl, globalPath, propertyKey, propertyName } from "../internal/ast.ts"
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
/**
|
|
7
|
+
* The names a step's length in seconds goes by, lowercased without `_`: a
|
|
8
|
+
* local, a constant (`STEP_SECONDS`), a field (`time.dt`), or a resource read
|
|
9
|
+
* (`resources.deltaTime.get()`).
|
|
10
|
+
*/
|
|
11
|
+
const deltaNames = new Set([
|
|
12
|
+
"dt", "deltatime", "deltaseconds", "dtseconds", "fixeddt", "fixeddelta", "fixeddeltatime", "fixeddeltaseconds",
|
|
13
|
+
"stepseconds", "fixedstepseconds", "fixedstep", "timestep", "fixedtimestep", "secondsperstep", "secondspertick", "tickseconds", "frameseconds"
|
|
14
|
+
])
|
|
15
|
+
/** Fields that are a step's length only on a receiver named for time: `time.delta`, `step.seconds`, but not a pointer's `delta`. */
|
|
16
|
+
const timeFields = new Map([
|
|
17
|
+
["delta", new Set(["time", "clock", "frame", "tick", "step"])],
|
|
18
|
+
["seconds", new Set(["frame", "tick", "step"])]
|
|
19
|
+
])
|
|
20
|
+
|
|
21
|
+
const normal = (name: string): string => name.replaceAll("_", "").toLowerCase()
|
|
8
22
|
|
|
9
|
-
/** `node` without the
|
|
23
|
+
/** `node` without the wrappers that keep its value (`dt as number`, `dt!`, `(dt)`). */
|
|
10
24
|
const unwrap = (node: ESTree.Node): ESTree.Node =>
|
|
11
|
-
node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression"
|
|
25
|
+
node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression" || node.type === "ParenthesizedExpression"
|
|
26
|
+
? unwrap(node.expression)
|
|
27
|
+
: node
|
|
12
28
|
|
|
13
|
-
|
|
14
|
-
const
|
|
29
|
+
const numberValue = (node: ESTree.Node): number | undefined => {
|
|
30
|
+
const value = unwrap(node)
|
|
31
|
+
return value.type === "Literal" && typeof value.value === "number" ? value.value : undefined
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Whether `call` is the global `Math.min(...)` or `Math.max(...)`. */
|
|
35
|
+
const isMinMax = (context: Context, call: ESTree.Node): call is ESTree.CallExpression => {
|
|
36
|
+
if (call.type !== "CallExpression") return false
|
|
37
|
+
const path = globalPath(context, call.callee)
|
|
38
|
+
return path === "Math.min" || path === "Math.max"
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Whether `node` is a step's length in seconds: `dt`, `time.dt`,
|
|
43
|
+
* `resources.deltaTime.get()`, `1 / 60`, one of these scaled by a number
|
|
44
|
+
* (`dt * 1000`) or clamped (`Math.min(dt, 0.1)`), or a `const` that holds
|
|
45
|
+
* one. A bare `delta` counts only where a timer counts down (`countdown`).
|
|
46
|
+
*/
|
|
47
|
+
const isDelta = (context: Context, raw: ESTree.Node, countdown = false): boolean => {
|
|
15
48
|
const node = unwrap(raw)
|
|
16
|
-
if (node.type === "Identifier")
|
|
17
|
-
|
|
49
|
+
if (node.type === "Identifier") {
|
|
50
|
+
if (deltaNames.has(normal(node.name)) || (countdown && node.name === "delta")) return true
|
|
51
|
+
const init = constValue(context, node)
|
|
52
|
+
return init !== undefined && isDelta(context, init)
|
|
53
|
+
}
|
|
54
|
+
if (node.type === "MemberExpression") {
|
|
55
|
+
const name = propertyName(node)
|
|
56
|
+
if (name === undefined) return false
|
|
57
|
+
if (deltaNames.has(normal(name))) return true
|
|
58
|
+
const receivers = timeFields.get(name)
|
|
59
|
+
const receiver = unwrap(node.object)
|
|
60
|
+
const owner = receiver.type === "Identifier" ? receiver.name : receiver.type === "MemberExpression" ? propertyName(receiver) : undefined
|
|
61
|
+
return receivers !== undefined && owner !== undefined && receivers.has(normal(owner))
|
|
62
|
+
}
|
|
18
63
|
if (node.type === "CallExpression" && calledMethod(node) === "get" && node.callee.type === "MemberExpression") {
|
|
19
64
|
const receiver = unwrap(node.callee.object)
|
|
20
|
-
return receiver.type === "MemberExpression" && deltaNames.
|
|
65
|
+
return receiver.type === "MemberExpression" && deltaNames.has(normal(propertyName(receiver) ?? ""))
|
|
21
66
|
}
|
|
67
|
+
if (node.type === "BinaryExpression") {
|
|
68
|
+
// `1 / 60`: one second split into steps.
|
|
69
|
+
if (node.operator === "/" && numberValue(node.left) === 1) {
|
|
70
|
+
const steps = numberValue(node.right)
|
|
71
|
+
return steps !== undefined && Number.isInteger(steps) && steps > 1
|
|
72
|
+
}
|
|
73
|
+
// `dt * 1000`, `dt / 2`: still a step's length, in other units.
|
|
74
|
+
if (node.operator === "*") return (isDelta(context, node.left) && numberValue(node.right) !== undefined) || (numberValue(node.left) !== undefined && isDelta(context, node.right))
|
|
75
|
+
if (node.operator === "/") return isDelta(context, node.left) && numberValue(node.right) !== undefined
|
|
76
|
+
}
|
|
77
|
+
if (isMinMax(context, node)) return node.arguments.some((argument) => isDelta(context, argument))
|
|
22
78
|
return false
|
|
23
79
|
}
|
|
24
80
|
|
|
25
|
-
/**
|
|
26
|
-
const
|
|
81
|
+
/** The last name of a stored value: `remaining` for `timer.remaining`, `left` for `left`. */
|
|
82
|
+
const lastName = (raw: ESTree.Node): string | undefined => {
|
|
27
83
|
const node = unwrap(raw)
|
|
28
|
-
|
|
84
|
+
if (node.type === "Identifier") return node.name
|
|
85
|
+
if (node.type === "MemberExpression") return propertyName(node)
|
|
86
|
+
return undefined
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Whether the value of `expression`, a stored value `stored` plus or minus a
|
|
91
|
+
* step, is written back where `stored` came from, so it counts across ticks:
|
|
92
|
+
* to a target of the same name (`x = x - dt`, `let cooldown =
|
|
93
|
+
* state.cooldown - dt`, `{ left: buff.left - dt }`, `resources.timer.set(timer
|
|
94
|
+
* - dt)`), or as the result of an `update` callback over it. A clamp
|
|
95
|
+
* (`Math.max(0, x - dt)`) or a branch (`a ? x - dt : 0`) passes the value on.
|
|
96
|
+
*/
|
|
97
|
+
const writtenBack = (context: Context, expression: ESTree.Node, stored: ESTree.Node): boolean => {
|
|
98
|
+
const name = lastName(stored)
|
|
99
|
+
if (name === undefined) return false
|
|
100
|
+
let node = expression
|
|
101
|
+
let parent = node.parent
|
|
102
|
+
while (
|
|
103
|
+
parent !== null &&
|
|
104
|
+
((parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression" || parent.type === "TSSatisfiesExpression" || parent.type === "ParenthesizedExpression") ||
|
|
105
|
+
(parent.type === "ConditionalExpression" && parent.test !== node) ||
|
|
106
|
+
parent.type === "LogicalExpression" ||
|
|
107
|
+
(isMinMax(context, parent) && parent.callee !== node))
|
|
108
|
+
) {
|
|
109
|
+
node = parent
|
|
110
|
+
parent = node.parent
|
|
111
|
+
}
|
|
112
|
+
if (parent === null) return false
|
|
113
|
+
if (parent.type === "AssignmentExpression") return parent.operator === "=" && parent.right === node && lastName(parent.left) === name
|
|
114
|
+
if (parent.type === "VariableDeclarator") return parent.init === node && parent.id.type === "Identifier" && parent.id.name === name
|
|
115
|
+
if (parent.type === "Property") return parent.value === node && parent.parent.type === "ObjectExpression" && propertyKey(parent) === name
|
|
116
|
+
// `resources.timer.set(timer - dt)`, `data.timer.set(entity, timer - dt)`
|
|
117
|
+
if (parent.type === "CallExpression" && calledMethod(parent) === "set" && parent.callee.type === "MemberExpression" && parent.arguments.at(-1) === node) {
|
|
118
|
+
return lastName(parent.callee.object) === name
|
|
119
|
+
}
|
|
120
|
+
// `resources.timer.update((left) => left - dt)`
|
|
121
|
+
const callback = parent.type === "ArrowFunctionExpression" && parent.body === node ? parent : undefined
|
|
122
|
+
if (callback !== undefined && callback.parent.type === "CallExpression" && calledMethod(callback.parent) === "update") {
|
|
123
|
+
const param = callback.params[0]
|
|
124
|
+
return param?.type === "Identifier" && param.name === name && unwrap(stored).type === "Identifier"
|
|
125
|
+
}
|
|
126
|
+
return false
|
|
29
127
|
}
|
|
30
128
|
|
|
31
129
|
/**
|
|
32
130
|
* A timer in simulation code is a deadline in steps, never a float counted
|
|
33
|
-
* down (or up) by
|
|
34
|
-
* nothing once the fixed step changes.
|
|
131
|
+
* down (or up) by a step's seconds: the float drifts, and the value it saves
|
|
132
|
+
* means nothing once the fixed step changes.
|
|
35
133
|
*/
|
|
36
134
|
export default defineRule({
|
|
37
135
|
meta: {
|
|
@@ -49,15 +147,22 @@ export default defineRule({
|
|
|
49
147
|
create(context) {
|
|
50
148
|
const report = (node: ESTree.Node) =>
|
|
51
149
|
context.report({ node, messageId: "floatTimer", data: { text: context.sourceCode.getText(node) } })
|
|
150
|
+
/** Whether `node` reads a stored value (a local or a field), the thing a timer counts. */
|
|
151
|
+
const isStored = (raw: ESTree.Node): boolean => {
|
|
152
|
+
const node = unwrap(raw)
|
|
153
|
+
return (node.type === "Identifier" || node.type === "MemberExpression") && !isDelta(context, node)
|
|
154
|
+
}
|
|
52
155
|
return {
|
|
53
156
|
AssignmentExpression(node) {
|
|
54
157
|
// `timer -= dt`, `elapsed += time.dt`
|
|
55
|
-
if (
|
|
158
|
+
if (node.operator === "-=" && isDelta(context, node.right, true)) report(node)
|
|
159
|
+
if (node.operator === "+=" && isDelta(context, node.right)) report(node)
|
|
56
160
|
},
|
|
57
161
|
BinaryExpression(node) {
|
|
58
|
-
// `cooldown.remaining - dt
|
|
162
|
+
// `cooldown.remaining - dt` written back; `x + vx * dt` scales dt, so it is integration, and `horizon + dt` stored elsewhere is a look-ahead.
|
|
59
163
|
if (node.operator !== "-" && node.operator !== "+") return
|
|
60
|
-
if (
|
|
164
|
+
if (isDelta(context, node.right, node.operator === "-") && isStored(node.left) && writtenBack(context, node, node.left)) report(node)
|
|
165
|
+
else if (node.operator === "+" && isDelta(context, node.left) && isStored(node.right) && writtenBack(context, node, node.right)) report(node)
|
|
61
166
|
}
|
|
62
167
|
}
|
|
63
168
|
}
|