tslaws 0.10.0 → 1.0.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 (122) hide show
  1. package/README.md +7 -2
  2. package/bin/tslaws.js +8 -2
  3. package/dist/browser.d.ts +1 -1
  4. package/dist/browser.js +25 -5
  5. package/dist/bundled.js +2 -2
  6. package/dist/bundlerPlugins.d.ts +2 -0
  7. package/dist/bundlerPlugins.js +7 -0
  8. package/dist/certificates.d.ts +139 -0
  9. package/dist/certificates.js +433 -0
  10. package/dist/chc.d.ts +85 -0
  11. package/dist/chc.js +298 -0
  12. package/dist/check.d.ts +13 -1
  13. package/dist/check.js +211 -27
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +175 -34
  16. package/dist/compile.d.ts +15 -5
  17. package/dist/compile.js +198 -69
  18. package/dist/coverage.d.ts +38 -1
  19. package/dist/coverage.js +94 -12
  20. package/dist/e2eApi.js +3 -1
  21. package/dist/generators.js +12 -2
  22. package/dist/github.d.ts +49 -5
  23. package/dist/github.js +107 -24
  24. package/dist/githubCli.d.ts +28 -0
  25. package/dist/githubCli.js +1039 -211
  26. package/dist/hints.js +2 -1
  27. package/dist/init.js +42 -0
  28. package/dist/isolate.d.ts +28 -0
  29. package/dist/isolate.js +262 -0
  30. package/dist/isolatedCheck.d.ts +1 -0
  31. package/dist/isolatedCheck.js +16 -0
  32. package/dist/lawHost.d.ts +50 -0
  33. package/dist/lawHost.js +199 -0
  34. package/dist/lawRuntime.d.ts +39 -0
  35. package/dist/lawRuntime.js +242 -0
  36. package/dist/lock.d.ts +49 -9
  37. package/dist/lock.js +132 -21
  38. package/dist/mcp.js +28 -7
  39. package/dist/mutate.d.ts +4 -0
  40. package/dist/mutate.js +7 -1
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +4 -0
  43. package/dist/pluginHooks.d.ts +16 -0
  44. package/dist/pluginHooks.js +48 -0
  45. package/dist/pluginHost.d.ts +5 -0
  46. package/dist/pluginHost.js +43 -0
  47. package/dist/pluginWorker.d.ts +1 -0
  48. package/dist/pluginWorker.js +40 -0
  49. package/dist/plural.d.ts +2 -0
  50. package/dist/plural.js +4 -0
  51. package/dist/pool.d.ts +80 -7
  52. package/dist/pool.js +222 -11
  53. package/dist/projects.d.ts +43 -1
  54. package/dist/projects.js +283 -11
  55. package/dist/promote.d.ts +56 -2
  56. package/dist/promote.js +429 -13
  57. package/dist/property.js +5 -1
  58. package/dist/propertyWorker.js +7 -0
  59. package/dist/proposals.d.ts +52 -4
  60. package/dist/proposals.js +484 -21
  61. package/dist/reporters.js +5 -1
  62. package/dist/runtimeEnv.d.ts +13 -5
  63. package/dist/runtimeEnv.js +48 -10
  64. package/dist/sandbox.d.ts +98 -0
  65. package/dist/sandbox.js +673 -0
  66. package/dist/sandboxGuard.d.ts +56 -0
  67. package/dist/sandboxGuard.js +249 -0
  68. package/dist/seal.d.ts +9 -0
  69. package/dist/seal.js +426 -0
  70. package/dist/security/cli.d.ts +6 -0
  71. package/dist/security/cli.js +39 -0
  72. package/dist/security/cwe.d.ts +14 -0
  73. package/dist/security/cwe.js +40 -0
  74. package/dist/security/deps/cache.d.ts +28 -0
  75. package/dist/security/deps/cache.js +107 -0
  76. package/dist/security/deps/config.d.ts +16 -0
  77. package/dist/security/deps/config.js +43 -0
  78. package/dist/security/deps/imports.d.ts +4 -0
  79. package/dist/security/deps/imports.js +33 -0
  80. package/dist/security/deps/lockfiles.d.ts +23 -0
  81. package/dist/security/deps/lockfiles.js +153 -0
  82. package/dist/security/deps/osv.d.ts +66 -0
  83. package/dist/security/deps/osv.js +137 -0
  84. package/dist/security/deps/run.d.ts +54 -0
  85. package/dist/security/deps/run.js +135 -0
  86. package/dist/security/deps/severity.d.ts +26 -0
  87. package/dist/security/deps/severity.js +78 -0
  88. package/dist/security/generators.d.ts +9 -0
  89. package/dist/security/generators.js +36 -0
  90. package/dist/security/index.d.ts +27 -0
  91. package/dist/security/index.js +18 -0
  92. package/dist/security/integers.d.ts +31 -0
  93. package/dist/security/integers.js +105 -0
  94. package/dist/security/law.d.ts +54 -0
  95. package/dist/security/law.js +54 -0
  96. package/dist/security/pathTraversal.d.ts +29 -0
  97. package/dist/security/pathTraversal.js +146 -0
  98. package/dist/security/prototypePollution.d.ts +30 -0
  99. package/dist/security/prototypePollution.js +142 -0
  100. package/dist/security/redirect.d.ts +21 -0
  101. package/dist/security/redirect.js +154 -0
  102. package/dist/security/redos.d.ts +21 -0
  103. package/dist/security/redos.js +93 -0
  104. package/dist/security/validation.d.ts +25 -0
  105. package/dist/security/validation.js +89 -0
  106. package/dist/security/xss.d.ts +21 -0
  107. package/dist/security/xss.js +90 -0
  108. package/dist/settings.d.ts +20 -0
  109. package/dist/settings.js +32 -0
  110. package/dist/smt.d.ts +29 -1
  111. package/dist/smt.js +239 -107
  112. package/dist/smtWorker.d.ts +1 -0
  113. package/dist/smtWorker.js +26 -0
  114. package/dist/solvers.d.ts +9 -0
  115. package/dist/solvers.js +11 -5
  116. package/dist/symbolic.d.ts +54 -1
  117. package/dist/symbolic.js +239 -13
  118. package/dist/tsconfigResolve.d.ts +28 -0
  119. package/dist/tsconfigResolve.js +141 -0
  120. package/dist/types.d.ts +28 -0
  121. package/hooks/claude-hook.mjs +2 -0
  122. package/package.json +18 -6
