/
Cursor.cs
2196 lines (1915 loc) · 68.1 KB
/
Cursor.cs
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
using Niecza;
using Niecza.Serialization;
using System;
using System.Collections.Generic;
using System.Text;
// global stuff
public sealed class GState {
public char[] orig_a;
public string orig_s;
public int highwater;
public Variable actions;
internal Frame CallAction(Frame th, string name, Cursor match) {
if (actions == null || name == "" || name == null)
return th;
if (Cursor.Trace)
Console.WriteLine("To call action {0}", name);
DispatchEnt m;
P6any actions_p = actions.Fetch();
Variable[] pos;
if (actions_p.mo.mro_methods.TryGetValue(name, out m)) {
pos = new Variable[] { actions, Kernel.NewROScalar(match) };
} else if (actions_p.mo.mro_methods.TryGetValue("FALLBACK", out m)) {
pos = new Variable[] { actions,
Kernel.BoxAnyMO<string>(name, Kernel.StrMO),
Kernel.NewROScalar(match) };
} else {
return th;
}
return m.info.SetupCall(th, m.outer, m.ip6, pos, null, false, m);
}
public GState(string orig, P6any actions) {
this.actions = (actions == Kernel.AnyP) ? null :
Kernel.NewROScalar(actions);
orig_s = orig;
orig_a = orig.ToCharArray();
highwater = (orig_a.Length < 100 || !Cursor.HwTrace) ?
int.MaxValue : 0;
}
public static readonly string BailAt =
Environment.GetEnvironmentVariable("NIECZA_DIE_AT_PCT");
public static readonly int BailAtI;
static GState() {
if (!int.TryParse(BailAt, out BailAtI))
BailAtI = 101;
}
public void IncHighwater(int to) {
int pct = to * 100 / orig_a.Length;
// cheat a bit: don't report highwater again until pct increases
// (pct+1) <= (new-to) * 100 / len
// (pct+1) * len <= (new-to) * 100
// ceil(((pct+1) * len) / 100) <= new-to
highwater = ((pct + 1) * orig_a.Length + 99) / 100;
Console.WriteLine("Parsed {0}% of {1} characters", pct, orig_a.Length);
if (pct == BailAtI)
throw new Exception("Backtrace at percent");
}
}
// stuff that should 'N'est, like subrules do
public sealed class NState {
public NState next;
public string name;
public Choice cut_to;
public int quant;
public STable klass;
public NState(Choice cut_to, string name, NState proto) {
next = proto; this.cut_to = cut_to; this.name = name;
if (proto != null) klass = proto.klass;
}
public NState(NState f) {
next = f.next; name = f.name; cut_to = f.cut_to;
quant = f.quant; klass = f.klass;
}
}
public sealed class CapInfo {
public CapInfo prev;
public string[] names;
public Variable cap;
public CapInfo(CapInfo prev, string[] names, Variable cap) {
this.prev = prev; this.names = names; this.cap = cap;
}
}
public struct State {
public CapInfo captures;
public NState ns;
public object subrule_iter;
public int pos;
}
public sealed class Choice {
public Choice prev;
public State st;
// the current Choice doesn't really have any of these fields, which are
// used for backtrack control
public int ip;
public void Commit() {
// we aren't going to backtrack here, so we can't use this.
// help out the GC
if (ip > 0 || ip < -10) {
st.subrule_iter = null;
}
ip = (ip < 0) ? ip : (-ip-10);
}
public Choice(Choice prev, int ip, State st) {
this.ip = ip;
this.st = st;
this.prev = prev;
}
}
public class AltInfo : IFreeze {
public int[] labels;
public LAD[] prefixes;
public string dba;
//public readonly STable in_class;
public AltInfo(LAD[] prefixes, string dba, int[] labels) {
this.labels = labels;
this.prefixes = prefixes;
this.dba = dba;
}
private AltInfo() { }
void IFreeze.Freeze(FreezeBuffer fb) {
fb.Byte((byte) SerializationCode.AltInfo);
fb.Ints(labels);
fb.Refs(prefixes);
fb.String(dba);
}
internal static AltInfo Thaw(ThawBuffer tb) {
var n = new AltInfo();
tb.Register(n);
n.labels = tb.Ints();
n.prefixes = tb.RefsA<LAD>();
n.dba = tb.String();
return n;
}
}
// extends Frame for a time/space tradeoff
// we keep the cursor in exploded form to avoid creating lots and lots of
// cursor objects
public sealed class RxFrame: IFreeze {
public Choice bt;
public State st;
// when this is set, one value has already been given, so we don't need
// any more Lists
public const int RETURN_ONE = 1;
// <( and )> have been used; MakeMatch needs to search for the end
// tokens
public const int USED_ENDS = 2;
public byte flags;
// .from in matches
public int from;
// these go into the match but currently aren't scoped by backtrack
// control in any way
public P6any ast;
public GState global;
// our backing string, in a cheap to index form
public char[] orig;
// cache of orig.Length
public int end;
public string name;
// don't remove this on backtracking, and quit if we would back into it
public readonly Choice rootf;
public RxFrame(string name, Cursor csr, bool passcut) {
global = csr.global;
orig = global.orig_a;
end = orig.Length;
rootf = bt = csr.xact;
this.name = name;
st.ns = passcut ? csr.nstate :
new NState(rootf, name, csr.nstate);
if (Cursor.Trace) {
Console.WriteLine("Entering subrule {0} at {1}/{2}", name, csr.pos,
end);
}
st.ns.klass = csr.mo;
st.pos = csr.pos;
from = csr.pos;
}
public Frame Backtrack(Frame th) {
// throw away cut or mark-only frames
while (bt != rootf && (bt.ip < 0)) {
if (bt.ip == -1) {
// Special frame that does $*GOAL cleanup ...
th.LexicalBind("$*GOAL", (Variable)bt.st.subrule_iter);
}
bt = bt.prev;
}
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
if (bt == rootf) {
if ((flags & RETURN_ONE) != 0) {
if (Cursor.Trace)
Console.WriteLine("Failing {0}@{1} after no matches",
name, from);
return Kernel.Take(th, Kernel.NewROScalar(Kernel.EMPTYP));
} else {
if (Cursor.Trace)
Console.WriteLine("Failing {0}@{1} after some matches",
name, from);
if (EmptyList == null) {
P6opaque lst = new P6opaque(Kernel.ListMO);
lst.slots[0 /*items*/] = new VarDeque();
lst.slots[1 /*rest*/ ] = new VarDeque();
EmptyList = Kernel.NewRWListVar(lst);
}
th.caller.resultSlot = EmptyList;
}
return th.Return();
} else {
th.ip = bt.ip;
st = bt.st;
bt = bt.prev;
return th;
}
}
public void PushBacktrack(int ip) {
bt = new Choice(bt, ip, st);
}
public void PushCapture(string[] cn, Variable cl) {
if (cn.Length == 0) return;
st.captures = new CapInfo(st.captures, cn, cl);
}
public void SetCursorList(object cl) {
st.subrule_iter = cl;
}
public void InitCursorList(Variable obj) {
st.subrule_iter = Builtins.start_iter(obj);
}
public Variable GetCursorList() {
return (Variable)st.subrule_iter;
}
public VarDeque GetCursorIter() {
return (VarDeque)st.subrule_iter;
}
public void SetPos(int pos) {
st.pos = pos;
}
// This is not the most efficient way, but it avoids adding another
// field to the backtrack state.
public void SetEndpoint(string which) {
flags |= USED_ENDS;
PushCapture(new string[] { null, which }, Builtins.MakeInt(st.pos));
}
public void IncorporateChild(string[] names, P6any match) {
Cursor child = match as Cursor;
if (child == null)
throw new NieczaException((names.Length == 0 ?
"Anonymous submatch" : "Submatch to be bound to " + names[0]) +
" returned a " + match.mo.name + " instead of a Cursor, " +
"violating the submatch protocol.");
SetPos(child.pos);
if (names != null)
PushCapture(names, Kernel.NewROScalar(child));
}
public const int IC_ZERO_WIDTH = 1;
public const int IC_NEGATIVE = 2;
public bool IncorpCut(string[] names, int mode, Variable list) {
Variable match_v = Kernel.GetFirst(list);
P6any match = match_v.Fetch();
if (match.IsDefined() == ((mode & IC_NEGATIVE) != 0))
return false;
if ((mode & IC_ZERO_WIDTH) == 0)
IncorporateChild(names, match);
return true;
}
public bool IncorpShift(string[] names, int label) {
if (!Kernel.IterHasFlat(GetCursorIter(), true))
return false;
PushBacktrack(label);
IncorporateChild(names, GetCursorIter().Shift().Fetch());
SetCursorList(null);
return true;
}
public int GetPos() {
return st.pos;
}
public void PushCutGroup(string tag) {
st.ns = new NState(bt, tag, st.ns);
}
public void PopCutGroup() {
st.ns = st.ns.next;
}
public void CommitAll() {
Choice x = bt;
while (x != null) {
x.Commit();
x = x.prev;
}
}
public void CommitRule() {
Choice x = bt;
while (x != rootf) {
x.Commit();
x = x.prev;
}
}
public void CommitGroup(string id) {
NState nsi = st.ns;
while (nsi != null && !nsi.name.Equals(id))
nsi = nsi.next;
Choice to = (nsi != null) ? nsi.cut_to : null;
Choice it = bt;
while (it != to) {
it.Commit();
it = it.prev;
}
}
public void PushGoal(Frame th, string newGoal) {
bt = new Choice(bt, -1, st);
bt.st.subrule_iter = th.LexicalFind("$*GOAL");
th.LexicalBind("$*GOAL", Builtins.MakeStr(newGoal));
st.ns = new NState(bt, "GOAL", st.ns);
st.ns.quant = st.pos;
}
public void PopGoal(Frame th) {
bt = new Choice(bt, -1, st);
bt.st.subrule_iter = th.LexicalFind("$*GOAL");
th.LexicalBind("$*GOAL", (Variable)st.ns.cut_to.st.subrule_iter);
st.ns = st.ns.next;
}
public bool Exact(string str) {
if (st.pos + str.Length > end)
return false;
foreach (char ch in str)
if (orig[st.pos++] != ch)
return false;
return true;
}
public bool ExactNoCase(string str) {
if (st.pos + str.Length > end)
return false;
foreach (char ch in str)
if (!CaselessEq(orig[st.pos++], ch))
return false;
return true;
}
// this is wrong, but it's good enough for now XXX
private static bool CaselessEq(char src, char tst) {
return src == char.ToLowerInvariant(tst) ||
src == char.ToUpperInvariant(tst);
}
public bool ExactOne(char ch) {
return !(st.pos == end || orig[st.pos++] != ch);
}
public bool ExactOneNoCase(char ch) {
return !(st.pos == end || !CaselessEq(orig[st.pos++], ch));
}
public bool AnyChar() {
if (st.pos++ == end) return false;
if (((uint)(orig[st.pos-1] - 0xD800)) < 0x400u && st.pos != end)
st.pos++; // skip low surrogate; we assume well-formed input
return true;
}
public bool CClass(CC x) {
if (st.pos++ == end) return false;
int ho = orig[st.pos-1];
int hs = ho - 0xD800;
if (((uint)hs) < 0x400u && st.pos != end) {
st.pos++;
return x.Accepts(0x10000 - 0xDC00 + orig[st.pos-1] + 0x400 * hs);
} else {
return x.Accepts(ho);
}
}
public bool Newline() {
if (st.pos == end) return false;
char next = orig[st.pos++];
if (next == '\r' && st.pos != end && orig[st.pos] == '\n') {
st.pos++;
return true;
}
return CC.VSpace.Accepts(next);
}
public bool ZeroWidth(int type) {
int next = (st.pos == end) ? -1 : orig[st.pos];
int prev = (st.pos == 0) ? -1 : orig[st.pos-1];
bool crlf = (prev == '\r' && next == '\n');
switch(type) {
case 0:
return (next >= 0) && CC.Word.Accepts((char)next) &&
((prev < 0) || !CC.Word.Accepts((char)prev));
case 1:
return (prev >= 0) && CC.Word.Accepts((char)prev) &&
((next < 0) || !CC.Word.Accepts((char)next));
case 2:
return (prev == -1);
case 3:
return (next == -1);
case 4:
return (prev == -1 ||
(!crlf && CC.VSpace.Accepts(prev) && next >= 0));
case 5:
return (CC.VSpace.Accepts(next) && !crlf) ||
(next == -1 && !CC.VSpace.Accepts(prev));
default:
return false;
}
}
public bool BeforeStr(bool not, string tx) {
bool ok = st.pos <= end - tx.Length;
for (int ix = 0; ix < tx.Length && ok; ix++)
ok = orig[st.pos + ix] == tx[ix];
return (not != ok);
}
public bool AfterCCs(bool neg, CC[] vec) {
int offs = st.pos;
for (int i = vec.Length - 1; i >= 0; i--) {
if (offs == 0)
return neg;
int ch = orig[--offs];
if (((uint)(ch - 0xDC00)) < 0x400u && offs != 0) {
ch = orig[--offs] * 0x400 + ch +
(0x10000 - (0xD800 * 0x400 + 0xDC00));
}
if (!vec[i].Accepts(ch))
return neg;
}
return !neg;
}
public bool BeforeCCs(bool neg, CC[] vec) {
int offs = st.pos;
int upto = end;
for (int i = 0; i < vec.Length; i++) {
if (offs == upto) return neg;
int ch = orig[offs++];
if (((uint)(ch - 0xD800)) < 0x400u && offs != upto) {
ch = orig[offs++] + ch * 0x400 +
(0x10000 - (0xD800 * 0x400 + 0xDC00));
}
if (!vec[i].Accepts(ch))
return neg;
}
return !neg;
}
public bool ScanCClass(int min, int max, CC x) {
int i = 0;
int at = st.pos;
int upto = end;
while (i < max && at < upto) {
int oat = at;
int ch = orig[at++];
if (((uint)(ch - 0xD800)) < 0x400u && at != upto) {
ch = orig[at++] + ch * 0x400 +
(0x10000 - (0xD800 * 0x400 + 0xDC00));
}
if (x.Accepts(ch)) {
i++;
} else {
at = oat;
break;
}
}
st.pos = at;
return (i >= min);
}
public void LTMPushAlts(Frame fr, AltInfo ai) {
Lexer lx = Lexer.GetLexer(fr, GetClass(), ai.prefixes, ai.dba);
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
PushCutGroup("LTM");
int[] cases = lx.Run(global.orig_s, st.pos);
for (int i = cases.Length - 1; i >= 0; i--) {
PushBacktrack(ai.labels[cases[i]]);
}
}
public Frame scalar_var(Frame th, Variable var) { return scalar_common(false, th, var); }
public Frame scalar_asn(Frame th, Variable var) { return scalar_common(true, th, var); }
Frame scalar_common(bool eval, Frame th, Variable var) {
P6any o = var.Fetch();
if (o.Isa(Kernel.RegexMO)) {
return o.Invoke(th, new Variable[] { MakeCursorV() }, null);
} else if (eval) {
P6any rx = Builtins.compile_bind_regex(th,
o.mo.mro_raw_Str.Get(var));
return rx.Invoke(th, new Variable[] { MakeCursorV() }, null);
} else {
if (Exact(o.mo.mro_raw_Str.Get(var))) {
th.resultSlot = MakeCursorV();
} else {
th.resultSlot = Kernel.NilP.mo.typeVar;
}
return th;
}
}
public Frame list_var(Frame th, Variable var) { return list_common(false, th, var); }
public Frame list_asn(Frame th, Variable var) { return list_common(true, th, var); }
public Frame list_common(bool eval, Frame th, Variable var) {
VarDeque iter = Builtins.start_iter(var);
List<object> toks = new List<object>();
List<LAD> lads = new List<LAD>();
NFA pad = new NFA();
pad.cursor_class = st.ns.klass;
while (Kernel.IterHasFlat(iter, true)) {
Variable svar = iter.Shift();
P6any sobj = svar.Fetch();
retry:
if (sobj.Isa(Kernel.RegexMO)) {
toks.Add(sobj);
pad.outer_stack.Add(Kernel.GetOuter(sobj));
pad.info_stack.Add(Kernel.GetInfo(sobj));
lads.Add(pad.info_stack[0].ltm.Reify(pad));
pad.outer_stack.Clear();
pad.info_stack.Clear();
} else if (eval) {
sobj = Builtins.compile_bind_regex(th,
sobj.mo.mro_raw_Str.Get(svar));
svar = Kernel.NewROScalar(sobj);
goto retry;
} else {
string str = sobj.mo.mro_raw_Str.Get(svar);
toks.Add(str);
lads.Add(new LADStr(str));
}
}
int[] cases = (new Lexer(pad, "array_var", lads.ToArray())).
Run(global.orig_s, st.pos);
Frame nth = th.MakeChild(null, ArrayHelperSI, Kernel.AnyP);
nth.lex0 = MakeCursor();
nth.lex1 = toks;
nth.lex2 = cases;
return nth;
}
public Frame proto_dispatch(Frame th, Variable unused) {
Frame nth = th.MakeChild(null, Lexer.StandardProtoSI, Kernel.AnyP);
nth.pos = new Variable[] { MakeCursorV() };
return nth;
}
private static SubInfo ArrayHelperSI = new SubInfo("KERNEL ArrayHelper", ArrayHelperC);
private static Frame ArrayHelperC(Frame th) {
int[] cases = (int[]) th.lex2;
List<object> toks = (List<object>) th.lex1;
object tok;
switch (th.ip) {
default:
return Kernel.Die(th, "Invalid IP");
case 1:
return th.rx.Backtrack(th);
case 0:
th.rx = new RxFrame("ArrayHelper", (Cursor) th.lex0, false);
th.lexi0 = 0;
goto case 2;
case 2:
if (th.lexi0 == cases.Length)
goto case 1;
th.rx.PushBacktrack(2);
tok = toks[cases[th.lexi0++]];
if (tok is string) {
if (!th.rx.Exact((string)tok))
goto case 1;
th.ip = 5;
return th.rx.MakeMatch(th);
} else {
th.ip = 3;
return ((P6any)tok).Invoke(th, new Variable[] {
th.rx.MakeCursorV() }, null);
}
case 3:
th.lex2 = Builtins.start_iter((Variable) th.resultSlot);
goto case 4;
case 4:
if (!Kernel.IterHasFlat((VarDeque)th.lex2, true))
goto case 1;
th.ip = 4;
return th.rx.EndWith(th, (Cursor) ((VarDeque)th.lex2).Shift().Fetch());
case 5:
th.ip = 1;
return th.rx.End(th);
}
}
public void PushConjStart() {
st.ns = new NState(bt, "CSTART", st.ns);
st.ns.quant = st.pos;
}
public void PushConjEnd() {
st.ns = new NState(bt, "CEND", st.ns);
st.ns.quant = st.pos;
}
public void GotoConjStart() {
st.pos = st.ns.next.quant;
}
public bool CheckConjEnd() {
return (st.pos == st.ns.quant);
}
public void EndConj() {
st.ns = st.ns.next.next;
}
public void OpenQuant() {
st.ns = new NState(bt, "QUANT", st.ns);
}
public int CloseQuant() {
int x = st.ns.quant;
st.ns = st.ns.next;
return x;
}
public void IncQuant() {
st.ns = new NState(st.ns);
st.ns.quant++;
}
public void SetQuant(int data) {
st.ns.quant = data;
}
public int GetQuant() {
return st.ns.quant;
}
public STable GetClass() { return st.ns.klass; }
public void SetClass(STable dm) {
st.ns.klass = dm;
}
public Variable StringCapture() {
return Kernel.NewROScalar(
new Cursor(global, st.ns.klass, st.ns.quant, st.pos,
null, null, "ANON"));
}
public Cursor MakeCursor() {
return new Cursor(global, st.ns.klass, this, st.ns, bt, st.pos, st.captures);
}
public Variable MakeCursorV() { return Kernel.NewROScalar(MakeCursor()); }
Cursor _matchObj;
public Frame MakeMatch(Frame th) {
int use_from = from;
int use_to = st.pos;
if ((flags & USED_ENDS) != 0) {
for (CapInfo c = st.captures; c != null; c = c.prev) {
if (c.names[0] == null && c.names[1] == "from")
use_from = Kernel.UnboxAny<int>(c.cap.Fetch());
if (c.names[0] == null && c.names[1] == "to")
use_to = Kernel.UnboxAny<int>(c.cap.Fetch());
}
}
if (Cursor.Trace)
Console.WriteLine("Matching {0} from {1} to {2} (really {3}-{4})",
name, use_from, use_to, from, st.pos);
_matchObj = new Cursor(global, st.ns.klass, use_from, use_to,
st.captures, ast, name);
return global.CallAction(th, name, _matchObj);
}
[CompartmentGlobal]
public static Variable EmptyList;
public Frame FinalEnd(Frame th) {
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
th.caller.resultSlot = Kernel.NewROScalar(_matchObj);
return th.Return();
}
public Frame End(Frame th) {
return EndWith(th, _matchObj);
}
// currently just used for protoregex
public Frame EndWith(Frame th, Cursor m) {
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
if ((flags & RETURN_ONE) != 0) {
return Kernel.Take(th, Kernel.NewROScalar(m));
} else {
th.MarkSharedChain();
flags |= RETURN_ONE;
VarDeque ks = new VarDeque();
ks.Push(Kernel.NewROScalar(m));
th.coro_return = th;
P6opaque it = new P6opaque(Kernel.GatherIteratorMO);
it.slots[0 /*frame*/] = Kernel.NewMuScalar(th);
it.slots[1 /*reify*/] = Kernel.NewMuScalar(Kernel.AnyP);
VarDeque iss = new VarDeque();
iss.Push(Kernel.NewROScalar(it));
P6opaque lst = new P6opaque(Kernel.ListMO);
lst.slots[0 /*items*/] = ks;
lst.slots[1 /*rest*/ ] = iss;
th.caller.resultSlot = Kernel.NewRWListVar(lst);
}
return th.Return();
}
void IFreeze.Freeze(FreezeBuffer fb) { throw new NotImplementedException(); }
}
// This is used to carry match states in and out of subrules. Within subrules,
// match states are represented much more ephemerally in the state of RxFrame.
// this does double duty backing Match; note that Cursor and Match need to be
// treated polymorphically in a couple places
public class Cursor : P6any {
public static readonly bool Trace =
Environment.GetEnvironmentVariable("NIECZA_RX_TRACE") != null;
public static readonly bool HwTrace =
Environment.GetEnvironmentVariable("NIECZA_HIGHWATER_TRACE") != null;
// common fields
public GState global;
public int pos;
// Cursor only
public Choice xact;
public NState nstate;
public RxFrame feedback;
// Match only
public string reduced;
public P6any ast;
public int from;
public CapInfo captures;
public STable save_klass;
public override string ReprName() { return "P6cursor"; }
public override void Freeze(FreezeBuffer fb) { throw new NotImplementedException(); }
public string GetBacking() { return global.orig_s; }
public Cursor(P6any proto, string text, P6any actions)
: this(new GState(text, actions), proto.mo, null, null, null, 0, null) { }
public Cursor(GState g, STable klass, int from, int pos, CapInfo captures, P6any ast, string reduced) {
this.global = g;
this.captures = captures;
this.pos = pos;
this.ast = ast;
this.from = from;
this.mo = Kernel.MatchMO;
this.save_klass = klass;
this.reduced = reduced;
}
public Cursor(GState g, STable klass, RxFrame feedback, NState ns, Choice xact, int pos, CapInfo captures) {
this.mo = this.save_klass = klass;
this.xact = xact;
this.nstate = ns;
this.feedback = feedback;
this.global = g;
this.pos = pos;
this.captures = captures;
}
public static Frame Synthetic(Frame th, Cursor parent, string method,
int from, int to, Variable caplist) {
VarDeque iter = Builtins.start_iter(caplist);
CapInfo ci = null;
while (Kernel.IterHasFlat(iter, true)) {
P6any pair = iter.Shift().Fetch();
Variable k = (Variable)pair.GetSlot(Kernel.EnumMO, "$!key");
Variable v = (Variable)pair.GetSlot(Kernel.EnumMO, "$!value");
ci = new CapInfo(ci, new string[] {
k.Fetch().mo.mro_raw_Str.Get(k) }, v);
}
Cursor r = new Cursor(parent.global, parent.save_klass, from, to, ci,
null, method);
th.info.dylex["$*match"].Set(th, Kernel.NewROScalar(r));
if (method == "") {
return th;
} else {
return r.global.CallAction(th, method, r);
}
}
public override bool IsDefined() {
return true;
}
public Cursor At(int npos) {
return new Cursor(global, mo, feedback, nstate, xact, npos, null);
}
public Cursor UnMatch() {
return new Cursor(global, save_klass, null, null, null, pos, null);
}
public Cursor FreshClass(P6any from) {
return new Cursor(global, from.mo, feedback, nstate, xact, pos, null);
}
public Cursor StripCaps() {
return new Cursor(global, save_klass, from, pos, null, ast, reduced);
}
private Variable FixupList(VarDeque caps) {
if (caps.Count() != 0 && caps[0] == null) {
caps.Shift();
P6opaque l = new P6opaque(Kernel.ListMO);
l.slots[0 /*items*/] = caps;
l.slots[1 /*rest*/ ] = new VarDeque();
return Kernel.NewROScalar(l);
} else {
return caps.Count() != 0 ? caps[0] : Kernel.AnyMO.typeVar;
}
}
public void Make(Variable itm) {
if (feedback != null)
feedback.ast = itm.Fetch();
else
ast = itm.Fetch();
}
public string Reduced() { return reduced; }
public P6any AST() {
P6any a = (feedback != null) ? feedback.ast : ast;
return a ?? Kernel.AnyMO.typeObject;
}
// TODO: cache generated lists
public Variable GetKey(string str) {
CapInfo it = captures;
VarDeque caps = new VarDeque();
for (; it != null; it = it.prev) {
if (it.names[0] == null)
continue; // special node
foreach (string cn in it.names) {
if (cn == str) {
caps.Unshift(it.cap);
break;
}
}
}
return FixupList(caps);
}
public void UnpackCaps(P6any into) {
List<VarDeque> posr = new List<VarDeque>();
Dictionary<string,VarDeque> namr = new Dictionary<string,VarDeque>();
CapInfo it = captures;
for (; it != null; it = it.prev) {
if (it.names[0] == null)
continue; // special node
foreach (string name in it.names) {
int nami;
VarDeque t;
if (int.TryParse(name, out nami) && nami >= 0) {
while(posr.Count <= nami) posr.Add(new VarDeque());
t = posr[nami];
} else {
if (!namr.TryGetValue(name, out t))
namr[name] = t = new VarDeque();
}
t.Unshift(it.cap);
}
}
VarHash nam = new VarHash();
Variable[] pos = new Variable[posr.Count];
foreach (KeyValuePair<string, VarDeque> kv in namr)
nam[kv.Key] = FixupList(kv.Value);
for (int i = 0; i < pos.Length; i++)
pos[i] = FixupList(posr[i]);
into.SetSlot(Kernel.CaptureMO, "$!positionals", pos);
into.SetSlot(Kernel.CaptureMO, "$!named", nam);
}
public Variable O(VarHash caps) {
Cursor nw = At(pos);
foreach (KeyValuePair<string,Variable> kv in caps)
nw.captures = new CapInfo(nw.captures, new string[] { kv.Key },
Kernel.NewMuScalar(kv.Value.Fetch()));
return Kernel.NewROScalar(nw);
}
public Variable SimpleWS() {
string backing = global.orig_s;
char[] backing_ca = global.orig_a;
int l = backing_ca.Length;
int p = pos;
if (p != 0 && p != l && CC.Word.Accepts(backing[p]) &&
CC.Word.Accepts(backing[p-1])) {
if (Trace)
Console.WriteLine("! no match <ws> at {0}", pos);
return Kernel.NilP.mo.typeVar;
} else {
while (p != l && Char.IsWhiteSpace(backing, p)) { p++; }
if (Trace)
Console.WriteLine("* match <ws> at {0} to {1}", pos, p);
return Kernel.NewROScalar(At(p));
}
}
}
public partial class Builtins {
public static Variable cursor_allcaps(Variable cv) {
Cursor c = (Cursor) cv.Fetch();
VarDeque dq = new VarDeque();
for (CapInfo it = c.captures; it != null; it = it.prev) {
if (it.names[0] == null || it.cap == null)
continue; // special node
if (!it.cap.Fetch().Isa(Kernel.MatchMO))
continue;
foreach (string name in it.names)
dq.Unshift(pair(MakeStr(name), it.cap));
}
P6opaque lst = new P6opaque(Kernel.ListMO);
lst.slots[0 /*items*/] = dq;
lst.slots[1 /*rest*/ ] = new VarDeque();
return Kernel.NewRWListVar(lst);
}
}
public sealed class CC : IFreeze {
public readonly int[] vec;
public CC(int[] vec) {
this.vec = vec;