Debian Codegraph @

texk/web2c/mfluadir/luapeg/lpeg.c

raw
1 #include "lpeg.h"
2
3 /*
4 ** $Id: lpprint.c,v 1.10 2016/09/13 16:06:03 roberto Exp $
5 ** Copyright 2007, Lua.org & PUC-Rio (see 'lpeg.html' for license)
6 */
7
8 /* #include <ctype.h> */
9 /* #include <limits.h> */
10 /* #include <stdio.h> */
11
12
13 /* #include "lptypes.h" */
14 /* #include "lpprint.h" */
15 /* #include "lpcode.h" */
16
17
18 #if defined(LPEG_DEBUG)
19
20 /*
21 ** {======================================================
22 ** Printing patterns (for debugging)
23 ** =======================================================
24 */
25
26
27 void printcharset (const byte *st) {
28 int i;
29 printf("[");
30 for (i = 0; i <= UCHAR_MAX; i++) {
31 int first = i;
32 while (testchar(st, i) && i <= UCHAR_MAX) i++;
33 if (i - 1 == first) /* unary range? */
34 printf("(%02x)", first);
35 else if (i - 1 > first) /* non-empty range? */
36 printf("(%02x-%02x)", first, i - 1);
37 }
38 printf("]");
39 }
40
41
42 static const char *capkind (int kind) {
43 const char *const modes[] = {
44 "close", "position", "constant", "backref",
45 "argument", "simple", "table", "function",
46 "query", "string", "num", "substitution", "fold",
47 "runtime", "group"};
48 return modes[kind];
49 }
50
51
52 static void printjmp (const Instruction *op, const Instruction *p) {
53 printf("-> %d", (int)(p + (p + 1)->offset - op));
54 }
55
56
57 void printinst (const Instruction *op, const Instruction *p) {
58 const char *const names[] = {
59 "any", "char", "set",
60 "testany", "testchar", "testset",
61 "span", "behind",
62 "ret", "end",
63 "choice", "jmp", "call", "open_call",
64 "commit", "partial_commit", "back_commit", "failtwice", "fail", "giveup",
65 "fullcapture", "opencapture", "closecapture", "closeruntime"
66 };
67 printf("%02ld: %s ", (long)(p - op), names[p->i.code]);
68 switch ((Opcode)p->i.code) {
69 case IChar: {
70 printf("'%c'", p->i.aux);
71 break;
72 }
73 case ITestChar: {
74 printf("'%c'", p->i.aux); printjmp(op, p);
75 break;
76 }
77 case IFullCapture: {
78 printf("%s (size = %d) (idx = %d)",
79 capkind(getkind(p)), getoff(p), p->i.key);
80 break;
81 }
82 case IOpenCapture: {
83 printf("%s (idx = %d)", capkind(getkind(p)), p->i.key);
84 break;
85 }
86 case ISet: {
87 printcharset((p+1)->buff);
88 break;
89 }
90 case ITestSet: {
91 printcharset((p+2)->buff); printjmp(op, p);
92 break;
93 }
94 case ISpan: {
95 printcharset((p+1)->buff);
96 break;
97 }
98 case IOpenCall: {
99 printf("-> %d", (p + 1)->offset);
100 break;
101 }
102 case IBehind: {
103 printf("%d", p->i.aux);
104 break;
105 }
106 case IJmp: case ICall: case ICommit: case IChoice:
107 case IPartialCommit: case IBackCommit: case ITestAny: {
108 printjmp(op, p);
109 break;
110 }
111 default: break;
112 }
113 printf("\n");
114 }
115
116
117 void printpatt (Instruction *p, int n) {
118 Instruction *op = p;
119 while (p < op + n) {
120 printinst(op, p);
121 p += sizei(p);
122 }
123 }
124
125
126 #if defined(LPEG_DEBUG)
127 static void printcap (Capture *cap) {
128 printf("%s (idx: %d - size: %d) -> %p\n",
129 capkind(cap->kind), cap->idx, cap->siz, cap->s);
130 }
131
132
133 void printcaplist (Capture *cap, Capture *limit) {
134 printf(">======\n");
135 for (; cap->s && (limit == NULL || cap < limit); cap++)
136 printcap(cap);
137 printf("=======\n");
138 }
139 #endif
140
141 /* }====================================================== */
142
143
144 /*
145 ** {======================================================
146 ** Printing trees (for debugging)
147 ** =======================================================
148 */
149
150 static const char *tagnames[] = {
151 "char", "set", "any",
152 "true", "false",
153 "rep",
154 "seq", "choice",
155 "not", "and",
156 "call", "opencall", "rule", "grammar",
157 "behind",
158 "capture", "run-time"
159 };
160
161
162 void printtree (TTree *tree, int ident) {
163 int i;
164 for (i = 0; i < ident; i++) printf(" ");
165 printf("%s", tagnames[tree->tag]);
166 switch (tree->tag) {
167 case TChar: {
168 int c = tree->u.n;
169 if (isprint(c))
170 printf(" '%c'\n", c);
171 else
172 printf(" (%02X)\n", c);
173 break;
174 }
175 case TSet: {
176 printcharset(treebuffer(tree));
177 printf("\n");
178 break;
179 }
180 case TOpenCall: case TCall: {
181 assert(sib2(tree)->tag == TRule);
182 printf(" key: %d (rule: %d)\n", tree->key, sib2(tree)->cap);
183 break;
184 }
185 case TBehind: {
186 printf(" %d\n", tree->u.n);
187 printtree(sib1(tree), ident + 2);
188 break;
189 }
190 case TCapture: {
191 printf(" kind: '%s' key: %d\n", capkind(tree->cap), tree->key);
192 printtree(sib1(tree), ident + 2);
193 break;
194 }
195 case TRule: {
196 printf(" n: %d key: %d\n", tree->cap, tree->key);
197 printtree(sib1(tree), ident + 2);
198 break; /* do not print next rule as a sibling */
199 }
200 case TGrammar: {
201 TTree *rule = sib1(tree);
202 printf(" %d\n", tree->u.n); /* number of rules */
203 for (i = 0; i < tree->u.n; i++) {
204 printtree(rule, ident + 2);
205 rule = sib2(rule);
206 }
207 assert(rule->tag == TTrue); /* sentinel */
208 break;
209 }
210 default: {
211 int sibs = numsiblings[tree->tag];
212 printf("\n");
213 if (sibs >= 1) {
214 printtree(sib1(tree), ident + 2);
215 if (sibs >= 2)
216 printtree(sib2(tree), ident + 2);
217 }
218 break;
219 }
220 }
221 }
222
223
224 void printktable (lua_State *L, int idx) {
225 int n, i;
226 lua_getuservalue(L, idx);
227 if (lua_isnil(L, -1)) /* no ktable? */
228 return;
229 n = lua_rawlen(L, -1);
230 printf("[");
231 for (i = 1; i <= n; i++) {
232 printf("%d = ", i);
233 lua_rawgeti(L, -1, i);
234 if (lua_isstring(L, -1))
235 printf("%s ", lua_tostring(L, -1));
236 else
237 printf("%s ", lua_typename(L, lua_type(L, -1)));
238 lua_pop(L, 1);
239 }
240 printf("]\n");
241 /* leave ktable at the stack */
242 }
243
244 /* }====================================================== */
245
246 #endif
247 /*
248 ** $Id: lpvm.c,v 1.9 2016/06/03 20:11:18 roberto Exp $
249 ** Copyright 2007, Lua.org & PUC-Rio (see 'lpeg.html' for license)
250 */
251
252 /* #include <limits.h> */
253 /* #include <string.h> */
254
255
256 /* #include "lua.h" */
257 /* #include "lauxlib.h" */
258
259 /* #include "lpcap.h" */
260 /* #include "lptypes.h" */
261 /* #include "lpvm.h" */
262 /* #include "lpprint.h" */
263
264
265 /* initial size for call/backtrack stack */
266 #if !defined(INITBACK)
267 #define INITBACK MAXBACK
268 #endif
269
270
271 #define getoffset(p) (((p) + 1)->offset)
272
273 static const Instruction giveup = {{IGiveup, 0, 0}};
274
275
276 /*
277 ** {======================================================
278 ** Virtual Machine
279 ** =======================================================
280 */
281
282
283 typedef struct Stack {
284 const char *s; /* saved position (or NULL for calls) */
285 const Instruction *p; /* next instruction */
286 int caplevel;
287 } Stack;
288
289
290 #define getstackbase(L, ptop) ((Stack *)lua_touserdata(L, stackidx(ptop)))
291
292
293 /*
294 ** Make the size of the array of captures 'cap' twice as large as needed
295 ** (which is 'captop'). ('n' is the number of new elements.)
296 */
297 static Capture *doublecap (lua_State *L, Capture *cap, int captop,
298 int n, int ptop) {
299 Capture *newc;
300 if (captop >= INT_MAX/((int)sizeof(Capture) * 2))
301 luaL_error(L, "too many captures");
302 newc = (Capture *)lua_newuserdata(L, captop * 2 * sizeof(Capture));
303 memcpy(newc, cap, (captop - n) * sizeof(Capture));
304 lua_replace(L, caplistidx(ptop));
305 return newc;
306 }
307
308
309 /*
310 ** Double the size of the stack
311 */
312 static Stack *doublestack (lua_State *L, Stack **stacklimit, int ptop) {
313 Stack *stack = getstackbase(L, ptop);
314 Stack *newstack;
315 int n = *stacklimit - stack; /* current stack size */
316 int max, newn;
317 lua_getfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
318 max = lua_tointeger(L, -1); /* maximum allowed size */
319 lua_pop(L, 1);
320 if (n >= max) /* already at maximum size? */
321 luaL_error(L, "backtrack stack overflow (current limit is %d)", max);
322 newn = 2 * n; /* new size */
323 if (newn > max) newn = max;
324 newstack = (Stack *)lua_newuserdata(L, newn * sizeof(Stack));
325 memcpy(newstack, stack, n * sizeof(Stack));
326 lua_replace(L, stackidx(ptop));
327 *stacklimit = newstack + newn;
328 return newstack + n; /* return next position */
329 }
330
331
332 /*
333 ** Interpret the result of a dynamic capture: false -> fail;
334 ** true -> keep current position; number -> next position.
335 ** Return new subject position. 'fr' is stack index where
336 ** is the result; 'curr' is current subject position; 'limit'
337 ** is subject's size.
338 */
339 static int resdyncaptures (lua_State *L, int fr, int curr, int limit) {
340 lua_Integer res;
341 if (!lua_toboolean(L, fr)) { /* false value? */
342 lua_settop(L, fr - 1); /* remove results */
343 return -1; /* and fail */
344 }
345 else if (lua_isboolean(L, fr)) /* true? */
346 res = curr; /* keep current position */
347 else {
348 res = lua_tointeger(L, fr) - 1; /* new position */
349 if (res < curr || res > limit)
350 luaL_error(L, "invalid position returned by match-time capture");
351 }
352 lua_remove(L, fr); /* remove first result (offset) */
353 return res;
354 }
355
356
357 /*
358 ** Add capture values returned by a dynamic capture to the capture list
359 ** 'base', nested inside a group capture. 'fd' indexes the first capture
360 ** value, 'n' is the number of values (at least 1).
361 */
362 static void adddyncaptures (const char *s, Capture *base, int n, int fd) {
363 int i;
364 base[0].kind = Cgroup; /* create group capture */
365 base[0].siz = 0;
366 base[0].idx = 0; /* make it an anonymous group */
367 for (i = 1; i <= n; i++) { /* add runtime captures */
368 base[i].kind = Cruntime;
369 base[i].siz = 1; /* mark it as closed */
370 base[i].idx = fd + i - 1; /* stack index of capture value */
371 base[i].s = s;
372 }
373 base[i].kind = Cclose; /* close group */
374 base[i].siz = 1;
375 base[i].s = s;
376 }
377
378
379 /*
380 ** Remove dynamic captures from the Lua stack (called in case of failure)
381 */
382 static int removedyncap (lua_State *L, Capture *capture,
383 int level, int last) {
384 int id = finddyncap(capture + level, capture + last); /* index of 1st cap. */
385 int top = lua_gettop(L);
386 if (id == 0) return 0; /* no dynamic captures? */
387 lua_settop(L, id - 1); /* remove captures */
388 return top - id + 1; /* number of values removed */
389 }
390
391
392 /*
393 ** Opcode interpreter luajit aarch64
394 */
395 /* luajit aarch64 */
396 /* https://github.com/LuaJIT/LuaJIT/pull/230#issuecomment-260205661 */
397 /* We play safe on arm64 assuming a virtual address bits VA_BITS >47,*/
398 /* even if a Linux kernel can be configured with VA_BITS < 47 */
399 /* and lightuserdata is ok then. Anyway, */
400 /* replacing lightuserdata with full userdata seems ok wrt performance. */
401 /* No need to free a userdata, it's GC */
402 const char *match (lua_State *L, const char *o, const char *s, const char *e,
403 Instruction *op, Capture *capture, int ptop) {
404 #if defined(__aarch64__) && defined(MFLuaJIT)
405 Stack *stackbase = (Stack*)lua_newuserdata(L,sizeof(Stack)*INITBACK);
406 Stack *stacklimit = stackbase + INITBACK;
407 Stack *stack = stackbase; /* point to first empty slot in stack */
408 int capsize = INITCAPSIZE;
409 int captop = 0; /* point to first empty slot in captures */
410 int ndyncap = 0; /* number of dynamic captures (in Lua stack) */
411 const Instruction *p = op; /* current instruction */
412 stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
413 #else
414 Stack stackbase[INITBACK];
415 Stack *stacklimit = stackbase + INITBACK;
416 Stack *stack = stackbase; /* point to first empty slot in stack */
417 int capsize = INITCAPSIZE;
418 int captop = 0; /* point to first empty slot in captures */
419 int ndyncap = 0; /* number of dynamic captures (in Lua stack) */
420 const Instruction *p = op; /* current instruction */
421 stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
422 lua_pushlightuserdata(L, stackbase);
423 #endif
424 for (;;) {
425 #if defined(DEBUG)
426 printf("-------------------------------------\n");
427 printcaplist(capture, capture + captop);
428 printf("s: |%s| stck:%d, dyncaps:%d, caps:%d ",
429 s, (int)(stack - getstackbase(L, ptop)), ndyncap, captop);
430 printinst(op, p);
431 #endif
432 assert(stackidx(ptop) + ndyncap == lua_gettop(L) && ndyncap <= captop);
433 switch ((Opcode)p->i.code) {
434 case IEnd: {
435 assert(stack == getstackbase(L, ptop) + 1);
436 capture[captop].kind = Cclose;
437 capture[captop].s = NULL;
438 return s;
439 }
440 case IGiveup: {
441 assert(stack == getstackbase(L, ptop));
442 return NULL;
443 }
444 case IRet: {
445 assert(stack > getstackbase(L, ptop) && (stack - 1)->s == NULL);
446 p = (--stack)->p;
447 continue;
448 }
449 case IAny: {
450 if (s < e) { p++; s++; }
451 else goto fail;
452 continue;
453 }
454 case ITestAny: {
455 if (s < e) p += 2;
456 else p += getoffset(p);
457 continue;
458 }
459 case IChar: {
460 if ((byte)*s == p->i.aux && s < e) { p++; s++; }
461 else goto fail;
462 continue;
463 }
464 case ITestChar: {
465 if ((byte)*s == p->i.aux && s < e) p += 2;
466 else p += getoffset(p);
467 continue;
468 }
469 case ISet: {
470 int c = (byte)*s;
471 if (testchar((p+1)->buff, c) && s < e)
472 { p += CHARSETINSTSIZE; s++; }
473 else goto fail;
474 continue;
475 }
476 case ITestSet: {
477 int c = (byte)*s;
478 if (testchar((p + 2)->buff, c) && s < e)
479 p += 1 + CHARSETINSTSIZE;
480 else p += getoffset(p);
481 continue;
482 }
483 case IBehind: {
484 int n = p->i.aux;
485 if (n > s - o) goto fail;
486 s -= n; p++;
487 continue;
488 }
489 case ISpan: {
490 for (; s < e; s++) {
491 int c = (byte)*s;
492 if (!testchar((p+1)->buff, c)) break;
493 }
494 p += CHARSETINSTSIZE;
495 continue;
496 }
497 case IJmp: {
498 p += getoffset(p);
499 continue;
500 }
501 case IChoice: {
502 if (stack == stacklimit)
503 stack = doublestack(L, &stacklimit, ptop);
504 stack->p = p + getoffset(p);
505 stack->s = s;
506 stack->caplevel = captop;
507 stack++;
508 p += 2;
509 continue;
510 }
511 case ICall: {
512 if (stack == stacklimit)
513 stack = doublestack(L, &stacklimit, ptop);
514 stack->s = NULL;
515 stack->p = p + 2; /* save return address */
516 stack++;
517 p += getoffset(p);
518 continue;
519 }
520 case ICommit: {
521 assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
522 stack--;
523 p += getoffset(p);
524 continue;
525 }
526 case IPartialCommit: {
527 assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
528 (stack - 1)->s = s;
529 (stack - 1)->caplevel = captop;
530 p += getoffset(p);
531 continue;
532 }
533 case IBackCommit: {
534 assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
535 s = (--stack)->s;
536 captop = stack->caplevel;
537 p += getoffset(p);
538 continue;
539 }
540 case IFailTwice:
541 assert(stack > getstackbase(L, ptop));
542 stack--;
543 /* go through */
544 case IFail:
545 fail: { /* pattern failed: try to backtrack */
546 do { /* remove pending calls */
547 assert(stack > getstackbase(L, ptop));
548 s = (--stack)->s;
549 } while (s == NULL);
550 if (ndyncap > 0) /* is there matchtime captures? */
551 ndyncap -= removedyncap(L, capture, stack->caplevel, captop);
552 captop = stack->caplevel;
553 p = stack->p;
554 #if defined(DEBUG)
555 printf("**FAIL**\n");
556 #endif
557 continue;
558 }
559 case ICloseRunTime: {
560 CapState cs;
561 int rem, res, n;
562 int fr = lua_gettop(L) + 1; /* stack index of first result */
563 cs.s = o; cs.L = L; cs.ocap = capture; cs.ptop = ptop;
564 n = runtimecap(&cs, capture + captop, s, &rem); /* call function */
565 captop -= n; /* remove nested captures */
566 ndyncap -= rem; /* update number of dynamic captures */
567 fr -= rem; /* 'rem' items were popped from Lua stack */
568 res = resdyncaptures(L, fr, s - o, e - o); /* get result */
569 if (res == -1) /* fail? */
570 goto fail;
571 s = o + res; /* else update current position */
572 n = lua_gettop(L) - fr + 1; /* number of new captures */
573 ndyncap += n; /* update number of dynamic captures */
574 if (n > 0) { /* any new capture? */
575 if (fr + n >= SHRT_MAX)
576 luaL_error(L, "too many results in match-time capture");
577 if ((captop += n + 2) >= capsize) {
578 capture = doublecap(L, capture, captop, n + 2, ptop);
579 capsize = 2 * captop;
580 }
581 /* add new captures to 'capture' list */
582 adddyncaptures(s, capture + captop - n - 2, n, fr);
583 }
584 p++;
585 continue;
586 }
587 case ICloseCapture: {
588 const char *s1 = s;
589 assert(captop > 0);
590 /* if possible, turn capture into a full capture */
591 if (capture[captop - 1].siz == 0 &&
592 s1 - capture[captop - 1].s < UCHAR_MAX) {
593 capture[captop - 1].siz = s1 - capture[captop - 1].s + 1;
594 p++;
595 continue;
596 }
597 else {
598 capture[captop].siz = 1; /* mark entry as closed */
599 capture[captop].s = s;
600 goto pushcapture;
601 }
602 }
603 case IOpenCapture:
604 capture[captop].siz = 0; /* mark entry as open */
605 capture[captop].s = s;
606 goto pushcapture;
607 case IFullCapture:
608 capture[captop].siz = getoff(p) + 1; /* save capture size */
609 capture[captop].s = s - getoff(p);
610 /* goto pushcapture; */
611 pushcapture: {
612 capture[captop].idx = p->i.key;
613 capture[captop].kind = getkind(p);
614 if (++captop >= capsize) {
615 capture = doublecap(L, capture, captop, 0, ptop);
616 capsize = 2 * captop;
617 }
618 p++;
619 continue;
620 }
621 default: assert(0); return NULL;
622 }
623 }
624 }
625
626 /* }====================================================== */
627
628
629 /*
630 ** $Id: lpcode.c,v 1.24 2016/09/15 17:46:13 roberto Exp $
631 ** Copyright 2007, Lua.org & PUC-Rio (see 'lpeg.html' for license)
632 */
633
634 /* #include <limits.h> */
635
636
637 /* #include "lua.h" */
638 /* #include "lauxlib.h" */
639
640 /* #include "lptypes.h" */
641 /* #include "lpcode.h" */
642
643
644 /* signals a "no-instruction */
645 #define NOINST -1
646
647
648
649 static const Charset fullset_ =
650 {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
651 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
652 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
653 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
654
655 static const Charset *fullset = &fullset_;
656
657 /*
658 ** {======================================================
659 ** Analysis and some optimizations
660 ** =======================================================
661 */
662
663 /*
664 ** Check whether a charset is empty (returns IFail), singleton (IChar),
665 ** full (IAny), or none of those (ISet). When singleton, '*c' returns
666 ** which character it is. (When generic set, the set was the input,
667 ** so there is no need to return it.)
668 */
669 static Opcode charsettype (const byte *cs, int *c) {
670 int count = 0; /* number of characters in the set */
671 int i;
672 int candidate = -1; /* candidate position for the singleton char */
673 for (i = 0; i < CHARSETSIZE; i++) { /* for each byte */
674 int b = cs[i];
675 if (b == 0) { /* is byte empty? */
676 if (count > 1) /* was set neither empty nor singleton? */
677 return ISet; /* neither full nor empty nor singleton */
678 /* else set is still empty or singleton */
679 }
680 else if (b == 0xFF) { /* is byte full? */
681 if (count < (i * BITSPERCHAR)) /* was set not full? */
682 return ISet; /* neither full nor empty nor singleton */
683 else count += BITSPERCHAR; /* set is still full */
684 }
685 else if ((b & (b - 1)) == 0) { /* has byte only one bit? */
686 if (count > 0) /* was set not empty? */
687 return ISet; /* neither full nor empty nor singleton */
688 else { /* set has only one char till now; track it */
689 count++;
690 candidate = i;
691 }
692 }
693 else return ISet; /* byte is neither empty, full, nor singleton */
694 }
695 switch (count) {
696 case 0: return IFail; /* empty set */
697 case 1: { /* singleton; find character bit inside byte */
698 int b = cs[candidate];
699 *c = candidate * BITSPERCHAR;
700 if ((b & 0xF0) != 0) { *c += 4; b >>= 4; }
701 if ((b & 0x0C) != 0) { *c += 2; b >>= 2; }
702 if ((b & 0x02) != 0) { *c += 1; }
703 return IChar;
704 }
705 default: {
706 assert(count == CHARSETSIZE * BITSPERCHAR); /* full set */
707 return IAny;
708 }
709 }
710 }
711
712
713 /*
714 ** A few basic operations on Charsets
715 */
716 static void cs_complement (Charset *cs) {
717 loopset(i, cs->cs[i] = ~cs->cs[i]);
718 }
719
720 static int cs_equal (const byte *cs1, const byte *cs2) {
721 loopset(i, if (cs1[i] != cs2[i]) return 0);
722 return 1;
723 }
724
725 static int cs_disjoint (const Charset *cs1, const Charset *cs2) {
726 loopset(i, if ((cs1->cs[i] & cs2->cs[i]) != 0) return 0;)
727 return 1;
728 }
729
730
731 /*
732 ** If 'tree' is a 'char' pattern (TSet, TChar, TAny), convert it into a
733 ** charset and return 1; else return 0.
734 */
735 int tocharset (TTree *tree, Charset *cs) {
736 switch (tree->tag) {
737 case TSet: { /* copy set */
738 loopset(i, cs->cs[i] = treebuffer(tree)[i]);
739 return 1;
740 }
741 case TChar: { /* only one char */
742 assert(0 <= tree->u.n && tree->u.n <= UCHAR_MAX);
743 loopset(i, cs->cs[i] = 0); /* erase all chars */
744 setchar(cs->cs, tree->u.n); /* add that one */
745 return 1;
746 }
747 case TAny: {
748 loopset(i, cs->cs[i] = 0xFF); /* add all characters to the set */
749 return 1;
750 }
751 default: return 0;
752 }
753 }
754
755
756 /*
757 ** Visit a TCall node taking care to stop recursion. If node not yet
758 ** visited, return 'f(sib2(tree))', otherwise return 'def' (default
759 ** value)
760 */
761 static int callrecursive (TTree *tree, int f (TTree *t), int def) {
762 int key = tree->key;
763 assert(tree->tag == TCall);
764 assert(sib2(tree)->tag == TRule);
765 if (key == 0) /* node already visited? */
766 return def; /* return default value */
767 else { /* first visit */
768 int result;
769 tree->key = 0; /* mark call as already visited */
770 result = f(sib2(tree)); /* go to called rule */
771 tree->key = key; /* restore tree */
772 return result;
773 }
774 }
775
776
777 /*
778 ** Check whether a pattern tree has captures
779 */
780 int hascaptures (TTree *tree) {
781 tailcall:
782 switch (tree->tag) {
783 case TCapture: case TRunTime:
784 return 1;
785 case TCall:
786 return callrecursive(tree, hascaptures, 0);
787 case TRule: /* do not follow siblings */
788 tree = sib1(tree); goto tailcall;
789 case TOpenCall: assert(0);
790 default: {
791 switch (numsiblings[tree->tag]) {
792 case 1: /* return hascaptures(sib1(tree)); */
793 tree = sib1(tree); goto tailcall;
794 case 2:
795 if (hascaptures(sib1(tree)))
796 return 1;
797 /* else return hascaptures(sib2(tree)); */
798 tree = sib2(tree); goto tailcall;
799 default: assert(numsiblings[tree->tag] == 0); return 0;
800 }
801 }
802 }
803 }
804
805
806 /*
807 ** Checks how a pattern behaves regarding the empty string,
808 ** in one of two different ways:
809 ** A pattern is *nullable* if it can match without consuming any character;
810 ** A pattern is *nofail* if it never fails for any string
811 ** (including the empty string).
812 ** The difference is only for predicates and run-time captures;
813 ** for other patterns, the two properties are equivalent.
814 ** (With predicates, &'a' is nullable but not nofail. Of course,
815 ** nofail => nullable.)
816 ** These functions are all convervative in the following way:
817 ** p is nullable => nullable(p)
818 ** nofail(p) => p cannot fail
819 ** The function assumes that TOpenCall is not nullable;
820 ** this will be checked again when the grammar is fixed.
821 ** Run-time captures can do whatever they want, so the result
822 ** is conservative.
823 */
824 int checkaux (TTree *tree, int pred) {
825 tailcall:
826 switch (tree->tag) {
827 case TChar: case TSet: case TAny:
828 case TFalse: case TOpenCall:
829 return 0; /* not nullable */
830 case TRep: case TTrue:
831 return 1; /* no fail */
832 case TNot: case TBehind: /* can match empty, but can fail */
833 if (pred == PEnofail) return 0;
834 else return 1; /* PEnullable */
835 case TAnd: /* can match empty; fail iff body does */
836 if (pred == PEnullable) return 1;
837 /* else return checkaux(sib1(tree), pred); */
838 tree = sib1(tree); goto tailcall;
839 case TRunTime: /* can fail; match empty iff body does */
840 if (pred == PEnofail) return 0;
841 /* else return checkaux(sib1(tree), pred); */
842 tree = sib1(tree); goto tailcall;
843 case TSeq:
844 if (!checkaux(sib1(tree), pred)) return 0;
845 /* else return checkaux(sib2(tree), pred); */
846 tree = sib2(tree); goto tailcall;
847 case TChoice:
848 if (checkaux(sib2(tree), pred)) return 1;
849 /* else return checkaux(sib1(tree), pred); */
850 tree = sib1(tree); goto tailcall;
851 case TCapture: case TGrammar: case TRule:
852 /* return checkaux(sib1(tree), pred); */
853 tree = sib1(tree); goto tailcall;
854 case TCall: /* return checkaux(sib2(tree), pred); */
855 tree = sib2(tree); goto tailcall;
856 default: assert(0); return 0;
857 }
858 }
859
860
861 /*
862 ** number of characters to match a pattern (or -1 if variable)
863 */
864 int fixedlen (TTree *tree) {
865 int len = 0; /* to accumulate in tail calls */
866 tailcall:
867 switch (tree->tag) {
868 case TChar: case TSet: case TAny:
869 return len + 1;
870 case TFalse: case TTrue: case TNot: case TAnd: case TBehind:
871 return len;
872 case TRep: case TRunTime: case TOpenCall:
873 return -1;
874 case TCapture: case TRule: case TGrammar:
875 /* return fixedlen(sib1(tree)); */
876 tree = sib1(tree); goto tailcall;
877 case TCall: {
878 int n1 = callrecursive(tree, fixedlen, -1);
879 if (n1 < 0)
880 return -1;
881 else
882 return len + n1;
883 }
884 case TSeq: {
885 int n1 = fixedlen(sib1(tree));
886 if (n1 < 0)
887 return -1;
888 /* else return fixedlen(sib2(tree)) + len; */
889 len += n1; tree = sib2(tree); goto tailcall;
890 }
891 case TChoice: {
892 int n1 = fixedlen(sib1(tree));
893 int n2 = fixedlen(sib2(tree));
894 if (n1 != n2 || n1 < 0)
895 return -1;
896 else
897 return len + n1;
898 }
899 default: assert(0); return 0;
900 };
901 }
902
903
904 /*
905 ** Computes the 'first set' of a pattern.
906 ** The result is a conservative aproximation:
907 ** match p ax -> x (for some x) ==> a belongs to first(p)
908 ** or
909 ** a not in first(p) ==> match p ax -> fail (for all x)
910 **
911 ** The set 'follow' is the first set of what follows the
912 ** pattern (full set if nothing follows it).
913 **
914 ** The function returns 0 when this resulting set can be used for
915 ** test instructions that avoid the pattern altogether.
916 ** A non-zero return can happen for two reasons:
917 ** 1) match p '' -> '' ==> return has bit 1 set
918 ** (tests cannot be used because they would always fail for an empty input);
919 ** 2) there is a match-time capture ==> return has bit 2 set
920 ** (optimizations should not bypass match-time captures).
921 */
922 static int getfirst (TTree *tree, const Charset *follow, Charset *firstset) {
923 tailcall:
924 switch (tree->tag) {
925 case TChar: case TSet: case TAny: {
926 tocharset(tree, firstset);
927 return 0;
928 }
929 case TTrue: {
930 loopset(i, firstset->cs[i] = follow->cs[i]);
931 return 1; /* accepts the empty string */
932 }
933 case TFalse: {
934 loopset(i, firstset->cs[i] = 0);
935 return 0;
936 }
937 case TChoice: {
938 Charset csaux;
939 int e1 = getfirst(sib1(tree), follow, firstset);
940 int e2 = getfirst(sib2(tree), follow, &csaux);
941 loopset(i, firstset->cs[i] |= csaux.cs[i]);
942 return e1 | e2;
943 }
944 case TSeq: {
945 if (!nullable(sib1(tree))) {
946 /* when p1 is not nullable, p2 has nothing to contribute;
947 return getfirst(sib1(tree), fullset, firstset); */
948 tree = sib1(tree); follow = fullset; goto tailcall;
949 }
950 else { /* FIRST(p1 p2, fl) = FIRST(p1, FIRST(p2, fl)) */
951 Charset csaux;
952 int e2 = getfirst(sib2(tree), follow, &csaux);
953 int e1 = getfirst(sib1(tree), &csaux, firstset);
954 if (e1 == 0) return 0; /* 'e1' ensures that first can be used */
955 else if ((e1 | e2) & 2) /* one of the children has a matchtime? */
956 return 2; /* pattern has a matchtime capture */
957 else return e2; /* else depends on 'e2' */
958 }
959 }
960 case TRep: {
961 getfirst(sib1(tree), follow, firstset);
962 loopset(i, firstset->cs[i] |= follow->cs[i]);
963 return 1; /* accept the empty string */
964 }
965 case TCapture: case TGrammar: case TRule: {
966 /* return getfirst(sib1(tree), follow, firstset); */
967 tree = sib1(tree); goto tailcall;
968 }
969 case TRunTime: { /* function invalidates any follow info. */
970 int e = getfirst(sib1(tree), fullset, firstset);
971 if (e) return 2; /* function is not "protected"? */
972 else return 0; /* pattern inside capture ensures first can be used */
973 }
974 case TCall: {
975 /* return getfirst(sib2(tree), follow, firstset); */
976 tree = sib2(tree); goto tailcall;
977 }
978 case TAnd: {
979 int e = getfirst(sib1(tree), follow, firstset);
980 loopset(i, firstset->cs[i] &= follow->cs[i]);
981 return e;
982 }
983 case TNot: {
984 if (tocharset(sib1(tree), firstset)) {
985 cs_complement(firstset);
986 return 1;
987 }
988 /* else go through */
989 }
990 case TBehind: { /* instruction gives no new information */
991 /* call 'getfirst' only to check for math-time captures */
992 int e = getfirst(sib1(tree), follow, firstset);
993 loopset(i, firstset->cs[i] = follow->cs[i]); /* uses follow */
994 return e | 1; /* always can accept the empty string */
995 }
996 default: assert(0); return 0;
997 }
998 }
999
1000
1001 /*
1002 ** If 'headfail(tree)' true, then 'tree' can fail only depending on the
1003 ** next character of the subject.
1004 */
1005 static int headfail (TTree *tree) {
1006 tailcall:
1007 switch (tree->tag) {
1008 case TChar: case TSet: case TAny: case TFalse:
1009 return 1;
1010 case TTrue: case TRep: case TRunTime: case TNot:
1011 case TBehind:
1012 return 0;
1013 case TCapture: case TGrammar: case TRule: case TAnd:
1014 tree = sib1(tree); goto tailcall; /* return headfail(sib1(tree)); */
1015 case TCall:
1016 tree = sib2(tree); goto tailcall; /* return headfail(sib2(tree)); */
1017 case TSeq:
1018 if (!nofail(sib2(tree))) return 0;
1019 /* else return headfail(sib1(tree)); */
1020 tree = sib1(tree); goto tailcall;
1021 case TChoice:
1022 if (!headfail(sib1(tree))) return 0;
1023 /* else return headfail(sib2(tree)); */
1024 tree = sib2(tree); goto tailcall;
1025 default: assert(0); return 0;
1026 }
1027 }
1028
1029
1030 /*
1031 ** Check whether the code generation for the given tree can benefit
1032 ** from a follow set (to avoid computing the follow set when it is
1033 ** not needed)
1034 */
1035 static int needfollow (TTree *tree) {
1036 tailcall:
1037 switch (tree->tag) {
1038 case TChar: case TSet: case TAny:
1039 case TFalse: case TTrue: case TAnd: case TNot:
1040 case TRunTime: case TGrammar: case TCall: case TBehind:
1041 return 0;
1042 case TChoice: case TRep:
1043 return 1;
1044 case TCapture:
1045 tree = sib1(tree); goto tailcall;
1046 case TSeq:
1047 tree = sib2(tree); goto tailcall;
1048 default: assert(0); return 0;
1049 }
1050 }
1051
1052 /* }====================================================== */
1053
1054
1055
1056 /*
1057 ** {======================================================
1058 ** Code generation
1059 ** =======================================================
1060 */
1061
1062
1063 /*
1064 ** size of an instruction
1065 */
1066 int sizei (const Instruction *i) {
1067 switch((Opcode)i->i.code) {
1068 case ISet: case ISpan: return CHARSETINSTSIZE;
1069 case ITestSet: return CHARSETINSTSIZE + 1;
1070 case ITestChar: case ITestAny: case IChoice: case IJmp: case ICall:
1071 case IOpenCall: case ICommit: case IPartialCommit: case IBackCommit:
1072 return 2;
1073 default: return 1;
1074 }
1075 }
1076
1077
1078 /*
1079 ** state for the compiler
1080 */
1081 typedef struct CompileState {
1082 Pattern *p; /* pattern being compiled */
1083 int ncode; /* next position in p->code to be filled */
1084 lua_State *L;
1085 } CompileState;
1086
1087
1088 /*
1089 ** code generation is recursive; 'opt' indicates that the code is being
1090 ** generated as the last thing inside an optional pattern (so, if that
1091 ** code is optional too, it can reuse the 'IChoice' already in place for
1092 ** the outer pattern). 'tt' points to a previous test protecting this
1093 ** code (or NOINST). 'fl' is the follow set of the pattern.
1094 */
1095 static void codegen (CompileState *compst, TTree *tree, int opt, int tt,
1096 const Charset *fl);
1097
1098
1099 void realloccode (lua_State *L, Pattern *p, int nsize) {
1100 void *ud;
1101 lua_Alloc f = lua_getallocf(L, &ud);
1102 void *newblock = f(ud, p->code, p->codesize * sizeof(Instruction),
1103 nsize * sizeof(Instruction));
1104 if (newblock == NULL && nsize > 0)
1105 luaL_error(L, "not enough memory");
1106 p->code = (Instruction *)newblock;
1107 p->codesize = nsize;
1108 }
1109
1110
1111 static int nextinstruction (CompileState *compst) {
1112 int size = compst->p->codesize;
1113 if (compst->ncode >= size)
1114 realloccode(compst->L, compst->p, size * 2);
1115 return compst->ncode++;
1116 }
1117
1118
1119 #define getinstr(cs,i) ((cs)->p->code[i])
1120
1121
1122 static int addinstruction (CompileState *compst, Opcode op, int aux) {
1123 int i = nextinstruction(compst);
1124 getinstr(compst, i).i.code = op;
1125 getinstr(compst, i).i.aux = aux;
1126 return i;
1127 }
1128
1129
1130 /*
1131 ** Add an instruction followed by space for an offset (to be set later)
1132 */
1133 static int addoffsetinst (CompileState *compst, Opcode op) {
1134 int i = addinstruction(compst, op, 0); /* instruction */
1135 addinstruction(compst, (Opcode)0, 0); /* open space for offset */
1136 assert(op == ITestSet || sizei(&getinstr(compst, i)) == 2);
1137 return i;
1138 }
1139
1140
1141 /*
1142 ** Set the offset of an instruction
1143 */
1144 static void setoffset (CompileState *compst, int instruction, int offset) {
1145 getinstr(compst, instruction + 1).offset = offset;
1146 }
1147
1148
1149 /*
1150 ** Add a capture instruction:
1151 ** 'op' is the capture instruction; 'cap' the capture kind;
1152 ** 'key' the key into ktable; 'aux' is the optional capture offset
1153 **
1154 */
1155 static int addinstcap (CompileState *compst, Opcode op, int cap, int key,
1156 int aux) {
1157 int i = addinstruction(compst, op, joinkindoff(cap, aux));
1158 getinstr(compst, i).i.key = key;
1159 return i;
1160 }
1161
1162
1163 #define gethere(compst) ((compst)->ncode)
1164
1165 #define target(code,i) ((i) + code[i + 1].offset)
1166
1167
1168 /*
1169 ** Patch 'instruction' to jump to 'target'
1170 */
1171 static void jumptothere (CompileState *compst, int instruction, int target) {
1172 if (instruction >= 0)
1173 setoffset(compst, instruction, target - instruction);
1174 }
1175
1176
1177 /*
1178 ** Patch 'instruction' to jump to current position
1179 */
1180 static void jumptohere (CompileState *compst, int instruction) {
1181 jumptothere(compst, instruction, gethere(compst));
1182 }
1183
1184
1185 /*
1186 ** Code an IChar instruction, or IAny if there is an equivalent
1187 ** test dominating it
1188 */
1189 static void codechar (CompileState *compst, int c, int tt) {
1190 if (tt >= 0 && getinstr(compst, tt).i.code == ITestChar &&
1191 getinstr(compst, tt).i.aux == c)
1192 addinstruction(compst, IAny, 0);
1193 else
1194 addinstruction(compst, IChar, c);
1195 }
1196
1197
1198 /*
1199 ** Add a charset posfix to an instruction
1200 */
1201 static void addcharset (CompileState *compst, const byte *cs) {
1202 int p = gethere(compst);
1203 int i;
1204 for (i = 0; i < (int)CHARSETINSTSIZE - 1; i++)
1205 nextinstruction(compst); /* space for buffer */
1206 /* fill buffer with charset */
1207 loopset(j, getinstr(compst, p).buff[j] = cs[j]);
1208 }
1209
1210
1211 /*
1212 ** code a char set, optimizing unit sets for IChar, "complete"
1213 ** sets for IAny, and empty sets for IFail; also use an IAny
1214 ** when instruction is dominated by an equivalent test.
1215 */
1216 static void codecharset (CompileState *compst, const byte *cs, int tt) {
1217 int c = 0; /* (=) to avoid warnings */
1218 Opcode op = charsettype(cs, &c);
1219 switch (op) {
1220 case IChar: codechar(compst, c, tt); break;
1221 case ISet: { /* non-trivial set? */
1222 if (tt >= 0 && getinstr(compst, tt).i.code == ITestSet &&
1223 cs_equal(cs, getinstr(compst, tt + 2).buff))
1224 addinstruction(compst, IAny, 0);
1225 else {
1226 addinstruction(compst, ISet, 0);
1227 addcharset(compst, cs);
1228 }
1229 break;
1230 }
1231 default: addinstruction(compst, op, c); break;
1232 }
1233 }
1234
1235
1236 /*
1237 ** code a test set, optimizing unit sets for ITestChar, "complete"
1238 ** sets for ITestAny, and empty sets for IJmp (always fails).
1239 ** 'e' is true iff test should accept the empty string. (Test
1240 ** instructions in the current VM never accept the empty string.)
1241 */
1242 static int codetestset (CompileState *compst, Charset *cs, int e) {
1243 if (e) return NOINST; /* no test */
1244 else {
1245 int c = 0;
1246 Opcode op = charsettype(cs->cs, &c);
1247 switch (op) {
1248 case IFail: return addoffsetinst(compst, IJmp); /* always jump */
1249 case IAny: return addoffsetinst(compst, ITestAny);
1250 case IChar: {
1251 int i = addoffsetinst(compst, ITestChar);
1252 getinstr(compst, i).i.aux = c;
1253 return i;
1254 }
1255 case ISet: {
1256 int i = addoffsetinst(compst, ITestSet);
1257 addcharset(compst, cs->cs);
1258 return i;
1259 }
1260 default: assert(0); return 0;
1261 }
1262 }
1263 }
1264
1265
1266 /*
1267 ** Find the final destination of a sequence of jumps
1268 */
1269 static int finaltarget (Instruction *code, int i) {
1270 while (code[i].i.code == IJmp)
1271 i = target(code, i);
1272 return i;
1273 }
1274
1275
1276 /*
1277 ** final label (after traversing any jumps)
1278 */
1279 static int finallabel (Instruction *code, int i) {
1280 return finaltarget(code, target(code, i));
1281 }
1282
1283
1284 /*
1285 ** <behind(p)> == behind n; <p> (where n = fixedlen(p))
1286 */
1287 static void codebehind (CompileState *compst, TTree *tree) {
1288 if (tree->u.n > 0)
1289 addinstruction(compst, IBehind, tree->u.n);
1290 codegen(compst, sib1(tree), 0, NOINST, fullset);
1291 }
1292
1293
1294 /*
1295 ** Choice; optimizations:
1296 ** - when p1 is headfail or
1297 ** when first(p1) and first(p2) are disjoint, than
1298 ** a character not in first(p1) cannot go to p1, and a character
1299 ** in first(p1) cannot go to p2 (at it is not in first(p2)).
1300 ** (The optimization is not valid if p1 accepts the empty string,
1301 ** as then there is no character at all...)
1302 ** - when p2 is empty and opt is true; a IPartialCommit can reuse
1303 ** the Choice already active in the stack.
1304 */
1305 static void codechoice (CompileState *compst, TTree *p1, TTree *p2, int opt,
1306 const Charset *fl) {
1307 int emptyp2 = (p2->tag == TTrue);
1308 Charset cs1, cs2;
1309 int e1 = getfirst(p1, fullset, &cs1);
1310 if (headfail(p1) ||
1311 (!e1 && (getfirst(p2, fl, &cs2), cs_disjoint(&cs1, &cs2)))) {
1312 /* <p1 / p2> == test (fail(p1)) -> L1 ; p1 ; jmp L2; L1: p2; L2: */
1313 int test = codetestset(compst, &cs1, 0);
1314 int jmp = NOINST;
1315 codegen(compst, p1, 0, test, fl);
1316 if (!emptyp2)
1317 jmp = addoffsetinst(compst, IJmp);
1318 jumptohere(compst, test);
1319 codegen(compst, p2, opt, NOINST, fl);
1320 jumptohere(compst, jmp);
1321 }
1322 else if (opt && emptyp2) {
1323 /* p1? == IPartialCommit; p1 */
1324 jumptohere(compst, addoffsetinst(compst, IPartialCommit));
1325 codegen(compst, p1, 1, NOINST, fullset);
1326 }
1327 else {
1328 /* <p1 / p2> ==
1329 test(first(p1)) -> L1; choice L1; <p1>; commit L2; L1: <p2>; L2: */
1330 int pcommit;
1331 int test = codetestset(compst, &cs1, e1);
1332 int pchoice = addoffsetinst(compst, IChoice);
1333 codegen(compst, p1, emptyp2, test, fullset);
1334 pcommit = addoffsetinst(compst, ICommit);
1335 jumptohere(compst, pchoice);
1336 jumptohere(compst, test);
1337 codegen(compst, p2, opt, NOINST, fl);
1338 jumptohere(compst, pcommit);
1339 }
1340 }
1341
1342
1343 /*
1344 ** And predicate
1345 ** optimization: fixedlen(p) = n ==> <&p> == <p>; behind n
1346 ** (valid only when 'p' has no captures)
1347 */
1348 static void codeand (CompileState *compst, TTree *tree, int tt) {
1349 int n = fixedlen(tree);
1350 if (n >= 0 && n <= MAXBEHIND && !hascaptures(tree)) {
1351 codegen(compst, tree, 0, tt, fullset);
1352 if (n > 0)
1353 addinstruction(compst, IBehind, n);
1354 }
1355 else { /* default: Choice L1; p1; BackCommit L2; L1: Fail; L2: */
1356 int pcommit;
1357 int pchoice = addoffsetinst(compst, IChoice);
1358 codegen(compst, tree, 0, tt, fullset);
1359 pcommit = addoffsetinst(compst, IBackCommit);
1360 jumptohere(compst, pchoice);
1361 addinstruction(compst, IFail, 0);
1362 jumptohere(compst, pcommit);
1363 }
1364 }
1365
1366
1367 /*
1368 ** Captures: if pattern has fixed (and not too big) length, and it
1369 ** has no nested captures, use a single IFullCapture instruction
1370 ** after the match; otherwise, enclose the pattern with OpenCapture -
1371 ** CloseCapture.
1372 */
1373 static void codecapture (CompileState *compst, TTree *tree, int tt,
1374 const Charset *fl) {
1375 int len = fixedlen(sib1(tree));
1376 if (len >= 0 && len <= MAXOFF && !hascaptures(sib1(tree))) {
1377 codegen(compst, sib1(tree), 0, tt, fl);
1378 addinstcap(compst, IFullCapture, tree->cap, tree->key, len);
1379 }
1380 else {
1381 addinstcap(compst, IOpenCapture, tree->cap, tree->key, 0);
1382 codegen(compst, sib1(tree), 0, tt, fl);
1383 addinstcap(compst, ICloseCapture, Cclose, 0, 0);
1384 }
1385 }
1386
1387
1388 static void coderuntime (CompileState *compst, TTree *tree, int tt) {
1389 addinstcap(compst, IOpenCapture, Cgroup, tree->key, 0);
1390 codegen(compst, sib1(tree), 0, tt, fullset);
1391 addinstcap(compst, ICloseRunTime, Cclose, 0, 0);
1392 }
1393
1394
1395 /*
1396 ** Repetion; optimizations:
1397 ** When pattern is a charset, can use special instruction ISpan.
1398 ** When pattern is head fail, or if it starts with characters that
1399 ** are disjoint from what follows the repetions, a simple test
1400 ** is enough (a fail inside the repetition would backtrack to fail
1401 ** again in the following pattern, so there is no need for a choice).
1402 ** When 'opt' is true, the repetion can reuse the Choice already
1403 ** active in the stack.
1404 */
1405 static void coderep (CompileState *compst, TTree *tree, int opt,
1406 const Charset *fl) {
1407 Charset st;
1408 if (tocharset(tree, &st)) {
1409 addinstruction(compst, ISpan, 0);
1410 addcharset(compst, st.cs);
1411 }
1412 else {
1413 int e1 = getfirst(tree, fullset, &st);
1414 if (headfail(tree) || (!e1 && cs_disjoint(&st, fl))) {
1415 /* L1: test (fail(p1)) -> L2; <p>; jmp L1; L2: */
1416 int jmp;
1417 int test = codetestset(compst, &st, 0);
1418 codegen(compst, tree, 0, test, fullset);
1419 jmp = addoffsetinst(compst, IJmp);
1420 jumptohere(compst, test);
1421 jumptothere(compst, jmp, test);
1422 }
1423 else {
1424 /* test(fail(p1)) -> L2; choice L2; L1: <p>; partialcommit L1; L2: */
1425 /* or (if 'opt'): partialcommit L1; L1: <p>; partialcommit L1; */
1426 int commit, l2;
1427 int test = codetestset(compst, &st, e1);
1428 int pchoice = NOINST;
1429 if (opt)
1430 jumptohere(compst, addoffsetinst(compst, IPartialCommit));
1431 else
1432 pchoice = addoffsetinst(compst, IChoice);
1433 l2 = gethere(compst);
1434 codegen(compst, tree, 0, NOINST, fullset);
1435 commit = addoffsetinst(compst, IPartialCommit);
1436 jumptothere(compst, commit, l2);
1437 jumptohere(compst, pchoice);
1438 jumptohere(compst, test);
1439 }
1440 }
1441 }
1442
1443
1444 /*
1445 ** Not predicate; optimizations:
1446 ** In any case, if first test fails, 'not' succeeds, so it can jump to
1447 ** the end. If pattern is headfail, that is all (it cannot fail
1448 ** in other parts); this case includes 'not' of simple sets. Otherwise,
1449 ** use the default code (a choice plus a failtwice).
1450 */
1451 static void codenot (CompileState *compst, TTree *tree) {
1452 Charset st;
1453 int e = getfirst(tree, fullset, &st);
1454 int test = codetestset(compst, &st, e);
1455 if (headfail(tree)) /* test (fail(p1)) -> L1; fail; L1: */
1456 addinstruction(compst, IFail, 0);
1457 else {
1458 /* test(fail(p))-> L1; choice L1; <p>; failtwice; L1: */
1459 int pchoice = addoffsetinst(compst, IChoice);
1460 codegen(compst, tree, 0, NOINST, fullset);
1461 addinstruction(compst, IFailTwice, 0);
1462 jumptohere(compst, pchoice);
1463 }
1464 jumptohere(compst, test);
1465 }
1466
1467
1468 /*
1469 ** change open calls to calls, using list 'positions' to find
1470 ** correct offsets; also optimize tail calls
1471 */
1472 static void correctcalls (CompileState *compst, int *positions,
1473 int from, int to) {
1474 int i;
1475 Instruction *code = compst->p->code;
1476 for (i = from; i < to; i += sizei(&code[i])) {
1477 if (code[i].i.code == IOpenCall) {
1478 int n = code[i].i.key; /* rule number */
1479 int rule = positions[n]; /* rule position */
1480 assert(rule == from || code[rule - 1].i.code == IRet);
1481 if (code[finaltarget(code, i + 2)].i.code == IRet) /* call; ret ? */
1482 code[i].i.code = IJmp; /* tail call */
1483 else
1484 code[i].i.code = ICall;
1485 jumptothere(compst, i, rule); /* call jumps to respective rule */
1486 }
1487 }
1488 assert(i == to);
1489 }
1490
1491
1492 /*
1493 ** Code for a grammar:
1494 ** call L1; jmp L2; L1: rule 1; ret; rule 2; ret; ...; L2:
1495 */
1496 static void codegrammar (CompileState *compst, TTree *grammar) {
1497 int positions[MAXRULES];
1498 int rulenumber = 0;
1499 TTree *rule;
1500 int firstcall = addoffsetinst(compst, ICall); /* call initial rule */
1501 int jumptoend = addoffsetinst(compst, IJmp); /* jump to the end */
1502 int start = gethere(compst); /* here starts the initial rule */
1503 jumptohere(compst, firstcall);
1504 for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
1505 positions[rulenumber++] = gethere(compst); /* save rule position */
1506 codegen(compst, sib1(rule), 0, NOINST, fullset); /* code rule */
1507 addinstruction(compst, IRet, 0);
1508 }
1509 assert(rule->tag == TTrue);
1510 jumptohere(compst, jumptoend);
1511 correctcalls(compst, positions, start, gethere(compst));
1512 }
1513
1514
1515 static void codecall (CompileState *compst, TTree *call) {
1516 int c = addoffsetinst(compst, IOpenCall); /* to be corrected later */
1517 getinstr(compst, c).i.key = sib2(call)->cap; /* rule number */
1518 assert(sib2(call)->tag == TRule);
1519 }
1520
1521
1522 /*
1523 ** Code first child of a sequence
1524 ** (second child is called in-place to allow tail call)
1525 ** Return 'tt' for second child
1526 */
1527 static int codeseq1 (CompileState *compst, TTree *p1, TTree *p2,
1528 int tt, const Charset *fl) {
1529 if (needfollow(p1)) {
1530 Charset fl1;
1531 getfirst(p2, fl, &fl1); /* p1 follow is p2 first */
1532 codegen(compst, p1, 0, tt, &fl1);
1533 }
1534 else /* use 'fullset' as follow */
1535 codegen(compst, p1, 0, tt, fullset);
1536 if (fixedlen(p1) != 0) /* can 'p1' consume anything? */
1537 return NOINST; /* invalidate test */
1538 else return tt; /* else 'tt' still protects sib2 */
1539 }
1540
1541
1542 /*
1543 ** Main code-generation function: dispatch to auxiliar functions
1544 ** according to kind of tree. ('needfollow' should return true
1545 ** only for consructions that use 'fl'.)
1546 */
1547 static void codegen (CompileState *compst, TTree *tree, int opt, int tt,
1548 const Charset *fl) {
1549 tailcall:
1550 switch (tree->tag) {
1551 case TChar: codechar(compst, tree->u.n, tt); break;
1552 case TAny: addinstruction(compst, IAny, 0); break;
1553 case TSet: codecharset(compst, treebuffer(tree), tt); break;
1554 case TTrue: break;
1555 case TFalse: addinstruction(compst, IFail, 0); break;
1556 case TChoice: codechoice(compst, sib1(tree), sib2(tree), opt, fl); break;
1557 case TRep: coderep(compst, sib1(tree), opt, fl); break;
1558 case TBehind: codebehind(compst, tree); break;
1559 case TNot: codenot(compst, sib1(tree)); break;
1560 case TAnd: codeand(compst, sib1(tree), tt); break;
1561 case TCapture: codecapture(compst, tree, tt, fl); break;
1562 case TRunTime: coderuntime(compst, tree, tt); break;
1563 case TGrammar: codegrammar(compst, tree); break;
1564 case TCall: codecall(compst, tree); break;
1565 case TSeq: {
1566 tt = codeseq1(compst, sib1(tree), sib2(tree), tt, fl); /* code 'p1' */
1567 /* codegen(compst, p2, opt, tt, fl); */
1568 tree = sib2(tree); goto tailcall;
1569 }
1570 default: assert(0);
1571 }
1572 }
1573
1574
1575 /*
1576 ** Optimize jumps and other jump-like instructions.
1577 ** * Update labels of instructions with labels to their final
1578 ** destinations (e.g., choice L1; ... L1: jmp L2: becomes
1579 ** choice L2)
1580 ** * Jumps to other instructions that do jumps become those
1581 ** instructions (e.g., jump to return becomes a return; jump
1582 ** to commit becomes a commit)
1583 */
1584 static void peephole (CompileState *compst) {
1585 Instruction *code = compst->p->code;
1586 int i;
1587 for (i = 0; i < compst->ncode; i += sizei(&code[i])) {
1588 redo:
1589 switch (code[i].i.code) {
1590 case IChoice: case ICall: case ICommit: case IPartialCommit:
1591 case IBackCommit: case ITestChar: case ITestSet:
1592 case ITestAny: { /* instructions with labels */
1593 jumptothere(compst, i, finallabel(code, i)); /* optimize label */
1594 break;
1595 }
1596 case IJmp: {
1597 int ft = finaltarget(code, i);
1598 switch (code[ft].i.code) { /* jumping to what? */
1599 case IRet: case IFail: case IFailTwice:
1600 case IEnd: { /* instructions with unconditional implicit jumps */
1601 code[i] = code[ft]; /* jump becomes that instruction */
1602 code[i + 1].i.code = IAny; /* 'no-op' for target position */
1603 break;
1604 }
1605 case ICommit: case IPartialCommit:
1606 case IBackCommit: { /* inst. with unconditional explicit jumps */
1607 int fft = finallabel(code, ft);
1608 code[i] = code[ft]; /* jump becomes that instruction... */
1609 jumptothere(compst, i, fft); /* but must correct its offset */
1610 goto redo; /* reoptimize its label */
1611 }
1612 default: {
1613 jumptothere(compst, i, ft); /* optimize label */
1614 break;
1615 }
1616 }
1617 break;
1618 }
1619 default: break;
1620 }
1621 }
1622 assert(code[i - 1].i.code == IEnd);
1623 }
1624
1625
1626 /*
1627 ** Compile a pattern
1628 */
1629 Instruction *compile (lua_State *L, Pattern *p) {
1630 CompileState compst;
1631 compst.p = p; compst.ncode = 0; compst.L = L;
1632 realloccode(L, p, 2); /* minimum initial size */
1633 codegen(&compst, p->tree, 0, NOINST, fullset);
1634 addinstruction(&compst, IEnd, 0);
1635 realloccode(L, p, compst.ncode); /* set final size */
1636 peephole(&compst);
1637 return p->code;
1638 }
1639
1640
1641 /* }====================================================== */
1642
1643 /*
1644 ** $Id: lpcap.c,v 1.6 2015/06/15 16:09:57 roberto Exp $
1645 ** Copyright 2007, Lua.org & PUC-Rio (see 'lpeg.html' for license)
1646 */
1647
1648 /* #include "lua.h" */
1649 /* #include "lauxlib.h" */
1650
1651 /* #include "lpcap.h" */
1652 /* #include "lptypes.h" */
1653
1654
1655 #define captype(cap) ((cap)->kind)
1656
1657 #define isclosecap(cap) (captype(cap) == Cclose)
1658
1659 #define closeaddr(c) ((c)->s + (c)->siz - 1)
1660
1661 #define isfullcap(cap) ((cap)->siz != 0)
1662
1663 #define getfromktable(cs,v) lua_rawgeti((cs)->L, ktableidx((cs)->ptop), v)
1664
1665 #define pushluaval(cs) getfromktable(cs, (cs)->cap->idx)
1666
1667
1668
1669 /*
1670 ** Put at the cache for Lua values the value indexed by 'v' in ktable
1671 ** of the running pattern (if it is not there yet); returns its index.
1672 */
1673 static int updatecache (CapState *cs, int v) {
1674 int idx = cs->ptop + 1; /* stack index of cache for Lua values */
1675 if (v != cs->valuecached) { /* not there? */
1676 getfromktable(cs, v); /* get value from 'ktable' */
1677 lua_replace(cs->L, idx); /* put it at reserved stack position */
1678 cs->valuecached = v; /* keep track of what is there */
1679 }
1680 return idx;
1681 }
1682
1683
1684 static int pushcapture (CapState *cs);
1685
1686
1687 /*
1688 ** Goes back in a list of captures looking for an open capture
1689 ** corresponding to a close
1690 */
1691 static Capture *findopen (Capture *cap) {
1692 int n = 0; /* number of closes waiting an open */
1693 for (;;) {
1694 cap--;
1695 if (isclosecap(cap)) n++; /* one more open to skip */
1696 else if (!isfullcap(cap))
1697 if (n-- == 0) return cap;
1698 }
1699 }
1700
1701
1702 /*
1703 ** Go to the next capture
1704 */
1705 static void nextcap (CapState *cs) {
1706 Capture *cap = cs->cap;
1707 if (!isfullcap(cap)) { /* not a single capture? */
1708 int n = 0; /* number of opens waiting a close */
1709 for (;;) { /* look for corresponding close */
1710 cap++;
1711 if (isclosecap(cap)) {
1712 if (n-- == 0) break;
1713 }
1714 else if (!isfullcap(cap)) n++;
1715 }
1716 }
1717 cs->cap = cap + 1; /* + 1 to skip last close (or entire single capture) */
1718 }
1719
1720
1721 /*
1722 ** Push on the Lua stack all values generated by nested captures inside
1723 ** the current capture. Returns number of values pushed. 'addextra'
1724 ** makes it push the entire match after all captured values. The
1725 ** entire match is pushed also if there are no other nested values,
1726 ** so the function never returns zero.
1727 */
1728 static int pushnestedvalues (CapState *cs, int addextra) {
1729 Capture *co = cs->cap;
1730 if (isfullcap(cs->cap++)) { /* no nested captures? */
1731 lua_pushlstring(cs->L, co->s, co->siz - 1); /* push whole match */
1732 return 1; /* that is it */
1733 }
1734 else {
1735 int n = 0;
1736 while (!isclosecap(cs->cap)) /* repeat for all nested patterns */
1737 n += pushcapture(cs);
1738 if (addextra || n == 0) { /* need extra? */
1739 lua_pushlstring(cs->L, co->s, cs->cap->s - co->s); /* push whole match */
1740 n++;
1741 }
1742 cs->cap++; /* skip close entry */
1743 return n;
1744 }
1745 }
1746
1747
1748 /*
1749 ** Push only the first value generated by nested captures
1750 */
1751 static void pushonenestedvalue (CapState *cs) {
1752 int n = pushnestedvalues(cs, 0);
1753 if (n > 1)
1754 lua_pop(cs->L, n - 1); /* pop extra values */
1755 }
1756
1757
1758 /*
1759 ** Try to find a named group capture with the name given at the top of
1760 ** the stack; goes backward from 'cap'.
1761 */
1762 static Capture *findback (CapState *cs, Capture *cap) {
1763 lua_State *L = cs->L;
1764 while (cap-- > cs->ocap) { /* repeat until end of list */
1765 if (isclosecap(cap))
1766 cap = findopen(cap); /* skip nested captures */
1767 else if (!isfullcap(cap))
1768 continue; /* opening an enclosing capture: skip and get previous */
1769 if (captype(cap) == Cgroup) {
1770 getfromktable(cs, cap->idx); /* get group name */
1771 if (lp_equal(L, -2, -1)) { /* right group? */
1772 lua_pop(L, 2); /* remove reference name and group name */
1773 return cap;
1774 }
1775 else lua_pop(L, 1); /* remove group name */
1776 }
1777 }
1778 luaL_error(L, "back reference '%s' not found", lua_tostring(L, -1));
1779 return NULL; /* to avoid warnings */
1780 }
1781
1782
1783 /*
1784 ** Back-reference capture. Return number of values pushed.
1785 */
1786 static int backrefcap (CapState *cs) {
1787 int n;
1788 Capture *curr = cs->cap;
1789 pushluaval(cs); /* reference name */
1790 cs->cap = findback(cs, curr); /* find corresponding group */
1791 n = pushnestedvalues(cs, 0); /* push group's values */
1792 cs->cap = curr + 1;
1793 return n;
1794 }
1795
1796
1797 /*
1798 ** Table capture: creates a new table and populates it with nested
1799 ** captures.
1800 */
1801 static int tablecap (CapState *cs) {
1802 lua_State *L = cs->L;
1803 int n = 0;
1804 lua_newtable(L);
1805 if (isfullcap(cs->cap++))
1806 return 1; /* table is empty */
1807 while (!isclosecap(cs->cap)) {
1808 if (captype(cs->cap) == Cgroup && cs->cap->idx != 0) { /* named group? */
1809 pushluaval(cs); /* push group name */
1810 pushonenestedvalue(cs);
1811 lua_settable(L, -3);
1812 }
1813 else { /* not a named group */
1814 int i;
1815 int k = pushcapture(cs);
1816 for (i = k; i > 0; i--) /* store all values into table */
1817 lua_rawseti(L, -(i + 1), n + i);
1818 n += k;
1819 }
1820 }
1821 cs->cap++; /* skip close entry */
1822 return 1; /* number of values pushed (only the table) */
1823 }
1824
1825
1826 /*
1827 ** Table-query capture
1828 */
1829 static int querycap (CapState *cs) {
1830 int idx = cs->cap->idx;
1831 pushonenestedvalue(cs); /* get nested capture */
1832 lua_gettable(cs->L, updatecache(cs, idx)); /* query cap. value at table */
1833 if (!lua_isnil(cs->L, -1))
1834 return 1;
1835 else { /* no value */
1836 lua_pop(cs->L, 1); /* remove nil */
1837 return 0;
1838 }
1839 }
1840
1841
1842 /*
1843 ** Fold capture
1844 */
1845 static int foldcap (CapState *cs) {
1846 int n;
1847 lua_State *L = cs->L;
1848 int idx = cs->cap->idx;
1849 if (isfullcap(cs->cap++) || /* no nested captures? */
1850 isclosecap(cs->cap) || /* no nested captures (large subject)? */
1851 (n = pushcapture(cs)) == 0) /* nested captures with no values? */
1852 return luaL_error(L, "no initial value for fold capture");
1853 if (n > 1)
1854 lua_pop(L, n - 1); /* leave only one result for accumulator */
1855 while (!isclosecap(cs->cap)) {
1856 lua_pushvalue(L, updatecache(cs, idx)); /* get folding function */
1857 lua_insert(L, -2); /* put it before accumulator */
1858 n = pushcapture(cs); /* get next capture's values */
1859 lua_call(L, n + 1, 1); /* call folding function */
1860 }
1861 cs->cap++; /* skip close entry */
1862 return 1; /* only accumulator left on the stack */
1863 }
1864
1865
1866 /*
1867 ** Function capture
1868 */
1869 static int functioncap (CapState *cs) {
1870 int n;
1871 int top = lua_gettop(cs->L);
1872 pushluaval(cs); /* push function */
1873 n = pushnestedvalues(cs, 0); /* push nested captures */
1874 lua_call(cs->L, n, LUA_MULTRET); /* call function */
1875 return lua_gettop(cs->L) - top; /* return function's results */
1876 }
1877
1878
1879 /*
1880 ** Select capture
1881 */
1882 static int numcap (CapState *cs) {
1883 int idx = cs->cap->idx; /* value to select */
1884 if (idx == 0) { /* no values? */
1885 nextcap(cs); /* skip entire capture */
1886 return 0; /* no value produced */
1887 }
1888 else {
1889 int n = pushnestedvalues(cs, 0);
1890 if (n < idx) /* invalid index? */
1891 return luaL_error(cs->L, "no capture '%d'", idx);
1892 else {
1893 lua_pushvalue(cs->L, -(n - idx + 1)); /* get selected capture */
1894 lua_replace(cs->L, -(n + 1)); /* put it in place of 1st capture */
1895 lua_pop(cs->L, n - 1); /* remove other captures */
1896 return 1;
1897 }
1898 }
1899 }
1900
1901
1902 /*
1903 ** Return the stack index of the first runtime capture in the given
1904 ** list of captures (or zero if no runtime captures)
1905 */
1906 int finddyncap (Capture *cap, Capture *last) {
1907 for (; cap < last; cap++) {
1908 if (cap->kind == Cruntime)
1909 return cap->idx; /* stack position of first capture */
1910 }
1911 return 0; /* no dynamic captures in this segment */
1912 }
1913
1914
1915 /*
1916 ** Calls a runtime capture. Returns number of captures removed by
1917 ** the call, including the initial Cgroup. (Captures to be added are
1918 ** on the Lua stack.)
1919 */
1920 int runtimecap (CapState *cs, Capture *close, const char *s, int *rem) {
1921 int n, id;
1922 lua_State *L = cs->L;
1923 int otop = lua_gettop(L);
1924 Capture *open = findopen(close);
1925 assert(captype(open) == Cgroup);
1926 id = finddyncap(open, close); /* get first dynamic capture argument */
1927 close->kind = Cclose; /* closes the group */
1928 close->s = s;
1929 cs->cap = open; cs->valuecached = 0; /* prepare capture state */
1930 luaL_checkstack(L, 4, "too many runtime captures");
1931 pushluaval(cs); /* push function to be called */
1932 lua_pushvalue(L, SUBJIDX); /* push original subject */
1933 lua_pushinteger(L, s - cs->s + 1); /* push current position */
1934 n = pushnestedvalues(cs, 0); /* push nested captures */
1935 lua_call(L, n + 2, LUA_MULTRET); /* call dynamic function */
1936 if (id > 0) { /* are there old dynamic captures to be removed? */
1937 int i;
1938 for (i = id; i <= otop; i++)
1939 lua_remove(L, id); /* remove old dynamic captures */
1940 *rem = otop - id + 1; /* total number of dynamic captures removed */
1941 }
1942 else
1943 *rem = 0; /* no dynamic captures removed */
1944 return close - open; /* number of captures of all kinds removed */
1945 }
1946
1947
1948 /*
1949 ** Auxiliary structure for substitution and string captures: keep
1950 ** information about nested captures for future use, avoiding to push
1951 ** string results into Lua
1952 */
1953 typedef struct StrAux {
1954 int isstring; /* whether capture is a string */
1955 union {
1956 Capture *cp; /* if not a string, respective capture */
1957 struct { /* if it is a string... */
1958 const char *s; /* ... starts here */
1959 const char *e; /* ... ends here */
1960 } s;
1961 } u;
1962 } StrAux;
1963
1964 #define MAXSTRCAPS 10
1965
1966 /*
1967 ** Collect values from current capture into array 'cps'. Current
1968 ** capture must be Cstring (first call) or Csimple (recursive calls).
1969 ** (In first call, fills %0 with whole match for Cstring.)
1970 ** Returns number of elements in the array that were filled.
1971 */
1972 static int getstrcaps (CapState *cs, StrAux *cps, int n) {
1973 int k = n++;
1974 cps[k].isstring = 1; /* get string value */
1975 cps[k].u.s.s = cs->cap->s; /* starts here */
1976 if (!isfullcap(cs->cap++)) { /* nested captures? */
1977 while (!isclosecap(cs->cap)) { /* traverse them */
1978 if (n >= MAXSTRCAPS) /* too many captures? */
1979 nextcap(cs); /* skip extra captures (will not need them) */
1980 else if (captype(cs->cap) == Csimple) /* string? */
1981 n = getstrcaps(cs, cps, n); /* put info. into array */
1982 else {
1983 cps[n].isstring = 0; /* not a string */
1984 cps[n].u.cp = cs->cap; /* keep original capture */
1985 nextcap(cs);
1986 n++;
1987 }
1988 }
1989 cs->cap++; /* skip close */
1990 }
1991 cps[k].u.s.e = closeaddr(cs->cap - 1); /* ends here */
1992 return n;
1993 }
1994
1995
1996 /*
1997 ** add next capture value (which should be a string) to buffer 'b'
1998 */
1999 static int addonestring (luaL_Buffer *b, CapState *cs, const char *what);
2000
2001
2002 /*
2003 ** String capture: add result to buffer 'b' (instead of pushing
2004 ** it into the stack)
2005 */
2006 static void stringcap (luaL_Buffer *b, CapState *cs) {
2007 StrAux cps[MAXSTRCAPS];
2008 int n;
2009 size_t len, i;
2010 const char *fmt; /* format string */
2011 fmt = lua_tolstring(cs->L, updatecache(cs, cs->cap->idx), &len);
2012 n = getstrcaps(cs, cps, 0) - 1; /* collect nested captures */
2013 for (i = 0; i < len; i++) { /* traverse them */
2014 if (fmt[i] != '%') /* not an escape? */
2015 luaL_addchar(b, fmt[i]); /* add it to buffer */
2016 else if (fmt[++i] < '0' || fmt[i] > '9') /* not followed by a digit? */
2017 luaL_addchar(b, fmt[i]); /* add to buffer */
2018 else {
2019 int l = fmt[i] - '0'; /* capture index */
2020 if (l > n)
2021 luaL_error(cs->L, "invalid capture index (%d)", l);
2022 else if (cps[l].isstring)
2023 luaL_addlstring(b, cps[l].u.s.s, cps[l].u.s.e - cps[l].u.s.s);
2024 else {
2025 Capture *curr = cs->cap;
2026 cs->cap = cps[l].u.cp; /* go back to evaluate that nested capture */
2027 if (!addonestring(b, cs, "capture"))
2028 luaL_error(cs->L, "no values in capture index %d", l);
2029 cs->cap = curr; /* continue from where it stopped */
2030 }
2031 }
2032 }
2033 }
2034
2035
2036 /*
2037 ** Substitution capture: add result to buffer 'b'
2038 */
2039 static void substcap (luaL_Buffer *b, CapState *cs) {
2040 const char *curr = cs->cap->s;
2041 if (isfullcap(cs->cap)) /* no nested captures? */
2042 luaL_addlstring(b, curr, cs->cap->siz - 1); /* keep original text */
2043 else {
2044 cs->cap++; /* skip open entry */
2045 while (!isclosecap(cs->cap)) { /* traverse nested captures */
2046 const char *next = cs->cap->s;
2047 luaL_addlstring(b, curr, next - curr); /* add text up to capture */
2048 if (addonestring(b, cs, "replacement"))
2049 curr = closeaddr(cs->cap - 1); /* continue after match */
2050 else /* no capture value */
2051 curr = next; /* keep original text in final result */
2052 }
2053 luaL_addlstring(b, curr, cs->cap->s - curr); /* add last piece of text */
2054 }
2055 cs->cap++; /* go to next capture */
2056 }
2057
2058
2059 /*
2060 ** Evaluates a capture and adds its first value to buffer 'b'; returns
2061 ** whether there was a value
2062 */
2063 static int addonestring (luaL_Buffer *b, CapState *cs, const char *what) {
2064 switch (captype(cs->cap)) {
2065 case Cstring:
2066 stringcap(b, cs); /* add capture directly to buffer */
2067 return 1;
2068 case Csubst:
2069 substcap(b, cs); /* add capture directly to buffer */
2070 return 1;
2071 default: {
2072 lua_State *L = cs->L;
2073 int n = pushcapture(cs);
2074 if (n > 0) {
2075 if (n > 1) lua_pop(L, n - 1); /* only one result */
2076 if (!lua_isstring(L, -1))
2077 luaL_error(L, "invalid %s value (a %s)", what, luaL_typename(L, -1));
2078 luaL_addvalue(b);
2079 }
2080 return n;
2081 }
2082 }
2083 }
2084
2085
2086 /*
2087 ** Push all values of the current capture into the stack; returns
2088 ** number of values pushed
2089 */
2090 static int pushcapture (CapState *cs) {
2091 lua_State *L = cs->L;
2092 luaL_checkstack(L, 4, "too many captures");
2093 switch (captype(cs->cap)) {
2094 case Cposition: {
2095 lua_pushinteger(L, cs->cap->s - cs->s + 1);
2096 cs->cap++;
2097 return 1;
2098 }
2099 case Cconst: {
2100 pushluaval(cs);
2101 cs->cap++;
2102 return 1;
2103 }
2104 case Carg: {
2105 int arg = (cs->cap++)->idx;
2106 if (arg + FIXEDARGS > cs->ptop)
2107 return luaL_error(L, "reference to absent extra argument #%d", arg);
2108 lua_pushvalue(L, arg + FIXEDARGS);
2109 return 1;
2110 }
2111 case Csimple: {
2112 int k = pushnestedvalues(cs, 1);
2113 lua_insert(L, -k); /* make whole match be first result */
2114 return k;
2115 }
2116 case Cruntime: {
2117 lua_pushvalue(L, (cs->cap++)->idx); /* value is in the stack */
2118 return 1;
2119 }
2120 case Cstring: {
2121 luaL_Buffer b;
2122 luaL_buffinit(L, &b);
2123 stringcap(&b, cs);
2124 luaL_pushresult(&b);
2125 return 1;
2126 }
2127 case Csubst: {
2128 luaL_Buffer b;
2129 luaL_buffinit(L, &b);
2130 substcap(&b, cs);
2131 luaL_pushresult(&b);
2132 return 1;
2133 }
2134 case Cgroup: {
2135 if (cs->cap->idx == 0) /* anonymous group? */
2136 return pushnestedvalues(cs, 0); /* add all nested values */
2137 else { /* named group: add no values */
2138 nextcap(cs); /* skip capture */
2139 return 0;
2140 }
2141 }
2142 case Cbackref: return backrefcap(cs);
2143 case Ctable: return tablecap(cs);
2144 case Cfunction: return functioncap(cs);
2145 case Cnum: return numcap(cs);
2146 case Cquery: return querycap(cs);
2147 case Cfold: return foldcap(cs);
2148 default: assert(0); return 0;
2149 }
2150 }
2151
2152
2153 /*
2154 ** Prepare a CapState structure and traverse the entire list of
2155 ** captures in the stack pushing its results. 's' is the subject
2156 ** string, 'r' is the final position of the match, and 'ptop'
2157 ** the index in the stack where some useful values were pushed.
2158 ** Returns the number of results pushed. (If the list produces no
2159 ** results, push the final position of the match.)
2160 */
2161 int getcaptures (lua_State *L, const char *s, const char *r, int ptop) {
2162 Capture *capture = (Capture *)lua_touserdata(L, caplistidx(ptop));
2163 int n = 0;
2164 if (!isclosecap(capture)) { /* is there any capture? */
2165 CapState cs;
2166 cs.ocap = cs.cap = capture; cs.L = L;
2167 cs.s = s; cs.valuecached = 0; cs.ptop = ptop;
2168 do { /* collect their values */
2169 n += pushcapture(&cs);
2170 } while (!isclosecap(cs.cap));
2171 }
2172 if (n == 0) { /* no capture values? */
2173 lua_pushinteger(L, r - s + 1); /* return only end position */
2174 n = 1;
2175 }
2176 return n;
2177 }
2178
2179
2180 /*
2181 ** $Id: lptree.c,v 1.22 2016/09/13 18:10:22 roberto Exp $
2182 ** Copyright 2013, Lua.org & PUC-Rio (see 'lpeg.html' for license)
2183 */
2184
2185 /* #include <ctype.h> */
2186 /* #include <limits.h> */
2187 /* #include <string.h> */
2188
2189
2190 /* #include "lua.h" */
2191 /* #include "lauxlib.h" */
2192
2193 /* #include "lptypes.h" */
2194 /* #include "lpcap.h" */
2195 /* #include "lpcode.h" */
2196 /* #include "lpprint.h" */
2197 /* #include "lptree.h" */
2198
2199
2200 /* number of siblings for each tree */
2201 const byte numsiblings[] = {
2202 0, 0, 0, /* char, set, any */
2203 0, 0, /* true, false */
2204 1, /* rep */
2205 2, 2, /* seq, choice */
2206 1, 1, /* not, and */
2207 0, 0, 2, 1, /* call, opencall, rule, grammar */
2208 1, /* behind */
2209 1, 1 /* capture, runtime capture */
2210 };
2211
2212
2213 static TTree *newgrammar (lua_State *L, int arg);
2214
2215
2216 /*
2217 ** returns a reasonable name for value at index 'idx' on the stack
2218 */
2219 static const char *val2str (lua_State *L, int idx) {
2220 const char *k = lua_tostring(L, idx);
2221 if (k != NULL)
2222 return lua_pushfstring(L, "%s", k);
2223 else
2224 return lua_pushfstring(L, "(a %s)", luaL_typename(L, idx));
2225 }
2226
2227
2228 /*
2229 ** Fix a TOpenCall into a TCall node, using table 'postable' to
2230 ** translate a key to its rule address in the tree. Raises an
2231 ** error if key does not exist.
2232 */
2233 static void fixonecall (lua_State *L, int postable, TTree *g, TTree *t) {
2234 int n;
2235 lua_rawgeti(L, -1, t->key); /* get rule's name */
2236 lua_gettable(L, postable); /* query name in position table */
2237 n = lua_tonumber(L, -1); /* get (absolute) position */
2238 lua_pop(L, 1); /* remove position */
2239 if (n == 0) { /* no position? */
2240 lua_rawgeti(L, -1, t->key); /* get rule's name again */
2241 luaL_error(L, "rule '%s' undefined in given grammar", val2str(L, -1));
2242 }
2243 t->tag = TCall;
2244 t->u.ps = n - (t - g); /* position relative to node */
2245 assert(sib2(t)->tag == TRule);
2246 sib2(t)->key = t->key; /* fix rule's key */
2247 }
2248
2249
2250 /*
2251 ** Transform left associative constructions into right
2252 ** associative ones, for sequence and choice; that is:
2253 ** (t11 + t12) + t2 => t11 + (t12 + t2)
2254 ** (t11 * t12) * t2 => t11 * (t12 * t2)
2255 ** (that is, Op (Op t11 t12) t2 => Op t11 (Op t12 t2))
2256 */
2257 static void correctassociativity (TTree *tree) {
2258 TTree *t1 = sib1(tree);
2259 assert(tree->tag == TChoice || tree->tag == TSeq);
2260 while (t1->tag == tree->tag) {
2261 int n1size = tree->u.ps - 1; /* t1 == Op t11 t12 */
2262 int n11size = t1->u.ps - 1;
2263 int n12size = n1size - n11size - 1;
2264 memmove(sib1(tree), sib1(t1), n11size * sizeof(TTree)); /* move t11 */
2265 tree->u.ps = n11size + 1;
2266 sib2(tree)->tag = tree->tag;
2267 sib2(tree)->u.ps = n12size + 1;
2268 }
2269 }
2270
2271
2272 /*
2273 ** Make final adjustments in a tree. Fix open calls in tree 't',
2274 ** making them refer to their respective rules or raising appropriate
2275 ** errors (if not inside a grammar). Correct associativity of associative
2276 ** constructions (making them right associative). Assume that tree's
2277 ** ktable is at the top of the stack (for error messages).
2278 */
2279 static void finalfix (lua_State *L, int postable, TTree *g, TTree *t) {
2280 tailcall:
2281 switch (t->tag) {
2282 case TGrammar: /* subgrammars were already fixed */
2283 return;
2284 case TOpenCall: {
2285 if (g != NULL) /* inside a grammar? */
2286 fixonecall(L, postable, g, t);
2287 else { /* open call outside grammar */
2288 lua_rawgeti(L, -1, t->key);
2289 luaL_error(L, "rule '%s' used outside a grammar", val2str(L, -1));
2290 }
2291 break;
2292 }
2293 case TSeq: case TChoice:
2294 correctassociativity(t);
2295 break;
2296 }
2297 switch (numsiblings[t->tag]) {
2298 case 1: /* finalfix(L, postable, g, sib1(t)); */
2299 t = sib1(t); goto tailcall;
2300 case 2:
2301 finalfix(L, postable, g, sib1(t));
2302 t = sib2(t); goto tailcall; /* finalfix(L, postable, g, sib2(t)); */
2303 default: assert(numsiblings[t->tag] == 0); break;
2304 }
2305 }
2306
2307
2308
2309 /*
2310 ** {===================================================================
2311 ** KTable manipulation
2312 **
2313 ** - The ktable of a pattern 'p' can be shared by other patterns that
2314 ** contain 'p' and no other constants. Because of this sharing, we
2315 ** should not add elements to a 'ktable' unless it was freshly created
2316 ** for the new pattern.
2317 **
2318 ** - The maximum index in a ktable is USHRT_MAX, because trees and
2319 ** patterns use unsigned shorts to store those indices.
2320 ** ====================================================================
2321 */
2322
2323 /*
2324 ** Create a new 'ktable' to the pattern at the top of the stack.
2325 */
2326 static void newktable (lua_State *L, int n) {
2327 lua_createtable(L, n, 0); /* create a fresh table */
2328 lua_setuservalue(L, -2); /* set it as 'ktable' for pattern */
2329 }
2330
2331
2332 /*
2333 ** Add element 'idx' to 'ktable' of pattern at the top of the stack;
2334 ** Return index of new element.
2335 ** If new element is nil, does not add it to table (as it would be
2336 ** useless) and returns 0, as ktable[0] is always nil.
2337 */
2338 static int addtoktable (lua_State *L, int idx) {
2339 if (lua_isnil(L, idx)) /* nil value? */
2340 return 0;
2341 else {
2342 int n;
2343 lua_getuservalue(L, -1); /* get ktable from pattern */
2344 n = lua_rawlen(L, -1);
2345 if (n >= USHRT_MAX)
2346 luaL_error(L, "too many Lua values in pattern");
2347 lua_pushvalue(L, idx); /* element to be added */
2348 lua_rawseti(L, -2, ++n);
2349 lua_pop(L, 1); /* remove 'ktable' */
2350 return n;
2351 }
2352 }
2353
2354
2355 /*
2356 ** Return the number of elements in the ktable at 'idx'.
2357 ** In Lua 5.2/5.3, default "environment" for patterns is nil, not
2358 ** a table. Treat it as an empty table. In Lua 5.1, assumes that
2359 ** the environment has no numeric indices (len == 0)
2360 */
2361 static int ktablelen (lua_State *L, int idx) {
2362 if (!lua_istable(L, idx)) return 0;
2363 else return lua_rawlen(L, idx);
2364 }
2365
2366
2367 /*
2368 ** Concatentate the contents of table 'idx1' into table 'idx2'.
2369 ** (Assume that both indices are negative.)
2370 ** Return the original length of table 'idx2' (or 0, if no
2371 ** element was added, as there is no need to correct any index).
2372 */
2373 static int concattable (lua_State *L, int idx1, int idx2) {
2374 int i;
2375 int n1 = ktablelen(L, idx1);
2376 int n2 = ktablelen(L, idx2);
2377 if (n1 + n2 > USHRT_MAX)
2378 luaL_error(L, "too many Lua values in pattern");
2379 if (n1 == 0) return 0; /* nothing to correct */
2380 for (i = 1; i <= n1; i++) {
2381 lua_rawgeti(L, idx1, i);
2382 lua_rawseti(L, idx2 - 1, n2 + i); /* correct 'idx2' */
2383 }
2384 return n2;
2385 }
2386
2387
2388 /*
2389 ** When joining 'ktables', constants from one of the subpatterns must
2390 ** be renumbered; 'correctkeys' corrects their indices (adding 'n'
2391 ** to each of them)
2392 */
2393 static void correctkeys (TTree *tree, int n) {
2394 if (n == 0) return; /* no correction? */
2395 tailcall:
2396 switch (tree->tag) {
2397 case TOpenCall: case TCall: case TRunTime: case TRule: {
2398 if (tree->key > 0)
2399 tree->key += n;
2400 break;
2401 }
2402 case TCapture: {
2403 if (tree->key > 0 && tree->cap != Carg && tree->cap != Cnum)
2404 tree->key += n;
2405 break;
2406 }
2407 default: break;
2408 }
2409 switch (numsiblings[tree->tag]) {
2410 case 1: /* correctkeys(sib1(tree), n); */
2411 tree = sib1(tree); goto tailcall;
2412 case 2:
2413 correctkeys(sib1(tree), n);
2414 tree = sib2(tree); goto tailcall; /* correctkeys(sib2(tree), n); */
2415 default: assert(numsiblings[tree->tag] == 0); break;
2416 }
2417 }
2418
2419
2420 /*
2421 ** Join the ktables from p1 and p2 the ktable for the new pattern at the
2422 ** top of the stack, reusing them when possible.
2423 */
2424 static void joinktables (lua_State *L, int p1, TTree *t2, int p2) {
2425 int n1, n2;
2426 lua_getuservalue(L, p1); /* get ktables */
2427 lua_getuservalue(L, p2);
2428 n1 = ktablelen(L, -2);
2429 n2 = ktablelen(L, -1);
2430 if (n1 == 0 && n2 == 0) /* are both tables empty? */
2431 lua_pop(L, 2); /* nothing to be done; pop tables */
2432 else if (n2 == 0 || lp_equal(L, -2, -1)) { /* 2nd table empty or equal? */
2433 lua_pop(L, 1); /* pop 2nd table */
2434 lua_setuservalue(L, -2); /* set 1st ktable into new pattern */
2435 }
2436 else if (n1 == 0) { /* first table is empty? */
2437 lua_setuservalue(L, -3); /* set 2nd table into new pattern */
2438 lua_pop(L, 1); /* pop 1st table */
2439 }
2440 else {
2441 lua_createtable(L, n1 + n2, 0); /* create ktable for new pattern */
2442 /* stack: new p; ktable p1; ktable p2; new ktable */
2443 concattable(L, -3, -1); /* from p1 into new ktable */
2444 concattable(L, -2, -1); /* from p2 into new ktable */
2445 lua_setuservalue(L, -4); /* new ktable becomes 'p' environment */
2446 lua_pop(L, 2); /* pop other ktables */
2447 correctkeys(t2, n1); /* correction for indices from p2 */
2448 }
2449 }
2450
2451
2452 /*
2453 ** copy 'ktable' of element 'idx' to new tree (on top of stack)
2454 */
2455 static void copyktable (lua_State *L, int idx) {
2456 lua_getuservalue(L, idx);
2457 lua_setuservalue(L, -2);
2458 }
2459
2460
2461 /*
2462 ** merge 'ktable' from 'stree' at stack index 'idx' into 'ktable'
2463 ** from tree at the top of the stack, and correct corresponding
2464 ** tree.
2465 */
2466 static void mergektable (lua_State *L, int idx, TTree *stree) {
2467 int n;
2468 lua_getuservalue(L, -1); /* get ktables */
2469 lua_getuservalue(L, idx);
2470 n = concattable(L, -1, -2);
2471 lua_pop(L, 2); /* remove both ktables */
2472 correctkeys(stree, n);
2473 }
2474
2475
2476 /*
2477 ** Create a new 'ktable' to the pattern at the top of the stack, adding
2478 ** all elements from pattern 'p' (if not 0) plus element 'idx' to it.
2479 ** Return index of new element.
2480 */
2481 static int addtonewktable (lua_State *L, int p, int idx) {
2482 newktable(L, 1);
2483 if (p)
2484 mergektable(L, p, NULL);
2485 return addtoktable(L, idx);
2486 }
2487
2488 /* }====================================================== */
2489
2490
2491 /*
2492 ** {======================================================
2493 ** Tree generation
2494 ** =======================================================
2495 */
2496
2497 /*
2498 ** In 5.2, could use 'luaL_testudata'...
2499 */
2500 static int testpattern (lua_State *L, int idx) {
2501 if (lua_touserdata(L, idx)) { /* value is a userdata? */
2502 if (lua_getmetatable(L, idx)) { /* does it have a metatable? */
2503 luaL_getmetatable(L, PATTERN_T);
2504 if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
2505 lua_pop(L, 2); /* remove both metatables */
2506 return 1;
2507 }
2508 }
2509 }
2510 return 0;
2511 }
2512
2513
2514 static Pattern *getpattern (lua_State *L, int idx) {
2515 return (Pattern *)luaL_checkudata(L, idx, PATTERN_T);
2516 }
2517
2518
2519 static int getsize (lua_State *L, int idx) {
2520 return (lua_rawlen(L, idx) - sizeof(Pattern)) / sizeof(TTree) + 1;
2521 }
2522
2523
2524 static TTree *gettree (lua_State *L, int idx, int *len) {
2525 Pattern *p = getpattern(L, idx);
2526 if (len)
2527 *len = getsize(L, idx);
2528 return p->tree;
2529 }
2530
2531
2532 /*
2533 ** create a pattern. Set its uservalue (the 'ktable') equal to its
2534 ** metatable. (It could be any empty sequence; the metatable is at
2535 ** hand here, so we use it.)
2536 */
2537 static TTree *newtree (lua_State *L, int len) {
2538 size_t size = (len - 1) * sizeof(TTree) + sizeof(Pattern);
2539 Pattern *p = (Pattern *)lua_newuserdata(L, size);
2540 luaL_getmetatable(L, PATTERN_T);
2541 lua_pushvalue(L, -1);
2542 lua_setuservalue(L, -3);
2543 lua_setmetatable(L, -2);
2544 p->code = NULL; p->codesize = 0;
2545 return p->tree;
2546 }
2547
2548
2549 static TTree *newleaf (lua_State *L, int tag) {
2550 TTree *tree = newtree(L, 1);
2551 tree->tag = tag;
2552 return tree;
2553 }
2554
2555
2556 static TTree *newcharset (lua_State *L) {
2557 TTree *tree = newtree(L, bytes2slots(CHARSETSIZE) + 1);
2558 tree->tag = TSet;
2559 loopset(i, treebuffer(tree)[i] = 0);
2560 return tree;
2561 }
2562
2563
2564 /*
2565 ** add to tree a sequence where first sibling is 'sib' (with size
2566 ** 'sibsize'); returns position for second sibling
2567 */
2568 static TTree *seqaux (TTree *tree, TTree *sib, int sibsize) {
2569 tree->tag = TSeq; tree->u.ps = sibsize + 1;
2570 memcpy(sib1(tree), sib, sibsize * sizeof(TTree));
2571 return sib2(tree);
2572 }
2573
2574
2575 /*
2576 ** Build a sequence of 'n' nodes, each with tag 'tag' and 'u.n' got
2577 ** from the array 's' (or 0 if array is NULL). (TSeq is binary, so it
2578 ** must build a sequence of sequence of sequence...)
2579 */
2580 static void fillseq (TTree *tree, int tag, int n, const char *s) {
2581 int i;
2582 for (i = 0; i < n - 1; i++) { /* initial n-1 copies of Seq tag; Seq ... */
2583 tree->tag = TSeq; tree->u.ps = 2;
2584 sib1(tree)->tag = tag;
2585 sib1(tree)->u.n = s ? (byte)s[i] : 0;
2586 tree = sib2(tree);
2587 }
2588 tree->tag = tag; /* last one does not need TSeq */
2589 tree->u.n = s ? (byte)s[i] : 0;
2590 }
2591
2592
2593 /*
2594 ** Numbers as patterns:
2595 ** 0 == true (always match); n == TAny repeated 'n' times;
2596 ** -n == not (TAny repeated 'n' times)
2597 */
2598 static TTree *numtree (lua_State *L, int n) {
2599 if (n == 0)
2600 return newleaf(L, TTrue);
2601 else {
2602 TTree *tree, *nd;
2603 if (n > 0)
2604 tree = nd = newtree(L, 2 * n - 1);
2605 else { /* negative: code it as !(-n) */
2606 n = -n;
2607 tree = newtree(L, 2 * n);
2608 tree->tag = TNot;
2609 nd = sib1(tree);
2610 }
2611 fillseq(nd, TAny, n, NULL); /* sequence of 'n' any's */
2612 return tree;
2613 }
2614 }
2615
2616
2617 /*
2618 ** Convert value at index 'idx' to a pattern
2619 */
2620 static TTree *getpatt (lua_State *L, int idx, int *len) {
2621 TTree *tree;
2622 switch (lua_type(L, idx)) {
2623 case LUA_TSTRING: {
2624 size_t slen;
2625 const char *s = lua_tolstring(L, idx, &slen); /* get string */
2626 if (slen == 0) /* empty? */
2627 tree = newleaf(L, TTrue); /* always match */
2628 else {
2629 tree = newtree(L, 2 * (slen - 1) + 1);
2630 fillseq(tree, TChar, slen, s); /* sequence of 'slen' chars */
2631 }
2632 break;
2633 }
2634 case LUA_TNUMBER: {
2635 int n = lua_tointeger(L, idx);
2636 tree = numtree(L, n);
2637 break;
2638 }
2639 case LUA_TBOOLEAN: {
2640 tree = (lua_toboolean(L, idx) ? newleaf(L, TTrue) : newleaf(L, TFalse));
2641 break;
2642 }
2643 case LUA_TTABLE: {
2644 tree = newgrammar(L, idx);
2645 break;
2646 }
2647 case LUA_TFUNCTION: {
2648 tree = newtree(L, 2);
2649 tree->tag = TRunTime;
2650 tree->key = addtonewktable(L, 0, idx);
2651 sib1(tree)->tag = TTrue;
2652 break;
2653 }
2654 default: {
2655 return gettree(L, idx, len);
2656 }
2657 }
2658 lua_replace(L, idx); /* put new tree into 'idx' slot */
2659 if (len)
2660 *len = getsize(L, idx);
2661 return tree;
2662 }
2663
2664
2665 /*
2666 ** create a new tree, whith a new root and one sibling.
2667 ** Sibling must be on the Lua stack, at index 1.
2668 */
2669 static TTree *newroot1sib (lua_State *L, int tag) {
2670 int s1;
2671 TTree *tree1 = getpatt(L, 1, &s1);
2672 TTree *tree = newtree(L, 1 + s1); /* create new tree */
2673 tree->tag = tag;
2674 memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
2675 copyktable(L, 1);
2676 return tree;
2677 }
2678
2679
2680 /*
2681 ** create a new tree, whith a new root and 2 siblings.
2682 ** Siblings must be on the Lua stack, first one at index 1.
2683 */
2684 static TTree *newroot2sib (lua_State *L, int tag) {
2685 int s1, s2;
2686 TTree *tree1 = getpatt(L, 1, &s1);
2687 TTree *tree2 = getpatt(L, 2, &s2);
2688 TTree *tree = newtree(L, 1 + s1 + s2); /* create new tree */
2689 tree->tag = tag;
2690 tree->u.ps = 1 + s1;
2691 memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
2692 memcpy(sib2(tree), tree2, s2 * sizeof(TTree));
2693 joinktables(L, 1, sib2(tree), 2);
2694 return tree;
2695 }
2696
2697
2698 static int lp_P (lua_State *L) {
2699 luaL_checkany(L, 1);
2700 getpatt(L, 1, NULL);
2701 lua_settop(L, 1);
2702 return 1;
2703 }
2704
2705
2706 /*
2707 ** sequence operator; optimizations:
2708 ** false x => false, x true => x, true x => x
2709 ** (cannot do x . false => false because x may have runtime captures)
2710 */
2711 static int lp_seq (lua_State *L) {
2712 TTree *tree1 = getpatt(L, 1, NULL);
2713 TTree *tree2 = getpatt(L, 2, NULL);
2714 if (tree1->tag == TFalse || tree2->tag == TTrue)
2715 lua_pushvalue(L, 1); /* false . x == false, x . true = x */
2716 else if (tree1->tag == TTrue)
2717 lua_pushvalue(L, 2); /* true . x = x */
2718 else
2719 newroot2sib(L, TSeq);
2720 return 1;
2721 }
2722
2723
2724 /*
2725 ** choice operator; optimizations:
2726 ** charset / charset => charset
2727 ** true / x => true, x / false => x, false / x => x
2728 ** (x / true is not equivalent to true)
2729 */
2730 static int lp_choice (lua_State *L) {
2731 Charset st1, st2;
2732 TTree *t1 = getpatt(L, 1, NULL);
2733 TTree *t2 = getpatt(L, 2, NULL);
2734 if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
2735 TTree *t = newcharset(L);
2736 loopset(i, treebuffer(t)[i] = st1.cs[i] | st2.cs[i]);
2737 }
2738 else if (nofail(t1) || t2->tag == TFalse)
2739 lua_pushvalue(L, 1); /* true / x => true, x / false => x */
2740 else if (t1->tag == TFalse)
2741 lua_pushvalue(L, 2); /* false / x => x */
2742 else
2743 newroot2sib(L, TChoice);
2744 return 1;
2745 }
2746
2747
2748 /*
2749 ** p^n
2750 */
2751 static int lp_star (lua_State *L) {
2752 int size1;
2753 int n = (int)luaL_checkinteger(L, 2);
2754 TTree *tree1 = getpatt(L, 1, &size1);
2755 if (n >= 0) { /* seq tree1 (seq tree1 ... (seq tree1 (rep tree1))) */
2756 TTree *tree = newtree(L, (n + 1) * (size1 + 1));
2757 if (nullable(tree1))
2758 luaL_error(L, "loop body may accept empty string");
2759 while (n--) /* repeat 'n' times */
2760 tree = seqaux(tree, tree1, size1);
2761 tree->tag = TRep;
2762 memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
2763 }
2764 else { /* choice (seq tree1 ... choice tree1 true ...) true */
2765 TTree *tree;
2766 n = -n;
2767 /* size = (choice + seq + tree1 + true) * n, but the last has no seq */
2768 tree = newtree(L, n * (size1 + 3) - 1);
2769 for (; n > 1; n--) { /* repeat (n - 1) times */
2770 tree->tag = TChoice; tree->u.ps = n * (size1 + 3) - 2;
2771 sib2(tree)->tag = TTrue;
2772 tree = sib1(tree);
2773 tree = seqaux(tree, tree1, size1);
2774 }
2775 tree->tag = TChoice; tree->u.ps = size1 + 1;
2776 sib2(tree)->tag = TTrue;
2777 memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
2778 }
2779 copyktable(L, 1);
2780 return 1;
2781 }
2782
2783
2784 /*
2785 ** #p == &p
2786 */
2787 static int lp_and (lua_State *L) {
2788 newroot1sib(L, TAnd);
2789 return 1;
2790 }
2791
2792
2793 /*
2794 ** -p == !p
2795 */
2796 static int lp_not (lua_State *L) {
2797 newroot1sib(L, TNot);
2798 return 1;
2799 }
2800
2801
2802 /*
2803 ** [t1 - t2] == Seq (Not t2) t1
2804 ** If t1 and t2 are charsets, make their difference.
2805 */
2806 static int lp_sub (lua_State *L) {
2807 Charset st1, st2;
2808 int s1, s2;
2809 TTree *t1 = getpatt(L, 1, &s1);
2810 TTree *t2 = getpatt(L, 2, &s2);
2811 if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
2812 TTree *t = newcharset(L);
2813 loopset(i, treebuffer(t)[i] = st1.cs[i] & ~st2.cs[i]);
2814 }
2815 else {
2816 TTree *tree = newtree(L, 2 + s1 + s2);
2817 tree->tag = TSeq; /* sequence of... */
2818 tree->u.ps = 2 + s2;
2819 sib1(tree)->tag = TNot; /* ...not... */
2820 memcpy(sib1(sib1(tree)), t2, s2 * sizeof(TTree)); /* ...t2 */
2821 memcpy(sib2(tree), t1, s1 * sizeof(TTree)); /* ... and t1 */
2822 joinktables(L, 1, sib1(tree), 2);
2823 }
2824 return 1;
2825 }
2826
2827
2828 static int lp_set (lua_State *L) {
2829 size_t l;
2830 const char *s = luaL_checklstring(L, 1, &l);
2831 TTree *tree = newcharset(L);
2832 while (l--) {
2833 setchar(treebuffer(tree), (byte)(*s));
2834 s++;
2835 }
2836 return 1;
2837 }
2838
2839
2840 static int lp_range (lua_State *L) {
2841 int arg;
2842 int top = lua_gettop(L);
2843 TTree *tree = newcharset(L);
2844 for (arg = 1; arg <= top; arg++) {
2845 int c;
2846 size_t l;
2847 const char *r = luaL_checklstring(L, arg, &l);
2848 luaL_argcheck(L, l == 2, arg, "range must have two characters");
2849 for (c = (byte)r[0]; c <= (byte)r[1]; c++)
2850 setchar(treebuffer(tree), c);
2851 }
2852 return 1;
2853 }
2854
2855
2856 /*
2857 ** Look-behind predicate
2858 */
2859 static int lp_behind (lua_State *L) {
2860 TTree *tree;
2861 TTree *tree1 = getpatt(L, 1, NULL);
2862 int n = fixedlen(tree1);
2863 luaL_argcheck(L, n >= 0, 1, "pattern may not have fixed length");
2864 luaL_argcheck(L, !hascaptures(tree1), 1, "pattern have captures");
2865 luaL_argcheck(L, n <= MAXBEHIND, 1, "pattern too long to look behind");
2866 tree = newroot1sib(L, TBehind);
2867 tree->u.n = n;
2868 return 1;
2869 }
2870
2871
2872 /*
2873 ** Create a non-terminal
2874 */
2875 static int lp_V (lua_State *L) {
2876 TTree *tree = newleaf(L, TOpenCall);
2877 luaL_argcheck(L, !lua_isnoneornil(L, 1), 1, "non-nil value expected");
2878 tree->key = addtonewktable(L, 0, 1);
2879 return 1;
2880 }
2881
2882
2883 /*
2884 ** Create a tree for a non-empty capture, with a body and
2885 ** optionally with an associated Lua value (at index 'labelidx' in the
2886 ** stack)
2887 */
2888 static int capture_aux (lua_State *L, int cap, int labelidx) {
2889 TTree *tree = newroot1sib(L, TCapture);
2890 tree->cap = cap;
2891 tree->key = (labelidx == 0) ? 0 : addtonewktable(L, 1, labelidx);
2892 return 1;
2893 }
2894
2895
2896 /*
2897 ** Fill a tree with an empty capture, using an empty (TTrue) sibling.
2898 */
2899 static TTree *auxemptycap (TTree *tree, int cap) {
2900 tree->tag = TCapture;
2901 tree->cap = cap;
2902 sib1(tree)->tag = TTrue;
2903 return tree;
2904 }
2905
2906
2907 /*
2908 ** Create a tree for an empty capture
2909 */
2910 static TTree *newemptycap (lua_State *L, int cap) {
2911 return auxemptycap(newtree(L, 2), cap);
2912 }
2913
2914
2915 /*
2916 ** Create a tree for an empty capture with an associated Lua value
2917 */
2918 static TTree *newemptycapkey (lua_State *L, int cap, int idx) {
2919 TTree *tree = auxemptycap(newtree(L, 2), cap);
2920 tree->key = addtonewktable(L, 0, idx);
2921 return tree;
2922 }
2923
2924
2925 /*
2926 ** Captures with syntax p / v
2927 ** (function capture, query capture, string capture, or number capture)
2928 */
2929 static int lp_divcapture (lua_State *L) {
2930 switch (lua_type(L, 2)) {
2931 case LUA_TFUNCTION: return capture_aux(L, Cfunction, 2);
2932 case LUA_TTABLE: return capture_aux(L, Cquery, 2);
2933 case LUA_TSTRING: return capture_aux(L, Cstring, 2);
2934 case LUA_TNUMBER: {
2935 int n = lua_tointeger(L, 2);
2936 TTree *tree = newroot1sib(L, TCapture);
2937 luaL_argcheck(L, 0 <= n && n <= SHRT_MAX, 1, "invalid number");
2938 tree->cap = Cnum;
2939 tree->key = n;
2940 return 1;
2941 }
2942 default: return luaL_argerror(L, 2, "invalid replacement value");
2943 }
2944 }
2945
2946
2947 static int lp_substcapture (lua_State *L) {
2948 return capture_aux(L, Csubst, 0);
2949 }
2950
2951
2952 static int lp_tablecapture (lua_State *L) {
2953 return capture_aux(L, Ctable, 0);
2954 }
2955
2956
2957 static int lp_groupcapture (lua_State *L) {
2958 if (lua_isnoneornil(L, 2))
2959 return capture_aux(L, Cgroup, 0);
2960 else
2961 return capture_aux(L, Cgroup, 2);
2962 }
2963
2964
2965 static int lp_foldcapture (lua_State *L) {
2966 luaL_checktype(L, 2, LUA_TFUNCTION);
2967 return capture_aux(L, Cfold, 2);
2968 }
2969
2970
2971 static int lp_simplecapture (lua_State *L) {
2972 return capture_aux(L, Csimple, 0);
2973 }
2974
2975
2976 static int lp_poscapture (lua_State *L) {
2977 newemptycap(L, Cposition);
2978 return 1;
2979 }
2980
2981
2982 static int lp_argcapture (lua_State *L) {
2983 int n = (int)luaL_checkinteger(L, 1);
2984 TTree *tree = newemptycap(L, Carg);
2985 tree->key = n;
2986 luaL_argcheck(L, 0 < n && n <= SHRT_MAX, 1, "invalid argument index");
2987 return 1;
2988 }
2989
2990
2991 static int lp_backref (lua_State *L) {
2992 luaL_checkany(L, 1);
2993 newemptycapkey(L, Cbackref, 1);
2994 return 1;
2995 }
2996
2997
2998 /*
2999 ** Constant capture
3000 */
3001 static int lp_constcapture (lua_State *L) {
3002 int i;
3003 int n = lua_gettop(L); /* number of values */
3004 if (n == 0) /* no values? */
3005 newleaf(L, TTrue); /* no capture */
3006 else if (n == 1)
3007 newemptycapkey(L, Cconst, 1); /* single constant capture */
3008 else { /* create a group capture with all values */
3009 TTree *tree = newtree(L, 1 + 3 * (n - 1) + 2);
3010 newktable(L, n); /* create a 'ktable' for new tree */
3011 tree->tag = TCapture;
3012 tree->cap = Cgroup;
3013 tree->key = 0;
3014 tree = sib1(tree);
3015 for (i = 1; i <= n - 1; i++) {
3016 tree->tag = TSeq;
3017 tree->u.ps = 3; /* skip TCapture and its sibling */
3018 auxemptycap(sib1(tree), Cconst);
3019 sib1(tree)->key = addtoktable(L, i);
3020 tree = sib2(tree);
3021 }
3022 auxemptycap(tree, Cconst);
3023 tree->key = addtoktable(L, i);
3024 }
3025 return 1;
3026 }
3027
3028
3029 static int lp_matchtime (lua_State *L) {
3030 TTree *tree;
3031 luaL_checktype(L, 2, LUA_TFUNCTION);
3032 tree = newroot1sib(L, TRunTime);
3033 tree->key = addtonewktable(L, 1, 2);
3034 return 1;
3035 }
3036
3037 /* }====================================================== */
3038
3039
3040 /*
3041 ** {======================================================
3042 ** Grammar - Tree generation
3043 ** =======================================================
3044 */
3045
3046 /*
3047 ** push on the stack the index and the pattern for the
3048 ** initial rule of grammar at index 'arg' in the stack;
3049 ** also add that index into position table.
3050 */
3051 static void getfirstrule (lua_State *L, int arg, int postab) {
3052 lua_rawgeti(L, arg, 1); /* access first element */
3053 if (lua_isstring(L, -1)) { /* is it the name of initial rule? */
3054 lua_pushvalue(L, -1); /* duplicate it to use as key */
3055 lua_gettable(L, arg); /* get associated rule */
3056 }
3057 else {
3058 lua_pushinteger(L, 1); /* key for initial rule */
3059 lua_insert(L, -2); /* put it before rule */
3060 }
3061 if (!testpattern(L, -1)) { /* initial rule not a pattern? */
3062 if (lua_isnil(L, -1))
3063 luaL_error(L, "grammar has no initial rule");
3064 else
3065 luaL_error(L, "initial rule '%s' is not a pattern", lua_tostring(L, -2));
3066 }
3067 lua_pushvalue(L, -2); /* push key */
3068 lua_pushinteger(L, 1); /* push rule position (after TGrammar) */
3069 lua_settable(L, postab); /* insert pair at position table */
3070 }
3071
3072 /*
3073 ** traverse grammar at index 'arg', pushing all its keys and patterns
3074 ** into the stack. Create a new table (before all pairs key-pattern) to
3075 ** collect all keys and their associated positions in the final tree
3076 ** (the "position table").
3077 ** Return the number of rules and (in 'totalsize') the total size
3078 ** for the new tree.
3079 */
3080 static int collectrules (lua_State *L, int arg, int *totalsize) {
3081 int n = 1; /* to count number of rules */
3082 int postab = lua_gettop(L) + 1; /* index of position table */
3083 int size; /* accumulator for total size */
3084 lua_newtable(L); /* create position table */
3085 getfirstrule(L, arg, postab);
3086 size = 2 + getsize(L, postab + 2); /* TGrammar + TRule + rule */
3087 lua_pushnil(L); /* prepare to traverse grammar table */
3088 while (lua_next(L, arg) != 0) {
3089 if (lua_tonumber(L, -2) == 1 ||
3090 lp_equal(L, -2, postab + 1)) { /* initial rule? */
3091 lua_pop(L, 1); /* remove value (keep key for lua_next) */
3092 continue;
3093 }
3094 if (!testpattern(L, -1)) /* value is not a pattern? */
3095 luaL_error(L, "rule '%s' is not a pattern", val2str(L, -2));
3096 luaL_checkstack(L, LUA_MINSTACK, "grammar has too many rules");
3097 lua_pushvalue(L, -2); /* push key (to insert into position table) */
3098 lua_pushinteger(L, size);
3099 lua_settable(L, postab);
3100 size += 1 + getsize(L, -1); /* update size */
3101 lua_pushvalue(L, -2); /* push key (for next lua_next) */
3102 n++;
3103 }
3104 *totalsize = size + 1; /* TTrue to finish list of rules */
3105 return n;
3106 }
3107
3108
3109 static void buildgrammar (lua_State *L, TTree *grammar, int frule, int n) {
3110 int i;
3111 TTree *nd = sib1(grammar); /* auxiliary pointer to traverse the tree */
3112 for (i = 0; i < n; i++) { /* add each rule into new tree */
3113 int ridx = frule + 2*i + 1; /* index of i-th rule */
3114 int rulesize;
3115 TTree *rn = gettree(L, ridx, &rulesize);
3116 nd->tag = TRule;
3117 nd->key = 0; /* will be fixed when rule is used */
3118 nd->cap = i; /* rule number */
3119 nd->u.ps = rulesize + 1; /* point to next rule */
3120 memcpy(sib1(nd), rn, rulesize * sizeof(TTree)); /* copy rule */
3121 mergektable(L, ridx, sib1(nd)); /* merge its ktable into new one */
3122 nd = sib2(nd); /* move to next rule */
3123 }
3124 nd->tag = TTrue; /* finish list of rules */
3125 }
3126
3127
3128 /*
3129 ** Check whether a tree has potential infinite loops
3130 */
3131 static int checkloops (TTree *tree) {
3132 tailcall:
3133 if (tree->tag == TRep && nullable(sib1(tree)))
3134 return 1;
3135 else if (tree->tag == TGrammar)
3136 return 0; /* sub-grammars already checked */
3137 else {
3138 switch (numsiblings[tree->tag]) {
3139 case 1: /* return checkloops(sib1(tree)); */
3140 tree = sib1(tree); goto tailcall;
3141 case 2:
3142 if (checkloops(sib1(tree))) return 1;
3143 /* else return checkloops(sib2(tree)); */
3144 tree = sib2(tree); goto tailcall;
3145 default: assert(numsiblings[tree->tag] == 0); return 0;
3146 }
3147 }
3148 }
3149
3150
3151 /*
3152 ** Give appropriate error message for 'verifyrule'. If a rule appears
3153 ** twice in 'passed', there is path from it back to itself without
3154 ** advancing the subject.
3155 */
3156 static int verifyerror (lua_State *L, int *passed, int npassed) {
3157 int i, j;
3158 for (i = npassed - 1; i >= 0; i--) { /* search for a repetition */
3159 for (j = i - 1; j >= 0; j--) {
3160 if (passed[i] == passed[j]) {
3161 lua_rawgeti(L, -1, passed[i]); /* get rule's key */
3162 return luaL_error(L, "rule '%s' may be left recursive", val2str(L, -1));
3163 }
3164 }
3165 }
3166 return luaL_error(L, "too many left calls in grammar");
3167 }
3168
3169
3170 /*
3171 ** Check whether a rule can be left recursive; raise an error in that
3172 ** case; otherwise return 1 iff pattern is nullable.
3173 ** The return value is used to check sequences, where the second pattern
3174 ** is only relevant if the first is nullable.
3175 ** Parameter 'nb' works as an accumulator, to allow tail calls in
3176 ** choices. ('nb' true makes function returns true.)
3177 ** Parameter 'passed' is a list of already visited rules, 'npassed'
3178 ** counts the elements in 'passed'.
3179 ** Assume ktable at the top of the stack.
3180 */
3181 static int verifyrule (lua_State *L, TTree *tree, int *passed, int npassed,
3182 int nb) {
3183 tailcall:
3184 switch (tree->tag) {
3185 case TChar: case TSet: case TAny:
3186 case TFalse:
3187 return nb; /* cannot pass from here */
3188 case TTrue:
3189 case TBehind: /* look-behind cannot have calls */
3190 return 1;
3191 case TNot: case TAnd: case TRep:
3192 /* return verifyrule(L, sib1(tree), passed, npassed, 1); */
3193 tree = sib1(tree); nb = 1; goto tailcall;
3194 case TCapture: case TRunTime:
3195 /* return verifyrule(L, sib1(tree), passed, npassed, nb); */
3196 tree = sib1(tree); goto tailcall;
3197 case TCall:
3198 /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
3199 tree = sib2(tree); goto tailcall;
3200 case TSeq: /* only check 2nd child if first is nb */
3201 if (!verifyrule(L, sib1(tree), passed, npassed, 0))
3202 return nb;
3203 /* else return verifyrule(L, sib2(tree), passed, npassed, nb); */
3204 tree = sib2(tree); goto tailcall;
3205 case TChoice: /* must check both children */
3206 nb = verifyrule(L, sib1(tree), passed, npassed, nb);
3207 /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
3208 tree = sib2(tree); goto tailcall;
3209 case TRule:
3210 if (npassed >= MAXRULES)
3211 return verifyerror(L, passed, npassed);
3212 else {
3213 passed[npassed++] = tree->key;
3214 /* return verifyrule(L, sib1(tree), passed, npassed); */
3215 tree = sib1(tree); goto tailcall;
3216 }
3217 case TGrammar:
3218 return nullable(tree); /* sub-grammar cannot be left recursive */
3219 default: assert(0); return 0;
3220 }
3221 }
3222
3223
3224 static void verifygrammar (lua_State *L, TTree *grammar) {
3225 int passed[MAXRULES];
3226 TTree *rule;
3227 /* check left-recursive rules */
3228 for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
3229 if (rule->key == 0) continue; /* unused rule */
3230 verifyrule(L, sib1(rule), passed, 0, 0);
3231 }
3232 assert(rule->tag == TTrue);
3233 /* check infinite loops inside rules */
3234 for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
3235 if (rule->key == 0) continue; /* unused rule */
3236 if (checkloops(sib1(rule))) {
3237 lua_rawgeti(L, -1, rule->key); /* get rule's key */
3238 luaL_error(L, "empty loop in rule '%s'", val2str(L, -1));
3239 }
3240 }
3241 assert(rule->tag == TTrue);
3242 }
3243
3244
3245 /*
3246 ** Give a name for the initial rule if it is not referenced
3247 */
3248 static void initialrulename (lua_State *L, TTree *grammar, int frule) {
3249 if (sib1(grammar)->key == 0) { /* initial rule is not referenced? */
3250 int n = lua_rawlen(L, -1) + 1; /* index for name */
3251 lua_pushvalue(L, frule); /* rule's name */
3252 lua_rawseti(L, -2, n); /* ktable was on the top of the stack */
3253 sib1(grammar)->key = n;
3254 }
3255 }
3256
3257
3258 static TTree *newgrammar (lua_State *L, int arg) {
3259 int treesize;
3260 int frule = lua_gettop(L) + 2; /* position of first rule's key */
3261 int n = collectrules(L, arg, &treesize);
3262 TTree *g = newtree(L, treesize);
3263 luaL_argcheck(L, n <= MAXRULES, arg, "grammar has too many rules");
3264 g->tag = TGrammar; g->u.n = n;
3265 lua_newtable(L); /* create 'ktable' */
3266 lua_setuservalue(L, -2);
3267 buildgrammar(L, g, frule, n);
3268 lua_getuservalue(L, -1); /* get 'ktable' for new tree */
3269 finalfix(L, frule - 1, g, sib1(g));
3270 initialrulename(L, g, frule);
3271 verifygrammar(L, g);
3272 lua_pop(L, 1); /* remove 'ktable' */
3273 lua_insert(L, -(n * 2 + 2)); /* move new table to proper position */
3274 lua_pop(L, n * 2 + 1); /* remove position table + rule pairs */
3275 return g; /* new table at the top of the stack */
3276 }
3277
3278 /* }====================================================== */
3279
3280
3281 static Instruction *prepcompile (lua_State *L, Pattern *p, int idx) {
3282 lua_getuservalue(L, idx); /* push 'ktable' (may be used by 'finalfix') */
3283 finalfix(L, 0, NULL, p->tree);
3284 lua_pop(L, 1); /* remove 'ktable' */
3285 return compile(L, p);
3286 }
3287
3288
3289 static int lp_printtree (lua_State *L) {
3290 TTree *tree = getpatt(L, 1, NULL);
3291 int c = lua_toboolean(L, 2);
3292 if (c) {
3293 lua_getuservalue(L, 1); /* push 'ktable' (may be used by 'finalfix') */
3294 finalfix(L, 0, NULL, tree);
3295 lua_pop(L, 1); /* remove 'ktable' */
3296 }
3297 printktable(L, 1);
3298 printtree(tree, 0);
3299 return 0;
3300 }
3301
3302
3303 static int lp_printcode (lua_State *L) {
3304 Pattern *p = getpattern(L, 1);
3305 printktable(L, 1);
3306 if (p->code == NULL) /* not compiled yet? */
3307 prepcompile(L, p, 1);
3308 printpatt(p->code, p->codesize);
3309 return 0;
3310 }
3311
3312
3313 /*
3314 ** Get the initial position for the match, interpreting negative
3315 ** values from the end of the subject
3316 */
3317 static size_t initposition (lua_State *L, size_t len) {
3318 lua_Integer ii = luaL_optinteger(L, 3, 1);
3319 if (ii > 0) { /* positive index? */
3320 if ((size_t)ii <= len) /* inside the string? */
3321 return (size_t)ii - 1; /* return it (corrected to 0-base) */
3322 else return len; /* crop at the end */
3323 }
3324 else { /* negative index */
3325 if ((size_t)(-ii) <= len) /* inside the string? */
3326 return len - ((size_t)(-ii)); /* return position from the end */
3327 else return 0; /* crop at the beginning */
3328 }
3329 }
3330
3331
3332 /*
3333 ** Main match function
3334 */
3335 static int lp_match (lua_State *L) {
3336 #if defined(__aarch64__) && defined(MFLuaJIT)
3337 Capture *capture;
3338 #else
3339 Capture capture[INITCAPSIZE];
3340 #endif
3341 const char *r;
3342 size_t l;
3343 /*int ret_val;*/
3344 Pattern *p = (getpatt(L, 1, NULL), getpattern(L, 1));
3345 Instruction *code = (p->code != NULL) ? p->code : prepcompile(L, p, 1);
3346 const char *s = luaL_checklstring(L, SUBJIDX, &l);
3347 size_t i = initposition(L, l);
3348 int ptop = lua_gettop(L);
3349 lua_pushnil(L); /* initialize subscache */
3350 #if defined(__aarch64__) && defined(MFLuaJIT)
3351 capture = (Capture *)lua_newuserdata(L, sizeof(Capture)*INITCAPSIZE);
3352 #else
3353 lua_pushlightuserdata(L, capture); /* initialize caplistidx */
3354 #endif
3355 lua_getuservalue(L, 1); /* initialize penvidx */
3356 r = match(L, s, s + i, s + l, code, capture, ptop);
3357 if (r == NULL) {
3358 lua_pushnil(L);
3359 return 1;
3360 }
3361 return getcaptures(L, s, r, ptop);
3362 }
3363
3364
3365
3366 /*
3367 ** {======================================================
3368 ** Library creation and functions not related to matching
3369 ** =======================================================
3370 */
3371
3372 /* maximum limit for stack size */
3373 #define MAXLIM (INT_MAX / 100)
3374
3375 static int lp_setmax (lua_State *L) {
3376 lua_Integer lim = luaL_checkinteger(L, 1);
3377 luaL_argcheck(L, 0 < lim && lim <= MAXLIM, 1, "out of range");
3378 lua_settop(L, 1);
3379 lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
3380 return 0;
3381 }
3382
3383
3384 static int lp_version (lua_State *L) {
3385 lua_pushstring(L, VERSION);
3386 return 1;
3387 }
3388
3389
3390 static int lp_type (lua_State *L) {
3391 if (testpattern(L, 1))
3392 lua_pushliteral(L, "pattern");
3393 else
3394 lua_pushnil(L);
3395 return 1;
3396 }
3397
3398
3399 int lp_gc (lua_State *L) {
3400 Pattern *p = getpattern(L, 1);
3401 realloccode(L, p, 0); /* delete code block */
3402 return 0;
3403 }
3404
3405
3406 static void createcat (lua_State *L, const char *catname, int (catf) (int)) {
3407 TTree *t = newcharset(L);
3408 int i;
3409 for (i = 0; i <= UCHAR_MAX; i++)
3410 if (catf(i)) setchar(treebuffer(t), i);
3411 lua_setfield(L, -2, catname);
3412 }
3413
3414
3415 static int lp_locale (lua_State *L) {
3416 if (lua_isnoneornil(L, 1)) {
3417 lua_settop(L, 0);
3418 lua_createtable(L, 0, 12);
3419 }
3420 else {
3421 luaL_checktype(L, 1, LUA_TTABLE);
3422 lua_settop(L, 1);
3423 }
3424 createcat(L, "alnum", isalnum);
3425 createcat(L, "alpha", isalpha);
3426 createcat(L, "cntrl", iscntrl);
3427 createcat(L, "digit", isdigit);
3428 createcat(L, "graph", isgraph);
3429 createcat(L, "lower", islower);
3430 createcat(L, "print", isprint);
3431 createcat(L, "punct", ispunct);
3432 createcat(L, "space", isspace);
3433 createcat(L, "upper", isupper);
3434 createcat(L, "xdigit", isxdigit);
3435 return 1;
3436 }
3437
3438
3439 static struct luaL_Reg pattreg[] = {
3440 {"ptree", lp_printtree},
3441 {"pcode", lp_printcode},
3442 {"match", lp_match},
3443 {"B", lp_behind},
3444 {"V", lp_V},
3445 {"C", lp_simplecapture},
3446 {"Cc", lp_constcapture},
3447 {"Cmt", lp_matchtime},
3448 {"Cb", lp_backref},
3449 {"Carg", lp_argcapture},
3450 {"Cp", lp_poscapture},
3451 {"Cs", lp_substcapture},
3452 {"Ct", lp_tablecapture},
3453 {"Cf", lp_foldcapture},
3454 {"Cg", lp_groupcapture},
3455 {"P", lp_P},
3456 {"S", lp_set},
3457 {"R", lp_range},
3458 {"locale", lp_locale},
3459 {"version", lp_version},
3460 {"setmaxstack", lp_setmax},
3461 {"type", lp_type},
3462 {NULL, NULL}
3463 };
3464
3465
3466 static struct luaL_Reg metareg[] = {
3467 {"__mul", lp_seq},
3468 {"__add", lp_choice},
3469 {"__pow", lp_star},
3470 {"__gc", lp_gc},
3471 {"__len", lp_and},
3472 {"__div", lp_divcapture},
3473 {"__unm", lp_not},
3474 {"__sub", lp_sub},
3475 {NULL, NULL}
3476 };
3477
3478
3479 int luaopen_lpeg (lua_State *L);
3480 int luaopen_lpeg (lua_State *L) {
3481 luaL_newmetatable(L, PATTERN_T);
3482 lua_pushnumber(L, MAXBACK); /* initialize maximum backtracking */
3483 lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
3484 luaL_setfuncs(L, metareg, 0);
3485 #if defined(MFLuaJIT)
3486 luaL_register(L,"lpeg",pattreg);
3487 #else
3488 luaL_newlib(L, pattreg);
3489 #endif
3490 lua_pushvalue(L, -1);
3491 lua_setfield(L, -3, "__index");
3492 return 1;
3493 }
3494
3495
3496 int mfluaopen_lpeg(lua_State * L);
3497 int mfluaopen_lpeg(lua_State * L) {
3498 lua_getglobal(L,"_G");
3499 /* set the lpeg table */
3500 lua_pushstring(L,"lpeg");
3501 luaopen_lpeg(L);
3502 lua_settable(L, -3);
3503 return 1;
3504 }
3505
3506
3507 /* }====================================================== */