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.

lptree.c 36KB

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