-
Notifications
You must be signed in to change notification settings - Fork 236
/
lpeg.c
2400 lines (2067 loc) · 63.1 KB
/
lpeg.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: lpeg.c,v 1.112 2010/11/03 17:07:50 roberto Exp $
** LPeg - PEG pattern matching for Lua
** Copyright 2007, Lua.org & PUC-Rio (see 'lpeg.html' for license)
** written by Roberto Ierusalimschy
*/
#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lpeg.h"
#define VERSION "0.10"
#define PATTERN_T "lpeg-pattern"
#define MAXSTACKIDX "lpeg-maxstack"
/*
** compatibility with Lua 5.2
*/
#if (LUA_VERSION_NUM == 502)
#undef lua_equal
#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ)
#undef lua_getfenv
#define lua_getfenv lua_getuservalue
#undef lua_setfenv
#define lua_setfenv lua_setuservalue
#undef lua_objlen
#define lua_objlen lua_rawlen
#undef luaL_register
#define luaL_register(L,n,f) \
{ if ((n) == NULL) luaL_setfuncs(L,f,0); else luaL_newlib(L,f); }
#endif
/* initial size for call/backtrack stack */
#define INITBACK 100
/* default maximum size for call/backtrack stack */
#define MAXBACK INITBACK
/* size for call/backtrack stack for verifier */
#define MAXBACKVER 200
/* initial size for capture's list */
#define INITCAPSIZE 32
/* index, on Lua stack, for subject */
#define SUBJIDX 2
/* number of fixed arguments to 'match' (before capture arguments) */
#define FIXEDARGS 3
/* index, on Lua stack, for substitution value cache */
#define subscache(cs) ((cs)->ptop + 1)
/* index, on Lua stack, for capture list */
#define caplistidx(ptop) ((ptop) + 2)
/* index, on Lua stack, for pattern's fenv */
#define penvidx(ptop) ((ptop) + 3)
/* index, on Lua stack, for backtracking stack */
#define stackidx(ptop) ((ptop) + 4)
typedef unsigned char byte;
#define CHARSETSIZE ((UCHAR_MAX/CHAR_BIT) + 1)
typedef byte Charset[CHARSETSIZE];
/* Virtual Machine's instructions */
typedef enum Opcode {
IAny, IChar, ISet, ISpan,
IBack,
IRet, IEnd,
IChoice, IJmp, ICall, IOpenCall,
ICommit, IPartialCommit, IBackCommit, IFailTwice, IFail, IGiveup,
IFunc,
IFullCapture, IEmptyCapture, IEmptyCaptureIdx,
IOpenCapture, ICloseCapture, ICloseRunTime
} Opcode;
#define ISJMP 0x1
#define ISCHECK 0x2
#define ISFIXCHECK 0x4
#define ISNOFAIL 0x8
#define ISCAPTURE 0x10
#define ISMOVABLE 0x20
#define ISFENVOFF 0x40
static const int opproperties[] = {
/* IAny */ ISCHECK | ISFIXCHECK | ISJMP,
/* IChar */ ISCHECK | ISFIXCHECK | ISJMP,
/* ISet */ ISCHECK | ISFIXCHECK | ISJMP,
/* ISpan */ ISNOFAIL,
/* IBack */ 0,
/* IRet */ 0,
/* IEnd */ 0,
/* IChoice */ ISJMP,
/* IJmp */ ISJMP | ISNOFAIL,
/* ICall */ ISJMP,
/* IOpenCall */ ISFENVOFF,
/* ICommit */ ISJMP,
/* IPartialCommit */ ISJMP,
/* IBackCommit */ ISJMP,
/* IFailTwice */ 0,
/* IFail */ 0,
/* IGiveup */ 0,
/* IFunc */ ISCHECK | ISJMP,
/* IFullCapture */ ISCAPTURE | ISNOFAIL | ISFENVOFF,
/* IEmptyCapture */ ISCAPTURE | ISNOFAIL | ISMOVABLE,
/* IEmptyCaptureIdx */ISCAPTURE | ISNOFAIL | ISMOVABLE | ISFENVOFF,
/* IOpenCapture */ ISCAPTURE | ISNOFAIL | ISMOVABLE | ISFENVOFF,
/* ICloseCapture */ ISCAPTURE | ISNOFAIL | ISMOVABLE | ISFENVOFF,
/* ICloseRunTime */ ISCAPTURE | ISFENVOFF
};
typedef union Instruction {
struct Inst {
byte code;
byte aux;
short offset;
} i;
PattFunc f;
int iv;
byte buff[1];
} Instruction;
static const Instruction giveup = {{IGiveup, 0, 0}};
#define getkind(op) ((op)->i.aux & 0xF)
#define getoff(op) (((op)->i.aux >> 4) & 0xF)
#define dest(p,x) ((x) + ((p)+(x))->i.offset)
#define MAXOFF 0xF
#define MAXAUX 0xFF
/* maximum size (in elements) for a pattern */
#define MAXPATTSIZE (SHRT_MAX - 10)
#define isprop(op,p) (opproperties[(op)->i.code] & (p))
#define isjmp(op) (isprop(op, ISJMP) && (op)->i.offset != 0)
#define iscapture(op) isprop(op, ISCAPTURE)
#define ischeck(op) (isprop(op, ISCHECK) && (op)->i.offset == 0)
#define isfixcheck(op) (isprop(op, ISFIXCHECK) && (op)->i.offset == 0)
#define istest(op) (isprop(op, ISCHECK) && (op)->i.offset != 0)
#define isnofail(op) isprop(op, ISNOFAIL)
#define ismovable(op) isprop(op, ISMOVABLE)
#define isfenvoff(op) isprop(op, ISFENVOFF)
/* kinds of captures */
typedef enum CapKind {
Cclose, Cposition, Cconst, Cbackref, Carg, Csimple, Ctable, Cfunction,
Cquery, Cstring, Csubst, Cfold, Cruntime, Cgroup
} CapKind;
#define iscapnosize(k) ((k) == Cposition || (k) == Cconst)
typedef struct Capture {
const char *s; /* position */
short idx;
byte kind;
byte siz;
} Capture;
/* size (in elements) for an instruction plus extra l bytes */
#define instsize(l) (((l) + sizeof(Instruction) - 1)/sizeof(Instruction) + 1)
/* size (in elements) for a ISet instruction */
#define CHARSETINSTSIZE instsize(CHARSETSIZE)
/* size (in elements) for a IFunc instruction */
#define funcinstsize(p) ((p)->i.aux + 2)
#define loopset(v,b) { int v; for (v = 0; v < CHARSETSIZE; v++) b; }
#define testchar(st,c) (((int)(st)[((c) >> 3)] & (1 << ((c) & 7))))
#define setchar(st,c) ((st)[(c) >> 3] |= (1 << ((c) & 7)))
static int sizei (const Instruction *i) {
switch((Opcode)i->i.code) {
case ISet: case ISpan: return CHARSETINSTSIZE;
case IFunc: return funcinstsize(i);
default: return 1;
}
}
static const char *val2str (lua_State *L, int idx) {
const char *k = lua_tostring(L, idx);
if (k != NULL)
return lua_pushfstring(L, "rule '%s'", k);
else
return lua_pushfstring(L, "rule <a %s>", luaL_typename(L, idx));
}
static int getposition (lua_State *L, int t, int i) {
int res;
lua_getfenv(L, -1);
lua_rawgeti(L, -1, i); /* get key from pattern's environment */
lua_gettable(L, t); /* get position from positions table */
res = lua_tointeger(L, -1);
if (res == 0) { /* key has no registered position? */
lua_rawgeti(L, -2, i); /* get key again */
return luaL_error(L, "%s is not defined in given grammar", val2str(L, -1));
}
lua_pop(L, 2); /* remove environment and position */
return res;
}
/*
** {======================================================
** Printing patterns
** =======================================================
*/
static void printcharset (const Charset st) {
int i;
printf("[");
for (i = 0; i <= UCHAR_MAX; i++) {
int first = i;
while (testchar(st, i) && i <= UCHAR_MAX) i++;
if (i - 1 == first) /* unary range? */
printf("(%02x)", first);
else if (i - 1 > first) /* non-empty range? */
printf("(%02x-%02x)", first, i - 1);
}
printf("]");
}
static void printcapkind (int kind) {
const char *const modes[] = {
"close", "position", "constant", "backref",
"argument", "simple", "table", "function",
"query", "string", "substitution", "fold",
"runtime", "group"};
printf("%s", modes[kind]);
}
static void printjmp (const Instruction *op, const Instruction *p) {
printf("-> ");
if (p->i.offset == 0) printf("FAIL");
else printf("%d", (int)(dest(0, p) - op));
}
static void printinst (const Instruction *op, const Instruction *p) {
const char *const names[] = {
"any", "char", "set", "span", "back",
"ret", "end",
"choice", "jmp", "call", "open_call",
"commit", "partial_commit", "back_commit", "failtwice", "fail", "giveup",
"func",
"fullcapture", "emptycapture", "emptycaptureidx", "opencapture",
"closecapture", "closeruntime"
};
printf("%02ld: %s ", (long)(p - op), names[p->i.code]);
switch ((Opcode)p->i.code) {
case IChar: {
printf("'%c'", p->i.aux);
printjmp(op, p);
break;
}
case IAny: {
printf("* %d", p->i.aux);
printjmp(op, p);
break;
}
case IFullCapture: case IOpenCapture:
case IEmptyCapture: case IEmptyCaptureIdx:
case ICloseCapture: case ICloseRunTime: {
printcapkind(getkind(p));
printf("(n = %d) (off = %d)", getoff(p), p->i.offset);
break;
}
case ISet: {
printcharset((p+1)->buff);
printjmp(op, p);
break;
}
case ISpan: {
printcharset((p+1)->buff);
break;
}
case IOpenCall: {
printf("-> %d", p->i.offset);
break;
}
case IChoice: {
printjmp(op, p);
printf(" (%d)", p->i.aux);
break;
}
case IJmp: case ICall: case ICommit:
case IPartialCommit: case IBackCommit: {
printjmp(op, p);
break;
}
default: break;
}
printf("\n");
}
static void printpatt (Instruction *p) {
Instruction *op = p;
for (;;) {
printinst(op, p);
if ((Opcode)p->i.code == IEnd) break;
p += sizei(p);
}
}
static void printcap (Capture *cap) {
printcapkind(cap->kind);
printf(" (idx: %d - size: %d) -> %p\n", cap->idx, cap->siz, cap->s);
}
static void printcaplist (Capture *cap) {
for (; cap->s; cap++) printcap(cap);
}
/* }====================================================== */
/*
** {======================================================
** Virtual Machine
** =======================================================
*/
typedef struct Stack {
const char *s;
const Instruction *p;
int caplevel;
} Stack;
#define getstackbase(L, ptop) ((Stack *)lua_touserdata(L, stackidx(ptop)))
static int runtimecap (lua_State *L, Capture *close, Capture *ocap,
const char *o, const char *s, int ptop);
static Capture *doublecap (lua_State *L, Capture *cap, int captop, int ptop) {
Capture *newc;
if (captop >= INT_MAX/((int)sizeof(Capture) * 2))
luaL_error(L, "too many captures");
newc = (Capture *)lua_newuserdata(L, captop * 2 * sizeof(Capture));
memcpy(newc, cap, captop * sizeof(Capture));
lua_replace(L, caplistidx(ptop));
return newc;
}
static Stack *doublestack (lua_State *L, Stack **stacklimit, int ptop) {
Stack *stack = getstackbase(L, ptop);
Stack *newstack;
int n = *stacklimit - stack;
int max, newn;
lua_getfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
max = lua_tointeger(L, -1);
lua_pop(L, 1);
if (n >= max)
luaL_error(L, "too many pending calls/choices");
newn = 2*n; if (newn > max) newn = max;
newstack = (Stack *)lua_newuserdata(L, newn * sizeof(Stack));
memcpy(newstack, stack, n * sizeof(Stack));
lua_replace(L, stackidx(ptop));
*stacklimit = newstack + newn;
return newstack + n;
}
static void adddyncaptures (const char *s, Capture *base, int n, int fd) {
int i;
assert(base[0].kind == Cruntime && base[0].siz == 0);
base[0].idx = fd; /* first returned capture */
for (i = 1; i < n; i++) { /* add extra captures */
base[i].siz = 1; /* mark it as closed */
base[i].s = s;
base[i].kind = Cruntime;
base[i].idx = fd + i; /* stack index */
}
base[n].kind = Cclose; /* add closing entry */
base[n].siz = 1;
base[n].s = s;
}
#define condfailed(p) { int f = p->i.offset; if (f) p+=f; else goto fail; }
static const char *match (lua_State *L,
const char *o, const char *s, const char *e,
Instruction *op, Capture *capture, int ptop) {
Stack stackbase[INITBACK];
Stack *stacklimit = stackbase + INITBACK;
Stack *stack = stackbase; /* point to first empty slot in stack */
int capsize = INITCAPSIZE;
int captop = 0; /* point to first empty slot in captures */
const Instruction *p = op;
stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
lua_pushlightuserdata(L, stackbase);
for (;;) {
#if defined(DEBUG)
printf("s: |%s| stck: %d c: %d ",
s, stack - getstackbase(L, ptop), captop);
printinst(op, p);
#endif
switch ((Opcode)p->i.code) {
case IEnd: {
assert(stack == getstackbase(L, ptop) + 1);
capture[captop].kind = Cclose;
capture[captop].s = NULL;
return s;
}
case IGiveup: {
assert(stack == getstackbase(L, ptop));
return NULL;
}
case IRet: {
assert(stack > getstackbase(L, ptop) && (stack - 1)->s == NULL);
p = (--stack)->p;
continue;
}
case IAny: {
int n = p->i.aux;
if (n <= e - s) { p++; s += n; }
else condfailed(p);
continue;
}
case IChar: {
if ((byte)*s == p->i.aux && s < e) { p++; s++; }
else condfailed(p);
continue;
}
case ISet: {
int c = (byte)*s;
if (testchar((p+1)->buff, c) && s < e)
{ p += CHARSETINSTSIZE; s++; }
else condfailed(p);
continue;
}
case IBack: {
int n = p->i.aux;
if (n > s - o) goto fail;
s -= n; p++;
continue;
}
case ISpan: {
for (; s < e; s++) {
int c = (byte)*s;
if (!testchar((p+1)->buff, c)) break;
}
p += CHARSETINSTSIZE;
continue;
}
case IFunc: {
const char *r = (p+1)->f(s, e, o, (p+2)->buff);
if (r != NULL) { s = r; p += funcinstsize(p); }
else condfailed(p);
continue;
}
case IJmp: {
p += p->i.offset;
continue;
}
case IChoice: {
if (stack == stacklimit)
stack = doublestack(L, &stacklimit, ptop);
stack->p = dest(0, p);
stack->s = s - p->i.aux;
stack->caplevel = captop;
stack++;
p++;
continue;
}
case ICall: {
if (stack == stacklimit)
stack = doublestack(L, &stacklimit, ptop);
stack->s = NULL;
stack->p = p + 1; /* save return address */
stack++;
p += p->i.offset;
continue;
}
case ICommit: {
assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
stack--;
p += p->i.offset;
continue;
}
case IPartialCommit: {
assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
(stack - 1)->s = s;
(stack - 1)->caplevel = captop;
p += p->i.offset;
continue;
}
case IBackCommit: {
assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
s = (--stack)->s;
captop = stack->caplevel;
p += p->i.offset;
continue;
}
case IFailTwice:
assert(stack > getstackbase(L, ptop));
stack--;
/* go through */
case IFail:
fail: { /* pattern failed: try to backtrack */
do { /* remove pending calls */
assert(stack > getstackbase(L, ptop));
s = (--stack)->s;
} while (s == NULL);
captop = stack->caplevel;
p = stack->p;
continue;
}
case ICloseRunTime: {
int fr = lua_gettop(L) + 1; /* stack index of first result */
int ncap = runtimecap(L, capture + captop, capture, o, s, ptop);
lua_Integer res = lua_tointeger(L, fr) - 1; /* offset */
int n = lua_gettop(L) - fr; /* number of new captures */
if (res == -1) { /* may not be a number */
if (!lua_toboolean(L, fr)) { /* false value? */
lua_settop(L, fr - 1); /* remove results */
goto fail; /* and fail */
}
else if (lua_isboolean(L, fr)) /* true? */
res = s - o; /* keep current position */
}
if (res < s - o || res > e - o)
luaL_error(L, "invalid position returned by match-time capture");
s = o + res; /* update current position */
captop -= ncap; /* remove nested captures */
lua_remove(L, fr); /* remove first result (offset) */
if (n > 0) { /* captures? */
if ((captop += n + 1) >= capsize) {
capture = doublecap(L, capture, captop, ptop);
capsize = 2 * captop;
}
adddyncaptures(s, capture + captop - n - 1, n, fr);
}
p++;
continue;
}
case ICloseCapture: {
const char *s1 = s - getoff(p);
assert(captop > 0);
if (capture[captop - 1].siz == 0 &&
s1 - capture[captop - 1].s < UCHAR_MAX) {
capture[captop - 1].siz = s1 - capture[captop - 1].s + 1;
p++;
continue;
}
else {
capture[captop].siz = 1; /* mark entry as closed */
goto capture;
}
}
case IEmptyCapture: case IEmptyCaptureIdx:
capture[captop].siz = 1; /* mark entry as closed */
goto capture;
case IOpenCapture:
capture[captop].siz = 0; /* mark entry as open */
goto capture;
case IFullCapture:
capture[captop].siz = getoff(p) + 1; /* save capture size */
capture: {
capture[captop].s = s - getoff(p);
capture[captop].idx = p->i.offset;
capture[captop].kind = getkind(p);
if (++captop >= capsize) {
capture = doublecap(L, capture, captop, ptop);
capsize = 2 * captop;
}
p++;
continue;
}
case IOpenCall: {
lua_rawgeti(L, penvidx(ptop), p->i.offset);
luaL_error(L, "reference to %s outside a grammar", val2str(L, -1));
}
default: assert(0); return NULL;
}
}
}
/* }====================================================== */
/*
** {======================================================
** Verifier
** =======================================================
*/
/*
** check whether pattern may go from 'p' to 'e' without consuming any
** input. Raises an error if it detects a left recursion. 'op' points
** the beginning of the pattern. If pattern belongs to a grammar,
** 'rule' is the stack index where is its corresponding key (only for
** error messages) and 'posttable' is the stack index with a table
** mapping rule keys to the position of their code in the pattern.
*/
static int verify (lua_State *L, Instruction *op, const Instruction *p,
Instruction *e, int postable, int rule) {
static const char dummy[] = "";
Stack back[MAXBACKVER];
int backtop = 0; /* point to first empty slot in back */
while (p != e) {
switch ((Opcode)p->i.code) {
case IRet: {
p = back[--backtop].p;
continue;
}
case IChoice: {
if (backtop >= MAXBACKVER)
return luaL_error(L, "too many pending calls/choices");
back[backtop].p = dest(0, p);
back[backtop++].s = dummy;
p++;
continue;
}
case ICall: {
assert((p + 1)->i.code != IRet); /* no tail call */
if (backtop >= MAXBACKVER)
return luaL_error(L, "too many pending calls/choices");
back[backtop].s = NULL;
back[backtop++].p = p + 1;
goto dojmp;
}
case IOpenCall: {
int i;
if (postable == 0) /* grammar still not fixed? */
goto fail; /* to be verified later */
for (i = 0; i < backtop; i++) {
if (back[i].s == NULL && back[i].p == p + 1)
return luaL_error(L, "%s is left recursive", val2str(L, rule));
}
if (backtop >= MAXBACKVER)
return luaL_error(L, "too many pending calls/choices");
back[backtop].s = NULL;
back[backtop++].p = p + 1;
p = op + getposition(L, postable, p->i.offset);
continue;
}
case IBackCommit:
case ICommit: {
assert(backtop > 0 && p->i.offset > 0);
backtop--;
goto dojmp;
}
case IPartialCommit: {
assert(backtop > 0);
if (p->i.offset > 0) goto dojmp; /* forward jump */
else { /* loop will be detected when checking corresponding rule */
assert(postable != 0);
backtop--;
p++; /* just go on now */
continue;
}
}
case IBack: {
if (p->i.aux == 1 && isfixcheck(p + 1)) { /* char test? */
p++; /* skip back instruction */
p += sizei(p); /* skip char test */
}
else { /* standard lookbehind code */
assert((Opcode)(p - 1)->i.code == IChoice); /* look behind */
backtop--;
p += (p - 1)->i.offset;
assert((Opcode)(p - 1)->i.code == IFail); /* look behind */
}
continue;
}
case IAny:
case IChar:
case ISet: {
const Instruction *next = p + sizei(p);
if ((Opcode)next->i.code == IBack)
p = next + 1; /* continue after the back instruction */
else if (p->i.offset == 0) goto fail;
else /* jump */
p += p->i.offset;
continue;
}
case IJmp:
dojmp: {
p += p->i.offset;
continue;
}
case IFailTwice: /* 'not' predicate */
goto fail; /* body could have failed; try to backtrack it */
case IFail: {
if (p > op && (p - 1)->i.code == IBackCommit) { /* 'and' predicate? */
p++; /* pretend it succeeded and go ahead */
continue;
}
/* else failed: go through */
}
fail: { /* pattern failed: try to backtrack */
do {
if (backtop-- == 0)
return 1; /* no more backtracking */
} while (back[backtop].s == NULL);
p = back[backtop].p;
continue;
}
case ISpan:
case IOpenCapture: case ICloseCapture:
case IEmptyCapture: case IEmptyCaptureIdx:
case IFullCapture: {
p += sizei(p);
continue;
}
case ICloseRunTime: {
goto fail; /* be liberal in this case */
}
case IFunc: {
const char *r = (p+1)->f(dummy, dummy, dummy, (p+2)->buff);
if (r != NULL) { p += funcinstsize(p); }
else condfailed(p);
continue;
}
case IEnd: /* cannot happen (should stop before it) */
default: assert(0); return 0;
}
}
assert(backtop == 0);
return 0;
}
static void checkrule (lua_State *L, Instruction *op, int from, int to,
int postable, int rule) {
int i;
int lastopen = 0; /* more recent OpenCall seen in the code */
for (i = from; i < to; i += sizei(op + i)) {
if (op[i].i.code == IPartialCommit && op[i].i.offset < 0) { /* loop? */
int start = dest(op, i);
assert(op[start - 1].i.code == IChoice && dest(op, start - 1) == i + 1);
if (start <= lastopen) { /* loop does contain an open call? */
if (!verify(L, op, op + start, op + i, postable, rule)) /* check body */
luaL_error(L, "possible infinite loop in %s", val2str(L, rule));
}
}
else if (op[i].i.code == IOpenCall)
lastopen = i;
}
assert(op[i - 1].i.code == IRet);
verify(L, op, op + from, op + to - 1, postable, rule);
}
/* }====================================================== */
/*
** {======================================================
** Building Patterns
** =======================================================
*/
enum charsetanswer { NOINFO, ISCHARSET, VALIDSTARTS };
typedef struct CharsetTag {
enum charsetanswer tag;
Charset cs;
} CharsetTag;
static Instruction *getpatt (lua_State *L, int idx, int *size);
static void check2test (Instruction *p, int n) {
assert(ischeck(p) && n != 0);
p->i.offset = n;
}
/*
** invert array slice p[0]-p[e] (both inclusive)
*/
static void invert (Instruction *p, int e) {
int i;
for (i = 0; i < e; i++, e--) {
Instruction temp = p[i];
p[i] = p[e];
p[e] = temp;
}
}
/*
** rotate array slice p[0]-p[e] (both inclusive) 'n' steps
** to the 'left'
*/
static void rotate (Instruction *p, int e, int n) {
invert(p, n - 1);
invert(p + n, e - n);
invert(p, e);
}
#define op_step(p) ((p)->i.code == IAny ? (p)->i.aux : 1)
static int skipchecks (Instruction *p, int up, int *pn) {
int i, n = 0;
for (i = 0; isfixcheck(p + i); i += sizei(p + i)) {
int st = op_step(p + i);
if (n + st > MAXOFF - up) break;
n += st;
}
*pn = n;
return i;
}
#define ismovablecap(op) (ismovable(op) && getoff(op) < MAXOFF)
static void optimizecaptures (Instruction *p) {
int i;
int limit = 0;
for (i = 0; p[i].i.code != IEnd; i += sizei(p + i)) {
if (isjmp(p + i) && dest(p, i) >= limit)
limit = dest(p, i) + 1; /* do not optimize jump targets */
else if (i >= limit && ismovablecap(p + i) && isfixcheck(p + i + 1)) {
int end, n, j; /* found a border capture|check */
int maxoff = getoff(p + i);
int start = i;
/* find first capture in the group */
while (start > limit && ismovablecap(p + start - 1)) {
start--;
if (getoff(p + start) > maxoff) maxoff = getoff(p + start);
}
end = skipchecks(p + i + 1, maxoff, &n) + i; /* find last check */
if (n == 0) continue; /* first check is too big to move across */
assert(n <= MAXOFF && start <= i && i < end);
for (j = start; j <= i; j++)
p[j].i.aux += (n << 4); /* correct offset of captures to be moved */
rotate(p + start, end - start, i - start + 1); /* move them up */
i = end;
assert(isfixcheck(p + start) && iscapture(p + i));
}
}
}
static int target (Instruction *p, int i) {
while (p[i].i.code == IJmp) i += p[i].i.offset;
return i;
}
static void optimizejumps (Instruction *p) {
int i;
for (i = 0; p[i].i.code != IEnd; i += sizei(p + i)) {
if (isjmp(p + i))
p[i].i.offset = target(p, dest(p, i)) - i;
}
}
static void optimizechoice (Instruction *p) {
assert(p->i.code == IChoice);
if (isfixcheck(p + 1)) {
int lc = sizei(p + 1);
rotate(p, lc, 1);
assert(isfixcheck(p) && (p + lc)->i.code == IChoice);
(p + lc)->i.aux = op_step(p);
check2test(p, (p + lc)->i.offset);
(p + lc)->i.offset -= lc;
}
}
/*
** A 'headfail' pattern is a pattern that can only fails in its first
** instruction, which must be a check.
*/
static int isheadfail (Instruction *p) {
if (!ischeck(p)) return 0;
/* check that other operations cannot fail */
for (p += sizei(p); p->i.code != IEnd; p += sizei(p))
if (!isnofail(p)) return 0;
return 1;
}
#define checkpattern(L, idx) ((Instruction *)luaL_checkudata(L, idx, PATTERN_T))
/*
** Return the number of elements in the ktable of a pattern.
** in Lua 5.2, default "environment" for patterns is nil, not
** a table. Treat it as an empty table.
*/
static int ktablelen (lua_State *L, int idx) {
if (!lua_istable(L, idx)) return 0;
else return lua_objlen(L, idx);
}
/*
** join the elements of the ktable from pattern 'p1' into the ktable of
** the pattern at the top of the stack ('p'). If 'p1' has no elements,
** 'p' keeps its original ktable. If 'p' has no elements, it shares
** 'p1' ktable. Otherwise, this function creates a new ktable for 'p'.
** Return the offset of original 'p' elements in the new ktable.
*/
static int jointable (lua_State *L, int p1) {
int n, n1, i;
lua_getfenv(L, p1);
n1 = ktablelen(L, -1); /* number of elements in p1's env */
lua_getfenv(L, -2);
if (n1 == 0 || lua_equal(L, -2, -1)) {
lua_pop(L, 2);
return 0; /* no need to change anything */
}
n = ktablelen(L, -1); /* number of elements in p's env */
if (n == 0) {
lua_pop(L, 1); /* removes p env */
lua_setfenv(L, -2); /* p now shares p1's env */
return 0; /* no need to correct anything */
}
lua_createtable(L, n + n1, 0);
/* stack: p; p1 env; p env; new p env */
for (i = 1; i <= n; i++) {
lua_rawgeti(L, -2, i);
lua_rawseti(L, -2, i);
}
for (i = 1; i <= n1; i++) {
lua_rawgeti(L, -3, i);
lua_rawseti(L, -2, n + i);
}
lua_setfenv(L, -4); /* new table becomes p env */
lua_pop(L, 2); /* remove p1 env and old p env */
return n;
}
#define copypatt(p1,p2,sz) memcpy(p1, p2, (sz) * sizeof(Instruction));
#define pattsize(L,idx) (lua_objlen(L, idx)/sizeof(Instruction) - 1)
static int addpatt (lua_State *L, Instruction *p, int p1idx) {
Instruction *p1 = (Instruction *)lua_touserdata(L, p1idx);
int sz = pattsize(L, p1idx);
int corr = jointable(L, p1idx);