robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
17.8 KiB612 linesraw
1
2#include "lua.h"
3#include "lauxlib.h"
4
5#include "lpcap.h"
6#include "lpprint.h"
7#include "lptypes.h"
8
9
10#define getfromktable(cs,v)	lua_rawgeti((cs)->L, ktableidx((cs)->ptop), v)
11
12#define pushluaval(cs)		getfromktable(cs, (cs)->cap->idx)
13
14
15
16#define skipclose(cs,head)  \
17	if (isopencap(head)) { assert(isclosecap(cs->cap)); cs->cap++; }
18
19
20/*
21** Return the size of capture 'cap'. If it is an open capture, 'close'
22** must be its corresponding close.
23*/
24static Index_t capsize (Capture *cap, Capture *close) {
25  if (isopencap(cap)) {
26    assert(isclosecap(close));
27    return close->index - cap->index;
28  }
29  else
30    return cap->siz - 1;
31}
32
33
34static Index_t closesize (CapState *cs, Capture *head) {
35  return capsize(head, cs->cap);
36}
37
38
39/*
40** Put at the cache for Lua values the value indexed by 'v' in ktable
41** of the running pattern (if it is not there yet); returns its index.
42*/
43static int updatecache (CapState *cs, int v) {
44  int idx = cs->ptop + 1;  /* stack index of cache for Lua values */
45  if (v != cs->valuecached) {  /* not there? */
46    getfromktable(cs, v);  /* get value from 'ktable' */
47    lua_replace(cs->L, idx);  /* put it at reserved stack position */
48    cs->valuecached = v;  /* keep track of what is there */
49  }
50  return idx;
51}
52
53
54static int pushcapture (CapState *cs);
55
56
57/*
58** Goes back in a list of captures looking for an open capture
59** corresponding to a close one.
60*/
61static Capture *findopen (Capture *cap) {
62  int n = 0;  /* number of closes waiting an open */
63  for (;;) {
64    cap--;
65    if (isclosecap(cap)) n++;  /* one more open to skip */
66    else if (isopencap(cap))
67      if (n-- == 0) return cap;
68  }
69}
70
71
72/*
73** Go to the next capture at the same level.
74*/
75static void nextcap (CapState *cs) {
76  Capture *cap = cs->cap;
77  if (isopencap(cap)) {  /* must look for a close? */
78    int n = 0;  /* number of opens waiting a close */
79    for (;;) {  /* look for corresponding close */
80      cap++;
81      if (isopencap(cap)) n++;
82      else if (isclosecap(cap))
83        if (n-- == 0) break;
84    }
85    cs->cap = cap + 1;  /* + 1 to skip last close */
86  }
87  else {
88    Capture *next;
89    for (next = cap + 1; capinside(cap, next); next++)
90      ;  /* skip captures inside current one */
91    cs->cap = next;
92  }
93}
94
95
96/*
97** Push on the Lua stack all values generated by nested captures inside
98** the current capture. Returns number of values pushed. 'addextra'
99** makes it push the entire match after all captured values. The
100** entire match is pushed also if there are no other nested values,
101** so the function never returns zero.
102*/
103static int pushnestedvalues (CapState *cs, int addextra) {
104  Capture *head = cs->cap++;  /* original capture */
105  int n = 0;  /* number of pushed subvalues */
106  /* repeat for all nested patterns */
107  while (capinside(head, cs->cap))
108    n += pushcapture(cs);
109  if (addextra || n == 0) {  /* need extra? */
110    lua_pushlstring(cs->L, cs->s + head->index, closesize(cs, head));
111    n++;
112  }
113  skipclose(cs, head);
114  return n;
115}
116
117
118/*
119** Push only the first value generated by nested captures
120*/
121static void pushonenestedvalue (CapState *cs) {
122  int n = pushnestedvalues(cs, 0);
123  if (n > 1)
124    lua_pop(cs->L, n - 1);  /* pop extra values */
125}
126
127
128/*
129** Checks whether group 'grp' is visible to 'ref', that is, 'grp' is
130** not nested inside a full capture that does not contain 'ref'.  (We
131** only need to care for full captures because the search at 'findback'
132** skips open-end blocks; so, if 'grp' is nested in a non-full capture,
133** 'ref' is also inside it.)  To check this, we search backward for the
134** inner full capture enclosing 'grp'.  A full capture cannot contain
135** non-full captures, so a close capture means we cannot be inside a
136** full capture anymore.
137*/
138static int capvisible (CapState *cs, Capture *grp, Capture *ref) {
139  Capture *cap = grp;
140  int i = MAXLOP;  /* maximum distance for an 'open' */
141  while (i-- > 0 && cap-- > cs->ocap) {
142    if (isclosecap(cap))
143      return 1;  /* can stop the search */
144    else if (grp->index - cap->index >= UCHAR_MAX)
145      return 1;  /* can stop the search */
146    else if (capinside(cap, grp))  /* is 'grp' inside cap? */
147      return capinside(cap, ref);  /* ok iff cap also contains 'ref' */
148  }
149  return 1;  /* 'grp' is not inside any capture */
150}
151
152
153/*
154** Try to find a named group capture with the name given at the top of
155** the stack; goes backward from 'ref'.
156*/
157static Capture *findback (CapState *cs, Capture *ref) {
158  lua_State *L = cs->L;
159  Capture *cap = ref;
160  while (cap-- > cs->ocap) {  /* repeat until end of list */
161    if (isclosecap(cap))
162      cap = findopen(cap);  /* skip nested captures */
163    else if (capinside(cap, ref))
164      continue;  /* enclosing captures are not visible to 'ref' */
165    if (captype(cap) == Cgroup && capvisible(cs, cap, ref)) {
166      getfromktable(cs, cap->idx);  /* get group name */
167      if (lp_equal(L, -2, -1)) {  /* right group? */
168        lua_pop(L, 2);  /* remove reference name and group name */
169        return cap;
170      }
171      else lua_pop(L, 1);  /* remove group name */
172    }
173  }
174  luaL_error(L, "back reference '%s' not found", lua_tostring(L, -1));
175  return NULL;  /* to avoid warnings */
176}
177
178
179/*
180** Back-reference capture. Return number of values pushed.
181*/
182static int backrefcap (CapState *cs) {
183  int n;
184  Capture *curr = cs->cap;
185  pushluaval(cs);  /* reference name */
186  cs->cap = findback(cs, curr);  /* find corresponding group */
187  n = pushnestedvalues(cs, 0);  /* push group's values */
188  cs->cap = curr + 1;
189  return n;
190}
191
192
193/*
194** Table capture: creates a new table and populates it with nested
195** captures.
196*/
197static int tablecap (CapState *cs) {
198  lua_State *L = cs->L;
199  Capture *head = cs->cap++;
200  int n = 0;
201  lua_newtable(L);
202  while (capinside(head, cs->cap)) {
203    if (captype(cs->cap) == Cgroup && cs->cap->idx != 0) {  /* named group? */
204      pushluaval(cs);  /* push group name */
205      pushonenestedvalue(cs);
206      lua_settable(L, -3);
207    }
208    else {  /* not a named group */
209      int i;
210      int k = pushcapture(cs);
211      for (i = k; i > 0; i--)  /* store all values into table */
212        lua_rawseti(L, -(i + 1), n + i);
213      n += k;
214    }
215  }
216  skipclose(cs, head);
217  return 1;  /* number of values pushed (only the table) */
218}
219
220
221/*
222** Table-query capture
223*/
224static int querycap (CapState *cs) {
225  int idx = cs->cap->idx;
226  pushonenestedvalue(cs);  /* get nested capture */
227  lua_gettable(cs->L, updatecache(cs, idx));  /* query cap. value at table */
228  if (!lua_isnil(cs->L, -1))
229    return 1;
230  else {  /* no value */
231    lua_pop(cs->L, 1);  /* remove nil */
232    return 0;
233  }
234}
235
236
237/*
238** Fold capture
239*/
240static int foldcap (CapState *cs) {
241  int n;
242  lua_State *L = cs->L;
243  Capture *head = cs->cap++;
244  int idx = head->idx;
245  if (isclosecap(cs->cap) ||  /* no nested captures (large subject)? */
246      (n = pushcapture(cs)) == 0)  /* nested captures with no values? */
247    return luaL_error(L, "no initial value for fold capture");
248  if (n > 1)
249    lua_pop(L, n - 1);  /* leave only one result for accumulator */
250  while (capinside(head, cs->cap)) {
251    lua_pushvalue(L, updatecache(cs, idx));  /* get folding function */
252    lua_insert(L, -2);  /* put it before accumulator */
253    n = pushcapture(cs);  /* get next capture's values */
254    lua_call(L, n + 1, 1);  /* call folding function */
255  }
256  skipclose(cs, head);
257  return 1;  /* only accumulator left on the stack */
258}
259
260
261/*
262** Function capture
263*/
264static int functioncap (CapState *cs) {
265  int n;
266  int top = lua_gettop(cs->L);
267  pushluaval(cs);  /* push function */
268  n = pushnestedvalues(cs, 0);  /* push nested captures */
269  lua_call(cs->L, n, LUA_MULTRET);  /* call function */
270  return lua_gettop(cs->L) - top;  /* return function's results */
271}
272
273
274/*
275** Accumulator capture
276*/
277static int accumulatorcap (CapState *cs) {
278  lua_State *L = cs->L;
279  int n;
280  if (lua_gettop(L) < cs->firstcap)
281    luaL_error(L, "no previous value for accumulator capture");
282  pushluaval(cs);  /* push function */
283  lua_insert(L, -2);  /* previous value becomes first argument */
284  n = pushnestedvalues(cs, 0);  /* push nested captures */
285  lua_call(L, n + 1, 1);  /* call function */
286  return 0;  /* did not add any extra value */
287}
288
289
290/*
291** Select capture
292*/
293static int numcap (CapState *cs) {
294  int idx = cs->cap->idx;  /* value to select */
295  if (idx == 0) {  /* no values? */
296    nextcap(cs);  /* skip entire capture */
297    return 0;  /* no value produced */
298  }
299  else {
300    int n = pushnestedvalues(cs, 0);
301    if (n < idx)  /* invalid index? */
302      return luaL_error(cs->L, "no capture '%d'", idx);
303    else {
304      lua_pushvalue(cs->L, -(n - idx + 1));  /* get selected capture */
305      lua_replace(cs->L, -(n + 1));  /* put it in place of 1st capture */
306      lua_pop(cs->L, n - 1);  /* remove other captures */
307      return 1;
308    }
309  }
310}
311
312
313/*
314** Return the stack index of the first runtime capture in the given
315** list of captures (or zero if no runtime captures)
316*/
317int finddyncap (Capture *cap, Capture *last) {
318  for (; cap < last; cap++) {
319    if (cap->kind == Cruntime)
320      return cap->idx;  /* stack position of first capture */
321  }
322  return 0;  /* no dynamic captures in this segment */
323}
324
325
326/*
327** Calls a runtime capture. Returns number of captures "removed" by the
328** call, that is, those inside the group capture. Captures to be added
329** are on the Lua stack.
330*/
331int runtimecap (CapState *cs, Capture *close, const char *s, int *rem) {
332  int n, id;
333  lua_State *L = cs->L;
334  int otop = lua_gettop(L);
335  Capture *open = findopen(close);  /* get open group capture */
336  assert(captype(open) == Cgroup);
337  id = finddyncap(open, close);  /* get first dynamic capture argument */
338  close->kind = Cclose;  /* closes the group */
339  close->index = s - cs->s;
340  cs->cap = open; cs->valuecached = 0;  /* prepare capture state */
341  luaL_checkstack(L, 4, "too many runtime captures");
342  pushluaval(cs);  /* push function to be called */
343  lua_pushvalue(L, SUBJIDX);  /* push original subject */
344  lua_pushinteger(L, s - cs->s + 1);  /* push current position */
345  n = pushnestedvalues(cs, 0);  /* push nested captures */
346  lua_call(L, n + 2, LUA_MULTRET);  /* call dynamic function */
347  if (id > 0) {  /* are there old dynamic captures to be removed? */
348    int i;
349    for (i = id; i <= otop; i++)
350      lua_remove(L, id);  /* remove old dynamic captures */
351    *rem = otop - id + 1;  /* total number of dynamic captures removed */
352  }
353  else
354    *rem = 0;  /* no dynamic captures removed */
355  return close - open - 1;  /* number of captures to be removed */
356}
357
358
359/*
360** Auxiliary structure for substitution and string captures: keep
361** information about nested captures for future use, avoiding to push
362** string results into Lua
363*/
364typedef struct StrAux {
365  int isstring;  /* whether capture is a string */
366  union {
367    Capture *cp;  /* if not a string, respective capture */
368    struct {  /* if it is a string... */
369      Index_t idx;  /* starts here */
370      Index_t siz;  /* with this size */
371    } s;
372  } u;
373} StrAux;
374
375#define MAXSTRCAPS	10
376
377/*
378** Collect values from current capture into array 'cps'. Current
379** capture must be Cstring (first call) or Csimple (recursive calls).
380** (In first call, fills %0 with whole match for Cstring.)
381** Returns number of elements in the array that were filled.
382*/
383static int getstrcaps (CapState *cs, StrAux *cps, int n) {
384  int k = n++;
385  Capture *head = cs->cap++;
386  cps[k].isstring = 1;  /* get string value */
387  cps[k].u.s.idx = head->index;  /* starts here */
388  while (capinside(head, cs->cap)) {
389    if (n >= MAXSTRCAPS)  /* too many captures? */
390      nextcap(cs);  /* skip extra captures (will not need them) */
391    else if (captype(cs->cap) == Csimple)  /* string? */
392      n = getstrcaps(cs, cps, n);  /* put info. into array */
393    else {
394      cps[n].isstring = 0;  /* not a string */
395      cps[n].u.cp = cs->cap;  /* keep original capture */
396      nextcap(cs);
397      n++;
398    }
399  }
400  cps[k].u.s.siz = closesize(cs, head);
401  skipclose(cs, head);
402  return n;
403}
404
405
406/*
407** add next capture value (which should be a string) to buffer 'b'
408*/
409static int addonestring (luaL_Buffer *b, CapState *cs, const char *what);
410
411
412/*
413** String capture: add result to buffer 'b' (instead of pushing
414** it into the stack)
415*/
416static void stringcap (luaL_Buffer *b, CapState *cs) {
417  StrAux cps[MAXSTRCAPS];
418  int n;
419  size_t len, i;
420  const char *fmt;  /* format string */
421  fmt = lua_tolstring(cs->L, updatecache(cs, cs->cap->idx), &len);
422  n = getstrcaps(cs, cps, 0) - 1;  /* collect nested captures */
423  for (i = 0; i < len; i++) {  /* traverse format string */
424    if (fmt[i] != '%')  /* not an escape? */
425      luaL_addchar(b, fmt[i]);  /* add it to buffer */
426    else if (fmt[++i] < '0' || fmt[i] > '9')  /* not followed by a digit? */
427      luaL_addchar(b, fmt[i]);  /* add to buffer */
428    else {
429      int l = fmt[i] - '0';  /* capture index */
430      if (l > n)
431        luaL_error(cs->L, "invalid capture index (%d)", l);
432      else if (cps[l].isstring)
433        luaL_addlstring(b, cs->s + cps[l].u.s.idx, cps[l].u.s.siz);
434      else {
435        Capture *curr = cs->cap;
436        cs->cap = cps[l].u.cp;  /* go back to evaluate that nested capture */
437        if (!addonestring(b, cs, "capture"))
438          luaL_error(cs->L, "no values in capture index %d", l);
439        cs->cap = curr;  /* continue from where it stopped */
440      }
441    }
442  }
443}
444
445
446/*
447** Substitution capture: add result to buffer 'b'
448*/
449static void substcap (luaL_Buffer *b, CapState *cs) {
450  const char *curr = cs->s + cs->cap->index;
451  Capture *head = cs->cap++;
452  while (capinside(head, cs->cap)) {
453    Capture *cap = cs->cap;
454    const char *caps = cs->s + cap->index;
455    luaL_addlstring(b, curr, caps - curr);  /* add text up to capture */
456    if (addonestring(b, cs, "replacement"))
457      curr = caps + capsize(cap, cs->cap - 1);  /* continue after match */
458    else  /* no capture value */
459      curr = caps;  /* keep original text in final result */
460  }
461  /* add last piece of text */
462  luaL_addlstring(b, curr, cs->s + head->index + closesize(cs, head) - curr);
463  skipclose(cs, head);
464}
465
466
467/*
468** Evaluates a capture and adds its first value to buffer 'b'; returns
469** whether there was a value
470*/
471static int addonestring (luaL_Buffer *b, CapState *cs, const char *what) {
472  switch (captype(cs->cap)) {
473    case Cstring:
474      stringcap(b, cs);  /* add capture directly to buffer */
475      return 1;
476    case Csubst:
477      substcap(b, cs);  /* add capture directly to buffer */
478      return 1;
479    case Cacc:  /* accumulator capture? */
480      return luaL_error(cs->L, "invalid context for an accumulator capture");
481    default: {
482      lua_State *L = cs->L;
483      int n = pushcapture(cs);
484      if (n > 0) {
485        if (n > 1) lua_pop(L, n - 1);  /* only one result */
486        if (!lua_isstring(L, -1))
487          return luaL_error(L, "invalid %s value (a %s)",
488                               what, luaL_typename(L, -1));
489        luaL_addvalue(b);
490      }
491      return n;
492    }
493  }
494}
495
496
497#if !defined(MAXRECLEVEL)
498#define MAXRECLEVEL	200
499#endif
500
501
502/*
503** Push all values of the current capture into the stack; returns
504** number of values pushed
505*/
506static int pushcapture (CapState *cs) {
507  lua_State *L = cs->L;
508  int res;
509  luaL_checkstack(L, 4, "too many captures");
510  if (cs->reclevel++ > MAXRECLEVEL)
511    return luaL_error(L, "subcapture nesting too deep");
512  switch (captype(cs->cap)) {
513    case Cposition: {
514      lua_pushinteger(L, cs->cap->index + 1);
515      cs->cap++;
516      res = 1;
517      break;
518    }
519    case Cconst: {
520      pushluaval(cs);
521      cs->cap++;
522      res = 1;
523      break;
524    }
525    case Carg: {
526      int arg = (cs->cap++)->idx;
527      if (arg + FIXEDARGS > cs->ptop)
528        return luaL_error(L, "reference to absent extra argument #%d", arg);
529      lua_pushvalue(L, arg + FIXEDARGS);
530      res = 1;
531      break;
532    }
533    case Csimple: {
534      int k = pushnestedvalues(cs, 1);
535      lua_insert(L, -k);  /* make whole match be first result */
536      res = k;
537      break;
538    }
539    case Cruntime: {
540      lua_pushvalue(L, (cs->cap++)->idx);  /* value is in the stack */
541      res = 1;
542      break;
543    }
544    case Cstring: {
545      luaL_Buffer b;
546      luaL_buffinit(L, &b);
547      stringcap(&b, cs);
548      luaL_pushresult(&b);
549      res = 1;
550      break;
551    }
552    case Csubst: {
553      luaL_Buffer b;
554      luaL_buffinit(L, &b);
555      substcap(&b, cs);
556      luaL_pushresult(&b);
557      res = 1;
558      break;
559    }
560    case Cgroup: {
561      if (cs->cap->idx == 0)  /* anonymous group? */
562        res = pushnestedvalues(cs, 0);  /* add all nested values */
563      else {  /* named group: add no values */
564        nextcap(cs);  /* skip capture */
565        res = 0;
566      }
567      break;
568    }
569    case Cbackref: res = backrefcap(cs); break;
570    case Ctable: res = tablecap(cs); break;
571    case Cfunction: res = functioncap(cs); break;
572    case Cacc: res = accumulatorcap(cs); break;
573    case Cnum: res = numcap(cs); break;
574    case Cquery: res = querycap(cs); break;
575    case Cfold: res = foldcap(cs); break;
576    default: assert(0); res = 0;
577  }
578  cs->reclevel--;
579  return res;
580}
581
582
583/*
584** Prepare a CapState structure and traverse the entire list of
585** captures in the stack pushing its results. 's' is the subject
586** string, 'r' is the final position of the match, and 'ptop'
587** the index in the stack where some useful values were pushed.
588** Returns the number of results pushed. (If the list produces no
589** results, push the final position of the match.)
590*/
591int getcaptures (lua_State *L, const char *s, const char *r, int ptop) {
592  Capture *capture = (Capture *)lua_touserdata(L, caplistidx(ptop));
593  int n = 0;
594  /* printcaplist(capture); */
595  if (!isclosecap(capture)) {  /* is there any capture? */
596    CapState cs;
597    cs.ocap = cs.cap = capture; cs.L = L; cs.reclevel = 0;
598    cs.s = s; cs.valuecached = 0; cs.ptop = ptop;
599    cs.firstcap = lua_gettop(L) + 1;  /* where first value (if any) will go */
600    do {  /* collect their values */
601      n += pushcapture(&cs);
602    } while (!isclosecap(cs.cap));
603    assert(lua_gettop(L) - cs.firstcap == n - 1);
604  }
605  if (n == 0) {  /* no capture values? */
606    lua_pushinteger(L, r - s + 1);  /* return only end position */
607    n = 1;
608  }
609  return n;
610}
611
612