@typeonce/oxlint-plugin-ritmo 0.14.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,78 +1,148 @@
1
1
  import { defineRule } from "@oxlint/plugins";
2
- import { docsUrl, globalMember } from "../internal/ast.js";
2
+ import { docsUrl, globalMember, isGlobalReference, propertyName, stringValue } from "../internal/ast.js";
3
3
  /** The Math functions engines may approximate; each has an `Ops` counterpart. */
4
4
  const approximated = new Set([
5
5
  "sin", "cos", "tan", "asin", "acos", "atan", "atan2",
6
6
  "exp", "expm1", "log", "log2", "log10", "log1p", "cbrt", "pow", "hypot",
7
7
  "sinh", "cosh", "tanh", "asinh", "acosh", "atanh"
8
8
  ]);
9
- /** The local name `Ops` is imported under in this file, if it is. */
9
+ /** Where the type checker reads `Math` as a type: these never run. */
10
+ const typePositions = new Set(["TSTypeQuery", "TSQualifiedName", "TSTypeReference", "TSClassImplements", "TSInterfaceHeritage"]);
11
+ /** The value `require("<source>")` loads, if `node` is that call. */
12
+ const requireOf = (node) => node?.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "require" && node.arguments.length === 1
13
+ ? stringValue(node.arguments[0])
14
+ : undefined;
15
+ /** The identifier `Ops` is bound to in this file (an import or a top-level `require`), if it is. */
10
16
  const opsBinding = (program) => {
11
17
  for (const statement of program.body) {
12
- if (statement.type !== "ImportDeclaration" || statement.importKind === "type")
18
+ if (statement.type === "ImportDeclaration") {
19
+ if (statement.importKind === "type")
20
+ continue;
21
+ const source = statement.source.value;
22
+ for (const specifier of statement.specifiers) {
23
+ if (source === "@typeonce/ritmo" && specifier.type === "ImportSpecifier" && specifier.importKind !== "type" &&
24
+ specifier.imported.type === "Identifier" && specifier.imported.name === "Ops")
25
+ return specifier.local;
26
+ if ((source === "@typeonce/ritmo/Ops" || /^\.{1,2}\/(.*\/)?Ops(\.ts)?$/.test(source)) && specifier.type === "ImportNamespaceSpecifier") {
27
+ return specifier.local;
28
+ }
29
+ }
30
+ }
31
+ if (statement.type !== "VariableDeclaration")
13
32
  continue;
14
- const source = statement.source.value;
15
- for (const specifier of statement.specifiers) {
16
- if (source === "@typeonce/ritmo-math" && specifier.type === "ImportSpecifier" && specifier.importKind !== "type" &&
17
- specifier.imported.type === "Identifier" && specifier.imported.name === "Ops")
18
- return specifier.local.name;
19
- if ((source === "@typeonce/ritmo-math/Ops" || /(^|\/)Ops(\.ts)?$/.test(source)) && specifier.type === "ImportNamespaceSpecifier") {
20
- return specifier.local.name;
33
+ for (const declarator of statement.declarations) {
34
+ const source = requireOf(declarator.init);
35
+ // const Ops = require("@typeonce/ritmo/Ops")
36
+ if (source === "@typeonce/ritmo/Ops" && declarator.id.type === "Identifier")
37
+ return declarator.id;
38
+ // const { Ops } = require("@typeonce/ritmo")
39
+ if (source !== "@typeonce/ritmo" || declarator.id.type !== "ObjectPattern")
40
+ continue;
41
+ for (const property of declarator.id.properties) {
42
+ if (property.type === "Property" && propertyKey(property) === "Ops" && property.value.type === "Identifier")
43
+ return property.value;
21
44
  }
22
45
  }
23
46
  }
24
47
  return undefined;
25
48
  };
49
+ /** The static name of an object pattern or literal property (`a`, `"a"`), if it has one. */
50
+ const propertyKey = (node) => !node.computed && node.key.type === "Identifier" ? node.key.name : stringValue(node.key);
51
+ /** The variable `name` resolves to from `scope`, if any declaration in the file binds it. */
52
+ const resolve = (scope, name) => {
53
+ for (let current = scope; current !== null; current = current.upper) {
54
+ const variable = current.set.get(name);
55
+ if (variable !== undefined && variable.defs.length > 0)
56
+ return variable;
57
+ }
58
+ return undefined;
59
+ };
60
+ /**
61
+ * Whether the file is CommonJS: a `.cjs` / `.cts` file, or one with no import
62
+ * or export that calls `require` or writes `module.exports` / `exports.`.
63
+ */
64
+ const isCommonJs = (context, program) => {
65
+ if (/\.c[jt]s$/.test(context.filename))
66
+ return true;
67
+ if (program.body.some((statement) => statement.type === "ImportDeclaration" || statement.type.startsWith("Export")))
68
+ return false;
69
+ return /\brequire\s*\(|\bmodule\.exports\b|\bexports\.[A-Za-z_$]/.test(context.sourceCode.text);
70
+ };
26
71
  /**
27
- * Simulation code uses `Ops` from `@typeonce/ritmo-math` for the math
28
- * functions engines may approximate, so every device computes the same bits.
72
+ * Simulation code uses `Ops` from `@typeonce/ritmo` for the math functions
73
+ * engines may approximate, so every device computes the same bits.
29
74
  */
30
75
  export default defineRule({
31
76
  meta: {
32
77
  type: "problem",
33
78
  docs: {
34
- description: "Use Ops from @typeonce/ritmo-math instead of the Math functions and `**` that differ across engines.",
79
+ description: "Use Ops from @typeonce/ritmo instead of the Math functions and `**` that differ across engines.",
35
80
  url: docsUrl("use-ops-for-math")
36
81
  },
37
82
  fixable: "code",
38
83
  messages: {
39
- math: "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.",
40
- power: "`{{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."
84
+ math: "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.",
85
+ power: "`{{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.",
86
+ alias: "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`)."
41
87
  },
42
88
  schema: []
43
89
  },
44
90
  create(context) {
45
- let ops;
91
+ const pending = [];
92
+ /** Whether `node` is the global Math: `Math` or `globalThis.Math` (not a local named Math). */
93
+ const isMath = (node) => node.type === "Identifier"
94
+ ? node.name === "Math" && isGlobalReference(context, node)
95
+ : node.type === "MemberExpression" && globalMember(context, node, "globalThis") === "Math";
96
+ /** Whether destructuring Math with `pattern` pulls only exact members by name. */
97
+ const pullsOnlyExact = (pattern) => pattern.type === "ObjectPattern" && pattern.properties.every((property) => {
98
+ if (property.type !== "Property")
99
+ return false;
100
+ const key = propertyKey(property);
101
+ return key !== undefined && !approximated.has(key);
102
+ });
103
+ /** Checks one use of the global Math. */
104
+ const checkMath = (node) => {
105
+ const parent = node.parent;
106
+ if (parent === null || typePositions.has(parent.type))
107
+ return;
108
+ if (parent.type === "MemberExpression" && parent.object === node) {
109
+ const name = propertyName(parent);
110
+ if (name === undefined) {
111
+ pending.push({ node: parent, messageId: "alias" });
112
+ return;
113
+ }
114
+ if (!approximated.has(name))
115
+ return;
116
+ pending.push({ node: parent, messageId: "math", data: { name }, rewrite: (ops) => `${ops}.${name}` });
117
+ return;
118
+ }
119
+ if (parent.type === "VariableDeclarator" && parent.init === node && pullsOnlyExact(parent.id))
120
+ return;
121
+ if (parent.type === "AssignmentExpression" && parent.right === node && pullsOnlyExact(parent.left))
122
+ return;
123
+ if (parent.type === "BinaryExpression" && parent.operator === "in")
124
+ return;
125
+ pending.push({ node, messageId: "alias" });
126
+ };
46
127
  return {
47
- Program(node) {
48
- ops = opsBinding(node);
128
+ Identifier(node) {
129
+ if (isMath(node))
130
+ checkMath(node);
49
131
  },
50
132
  MemberExpression(node) {
51
- const name = globalMember(context, node, "Math");
52
- if (name === undefined || !approximated.has(name))
53
- return;
54
- const local = ops;
55
- context.report({
56
- node,
57
- messageId: "math",
58
- data: { name },
59
- ...(local === undefined ? {} : { fix: (fixer) => fixer.replaceText(node, `${local}.${name}`) })
60
- });
133
+ if (isMath(node))
134
+ checkMath(node);
61
135
  },
62
136
  BinaryExpression(node) {
63
137
  if (node.operator !== "**")
64
138
  return;
65
139
  if (node.right.type === "Literal" && node.right.value === 2)
66
140
  return;
67
- const local = ops;
68
- const text = context.sourceCode;
69
- context.report({
141
+ pending.push({
70
142
  node,
71
143
  messageId: "power",
72
144
  data: { operator: "a ** b" },
73
- ...(local === undefined
74
- ? {}
75
- : { fix: (fixer) => fixer.replaceText(node, `${local}.pow(${text.getText(node.left)}, ${text.getText(node.right)})`) })
145
+ rewrite: (ops, text) => `${ops}.pow(${text(node.left)}, ${text(node.right)})`
76
146
  });
77
147
  },
78
148
  AssignmentExpression(node) {
@@ -80,9 +150,103 @@ export default defineRule({
80
150
  return;
81
151
  if (node.right.type === "Literal" && node.right.value === 2)
82
152
  return;
83
- context.report({ node, messageId: "power", data: { operator: "a **= b" } });
153
+ const target = node.left;
154
+ pending.push({
155
+ node,
156
+ messageId: "power",
157
+ data: { operator: "a **= b" },
158
+ // `a.b **= c` is left alone: writing `a.b = Ops.pow(a.b, c)` evaluates `a` twice.
159
+ ...(target.type === "Identifier"
160
+ ? { rewrite: (ops, text) => `${target.name} = ${ops}.pow(${target.name}, ${text(node.right)})` }
161
+ : {})
162
+ });
163
+ },
164
+ "Program:exit"(program) {
165
+ const binding = opsBinding(program);
166
+ const ops = binding?.name ?? "Ops";
167
+ /** Whether `Ops` (or its local name) at `node` names the binding the fix relies on. */
168
+ const reachable = (node) => {
169
+ const variable = resolve(context.sourceCode.getScope(node), ops);
170
+ return binding === undefined ? variable === undefined : variable?.identifiers.some((identifier) => identifier.range[0] === binding.range[0]) === true;
171
+ };
172
+ pending.sort((a, b) => a.node.range[0] - b.node.range[0] || b.node.range[1] - a.node.range[1]);
173
+ const fixable = pending.filter((report) => report.rewrite !== undefined && reachable(report.node));
174
+ /** The fixable reports inside `node` that no other one inside it holds. */
175
+ const outermostWithin = (node) => {
176
+ const found = [];
177
+ for (const report of fixable) {
178
+ const [start, end] = report.node.range;
179
+ if (report.node === node || start < node.range[0] || end > node.range[1])
180
+ continue;
181
+ const last = found[found.length - 1];
182
+ if (last === undefined || start >= last.node.range[1])
183
+ found.push(report);
184
+ }
185
+ return found;
186
+ };
187
+ /** The text of `node` with every fix inside it applied, so one fix also covers the ones it holds. */
188
+ const text = (node) => {
189
+ const own = fixable.find((report) => report.node === node);
190
+ if (own !== undefined)
191
+ return rewritten(own);
192
+ const [start] = node.range;
193
+ let source = context.sourceCode.getText(node);
194
+ for (const inner of outermostWithin(node).reverse()) {
195
+ source = source.slice(0, inner.node.range[0] - start) + rewritten(inner) + source.slice(inner.node.range[1] - start);
196
+ }
197
+ return node.type === "SequenceExpression" ? `(${source})` : source;
198
+ };
199
+ const rewritten = (report) => report.rewrite(ops, text);
200
+ const topLevel = new Map(outermostWithin(program).map((report) => [report.node, report]));
201
+ let importAdded = binding !== undefined;
202
+ for (const { node, messageId, data } of pending) {
203
+ const report = topLevel.get(node);
204
+ // A fix inside another one is applied by the outer one.
205
+ if (report === undefined) {
206
+ context.report({ node, messageId, ...(data === undefined ? {} : { data }) });
207
+ continue;
208
+ }
209
+ // The first fix in the file also adds the import; it spans the code up to its node,
210
+ // which holds no other fix, so every fix applies in the same pass.
211
+ const addsImport = !importAdded;
212
+ importAdded = true;
213
+ const replace = (fixer) => fixer.replaceText(node, rewritten(report));
214
+ context.report({
215
+ node,
216
+ messageId,
217
+ ...(data === undefined ? {} : { data }),
218
+ fix: (fixer) => addsImport ? [importOps(context, fixer, program), replace(fixer)] : replace(fixer)
219
+ });
220
+ }
84
221
  }
85
222
  };
86
223
  }
87
224
  });
225
+ /**
226
+ * Adds `import { Ops } from "@typeonce/ritmo"` after the file's last import
227
+ * (or `const { Ops } = require("@typeonce/ritmo")` after its last top-level
228
+ * `require` in CommonJS), or at the top after any directives.
229
+ */
230
+ const importOps = (context, fixer, program) => {
231
+ const commonJs = isCommonJs(context, program);
232
+ let lastLoad;
233
+ let lastDirective;
234
+ for (const statement of program.body) {
235
+ if (statement.type === "ExpressionStatement" && typeof statement.directive === "string")
236
+ lastDirective = statement;
237
+ const loads = commonJs
238
+ ? statement.type === "VariableDeclaration" && statement.declarations.some((declarator) => requireOf(declarator.init) !== undefined)
239
+ : statement.type === "ImportDeclaration";
240
+ if (loads)
241
+ lastLoad = statement;
242
+ }
243
+ const anchor = lastLoad ?? lastDirective;
244
+ const reference = anchor ?? program.body[0];
245
+ const semicolon = reference !== undefined && context.sourceCode.getText(reference).endsWith(";") ? ";" : "";
246
+ const line = (commonJs ? "const { Ops } = require(\"@typeonce/ritmo\")" : "import { Ops } from \"@typeonce/ritmo\"") + semicolon;
247
+ if (anchor !== undefined)
248
+ return fixer.insertTextAfter(anchor, `\n${line}`);
249
+ const start = reference?.range[0] ?? 0;
250
+ return fixer.insertTextBeforeRange([start, start], `${line}\n`);
251
+ };
88
252
  //# sourceMappingURL=use-ops-for-math.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-ops-for-math.js","sourceRoot":"","sources":["../../src/rules/use-ops-for-math.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAG5C,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAE1D,iFAAiF;AACjF,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC;IAC3B,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO;IACpD,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO;IACvE,MAAM,EAAE,MAAM,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,KAAK,IAAI,EAAE,CAAC,CAAA;IAC3E,MAAM,KAAK,GAAG,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IACtC,OAAO,KAAK,CAAC,qBAAqB,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,GAAG,IAAI,IAAI,CAAC,CAAA;AACjE,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typeonce/oxlint-plugin-ritmo",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Oxlint rules for Ritmo games: deterministic, headless simulation code and checked runtime results",
5
5
  "author": "Sandro Maglione",
6
6
  "license": "MIT",
package/src/index.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Types catch wrong calls and devtools catch wrong runs; these rules catch
5
5
  * the source patterns neither can see: simulation code that reads the wall
6
- * clock, `Math.random`, engine-dependent math, or the page, data that cannot
7
- * be saved, state values that keep a previous state's fields, and runtime
8
- * results that are dropped. Every report names the
9
- * Ritmo API to use instead.
6
+ * clock, `Math.random`, engine-dependent math, or the page, timers counted
7
+ * in floats, data that cannot be saved, casts that skip a brand's check,
8
+ * state values that keep a previous state's fields, and runtime results that
9
+ * are dropped. Every report names the Ritmo API to use instead.
10
10
  *
11
11
  * Register the plugin in `.oxlintrc.json` with `"jsPlugins":
12
12
  * ["@typeonce/oxlint-plugin-ritmo"]`. Its rules are named `ritmo/<rule>`.
@@ -16,7 +16,8 @@
16
16
  *
17
17
  * - Simulation files: `ritmo/use-clock-for-time`,
18
18
  * `ritmo/use-random-for-randomness`, `ritmo/use-ops-for-math`,
19
- * `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`.
19
+ * `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`,
20
+ * `ritmo/no-float-timers`, `ritmo/no-brand-cast`.
20
21
  * - Every file: `ritmo/handle-tick-result`,
21
22
  * `ritmo/prefix-descriptor-and-system-names`, `ritmo/use-cell-value`,
22
23
  * `ritmo/no-state-spread`.
@@ -27,6 +28,8 @@ import { definePlugin } from "@oxlint/plugins"
27
28
 
28
29
  import handleTickResult from "./rules/handle-tick-result.ts"
29
30
  import keepSimulationHeadless from "./rules/keep-simulation-headless.ts"
31
+ import noBrandCast from "./rules/no-brand-cast.ts"
32
+ import noFloatTimers from "./rules/no-float-timers.ts"
30
33
  import noInfinityInSimulationData from "./rules/no-infinity-in-simulation-data.ts"
31
34
  import noStateSpread from "./rules/no-state-spread.ts"
32
35
  import prefixDescriptorAndSystemNames from "./rules/prefix-descriptor-and-system-names.ts"
@@ -43,6 +46,8 @@ export default definePlugin({
43
46
  "use-ops-for-math": useOpsForMath,
44
47
  "keep-simulation-headless": keepSimulationHeadless,
45
48
  "no-infinity-in-simulation-data": noInfinityInSimulationData,
49
+ "no-float-timers": noFloatTimers,
50
+ "no-brand-cast": noBrandCast,
46
51
  "handle-tick-result": handleTickResult,
47
52
  "prefix-descriptor-and-system-names": prefixDescriptorAndSystemNames,
48
53
  "use-cell-value": useCellValue,
@@ -0,0 +1,195 @@
1
+ import { defineRule } from "@oxlint/plugins"
2
+ import type { ESTree } from "@oxlint/plugins"
3
+
4
+ import { docsUrl } from "../internal/ast.ts"
5
+
6
+ /** The type names that are brands wherever they come from: `Brand.Branded<...>`, Effect's `Brand.Brand<...>`, Zod's `z.BRAND<...>` / `z.$brand<...>`. */
7
+ const brandNames = new Set(["Brand", "Branded", "BRAND", "$brand"])
8
+
9
+ /** Property keys that only a brand declares (`T & { readonly __brand: "UserId" }`). */
10
+ const brandKey = /^(__?brand|__publicBrand|__type)$/
11
+
12
+ /** Ritmo's branded exports, by module: `Clock.Deadline`, `Random.State`, `Entity.Handle`, ... */
13
+ const ritmoBrands = new Map<string, ReadonlySet<string>>([
14
+ ["Clock", new Set(["Deadline", "Step", "Duration", "ClockResource"])],
15
+ ["Entity", new Set(["Handle", "EntityId"])],
16
+ ["Random", new Set(["State"])],
17
+ ["Checkpoint", new Set(["Checkpoint", "Rewindable"])]
18
+ ])
19
+
20
+ /** The type helpers that read the type out of a schema: `z.infer<typeof X>`, `Schema.Schema.Type<typeof X>`. */
21
+ const schemaTypeHelpers = new Set(["infer", "output", "TypeOf", "Infer", "Type"])
22
+
23
+ /** A schema built with a brand: Zod's `.brand(...)` / `.brand<"X">()`, Effect's `Schema.brand(...)` / `.pipe(Schema.brand(...))`. */
24
+ const brandsSchema = /\bbrand\s*(<[^>]*>\s*)?\(/
25
+
26
+ /** The dotted names of a type name or expression (`Clock.Deadline` gives `["Clock", "Deadline"]`). */
27
+ const segments = (node: ESTree.Node): Array<string> | undefined => {
28
+ if (node.type === "Identifier") return [node.name]
29
+ if (node.type === "TSQualifiedName") {
30
+ const left = segments(node.left)
31
+ return left === undefined ? undefined : [...left, node.right.name]
32
+ }
33
+ if (node.type === "MemberExpression" && !node.computed && node.property.type === "Identifier") {
34
+ const left = segments(node.object)
35
+ return left === undefined ? undefined : [...left, node.property.name]
36
+ }
37
+ return undefined
38
+ }
39
+
40
+ /** Where a local name imported from Ritmo points: `[]` for the package, `["Clock"]` for a module, `["Clock", "Deadline"]` for a type. */
41
+ const ritmoImport = (declaration: ESTree.ImportDeclaration, specifier: ESTree.ImportDeclarationSpecifier): Array<string> | undefined => {
42
+ const match = /^@typeonce\/ritmo(\/([A-Za-z0-9]+))?$/.exec(declaration.source.value)
43
+ if (match === null) return undefined
44
+ const module = match[2]
45
+ const base = module === undefined ? [] : [module]
46
+ if (specifier.type === "ImportNamespaceSpecifier") return base
47
+ if (specifier.type !== "ImportSpecifier") return undefined
48
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value
49
+ return [...base, imported]
50
+ }
51
+
52
+ /**
53
+ * Simulation code never casts a value to a branded type: a brand stands for a
54
+ * check, and the cast claims it without running it.
55
+ */
56
+ export default defineRule({
57
+ meta: {
58
+ type: "problem",
59
+ docs: {
60
+ description: "Make a branded value through its schema or constructor, not with `as` / `<T>` casts.",
61
+ url: docsUrl("no-brand-cast")
62
+ },
63
+ messages: {
64
+ cast:
65
+ "This casts to `{{type}}`, a branded type: a brand stands for a check the value passed, and the cast claims it without running the check, so an invalid value travels as a valid one (and a save holding it fails to load, or the simulation computes with it). Make the value through its check instead: decode it at the boundary with the schema that brands it (`UserId.parse(raw)` with Zod, `Schema.decodeUnknownSync(UserId)(raw)` with Effect), or with Ritmo's constructor or guard: `Random.seed(n)` / `Random.result(n)`, `Clock.deadline(time, duration)` / `Clock.isDeadline(step)`, `Game.Entity.handle(id)` / `Entity.isHandle(Root)`."
66
+ },
67
+ schema: []
68
+ },
69
+ create(context) {
70
+ const aliases = new Map<string, ESTree.TSType>()
71
+ const interfaces = new Map<string, ESTree.TSInterfaceDeclaration>()
72
+ const values = new Map<string, ESTree.Node>()
73
+ const uniqueSymbols = new Set<string>()
74
+ const imports = new Map<string, Array<string>>()
75
+ const casts: Array<ESTree.TSAsExpression | ESTree.TSTypeAssertion> = []
76
+
77
+ /** Whether the value named `name` is a schema built with a brand in this file. */
78
+ const isBrandedSchema = (name: string): boolean => {
79
+ const init = values.get(name)
80
+ return init !== undefined && brandsSchema.test(context.sourceCode.getText(init))
81
+ }
82
+
83
+ /** Whether a dotted name is a brand: a brand helper, Ritmo's branded export, or a local brand alias. */
84
+ const namesBrand = (names: Array<string>, hasArguments: boolean, seen: Set<string>): boolean => {
85
+ const [root, ...rest] = names
86
+ if (root === undefined) return false
87
+ const imported = imports.get(root)
88
+ if (imported !== undefined) {
89
+ const [module, type, ...more] = [...imported, ...rest]
90
+ if (module !== undefined && type !== undefined && more.length === 0 && ritmoBrands.get(module)?.has(type) === true) return true
91
+ }
92
+ const last = names[names.length - 1]!
93
+ if (names.length === 1) {
94
+ const alias = aliases.get(root)
95
+ if (alias !== undefined) return !seen.has(root) && isBrand(alias, new Set([...seen, root]))
96
+ const declared = interfaces.get(root)
97
+ if (declared !== undefined) return !seen.has(root) && interfaceIsBrand(declared, new Set([...seen, root]))
98
+ return hasArguments && brandNames.has(root)
99
+ }
100
+ return brandNames.has(last)
101
+ }
102
+
103
+ const interfaceIsBrand = (node: ESTree.TSInterfaceDeclaration, seen: Set<string>): boolean =>
104
+ node.body.body.some(memberIsBrand) ||
105
+ node.extends.some((heritage) => {
106
+ const names = segments(heritage.expression)
107
+ return names !== undefined && namesBrand(names, heritage.typeArguments !== null, seen)
108
+ })
109
+
110
+ const memberIsBrand = (member: ESTree.TSSignature): boolean => {
111
+ if (member.type !== "TSPropertySignature") return false
112
+ if (!member.computed) return member.key.type === "Identifier" ? brandKey.test(member.key.name) : false
113
+ if (member.key.type === "Identifier" && uniqueSymbols.has(member.key.name)) return true
114
+ return /brand/i.test(context.sourceCode.getText(member.key))
115
+ }
116
+
117
+ /** Whether `node` reads the type of a branded schema: `typeof X.Type`, `(typeof X)["Type"]`. */
118
+ const readsBrandedSchema = (node: ESTree.TSType): boolean => {
119
+ if (node.type === "TSTypeQuery") {
120
+ const names = segments(node.exprName)
121
+ return names !== undefined && names.length === 2 && names[1] === "Type" && isBrandedSchema(names[0]!)
122
+ }
123
+ if (node.type === "TSIndexedAccessType" && node.objectType.type === "TSTypeQuery") {
124
+ const names = segments(node.objectType.exprName)
125
+ const index = node.indexType
126
+ return names !== undefined && names.length === 1 && isBrandedSchema(names[0]!) &&
127
+ index.type === "TSLiteralType" && index.literal.type === "Literal" && index.literal.value === "Type"
128
+ }
129
+ return false
130
+ }
131
+
132
+ const isBrand = (node: ESTree.TSType, seen: Set<string>): boolean => {
133
+ switch (node.type) {
134
+ case "TSIntersectionType":
135
+ case "TSUnionType":
136
+ return node.types.some((type) => isBrand(type, seen))
137
+ case "TSArrayType":
138
+ return isBrand(node.elementType, seen)
139
+ case "TSTypeOperator":
140
+ return node.operator === "readonly" && isBrand(node.typeAnnotation, seen)
141
+ case "TSParenthesizedType":
142
+ return isBrand(node.typeAnnotation, seen)
143
+ case "TSTypeLiteral":
144
+ return node.members.some(memberIsBrand)
145
+ case "TSTypeReference": {
146
+ const names = segments(node.typeName)
147
+ if (names === undefined) return false
148
+ const schema = node.typeArguments?.params[0]
149
+ if (names.length > 1 && schemaTypeHelpers.has(names[names.length - 1]!) && schema?.type === "TSTypeQuery") {
150
+ const target = segments(schema.exprName)
151
+ if (target !== undefined && target.length === 1 && isBrandedSchema(target[0]!)) return true
152
+ }
153
+ return namesBrand(names, node.typeArguments !== null, seen)
154
+ }
155
+ default:
156
+ return readsBrandedSchema(node)
157
+ }
158
+ }
159
+
160
+ return {
161
+ ImportDeclaration(node) {
162
+ for (const specifier of node.specifiers) {
163
+ const target = ritmoImport(node, specifier)
164
+ if (target !== undefined) imports.set(specifier.local.name, target)
165
+ }
166
+ },
167
+ TSTypeAliasDeclaration(node) {
168
+ aliases.set(node.id.name, node.typeAnnotation)
169
+ },
170
+ TSInterfaceDeclaration(node) {
171
+ interfaces.set(node.id.name, node)
172
+ },
173
+ VariableDeclarator(node) {
174
+ if (node.id.type !== "Identifier") return
175
+ const annotation = node.id.typeAnnotation?.typeAnnotation
176
+ // `declare const brand: unique symbol` names a key no value has; a symbol made at runtime is a real key.
177
+ if (annotation?.type === "TSTypeOperator" && annotation.operator === "unique" && node.init === null) uniqueSymbols.add(node.id.name)
178
+ if (node.init !== null) values.set(node.id.name, node.init)
179
+ },
180
+ TSAsExpression(node) {
181
+ casts.push(node)
182
+ },
183
+ TSTypeAssertion(node) {
184
+ casts.push(node)
185
+ },
186
+ // Declarations may follow the casts that use them, so casts are checked once the file is read.
187
+ "Program:exit"() {
188
+ for (const cast of casts) {
189
+ if (!isBrand(cast.typeAnnotation, new Set())) continue
190
+ context.report({ node: cast, messageId: "cast", data: { type: context.sourceCode.getText(cast.typeAnnotation) } })
191
+ }
192
+ }
193
+ }
194
+ }
195
+ })
@@ -0,0 +1,64 @@
1
+ import { defineRule } from "@oxlint/plugins"
2
+ import type { ESTree } from "@oxlint/plugins"
3
+
4
+ import { calledMethod, docsUrl, propertyName } from "../internal/ast.ts"
5
+
6
+ // The names a tick's seconds go by: a local, a field (`time.dt`), or a resource read (`resources.deltaTime.get()`).
7
+ const deltaNames = ["dt", "deltaTime", "deltaSeconds"]
8
+
9
+ /** `node` without the type-only wrappers TypeScript adds (`dt as number`, `dt!`). */
10
+ const unwrap = (node: ESTree.Node): ESTree.Node =>
11
+ node.type === "TSAsExpression" || node.type === "TSNonNullExpression" || node.type === "TSSatisfiesExpression" ? unwrap(node.expression) : node
12
+
13
+ /** Whether `node` is a tick's seconds on their own: `dt`, `time.dt`, or `resources.deltaTime.get()`. */
14
+ const isDelta = (raw: ESTree.Node): boolean => {
15
+ const node = unwrap(raw)
16
+ if (node.type === "Identifier") return deltaNames.includes(node.name)
17
+ if (node.type === "MemberExpression") return deltaNames.includes(propertyName(node) ?? "")
18
+ if (node.type === "CallExpression" && calledMethod(node) === "get" && node.callee.type === "MemberExpression") {
19
+ const receiver = unwrap(node.callee.object)
20
+ return receiver.type === "MemberExpression" && deltaNames.includes(propertyName(receiver) ?? "")
21
+ }
22
+ return false
23
+ }
24
+
25
+ /** Whether `node` reads a stored value (a local or a field), the thing a timer counts. */
26
+ const isStored = (raw: ESTree.Node): boolean => {
27
+ const node = unwrap(raw)
28
+ return (node.type === "Identifier" || node.type === "MemberExpression") && !isDelta(node)
29
+ }
30
+
31
+ /**
32
+ * A timer in simulation code is a deadline in steps, never a float counted
33
+ * down (or up) by `dt`: the float drifts, and the value it saves means
34
+ * nothing once the fixed step changes.
35
+ */
36
+ export default defineRule({
37
+ meta: {
38
+ type: "problem",
39
+ docs: {
40
+ description: "Keep timers and cooldowns as Clock deadlines in steps, not floats counted by dt.",
41
+ url: docsUrl("no-float-timers")
42
+ },
43
+ messages: {
44
+ floatTimer:
45
+ "`{{text}}` counts a timer by `dt` in floating point: rounding error builds up each tick, so it ends a step early or late, and the float it saves means nothing once the fixed step changes. Store the step it ends on instead: `ready: Clock.deadline(time, Clock.duration(step, seconds))` in the component or resource (its schema narrows with `Clock.isDeadline(step)`), and check `Clock.reached(time, ready)` each tick (`Clock.remaining(time, ready)` for a readout, `Clock.every(time, duration)` for something that repeats, `Clock.elapsed(time)` for seconds since the start)."
46
+ },
47
+ schema: []
48
+ },
49
+ create(context) {
50
+ const report = (node: ESTree.Node) =>
51
+ context.report({ node, messageId: "floatTimer", data: { text: context.sourceCode.getText(node) } })
52
+ return {
53
+ AssignmentExpression(node) {
54
+ // `timer -= dt`, `elapsed += time.dt`
55
+ if ((node.operator === "-=" || node.operator === "+=") && isDelta(node.right)) report(node)
56
+ },
57
+ BinaryExpression(node) {
58
+ // `cooldown.remaining - dt`, `time.dt + since`; `x + vx * dt` scales dt, so it is integration.
59
+ if (node.operator !== "-" && node.operator !== "+") return
60
+ if ((isDelta(node.right) && isStored(node.left)) || (isDelta(node.left) && isStored(node.right))) report(node)
61
+ }
62
+ }
63
+ }
64
+ })
@@ -19,7 +19,7 @@ export default defineRule({
19
19
  wallClock:
20
20
  "{{call}} reads the wall clock, so the simulation plays differently on every run and replays diverge. For time since the start, read the Clock resource (`Clock.elapsed(time)` in seconds, `time.step` in steps). For today's date, read it in host code and pass it in with `runtime.send(...)` or a resource, so the replay records it.",
21
21
  timer:
22
- "{{call}}() runs its callback outside the tick, at a moment a replay cannot reproduce. Count steps instead: store the step it fires at (`time.step + Clock.steps(Clock.duration(step, seconds))`) in a component or resource and compare it each tick, or use `Clock.every(time, duration)` for something that repeats."
22
+ "{{call}}() runs its callback outside the tick, at a moment a replay cannot reproduce. Count steps instead: store the step it fires at (`Clock.deadline(time, Clock.duration(step, seconds))`) in a component or resource and check it each tick with `Clock.reached(time, due)`, or use `Clock.every(time, duration)` for something that repeats."
23
23
  },
24
24
  schema: []
25
25
  },