tla-ts 0.0.10-dev.3a85c3a9e → 0.0.10-dev.5ffc55ce5

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/dist/deciders.cjs +35 -35
  2. package/dist/deciders.js +29 -29
  3. package/dist/index.d.cts +1 -1
  4. package/dist/index.d.ts +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +25 -25
  8. package/dist/prove.js +57 -57
  9. package/dist/run.cjs +32 -34
  10. package/dist/run.js +31 -33
  11. package/dist/transfer.cjs +35 -35
  12. package/dist/transfer.js +28 -28
  13. package/dist/worker.cjs +1 -1
  14. package/dist/worker.js +1 -1
  15. package/package.json +1 -1
  16. package/src/bags.ts +47 -28
  17. package/src/check-trace.ts +2 -16
  18. package/src/check.ts +143 -61
  19. package/src/cli/runtime-invariants.ts +20 -56
  20. package/src/cli/tlc-arguments.ts +2 -2
  21. package/src/cli/tlc-output.ts +4 -5
  22. package/src/cli/tlc.ts +26 -7
  23. package/src/dfid.ts +9 -2
  24. package/src/environment.ts +28 -5
  25. package/src/evaluate.ts +9 -3
  26. package/src/exit-codes.ts +2 -0
  27. package/src/liveness-checker.ts +45 -4
  28. package/src/parallel-worker.ts +8 -2
  29. package/src/parallel.ts +5 -0
  30. package/src/prover/smt/solver/ast.ts +1 -1
  31. package/src/prover/smt/solver/context.ts +6 -2
  32. package/src/prover/smt/solver/euf/egraph.ts +1 -1
  33. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  34. package/src/prover/smt/solver/factor.ts +36 -14
  35. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  36. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  37. package/src/prover/smt/solver/goal.ts +2 -0
  38. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  39. package/src/prover/smt/solver/lp/containers.ts +7 -1
  40. package/src/prover/smt/solver/lp/cross-nested.ts +1 -3
  41. package/src/prover/smt/solver/lp/nex-creator.ts +3 -2
  42. package/src/prover/smt/solver/lp/nex.ts +2 -1
  43. package/src/prover/smt/solver/lp/nla-basics.ts +46 -1
  44. package/src/prover/smt/solver/lp/nla-core.ts +26 -6
  45. package/src/prover/smt/solver/lp/nla-grobner.ts +156 -79
  46. package/src/prover/smt/solver/lp/nra-solver.ts +138 -95
  47. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  48. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  49. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  50. package/src/prover/smt/solver/lp/pdd.ts +725 -289
  51. package/src/prover/smt/solver/muz/dl-context.ts +8 -2
  52. package/src/prover/smt/solver/muz/spacer-context.ts +1 -0
  53. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  54. package/src/prover/smt/solver/nlsat/algebraic.ts +194 -89
  55. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  56. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  57. package/src/prover/smt/solver/nlsat/levelwise.ts +464 -240
  58. package/src/prover/smt/solver/nlsat/polynomial.ts +2400 -680
  59. package/src/prover/smt/solver/nlsat/solver.ts +74 -71
  60. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  61. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  62. package/src/prover/smt/solver/nlsat/upolynomial.ts +40 -17
  63. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  64. package/src/prover/smt/solver/opt-solver.ts +2 -3
  65. package/src/prover/smt/solver/rlimit.ts +13 -0
  66. package/src/prover/smt/solver/sat/sat-tactic.ts +2 -1
  67. package/src/prover/smt/solver/seq-derive.ts +3 -6
  68. package/src/prover/smt/solver/smtlib-parser.ts +10 -10
  69. package/src/prover/smt/solver/smtlib-script.ts +91 -28
  70. package/src/prover/smt/solver/tactic.ts +14 -5
  71. package/src/prover/smt/solver/theory-lra-internalize.ts +8 -0
  72. package/src/prover/zenon/equality-rules.ts +24 -0
  73. package/src/prover/zenon/expr.ts +21 -0
  74. package/src/prover/zenon/index-table.ts +2 -0
  75. package/src/prover/zenon/rules.ts +2 -1
  76. package/src/resolve.ts +2 -3
  77. package/src/runtime.ts +6 -0
  78. package/src/sany/generator-expressions.ts +6 -13
  79. package/src/search.ts +67 -29
  80. package/src/simulate.ts +3 -0
  81. package/src/standard-definitions.ts +4 -0
  82. package/src/tlc/order.ts +14 -3
  83. package/src/tlc/tlcext-operators.ts +61 -16
  84. package/src/tlc/trace-spec.ts +2 -3
@@ -1,5 +1,3 @@
1
- // Deviation from Z3: nodes are never freed, so node indices match Z3 only until its first
2
- // collection.
3
1
  import { PddMemoryOutError } from "../../../../errors";
4
2
  import { getGcd, Rational } from "../rational";
5
3
  import { shrink } from "../array";
@@ -12,7 +10,7 @@ const MINUS_OP = 4;
12
10
  const MUL_OP = 5;
13
11
  const REDUCE_OP = 6;
14
12
  const NO_OP = 10;
15
- const INITIAL_FREE_NODES = 1024;
13
+ const MAX_RC = (1 << 10) - 1;
16
14
 
