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 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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. luaL_getmetatable(L, PATTERN_T);
  314. lua_pushvalue(L, -1);
  315. lua_setuservalue(L, -3);
  316. lua_setmetatable(L, -2);
  317. p->code = NULL; p->codesize = 0;
  318. return p->tree;
  319. }
  320. static TTree *newleaf (lua_State *L, int tag) {
  321. TTree *tree = newtree(L, 1);
  322. tree->tag = tag;
  323. return tree;
  324. }
  325. static TTree *newcharset (lua_State *L) {
  326. TTree *tree = newtree(L, bytes2slots(CHARSETSIZE) + 1);
  327. tree->tag = TSet;
  328. loopset(i, treebuffer(tree)[i] = 0);
  329. return tree;
  330. }
  331. /*
  332. ** add to tree a sequence where first sibling is 'sib' (with size
  333. ** 'sibsize'); returns position for second sibling
  334. */
  335. static TTree *seqaux (TTree *tree, TTree *sib, int sibsize) {
  336. tree->tag = TSeq; tree->u.ps = sibsize + 1;
  337. memcpy(sib1(tree), sib, sibsize * sizeof(TTree));
  338. return sib2(tree);
  339. }
  340. /*
  341. ** Build a sequence of 'n' nodes, each with tag 'tag' and 'u.n' got
  342. ** from the array 's' (or 0 if array is NULL). (TSeq is binary, so it
  343. ** must build a sequence of sequence of sequence...)
  344. */
  345. static void fillseq (TTree *tree, int tag, int n, const char *s) {
  346. int i;
  347. for (i = 0; i < n - 1; i++) { /* initial n-1 copies of Seq tag; Seq ... */
  348. tree->tag = TSeq; tree->u.ps = 2;
  349. sib1(tree)->tag = tag;
  350. sib1(tree)->u.n = s ? (byte)s[i] : 0;
  351. tree = sib2(tree);
  352. }
  353. tree->tag = tag; /* last one does not need TSeq */
  354. tree->u.n = s ? (byte)s[i] : 0;
  355. }
  356. /*
  357. ** Numbers as patterns:
  358. ** 0 == true (always match); n == TAny repeated 'n' times;
  359. ** -n == not (TAny repeated 'n' times)
  360. */
  361. static TTree *numtree (lua_State *L, int n) {
  362. if (n == 0)
  363. return newleaf(L, TTrue);
  364. else {
  365. TTree *tree, *nd;
  366. if (n > 0)
  367. tree = nd = newtree(L, 2 * n - 1);
  368. else { /* negative: code it as !(-n) */
  369. n = -n;
  370. tree = newtree(L, 2 * n);
  371. tree->tag = TNot;
  372. nd = sib1(tree);
  373. }
  374. fillseq(nd, TAny, n, NULL); /* sequence of 'n' any's */
  375. return tree;
  376. }
  377. }
  378. /*
  379. ** Convert value at index 'idx' to a pattern
  380. */
  381. static TTree *getpatt (lua_State *L, int idx, int *len) {
  382. TTree *tree;
  383. switch (lua_type(L, idx)) {
  384. case LUA_TSTRING: {
  385. size_t slen;
  386. const char *s = lua_tolstring(L, idx, &slen); /* get string */
  387. if (slen == 0) /* empty? */
  388. tree = newleaf(L, TTrue); /* always match */
  389. else {
  390. tree = newtree(L, 2 * (slen - 1) + 1);
  391. fillseq(tree, TChar, slen, s); /* sequence of 'slen' chars */
  392. }
  393. break;
  394. }
  395. case LUA_TNUMBER: {
  396. int n = lua_tointeger(L, idx);
  397. tree = numtree(L, n);
  398. break;
  399. }
  400. case LUA_TBOOLEAN: {
  401. tree = (lua_toboolean(L, idx) ? newleaf(L, TTrue) : newleaf(L, TFalse));
  402. break;
  403. }
  404. case LUA_TTABLE: {
  405. tree = newgrammar(L, idx);
  406. break;
  407. }
  408. case LUA_TFUNCTION: {
  409. tree = newtree(L, 2);
  410. tree->tag = TRunTime;
  411. tree->key = addtonewktable(L, 0, idx);
  412. sib1(tree)->tag = TTrue;
  413. break;
  414. }
  415. default: {
  416. return gettree(L, idx, len);
  417. }
  418. }
  419. lua_replace(L, idx); /* put new tree into 'idx' slot */
  420. if (len)
  421. *len = getsize(L, idx);
  422. return tree;
  423. }
  424. /*
  425. ** create a new tree, with a new root and one sibling.
  426. ** Sibling must be on the Lua stack, at index 1.
  427. */
  428. static TTree *newroot1sib (lua_State *L, int tag) {
  429. int s1;
  430. TTree *tree1 = getpatt(L, 1, &s1);
  431. TTree *tree = newtree(L, 1 + s1); /* create new tree */
  432. tree->tag = tag;
  433. memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
  434. copyktable(L, 1);
  435. return tree;
  436. }
  437. /*
  438. ** create a new tree, with a new root and 2 siblings.
  439. ** Siblings must be on the Lua stack, first one at index 1.
  440. */
  441. static TTree *newroot2sib (lua_State *L, int tag) {
  442. int s1, s2;
  443. TTree *tree1 = getpatt(L, 1, &s1);
  444. TTree *tree2 = getpatt(L, 2, &s2);
  445. TTree *tree = newtree(L, 1 + s1 + s2); /* create new tree */
  446. tree->tag = tag;
  447. tree->u.ps = 1 + s1;
  448. memcpy(sib1(tree), tree1, s1 * sizeof(TTree));
  449. memcpy(sib2(tree), tree2, s2 * sizeof(TTree));
  450. joinktables(L, 1, sib2(tree), 2);
  451. return tree;
  452. }
  453. static int lp_P (lua_State *L) {
  454. luaL_checkany(L, 1);
  455. getpatt(L, 1, NULL);
  456. lua_settop(L, 1);
  457. return 1;
  458. }
  459. /*
  460. ** sequence operator; optimizations:
  461. ** false x => false, x true => x, true x => x
  462. ** (cannot do x . false => false because x may have runtime captures)
  463. */
  464. static int lp_seq (lua_State *L) {
  465. TTree *tree1 = getpatt(L, 1, NULL);
  466. TTree *tree2 = getpatt(L, 2, NULL);
  467. if (tree1->tag == TFalse || tree2->tag == TTrue)
  468. lua_pushvalue(L, 1); /* false . x == false, x . true = x */
  469. else if (tree1->tag == TTrue)
  470. lua_pushvalue(L, 2); /* true . x = x */
  471. else
  472. newroot2sib(L, TSeq);
  473. return 1;
  474. }
  475. /*
  476. ** choice operator; optimizations:
  477. ** charset / charset => charset
  478. ** true / x => true, x / false => x, false / x => x
  479. ** (x / true is not equivalent to true)
  480. */
  481. static int lp_choice (lua_State *L) {
  482. Charset st1, st2;
  483. TTree *t1 = getpatt(L, 1, NULL);
  484. TTree *t2 = getpatt(L, 2, NULL);
  485. if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
  486. TTree *t = newcharset(L);
  487. loopset(i, treebuffer(t)[i] = st1.cs[i] | st2.cs[i]);
  488. }
  489. else if (nofail(t1) || t2->tag == TFalse)
  490. lua_pushvalue(L, 1); /* true / x => true, x / false => x */
  491. else if (t1->tag == TFalse)
  492. lua_pushvalue(L, 2); /* false / x => x */
  493. else
  494. newroot2sib(L, TChoice);
  495. return 1;
  496. }
  497. /*
  498. ** p^n
  499. */
  500. static int lp_star (lua_State *L) {
  501. int size1;
  502. int n = (int)luaL_checkinteger(L, 2);
  503. TTree *tree1 = getpatt(L, 1, &size1);
  504. if (n >= 0) { /* seq tree1 (seq tree1 ... (seq tree1 (rep tree1))) */
  505. TTree *tree = newtree(L, (n + 1) * (size1 + 1));
  506. if (nullable(tree1))
  507. luaL_error(L, "loop body may accept empty string");
  508. while (n--) /* repeat 'n' times */
  509. tree = seqaux(tree, tree1, size1);
  510. tree->tag = TRep;
  511. memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
  512. }
  513. else { /* choice (seq tree1 ... choice tree1 true ...) true */
  514. TTree *tree;
  515. n = -n;
  516. /* size = (choice + seq + tree1 + true) * n, but the last has no seq */
  517. tree = newtree(L, n * (size1 + 3) - 1);
  518. for (; n > 1; n--) { /* repeat (n - 1) times */
  519. tree->tag = TChoice; tree->u.ps = n * (size1 + 3) - 2;
  520. sib2(tree)->tag = TTrue;
  521. tree = sib1(tree);
  522. tree = seqaux(tree, tree1, size1);
  523. }
  524. tree->tag = TChoice; tree->u.ps = size1 + 1;
  525. sib2(tree)->tag = TTrue;
  526. memcpy(sib1(tree), tree1, size1 * sizeof(TTree));
  527. }
  528. copyktable(L, 1);
  529. return 1;
  530. }
  531. /*
  532. ** #p == &p
  533. */
  534. static int lp_and (lua_State *L) {
  535. newroot1sib(L, TAnd);
  536. return 1;
  537. }
  538. /*
  539. ** -p == !p
  540. */
  541. static int lp_not (lua_State *L) {
  542. newroot1sib(L, TNot);
  543. return 1;
  544. }
  545. /*
  546. ** [t1 - t2] == Seq (Not t2) t1
  547. ** If t1 and t2 are charsets, make their difference.
  548. */
  549. static int lp_sub (lua_State *L) {
  550. Charset st1, st2;
  551. int s1, s2;
  552. TTree *t1 = getpatt(L, 1, &s1);
  553. TTree *t2 = getpatt(L, 2, &s2);
  554. if (tocharset(t1, &st1) && tocharset(t2, &st2)) {
  555. TTree *t = newcharset(L);
  556. loopset(i, treebuffer(t)[i] = st1.cs[i] & ~st2.cs[i]);
  557. }
  558. else {
  559. TTree *tree = newtree(L, 2 + s1 + s2);
  560. tree->tag = TSeq; /* sequence of... */
  561. tree->u.ps = 2 + s2;
  562. sib1(tree)->tag = TNot; /* ...not... */
  563. memcpy(sib1(sib1(tree)), t2, s2 * sizeof(TTree)); /* ...t2 */
  564. memcpy(sib2(tree), t1, s1 * sizeof(TTree)); /* ... and t1 */
  565. joinktables(L, 1, sib1(tree), 2);
  566. }
  567. return 1;
  568. }
  569. static int lp_set (lua_State *L) {
  570. size_t l;
  571. const char *s = luaL_checklstring(L, 1, &l);
  572. TTree *tree = newcharset(L);
  573. while (l--) {
  574. setchar(treebuffer(tree), (byte)(*s));
  575. s++;
  576. }
  577. return 1;
  578. }
  579. static int lp_range (lua_State *L) {
  580. int arg;
  581. int top = lua_gettop(L);
  582. TTree *tree = newcharset(L);
  583. for (arg = 1; arg <= top; arg++) {
  584. int c;
  585. size_t l;
  586. const char *r = luaL_checklstring(L, arg, &l);
  587. luaL_argcheck(L, l == 2, arg, "range must have two characters");
  588. for (c = (byte)r[0]; c <= (byte)r[1]; c++)
  589. setchar(treebuffer(tree), c);
  590. }
  591. return 1;
  592. }
  593. /*
  594. ** Look-behind predicate
  595. */
  596. static int lp_behind (lua_State *L) {
  597. TTree *tree;
  598. TTree *tree1 = getpatt(L, 1, NULL);
  599. int n = fixedlen(tree1);
  600. luaL_argcheck(L, n >= 0, 1, "pattern may not have fixed length");
  601. luaL_argcheck(L, !hascaptures(tree1), 1, "pattern have captures");
  602. luaL_argcheck(L, n <= MAXBEHIND, 1, "pattern too long to look behind");
  603. tree = newroot1sib(L, TBehind);
  604. tree->u.n = n;
  605. return 1;
  606. }
  607. /*
  608. ** Create a non-terminal
  609. */
  610. static int lp_V (lua_State *L) {
  611. TTree *tree = newleaf(L, TOpenCall);
  612. luaL_argcheck(L, !lua_isnoneornil(L, 1), 1, "non-nil value expected");
  613. tree->key = addtonewktable(L, 0, 1);
  614. return 1;
  615. }
  616. /*
  617. ** Create a tree for a non-empty capture, with a body and
  618. ** optionally with an associated Lua value (at index 'labelidx' in the
  619. ** stack)
  620. */
  621. static int capture_aux (lua_State *L, int cap, int labelidx) {
  622. TTree *tree = newroot1sib(L, TCapture);
  623. tree->cap = cap;
  624. tree->key = (labelidx == 0) ? 0 : addtonewktable(L, 1, labelidx);
  625. return 1;
  626. }
  627. /*
  628. ** Fill a tree with an empty capture, using an empty (TTrue) sibling.
  629. */
  630. static TTree *auxemptycap (TTree *tree, int cap) {
  631. tree->tag = TCapture;
  632. tree->cap = cap;
  633. sib1(tree)->tag = TTrue;
  634. return tree;
  635. }
  636. /*
  637. ** Create a tree for an empty capture
  638. */
  639. static TTree *newemptycap (lua_State *L, int cap) {
  640. return auxemptycap(newtree(L, 2), cap);
  641. }
  642. /*
  643. ** Create a tree for an empty capture with an associated Lua value
  644. */
  645. static TTree *newemptycapkey (lua_State *L, int cap, int idx) {
  646. TTree *tree = auxemptycap(newtree(L, 2), cap);
  647. tree->key = addtonewktable(L, 0, idx);
  648. return tree;
  649. }
  650. /*
  651. ** Captures with syntax p / v
  652. ** (function capture, query capture, string capture, or number capture)
  653. */
  654. static int lp_divcapture (lua_State *L) {
  655. switch (lua_type(L, 2)) {
  656. case LUA_TFUNCTION: return capture_aux(L, Cfunction, 2);
  657. case LUA_TTABLE: return capture_aux(L, Cquery, 2);
  658. case LUA_TSTRING: return capture_aux(L, Cstring, 2);
  659. case LUA_TNUMBER: {
  660. int n = lua_tointeger(L, 2);
  661. TTree *tree = newroot1sib(L, TCapture);
  662. luaL_argcheck(L, 0 <= n && n <= SHRT_MAX, 1, "invalid number");
  663. tree->cap = Cnum;
  664. tree->key = n;
  665. return 1;
  666. }
  667. default: return luaL_argerror(L, 2, "invalid replacement value");
  668. }
  669. }
  670. static int lp_substcapture (lua_State *L) {
  671. return capture_aux(L, Csubst, 0);
  672. }
  673. static int lp_tablecapture (lua_State *L) {
  674. return capture_aux(L, Ctable, 0);
  675. }
  676. static int lp_groupcapture (lua_State *L) {
  677. if (lua_isnoneornil(L, 2))
  678. return capture_aux(L, Cgroup, 0);
  679. else
  680. return capture_aux(L, Cgroup, 2);
  681. }
  682. static int lp_foldcapture (lua_State *L) {
  683. luaL_checktype(L, 2, LUA_TFUNCTION);
  684. return capture_aux(L, Cfold, 2);
  685. }
  686. static int lp_simplecapture (lua_State *L) {
  687. return capture_aux(L, Csimple, 0);
  688. }
  689. static int lp_poscapture (lua_State *L) {
  690. newemptycap(L, Cposition);
  691. return 1;
  692. }
  693. static int lp_argcapture (lua_State *L) {
  694. int n = (int)luaL_checkinteger(L, 1);
  695. TTree *tree = newemptycap(L, Carg);
  696. tree->key = n;
  697. luaL_argcheck(L, 0 < n && n <= SHRT_MAX, 1, "invalid argument index");
  698. return 1;
  699. }
  700. static int lp_backref (lua_State *L) {
  701. luaL_checkany(L, 1);
  702. newemptycapkey(L, Cbackref, 1);
  703. return 1;
  704. }
  705. /*
  706. ** Constant capture
  707. */
  708. static int lp_constcapture (lua_State *L) {
  709. int i;
  710. int n = lua_gettop(L); /* number of values */
  711. if (n == 0) /* no values? */
  712. newleaf(L, TTrue); /* no capture */
  713. else if (n == 1)
  714. newemptycapkey(L, Cconst, 1); /* single constant capture */
  715. else { /* create a group capture with all values */
  716. TTree *tree = newtree(L, 1 + 3 * (n - 1) + 2);
  717. newktable(L, n); /* create a 'ktable' for new tree */
  718. tree->tag = TCapture;
  719. tree->cap = Cgroup;
  720. tree->key = 0;
  721. tree = sib1(tree);
  722. for (i = 1; i <= n - 1; i++) {
  723. tree->tag = TSeq;
  724. tree->u.ps = 3; /* skip TCapture and its sibling */
  725. auxemptycap(sib1(tree), Cconst);
  726. sib1(tree)->key = addtoktable(L, i);
  727. tree = sib2(tree);
  728. }
  729. auxemptycap(tree, Cconst);
  730. tree->key = addtoktable(L, i);
  731. }
  732. return 1;
  733. }
  734. static int lp_matchtime (lua_State *L) {
  735. TTree *tree;
  736. luaL_checktype(L, 2, LUA_TFUNCTION);
  737. tree = newroot1sib(L, TRunTime);
  738. tree->key = addtonewktable(L, 1, 2);
  739. return 1;
  740. }
  741. /* }====================================================== */
  742. /*
  743. ** {======================================================
  744. ** Grammar - Tree generation
  745. ** =======================================================
  746. */
  747. /*
  748. ** push on the stack the index and the pattern for the
  749. ** initial rule of grammar at index 'arg' in the stack;
  750. ** also add that index into position table.
  751. */
  752. static void getfirstrule (lua_State *L, int arg, int postab) {
  753. lua_rawgeti(L, arg, 1); /* access first element */
  754. if (lua_isstring(L, -1)) { /* is it the name of initial rule? */
  755. lua_pushvalue(L, -1); /* duplicate it to use as key */
  756. lua_gettable(L, arg); /* get associated rule */
  757. }
  758. else {
  759. lua_pushinteger(L, 1); /* key for initial rule */
  760. lua_insert(L, -2); /* put it before rule */
  761. }
  762. if (!testpattern(L, -1)) { /* initial rule not a pattern? */
  763. if (lua_isnil(L, -1))
  764. luaL_error(L, "grammar has no initial rule");
  765. else
  766. luaL_error(L, "initial rule '%s' is not a pattern", lua_tostring(L, -2));
  767. }
  768. lua_pushvalue(L, -2); /* push key */
  769. lua_pushinteger(L, 1); /* push rule position (after TGrammar) */
  770. lua_settable(L, postab); /* insert pair at position table */
  771. }
  772. /*
  773. ** traverse grammar at index 'arg', pushing all its keys and patterns
  774. ** into the stack. Create a new table (before all pairs key-pattern) to
  775. ** collect all keys and their associated positions in the final tree
  776. ** (the "position table").
  777. ** Return the number of rules and (in 'totalsize') the total size
  778. ** for the new tree.
  779. */
  780. static int collectrules (lua_State *L, int arg, int *totalsize) {
  781. int n = 1; /* to count number of rules */
  782. int postab = lua_gettop(L) + 1; /* index of position table */
  783. int size; /* accumulator for total size */
  784. lua_newtable(L); /* create position table */
  785. getfirstrule(L, arg, postab);
  786. size = 2 + getsize(L, postab + 2); /* TGrammar + TRule + rule */
  787. lua_pushnil(L); /* prepare to traverse grammar table */
  788. while (lua_next(L, arg) != 0) {
  789. if (lua_tonumber(L, -2) == 1 ||
  790. lp_equal(L, -2, postab + 1)) { /* initial rule? */
  791. lua_pop(L, 1); /* remove value (keep key for lua_next) */
  792. continue;
  793. }
  794. if (!testpattern(L, -1)) /* value is not a pattern? */
  795. luaL_error(L, "rule '%s' is not a pattern", val2str(L, -2));
  796. luaL_checkstack(L, LUA_MINSTACK, "grammar has too many rules");
  797. lua_pushvalue(L, -2); /* push key (to insert into position table) */
  798. lua_pushinteger(L, size);
  799. lua_settable(L, postab);
  800. size += 1 + getsize(L, -1); /* update size */
  801. lua_pushvalue(L, -2); /* push key (for next lua_next) */
  802. n++;
  803. }
  804. *totalsize = size + 1; /* TTrue to finish list of rules */
  805. return n;
  806. }
  807. static void buildgrammar (lua_State *L, TTree *grammar, int frule, int n) {
  808. int i;
  809. TTree *nd = sib1(grammar); /* auxiliary pointer to traverse the tree */
  810. for (i = 0; i < n; i++) { /* add each rule into new tree */
  811. int ridx = frule + 2*i + 1; /* index of i-th rule */
  812. int rulesize;
  813. TTree *rn = gettree(L, ridx, &rulesize);
  814. nd->tag = TRule;
  815. nd->key = 0;
  816. nd->cap = i; /* rule number */
  817. nd->u.ps = rulesize + 1; /* point to next rule */
  818. memcpy(sib1(nd), rn, rulesize * sizeof(TTree)); /* copy rule */
  819. mergektable(L, ridx, sib1(nd)); /* merge its ktable into new one */
  820. nd = sib2(nd); /* move to next rule */
  821. }
  822. nd->tag = TTrue; /* finish list of rules */
  823. }
  824. /*
  825. ** Check whether a tree has potential infinite loops
  826. */
  827. static int checkloops (TTree *tree) {
  828. tailcall:
  829. if (tree->tag == TRep && nullable(sib1(tree)))
  830. return 1;
  831. else if (tree->tag == TGrammar)
  832. return 0; /* sub-grammars already checked */
  833. else {
  834. switch (numsiblings[tree->tag]) {
  835. case 1: /* return checkloops(sib1(tree)); */
  836. tree = sib1(tree); goto tailcall;
  837. case 2:
  838. if (checkloops(sib1(tree))) return 1;
  839. /* else return checkloops(sib2(tree)); */
  840. tree = sib2(tree); goto tailcall;
  841. default: assert(numsiblings[tree->tag] == 0); return 0;
  842. }
  843. }
  844. }
  845. static int verifyerror (lua_State *L, int *passed, int npassed) {
  846. int i, j;
  847. for (i = npassed - 1; i >= 0; i--) { /* search for a repetition */
  848. for (j = i - 1; j >= 0; j--) {
  849. if (passed[i] == passed[j]) {
  850. lua_rawgeti(L, -1, passed[i]); /* get rule's key */
  851. return luaL_error(L, "rule '%s' may be left recursive", val2str(L, -1));
  852. }
  853. }
  854. }
  855. return luaL_error(L, "too many left calls in grammar");
  856. }
  857. /*
  858. ** Check whether a rule can be left recursive; raise an error in that
  859. ** case; otherwise return 1 iff pattern is nullable.
  860. ** The return value is used to check sequences, where the second pattern
  861. ** is only relevant if the first is nullable.
  862. ** Parameter 'nb' works as an accumulator, to allow tail calls in
  863. ** choices. ('nb' true makes function returns true.)
  864. ** Assume ktable at the top of the stack.
  865. */
  866. static int verifyrule (lua_State *L, TTree *tree, int *passed, int npassed,
  867. int nb) {
  868. tailcall:
  869. switch (tree->tag) {
  870. case TChar: case TSet: case TAny:
  871. case TFalse:
  872. return nb; /* cannot pass from here */
  873. case TTrue:
  874. case TBehind: /* look-behind cannot have calls */
  875. return 1;
  876. case TNot: case TAnd: case TRep:
  877. /* return verifyrule(L, sib1(tree), passed, npassed, 1); */
  878. tree = sib1(tree); nb = 1; goto tailcall;
  879. case TCapture: case TRunTime:
  880. /* return verifyrule(L, sib1(tree), passed, npassed, nb); */
  881. tree = sib1(tree); goto tailcall;
  882. case TCall:
  883. /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
  884. tree = sib2(tree); goto tailcall;
  885. case TSeq: /* only check 2nd child if first is nb */
  886. if (!verifyrule(L, sib1(tree), passed, npassed, 0))
  887. return nb;
  888. /* else return verifyrule(L, sib2(tree), passed, npassed, nb); */
  889. tree = sib2(tree); goto tailcall;
  890. case TChoice: /* must check both children */
  891. nb = verifyrule(L, sib1(tree), passed, npassed, nb);
  892. /* return verifyrule(L, sib2(tree), passed, npassed, nb); */
  893. tree = sib2(tree); goto tailcall;
  894. case TRule:
  895. if (npassed >= MAXRULES)
  896. return verifyerror(L, passed, npassed);
  897. else {
  898. passed[npassed++] = tree->key;
  899. /* return verifyrule(L, sib1(tree), passed, npassed); */
  900. tree = sib1(tree); goto tailcall;
  901. }
  902. case TGrammar:
  903. return nullable(tree); /* sub-grammar cannot be left recursive */
  904. default: assert(0); return 0;
  905. }
  906. }
  907. static void verifygrammar (lua_State *L, TTree *grammar) {
  908. int passed[MAXRULES];
  909. TTree *rule;
  910. /* check left-recursive rules */
  911. for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
  912. if (rule->key == 0) continue; /* unused rule */
  913. verifyrule(L, sib1(rule), passed, 0, 0);
  914. }
  915. assert(rule->tag == TTrue);
  916. /* check infinite loops inside rules */
  917. for (rule = sib1(grammar); rule->tag == TRule; rule = sib2(rule)) {
  918. if (rule->key == 0) continue; /* unused rule */
  919. if (checkloops(sib1(rule))) {
  920. lua_rawgeti(L, -1, rule->key); /* get rule's key */
  921. luaL_error(L, "empty loop in rule '%s'", val2str(L, -1));
  922. }
  923. }
  924. assert(rule->tag == TTrue);
  925. }
  926. /*
  927. ** Give a name for the initial rule if it is not referenced
  928. */
  929. static void initialrulename (lua_State *L, TTree *grammar, int frule) {
  930. if (sib1(grammar)->key == 0) { /* initial rule is not referenced? */
  931. int n = lua_rawlen(L, -1) + 1; /* index for name */
  932. lua_pushvalue(L, frule); /* rule's name */
  933. lua_rawseti(L, -2, n); /* ktable was on the top of the stack */
  934. sib1(grammar)->key = n;
  935. }
  936. }
  937. static TTree *newgrammar (lua_State *L, int arg) {
  938. int treesize;
  939. int frule = lua_gettop(L) + 2; /* position of first rule's key */
  940. int n = collectrules(L, arg, &treesize);
  941. TTree *g = newtree(L, treesize);
  942. luaL_argcheck(L, n <= MAXRULES, arg, "grammar has too many rules");
  943. g->tag = TGrammar; g->u.n = n;
  944. lua_newtable(L); /* create 'ktable' */
  945. lua_setuservalue(L, -2);
  946. buildgrammar(L, g, frule, n);
  947. lua_getuservalue(L, -1); /* get 'ktable' for new tree */
  948. finalfix(L, frule - 1, g, sib1(g));
  949. initialrulename(L, g, frule);
  950. verifygrammar(L, g);
  951. lua_pop(L, 1); /* remove 'ktable' */
  952. lua_insert(L, -(n * 2 + 2)); /* move new table to proper position */
  953. lua_pop(L, n * 2 + 1); /* remove position table + rule pairs */
  954. return g; /* new table at the top of the stack */
  955. }
  956. /* }====================================================== */
  957. static Instruction *prepcompile (lua_State *L, Pattern *p, int idx) {
  958. lua_getuservalue(L, idx); /* push 'ktable' (may be used by 'finalfix') */
  959. finalfix(L, 0, NULL, p->tree);
  960. lua_pop(L, 1); /* remove 'ktable' */
  961. return compile(L, p);
  962. }
  963. static int lp_printtree (lua_State *L) {
  964. TTree *tree = getpatt(L, 1, NULL);
  965. int c = lua_toboolean(L, 2);
  966. if (c) {
  967. lua_getuservalue(L, 1); /* push 'ktable' (may be used by 'finalfix') */
  968. finalfix(L, 0, NULL, tree);
  969. lua_pop(L, 1); /* remove 'ktable' */
  970. }
  971. printktable(L, 1);
  972. printtree(tree, 0);
  973. return 0;
  974. }
  975. static int lp_printcode (lua_State *L) {
  976. Pattern *p = getpattern(L, 1);
  977. printktable(L, 1);
  978. if (p->code == NULL) /* not compiled yet? */
  979. prepcompile(L, p, 1);
  980. printpatt(p->code, p->codesize);
  981. return 0;
  982. }
  983. /*
  984. ** Get the initial position for the match, interpreting negative
  985. ** values from the end of the subject
  986. */
  987. static size_t initposition (lua_State *L, size_t len) {
  988. lua_Integer ii = luaL_optinteger(L, 3, 1);
  989. if (ii > 0) { /* positive index? */
  990. if ((size_t)ii <= len) /* inside the string? */
  991. return (size_t)ii - 1; /* return it (corrected to 0-base) */
  992. else return len; /* crop at the end */
  993. }
  994. else { /* negative index */
  995. if ((size_t)(-ii) <= len) /* inside the string? */
  996. return len - ((size_t)(-ii)); /* return position from the end */
  997. else return 0; /* crop at the beginning */
  998. }
  999. }
  1000. /*
  1001. ** Main match function
  1002. */
  1003. static int lp_match (lua_State *L) {
  1004. Capture capture[INITCAPSIZE];
  1005. const char *r;
  1006. size_t l;
  1007. Pattern *p = (getpatt(L, 1, NULL), getpattern(L, 1));
  1008. Instruction *code = (p->code != NULL) ? p->code : prepcompile(L, p, 1);
  1009. const char *s = luaL_checklstring(L, SUBJIDX, &l);
  1010. size_t i = initposition(L, l);
  1011. int ptop = lua_gettop(L);
  1012. lua_pushnil(L); /* initialize subscache */
  1013. lua_pushlightuserdata(L, capture); /* initialize caplistidx */
  1014. lua_getuservalue(L, 1); /* initialize penvidx */
  1015. r = match(L, s, s + i, s + l, code, capture, ptop);
  1016. if (r == NULL) {
  1017. lua_pushnil(L);
  1018. return 1;
  1019. }
  1020. return getcaptures(L, s, r, ptop);
  1021. }
  1022. /*
  1023. ** {======================================================
  1024. ** Library creation and functions not related to matching
  1025. ** =======================================================
  1026. */
  1027. /* maximum limit for stack size */
  1028. #define MAXLIM (INT_MAX / 100)
  1029. static int lp_setmax (lua_State *L) {
  1030. lua_Integer lim = luaL_checkinteger(L, 1);
  1031. luaL_argcheck(L, 0 < lim && lim <= MAXLIM, 1, "out of range");
  1032. lua_settop(L, 1);
  1033. lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
  1034. return 0;
  1035. }
  1036. static int lp_version (lua_State *L) {
  1037. lua_pushstring(L, VERSION);
  1038. return 1;
  1039. }
  1040. static int lp_type (lua_State *L) {
  1041. if (testpattern(L, 1))
  1042. lua_pushliteral(L, "pattern");
  1043. else
  1044. lua_pushnil(L);
  1045. return 1;
  1046. }
  1047. int lp_gc (lua_State *L) {
  1048. Pattern *p = getpattern(L, 1);
  1049. realloccode(L, p, 0); /* delete code block */
  1050. return 0;
  1051. }
  1052. static void createcat (lua_State *L, const char *catname, int (catf) (int)) {
  1053. TTree *t = newcharset(L);
  1054. int i;
  1055. for (i = 0; i <= UCHAR_MAX; i++)
  1056. if (catf(i)) setchar(treebuffer(t), i);
  1057. lua_setfield(L, -2, catname);
  1058. }
  1059. static int lp_locale (lua_State *L) {
  1060. if (lua_isnoneornil(L, 1)) {
  1061. lua_settop(L, 0);
  1062. lua_createtable(L, 0, 12);
  1063. }
  1064. else {
  1065. luaL_checktype(L, 1, LUA_TTABLE);
  1066. lua_settop(L, 1);
  1067. }
  1068. createcat(L, "alnum", isalnum);
  1069. createcat(L, "alpha", isalpha);
  1070. createcat(L, "cntrl", iscntrl);
  1071. createcat(L, "digit", isdigit);
  1072. createcat(L, "graph", isgraph);
  1073. createcat(L, "lower", islower);
  1074. createcat(L, "print", isprint);
  1075. createcat(L, "punct", ispunct);
  1076. createcat(L, "space", isspace);
  1077. createcat(L, "upper", isupper);
  1078. createcat(L, "xdigit", isxdigit);
  1079. return 1;
  1080. }
  1081. static struct luaL_Reg pattreg[] = {
  1082. {"ptree", lp_printtree},
  1083. {"pcode", lp_printcode},
  1084. {"match", lp_match},
  1085. {"B", lp_behind},
  1086. {"V", lp_V},
  1087. {"C", lp_simplecapture},
  1088. {"Cc", lp_constcapture},
  1089. {"Cmt", lp_matchtime},
  1090. {"Cb", lp_backref},
  1091. {"Carg", lp_argcapture},
  1092. {"Cp", lp_poscapture},
  1093. {"Cs", lp_substcapture},
  1094. {"Ct", lp_tablecapture},
  1095. {"Cf", lp_foldcapture},
  1096. {"Cg", lp_groupcapture},
  1097. {"P", lp_P},
  1098. {"S", lp_set},
  1099. {"R", lp_range},
  1100. {"locale", lp_locale},
  1101. {"version", lp_version},
  1102. {"setmaxstack", lp_setmax},
  1103. {"type", lp_type},
  1104. {NULL, NULL}
  1105. };
  1106. static struct luaL_Reg metareg[] = {
  1107. {"__mul", lp_seq},
  1108. {"__add", lp_choice},
  1109. {"__pow", lp_star},
  1110. {"__gc", lp_gc},
  1111. {"__len", lp_and},
  1112. {"__div", lp_divcapture},
  1113. {"__unm", lp_not},
  1114. {"__sub", lp_sub},
  1115. {NULL, NULL}
  1116. };
  1117. int luaopen_lpeg (lua_State *L) {
  1118. luaL_newmetatable(L, PATTERN_T);
  1119. lua_pushnumber(L, MAXBACK); /* initialize maximum backtracking */
  1120. lua_setfield(L, LUA_REGISTRYINDEX, MAXSTACKIDX);
  1121. luaL_setfuncs(L, metareg, 0);
  1122. luaL_newlib(L, pattreg);
  1123. lua_pushvalue(L, -1);
  1124. lua_setfield(L, -3, "__index");
  1125. return 1;
  1126. }
  1127. /* }====================================================== */