@toiroakr/chisel 0.0.0-stage → 0.1.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 (84) hide show
  1. package/README.md +464 -2
  2. package/dist/behavior.d.ts +181 -0
  3. package/dist/behavior.js +422 -0
  4. package/dist/behavior.js.map +1 -0
  5. package/dist/beside.d.ts +27 -0
  6. package/dist/beside.js +88 -0
  7. package/dist/beside.js.map +1 -0
  8. package/dist/border.d.ts +64 -0
  9. package/dist/border.js +426 -0
  10. package/dist/border.js.map +1 -0
  11. package/dist/cli.d.ts +5 -0
  12. package/dist/cli.js +567 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/codec.d.ts +6 -0
  15. package/dist/codec.js +83 -0
  16. package/dist/codec.js.map +1 -0
  17. package/dist/codegen.d.ts +2 -0
  18. package/dist/codegen.js +65 -0
  19. package/dist/codegen.js.map +1 -0
  20. package/dist/composition.d.ts +38 -0
  21. package/dist/composition.js +242 -0
  22. package/dist/composition.js.map +1 -0
  23. package/dist/data.d.ts +16 -0
  24. package/dist/data.js +49 -0
  25. package/dist/data.js.map +1 -0
  26. package/dist/dependency.d.ts +98 -0
  27. package/dist/dependency.js +155 -0
  28. package/dist/dependency.js.map +1 -0
  29. package/dist/domain.d.ts +8 -0
  30. package/dist/domain.js +217 -0
  31. package/dist/domain.js.map +1 -0
  32. package/dist/ensures.d.ts +15 -0
  33. package/dist/ensures.js +88 -0
  34. package/dist/ensures.js.map +1 -0
  35. package/dist/exact.d.ts +21 -0
  36. package/dist/exact.js +80 -0
  37. package/dist/exact.js.map +1 -0
  38. package/dist/feasibility.d.ts +61 -0
  39. package/dist/feasibility.js +984 -0
  40. package/dist/feasibility.js.map +1 -0
  41. package/dist/guard-borders.d.ts +50 -0
  42. package/dist/guard-borders.js +809 -0
  43. package/dist/guard-borders.js.map +1 -0
  44. package/dist/index.d.ts +37 -0
  45. package/dist/index.js +19 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/interval.d.ts +3 -0
  48. package/dist/interval.js +161 -0
  49. package/dist/interval.js.map +1 -0
  50. package/dist/isolated.d.ts +9 -0
  51. package/dist/isolated.js +41 -0
  52. package/dist/isolated.js.map +1 -0
  53. package/dist/model.d.ts +95 -0
  54. package/dist/model.js +343 -0
  55. package/dist/model.js.map +1 -0
  56. package/dist/pairs.d.ts +26 -0
  57. package/dist/pairs.js +107 -0
  58. package/dist/pairs.js.map +1 -0
  59. package/dist/partition.d.ts +44 -0
  60. package/dist/partition.js +275 -0
  61. package/dist/partition.js.map +1 -0
  62. package/dist/proof.d.ts +15 -0
  63. package/dist/proof.js +482 -0
  64. package/dist/proof.js.map +1 -0
  65. package/dist/report-json.d.ts +11 -0
  66. package/dist/report-json.js +94 -0
  67. package/dist/report-json.js.map +1 -0
  68. package/dist/rule.d.ts +146 -0
  69. package/dist/rule.js +599 -0
  70. package/dist/rule.js.map +1 -0
  71. package/dist/schema.d.ts +163 -0
  72. package/dist/schema.js +524 -0
  73. package/dist/schema.js.map +1 -0
  74. package/dist/specification.d.ts +256 -0
  75. package/dist/specification.js +1583 -0
  76. package/dist/specification.js.map +1 -0
  77. package/dist/text.d.ts +1 -0
  78. package/dist/text.js +11 -0
  79. package/dist/text.js.map +1 -0
  80. package/dist/ways.d.ts +25 -0
  81. package/dist/ways.js +95 -0
  82. package/dist/ways.js.map +1 -0
  83. package/package.json +53 -4
  84. package/schema/report.schema.json +1062 -0
