-
Notifications
You must be signed in to change notification settings - Fork 3
/
spipat.mjs
3090 lines (2601 loc) · 72.2 KB
/
spipat.mjs
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
// -*-javascript-*-
// SPITBOL Patterns in JavaScript
// Based on GNAT (GNU Ada Translator) GNAT.SPITBOL.PATTERNS
////////////////////////////////////////////////////////////////
// Copyright (C) 1998-2013, AdaCore
// Copyright (C) 2007-2019, Philip L. Budne
// GNAT is free software; you can redistribute it and/or modify it under
// terms of the GNU General Public License as published by the Free Soft-
// ware Foundation; either version 3, or (at your option) any later ver-
// sion. GNAT is distributed in the hope that it will be useful, but WITH-
// OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.
//
// As a special exception under Section 7 of GPL version 3, you are granted
// additional permissions described in the GCC Runtime Library Exception,
// version 3.1, as published by the Free Software Foundation.
//
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
//
// GNAT was originally developed by the GNAT team at New York University.
// Extensive contributions were provided by Ada Core Technologies Inc.
// The C and JavaScript translations were done by Philip L. Budne
////////////////////////////////////////////////////////////////
// This is a native JavaScript implementation of SNOBOL/SPITBOL pattern
// matching. It's a translation of the C translation of the GNAT
// (GNU Ada Translator) gnat.spitbol.patterns library.
// Written as ES6 (2015) under nodejs 13.5.0
// I hope I won't regret that choice as much as I did
// using C99 for the C port!!
// Different node types implemented as subclasses of PE. Probably not
// as efficient as a big switch, but keeps different aspects of each
// node (construction, booleans, match operation, display) in one place.
//let STRING_LENGTHS = new Array(10).fill(0);
// XXX for testing under nodejs, set from command line???
// look at process.argv or process.env
const DEBUG_STACK = false;
const DEBUG_IMAGE = false;
const TEST_IMAGE = false;
const PARANOIA = true; // stack sanity checks
// uni-chars for display of strings:
export const LQ = '«'; // string left quote
export const RQ = '»'; // string right quote
const CURSOR = '⯈'; // display before cursor location
const EOP_INDEX = 0;
const EOP_SYMBOL = '∎'; // "end of proof" (QED)
//////////////// helpers
function is_func(x) {
return (typeof x === 'function');
}
function is_str(x) {
return (typeof x === 'string');
}
function is_int(x) {
return (typeof x === 'number') && (x % 1 === 0);
}
function is_bool(x) {
return (typeof x === 'boolean');
}
function is_set(x) {
return x instanceof Set;
}
export function is_pat(x) {
return x instanceof Pattern;
}
function is_var(x) {
return x instanceof Var;
}
// explode string into unicode "runes" which may be JS strings of
// length one or two :-( (Where two-character sequences are UTF-16
// "surrogate pairs" (and include all emoji)).
// EXPLODE was a function in MacLISP that took an atom/symbol
// and expanded it to a list with one symbol per character, see:
// http://www.maclisp.info/pitmanual/charac.html#EXPLODE
// "Rune" was the name the datatype used to hold unicode characters
// (code points) on "Plan9 from Bell Labs", where UTF-8 was invented
// by Brian Kernighan and implement by Kernighan and Pike.
// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.45.1638&rep=rep1&type=pdf
// https://www.researchgate.net/scientific-contributions/3228095_Ken_Thompson
// https://www.unix.com/man-page/plan9/6/utf/
// https://9fans.github.io/plan9port/man/man3/rune.html
// https://www.cl.cam.ac.uk/~mgk25/ucs/utf-8-history.txt
// Ironically the Plan9 rune type was ORIGINALLY only 16 bits, much as
// "characters" in JavaScript are now, but I can't imagine Plan9 ever
// resorted to "surrogate pairs" madness, and probably moved to 32-bit
// runes at some point by just recompiling all their code.
function explode(str) {
return Array.from(str);
}
// return str as a JS quoted string.
function stringify(str) {
// maybe use single quotes
// if string contains double quote (and no singles)??
return JSON.stringify(str);
}
//////////////// errors
class SpipatError extends Error {}
function error(msg) {
throw new SpipatError(msg);
}
class SpipatUserError extends SpipatError {}
function uerror(msg) {
throw new SpipatUserError(msg);
}
function need_ssfv(who) {
throw new SpipatUserError(`'${who}' needs String, Set, Function or Var`);
}
// from "ssf" matching functions
function need_sf(who, got, func) {
throw new SpipatUserError(`'${who}' needs String or Set, got ${got} from ${func}`);
}
// from _Var matching functions
function need_s(who, got, v) {
throw new SpipatUserError(`'${who}' needs String got ${got} from ${v.toString()}`);
}
function need_nnifv(who, n) {
throw new SpipatUserError(`'${who}' needs non-negative integer, Function, or Var, got ${n}`);
}
function need_nni_func(who, n, func) {
throw new SpipatUserError(`'${who}' needs non-negative integer from function ${func} got ${n}`);
}
function need_nni_var(who, n, v) {
throw new SpipatUserError(`'${who}' needs non-negative integer from var ${v.name} got ${n}`);
}
// onmatch/imm/cursor need function or Var
function need_fv(who) {
throw new SpipatUserError(`'${who}' needs Function or Var`);
}
////////////////////////////////////////////////////////////////
// Pattern Element class
// return values for PE.match method (want enum or class constants):
const M_Pattern_Success = 0; // entire pattern succeeded
const M_Pattern_Fail = 1; // entire pattern failed
const M_Succeed = 2; // node match succeeded
const M_Fail = 3; // node match failed
const M_Continue = 4; // node changed, continue
// super-base class. The only instance of a class directly derived
// from _PE is the singleton PE_EOP instance, EOP, so that the const
// EOP can be used in the constructor for the "PE" class used as the
// base for all other pattern element node types.
class _PE { // Pattern Element
constructor(index, pthen, ok_for_simple_arbno, has_alt) {
this.index = index;
this.pthen = pthen;
// want (const) class members:
this.ok_for_simple_arbno = ok_for_simple_arbno;
this.has_alt = has_alt;
this.assign = false; // imm/onmatch wrappers
this.need_pat = false; // image needs pat(x)
}
// methods for image (conversion to string):
name() {
return this.constructor.name;
}
data() { // return string for additional data
return null;
}
inext(ic) { // return subsequent pattern (for image)
return this.pthen;
}
image(ic) {
error(this.name() + " image not defined!");
}
match(m) {
error(this.name() + " match not defined!");
}
// return an array of pointers to elements of pattern
// rooted at this element.
ref_array() {
// XXX cache in this.ra???
let ra = new Array(this.index);
// Record given pattern element if not already recorded in ra,
// and also record any referenced pattern elements recursively.
function record(pe) {
if (pe === EOP || ra[pe.index-1])
return;
ra[pe.index-1] = pe;
record(pe.pthen);
if (pe.has_alt)
record(pe.alt);
}
record(this); // walk the tree
Object.freeze(ra);
return ra;
} // ref_array
copy() { // copy pattern rooted at this node
let refs = this.ref_array();
// Holds copies of elements, indexed by index-1
let copies = new Array(this.index);
// Now copy all nodes
for (let j = 0; j < this.index; j++)
copies[j] = refs[j].clone();
// Adjust all internal references
for (let j = 0; j < this.index; j++) {
let e = copies[j];
// Adjust successor pointer to point to copy
if (e.pthen !== EOP)
e.pthen = copies[e.pthen.index-1];
// Adjust Alt pointer if there is one to point to copy
if (e.has_alt && e.alt !== EOP)
e.alt = copies[e.alt.index-1];
} // for j
return copies[this.index-1];
} // copy
clone() { // clone this element, for copy()
// from https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance
// NOTE: works for symbols but not:
// accessor properties (get/set)
// non-enumerable properties (including static methods?)
return Object.assign(Object.create(Object.getPrototypeOf(this)),
this);
}
// Note: this procedure is not used by the normal concatenation circuit,
// since other fixups are required on the left operand in this case, and
// they might as well be done all together.
set_successor(succ) {
for (let p of this.ref_array()) {
if (p.pthen === EOP) {
p.pthen = succ;
//console.log(`set node ${p.index} pthen to ${succ.index}`);
}
if (p.has_alt && p.alt === EOP) {
p.alt = succ;
//console.log(`set node ${p.index} alt to ${succ.index}`);
}
}
}
seal() {
Object.seal(this);
}
}
//////////////// end of pattern (internal)
class PE_EOP extends _PE { // End Of Pattern
constructor() {
super(EOP_INDEX, null, false, false, false);
this.seal();
}
match(m) {
if (m.stack.base === m.stack.init) {
m.trace(" === end of pattern ==="); // no node addr
return M_Pattern_Success;
}
else {
// End of recursive inner match. See separate section on
// handing of recursive pattern matches for details.
m.trace(" terminating recursive match"); // no node addr
let elt = m.stack.peek(m.stack.base - 1);
m.node = elt.node;
m.pop_region();
return M_Continue;
}
}
name() {
return "EOP";
}
clone() { // single instance
error("EOP.clone");
}
}
const EOP = new PE_EOP(); // single instance, never copied
//////////////// PE base class
// base class for all Pattern Element nodes OTHER than EOP.
// UnsealedPE is NOT for direct use!
// All classes that inherit from it should call this.seal
// in the constructor!
export class UnsealedPE extends _PE {
constructor(index, pthen, ok_for_simple_arbno, has_alt) {
super(index || 1,
pthen || EOP,
ok_for_simple_arbno || false,
has_alt || false);
}
}
// base for classes that don't require private data/constructor
class PE extends UnsealedPE {
constructor(index, pthen, ok_for_simple_arbno, has_alt) {
super(index, pthen, ok_for_simple_arbno, has_alt);
this.seal();
}
}
class VarPE extends UnsealedPE {
constructor(index, v, ok_for_simple_arbno) {
super(index, EOP, ok_for_simple_arbno);
this.assign = true; // want class member
this.v = v;
this.seal();
}
data() {
return this.v.toString();
}
image(ic) {
ic.append(`${this.name()}(${this.data()})`);
}
}
//////////////// string
// Note, the following is not just an optimization, it is needed
// to ensure that arbno(len(0)) and arbno('') do not generate infinite
// matching loops (PE_Null is *NOT* safe_for_simple_arbno)!
class PE_Null extends PE { // match zero length string
match(m) {
m.petrace(this, "matching null string");
return M_Succeed;
}
image(ic) {
ic.pappend('""');
}
}
class RunesPE extends UnsealedPE {
constructor(runes) {
super(1, EOP, true); // ok_for_simple_arbno
this.runes = runes;
this.length = runes.length; // for general case
this.need_pat = true;
this.str = runes.join('');
this.seal();
}
data() {
return stringify(this.str);
}
image(ic) {
ic.pappend(stringify(this.str));
}
}
// special case to match single unicode character (rune)
// (which may be one or two javascript "characters" long due to UTF-16)
class PE_String_1 extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= 1 &&
m.subject[m.cursor+0] === this.runes[0]) {
m.cursor++;
return M_Succeed;
}
return M_Fail;
}
}
class PE_String_2 extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= 2 &&
m.subject[m.cursor+0] === this.runes[0] &&
m.subject[m.cursor+1] === this.runes[1]) {
m.cursor += 2;
return M_Succeed;
}
return M_Fail;
}
}
class PE_String_3 extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= 3 &&
m.subject[m.cursor+0] === this.runes[0] &&
m.subject[m.cursor+1] === this.runes[1] &&
m.subject[m.cursor+2] === this.runes[2]) {
m.cursor += 3;
return M_Succeed;
}
return M_Fail;
}
}
class PE_String_4 extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= 4 &&
m.subject[m.cursor+0] === this.runes[0] &&
m.subject[m.cursor+1] === this.runes[1] &&
m.subject[m.cursor+2] === this.runes[2] &&
m.subject[m.cursor+3] === this.runes[3]) {
m.cursor += 4;
return M_Succeed;
}
return M_Fail;
}
}
class PE_String_5 extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= 5 &&
m.subject[m.cursor+0] === this.runes[0] &&
m.subject[m.cursor+1] === this.runes[1] &&
m.subject[m.cursor+2] === this.runes[2] &&
m.subject[m.cursor+3] === this.runes[3] &&
m.subject[m.cursor+4] === this.runes[4]) {
m.cursor += 5;
return M_Succeed;
}
return M_Fail;
}
}
class PE_String_6 extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= 6 &&
m.subject[m.cursor+0] === this.runes[0] &&
m.subject[m.cursor+1] === this.runes[1] &&
m.subject[m.cursor+2] === this.runes[2] &&
m.subject[m.cursor+3] === this.runes[3] &&
m.subject[m.cursor+4] === this.runes[4] &&
m.subject[m.cursor+5] === this.runes[5]) {
m.cursor += 6;
return M_Succeed;
}
return M_Fail;
}
}
class PE_String extends RunesPE {
match(m) {
m.petrace(this, `matching ${LQ}${this.str}${RQ}`);
if ((m.length - m.cursor) >= this.length) {
for (let i = 0; i < this.length; i++)
if (m.subject[m.cursor + i] !== this.runes[i])
return M_Fail;
m.cursor += this.runes.length;
return M_Succeed;
}
return M_Fail;
}
}
class PE_Var extends VarPE {
constructor(v) { // XXX Var1PE?
super(1, v);
this.need_pat = true;
}
match(m) {
let str = this.v.get();
m.petrace(this, `matching ${LQ}${str}${RQ}`);
if (!is_str(str))
need_s('pat', str, this.v);
let runes = explode(str);
if ((m.length - m.cursor) >= runes.length) {
for (let i = 0; i < runes.length; i++)
if (m.subject[m.cursor + i] !== runes[i])
return M_Fail;
m.cursor += runes.length;
return M_Succeed;
}
return M_Fail;
}
image(ic) {
ic.append(this.v.toString());
}
}
class FuncPE extends UnsealedPE {
constructor(index, func, ok_for_simple_arbno, need_pat) {
super(index, EOP, ok_for_simple_arbno);
this.func = func;
// true if node needs to be wrapped in pat() for image:
this.need_pat = need_pat || false;
this.seal();
}
data() {
if (this.func.name)
return this.func.name;
else
return this.func.toString(); // anonymous: return defn
}
image(ic) {
ic.append(`${this.name()}(${this.data()})`);
}
}
// call func at match time, handles:
// string, pattern, boolean
class PE_Func extends FuncPE {
constructor(func) { // XXX Func1PE?
super(1, func, false, true); // need_pat
}
match(m) {
let x = this.func();
if (is_str(x)) {
if (m.debug)
m.petrace(this, `function ${this.data()} matching ${LQ}${x}${RQ}`);
let runes = explode(x);
let length = runes.length;
if ((m.length - m.cursor) >= length) {
for (let i = 0; i < length; i++) {
if (m.subject[m.cursor + i] !== runes[i]) {
return M_Fail;
}
}
m.cursor += length;
return M_Succeed;
}
return M_Fail;
}
else if (is_pat(x)) {
if (m.debug)
m.petrace(this, `function ${this.data()} starting recursive match`);
if (!m.stack.room(x.stk))
error("pattern stack overflow");
m.stack.put_node(m.stack.ptr + 1, this.pthen);
m.push_region()
m.node = x.p;
return M_Continue;
}
else if (is_bool(x) || is_int(x)) {
if (m.debug)
m.petrace(this, `function ${this.data()} returned ${x}`);
if (x)
return M_Succeed;
else
return M_Fail;
}
else {
uerror(`need String, Pattern, integer, or Boolean from ${this.data()}`);
}
}
image(ic) {
ic.pappend(`${this.data()}`); // function name or defn
}
} // PE_Func
// String, Function or Var to PE
function sfv_to_pe(who, x) {
if (is_str(x)) {
let runes = explode(x);
// gather stats:
// if (STRING_LENGTHS) {
// let sl = runes.length < STRING_LENGTHS.length ? runes.length : STRING_LENGTHS.length-1;
// STRING_LENGTHS[sl] += 1;
// }
switch (runes.length) {
case 0: return new PE_Null(); // not ok_for_simple_arbno!
case 1: return new PE_String_1(runes);
case 2: return new PE_String_2(runes);
case 3: return new PE_String_3(runes);
case 4: return new PE_String_4(runes);
case 5: return new PE_String_5(runes);
case 6: return new PE_String_6(runes);
default: return new PE_String(runes);
}
}
else if (is_func(x))
return new PE_Func(x);
else if (is_var(x))
return new PE_Var(x);
else
uerror(`'${who}' needs String, Function, or Var`);
}
// NOTE: _COULD_ rename Pattern class to PPattern (primative pattern)
// and construct new patterns thru a Pattern subclass constructor.
// But this requires fewer keystrokes:
export function pat(x) { // string or function to Pattern
return new Pattern(0, sfv_to_pe('pat', x));
}
////////////////
// Abort Node (internal)
// Abort on backtrack of anchored match, fence; abort primative
class PE_Abort extends PE {
match(m) {
m.petrace(this, "matching abort");
return M_Pattern_Fail;
}
image(ic) {
ic.append("abort");
}
}
const CP_Abort = new PE_Abort(); // for anchored match, fence
////////////////
// Assign Node (internal)
class PE_Assign extends PE { // Assignment on match
match(m) {
// If this node is executed, it means the assign-on-match
// (call-on-match) operation will not happen after all, so we
// propagate the failure, removing the PE_Assign node.
m.petrace(this, "deferred assign/call cancelled");
return M_Fail;
}
clone() { // single instance, stacked only
error("PE_Assign.clone");
}
}
const CP_Assign = new PE_Assign();
////////////////
// Region Enter node (internal)
// Region Enter. Initiate new pattern history stack region
// used by immediate and "on match" assignment
class PE_R_Enter extends PE {
constructor() {
super();
this.assign = true;
}
match(m) {
m.petrace(this, "starting match of nested pattern");
m.stack.put_cursor(m.stack.ptr + 1, m.cursor);
m.push_region();
return M_Succeed;
}
image(ic) {
const action = ic.refs[this.index-2];
action.image(ic); // Imm/OnMatch node
}
inext(ic) {
return ic.refs[this.index-2].pthen; // pick up after Imm/OnMatch
}
}
////////////////
// Region Remove node (internal).
// This is the node stacked by an R_Enter.
// It removes the special format stack entry right underneath, and
// then restores the outer level stack base and signals failure.
class PE_R_Remove extends PE {
match(m) {
// Note: the cursor value at this stage is actually the (negative)
// stack base value for the outer level.
m.petrace(this, "failure, match of nested pattern terminated");
m.stack.set_base(m.cursor);
m.region_level--; // XXX check?
m.stack.ptr--; // XXX check? HIDE??
return M_Fail;
}
clone() { // single instance: stacked only
error("PE_R_Remove.clone");
}
}
const CP_R_Remove = new PE_R_Remove();
////////////////
// Region restore node. (internal)
// This is the node stacked at the end of an
// inner level match. Its function is to restore the inner level
// region, so that alternatives in this region can be sought.
class PE_R_Restore extends PE {
match(m) {
// Note: the Cursor at this stage is actually the negative of the
// inner stack base value, which we use to restore the inner region.
m.petrace(this, "failure, search for alternatives in nested pattern");
m.region_level++;
m.stack.set_base(m.cursor);
return M_Fail;
}
clone() { // single instance: stacked only
error("PE_R_Restore.clone");
}
}
const CP_R_Restore = new PE_R_Restore();
////////////////
// Unanchored match helper
class PE_Unanchored extends PE { // Unanchored movement
constructor(node) {
super(0, node, false);
}
match(m) {
m.trace(" attempting to move anchor point"); // no node addr
if (m.cursor > m.length) {
return M_Pattern_Fail; // All done if we tried every position
}
// Otherwise extend the anchor point, and restack ourself
m.cursor++;
m.push(this);
return M_Succeed;
}
}
////////////////
// Concat
// Concat needs to traverse the left operand performing the following
// set of fixups:
// a) Any successor pointers (Pthen fields) that are set to EOP are
// reset to point to the second operand.
// b) Any PC_Arbno_Y node has its stack count field incremented
// by the parameter Incr provided for this purpose.
// d) Num fields of all pattern elements in the left operand are
// adjusted to include the elements of the right operand.
// Note: we do not use Set_Successor in the processing for Concat, since
// there is no point in doing two traversals, we may as well do everything
// at the same time.
function pe_conc(l, r, incr) {
if (l === EOP)
return r;
if (r === EOP)
return l;
// XXX optimize two strings with no alts?
// loop for all nodes in left
for (let p of l.ref_array()) {
p.index += r.index;
if (p instanceof PE_Arbno_Y) // OOF!
p.n += incr;
if (p.pthen === EOP)
p.pthen = r;
if (p.has_alt && p.alt === EOP)
p.alt = r;
} // for
return l;
}
////////////////
const STACK_SIZE = 2000; // XXX
class Match {
constructor(anchored) {
this.anchored = anchored;
this.region_level = 0;
this.cursor = 0;
this.subject = null; // set by match()
this.length = 0; // set by match()
this.node = null; // set by match()
this.stack = null; // set by match()
// Set true when assign-on-match (call-on-match) operations may be
// present in the history stack, which must then be scanned on a
// successful match.
this.assign_on_match = false;
this.debug = false;
// output:
this.start = 0;
this.stop = 0;
this.matched = null;
Object.seal(this);
}
match(subject, pat, stack_size) {
if (TEST_IMAGE)
console.log("match", pat.toString()); // XXX this.trace?
// XXX call this.trace w/ pat.trace??
this.subject = explode(subject); // Array of runes
this.length = this.subject.length;
this.node = pat.p;
if (!stack_size)
stack_size = STACK_SIZE;
if (stack_size < pat.stk*2)
stack_size = pat.stk*2;
this.stack = new Stack(stack_size);
// push initial stack entry based on anchored mode
if (this.anchored) {
// anchored: abort on backtrack.
this.stack.put(this.stack.init, 0, CP_Abort);
}
else {
// In unanchored mode, the bottom entry on the stack references
// the special pattern element PE_Unanchored, whose Pthen field
// points to the initial pattern element. The cursor value in this
// entry is the number of anchor moves so far.
this.stack.put(this.stack.init, 0, new PE_Unanchored(this.node));
}
this.trace(`======== match ${LQ}${subject}${RQ} anchored=${this.anchored}`);
while (this.node) {
let n = this.node;
this.trace_match(n)
switch (n.match(this)) {
case M_Succeed:
this.node = this.node.pthen;
this.trace(" success");
break;
case M_Fail: {
let stk = this.stack;
let top = stk.peek(stk.ptr);
if (DEBUG_STACK)
console.log(`ptr ${stk.ptr} top ${top.cursor} node ${top.node}`)
stk.ptr--; // XXX check? HIDE??
this.cursor = top.cursor;
this.node = top.node;
this.trace(` failed, cursor reset to ${this.cursor}`);
break;
}
case M_Continue: // node changed, continue
this.trace(" continue");
break;
case M_Pattern_Success:
this.trace("match succeeded");
this.start = this.stack.peek(this.stack.init).cursor + 1;
this.stop = this.cursor;
this.matched = this.slice(this.start, this.stop);
this.trace(` matched positions ${this.start} .. ${this.stop}`);
this.trace(` matched substring ${LQ}${this.matched}${RQ}`);
if (this.assign_on_match) {
let stk = this.stack;
for (let s = stk.first; s <= stk.ptr; s++) {
let stkent = stk.peek(s);
if (stkent.node === CP_Assign) {
let inner_base = stk.peek(s + 1).cursor; // stack ptr
let special_entry = stk.peek(inner_base - 1);
let start = special_entry.cursor + 1;
let stop = stkent.cursor; // from a CP_Assign stack entry
let str = this.slice(start, stop);
let on_match = special_entry.node;
on_match.onmatch(this, str);
} // CP_Assign
} // for each stack entry
} // assign_on_match
return true;
case M_Pattern_Fail:
this.trace("match failed");
return false;
}
} // while this.node
error("null PE node");
} // match
replace(repl) {
let before = this.subject.slice(0, this.start-1).join('');
let after = this.subject.slice(this.stop, this.length).join('');
return before + repl + after;
}
slice(start, stop) {
return this.subject.slice(start-1, stop).join('');
}
// Internal:
trace_match(n) { // overridden in DMatch
}
trace(msg) { // overridden in DMatch
}
petrace(pe, msg) { // overridden in DMatch
}
push(node) {
let stack = this.stack;
if (DEBUG_STACK)
console.log(`stack.push ${this.cursor} ${node.index}`);
stack.ptr++; // XXX check? HIDE??
stack.put(stack.ptr, this.cursor, node);
}
push_region() {
this.region_level++;
let stack = this.stack;
stack.ptr += 2; // XXX check? HIDE??
if (DEBUG_STACK) console.log("push_region", stack.base);
stack.put(stack.ptr, stack.base, CP_R_Remove);
stack.set_base(stack.ptr);
}
pop_region() {
this.region_level--; // XXX check?
let stack = this.stack;
if (stack.ptr === stack.base) {
stack.ptr -= 2; // XXX check? HIDE??
stack.set_base(stack.peek(stack.ptr + 2).cursor);
}
else {
stack.ptr++; // XXX check? HIDE??
stack.put(stack.ptr, stack.base, CP_R_Restore);
stack.set_base(stack.peek(stack.base).cursor);
}
}
} // Match
class DMatch extends Match { // debug match
constructor(anchored, stack_size) {
super(anchored, stack_size);
this.debug = true;
}
trace_match(n) {
// XXX if this.cursor < 0, display as stack pointer!!
// XXX need to handle negative (SP) values??
let before = this.slice(1, this.cursor);
let after = this.slice(this.cursor+1, this.length);
let str = LQ + before + CURSOR + after + RQ;
let nname = n.constructor.name;
this.trace(`cursor @${this.cursor} node #${n.index} ${nname} ${str}`);
}