lpcode.c 32 KB

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