@@ -0,0 +1,809 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { bordersOf, decimalUnitsCarrier, integerCarrier, nanosecondCarrier, normalize, numberCarrier, } from "./border.js";
3
+ import { carrierOf, positionsOf } from "./partition.js";
4
+ import { DEPS, boundTermPath, conjuncts, describeRule, holds, isDecimal, isTerm, readOperand, selfTerm, shiftTerms, sizeOf, stepInto, termData, termPaths, positionData, positionOf, positionTerm, differenceOf, withDeps, decimalOfUnits, decimalUnits, } from "./rule.js";
5
+ import { enumOf, holdsNoDecimal, int, isVariantsSchema, object, offGridEquality, schemaAtPath } from "./schema.js";
6
+ export function guardScope(definition, tag) {
7
+ const variant = definition.input.variants[tag];
8
+ const values = Object.entries(definition.requires).flatMap(([name, declared]) => declared.takes === "nothing" ? [[name, declared.output]] : []);
9
+ if (values.length === 0) {
10
+ return variant;
11
+ }
12
+ const deps = { ...object(Object.fromEntries(values)) };
13
+ return { ...variant, shape: { ...variant.shape, [DEPS]: deps } };
14
+ }
15
+ // The case as feasibility reads it: the invariants written on the input sum
16
+ // hold of every case, as the partition passes them down, and read the
17
+ // discriminant as the one value it has under this case.
18
+ export function feasibilityScope(definition, tag) {
19
+ const scope = guardScope(definition, tag);
20
+ const { discriminant } = definition.input;
21
+ return {
22
+ ...scope,
23
+ shape: Object.hasOwn(scope.shape, discriminant)
24
+ ? scope.shape
25
+ : { ...scope.shape, [discriminant]: enumOf([tag]) },
26
+ invariants: [...scope.invariants, ...definition.input.invariants],
27
+ };
28
+ }
29
+ export function guardBordersOf(implementation) {
30
+ const input = implementation.behavior.input;
31
+ const positions = positionsOf(input, { containers: true });
32
+ const at = (segments) => positions.find(position => isDeepStrictEqual(position.segments, segments));
33
+ return Object.entries(implementation.cases).flatMap(([tag, decision]) => decision.kind !== "rules"
34
+ ? []
35
+ : decision.guards.flatMap(candidate => walk(candidate.condition, framesAt(guardScope(implementation.behavior, tag), `@${tag}`, "$"), at, asGuard).map(drawn => ({
36
+ ...drawn,
37
+ origin: { decision, scope: feasibilityScope(implementation.behavior, tag), tag },
38
+ }))));
39
+ }
40
+ export function ensuresBordersOf(definition) {
41
+ const input = definition.input;
42
+ const positions = positionsOf(input);
43
+ const at = (segments) => positions.find(position => isDeepStrictEqual(position.segments, segments));
44
+ return definition.ensures.flatMap(clause => conjuncts(clause.rule).flatMap(part => {
45
+ const onInput = unrooted(part);
46
+ if (onInput === undefined) {
47
+ return [];
48
+ }
49
+ return input.variantTags.flatMap(tag => walk(onInput, framesAt(input.variants[tag], `@${tag}`, "$"), at, {
50
+ source: "ensures",
51
+ describe: () => `${clause.name}: ${describeRule(part, "")}`,
52
+ }));
53
+ }));
54
+ }
55
+ // An invariant comparing one position with a constant draws its border on that
56
+ // position (src/border.ts); this one draws those comparing two positions, which
57
+ // no single position carries.
58
+ export function invariantPairBordersOf(definition) {
59
+ const positions = positionsOf(definition.input, { containers: true });
60
+ const at = (segments) => positions.find(position => isDeepStrictEqual(position.segments, segments));
61
+ const reading = {
62
+ source: "invariant",
63
+ describe: (compared, read) => describeRule(compared, read.root.label, labelsOf(read)),
64
+ };
65
+ const invariants = pairInvariantsOf(definition);
66
+ return definition.input.variantTags.flatMap(tag => {
67
+ const drawn = invariants.filter(invariant => invariant.tag === tag).flatMap(({ frame, rule }) => {
68
+ const frames = { root: frame, elements: {} };
69
+ if (settledAlone(rule) !== undefined) {
70
+ return [];
71
+ }
72
+ const borders = [rule.left, rule.right].some(operand => isTerm(operand) && positionData(operand) === undefined)
73
+ ? betweenExpression(rule, frames, at, reading)
74
+ : isTerm(rule.left) && isTerm(rule.right)
75
+ ? between(rule, rule.left, rule.right, frames, at, reading)
76
+ : [];
77
+ const keys = frame.segments.slice(1).map(segment => segment.slice(1));
78
+ return borders.map(border => ({
79
+ ...border,
80
+ coordinateOf: (reached) => border.coordinateOf({
81
+ ...reached,
82
+ scope: keys.reduce((value, key) => value?.[key], reached.scope),
83
+ }),
84
+ }));
85
+ });
86
+ return drawn.map(border => withoutPairRefusedPoints(border, drawn));
87
+ });
88
+ }
89
+ // An input invariant whose sides cancel, such as $.x < $.x, holds of no value,
90
+ // unless a field it reads may be left out: a comparison with it absent holds.
91
+ export function invariantContradictionsOf(definition) {
92
+ return pairInvariantsOf(definition).flatMap(({ frame, rule }) => settledAlone(rule) === false &&
93
+ !readPathsOf(rule).some(path => mayBeLeftOut(definition, [...frame.segments, ...path.map(key => `.${key}`)]))
94
+ ? [
95
+ `${frame.path}: 不変条件を満たす値がありません (invariant ${rule.name === undefined ? "" : `${rule.name}: `}${describeRule(rule, frame.label)})`,
96
+ ]
97
+ : []);
98
+ }
99
+ function readPathsOf(rule) {
100
+ return [rule.left, rule.right].flatMap(operand => {
101
+ if (!isTerm(operand)) {
102
+ return [];
103
+ }
104
+ const data = termData(operand);
105
+ return data.kind === "position" ? [data.path] : data.parts.map(part => part.path);
106
+ });
107
+ }
108
+ // Whether a position an object invariant reads, named by segments such as
109
+ // ["@case", ".key"], is or lies under a field that may be left out.
110
+ export function mayBeLeftOut(definition, segments) {
111
+ const [caseSegment, ...keys] = segments;
112
+ return leavesOut(definition.input.variants[caseSegment.slice(1)], keys);
113
+ }
114
+ // A sum field leaves a path out when any of its cases does: the path names a
115
+ // field its cases share, and a value may be of the case that omits it.
116
+ function leavesOut(schema, keys) {
117
+ if (schema === undefined) {
118
+ return false;
119
+ }
120
+ if (schema.kind === "optional") {
121
+ return true;
122
+ }
123
+ if (isVariantsSchema(schema)) {
124
+ const [key, ...rest] = keys;
125
+ return key?.startsWith("@") === true
126
+ ? leavesOut(schema.variants[key.slice(1)], rest)
127
+ : schema.variantTags.some(tag => leavesOut(schema.variants[tag], keys));
128
+ }
129
+ const [key, ...rest] = keys;
130
+ if (key === undefined || schema.kind !== "object" || !key.startsWith(".")) {
131
+ return false;
132
+ }
133
+ return leavesOut(schema.shape[key.slice(1)], rest);
134
+ }
135
+ function pairInvariantsOf(definition) {
136
+ const input = definition.input;
137
+ return input.variantTags.flatMap(tag => {
138
+ const scope = input.variants[tag];
139
+ return objectFramesIn({ scope, path: `@${tag}`, segments: [`@${tag}`], label: "$" }).flatMap(frame => [...(frame.scope === scope ? input.invariants : []), ...frame.scope.invariants]
140
+ .flatMap(conjuncts)
141
+ .flatMap(rule => (rule.kind === "compare" ? [{ tag, frame, rule }] : [])));
142
+ });
143
+ }
144
+ // Whether a comparison of numbers holds whatever the positions hold, when its
145
+ // positions cancel; undefined while one is left to draw a border on.
146
+ function comparesTwoPositions(drawn) {
147
+ return [drawn.comparison.left, drawn.comparison.right].every(operand => isTerm(operand) && positionData(operand) !== undefined);
148
+ }
149
+ function settledAlone(rule) {
150
+ if (![rule.left, rule.right].every(operand => isTerm(operand) || typeof operand === "number" || isDecimal(operand))) {
151
+ return undefined;
152
+ }
153
+ const form = differenceOf(rule);
154
+ if (form.parts.length > 0) {
155
+ return undefined;
156
+ }
157
+ // Compared by its sign, so a decimal constant is read as a number is.
158
+ const sign = typeof form.constant === "number" ? Math.sign(form.constant) : form.constant.comparedTo(0);
159
+ return holds({ kind: "compare", left: sign, operator: rule.operator, right: 0 }, undefined);
160
+ }
161
+ // Optionals, arrays, records and sum fields are not descended, as the invariants
162
+ // relating finite positions are not (src/feasibility.ts).
163
+ function objectFramesIn(frame) {
164
+ if (frame.scope.kind !== "object") {
165
+ return [];
166
+ }
167
+ const shape = frame.scope.shape;
168
+ return [
169
+ frame,
170
+ ...Object.entries(shape).flatMap(([key, field]) => objectFramesIn({ scope: field, path: pathOf(frame, [key]), segments: segmentsOf(frame, [key]), label: "$" })),
171
+ ];
172
+ }
173
+ // Not left to bordersOf, which excludes a point another bound on the same
174
+ // measure refuses: each comparison of two positions is drawn on a difference of
175
+ // its own, so the bounds on one difference never meet there.
176
+ function withoutPairRefusedPoints(border, all) {
177
+ const [first, second] = (border.reads ?? []).map(segments => JSON.stringify(segments));
178
+ const others = all.flatMap(other => {
179
+ const [otherFirst, otherSecond] = (other.reads ?? []).map(segments => JSON.stringify(segments));
180
+ if (other === border || first === undefined || !comparesTwoPositions(border) || !comparesTwoPositions(other)) {
181
+ return [];
182
+ }
183
+ return otherFirst === first && otherSecond === second
184
+ ? [{ other, sign: 1 }]
185
+ : otherFirst === second && otherSecond === first
186
+ ? [{ other, sign: -1 }]
187
+ : [];
188
+ });
189
+ const refuses = (witness) => others.some(({ other, sign }) => {
190
+ const value = sign * (typeof witness === "bigint" ? Number(witness > 0n) - Number(witness < 0n) : witness);
191
+ return !holds({ ...other.comparison, left: value, right: 0 }, undefined);
192
+ });
193
+ return {
194
+ ...border,
195
+ border: {
196
+ ...border.border,
197
+ points: border.border.points.map(point => point.status === "owed" && point.witness !== undefined && refuses(point.witness)
198
+ ? { ...point, status: "excluded" }
199
+ : point),
200
+ },
201
+ };
202
+ }
203
+ function unrooted(rule) {
204
+ if (rule.kind !== "compare") {
205
+ return undefined;
206
+ }
207
+ const terms = [rule.left, rule.right].filter(isTerm);
208
+ if (terms.length === 0 || termPaths(rule).some(path => path[0] !== "input")) {
209
+ return undefined;
210
+ }
211
+ return shiftTerms(rule);
212
+ }
213
+ export function guardPartitionsOf(implementation) {
214
+ const input = implementation.behavior.input;
215
+ const thresholds = Object.entries(implementation.cases).flatMap(([tag, decision]) => decision.kind !== "rules"
216
+ ? []
217
+ : decision.guards.flatMap(candidate => thresholdsIn(candidate.condition, framesAt(guardScope(implementation.behavior, tag), `@${tag}`, "$"))));
218
+ const trails = [...new Set(thresholds.map(threshold => JSON.stringify(threshold.segments)))];
219
+ return trails.flatMap(trail => {
220
+ const atPath = thresholds.filter(threshold => JSON.stringify(threshold.segments) === trail);
221
+ const partition = partitionAt(atPath[0].path, atPath[0].segments, atPath[0].schema, atPath[0].inherited, atPath.map(threshold => threshold.rule));
222
+ return partition === undefined ? [] : [partition];
223
+ });
224
+ }
225
+ // Guards are read here rather than through offGridEquality, since a guard's
226
+ // terms reach the dependencies and are located through the guard's frames.
227
+ export function offGridEqualityIn(definition, tag, decision) {
228
+ const frames = framesAt(guardScope(definition, tag), `@${tag}`, "$");
229
+ for (const threshold of decision.guards.flatMap(candidate => thresholdsIn(candidate.condition, frames))) {
230
+ const { operator, bound } = normalize(threshold.rule);
231
+ if (holdsNoDecimal(threshold.schema, operator, bound)) {
232
+ const scale = threshold.schema.scale;
233
+ return `compares ${threshold.label} with ${String(bound)}, which no decimal(${scale}) holds: ${threshold.described}`;
234
+ }
235
+ }
236
+ const scope = guardScope(definition, tag);
237
+ return decision.guards
238
+ .map(candidate => offGridEquality(candidate.condition, path => schemaAtPath(scope, path), "$"))
239
+ .find(found => found !== undefined);
240
+ }
241
+ function framesAt(scope, path, label) {
242
+ return { root: { scope, path, segments: [path], label }, elements: {} };
243
+ }
244
+ function locate(term, frames) {
245
+ const keys = positionOf(term).path;
246
+ const element = keys[0] === undefined ? undefined : frames.elements[keys[0]];
247
+ return element === undefined
248
+ ? { frame: frames.root, keys }
249
+ : { frame: element, keys: keys.slice(1) };
250
+ }
251
+ function enter(rule, frames) {
252
+ const { frame, keys } = locate(rule.of, frames);
253
+ const collection = schemaAt(frame.scope, keys);
254
+ if (collection?.kind !== "array") {
255
+ return undefined;
256
+ }
257
+ const suffix = keys.map(key => `.${key}`).join("");
258
+ return {
259
+ root: frames.root,
260
+ elements: {
261
+ ...frames.elements,
262
+ [rule.element]: {
263
+ scope: collection.element,
264
+ path: `${frame.path}${suffix}[]`,
265
+ segments: [...segmentsOf(frame, keys), "[]"],
266
+ label: `${frame.label}${suffix}[]`,
267
+ },
268
+ },
269
+ };
270
+ }
271
+ function labelsOf(frames) {
272
+ return Object.fromEntries(Object.entries(frames.elements).map(([name, frame]) => [name, frame.label]));
273
+ }
274
+ function pathOf(frame, keys) {
275
+ return `${frame.path}${keys.map(key => `.${key}`).join("")}`;
276
+ }
277
+ // The rendered path is for reports; positions are found by segments, since a
278
+ // key holding "." renders the same as the nested path it spells.
279
+ function segmentsOf(frame, keys) {
280
+ return [...frame.segments, ...keys.map(key => `.${key}`)];
281
+ }
282
+ function thresholdsIn(rule, frames) {
283
+ if (rule.kind === "and" || rule.kind === "or") {
284
+ return rule.rules.flatMap(part => thresholdsIn(part, frames));
285
+ }
286
+ if (rule.kind === "not") {
287
+ return thresholdsIn(rule.rule, frames);
288
+ }
289
+ if (rule.kind === "all" || rule.kind === "any") {
290
+ const inner = enter(rule, frames);
291
+ return inner === undefined ? [] : thresholdsIn(rule.each, inner);
292
+ }
293
+ const normalized = normalize(rule);
294
+ if (rule.kind !== "compare" || normalized === undefined || normalized.measure !== "value") {
295
+ return [];
296
+ }
297
+ const term = (isTerm(rule.left) ? rule.left : rule.right);
298
+ const { frame, keys } = locate(term, frames);
299
+ const schema = schemaAt(frame.scope, keys);
300
+ return schema === undefined
301
+ ? []
302
+ : [
303
+ {
304
+ path: pathOf(frame, keys),
305
+ label: `${frame.label}${keys.map(key => `.${key}`).join("")}`,
306
+ described: describeRule(rule, frames.root.label, labelsOf(frames)),
307
+ segments: segmentsOf(frame, keys),
308
+ schema,
309
+ inherited: inheritedAt(frame.scope, keys),
310
+ rule,
311
+ },
312
+ ];
313
+ }
314
+ function partitionAt(path, segments, schema, inherited, rules) {
315
+ const carrier = carrierOf(schema, "value");
316
+ if (carrier === undefined) {
317
+ return undefined;
318
+ }
319
+ const cuts = rules.flatMap(rule => {
320
+ const { operator, bound } = normalize(rule);
321
+ return operator === "==" || operator === "!="
322
+ ? [
323
+ { value: bound, lowerHoldsIt: false },
324
+ { value: bound, lowerHoldsIt: true },
325
+ ]
326
+ : [{ value: bound, lowerHoldsIt: operator === "<=" || operator === ">" }];
327
+ });
328
+ const unique = cuts
329
+ .filter((cut, index) => cuts.findIndex(other => carrier.compare(other.value, cut.value) === 0 &&
330
+ other.lowerHoldsIt === cut.lowerHoldsIt) === index)
331
+ .sort((left, right) => carrier.compare(left.value, right.value));
332
+ const { lower, upper } = admittedRange([...schema.invariants, ...inherited], carrier);
333
+ const edges = [
334
+ lower,
335
+ ...unique.flatMap(cut => [
336
+ { value: cut.value, inclusive: cut.lowerHoldsIt },
337
+ { value: cut.value, inclusive: !cut.lowerHoldsIt },
338
+ ]),
339
+ upper,
340
+ ];
341
+ const classes = [];
342
+ const excluded = [];
343
+ for (let index = 0; index < edges.length; index += 2) {
344
+ const from = edges[index];
345
+ const to = edges[index + 1];
346
+ const contains = (value) => (from === undefined ||
347
+ carrier.compare(value, from.value) > 0 ||
348
+ (from.inclusive && carrier.compare(value, from.value) === 0)) &&
349
+ (to === undefined ||
350
+ carrier.compare(value, to.value) < 0 ||
351
+ (to.inclusive && carrier.compare(value, to.value) === 0));
352
+ const witness = from === undefined
353
+ ? to === undefined
354
+ ? undefined
355
+ : to.inclusive
356
+ ? to.value
357
+ : (carrier.step?.(to.value, -1) ?? carrier.past?.(to.value, -1))
358
+ : from.inclusive
359
+ ? from.value
360
+ : (carrier.step?.(from.value, 1) ?? carrier.past?.(from.value, 1));
361
+ const single = from !== undefined &&
362
+ to !== undefined &&
363
+ from.inclusive &&
364
+ to.inclusive &&
365
+ carrier.compare(from.value, to.value) === 0;
366
+ const name = single
367
+ ? `v = ${carrier.format(from.value)}`
368
+ : [
369
+ from === undefined ? "" : `${carrier.format(from.value)} ${from.inclusive ? "<=" : "<"} `,
370
+ "v",
371
+ to === undefined ? "" : ` ${to.inclusive ? "<=" : "<"} ${carrier.format(to.value)}`,
372
+ ].join("");
373
+ if (witness === undefined || !contains(witness)) {
374
+ excluded.push(name);
375
+ continue;
376
+ }
377
+ classes.push({ name, witness, contains });
378
+ }
379
+ return { path, segments, classes, excluded };
380
+ }
381
+ export function inheritedAt(scope, keys) {
382
+ const [key, ...rest] = keys;
383
+ const unwrapped = scope.kind === "optional" ? scope.schema : scope;
384
+ if (key === undefined || unwrapped.kind !== "object") {
385
+ return [];
386
+ }
387
+ const field = unwrapped.shape[key];
388
+ const here = unwrapped.invariants.flatMap(conjuncts).flatMap(rule => {
389
+ const stepped = keys.reduce((current, next) => (current === undefined ? undefined : stepInto(current, next)), rule);
390
+ return stepped === undefined ? [] : [stepped];
391
+ });
392
+ return field === undefined ? here : [...here, ...inheritedAt(field, rest)];
393
+ }
394
+ function admittedRange(invariants, carrier) {
395
+ let lower;
396
+ let upper;
397
+ for (const rule of invariants.flatMap(conjuncts)) {
398
+ if (rule.kind !== "compare" || boundTermPath(rule)?.length !== 0) {
399
+ continue;
400
+ }
401
+ const normalized = normalize(rule);
402
+ if (normalized === undefined || normalized.measure !== "value") {
403
+ continue;
404
+ }
405
+ const { operator, bound } = normalized;
406
+ if (operator === ">=" || operator === ">") {
407
+ const edge = { value: bound, inclusive: operator === ">=" };
408
+ if (lower === undefined || carrier.compare(bound, lower.value) > 0) {
409
+ lower = edge;
410
+ }
411
+ }
412
+ if (operator === "<=" || operator === "<") {
413
+ const edge = { value: bound, inclusive: operator === "<=" };
414
+ if (upper === undefined || carrier.compare(bound, upper.value) < 0) {
415
+ upper = edge;
416
+ }
417
+ }
418
+ }
419
+ return { lower, upper };
420
+ }
421
+ const asGuard = {
422
+ source: "guard",
423
+ describe: (rule, frames) => describeRule(rule, frames.root.label, labelsOf(frames)),
424
+ };
425
+ function walk(rule, frames, at, reading) {
426
+ if (rule.kind === "and" || rule.kind === "or") {
427
+ return rule.rules.flatMap(part => walk(part, frames, at, reading));
428
+ }
429
+ if (rule.kind === "not") {
430
+ return walk(rule.rule, frames, at, reading);
431
+ }
432
+ if (rule.kind === "all" || rule.kind === "any") {
433
+ const inner = enter(rule, frames);
434
+ return inner === undefined ? [] : walk(rule.each, inner, at, reading);
435
+ }
436
+ if ([rule.left, rule.right].some(operand => isTerm(operand) && positionData(operand) === undefined)) {
437
+ return betweenExpression(rule, frames, at, reading);
438
+ }
439
+ if (isTerm(rule.left) && isTerm(rule.right)) {
440
+ return between(rule, rule.left, rule.right, frames, at, reading);
441
+ }
442
+ const term = isTerm(rule.left) ? rule.left : isTerm(rule.right) ? rule.right : undefined;
443
+ if (term === undefined) {
444
+ return [];
445
+ }
446
+ const { frame, keys } = locate(term, frames);
447
+ const { measure } = positionOf(term);
448
+ const schema = schemaAt(frame.scope, keys);
449
+ if (schema === undefined) {
450
+ return [];
451
+ }
452
+ const borders = bordersOf([rule], found => carrierOf(schema, found), {
453
+ source: reading.source,
454
+ describe: () => reading.describe(rule, frames),
455
+ admits: coordinate => measure !== "value" ||
456
+ (schema.parse(coordinate).success &&
457
+ inheritedAt(frame.scope, keys).every(inherited => holds(inherited, coordinate))),
458
+ });
459
+ const positionPath = pathOf(frame, keys);
460
+ const positionSegments = segmentsOf(frame, keys);
461
+ return borders.map(border => ({
462
+ path: positionPath,
463
+ segments: positionSegments,
464
+ comparison: rule,
465
+ border,
466
+ coordinateOf: reached => readOperand(term, reached.scope),
467
+ compose: (given, coordinate) => at(positionSegments)?.write(given, measure, coordinate),
468
+ }));
469
+ }
470
+ function betweenExpression(rule, frames, at, reading) {
471
+ const form = differenceOf(rule);
472
+ if (rule.operator === "==" || rule.operator === "!=" || typeof form.constant !== "number") {
473
+ return [];
474
+ }
475
+ const parts = form.parts.map(part => {
476
+ const term = positionTerm(part.path, part.measure);
477
+ const { frame, keys } = locate(term, frames);
478
+ const schema = schemaAt(frame.scope, keys);
479
+ const standsIn = frame === frames.root && keys[0] === DEPS;
480
+ return {
481
+ term,
482
+ coefficient: part.coefficient,
483
+ measure: part.measure,
484
+ standsIn,
485
+ path: standsIn ? ["deps", ...keys.slice(1)].join(".") : pathOf(frame, keys),
486
+ segments: segmentsOf(frame, keys),
487
+ kind: part.measure === "length" ? "integer" : schema?.kind,
488
+ };
489
+ });
490
+ const carrier = parts.every(part => part.kind === "integer")
491
+ ? integerCarrier
492
+ : parts.every(part => part.kind === "integer" || part.kind === "number")
493
+ ? numberCarrier
494
+ : undefined;
495
+ if (carrier === undefined || parts.length === 0) {
496
+ return [];
497
+ }
498
+ const constant = form.constant;
499
+ const difference = {
500
+ ...(rule.name === undefined ? {} : { name: rule.name }),
501
+ kind: "compare",
502
+ operator: rule.operator,
503
+ left: selfTerm(),
504
+ right: 0,
505
+ };
506
+ const borders = bordersOf([difference], () => carrier, {
507
+ source: reading.source,
508
+ describe: () => reading.describe(rule, frames),
509
+ admits: () => true,
510
+ });
511
+ const valueOf = (part, scope) => {
512
+ const value = readOperand(part.term, scope);
513
+ return value === undefined ? undefined : value;
514
+ };
515
+ const written = parts
516
+ .map((part, index) => {
517
+ const size = Math.abs(part.coefficient);
518
+ const body = size === 1 ? part.path : `${size} * ${part.path}`;
519
+ return index === 0 ? (part.coefficient < 0 ? `−${body}` : body) : `${part.coefficient < 0 ? "−" : "+"} ${body}`;
520
+ })
521
+ .join(" ");
522
+ const path = constant === 0 ? written : `${written} ${constant < 0 ? "−" : "+"} ${Math.abs(constant)}`;
523
+ // Each part weighed by one can be moved onto any value, and the first the input
524
+ // takes is written: an earlier one may be held to a bound of its own.
525
+ const movable = parts.filter(part => !part.standsIn && Math.abs(part.coefficient) === 1);
526
+ const weighed = parts.length > 1 && parts.every(part => !part.standsIn)
527
+ ? {
528
+ parts: parts.map(part => ({
529
+ path: part.path,
530
+ coefficient: part.coefficient,
531
+ valueOf: scope => valueOf(part, scope),
532
+ write: (given, value) => at(part.segments)?.write(given, part.measure, value),
533
+ })),
534
+ }
535
+ : undefined;
536
+ return borders.map(border => ({
537
+ path,
538
+ segments: (parts.find(part => !part.standsIn) ?? parts[0]).segments,
539
+ reads: parts.filter(part => !part.standsIn).map(part => part.segments),
540
+ comparison: rule,
541
+ border,
542
+ ...(weighed === undefined ? {} : { form: weighed }),
543
+ coordinateOf: reached => {
544
+ let total = constant;
545
+ for (const part of parts) {
546
+ const value = valueOf(part, reached.scope);
547
+ if (value === undefined) {
548
+ return undefined;
549
+ }
550
+ total += part.coefficient * value;
551
+ }
552
+ return total;
553
+ },
554
+ sides: movable.length,
555
+ compose: (given, coordinate, deps, side) => {
556
+ const moving = movable[side ?? 0];
557
+ const moved = moving === undefined ? undefined : at(moving.segments);
558
+ if (moving === undefined || moved === undefined) {
559
+ return undefined;
560
+ }
561
+ let rest = constant;
562
+ for (const part of parts) {
563
+ if (part === moving) {
564
+ continue;
565
+ }
566
+ const value = part.standsIn
567
+ ? readOperand(part.term, withDeps({}, deps))
568
+ : at(part.segments)?.valuesIn(given)[0];
569
+ if (value === undefined) {
570
+ return undefined;
571
+ }
572
+ rest += part.coefficient * (part.measure === "length" && !part.standsIn ? sizeOf(value) : value);
573
+ }
574
+ return moved.write(given, moving.measure, (coordinate - rest) / moving.coefficient);
575
+ },
576
+ }));
577
+ }
578
+ function between(rule, left, right, frames, at, reading) {
579
+ const sides = [left, right].map(term => {
580
+ const { frame, keys } = locate(term, frames);
581
+ const { measure } = positionOf(term);
582
+ const schema = schemaAt(frame.scope, keys);
583
+ const standsIn = frame === frames.root && keys[0] === DEPS;
584
+ return {
585
+ term,
586
+ measure,
587
+ standsIn,
588
+ path: standsIn ? ["deps", ...keys.slice(1)].join(".") : pathOf(frame, keys),
589
+ segments: segmentsOf(frame, keys),
590
+ kind: measure === "length" ? "integer" : schema?.kind,
591
+ scale: measure === "value" && schema?.kind === "decimal" ? schema.scale : 0,
592
+ };
593
+ });
594
+ const [first, second] = sides;
595
+ const carrier = differenceCarrier(first, second);
596
+ if (carrier === undefined || rule.operator === "==" || rule.operator === "!=") {
597
+ return [];
598
+ }
599
+ const moment = first.kind === "decimal" || second.kind === "decimal"
600
+ ? decimalMoment(first, second)
601
+ : first.kind === second.kind
602
+ ? MOMENTS[first.kind ?? ""]
603
+ : undefined;
604
+ const difference = {
605
+ ...(rule.name === undefined ? {} : { name: rule.name }),
606
+ kind: "compare",
607
+ operator: rule.operator,
608
+ left: selfTerm(),
609
+ right: carrier === nanosecondCarrier || first.kind === "decimal" || second.kind === "decimal" ? 0n : 0,
610
+ };
611
+ const borders = bordersOf([difference], () => carrier, {
612
+ source: reading.source,
613
+ describe: () => reading.describe(rule, frames),
614
+ admits: () => true,
615
+ });
616
+ const read = (side, scopeValue) => {
617
+ const value = readOperand(side.term, scopeValue);
618
+ if (value === undefined) {
619
+ return undefined;
620
+ }
621
+ return moment === undefined ? value : moment.read(value, side);
622
+ };
623
+ const form = sides.every(side => !side.standsIn && (side.kind === "integer" || side.kind === "number"))
624
+ ? {
625
+ parts: sides.map((side, index) => ({
626
+ path: side.path,
627
+ coefficient: index === 0 ? 1 : -1,
628
+ valueOf: scope => read(side, scope),
629
+ write: (given, value) => at(side.segments)?.write(given, side.measure, value),
630
+ })),
631
+ }
632
+ : undefined;
633
+ return borders.map(border => ({
634
+ path: `${first.path} − ${second.path}`,
635
+ segments: (first.standsIn ? second : first).segments,
636
+ reads: sides.filter(side => !side.standsIn).map(side => side.segments),
637
+ comparison: rule,
638
+ border,
639
+ ...(form === undefined ? {} : { form }),
640
+ coordinateOf: reached => {
641
+ const a = read(first, reached.scope);
642
+ const b = read(second, reached.scope);
643
+ return a === undefined || b === undefined ? undefined : a - b;
644
+ },
645
+ compose: (given, coordinate, deps, side) => {
646
+ const otherSide = side === 1;
647
+ // Move the side that can take every value of the difference: the finer of
648
+ // a decimal and an integer, and never a stand-in, which a row writes as given.
649
+ const preferred = first.standsIn || (!second.standsIn && second.scale > first.scale);
650
+ const swappable = !first.standsIn && !second.standsIn && first.scale === second.scale;
651
+ const moveSecond = otherSide === true && swappable ? !preferred : preferred;
652
+ const [moving, fixed, sign] = moveSecond ? [second, first, -1] : [first, second, 1];
653
+ const moved = moving.standsIn ? undefined : at(moving.segments);
654
+ const other = fixed.standsIn
655
+ ? readOperand(fixed.term, withDeps({}, deps))
656
+ : at(fixed.segments)?.valuesIn(given)[0];
657
+ if (moved === undefined || other === undefined) {
658
+ return undefined;
659
+ }
660
+ if (moment?.write !== undefined) {
661
+ const units = moment.read(other, fixed) + BigInt(sign) * coordinate;
662
+ const written = moment.write(units, moving, other);
663
+ return written === undefined ? undefined : moved.write(given, moving.measure, written);
664
+ }
665
+ if (moment !== undefined) {
666
+ const amount = sign * Number(coordinate);
667
+ const shifted = moment.shift(other, amount);
668
+ if (shifted !== undefined) {
669
+ return moved.write(given, moving.measure, shifted);
670
+ }
671
+ // Moving this side would carry it past an end of the day, so the other
672
+ // side is moved against the value this one already holds instead.
673
+ const held = fixed.standsIn ? undefined : at(fixed.segments);
674
+ const current = moved.valuesIn(given)[0];
675
+ const counter = current === undefined ? undefined : moment.shift(current, -amount);
676
+ return held === undefined || counter === undefined
677
+ ? undefined
678
+ : held.write(given, fixed.measure, counter);
679
+ }
680
+ const base = fixed.measure === "length" && !fixed.standsIn ? sizeOf(other) : other;
681
+ return moved.write(given, moving.measure, base + sign * coordinate);
682
+ },
683
+ }));
684
+ }
685
+ // Reads two decimals as whole numbers of units of the finer scale of the two, so
686
+ // their difference is exact, and writes one back where the other side's value
687
+ // plus the difference lands on its own scale.
688
+ function decimalMoment(first, second) {
689
+ const scale = Math.max(first.scale, second.scale);
690
+ return {
691
+ read: value => decimalUnits(value, scale, "floor"),
692
+ shift: () => undefined,
693
+ write: (units, side, like) => {
694
+ const coarser = 10n ** BigInt(scale - side.scale);
695
+ return units % coarser === 0n ? decimalOfUnits(like, units / coarser, side.scale) : undefined;
696
+ },
697
+ };
698
+ }
699
+ const MOMENTS = {
700
+ instant: {
701
+ read: value => value.epochNanoseconds,
702
+ shift: (value, amount) => value.add({ nanoseconds: amount }),
703
+ },
704
+ date: {
705
+ // Counted in the ISO calendar, since until refuses two dates in different
706
+ // calendars and a date in any calendar is one the schema accepts.
707
+ read: value => value.constructor
708
+ .from("1970-01-01")
709
+ .until(value.withCalendar("iso8601"), { largestUnit: "days" })
710
+ .total("days"),
711
+ shift: (value, amount) => value.add({ days: amount }),
712
+ },
713
+ datetime: {
714
+ // Read through UTC as an exact bigint: a total in nanoseconds since 1970 is
715
+ // past what a number holds exactly, and would round a one-nanosecond gap away.
716
+ read: value => value.toZonedDateTime("UTC").epochNanoseconds,
717
+ shift: (value, amount) => value.add({ nanoseconds: amount }),
718
+ },
719
+ time: {
720
+ read: value => BigInt(value.constructor.from("00:00").until(value, { largestUnit: "hours" }).total("nanoseconds")),
721
+ shift: (value, amount) => {
722
+ const shifted = value.add({ nanoseconds: amount });
723
+ const order = value.constructor.compare(shifted, value);
724
+ return Math.sign(order) === Math.sign(amount) ? shifted : undefined;
725
+ },
726
+ },
727
+ };
728
+ function differenceCarrier({ kind: first, scale: firstScale }, { kind: second, scale: secondScale }) {
729
+ const numeric = (kind) => kind === "integer" || kind === "number";
730
+ if (first === "integer" && second === "integer") {
731
+ return integerCarrier;
732
+ }
733
+ // Two decimals count their difference in units of the finer scale; a decimal
734
+ // is not ordered against any other kind.
735
+ if (first === "decimal" && second === "decimal") {
736
+ return decimalUnitsCarrier(Math.max(firstScale, secondScale));
737
+ }
738
+ if (first === "decimal" || second === "decimal") {
739
+ return undefined;
740
+ }
741
+ if (numeric(first) && numeric(second)) {
742
+ return numberCarrier;
743
+ }
744
+ if (first !== second) {
745
+ return undefined;
746
+ }
747
+ return first === "date" ? integerCarrier : first === "instant" || first === "datetime" || first === "time" ? nanosecondCarrier : undefined;
748
+ }
749
+ export function comparisonsNotReadOf(implementation) {
750
+ const input = implementation.behavior.input;
751
+ return Object.entries(implementation.cases).flatMap(([tag, decision]) => decision.kind !== "rules"
752
+ ? []
753
+ : decision.guards.flatMap(candidate => unreadIn(candidate.condition, framesAt(guardScope(implementation.behavior, tag), `@${tag}`, "$")).map(text => `${decision.id}: ${text}`)));
754
+ }
755
+ function unreadIn(rule, frames) {
756
+ switch (rule.kind) {
757
+ case "and":
758
+ case "or":
759
+ return rule.rules.flatMap(part => unreadIn(part, frames));
760
+ case "not":
761
+ return unreadIn(rule.rule, frames);
762
+ case "all":
763
+ case "any": {
764
+ const inner = enter(rule, frames);
765
+ return inner === undefined
766
+ ? [describeRule(rule, frames.root.label, labelsOf(frames))]
767
+ : unreadIn(rule.each, inner);
768
+ }
769
+ case "compare": {
770
+ const terms = [rule.left, rule.right].filter(isTerm);
771
+ if (terms.some(term => positionData(term) === undefined)) {
772
+ const kinds = differenceOf(rule).parts.map(part => {
773
+ const { frame, keys } = locate(positionTerm(part.path, part.measure), frames);
774
+ return part.measure === "length" ? "integer" : schemaAt(frame.scope, keys)?.kind;
775
+ });
776
+ return kinds.every(kind => kind === "integer" || kind === "number")
777
+ ? []
778
+ : [describeRule(rule, frames.root.label, labelsOf(frames))];
779
+ }
780
+ const schemas = terms.map(term => {
781
+ const { frame, keys } = locate(term, frames);
782
+ const schema = schemaAt(frame.scope, keys);
783
+ // The length of an enum is not read: see carrierOf.
784
+ return positionOf(term).measure === "length" ? (schema?.kind === "enum" ? undefined : int()) : schema;
785
+ });
786
+ const sides = schemas.map((schema) => ({
787
+ kind: schema?.kind,
788
+ scale: schema?.kind === "decimal" ? schema.scale : 0,
789
+ }));
790
+ const kind = schemas[0]?.kind;
791
+ const readable = terms.length === 2
792
+ ? rule.operator === "==" ||
793
+ rule.operator === "!=" ||
794
+ differenceCarrier(sides[0], sides[1]) !== undefined
795
+ : kind === "boolean" ||
796
+ // An enum's values are ordered by their text, not as they were named,
797
+ // so only an equality with one of them is read.
798
+ (kind === "enum" && (rule.operator === "==" || rule.operator === "!=")) ||
799
+ kind === "variants" ||
800
+ kind === "literal" ||
801
+ (schemas[0] !== undefined && carrierOf(schemas[0], "value") !== undefined);
802
+ return readable ? [] : [describeRule(rule, frames.root.label, labelsOf(frames))];
803
+ }
804
+ }
805
+ }
806
+ function schemaAt(schema, keys) {
807
+ return schemaAtPath(schema, keys);
808
+ }
809
+ //# sourceMappingURL=guard-borders.js.map