17
15
  interface PddMonomial {
18
16
  coeff: Rational;
@@ -29,9 +27,9 @@ interface PddPower {
29
27
  degree: number;
30
28
  }
31
29
 
32
- interface PddFactor {
33
- lc: Pdd;
34
- rest: Pdd;
30
+ interface FactorEntry {
31
+ lc: number;
32
+ rest: number;
35
33
  }
36
34
 
37
35
  interface PddVarFactors {
@@ -51,68 +49,91 @@ interface CommonFactors {
51
49
  secondCoeff: Rational;
52
50
  }
53
51
 
52
+ const getNodeKey = (level: number, lo: number, hi: number) => `${level},${lo},${hi}`;
53
+
54
54
  export class PddManager {
55
55
  private levels: number[] = [];
56
56
  private los: number[] = [];
57
57
  private his: number[] = [];
58
+ private refcounts: number[] = [];
58
59
  private values: Rational[] = [];
60
+ private opCache = new Map<number, number>();
61
+ private factorCache = new Map<string, FactorEntry>();
59
62
  private nodeTable = new Map<string, number>();
60
63
  private valueTable = new Map<string, number>();
61
- private opCache = new Map<string, number>();
62
- private factorCache = new Map<string, PddFactor>();
63
- private degrees: number[] = [];
64
- private numAllocated = 0;
65
- private maxNumNodes = 1 << 24;
66
- private isApplying = false;
64
+ private pddStack: number[] = [];
65
+ private pddStackSize = 0;
67
66
  private var2pdd: number[] = [];
68
67
  var2level: number[] = [];
69
68
  level2var: number[] = [];
69
+ private freeNodes: number[] = [];
70
+ private dmarks: number[] = [];
71
+ private dmarkLevel = 0;
72
+ private degrees: number[] = [];
73
+ private degreeTodo: number[] = [];
74
+ private maxNumNodes = 1 << 24;
75
+ private freeValues: number[] = [];
76
+ private freezeValue = Rational.zero;
70
77
 
71
78
  constructor(numVars: number) {
72
79
  this.initNodes(Array.from({ length: numVars }, (_, index) => index));
73
80
  }
74
81
 
75
82
  reset(level2var: number[]) {
83
+ this.opCache.clear();
84
+ this.factorCache.clear();
85
+ this.nodeTable.clear();
76
86
  this.levels = [];
77
87
  this.los = [];
78
88
  this.his = [];
89
+ this.refcounts = [];
90
+ this.dmarks = [];
91
+ this.degrees = [];
92
+ this.freeNodes = [];
93
+ this.pddStackSize = 0;
79
94
  this.values = [];
80
- this.nodeTable.clear();
95
+ this.freeValues = [];
81
96
  this.valueTable.clear();
82
- this.opCache.clear();
83
- this.factorCache.clear();
84
- this.degrees = [];
85
97
  this.initNodes(level2var);
86
98
  }
87
99
 
100
+ setMaxNumNodes(limit: number) {
101
+ this.maxNumNodes = limit + this.level2var.length;
102
+ }
103
+
104
+ numNodes() {
105
+ return this.levels.length - this.freeNodes.length;
106
+ }
107
+
88
108
  private initNodes(level2var: number[]) {
89
109
  for (let index = 0; index < NO_OP; index++) {
90
110
  this.levels.push(0);
91
111
  this.los.push(0);
92
112
  this.his.push(0);
113
+ this.refcounts.push(MAX_RC);
114
+ this.dmarks.push(0);
115
+ this.degrees.push(0);
93
116
  }
94
117
  this.los[ONE_PDD] = 1;
95
118
  this.values.push(Rational.zero, Rational.one);
96
- this.numAllocated = NO_OP + INITIAL_FREE_NODES + level2var.length;
97
- this.var2pdd = [];
98
- this.var2level = [];
99
- this.level2var = [];
100
- for (let level = 0; level < level2var.length; level++) {
119
+ this.allocFreeNodes(1024 + level2var.length);
120
+ this.initVars(level2var);
121
+ }
122
+
123
+ private initVars(level2var: number[]) {
124
+ const count = level2var.length;
125
+ this.level2var = Array.from({ length: count }, () => 0);
126
+ this.var2level = Array.from({ length: count }, () => 0);
127
+ this.var2pdd = Array.from({ length: count }, () => 0);
128
+ for (let level = 0; level < count; level++) {
101
129
  const variable = level2var[level];
102
130
  this.var2pdd[variable] = this.makeNode(level, ZERO_PDD, ONE_PDD);
131
+ this.refcounts[this.var2pdd[variable]] = MAX_RC;
103
132
  this.var2level[variable] = level;
104
133
  this.level2var[level] = variable;
105
134
  }
106
135
  }
107
136
 
108
- setMaxNumNodes(limit: number) {
109
- this.maxNumNodes = limit + this.level2var.length;
110
- }
111
-
112
- numNodes() {
113
- return this.levels.length;
114
- }
115
-
116
137
  isVal(node: number) {
117
138
  return this.his[node] === 0;
118
139
  }
@@ -137,13 +158,26 @@ export class PddManager {
137
158
  return this.values[this.los[node]];
138
159
  }
139
160
 
140
- mkVar(variable: number) {
161
+ incRef(node: number) {
162
+ if (this.refcounts[node] !== MAX_RC) this.refcounts[node]++;
163
+ }
164
+
165
+ decRef(node: number) {
166
+ if (this.refcounts[node] !== MAX_RC) this.refcounts[node]--;
167
+ }
168
+
169
+ private reserveVar(variable: number) {
141
170
  while (this.var2level.length <= variable) {
142
171
  const next = this.var2level.length;
143
172
  this.var2pdd.push(this.makeNode(next, ZERO_PDD, ONE_PDD));
173
+ this.refcounts[this.var2pdd[next]] = MAX_RC;
144
174
  this.var2level.push(next);
145
175
  this.level2var.push(next);
146
176
  }
177
+ }
178
+
179
+ mkVar(variable: number) {
180
+ this.reserveVar(variable);
147
181
  return new Pdd(this, this.var2pdd[variable]);
148
182
  }
149
183
 
@@ -175,151 +209,228 @@ export class PddManager {
175
209
  return new Pdd(this, this.apply(first.root, second.root, REDUCE_OP));
176
210
  }
177
211
 
212
+ mulValue(value: Rational, poly: Pdd) {
213
+ const constant = this.mkVal(value);
214
+ const result = new Pdd(this, this.apply(constant.root, poly.root, MUL_OP));
215
+ constant.release();
216
+ return result;
217
+ }
218
+
219
+ addValue(value: Rational, poly: Pdd) {
220
+ const constant = this.mkVal(value);
221
+ const result = new Pdd(this, this.apply(constant.root, poly.root, ADD_OP));
222
+ constant.release();
223
+ return result;
224
+ }
225
+
178
226
  minus(poly: Pdd) {
179
- return new Pdd(
180
- this,
181
- this.whileApplying(() => this.minusRec(poly.root)),
182
- );
227
+ const size = this.pddStackSize;
228
+ try {
229
+ for (let count = 0; ; count++) {
230
+ try {
231
+ return new Pdd(this, this.minusRec(poly.root));
232
+ } catch (error) {
233
+ if (!(error instanceof PddMemoryOutError)) throw error;
234
+ this.tryGc();
235
+ if (count > 0) this.maxNumNodes *= 2;
236
+ }
237
+ }
238
+ } finally {
239
+ this.pddStackSize = size;
240
+ }
183
241
  }
184
242
 
185
- pow(poly: Pdd, exponent: number): Pdd {
186
- if (exponent === 0) return this.one();
187
- if (exponent === 1 || poly.isZero() || poly.isOne()) return poly;
188
- if (poly.isVal()) return this.mkVal(poly.val().pow(exponent));
189
- const half = this.pow(this.mul(poly, poly), Math.floor(exponent / 2));
190
- return exponent % 2 === 1 ? this.mul(half, poly) : half;
243
+ pow(poly: Pdd, exponent: number) {
244
+ return new Pdd(this, this.powNode(poly.root, exponent));
191
245
  }
192
246
 
193
- private apply(first: number, second: number, op: number) {
194
- return this.whileApplying(() => this.applyRec(first, second, op));
247
+ private powNode(node: number, exponent: number) {
248
+ if (exponent === 0) return ONE_PDD;
249
+ if (exponent === 1) return node;
250
+ if (node === ZERO_PDD) return ZERO_PDD;
251
+ if (node === ONE_PDD) return ONE_PDD;
252
+ if (this.isVal(node)) return this.imkVal(this.val(node).pow(exponent));
253
+ return this.powRec(node, exponent);
254
+ }
255
+
256
+ private powRec(node: number, exponent: number): number {
257
+ if (exponent === 1) return node;
258
+ const half = this.powRec(this.apply(node, node, MUL_OP), Math.floor(exponent / 2));
259
+ return exponent % 2 === 1 ? this.apply(half, node, MUL_OP) : half;
195
260
  }
196
261
 
197
- private whileApplying(compute: () => number) {
198
- this.isApplying = true;
262
+ private apply(first: number, second: number, op: number) {
263
+ const size = this.pddStackSize;
199
264
  try {
200
- return compute();
265
+ for (let count = 0; ; count++) {
266
+ try {
267
+ return this.applyRec(first, second, op);
268
+ } catch (error) {
269
+ if (!(error instanceof PddMemoryOutError)) throw error;
270
+ this.tryGc();
271
+ if (count > 0) this.maxNumNodes *= 2;
272
+ }
273
+ }
201
274
  } finally {
202
- this.isApplying = false;
275
+ this.pddStackSize = size;
203
276
  }
204
277
  }
205
278
 
206
279
  private applyRec(first: number, second: number, op: number): number {
280
+ let p = first;
281
+ let q = second;
207
282
  switch (op) {
208
283
  case SUB_OP:
209
- if (second === ZERO_PDD) return first;
210
- if (this.isVal(first) && this.isVal(second)) {
211
- return this.imkVal(this.val(first).sub(this.val(second)));
212
- }
284
+ if (q === ZERO_PDD) return p;
285
+ if (this.isVal(p) && this.isVal(q)) return this.imkVal(this.val(p).sub(this.val(q)));
213
286
  break;
214
287
  case ADD_OP:
215
- if (first === ZERO_PDD) return second;
216
- if (second === ZERO_PDD) return first;
217
- if (this.isVal(first) && this.isVal(second)) {
218
- return this.imkVal(this.val(first).add(this.val(second)));
219
- }
220
- if (this.isVal(first) || (!this.isVal(second) && this.level(first) < this.level(second))) {
221
- return this.applyRec(second, first, op);
288
+ if (p === ZERO_PDD) return q;
289
+ if (q === ZERO_PDD) return p;
290
+ if (this.isVal(p) && this.isVal(q)) return this.imkVal(this.val(p).add(this.val(q)));
291
+ if (this.isVal(p) || (!this.isVal(q) && this.level(p) < this.level(q))) {
292
+ p = second;
293
+ q = first;
222
294
  }
223
295
  break;
224
296
  case MUL_OP:
225
- if (first === ZERO_PDD || second === ZERO_PDD) return ZERO_PDD;
226
- if (first === ONE_PDD) return second;
227
- if (second === ONE_PDD) return first;
228
- if (this.isVal(first) && this.isVal(second)) {
229
- return this.imkVal(this.val(first).mul(this.val(second)));
230
- }
231
- if (this.isVal(first) || (!this.isVal(second) && this.level(first) < this.level(second))) {
232
- return this.applyRec(second, first, op);
297
+ if (p === ZERO_PDD || q === ZERO_PDD) return ZERO_PDD;
298
+ if (p === ONE_PDD) return q;
299
+ if (q === ONE_PDD) return p;
300
+ if (this.isVal(p) && this.isVal(q)) return this.imkVal(this.val(p).mul(this.val(q)));
301
+ if (this.isVal(p) || (!this.isVal(q) && this.level(p) < this.level(q))) {
302
+ p = second;
303
+ q = first;
233
304
  }
234
305
  break;
235
- case REDUCE_OP:
236
- if (second === ZERO_PDD || this.isVal(first)) return first;
237
- if (this.degree(first) < this.degree(second)) return first;
238
- if (this.level(this.firstLeading(second)) > this.level(first)) return first;
306
+ default:
307
+ if (q === ZERO_PDD || this.isVal(p)) return p;
308
+ if (this.degree(p) < this.degree(q)) return p;
309
+ if (this.level(this.firstLeading(q)) > this.level(p)) return p;
239
310
  break;
240
311
  }
241
- const key = `${op},${first},${second}`;
242
- const cached = this.opCache.get(key);
243
- if (cached !== undefined) return cached;
244
- const result = this.computeApply(first, second, op);
245
- this.opCache.set(key, result);
246
- return result;
247
- }
248
-
249
- private computeApply(first: number, second: number, op: number) {
250
- const firstLevel = this.level(first);
251
- const secondLevel = this.level(second);
252
- const firstLo = this.lo(first);
253
- const firstHi = this.hi(first);
312
+ // Z3's op_entry equality compares the cached first operand with the new second one, so
313
+ // only an operation on two equal operands finds its cached result.
314
+ // Deviation from Z3: on a hash collision Z3 returns that result for unequal operands too.
315
+ const isCached = p === q;
316
+ if (isCached) {
317
+ const cached = this.opCache.get(q * NO_OP + op);
318
+ if (cached !== undefined) return cached;
319
+ }
320
+ let result: number;
321
+ const levelP = this.level(p);
322
+ const levelQ = this.level(q);
323
+ let npop = 2;
254
324
  switch (op) {
255
- case ADD_OP: {
256
- if (this.isVal(second) || firstLevel !== secondLevel) {
257
- return this.makeNode(firstLevel, this.applyRec(firstLo, second, op), firstHi);
258
- }
259
- const lo = this.applyRec(firstLo, this.lo(second), op);
260
- return this.makeNode(firstLevel, lo, this.applyRec(firstHi, this.hi(second), op));
261
- }
262
- case SUB_OP: {
263
- if (this.isVal(first) || (!this.isVal(second) && firstLevel < secondLevel)) {
264
- const lo = this.applyRec(first, this.lo(second), op);
265
- return this.makeNode(secondLevel, lo, this.minusRec(this.hi(second)));
266
- }
267
- if (this.isVal(second) || firstLevel > secondLevel) {
268
- return this.makeNode(firstLevel, this.applyRec(firstLo, second, op), firstHi);
269
- }
270
- const lo = this.applyRec(firstLo, this.lo(second), op);
271
- return this.makeNode(firstLevel, lo, this.applyRec(firstHi, this.hi(second), op));
272
- }
273
- case MUL_OP: {
274
- if (this.isVal(second) || firstLevel !== secondLevel) {
275
- const lo = this.applyRec(firstLo, second, op);
276
- return this.makeNode(firstLevel, lo, this.applyRec(firstHi, second, op));
325
+ case ADD_OP:
326
+ if (this.isVal(q)) {
327
+ this.push(this.applyRec(this.lo(p), q, op));
328
+ result = this.makeNode(levelP, this.read(1), this.hi(p));
329
+ npop = 1;
330
+ } else if (levelP === levelQ) {
331
+ this.push(this.applyRec(this.lo(p), this.lo(q), op));
332
+ this.push(this.applyRec(this.hi(p), this.hi(q), op));
333
+ result = this.makeNode(levelP, this.read(2), this.read(1));
334
+ } else {
335
+ this.push(this.applyRec(this.lo(p), q, op));
336
+ result = this.makeNode(levelP, this.read(1), this.hi(p));
337
+ npop = 1;
277
338
  }
278
- const ac = this.applyRec(firstHi, this.hi(second), op);
279
- const ad = this.applyRec(firstHi, this.lo(second), op);
280
- const bc = this.applyRec(firstLo, this.hi(second), op);
281
- const bd = this.applyRec(firstLo, this.lo(second), op);
282
- const sum = this.applyRec(ad, bc, ADD_OP);
283
- if (!this.isVal(sum) && this.level(sum) === firstLevel) {
284
- const hi = this.applyRec(ac, this.hi(sum), ADD_OP);
285
- return this.makeNode(firstLevel, bd, this.makeNode(firstLevel, this.lo(sum), hi));
339
+ break;
340
+ case SUB_OP:
341
+ if (this.isVal(p) || (!this.isVal(q) && levelP < levelQ)) {
342
+ this.push(this.applyRec(p, this.lo(q), op));
343
+ this.push(this.minusRec(this.hi(q)));
344
+ result = this.makeNode(levelQ, this.read(2), this.read(1));
345
+ } else if (this.isVal(q) || levelP > levelQ) {
346
+ this.push(this.applyRec(this.lo(p), q, op));
347
+ result = this.makeNode(levelP, this.read(1), this.hi(p));
348
+ npop = 1;
349
+ } else {
350
+ this.push(this.applyRec(this.lo(p), this.lo(q), op));
351
+ this.push(this.applyRec(this.hi(p), this.hi(q), op));
352
+ result = this.makeNode(levelP, this.read(2), this.read(1));
286
353
  }
287
- return this.makeNode(firstLevel, bd, this.makeNode(firstLevel, sum, ac));
288
- }
289
- default: {
290
- if (this.level(this.firstLeading(second)) >= firstLevel) {
291
- return this.reduceOnMatch(first, second);
354
+ break;
355
+ case MUL_OP:
356
+ if (this.isVal(q) || levelP !== levelQ) {
357
+ this.push(this.applyRec(this.lo(p), q, op));
358
+ this.push(this.applyRec(this.hi(p), q, op));
359
+ result = this.makeNode(levelP, this.read(2), this.read(1));
360
+ } else {
361
+ this.push(this.applyRec(this.hi(p), this.hi(q), op));
362
+ this.push(this.applyRec(this.hi(p), this.lo(q), op));
363
+ this.push(this.applyRec(this.lo(p), this.hi(q), op));
364
+ this.push(this.applyRec(this.lo(p), this.lo(q), op));
365
+ const ac = this.read(4);
366
+ const ad = this.read(3);
367
+ const bc = this.read(2);
368
+ const bd = this.read(1);
369
+ this.push(this.applyRec(ad, bc, ADD_OP));
370
+ const sum = this.read(1);
371
+ if (!this.isVal(sum) && this.level(sum) === levelP) {
372
+ this.push(this.applyRec(ac, this.hi(sum), ADD_OP));
373
+ this.push(this.makeNode(levelP, this.lo(sum), this.read(1)));
374
+ result = this.makeNode(levelP, bd, this.read(1));
375
+ npop = 7;
376
+ } else {
377
+ this.push(this.makeNode(levelP, sum, ac));
378
+ result = this.makeNode(levelP, bd, this.read(1));
379
+ npop = 6;
380
+ }
292
381
  }
293
- const lo = this.applyRec(firstLo, second, op);
294
- const hi = this.applyRec(firstHi, second, op);
295
- if (lo === firstLo && hi === firstHi) return first;
296
- if (this.level(lo) < firstLevel && this.level(hi) <= firstLevel) {
297
- return this.makeNode(firstLevel, lo, hi);
382
+ break;
383
+ default:
384
+ if (this.level(this.firstLeading(q)) < levelP) {
385
+ this.push(this.applyRec(this.lo(p), q, op));
386
+ this.push(this.applyRec(this.hi(p), q, op));
387
+ const lo = this.read(2);
388
+ const hi = this.read(1);
389
+ if (lo === this.lo(p) && hi === this.hi(p)) {
390
+ result = p;
391
+ } else if (this.level(lo) < levelP && this.level(hi) <= levelP) {
392
+ result = this.makeNode(levelP, lo, hi);
393
+ } else {
394
+ this.push(this.applyRec(hi, this.var2pdd[this.var(p)], MUL_OP));
395
+ this.push(this.applyRec(this.read(1), lo, ADD_OP));
396
+ result = this.read(1);
397
+ npop = 4;
398
+ }
399
+ } else {
400
+ result = this.reduceOnMatch(p, q);
401
+ npop = 0;
298
402
  }
299
- const product = this.applyRec(hi, this.var2pdd[this.var(first)], MUL_OP);
300
- return this.applyRec(product, lo, ADD_OP);
301
- }
302
403
  }
404
+ this.pop(npop);
405
+ if (isCached) this.opCache.set(q * NO_OP + op, result);
406
+ return result;
303
407
  }
304
408
 
305
409
  private minusRec(node: number): number {
306
410
  if (node === ZERO_PDD) return ZERO_PDD;
307
411
  if (this.isVal(node)) return this.imkVal(this.val(node).neg());
308
- const key = `${MINUS_OP},${node},${node}`;
309
- const cached = this.opCache.get(key);
412
+ const cached = this.opCache.get(node * NO_OP + MINUS_OP);
310
413
  if (cached !== undefined) return cached;
311
- const lo = this.minusRec(this.lo(node));
312
- const result = this.makeNode(this.level(node), lo, this.minusRec(this.hi(node)));
313
- this.opCache.set(key, result);
414
+ this.push(this.minusRec(this.lo(node)));
415
+ this.push(this.minusRec(this.hi(node)));
416
+ const result = this.makeNode(this.level(node), this.read(2), this.read(1));
417
+ this.pop(2);
418
+ this.opCache.set(node * NO_OP + MINUS_OP, result);
314
419
  return result;
315
420
  }
316
421
 
317
422
  private reduceOnMatch(first: number, second: number) {
318
423
  let current = first;
424
+ this.push(current);
319
425
  while (this.lmOccurs(second, current)) {
320
- const product = this.applyRec(this.ltQuotient(second, current), second, MUL_OP);
321
- current = this.applyRec(current, product, ADD_OP);
426
+ this.push(this.ltQuotient(second, current));
427
+ this.push(this.applyRec(this.read(1), second, MUL_OP));
428
+ this.push(this.applyRec(current, this.read(1), ADD_OP));
429
+ current = this.read(1);
430
+ this.pop(4);
431
+ this.push(current);
322
432
  }
433
+ this.pop(1);
323
434
  return current;
324
435
  }
325
436
 
@@ -359,22 +470,45 @@ export class PddManager {
359
470
  }
360
471
 
361
472
  private ltQuotientHi(first: number, second: number) {
362
- const quotient = this.ltQuotient(first, this.hi(second));
363
- return this.applyRec(this.var2pdd[this.var(second)], quotient, MUL_OP);
473
+ this.push(this.ltQuotient(first, this.hi(second)));
474
+ const result = this.applyRec(this.var2pdd[this.var(second)], this.read(1), MUL_OP);
475
+ this.pop(1);
476
+ return result;
364
477
  }
365
478
 
366
- trySpoly(first: Pdd, second: Pdd) {
479
+ trySpoly(first: Pdd, second: Pdd, result: Pdd) {
367
480
  const factors = this.commonFactors(first, second);
368
- if (factors === null) return null;
369
- let firstMultiplier = this.mkVal(factors.secondCoeff);
370
- for (let index = factors.second.length; index-- > 0;) {
371
- firstMultiplier = firstMultiplier.mul(this.mkVar(factors.second[index]));
372
- }
373
- let secondMultiplier = this.mkVal(factors.firstCoeff.neg());
374
- for (let index = factors.first.length; index-- > 0;) {
375
- secondMultiplier = secondMultiplier.mul(this.mkVar(factors.first[index]));
481
+ if (factors === null) return false;
482
+ const spoly = this.spoly(first, second, factors);
483
+ result.assign(spoly);
484
+ spoly.release();
485
+ return true;
486
+ }
487
+
488
+ private spoly(first: Pdd, second: Pdd, factors: CommonFactors) {
489
+ const firstMultiplier = this.mkVal(factors.secondCoeff);
490
+ try {
491
+ for (let index = factors.second.length; index-- > 0;) {
492
+ const variable = this.mkVar(factors.second[index]);
493
+ firstMultiplier.mulAssign(variable);
494
+ variable.release();
495
+ }
496
+ const secondMultiplier = this.mkVal(factors.firstCoeff.neg());
497
+ for (let index = factors.first.length; index-- > 0;) {
498
+ const variable = this.mkVar(factors.first[index]);
499
+ secondMultiplier.mulAssign(variable);
500
+ variable.release();
501
+ }
502
+ const firstProduct = firstMultiplier.mul(first);
503
+ const secondProduct = secondMultiplier.mul(second);
504
+ const result = firstProduct.add(secondProduct);
505
+ secondProduct.release();
506
+ firstProduct.release();
507
+ secondMultiplier.release();
508
+ return result;
509
+ } finally {
510
+ firstMultiplier.release();
376
511
  }
377
- return firstMultiplier.mul(first).add(secondMultiplier.mul(second));
378
512
  }
379
513
 
380
514
  private commonFactors(first: Pdd, second: Pdd): CommonFactors | null {
@@ -478,56 +612,109 @@ export class PddManager {
478
612
  return this.firstLeading(this.hi(node));
479
613
  }
480
614
 
481
- degree(node: number): number {
615
+ degree(node: number) {
482
616
  if (node === ZERO_PDD || node === ONE_PDD) return 0;
483
- const cached = this.degrees[node];
484
- if (cached !== undefined) return cached;
485
- const degree = this.isVal(node)
486
- ? 0
487
- : Math.max(this.degree(this.lo(node)), this.degree(this.hi(node)) + 1);
488
- this.degrees[node] = degree;
489
- return degree;
617
+ const dmarkLevel = this.dmarkLevel;
618
+ if (this.dmarks[node] === dmarkLevel) return this.degrees[node];
619
+ const todo = this.degreeTodo;
620
+ todo.push(node);
621
+ while (todo.length > 0) {
622
+ const current = todo[todo.length - 1];
623
+ if (this.dmarks[current] === dmarkLevel) {
624
+ todo.pop();
625
+ } else if (this.isVal(current)) {
626
+ this.degrees[current] = 0;
627
+ this.dmarks[current] = dmarkLevel;
628
+ } else {
629
+ const lo = this.lo(current);
630
+ const hi = this.hi(current);
631
+ if (this.dmarks[lo] !== dmarkLevel || this.dmarks[hi] !== dmarkLevel) {
632
+ todo.push(lo, hi);
633
+ } else {
634
+ this.degrees[current] = Math.max(this.degrees[lo], this.degrees[hi] + 1);
635
+ this.dmarks[current] = dmarkLevel;
636
+ }
637
+ }
638
+ }
639
+ return this.degrees[node];
490
640
  }
491
641
 
492
- factor(poly: Pdd, variable: number, degree: number): PddFactor {
642
+ factor(poly: Pdd, variable: number, degree: number, lc: Pdd, rest: Pdd) {
493
643
  const variableLevel = this.var2level[variable];
494
644
  if (degree === 0 || this.level(poly.root) < variableLevel) {
495
- return { lc: this.zero(), rest: poly };
645
+ const zero = this.zero();
646
+ lc.assign(zero);
647
+ zero.release();
648
+ rest.assign(poly);
649
+ return;
496
650
  }
497
651
  const key = `${poly.root},${variable},${degree}`;
498
652
  const cached = this.factorCache.get(key);
499
- if (cached !== undefined) return cached;
500
- const result = this.computeFactor(poly, variable, degree);
501
- this.factorCache.set(key, result);
502
- return result;
503
- }
504
-
505
- private computeFactor(poly: Pdd, variable: number, degree: number): PddFactor {
506
- const variableLevel = this.var2level[variable];
653
+ if (cached !== undefined) {
654
+ const cachedLc = new Pdd(this, cached.lc);
655
+ lc.assign(cachedLc);
656
+ cachedLc.release();
657
+ const cachedRest = new Pdd(this, cached.rest);
658
+ rest.assign(cachedRest);
659
+ cachedRest.release();
660
+ return;
661
+ }
507
662
  if (this.level(poly.root) > variableLevel) {
663
+ const lc1 = this.zero();
664
+ const rest1 = this.zero();
508
665
  const node = this.mkVar(poly.var());
509
- const hiFactor = this.factor(poly.hi(), variable, degree);
510
- const loFactor = this.factor(poly.lo(), variable, degree);
511
- const lc = hiFactor.lc.mul(node);
512
- const rest = hiFactor.rest.mul(node);
513
- return { lc: lc.add(loFactor.lc), rest: rest.add(loFactor.rest) };
514
- }
515
- let found = 0;
516
- let lc = poly;
517
- while (found < degree && !lc.isVal() && this.level(lc.root) === variableLevel) {
518
- found++;
519
- lc = lc.hi();
520
- }
521
- if (found < degree) return { lc: this.zero(), rest: poly };
522
- let rest = this.zero();
523
- let power = this.one();
524
- let current = poly;
525
- for (let index = 0; index < degree; index++) {
526
- rest = rest.add(power.mul(current.lo()));
527
- current = current.hi();
528
- power = power.mul(this.mkVar(variable));
529
- }
530
- return { lc, rest };
666
+ const hi = poly.hi();
667
+ this.factor(hi, variable, degree, lc, rest);
668
+ hi.release();
669
+ const lo = poly.lo();
670
+ this.factor(lo, variable, degree, lc1, rest1);
671
+ lo.release();
672
+ lc.mulAssign(node);
673
+ rest.mulAssign(node);
674
+ lc.addAssign(lc1);
675
+ rest.addAssign(rest1);
676
+ node.release();
677
+ rest1.release();
678
+ lc1.release();
679
+ } else {
680
+ let found = 0;
681
+ const current = poly.copy();
682
+ while (found < degree && !current.isVal() && this.level(current.root) === variableLevel) {
683
+ found++;
684
+ const hi = current.hi();
685
+ current.assign(hi);
686
+ hi.release();
687
+ }
688
+ if (found === degree) {
689
+ lc.assign(current);
690
+ current.assign(poly);
691
+ const zero = this.zero();
692
+ rest.assign(zero);
693
+ zero.release();
694
+ const power = this.one();
695
+ for (let index = 0; index < degree; index++) {
696
+ const lo = current.lo();
697
+ const term = power.mul(lo);
698
+ rest.addAssign(term);
699
+ term.release();
700
+ lo.release();
701
+ const hi = current.hi();
702
+ current.assign(hi);
703
+ const variablePdd = this.mkVar(variable);
704
+ power.mulAssign(variablePdd);
705
+ variablePdd.release();
706
+ hi.release();
707
+ }
708
+ power.release();
709
+ } else {
710
+ const zero = this.zero();
711
+ lc.assign(zero);
712
+ zero.release();
713
+ rest.assign(poly);
714
+ }
715
+ current.release();
716
+ }
717
+ this.factorCache.set(key, { lc: lc.root, rest: rest.root });
531
718
  }
532
719
 
533
720
  isBinary(node: number) {
@@ -605,14 +792,36 @@ export class PddManager {
605
792
  return vars;
606
793
  }
607
794
 
795
+ private push(node: number) {
796
+ this.pddStack[this.pddStackSize++] = node;
797
+ }
798
+
799
+ private pop(count: number) {
800
+ this.pddStackSize -= count;
801
+ }
802
+
803
+ private read(index: number) {
804
+ return this.pddStack[this.pddStackSize - index];
805
+ }
806
+
608
807
  private imkVal(value: Rational) {
609
808
  if (value.isZero()) return ZERO_PDD;
610
809
  if (value.equals(Rational.one)) return ONE_PDD;
611
810
  const key = value.toString();
612
- const existing = this.valueTable.get(key);
613
- if (existing !== undefined) return existing;
614
- const node = this.insertNode(0, this.values.length, 0);
615
- this.values.push(value);
811
+ return this.valueTable.get(key) ?? this.initValue(value, key);
812
+ }
813
+
814
+ private initValue(value: Rational, key: string) {
815
+ let valueIndex = this.values.length;
816
+ if (this.freeValues.length === 0) {
817
+ this.values.push(value);
818
+ } else {
819
+ valueIndex = this.freeValues[this.freeValues.length - 1];
820
+ this.freeValues.pop();
821
+ this.values[valueIndex] = value;
822
+ }
823
+ this.freezeValue = value;
824
+ const node = this.insertNode(0, valueIndex, 0);
616
825
  this.valueTable.set(key, node);
617
826
  return node;
618
827
  }
@@ -622,28 +831,158 @@ export class PddManager {
622
831
  }
623
832
 
624
833
  private insertNode(level: number, lo: number, hi: number) {
625
- const key = `${level},${lo},${hi}`;
834
+ const key = getNodeKey(level, lo, hi);
626
835
  const existing = this.nodeTable.get(key);
627
836
  if (existing !== undefined) return existing;
628
- if (this.levels.length === this.numAllocated) {
629
- if (this.numAllocated > this.maxNumNodes && !this.isApplying) throw new PddMemoryOutError();
630
- while (this.numAllocated > this.maxNumNodes) this.maxNumNodes *= 2;
631
- this.numAllocated += Math.floor(this.numAllocated / 2);
632
- }
633
- const node = this.levels.length;
634
- this.levels.push(level);
635
- this.los.push(lo);
636
- this.his.push(hi);
837
+ if (this.freeNodes.length === 0) {
838
+ this.gc();
839
+ if (this.levels.length > this.maxNumNodes) throw new PddMemoryOutError();
840
+ this.allocFreeNodes(Math.floor(this.levels.length / 2));
841
+ }
842
+ const node = this.freeNodes[this.freeNodes.length - 1];
843
+ this.freeNodes.pop();
844
+ this.levels[node] = level;
845
+ this.los[node] = lo;
846
+ this.his[node] = hi;
847
+ this.refcounts[node] = 0;
637
848
  this.nodeTable.set(key, node);
638
849
  return node;
639
850
  }
851
+
852
+ private tryGc() {
853
+ this.gc();
854
+ this.opCache.clear();
855
+ }
856
+
857
+ private allocFreeNodes(count: number) {
858
+ for (let index = 0; index < count; index++) {
859
+ this.freeNodes.push(this.levels.length);
860
+ this.levels.push(0);
861
+ this.los.push(0);
862
+ this.his.push(0);
863
+ this.refcounts.push(0);
864
+ this.dmarks.push(0);
865
+ this.degrees.push(0);
866
+ }
867
+ this.freeNodes.sort((first, second) => second - first);
868
+ this.initDmark();
869
+ }
870
+
871
+ private computeReachable(reachable: Uint8Array) {
872
+ const todo: number[] = [];
873
+ for (let index = this.pddStackSize; index-- > 0;) {
874
+ reachable[this.pddStack[index]] = 1;
875
+ todo.push(this.pddStack[index]);
876
+ }
877
+ for (let node = NO_OP; node-- > 0;) reachable[node] = 1;
878
+ for (let node = this.levels.length; node-- > NO_OP;) {
879
+ if (this.refcounts[node] > 0) {
880
+ reachable[node] = 1;
881
+ todo.push(node);
882
+ }
883
+ }
884
+ for (let node = todo.pop(); node !== undefined; node = todo.pop()) {
885
+ if (this.isVal(node)) continue;
886
+ const lo = this.lo(node);
887
+ const hi = this.hi(node);
888
+ if (reachable[lo] === 0) {
889
+ reachable[lo] = 1;
890
+ todo.push(lo);
891
+ }
892
+ if (reachable[hi] === 0) {
893
+ reachable[hi] = 1;
894
+ todo.push(hi);
895
+ }
896
+ }
897
+ }
898
+
899
+ private gc() {
900
+ this.initDmark();
901
+ this.freeNodes = [];
902
+ const size = this.levels.length;
903
+ const reachable = new Uint8Array(size);
904
+ this.computeReachable(reachable);
905
+ for (let node = size; node-- > NO_OP;) {
906
+ if (reachable[node] === 1) continue;
907
+ if (this.his[node] === 0 && this.los[node] !== 0) {
908
+ const value = this.values[this.los[node]];
909
+ if (this.freezeValue.equals(value)) continue;
910
+ this.freeValues.push(this.los[node]);
911
+ this.valueTable.delete(value.toString());
912
+ }
913
+ this.los[node] = 0;
914
+ this.his[node] = 0;
915
+ this.freeNodes.push(node);
916
+ }
917
+ this.opCache.clear();
918
+ this.factorCache.clear();
919
+ this.nodeTable.clear();
920
+ for (let node = size; node-- > 2;) {
921
+ if (reachable[node] === 0) continue;
922
+ this.nodeTable.set(getNodeKey(this.levels[node], this.los[node], this.his[node]), node);
923
+ }
924
+ }
925
+
926
+ private initDmark() {
927
+ this.dmarkLevel++;
928
+ }
640
929
  }
641
930
 
931
+ const getMonomials = (poly: Pdd): PddMonomial[] => {
932
+ if (poly.isVal()) return poly.val().isZero() ? [] : [{ coeff: poly.val(), vars: [] }];
933
+ const hi = poly.hi();
934
+ const monomials = getMonomials(hi);
935
+ hi.release();
936
+ for (const monomial of monomials) monomial.vars.push(poly.var());
937
+ const lo = poly.lo();
938
+ monomials.push(...getMonomials(lo));
939
+ lo.release();
940
+ return monomials;
941
+ };
942
+
642
943
  export class Pdd {
643
944
  constructor(
644
945
  private readonly manager: PddManager,
645
- readonly root: number,
646
- ) {}
946
+ public root: number,
947
+ ) {
948
+ manager.incRef(root);
949
+ }
950
+
951
+ copy() {
952
+ const result = new Pdd(this.manager, this.root);
953
+ // Like Z3, whose copy constructor delegates to a counting constructor and then counts again.
954
+ this.manager.incRef(this.root);
955
+ return result;
956
+ }
957
+
958
+ release() {
959
+ this.manager.decRef(this.root);
960
+ }
961
+
962
+ assign(other: Pdd) {
963
+ const previous = this.root;
964
+ this.root = other.root;
965
+ this.manager.incRef(this.root);
966
+ this.manager.decRef(previous);
967
+ }
968
+
969
+ addAssign(other: Pdd) {
970
+ const sum = this.add(other);
971
+ this.assign(sum);
972
+ sum.release();
973
+ }
974
+
975
+ subAssign(value: Rational) {
976
+ const difference = this.sub(value);
977
+ this.assign(difference);
978
+ difference.release();
979
+ }
980
+
981
+ mulAssign(other: Pdd | Rational) {
982
+ const product = this.mul(other);
983
+ this.assign(product);
984
+ product.release();
985
+ }
647
986
 
648
987
  lo() {
649
988
  return new Pdd(this.manager, this.manager.lo(this.root));
@@ -678,11 +1017,29 @@ export class Pdd {
678
1017
  }
679
1018
 
680
1019
  isUnary() {
681
- return !this.isVal() && this.lo().isZero() && this.hi().isVal();
1020
+ if (this.isVal()) return false;
1021
+ const lo = this.lo();
1022
+ let isUnary = lo.isZero();
1023
+ if (isUnary) {
1024
+ const hi = this.hi();
1025
+ isUnary = hi.isVal();
1026
+ hi.release();
1027
+ }
1028
+ lo.release();
1029
+ return isUnary;
682
1030
  }
683
1031
 
684
1032
  isOffset() {
685
- return !this.isVal() && this.lo().isVal() && this.hi().isOne();
1033
+ if (this.isVal()) return false;
1034
+ const lo = this.lo();
1035
+ let isOffset = lo.isVal();
1036
+ if (isOffset) {
1037
+ const hi = this.hi();
1038
+ isOffset = hi.isOne();
1039
+ hi.release();
1040
+ }
1041
+ lo.release();
1042
+ return isOffset;
686
1043
  }
687
1044
 
688
1045
  isBinary() {
@@ -699,17 +1056,19 @@ export class Pdd {
699
1056
 
700
1057
  add(other: Pdd | Rational) {
701
1058
  return other instanceof Rational
702
- ? this.manager.add(this.manager.mkVal(other), this)
1059
+ ? this.manager.addValue(other, this)
703
1060
  : this.manager.add(this, other);
704
1061
  }
705
1062
 
706
1063
  sub(other: Pdd | Rational) {
707
- return other instanceof Rational ? this.add(other.neg()) : this.manager.sub(this, other);
1064
+ return other instanceof Rational
1065
+ ? this.manager.addValue(other.neg(), this)
1066
+ : this.manager.sub(this, other);
708
1067
  }
709
1068
 
710
1069
  mul(other: Pdd | Rational) {
711
1070
  return other instanceof Rational
712
- ? this.manager.mul(this.manager.mkVal(other), this)
1071
+ ? this.manager.mulValue(other, this)
713
1072
  : this.manager.mul(this, other);
714
1073
  }
715
1074
 
@@ -721,8 +1080,8 @@ export class Pdd {
721
1080
  return this.manager.reduce(this, other);
722
1081
  }
723
1082
 
724
- factor(variable: number, degree: number) {
725
- return this.manager.factor(this, variable, degree);
1083
+ factor(variable: number, degree: number, lc: Pdd, rest: Pdd) {
1084
+ this.manager.factor(this, variable, degree, lc, rest);
726
1085
  }
727
1086
 
728
1087
  differentLeadingTerm(other: Pdd) {
@@ -750,18 +1109,34 @@ export class Pdd {
750
1109
  }
751
1110
 
752
1111
  varFactors(): PddVarFactors {
753
- if (this.isVal()) return { vars: [], poly: this };
1112
+ if (this.isVal()) return { vars: [], poly: this.copy() };
754
1113
  const manager = this.manager;
755
1114
  const variable = this.var();
756
- if (this.lo().isVal()) {
757
- if (!this.lo().isZero()) return { vars: [], poly: this };
758
- const factors = this.hi().varFactors();
1115
+ const firstLo = this.lo();
1116
+ const isLoVal = firstLo.isVal();
1117
+ firstLo.release();
1118
+ if (isLoVal) {
1119
+ const secondLo = this.lo();
1120
+ const isLoZero = secondLo.isZero();
1121
+ secondLo.release();
1122
+ if (!isLoZero) return { vars: [], poly: this.copy() };
1123
+ const hi = this.hi();
1124
+ const factors = hi.varFactors();
1125
+ hi.release();
759
1126
  factors.vars.push(variable);
760
- return factors;
1127
+ const result = { vars: factors.vars, poly: factors.poly.copy() };
1128
+ factors.poly.release();
1129
+ return result;
761
1130
  }
762
- const loFactors = this.lo().varFactors();
1131
+ const lo = this.lo();
1132
+ const loFactors = lo.varFactors();
1133
+ lo.release();
763
1134
  const loVars = loFactors.vars;
764
- if (loVars.length === 0) return { vars: [], poly: this };
1135
+ if (loVars.length === 0) {
1136
+ const result = { vars: [], poly: this.copy() };
1137
+ loFactors.poly.release();
1138
+ return result;
1139
+ }
765
1140
  const loAndHi: number[] = [];
766
1141
  const merge = (hiVars: number[]) => {
767
1142
  let loKept = 0;
@@ -786,104 +1161,161 @@ export class Pdd {
786
1161
  shrink(loVars, loKept);
787
1162
  shrink(hiVars, hiKept);
788
1163
  };
789
- const multiply = (vars: number[], poly: Pdd) =>
790
- vars.reduce((product, innerVar) => product.mul(manager.mkVar(innerVar)), poly);
791
- const hiFactors = this.hi().varFactors();
1164
+ const multiply = (vars: number[], poly: Pdd) => {
1165
+ const product = poly.copy();
1166
+ for (const innerVar of vars) {
1167
+ const variablePdd = manager.mkVar(innerVar);
1168
+ product.mulAssign(variablePdd);
1169
+ variablePdd.release();
1170
+ }
1171
+ return product;
1172
+ };
1173
+ const hi = this.hi();
1174
+ const hiFactors = hi.varFactors();
1175
+ hi.release();
792
1176
  const hiVars = hiFactors.vars;
793
1177
  if (loVars[loVars.length - 1] === variable) {
794
1178
  loVars.pop();
795
1179
  merge(hiVars);
796
1180
  loAndHi.push(variable);
797
- return {
798
- vars: loAndHi,
799
- poly: multiply(loVars, loFactors.poly).add(multiply(hiVars, hiFactors.poly)),
800
- };
801
- }
802
- if (hiVars.length === 0) return { vars: [], poly: this };
803
- merge(hiVars);
804
- hiVars.push(variable);
805
- if (loAndHi.length === 0) return { vars: [], poly: this };
806
- return {
807
- vars: loAndHi,
808
- poly: multiply(loVars, loFactors.poly).add(multiply(hiVars, hiFactors.poly)),
809
- };
1181
+ } else if (hiVars.length > 0) {
1182
+ merge(hiVars);
1183
+ hiVars.push(variable);
1184
+ }
1185
+ let result: PddVarFactors;
1186
+ if (loAndHi.length === 0) {
1187
+ result = { vars: [], poly: this.copy() };
1188
+ } else {
1189
+ const loProduct = multiply(loVars, loFactors.poly);
1190
+ const hiProduct = multiply(hiVars, hiFactors.poly);
1191
+ result = { vars: loAndHi, poly: loProduct.add(hiProduct) };
1192
+ hiProduct.release();
1193
+ loProduct.release();
1194
+ }
1195
+ hiFactors.poly.release();
1196
+ loFactors.poly.release();
1197
+ return result;
810
1198
  }
811
1199
 
812
1200
  substPdd(variable: number, replacement: Pdd): Pdd {
813
1201
  const manager = this.manager;
814
- if (this.isVal() || manager.var2level[this.var()] < manager.var2level[variable]) return this;
815
- const lo = this.lo().substPdd(variable, replacement);
816
- const hi = this.hi().substPdd(variable, replacement);
817
- if (this.var() === variable) return replacement.mul(hi).add(lo);
818
- if (lo.equals(this.lo()) && hi.equals(this.hi())) return this;
819
- return manager.mkVar(this.var()).mul(hi).add(lo);
1202
+ if (this.isVal() || manager.var2level[this.var()] < manager.var2level[variable]) {
1203
+ return this.copy();
1204
+ }
1205
+ const lo = this.lo();
1206
+ const substitutedLo = lo.substPdd(variable, replacement);
1207
+ lo.release();
1208
+ const hi = this.hi();
1209
+ const substitutedHi = hi.substPdd(variable, replacement);
1210
+ hi.release();
1211
+ let result: Pdd;
1212
+ if (this.var() === variable) {
1213
+ const product = replacement.mul(substitutedHi);
1214
+ result = product.add(substitutedLo);
1215
+ product.release();
1216
+ } else {
1217
+ const thisLo = this.lo();
1218
+ let isUnchanged = substitutedLo.equals(thisLo);
1219
+ if (isUnchanged) {
1220
+ const thisHi = this.hi();
1221
+ isUnchanged = substitutedHi.equals(thisHi);
1222
+ thisHi.release();
1223
+ }
1224
+ thisLo.release();
1225
+ if (isUnchanged) {
1226
+ result = this.copy();
1227
+ } else {
1228
+ const variablePdd = manager.mkVar(this.var());
1229
+ const product = variablePdd.mul(substitutedHi);
1230
+ result = product.add(substitutedLo);
1231
+ product.release();
1232
+ variablePdd.release();
1233
+ }
1234
+ }
1235
+ substitutedHi.release();
1236
+ substitutedLo.release();
1237
+ return result;
820
1238
  }
821
1239
 
822
1240
  *[Symbol.iterator](): Generator<PddMonomial> {
823
- const manager = this.manager;
824
- const nodes: IteratorNode[] = [];
825
- const vars: number[] = [];
826
- let node = this.root;
827
- while (!manager.isVal(node)) {
828
- nodes.push({ isFirst: true, node });
829
- vars.push(manager.var(node));
830
- node = manager.hi(node);
831
- }
832
- if (nodes.length === 0) {
833
- if (!manager.val(node).isZero()) yield { coeff: manager.val(node), vars: [] };
834
- return;
835
- }
836
- yield { coeff: manager.val(node), vars: [...vars] };
837
- while (nodes.length > 0) {
838
- const top = nodes[nodes.length - 1];
839
- if (!top.isFirst) {
840
- nodes.pop();
841
- continue;
1241
+ const begin = this.copy();
1242
+ const end = this.copy();
1243
+ try {
1244
+ const manager = this.manager;
1245
+ const nodes: IteratorNode[] = [];
1246
+ const vars: number[] = [];
1247
+ let node = begin.root;
1248
+ while (!manager.isVal(node)) {
1249
+ nodes.push({ isFirst: true, node });
1250
+ vars.push(manager.var(node));
1251
+ node = manager.hi(node);
842
1252
  }
843
- top.isFirst = false;
844
- vars.pop();
845
- let next = manager.lo(top.node);
846
- if (next === ZERO_PDD) {
847
- nodes.pop();
848
- continue;
1253
+ if (nodes.length === 0) {
1254
+ if (!manager.val(node).isZero()) yield { coeff: manager.val(node), vars: [] };
1255
+ return;
849
1256
  }
850
- while (!manager.isVal(next)) {
851
- nodes.push({ isFirst: true, node: next });
852
- vars.push(manager.var(next));
853
- next = manager.hi(next);
1257
+ yield { coeff: manager.val(node), vars: [...vars] };
1258
+ while (nodes.length > 0) {
1259
+ const top = nodes[nodes.length - 1];
1260
+ if (!top.isFirst) {
1261
+ nodes.pop();
1262
+ continue;
1263
+ }
1264
+ top.isFirst = false;
1265
+ vars.pop();
1266
+ let next = manager.lo(top.node);
1267
+ if (next === ZERO_PDD) {
1268
+ nodes.pop();
1269
+ continue;
1270
+ }
1271
+ while (!manager.isVal(next)) {
1272
+ nodes.push({ isFirst: true, node: next });
1273
+ vars.push(manager.var(next));
1274
+ next = manager.hi(next);
1275
+ }
1276
+ yield { coeff: manager.val(next), vars: [...vars] };
854
1277
  }
855
- yield { coeff: manager.val(next), vars: [...vars] };
1278
+ } finally {
1279
+ end.release();
1280
+ begin.release();
856
1281
  }
857
1282
  }
858
1283
 
859
1284
  *coefficients(): Generator<PddCoefficient> {
860
- const manager = this.manager;
861
- const nodes: number[] = [];
862
- let node = this.root;
863
- while (!manager.isVal(node)) {
864
- nodes.push(node);
865
- node = manager.hi(node);
866
- }
867
- yield { coeff: manager.val(node), isConstant: nodes.length === 0 };
868
- for (let top = nodes.pop(); top !== undefined; top = nodes.pop()) {
869
- let next = manager.lo(top);
870
- if (next === ZERO_PDD) continue;
871
- while (!manager.isVal(next)) {
872
- nodes.push(next);
873
- next = manager.hi(next);
1285
+ const begin = this.copy();
1286
+ const end = this.copy();
1287
+ try {
1288
+ const manager = this.manager;
1289
+ const nodes: number[] = [];
1290
+ let node = begin.root;
1291
+ while (!manager.isVal(node)) {
1292
+ nodes.push(node);
1293
+ node = manager.hi(node);
874
1294
  }
875
- yield { coeff: manager.val(next), isConstant: nodes.length === 0 };
1295
+ yield { coeff: manager.val(node), isConstant: nodes.length === 0 };
1296
+ for (let top = nodes.pop(); top !== undefined; top = nodes.pop()) {
1297
+ let next = manager.lo(top);
1298
+ if (next === ZERO_PDD) continue;
1299
+ while (!manager.isVal(next)) {
1300
+ nodes.push(next);
1301
+ next = manager.hi(next);
1302
+ }
1303
+ yield { coeff: manager.val(next), isConstant: nodes.length === 0 };
1304
+ }
1305
+ } finally {
1306
+ end.release();
1307
+ begin.release();
876
1308
  }
877
1309
  }
878
1310
 
879
1311
  toString() {
880
1312
  let text = "";
881
- for (const monomial of this) {
1313
+ for (const monomial of getMonomials(this)) {
882
1314
  if (text !== "") text += " ";
883
1315
  if (monomial.coeff.isNegative()) text += "- ";
884
1316
  else if (text !== "") text += "+ ";
885
1317
  const coeff = monomial.coeff.abs();
886
- const vars = monomial.vars;
1318
+ const vars = monomial.vars.reverse();
887
1319
  if (!coeff.equals(Rational.one) || vars.length === 0) {
888
1320
  text += vars.length === 0 ? `${coeff}` : `${coeff}*`;
889
1321
  }
@@ -900,9 +1332,13 @@ export class Pdd {
900
1332
  }
901
1333
  }
902
1334
 
903
- export const evaluatePdd = (poly: Pdd, getValue: (variable: number) => Rational): Rational =>
904
- poly.isVal()
905
- ? poly.val()
906
- : evaluatePdd(poly.hi(), getValue)
907
- .mul(getValue(poly.var()))
908
- .add(evaluatePdd(poly.lo(), getValue));
1335
+ export const evaluatePdd = (poly: Pdd, getValue: (variable: number) => Rational): Rational => {
1336
+ if (poly.isVal()) return poly.val();
1337
+ const hi = poly.hi();
1338
+ const product = evaluatePdd(hi, getValue).mul(getValue(poly.var()));
1339
+ const lo = poly.lo();
1340
+ const result = product.add(evaluatePdd(lo, getValue));
1341
+ lo.release();
1342
+ hi.release();
1343
+ return result;
1344
+ };