-
Notifications
You must be signed in to change notification settings - Fork 0
/
lptree.c
1235 lines (1077 loc) · 33.3 KB
/
lptree.c
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
/*
** $Id: lptree.c,v 1.10 2013/04/12 16:30:33 roberto Exp $
** Copyright 2013, Lua.org & PUC-Rio (see 'lpeg.html' for license)
*/
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lptypes.h"
#include "lpcap.h"
#include "lpcode.h"
#include "lpprint.h"
#include "lptree.h"
/* number of siblings for each tree */
const byte numsiblings[] = {
0, 0, 0, /* char, set, any */
0, 0, /* true, false */
1, /* rep */
2, 2, /* seq, choice */
1, 1, /* not, and */
0, 0, 2, 1, /* call, opencall, rule, grammar */
1, /* behind */
1, 1 /* capture, runtime capture */
};
static TTree *newgrammar (lua_State *L, int arg);
/*
** returns a reasonable name for value at index 'idx' on the stack
*/
static const char *val2str (lua_State *L, int idx) {
const char *k = lua_tostring(L, idx);
if (k != NULL)
return lua_pushfstring(L, "%s", k);
else
return lua_pushfstring(L, "(a %s)", luaL_typename(L, idx));
}
/*
** Fix a TOpenCall into a TCall node, using table 'postable' to
** translate a key to its rule address in the tree. Raises an
** error if key does not exist.
*/
static void fixonecall (lua_State *L, int postable, TTree *g, TTree *t) {
int n;
lua_rawgeti(L, -1, t->key); /* get rule's name */
lua_gettable(L, postable); /* query name in position table */
n = lua_tonumber(L, -1); /* get (absolute) position */
lua_pop(L, 1); /* remove position */
if (n == 0) { /* no position? */
lua_rawgeti(L, -1, t->key); /* get rule's name again */
luaL_error(L, "rule '%s' undefined in given grammar", val2str(L, -1));
}
t->tag = TCall;
t->u.ps = n - (t - g); /* position relative to node */
assert(sib2(t)->tag == TRule);
sib2(t)->key = t->key;
}
/*
** Transform left associative constructions into right
** associative ones, for sequence and choice; that is:
** (t11 + t12) + t2 => t11 + (t12 + t2)
** (t11 * t12) * t2 => t11 * (t12 * t2)
** (that is, Op (Op t11 t12) t2 => Op t11 (Op t12 t2))
*/
static void correctassociativity (TTree *tree) {
TTree *t1 = sib1(tree);
assert(tree->tag == TChoice || tree->tag == TSeq);
while (t1->tag == tree->tag) {
int n1size = tree->u.ps - 1; /* t1 == Op t11 t12 */
int n11size = t1->u.ps - 1;
int n12size = n1size - n11size - 1;
memmove(sib1(tree), sib1(t1), n11size * sizeof(TTree)); /* move t11 */
tree->u.ps = n11size + 1;
sib2(tree)->tag = tree->tag;
sib2(tree)->u.ps = n12size + 1;
}
}
/*
** Make final adjustments in a tree. Fix open calls in tree 't',
** making them refer to their respective rules or raising appropriate
** errors (if not inside a grammar). Correct associativity of associative
** constructions (making them right associative). Assume that tree's
** ktable is at the top of the stack (for error messages).
*/
static void finalfix (lua_State *L, int postable, TTree *g, TTree *t) {
tailcall:
switch (t->tag) {
case TGrammar: /* subgrammars were already fixed */
return;
case TOpenCall: {
if (g != NULL) /* inside a grammar? */
fixonecall(L, postable, g, t);
else { /* open call outside grammar */
lua_rawgeti(L, -1, t->key);
luaL_error(L, "rule '%s' used outside a grammar", val2str(L, -1));
}
break;
}
case TSeq: case TChoice:
correctassociativity(t);
break;
}
switch (numsiblings[t->tag]) {
case 1: /* finalfix(L, postable, g, sib1(t)); */
t = sib1(t); goto tailcall;
case 2:
finalfix(L, postable, g, sib1(t));
t = sib2(t); goto tailcall; /* finalfix(L, postable, g, sib2(t)); */
default: assert(numsiblings[t->tag] == 0); break;
}
}
/*
** {======================================================
** Tree generation
** =======================================================
*/
/*
** In 5.2, could use 'luaL_testudata'...
*/
static int testpattern (lua_State *L, int idx) {
if (lua_touserdata(L, idx)) { /* value is a userdata? */
if (lua_getmetatable(L, idx)) { /* does it have a metatable? */
luaL_getmetatable(L, PATTERN_T);
if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
lua_pop(L, 2); /* remove both metatables */
return 1;
}
}
}
return 0;
}
static Pattern *getpattern (lua_State *L, int idx) {
return (Pattern *)luaL_checkudata(L, idx, PATTERN_T);
}
static int getsize (lua_State *L, int idx) {
return (lua_objlen(L, idx) - sizeof(Pattern)) / sizeof(TTree) + 1;
}
static TTree *gettree (lua_State *L, int idx, int *len) {
Pattern *p = getpattern(L, idx);
if (len)
*len = getsize(L, idx);
return p->tree;
}
/*
** create a pattern
*/
static TTree *newtree (lua_State *L, int len) {
size_t size = (len - 1) * sizeof(TTree) + sizeof(Pattern);
Pattern *p = (Pattern *)lua_newuserdata(L, size);
luaL_getmetatable(L, PATTERN_T);
lua_setmetatable(L, -2);
p->code = NULL; p->codesize = 0;
return p->tree;
}
static TTree *newleaf (lua_State *L, int tag) {
TTree *tree = newtree(L, 1);
tree->tag = tag;
return tree;
}
static TTree *newcharset (lua_State *L) {
TTree *tree = newtree(L, bytes2slots(CHARSETSIZE) + 1);
tree->tag = TSet;
loopset(i, treebuffer(tree)[i] = 0);
return tree;
}
/*
** add to tree a sequence where first sibling is 'sib' (with size
** 'sibsize'); returns position for second sibling
*/
static TTree *seqaux (TTree *tree, TTree *sib, int sibsize) {
tree->tag = TSeq; tree->u.ps = sibsize + 1;
memcpy(sib1(tree), sib, sibsize * sizeof(TTree));
return sib2(tree);
}
/*
** Add element 'idx' to 'ktable' of pattern at the top of the stack;
** create new 'ktable' if necessary. Return index of new element.
*/
static int addtoktable (lua_State *L, int idx) {
if (idx == 0 || lua_isnil(L, idx)) /* no actual value to insert? */
return 0;
else {
int n;
lua_getfenv(L, -1); /* get ktable from pattern */
n = lua_objlen(L, -1);
if (n == 0) { /* is it empty/non-existent? */
lua_pop(L, 1); /* remove it */
lua_createtable(L, 1, 0); /* create a fresh table */
}
lua_pushvalue(L, idx); /* element to be added */
lua_rawseti(L, -2, n + 1);
lua_setfenv(L, -2); /* set it as ktable for pattern */
return n + 1;
}
}
/*
** Build a sequence of 'n' nodes, each with tag 'tag' and 'u.n' got
** from the array 's' (or 0 if array is NULL). (TSeq is binary, so it
** must build a sequence of sequence of sequence...)
*/
static void fillseq (TTree *tree, int tag, int n, const char *s) {
int i;
for (i = 0; i < n - 1; i++) { /* initial n-1 copies of Seq tag; Seq ... */
tree->tag = TSeq; tree->u.ps = 2;
sib1(tree)->tag = tag;
sib1(tree)->u.n = s ? (byte)s[i] : 0;
tree = sib2(tree);
}
tree->tag = tag; /* last one does not need TSeq */
tree->u.n = s ? (byte)s[i] : 0;
}
/*
** Numbers as patterns:
** 0 == true (always match); n == TAny repeated 'n' times;
** -n == not (TAny repeated 'n' times)
*/
static TTree *numtree (lua_State *L, int n) {
if (n == 0)
return newleaf(L, TTrue);
else {
TTree *tree, *nd;
if (n > 0)
tree = nd = newtree(L, 2 * n - 1);
else { /* negative: code it as !(-n) */
n = -n;
tree = newtree(L, 2 * n);
tree->tag = TNot;
nd = sib1(tree);
}
fillseq(nd, TAny, n, NULL); /* sequence of 'n' any's */
return tree;
}
}
/*
** Convert value at index 'idx' to a pattern
*/
static TTree *getpatt (lua_State *L, int idx, int *len) {
TTree *tree;
switch (lua_type(L, idx)) {
case LUA_TSTRING: {
size_t slen;
const char *s = lua_tolstring(L, idx, &slen); /* get string */
if (slen == 0) /* empty? */
tree = newleaf(L, TTrue); /* always match */
else {
tree = newtree(L, 2 * (slen - 1) + 1);
fillseq(tree, TChar, slen, s); /* sequence of 'slen' chars */
}
break;
}
case LUA_TNUMBER: {
int n = lua_tointeger(L, idx);
tree = numtree(L, n);
break;
}
case LUA_TBOOLEAN: {
tree = (lua_toboolean(L, idx) ? newleaf(L, TTrue) : newleaf(L, TFalse));
break;
}
case LUA_TTABLE: {
tree = newgrammar(L, idx);
break;
}
case LUA_TFUNCTION: {
tree = newtree(L, 2);
tree->tag = TRunTime;
tree->key = addtoktable(L, idx);
sib1(tree)->tag = TTrue;
break;
}
default: {
return gettree(L, idx, len);
}
}
lua_replace(L, idx); /* put new tree into 'idx' slot */
if (len)
*len = getsize(L, idx);
return tree;
}
/*
** Return the number of elements in the ktable of pattern at 'idx'.
** In Lua 5.2, default "environment" for patterns is nil, not
** a table. Treat it as an empty table. In Lua 5.1, assumes that
** the environment has no numeric indices (len == 0)
*/
static int ktablelen (lua_State *L, int idx) {
if (!lua_istable(L, idx)) return 0;
else return lua_objlen(L, idx);
}
/*
** Concatentate the contents of table 'idx1' into table 'idx2'.
** (Assume that both indices are negative.)
** Return the original length of table 'idx2'
*/
static int concattable (lua_State *L, int idx1, int idx2) {
int i;
int n1 = ktablelen(L, idx1);
int n2 = ktablelen(L, idx2);
if (n1 == 0) return 0; /* nothing to correct */
for (i = 1; i <= n1; i++) {
lua_rawgeti(L, idx1, i);
lua_rawseti(L, idx2 - 1, n2 + i); /* correct 'idx2' */
}
return n2;
}
/*
** Make a merge of ktables from p1 and p2 the ktable for the new
** pattern at the top of the stack.
*/
static int joinktables (lua_State *L, int p1, int p2) {
int n1, n2;
lua_getfenv(L, p1); /* get ktables */
lua_getfenv(L, p2);
n1 = ktablelen(L, -2);
n2 = ktablelen(L, -1);
if (n1 == 0 && n2 == 0) { /* are both tables empty? */
lua_pop(L, 2); /* nothing to be done; pop tables */
return 0; /* nothing to correct */
}
if (n2 == 0 || lua_equal(L, -2, -1)) { /* second table is empty or equal? */
lua_pop(L, 1); /* pop 2nd table */
lua_setfenv(L, -2); /* set 1st ktable into new pattern */
return 0; /* nothing to correct */
}
if (n1 == 0) { /* first table is empty? */
lua_setfenv(L, -3); /* set 2nd table into new pattern */
lua_pop(L, 1); /* pop 1st table */
return 0; /* nothing to correct */
}
else {
lua_createtable(L, n1 + n2, 0); /* create ktable for new pattern */
/* stack: new p; ktable p1; ktable p2; new ktable */
concattable(L, -3, -1); /* from p1 into new ktable */
concattable(L, -2, -1); /* from p2 into new ktable */
lua_setfenv(L, -4); /* new ktable becomes p env */
lua_pop(L, 2); /* pop other ktables */
return n1; /* correction for indices from p2 */
}
}
static void correctkeys (TTree *tree, int n) {
if (n == 0) return; /* no correction? */
tailcall:
switch (tree->tag) {
case TOpenCall: case TCall: case TRunTime: case TRule: {
if (tree->key > 0)
tree->key += n;
break;
}
case TCapture: {
if (tree->key > 0 && tree->cap != Carg && tree->cap != Cnum)
tree->key += n;
break;
}
default: break;
}
switch (numsiblings[tree->tag]) {
case 1: /* correctkeys(sib1(tree), n); */
tree = sib1(tree); goto tailcall;
case 2:
correctkeys(sib1(tree), n);
tree = sib2(tree); goto tailcall; /* correctkeys(sib2(tree), n); */
default: assert(numsiblings[tree->tag] == 0); break;
}
}
/*
** copy 'ktable' of element 'idx' to new tree (on top of stack)
*/
static void copyktable (lua_State *L, int idx) {
lua_getfenv(L, idx);
lua_setfenv(L, -2);
}
/*
** merge 'ktable' from rule at stack index 'idx' into 'ktable'
** from tree at the top of the stack, and correct corresponding
** tree.
*/
static void mergektable (lua_State *L, int idx, TTree *rule) {
int n;
lua_getfenv(L, -1); /* get ktables */
lua_getfenv(L, idx);
n = concattable(L, -1, -2);
lua_pop(L, 2); /* remove both ktables */
correctkeys(rule, n);
}
/*
** create a new tree, whith a new root and one sibling.
** Sibling must be on the Lua stack, at index 1.
*/
static TTree *newroot1sib (lua_State *L, int tag) {
int s1;
TTree *tree1 = getpatt(L, 1, &s1);
TTree *tree = newtree(L, 1 + s1); /* create new tree */
tree->tag = tag;
memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
copyktable(L, 1);
return tree;
}
/*
** create a new tree, whith a new root and 2 siblings.
** Siblings must be on the Lua stack, first one at index 1.
*/
static TTree *newroot2sib (lua_State *L, int tag) {
int s1, s2;
TTree *tree1 = getpatt(L, 1, &s1);
TTree *tree2 = getpatt(L, 2, &s2);
TTree *tree = newtree(L, 1 + s1 + s2); /* create new tree */
tree->tag = tag;
tree->u.ps = 1 + s1;
memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
memcpy(sib2(tree), tree2, s2 * sizeof(TTree));
correctkeys(sib2(tree), joinktables(L, 1, 2));
return tree;
}
static int lp_P (lua_State *L) {
luaL_checkany(L, 1);
getpatt(L, 1, NULL);
lua_settop(L, 1);
return 1;
}
/*
** sequence operator; optimizations:
** false x => false, x true => x, true x => x
** (cannot do x . false => false because x may have runtime captures)
*/
static int lp_seq (lua_State *L) {
TTree *tree1 = getpatt(L, 1, NULL);
TTree *tree2 = getpatt(L, 2, NULL);
if (tree1->tag == TFalse || tree2->tag == TTrue)
lua_pushvalue(L, 1); /* false . x == false, x . true = x */
else if (tree1->tag == TTrue)
lua_pushvalue(L, 2); /* true . x = x */
else
newroot2sib(L, TSeq);
return 1;
}
/*
** choice operator; optimizations:
** charset / charset => charset
** true / x => true, x / false => x, false / x => x
** (x / true is not equivalent to true)
*/
static int lp_choice (lua_State *L) {
Charset st1, st2;
TTree *t1 = getpatt(L, 1, NULL);
TTree *t2 = getpatt(L, 2, NULL);
if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
TTree *t = newcharset(L);
loopset(i, treebuffer(t)[i] = st1.cs[i] | st2.cs[i]);
}
else if (nofail(t1) || t2->tag == TFalse)
lua_pushvalue(L, 1); /* true / x => true, x / false => x */
else if (t1->tag == TFalse)
lua_pushvalue(L, 2); /* false / x => x */
else
newroot2sib(L, TChoice);
return 1;
}
/*
** p^n
*/
static int lp_star (lua_State *L) {
int size1;
int n = luaL_checkint(L, 2);
TTree *tree1 = gettree(L, 1, &size1);
if (n >= 0) { /* seq tree1 (seq tree1 ... (seq tree1 (rep tree1))) */
TTree *tree = newtree(L, (n + 1) * (size1 + 1));
if (nullable(tree1))
luaL_error(L, "loop body may accept empty string");
while (n--) /* repeat 'n' times */
tree = seqaux(tree, tree1, size1);
tree->tag = TRep;
memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
}
else { /* choice (seq tree1 ... choice tree1 true ...) true */
TTree *tree;
n = -n;
/* size = (choice + seq + tree1 + true) * n, but the last has no seq */
tree = newtree(L, n * (size1 + 3) - 1);
for (; n > 1; n--) { /* repeat (n - 1) times */
tree->tag = TChoice; tree->u.ps = n * (size1 + 3) - 2;
sib2(tree)->tag = TTrue;
tree = sib1(tree);
tree = seqaux(tree, tree1, size1);
}
tree->tag = TChoice; tree->u.ps = size1 + 1;
sib2(tree)->tag = TTrue;
memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
}
copyktable(L, 1);
return 1;
}
/*
** #p == &p
*/
static int lp_and (lua_State *L) {
newroot1sib(L, TAnd);
return 1;
}
/*
** -p == !p
*/
static int lp_not (lua_State *L) {
newroot1sib(L, TNot);
return 1;
}
/*
** [t1 - t2] == Seq (Not t2) t1
** If t1 and t2 are charsets, make their difference.
*/
static int lp_sub (lua_State *L) {
Charset st1, st2;
int s1, s2;
TTree *t1 = getpatt(L, 1, &s1);
TTree *t2 = getpatt(L, 2, &s2);
if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
TTree *t = newcharset(L);
loopset(i, treebuffer(t)[i] = st1.cs[i] & ~st2.cs[i]);
}
else {
TTree *tree = newtree(L, 2 + s1 + s2);
tree->tag = TSeq; /* sequence of... */
tree->u.ps = 2 + s2;
sib1(tree)->tag = TNot; /* ...not... */
memcpy(sib1(sib1(tree)), t2, s2 * sizeof(TTree)); /* ...t2 */
memcpy(sib2(tree), t1, s1 * sizeof(TTree)); /* ... and t1 */
correctkeys(sib1(tree), joinktables(L, 1, 2));
}
return 1;
}
static int lp_set (lua_State *L) {
size_t l;
const char *s = luaL_checklstring(L, 1, &l);
TTree *tree = newcharset(L);
while (l--) {
setchar(treebuffer(tree), (byte)(*s));
s++;
}
return 1;
}
static int lp_range (lua_State *L) {
int arg;
int top = lua_gettop(L);
TTree *tree = newcharset(L);
for (arg = 1; arg <= top; arg++) {
int c;
size_t l;
const char *r = luaL_checklstring(L, arg, &l);
luaL_argcheck(L, l == 2, arg, "range must have two characters");
for (c = (byte)r[0]; c <= (byte)r[1]; c++)
setchar(treebuffer(tree), c);
}
return 1;
}
/*
** Look-behind predicate
*/
static int lp_behind (lua_State *L) {
TTree *tree;
TTree *tree1 = getpatt(L, 1, NULL);
int n = fixedlen(tree1);
luaL_argcheck(L, !hascaptures(tree1), 1, "pattern have captures");
luaL_argcheck(L, n > 0, 1, "pattern may not have fixed length");
luaL_argcheck(L, n <= MAXBEHIND, 1, "pattern too long to look behind");
tree = newroot1sib(L, TBehind);
tree->u.n = n;
return 1;
}
/*
** Create a non-terminal
*/
static int lp_V (lua_State *L) {
TTree *tree = newleaf(L, TOpenCall);
luaL_argcheck(L, !lua_isnoneornil(L, 1), 1, "non-nil value expected");
tree->key = addtoktable(L, 1);
return 1;
}
/*
** Create a tree for a non-empty capture, with a body and
** optionally with an associated Lua value (at index 'labelidx' in the
** stack)
*/
static int capture_aux (lua_State *L, int cap, int labelidx) {
TTree *tree = newroot1sib(L, TCapture);
tree->cap = cap;
tree->key = addtoktable(L, labelidx);
return 1;
}
/*
** Fill a tree with an empty capture, using an empty (TTrue) sibling.
*/
static TTree *auxemptycap (lua_State *L, TTree *tree, int cap, int idx) {
tree->tag = TCapture;
tree->cap = cap;
tree->key = addtoktable(L, idx);
sib1(tree)->tag = TTrue;
return tree;
}
/*
** Create a tree for an empty capture
*/
static TTree *newemptycap (lua_State *L, int cap, int idx) {
return auxemptycap(L, newtree(L, 2), cap, idx);
}
/*
** Captures with syntax p / v
** (function capture, query capture, string capture, or number capture)
*/
static int lp_divcapture (lua_State *L) {
switch (lua_type(L, 2)) {
case LUA_TFUNCTION: return capture_aux(L, Cfunction, 2);
case LUA_TTABLE: return capture_aux(L, Cquery, 2);
case LUA_TSTRING: return capture_aux(L, Cstring, 2);
case LUA_TNUMBER: {
int n = lua_tointeger(L, 2);
TTree *tree = newroot1sib(L, TCapture);
luaL_argcheck(L, 0 <= n && n <= SHRT_MAX, 1, "invalid number");
tree->cap = Cnum;
tree->key = n;
return 1;
}
default: return luaL_argerror(L, 2, "invalid replacement value");
}
}
static int lp_substcapture (lua_State *L) {
return capture_aux(L, Csubst, 0);
}
static int lp_tablecapture (lua_State *L) {
return capture_aux(L, Ctable, 0);
}
static int lp_groupcapture (lua_State *L) {
if (lua_isnoneornil(L, 2))
return capture_aux(L, Cgroup, 0);
else {
luaL_checkstring(L, 2);
return capture_aux(L, Cgroup, 2);
}
}
static int lp_foldcapture (lua_State *L) {
luaL_checktype(L, 2, LUA_TFUNCTION);
return capture_aux(L, Cfold, 2);
}
static int lp_simplecapture (lua_State *L) {
return capture_aux(L, Csimple, 0);
}
static int lp_poscapture (lua_State *L) {
newemptycap(L, Cposition, 0);
return 1;
}
static int lp_argcapture (lua_State *L) {
int n = luaL_checkint(L, 1);
TTree *tree = newemptycap(L, Carg, 0);
tree->key = n;
luaL_argcheck(L, 0 < n && n <= SHRT_MAX, 1, "invalid argument index");
return 1;
}
static int lp_backref (lua_State *L) {
luaL_checkstring(L, 1);
newemptycap(L, Cbackref, 1);
return 1;
}
/*
** Constant capture
*/
static int lp_constcapture (lua_State *L) {
int i;
int n = lua_gettop(L); /* number of values */
if (n == 0) /* no values? */
newleaf(L, TTrue); /* no capture */
else if (n == 1)
newemptycap(L, Cconst, 1); /* single constant capture */
else { /* create a group capture with all values */
TTree *tree = newtree(L, 1 + 3 * (n - 1) + 2);
tree->tag = TCapture;
tree->cap = Cgroup;
tree->key = 0;
tree = sib1(tree);
for (i = 1; i <= n - 1; i++) {
tree->tag = TSeq;
tree->u.ps = 3; /* skip TCapture and its sibling */
auxemptycap(L, sib1(tree), Cconst, i);
tree = sib2(tree);
}
auxemptycap(L, tree, Cconst, i);
}
return 1;
}
static int lp_matchtime (lua_State *L) {
TTree *tree;
luaL_checktype(L, 2, LUA_TFUNCTION);
tree = newroot1sib(L, TRunTime);
tree->key = addtoktable(L, 2);
return 1;
}
/* }====================================================== */
/*
** {======================================================
** Grammar - Tree generation
** =======================================================
*/
/*
** push on the stack the index and the pattern for the
** initial rule of grammar at index 'arg' in the stack;
** also add that index into position table.
*/
static void getfirstrule (lua_State *L, int arg, int postab) {
lua_rawgeti(L, arg, 1); /* access first element */
if (lua_isstring(L, -1)) { /* is it the name of initial rule? */
lua_pushvalue(L, -1); /* duplicate it to use as key */
lua_gettable(L, arg); /* get associated rule */
}
else {
lua_pushinteger(L, 1); /* key for initial rule */
lua_insert(L, -2); /* put it before rule */
}
if (!testpattern(L, -1)) { /* initial rule not a pattern? */
if (lua_isnil(L, -1))
luaL_error(L, "grammar has no initial rule");
else
luaL_error(L, "initial rule '%s' is not a pattern", lua_tostring(L, -2));
}
lua_pushvalue(L, -2); /* push key */
lua_pushinteger(L, 1); /* push rule position (after TGrammar) */
lua_settable(L, postab); /* insert pair at position table */
}
/*
** traverse grammar at index 'arg', pushing all its keys and patterns
** into the stack. Create a new table (before all pairs key-pattern) to
** collect all keys and their associated positions in the final tree
** (the "position table").
** Return the number of rules and (in 'totalsize') the total size
** for the new tree.
*/
static int collectrules (lua_State *L, int arg, int *totalsize) {
int n = 1; /* to count number of rules */
int postab = lua_gettop(L) + 1; /* index of position table */
int size; /* accumulator for total size */
lua_newtable(L); /* create position table */
getfirstrule(L, arg, postab);
size = 2 + getsize(L, postab + 2); /* TGrammar + TRule + rule */
lua_pushnil(L); /* prepare to traverse grammar table */
while (lua_next(L, arg) != 0) {
if (lua_tonumber(L, -2) == 1 ||
lua_equal(L, -2, postab + 1)) { /* initial rule? */
lua_pop(L, 1); /* remove value (keep key for lua_next) */
continue;
}
if (!testpattern(L, -1)) /* value is not a pattern? */
luaL_error(L, "rule '%s' is not a pattern", val2str(L, -2));
luaL_checkstack(L, LUA_MINSTACK, "grammar has too many rules");
lua_pushvalue(L, -2); /* push key (to insert into position table) */
lua_pushinteger(L, size);
lua_settable(L, postab);
size += 1 + getsize(L, -1); /* update size */
lua_pushvalue(L, -2); /* push key (for next lua_next) */
n++;
}
*totalsize = size + 1; /* TTrue to finish list of rules */
return n;
}
static void buildgrammar (lua_State *L, TTree *grammar, int frule, int n) {
int i;
TTree *nd = sib1(grammar); /* auxiliary pointer to traverse the tree */
for (i = 0; i < n; i++) { /* add each rule into new tree */
int ridx = frule + 2*i + 1; /* index of i-th rule */
int rulesize;
TTree *rn = gettree(L, ridx, &rulesize);
nd->tag = TRule;
nd->key = 0;
nd->cap = i; /* rule number */
nd->u.ps = rulesize + 1; /* point to next rule */
memcpy(sib1(nd), rn, rulesize * sizeof(TTree)); /* copy rule */
mergektable(L, ridx, sib1(nd)); /* merge its ktable into new one */
nd = sib2(nd); /* move to next rule */
}
nd->tag = TTrue; /* finish list of rules */
}
/*
** Check whether a tree has potential infinite loops
*/
static int checkloops (TTree *tree) {
tailcall:
if (tree->tag == TRep && nullable(sib1(tree)))
return 1;
else if (tree->tag == TGrammar)
return 0; /* sub-grammars already checked */
else {
switch (numsiblings[tree->tag]) {
case 1: /* return checkloops(sib1(tree)); */
tree = sib1(tree); goto tailcall;
case 2:
if (checkloops(sib1(tree))) return 1;
/* else return checkloops(sib2(tree)); */
tree = sib2(tree); goto tailcall;
default: assert(numsiblings[tree->tag] == 0); return 0;
}
}
}
static int verifyerror (lua_State *L, int *passed, int npassed) {
int i, j;
for (i = npassed - 1; i >= 0; i--) { /* search for a repetition */
for (j = i - 1; j >= 0; j--) {
if (passed[i] == passed[j]) {
lua_rawgeti(L, -1, passed[i]); /* get rule's key */
return luaL_error(L, "rule '%s' may be left recursive", val2str(L, -1));
}
}
}
return luaL_error(L, "too many left calls in grammar");
}
/*
** Check whether a rule can be left recursive; raise an error in that
** case; otherwise return 1 iff pattern is nullable. Assume ktable at
** the top of the stack.
*/
static int verifyrule (lua_State *L, TTree *tree, int *passed, int npassed,
int nullable) {
tailcall:
switch (tree->tag) {
case TChar: case TSet: case TAny:
case TFalse:
return nullable; /* cannot pass from here */
case TTrue:
case TBehind: /* look-behind cannot have calls */
return 1;
case TNot: case TAnd: case TRep:
/* return verifyrule(L, sib1(tree), passed, npassed, 1); */
tree = sib1(tree); nullable = 1; goto tailcall;
case TCapture: case TRunTime:
/* return verifyrule(L, sib1(tree), passed, npassed); */
tree = sib1(tree); goto tailcall;
case TCall:
/* return verifyrule(L, sib2(tree), passed, npassed); */
tree = sib2(tree); goto tailcall;
case TSeq: /* only check 2nd child if first is nullable */
if (!verifyrule(L, sib1(tree), passed, npassed, 0))
return nullable;
/* else return verifyrule(L, sib2(tree), passed, npassed); */
tree = sib2(tree); goto tailcall;
case TChoice: /* must check both children */
nullable = verifyrule(L, sib1(tree), passed, npassed, nullable);
/* return verifyrule(L, sib2(tree), passed, npassed, nullable); */
tree = sib2(tree); goto tailcall;
case TRule:
if (npassed >= MAXRULES)
return verifyerror(L, passed, npassed);
else {
passed[npassed++] = tree->key;
/* return verifyrule(L, sib1(tree), passed, npassed); */
tree = sib1(tree); goto tailcall;
}
case TGrammar:
return nullable(tree); /* sub-grammar cannot be left recursive */
default: assert(0); return 0;
}
}
static void verifygrammar (lua_State *L, TTree *grammar) {
int passed[MAXRULES];
TTree *rule;
/* check left-recursive rules */
for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
if (rule->key == 0) continue; /* unused rule */
verifyrule(L, sib1(rule), passed, 0, 0);
}
assert(rule->tag == TTrue);
/* check infinite loops inside rules */
for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
if (rule->key == 0) continue; /* unused rule */
if (checkloops(sib1(rule))) {
lua_rawgeti(L, -1, rule->key); /* get rule's key */
luaL_error(L, "empty loop in rule '%s'", val2str(L, -1));
}
}
assert(rule->tag == TTrue);
}
/*
** Give a name for the initial rule if it is not referenced
*/