You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lpcode.c 30KB

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