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

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