robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
1 2#include <limits.h> 3#include <string.h> 4 5 6#include "lua.h" 7#include "lauxlib.h" 8 9#include "lpcap.h" 10#include "lptypes.h" 11#include "lpvm.h" 12#include "lpprint.h" 13 14 15/* initial size for call/backtrack stack */ 16#if !defined(INITBACK ) 17#define INITBACK MAXBACK 18#endif 19 20 21#define getoffset (p ) (((p) + 1)->offset) 22 23static const Instruction giveup = {{IGiveup ,0 , {0 }}}; 24 25 26int charinset (const Instruction * i ,const byte * buff ,uint c ) { 27c -= i -> i .aux2 .set .offset ; 28if (c >= ((uint )i -> i .aux2 .set .size /* size in instructions... */ 29* (uint )sizeof (Instruction )/* in bytes... */ 30* 8u ))/* in bits */ 31return i -> i .aux1 ;/* out of range; return default value */ 32return testchar (buff ,c ); 33} 34 35 36/* 37** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid. 38*/ 39static const char * utf8_decode (const char * o ,int * val ) { 40static const uint limits []= {0xFF ,0x7F ,0x7FF ,0xFFFFu }; 41const unsigned char * s = (const unsigned char * )o ; 42uint c = s [0 ];/* first byte */ 43uint res = 0 ;/* final result */ 44if (c < 0x80 )/* ascii? */ 45res = c ; 46else { 47int count = 0 ;/* to count number of continuation bytes */ 48while (c & 0x40 ) {/* still have continuation bytes? */ 49int cc = s [++ count ];/* read next byte */ 50if ((cc & 0xC0 )!= 0x80 )/* not a continuation byte? */ 51return NULL ;/* invalid byte sequence */ 52res = (res <<6 ) | (cc & 0x3F );/* add lower 6 bits from cont. byte */ 53c <<=1 ;/* to test next bit */ 54 } 55res |= (c & 0x7F ) << (count * 5 );/* add first byte */ 56if (count > 3 || res > 0x10FFFFu || res <=limits [count ]) 57return NULL ;/* invalid byte sequence */ 58s += count ;/* skip continuation bytes read */ 59 } 60* val = res ; 61return (const char * )s + 1 ;/* +1 to include first byte */ 62} 63 64 65/* 66** {====================================================== 67** Virtual Machine 68** ======================================================= 69*/ 70 71 72typedef struct Stack { 73const char * s ;/* saved position (or NULL for calls) */ 74const Instruction * p ;/* next instruction */ 75int caplevel ; 76}Stack ; 77 78 79#define getstackbase (L ,ptop ) ((Stack *)lua_touserdata(L, stackidx(ptop))) 80 81 82/* 83** Ensures the size of array 'capture' (with size '*capsize' and 84** 'captop' elements being used) is enough to accomodate 'n' extra 85** elements plus one. (Because several opcodes add stuff to the capture 86** array, it is simpler to ensure the array always has at least one free 87** slot upfront and check its size later.) 88*/ 89 90/* new size in number of elements cannot overflow integers, and new 91size in bytes cannot overflow size_t. */ 92#define MAXNEWSIZE \ 93 (((size_t)INT_MAX) <= (~(size_t)0 / sizeof(Capture)) ? \ 94 ((size_t)INT_MAX) : (~(size_t)0 / sizeof(Capture))) 95 96static Capture * growcap (lua_State * L ,Capture * capture ,int * capsize , 97int captop ,int n ,int ptop ) { 98if (* capsize - captop > n ) 99return capture ;/* no need to grow array */ 100else {/* must grow */ 101Capture * newc ; 102uint newsize = captop + n + 1 ;/* minimum size needed */ 103if (newsize < (MAXNEWSIZE /3 )* 2 ) 104newsize += newsize /2 ;/* 1.5 that size, if not too big */ 105else if (newsize < (MAXNEWSIZE /9 )* 8 ) 106newsize += newsize /8 ;/* else, try 9/8 that size */ 107else 108luaL_error (L ,"too many captures" ); 109newc = (Capture * )lua_newuserdata (L ,newsize * sizeof (Capture )); 110memcpy (newc ,capture ,captop * sizeof (Capture )); 111* capsize = newsize ; 112lua_replace (L ,caplistidx (ptop )); 113return newc ; 114 } 115} 116 117 118/* 119** Double the size of the stack 120*/ 121static Stack * doublestack (lua_State * L ,Stack ** stacklimit ,int ptop ) { 122Stack * stack = getstackbase (L ,ptop ); 123Stack * newstack ; 124int n = * stacklimit - stack ;/* current stack size */ 125int max ,newn ; 126lua_getfield (L ,LUA_REGISTRYINDEX ,MAXSTACKIDX ); 127max = lua_tointeger (L ,-1 );/* maximum allowed size */ 128lua_pop (L ,1 ); 129if (n >=max )/* already at maximum size? */ 130luaL_error (L ,"backtrack stack overflow (current limit is %d)" ,max ); 131newn = 2 * n ;/* new size */ 132if (newn > max )newn = max ; 133newstack = (Stack * )lua_newuserdata (L ,newn * sizeof (Stack )); 134memcpy (newstack ,stack ,n * sizeof (Stack )); 135lua_replace (L ,stackidx (ptop )); 136* stacklimit = newstack + newn ; 137return newstack + n ;/* return next position */ 138} 139 140 141/* 142** Interpret the result of a dynamic capture: false -> fail; 143** true -> keep current position; number -> next position. 144** Return new subject position. 'fr' is stack index where 145** is the result; 'curr' is current subject position; 'limit' 146** is subject's size. 147*/ 148static int resdyncaptures (lua_State * L ,int fr ,int curr ,int limit ) { 149lua_Integer res ; 150if (!lua_toboolean (L ,fr )) {/* false value? */ 151lua_settop (L ,fr - 1 );/* remove results */ 152return -1 ;/* and fail */ 153 } 154else if (lua_isboolean (L ,fr ))/* true? */ 155res = curr ;/* keep current position */ 156else { 157res = lua_tointeger (L ,fr )- 1 ;/* new position */ 158if (res < curr || res > limit ) 159luaL_error (L ,"invalid position returned by match-time capture" ); 160 } 161lua_remove (L ,fr );/* remove first result (offset) */ 162return res ; 163} 164 165 166/* 167** Add capture values returned by a dynamic capture to the list 168** 'capture', nested inside a group. 'fd' indexes the first capture 169** value, 'n' is the number of values (at least 1). The open group 170** capture is already in 'capture', before the place for the new entries. 171*/ 172static void adddyncaptures (Index_t index ,Capture * capture ,int n ,int fd ) { 173int i ; 174assert (capture [-1 ].kind == Cgroup && capture [-1 ].siz == 0 ); 175capture [-1 ].idx = 0 ;/* make group capture an anonymous group */ 176for (i = 0 ;i < n ;i ++ ) {/* add runtime captures */ 177capture [i ].kind = Cruntime ; 178capture [i ].siz = 1 ;/* mark it as closed */ 179capture [i ].idx = fd + i ;/* stack index of capture value */ 180capture [i ].index = index ; 181 } 182capture [n ].kind = Cclose ;/* close group */ 183capture [n ].siz = 1 ; 184capture [n ].index = index ; 185} 186 187 188/* 189** Remove dynamic captures from the Lua stack (called in case of failure) 190*/ 191static int removedyncap (lua_State * L ,Capture * capture , 192int level ,int last ) { 193int id = finddyncap (capture + level ,capture + last );/* index of 1st cap. */ 194int top = lua_gettop (L ); 195if (id == 0 )return 0 ;/* no dynamic captures? */ 196lua_settop (L ,id - 1 );/* remove captures */ 197return top - id + 1 ;/* number of values removed */ 198} 199 200 201/* 202** Find the corresponding 'open' capture before 'cap', when that capture 203** can become a full capture. If a full capture c1 is followed by an 204** empty capture c2, there is no way to know whether c2 is inside 205** c1. So, full captures can enclose only captures that start *before* 206** its end. 207*/ 208static Capture * findopen (Capture * cap ,Index_t currindex ) { 209int i ; 210cap -- ;/* check last capture */ 211/* Must it be inside current one, but starts where current one ends? */ 212if (!isopencap (cap )&& cap -> index == currindex ) 213return NULL ;/* current one cannot be a full capture */ 214/* else, look for an 'open' capture */ 215for (i = 0 ;i < MAXLOP ;i ++ ,cap -- ) { 216if (currindex - cap -> index >=UCHAR_MAX ) 217return NULL ;/* capture too long for a full capture */ 218else if (isopencap (cap ))/* open capture? */ 219return cap ;/* that's the one to be closed */ 220else if (cap -> kind == Cclose ) 221return NULL ;/* a full capture should not nest a non-full one */ 222 } 223return NULL ;/* not found within allowed search limit */ 224} 225 226 227/* 228** Opcode interpreter 229*/ 230const char * match (lua_State * L ,const char * o ,const char * s ,const char * e , 231Instruction * op ,Capture * capture ,int ptop ) { 232Stack stackbase [INITBACK ]; 233Stack * stacklimit = stackbase + INITBACK ; 234Stack * stack = stackbase ;/* point to first empty slot in stack */ 235int capsize = INITCAPSIZE ; 236int captop = 0 ;/* point to first empty slot in captures */ 237int ndyncap = 0 ;/* number of dynamic captures (in Lua stack) */ 238const Instruction * p = op ;/* current instruction */ 239stack -> p = & giveup ;stack -> s = s ;stack -> caplevel = 0 ;stack ++ ; 240lua_pushlightuserdata (L ,stackbase ); 241for (;;) { 242#if defined(DEBUG ) 243printf ("-------------------------------------\n" ); 244printcaplist (capture ,capture + captop ); 245printf ("s: |%s| stck:%d, dyncaps:%d, caps:%d " , 246s , (int )(stack - getstackbase (L ,ptop )),ndyncap ,captop ); 247printinst (op ,p ); 248#endif 249assert (stackidx (ptop )+ ndyncap == lua_gettop (L )&& ndyncap <=captop ); 250switch ((Opcode )p -> i .code ) { 251case IEnd : { 252assert (stack == getstackbase (L ,ptop )+ 1 ); 253capture [captop ].kind = Cclose ; 254capture [captop ].index = MAXINDT ; 255return s ; 256 } 257case IGiveup : { 258assert (stack == getstackbase (L ,ptop )); 259return NULL ; 260 } 261case IRet : { 262assert (stack > getstackbase (L ,ptop )&& (stack - 1 )-> s == NULL ); 263p = (-- stack )-> p ; 264continue ; 265 } 266case IAny : { 267if (s < e ) {p ++ ;s ++ ; } 268else gotofail ; 269continue ; 270 } 271case IUTFR : { 272int codepoint ; 273if (s >=e ) 274 gotofail ; 275s = utf8_decode (s ,& codepoint ); 276if (s && p [1 ].offset <=codepoint && codepoint <=utf_to (p )) 277p += 2 ; 278else 279 gotofail ; 280continue ; 281 } 282case ITestAny : { 283if (s < e )p += 2 ; 284else p += getoffset (p ); 285continue ; 286 } 287case IChar : { 288if ((byte )* s == p -> i .aux1 && s < e ) {p ++ ;s ++ ; } 289else gotofail ; 290continue ; 291 } 292case ITestChar : { 293if ((byte )* s == p -> i .aux1 && s < e )p += 2 ; 294else p += getoffset (p ); 295continue ; 296 } 297case ISet : { 298uint c = (byte )* s ; 299if (charinset (p , (p + 1 )-> buff ,c )&& s < e ) 300 {p += 1 + p -> i .aux2 .set .size ;s ++ ; } 301else gotofail ; 302continue ; 303 } 304case ITestSet : { 305uint c = (byte )* s ; 306if (charinset (p , (p + 2 )-> buff ,c )&& s < e ) 307p += 2 + p -> i .aux2 .set .size ; 308else p += getoffset (p ); 309continue ; 310 } 311case IBehind : { 312int n = p -> i .aux1 ; 313if (n > s - o ) gotofail ; 314s -= n ;p ++ ; 315continue ; 316 } 317case ISpan : { 318for (;s < e ;s ++ ) { 319uint c = (byte )* s ; 320if (!charinset (p , (p + 1 )-> buff ,c ))break ; 321 } 322p += 1 + p -> i .aux2 .set .size ; 323continue ; 324 } 325case IJmp : { 326p += getoffset (p ); 327continue ; 328 } 329case IChoice : { 330if (stack == stacklimit ) 331stack = doublestack (L ,& stacklimit ,ptop ); 332stack -> p = p + getoffset (p ); 333stack -> s = s ; 334stack -> caplevel = captop ; 335stack ++ ; 336p += 2 ; 337continue ; 338 } 339case ICall : { 340if (stack == stacklimit ) 341stack = doublestack (L ,& stacklimit ,ptop ); 342stack -> s = NULL ; 343stack -> p = p + 2 ;/* save return address */ 344stack ++ ; 345p += getoffset (p ); 346continue ; 347 } 348case ICommit : { 349assert (stack > getstackbase (L ,ptop )&& (stack - 1 )-> s != NULL ); 350stack -- ; 351p += getoffset (p ); 352continue ; 353 } 354case IPartialCommit : { 355assert (stack > getstackbase (L ,ptop )&& (stack - 1 )-> s != NULL ); 356 (stack - 1 )-> s = s ; 357 (stack - 1 )-> caplevel = captop ; 358p += getoffset (p ); 359continue ; 360 } 361case IBackCommit : { 362assert (stack > getstackbase (L ,ptop )&& (stack - 1 )-> s != NULL ); 363s = (-- stack )-> s ; 364if (ndyncap > 0 )/* are there matchtime captures? */ 365ndyncap -= removedyncap (L ,capture ,stack -> caplevel ,captop ); 366captop = stack -> caplevel ; 367p += getoffset (p ); 368continue ; 369 } 370case IFailTwice : 371assert (stack > getstackbase (L ,ptop )); 372stack -- ; 373/* FALLTHROUGH */ 374case IFail : 375fail : {/* pattern failed: try to backtrack */ 376do {/* remove pending calls */ 377assert (stack > getstackbase (L ,ptop )); 378s = (-- stack )-> s ; 379 }while (s == NULL ); 380if (ndyncap > 0 )/* is there matchtime captures? */ 381ndyncap -= removedyncap (L ,capture ,stack -> caplevel ,captop ); 382captop = stack -> caplevel ; 383p = stack -> p ; 384#if defined(DEBUG ) 385printf ("**FAIL**\n" ); 386#endif 387continue ; 388 } 389case ICloseRunTime : { 390CapState cs ; 391int rem ,res ,n ; 392int fr = lua_gettop (L )+ 1 ;/* stack index of first result */ 393cs .reclevel = 0 ;cs .L = L ; 394cs .s = o ;cs .ocap = capture ;cs .ptop = ptop ; 395n = runtimecap (& cs ,capture + captop ,s ,& rem );/* call function */ 396captop -= n ;/* remove nested captures */ 397ndyncap -= rem ;/* update number of dynamic captures */ 398fr -= rem ;/* 'rem' items were popped from Lua stack */ 399res = resdyncaptures (L ,fr ,s - o ,e - o );/* get result */ 400if (res == -1 )/* fail? */ 401 gotofail ; 402s = o + res ;/* else update current position */ 403n = lua_gettop (L )- fr + 1 ;/* number of new captures */ 404ndyncap += n ;/* update number of dynamic captures */ 405if (n == 0 )/* no new captures? */ 406captop -- ;/* remove open group */ 407else {/* new captures; keep original open group */ 408if (fr + n >=SHRT_MAX ) 409luaL_error (L ,"too many results in match-time capture" ); 410/* add new captures + close group to 'capture' list */ 411capture = growcap (L ,capture ,& capsize ,captop ,n + 1 ,ptop ); 412adddyncaptures (s - o ,capture + captop ,n ,fr ); 413captop += n + 1 ;/* new captures + close group */ 414 } 415p ++ ; 416continue ; 417 } 418case ICloseCapture : { 419Capture * open = findopen (capture + captop ,s - o ); 420assert (captop > 0 ); 421if (open ) {/* if possible, turn capture into a full capture */ 422open -> siz = (s - o )- open -> index + 1 ; 423p ++ ; 424continue ; 425 } 426else {/* must create a close capture */ 427capture [captop ].siz = 1 ;/* mark entry as closed */ 428capture [captop ].index = s - o ; 429 gotopushcapture ; 430 } 431 } 432case IOpenCapture : 433capture [captop ].siz = 0 ;/* mark entry as open */ 434capture [captop ].index = s - o ; 435 gotopushcapture ; 436case IFullCapture : 437capture [captop ].siz = getoff (p )+ 1 ;/* save capture size */ 438capture [captop ].index = s - o - getoff (p ); 439/* goto pushcapture; */ 440pushcapture : { 441capture [captop ].idx = p -> i .aux2 .key ; 442capture [captop ].kind = getkind (p ); 443captop ++ ; 444capture = growcap (L ,capture ,& capsize ,captop ,0 ,ptop ); 445p ++ ; 446continue ; 447 } 448default :assert (0 );return NULL ; 449 } 450 } 451} 452 453/* }====================================================== */ 454 455