@@ -1,4 +1,5 @@
1
1
  import ts from 'typescript';
2
+ import type { Predicate } from './chc.ts';
2
3
  export declare class Unsupported extends Error {
3
4
  }
4
5
  export declare const maxSafe = 9007199254740991n;
@@ -34,6 +35,22 @@ export interface Arr {
34
35
  escaped: boolean;
35
36
  };
36
37
  }
38
+ /**
39
+ * An array of any length, as an SMT array from index to element plus a length: a claim about it holds for every length.
40
+ * Only parameters and copies of them take this form, and only with integer, bigint or boolean elements.
41
+ */
42
+ export interface Seq {
43
+ k: 'seq';
44
+ len: Int;
45
+ /** An SMT array term from Int to the element sort. */
46
+ data: string;
47
+ elem: SeqElement;
48
+ id: {
49
+ escaped: boolean;
50
+ };
51
+ }
52
+ export type SeqElement = 'int' | 'big' | 'bool';
53
+ export declare const elementSort: (e: SeqElement) => string;
37
54
  export interface Rec {
38
55
  k: 'rec';
39
56
  fields: Map<string, Value>;
@@ -41,7 +58,7 @@ export interface Rec {
41
58
  export interface Undef {
42
59
  k: 'undef';
43
60
  }
44
- export type Value = Bool | Int | Big | Fp | Str | Arr | Rec | Undef;
61
+ export type Value = Bool | Int | Big | Fp | Str | Arr | Seq | Rec | Undef;
45
62
  type FunctionNode = ts.FunctionDeclaration | ts.ArrowFunction | ts.FunctionExpression;
46
63
  interface FileIndex {
47
64
  functions: Map<string, FunctionNode>;
@@ -79,6 +96,22 @@ export declare class Executor {
79
96
  readonly bounded: string[];
80
97
  /** Advice for the reader when a proof fails on an obligation (a divisor that may be 0). */
81
98
  readonly hints: string[];
99
+ /** Terms `share` named, by name, for a consumer that cannot keep the `define-fun`s (a Horn clause is closed). */
100
+ readonly sharedTerms: Map<string, string>;
101
+ /**
102
+ * Prove loops for every iteration count: arrays that are parameters become SMT arrays of any length, and a loop
103
+ * without an `invariant` becomes constrained Horn clauses (`predicates` and `clauses`) for a solver to find one.
104
+ * Anything this cannot express throws `Unsupported`, and the caller runs again without it, unrolling to the bound.
105
+ */
106
+ infer: boolean;
107
+ /** The unknown invariant predicates, one per loop that was turned into clauses. */
108
+ readonly predicates: Predicate[];
109
+ /** `(=> body head)` for the entry and the step of each such loop; the final query is added by the caller. */
110
+ readonly clauses: string[];
111
+ /** Facts that hold inside the loops being executed (each loop's invariant on its arbitrary state), innermost last. */
112
+ private readonly scope;
113
+ /** Ints stay within this in the second attempt (see smt.ts), which the elements of an array read share. */
114
+ intLimit: bigint | undefined;
82
115
  private readonly files;
83
116
  readonly bound: number;
84
117
  constructor(bound: number);
@@ -126,11 +159,27 @@ export declare class Executor {
126
159
  /** A constant standing for an arbitrary value of the same kind as `v`, with the facts every such value has. */
127
160
  private fresh;
128
161
  private invariantTerm;
162
+ /**
163
+ * The invariants and the condition read in an arbitrary state. What reading them owes (`2 * s` in range) is owed
164
+ * only in a state that satisfies the invariants, which is the only kind of state the loop is in.
165
+ */
166
+ private evaluatedWhere;
129
167
  /**
130
168
  * Hoare-style: the invariant must hold on entry and after any iteration that starts from a state satisfying it; the
131
169
  * code after the loop sees an arbitrary such state where the condition is false. No unrolling, so no bound.
132
170
  */
133
171
  private invariantLoop;
172
+ /** The SMT terms a value contributes as predicate arguments, with their sorts; undefined when it is not one. */
173
+ private terms;
174
+ /**
175
+ * The loop as constrained Horn clauses over an unknown predicate `Inv` of the live variables: the state on entry
176
+ * satisfies it, one pass of the body keeps it, and after the loop the code sees an arbitrary state satisfying it with
177
+ * the condition false. The caller asks a solver for an `Inv` that makes the law hold; there is no unrolling and no
178
+ * bound. A loop that returns or breaks is left to the unrolling.
179
+ */
180
+ private inferLoop;
181
+ /** A length of an array that is a parameter or a copy of one: not negative, and at most what JavaScript allows. */
182
+ private lengthRange;
134
183
  private forOf;
135
184
  /** `statement`: the value is unused, so mutations are allowed. `value`: an identifier here is a use, not an alias. */
136
185
  ev(node: ts.Expression, f: Frame, pc: string, statement?: boolean, plain?: boolean): Value;
@@ -145,6 +194,8 @@ export declare class Executor {
145
194
  private update;
146
195
  private property;
147
196
  private element;
197
+ /** `xs[i]` of an array of any length: the index must be inside it, and the element is one of the domain. */
198
+ private readElement;
148
199
  private readSlot;
149
200
  private arrayLiteral;
150
201
  /** `...xs`, or `...new Set(xs)` which removes duplicates. */
@@ -186,6 +237,8 @@ export declare class Executor {
186
237
  private callback;
187
238
  private applyCallback;
188
239
  private method;
240
+ /** What an array of any length supports: copying, push and pop (on a copy), length and indexing are elsewhere. */
241
+ private seqMethod;
189
242
  /** Insertion sort as a fixed network of guarded swaps; stable, as `Array.prototype.sort` is. */
190
243
  private sort;
191
244
  private stringMethod;
package/dist/symbolic.js CHANGED
@@ -11,9 +11,11 @@
11
11
  import { readFileSync } from 'node:fs';
12
12
  import { dirname, resolve } from 'node:path';
13
13
  import ts from 'typescript';
14
+ import { plural } from "./plural.js";
14
15
  export class Unsupported extends Error {
15
16
  }
16
17
  export const maxSafe = 9007199254740991n;
18
+ export const elementSort = (e) => (e === 'bool' ? 'Bool' : 'Int');
17
19
  class Frame {
18
20
  env = new Map();
19
21
  done = 'false';
@@ -92,6 +94,22 @@ export class Executor {
92
94
  bounded = [];
93
95
  /** Advice for the reader when a proof fails on an obligation (a divisor that may be 0). */
94
96
  hints = [];
97
+ /** Terms `share` named, by name, for a consumer that cannot keep the `define-fun`s (a Horn clause is closed). */
98
+ sharedTerms = new Map();
99
+ /**
100
+ * Prove loops for every iteration count: arrays that are parameters become SMT arrays of any length, and a loop
101
+ * without an `invariant` becomes constrained Horn clauses (`predicates` and `clauses`) for a solver to find one.
102
+ * Anything this cannot express throws `Unsupported`, and the caller runs again without it, unrolling to the bound.
103
+ */
104
+ infer = false;
105
+ /** The unknown invariant predicates, one per loop that was turned into clauses. */
106
+ predicates = [];
107
+ /** `(=> body head)` for the entry and the step of each such loop; the final query is added by the caller. */
108
+ clauses = [];
109
+ /** Facts that hold inside the loops being executed (each loop's invariant on its arbitrary state), innermost last. */
110
+ scope = [];
111
+ /** Ints stay within this in the second attempt (see smt.ts), which the elements of an array read share. */
112
+ intLimit;
95
113
  files = new Map();
96
114
  bound;
97
115
  constructor(bound) {
@@ -293,7 +311,7 @@ export class Executor {
293
311
  }
294
312
  // ---- values -------------------------------------------------------------------------------------------------
295
313
  share(v) {
296
- if (v.k === 'arr' || v.k === 'rec' || v.k === 'undef')
314
+ if (v.k === 'arr' || v.k === 'seq' || v.k === 'rec' || v.k === 'undef')
297
315
  return v;
298
316
  const t = v.t;
299
317
  if (t.length < 160)
@@ -301,6 +319,7 @@ export class Executor {
301
319
  const sort = { bool: 'Bool', int: 'Int', big: 'Int', fp: '(_ FloatingPoint 11 53)', str: 'String' }[v.k];
302
320
  const name = `_s${this.shared++}`;
303
321
  this.defs.push(`(define-fun ${name} () ${sort} ${t})`);
322
+ this.sharedTerms.set(name, t);
304
323
  return { ...v, t: name };
305
324
  }
306
325
  merge(c, a, b, slot = false) {
@@ -346,6 +365,20 @@ export class Executor {
346
365
  a.id.escaped = o.id.escaped = true;
347
366
  return { k: 'arr', len: this.merge(c, a.len, o.len), slots, id: a.id };
348
367
  }
368
+ case 'seq': {
369
+ const o = b;
370
+ if (a.elem !== o.elem)
371
+ throw new Unsupported('arrays of different element kinds meet on two paths');
372
+ if (a.id !== o.id)
373
+ a.id.escaped = o.id.escaped = true;
374
+ return {
375
+ k: 'seq',
376
+ len: this.merge(c, a.len, o.len),
377
+ data: ite(c, a.data, o.data),
378
+ elem: a.elem,
379
+ id: a.id,
380
+ };
381
+ }
349
382
  case 'rec': {
350
383
  const o = b;
351
384
  const fields = new Map();
@@ -384,7 +417,7 @@ export class Executor {
384
417
  }
385
418
  /** `v` used as a value somewhere other than a method receiver or index: a second name may now reach an array. */
386
419
  escape(v) {
387
- if (v.k === 'arr')
420
+ if (v.k === 'arr' || v.k === 'seq')
388
421
  v.id.escaped = true;
389
422
  if (v.k === 'rec')
390
423
  for (const field of v.fields.values())
@@ -503,6 +536,10 @@ export class Executor {
503
536
  this.invariantLoop(condition, incrementor, invariants.rest, invariants.exprs, f, pc);
504
537
  return;
505
538
  }
539
+ if (this.infer) {
540
+ this.inferLoop(condition, incrementor, body, f, pc);
541
+ return;
542
+ }
506
543
  for (let iteration = 0;; iteration += 1) {
507
544
  const c = condition === undefined ? 'true' : this.asBool(this.ev(condition, f, this.guard(f, pc)));
508
545
  const go = and(this.active(f), c);
@@ -613,7 +650,7 @@ export class Executor {
613
650
  const room = v.slots.length;
614
651
  const len = declare('Int');
615
652
  this.assumptions.push(`(and (<= 0 ${len}) (<= ${len} ${room}))`);
616
- const why = `arrays changed in an invariant loop hold at most ${room} elements`;
653
+ const why = `arrays changed in an invariant loop hold at most ${plural(room, 'element')}`;
617
654
  if (!this.bounded.includes(why))
618
655
  this.bounded.push(why);
619
656
  return {
@@ -623,6 +660,12 @@ export class Executor {
623
660
  id: { escaped: v.id.escaped },
624
661
  };
625
662
  }
663
+ case 'seq': {
664
+ const data = declare(`(Array Int ${elementSort(v.elem)})`);
665
+ const len = declare('Int');
666
+ this.assumptions.push(this.lengthRange(len));
667
+ return { k: 'seq', len: { k: 'int', t: len }, data, elem: v.elem, id: { escaped: v.id.escaped } };
668
+ }
626
669
  case 'undef':
627
670
  return v;
628
671
  }
@@ -630,11 +673,26 @@ export class Executor {
630
673
  invariantTerm(exprs, f, pc) {
631
674
  return and(...exprs.map((e) => this.asBool(this.ev(e, f, pc))));
632
675
  }
676
+ /**
677
+ * The invariants and the condition read in an arbitrary state. What reading them owes (`2 * s` in range) is owed
678
+ * only in a state that satisfies the invariants, which is the only kind of state the loop is in.
679
+ */
680
+ evaluatedWhere(exprs, condition, f, g) {
681
+ const from = this.obligations.length;
682
+ const holds = this.invariantTerm(exprs, f, g);
683
+ const c = condition === undefined ? 'true' : this.asBool(this.ev(condition, f, g));
684
+ for (const fact of this.obligations.splice(from))
685
+ this.obligations.push(`(=> ${holds} ${fact})`);
686
+ return [holds, c];
687
+ }
633
688
  /**
634
689
  * Hoare-style: the invariant must hold on entry and after any iteration that starts from a state satisfying it; the
635
690
  * code after the loop sees an arbitrary such state where the condition is false. No unrolling, so no bound.
636
691
  */
637
692
  invariantLoop(condition, incrementor, rest, exprs, f, pc) {
693
+ // The condition is read from the arbitrary state of the loop, so a write in it would go unmodelled.
694
+ if (condition !== undefined && this.modifiedNames([condition]).size > 0)
695
+ throw new Unsupported('a loop whose condition changes a variable');
638
696
  this.oblige(f, pc, this.invariantTerm(exprs, f, this.guard(f, pc)));
639
697
  const touched = this.modifiedNames([...rest, ...(incrementor === undefined ? [] : [incrementor])]);
640
698
  const kinds = new Map();
@@ -645,10 +703,16 @@ export class Executor {
645
703
  kinds.set(name, old.k);
646
704
  f.env.set(name, this.fresh(old));
647
705
  }
648
- const holds = this.invariantTerm(exprs, f, this.guard(f, pc));
649
- this.assume(f, pc, holds);
650
- const c = condition === undefined ? 'true' : this.asBool(this.ev(condition, f, this.guard(f, pc)));
706
+ // Two arbitrary states: `run` is the one an iteration starts from, and `f` is the one the code after the loop
707
+ // sees. They are different constants, so what the body owes is checked where the condition holds even though the
708
+ // code after the loop assumes it does not.
651
709
  const run = f.fork();
710
+ for (const name of touched) {
711
+ const old = run.env.get(name);
712
+ if (old !== undefined)
713
+ run.env.set(name, this.fresh(old));
714
+ }
715
+ const [holds, c] = this.evaluatedWhere(exprs, condition, run, this.guard(f, pc));
652
716
  const inside = and(pc, holds, c);
653
717
  this.execList(rest, run, inside);
654
718
  run.cnt = 'false';
@@ -664,20 +728,109 @@ export class Executor {
664
728
  // After the loop: any state satisfying the invariant in which the condition is false, or the state of an iteration
665
729
  // that started from such a state and left through a return or break. Which of the two is not known: a fresh choice.
666
730
  const left = or(and(run.done, not(f.done)), run.brk);
731
+ const [holdsAfter, continues] = this.evaluatedWhere(exprs, condition, f, this.guard(f, pc));
732
+ const stopped = not(continues);
667
733
  if (left === 'false') {
668
- this.assume(f, pc, not(c));
734
+ this.assume(f, pc, holdsAfter);
735
+ this.assume(f, pc, stopped);
669
736
  }
670
737
  else {
671
738
  const choice = `_h${this.havocked++}`;
672
739
  this.freshDecls.push(`(declare-const ${choice} Bool)`);
673
740
  this.assume(f, pc, or(not(choice), and(holds, c, left)));
674
- this.assume(f, pc, or(choice, not(c)));
741
+ this.assume(f, pc, or(choice, and(holdsAfter, stopped)));
675
742
  run.brk = 'false';
676
743
  run.cnt = 'false';
677
744
  this.mergeFrames(choice, run, f, f);
678
745
  }
679
746
  f.brk = 'false';
680
747
  }
748
+ // ---- loops without an invariant: Horn clauses for a solver to find one ----------------------------------------
749
+ /** The SMT terms a value contributes as predicate arguments, with their sorts; undefined when it is not one. */
750
+ terms(v) {
751
+ if (v.k === 'int' || v.k === 'big')
752
+ return { terms: [v.t], sorts: ['Int'] };
753
+ if (v.k === 'bool')
754
+ return { terms: [v.t], sorts: ['Bool'] };
755
+ if (v.k === 'seq')
756
+ return { terms: [v.len.t, v.data], sorts: ['Int', `(Array Int ${elementSort(v.elem)})`] };
757
+ return undefined;
758
+ }
759
+ /**
760
+ * The loop as constrained Horn clauses over an unknown predicate `Inv` of the live variables: the state on entry
761
+ * satisfies it, one pass of the body keeps it, and after the loop the code sees an arbitrary state satisfying it with
762
+ * the condition false. The caller asks a solver for an `Inv` that makes the law hold; there is no unrolling and no
763
+ * bound. A loop that returns or breaks is left to the unrolling.
764
+ */
765
+ inferLoop(condition, incrementor, body, f, pc) {
766
+ const g = this.guard(f, pc);
767
+ if (g === 'false')
768
+ return;
769
+ if (f.brk !== 'false' || f.cnt !== 'false')
770
+ throw new Unsupported('a loop inside a break or continue');
771
+ // The condition is read again from every state of the loop, so one that writes (`while (i++ < n)`) is left to the
772
+ // unrolling, which runs it once per iteration.
773
+ if (condition !== undefined && this.modifiedNames([condition]).size > 0)
774
+ throw new Unsupported('a loop whose condition changes a variable');
775
+ const touched = this.modifiedNames([body, ...(incrementor === undefined ? [] : [incrementor])]);
776
+ // The live variables are the arguments: the invariant may relate any of them, the ones the loop leaves alone too.
777
+ const live = [...f.env].filter(([, v]) => this.terms(v) !== undefined);
778
+ for (const name of touched) {
779
+ const old = f.env.get(name);
780
+ if (old !== undefined && this.terms(old) === undefined)
781
+ throw new Unsupported(`${name} is a ${old.k}, which a loop without an invariant cannot change`);
782
+ }
783
+ const arguments_ = (env) => live.flatMap(([name]) => {
784
+ const v = env.get(name);
785
+ const t = v === undefined ? undefined : this.terms(v);
786
+ if (v === undefined || t === undefined || v.k !== f.env.get(name).k)
787
+ throw new Unsupported(`${name} changes kind in a loop`);
788
+ return t.terms;
789
+ });
790
+ const predicate = {
791
+ name: `Inv${this.predicates.length}`,
792
+ sorts: live.flatMap(([, v]) => this.terms(v).sorts),
793
+ names: live.flatMap(([name, v]) => (v.k === 'seq' ? [`${name}.length`, name] : [name])),
794
+ };
795
+ this.predicates.push(predicate);
796
+ const atom = (args) => args.length === 0 ? predicate.name : `(${predicate.name} ${args.join(' ')})`;
797
+ this.clauses.push(`(=> ${and(...this.assumptions, ...this.scope, g)} ${atom(arguments_(f.env))})`);
798
+ for (const name of touched) {
799
+ const old = f.env.get(name);
800
+ if (old !== undefined)
801
+ f.env.set(name, this.fresh(old));
802
+ }
803
+ const inv = atom(arguments_(f.env));
804
+ const c = condition === undefined ? 'true' : this.asBool(this.ev(condition, f, g));
805
+ const inside = and(pc, c);
806
+ const run = f.fork();
807
+ // What the body and the incrementor owe (an index in range, an int in range, a divisor not 0) is owed on every
808
+ // iteration, so it is checked from a state that satisfies the invariant and the condition. Left in
809
+ // `obligations` it would only be checked after the loop, where the condition is false and it holds vacuously.
810
+ const owedFrom = this.obligations.length;
811
+ this.scope.push(and(g, inv));
812
+ this.branch(body, run, inside);
813
+ run.cnt = 'false';
814
+ if (incrementor !== undefined)
815
+ this.ev(incrementor, run, inside, true);
816
+ this.scope.pop();
817
+ if (run.done !== f.done || run.brk !== 'false')
818
+ throw new Unsupported('a loop that returns or breaks');
819
+ const owed = this.obligations.splice(owedFrom);
820
+ const inStep = [...this.assumptions, ...this.scope, g, inv, c];
821
+ this.clauses.push(`(=> ${and(...inStep)} ${atom(arguments_(run.env))})`);
822
+ // A query clause: no state satisfying the invariant and the condition breaks what one pass owes.
823
+ for (const fact of owed)
824
+ this.clauses.push(`(=> ${and(...inStep, not(fact))} false)`);
825
+ // After the loop: any state satisfying the invariant in which the condition is false.
826
+ this.assumptions.push(or(not(g), inv));
827
+ this.assume(f, pc, not(c));
828
+ f.brk = 'false';
829
+ }
830
+ /** A length of an array that is a parameter or a copy of one: not negative, and at most what JavaScript allows. */
831
+ lengthRange(t) {
832
+ return `(and (<= 0 ${t}) (<= ${t} 4294967295))`;
833
+ }
681
834
  forOf(node, f, pc) {
682
835
  if (!ts.isVariableDeclarationList(node.initializer) ||
683
836
  node.initializer.declarations.length !== 1 ||
@@ -779,6 +932,7 @@ export class Executor {
779
932
  bool: 'boolean',
780
933
  str: 'string',
781
934
  arr: 'object',
935
+ seq: 'object',
782
936
  rec: 'object',
783
937
  undef: 'undefined',
784
938
  }[v.k];
@@ -864,7 +1018,7 @@ export class Executor {
864
1018
  }
865
1019
  const base = this.ev(node.expression, f, pc);
866
1020
  if (name === 'length') {
867
- if (base.k === 'arr')
1021
+ if (base.k === 'arr' || base.k === 'seq')
868
1022
  return base.len;
869
1023
  if (base.k === 'str')
870
1024
  return base.c !== undefined ? intLit(BigInt(base.c.length)) : { k: 'int', t: `(str.len ${base.t})` };
@@ -883,12 +1037,27 @@ export class Executor {
883
1037
  throw new Unsupported('index is not an integer value');
884
1038
  if (base.k === 'arr')
885
1039
  return this.readSlot(base, index, f, pc);
1040
+ if (base.k === 'seq')
1041
+ return this.readElement(base, index, f, pc);
886
1042
  if (base.k === 'str') {
887
1043
  this.oblige(f, pc, and(this.le(intLit(0n), index).t, this.lt(index, { k: 'int', t: `(str.len ${base.t})` }).t));
888
1044
  return { k: 'str', t: `(str.at ${base.t} ${index.t})` };
889
1045
  }
890
1046
  throw new Unsupported('indexing something other than an array or string');
891
1047
  }
1048
+ /** `xs[i]` of an array of any length: the index must be inside it, and the element is one of the domain. */
1049
+ readElement(seq, index, f, pc) {
1050
+ this.oblige(f, pc, and(this.le(intLit(0n), index).t, this.lt(index, seq.len).t));
1051
+ const t = `(select ${seq.data} ${index.t})`;
1052
+ if (seq.elem === 'bool')
1053
+ return bool(t);
1054
+ if (seq.elem === 'big')
1055
+ return { k: 'big', t };
1056
+ // Every element of an array parameter is in the int range, as a parameter is; this is that fact for this one.
1057
+ const limit = this.intLimit ?? maxSafe;
1058
+ this.assume(f, pc, `(and (<= (- ${limit}) ${t}) (<= ${t} ${limit}))`);
1059
+ return { k: 'int', t };
1060
+ }
892
1061
  readSlot(arr, index, f, pc) {
893
1062
  this.oblige(f, pc, and(this.le(intLit(0n), index).t, this.lt(index, arr.len).t));
894
1063
  if (index.c !== undefined) {
@@ -908,6 +1077,13 @@ export class Executor {
908
1077
  return result;
909
1078
  }
910
1079
  arrayLiteral(node, f, pc) {
1080
+ const only = node.elements.length === 1 ? node.elements[0] : undefined;
1081
+ if (only !== undefined && ts.isSpreadElement(only)) {
1082
+ // `[...xs]` of an array of any length is a copy of it.
1083
+ const source = this.ev(only.expression, f, pc);
1084
+ if (source.k === 'seq')
1085
+ return { ...source, id: { escaped: false } };
1086
+ }
911
1087
  let out = { k: 'arr', len: intLit(0n), slots: [], id: { escaped: false } };
912
1088
  for (const element of node.elements) {
913
1089
  if (ts.isSpreadElement(element)) {
@@ -1150,11 +1326,9 @@ export class Executor {
1150
1326
  return bool(p === q ? `(not (fp.isNaN ${p}))` : `(fp.eq ${p} ${q})`);
1151
1327
  }
1152
1328
  if (a.k !== b.k) {
1153
- if ((a.k === 'arr' || a.k === 'rec') && (b.k === 'arr' || b.k === 'rec'))
1154
- return F;
1155
1329
  return F;
1156
1330
  }
1157
- if (a.k === 'rec' || a.k === 'arr')
1331
+ if (a.k === 'rec' || a.k === 'arr' || a.k === 'seq')
1158
1332
  throw new Unsupported('=== on objects compares references');
1159
1333
  const [p, q] = sorted(a.t, b.t);
1160
1334
  return bool(p === q ? 'true' : `(= ${p} ${q})`);
@@ -1231,6 +1405,16 @@ export class Executor {
1231
1405
  const arr = f.env.get(target.expression.text);
1232
1406
  const index = this.ev(target.argumentExpression, f, pc);
1233
1407
  const value = this.escape(this.ev(node.right, f, pc));
1408
+ if (arr?.k === 'seq' && index.k === 'int') {
1409
+ if (arr.id.escaped)
1410
+ throw new Unsupported('mutation of an array another name can reach');
1411
+ if (value.k !== arr.elem)
1412
+ throw new Unsupported(`an array of ${arr.elem} elements is given a ${value.k}`);
1413
+ this.oblige(f, pc, and(this.le(intLit(0n), index).t, this.lt(index, arr.len).t));
1414
+ const data = `(store ${arr.data} ${index.t} ${value.t})`;
1415
+ this.setVar(f, target.expression.text, { ...arr, data });
1416
+ return value;
1417
+ }
1234
1418
  if (arr?.k !== 'arr' || index.k !== 'int')
1235
1419
  throw new Unsupported('indexed assignment only on arrays with integer indexes');
1236
1420
  if (arr.id.escaped)
@@ -1256,7 +1440,7 @@ export class Executor {
1256
1440
  slots.push({ k: 'undef' });
1257
1441
  else if (slots.length > 0) {
1258
1442
  this.assume(f, pc, this.implies(when, this.lt(arr.len, intLit(BigInt(slots.length))).t));
1259
- const why = `arrays hold at most ${slots.length} elements here`;
1443
+ const why = `arrays hold at most ${plural(slots.length, 'element')} here`;
1260
1444
  if (!this.bounded.includes(why))
1261
1445
  this.bounded.push(why);
1262
1446
  }
@@ -1334,6 +1518,8 @@ export class Executor {
1334
1518
  const target = this.ev(receiver, f, pc);
1335
1519
  if (target.k === 'str')
1336
1520
  return this.stringMethod(target, name, args, f, pc);
1521
+ if (target.k === 'seq')
1522
+ return this.seqMethod(target, receiver, name, args, f, pc, statement);
1337
1523
  if (target.k !== 'arr')
1338
1524
  throw new Unsupported(`method ${name} on a ${target.k}`);
1339
1525
  const arr = target;
@@ -1461,6 +1647,46 @@ export class Executor {
1461
1647
  }
1462
1648
  throw new Unsupported(`array method ${name} does not lower`);
1463
1649
  }
1650
+ /** What an array of any length supports: copying, push and pop (on a copy), length and indexing are elsewhere. */
1651
+ seqMethod(seq, receiver, name, args, f, pc, statement) {
1652
+ const mutate = (next) => {
1653
+ if (!ts.isIdentifier(receiver))
1654
+ throw new Unsupported(`${name} on something other than a named array`);
1655
+ if (seq.id.escaped)
1656
+ throw new Unsupported('mutation of an array another name can reach');
1657
+ this.setVar(f, receiver.text, next);
1658
+ };
1659
+ const one = intLit(1n);
1660
+ switch (name) {
1661
+ case 'slice':
1662
+ if (args.length !== 0)
1663
+ throw new Unsupported('slice of an array of any length takes no arguments here');
1664
+ return { ...seq, id: { escaped: false } };
1665
+ case 'push': {
1666
+ if (args.length !== 1)
1667
+ throw new Unsupported('push takes one value here');
1668
+ if (!statement)
1669
+ throw new Unsupported('the result of push is not modelled');
1670
+ const value = this.escape(this.ev(args[0], f, pc));
1671
+ if (value.k !== seq.elem)
1672
+ throw new Unsupported(`an array of ${seq.elem} elements is given a ${value.k}`);
1673
+ const len = this.addLen(seq.len, one);
1674
+ mutate({ ...seq, len, data: `(store ${seq.data} ${seq.len.t} ${value.t})` });
1675
+ return { k: 'undef' };
1676
+ }
1677
+ case 'pop': {
1678
+ if (args.length !== 0)
1679
+ throw new Unsupported('pop takes no arguments');
1680
+ // Popping an empty array gives undefined in JavaScript; that is not modelled, so it must not happen.
1681
+ this.oblige(f, pc, this.lt(intLit(0n), seq.len).t);
1682
+ const last = { k: 'int', t: `(- ${seq.len.t} 1)` };
1683
+ const value = this.readElement(seq, last, f, pc);
1684
+ mutate({ ...seq, len: last });
1685
+ return value;
1686
+ }
1687
+ }
1688
+ throw new Unsupported(`array method ${name} does not lower on an array of any length`);
1689
+ }
1464
1690
  /** Insertion sort as a fixed network of guarded swaps; stable, as `Array.prototype.sort` is. */
1465
1691
  sort(arr, args, receiver, mutate, f, pc) {
1466
1692
  if (args.length !== 1)
@@ -0,0 +1,28 @@
1
+ import ts from 'typescript';
2
+ /** Resolution options as JSON: every path absolute, no `baseUrl` (it is folded into `paths`). */
3
+ export type ResolutionOptions = Record<string, unknown>;
4
+ export interface Resolution {
5
+ /** The tsconfig the options come from. */
6
+ file: string;
7
+ options: ResolutionOptions;
8
+ }
9
+ /** The nearest `tsconfig.json` in `dir` or above it. */
10
+ export declare function nearestTsconfig(dir: string): string | undefined;
11
+ /** The resolution options of `file` and everything it extends (relative files and packages in node_modules). */
12
+ export declare function readResolutionOf(file: string, strict: boolean): ResolutionOptions;
13
+ /**
14
+ * The tsconfig a project's laws are compiled with: `"tsconfig": "<path>"` in tslaws.json, else the nearest tsconfig.json
15
+ * above the project; none for `"tsconfig": false` or when there is no file. An explicit path that is missing or broken is
16
+ * an error; a discovered file that cannot be read is skipped.
17
+ */
18
+ export declare function readResolution(cwd: string): Resolution | undefined;
19
+ /** The same options as compiler options for the API (every value is plain JSON, so nothing needs converting). */
20
+ export declare function resolutionCompilerOptions(options: ResolutionOptions | undefined): ts.CompilerOptions;
21
+ /** Whether `file` lies inside `dir`. */
22
+ export declare function isInside(dir: string, file: string): boolean;
23
+ /**
24
+ * The directory the compiler's `rootDir` must be so that every source file a `paths` target can reach lies under it: the
25
+ * deepest common ancestor of the project and the directories the targets name (up to the first `*`). Targets on another
26
+ * drive are left out; the project itself when no target leaves it.
27
+ */
28
+ export declare function commonRoot(cwd: string, options: ResolutionOptions | undefined): string;