robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
1 2#include "lua.h" 3#include "lauxlib.h" 4 5#include "lpcap.h" 6#include "lpprint.h" 7#include "lptypes.h" 8 9 10#define getfromktable (cs ,v ) lua_rawgeti((cs)->L, ktableidx((cs)->ptop), v) 11 12#define pushluaval (cs ) getfromktable(cs, (cs)->cap->idx) 13 14 15 16#define skipclose (cs ,head ) \ 17 if (isopencap(head)) { assert(isclosecap(cs->cap)); cs->cap++; } 18 19 20/* 21** Return the size of capture 'cap'. If it is an open capture, 'close' 22** must be its corresponding close. 23*/ 24static Index_t capsize (Capture * cap ,Capture * close ) { 25if (isopencap (cap )) { 26assert (isclosecap (close )); 27return close -> index - cap -> index ; 28 } 29else 30return cap -> siz - 1 ; 31} 32 33 34static Index_t closesize (CapState * cs ,Capture * head ) { 35return capsize (head ,cs -> cap ); 36} 37 38 39/* 40** Put at the cache for Lua values the value indexed by 'v' in ktable 41** of the running pattern (if it is not there yet); returns its index. 42*/ 43static int updatecache (CapState * cs ,int v ) { 44int idx = cs -> ptop + 1 ;/* stack index of cache for Lua values */ 45if (v != cs -> valuecached ) {/* not there? */ 46getfromktable (cs ,v );/* get value from 'ktable' */ 47lua_replace (cs -> L ,idx );/* put it at reserved stack position */ 48cs -> valuecached = v ;/* keep track of what is there */ 49 } 50return idx ; 51} 52 53 54static int pushcapture (CapState * cs ); 55 56 57/* 58** Goes back in a list of captures looking for an open capture 59** corresponding to a close one. 60*/ 61static Capture * findopen (Capture * cap ) { 62int n = 0 ;/* number of closes waiting an open */ 63for (;;) { 64cap -- ; 65if (isclosecap (cap ))n ++ ;/* one more open to skip */ 66else if (isopencap (cap )) 67if (n -- == 0 )return cap ; 68 } 69} 70 71 72/* 73** Go to the next capture at the same level. 74*/ 75static void nextcap (CapState * cs ) { 76Capture * cap = cs -> cap ; 77if (isopencap (cap )) {/* must look for a close? */ 78int n = 0 ;/* number of opens waiting a close */ 79for (;;) {/* look for corresponding close */ 80cap ++ ; 81if (isopencap (cap ))n ++ ; 82else if (isclosecap (cap )) 83if (n -- == 0 )break ; 84 } 85cs -> cap = cap + 1 ;/* + 1 to skip last close */ 86 } 87else { 88Capture * next ; 89for (next = cap + 1 ;capinside (cap ,next );next ++ ) 90 ;/* skip captures inside current one */ 91cs -> cap = next ; 92 } 93} 94 95 96/* 97** Push on the Lua stack all values generated by nested captures inside 98** the current capture. Returns number of values pushed. 'addextra' 99** makes it push the entire match after all captured values. The 100** entire match is pushed also if there are no other nested values, 101** so the function never returns zero. 102*/ 103static int pushnestedvalues (CapState * cs ,int addextra ) { 104Capture * head = cs -> cap ++ ;/* original capture */ 105int n = 0 ;/* number of pushed subvalues */ 106/* repeat for all nested patterns */ 107while (capinside (head ,cs -> cap )) 108n += pushcapture (cs ); 109if (addextra || n == 0 ) {/* need extra? */ 110lua_pushlstring (cs -> L ,cs -> s + head -> index ,closesize (cs ,head )); 111n ++ ; 112 } 113skipclose (cs ,head ); 114return n ; 115} 116 117 118/* 119** Push only the first value generated by nested captures 120*/ 121static void pushonenestedvalue (CapState * cs ) { 122int n = pushnestedvalues (cs ,0 ); 123if (n > 1 ) 124lua_pop (cs -> L ,n - 1 );/* pop extra values */ 125} 126 127 128/* 129** Checks whether group 'grp' is visible to 'ref', that is, 'grp' is 130** not nested inside a full capture that does not contain 'ref'. (We 131** only need to care for full captures because the search at 'findback' 132** skips open-end blocks; so, if 'grp' is nested in a non-full capture, 133** 'ref' is also inside it.) To check this, we search backward for the 134** inner full capture enclosing 'grp'. A full capture cannot contain 135** non-full captures, so a close capture means we cannot be inside a 136** full capture anymore. 137*/ 138static int capvisible (CapState * cs ,Capture * grp ,Capture * ref ) { 139Capture * cap = grp ; 140int i = MAXLOP ;/* maximum distance for an 'open' */ 141while (i -- > 0 && cap -- > cs -> ocap ) { 142if (isclosecap (cap )) 143return 1 ;/* can stop the search */ 144else if (grp -> index - cap -> index >=UCHAR_MAX ) 145return 1 ;/* can stop the search */ 146else if (capinside (cap ,grp ))/* is 'grp' inside cap? */ 147return capinside (cap ,ref );/* ok iff cap also contains 'ref' */ 148 } 149return 1 ;/* 'grp' is not inside any capture */ 150} 151 152 153/* 154** Try to find a named group capture with the name given at the top of 155** the stack; goes backward from 'ref'. 156*/ 157static Capture * findback (CapState * cs ,Capture * ref ) { 158lua_State * L = cs -> L ; 159Capture * cap = ref ; 160while (cap -- > cs -> ocap ) {/* repeat until end of list */ 161if (isclosecap (cap )) 162cap = findopen (cap );/* skip nested captures */ 163else if (capinside (cap ,ref )) 164continue ;/* enclosing captures are not visible to 'ref' */ 165if (captype (cap )== Cgroup && capvisible (cs ,cap ,ref )) { 166getfromktable (cs ,cap -> idx );/* get group name */ 167if (lp_equal (L ,-2 ,-1 )) {/* right group? */ 168lua_pop (L ,2 );/* remove reference name and group name */ 169return cap ; 170 } 171else lua_pop (L ,1 );/* remove group name */ 172 } 173 } 174luaL_error (L ,"back reference '%s' not found" ,lua_tostring (L ,-1 )); 175return NULL ;/* to avoid warnings */ 176} 177 178 179/* 180** Back-reference capture. Return number of values pushed. 181*/ 182static int backrefcap (CapState * cs ) { 183int n ; 184Capture * curr = cs -> cap ; 185pushluaval (cs );/* reference name */ 186cs -> cap = findback (cs ,curr );/* find corresponding group */ 187n = pushnestedvalues (cs ,0 );/* push group's values */ 188cs -> cap = curr + 1 ; 189return n ; 190} 191 192 193/* 194** Table capture: creates a new table and populates it with nested 195** captures. 196*/ 197static int tablecap (CapState * cs ) { 198lua_State * L = cs -> L ; 199Capture * head = cs -> cap ++ ; 200int n = 0 ; 201lua_newtable (L ); 202while (capinside (head ,cs -> cap )) { 203if (captype (cs -> cap )== Cgroup && cs -> cap -> idx != 0 ) {/* named group? */ 204pushluaval (cs );/* push group name */ 205pushonenestedvalue (cs ); 206lua_settable (L ,-3 ); 207 } 208else {/* not a named group */ 209int i ; 210int k = pushcapture (cs ); 211for (i = k ;i > 0 ;i -- )/* store all values into table */ 212lua_rawseti (L ,- (i + 1 ),n + i ); 213n += k ; 214 } 215 } 216skipclose (cs ,head ); 217return 1 ;/* number of values pushed (only the table) */ 218} 219 220 221/* 222** Table-query capture 223*/ 224static int querycap (CapState * cs ) { 225int idx = cs -> cap -> idx ; 226pushonenestedvalue (cs );/* get nested capture */ 227lua_gettable (cs -> L ,updatecache (cs ,idx ));/* query cap. value at table */ 228if (!lua_isnil (cs -> L ,-1 )) 229return 1 ; 230else {/* no value */ 231lua_pop (cs -> L ,1 );/* remove nil */ 232return 0 ; 233 } 234} 235 236 237/* 238** Fold capture 239*/ 240static int foldcap (CapState * cs ) { 241int n ; 242lua_State * L = cs -> L ; 243Capture * head = cs -> cap ++ ; 244int idx = head -> idx ; 245if (isclosecap (cs -> cap )|| /* no nested captures (large subject)? */ 246 (n = pushcapture (cs ))== 0 )/* nested captures with no values? */ 247return luaL_error (L ,"no initial value for fold capture" ); 248if (n > 1 ) 249lua_pop (L ,n - 1 );/* leave only one result for accumulator */ 250while (capinside (head ,cs -> cap )) { 251lua_pushvalue (L ,updatecache (cs ,idx ));/* get folding function */ 252lua_insert (L ,-2 );/* put it before accumulator */ 253n = pushcapture (cs );/* get next capture's values */ 254lua_call (L ,n + 1 ,1 );/* call folding function */ 255 } 256skipclose (cs ,head ); 257return 1 ;/* only accumulator left on the stack */ 258} 259 260 261/* 262** Function capture 263*/ 264static int functioncap (CapState * cs ) { 265int n ; 266int top = lua_gettop (cs -> L ); 267pushluaval (cs );/* push function */ 268n = pushnestedvalues (cs ,0 );/* push nested captures */ 269lua_call (cs -> L ,n ,LUA_MULTRET );/* call function */ 270return lua_gettop (cs -> L )- top ;/* return function's results */ 271} 272 273 274/* 275** Accumulator capture 276*/ 277static int accumulatorcap (CapState * cs ) { 278lua_State * L = cs -> L ; 279int n ; 280if (lua_gettop (L )< cs -> firstcap ) 281luaL_error (L ,"no previous value for accumulator capture" ); 282pushluaval (cs );/* push function */ 283lua_insert (L ,-2 );/* previous value becomes first argument */ 284n = pushnestedvalues (cs ,0 );/* push nested captures */ 285lua_call (L ,n + 1 ,1 );/* call function */ 286return 0 ;/* did not add any extra value */ 287} 288 289 290/* 291** Select capture 292*/ 293static int numcap (CapState * cs ) { 294int idx = cs -> cap -> idx ;/* value to select */ 295if (idx == 0 ) {/* no values? */ 296nextcap (cs );/* skip entire capture */ 297return 0 ;/* no value produced */ 298 } 299else { 300int n = pushnestedvalues (cs ,0 ); 301if (n < idx )/* invalid index? */ 302return luaL_error (cs -> L ,"no capture '%d'" ,idx ); 303else { 304lua_pushvalue (cs -> L ,- (n - idx + 1 ));/* get selected capture */ 305lua_replace (cs -> L ,- (n + 1 ));/* put it in place of 1st capture */ 306lua_pop (cs -> L ,n - 1 );/* remove other captures */ 307return 1 ; 308 } 309 } 310} 311 312 313/* 314** Return the stack index of the first runtime capture in the given 315** list of captures (or zero if no runtime captures) 316*/ 317int finddyncap (Capture * cap ,Capture * last ) { 318for (;cap < last ;cap ++ ) { 319if (cap -> kind == Cruntime ) 320return cap -> idx ;/* stack position of first capture */ 321 } 322return 0 ;/* no dynamic captures in this segment */ 323} 324 325 326/* 327** Calls a runtime capture. Returns number of captures "removed" by the 328** call, that is, those inside the group capture. Captures to be added 329** are on the Lua stack. 330*/ 331int runtimecap (CapState * cs ,Capture * close ,const char * s ,int * rem ) { 332int n ,id ; 333lua_State * L = cs -> L ; 334int otop = lua_gettop (L ); 335Capture * open = findopen (close );/* get open group capture */ 336assert (captype (open )== Cgroup ); 337id = finddyncap (open ,close );/* get first dynamic capture argument */ 338close -> kind = Cclose ;/* closes the group */ 339close -> index = s - cs -> s ; 340cs -> cap = open ;cs -> valuecached = 0 ;/* prepare capture state */ 341luaL_checkstack (L ,4 ,"too many runtime captures" ); 342pushluaval (cs );/* push function to be called */ 343lua_pushvalue (L ,SUBJIDX );/* push original subject */ 344lua_pushinteger (L ,s - cs -> s + 1 );/* push current position */ 345n = pushnestedvalues (cs ,0 );/* push nested captures */ 346lua_call (L ,n + 2 ,LUA_MULTRET );/* call dynamic function */ 347if (id > 0 ) {/* are there old dynamic captures to be removed? */ 348int i ; 349for (i = id ;i <=otop ;i ++ ) 350lua_remove (L ,id );/* remove old dynamic captures */ 351* rem = otop - id + 1 ;/* total number of dynamic captures removed */ 352 } 353else 354* rem = 0 ;/* no dynamic captures removed */ 355return close - open - 1 ;/* number of captures to be removed */ 356} 357 358 359/* 360** Auxiliary structure for substitution and string captures: keep 361** information about nested captures for future use, avoiding to push 362** string results into Lua 363*/ 364typedef struct StrAux { 365int isstring ;/* whether capture is a string */ 366union { 367Capture * cp ;/* if not a string, respective capture */ 368struct {/* if it is a string... */ 369Index_t idx ;/* starts here */ 370Index_t siz ;/* with this size */ 371 }s ; 372 }u ; 373}StrAux ; 374 375#define MAXSTRCAPS 10 376 377/* 378** Collect values from current capture into array 'cps'. Current 379** capture must be Cstring (first call) or Csimple (recursive calls). 380** (In first call, fills %0 with whole match for Cstring.) 381** Returns number of elements in the array that were filled. 382*/ 383static int getstrcaps (CapState * cs ,StrAux * cps ,int n ) { 384int k = n ++ ; 385Capture * head = cs -> cap ++ ; 386cps [k ].isstring = 1 ;/* get string value */ 387cps [k ].u .s .idx = head -> index ;/* starts here */ 388while (capinside (head ,cs -> cap )) { 389if (n >=MAXSTRCAPS )/* too many captures? */ 390nextcap (cs );/* skip extra captures (will not need them) */ 391else if (captype (cs -> cap )== Csimple )/* string? */ 392n = getstrcaps (cs ,cps ,n );/* put info. into array */ 393else { 394cps [n ].isstring = 0 ;/* not a string */ 395cps [n ].u .cp = cs -> cap ;/* keep original capture */ 396nextcap (cs ); 397n ++ ; 398 } 399 } 400cps [k ].u .s .siz = closesize (cs ,head ); 401skipclose (cs ,head ); 402return n ; 403} 404 405 406/* 407** add next capture value (which should be a string) to buffer 'b' 408*/ 409static int addonestring (luaL_Buffer * b ,CapState * cs ,const char * what ); 410 411 412/* 413** String capture: add result to buffer 'b' (instead of pushing 414** it into the stack) 415*/ 416static void stringcap (luaL_Buffer * b ,CapState * cs ) { 417StrAux cps [MAXSTRCAPS ]; 418int n ; 419size_t len ,i ; 420const char * fmt ;/* format string */ 421fmt = lua_tolstring (cs -> L ,updatecache (cs ,cs -> cap -> idx ),& len ); 422n = getstrcaps (cs ,cps ,0 )- 1 ;/* collect nested captures */ 423for (i = 0 ;i < len ;i ++ ) {/* traverse format string */ 424if (fmt [i ]!= '%' )/* not an escape? */ 425luaL_addchar (b ,fmt [i ]);/* add it to buffer */ 426else if (fmt [++ i ]< '0' || fmt [i ]> '9' )/* not followed by a digit? */ 427luaL_addchar (b ,fmt [i ]);/* add to buffer */ 428else { 429int l = fmt [i ]- '0' ;/* capture index */ 430if (l > n ) 431luaL_error (cs -> L ,"invalid capture index (%d)" ,l ); 432else if (cps [l ].isstring ) 433luaL_addlstring (b ,cs -> s + cps [l ].u .s .idx ,cps [l ].u .s .siz ); 434else { 435Capture * curr = cs -> cap ; 436cs -> cap = cps [l ].u .cp ;/* go back to evaluate that nested capture */ 437if (!addonestring (b ,cs ,"capture" )) 438luaL_error (cs -> L ,"no values in capture index %d" ,l ); 439cs -> cap = curr ;/* continue from where it stopped */ 440 } 441 } 442 } 443} 444 445 446/* 447** Substitution capture: add result to buffer 'b' 448*/ 449static void substcap (luaL_Buffer * b ,CapState * cs ) { 450const char * curr = cs -> s + cs -> cap -> index ; 451Capture * head = cs -> cap ++ ; 452while (capinside (head ,cs -> cap )) { 453Capture * cap = cs -> cap ; 454const char * caps = cs -> s + cap -> index ; 455luaL_addlstring (b ,curr ,caps - curr );/* add text up to capture */ 456if (addonestring (b ,cs ,"replacement" )) 457curr = caps + capsize (cap ,cs -> cap - 1 );/* continue after match */ 458else /* no capture value */ 459curr = caps ;/* keep original text in final result */ 460 } 461/* add last piece of text */ 462luaL_addlstring (b ,curr ,cs -> s + head -> index + closesize (cs ,head )- curr ); 463skipclose (cs ,head ); 464} 465 466 467/* 468** Evaluates a capture and adds its first value to buffer 'b'; returns 469** whether there was a value 470*/ 471static int addonestring (luaL_Buffer * b ,CapState * cs ,const char * what ) { 472switch (captype (cs -> cap )) { 473case Cstring : 474stringcap (b ,cs );/* add capture directly to buffer */ 475return 1 ; 476case Csubst : 477substcap (b ,cs );/* add capture directly to buffer */ 478return 1 ; 479case Cacc :/* accumulator capture? */ 480return luaL_error (cs -> L ,"invalid context for an accumulator capture" ); 481default : { 482lua_State * L = cs -> L ; 483int n = pushcapture (cs ); 484if (n > 0 ) { 485if (n > 1 )lua_pop (L ,n - 1 );/* only one result */ 486if (!lua_isstring (L ,-1 )) 487return luaL_error (L ,"invalid %s value (a %s)" , 488what ,luaL_typename (L ,-1 )); 489luaL_addvalue (b ); 490 } 491return n ; 492 } 493 } 494} 495 496 497#if !defined(MAXRECLEVEL ) 498#define MAXRECLEVEL 200 499#endif 500 501 502/* 503** Push all values of the current capture into the stack; returns 504** number of values pushed 505*/ 506static int pushcapture (CapState * cs ) { 507lua_State * L = cs -> L ; 508int res ; 509luaL_checkstack (L ,4 ,"too many captures" ); 510if (cs -> reclevel ++ > MAXRECLEVEL ) 511return luaL_error (L ,"subcapture nesting too deep" ); 512switch (captype (cs -> cap )) { 513case Cposition : { 514lua_pushinteger (L ,cs -> cap -> index + 1 ); 515cs -> cap ++ ; 516res = 1 ; 517break ; 518 } 519case Cconst : { 520pushluaval (cs ); 521cs -> cap ++ ; 522res = 1 ; 523break ; 524 } 525case Carg : { 526int arg = (cs -> cap ++ )-> idx ; 527if (arg + FIXEDARGS > cs -> ptop ) 528return luaL_error (L ,"reference to absent extra argument #%d" ,arg ); 529lua_pushvalue (L ,arg + FIXEDARGS ); 530res = 1 ; 531break ; 532 } 533case Csimple : { 534int k = pushnestedvalues (cs ,1 ); 535lua_insert (L ,- k );/* make whole match be first result */ 536res = k ; 537break ; 538 } 539case Cruntime : { 540lua_pushvalue (L , (cs -> cap ++ )-> idx );/* value is in the stack */ 541res = 1 ; 542break ; 543 } 544case Cstring : { 545luaL_Buffer b ; 546luaL_buffinit (L ,& b ); 547stringcap (& b ,cs ); 548luaL_pushresult (& b ); 549res = 1 ; 550break ; 551 } 552case Csubst : { 553luaL_Buffer b ; 554luaL_buffinit (L ,& b ); 555substcap (& b ,cs ); 556luaL_pushresult (& b ); 557res = 1 ; 558break ; 559 } 560case Cgroup : { 561if (cs -> cap -> idx == 0 )/* anonymous group? */ 562res = pushnestedvalues (cs ,0 );/* add all nested values */ 563else {/* named group: add no values */ 564nextcap (cs );/* skip capture */ 565res = 0 ; 566 } 567break ; 568 } 569case Cbackref :res = backrefcap (cs );break ; 570case Ctable :res = tablecap (cs );break ; 571case Cfunction :res = functioncap (cs );break ; 572case Cacc :res = accumulatorcap (cs );break ; 573case Cnum :res = numcap (cs );break ; 574case Cquery :res = querycap (cs );break ; 575case Cfold :res = foldcap (cs );break ; 576default :assert (0 );res = 0 ; 577 } 578cs -> reclevel -- ; 579return res ; 580} 581 582 583/* 584** Prepare a CapState structure and traverse the entire list of 585** captures in the stack pushing its results. 's' is the subject 586** string, 'r' is the final position of the match, and 'ptop' 587** the index in the stack where some useful values were pushed. 588** Returns the number of results pushed. (If the list produces no 589** results, push the final position of the match.) 590*/ 591int getcaptures (lua_State * L ,const char * s ,const char * r ,int ptop ) { 592Capture * capture = (Capture * )lua_touserdata (L ,caplistidx (ptop )); 593int n = 0 ; 594/* printcaplist(capture); */ 595if (!isclosecap (capture )) {/* is there any capture? */ 596CapState cs ; 597cs .ocap = cs .cap = capture ;cs .L = L ;cs .reclevel = 0 ; 598cs .s = s ;cs .valuecached = 0 ;cs .ptop = ptop ; 599cs .firstcap = lua_gettop (L )+ 1 ;/* where first value (if any) will go */ 600do {/* collect their values */ 601n += pushcapture (& cs ); 602 }while (!isclosecap (cs .cap )); 603assert (lua_gettop (L )- cs .firstcap == n - 1 ); 604 } 605if (n == 0 ) {/* no capture values? */ 606lua_pushinteger (L ,r - s + 1 );/* return only end position */ 607n = 1 ; 608 } 609return n ; 610} 611 612