robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 9a29622b3b00ddb601

master
38.5 KiB1399 linesraw
1
2#include <ctype.h>
3#include <limits.h>
4#include <string.h>
5
6
7#include "lua.h"
8#include "lauxlib.h"
9
10#include "lptypes.h"
11#include "lpcap.h"
12#include "lpcode.h"
13#include "lpprint.h"
14#include "lptree.h"
15#include "lpcset.h"
16
17
18/* number of siblings for each tree */
19const byte numsiblings[] = {
20  0, 0, 0,	/* char, set, any */
21  0, 0, 0,	/* true, false, utf-range */
22  1,		/* acc */
23  2, 2,		/* seq, choice */
24  1, 1,		/* not, and */
25  0, 0, 2, 1, 1,  /* call, opencall, rule, prerule, grammar */
26  1,  /* behind */
27  1, 1  /* capture, runtime capture */
28};
29
30
31static TTree *newgrammar (lua_State *L, int arg);
32
33
34/*
35** returns a reasonable name for value at index 'idx' on the stack
36*/
37static const char *val2str (lua_State *L, int idx) {
38  const char *k = lua_tostring(L, idx);
39  if (k != NULL)
40    return lua_pushfstring(L, "%s", k);
41  else
42    return lua_pushfstring(L, "(a %s)", luaL_typename(L, idx));
43}
44
45
46/*
47** Fix a TOpenCall into a TCall node, using table 'postable' to
48** translate a key to its rule address in the tree. Raises an
49** error if key does not exist.
50*/
51static void fixonecall (lua_State *L, int postable, TTree *g, TTree *t) {
52  int n;
53  lua_rawgeti(L, -1, t->key);  /* get rule's name */
54  lua_gettable(L, postable);  /* query name in position table */
55  n = lua_tonumber(L, -1);  /* get (absolute) position */
56  lua_pop(L, 1);  /* remove position */
57  if (n == 0) {  /* no position? */
58    lua_rawgeti(L, -1, t->key);  /* get rule's name again */
59    luaL_error(L, "rule '%s' undefined in given grammar", val2str(L, -1));
60  }
61  t->tag = TCall;
62  t->u.ps = n - (t - g);  /* position relative to node */
63  assert(sib2(t)->tag == TRule);
64  sib2(t)->key = t->key;  /* fix rule's key */
65}
66
67
68/*
69** Transform left associative constructions into right
70** associative ones, for sequence and choice; that is:
71** (t11 + t12) + t2  =>  t11 + (t12 + t2)
72** (t11 * t12) * t2  =>  t11 * (t12 * t2)
73** (that is, Op (Op t11 t12) t2 => Op t11 (Op t12 t2))
74*/
75static void correctassociativity (TTree *tree) {
76  TTree *t1 = sib1(tree);
77  assert(tree->tag == TChoice || tree->tag == TSeq);
78  while (t1->tag == tree->tag) {
79    int n1size = tree->u.ps - 1;  /* t1 == Op t11 t12 */
80    int n11size = t1->u.ps - 1;
81    int n12size = n1size - n11size - 1;
82    memmove(sib1(tree), sib1(t1), n11size * sizeof(TTree)); /* move t11 */
83    tree->u.ps = n11size + 1;
84    sib2(tree)->tag = tree->tag;
85    sib2(tree)->u.ps = n12size + 1;
86  }
87}
88
89
90/*
91** Make final adjustments in a tree. Fix open calls in tree 't',
92** making them refer to their respective rules or raising appropriate
93** errors (if not inside a grammar). Correct associativity of associative
94** constructions (making them right associative). Assume that tree's
95** ktable is at the top of the stack (for error messages).
96*/
97static void finalfix (lua_State *L, int postable, TTree *g, TTree *t) {
98 tailcall:
99  switch (t->tag) {
100    case TGrammar:  /* subgrammars were already fixed */
101      return;
102    case TOpenCall: {
103      if (g != NULL)  /* inside a grammar? */
104        fixonecall(L, postable, g, t);
105      else {  /* open call outside grammar */
106        lua_rawgeti(L, -1, t->key);
107        luaL_error(L, "rule '%s' used outside a grammar", val2str(L, -1));
108      }
109      break;
110    }
111    case TSeq: case TChoice:
112      correctassociativity(t);
113      break;
114  }
115  switch (numsiblings[t->tag]) {
116    case 1: /* finalfix(L, postable, g, sib1(t)); */
117      t = sib1(t); goto tailcall;
118    case 2:
119      finalfix(L, postable, g, sib1(t));
120      t = sib2(t); goto tailcall;  /* finalfix(L, postable, g, sib2(t)); */
121    default: assert(numsiblings[t->tag] == 0); break;
122  }
123}
124
125
126
127/*
128** {===================================================================
129** KTable manipulation
130**
131** - The ktable of a pattern 'p' can be shared by other patterns that
132** contain 'p' and no other constants. Because of this sharing, we
133** should not add elements to a 'ktable' unless it was freshly created
134** for the new pattern.
135**
136** - The maximum index in a ktable is USHRT_MAX, because trees and
137** patterns use unsigned shorts to store those indices.
138** ====================================================================
139*/
140
141/*
142** Create a new 'ktable' to the pattern at the top of the stack.
143*/
144static void newktable (lua_State *L, int n) {
145  lua_createtable(L, n, 0);  /* create a fresh table */
146  lua_setuservalue(L, -2);  /* set it as 'ktable' for pattern */
147}
148
149
150/*
151** Add element 'idx' to 'ktable' of pattern at the top of the stack;
152** Return index of new element.
153** If new element is nil, does not add it to table (as it would be
154** useless) and returns 0, as ktable[0] is always nil.
155*/
156static int addtoktable (lua_State *L, int idx) {
157  if (lua_isnil(L, idx))  /* nil value? */
158    return 0;
159  else {
160    int n;
161    lua_getuservalue(L, -1);  /* get ktable from pattern */
162    n = lua_rawlen(L, -1);
163    if (n >= USHRT_MAX)
164      luaL_error(L, "too many Lua values in pattern");
165    lua_pushvalue(L, idx);  /* element to be added */
166    lua_rawseti(L, -2, ++n);
167    lua_pop(L, 1);  /* remove 'ktable' */
168    return n;
169  }
170}
171
172
173/*
174** Return the number of elements in the ktable at 'idx'.
175** In Lua 5.2/5.3, default "environment" for patterns is nil, not
176** a table. Treat it as an empty table. In Lua 5.1, assumes that
177** the environment has no numeric indices (len == 0)
178*/
179static int ktablelen (lua_State *L, int idx) {
180  if (!lua_istable(L, idx)) return 0;
181  else return lua_rawlen(L, idx);
182}
183
184
185/*
186** Concatentate the contents of table 'idx1' into table 'idx2'.
187** (Assume that both indices are negative.)
188** Return the original length of table 'idx2' (or 0, if no
189** element was added, as there is no need to correct any index).
190*/
191static int concattable (lua_State *L, int idx1, int idx2) {
192  int i;
193  int n1 = ktablelen(L, idx1);
194  int n2 = ktablelen(L, idx2);
195  if (n1 + n2 > USHRT_MAX)
196    luaL_error(L, "too many Lua values in pattern");
197  if (n1 == 0) return 0;  /* nothing to correct */
198  for (i = 1; i <= n1; i++) {
199    lua_rawgeti(L, idx1, i);
200    lua_rawseti(L, idx2 - 1, n2 + i);  /* correct 'idx2' */
201  }
202  return n2;
203}
204
205
206/*
207** When joining 'ktables', constants from one of the subpatterns must
208** be renumbered; 'correctkeys' corrects their indices (adding 'n'
209** to each of them)
210*/
211static void correctkeys (TTree *tree, int n) {
212  if (n == 0) return;  /* no correction? */
213 tailcall:
214  switch (tree->tag) {
215    case TOpenCall: case TCall: case TRunTime: case TRule: {
216      if (tree->key > 0)
217        tree->key += n;
218      break;
219    }
220    case TCapture: {
221      if (tree->key > 0 && tree->cap != Carg && tree->cap != Cnum)
222        tree->key += n;
223      break;
224    }
225    default: break;
226  }
227  switch (numsiblings[tree->tag]) {
228    case 1:  /* correctkeys(sib1(tree), n); */
229      tree = sib1(tree); goto tailcall;
230    case 2:
231      correctkeys(sib1(tree), n);
232      tree = sib2(tree); goto tailcall;  /* correctkeys(sib2(tree), n); */
233    default: assert(numsiblings[tree->tag] == 0); break;
234  }
235}
236
237
238/*
239** Join the ktables from p1 and p2 the ktable for the new pattern at the
240** top of the stack, reusing them when possible.
241*/
242static void joinktables (lua_State *L, int p1, TTree *t2, int p2) {
243  int n1, n2;
244  lua_getuservalue(L, p1);  /* get ktables */
245  lua_getuservalue(L, p2);
246  n1 = ktablelen(L, -2);
247  n2 = ktablelen(L, -1);
248  if (n1 == 0 && n2 == 0)  /* are both tables empty? */
249    lua_pop(L, 2);  /* nothing to be done; pop tables */
250  else if (n2 == 0 || lp_equal(L, -2, -1)) {  /* 2nd table empty or equal? */
251    lua_pop(L, 1);  /* pop 2nd table */
252    lua_setuservalue(L, -2);  /* set 1st ktable into new pattern */
253  }
254  else if (n1 == 0) {  /* first table is empty? */
255    lua_setuservalue(L, -3);  /* set 2nd table into new pattern */
256    lua_pop(L, 1);  /* pop 1st table */
257  }
258  else {
259    lua_createtable(L, n1 + n2, 0);  /* create ktable for new pattern */
260    /* stack: new p; ktable p1; ktable p2; new ktable */
261    concattable(L, -3, -1);  /* from p1 into new ktable */
262    concattable(L, -2, -1);  /* from p2 into new ktable */
263    lua_setuservalue(L, -4);  /* new ktable becomes 'p' environment */
264    lua_pop(L, 2);  /* pop other ktables */
265    correctkeys(t2, n1);  /* correction for indices from p2 */
266  }
267}
268
269
270/*
271** copy 'ktable' of element 'idx' to new tree (on top of stack)
272*/
273static void copyktable (lua_State *L, int idx) {
274  lua_getuservalue(L, idx);
275  lua_setuservalue(L, -2);
276}
277
278
279/*
280** merge 'ktable' from 'stree' at stack index 'idx' into 'ktable'
281** from tree at the top of the stack, and correct corresponding
282** tree.
283*/
284static void mergektable (lua_State *L, int idx, TTree *stree) {
285  int n;
286  lua_getuservalue(L, -1);  /* get ktables */
287  lua_getuservalue(L, idx);
288  n = concattable(L, -1, -2);
289  lua_pop(L, 2);  /* remove both ktables */
290  correctkeys(stree, n);
291}
292
293
294/*
295** Create a new 'ktable' to the pattern at the top of the stack, adding
296** all elements from pattern 'p' (if not 0) plus element 'idx' to it.
297** Return index of new element.
298*/
299static int addtonewktable (lua_State *L, int p, int idx) {
300  newktable(L, 1);
301  if (p)
302    mergektable(L, p, NULL);
303  return addtoktable(L, idx);
304}
305
306/* }====================================================== */
307
308
309/*
310** {======================================================
311** Tree generation
312** =======================================================
313*/
314
315/*
316** In 5.2, could use 'luaL_testudata'...
317*/
318static int testpattern (lua_State *L, int idx) {
319  if (lua_touserdata(L, idx)) {  /* value is a userdata? */
320    if (lua_getmetatable(L, idx)) {  /* does it have a metatable? */
321      luaL_getmetatable(L, PATTERN_T);
322      if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */
323        lua_pop(L, 2);  /* remove both metatables */
324        return 1;
325      }
326    }
327  }
328  return 0;
329}
330
331
332static Pattern *getpattern (lua_State *L, int idx) {
333  return (Pattern *)luaL_checkudata(L, idx, PATTERN_T);
334}
335
336
337static int getsize (lua_State *L, int idx) {
338  return (lua_rawlen(L, idx) - offsetof(Pattern, tree)) / sizeof(TTree);
339}
340
341
342static TTree *gettree (lua_State *L, int idx, int *len) {
343  Pattern *p = getpattern(L, idx);
344  if (len)
345    *len = getsize(L, idx);
346  return p->tree;
347}
348
349
350/*
351** create a pattern followed by a tree with 'len' nodes. Set its
352** uservalue (the 'ktable') equal to its metatable. (It could be any
353** empty sequence; the metatable is at hand here, so we use it.)
354*/
355static TTree *newtree (lua_State *L, int len) {
356  size_t size = offsetof(Pattern, tree) + len * sizeof(TTree);
357  Pattern *p = (Pattern *)lua_newuserdata(L, size);
358  luaL_getmetatable(L, PATTERN_T);
359  lua_pushvalue(L, -1);
360  lua_setuservalue(L, -3);
361  lua_setmetatable(L, -2);
362  p->code = NULL;
363  return p->tree;
364}
365
366
367static TTree *newleaf (lua_State *L, int tag) {
368  TTree *tree = newtree(L, 1);
369  tree->tag = tag;
370  return tree;
371}
372
373
374/*
375** Create a tree for a charset, optimizing for special cases: empty set,
376** full set, and singleton set.
377*/
378static TTree *newcharset (lua_State *L, byte *cs) {
379  charsetinfo info;
380  Opcode op = charsettype(cs, &info);
381  switch (op) {
382    case IFail: return newleaf(L, TFalse);  /* empty set */
383    case IAny: return newleaf(L, TAny);  /* full set */
384    case IChar: {  /* singleton set */
385      TTree *tree =newleaf(L, TChar);
386      tree->u.n = info.offset;
387      return tree;
388    }
389    default: {  /* regular set */
390      int i;
391      int bsize =  /* tree size in bytes */
392                  (int)offsetof(TTree, u.set.bitmap) + info.size;
393      TTree *tree = newtree(L, bytes2slots(bsize));
394      assert(op == ISet);
395      tree->tag = TSet;
396      tree->u.set.offset = info.offset;
397      tree->u.set.size = info.size;
398      tree->u.set.deflt = info.deflt;
399      for (i = 0; i < info.size; i++) {
400        assert(&treebuffer(tree)[i] < (byte*)tree + bsize);
401        treebuffer(tree)[i] = cs[info.offset + i];
402      }
403      return tree;
404    }
405  }
406}
407
408
409/*
410** Add to tree a sequence where first sibling is 'sib' (with size
411** 'sibsize'); return position for second sibling.
412*/
413static TTree *seqaux (TTree *tree, TTree *sib, int sibsize) {
414  tree->tag = TSeq; tree->u.ps = sibsize + 1;
415  memcpy(sib1(tree), sib, sibsize * sizeof(TTree));
416  return sib2(tree);
417}
418
419
420/*
421** Build a sequence of 'n' nodes, each with tag 'tag' and 'u.n' got
422** from the array 's' (or 0 if array is NULL). (TSeq is binary, so it
423** must build a sequence of sequence of sequence...)
424*/
425static void fillseq (TTree *tree, int tag, int n, const char *s) {
426  int i;
427  for (i = 0; i < n - 1; i++) {  /* initial n-1 copies of Seq tag; Seq ... */
428    tree->tag = TSeq; tree->u.ps = 2;
429    sib1(tree)->tag = tag;
430    sib1(tree)->u.n = s ? (byte)s[i] : 0;
431    tree = sib2(tree);
432  }
433  tree->tag = tag;  /* last one does not need TSeq */
434  tree->u.n = s ? (byte)s[i] : 0;
435}
436
437
438/*
439** Numbers as patterns:
440** 0 == true (always match); n == TAny repeated 'n' times;
441** -n == not (TAny repeated 'n' times)
442*/
443static TTree *numtree (lua_State *L, int n) {
444  if (n == 0)
445    return newleaf(L, TTrue);
446  else {
447    TTree *tree, *nd;
448    if (n > 0)
449      tree = nd = newtree(L, 2 * n - 1);
450    else {  /* negative: code it as !(-n) */
451      n = -n;
452      tree = newtree(L, 2 * n);
453      tree->tag = TNot;
454      nd = sib1(tree);
455    }
456    fillseq(nd, TAny, n, NULL);  /* sequence of 'n' any's */
457    return tree;
458  }
459}
460
461
462/*
463** Convert value at index 'idx' to a pattern
464*/
465static TTree *getpatt (lua_State *L, int idx, int *len) {
466  TTree *tree;
467  switch (lua_type(L, idx)) {
468    case LUA_TSTRING: {
469      size_t slen;
470      const char *s = lua_tolstring(L, idx, &slen);  /* get string */
471      if (slen == 0)  /* empty? */
472        tree = newleaf(L, TTrue);  /* always match */
473      else {
474        tree = newtree(L, 2 * (slen - 1) + 1);
475        fillseq(tree, TChar, slen, s);  /* sequence of 'slen' chars */
476      }
477      break;
478    }
479    case LUA_TNUMBER: {
480      int n = lua_tointeger(L, idx);
481      tree = numtree(L, n);
482      break;
483    }
484    case LUA_TBOOLEAN: {
485      tree = (lua_toboolean(L, idx) ? newleaf(L, TTrue) : newleaf(L, TFalse));
486      break;
487    }
488    case LUA_TTABLE: {
489      tree = newgrammar(L, idx);
490      break;
491    }
492    case LUA_TFUNCTION: {
493      tree = newtree(L, 2);
494      tree->tag = TRunTime;
495      tree->key = addtonewktable(L, 0, idx);
496      sib1(tree)->tag = TTrue;
497      break;
498    }
499    default: {
500      return gettree(L, idx, len);
501    }
502  }
503  lua_replace(L, idx);  /* put new tree into 'idx' slot */
504  if (len)
505    *len = getsize(L, idx);
506  return tree;
507}
508
509
510/*
511** create a new tree, whith a new root and one sibling.
512** Sibling must be on the Lua stack, at index 1.
513*/
514static TTree *newroot1sib (lua_State *L, int tag) {
515  int s1;
516  TTree *tree1 = getpatt(L, 1, &s1);
517  TTree *tree = newtree(L, 1 + s1);  /* create new tree */
518  tree->tag = tag;
519  memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
520  copyktable(L, 1);
521  return tree;
522}
523
524
525/*
526** create a new tree, whith a new root and 2 siblings.
527** Siblings must be on the Lua stack, first one at index 1.
528*/
529static TTree *newroot2sib (lua_State *L, int tag) {
530  int s1, s2;
531  TTree *tree1 = getpatt(L, 1, &s1);
532  TTree *tree2 = getpatt(L, 2, &s2);
533  TTree *tree = newtree(L, 1 + s1 + s2);  /* create new tree */
534  tree->tag = tag;
535  tree->u.ps =  1 + s1;
536  memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
537  memcpy(sib2(tree), tree2, s2 * sizeof(TTree));
538  joinktables(L, 1, sib2(tree), 2);
539  return tree;
540}
541
542
543static int lp_P (lua_State *L) {
544  luaL_checkany(L, 1);
545  getpatt(L, 1, NULL);
546  lua_settop(L, 1);
547  return 1;
548}
549
550
551/*
552** sequence operator; optimizations:
553** false x => false, x true => x, true x => x
554** (cannot do x . false => false because x may have runtime captures)
555*/
556static int lp_seq (lua_State *L) {
557  TTree *tree1 = getpatt(L, 1, NULL);
558  TTree *tree2 = getpatt(L, 2, NULL);
559  if (tree1->tag == TFalse || tree2->tag == TTrue)
560    lua_pushvalue(L, 1);  /* false . x == false, x . true = x */
561  else if (tree1->tag == TTrue)
562    lua_pushvalue(L, 2);  /* true . x = x */
563  else
564    newroot2sib(L, TSeq);
565  return 1;
566}
567
568
569/*
570** choice operator; optimizations:
571** charset / charset => charset
572** true / x => true, x / false => x, false / x => x
573** (x / true is not equivalent to true)
574*/
575static int lp_choice (lua_State *L) {
576  Charset st1, st2;
577  TTree *t1 = getpatt(L, 1, NULL);
578  TTree *t2 = getpatt(L, 2, NULL);
579  if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
580    loopset(i, st1.cs[i] |= st2.cs[i]);
581    newcharset(L, st1.cs);
582  }
583  else if (nofail(t1) || t2->tag == TFalse)
584    lua_pushvalue(L, 1);  /* true / x => true, x / false => x */
585  else if (t1->tag == TFalse)
586    lua_pushvalue(L, 2);  /* false / x => x */
587  else
588    newroot2sib(L, TChoice);
589  return 1;
590}
591
592
593/*
594** p^n
595*/
596static int lp_star (lua_State *L) {
597  int size1;
598  int n = (int)luaL_checkinteger(L, 2);
599  TTree *tree1 = getpatt(L, 1, &size1);
600  if (n >= 0) {  /* seq tree1 (seq tree1 ... (seq tree1 (rep tree1))) */
601    TTree *tree = newtree(L, (n + 1) * (size1 + 1));
602    if (nullable(tree1))
603      luaL_error(L, "loop body may accept empty string");
604    while (n--)  /* repeat 'n' times */
605      tree = seqaux(tree, tree1, size1);
606    tree->tag = TRep;
607    memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
608  }
609  else {  /* choice (seq tree1 ... choice tree1 true ...) true */
610    TTree *tree;
611    n = -n;
612    /* size = (choice + seq + tree1 + true) * n, but the last has no seq */
613    tree = newtree(L, n * (size1 + 3) - 1);
614    for (; n > 1; n--) {  /* repeat (n - 1) times */
615      tree->tag = TChoice; tree->u.ps = n * (size1 + 3) - 2;
616      sib2(tree)->tag = TTrue;
617      tree = sib1(tree);
618      tree = seqaux(tree, tree1, size1);
619    }
620    tree->tag = TChoice; tree->u.ps = size1 + 1;
621    sib2(tree)->tag = TTrue;
622    memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
623  }
624  copyktable(L, 1);
625  return 1;
626}
627
628
629/*
630** #p == &p
631*/
632static int lp_and (lua_State *L) {
633  newroot1sib(L, TAnd);
634  return 1;
635}
636
637
638/*
639** -p == !p
640*/
641static int lp_not (lua_State *L) {
642  newroot1sib(L, TNot);
643  return 1;
644}
645
646
647/*
648** [t1 - t2] == Seq (Not t2) t1
649** If t1 and t2 are charsets, make their difference.
650*/
651static int lp_sub (lua_State *L) {
652  Charset st1, st2;
653  int s1, s2;
654  TTree *t1 = getpatt(L, 1, &s1);
655  TTree *t2 = getpatt(L, 2, &s2);
656  if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
657    loopset(i, st1.cs[i] &= ~st2.cs[i]);
658    newcharset(L, st1.cs);
659  }
660  else {
661    TTree *tree = newtree(L, 2 + s1 + s2);
662    tree->tag = TSeq;  /* sequence of... */
663    tree->u.ps =  2 + s2;
664    sib1(tree)->tag = TNot;  /* ...not... */
665    memcpy(sib1(sib1(tree)), t2, s2 * sizeof(TTree));  /* ...t2 */
666    memcpy(sib2(tree), t1, s1 * sizeof(TTree));  /* ... and t1 */
667    joinktables(L, 1, sib1(tree), 2);
668  }
669  return 1;
670}
671
672
673static int lp_set (lua_State *L) {
674  size_t l;
675  const char *s = luaL_checklstring(L, 1, &l);
676  byte buff[CHARSETSIZE];
677  clearset(buff);
678  while (l--) {
679    setchar(buff, (byte)(*s));
680    s++;
681  }
682  newcharset(L, buff);
683  return 1;
684}
685
686
687static int lp_range (lua_State *L) {
688  int arg;
689  int top = lua_gettop(L);
690  byte buff[CHARSETSIZE];
691  clearset(buff);
692  for (arg = 1; arg <= top; arg++) {
693    int c;
694    size_t l;
695    const char *r = luaL_checklstring(L, arg, &l);
696    luaL_argcheck(L, l == 2, arg, "range must have two characters");
697    for (c = (byte)r[0]; c <= (byte)r[1]; c++)
698      setchar(buff, c);
699  }
700  newcharset(L, buff);
701  return 1;
702}
703
704
705/*
706** Fills a tree node with basic information about the UTF-8 code point
707** 'cpu': its value in 'n', its length in 'cap', and its first byte in
708** 'key'
709*/
710static void codeutftree (lua_State *L, TTree *t, lua_Unsigned cpu, int arg) {
711  int len, fb, cp;
712  cp = (int)cpu;
713  if (cp <= 0x7f) {  /* one byte? */
714    len = 1;
715    fb = cp;
716  } else if (cp <= 0x7ff) {
717    len = 2;
718    fb = 0xC0 | (cp >> 6);
719  } else if (cp <= 0xffff) {
720    len = 3;
721    fb = 0xE0 | (cp >> 12);
722  }
723  else {
724    luaL_argcheck(L, cpu <= 0x10ffffu, arg, "invalid code point");
725    len = 4;
726    fb = 0xF0 | (cp >> 18);
727  }
728  t->u.n = cp;
729  t->cap = len;
730  t->key = fb;
731}
732
733
734static int lp_utfr (lua_State *L) {
735  lua_Unsigned from = (lua_Unsigned)luaL_checkinteger(L, 1);
736  lua_Unsigned to = (lua_Unsigned)luaL_checkinteger(L, 2);
737  luaL_argcheck(L, from <= to, 2, "empty range");
738  if (to <= 0x7f) {  /* ascii range? */
739    uint f;
740    byte buff[CHARSETSIZE];  /* code it as a regular charset */
741    clearset(buff);
742    for (f = (int)from; f <= to; f++)
743      setchar(buff, f);
744    newcharset(L, buff);
745  }
746  else {  /* multi-byte utf-8 range */
747    TTree *tree = newtree(L, 2);
748    tree->tag = TUTFR;
749    codeutftree(L, tree, from, 1);
750    sib1(tree)->tag = TXInfo;
751    codeutftree(L, sib1(tree), to, 2);
752  }
753  return 1;
754}
755
756
757/*
758** Look-behind predicate
759*/
760static int lp_behind (lua_State *L) {
761  TTree *tree;
762  TTree *tree1 = getpatt(L, 1, NULL);
763  int n = fixedlen(tree1);
764  luaL_argcheck(L, n >= 0, 1, "pattern may not have fixed length");
765  luaL_argcheck(L, !hascaptures(tree1), 1, "pattern have captures");
766  luaL_argcheck(L, n <= MAXBEHIND, 1, "pattern too long to look behind");
767  tree = newroot1sib(L, TBehind);
768  tree->u.n = n;
769  return 1;
770}
771
772
773/*
774** Create a non-terminal
775*/
776static int lp_V (lua_State *L) {
777  TTree *tree = newleaf(L, TOpenCall);
778  luaL_argcheck(L, !lua_isnoneornil(L, 1), 1, "non-nil value expected");
779  tree->key = addtonewktable(L, 0, 1);
780  return 1;
781}
782
783
784/*
785** Create a tree for a non-empty capture, with a body and
786** optionally with an associated Lua value (at index 'labelidx' in the
787** stack)
788*/
789static int capture_aux (lua_State *L, int cap, int labelidx) {
790  TTree *tree = newroot1sib(L, TCapture);
791  tree->cap = cap;
792  tree->key = (labelidx == 0) ? 0 : addtonewktable(L, 1, labelidx);
793  return 1;
794}
795
796
797/*
798** Fill a tree with an empty capture, using an empty (TTrue) sibling.
799** (The 'key' field must be filled by the caller to finish the tree.)
800*/
801static TTree *auxemptycap (TTree *tree, int cap) {
802  tree->tag = TCapture;
803  tree->cap = cap;
804  sib1(tree)->tag = TTrue;
805  return tree;
806}
807
808
809/*
810** Create a tree for an empty capture.
811*/
812static TTree *newemptycap (lua_State *L, int cap, int key) {
813  TTree *tree = auxemptycap(newtree(L, 2), cap);
814  tree->key = key;
815  return tree;
816}
817
818
819/*
820** Create a tree for an empty capture with an associated Lua value.
821*/
822static TTree *newemptycapkey (lua_State *L, int cap, int idx) {
823  TTree *tree = auxemptycap(newtree(L, 2), cap);
824  tree->key = addtonewktable(L, 0, idx);
825  return tree;
826}
827
828
829/*
830** Captures with syntax p / v
831** (function capture, query capture, string capture, or number capture)
832*/
833static int lp_divcapture (lua_State *L) {
834  switch (lua_type(L, 2)) {
835    case LUA_TFUNCTION: return capture_aux(L, Cfunction, 2);
836    case LUA_TTABLE: return capture_aux(L, Cquery, 2);
837    case LUA_TSTRING: return capture_aux(L, Cstring, 2);
838    case LUA_TNUMBER: {
839      int n = lua_tointeger(L, 2);
840      TTree *tree = newroot1sib(L, TCapture);
841      luaL_argcheck(L, 0 <= n && n <= SHRT_MAX, 1, "invalid number");
842      tree->cap = Cnum;
843      tree->key = n;
844      return 1;
845    }
846    default:
847      return luaL_error(L, "unexpected %s as 2nd operand to LPeg '/'",
848                           luaL_typename(L, 2));
849  }
850}
851
852
853static int lp_acccapture (lua_State *L) {
854  return capture_aux(L, Cacc, 2);
855}
856
857
858static int lp_substcapture (lua_State *L) {
859  return capture_aux(L, Csubst, 0);
860}
861
862
863static int lp_tablecapture (lua_State *L) {
864  return capture_aux(L, Ctable, 0);
865}
866
867
868static int lp_groupcapture (lua_State *L) {
869  if (lua_isnoneornil(L, 2))
870    return capture_aux(L, Cgroup, 0);
871  else
872    return capture_aux(L, Cgroup, 2);
873}
874
875
876static int lp_foldcapture (lua_State *L) {
877  luaL_checktype(L, 2, LUA_TFUNCTION);
878  return capture_aux(L, Cfold, 2);
879}
880
881
882static int lp_simplecapture (lua_State *L) {
883  return capture_aux(L, Csimple, 0);
884}
885
886
887static int lp_poscapture (lua_State *L) {
888  newemptycap(L, Cposition, 0);
889  return 1;
890}
891
892
893static int lp_argcapture (lua_State *L) {
894  int n = (int)luaL_checkinteger(L, 1);
895  luaL_argcheck(L, 0 < n && n <= SHRT_MAX, 1, "invalid argument index");
896  newemptycap(L, Carg, n);
897  return 1;
898}
899
900
901static int lp_backref (lua_State *L) {
902  luaL_checkany(L, 1);
903  newemptycapkey(L, Cbackref, 1);
904  return 1;
905}
906
907
908/*
909** Constant capture
910*/
911static int lp_constcapture (lua_State *L) {
912  int i;
913  int n = lua_gettop(L);  /* number of values */
914  if (n == 0)  /* no values? */
915    newleaf(L, TTrue);  /* no capture */
916  else if (n == 1)
917    newemptycapkey(L, Cconst, 1);  /* single constant capture */
918  else {  /* create a group capture with all values */
919    TTree *tree = newtree(L, 1 + 3 * (n - 1) + 2);
920    newktable(L, n);  /* create a 'ktable' for new tree */
921    tree->tag = TCapture;
922    tree->cap = Cgroup;
923    tree->key = 0;
924    tree = sib1(tree);
925    for (i = 1; i <= n - 1; i++) {
926      tree->tag = TSeq;
927      tree->u.ps = 3;  /* skip TCapture and its sibling */
928      auxemptycap(sib1(tree), Cconst);
929      sib1(tree)->key = addtoktable(L, i);
930      tree = sib2(tree);
931    }
932    auxemptycap(tree, Cconst);
933    tree->key = addtoktable(L, i);
934  }
935  return 1;
936}
937
938
939static int lp_matchtime (lua_State *L) {
940  TTree *tree;
941  luaL_checktype(L, 2, LUA_TFUNCTION);
942  tree = newroot1sib(L, TRunTime);
943  tree->key = addtonewktable(L, 1, 2);
944  return 1;
945}
946
947/* }====================================================== */
948
949
950/*
951** {======================================================
952** Grammar - Tree generation
953** =======================================================
954*/
955
956/*
957** push on the stack the index and the pattern for the
958** initial rule of grammar at index 'arg' in the stack;
959** also add that index into position table.
960*/
961static void getfirstrule (lua_State *L, int arg, int postab) {
962  lua_rawgeti(L, arg, 1);  /* access first element */
963  if (lua_isstring(L, -1)) {  /* is it the name of initial rule? */
964    lua_pushvalue(L, -1);  /* duplicate it to use as key */
965    lua_gettable(L, arg);  /* get associated rule */
966  }
967  else {
968    lua_pushinteger(L, 1);  /* key for initial rule */
969    lua_insert(L, -2);  /* put it before rule */
970  }
971  if (!testpattern(L, -1)) {  /* initial rule not a pattern? */
972    if (lua_isnil(L, -1))
973      luaL_error(L, "grammar has no initial rule");
974    else
975      luaL_error(L, "initial rule '%s' is not a pattern", lua_tostring(L, -2));
976  }
977  lua_pushvalue(L, -2);  /* push key */
978  lua_pushinteger(L, 1);  /* push rule position (after TGrammar) */
979  lua_settable(L, postab);  /* insert pair at position table */
980}
981
982/*
983** traverse grammar at index 'arg', pushing all its keys and patterns
984** into the stack. Create a new table (before all pairs key-pattern) to
985** collect all keys and their associated positions in the final tree
986** (the "position table").
987** Return the number of rules and (in 'totalsize') the total size
988** for the new tree.
989*/
990static int collectrules (lua_State *L, int arg, int *totalsize) {
991  int n = 1;  /* to count number of rules */
992  int postab = lua_gettop(L) + 1;  /* index of position table */
993  int size;  /* accumulator for total size */
994  lua_newtable(L);  /* create position table */
995  getfirstrule(L, arg, postab);
996  size = 3 + getsize(L, postab + 2);  /* TGrammar + TRule + TXInfo + rule */
997  lua_pushnil(L);  /* prepare to traverse grammar table */
998  while (lua_next(L, arg) != 0) {
999    if (lua_tonumber(L, -2) == 1 ||
1000        lp_equal(L, -2, postab + 1)) {  /* initial rule? */
1001      lua_pop(L, 1);  /* remove value (keep key for lua_next) */
1002      continue;
1003    }
1004    if (!testpattern(L, -1))  /* value is not a pattern? */
1005      luaL_error(L, "rule '%s' is not a pattern", val2str(L, -2));
1006    luaL_checkstack(L, LUA_MINSTACK, "grammar has too many rules");
1007    lua_pushvalue(L, -2);  /* push key (to insert into position table) */
1008    lua_pushinteger(L, size);
1009    lua_settable(L, postab);
1010    size += 2 + getsize(L, -1);  /* add 'TRule + TXInfo + rule' to size */
1011    lua_pushvalue(L, -2);  /* push key (for next lua_next) */
1012    n++;
1013  }
1014  *totalsize = size + 1;  /* space for 'TTrue' finishing list of rules */
1015  return n;
1016}
1017
1018
1019static void buildgrammar (lua_State *L, TTree *grammar, int frule, int n) {
1020  int i;
1021  TTree *nd = sib1(grammar);  /* auxiliary pointer to traverse the tree */
1022  for (i = 0; i < n; i++) {  /* add each rule into new tree */
1023    int ridx = frule + 2*i + 1;  /* index of i-th rule */
1024    int rulesize;
1025    TTree *rn = gettree(L, ridx, &rulesize);
1026    TTree *pr = sib1(nd);  /* points to rule's prerule */
1027    nd->tag = TRule;
1028    nd->key = 0;  /* will be fixed when rule is used */
1029    pr->tag = TXInfo;
1030    pr->u.n = i;  /* rule number */
1031    nd->u.ps = rulesize + 2;  /* point to next rule */
1032    memcpy(sib1(pr), rn, rulesize * sizeof(TTree));  /* copy rule */
1033    mergektable(L, ridx, sib1(nd));  /* merge its ktable into new one */
1034    nd = sib2(nd);  /* move to next rule */
1035  }
1036  nd->tag = TTrue;  /* finish list of rules */
1037}
1038
1039
1040/*
1041** Check whether a tree has potential infinite loops
1042*/
1043static int checkloops (TTree *tree) {
1044 tailcall:
1045  if (tree->tag == TRep && nullable(sib1(tree)))
1046    return 1;
1047  else if (tree->tag == TGrammar)
1048    return 0;  /* sub-grammars already checked */
1049  else {
1050    switch (numsiblings[tree->tag]) {
1051      case 1:  /* return checkloops(sib1(tree)); */
1052        tree = sib1(tree); goto tailcall;
1053      case 2:
1054        if (checkloops(sib1(tree))) return 1;
1055        /* else return checkloops(sib2(tree)); */
1056        tree = sib2(tree); goto tailcall;
1057      default: assert(numsiblings[tree->tag] == 0); return 0;
1058    }
1059  }
1060}
1061
1062
1063/*
1064** Give appropriate error message for 'verifyrule'. If a rule appears
1065** twice in 'passed', there is path from it back to itself without
1066** advancing the subject.
1067*/
1068static int verifyerror (lua_State *L, unsigned short *passed, int npassed) {
1069  int i, j;
1070  for (i = npassed - 1; i >= 0; i--) {  /* search for a repetition */
1071    for (j = i - 1; j >= 0; j--) {
1072      if (passed[i] == passed[j]) {
1073        lua_rawgeti(L, -1, passed[i]);  /* get rule's key */
1074        return luaL_error(L, "rule '%s' may be left recursive", val2str(L, -1));
1075      }
1076    }
1077  }
1078  return luaL_error(L, "too many left calls in grammar");
1079}
1080
1081
1082/*
1083** Check whether a rule can be left recursive; raise an error in that
1084** case; otherwise return 1 iff pattern is nullable.
1085** The return value is used to check sequences, where the second pattern
1086** is only relevant if the first is nullable.
1087** Parameter 'nb' works as an accumulator, to allow tail calls in
1088** choices. ('nb' true makes function returns true.)
1089** Parameter 'passed' is a list of already visited rules, 'npassed'
1090** counts the elements in 'passed'.
1091** Assume ktable at the top of the stack.
1092*/
1093static int verifyrule (lua_State *L, TTree *tree, unsigned short *passed,
1094                                     int npassed, int nb) {
1095 tailcall:
1096  switch (tree->tag) {
1097    case TChar: case TSet: case TAny:
1098    case TFalse: case TUTFR:
1099      return nb;  /* cannot pass from here */
1100    case TTrue:
1101    case TBehind:  /* look-behind cannot have calls */
1102      return 1;
1103    case TNot: case TAnd: case TRep:
1104      /* return verifyrule(L, sib1(tree), passed, npassed, 1); */
1105      tree = sib1(tree); nb = 1; goto tailcall;
1106    case TCapture: case TRunTime: case TXInfo:
1107      /* return verifyrule(L, sib1(tree), passed, npassed, nb); */
1108      tree = sib1(tree); goto tailcall;
1109    case TCall:
1110      /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
1111      tree = sib2(tree); goto tailcall;
1112    case TSeq:  /* only check 2nd child if first is nb */
1113      if (!verifyrule(L, sib1(tree), passed, npassed, 0))
1114        return nb;
1115      /* else return verifyrule(L, sib2(tree), passed, npassed, nb); */
1116      tree = sib2(tree); goto tailcall;
1117    case TChoice:  /* must check both children */
1118      nb = verifyrule(L, sib1(tree), passed, npassed, nb);
1119      /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
1120      tree = sib2(tree); goto tailcall;
1121    case TRule:
1122      if (npassed >= MAXRULES)  /* too many steps? */
1123        return verifyerror(L, passed, npassed);  /* error */
1124      else {
1125        passed[npassed++] = tree->key;  /* add rule to path */
1126        /* return verifyrule(L, sib1(tree), passed, npassed); */
1127        tree = sib1(tree); goto tailcall;
1128      }
1129    case TGrammar:
1130      return nullable(tree);  /* sub-grammar cannot be left recursive */
1131    default: assert(0); return 0;
1132  }
1133}
1134
1135
1136static void verifygrammar (lua_State *L, TTree *grammar) {
1137  unsigned short passed[MAXRULES];
1138  TTree *rule;
1139  /* check left-recursive rules */
1140  for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
1141    if (rule->key == 0) continue;  /* unused rule */
1142    verifyrule(L, sib1(rule), passed, 0, 0);
1143  }
1144  assert(rule->tag == TTrue);
1145  /* check infinite loops inside rules */
1146  for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
1147    if (rule->key == 0) continue;  /* unused rule */
1148    if (checkloops(sib1(rule))) {
1149      lua_rawgeti(L, -1, rule->key);  /* get rule's key */
1150      luaL_error(L, "empty loop in rule '%s'", val2str(L, -1));
1151    }
1152  }
1153  assert(rule->tag == TTrue);
1154}
1155
1156
1157/*
1158** Give a name for the initial rule if it is not referenced
1159*/
1160static void initialrulename (lua_State *L, TTree *grammar, int frule) {
1161  if (sib1(grammar)->key == 0) {  /* initial rule is not referenced? */
1162    int n = lua_rawlen(L, -1) + 1;  /* index for name */
1163    lua_pushvalue(L, frule);  /* rule's name */
1164    lua_rawseti(L, -2, n);  /* ktable was on the top of the stack */
1165    sib1(grammar)->key = n;
1166  }
1167}
1168
1169
1170static TTree *newgrammar (lua_State *L, int arg) {
1171  int treesize;
1172  int frule = lua_gettop(L) + 2;  /* position of first rule's key */
1173  int n = collectrules(L, arg, &treesize);
1174  TTree *g = newtree(L, treesize);
1175  luaL_argcheck(L, n <= MAXRULES, arg, "grammar has too many rules");
1176  g->tag = TGrammar;  g->u.n = n;
1177  lua_newtable(L);  /* create 'ktable' */
1178  lua_setuservalue(L, -2);
1179  buildgrammar(L, g, frule, n);
1180  lua_getuservalue(L, -1);  /* get 'ktable' for new tree */
1181  finalfix(L, frule - 1, g, sib1(g));
1182  initialrulename(L, g, frule);
1183  verifygrammar(L, g);
1184  lua_pop(L, 1);  /* remove 'ktable' */
1185  lua_insert(L, -(n * 2 + 2));  /* move new table to proper position */
1186  lua_pop(L, n * 2 + 1);  /* remove position table + rule pairs */
1187  return g;  /* new table at the top of the stack */
1188}
1189
1190/* }====================================================== */
1191
1192
1193static Instruction *prepcompile (lua_State *L, Pattern *p, int idx) {
1194  lua_getuservalue(L, idx);  /* push 'ktable' (may be used by 'finalfix') */
1195  finalfix(L, 0, NULL, p->tree);
1196  lua_pop(L, 1);  /* remove 'ktable' */
1197  return compile(L, p, getsize(L, idx));
1198}
1199
1200
1201static int lp_printtree (lua_State *L) {
1202  TTree *tree = getpatt(L, 1, NULL);
1203  int c = lua_toboolean(L, 2);
1204  if (c) {
1205    lua_getuservalue(L, 1);  /* push 'ktable' (may be used by 'finalfix') */
1206    finalfix(L, 0, NULL, tree);
1207    lua_pop(L, 1);  /* remove 'ktable' */
1208  }
1209  printktable(L, 1);
1210  printtree(tree, 0);
1211  return 0;
1212}
1213
1214
1215static int lp_printcode (lua_State *L) {
1216  Pattern *p = getpattern(L, 1);
1217  printktable(L, 1);
1218  if (p->code == NULL)  /* not compiled yet? */
1219    prepcompile(L, p, 1);
1220  printpatt(p->code);
1221  return 0;
1222}
1223
1224
1225/*
1226** Get the initial position for the match, interpreting negative
1227** values from the end of the subject
1228*/
1229static size_t initposition (lua_State *L, size_t len) {
1230  lua_Integer ii = luaL_optinteger(L, 3, 1);
1231  if (ii > 0) {  /* positive index? */
1232    if ((size_t)ii <= len)  /* inside the string? */
1233      return (size_t)ii - 1;  /* return it (corrected to 0-base) */
1234    else return len;  /* crop at the end */
1235  }
1236  else {  /* negative index */
1237    if ((size_t)(-ii) <= len)  /* inside the string? */
1238      return len - ((size_t)(-ii));  /* return position from the end */
1239    else return 0;  /* crop at the beginning */
1240  }
1241}
1242
1243
1244/*
1245** Main match function
1246*/
1247static int lp_match (lua_State *L) {
1248  Capture capture[INITCAPSIZE];
1249  const char *r;
1250  size_t l;
1251  Pattern *p = (getpatt(L, 1, NULL), getpattern(L, 1));
1252  Instruction *code = (p->code != NULL) ? p->code : prepcompile(L, p, 1);
1253  const char *s = luaL_checklstring(L, SUBJIDX, &l);
1254  size_t i = initposition(L, l);
1255  int ptop = lua_gettop(L);
1256  luaL_argcheck(L, l < MAXINDT, SUBJIDX, "subject too long");
1257  lua_pushnil(L);  /* initialize subscache */
1258  lua_pushlightuserdata(L, capture);  /* initialize caplistidx */
1259  lua_getuservalue(L, 1);  /* initialize ktableidx */
1260  r = match(L, s, s + i, s + l, code, capture, ptop);
1261  if (r == NULL) {
1262    lua_pushnil(L);
1263    return 1;
1264  }
1265  return getcaptures(L, s, r, ptop);
1266}
1267
1268
1269
1270/*
1271** {======================================================
1272** Library creation and functions not related to matching
1273** =======================================================
1274*/
1275
1276/* maximum limit for stack size */
1277#define MAXLIM		(INT_MAX / 100)
1278
1279static int lp_setmax (lua_State *L) {
1280  lua_Integer lim = luaL_checkinteger(L, 1);
1281  luaL_argcheck(L, 0 < lim && lim <= MAXLIM, 1, "out of range");
1282  lua_settop(L, 1);
1283  lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
1284  return 0;
1285}
1286
1287
1288static int lp_type (lua_State *L) {
1289  if (testpattern(L, 1))
1290    lua_pushliteral(L, "pattern");
1291  else
1292    lua_pushnil(L);
1293  return 1;
1294}
1295
1296
1297int lp_gc (lua_State *L) {
1298  Pattern *p = getpattern(L, 1);
1299  freecode(L, p);  /* delete code block */
1300  return 0;
1301}
1302
1303
1304/*
1305** Create a charset representing a category of characters, given by
1306** the predicate 'catf'.
1307*/
1308static void createcat (lua_State *L, const char *catname, int (catf) (int)) {
1309  int c;
1310  byte buff[CHARSETSIZE];
1311  clearset(buff);
1312  for (c = 0; c <= UCHAR_MAX; c++)
1313    if (catf(c)) setchar(buff, c);
1314  newcharset(L, buff);
1315  lua_setfield(L, -2, catname);
1316}
1317
1318
1319static int lp_locale (lua_State *L) {
1320  if (lua_isnoneornil(L, 1)) {
1321    lua_settop(L, 0);
1322    lua_createtable(L, 0, 12);
1323  }
1324  else {
1325    luaL_checktype(L, 1, LUA_TTABLE);
1326    lua_settop(L, 1);
1327  }
1328  createcat(L, "alnum", isalnum);
1329  createcat(L, "alpha", isalpha);
1330  createcat(L, "cntrl", iscntrl);
1331  createcat(L, "digit", isdigit);
1332  createcat(L, "graph", isgraph);
1333  createcat(L, "lower", islower);
1334  createcat(L, "print", isprint);
1335  createcat(L, "punct", ispunct);
1336  createcat(L, "space", isspace);
1337  createcat(L, "upper", isupper);
1338  createcat(L, "xdigit", isxdigit);
1339  return 1;
1340}
1341
1342
1343static struct luaL_Reg pattreg[] = {
1344  {"ptree", lp_printtree},
1345  {"pcode", lp_printcode},
1346  {"match", lp_match},
1347  {"B", lp_behind},
1348  {"V", lp_V},
1349  {"C", lp_simplecapture},
1350  {"Cc", lp_constcapture},
1351  {"Cmt", lp_matchtime},
1352  {"Cb", lp_backref},
1353  {"Carg", lp_argcapture},
1354  {"Cp", lp_poscapture},
1355  {"Cs", lp_substcapture},
1356  {"Ct", lp_tablecapture},
1357  {"Cf", lp_foldcapture},
1358  {"Cg", lp_groupcapture},
1359  {"P", lp_P},
1360  {"S", lp_set},
1361  {"R", lp_range},
1362  {"utfR", lp_utfr},
1363  {"locale", lp_locale},
1364  {"version", NULL},
1365  {"setmaxstack", lp_setmax},
1366  {"type", lp_type},
1367  {NULL, NULL}
1368};
1369
1370
1371static struct luaL_Reg metareg[] = {
1372  {"__mul", lp_seq},
1373  {"__add", lp_choice},
1374  {"__pow", lp_star},
1375  {"__gc", lp_gc},
1376  {"__len", lp_and},
1377  {"__div", lp_divcapture},
1378  {"__mod", lp_acccapture},
1379  {"__unm", lp_not},
1380  {"__sub", lp_sub},
1381  {NULL, NULL}
1382};
1383
1384
1385int luaopen_lpeg (lua_State *L);
1386int luaopen_lpeg (lua_State *L) {
1387  luaL_newmetatable(L, PATTERN_T);
1388  lua_pushnumber(L, MAXBACK);  /* initialize maximum backtracking */
1389  lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
1390  luaL_setfuncs(L, metareg, 0);
1391  luaL_register(L, "lpeg", pattreg); // Nvim: inline conflicting luaL_newlib macro
1392  lua_pushvalue(L, -1);
1393  lua_setfield(L, -3, "__index");
1394  lua_pushliteral(L, "LPeg " VERSION);
1395  lua_setfield(L, -2, "version");
1396  return 1;
1397}
1398
1399/* }====================================================== */