@typeonce/oxlint-plugin-ritmo 0.13.0 → 0.15.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.
@@ -1,7 +1,7 @@
1
1
  import { defineRule } from "@oxlint/plugins"
2
- import type { ESTree } from "@oxlint/plugins"
2
+ import type { Context, ESTree, Fixer, Fix } from "@oxlint/plugins"
3
3
 
4
- import { docsUrl, globalMember } from "../internal/ast.ts"
4
+ import { docsUrl, globalMember, isGlobalReference, propertyName, stringValue } from "../internal/ast.ts"
5
5
 
6
6
  /** The Math functions engines may approximate; each has an `Ops` counterpart. */
7
7
  const approximated = new Set([
@@ -10,78 +10,250 @@ const approximated = new Set([
10
10
  "sinh", "cosh", "tanh", "asinh", "acosh", "atanh"
11
11
  ])
12
12
 
13
- /** The local name `Ops` is imported under in this file, if it is. */
14
- const opsBinding = (program: ESTree.Program): string | undefined => {
13
+ /** Where the type checker reads `Math` as a type: these never run. */
14
+ const typePositions = new Set(["TSTypeQuery", "TSQualifiedName", "TSTypeReference", "TSClassImplements", "TSInterfaceHeritage"])
15
+
16
+ /** The value `require("<source>")` loads, if `node` is that call. */
17
+ const requireOf = (node: ESTree.Node | null | undefined): string | undefined =>
18
+ node?.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "require" && node.arguments.length === 1
19
+ ? stringValue(node.arguments[0])
20
+ : undefined
21
+
22
+ /** The identifier `Ops` is bound to in this file (an import or a top-level `require`), if it is. */
23
+ const opsBinding = (program: ESTree.Program): ESTree.BindingIdentifier | undefined => {
15
24
  for (const statement of program.body) {
16
- if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue
17
- const source = statement.source.value
18
- for (const specifier of statement.specifiers) {
19
- if (source === "@typeonce/ritmo-math" && specifier.type === "ImportSpecifier" && specifier.importKind !== "type" &&
20
- specifier.imported.type === "Identifier" && specifier.imported.name === "Ops") return specifier.local.name
21
- if ((source === "@typeonce/ritmo-math/Ops" || /(^|\/)Ops(\.ts)?$/.test(source)) && specifier.type === "ImportNamespaceSpecifier") {
22
- return specifier.local.name
25
+ if (statement.type === "ImportDeclaration") {
26
+ if (statement.importKind === "type") continue
27
+ const source = statement.source.value
28
+ for (const specifier of statement.specifiers) {
29
+ if (source === "@typeonce/ritmo" && specifier.type === "ImportSpecifier" && specifier.importKind !== "type" &&
30
+ specifier.imported.type === "Identifier" && specifier.imported.name === "Ops") return specifier.local
31
+ if ((source === "@typeonce/ritmo/Ops" || /^\.{1,2}\/(.*\/)?Ops(\.ts)?$/.test(source)) && specifier.type === "ImportNamespaceSpecifier") {
32
+ return specifier.local
33
+ }
23
34
  }
24
35
  }
36
+ if (statement.type !== "VariableDeclaration") continue
37
+ for (const declarator of statement.declarations) {
38
+ const source = requireOf(declarator.init)
39
+ // const Ops = require("@typeonce/ritmo/Ops")
40
+ if (source === "@typeonce/ritmo/Ops" && declarator.id.type === "Identifier") return declarator.id
41
+ // const { Ops } = require("@typeonce/ritmo")
42
+ if (source !== "@typeonce/ritmo" || declarator.id.type !== "ObjectPattern") continue
43
+ for (const property of declarator.id.properties) {
44
+ if (property.type === "Property" && propertyKey(property) === "Ops" && property.value.type === "Identifier") return property.value
45
+ }
46
+ }
47
+ }
48
+ return undefined
49
+ }
50
+
51
+ /** The static name of an object pattern or literal property (`a`, `"a"`), if it has one. */
52
+ const propertyKey = (node: ESTree.ObjectProperty | ESTree.AssignmentTargetProperty | ESTree.BindingProperty): string | undefined =>
53
+ !node.computed && node.key.type === "Identifier" ? node.key.name : stringValue(node.key)
54
+
55
+ /** The variable `name` resolves to from `scope`, if any declaration in the file binds it. */
56
+ const resolve = (scope: ReturnType<Context["sourceCode"]["getScope"]>, name: string) => {
57
+ for (let current: typeof scope | null = scope; current !== null; current = current.upper) {
58
+ const variable = current.set.get(name)
59
+ if (variable !== undefined && variable.defs.length > 0) return variable
25
60
  }
26
61
  return undefined
27
62
  }
28
63
 
29
64
  /**
30
- * Simulation code uses `Ops` from `@typeonce/ritmo-math` for the math
31
- * functions engines may approximate, so every device computes the same bits.
65
+ * Whether the file is CommonJS: a `.cjs` / `.cts` file, or one with no import
66
+ * or export that calls `require` or writes `module.exports` / `exports.`.
67
+ */
68
+ const isCommonJs = (context: Context, program: ESTree.Program): boolean => {
69
+ if (/\.c[jt]s$/.test(context.filename)) return true
70
+ if (program.body.some((statement) => statement.type === "ImportDeclaration" || statement.type.startsWith("Export"))) return false
71
+ return /\brequire\s*\(|\bmodule\.exports\b|\bexports\.[A-Za-z_$]/.test(context.sourceCode.text)
72
+ }
73
+
74
+ /** A report waiting for the end of the file, where the first fixable one also adds the `Ops` import. */
75
+ type Pending = {
76
+ readonly node: ESTree.Node
77
+ readonly messageId: "math" | "power" | "alias"
78
+ readonly data?: Record<string, string>
79
+ /**
80
+ * The node's new text, given the local name of `Ops` and the (rewritten)
81
+ * text of a child; none when rewriting could change behaviour.
82
+ */
83
+ readonly rewrite?: (ops: string, text: (child: ESTree.Node) => string) => string
84
+ }
85
+ type Fixable = Pending & Required<Pick<Pending, "rewrite">>
86
+
87
+ /**
88
+ * Simulation code uses `Ops` from `@typeonce/ritmo` for the math functions
89
+ * engines may approximate, so every device computes the same bits.
32
90
  */
33
91
  export default defineRule({
34
92
  meta: {
35
93
  type: "problem",
36
94
  docs: {
37
- description: "Use Ops from @typeonce/ritmo-math instead of the Math functions and `**` that differ across engines.",
95
+ description: "Use Ops from @typeonce/ritmo instead of the Math functions and `**` that differ across engines.",
38
96
  url: docsUrl("use-ops-for-math")
39
97
  },
40
98
  fixable: "code",
41
99
  messages: {
42
100
  math:
43
- "Math.{{name}} may return a different last bit on another browser or CPU, and the simulation grows that bit into a different run. Use `Ops.{{name}}` from `@typeonce/ritmo-math` (`import { Ops } from \"@typeonce/ritmo-math\"`), which returns the same bits everywhere. Math.sqrt, abs, min, max, floor, ceil, round, trunc, and sign are exact everywhere and stay as they are.",
101
+ "Math.{{name}} may return a different last bit on another browser or CPU, and the simulation grows that bit into a different run. Use `Ops.{{name}}` from `@typeonce/ritmo` (`import { Ops } from \"@typeonce/ritmo\"`), which returns the same bits everywhere. Math.sqrt, abs, min, max, floor, ceil, round, trunc, and sign are exact everywhere and stay as they are.",
44
102
  power:
45
- "`{{operator}}` may return a different last bit on another browser or CPU, and the simulation grows that bit into a different run. Use `Ops.pow(base, exponent)` from `@typeonce/ritmo-math` (`import { Ops } from \"@typeonce/ritmo-math\"`). Squaring stays as it is: `x ** 2` and `x * x` are exact everywhere."
103
+ "`{{operator}}` may return a different last bit on another browser or CPU, and the simulation grows that bit into a different run. Use `Ops.pow(base, exponent)` from `@typeonce/ritmo` (`import { Ops } from \"@typeonce/ritmo\"`). Squaring stays as it is: `x ** 2` and `x * x` are exact everywhere.",
104
+ alias:
105
+ "This hands the global Math on as a value (an alias, a destructured function, an argument, or a computed key), which hides the calls made through it from this rule, so a function engines approximate (Math.sin, Math.pow, ...) can reach the simulation unchecked and return a different last bit on another device. Call `Ops.<name>` from `@typeonce/ritmo` directly (`import { Ops } from \"@typeonce/ritmo\"`; `Ops.sin(x)`), and read exact members by name where they are used (`Math.sqrt(x)`, `Math.PI`), or destructure only exact members (`const { abs, min, PI } = Math`)."
46
106
  },
47
107
  schema: []
48
108
  },
49
109
  create(context) {
50
- let ops: string | undefined
110
+ const pending: Array<Pending> = []
111
+
112
+ /** Whether `node` is the global Math: `Math` or `globalThis.Math` (not a local named Math). */
113
+ const isMath = (node: ESTree.Node): boolean =>
114
+ node.type === "Identifier"
115
+ ? node.name === "Math" && isGlobalReference(context, node)
116
+ : node.type === "MemberExpression" && globalMember(context, node, "globalThis") === "Math"
117
+
118
+ /** Whether destructuring Math with `pattern` pulls only exact members by name. */
119
+ const pullsOnlyExact = (pattern: ESTree.Node): boolean =>
120
+ pattern.type === "ObjectPattern" && pattern.properties.every((property) => {
121
+ if (property.type !== "Property") return false
122
+ const key = propertyKey(property)
123
+ return key !== undefined && !approximated.has(key)
124
+ })
125
+
126
+ /** Checks one use of the global Math. */
127
+ const checkMath = (node: ESTree.Node): void => {
128
+ const parent = node.parent
129
+ if (parent === null || typePositions.has(parent.type)) return
130
+ if (parent.type === "MemberExpression" && parent.object === node) {
131
+ const name = propertyName(parent)
132
+ if (name === undefined) {
133
+ pending.push({ node: parent, messageId: "alias" })
134
+ return
135
+ }
136
+ if (!approximated.has(name)) return
137
+ pending.push({ node: parent, messageId: "math", data: { name }, rewrite: (ops) => `${ops}.${name}` })
138
+ return
139
+ }
140
+ if (parent.type === "VariableDeclarator" && parent.init === node && pullsOnlyExact(parent.id)) return
141
+ if (parent.type === "AssignmentExpression" && parent.right === node && pullsOnlyExact(parent.left)) return
142
+ if (parent.type === "BinaryExpression" && parent.operator === "in") return
143
+ pending.push({ node, messageId: "alias" })
144
+ }
145
+
51
146
  return {
52
- Program(node) {
53
- ops = opsBinding(node)
147
+ Identifier(node) {
148
+ if (isMath(node)) checkMath(node)
54
149
  },
55
150
  MemberExpression(node) {
56
- const name = globalMember(context, node, "Math")
57
- if (name === undefined || !approximated.has(name)) return
58
- const local = ops
59
- context.report({
60
- node,
61
- messageId: "math",
62
- data: { name },
63
- ...(local === undefined ? {} : { fix: (fixer) => fixer.replaceText(node, `${local}.${name}`) })
64
- })
151
+ if (isMath(node)) checkMath(node)
65
152
  },
66
153
  BinaryExpression(node) {
67
154
  if (node.operator !== "**") return
68
155
  if (node.right.type === "Literal" && node.right.value === 2) return
69
- const local = ops
70
- const text = context.sourceCode
71
- context.report({
156
+ pending.push({
72
157
  node,
73
158
  messageId: "power",
74
159
  data: { operator: "a ** b" },
75
- ...(local === undefined
76
- ? {}
77
- : { fix: (fixer) => fixer.replaceText(node, `${local}.pow(${text.getText(node.left)}, ${text.getText(node.right)})`) })
160
+ rewrite: (ops, text) => `${ops}.pow(${text(node.left)}, ${text(node.right)})`
78
161
  })
79
162
  },
80
163
  AssignmentExpression(node) {
81
164
  if (node.operator !== "**=") return
82
165
  if (node.right.type === "Literal" && node.right.value === 2) return
83
- context.report({ node, messageId: "power", data: { operator: "a **= b" } })
166
+ const target = node.left
167
+ pending.push({
168
+ node,
169
+ messageId: "power",
170
+ data: { operator: "a **= b" },
171
+ // `a.b **= c` is left alone: writing `a.b = Ops.pow(a.b, c)` evaluates `a` twice.
172
+ ...(target.type === "Identifier"
173
+ ? { rewrite: (ops: string, text: (child: ESTree.Node) => string) => `${target.name} = ${ops}.pow(${target.name}, ${text(node.right)})` }
174
+ : {})
175
+ })
176
+ },
177
+ "Program:exit"(program) {
178
+ const binding = opsBinding(program)
179
+ const ops = binding?.name ?? "Ops"
180
+ /** Whether `Ops` (or its local name) at `node` names the binding the fix relies on. */
181
+ const reachable = (node: ESTree.Node): boolean => {
182
+ const variable = resolve(context.sourceCode.getScope(node), ops)
183
+ return binding === undefined ? variable === undefined : variable?.identifiers.some((identifier) => identifier.range[0] === binding.range[0]) === true
184
+ }
185
+ pending.sort((a, b) => a.node.range[0] - b.node.range[0] || b.node.range[1] - a.node.range[1])
186
+ const fixable = pending.filter((report): report is Fixable => report.rewrite !== undefined && reachable(report.node))
187
+ /** The fixable reports inside `node` that no other one inside it holds. */
188
+ const outermostWithin = (node: ESTree.Node): Array<Fixable> => {
189
+ const found: Array<Fixable> = []
190
+ for (const report of fixable) {
191
+ const [start, end] = report.node.range
192
+ if (report.node === node || start < node.range[0] || end > node.range[1]) continue
193
+ const last = found[found.length - 1]
194
+ if (last === undefined || start >= last.node.range[1]) found.push(report)
195
+ }
196
+ return found
197
+ }
198
+ /** The text of `node` with every fix inside it applied, so one fix also covers the ones it holds. */
199
+ const text = (node: ESTree.Node): string => {
200
+ const own = fixable.find((report) => report.node === node)
201
+ if (own !== undefined) return rewritten(own)
202
+ const [start] = node.range
203
+ let source = context.sourceCode.getText(node)
204
+ for (const inner of outermostWithin(node).reverse()) {
205
+ source = source.slice(0, inner.node.range[0] - start) + rewritten(inner) + source.slice(inner.node.range[1] - start)
206
+ }
207
+ return node.type === "SequenceExpression" ? `(${source})` : source
208
+ }
209
+ const rewritten = (report: Fixable): string => report.rewrite(ops, text)
210
+ const topLevel = new Map(outermostWithin(program).map((report) => [report.node, report]))
211
+ let importAdded = binding !== undefined
212
+ for (const { node, messageId, data } of pending) {
213
+ const report = topLevel.get(node)
214
+ // A fix inside another one is applied by the outer one.
215
+ if (report === undefined) {
216
+ context.report({ node, messageId, ...(data === undefined ? {} : { data }) })
217
+ continue
218
+ }
219
+ // The first fix in the file also adds the import; it spans the code up to its node,
220
+ // which holds no other fix, so every fix applies in the same pass.
221
+ const addsImport = !importAdded
222
+ importAdded = true
223
+ const replace = (fixer: Fixer): Fix => fixer.replaceText(node, rewritten(report))
224
+ context.report({
225
+ node,
226
+ messageId,
227
+ ...(data === undefined ? {} : { data }),
228
+ fix: (fixer) => addsImport ? [importOps(context, fixer, program), replace(fixer)] : replace(fixer)
229
+ })
230
+ }
84
231
  }
85
232
  }
86
233
  }
87
234
  })
235
+
236
+ /**
237
+ * Adds `import { Ops } from "@typeonce/ritmo"` after the file's last import
238
+ * (or `const { Ops } = require("@typeonce/ritmo")` after its last top-level
239
+ * `require` in CommonJS), or at the top after any directives.
240
+ */
241
+ const importOps = (context: Context, fixer: Fixer, program: ESTree.Program): Fix => {
242
+ const commonJs = isCommonJs(context, program)
243
+ let lastLoad: ESTree.Node | undefined
244
+ let lastDirective: ESTree.Node | undefined
245
+ for (const statement of program.body) {
246
+ if (statement.type === "ExpressionStatement" && typeof statement.directive === "string") lastDirective = statement
247
+ const loads = commonJs
248
+ ? statement.type === "VariableDeclaration" && statement.declarations.some((declarator) => requireOf(declarator.init) !== undefined)
249
+ : statement.type === "ImportDeclaration"
250
+ if (loads) lastLoad = statement
251
+ }
252
+ const anchor = lastLoad ?? lastDirective
253
+ const reference = anchor ?? program.body[0]
254
+ const semicolon = reference !== undefined && context.sourceCode.getText(reference).endsWith(";") ? ";" : ""
255
+ const line = (commonJs ? "const { Ops } = require(\"@typeonce/ritmo\")" : "import { Ops } from \"@typeonce/ritmo\"") + semicolon
256
+ if (anchor !== undefined) return fixer.insertTextAfter(anchor, `\n${line}`)
257
+ const start = reference?.range[0] ?? 0
258
+ return fixer.insertTextBeforeRange([start, start], `${line}\n`)
259
+ }