forked from Qihoo360/Atlas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlpeg.c
More file actions
2165 lines (1853 loc) · 56.1 KB
/
Copy pathlpeg.c
File metadata and controls
2165 lines (1853 loc) · 56.1 KB
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.86 2008/03/07 17:20:19 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 <limits.h>
#include <stdio.h>
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#define VERSION "0.8"
#define PATTERN_T "pattern"
/* maximum call/backtrack levels */
#define MAXBACK 400
/* initial size for capture's list */
#define IMAXCAPTURES 600
/* 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(ptop) ((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)
typedef unsigned char byte;
#define CHARSETSIZE ((UCHAR_MAX/CHAR_BIT) + 1)
typedef byte Charset[CHARSETSIZE];
typedef const char *(*PattFunc) (const void *ud,
const char *o, /* string start */
const char *s, /* current position */
const char *e); /* string end */
/* Virtual Machine's instructions */
typedef enum Opcode {
IAny, IChar, ISet, IZSet,
ITestAny, ITestChar, ITestSet, ITestZSet,
ISpan, ISpanZ,
IRet, IEnd,
IChoice, IJmp, ICall, IOpenCall,
ICommit, IPartialCommit, IBackCommit, IFailTwice, IFail, IGiveup,
IFunc,
IFullCapture, IEmptyCapture, IEmptyCaptureIdx,
IOpenCapture, ICloseCapture, ICloseRunTime
} Opcode;
#define ISJMP 1
#define ISCHECK 2
#define ISTEST 4
#define ISNOFAIL 8
#define ISCAPTURE 16
#define ISMOVABLE 32
#define ISFENVOFF 64
#define HASCHARSET 128
static const byte opproperties[] = {
/* IAny */ ISCHECK,
/* IChar */ ISCHECK,
/* ISet */ ISCHECK | HASCHARSET,
/* IZSet */ ISCHECK | HASCHARSET,
/* ITestAny */ ISJMP | ISTEST | ISNOFAIL,
/* ITestChar */ ISJMP | ISTEST | ISNOFAIL,
/* ITestSet */ ISJMP | ISTEST | ISNOFAIL | HASCHARSET,
/* ITestZSet */ ISJMP | ISTEST | ISNOFAIL | HASCHARSET,
/* ISpan */ ISNOFAIL | HASCHARSET,
/* ISpanZ */ ISNOFAIL | HASCHARSET,
/* 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 */ 0,
/* 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;
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 isprop(op,p) (opproperties[(op)->i.code] & (p))
#define isjmp(op) isprop(op, ISJMP)
#define iscapture(op) isprop(op, ISCAPTURE)
#define ischeck(op) isprop(op, ISCHECK)
#define istest(op) isprop(op, ISTEST)
#define isnofail(op) isprop(op, ISNOFAIL)
#define ismovable(op) isprop(op, ISMOVABLE)
#define isfenvoff(op) isprop(op, ISFENVOFF)
#define hascharset(op) isprop(op, HASCHARSET)
/* kinds of captures */
typedef enum CapKind {
Cclose, Cposition, Cconst, Cbackref, Carg, Csimple, Ctable, Cfunction,
Cquery, Cstring, Csubst, Caccum, Cruntime
} CapKind;
#define iscapnosize(k) ((k) == Cposition || (k) == Cconst)
typedef struct Capture {
const char *s; /* position */
short idx;
byte kind;
byte siz;
} Capture;
/* maximum size (in elements) for a pattern */
#define MAXPATTSIZE (SHRT_MAX - 10)
/* size (in elements) for an instruction plus extra l bytes */
#define instsize(l) (((l) - 1)/sizeof(Instruction) + 2)
/* size (in elements) for a ISet instruction */
#define CHARSETINSTSIZE instsize(CHARSETSIZE)
#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) {
if (hascharset(i)) return CHARSETINSTSIZE;
else if (i->i.code == IFunc) return i->i.offset;
else 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, -1));
}
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", "accumulator",
"runtime"};
printf("%s", modes[kind]);
}
static void printjmp (const Instruction *op, const Instruction *p) {
printf("-> %ld", (long)(dest(0, p) - op));
}
static void printinst (const Instruction *op, const Instruction *p) {
const char *const names[] = {
"any", "char", "set", "zset",
"testany", "testchar", "testset", "testzset",
"span", "spanz",
"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);
break;
}
case ITestChar: {
printf("'%c'", p->i.aux);
printjmp(op, p);
break;
}
case IAny: {
printf("* %d", p->i.aux);
break;
}
case ITestAny: {
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: case IZSet: case ISpan: case ISpanZ: {
printcharset((p+1)->buff);
break;
}
case ITestSet: case ITestZSet: {
printcharset((p+1)->buff);
printjmp(op, p);
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 (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;
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 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;
}
static const char *match (lua_State *L,
const char *o, const char *s, const char *e,
Instruction *op, Capture *capture, int ptop) {
Stack stackbase[MAXBACK];
Stack *stacklimit = stackbase + MAXBACK;
Stack *stack = stackbase; /* point to first empty slot in stack */
int capsize = IMAXCAPTURES;
int captop = 0; /* point to first empty slot in captures */
const Instruction *p = op;
stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
for (;;) {
#if defined(DEBUG)
printf("s: |%s| stck: %d c: %d ", s, stack - stackbase, captop);
printinst(op, p);
#endif
switch ((Opcode)p->i.code) {
case IEnd: {
assert(stack == stackbase + 1);
capture[captop].kind = Cclose;
capture[captop].s = NULL;
return s;
}
case IGiveup: {
assert(stack == stackbase);
return NULL;
}
case IRet: {
assert(stack > stackbase && (stack - 1)->s == NULL);
p = (--stack)->p;
continue;
}
case IAny: {
int n = p->i.aux;
if (n > e - s) goto fail;
else { p++; s += n; }
continue;
}
case ITestAny: {
int n = p->i.aux;
if (n > e - s) p += p->i.offset;
else { p++; s += n; }
continue;
}
case IChar: {
if ((byte)*s != p->i.aux || s >= e) goto fail;
else { p++; s++; }
continue;
}
case ITestChar: {
if ((byte)*s != p->i.aux || s >= e) p += p->i.offset;
else { p++; s++; }
continue;
}
case ISet: {
int c = (unsigned char)*s;
if (!testchar((p+1)->buff, c)) goto fail;
else { p += CHARSETINSTSIZE; s++; }
continue;
}
case ITestSet: {
int c = (unsigned char)*s;
if (!testchar((p+1)->buff, c)) p += p->i.offset;
else { p += CHARSETINSTSIZE; s++; }
continue;
}
case IZSet: {
int c = (unsigned char)*s;
if (!testchar((p+1)->buff, c) || s >= e) goto fail;
else { p += CHARSETINSTSIZE; s++; }
continue;
}
case ITestZSet: {
int c = (unsigned char)*s;
if (!testchar((p+1)->buff, c) || s >= e) p += p->i.offset;
else { p += CHARSETINSTSIZE; s++; }
continue;
}
case ISpan: {
for (;; s++) {
int c = (unsigned char)*s;
if (!testchar((p+1)->buff, c)) break;
}
p += CHARSETINSTSIZE;
continue;
}
case ISpanZ: {
for (; s < e; s++) {
int c = (unsigned char)*s;
if (!testchar((p+1)->buff, c)) break;
}
p += CHARSETINSTSIZE;
continue;
}
case IFunc: {
const char *r = (p+1)->f((p+2)->buff, o, s, e);
if (r == NULL) goto fail;
s = r;
p += p->i.offset;
continue;
}
case IJmp: {
p += p->i.offset;
continue;
}
case IChoice: {
if (stack >= stacklimit)
return (luaL_error(L, "too many pending calls/choices"), (char *)0);
stack->p = dest(0, p);
stack->s = s - p->i.aux;
stack->caplevel = captop;
stack++;
p++;
continue;
}
case ICall: {
if (stack >= stacklimit)
return (luaL_error(L, "too many pending calls/choices"), (char *)0);
stack->s = NULL;
stack->p = p + 1; /* save return address */
stack++;
p += p->i.offset;
continue;
}
case ICommit: {
assert(stack > stackbase && (stack - 1)->s != NULL);
stack--;
p += p->i.offset;
continue;
}
case IPartialCommit: {
assert(stack > stackbase && (stack - 1)->s != NULL);
(stack - 1)->s = s;
(stack - 1)->caplevel = captop;
p += p->i.offset;
continue;
}
case IBackCommit: {
assert(stack > stackbase && (stack - 1)->s != NULL);
s = (--stack)->s;
p += p->i.offset;
continue;
}
case IFailTwice:
assert(stack > stackbase);
stack--;
/* go through */
case IFail:
fail: { /* pattern failed: try to backtrack */
do { /* remove pending calls */
assert(stack > stackbase);
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
** =======================================================
*/
static int verify (lua_State *L, Instruction *op, const Instruction *p,
Instruction *e, int postable, int rule) {
static const char dummy[] = "";
Stack back[MAXBACK];
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 >= MAXBACK)
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 >= MAXBACK)
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 >= MAXBACK)
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 ITestAny:
case ITestChar: /* all these cases jump for empty subject */
case ITestSet:
case ITestZSet:
case IJmp:
dojmp: {
p += p->i.offset;
continue;
}
case IAny:
case IChar:
case ISet:
case IZSet:
case IFailTwice: /* assume that first level failed; try to backtrack */
goto fail;
case IFail: {
if (p->i.aux) { /* is an 'and' predicate? */
assert((p - 1)->i.code == IBackCommit && (p - 1)->i.offset == 2);
p++; /* pretend it succeeded and go ahead */
continue;
}
/* else 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 ISpanZ:
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((p+2)->buff, dummy, dummy, dummy);
if (r == NULL) goto fail;
p += p->i.offset;
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));
p->i.code += ITestAny - IAny;
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; ischeck(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) && ischeck(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(ischeck(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 (ischeck(p + 1)) {
int lc = sizei(p + 1);
rotate(p, lc, 1);
assert(ischeck(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))
static int jointable (lua_State *L, int p1) {
int n, n1, i;
lua_getfenv(L, p1);
n1 = lua_objlen(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 = lua_objlen(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);
copypatt(p, p1, sz + 1);
if (corr != 0) {
Instruction *px;
for (px = p; px < p + sz; px += sizei(px)) {
if (isfenvoff(px) && px->i.offset != 0)
px->i.offset += corr;
}
}
return sz;
}
static void setinstaux (Instruction *i, Opcode op, int offset, int aux) {
i->i.code = op;
i->i.offset = offset;
i->i.aux = aux;
}
#define setinst(i,op,off) setinstaux(i,op,off,0)
#define setinstcap(i,op,idx,k,n) setinstaux(i,op,idx,((k) | ((n) << 4)))
static int value2fenv (lua_State *L, int vidx) {
lua_createtable(L, 1, 0);
lua_pushvalue(L, vidx);
lua_rawseti(L, -2, 1);
lua_setfenv(L, -2);
return 1;
}
static Instruction *newpatt (lua_State *L, size_t n) {
Instruction *p;
if (n >= MAXPATTSIZE - 1)
luaL_error(L, "pattern too big");
p = (Instruction *)lua_newuserdata(L, (n + 1) * sizeof(Instruction));
luaL_getmetatable(L, PATTERN_T);
lua_setmetatable(L, -2);
setinst(p + n, IEnd, 0);
return p;
}
static void fillcharset (Instruction *p, Charset cs) {
switch (p[0].i.code) {
case IZSet: case ITestZSet:
assert(testchar(p[1].buff, '\0'));
/* go through */
case ISet: case ITestSet: {
loopset(i, cs[i] = p[1].buff[i]);
break;
}
case IChar: case ITestChar: {
loopset(i, cs[i] = 0);