-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy patheval.js
5215 lines (4424 loc) · 195 KB
/
eval.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* TLA+ interpreter.
*
* Contains logic for expression evaluation and initial/next state generation.
* See the `evalExpr` function below.
*
*/
// For debugging.
let depth = 0;
let cloneTime = 0.0;
const TLA_STANDARD_MODULES = [
"TLC",
"FiniteSets",
"Sequences",
"Integers",
"Bags",
"Naturals",
"Reals",
"Randomization"
]
// Some hard-coded modules which can be found in TLA+ CommunityModules repo:
// https://github.com/tlaplus/CommunityModules/blob/master/modules
const TLA_COMMUNITY_MODULES = [
"BagsExt",
"Bitwise",
"Combinatorics",
"FiniteSetsExt",
"Folds",
"Functions",
"Graphs",
"Relation",
"SequencesExt",
"UndirectedGraphs"
]
const TLA_COMMUNITY_MODULES_BASE_URL = "https://raw.githubusercontent.com/tlaplus/CommunityModules/master/modules";
// Simple assertion utility.
function assert(condition, message) {
if (!condition) {
console.error("assertion failed");
if (message) {
console.error(message);
}
throw new Error(message || 'Assertion failed');
}
}
function evalLog(...msgArgs) {
if (enableEvalTracing) {
let indent = "(L" + depth + ")" + ("|".repeat(depth * 2));
let args = [indent].concat(msgArgs)
console.log(...args);
}
}
function cartesianProductOf() {
return _.reduce(arguments, function (a, b) {
return _.flatten(_.map(a, function (x) {
return _.map(b, function (y) {
return x.concat([y]);
});
}), true);
}, [[]]);
}
function subsets(vals) {
const powerset = [];
generatePowerset([], 0);
function generatePowerset(path, index) {
powerset.push(path);
for (let i = index; i < vals.length; i++) {
generatePowerset([...path, vals[i]], i + 1);
}
}
return powerset;
}
// Combinations with replacement.
// See: https://stackoverflow.com/questions/32543936/combination-with-repetition
function combinations(arr, l) {
if (l === void 0) l = arr.length; // Length of the combinations
var data = Array(l), // Used to store state
results = []; // Array of results
(function f(pos, start) { // Recursive function
if (pos === l) { // End reached
results.push(data.slice()); // Add a copy of data to results
return;
}
for (var i = start; i < arr.length; ++i) {
data[pos] = arr[i]; // Update data
f(pos + 1, i); // Call f recursively
}
})(0, 0); // Start at index 0
return results; // Return results
}
function hashState(stateObj) {
return hashSum(stateObj);
}
// Meant to represent an abstract node in the expression evaluation tree.
// Can be evaluated on inputs and produces outputs that can then feed into
// other eval nodes.
class AbstractEvalNode {
constructor(name, type, children) {
this.name = name;
this.type = type;
this.children = children;
}
}
//
//
// TLA+ Value type definitions.
//
//
class TLAValue {
constructor() {
}
toJSONITF() {
return "'toJSONITF' unimplemented";
}
fingerprint() {
return "no_fingerprint";
}
/**
* Check if this value is equal to the value 'other'.
* @param {TLAValue} other
*/
equals(other) {
throw new Exception("equality check unimplemented!");
}
/**
* Convert value to tuple, if possible.
*/
toTuple() {
console.error("toTuple: value cannot be converted to tuple");
throw "value cannot be converted to tuple";
}
}
// Lazy value. Currently unused but may be utilized in future.
class LazyValue extends TLAValue {
constructor(n) {
super(n);
this.expr = n;
this.context = n;
}
fingerprint(){
return evalExpr(this.expr, this.context)[0]["val"].fingerprint();
}
}
class IntValue extends TLAValue {
constructor(n) {
super(n);
this.val = n;
}
toString() {
return this.val.toString();
}
toJSON() {
return this.val;
}
toJSONITF() {
return { "#type": "int", "#value": this.val };
}
getVal() {
return this.val;
}
plus(other) {
assert(other instanceof IntValue);
return new IntValue(this.val + other.getVal())
}
minus(other) {
assert(other instanceof IntValue);
return new IntValue(this.val - other.getVal())
}
fingerprint() {
return hashSum(this.val);
}
equals(other) {
if (!other instanceof IntValue) {
return false;
} else {
return this.val === other.getVal();
}
}
}
class BoolValue extends TLAValue {
constructor(n) {
super(n);
this.val = n;
}
toString() {
return this.val ? "TRUE" : "FALSE";
}
toJSON() {
return this.val;
}
toJSONITF() {
return { "#type": "bool", "#value": this.val };
}
fingerprint() {
return hashSum(this.val);
}
getVal() {
return this.val;
}
and(other) {
return new BoolValue(this.getVal() && other.getVal());
}
}
// Basically behaves as a string value, but can be only be instantiated by CONSTANT declarations.
class ModelValue extends TLAValue {
constructor(s) {
super(s);
this.val = s;
}
getVal() {
return this.val;
}
toString() {
return this.val;
}
toJSON() {
return this.val;
}
toJSONITF() {
return { "#type": "modelVal", "#value": this.val };
}
fingerprint() {
return this.val;
}
}
class StringValue extends TLAValue {
constructor(s) {
super(s);
this.val = s;
}
getVal() {
return this.val;
}
toString() {
return "\"" + this.val + "\"";
}
toJSON() {
return this.val;
}
toJSONITF() {
return { "#type": "string", "#value": this.val };
}
fingerprint() {
return this.val;
}
}
class SetValue extends TLAValue {
constructor(elems) {
super(elems);
// Remove duplicates at construction.
this.elems = _.uniqBy(elems, (e) => e.fingerprint());
}
toString() {
return "{" + this.elems.map(x => x.toString()).join(",") + "}";
}
toJSON() {
return this.elems;
}
toJSONITF() {
// Do a crude normalization by sorting by stringified version of each value
// TODO: Eventually will need a more principled way to do normalization
// and/or equality checking.
return {
"#type": "set",
"#value": _.sortBy(this.elems, (e) => e.toString()).map(el => el.toJSONITF())
};
}
getElems() {
return this.elems;
}
size() {
// TODO: Need to consider duplicates. Will likely require better equality handling for all types.
return this.elems.length;
}
unionWith(otherSet) {
return new SetValue(_.uniqWith(this.elems.concat(otherSet.getElems()), _.isEqual));
}
intersectionWith(otherSet) {
return new SetValue(_.intersectionWith(this.elems, otherSet.getElems(), _.isEqual));
}
isSubsetOf(otherSet) {
return new BoolValue(this.intersectionWith(otherSet).size() === this.size());
}
diffWith(otherSet) {
return new SetValue(_.differenceWith(this.elems, otherSet.getElems(), _.isEqual));
}
fingerprint() {
return hashSum(this.elems.map(e => e.fingerprint()).sort());
}
}
class TupleValue extends TLAValue {
constructor(elems) {
super(elems);
this.elems = elems;
}
toString() {
return "<<" + this.elems.map(x => x.toString()).join(",") + ">>";
}
toJSON() {
return this.elems;
}
append(el) {
return new TupleValue(this.elems.concat([el]));
}
concatTup(tup) {
return new TupleValue(this.elems.concat(tup.getElems()));
}
head() {
if (this.elems.length === 0) {
throw new Error("Tried to get head of empty list");
}
return this.elems[0];
}
tail() {
if (this.elems.length === 0) {
throw new Exception("Tried to get tail of empty list");
}
return new TupleValue(this.elems.slice(1));
}
getElems() {
return this.elems;
}
toJSONITF() {
return { "#type": "tup", "#value": this.elems.map(el => el.toJSONITF()) };
}
fingerprint() {
let rcd = this.toFcnRcd();
return rcd.fingerprint();
}
/**
* Return this tuple as an equivalent function value.
*/
toFcnRcd() {
// Tuples are functions with contiguous natural number domains.
let domainVals = _.range(1, this.elems.length + 1).map(v => new IntValue(v));
return new FcnRcdValue(domainVals, this.elems);
}
length() {
return this.elems.length;
}
toTuple() {
return this;
}
}
class FcnRcdValue extends TLAValue {
constructor(domain, values, isRecord) {
super(domain, values);
this.domain = domain;
this.values = values
// Trace 'record' types explicitly.
this.isRecord = isRecord || false;
}
toString() {
if (this.isRecord) {
return "[" + this.domain.map((dv, idx) => dv.getVal() + " |-> " + this.values[idx]).join(", ") + "]";
} else {
return "(" + this.domain.map((dv, idx) => dv.toString() + " :> " + this.values[idx]).join(" @@ ") + ")";
}
}
toJSON() {
return _.fromPairs(_.zip(this.domain, this.values))
}
getDomain() {
return this.domain;
}
getValues() {
return this.values;
}
// Get index of function argument in the function's domain.
argIndex(arg) {
return _.findIndex(this.domain, (v) => {
return v.fingerprint() === arg.fingerprint();
});
}
/**
* Apply the function to the argument 'arg'.
*/
applyArg(arg) {
let idx = this.argIndex(arg);
assert(idx >= 0, "argument " + arg + " doesn't exist in function domain.");
return this.values[idx];
}
/**
* Apply the function to the path argument 'arg', given as array of args e.g. ["x", "y"].
*/
applyPathArg(pathArg) {
if (pathArg.length === 1) {
return this.applyArg(pathArg[0]);
}
// Apply head of the path arg.
let fApplied = this.applyArg(pathArg[0])
// Apply rest of the path arg.
return fApplied.applyPathArg(pathArg.slice(1));
// let idx = this.argIndex(pathArg[0]);
// assert(idx >= 0, "argument " + arg + " doesn't exist in function domain.");
// return this.values[idx].applyPathArg(pathArg.slice(1));
}
updateWith(arg, newVal) {
let idx = this.argIndex(arg);
let newFn = _.cloneDeep(this);
newFn.values[idx] = newVal;
return newFn;
}
// Update a record value given a key sequence, representing a nested update.
// e.g. given ["x", "y", "z"], we make the update rcd["x"]["y"]["z"] := newVal.
updateWithPath(args, newVal) {
evalLog("updateWithPath args:", args);
evalLog("updateWithPath obj:", this);
// Base case, when the update is non-nested.
if (args.length === 1) {
evalLog("Hit non-nested update", args);
let idx = this.argIndex(args[0]);
assert(idx >= 0, "arg index wasn't found for argument " + args[0]);
let newFn = _.cloneDeep(this);
evalLog("newVal", newVal);
newFn.values[idx] = newVal;
return newFn;
}
// Otherwise, recursively update.
let idx = this.argIndex(args[0]);
let newFn = _.cloneDeep(this);
evalLog("newFn", newFn);
newFn.values[idx] = newFn.values[idx].updateWithPath(args.slice(1), newVal);
return newFn;
}
/**
* Compose this function with the given function value and return the result.
* @param {FcnRcdValue} other
*/
compose(other) {
assert(other instanceof FcnRcdValue);
// [x \in (DOMAIN f) \cup (DOMAIN g) |-> IF x \in DOMAIN f THEN f[x] ELSE g[x]]
// Construct the new domain.
// Take the union of the two domains, based on fingerprint equality.
let thisDomainFps = this.domain.map(x => x.fingerprint());
let newDomain = _.cloneDeep(this.domain);
for (const v of other.getDomain()) {
if (!thisDomainFps.includes(v.fingerprint())) {
newDomain.push(v);
}
}
evalLog("new domain:", newDomain);
let newRange = [];
// Construct the new range. If a domain value appeared in domains of both functions,
// we prefer the range value of ourselves.
for (const v of newDomain) {
if (thisDomainFps.includes(v.fingerprint())) {
// use our value.
newRange.push(this.applyArg(v));
} else {
// use the other value.
newRange.push(other.applyArg(v));
}
}
return new FcnRcdValue(newDomain, newRange);
}
toJSONITF() {
if (this.isRecord) {
console.log(this.domain);
console.log(this.values);
// Record domains should always be over strings.
return {
"#type": "record",
"#value": _.zipObject(this.domain.map(x => x.getVal()),
this.values.map(x => x.toJSONITF()))
};
} else {
return {
"#type": "map",
"#value": _.zip(this.domain.map(x => x.toJSONITF()),
this.values.map(x => x.toJSONITF()))
};
}
}
fingerprint() {
// Attempt normalization by sorting by fingerprints before hashing.
let domFps = this.domain.map(v => v.fingerprint());
let valsFp = this.values.map(v => v.fingerprint());
let fcnPairs = _.zip(domFps, valsFp);
let fcnPairsHashed = fcnPairs.map(hashSum);
fcnPairsHashed.sort();
return hashSum(fcnPairsHashed);
}
/**
* Convert this function/record to a tuple, if it has a valid domain (i.e. {1,2,...,n}).
*/
toTuple() {
let dom = this.getDomain();
// Domain must consist of all integral (i.e. natural numbered) values.
if (!dom.every(v => v instanceof IntValue)) {
throw "cannot convert record with domain '" + dom + "' to tuple";
}
let expectedDomain = _.range(1, dom.length + 1)
let hasTupleDomain = _.isEqual(expectedDomain, _.sortBy(dom.map(v => v.getVal())));
if (!hasTupleDomain) {
throw "cannot convert record with domain '" + dom + "' to tuple";
}
let vals = this.getValues();
let valsRevIndex = {};
for (var ind = 0; ind < vals.length; ind++) {
valsRevIndex[vals[ind]] = this.getDomain()[ind];
}
// Make sure the values are sorted by increasing indices.
let sortedVals = _.sortBy(vals, v => valsRevIndex[v])
return new TupleValue(sortedVals);
}
}
//
// TODO: Eventually consider moving over definition objects and table into these more structured formats.
//
/**
* Represents a TLA+ definition (either 0-arity or an n-arity operation definition.)
*/
// class Definition {
// constructor(name, isLocalDef, infixOpSymbol, args, var_decls, op_defs, parentModuleName) {
// this.name = name;
// this.isLocalDef = isLocalDef;
// this.infixOpSymbol = infixOpSymbol;
// this.args = args;
// this.var_decls = var_decls;
// this.op_defs = op_defs;
// this.parentModuleName = parentModuleName;
// }
// }
/**
* Stores a global table of definitions encountered during parsing a root spec and all imported/instantiated modules.
*/
// class GlobalDefinitionTable {
// constructor() {
// this.defs = {};
// }
// addDefinition(name, definition) {
// this.defs[definition.parentModuleName + "$$$" + name] = definition;
// definition.parentModuleName;
// console.log("added definition", name, definition, definition.parentModuleName);
// }
// }
/**
* Represents a concrete TLA+ state i.e. a mapping from variable names to values.
*/
class TLAState {
/**
* Construct with a mapping from variable names to their corresponding TLAValue.
*/
constructor(var_map) {
this.stateVars = var_map;
}
hasVar(varname) {
return this.stateVars.hasOwnProperty(varname);
}
/**
* Return the assigned value for the given variable name in this state.
*/
getVarVal(varname) {
return this.stateVars[varname];
}
/**
* Return the state as an object mapping variables to values.
*/
getStateObj() {
return this.stateVars;
}
/**
* Returns a new copy of this state with the given variable updated to the
* specified value.
*/
withVarVal(varName, newVal) {
return new TLAState(_.mapValues(this.stateVars, (val, k, obj) => {
if (k === varName) {
return newVal;
} else {
return val;
}
}));
}
/**
* Given a state with primed and unprimed variables, remove the original
* unprimed variables and rename the primed variables to unprimed versions.
*/
deprimeVars() {
let newVars = _.pickBy(this.stateVars, (val, k, obj) => k.endsWith("'"));
return new TLAState(_.mapKeys(newVars, (val, k, obj) => k.slice(0, k.length - 1)));
}
/**
* Return an object representing this state using the Informal Trace Format
* (ITF) serialization conventions for TLA values.
*
* See https://apalache.informal.systems/docs/adr/015adr-trace.html.
*/
toJSONITF() {
// Sort keys for now.
let outObj = {};
for (var k of Object.keys(this.stateVars).sort()) {
outObj[k] = this.stateVars[k].toJSONITF();
}
return outObj;
// return _.mapValues(this.vars, (v) => v.toJSONITF());
}
toString() {
let out = "";
for (var k of Object.keys(this.stateVars).sort()) {
out += "/\\ " + k + " = " + this.stateVars[k].toString() + "\n";
}
return out;
}
/**
* Return a unique, string hash of this state.
*/
fingerprint() {
let stateKeys = Object.keys(this.stateVars).sort();
// Construct an array that is sequence of each state varialbe name and a
// fingerprint of its TLA value. Then we hash this array to produce the
// fingerprint for this state.
let valsToHash = [];
for (var k of stateKeys) {
valsToHash.push(k);
valsToHash.push(this.stateVars[k].fingerprint());
}
return hashSum(valsToHash);
}
// Compute the set of variables that are different between this state and the given 'otherState'.
// Assumes they have the same set of state variables.
varDiff(otherState){
let stateKeys = Object.keys(this.stateVars).sort();
// Construct an array that is sequence of each state varialbe name and a
// fingerprint of its TLA value. Then we hash this array to produce the
// fingerprint for this state.
let varDiff = [];
for (var k of stateKeys) {
let mine = this.stateVars[k].fingerprint();
let other = otherState.stateVars[k].fingerprint();
if(mine !== other){
varDiff.push(k);
}
}
return varDiff;
}
// toString(){
// return "[" + this.domain.map((dv,idx) => dv + " |-> " + this.values[idx]).join(", ") + "]";
// }
// toJSON(){
// return _.fromPairs(_.zip(this.domain, this.values))
// }
}
/**
* Represents an abstract action of a parsed specification (i.e. a sub-expression of the next state relation).
*/
class TLAAction{
constructor(id, node, name) {
this.id = id;
this.node = node;
this.name = name;
}
}
/**
* Generates and performs syntactic rewrites on a TLA+ spec as part of a
* pre-processing step before parsing and evaluation.
*/
class SyntaxRewriter {
setInUniqueVarId = 0;
origSpecText;
identUniqueId = 0;
opArgsToRename = {};
// Map from rewritten spec back to the original.
// maps from (line_new, col_new) to (line_old, col_old)
constructor(origSpecText, parser) {
this.origSpecText = origSpecText;
this.parser = parser;
this.sourceMapOffsets = [];
}
/**
* Generate and apply syntax rewrites on the original spec text repeatedly
* until a fixpoint is reached i.e until no more rewrite operations can be
* generated. Returns the rewritten version of the spec.
*/
doRewrites() {
// Start with the original spec text.
this.sourceMapOffsets = [];
let specTextRewritten = this.origSpecText;
let specTree = this.parser.parse(specTextRewritten + "\n", null);
// Generate initial rewrite batch.
let rewriteBatch = this.genSyntaxRewrites(specTree);
// Apply AST rewrite batches until a fixpoint is reached.
const start = performance.now();
while (rewriteBatch.length > 0) {
// console.log("New syntax rewrite iteration");
// console.log("rewrite batch: ", rewriteBatch, "length: ", rewriteBatch.length);
specTextRewritten = this.applySyntaxRewrites(specTextRewritten, rewriteBatch);
// console.log("REWRITTEN:", specTextRewritten);
specTree = this.parser.parse(specTextRewritten + "\n", null);
rewriteBatch = this.genSyntaxRewrites(specTree);
}
const duration = (performance.now() - start).toFixed(1);
console.log(`Completed spec rewriting in ${duration}ms`)
// console.log(specTextRewritten);
return specTextRewritten;
}
/**
* Compute original location of given position from the rewritten spec.
*/
getOrigLocation(line, col) {
console.log("#getOrigLocation");
let lineArg = line;
let colArg = col;
console.log("initial curr line,col:", lineArg, colArg);
for (var f of _.reverse(this.sourceMapOffsets)) {
// for (var f of this.sourceMapOffsets) {
// console.log("smap:", f);
let newPos = f(lineArg, colArg);
lineArg = newPos[0];
colArg = newPos[1];
// let posAfter = m[0];
// let lineAfter = posAfter[0]
// let colAfter = posAfter[1];
// // Inverse the diff direction as we apply the offsets.
// let lineDiff = -m[1];
// let colDiff = -m[2];
// // Is the given position after the start of the rewritten portion?
// // Otherwise no offset is required.
// if (lineArg === lineAfter && colArg >= colAfter) {
// // lineArg unchanged.
// colArg += colDiff
// }
// else if (lineArg > lineAfter) {
// console.log("diff:", lineAfter, colDiff);
// if (lineArg > lineAfter) {
// lineArg += lineDiff;
// if (lineArg == lineAfter) {
// colArg += colDiff;
// }
// }
// }
// console.log("curr line,col:", lineArg, colArg);
}
return [lineArg, colArg];
}
// Apply a given set of text rewrites to a given source text. Assumes the given
// 'text' argument is a string given as a list of lines.
applySyntaxRewrites(text, rewrites) {
let lines = text.split("\n");
// let sourceMapFn = (line, col) => (line, col);
for (const rewrite of rewrites) {
let startRow = rewrite["startPosition"]["row"];
let startCol = rewrite["startPosition"]["column"];
let endRow = rewrite["endPosition"]["row"];
let endCol = rewrite["endPosition"]["column"];
// Cut out original chunk.
let prechunk = lines.slice(0, startRow).concat([lines[startRow].substring(0, startCol)]);
let postchunk = [lines[endRow].substring(endCol)].concat(lines.slice(endRow + 1));
// console.log("chunk out: ");
// console.log(prechunk.join("\n").concat("<CHUNK>").concat(postchunk.join("\n")));
// console.log("postchunk: ");
// console.log(postchunk.join("\n"));
// Delete line entirely.
if (rewrite["deleteRow"] !== undefined) {
lines[rewrite["deleteRow"]] = "";
// TODO: Make this work.
// lines = lines.filter((_, index) => index !== rewrite["deleteRow"]);
} else {
let lineInd = rewrite["startPosition"]["row"]
let line = lines[lineInd];
// <
// PRECHUNK
// >|<
// CHUNK TO REPLACE
// >|<
// POST CHUNK
// >
// Append the new string to the last line of the prechunk,
// followed by the first line of the post chunk.
prechunk[prechunk.length - 1] = prechunk[prechunk.length - 1].concat(rewrite["newStr"]).concat(postchunk[0]);
// Then append the rest of the postchunk
let linesUpdated = prechunk.concat(postchunk.slice(1));
//
// TODO: Revisit how to do source mapping here for error reporting.
//
// Everything after the changed lines must be shifted but everything before
// remain reamin the same.
// let afterPos = [startRow, startCol];
// let lineDiff = -(endRow - startRow)
let colDiff = (rewrite["newStr"].length - prechunk.length);
// let diff = [afterPos, lineDiff, colDiff];
// this.sourceMapOffsets.push(diff);
let newStartRow = startRow;
let newStartCol = startCol;
let newEndRow = startRow;
let newEndCol = prechunk[prechunk.length - 1].length + rewrite["newStr"].length - 1;
let transform = (targetRow, targetCol) => {
// console.log("newStartRow, newEndRow", newStartRow, newEndRow);
// console.log("start", newEndRow);
// if(targetRow < newStartRow){
// return [targetRow, targetCol];
// }
// Target position is >= the new chunk end position.
if (targetRow > startRow || targetRow === newEndRow && targetCol >= newEndCol) {
// Shift by line diff, and by column diff (if necessary).
// Diff from end of new chunk.
let lineDiff = targetRow - newEndRow;
let colDiff = targetRow === newEndRow ? targetCol - newEndCol : newEndCol;
// console.log("lineDiff:", lineDiff);
// console.log("colDiff:", colDiff);
// console.log("startRow:", startRow);
// console.log("startRow:", startRow);
// Transformed position is equivalent to same diff from original end position.
return [endRow + lineDiff, endCol + colDiff]
} else {
// No shift.
return [targetRow, targetCol];
}
// if(targetRow === newStartRow && targetCol == newStartCol){
// return [startRow, startCol]
// }
// if(targetRow === startRow && targetCol == newEndCol){
// return [endRow, endCol]
// }
// if(targetRow > startRow){
// let lineDiff = endRow - startRow;
// if(targetRow === end)
// return [targetRow + lineDiff, endCol]
// }
// return [targetRow, targetCol];
}
this.sourceMapOffsets.push(transform);
lines = linesUpdated;
}
// TODO: Consider removing line entirely if it is empty after rewrite.
// if(lineNew.length > 0){
// lines[lineInd] = lineNew;
// } else{
// If line is empty, remove it.
// lines.splice(lineInd, 1);
// }
}
return lines.join("\n");
}
/**
* Walks a given TLA syntax tree and generates a new batch of syntactic rewrites to be
* performed on the source module text before we do any evaluation/interpreting
* e.g. syntactic desugaring. Should be repeatedly applied until no more rewrites are
* produced.
*
* @param {TLASyntaxTree} treeArg
*/
genSyntaxRewrites(treeArg) {
// Records a set of transformations to make to the text that produced this
// parsed syntax tree. Each rewrite is specified by a replacement rule,
// given by a structure {startPosition: Pos, endPosition: Pos, newStr: Str}
// where startPosition/endPosition correspond to the start and end points of
// the source text to replace, and 'newStr' represents the string to insert
// at this position.
let sourceRewrites = [];
const cursor = treeArg.walk();
// isRendering = false;
let currentRenderCount = 0;
let row = '';
let rows = [];
let finishedRow = false;
let visitedChildren = false;
let indentLevel = 0;
let currOpDefNameContext = null;
for (let i = 0; ; i++) {
let displayName;
if (cursor.nodeIsMissing) {
displayName = `MISSING ${cursor.nodeType}`
} else if (cursor.nodeIsNamed) {
displayName = cursor.nodeType;
}
if (visitedChildren) {
if (displayName) {
finishedRow = true;
}
if (cursor.gotoNextSibling()) {
visitedChildren = false;
} else if (cursor.gotoParent()) {
visitedChildren = true;
indentLevel--;
} else {