lptree.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. #include <ctype.h>
  2. #include <limits.h>
  3. #include <string.h>
  4. #include "lua.h"
  5. #include "lauxlib.h"
  6. #include "lptypes.h"
  7. #include "lpcap.h"
  8. #include "lpcode.h"
  9. #include "lpprint.h"
  10. #include "lptree.h"
  11. #include "lpcset.h"
  12. /* number of siblings for each tree */
  13. const byte numsiblings[] = {
  14. 0, 0, 0, /* char, set, any */
  15. 0, 0, 0, /* true, false, utf-range */
  16. 1, /* acc */
  17. 2, 2, /* seq, choice */
  18. 1, 1, /* not, and */
  19. 0, 0, 2, 1, 1, /* call, opencall, rule, prerule, grammar */
  20. 1, /* behind */
  21. 1, 1 /* capture, runtime capture */
  22. };
  23. static TTree *newgrammar (lua_State *L, int arg);
  24. /*
  25. ** returns a reasonable name for value at index 'idx' on the stack
  26. */
  27. static const char *val2str (lua_State *L, int idx) {
  28. const char *k = lua_tostring(L, idx);
  29. if (k != NULL)
  30. return lua_pushfstring(L, "%s", k);
  31. else
  32. return lua_pushfstring(L, "(a %s)", luaL_typename(L, idx));
  33. }
  34. /*
  35. ** Fix a TOpenCall into a TCall node, using table 'postable' to
  36. ** translate a key to its rule address in the tree. Raises an
  37. ** error if key does not exist.
  38. */
  39. static void fixonecall (lua_State *L, int postable, TTree *g, TTree *t) {
  40. int n;
  41. lua_rawgeti(L, -1, t->key); /* get rule's name */
  42. lua_gettable(L, postable); /* query name in position table */
  43. n = lua_tonumber(L, -1); /* get (absolute) position */
  44. lua_pop(L, 1); /* remove position */
  45. if (n == 0) { /* no position? */
  46. lua_rawgeti(L, -1, t->key); /* get rule's name again */
  47. luaL_error(L, "rule '%s' undefined in given grammar", val2str(L, -1));
  48. }
  49. t->tag = TCall;
  50. t->u.ps = n - (t - g); /* position relative to node */
  51. assert(sib2(t)->tag == TRule);
  52. sib2(t)->key = t->key; /* fix rule's key */
  53. }
  54. /*
  55. ** Transform left associative constructions into right
  56. ** associative ones, for sequence and choice; that is:
  57. ** (t11 + t12) + t2 => t11 + (t12 + t2)
  58. ** (t11 * t12) * t2 => t11 * (t12 * t2)
  59. ** (that is, Op (Op t11 t12) t2 => Op t11 (Op t12 t2))
  60. */
  61. static void correctassociativity (TTree *tree) {
  62. TTree *t1 = sib1(tree);
  63. assert(tree->tag == TChoice || tree->tag == TSeq);
  64. while (t1->tag == tree->tag) {
  65. int n1size = tree->u.ps - 1; /* t1 == Op t11 t12 */
  66. int n11size = t1->u.ps - 1;
  67. int n12size = n1size - n11size - 1;
  68. memmove(sib1(tree), sib1(t1), n11size * sizeof(TTree)); /* move t11 */
  69. tree->u.ps = n11size + 1;
  70. sib2(tree)->tag = tree->tag;
  71. sib2(tree)->u.ps = n12size + 1;
  72. }
  73. }
  74. /*
  75. ** Make final adjustments in a tree. Fix open calls in tree 't',
  76. ** making them refer to their respective rules or raising appropriate
  77. ** errors (if not inside a grammar). Correct associativity of associative
  78. ** constructions (making them right associative). Assume that tree's
  79. ** ktable is at the top of the stack (for error messages).
  80. */
  81. static void finalfix (lua_State *L, int postable, TTree *g, TTree *t) {
  82. tailcall:
  83. switch (t->tag) {
  84. case TGrammar: /* subgrammars were already fixed */
  85. return;
  86. case TOpenCall: {
  87. if (g != NULL) /* inside a grammar? */
  88. fixonecall(L, postable, g, t);
  89. else { /* open call outside grammar */
  90. lua_rawgeti(L, -1, t->key);
  91. luaL_error(L, "rule '%s' used outside a grammar", val2str(L, -1));
  92. }
  93. break;
  94. }
  95. case TSeq: case TChoice:
  96. correctassociativity(t);
  97. break;
  98. }
  99. switch (numsiblings[t->tag]) {
  100. case 1: /* finalfix(L, postable, g, sib1(t)); */
  101. t = sib1(t); goto tailcall;
  102. case 2:
  103. finalfix(L, postable, g, sib1(t));
  104. t = sib2(t); goto tailcall; /* finalfix(L, postable, g, sib2(t)); */
  105. default: assert(numsiblings[t->tag] == 0); break;
  106. }
  107. }
  108. /*
  109. ** {===================================================================
  110. ** KTable manipulation
  111. **
  112. ** - The ktable of a pattern 'p' can be shared by other patterns that
  113. ** contain 'p' and no other constants. Because of this sharing, we
  114. ** should not add elements to a 'ktable' unless it was freshly created
  115. ** for the new pattern.
  116. **
  117. ** - The maximum index in a ktable is USHRT_MAX, because trees and
  118. ** patterns use unsigned shorts to store those indices.
  119. ** ====================================================================
  120. */
  121. /*
  122. ** Create a new 'ktable' to the pattern at the top of the stack.
  123. */
  124. static void newktable (lua_State *L, int n) {
  125. lua_createtable(L, n, 0); /* create a fresh table */
  126. lua_setuservalue(L, -2); /* set it as 'ktable' for pattern */
  127. }
  128. /*
  129. ** Add element 'idx' to 'ktable' of pattern at the top of the stack;
  130. ** Return index of new element.
  131. ** If new element is nil, does not add it to table (as it would be
  132. ** useless) and returns 0, as ktable[0] is always nil.
  133. */
  134. static int addtoktable (lua_State *L, int idx) {
  135. if (lua_isnil(L, idx)) /* nil value? */
  136. return 0;
  137. else {
  138. int n;
  139. lua_getuservalue(L, -1); /* get ktable from pattern */
  140. n = lua_rawlen(L, -1);
  141. if (n >= USHRT_MAX)
  142. luaL_error(L, "too many Lua values in pattern");
  143. lua_pushvalue(L, idx); /* element to be added */
  144. lua_rawseti(L, -2, ++n);
  145. lua_pop(L, 1); /* remove 'ktable' */
  146. return n;
  147. }
  148. }
  149. /*
  150. ** Return the number of elements in the ktable at 'idx'.
  151. ** In Lua 5.2/5.3, default "environment" for patterns is nil, not
  152. ** a table. Treat it as an empty table. In Lua 5.1, assumes that
  153. ** the environment has no numeric indices (len == 0)
  154. */
  155. static int ktablelen (lua_State *L, int idx) {
  156. if (!lua_istable(L, idx)) return 0;
  157. else return lua_rawlen(L, idx);
  158. }
  159. /*
  160. ** Concatentate the contents of table 'idx1' into table 'idx2'.
  161. ** (Assume that both indices are negative.)
  162. ** Return the original length of table 'idx2' (or 0, if no
  163. ** element was added, as there is no need to correct any index).
  164. */
  165. static int concattable (lua_State *L, int idx1, int idx2) {
  166. int i;
  167. int n1 = ktablelen(L, idx1);
  168. int n2 = ktablelen(L, idx2);
  169. if (n1 + n2 > USHRT_MAX)
  170. luaL_error(L, "too many Lua values in pattern");
  171. if (n1 == 0) return 0; /* nothing to correct */
  172. for (i = 1; i <= n1; i++) {
  173. lua_rawgeti(L, idx1, i);
  174. lua_rawseti(L, idx2 - 1, n2 + i); /* correct 'idx2' */
  175. }
  176. return n2;
  177. }
  178. /*
  179. ** When joining 'ktables', constants from one of the subpatterns must
  180. ** be renumbered; 'correctkeys' corrects their indices (adding 'n'
  181. ** to each of them)
  182. */
  183. static void correctkeys (TTree *tree, int n) {
  184. if (n == 0) return; /* no correction? */
  185. tailcall:
  186. switch (tree->tag) {
  187. case TOpenCall: case TCall: case TRunTime: case TRule: {
  188. if (tree->key > 0)
  189. tree->key += n;
  190. break;
  191. }
  192. case TCapture: {
  193. if (tree->key > 0 && tree->cap != Carg && tree->cap != Cnum)
  194. tree->key += n;
  195. break;
  196. }
  197. default: break;
  198. }
  199. switch (numsiblings[tree->tag]) {
  200. case 1: /* correctkeys(sib1(tree), n); */
  201. tree = sib1(tree); goto tailcall;
  202. case 2:
  203. correctkeys(sib1(tree), n);
  204. tree = sib2(tree); goto tailcall; /* correctkeys(sib2(tree), n); */
  205. default: assert(numsiblings[tree->tag] == 0); break;
  206. }
  207. }
  208. /*
  209. ** Join the ktables from p1 and p2 the ktable for the new pattern at the
  210. ** top of the stack, reusing them when possible.
  211. */
  212. static void joinktables (lua_State *L, int p1, TTree *t2, int p2) {
  213. int n1, n2;
  214. lua_getuservalue(L, p1); /* get ktables */
  215. lua_getuservalue(L, p2);
  216. n1 = ktablelen(L, -2);
  217. n2 = ktablelen(L, -1);
  218. if (n1 == 0 && n2 == 0) /* are both tables empty? */
  219. lua_pop(L, 2); /* nothing to be done; pop tables */
  220. else if (n2 == 0 || lp_equal(L, -2, -1)) { /* 2nd table empty or equal? */
  221. lua_pop(L, 1); /* pop 2nd table */
  222. lua_setuservalue(L, -2); /* set 1st ktable into new pattern */
  223. }
  224. else if (n1 == 0) { /* first table is empty? */
  225. lua_setuservalue(L, -3); /* set 2nd table into new pattern */
  226. lua_pop(L, 1); /* pop 1st table */
  227. }
  228. else {
  229. lua_createtable(L, n1 + n2, 0); /* create ktable for new pattern */
  230. /* stack: new p; ktable p1; ktable p2; new ktable */
  231. concattable(L, -3, -1); /* from p1 into new ktable */
  232. concattable(L, -2, -1); /* from p2 into new ktable */
  233. lua_setuservalue(L, -4); /* new ktable becomes 'p' environment */
  234. lua_pop(L, 2); /* pop other ktables */
  235. correctkeys(t2, n1); /* correction for indices from p2 */
  236. }
  237. }
  238. /*
  239. ** copy 'ktable' of element 'idx' to new tree (on top of stack)
  240. */
  241. static void copyktable (lua_State *L, int idx) {
  242. lua_getuservalue(L, idx);
  243. lua_setuservalue(L, -2);
  244. }
  245. /*
  246. ** merge 'ktable' from 'stree' at stack index 'idx' into 'ktable'
  247. ** from tree at the top of the stack, and correct corresponding
  248. ** tree.
  249. */
  250. static void mergektable (lua_State *L, int idx, TTree *stree) {
  251. int n;
  252. lua_getuservalue(L, -1); /* get ktables */
  253. lua_getuservalue(L, idx);
  254. n = concattable(L, -1, -2);
  255. lua_pop(L, 2); /* remove both ktables */
  256. correctkeys(stree, n);
  257. }
  258. /*
  259. ** Create a new 'ktable' to the pattern at the top of the stack, adding
  260. ** all elements from pattern 'p' (if not 0) plus element 'idx' to it.
  261. ** Return index of new element.
  262. */
  263. static int addtonewktable (lua_State *L, int p, int idx) {
  264. newktable(L, 1);
  265. if (p)
  266. mergektable(L, p, NULL);
  267. return addtoktable(L, idx);
  268. }
  269. /* }====================================================== */
  270. /*
  271. ** {======================================================
  272. ** Tree generation
  273. ** =======================================================
  274. */
  275. /*
  276. ** In 5.2, could use 'luaL_testudata'...
  277. */
  278. static int testpattern (lua_State *L, int idx) {
  279. if (lua_touserdata(L, idx)) { /* value is a userdata? */
  280. if (lua_getmetatable(L, idx)) { /* does it have a metatable? */
  281. luaL_getmetatable(L, PATTERN_T);
  282. if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
  283. lua_pop(L, 2); /* remove both metatables */
  284. return 1;
  285. }
  286. }
  287. }
  288. return 0;
  289. }
  290. static Pattern *getpattern (lua_State *L, int idx) {
  291. return (Pattern *)luaL_checkudata(L, idx, PATTERN_T);
  292. }
  293. static int getsize (lua_State *L, int idx) {
  294. return (lua_rawlen(L, idx) - offsetof(Pattern, tree)) / sizeof(TTree);
  295. }
  296. static TTree *gettree (lua_State *L, int idx, int *len) {
  297. Pattern *p = getpattern(L, idx);
  298. if (len)
  299. *len = getsize(L, idx);
  300. return p->tree;
  301. }
  302. /*
  303. ** create a pattern followed by a tree with 'len' nodes. Set its
  304. ** uservalue (the 'ktable') equal to its metatable. (It could be any
  305. ** empty sequence; the metatable is at hand here, so we use it.)
  306. */
  307. static TTree *newtree (lua_State *L, int len) {
  308. size_t size = offsetof(Pattern, tree) + len * sizeof(TTree);
  309. Pattern *p = (Pattern *)lua_newuserdata(L, size);
  310. luaL_getmetatable(L, PATTERN_T);
  311. lua_pushvalue(L, -1);
  312. lua_setuservalue(L, -3);
  313. lua_setmetatable(L, -2);
  314. p->code = NULL;
  315. return p->tree;
  316. }
  317. static TTree *newleaf (lua_State *L, int tag) {
  318. TTree *tree = newtree(L, 1);
  319. tree->tag = tag;
  320. return tree;
  321. }
  322. /*
  323. ** Create a tree for a charset, optimizing for special cases: empty set,
  324. ** full set, and singleton set.
  325. */
  326. static TTree *newcharset (lua_State *L, byte *cs) {
  327. charsetinfo info;
  328. Opcode op = charsettype(cs, &info);
  329. switch (op) {
  330. case IFail: return newleaf(L, TFalse); /* empty set */
  331. case IAny: return newleaf(L, TAny); /* full set */
  332. case IChar: { /* singleton set */
  333. TTree *tree =newleaf(L, TChar);
  334. tree->u.n = info.offset;
  335. return tree;
  336. }
  337. default: { /* regular set */
  338. int i;
  339. int bsize = /* tree size in bytes */
  340. (int)offsetof(TTree, u.set.bitmap) + info.size;
  341. TTree *tree = newtree(L, bytes2slots(bsize));
  342. assert(op == ISet);
  343. tree->tag = TSet;
  344. tree->u.set.offset = info.offset;
  345. tree->u.set.size = info.size;
  346. tree->u.set.deflt = info.deflt;
  347. for (i = 0; i < info.size; i++) {
  348. assert(&treebuffer(tree)[i] < (byte*)tree + bsize);
  349. treebuffer(tree)[i] = cs[info.offset + i];
  350. }
  351. return tree;
  352. }
  353. }
  354. }
  355. /*
  356. ** Add to tree a sequence where first sibling is 'sib' (with size
  357. ** 'sibsize'); return position for second sibling.
  358. */
  359. static TTree *seqaux (TTree *tree, TTree *sib, int sibsize) {
  360. tree->tag = TSeq; tree->u.ps = sibsize + 1;
  361. memcpy(sib1(tree), sib, sibsize * sizeof(TTree));
  362. return sib2(tree);
  363. }
  364. /*
  365. ** Build a sequence of 'n' nodes, each with tag 'tag' and 'u.n' got
  366. ** from the array 's' (or 0 if array is NULL). (TSeq is binary, so it
  367. ** must build a sequence of sequence of sequence...)
  368. */
  369. static void fillseq (TTree *tree, int tag, int n, const char *s) {
  370. int i;
  371. for (i = 0; i < n - 1; i++) { /* initial n-1 copies of Seq tag; Seq ... */
  372. tree->tag = TSeq; tree->u.ps = 2;
  373. sib1(tree)->tag = tag;
  374. sib1(tree)->u.n = s ? (byte)s[i] : 0;
  375. tree = sib2(tree);
  376. }
  377. tree->tag = tag; /* last one does not need TSeq */
  378. tree->u.n = s ? (byte)s[i] : 0;
  379. }
  380. /*
  381. ** Numbers as patterns:
  382. ** 0 == true (always match); n == TAny repeated 'n' times;
  383. ** -n == not (TAny repeated 'n' times)
  384. */
  385. static TTree *numtree (lua_State *L, int n) {
  386. if (n == 0)
  387. return newleaf(L, TTrue);
  388. else {
  389. TTree *tree, *nd;
  390. if (n > 0)
  391. tree = nd = newtree(L, 2 * n - 1);
  392. else { /* negative: code it as !(-n) */
  393. n = -n;
  394. tree = newtree(L, 2 * n);
  395. tree->tag = TNot;
  396. nd = sib1(tree);
  397. }
  398. fillseq(nd, TAny, n, NULL); /* sequence of 'n' any's */
  399. return tree;
  400. }
  401. }
  402. /*
  403. ** Convert value at index 'idx' to a pattern
  404. */
  405. static TTree *getpatt (lua_State *L, int idx, int *len) {
  406. TTree *tree;
  407. switch (lua_type(L, idx)) {
  408. case LUA_TSTRING: {
  409. size_t slen;
  410. const char *s = lua_tolstring(L, idx, &slen); /* get string */
  411. if (slen == 0) /* empty? */
  412. tree = newleaf(L, TTrue); /* always match */
  413. else {
  414. tree = newtree(L, 2 * (slen - 1) + 1);
  415. fillseq(tree, TChar, slen, s); /* sequence of 'slen' chars */
  416. }
  417. break;
  418. }
  419. case LUA_TNUMBER: {
  420. int n = lua_tointeger(L, idx);
  421. tree = numtree(L, n);
  422. break;
  423. }
  424. case LUA_TBOOLEAN: {
  425. tree = (lua_toboolean(L, idx) ? newleaf(L, TTrue) : newleaf(L, TFalse));
  426. break;
  427. }
  428. case LUA_TTABLE: {
  429. tree = newgrammar(L, idx);
  430. break;
  431. }
  432. case LUA_TFUNCTION: {
  433. tree = newtree(L, 2);
  434. tree->tag = TRunTime;
  435. tree->key = addtonewktable(L, 0, idx);
  436. sib1(tree)->tag = TTrue;
  437. break;
  438. }
  439. default: {
  440. return gettree(L, idx, len);
  441. }
  442. }
  443. lua_replace(L, idx); /* put new tree into 'idx' slot */
  444. if (len)
  445. *len = getsize(L, idx);
  446. return tree;
  447. }
  448. /*
  449. ** create a new tree, whith a new root and one sibling.
  450. ** Sibling must be on the Lua stack, at index 1.
  451. */
  452. static TTree *newroot1sib (lua_State *L, int tag) {
  453. int s1;
  454. TTree *tree1 = getpatt(L, 1, &s1);
  455. TTree *tree = newtree(L, 1 + s1); /* create new tree */
  456. tree->tag = tag;
  457. memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
  458. copyktable(L, 1);
  459. return tree;
  460. }
  461. /*
  462. ** create a new tree, whith a new root and 2 siblings.
  463. ** Siblings must be on the Lua stack, first one at index 1.
  464. */
  465. static TTree *newroot2sib (lua_State *L, int tag) {
  466. int s1, s2;
  467. TTree *tree1 = getpatt(L, 1, &s1);
  468. TTree *tree2 = getpatt(L, 2, &s2);
  469. TTree *tree = newtree(L, 1 + s1 + s2); /* create new tree */
  470. tree->tag = tag;
  471. tree->u.ps = 1 + s1;
  472. memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
  473. memcpy(sib2(tree), tree2, s2 * sizeof(TTree));
  474. joinktables(L, 1, sib2(tree), 2);
  475. return tree;
  476. }
  477. static int lp_P (lua_State *L) {
  478. luaL_checkany(L, 1);
  479. getpatt(L, 1, NULL);
  480. lua_settop(L, 1);
  481. return 1;
  482. }
  483. /*
  484. ** sequence operator; optimizations:
  485. ** false x => false, x true => x, true x => x
  486. ** (cannot do x . false => false because x may have runtime captures)
  487. */
  488. static int lp_seq (lua_State *L) {
  489. TTree *tree1 = getpatt(L, 1, NULL);
  490. TTree *tree2 = getpatt(L, 2, NULL);
  491. if (tree1->tag == TFalse || tree2->tag == TTrue)
  492. lua_pushvalue(L, 1); /* false . x == false, x . true = x */
  493. else if (tree1->tag == TTrue)
  494. lua_pushvalue(L, 2); /* true . x = x */
  495. else
  496. newroot2sib(L, TSeq);
  497. return 1;
  498. }
  499. /*
  500. ** choice operator; optimizations:
  501. ** charset / charset => charset
  502. ** true / x => true, x / false => x, false / x => x
  503. ** (x / true is not equivalent to true)
  504. */
  505. static int lp_choice (lua_State *L) {
  506. Charset st1, st2;
  507. TTree *t1 = getpatt(L, 1, NULL);
  508. TTree *t2 = getpatt(L, 2, NULL);
  509. if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
  510. loopset(i, st1.cs[i] |= st2.cs[i]);
  511. newcharset(L, st1.cs);
  512. }
  513. else if (nofail(t1) || t2->tag == TFalse)
  514. lua_pushvalue(L, 1); /* true / x => true, x / false => x */
  515. else if (t1->tag == TFalse)
  516. lua_pushvalue(L, 2); /* false / x => x */
  517. else
  518. newroot2sib(L, TChoice);
  519. return 1;
  520. }
  521. /*
  522. ** p^n
  523. */
  524. static int lp_star (lua_State *L) {
  525. int size1;
  526. int n = (int)luaL_checkinteger(L, 2);
  527. TTree *tree1 = getpatt(L, 1, &size1);
  528. if (n >= 0) { /* seq tree1 (seq tree1 ... (seq tree1 (rep tree1))) */
  529. TTree *tree = newtree(L, (n + 1) * (size1 + 1));
  530. if (nullable(tree1))
  531. luaL_error(L, "loop body may accept empty string");
  532. while (n--) /* repeat 'n' times */
  533. tree = seqaux(tree, tree1, size1);
  534. tree->tag = TRep;
  535. memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
  536. }
  537. else { /* choice (seq tree1 ... choice tree1 true ...) true */
  538. TTree *tree;
  539. n = -n;
  540. /* size = (choice + seq + tree1 + true) * n, but the last has no seq */
  541. tree = newtree(L, n * (size1 + 3) - 1);
  542. for (; n > 1; n--) { /* repeat (n - 1) times */
  543. tree->tag = TChoice; tree->u.ps = n * (size1 + 3) - 2;
  544. sib2(tree)->tag = TTrue;
  545. tree = sib1(tree);
  546. tree = seqaux(tree, tree1, size1);
  547. }
  548. tree->tag = TChoice; tree->u.ps = size1 + 1;
  549. sib2(tree)->tag = TTrue;
  550. memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
  551. }
  552. copyktable(L, 1);
  553. return 1;
  554. }
  555. /*
  556. ** #p == &p
  557. */
  558. static int lp_and (lua_State *L) {
  559. newroot1sib(L, TAnd);
  560. return 1;
  561. }
  562. /*
  563. ** -p == !p
  564. */
  565. static int lp_not (lua_State *L) {
  566. newroot1sib(L, TNot);
  567. return 1;
  568. }
  569. /*
  570. ** [t1 - t2] == Seq (Not t2) t1
  571. ** If t1 and t2 are charsets, make their difference.
  572. */
  573. static int lp_sub (lua_State *L) {
  574. Charset st1, st2;
  575. int s1, s2;
  576. TTree *t1 = getpatt(L, 1, &s1);
  577. TTree *t2 = getpatt(L, 2, &s2);
  578. if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
  579. loopset(i, st1.cs[i] &= ~st2.cs[i]);
  580. newcharset(L, st1.cs);
  581. }
  582. else {
  583. TTree *tree = newtree(L, 2 + s1 + s2);
  584. tree->tag = TSeq; /* sequence of... */
  585. tree->u.ps = 2 + s2;
  586. sib1(tree)->tag = TNot; /* ...not... */
  587. memcpy(sib1(sib1(tree)), t2, s2 * sizeof(TTree)); /* ...t2 */
  588. memcpy(sib2(tree), t1, s1 * sizeof(TTree)); /* ... and t1 */
  589. joinktables(L, 1, sib1(tree), 2);
  590. }
  591. return 1;
  592. }
  593. static int lp_set (lua_State *L) {
  594. size_t l;
  595. const char *s = luaL_checklstring(L, 1, &l);
  596. byte buff[CHARSETSIZE];
  597. clearset(buff);
  598. while (l--) {
  599. setchar(buff, (byte)(*s));
  600. s++;
  601. }
  602. newcharset(L, buff);
  603. return 1;
  604. }
  605. static int lp_range (lua_State *L) {
  606. int arg;
  607. int top = lua_gettop(L);
  608. byte buff[CHARSETSIZE];
  609. clearset(buff);
  610. for (arg = 1; arg <= top; arg++) {
  611. int c;
  612. size_t l;
  613. const char *r = luaL_checklstring(L, arg, &l);
  614. luaL_argcheck(L, l == 2, arg, "range must have two characters");
  615. for (c = (byte)r[0]; c <= (byte)r[1]; c++)
  616. setchar(buff, c);
  617. }
  618. newcharset(L, buff);
  619. return 1;
  620. }
  621. /*
  622. ** Fills a tree node with basic information about the UTF-8 code point
  623. ** 'cpu': its value in 'n', its length in 'cap', and its first byte in
  624. ** 'key'
  625. */
  626. static void codeutftree (lua_State *L, TTree *t, lua_Unsigned cpu, int arg) {
  627. int len, fb, cp;
  628. cp = (int)cpu;
  629. if (cp <= 0x7f) { /* one byte? */
  630. len = 1;
  631. fb = cp;
  632. } else if (cp <= 0x7ff) {
  633. len = 2;
  634. fb = 0xC0 | (cp >> 6);
  635. } else if (cp <= 0xffff) {
  636. len = 3;
  637. fb = 0xE0 | (cp >> 12);
  638. }
  639. else {
  640. luaL_argcheck(L, cpu <= 0x10ffffu, arg, "invalid code point");
  641. len = 4;
  642. fb = 0xF0 | (cp >> 18);
  643. }
  644. t->u.n = cp;
  645. t->cap = len;
  646. t->key = fb;
  647. }
  648. static int lp_utfr (lua_State *L) {
  649. lua_Unsigned from = (lua_Unsigned)luaL_checkinteger(L, 1);
  650. lua_Unsigned to = (lua_Unsigned)luaL_checkinteger(L, 2);
  651. luaL_argcheck(L, from <= to, 2, "empty range");
  652. if (to <= 0x7f) { /* ascii range? */
  653. uint f;
  654. byte buff[CHARSETSIZE]; /* code it as a regular charset */
  655. clearset(buff);
  656. for (f = (int)from; f <= to; f++)
  657. setchar(buff, f);
  658. newcharset(L, buff);
  659. }
  660. else { /* multi-byte utf-8 range */
  661. TTree *tree = newtree(L, 2);
  662. tree->tag = TUTFR;
  663. codeutftree(L, tree, from, 1);
  664. sib1(tree)->tag = TXInfo;
  665. codeutftree(L, sib1(tree), to, 2);
  666. }
  667. return 1;
  668. }
  669. /*
  670. ** Look-behind predicate
  671. */
  672. static int lp_behind (lua_State *L) {
  673. TTree *tree;
  674. TTree *tree1 = getpatt(L, 1, NULL);
  675. int n = fixedlen(tree1);
  676. luaL_argcheck(L, n >= 0, 1, "pattern may not have fixed length");
  677. luaL_argcheck(L, !hascaptures(tree1), 1, "pattern have captures");
  678. luaL_argcheck(L, n <= MAXBEHIND, 1, "pattern too long to look behind");
  679. tree = newroot1sib(L, TBehind);
  680. tree->u.n = n;
  681. return 1;
  682. }
  683. /*
  684. ** Create a non-terminal
  685. */
  686. static int lp_V (lua_State *L) {
  687. TTree *tree = newleaf(L, TOpenCall);
  688. luaL_argcheck(L, !lua_isnoneornil(L, 1), 1, "non-nil value expected");
  689. tree->key = addtonewktable(L, 0, 1);
  690. return 1;
  691. }
  692. /*
  693. ** Create a tree for a non-empty capture, with a body and
  694. ** optionally with an associated Lua value (at index 'labelidx' in the
  695. ** stack)
  696. */
  697. static int capture_aux (lua_State *L, int cap, int labelidx) {
  698. TTree *tree = newroot1sib(L, TCapture);
  699. tree->cap = cap;
  700. tree->key = (labelidx == 0) ? 0 : addtonewktable(L, 1, labelidx);
  701. return 1;
  702. }
  703. /*
  704. ** Fill a tree with an empty capture, using an empty (TTrue) sibling.
  705. ** (The 'key' field must be filled by the caller to finish the tree.)
  706. */
  707. static TTree *auxemptycap (TTree *tree, int cap) {
  708. tree->tag = TCapture;
  709. tree->cap = cap;
  710. sib1(tree)->tag = TTrue;
  711. return tree;
  712. }
  713. /*
  714. ** Create a tree for an empty capture.
  715. */
  716. static TTree *newemptycap (lua_State *L, int cap, int key) {
  717. TTree *tree = auxemptycap(newtree(L, 2), cap);
  718. tree->key = key;
  719. return tree;
  720. }
  721. /*
  722. ** Create a tree for an empty capture with an associated Lua value.
  723. */
  724. static TTree *newemptycapkey (lua_State *L, int cap, int idx) {
  725. TTree *tree = auxemptycap(newtree(L, 2), cap);
  726. tree->key = addtonewktable(L, 0, idx);
  727. return tree;
  728. }
  729. /*
  730. ** Captures with syntax p / v
  731. ** (function capture, query capture, string capture, or number capture)
  732. */
  733. static int lp_divcapture (lua_State *L) {
  734. switch (lua_type(L, 2)) {
  735. case LUA_TFUNCTION: return capture_aux(L, Cfunction, 2);
  736. case LUA_TTABLE: return capture_aux(L, Cquery, 2);
  737. case LUA_TSTRING: return capture_aux(L, Cstring, 2);
  738. case LUA_TNUMBER: {
  739. int n = lua_tointeger(L, 2);
  740. TTree *tree = newroot1sib(L, TCapture);
  741. luaL_argcheck(L, 0 <= n && n <= SHRT_MAX, 1, "invalid number");
  742. tree->cap = Cnum;
  743. tree->key = n;
  744. return 1;
  745. }
  746. default:
  747. return luaL_error(L, "unexpected %s as 2nd operand to LPeg '/'",
  748. luaL_typename(L, 2));
  749. }
  750. }
  751. static int lp_acccapture (lua_State *L) {
  752. return capture_aux(L, Cacc, 2);
  753. }
  754. static int lp_substcapture (lua_State *L) {
  755. return capture_aux(L, Csubst, 0);
  756. }
  757. static int lp_tablecapture (lua_State *L) {
  758. return capture_aux(L, Ctable, 0);
  759. }
  760. static int lp_groupcapture (lua_State *L) {
  761. if (lua_isnoneornil(L, 2))
  762. return capture_aux(L, Cgroup, 0);
  763. else
  764. return capture_aux(L, Cgroup, 2);
  765. }
  766. static int lp_foldcapture (lua_State *L) {
  767. luaL_checktype(L, 2, LUA_TFUNCTION);
  768. return capture_aux(L, Cfold, 2);
  769. }
  770. static int lp_simplecapture (lua_State *L) {
  771. return capture_aux(L, Csimple, 0);
  772. }
  773. static int lp_poscapture (lua_State *L) {
  774. newemptycap(L, Cposition, 0);
  775. return 1;
  776. }
  777. static int lp_argcapture (lua_State *L) {
  778. int n = (int)luaL_checkinteger(L, 1);
  779. luaL_argcheck(L, 0 < n && n <= SHRT_MAX, 1, "invalid argument index");
  780. newemptycap(L, Carg, n);
  781. return 1;
  782. }
  783. static int lp_backref (lua_State *L) {
  784. luaL_checkany(L, 1);
  785. newemptycapkey(L, Cbackref, 1);
  786. return 1;
  787. }
  788. /*
  789. ** Constant capture
  790. */
  791. static int lp_constcapture (lua_State *L) {
  792. int i;
  793. int n = lua_gettop(L); /* number of values */
  794. if (n == 0) /* no values? */
  795. newleaf(L, TTrue); /* no capture */
  796. else if (n == 1)
  797. newemptycapkey(L, Cconst, 1); /* single constant capture */
  798. else { /* create a group capture with all values */
  799. TTree *tree = newtree(L, 1 + 3 * (n - 1) + 2);
  800. newktable(L, n); /* create a 'ktable' for new tree */
  801. tree->tag = TCapture;
  802. tree->cap = Cgroup;
  803. tree->key = 0;
  804. tree = sib1(tree);
  805. for (i = 1; i <= n - 1; i++) {
  806. tree->tag = TSeq;
  807. tree->u.ps = 3; /* skip TCapture and its sibling */
  808. auxemptycap(sib1(tree), Cconst);
  809. sib1(tree)->key = addtoktable(L, i);
  810. tree = sib2(tree);
  811. }
  812. auxemptycap(tree, Cconst);
  813. tree->key = addtoktable(L, i);
  814. }
  815. return 1;
  816. }
  817. static int lp_matchtime (lua_State *L) {
  818. TTree *tree;
  819. luaL_checktype(L, 2, LUA_TFUNCTION);
  820. tree = newroot1sib(L, TRunTime);
  821. tree->key = addtonewktable(L, 1, 2);
  822. return 1;
  823. }
  824. /* }====================================================== */
  825. /*
  826. ** {======================================================
  827. ** Grammar - Tree generation
  828. ** =======================================================
  829. */
  830. /*
  831. ** push on the stack the index and the pattern for the
  832. ** initial rule of grammar at index 'arg' in the stack;
  833. ** also add that index into position table.
  834. */
  835. static void getfirstrule (lua_State *L, int arg, int postab) {
  836. lua_rawgeti(L, arg, 1); /* access first element */
  837. if (lua_isstring(L, -1)) { /* is it the name of initial rule? */
  838. lua_pushvalue(L, -1); /* duplicate it to use as key */
  839. lua_gettable(L, arg); /* get associated rule */
  840. }
  841. else {
  842. lua_pushinteger(L, 1); /* key for initial rule */
  843. lua_insert(L, -2); /* put it before rule */
  844. }
  845. if (!testpattern(L, -1)) { /* initial rule not a pattern? */
  846. if (lua_isnil(L, -1))
  847. luaL_error(L, "grammar has no initial rule");
  848. else
  849. luaL_error(L, "initial rule '%s' is not a pattern", lua_tostring(L, -2));
  850. }
  851. lua_pushvalue(L, -2); /* push key */
  852. lua_pushinteger(L, 1); /* push rule position (after TGrammar) */
  853. lua_settable(L, postab); /* insert pair at position table */
  854. }
  855. /*
  856. ** traverse grammar at index 'arg', pushing all its keys and patterns
  857. ** into the stack. Create a new table (before all pairs key-pattern) to
  858. ** collect all keys and their associated positions in the final tree
  859. ** (the "position table").
  860. ** Return the number of rules and (in 'totalsize') the total size
  861. ** for the new tree.
  862. */
  863. static int collectrules (lua_State *L, int arg, int *totalsize) {
  864. int n = 1; /* to count number of rules */
  865. int postab = lua_gettop(L) + 1; /* index of position table */
  866. int size; /* accumulator for total size */
  867. lua_newtable(L); /* create position table */
  868. getfirstrule(L, arg, postab);
  869. size = 3 + getsize(L, postab + 2); /* TGrammar + TRule + TXInfo + rule */
  870. lua_pushnil(L); /* prepare to traverse grammar table */
  871. while (lua_next(L, arg) != 0) {
  872. if (lua_tonumber(L, -2) == 1 ||
  873. lp_equal(L, -2, postab + 1)) { /* initial rule? */
  874. lua_pop(L, 1); /* remove value (keep key for lua_next) */
  875. continue;
  876. }
  877. if (!testpattern(L, -1)) /* value is not a pattern? */
  878. luaL_error(L, "rule '%s' is not a pattern", val2str(L, -2));
  879. luaL_checkstack(L, LUA_MINSTACK, "grammar has too many rules");
  880. lua_pushvalue(L, -2); /* push key (to insert into position table) */
  881. lua_pushinteger(L, size);
  882. lua_settable(L, postab);
  883. size += 2 + getsize(L, -1); /* add 'TRule + TXInfo + rule' to size */
  884. lua_pushvalue(L, -2); /* push key (for next lua_next) */
  885. n++;
  886. }
  887. *totalsize = size + 1; /* space for 'TTrue' finishing list of rules */
  888. return n;
  889. }
  890. static void buildgrammar (lua_State *L, TTree *grammar, int frule, int n) {
  891. int i;
  892. TTree *nd = sib1(grammar); /* auxiliary pointer to traverse the tree */
  893. for (i = 0; i < n; i++) { /* add each rule into new tree */
  894. int ridx = frule + 2*i + 1; /* index of i-th rule */
  895. int rulesize;
  896. TTree *rn = gettree(L, ridx, &rulesize);
  897. TTree *pr = sib1(nd); /* points to rule's prerule */
  898. nd->tag = TRule;
  899. nd->key = 0; /* will be fixed when rule is used */
  900. pr->tag = TXInfo;
  901. pr->u.n = i; /* rule number */
  902. nd->u.ps = rulesize + 2; /* point to next rule */
  903. memcpy(sib1(pr), rn, rulesize * sizeof(TTree)); /* copy rule */
  904. mergektable(L, ridx, sib1(nd)); /* merge its ktable into new one */
  905. nd = sib2(nd); /* move to next rule */
  906. }
  907. nd->tag = TTrue; /* finish list of rules */
  908. }
  909. /*
  910. ** Check whether a tree has potential infinite loops
  911. */
  912. static int checkloops (TTree *tree) {
  913. tailcall:
  914. if (tree->tag == TRep && nullable(sib1(tree)))
  915. return 1;
  916. else if (tree->tag == TGrammar)
  917. return 0; /* sub-grammars already checked */
  918. else {
  919. switch (numsiblings[tree->tag]) {
  920. case 1: /* return checkloops(sib1(tree)); */
  921. tree = sib1(tree); goto tailcall;
  922. case 2:
  923. if (checkloops(sib1(tree))) return 1;
  924. /* else return checkloops(sib2(tree)); */
  925. tree = sib2(tree); goto tailcall;
  926. default: assert(numsiblings[tree->tag] == 0); return 0;
  927. }
  928. }
  929. }
  930. /*
  931. ** Give appropriate error message for 'verifyrule'. If a rule appears
  932. ** twice in 'passed', there is path from it back to itself without
  933. ** advancing the subject.
  934. */
  935. static int verifyerror (lua_State *L, unsigned short *passed, int npassed) {
  936. int i, j;
  937. for (i = npassed - 1; i >= 0; i--) { /* search for a repetition */
  938. for (j = i - 1; j >= 0; j--) {
  939. if (passed[i] == passed[j]) {
  940. lua_rawgeti(L, -1, passed[i]); /* get rule's key */
  941. return luaL_error(L, "rule '%s' may be left recursive", val2str(L, -1));
  942. }
  943. }
  944. }
  945. return luaL_error(L, "too many left calls in grammar");
  946. }
  947. /*
  948. ** Check whether a rule can be left recursive; raise an error in that
  949. ** case; otherwise return 1 iff pattern is nullable.
  950. ** The return value is used to check sequences, where the second pattern
  951. ** is only relevant if the first is nullable.
  952. ** Parameter 'nb' works as an accumulator, to allow tail calls in
  953. ** choices. ('nb' true makes function returns true.)
  954. ** Parameter 'passed' is a list of already visited rules, 'npassed'
  955. ** counts the elements in 'passed'.
  956. ** Assume ktable at the top of the stack.
  957. */
  958. static int verifyrule (lua_State *L, TTree *tree, unsigned short *passed,
  959. int npassed, int nb) {
  960. tailcall:
  961. switch (tree->tag) {
  962. case TChar: case TSet: case TAny:
  963. case TFalse: case TUTFR:
  964. return nb; /* cannot pass from here */
  965. case TTrue:
  966. case TBehind: /* look-behind cannot have calls */
  967. return 1;
  968. case TNot: case TAnd: case TRep:
  969. /* return verifyrule(L, sib1(tree), passed, npassed, 1); */
  970. tree = sib1(tree); nb = 1; goto tailcall;
  971. case TCapture: case TRunTime: case TXInfo:
  972. /* return verifyrule(L, sib1(tree), passed, npassed, nb); */
  973. tree = sib1(tree); goto tailcall;
  974. case TCall:
  975. /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
  976. tree = sib2(tree); goto tailcall;
  977. case TSeq: /* only check 2nd child if first is nb */
  978. if (!verifyrule(L, sib1(tree), passed, npassed, 0))
  979. return nb;
  980. /* else return verifyrule(L, sib2(tree), passed, npassed, nb); */
  981. tree = sib2(tree); goto tailcall;
  982. case TChoice: /* must check both children */
  983. nb = verifyrule(L, sib1(tree), passed, npassed, nb);
  984. /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
  985. tree = sib2(tree); goto tailcall;
  986. case TRule:
  987. if (npassed >= MAXRULES) /* too many steps? */
  988. return verifyerror(L, passed, npassed); /* error */
  989. else {
  990. passed[npassed++] = tree->key; /* add rule to path */
  991. /* return verifyrule(L, sib1(tree), passed, npassed); */
  992. tree = sib1(tree); goto tailcall;
  993. }
  994. case TGrammar:
  995. return nullable(tree); /* sub-grammar cannot be left recursive */
  996. default: assert(0); return 0;
  997. }
  998. }
  999. static void verifygrammar (lua_State *L, TTree *grammar) {
  1000. unsigned short passed[MAXRULES];
  1001. TTree *rule;
  1002. /* check left-recursive rules */
  1003. for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
  1004. if (rule->key == 0) continue; /* unused rule */
  1005. verifyrule(L, sib1(rule), passed, 0, 0);
  1006. }
  1007. assert(rule->tag == TTrue);
  1008. /* check infinite loops inside rules */
  1009. for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
  1010. if (rule->key == 0) continue; /* unused rule */
  1011. if (checkloops(sib1(rule))) {
  1012. lua_rawgeti(L, -1, rule->key); /* get rule's key */
  1013. luaL_error(L, "empty loop in rule '%s'", val2str(L, -1));
  1014. }
  1015. }
  1016. assert(rule->tag == TTrue);
  1017. }
  1018. /*
  1019. ** Give a name for the initial rule if it is not referenced
  1020. */
  1021. static void initialrulename (lua_State *L, TTree *grammar, int frule) {
  1022. if (sib1(grammar)->key == 0) { /* initial rule is not referenced? */
  1023. int n = lua_rawlen(L, -1) + 1; /* index for name */
  1024. lua_pushvalue(L, frule); /* rule's name */
  1025. lua_rawseti(L, -2, n); /* ktable was on the top of the stack */
  1026. sib1(grammar)->key = n;
  1027. }
  1028. }
  1029. static TTree *newgrammar (lua_State *L, int arg) {
  1030. int treesize;
  1031. int frule = lua_gettop(L) + 2; /* position of first rule's key */
  1032. int n = collectrules(L, arg, &treesize);
  1033. TTree *g = newtree(L, treesize);
  1034. luaL_argcheck(L, n <= MAXRULES, arg, "grammar has too many rules");
  1035. g->tag = TGrammar; g->u.n = n;
  1036. lua_newtable(L); /* create 'ktable' */
  1037. lua_setuservalue(L, -2);
  1038. buildgrammar(L, g, frule, n);
  1039. lua_getuservalue(L, -1); /* get 'ktable' for new tree */
  1040. finalfix(L, frule - 1, g, sib1(g));
  1041. initialrulename(L, g, frule);
  1042. verifygrammar(L, g);
  1043. lua_pop(L, 1); /* remove 'ktable' */
  1044. lua_insert(L, -(n * 2 + 2)); /* move new table to proper position */
  1045. lua_pop(L, n * 2 + 1); /* remove position table + rule pairs */
  1046. return g; /* new table at the top of the stack */
  1047. }
  1048. /* }====================================================== */
  1049. static Instruction *prepcompile (lua_State *L, Pattern *p, int idx) {
  1050. lua_getuservalue(L, idx); /* push 'ktable' (may be used by 'finalfix') */
  1051. finalfix(L, 0, NULL, p->tree);
  1052. lua_pop(L, 1); /* remove 'ktable' */
  1053. return compile(L, p, getsize(L, idx));
  1054. }
  1055. static int lp_printtree (lua_State *L) {
  1056. TTree *tree = getpatt(L, 1, NULL);
  1057. int c = lua_toboolean(L, 2);
  1058. if (c) {
  1059. lua_getuservalue(L, 1); /* push 'ktable' (may be used by 'finalfix') */
  1060. finalfix(L, 0, NULL, tree);
  1061. lua_pop(L, 1); /* remove 'ktable' */
  1062. }
  1063. printktable(L, 1);
  1064. printtree(tree, 0);
  1065. return 0;
  1066. }
  1067. static int lp_printcode (lua_State *L) {
  1068. Pattern *p = getpattern(L, 1);
  1069. printktable(L, 1);
  1070. if (p->code == NULL) /* not compiled yet? */
  1071. prepcompile(L, p, 1);
  1072. printpatt(p->code);
  1073. return 0;
  1074. }
  1075. /*
  1076. ** Get the initial position for the match, interpreting negative
  1077. ** values from the end of the subject
  1078. */
  1079. static size_t initposition (lua_State *L, size_t len) {
  1080. lua_Integer ii = luaL_optinteger(L, 3, 1);
  1081. if (ii > 0) { /* positive index? */
  1082. if ((size_t)ii <= len) /* inside the string? */
  1083. return (size_t)ii - 1; /* return it (corrected to 0-base) */
  1084. else return len; /* crop at the end */
  1085. }
  1086. else { /* negative index */
  1087. if ((size_t)(-ii) <= len) /* inside the string? */
  1088. return len - ((size_t)(-ii)); /* return position from the end */
  1089. else return 0; /* crop at the beginning */
  1090. }
  1091. }
  1092. /*
  1093. ** Main match function
  1094. */
  1095. static int lp_match (lua_State *L) {
  1096. Capture capture[INITCAPSIZE];
  1097. const char *r;
  1098. size_t l;
  1099. Pattern *p = (getpatt(L, 1, NULL), getpattern(L, 1));
  1100. Instruction *code = (p->code != NULL) ? p->code : prepcompile(L, p, 1);
  1101. const char *s = luaL_checklstring(L, SUBJIDX, &l);
  1102. size_t i = initposition(L, l);
  1103. int ptop = lua_gettop(L);
  1104. luaL_argcheck(L, l < MAXINDT, SUBJIDX, "subject too long");
  1105. lua_pushnil(L); /* initialize subscache */
  1106. lua_pushlightuserdata(L, capture); /* initialize caplistidx */
  1107. lua_getuservalue(L, 1); /* initialize ktableidx */
  1108. r = match(L, s, s + i, s + l, code, capture, ptop);
  1109. if (r == NULL) {
  1110. lua_pushnil(L);
  1111. return 1;
  1112. }
  1113. return getcaptures(L, s, r, ptop);
  1114. }
  1115. /*
  1116. ** {======================================================
  1117. ** Library creation and functions not related to matching
  1118. ** =======================================================
  1119. */
  1120. /* maximum limit for stack size */
  1121. #define MAXLIM (INT_MAX / 100)
  1122. static int lp_setmax (lua_State *L) {
  1123. lua_Integer lim = luaL_checkinteger(L, 1);
  1124. luaL_argcheck(L, 0 < lim && lim <= MAXLIM, 1, "out of range");
  1125. lua_settop(L, 1);
  1126. lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
  1127. return 0;
  1128. }
  1129. static int lp_type (lua_State *L) {
  1130. if (testpattern(L, 1))
  1131. lua_pushliteral(L, "pattern");
  1132. else
  1133. lua_pushnil(L);
  1134. return 1;
  1135. }
  1136. int lp_gc (lua_State *L) {
  1137. Pattern *p = getpattern(L, 1);
  1138. freecode(L, p); /* delete code block */
  1139. return 0;
  1140. }
  1141. /*
  1142. ** Create a charset representing a category of characters, given by
  1143. ** the predicate 'catf'.
  1144. */
  1145. static void createcat (lua_State *L, const char *catname, int (catf) (int)) {
  1146. int c;
  1147. byte buff[CHARSETSIZE];
  1148. clearset(buff);
  1149. for (c = 0; c <= UCHAR_MAX; c++)
  1150. if (catf(c)) setchar(buff, c);
  1151. newcharset(L, buff);
  1152. lua_setfield(L, -2, catname);
  1153. }
  1154. static int lp_locale (lua_State *L) {
  1155. if (lua_isnoneornil(L, 1)) {
  1156. lua_settop(L, 0);
  1157. lua_createtable(L, 0, 12);
  1158. }
  1159. else {
  1160. luaL_checktype(L, 1, LUA_TTABLE);
  1161. lua_settop(L, 1);
  1162. }
  1163. createcat(L, "alnum", isalnum);
  1164. createcat(L, "alpha", isalpha);
  1165. createcat(L, "cntrl", iscntrl);
  1166. createcat(L, "digit", isdigit);
  1167. createcat(L, "graph", isgraph);
  1168. createcat(L, "lower", islower);
  1169. createcat(L, "print", isprint);
  1170. createcat(L, "punct", ispunct);
  1171. createcat(L, "space", isspace);
  1172. createcat(L, "upper", isupper);
  1173. createcat(L, "xdigit", isxdigit);
  1174. return 1;
  1175. }
  1176. static struct luaL_Reg pattreg[] = {
  1177. {"ptree", lp_printtree},
  1178. {"pcode", lp_printcode},
  1179. {"match", lp_match},
  1180. {"B", lp_behind},
  1181. {"V", lp_V},
  1182. {"C", lp_simplecapture},
  1183. {"Cc", lp_constcapture},
  1184. {"Cmt", lp_matchtime},
  1185. {"Cb", lp_backref},
  1186. {"Carg", lp_argcapture},
  1187. {"Cp", lp_poscapture},
  1188. {"Cs", lp_substcapture},
  1189. {"Ct", lp_tablecapture},
  1190. {"Cf", lp_foldcapture},
  1191. {"Cg", lp_groupcapture},
  1192. {"P", lp_P},
  1193. {"S", lp_set},
  1194. {"R", lp_range},
  1195. {"utfR", lp_utfr},
  1196. {"locale", lp_locale},
  1197. {"version", NULL},
  1198. {"setmaxstack", lp_setmax},
  1199. {"type", lp_type},
  1200. {NULL, NULL}
  1201. };
  1202. static struct luaL_Reg metareg[] = {
  1203. {"__mul", lp_seq},
  1204. {"__add", lp_choice},
  1205. {"__pow", lp_star},
  1206. {"__gc", lp_gc},
  1207. {"__len", lp_and},
  1208. {"__div", lp_divcapture},
  1209. {"__mod", lp_acccapture},
  1210. {"__unm", lp_not},
  1211. {"__sub", lp_sub},
  1212. {NULL, NULL}
  1213. };
  1214. int luaopen_lpeg (lua_State *L);
  1215. int luaopen_lpeg (lua_State *L) {
  1216. luaL_newmetatable(L, PATTERN_T);
  1217. lua_pushnumber(L, MAXBACK); /* initialize maximum backtracking */
  1218. lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
  1219. luaL_setfuncs(L, metareg, 0);
  1220. luaL_newlib(L, pattreg);
  1221. lua_pushvalue(L, -1);
  1222. lua_setfield(L, -3, "__index");
  1223. lua_pushliteral(L, "LPeg " VERSION);
  1224. lua_setfield(L, -2, "version");
  1225. return 1;
  1226. }
  1227. /* }====================================================== */