@toiroakr/chisel 0.0.0-stage → 0.2.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 (129) hide show
  1. package/README.md +693 -2
  2. package/dist/absence.d.ts +27 -0
  3. package/dist/absence.js +228 -0
  4. package/dist/absence.js.map +1 -0
  5. package/dist/behavior.d.ts +193 -0
  6. package/dist/behavior.js +589 -0
  7. package/dist/behavior.js.map +1 -0
  8. package/dist/beside.d.ts +27 -0
  9. package/dist/beside.js +88 -0
  10. package/dist/beside.js.map +1 -0
  11. package/dist/border.d.ts +61 -0
  12. package/dist/border.js +434 -0
  13. package/dist/border.js.map +1 -0
  14. package/dist/bounds.d.ts +1 -0
  15. package/dist/bounds.js +26 -0
  16. package/dist/bounds.js.map +1 -0
  17. package/dist/cli.d.ts +7 -0
  18. package/dist/cli.js +835 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/codec.d.ts +6 -0
  21. package/dist/codec.js +86 -0
  22. package/dist/codec.js.map +1 -0
  23. package/dist/codegen.d.ts +2 -0
  24. package/dist/codegen.js +61 -0
  25. package/dist/codegen.js.map +1 -0
  26. package/dist/composition.d.ts +38 -0
  27. package/dist/composition.js +242 -0
  28. package/dist/composition.js.map +1 -0
  29. package/dist/data.d.ts +17 -0
  30. package/dist/data.js +51 -0
  31. package/dist/data.js.map +1 -0
  32. package/dist/dependency.d.ts +101 -0
  33. package/dist/dependency.js +161 -0
  34. package/dist/dependency.js.map +1 -0
  35. package/dist/domain.d.ts +12 -0
  36. package/dist/domain.js +217 -0
  37. package/dist/domain.js.map +1 -0
  38. package/dist/ensures.d.ts +15 -0
  39. package/dist/ensures.js +88 -0
  40. package/dist/ensures.js.map +1 -0
  41. package/dist/equal.d.ts +1 -0
  42. package/dist/equal.js +135 -0
  43. package/dist/equal.js.map +1 -0
  44. package/dist/exact.d.ts +21 -0
  45. package/dist/exact.js +80 -0
  46. package/dist/exact.js.map +1 -0
  47. package/dist/feasibility.d.ts +63 -0
  48. package/dist/feasibility.js +1053 -0
  49. package/dist/feasibility.js.map +1 -0
  50. package/dist/guard-borders.d.ts +57 -0
  51. package/dist/guard-borders.js +760 -0
  52. package/dist/guard-borders.js.map +1 -0
  53. package/dist/guard-scope.d.ts +61 -0
  54. package/dist/guard-scope.js +364 -0
  55. package/dist/guard-scope.js.map +1 -0
  56. package/dist/index.d.ts +48 -0
  57. package/dist/index.js +24 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/interleave.d.ts +31 -0
  60. package/dist/interleave.js +202 -0
  61. package/dist/interleave.js.map +1 -0
  62. package/dist/interval.d.ts +10 -0
  63. package/dist/interval.js +311 -0
  64. package/dist/interval.js.map +1 -0
  65. package/dist/isolated.d.ts +9 -0
  66. package/dist/isolated.js +41 -0
  67. package/dist/isolated.js.map +1 -0
  68. package/dist/machine-check.d.ts +73 -0
  69. package/dist/machine-check.js +215 -0
  70. package/dist/machine-check.js.map +1 -0
  71. package/dist/machine.d.ts +97 -0
  72. package/dist/machine.js +200 -0
  73. package/dist/machine.js.map +1 -0
  74. package/dist/model.d.ts +160 -0
  75. package/dist/model.js +778 -0
  76. package/dist/model.js.map +1 -0
  77. package/dist/outcomes.d.ts +7 -0
  78. package/dist/outcomes.js +38 -0
  79. package/dist/outcomes.js.map +1 -0
  80. package/dist/pairs.d.ts +26 -0
  81. package/dist/pairs.js +115 -0
  82. package/dist/pairs.js.map +1 -0
  83. package/dist/partition.d.ts +45 -0
  84. package/dist/partition.js +354 -0
  85. package/dist/partition.js.map +1 -0
  86. package/dist/proof.d.ts +21 -0
  87. package/dist/proof.js +556 -0
  88. package/dist/proof.js.map +1 -0
  89. package/dist/replay.d.ts +45 -0
  90. package/dist/replay.js +157 -0
  91. package/dist/replay.js.map +1 -0
  92. package/dist/report-json.d.ts +11 -0
  93. package/dist/report-json.js +94 -0
  94. package/dist/report-json.js.map +1 -0
  95. package/dist/rule.d.ts +186 -0
  96. package/dist/rule.js +866 -0
  97. package/dist/rule.js.map +1 -0
  98. package/dist/runtime.d.ts +12 -0
  99. package/dist/runtime.js +8 -0
  100. package/dist/runtime.js.map +1 -0
  101. package/dist/schema.d.ts +163 -0
  102. package/dist/schema.js +528 -0
  103. package/dist/schema.js.map +1 -0
  104. package/dist/specification.d.ts +266 -0
  105. package/dist/specification.js +2123 -0
  106. package/dist/specification.js.map +1 -0
  107. package/dist/temporal-global.d.ts +4 -0
  108. package/dist/temporal-global.js +11 -0
  109. package/dist/temporal-global.js.map +1 -0
  110. package/dist/temporal.d.ts +22 -0
  111. package/dist/temporal.js +113 -0
  112. package/dist/temporal.js.map +1 -0
  113. package/dist/text.d.ts +1 -0
  114. package/dist/text.js +11 -0
  115. package/dist/text.js.map +1 -0
  116. package/dist/tla.d.ts +54 -0
  117. package/dist/tla.js +579 -0
  118. package/dist/tla.js.map +1 -0
  119. package/dist/verification.d.ts +7 -0
  120. package/dist/verification.js +5 -0
  121. package/dist/verification.js.map +1 -0
  122. package/dist/ways.d.ts +28 -0
  123. package/dist/ways.js +86 -0
  124. package/dist/ways.js.map +1 -0
  125. package/dist/world.d.ts +98 -0
  126. package/dist/world.js +467 -0
  127. package/dist/world.js.map +1 -0
  128. package/package.json +76 -4
  129. package/schema/report.schema.json +1062 -0
