robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
14.5 KiB455 linesraw
1
2#include <limits.h>
3#include <string.h>
4
5
6#include "lua.h"
7#include "lauxlib.h"
8
9#include "lpcap.h"
10#include "lptypes.h"
11#include "lpvm.h"
12#include "lpprint.h"
13
14
15/* initial size for call/backtrack stack */
16#if !defined(INITBACK)
17#define INITBACK	MAXBACK
18#endif
19
20
21#define getoffset(p)	(((p) + 1)->offset)
22
23static const Instruction giveup = {{IGiveup, 0, {0}}};
24
25
26int charinset (const Instruction *i, const byte *buff, uint c) {
27  c -= i->i.aux2.set.offset;
28  if (c >= ((uint)i->i.aux2.set.size  /* size in instructions... */
29           * (uint)sizeof(Instruction)  /* in bytes... */
30           * 8u))  /* in bits */
31    return i->i.aux1;  /* out of range; return default value */
32  return testchar(buff, c);
33}
34
35
36/*
37** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
38*/
39static const char *utf8_decode (const char *o, int *val) {
40  static const uint limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFFu};
41  const unsigned char *s = (const unsigned char *)o;
42  uint c = s[0];  /* first byte */
43  uint res = 0;  /* final result */
44  if (c < 0x80)  /* ascii? */
45    res = c;
46  else {
47    int count = 0;  /* to count number of continuation bytes */
48    while (c & 0x40) {  /* still have continuation bytes? */
49      int cc = s[++count];  /* read next byte */
50      if ((cc & 0xC0) != 0x80)  /* not a continuation byte? */
51        return NULL;  /* invalid byte sequence */
52      res = (res << 6) | (cc & 0x3F);  /* add lower 6 bits from cont. byte */
53      c <<= 1;  /* to test next bit */
54    }
55    res |= (c & 0x7F) << (count * 5);  /* add first byte */
56    if (count > 3 || res > 0x10FFFFu || res <= limits[count])
57      return NULL;  /* invalid byte sequence */
58    s += count;  /* skip continuation bytes read */
59  }
60  *val = res;
61  return (const char *)s + 1;  /* +1 to include first byte */
62}
63
64
65/*
66** {======================================================
67** Virtual Machine
68** =======================================================
69*/
70
71
72typedef struct Stack {
73  const char *s;  /* saved position (or NULL for calls) */
74  const Instruction *p;  /* next instruction */
75  int caplevel;
76} Stack;
77
78
79#define getstackbase(L, ptop)	((Stack *)lua_touserdata(L, stackidx(ptop)))
80
81
82/*
83** Ensures the size of array 'capture' (with size '*capsize' and
84** 'captop' elements being used) is enough to accomodate 'n' extra
85** elements plus one.  (Because several opcodes add stuff to the capture
86** array, it is simpler to ensure the array always has at least one free
87** slot upfront and check its size later.)
88*/
89
90/* new size in number of elements cannot overflow integers, and new
91   size in bytes cannot overflow size_t. */
92#define MAXNEWSIZE  \
93    (((size_t)INT_MAX) <= (~(size_t)0 / sizeof(Capture)) ?  \
94     ((size_t)INT_MAX) : (~(size_t)0 / sizeof(Capture)))
95
96static Capture *growcap (lua_State *L, Capture *capture, int *capsize,
97                                       int captop, int n, int ptop) {
98  if (*capsize - captop > n)
99    return capture;  /* no need to grow array */
100  else {  /* must grow */
101    Capture *newc;
102    uint newsize = captop + n + 1;  /* minimum size needed */
103    if (newsize < (MAXNEWSIZE / 3) * 2)
104      newsize += newsize / 2;  /* 1.5 that size, if not too big */
105    else if (newsize < (MAXNEWSIZE / 9) * 8)
106      newsize += newsize / 8;  /* else, try 9/8 that size */
107    else
108      luaL_error(L, "too many captures");
109    newc = (Capture *)lua_newuserdata(L, newsize * sizeof(Capture));
110    memcpy(newc, capture, captop * sizeof(Capture));
111    *capsize = newsize;
112    lua_replace(L, caplistidx(ptop));
113    return newc;
114  }
115}
116
117
118/*
119** Double the size of the stack
120*/
121static Stack *doublestack (lua_State *L, Stack **stacklimit, int ptop) {
122  Stack *stack = getstackbase(L, ptop);
123  Stack *newstack;
124  int n = *stacklimit - stack;  /* current stack size */
125  int max, newn;
126  lua_getfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
127  max = lua_tointeger(L, -1);  /* maximum allowed size */
128  lua_pop(L, 1);
129  if (n >= max)  /* already at maximum size? */
130    luaL_error(L, "backtrack stack overflow (current limit is %d)", max);
131  newn = 2 * n;  /* new size */
132  if (newn > max) newn = max;
133  newstack = (Stack *)lua_newuserdata(L, newn * sizeof(Stack));
134  memcpy(newstack, stack, n * sizeof(Stack));
135  lua_replace(L, stackidx(ptop));
136  *stacklimit = newstack + newn;
137  return newstack + n;  /* return next position */
138}
139
140
141/*
142** Interpret the result of a dynamic capture: false -> fail;
143** true -> keep current position; number -> next position.
144** Return new subject position. 'fr' is stack index where
145** is the result; 'curr' is current subject position; 'limit'
146** is subject's size.
147*/
148static int resdyncaptures (lua_State *L, int fr, int curr, int limit) {
149  lua_Integer res;
150  if (!lua_toboolean(L, fr)) {  /* false value? */
151    lua_settop(L, fr - 1);  /* remove results */
152    return -1;  /* and fail */
153  }
154  else if (lua_isboolean(L, fr))  /* true? */
155    res = curr;  /* keep current position */
156  else {
157    res = lua_tointeger(L, fr) - 1;  /* new position */
158    if (res < curr || res > limit)
159      luaL_error(L, "invalid position returned by match-time capture");
160  }
161  lua_remove(L, fr);  /* remove first result (offset) */
162  return res;
163}
164
165
166/*
167** Add capture values returned by a dynamic capture to the list
168** 'capture', nested inside a group. 'fd' indexes the first capture
169** value, 'n' is the number of values (at least 1). The open group
170** capture is already in 'capture', before the place for the new entries.
171*/
172static void adddyncaptures (Index_t index, Capture *capture, int n, int fd) {
173  int i;
174  assert(capture[-1].kind == Cgroup && capture[-1].siz == 0);
175  capture[-1].idx = 0;  /* make group capture an anonymous group */
176  for (i = 0; i < n; i++) {  /* add runtime captures */
177    capture[i].kind = Cruntime;
178    capture[i].siz = 1;  /* mark it as closed */
179    capture[i].idx = fd + i;  /* stack index of capture value */
180    capture[i].index = index;
181  }
182  capture[n].kind = Cclose;  /* close group */
183  capture[n].siz = 1;
184  capture[n].index = index;
185}
186
187
188/*
189** Remove dynamic captures from the Lua stack (called in case of failure)
190*/
191static int removedyncap (lua_State *L, Capture *capture,
192                         int level, int last) {
193  int id = finddyncap(capture + level, capture + last);  /* index of 1st cap. */
194  int top = lua_gettop(L);
195  if (id == 0) return 0;  /* no dynamic captures? */
196  lua_settop(L, id - 1);  /* remove captures */
197  return top - id + 1;  /* number of values removed */
198}
199
200
201/*
202** Find the corresponding 'open' capture before 'cap', when that capture
203** can become a full capture. If a full capture c1 is followed by an
204** empty capture c2, there is no way to know whether c2 is inside
205** c1. So, full captures can enclose only captures that start *before*
206** its end.
207*/
208static Capture *findopen (Capture *cap, Index_t currindex) {
209  int i;
210  cap--;  /* check last capture */
211  /* Must it be inside current one, but starts where current one ends? */
212  if (!isopencap(cap) && cap->index == currindex)
213    return NULL;  /* current one cannot be a full capture */
214  /* else, look for an 'open' capture */
215  for (i = 0; i < MAXLOP; i++, cap--) {
216    if (currindex - cap->index >= UCHAR_MAX)
217      return NULL;  /* capture too long for a full capture */
218    else if (isopencap(cap))  /* open capture? */
219      return cap;  /* that's the one to be closed */
220    else if (cap->kind == Cclose)
221      return NULL;  /* a full capture should not nest a non-full one */
222  }
223  return NULL;  /* not found within allowed search limit */
224}
225
226
227/*
228** Opcode interpreter
229*/
230const char *match (lua_State *L, const char *o, const char *s, const char *e,
231                   Instruction *op, Capture *capture, int ptop) {
232  Stack stackbase[INITBACK];
233  Stack *stacklimit = stackbase + INITBACK;
234  Stack *stack = stackbase;  /* point to first empty slot in stack */
235  int capsize = INITCAPSIZE;
236  int captop = 0;  /* point to first empty slot in captures */
237  int ndyncap = 0;  /* number of dynamic captures (in Lua stack) */
238  const Instruction *p = op;  /* current instruction */
239  stack->p = &giveup; stack->s = s; stack->caplevel = 0; stack++;
240  lua_pushlightuserdata(L, stackbase);
241  for (;;) {
242#if defined(DEBUG)
243      printf("-------------------------------------\n");
244      printcaplist(capture, capture + captop);
245      printf("s: |%s| stck:%d, dyncaps:%d, caps:%d  ",
246             s, (int)(stack - getstackbase(L, ptop)), ndyncap, captop);
247      printinst(op, p);
248#endif
249    assert(stackidx(ptop) + ndyncap == lua_gettop(L) && ndyncap <= captop);
250    switch ((Opcode)p->i.code) {
251      case IEnd: {
252        assert(stack == getstackbase(L, ptop) + 1);
253        capture[captop].kind = Cclose;
254        capture[captop].index = MAXINDT;
255        return s;
256      }
257      case IGiveup: {
258        assert(stack == getstackbase(L, ptop));
259        return NULL;
260      }
261      case IRet: {
262        assert(stack > getstackbase(L, ptop) && (stack - 1)->s == NULL);
263        p = (--stack)->p;
264        continue;
265      }
266      case IAny: {
267        if (s < e) { p++; s++; }
268        else goto fail;
269        continue;
270      }
271      case IUTFR: {
272        int codepoint;
273        if (s >= e)
274          goto fail;
275        s = utf8_decode (s, &codepoint);
276        if (s && p[1].offset <= codepoint && codepoint <= utf_to(p))
277          p += 2;
278        else
279          goto fail;
280        continue;
281      }
282      case ITestAny: {
283        if (s < e) p += 2;
284        else p += getoffset(p);
285        continue;
286      }
287      case IChar: {
288        if ((byte)*s == p->i.aux1 && s < e) { p++; s++; }
289        else goto fail;
290        continue;
291      }
292      case ITestChar: {
293        if ((byte)*s == p->i.aux1 && s < e) p += 2;
294        else p += getoffset(p);
295        continue;
296      }
297      case ISet: {
298        uint c = (byte)*s;
299        if (charinset(p, (p+1)->buff, c) && s < e)
300          { p += 1 + p->i.aux2.set.size; s++; }
301        else goto fail;
302        continue;
303      }
304      case ITestSet: {
305        uint c = (byte)*s;
306        if (charinset(p, (p + 2)->buff, c) && s < e)
307          p += 2 + p->i.aux2.set.size;
308        else p += getoffset(p);
309        continue;
310      }
311      case IBehind: {
312        int n = p->i.aux1;
313        if (n > s - o) goto fail;
314        s -= n; p++;
315        continue;
316      }
317      case ISpan: {
318        for (; s < e; s++) {
319          uint c = (byte)*s;
320          if (!charinset(p, (p+1)->buff, c)) break;
321        }
322        p += 1 + p->i.aux2.set.size;
323        continue;
324      }
325      case IJmp: {
326        p += getoffset(p);
327        continue;
328      }
329      case IChoice: {
330        if (stack == stacklimit)
331          stack = doublestack(L, &stacklimit, ptop);
332        stack->p = p + getoffset(p);
333        stack->s = s;
334        stack->caplevel = captop;
335        stack++;
336        p += 2;
337        continue;
338      }
339      case ICall: {
340        if (stack == stacklimit)
341          stack = doublestack(L, &stacklimit, ptop);
342        stack->s = NULL;
343        stack->p = p + 2;  /* save return address */
344        stack++;
345        p += getoffset(p);
346        continue;
347      }
348      case ICommit: {
349        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
350        stack--;
351        p += getoffset(p);
352        continue;
353      }
354      case IPartialCommit: {
355        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
356        (stack - 1)->s = s;
357        (stack - 1)->caplevel = captop;
358        p += getoffset(p);
359        continue;
360      }
361      case IBackCommit: {
362        assert(stack > getstackbase(L, ptop) && (stack - 1)->s != NULL);
363        s = (--stack)->s;
364        if (ndyncap > 0)  /* are there matchtime captures? */
365          ndyncap -= removedyncap(L, capture, stack->caplevel, captop);
366        captop = stack->caplevel;
367        p += getoffset(p);
368        continue;
369      }
370      case IFailTwice:
371        assert(stack > getstackbase(L, ptop));
372        stack--;
373        /* FALLTHROUGH */
374      case IFail:
375      fail: { /* pattern failed: try to backtrack */
376        do {  /* remove pending calls */
377          assert(stack > getstackbase(L, ptop));
378          s = (--stack)->s;
379        } while (s == NULL);
380        if (ndyncap > 0)  /* is there matchtime captures? */
381          ndyncap -= removedyncap(L, capture, stack->caplevel, captop);
382        captop = stack->caplevel;
383        p = stack->p;
384#if defined(DEBUG)
385        printf("**FAIL**\n");
386#endif
387        continue;
388      }
389      case ICloseRunTime: {
390        CapState cs;
391        int rem, res, n;
392        int fr = lua_gettop(L) + 1;  /* stack index of first result */
393        cs.reclevel = 0; cs.L = L;
394        cs.s = o; cs.ocap = capture; cs.ptop = ptop;
395        n = runtimecap(&cs, capture + captop, s, &rem);  /* call function */
396        captop -= n;  /* remove nested captures */
397        ndyncap -= rem;  /* update number of dynamic captures */
398        fr -= rem;  /* 'rem' items were popped from Lua stack */
399        res = resdyncaptures(L, fr, s - o, e - o);  /* get result */
400        if (res == -1)  /* fail? */
401          goto fail;
402        s = o + res;  /* else update current position */
403        n = lua_gettop(L) - fr + 1;  /* number of new captures */
404        ndyncap += n;  /* update number of dynamic captures */
405        if (n == 0)  /* no new captures? */
406          captop--;  /* remove open group */
407        else {  /* new captures; keep original open group */
408          if (fr + n >= SHRT_MAX)
409            luaL_error(L, "too many results in match-time capture");
410          /* add new captures + close group to 'capture' list */
411          capture = growcap(L, capture, &capsize, captop, n + 1, ptop);
412          adddyncaptures(s - o, capture + captop, n, fr);
413          captop += n + 1;  /* new captures + close group */
414        }
415        p++;
416        continue;
417      }
418      case ICloseCapture: {
419        Capture *open = findopen(capture + captop, s - o);
420        assert(captop > 0);
421        if (open) {  /* if possible, turn capture into a full capture */
422          open->siz = (s - o) - open->index + 1;
423          p++;
424          continue;
425        }
426        else {  /* must create a close capture */
427          capture[captop].siz = 1;  /* mark entry as closed */
428          capture[captop].index = s - o;
429          goto pushcapture;
430        }
431      }
432      case IOpenCapture:
433        capture[captop].siz = 0;  /* mark entry as open */
434        capture[captop].index = s - o;
435        goto pushcapture;
436      case IFullCapture:
437        capture[captop].siz = getoff(p) + 1;  /* save capture size */
438        capture[captop].index = s - o - getoff(p);
439        /* goto pushcapture; */
440      pushcapture: {
441        capture[captop].idx = p->i.aux2.key;
442        capture[captop].kind = getkind(p);
443        captop++;
444        capture = growcap(L, capture, &capsize, captop, 0, ptop);
445        p++;
446        continue;
447      }
448      default: assert(0); return NULL;
449    }
450  }
451}
452
453/* }====================================================== */
454
455