robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
31.9 KiB1051 linesraw
1
2#include <limits.h>
3
4
5#include "lua.h"
6#include "lauxlib.h"
7
8#include "lptypes.h"
9#include "lpcode.h"
10#include "lpcset.h"
11
12
13/* signals a "no-instruction */
14#define NOINST		-1
15
16
17
18static const Charset fullset_ =
19  {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
20    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
21    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
22    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}};
23
24static const Charset *fullset = &fullset_;
25
26
27/*
28** {======================================================
29** Analysis and some optimizations
30** =======================================================
31*/
32
33
34/*
35** A few basic operations on Charsets
36*/
37static void cs_complement (Charset *cs) {
38  loopset(i, cs->cs[i] = ~cs->cs[i]);
39}
40
41static int cs_disjoint (const Charset *cs1, const Charset *cs2) {
42  loopset(i, if ((cs1->cs[i] & cs2->cs[i]) != 0) return 0;)
43  return 1;
44}
45
46
47/*
48** Visit a TCall node taking care to stop recursion. If node not yet
49** visited, return 'f(sib2(tree))', otherwise return 'def' (default
50** value)
51*/
52static int callrecursive (TTree *tree, int f (TTree *t), int def) {
53  int key = tree->key;
54  assert(tree->tag == TCall);
55  assert(sib2(tree)->tag == TRule);
56  if (key == 0)  /* node already visited? */
57    return def;  /* return default value */
58  else {  /* first visit */
59    int result;
60    tree->key = 0;  /* mark call as already visited */
61    result = f(sib2(tree));  /* go to called rule */
62    tree->key = key;  /* restore tree */
63    return result;
64  }
65}
66
67
68/*
69** Check whether a pattern tree has captures
70*/
71int hascaptures (TTree *tree) {
72 tailcall:
73  switch (tree->tag) {
74    case TCapture: case TRunTime:
75      return 1;
76    case TCall:
77      return callrecursive(tree, hascaptures, 0);
78    case TRule:  /* do not follow siblings */
79      tree = sib1(tree); goto tailcall;
80    case TOpenCall: assert(0);
81    default: {
82      switch (numsiblings[tree->tag]) {
83        case 1:  /* return hascaptures(sib1(tree)); */
84          tree = sib1(tree); goto tailcall;
85        case 2:
86          if (hascaptures(sib1(tree)))
87            return 1;
88          /* else return hascaptures(sib2(tree)); */
89          tree = sib2(tree); goto tailcall;
90        default: assert(numsiblings[tree->tag] == 0); return 0;
91      }
92    }
93  }
94}
95
96
97/*
98** Checks how a pattern behaves regarding the empty string,
99** in one of two different ways:
100** A pattern is *nullable* if it can match without consuming any character;
101** A pattern is *nofail* if it never fails for any string
102** (including the empty string).
103** The difference is only for predicates and run-time captures;
104** for other patterns, the two properties are equivalent.
105** (With predicates, &'a' is nullable but not nofail. Of course,
106** nofail => nullable.)
107** These functions are all convervative in the following way:
108**    p is nullable => nullable(p)
109**    nofail(p) => p cannot fail
110** The function assumes that TOpenCall is not nullable;
111** this will be checked again when the grammar is fixed.
112** Run-time captures can do whatever they want, so the result
113** is conservative.
114*/
115int checkaux (TTree *tree, int pred) {
116 tailcall:
117  switch (tree->tag) {
118    case TChar: case TSet: case TAny: case TUTFR:
119    case TFalse: case TOpenCall:
120      return 0;  /* not nullable */
121    case TRep: case TTrue:
122      return 1;  /* no fail */
123    case TNot: case TBehind:  /* can match empty, but can fail */
124      if (pred == PEnofail) return 0;
125      else return 1;  /* PEnullable */
126    case TAnd:  /* can match empty; fail iff body does */
127      if (pred == PEnullable) return 1;
128      /* else return checkaux(sib1(tree), pred); */
129      tree = sib1(tree); goto tailcall;
130    case TRunTime:  /* can fail; match empty iff body does */
131      if (pred == PEnofail) return 0;
132      /* else return checkaux(sib1(tree), pred); */
133      tree = sib1(tree); goto tailcall;
134    case TSeq:
135      if (!checkaux(sib1(tree), pred)) return 0;
136      /* else return checkaux(sib2(tree), pred); */
137      tree = sib2(tree); goto tailcall;
138    case TChoice:
139      if (checkaux(sib2(tree), pred)) return 1;
140      /* else return checkaux(sib1(tree), pred); */
141      tree = sib1(tree); goto tailcall;
142    case TCapture: case TGrammar: case TRule: case TXInfo:
143      /* return checkaux(sib1(tree), pred); */
144      tree = sib1(tree); goto tailcall;
145    case TCall:  /* return checkaux(sib2(tree), pred); */
146      tree = sib2(tree); goto tailcall;
147    default: assert(0); return 0;
148  }
149}
150
151
152/*
153** number of characters to match a pattern (or -1 if variable)
154*/
155int fixedlen (TTree *tree) {
156  int len = 0;  /* to accumulate in tail calls */
157 tailcall:
158  switch (tree->tag) {
159    case TChar: case TSet: case TAny:
160      return len + 1;
161    case TUTFR:
162      return (tree->cap == sib1(tree)->cap) ? len + tree->cap : -1;
163    case TFalse: case TTrue: case TNot: case TAnd: case TBehind:
164      return len;
165    case TRep: case TRunTime: case TOpenCall:
166      return -1;
167    case TCapture: case TRule: case TGrammar: case TXInfo:
168      /* return fixedlen(sib1(tree)); */
169      tree = sib1(tree); goto tailcall;
170    case TCall: {
171      int n1 = callrecursive(tree, fixedlen, -1);
172      if (n1 < 0)
173        return -1;
174      else
175        return len + n1;
176    }
177    case TSeq: {
178      int n1 = fixedlen(sib1(tree));
179      if (n1 < 0)
180        return -1;
181      /* else return fixedlen(sib2(tree)) + len; */
182      len += n1; tree = sib2(tree); goto tailcall;
183    }
184    case TChoice: {
185      int n1 = fixedlen(sib1(tree));
186      int n2 = fixedlen(sib2(tree));
187      if (n1 != n2 || n1 < 0)
188        return -1;
189      else
190        return len + n1;
191    }
192    default: assert(0); return 0;
193  };
194}
195
196
197/*
198** Computes the 'first set' of a pattern.
199** The result is a conservative aproximation:
200**   match p ax -> x (for some x) ==> a belongs to first(p)
201** or
202**   a not in first(p) ==> match p ax -> fail (for all x)
203**
204** The set 'follow' is the first set of what follows the
205** pattern (full set if nothing follows it).
206**
207** The function returns 0 when this resulting set can be used for
208** test instructions that avoid the pattern altogether.
209** A non-zero return can happen for two reasons:
210** 1) match p '' -> ''            ==> return has bit 1 set
211** (tests cannot be used because they would always fail for an empty input);
212** 2) there is a match-time capture ==> return has bit 2 set
213** (optimizations should not bypass match-time captures).
214*/
215static int getfirst (TTree *tree, const Charset *follow, Charset *firstset) {
216 tailcall:
217  switch (tree->tag) {
218    case TChar: case TSet: case TAny: case TFalse: {
219      tocharset(tree, firstset);
220      return 0;
221    }
222    case TUTFR: {
223      int c;
224      clearset(firstset->cs);  /* erase all chars */
225      for (c = tree->key; c <= sib1(tree)->key; c++)
226        setchar(firstset->cs, c);
227      return 0;
228    }
229    case TTrue: {
230      loopset(i, firstset->cs[i] = follow->cs[i]);
231      return 1;  /* accepts the empty string */
232    }
233    case TChoice: {
234      Charset csaux;
235      int e1 = getfirst(sib1(tree), follow, firstset);
236      int e2 = getfirst(sib2(tree), follow, &csaux);
237      loopset(i, firstset->cs[i] |= csaux.cs[i]);
238      return e1 | e2;
239    }
240    case TSeq: {
241      if (!nullable(sib1(tree))) {
242        /* when p1 is not nullable, p2 has nothing to contribute;
243           return getfirst(sib1(tree), fullset, firstset); */
244        tree = sib1(tree); follow = fullset; goto tailcall;
245      }
246      else {  /* FIRST(p1 p2, fl) = FIRST(p1, FIRST(p2, fl)) */
247        Charset csaux;
248        int e2 = getfirst(sib2(tree), follow, &csaux);
249        int e1 = getfirst(sib1(tree), &csaux, firstset);
250        if (e1 == 0) return 0;  /* 'e1' ensures that first can be used */
251        else if ((e1 | e2) & 2)  /* one of the children has a matchtime? */
252          return 2;  /* pattern has a matchtime capture */
253        else return e2;  /* else depends on 'e2' */
254      }
255    }
256    case TRep: {
257      getfirst(sib1(tree), follow, firstset);
258      loopset(i, firstset->cs[i] |= follow->cs[i]);
259      return 1;  /* accept the empty string */
260    }
261    case TCapture: case TGrammar: case TRule: case TXInfo: {
262      /* return getfirst(sib1(tree), follow, firstset); */
263      tree = sib1(tree); goto tailcall;
264    }
265    case TRunTime: {  /* function invalidates any follow info. */
266      int e = getfirst(sib1(tree), fullset, firstset);
267      if (e) return 2;  /* function is not "protected"? */
268      else return 0;  /* pattern inside capture ensures first can be used */
269    }
270    case TCall: {
271      /* return getfirst(sib2(tree), follow, firstset); */
272      tree = sib2(tree); goto tailcall;
273    }
274    case TAnd: {
275      int e = getfirst(sib1(tree), follow, firstset);
276      loopset(i, firstset->cs[i] &= follow->cs[i]);
277      return e;
278    }
279    case TNot: {
280      if (tocharset(sib1(tree), firstset)) {
281        cs_complement(firstset);
282        return 1;
283      }  /* else */
284    }    /* FALLTHROUGH */
285    case TBehind: {  /* instruction gives no new information */
286      /* call 'getfirst' only to check for math-time captures */
287      int e = getfirst(sib1(tree), follow, firstset);
288      loopset(i, firstset->cs[i] = follow->cs[i]);  /* uses follow */
289      return e | 1;  /* always can accept the empty string */
290    }
291    default: assert(0); return 0;
292  }
293}
294
295
296/*
297** If 'headfail(tree)' true, then 'tree' can fail only depending on the
298** next character of the subject.
299*/
300static int headfail (TTree *tree) {
301 tailcall:
302  switch (tree->tag) {
303    case TChar: case TSet: case TAny: case TFalse:
304      return 1;
305    case TTrue: case TRep: case TRunTime: case TNot:
306    case TBehind: case TUTFR:
307      return 0;
308    case TCapture: case TGrammar: case TRule: case TXInfo: case TAnd:
309      tree = sib1(tree); goto tailcall;  /* return headfail(sib1(tree)); */
310    case TCall:
311      tree = sib2(tree); goto tailcall;  /* return headfail(sib2(tree)); */
312    case TSeq:
313      if (!nofail(sib2(tree))) return 0;
314      /* else return headfail(sib1(tree)); */
315      tree = sib1(tree); goto tailcall;
316    case TChoice:
317      if (!headfail(sib1(tree))) return 0;
318      /* else return headfail(sib2(tree)); */
319      tree = sib2(tree); goto tailcall;
320    default: assert(0); return 0;
321  }
322}
323
324
325/*
326** Check whether the code generation for the given tree can benefit
327** from a follow set (to avoid computing the follow set when it is
328** not needed)
329*/
330static int needfollow (TTree *tree) {
331 tailcall:
332  switch (tree->tag) {
333    case TChar: case TSet: case TAny: case TUTFR:
334    case TFalse: case TTrue: case TAnd: case TNot:
335    case TRunTime: case TGrammar: case TCall: case TBehind:
336      return 0;
337    case TChoice: case TRep:
338      return 1;
339    case TCapture:
340      tree = sib1(tree); goto tailcall;
341    case TSeq:
342      tree = sib2(tree); goto tailcall;
343    default: assert(0); return 0;
344  }
345}
346
347/* }====================================================== */
348
349
350
351/*
352** {======================================================
353** Code generation
354** =======================================================
355*/
356
357
358/*
359** size of an instruction
360*/
361int sizei (const Instruction *i) {
362  switch((Opcode)i->i.code) {
363    case ISet: case ISpan: return 1 + i->i.aux2.set.size;
364    case ITestSet: return 2 + i->i.aux2.set.size;
365    case ITestChar: case ITestAny: case IChoice: case IJmp: case ICall:
366    case IOpenCall: case ICommit: case IPartialCommit: case IBackCommit:
367    case IUTFR:
368      return 2;
369    default: return 1;
370  }
371}
372
373
374/*
375** state for the compiler
376*/
377typedef struct CompileState {
378  Pattern *p;  /* pattern being compiled */
379  int ncode;  /* next position in p->code to be filled */
380  lua_State *L;
381} CompileState;
382
383
384/*
385** code generation is recursive; 'opt' indicates that the code is being
386** generated as the last thing inside an optional pattern (so, if that
387** code is optional too, it can reuse the 'IChoice' already in place for
388** the outer pattern). 'tt' points to a previous test protecting this
389** code (or NOINST). 'fl' is the follow set of the pattern.
390*/
391static void codegen (CompileState *compst, TTree *tree, int opt, int tt,
392                     const Charset *fl);
393
394
395static void finishrelcode (lua_State *L, Pattern *p, Instruction *block,
396                                         int size) {
397  if (block == NULL)
398    luaL_error(L, "not enough memory");
399  block->codesize = size;
400  p->code = (Instruction *)block + 1;
401}
402
403
404/*
405** Initialize array 'p->code'
406*/
407static void newcode (lua_State *L, Pattern *p, int size) {
408  void *ud;
409  Instruction *block;
410  lua_Alloc f = lua_getallocf(L, &ud);
411  size++;  /* slot for 'codesize' */
412  block = (Instruction*) f(ud, NULL, 0, size * sizeof(Instruction));
413  finishrelcode(L, p, block, size);
414}
415
416
417void freecode (lua_State *L, Pattern *p) {
418  if (p->code != NULL) {
419    void *ud;
420    lua_Alloc f = lua_getallocf(L, &ud);
421    uint osize = p->code[-1].codesize;
422    f(ud, p->code - 1, osize * sizeof(Instruction), 0);  /* free block */
423  }
424}
425
426
427/*
428** Assume that 'nsize' is not zero and that 'p->code' already exists.
429*/
430static void realloccode (lua_State *L, Pattern *p, int nsize) {
431  void *ud;
432  lua_Alloc f = lua_getallocf(L, &ud);
433  Instruction *block = p->code - 1;
434  uint osize = block->codesize;
435  nsize++;  /* add the 'codesize' slot to size */
436  block = (Instruction*) f(ud, block, osize * sizeof(Instruction),
437                                      nsize * sizeof(Instruction));
438  finishrelcode(L, p, block, nsize);
439}
440
441
442/*
443** Add space for an instruction with 'n' slots and return its index.
444*/
445static int nextinstruction (CompileState *compst, int n) {
446  int size = compst->p->code[-1].codesize - 1;
447  int ncode = compst->ncode;
448  if (ncode > size - n) {
449    uint nsize = size + (size >> 1) + n;
450    if (nsize >= INT_MAX)
451      luaL_error(compst->L, "pattern code too large");
452    realloccode(compst->L, compst->p, nsize);
453  }
454  compst->ncode = ncode + n;
455  return ncode;
456}
457
458
459#define getinstr(cs,i)		((cs)->p->code[i])
460
461
462static int addinstruction (CompileState *compst, Opcode op, int aux) {
463  int i = nextinstruction(compst, 1);
464  getinstr(compst, i).i.code = op;
465  getinstr(compst, i).i.aux1 = aux;
466  return i;
467}
468
469
470/*
471** Add an instruction followed by space for an offset (to be set later)
472*/
473static int addoffsetinst (CompileState *compst, Opcode op) {
474  int i = addinstruction(compst, op, 0);  /* instruction */
475  addinstruction(compst, (Opcode)0, 0);  /* open space for offset */
476  assert(op == ITestSet || sizei(&getinstr(compst, i)) == 2);
477  return i;
478}
479
480
481/*
482** Set the offset of an instruction
483*/
484static void setoffset (CompileState *compst, int instruction, int offset) {
485  getinstr(compst, instruction + 1).offset = offset;
486}
487
488
489static void codeutfr (CompileState *compst, TTree *tree) {
490  int i = addoffsetinst(compst, IUTFR);
491  int to = sib1(tree)->u.n;
492  assert(sib1(tree)->tag == TXInfo);
493  getinstr(compst, i + 1).offset = tree->u.n;
494  getinstr(compst, i).i.aux1 = to & 0xff;
495  getinstr(compst, i).i.aux2.key = to >> 8;
496}
497
498
499/*
500** Add a capture instruction:
501** 'op' is the capture instruction; 'cap' the capture kind;
502** 'key' the key into ktable; 'aux' is the optional capture offset
503**
504*/
505static int addinstcap (CompileState *compst, Opcode op, int cap, int key,
506                       int aux) {
507  int i = addinstruction(compst, op, joinkindoff(cap, aux));
508  getinstr(compst, i).i.aux2.key = key;
509  return i;
510}
511
512
513#define gethere(compst) 	((compst)->ncode)
514
515#define target(code,i)		((i) + code[i + 1].offset)
516
517
518/*
519** Patch 'instruction' to jump to 'target'
520*/
521static void jumptothere (CompileState *compst, int instruction, int target) {
522  if (instruction >= 0)
523    setoffset(compst, instruction, target - instruction);
524}
525
526
527/*
528** Patch 'instruction' to jump to current position
529*/
530static void jumptohere (CompileState *compst, int instruction) {
531  jumptothere(compst, instruction, gethere(compst));
532}
533
534
535/*
536** Code an IChar instruction, or IAny if there is an equivalent
537** test dominating it
538*/
539static void codechar (CompileState *compst, int c, int tt) {
540  if (tt >= 0 && getinstr(compst, tt).i.code == ITestChar &&
541                 getinstr(compst, tt).i.aux1 == c)
542    addinstruction(compst, IAny, 0);
543  else
544    addinstruction(compst, IChar, c);
545}
546
547
548/*
549** Add a charset posfix to an instruction.
550*/
551static void addcharset (CompileState *compst, int inst, charsetinfo *info) {
552  int p;
553  Instruction *I = &getinstr(compst, inst);
554  byte *charset;
555  int isize = instsize(info->size);  /* size in instructions */
556  int i;
557  I->i.aux2.set.offset = info->offset * 8;  /* offset in bits */
558  I->i.aux2.set.size = isize;
559  I->i.aux1 = info->deflt;
560  p = nextinstruction(compst, isize);  /* space for charset */
561  charset = getinstr(compst, p).buff;  /* charset buffer */
562  for (i = 0; i < isize * (int)sizeof(Instruction); i++)
563    charset[i] = getbytefromcharset(info, i);  /* copy the buffer */
564}
565
566
567/*
568** Check whether charset 'info' is dominated by instruction 'p'
569*/
570static int cs_equal (Instruction *p, charsetinfo *info) {
571  if (p->i.code != ITestSet)
572    return 0;
573  else if (p->i.aux2.set.offset != info->offset * 8 ||
574           p->i.aux2.set.size != instsize(info->size) ||
575           p->i.aux1 != info->deflt)
576    return 0;
577  else {
578    int i;
579    for (i = 0; i < instsize(info->size) * (int)sizeof(Instruction); i++) {
580      if ((p + 2)->buff[i] != getbytefromcharset(info, i))
581        return 0;
582    }
583  }
584  return 1;
585}
586
587
588/*
589** Code a char set, using IAny when instruction is dominated by an
590** equivalent test.
591*/
592static void codecharset (CompileState *compst, TTree *tree, int tt) {
593  charsetinfo info;
594  tree2cset(tree, &info);
595  if (tt >= 0 && cs_equal(&getinstr(compst, tt), &info))
596    addinstruction(compst, IAny, 0);
597  else {
598    int i = addinstruction(compst, ISet, 0);
599    addcharset(compst, i, &info);
600  }
601}
602
603
604/*
605** Code a test set, optimizing unit sets for ITestChar, "complete"
606** sets for ITestAny, and empty sets for IJmp (always fails).
607** 'e' is true iff test should accept the empty string. (Test
608** instructions in the current VM never accept the empty string.)
609*/
610static int codetestset (CompileState *compst, Charset *cs, int e) {
611  if (e) return NOINST;  /* no test */
612  else {
613    charsetinfo info;
614    Opcode op = charsettype(cs->cs, &info);
615    switch (op) {
616      case IFail: return addoffsetinst(compst, IJmp);  /* always jump */
617      case IAny: return addoffsetinst(compst, ITestAny);
618      case IChar: {
619        int i = addoffsetinst(compst, ITestChar);
620        getinstr(compst, i).i.aux1 = info.offset;
621        return i;
622      }
623      default: {  /* regular set */
624        int i = addoffsetinst(compst, ITestSet);
625        addcharset(compst, i, &info);
626        assert(op == ISet);
627        return i;
628      }
629    }
630  }
631}
632
633
634/*
635** Find the final destination of a sequence of jumps
636*/
637static int finaltarget (Instruction *code, int i) {
638  while (code[i].i.code == IJmp)
639    i = target(code, i);
640  return i;
641}
642
643
644/*
645** final label (after traversing any jumps)
646*/
647static int finallabel (Instruction *code, int i) {
648  return finaltarget(code, target(code, i));
649}
650
651
652/*
653** <behind(p)> == behind n; <p>   (where n = fixedlen(p))
654*/
655static void codebehind (CompileState *compst, TTree *tree) {
656  if (tree->u.n > 0)
657    addinstruction(compst, IBehind, tree->u.n);
658  codegen(compst, sib1(tree), 0, NOINST, fullset);
659}
660
661
662/*
663** Choice; optimizations:
664** - when p1 is headfail or when first(p1) and first(p2) are disjoint,
665** than a character not in first(p1) cannot go to p1 and a character
666** in first(p1) cannot go to p2, either because p1 will accept
667** (headfail) or because it is not in first(p2) (disjoint).
668** (The second case is not valid if p1 accepts the empty string,
669** as then there is no character at all...)
670** - when p2 is empty and opt is true; a IPartialCommit can reuse
671** the Choice already active in the stack.
672*/
673static void codechoice (CompileState *compst, TTree *p1, TTree *p2, int opt,
674                        const Charset *fl) {
675  int emptyp2 = (p2->tag == TTrue);
676  Charset cs1, cs2;
677  int e1 = getfirst(p1, fullset, &cs1);
678  if (headfail(p1) ||
679      (!e1 && (getfirst(p2, fl, &cs2), cs_disjoint(&cs1, &cs2)))) {
680    /* <p1 / p2> == test (fail(p1)) -> L1 ; p1 ; jmp L2; L1: p2; L2: */
681    int test = codetestset(compst, &cs1, 0);
682    int jmp = NOINST;
683    codegen(compst, p1, 0, test, fl);
684    if (!emptyp2)
685      jmp = addoffsetinst(compst, IJmp);
686    jumptohere(compst, test);
687    codegen(compst, p2, opt, NOINST, fl);
688    jumptohere(compst, jmp);
689  }
690  else if (opt && emptyp2) {
691    /* p1? == IPartialCommit; p1 */
692    jumptohere(compst, addoffsetinst(compst, IPartialCommit));
693    codegen(compst, p1, 1, NOINST, fullset);
694  }
695  else {
696    /* <p1 / p2> ==
697        test(first(p1)) -> L1; choice L1; <p1>; commit L2; L1: <p2>; L2: */
698    int pcommit;
699    int test = codetestset(compst, &cs1, e1);
700    int pchoice = addoffsetinst(compst, IChoice);
701    codegen(compst, p1, emptyp2, test, fullset);
702    pcommit = addoffsetinst(compst, ICommit);
703    jumptohere(compst, pchoice);
704    jumptohere(compst, test);
705    codegen(compst, p2, opt, NOINST, fl);
706    jumptohere(compst, pcommit);
707  }
708}
709
710
711/*
712** And predicate
713** optimization: fixedlen(p) = n ==> <&p> == <p>; behind n
714** (valid only when 'p' has no captures)
715*/
716static void codeand (CompileState *compst, TTree *tree, int tt) {
717  int n = fixedlen(tree);
718  if (n >= 0 && n <= MAXBEHIND && !hascaptures(tree)) {
719    codegen(compst, tree, 0, tt, fullset);
720    if (n > 0)
721      addinstruction(compst, IBehind, n);
722  }
723  else {  /* default: Choice L1; p1; BackCommit L2; L1: Fail; L2: */
724    int pcommit;
725    int pchoice = addoffsetinst(compst, IChoice);
726    codegen(compst, tree, 0, tt, fullset);
727    pcommit = addoffsetinst(compst, IBackCommit);
728    jumptohere(compst, pchoice);
729    addinstruction(compst, IFail, 0);
730    jumptohere(compst, pcommit);
731  }
732}
733
734
735/*
736** Captures: if pattern has fixed (and not too big) length, and it
737** has no nested captures, use a single IFullCapture instruction
738** after the match; otherwise, enclose the pattern with OpenCapture -
739** CloseCapture.
740*/
741static void codecapture (CompileState *compst, TTree *tree, int tt,
742                         const Charset *fl) {
743  int len = fixedlen(sib1(tree));
744  if (len >= 0 && len <= MAXOFF && !hascaptures(sib1(tree))) {
745    codegen(compst, sib1(tree), 0, tt, fl);
746    addinstcap(compst, IFullCapture, tree->cap, tree->key, len);
747  }
748  else {
749    addinstcap(compst, IOpenCapture, tree->cap, tree->key, 0);
750    codegen(compst, sib1(tree), 0, tt, fl);
751    addinstcap(compst, ICloseCapture, Cclose, 0, 0);
752  }
753}
754
755
756static void coderuntime (CompileState *compst, TTree *tree, int tt) {
757  addinstcap(compst, IOpenCapture, Cgroup, tree->key, 0);
758  codegen(compst, sib1(tree), 0, tt, fullset);
759  addinstcap(compst, ICloseRunTime, Cclose, 0, 0);
760}
761
762
763/*
764** Create a jump to 'test' and fix 'test' to jump to next instruction
765*/
766static void closeloop (CompileState *compst, int test) {
767  int jmp = addoffsetinst(compst, IJmp);
768  jumptohere(compst, test);
769  jumptothere(compst, jmp, test);
770}
771
772
773/*
774** Try repetition of charsets:
775** For an empty set, repetition of fail is a no-op;
776** For any or char, code a tight loop;
777** For generic charset, use a span instruction.
778*/
779static int coderepcharset (CompileState *compst, TTree *tree) {
780  switch (tree->tag) {
781    case TFalse: return 1;  /* 'fail*' is a no-op */
782    case TAny: {  /* L1: testany -> L2; any; jmp L1; L2: */
783      int test = addoffsetinst(compst, ITestAny);
784      addinstruction(compst, IAny, 0);
785      closeloop(compst, test);
786      return 1;
787    }
788    case TChar: {  /* L1: testchar c -> L2; any; jmp L1; L2: */
789      int test = addoffsetinst(compst, ITestChar);
790      getinstr(compst, test).i.aux1 = tree->u.n;
791      addinstruction(compst, IAny, 0);
792      closeloop(compst, test);
793      return 1;
794    }
795    case TSet: {  /* regular set */
796      charsetinfo info;
797      int i = addinstruction(compst, ISpan, 0);
798      tree2cset(tree, &info);
799      addcharset(compst, i, &info);
800      return 1;
801    }
802    default: return 0;  /* not a charset */
803  }
804}
805
806
807/*
808** Repetion; optimizations:
809** When pattern is a charset, use special code.
810** When pattern is head fail, or if it starts with characters that
811** are disjoint from what follows the repetions, a simple test
812** is enough (a fail inside the repetition would backtrack to fail
813** again in the following pattern, so there is no need for a choice).
814** When 'opt' is true, the repetion can reuse the Choice already
815** active in the stack.
816*/
817static void coderep (CompileState *compst, TTree *tree, int opt,
818                     const Charset *fl) {
819  if (!coderepcharset(compst, tree)) {
820    Charset st;
821    int e1 = getfirst(tree, fullset, &st);
822    if (headfail(tree) || (!e1 && cs_disjoint(&st, fl))) {
823      /* L1: test (fail(p1)) -> L2; <p>; jmp L1; L2: */
824      int test = codetestset(compst, &st, 0);
825      codegen(compst, tree, 0, test, fullset);
826      closeloop(compst, test);
827    }
828    else {
829      /* test(fail(p1)) -> L2; choice L2; L1: <p>; partialcommit L1; L2: */
830      /* or (if 'opt'): partialcommit L1; L1: <p>; partialcommit L1; */
831      int commit, l2;
832      int test = codetestset(compst, &st, e1);
833      int pchoice = NOINST;
834      if (opt)
835        jumptohere(compst, addoffsetinst(compst, IPartialCommit));
836      else
837        pchoice = addoffsetinst(compst, IChoice);
838      l2 = gethere(compst);
839      codegen(compst, tree, 0, NOINST, fullset);
840      commit = addoffsetinst(compst, IPartialCommit);
841      jumptothere(compst, commit, l2);
842      jumptohere(compst, pchoice);
843      jumptohere(compst, test);
844    }
845  }
846}
847
848
849/*
850** Not predicate; optimizations:
851** In any case, if first test fails, 'not' succeeds, so it can jump to
852** the end. If pattern is headfail, that is all (it cannot fail
853** in other parts); this case includes 'not' of simple sets. Otherwise,
854** use the default code (a choice plus a failtwice).
855*/
856static void codenot (CompileState *compst, TTree *tree) {
857  Charset st;
858  int e = getfirst(tree, fullset, &st);
859  int test = codetestset(compst, &st, e);
860  if (headfail(tree))  /* test (fail(p1)) -> L1; fail; L1:  */
861    addinstruction(compst, IFail, 0);
862  else {
863    /* test(fail(p))-> L1; choice L1; <p>; failtwice; L1:  */
864    int pchoice = addoffsetinst(compst, IChoice);
865    codegen(compst, tree, 0, NOINST, fullset);
866    addinstruction(compst, IFailTwice, 0);
867    jumptohere(compst, pchoice);
868  }
869  jumptohere(compst, test);
870}
871
872
873/*
874** change open calls to calls, using list 'positions' to find
875** correct offsets; also optimize tail calls
876*/
877static void correctcalls (CompileState *compst, int *positions,
878                          int from, int to) {
879  int i;
880  Instruction *code = compst->p->code;
881  for (i = from; i < to; i += sizei(&code[i])) {
882    if (code[i].i.code == IOpenCall) {
883      int n = code[i].i.aux2.key;  /* rule number */
884      int rule = positions[n];  /* rule position */
885      assert(rule == from || code[rule - 1].i.code == IRet);
886      if (code[finaltarget(code, i + 2)].i.code == IRet)  /* call; ret ? */
887        code[i].i.code = IJmp;  /* tail call */
888      else
889        code[i].i.code = ICall;
890      jumptothere(compst, i, rule);  /* call jumps to respective rule */
891    }
892  }
893  assert(i == to);
894}
895
896
897/*
898** Code for a grammar:
899** call L1; jmp L2; L1: rule 1; ret; rule 2; ret; ...; L2:
900*/
901static void codegrammar (CompileState *compst, TTree *grammar) {
902  int positions[MAXRULES];
903  int rulenumber = 0;
904  TTree *rule;
905  int firstcall = addoffsetinst(compst, ICall);  /* call initial rule */
906  int jumptoend = addoffsetinst(compst, IJmp);  /* jump to the end */
907  int start = gethere(compst);  /* here starts the initial rule */
908  jumptohere(compst, firstcall);
909  for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
910    TTree *r = sib1(rule);
911    assert(r->tag == TXInfo);
912    positions[rulenumber++] = gethere(compst);  /* save rule position */
913    codegen(compst, sib1(r), 0, NOINST, fullset);  /* code rule */
914    addinstruction(compst, IRet, 0);
915  }
916  assert(rule->tag == TTrue);
917  jumptohere(compst, jumptoend);
918  correctcalls(compst, positions, start, gethere(compst));
919}
920
921
922static void codecall (CompileState *compst, TTree *call) {
923  int c = addoffsetinst(compst, IOpenCall);  /* to be corrected later */
924  assert(sib1(sib2(call))->tag == TXInfo);
925  getinstr(compst, c).i.aux2.key = sib1(sib2(call))->u.n;  /* rule number */
926}
927
928
929/*
930** Code first child of a sequence
931** (second child is called in-place to allow tail call)
932** Return 'tt' for second child
933*/
934static int codeseq1 (CompileState *compst, TTree *p1, TTree *p2,
935                     int tt, const Charset *fl) {
936  if (needfollow(p1)) {
937    Charset fl1;
938    getfirst(p2, fl, &fl1);  /* p1 follow is p2 first */
939    codegen(compst, p1, 0, tt, &fl1);
940  }
941  else  /* use 'fullset' as follow */
942    codegen(compst, p1, 0, tt, fullset);
943  if (fixedlen(p1) != 0)  /* can 'p1' consume anything? */
944    return  NOINST;  /* invalidate test */
945  else return tt;  /* else 'tt' still protects sib2 */
946}
947
948
949/*
950** Main code-generation function: dispatch to auxiliar functions
951** according to kind of tree. ('needfollow' should return true
952** only for consructions that use 'fl'.)
953*/
954static void codegen (CompileState *compst, TTree *tree, int opt, int tt,
955                     const Charset *fl) {
956 tailcall:
957  switch (tree->tag) {
958    case TChar: codechar(compst, tree->u.n, tt); break;
959    case TAny: addinstruction(compst, IAny, 0); break;
960    case TSet: codecharset(compst, tree, tt); break;
961    case TTrue: break;
962    case TFalse: addinstruction(compst, IFail, 0); break;
963    case TUTFR: codeutfr(compst, tree); break;
964    case TChoice: codechoice(compst, sib1(tree), sib2(tree), opt, fl); break;
965    case TRep: coderep(compst, sib1(tree), opt, fl); break;
966    case TBehind: codebehind(compst, tree); break;
967    case TNot: codenot(compst, sib1(tree)); break;
968    case TAnd: codeand(compst, sib1(tree), tt); break;
969    case TCapture: codecapture(compst, tree, tt, fl); break;
970    case TRunTime: coderuntime(compst, tree, tt); break;
971    case TGrammar: codegrammar(compst, tree); break;
972    case TCall: codecall(compst, tree); break;
973    case TSeq: {
974      tt = codeseq1(compst, sib1(tree), sib2(tree), tt, fl);  /* code 'p1' */
975      /* codegen(compst, p2, opt, tt, fl); */
976      tree = sib2(tree); goto tailcall;
977    }
978    default: assert(0);
979  }
980}
981
982
983/*
984** Optimize jumps and other jump-like instructions.
985** * Update labels of instructions with labels to their final
986** destinations (e.g., choice L1; ... L1: jmp L2: becomes
987** choice L2)
988** * Jumps to other instructions that do jumps become those
989** instructions (e.g., jump to return becomes a return; jump
990** to commit becomes a commit)
991*/
992static void peephole (CompileState *compst) {
993  Instruction *code = compst->p->code;
994  int i;
995  for (i = 0; i < compst->ncode; i += sizei(&code[i])) {
996   redo:
997    switch (code[i].i.code) {
998      case IChoice: case ICall: case ICommit: case IPartialCommit:
999      case IBackCommit: case ITestChar: case ITestSet:
1000      case ITestAny: {  /* instructions with labels */
1001        jumptothere(compst, i, finallabel(code, i));  /* optimize label */
1002        break;
1003      }
1004      case IJmp: {
1005        int ft = finaltarget(code, i);
1006        switch (code[ft].i.code) {  /* jumping to what? */
1007          case IRet: case IFail: case IFailTwice:
1008          case IEnd: {  /* instructions with unconditional implicit jumps */
1009            code[i] = code[ft];  /* jump becomes that instruction */
1010            code[i + 1].i.code = IEmpty;  /* 'no-op' for target position */
1011            break;
1012          }
1013          case ICommit: case IPartialCommit:
1014          case IBackCommit: {  /* inst. with unconditional explicit jumps */
1015            int fft = finallabel(code, ft);
1016            code[i] = code[ft];  /* jump becomes that instruction... */
1017            jumptothere(compst, i, fft);  /* but must correct its offset */
1018            goto redo;  /* reoptimize its label */
1019          }
1020          default: {
1021            jumptothere(compst, i, ft);  /* optimize label */
1022            break;
1023          }
1024        }
1025        break;
1026      }
1027      default: break;
1028    }
1029  }
1030  assert(code[i - 1].i.code == IEnd);
1031}
1032
1033
1034/*
1035** Compile a pattern. 'size' is the size of the pattern's tree,
1036** which gives a hint for the size of the final code.
1037*/
1038Instruction *compile (lua_State *L, Pattern *p, uint size) {
1039  CompileState compst;
1040  compst.p = p;  compst.ncode = 0;  compst.L = L;
1041  newcode(L, p, size/2u + 2);  /* set initial size */
1042  codegen(&compst, p->tree, 0, NOINST, fullset);
1043  addinstruction(&compst, IEnd, 0);
1044  realloccode(L, p, compst.ncode);  /* set final size */
1045  peephole(&compst);
1046  return p->code;
1047}
1048
1049
1050/* }====================================================== */
1051