package/dist/rule.js ADDED
@@ -0,0 +1,866 @@
1
+ import { Rational, isRational, fractionOf, decimalOf } from "./exact.js";
2
+ import { compareText } from "./text.js";
3
+ import { deepEqual } from "./equal.js";
4
+ // Symbol.for, not Symbol(): the CLI loads spec files through tsImport in a
5
+ // separate module graph, and a per-module symbol would not recognise their terms.
6
+ const TERM = Symbol.for("chisel.term");
7
+ export function measureOf(transforms, reading) {
8
+ return transforms.length === 0 ? reading : `${transforms.join(",")}:${reading}`;
9
+ }
10
+ export function partsOfMeasure(measure) {
11
+ const colon = measure.lastIndexOf(":");
12
+ return colon === -1
13
+ ? { transforms: [], reading: measure }
14
+ : { transforms: measure.slice(0, colon).split(","), reading: measure.slice(colon + 1) };
15
+ }
16
+ // Each part of a named invariant keeps its name.
17
+ export function conjuncts(rule) {
18
+ if (rule.kind !== "and") {
19
+ return [rule];
20
+ }
21
+ const { name } = rule;
22
+ return rule.rules.flatMap(part => conjuncts(name === undefined || part.name !== undefined ? part : { ...part, name }));
23
+ }
24
+ let quantifiedDepth = 0;
25
+ // The element is named by nesting depth, not by a fresh symbol: a term from an
26
+ // enclosing all/any must keep a path the analysis can resolve to that
27
+ // enclosing element, and a depth reads the same in every module graph.
28
+ function quantified(kind, of, each) {
29
+ const element = `#each${quantifiedDepth}`;
30
+ quantifiedDepth += 1;
31
+ try {
32
+ return condition({
33
+ kind,
34
+ of: of,
35
+ element,
36
+ each: each(termAt([element], "value")),
37
+ });
38
+ }
39
+ finally {
40
+ quantifiedDepth -= 1;
41
+ }
42
+ }
43
+ // The combinators are not enumerable, so a rule still compares, prints and
44
+ // serialises as the plain data the analysis reads.
45
+ function condition(rule) {
46
+ Object.defineProperties(rule, {
47
+ $and: { value: (other) => condition({ kind: "and", rules: [rule, other] }) },
48
+ $or: { value: (other) => condition({ kind: "or", rules: [rule, other] }) },
49
+ $not: { value: () => condition({ kind: "not", rule }) },
50
+ $else: { value: (orElse) => ({ kind: "guard", condition: rule, orElse }) },
51
+ });
52
+ return rule;
53
+ }
54
+ // A key no object schema field is expected to take: deps terms live beside the
55
+ // input fields in the scope a guard is evaluated against, not in a separate one,
56
+ // so a comparison reached records the dependency values with the input.
57
+ export const DEPS = "#deps";
58
+ const INPUT = Symbol.for("chisel.input");
59
+ export function depsTerm() {
60
+ return termAt([DEPS], "value");
61
+ }
62
+ export function bindElement(scope, name, element) {
63
+ return typeof scope === "object" && scope !== null && !Array.isArray(scope)
64
+ ? { ...scope, [name]: element }
65
+ : { [name]: element };
66
+ }
67
+ export function withLocal(scope, name, value) {
68
+ const original = typeof scope === "object" && scope !== null && INPUT in scope ? scope[INPUT] : scope;
69
+ return { ...(typeof scope === "object" && scope !== null ? scope : {}), [name]: value, [INPUT]: original };
70
+ }
71
+ export function withDeps(input, deps) {
72
+ return deps === undefined || typeof input !== "object" || input === null
73
+ ? input
74
+ : { ...input, [DEPS]: deps, [INPUT]: input };
75
+ }
76
+ export function rootTerm(key) {
77
+ return termAt([key], "value");
78
+ }
79
+ export function termPaths(rule) {
80
+ switch (rule.kind) {
81
+ case "compare":
82
+ return [rule.left, rule.right].filter(isTerm).flatMap(term => pathsOf(termData(term)));
83
+ case "all":
84
+ case "any":
85
+ return [positionOf(rule.of).path];
86
+ case "and":
87
+ case "or":
88
+ return rule.rules.flatMap(termPaths);
89
+ case "not":
90
+ return termPaths(rule.rule);
91
+ }
92
+ }
93
+ // Every path the rule reads, inside a quantifier's condition too, less those
94
+ // of the element it ranges over.
95
+ export function pathsRead(rule) {
96
+ switch (rule.kind) {
97
+ case "compare":
98
+ return termPaths(rule);
99
+ case "all":
100
+ case "any":
101
+ return [positionOf(rule.of).path, ...pathsRead(rule.each).filter(path => path[0] !== rule.element)];
102
+ case "and":
103
+ case "or":
104
+ return rule.rules.flatMap(pathsRead);
105
+ case "not":
106
+ return pathsRead(rule.rule);
107
+ }
108
+ }
109
+ export function rootsRead(rule) {
110
+ const roots = new Set(termPaths(rule).map(path => path[0]));
111
+ if (rule.kind === "all" || rule.kind === "any") {
112
+ for (const root of rootsRead(rule.each)) {
113
+ roots.add(root);
114
+ }
115
+ }
116
+ if (rule.kind === "and" || rule.kind === "or") {
117
+ rule.rules.forEach(part => rootsRead(part).forEach(root => roots.add(root)));
118
+ }
119
+ if (rule.kind === "not") {
120
+ rootsRead(rule.rule).forEach(root => roots.add(root));
121
+ }
122
+ return roots;
123
+ }
124
+ export function selfTerm() {
125
+ return termAt([], "value");
126
+ }
127
+ export function isTerm(value) {
128
+ return ((typeof value === "object" || typeof value === "function") &&
129
+ value !== null &&
130
+ TERM in value);
131
+ }
132
+ export function termData(term) {
133
+ return term[TERM];
134
+ }
135
+ export function boundTermPath(rule) {
136
+ if (rule.kind !== "compare") {
137
+ return undefined;
138
+ }
139
+ if (isTerm(rule.left) !== isTerm(rule.right)) {
140
+ return positionData((isTerm(rule.left) ? rule.left : rule.right))?.path;
141
+ }
142
+ return undefined;
143
+ }
144
+ export function shiftTerms(rule) {
145
+ const shift = (operand) => (isTerm(operand) ? shiftedTerm(termData(operand)) : operand);
146
+ return { ...rule, left: shift(rule.left), right: shift(rule.right) };
147
+ }
148
+ export function stepInto(rule, key) {
149
+ const path = boundTermPath(rule);
150
+ if (rule.kind !== "compare" || path === undefined || path[0] !== key) {
151
+ return undefined;
152
+ }
153
+ const shift = (operand) => (isTerm(operand) ? shiftedTerm(termData(operand)) : operand);
154
+ return { ...rule, left: shift(rule.left), right: shift(rule.right) };
155
+ }
156
+ export function holds(rule, value, observe, decide) {
157
+ switch (rule.kind) {
158
+ case "and":
159
+ return rule.rules.every(part => holds(part, value, observe, decide));
160
+ case "or":
161
+ return rule.rules.some(part => holds(part, value, observe, decide));
162
+ case "not":
163
+ return !holds(rule.rule, value, observe, decide);
164
+ case "all":
165
+ case "any": {
166
+ const elements = read(rule.of, value);
167
+ const each = (element) => holds(rule.each, bindElement(value, rule.element, element), observe);
168
+ const outcome = !Array.isArray(elements)
169
+ ? rule.kind === "all"
170
+ : rule.kind === "all"
171
+ ? elements.every(each)
172
+ : elements.some(each);
173
+ decide?.(rule, outcome);
174
+ return outcome;
175
+ }
176
+ case "compare": {
177
+ const outcome = compares(rule, value, observe);
178
+ decide?.(rule, outcome);
179
+ return outcome;
180
+ }
181
+ }
182
+ }
183
+ function compares(rule, value, observe) {
184
+ observe?.(rule, value);
185
+ const left = read(rule.left, value);
186
+ const right = read(rule.right, value);
187
+ if (left === undefined || right === undefined) {
188
+ return true;
189
+ }
190
+ const order = ordering(left, right);
191
+ switch (rule.operator) {
192
+ case "<":
193
+ return order < 0;
194
+ case "<=":
195
+ return order <= 0;
196
+ case ">":
197
+ return order > 0;
198
+ case ">=":
199
+ return order >= 0;
200
+ case "==":
201
+ return order === 0;
202
+ case "!=":
203
+ return order !== 0;
204
+ }
205
+ }
206
+ // `stepAt` names the step of the value a term reads, where it is not the default
207
+ // (the value next to 0.5 in a decimal of cents is 0.51, not 1.5), or the values it
208
+ // may take: an enum's that its own invariants keep.
209
+ export function satisfy(rule, value, stepAt) {
210
+ if (holds(rule, value)) {
211
+ return value;
212
+ }
213
+ switch (rule.kind) {
214
+ case "and":
215
+ return rule.rules.reduce((current, part) => satisfy(part, current, stepAt), value);
216
+ case "or": {
217
+ for (const part of rule.rules) {
218
+ const moved = satisfy(part, value, stepAt);
219
+ if (holds(rule, moved)) {
220
+ return moved;
221
+ }
222
+ }
223
+ return value;
224
+ }
225
+ case "compare":
226
+ return satisfyComparison(rule, value, stepAt);
227
+ default:
228
+ return value;
229
+ }
230
+ }
231
+ function satisfyComparison(rule, value, stepAt) {
232
+ const [term, other, operator] = isTerm(rule.left) && positionData(rule.left) !== undefined
233
+ ? [rule.left, rule.right, rule.operator]
234
+ : isTerm(rule.right) && positionData(rule.right) !== undefined
235
+ ? [rule.right, rule.left, mirrored[rule.operator]]
236
+ : [rule.left, rule.right, rule.operator];
237
+ if (!isTerm(term)) {
238
+ return value;
239
+ }
240
+ const bound = read(other, value);
241
+ if (bound === undefined) {
242
+ return value;
243
+ }
244
+ const position = positionData(term);
245
+ if (position === undefined) {
246
+ return value;
247
+ }
248
+ const { path, measure } = position;
249
+ const named = stepAt?.(path);
250
+ if (named !== undefined && typeof named !== "function") {
251
+ // A value of a finite domain is chosen, not stepped to: the first one the rule
252
+ // keeps, whichever way the rule orders them, and however it reads the value
253
+ // (`$lowercase()` would otherwise write "high" into an enum of "High").
254
+ const chosen = named.among.find(candidate => holds(rule, writeAt(value, path, () => candidate)));
255
+ return chosen === undefined ? value : writeAt(value, path, () => chosen);
256
+ }
257
+ const move = (measure === "value" ? named : undefined) ?? step;
258
+ const target = operator === ">" || operator === "!="
259
+ ? move(bound, 1)
260
+ : operator === "<"
261
+ ? move(bound, -1)
262
+ : bound;
263
+ const written = writeAt(value, path, current => rewrite(current, measure, target));
264
+ if (operator === "==" && !holds(rule, written)) {
265
+ // A rule that the string reads the same transformed, `uppercase($) == $`, is
266
+ // kept by the transformed value itself, which no transform changes again.
267
+ const { transforms, reading } = partsOfMeasure(measure);
268
+ if (reading === "value" && transforms.length > 0) {
269
+ const kept = writeAt(value, path, current => transformed(current, transforms));
270
+ if (holds(rule, kept)) {
271
+ return kept;
272
+ }
273
+ }
274
+ }
275
+ return written;
276
+ }
277
+ export function describeRule(rule, path = "$", elements = {}) {
278
+ switch (rule.kind) {
279
+ case "all":
280
+ case "any": {
281
+ const of = describeOperand(rule.of, path, elements);
282
+ return `${rule.kind}(${of}, ${describeRule(rule.each, path, { ...elements, [rule.element]: `${of}[]` })})`;
283
+ }
284
+ case "and":
285
+ case "or":
286
+ return `${rule.kind}(${rule.rules.map(part => describeRule(part, path, elements)).join(", ")})`;
287
+ case "not":
288
+ return `not(${describeRule(rule.rule, path, elements)})`;
289
+ case "compare":
290
+ break;
291
+ }
292
+ return `${describeOperand(rule.left, path, elements)} ${rule.operator} ${describeOperand(rule.right, path, elements)}`;
293
+ }
294
+ const mirrored = {
295
+ "<": ">",
296
+ "<=": ">=",
297
+ ">": "<",
298
+ ">=": "<=",
299
+ "==": "==",
300
+ "!=": "!=",
301
+ };
302
+ // A Decimal from decimal.js, read by its methods rather than by instanceof, so a
303
+ // specification using another copy of the library is read the same.
304
+ export function isDecimal(value) {
305
+ return (typeof value === "object" &&
306
+ value !== null &&
307
+ typeof value.comparedTo === "function" &&
308
+ typeof value.toFixed === "function" &&
309
+ typeof value.decimalPlaces === "function");
310
+ }
311
+ // A decimal of `scale` digits after the point, as a whole number of units of its
312
+ // last digit: exact, and free of the precision a Decimal's arithmetic rounds to.
313
+ // A value off that grid is rounded down or up, as `rounding` says.
314
+ export function decimalUnits(value, scale, rounding) {
315
+ const mode = rounding === "floor" ? 3 : 2; // decimal.js ROUND_FLOOR and ROUND_CEIL
316
+ const text = value.toFixed(scale, mode);
317
+ return BigInt(text.replace(".", ""));
318
+ }
319
+ // The Decimal a whole number of units stands for, built with the constructor of
320
+ // `like`, so the value comes back as the kind the specification uses.
321
+ export function decimalOfUnits(like, units, scale) {
322
+ const negative = units < 0n;
323
+ const digits = (negative ? -units : units).toString().padStart(scale + 1, "0");
324
+ const text = scale === 0 ? digits : `${digits.slice(0, -scale)}.${digits.slice(-scale)}`;
325
+ const Constructor = like.constructor;
326
+ return new Constructor(negative ? `-${text}` : text);
327
+ }
328
+ // Steps a decimal to the next value of `scale` digits strictly past it, so a bound
329
+ // written off that grid, such as 0.004 in cents, steps to 0.01 above and 0 below.
330
+ export function decimalStep(scale) {
331
+ return (bound, direction) => {
332
+ const value = bound;
333
+ const units = direction > 0 ? decimalUnits(value, scale, "floor") + 1n : decimalUnits(value, scale, "ceil") - 1n;
334
+ return decimalOfUnits(value, units, scale);
335
+ };
336
+ }
337
+ function step(bound, direction) {
338
+ if (typeof bound === "number") {
339
+ return bound + direction;
340
+ }
341
+ const add = bound?.add;
342
+ if (typeof add === "function") {
343
+ const moved = add.call(bound, isPlainDate(bound) ? { days: direction } : { nanoseconds: direction });
344
+ // A plain time wraps past midnight, landing on the far side of the bound; no
345
+ // time of day lies past either end, so the bound is kept rather than wrapped.
346
+ return Math.sign(ordering(moved, bound)) === direction ? moved : bound;
347
+ }
348
+ return bound;
349
+ }
350
+ function writeAt(value, path, change) {
351
+ const [key, ...rest] = path;
352
+ if (key === undefined) {
353
+ return change(value);
354
+ }
355
+ const record = value;
356
+ return { ...record, [key]: writeAt(record[key], rest, change) };
357
+ }
358
+ export function sizeOf(value) {
359
+ return typeof value === "string" ? [...value.normalize("NFC")].length : Array.isArray(value)
360
+ ? value.length
361
+ : Object.keys(value).length;
362
+ }
363
+ export function resize(current, size, empty) {
364
+ if (typeof current === "string") {
365
+ const points = [...current.normalize("NFC")];
366
+ return points.length >= size ? points.slice(0, size).join("") : current.normalize("NFC") + "_".repeat(size - points.length);
367
+ }
368
+ if (Array.isArray(current)) {
369
+ const filler = current.length > 0 ? current[current.length - 1] : empty?.();
370
+ return Array.from({ length: Math.max(size, 0) }, (_, index) => current[index] ?? filler);
371
+ }
372
+ if (typeof current === "object" && current !== null) {
373
+ const entries = Object.entries(current);
374
+ const filler = entries.length > 0 ? entries[entries.length - 1][1] : empty?.();
375
+ return Object.fromEntries(Array.from({ length: Math.max(size, 0) }, (_, index) => entries[index] ?? [`<key${index + 1}>`, filler]));
376
+ }
377
+ return current;
378
+ }
379
+ // Whether a measure counts (a length), rather than reading a value.
380
+ export function counts(measure) {
381
+ return partsOfMeasure(measure).reading === "length";
382
+ }
383
+ const TRANSFORMS = {
384
+ trim: text => text.trim(),
385
+ lowercase: text => text.toLowerCase(),
386
+ uppercase: text => text.toUpperCase(),
387
+ };
388
+ export function transformed(value, transforms) {
389
+ if (typeof value !== "string") {
390
+ return value;
391
+ }
392
+ return transforms.reduce((text, transform) => TRANSFORMS[transform](text), value);
393
+ }
394
+ // Whether the transforms leave a string as it reads, compared as text is: "İ"
395
+ // lowercases to "i̇" and uppercases back to "I" with a combining dot, which
396
+ // reads as "İ" though it is not the same code points.
397
+ export function leftAsItReads(value, transforms) {
398
+ return typeof value === "string" && compareText(transformed(value, transforms), value) === 0;
399
+ }
400
+ // A location as `measure` reads it: `length(lowercase(trim($.x)))`.
401
+ export function measureLabel(location, measure) {
402
+ const { transforms, reading } = partsOfMeasure(measure);
403
+ const read = transforms.reduce((inner, transform) => `${transform}(${inner})`, location);
404
+ return reading === "length" ? `length(${read})` : read;
405
+ }
406
+ // What `measure` reads of a value found at a term's path.
407
+ export function measured(value, measure) {
408
+ const { transforms, reading } = partsOfMeasure(measure);
409
+ const read = transformed(value, transforms);
410
+ return reading === "length" ? sizeOf(read) : read;
411
+ }
412
+ // A value whose `measure` reads `target`, written on the current value. Each
413
+ // transform gives back a string it then leaves as it is, so a target the
414
+ // transforms leave alone is written as it is, and one they change is not
415
+ // written at all, since no value reads back as it. A length is written by
416
+ // resizing the transformed value, or by a string of `_` where resizing leaves
417
+ // whitespace at an end that `trim` would take off.
418
+ export function rewrite(current, measure, target, empty) {
419
+ const { transforms, reading } = partsOfMeasure(measure);
420
+ if (reading === "value") {
421
+ return transforms.length === 0 || leftAsItReads(target, transforms) ? target : current;
422
+ }
423
+ if (transforms.length === 0 || typeof current !== "string") {
424
+ return resize(current, target, empty);
425
+ }
426
+ const resized = resize(transformed(current, transforms), target);
427
+ return measured(resized, measure) === target ? resized : resize("", target);
428
+ }
429
+ function compare(operator, left, right) {
430
+ return condition({ kind: "compare", operator, left, right });
431
+ }
432
+ const OPERATORS = {
433
+ lt: "<",
434
+ lte: "<=",
435
+ gt: ">",
436
+ gte: ">=",
437
+ eq: "==",
438
+ ne: "!=",
439
+ };
440
+ function termAt(path, measure) {
441
+ const data = { kind: "position", path, measure };
442
+ const self = new Proxy({}, {
443
+ get: (_target, key) => {
444
+ if (key === TERM) {
445
+ return data;
446
+ }
447
+ if (typeof key !== "string") {
448
+ return undefined;
449
+ }
450
+ if (!key.startsWith("$")) {
451
+ return termAt([...path, key], "value");
452
+ }
453
+ const name = key.slice(1);
454
+ const operator = Object.hasOwn(OPERATORS, name) ? OPERATORS[name] : undefined;
455
+ if (operator !== undefined) {
456
+ return (other) => compare(operator, self, other);
457
+ }
458
+ switch (name) {
459
+ case "plus":
460
+ return (other) => linearTerm(combined(data, other, 1));
461
+ case "minus":
462
+ return (other) => linearTerm(combined(data, other, -1));
463
+ case "length":
464
+ return () => termAt(path, measureOf(partsOfMeasure(measure).transforms, "length"));
465
+ case "trim":
466
+ case "lowercase":
467
+ case "uppercase":
468
+ return () => termAt(path, measureOf([...partsOfMeasure(measure).transforms, name], "value"));
469
+ case "all":
470
+ case "any":
471
+ return (each) => quantified(name, self, each);
472
+ default:
473
+ return termAt([...path, key], "value");
474
+ }
475
+ },
476
+ has: (_target, key) => key === TERM,
477
+ });
478
+ return self;
479
+ }
480
+ export function positionTerm(path, measure) {
481
+ return termAt(path, measure);
482
+ }
483
+ // The expression a comparison draws its line on: its left side less its right.
484
+ export function differenceOf(rule) {
485
+ const left = linearOf(rule.left);
486
+ const right = linearOf(rule.right);
487
+ return combined(left, linearTerm(right), -1);
488
+ }
489
+ export function positionData(term) {
490
+ const data = termData(term);
491
+ return data.kind === "position" ? data : undefined;
492
+ }
493
+ // Where only one position can stand, such as what a match selects or what $all
494
+ // ranges over, an expression is refused rather than read as some position.
495
+ export function positionOf(term) {
496
+ const data = positionData(term);
497
+ if (data === undefined) {
498
+ throw new Error(`${describeTerm(term)} is an expression of positions, not one position`);
499
+ }
500
+ return data;
501
+ }
502
+ function pathsOf(data) {
503
+ return data.kind === "position" ? [data.path] : data.parts.map(part => part.path);
504
+ }
505
+ function shiftedTerm(data) {
506
+ return data.kind === "position"
507
+ ? termAt(data.path.slice(1), data.measure)
508
+ : linearTerm({ ...data, parts: data.parts.map(part => ({ ...part, path: part.path.slice(1) })) });
509
+ }
510
+ function linearOf(operand) {
511
+ if (!isTerm(operand)) {
512
+ return { kind: "linear", parts: [], constant: operand };
513
+ }
514
+ const data = termData(operand);
515
+ return data.kind === "linear"
516
+ ? data
517
+ : { kind: "linear", parts: [{ path: data.path, measure: data.measure, coefficient: 1 }], constant: 0 };
518
+ }
519
+ function combined(data, other, sign) {
520
+ const base = data.kind === "linear"
521
+ ? data
522
+ : { kind: "linear", parts: [{ path: data.path, measure: data.measure, coefficient: 1 }], constant: 0 };
523
+ const right = linearOf(other);
524
+ const parts = [...base.parts];
525
+ for (const part of right.parts) {
526
+ const index = parts.findIndex(existing => existing.measure === part.measure && deepEqual(existing.path, part.path));
527
+ const coefficient = sign * part.coefficient;
528
+ if (index === -1) {
529
+ parts.push({ ...part, coefficient });
530
+ }
531
+ else {
532
+ parts[index] = { ...parts[index], coefficient: parts[index].coefficient + coefficient };
533
+ }
534
+ }
535
+ if (parts.some(part => !Number.isSafeInteger(part.coefficient)))
536
+ throw new Error("Linear coefficient exceeds the exact integer range; use Rational expressions");
537
+ return {
538
+ kind: "linear",
539
+ parts: parts.filter(part => part.coefficient !== 0),
540
+ constant: sum(base.constant, scaled(right.constant, sign)),
541
+ };
542
+ }
543
+ function linearTerm(data) {
544
+ const self = new Proxy({}, {
545
+ get: (_target, key) => {
546
+ if (key === TERM) {
547
+ return data;
548
+ }
549
+ if (typeof key !== "string" || !key.startsWith("$")) {
550
+ return undefined;
551
+ }
552
+ const name = key.slice(1);
553
+ const operator = Object.hasOwn(OPERATORS, name) ? OPERATORS[name] : undefined;
554
+ if (operator !== undefined) {
555
+ return (other) => compare(operator, self, other);
556
+ }
557
+ if (name === "plus") {
558
+ return (other) => linearTerm(combined(data, other, 1));
559
+ }
560
+ if (name === "minus") {
561
+ return (other) => linearTerm(combined(data, other, -1));
562
+ }
563
+ return undefined;
564
+ },
565
+ has: (_target, key) => key === TERM,
566
+ });
567
+ return self;
568
+ }
569
+ function readLinear(data, value) {
570
+ let total = fractionOf(data.constant);
571
+ let decimal = isDecimal(data.constant);
572
+ for (const part of data.parts) {
573
+ const found = read(termAt(part.path, part.measure), value);
574
+ if (found === undefined)
575
+ return undefined;
576
+ decimal ||= isDecimal(found);
577
+ total = total.plus(fractionOf(found).times(fractionOf(part.coefficient)));
578
+ }
579
+ if (decimal)
580
+ return decimalOf(total);
581
+ if (total.denominator === 1n && (total.numerator < BigInt(Number.MIN_SAFE_INTEGER) || total.numerator > BigInt(Number.MAX_SAFE_INTEGER))) {
582
+ throw new Error("Exact integer arithmetic exceeds the safe range; use int64 or Rational expressions");
583
+ }
584
+ return decimalOf(total).toNumber();
585
+ }
586
+ function scaled(value, coefficient) {
587
+ return isDecimal(value) ? decimalOf(fractionOf(value).times(fractionOf(coefficient))) : value * coefficient;
588
+ }
589
+ function sum(left, right) {
590
+ if (isDecimal(left)) {
591
+ return decimalOf(fractionOf(left).plus(fractionOf(right)));
592
+ }
593
+ if (isDecimal(right)) {
594
+ return decimalOf(fractionOf(right).plus(fractionOf(left)));
595
+ }
596
+ return left + right;
597
+ }
598
+ function describeLinear(data, describePart) {
599
+ const pieces = data.parts.map((part, index) => {
600
+ const size = Math.abs(part.coefficient);
601
+ const sign = part.coefficient < 0 ? "-" : "+";
602
+ const body = size === 1 ? describePart(part) : `${size} * ${describePart(part)}`;
603
+ return index === 0 ? (sign === "-" ? `-${body}` : body) : `${sign} ${body}`;
604
+ });
605
+ const constant = data.constant;
606
+ const zero = isDecimal(constant) ? constant.isZero() : constant === 0;
607
+ if (!zero) {
608
+ const negative = isDecimal(constant) ? constant.isNegative() : constant < 0;
609
+ const size = isDecimal(constant) ? constant.abs().toString() : String(Math.abs(constant));
610
+ pieces.push(pieces.length === 0 ? String(constant) : `${negative ? "-" : "+"} ${size}`);
611
+ }
612
+ return pieces.length === 0 ? "0" : pieces.join(" ");
613
+ }
614
+ export function readOperand(operand, value) {
615
+ return read(operand, value);
616
+ }
617
+ function read(operand, value) {
618
+ if (!isTerm(operand)) {
619
+ return operand;
620
+ }
621
+ const data = termData(operand);
622
+ if (data.kind === "linear") {
623
+ return readLinear(data, value);
624
+ }
625
+ const { path, measure } = data;
626
+ if (path.length === 0 && typeof value === "object" && value !== null && INPUT in value)
627
+ value = value[INPUT];
628
+ const found = path.reduce((current, key) => typeof current === "object" && current !== null
629
+ ? current[key]
630
+ : undefined, value);
631
+ return found === undefined ? found : measured(found, measure);
632
+ }
633
+ function ordering(left, right) {
634
+ if (typeof left === "bigint" && typeof right === "bigint")
635
+ return left < right ? -1 : left > right ? 1 : 0;
636
+ if (isRational(left) && isRational(right))
637
+ return left.comparedTo(right);
638
+ if (typeof left === "number" && typeof right === "number") {
639
+ return left - right;
640
+ }
641
+ if (typeof left === "string" && typeof right === "string") {
642
+ return compareText(left, right);
643
+ }
644
+ if (typeof left === "boolean" && typeof right === "boolean") {
645
+ return left === right ? 0 : Number.NaN;
646
+ }
647
+ // A Decimal compares exactly, by its own comparedTo.
648
+ if (isDecimal(left)) {
649
+ return left.comparedTo(right);
650
+ }
651
+ if (isDecimal(right)) {
652
+ return -right.comparedTo(left);
653
+ }
654
+ const compareInstants = left?.constructor?.compare;
655
+ if (typeof compareInstants === "function") {
656
+ return compareInstants(left, right);
657
+ }
658
+ return Number.NaN;
659
+ }
660
+ // A local bound to a dependency's answer reads as the call, any other by its number.
661
+ export function localLabel(name) {
662
+ const rest = name.slice("#local:".length);
663
+ if (rest.startsWith("call:"))
664
+ return `${rest.slice("call:".length, rest.lastIndexOf(":"))}()`;
665
+ const at = rest.indexOf("@");
666
+ return at === -1 ? `local${rest}` : rest.slice(at + 1);
667
+ }
668
+ export function describeTerm(term, path = "$", elements = {}) {
669
+ return describeOperand(term, path, elements);
670
+ }
671
+ function describeOperand(operand, path, elements = {}) {
672
+ if (!isTerm(operand)) {
673
+ return typeof operand === "string" ? JSON.stringify(operand) : String(operand);
674
+ }
675
+ const data = termData(operand);
676
+ if (data.kind === "linear") {
677
+ return describeLinear(data, part => describeOperand(termAt(part.path, part.measure), path, elements));
678
+ }
679
+ const { path: keys, measure } = data;
680
+ const [first = "", ...rest] = keys;
681
+ const location = (first === DEPS
682
+ ? ["deps", ...rest]
683
+ : first.startsWith("#local:")
684
+ ? [localLabel(first), ...rest]
685
+ : elements[first] !== undefined
686
+ ? [elements[first], ...rest]
687
+ : [path, ...keys])
688
+ .filter(part => part !== "")
689
+ .join(".");
690
+ const { transforms, reading } = partsOfMeasure(measure);
691
+ const read = transforms.reduce((inner, transform) => `${transform}(${inner})`, location);
692
+ return reading === "length" ? `length(${read})` : read;
693
+ }
694
+ // A plain date has no time of day, so adding a nanosecond leaves it where it is.
695
+ function isPlainDate(value) {
696
+ const constructor = globalThis
697
+ .Temporal?.PlainDate;
698
+ return constructor !== undefined && value instanceof constructor;
699
+ }
700
+ export function rebaseTerm(term, move) {
701
+ const data = termData(term);
702
+ return data.kind === "position"
703
+ ? termAt(move(data.path), data.measure)
704
+ : linearTerm({ ...data, parts: data.parts.map(part => ({ ...part, path: move(part.path) })) });
705
+ }
706
+ // The rule with every term moved by `move`, which takes a path and answers the
707
+ // path to read instead; constants, operators, names and element roots are kept.
708
+ export function rebaseRule(rule, move) {
709
+ const term = (value) => (isTerm(value) ? rebaseTerm(value, move) : value);
710
+ const named = (rebased) => (rule.name === undefined ? rebased : { ...rebased, name: rule.name });
711
+ switch (rule.kind) {
712
+ case "compare":
713
+ return named({ kind: "compare", operator: rule.operator, left: term(rule.left), right: term(rule.right) });
714
+ case "all":
715
+ case "any":
716
+ return named({ ...rule, of: term(rule.of), each: rebaseRule(rule.each, path => (path[0] === rule.element ? path : move(path))) });
717
+ case "and":
718
+ case "or":
719
+ return named({ kind: rule.kind, rules: rule.rules.map(part => rebaseRule(part, move)) });
720
+ case "not":
721
+ return named({ kind: "not", rule: rebaseRule(rule.rule, move) });
722
+ }
723
+ }
724
+ // A sum of operands weighed by whole numbers: a term where any operand is one,
725
+ // otherwise the constant it adds up to. Undefined where a term is not a value
726
+ // of a position or an expression of them.
727
+ function foldsExactly(items, folded) {
728
+ try {
729
+ const exact = items.reduce((total, { operand, coefficient }) => total.plus(fractionOf(linearOf(operand).constant).times(fractionOf(coefficient))), fractionOf(0));
730
+ return fractionOf(folded).comparedTo(exact) === 0;
731
+ }
732
+ catch {
733
+ return false;
734
+ }
735
+ }
736
+ export function linearCombination(items) {
737
+ let parts = [];
738
+ let constant = 0;
739
+ for (const { operand, coefficient } of items) {
740
+ const data = linearOf(operand);
741
+ for (const part of data.parts) {
742
+ const index = parts.findIndex(existing => existing.measure === part.measure && deepEqual(existing.path, part.path));
743
+ const weight = part.coefficient * coefficient;
744
+ const total = index === -1 ? weight : parts[index].coefficient + weight;
745
+ // A weight or a running total that rounds could cancel to a value the exact sum does not have.
746
+ if (!Number.isSafeInteger(weight) || !Number.isSafeInteger(total))
747
+ return undefined;
748
+ if (index === -1)
749
+ parts.push({ ...part, coefficient: total });
750
+ else
751
+ parts[index] = { ...parts[index], coefficient: total };
752
+ }
753
+ constant = sum(constant, scaled(data.constant, coefficient));
754
+ }
755
+ parts = parts.filter(part => part.coefficient !== 0);
756
+ // A constant is read exactly, as a term reads it: a fold that rounds is not read.
757
+ if (typeof constant === "number" && (!Number.isFinite(constant) || (Number.isInteger(constant) && !Number.isSafeInteger(constant)) || !foldsExactly(items, constant)))
758
+ return undefined;
759
+ // What decimals add to stays a decimal where their parts cancel.
760
+ if (typeof constant === "number" && items.some(({ operand }) => isDecimal(operand) || (isTerm(operand) && isDecimal(linearOf(operand).constant))))
761
+ constant = decimalOf(fractionOf(constant));
762
+ if (parts.length === 0)
763
+ return constant;
764
+ if (parts.length === 1 && parts[0].coefficient === 1 && constant === 0)
765
+ return termAt(parts[0].path, parts[0].measure);
766
+ return linearTerm({ kind: "linear", parts, constant: constant });
767
+ }
768
+ export function substitutedOperand(value, replace) {
769
+ {
770
+ if (!isTerm(value))
771
+ return { with: value };
772
+ const data = termData(value);
773
+ if (data.kind === "position") {
774
+ const found = replace(data.path);
775
+ if (found === undefined)
776
+ return { with: value };
777
+ if (data.measure === "value")
778
+ return found;
779
+ if (found.over !== undefined)
780
+ return undefined;
781
+ if (isTerm(found.with)) {
782
+ const inner = termData(found.with);
783
+ return inner.kind === "position" && inner.measure === "value" ? { with: termAt(inner.path, data.measure) } : undefined;
784
+ }
785
+ return { with: measured(found.with, data.measure) };
786
+ }
787
+ const items = [{ operand: data.constant, coefficient: 1 }];
788
+ for (const part of data.parts) {
789
+ const found = part.measure === "value" ? replace(part.path) : undefined;
790
+ if (found === undefined && part.measure !== "value" && replace(part.path) !== undefined)
791
+ return undefined;
792
+ if (found?.over !== undefined)
793
+ return undefined;
794
+ items.push({ operand: found === undefined ? termAt(part.path, part.measure) : found.with, coefficient: part.coefficient });
795
+ }
796
+ const combined = linearCombination(items);
797
+ return combined === undefined ? undefined : { with: combined };
798
+ }
799
+ }
800
+ export function substitutedRule(rule, replace) {
801
+ const operand = (value) => substitutedOperand(value, replace);
802
+ const named = (made) => (rule.name === undefined ? made : { ...made, name: rule.name });
803
+ switch (rule.kind) {
804
+ case "compare": {
805
+ const left = operand(rule.left), right = operand(rule.right);
806
+ if (left === undefined || right === undefined)
807
+ return undefined;
808
+ if (left.over === undefined && right.over === undefined)
809
+ return named({ kind: "compare", operator: rule.operator, left: left.with, right: right.with });
810
+ if (left.over !== undefined && right.over !== undefined)
811
+ return undefined;
812
+ // x / k op y is x op y * k, the order turned where k is negative. A
813
+ // quotient is a rational, which compares as written only with a rational.
814
+ const divisor = (left.over ?? right.over);
815
+ if (!isRational(left.over === undefined ? left.with : right.with))
816
+ return undefined;
817
+ const multiplied = scaledBy(left.over === undefined ? left.with : right.with, divisor);
818
+ if (multiplied === undefined)
819
+ return undefined;
820
+ const operator = divisor < 0 ? mirrored[rule.operator] : rule.operator;
821
+ return left.over !== undefined
822
+ ? named({ kind: "compare", operator, left: left.with, right: multiplied })
823
+ : named({ kind: "compare", operator, left: multiplied, right: right.with });
824
+ }
825
+ case "all":
826
+ case "any": {
827
+ const of = operand(rule.of);
828
+ const each = substitutedRule(rule.each, replace);
829
+ return of === undefined || !isTerm(of.with) || each === undefined ? undefined : named({ ...rule, of: of.with, each });
830
+ }
831
+ case "and":
832
+ case "or": {
833
+ const rules = rule.rules.map(part => substitutedRule(part, replace));
834
+ return rules.some(part => part === undefined) ? undefined : named({ kind: rule.kind, rules: rules });
835
+ }
836
+ case "not": {
837
+ const inner = substitutedRule(rule.rule, replace);
838
+ return inner === undefined ? undefined : named({ kind: "not", rule: inner });
839
+ }
840
+ }
841
+ }
842
+ // A value multiplied by a whole number, a term or a number, decimal or rational
843
+ // constant; undefined where a rational does not come out whole.
844
+ function scaledBy(value, factor) {
845
+ if (isRational(value)) {
846
+ const product = value.times(new Rational(BigInt(factor)));
847
+ return product.denominator === 1n && product.numerator <= BigInt(Number.MAX_SAFE_INTEGER) && product.numerator >= BigInt(Number.MIN_SAFE_INTEGER)
848
+ ? Number(product.numerator) : undefined;
849
+ }
850
+ return linearCombination([{ operand: value, coefficient: factor }]);
851
+ }
852
+ export function normalize(rule) {
853
+ if (rule.kind !== "compare") {
854
+ return undefined;
855
+ }
856
+ const left = isTerm(rule.left) ? positionData(rule.left) : undefined;
857
+ const right = isTerm(rule.right) ? positionData(rule.right) : undefined;
858
+ if (left !== undefined && !isTerm(rule.right)) {
859
+ return { operator: rule.operator, bound: rule.right, measure: left.measure };
860
+ }
861
+ if (right !== undefined && !isTerm(rule.left)) {
862
+ return { operator: mirrored[rule.operator], bound: rule.left, measure: right.measure };
863
+ }
864
+ return undefined;
865
+ }
866
+ //# sourceMappingURL=rule.js.map