-
Notifications
You must be signed in to change notification settings - Fork 15
/
Cursor.cs
1701 lines (1447 loc) · 51.2 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 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 void CallAction(string name, Cursor match) {
if (Cursor.Trace)
Console.WriteLine("To call action {0}", name);
if (actions == null || name == "" || name == null)
return;
DispatchEnt m;
IP6 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;
}
Frame nf = m.info.Binder(Kernel.GetInferiorRoot()
.MakeChild(m.outer, m.info), pos, null);
nf.curDisp = m;
Kernel.RunInferior(nf);
}
public GState(string orig, IP6 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 string BailAt =
Environment.GetEnvironmentVariable("NIECZA_DIE_AT_PCT");
public static 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 DynMetaObject 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 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
st.subrule_iter = null;
ip = (ip < 0) ? ip : (-ip-1);
}
public Choice(Choice prev, int ip, State st) {
this.ip = ip;
this.st = st;
this.prev = prev;
}
}
// 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 {
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 bool return_one;
// .from in matches
public int from;
// these go into the match but currently aren't scoped by backtrack
// control in any way
public IP6 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 passcap, 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, "RULE " + name, csr.nstate);
if (passcap)
st.captures = csr.captures;
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))
bt = bt.prev;
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
if (bt == rootf) {
if (return_one) {
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) {
DynObject lst = new DynObject(Kernel.ListMO);
lst.slots[0 /*items*/] = new VarDeque();
lst.slots[1 /*rest*/ ] = new VarDeque();
EmptyList = Kernel.NewRWListVar(lst);
}
th.caller.resultSlot = EmptyList;
}
return th.caller;
} 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) {
st.captures = new CapInfo(st.captures, cn, cl);
}
public void SetCursorList(object cl) {
st.subrule_iter = cl;
}
public Variable GetCursorList() {
return (Variable)st.subrule_iter;
}
public VarDeque GetCursorIter() {
return (VarDeque)st.subrule_iter;
}
public void SetCapturesFrom(Cursor inp) {
st.captures = inp.captures;
}
public void SetPos(int pos) {
st.pos = pos;
}
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 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() {
return !(st.pos++ == end);
}
public bool CClass(CC x) {
return !(st.pos == end || !x.Accepts(orig[st.pos++]));
}
public bool ZeroWidth(int type) {
int next = (st.pos == end) ? -1 : orig[st.pos];
int prev = (st.pos == 0) ? -1 : orig[st.pos-1];
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) || (prev == '\n' && next >= 0);
case 5:
return (next == '\n') || (next == -1 && prev != '\n');
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 - vec.Length;
if (offs < 0) return neg;
for (int i = 0; i < vec.Length; i++)
if (!vec[i].Accepts(orig[offs + i]))
return neg;
return !neg;
}
public bool BeforeCCs(bool neg, CC[] vec) {
if (end - st.pos < vec.Length) return neg;
for (int i = 0; i < vec.Length; i++)
if (!vec[i].Accepts(orig[st.pos + i]))
return neg;
return !neg;
}
public bool ScanCClass(int min, int max, CC x) {
int i;
int maxr = end - st.pos;
if (maxr < max) max = maxr;
for (i = 0; i < max && x.Accepts(orig[st.pos + i]); i++);
st.pos += i;
return (i >= min);
}
public void LTMPushAlts(Lexer lx, int[] addrs) {
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(addrs[cases[i]]);
}
}
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.quant++;
}
public void SetQuant(int data) {
st.ns.quant = data;
}
public int GetQuant() {
return st.ns.quant;
}
public DynMetaObject GetClass() { return st.ns.klass; }
public void SetClass(DynMetaObject dm) {
st.ns.klass = dm;
}
public Cursor MakeCursor() {
return new Cursor(global, st.ns.klass, this, st.ns, bt, st.pos, st.captures);
}
public Cursor MakeMatch() {
if (Cursor.Trace)
Console.WriteLine("Matching {0} from {1} to {2}",
name, from, st.pos);
return new Cursor(global, st.ns.klass, from, st.pos, st.captures, ast, name);
}
public static Variable EmptyList;
public Frame FinalEnd(Frame th) {
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
th.caller.resultSlot = Kernel.NewROScalar(MakeMatch());
return th.caller;
}
public Frame End(Frame th) {
return EndWith(th, MakeMatch());
}
// currently just used for protoregex
public Frame EndWith(Frame th, Cursor m) {
if (st.pos > global.highwater)
global.IncHighwater(st.pos);
if (return_one) {
return Kernel.Take(th, Kernel.NewROScalar(m));
} else {
th.MarkSharedChain();
return_one = true;
VarDeque ks = new VarDeque();
ks.Push(Kernel.NewROScalar(m));
th.lex = new Dictionary<string,object>();
th.lex["!return"] = null;
DynObject it = new DynObject(Kernel.GatherIteratorMO);
it.slots[0 /*frame*/] = Kernel.NewRWScalar(Kernel.AnyMO, th);
it.slots[1 /*reify*/] = Kernel.NewRWScalar(Kernel.AnyMO, Kernel.AnyP);
VarDeque iss = new VarDeque();
iss.Push(Kernel.NewROScalar(it));
DynObject lst = new DynObject(Kernel.ListMO);
lst.slots[0 /*items*/] = ks;
lst.slots[1 /*rest*/ ] = iss;
th.caller.resultSlot = Kernel.NewRWListVar(lst);
}
return th.caller;
}
}
// 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 : IP6 {
public static bool Trace =
Environment.GetEnvironmentVariable("NIECZA_RX_TRACE") != null;
public static 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 IP6 ast;
public int from;
public CapInfo captures;
public DynMetaObject save_klass;
public string GetBacking() { return global.orig_s; }
public Cursor(IP6 proto, string text, IP6 actions)
: this(new GState(text, actions), proto.mo, null, null, null, 0, null) { }
public Cursor(GState g, DynMetaObject klass, int from, int pos, CapInfo captures, IP6 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;
if (reduced != null)
g.CallAction(reduced, this);
}
public Cursor(GState g, DynMetaObject 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 Cursor Synthetic(Cursor parent, string method, int from,
int to, Variable caplist) {
VarDeque iter = new VarDeque(caplist);
CapInfo ci = null;
while (Kernel.IterHasFlat(iter, true)) {
IP6 pair = iter.Shift().Fetch();
Variable k = (Variable)pair.GetSlot("key");
Variable v = (Variable)pair.GetSlot("value");
ci = new CapInfo(ci, new string[] {
k.Fetch().mo.mro_raw_Str.Get(k) }, v);
}
return new Cursor(parent.global, parent.save_klass, from, to, ci,
null, method);
}
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(IP6 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();
DynObject l = new DynObject(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.NewROScalar(Kernel.AnyP);
}
}
public void Make(Variable itm) {
if (feedback != null)
feedback.ast = itm.Fetch();
else
ast = itm.Fetch();
}
public string Reduced() { return reduced; }
public IP6 AST() {
IP6 a = (feedback != null) ? feedback.ast : ast;
if (a != null)
return a;
else
return Kernel.BoxRaw<string>(GetBacking().Substring(from, pos - from), Kernel.StrMO);
}
// TODO: cache generated lists
public Variable GetKey(string str) {
CapInfo it = captures;
VarDeque caps = new VarDeque();
while (it != null) {
foreach (string cn in it.names) {
if (cn == str) {
caps.Unshift(it.cap);
break;
}
}
it = it.prev;
}
return FixupList(caps);
}
public void UnpackCaps(IP6 into) {
List<VarDeque> posr = new List<VarDeque>();
Dictionary<string,VarDeque> namr = new Dictionary<string,VarDeque>();
CapInfo it = captures;
while (it != null) {
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);
}
it = it.prev;
}
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("positionals", pos);
into.SetSlot("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.NewRWScalar(Kernel.AnyMO, kv.Value.Fetch()));
VarDeque ks = new VarDeque();
DynObject lst = new DynObject(Kernel.ListMO);
lst.slots[0 /*items*/] = ks;
lst.slots[1 /*rest*/ ] = new VarDeque();
ks.Push(Kernel.NewROScalar(nw));
return Kernel.NewRWListVar(lst);
}
public Variable SimpleWS() {
string backing = global.orig_s;
char[] backing_ca = global.orig_a;
int l = backing_ca.Length;
int p = pos;
VarDeque ks = new VarDeque();
DynObject lst = new DynObject(Kernel.ListMO);
lst.slots[0 /*items*/] = ks;
lst.slots[1 /*rest*/ ] = new VarDeque();
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);
} else {
while (p != l && Char.IsWhiteSpace(backing, p)) { p++; }
if (Trace)
Console.WriteLine("* match <ws> at {0} to {1}", pos, p);
ks.Push(Kernel.NewROScalar(At(p)));
}
return Kernel.NewRWListVar(lst);
}
}
public sealed class CC {
public readonly int[] vec;
public CC(int[] vec) {
this.vec = vec;
}
public CC(char butyes) : this(new int[] { butyes, -1, butyes+1, 0 }) { }
public CC(int catmask) : this(new int[] { 0, catmask }) { }
public CC(char butyes, bool nocase) {
if (nocase) {
char a = char.ToLowerInvariant(butyes);
char b = char.ToUpperInvariant(butyes);
if (a > b) { char t = a; a = b; b = t; }
if (a == b) {
vec = new int[] { a, -1, a+1, 0 };
} else {
vec = new int[] { a, -1, a+1, 0, b, -1, b+1, 0 };
}
} else {
vec = new int[] { butyes, -1, butyes+1, 0 };
}
}
public bool Accepts(char ch) {
int l = 0;
int h = vec.Length / 2;
if (h == 0 || ch < vec[0])
return false;
while (h - l > 1) {
int m = l + (h - l) / 2;
if (vec[m * 2] > ch) {
h = m;
} else {
l = m;
}
}
int mask = 1 << (int)char.GetUnicodeCategory(ch);
return (vec[l * 2 + 1] & mask) != 0;
}
public const int MAlpha = 0x1F;
public const int MMark = 0xE0;
public const int MNum = 0x700;
public const int MSpace = 0x3800;
public const int MControl = 0x3C000;
public const int MPunct = 0x1FC0000;
public const int MSymbol = 0x1E000000;
public const int MOther = 0x20000000;
public const int MAll = 0x3FFFFFFF;
public const int MAlNum = MAlpha | MNum;
public static readonly CC Word = new CC(new int[] { 0, MAlNum,
'_', MAll, '_'+1, MAlNum });
public static readonly CC All = new CC(MAll);
public static readonly CC None = new CC(0);
public static readonly CC AlNum = new CC(MAlNum);
private static readonly int[] masks = new int[] {
MAll, (MAll & ~MOther), 0x71F,
0x1F, 0xE0, 0x700, 0x3800, 0x3C000, 0x1FC0000, 0x1E000000,
(1<<0), (1<<1), (1<<2), (1<<3), (1<<4), (1<<5), (1<<6), (1<<7),
(1<<8), (1<<9), (1<<10), (1<<11), (1<<12), (1<<13), (1<<14), (1<<15),
(1<<16), (1<<17), (1<<18), (1<<19), (1<<20), (1<<21), (1<<22), (1<<23),
(1<<24), (1<<25), (1<<26), (1<<27), (1<<28), (1<<29),
};
private static readonly string[] masknames = new string[] {
"ALL", "Assigned", "Alnum",
"Alpha", "Mark", "Num", "Space", "Control", "Punct", "Symbol",
"Lu", "Ll", "Lt", "Lm", "Lo", "Mn", "Mc", "Me",
"Nd", "Nl", "No", "Zs", "Zl", "Zp", "Cc", "Cf",
"Cs", "Co", "Pc", "Pd", "Ps", "Pe", "Pi", "Pf",
"Po", "Sm", "Sc", "Sk", "So", "Cn"
};
public override string ToString() {
List<string> clauses = new List<string>();
for (int ix = 0; ix < vec.Length; ix += 2) {
string head = "";
int l = vec[ix];
int msk = vec[ix+1];
int h = (ix + 2 < vec.Length) ? vec[ix+2] : 0x110000;
if (msk == 0)
continue;
while (ix + 2 < vec.Length &&
(vec[ix+3] == MAll || vec[ix+3] == msk)) {
h = (ix + 4 < vec.Length) ? vec[ix+4] : 0x110000;
if (vec[ix+3] == MAll)
clauses.Add(h == vec[ix+2] + 1 ?
string.Format("({0:X4})", vec[ix+2]) :
string.Format("({0:X4}..{1:X4})", vec[ix+2], h-1));
ix += 2;
}
if (h != 0x110000 || l != 0 || ((msk & MAll) == MAll))
head = (h == l + 1) ?
string.Format("({0:X4})", l) :
string.Format("({0:X4}..{1:X4})", l, h-1);
if ((msk & MAll) != MAll) {
List<string> vc = new List<string>();
for (int mix = 0; mix < masks.Length; mix++)
if ((msk & masks[mix]) == masks[mix]) {
msk &= ~masks[mix];
vc.Add(masknames[mix]);
}
clauses.Add(head + Kernel.JoinS("+", vc));
} else
clauses.Add(head);
}
return Kernel.JoinS(",", clauses);
}
}
public sealed class NFA {
public sealed class Node {
public int fate;
public bool final;
public List<Edge> edges_l = new List<Edge>();
public Edge[] edges;
public Node(int curfate) { fate = curfate; }
public override string ToString() {
return "(" + fate + ")" + (final ? "+ " : " ") +
Kernel.JoinS(", ", edges_l);
}
}
public struct Edge {
public int to;
public CC when; // null if epsilon
public override string ToString() {
return ((when != null) ? when.ToString() : "ε") + " => " + to;
}
}
public List<Node> nodes_l = new List<Node>();
public Node[] nodes;
public int curfate;
public DynMetaObject cursor_class;
public HashSet<string> method_stack = new HashSet<string>();
public HashSet<string> used_methods = new HashSet<string>();
public List<Frame> outer_stack = new List<Frame>();
public Dictionary<string,LAD> method_cache = new Dictionary<string,LAD>();
public Dictionary<string,Frame> outer_cache = new Dictionary<string,Frame>();
public LAD ResolveMethod(string name, out Frame outer) {
LAD sub = null;
if (method_cache.TryGetValue(name, out sub)) {
if (Lexer.LtmTrace)
Console.WriteLine("+ Method HIT for {0}", name);
outer = outer_cache[name];
return sub;
}
if (Lexer.LtmTrace)
Console.WriteLine("+ Method MISS for {0}", name);
IP6 method = cursor_class.Can(name);
if (Lexer.LtmTrace && method != null)
Console.WriteLine("+ Found method");
if (method == null) {
outer = outer_cache[name] = null;
return method_cache[name] = new LADImp();
}
sub = ((SubInfo)(((DynObject)method).GetSlot("info"))).ltm;
outer = ((Frame)(((DynObject)method).GetSlot("outer")));
if (Lexer.LtmTrace)
Console.WriteLine("+ {0} to sub-automaton",
(sub != null ? "Resolved" : "Failed to resolve"));
method_cache[name] = sub;
outer_cache[name] = outer;
return sub;
}
public int AddNode() {
nodes_l.Add(new Node(curfate));
return nodes_l.Count - 1;
}
public void AddEdge(int from, int to, CC when) {
Edge e;
e.to = to;
e.when = when;
nodes_l[from].edges_l.Add(e);
}
public void Dump() {
for (int ix = 0; ix < nodes_l.Count; ix++) {
Console.WriteLine(ix + ": " + nodes_l[ix].ToString());
}
}
int[] greybuf;
public void Close(LexerState ls) {
int ngrey = 0;
for (int i = 0; i < ls.nstates.Length; i++) {
int bm = ls.nstates[i];
for (int j = 0; j < 32; j++) {
if ((bm & (1 << j)) != 0)
greybuf[ngrey++] = 32*i + j;
}
}
while (ngrey != 0) {
int val = greybuf[--ngrey];
foreach (NFA.Edge e in nodes[val].edges) {
if (e.when == null) {
int ix = e.to >> 5;
int m = 1 << (e.to & 31);
if ((ls.nstates[ix] & m) == 0) {
ls.nstates[ix] |= m;
greybuf[ngrey++] = e.to;
}
}
}
}
}
public void Complete() {
nodes = nodes_l.ToArray();
greybuf = new int[nodes.Length];
foreach (Node n in nodes)
n.edges = n.edges_l.ToArray();
}
public Dictionary<LexerState,LexerState> dfashare
= new Dictionary<LexerState,LexerState>();
}
// ltm automaton descriptors
public abstract class LAD {
public abstract void ToNFA(NFA pad, int from, int to);
public abstract void Dump(int indent);
public virtual void QueryLiteral(NFA pad, out int len, out bool cont) {
len = 0; cont = false;
}
public abstract LAD Reify(NFA pad);
}
public class LADStr : LAD {
public readonly string text;
public LADStr(string text) { this.text = text; }
public override LAD Reify(NFA pad) { return this; }
public override void QueryLiteral(NFA pad, out int len, out bool cont) {
len = text.Length; cont = true;
}
public override void ToNFA(NFA pad, int from, int to) {
if (text.Length == 0) {
pad.AddEdge(from, to, null);
} else {
int len = text.Length;
for (int c = 0; c < len; c++) {
int fromp = (c == len - 1) ? to : pad.AddNode();
pad.AddEdge(from, fromp, new CC(text[c]));
from = fromp;
}
}
}
public override void Dump(int indent) {
Console.WriteLine(new string(' ', indent) + "str: " + text);
}
}
public class LADStrNoCase : LAD {
public readonly string text;
public LADStrNoCase(string text) { this.text = text; }
public override LAD Reify(NFA pad) { return this; }
public override void QueryLiteral(NFA pad, out int len, out bool cont) {
len = text.Length; cont = true;
}
public override void ToNFA(NFA pad, int from, int to) {
if (text.Length == 0) {
pad.AddEdge(from, to, null);
} else {
int len = text.Length;
for (int c = 0; c < len; c++) {
int fromp = (c == len - 1) ? to : pad.AddNode();
pad.AddEdge(from, fromp, new CC(text[c], true));
from = fromp;
}
}
}
public override void Dump(int indent) {
Console.WriteLine(new string(' ', indent) + "strnocase: " + text);
}
}
public class LADCC : LAD {
public readonly CC cc;
public LADCC(CC cc) { this.cc = cc; }
public override LAD Reify(NFA pad) { return this; }
public override void ToNFA(NFA pad, int from, int to) {
pad.AddEdge(from, to, cc);
}
public override void Dump(int indent) {
Console.WriteLine(new string(' ', indent) + "cc: " + cc.ToString());
}
}
public class LADImp : LAD {
public override LAD Reify(NFA pad) { return this; }
public override void ToNFA(NFA pad, int from, int to) {
int knot = pad.AddNode();
pad.nodes_l[knot].final = true;
pad.AddEdge(from, knot, null);
}
public override void Dump(int indent) {
Console.WriteLine(new string(' ', indent) + "imp");
}
}
public class LADNull : LAD {