robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
1 2#include <limits.h> 3 4 5#include "lua.h" 6#include "lauxlib.h" 7 8#include "lptypes.h" 9#include "lpcode.h" 10#include "lpcset.h" 11 12 13/* signals a "no-instruction */ 14#define NOINST -1 15 16 17 18static const Charset fullset_ = 19 {{0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF , 200xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF , 210xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF , 220xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF ,0xFF }}; 23 24static const Charset * fullset = & fullset_ ; 25 26 27/* 28** {====================================================== 29** Analysis and some optimizations 30** ======================================================= 31*/ 32 33 34/* 35** A few basic operations on Charsets 36*/ 37static void cs_complement (Charset * cs ) { 38loopset (i ,cs -> cs [i ]= ~cs -> cs [i ]); 39} 40 41static int cs_disjoint (const Charset * cs1 ,const Charset * cs2 ) { 42loopset (i ,if ((cs1 -> cs [i ]& cs2 -> cs [i ])!= 0 )return 0 ;) 43return 1 ; 44} 45 46 47/* 48** Visit a TCall node taking care to stop recursion. If node not yet 49** visited, return 'f(sib2(tree))', otherwise return 'def' (default 50** value) 51*/ 52static int callrecursive (TTree * tree ,int f (TTree * t ),int def ) { 53int key = tree -> key ; 54assert (tree -> tag == TCall ); 55assert (sib2 (tree )-> tag == TRule ); 56if (key == 0 )/* node already visited? */ 57return def ;/* return default value */ 58else {/* first visit */ 59int result ; 60tree -> key = 0 ;/* mark call as already visited */ 61result = f (sib2 (tree ));/* go to called rule */ 62tree -> key = key ;/* restore tree */ 63return result ; 64 } 65} 66 67 68/* 69** Check whether a pattern tree has captures 70*/ 71int hascaptures (TTree * tree ) { 72tailcall : 73switch (tree -> tag ) { 74case TCapture :case TRunTime : 75return 1 ; 76case TCall : 77return callrecursive (tree ,hascaptures ,0 ); 78case TRule :/* do not follow siblings */ 79tree = sib1 (tree ); gototailcall ; 80case TOpenCall :assert (0 ); 81default : { 82switch (numsiblings [tree -> tag ]) { 83case 1 :/* return hascaptures(sib1(tree)); */ 84tree = sib1 (tree ); gototailcall ; 85case 2 : 86if (hascaptures (sib1 (tree ))) 87return 1 ; 88/* else return hascaptures(sib2(tree)); */ 89tree = sib2 (tree ); gototailcall ; 90default :assert (numsiblings [tree -> tag ]== 0 );return 0 ; 91 } 92 } 93 } 94} 95 96 97/* 98** Checks how a pattern behaves regarding the empty string, 99** in one of two different ways: 100** A pattern is *nullable* if it can match without consuming any character; 101** A pattern is *nofail* if it never fails for any string 102** (including the empty string). 103** The difference is only for predicates and run-time captures; 104** for other patterns, the two properties are equivalent. 105** (With predicates, &'a' is nullable but not nofail. Of course, 106** nofail => nullable.) 107** These functions are all convervative in the following way: 108** p is nullable => nullable(p) 109** nofail(p) => p cannot fail 110** The function assumes that TOpenCall is not nullable; 111** this will be checked again when the grammar is fixed. 112** Run-time captures can do whatever they want, so the result 113** is conservative. 114*/ 115int checkaux (TTree * tree ,int pred ) { 116tailcall : 117switch (tree -> tag ) { 118case TChar :case TSet :case TAny :case TUTFR : 119case TFalse :case TOpenCall : 120return 0 ;/* not nullable */ 121case TRep :case TTrue : 122return 1 ;/* no fail */ 123case TNot :case TBehind :/* can match empty, but can fail */ 124if (pred == PEnofail )return 0 ; 125else return 1 ;/* PEnullable */ 126case TAnd :/* can match empty; fail iff body does */ 127if (pred == PEnullable )return 1 ; 128/* else return checkaux(sib1(tree), pred); */ 129tree = sib1 (tree ); gototailcall ; 130case TRunTime :/* can fail; match empty iff body does */ 131if (pred == PEnofail )return 0 ; 132/* else return checkaux(sib1(tree), pred); */ 133tree = sib1 (tree ); gototailcall ; 134case TSeq : 135if (!checkaux (sib1 (tree ),pred ))return 0 ; 136/* else return checkaux(sib2(tree), pred); */ 137tree = sib2 (tree ); gototailcall ; 138case TChoice : 139if (checkaux (sib2 (tree ),pred ))return 1 ; 140/* else return checkaux(sib1(tree), pred); */ 141tree = sib1 (tree ); gototailcall ; 142case TCapture :case TGrammar :case TRule :case TXInfo : 143/* return checkaux(sib1(tree), pred); */ 144tree = sib1 (tree ); gototailcall ; 145case TCall :/* return checkaux(sib2(tree), pred); */ 146tree = sib2 (tree ); gototailcall ; 147default :assert (0 );return 0 ; 148 } 149} 150 151 152/* 153** number of characters to match a pattern (or -1 if variable) 154*/ 155int fixedlen (TTree * tree ) { 156int len = 0 ;/* to accumulate in tail calls */ 157tailcall : 158switch (tree -> tag ) { 159case TChar :case TSet :case TAny : 160return len + 1 ; 161case TUTFR : 162return (tree -> cap == sib1 (tree )-> cap ) ?len + tree -> cap :-1 ; 163case TFalse :case TTrue :case TNot :case TAnd :case TBehind : 164return len ; 165case TRep :case TRunTime :case TOpenCall : 166return -1 ; 167case TCapture :case TRule :case TGrammar :case TXInfo : 168/* return fixedlen(sib1(tree)); */ 169tree = sib1 (tree ); gototailcall ; 170case TCall : { 171int n1 = callrecursive (tree ,fixedlen ,-1 ); 172if (n1 < 0 ) 173return -1 ; 174else 175return len + n1 ; 176 } 177case TSeq : { 178int n1 = fixedlen (sib1 (tree )); 179if (n1 < 0 ) 180return -1 ; 181/* else return fixedlen(sib2(tree)) + len; */ 182len += n1 ;tree = sib2 (tree ); gototailcall ; 183 } 184case TChoice : { 185int n1 = fixedlen (sib1 (tree )); 186int n2 = fixedlen (sib2 (tree )); 187if (n1 != n2 || n1 < 0 ) 188return -1 ; 189else 190return len + n1 ; 191 } 192default :assert (0 );return 0 ; 193 }; 194} 195 196 197/* 198** Computes the 'first set' of a pattern. 199** The result is a conservative aproximation: 200** match p ax -> x (for some x) ==> a belongs to first(p) 201** or 202** a not in first(p) ==> match p ax -> fail (for all x) 203** 204** The set 'follow' is the first set of what follows the 205** pattern (full set if nothing follows it). 206** 207** The function returns 0 when this resulting set can be used for 208** test instructions that avoid the pattern altogether. 209** A non-zero return can happen for two reasons: 210** 1) match p '' -> '' ==> return has bit 1 set 211** (tests cannot be used because they would always fail for an empty input); 212** 2) there is a match-time capture ==> return has bit 2 set 213** (optimizations should not bypass match-time captures). 214*/ 215static int getfirst (TTree * tree ,const Charset * follow ,Charset * firstset ) { 216tailcall : 217switch (tree -> tag ) { 218case TChar :case TSet :case TAny :case TFalse : { 219tocharset (tree ,firstset ); 220return 0 ; 221 } 222case TUTFR : { 223int c ; 224clearset (firstset -> cs );/* erase all chars */ 225for (c = tree -> key ;c <=sib1 (tree )-> key ;c ++ ) 226setchar (firstset -> cs ,c ); 227return 0 ; 228 } 229case TTrue : { 230loopset (i ,firstset -> cs [i ]= follow -> cs [i ]); 231return 1 ;/* accepts the empty string */ 232 } 233case TChoice : { 234Charset csaux ; 235int e1 = getfirst (sib1 (tree ),follow ,firstset ); 236int e2 = getfirst (sib2 (tree ),follow ,& csaux ); 237loopset (i ,firstset -> cs [i ] |=csaux .cs [i ]); 238return e1 |e2 ; 239 } 240case TSeq : { 241if (!nullable (sib1 (tree ))) { 242/* when p1 is not nullable, p2 has nothing to contribute; 243return getfirst(sib1(tree), fullset, firstset); */ 244tree = sib1 (tree );follow = fullset ; gototailcall ; 245 } 246else {/* FIRST(p1 p2, fl) = FIRST(p1, FIRST(p2, fl)) */ 247Charset csaux ; 248int e2 = getfirst (sib2 (tree ),follow ,& csaux ); 249int e1 = getfirst (sib1 (tree ),& csaux ,firstset ); 250if (e1 == 0 )return 0 ;/* 'e1' ensures that first can be used */ 251else if ((e1 |e2 )& 2 )/* one of the children has a matchtime? */ 252return 2 ;/* pattern has a matchtime capture */ 253else return e2 ;/* else depends on 'e2' */ 254 } 255 } 256case TRep : { 257getfirst (sib1 (tree ),follow ,firstset ); 258loopset (i ,firstset -> cs [i ] |=follow -> cs [i ]); 259return 1 ;/* accept the empty string */ 260 } 261case TCapture :case TGrammar :case TRule :case TXInfo : { 262/* return getfirst(sib1(tree), follow, firstset); */ 263tree = sib1 (tree ); gototailcall ; 264 } 265case TRunTime : {/* function invalidates any follow info. */ 266int e = getfirst (sib1 (tree ),fullset ,firstset ); 267if (e )return 2 ;/* function is not "protected"? */ 268else return 0 ;/* pattern inside capture ensures first can be used */ 269 } 270case TCall : { 271/* return getfirst(sib2(tree), follow, firstset); */ 272tree = sib2 (tree ); gototailcall ; 273 } 274case TAnd : { 275int e = getfirst (sib1 (tree ),follow ,firstset ); 276loopset (i ,firstset -> cs [i ] &=follow -> cs [i ]); 277return e ; 278 } 279case TNot : { 280if (tocharset (sib1 (tree ),firstset )) { 281cs_complement (firstset ); 282return 1 ; 283 }/* else */ 284 }/* FALLTHROUGH */ 285case TBehind : {/* instruction gives no new information */ 286/* call 'getfirst' only to check for math-time captures */ 287int e = getfirst (sib1 (tree ),follow ,firstset ); 288loopset (i ,firstset -> cs [i ]= follow -> cs [i ]);/* uses follow */ 289return e |1 ;/* always can accept the empty string */ 290 } 291default :assert (0 );return 0 ; 292 } 293} 294 295 296/* 297** If 'headfail(tree)' true, then 'tree' can fail only depending on the 298** next character of the subject. 299*/ 300static int headfail (TTree * tree ) { 301tailcall : 302switch (tree -> tag ) { 303case TChar :case TSet :case TAny :case TFalse : 304return 1 ; 305case TTrue :case TRep :case TRunTime :case TNot : 306case TBehind :case TUTFR : 307return 0 ; 308case TCapture :case TGrammar :case TRule :case TXInfo :case TAnd : 309tree = sib1 (tree ); gototailcall ;/* return headfail(sib1(tree)); */ 310case TCall : 311tree = sib2 (tree ); gototailcall ;/* return headfail(sib2(tree)); */ 312case TSeq : 313if (!nofail (sib2 (tree )))return 0 ; 314/* else return headfail(sib1(tree)); */ 315tree = sib1 (tree ); gototailcall ; 316case TChoice : 317if (!headfail (sib1 (tree )))return 0 ; 318/* else return headfail(sib2(tree)); */ 319tree = sib2 (tree ); gototailcall ; 320default :assert (0 );return 0 ; 321 } 322} 323 324 325/* 326** Check whether the code generation for the given tree can benefit 327** from a follow set (to avoid computing the follow set when it is 328** not needed) 329*/ 330static int needfollow (TTree * tree ) { 331tailcall : 332switch (tree -> tag ) { 333case TChar :case TSet :case TAny :case TUTFR : 334case TFalse :case TTrue :case TAnd :case TNot : 335case TRunTime :case TGrammar :case TCall :case TBehind : 336return 0 ; 337case TChoice :case TRep : 338return 1 ; 339case TCapture : 340tree = sib1 (tree ); gototailcall ; 341case TSeq : 342tree = sib2 (tree ); gototailcall ; 343default :assert (0 );return 0 ; 344 } 345} 346 347/* }====================================================== */ 348 349 350 351/* 352** {====================================================== 353** Code generation 354** ======================================================= 355*/ 356 357 358/* 359** size of an instruction 360*/ 361int sizei (const Instruction * i ) { 362switch ((Opcode )i -> i .code ) { 363case ISet :case ISpan :return 1 + i -> i .aux2 .set .size ; 364case ITestSet :return 2 + i -> i .aux2 .set .size ; 365case ITestChar :case ITestAny :case IChoice :case IJmp :case ICall : 366case IOpenCall :case ICommit :case IPartialCommit :case IBackCommit : 367case IUTFR : 368return 2 ; 369default :return 1 ; 370 } 371} 372 373 374/* 375** state for the compiler 376*/ 377typedef struct CompileState { 378Pattern * p ;/* pattern being compiled */ 379int ncode ;/* next position in p->code to be filled */ 380lua_State * L ; 381}CompileState ; 382 383 384/* 385** code generation is recursive; 'opt' indicates that the code is being 386** generated as the last thing inside an optional pattern (so, if that 387** code is optional too, it can reuse the 'IChoice' already in place for 388** the outer pattern). 'tt' points to a previous test protecting this 389** code (or NOINST). 'fl' is the follow set of the pattern. 390*/ 391static void codegen (CompileState * compst ,TTree * tree ,int opt ,int tt , 392const Charset * fl ); 393 394 395static void finishrelcode (lua_State * L ,Pattern * p ,Instruction * block , 396int size ) { 397if (block == NULL ) 398luaL_error (L ,"not enough memory" ); 399block -> codesize = size ; 400p -> code = (Instruction * )block + 1 ; 401} 402 403 404/* 405** Initialize array 'p->code' 406*/ 407static void newcode (lua_State * L ,Pattern * p ,int size ) { 408void * ud ; 409Instruction * block ; 410lua_Alloc f = lua_getallocf (L ,& ud ); 411size ++ ;/* slot for 'codesize' */ 412block = (Instruction * )f (ud ,NULL ,0 ,size * sizeof (Instruction )); 413finishrelcode (L ,p ,block ,size ); 414} 415 416 417void freecode (lua_State * L ,Pattern * p ) { 418if (p -> code != NULL ) { 419void * ud ; 420lua_Alloc f = lua_getallocf (L ,& ud ); 421uint osize = p -> code [-1 ].codesize ; 422f (ud ,p -> code - 1 ,osize * sizeof (Instruction ),0 );/* free block */ 423 } 424} 425 426 427/* 428** Assume that 'nsize' is not zero and that 'p->code' already exists. 429*/ 430static void realloccode (lua_State * L ,Pattern * p ,int nsize ) { 431void * ud ; 432lua_Alloc f = lua_getallocf (L ,& ud ); 433Instruction * block = p -> code - 1 ; 434uint osize = block -> codesize ; 435nsize ++ ;/* add the 'codesize' slot to size */ 436block = (Instruction * )f (ud ,block ,osize * sizeof (Instruction ), 437nsize * sizeof (Instruction )); 438finishrelcode (L ,p ,block ,nsize ); 439} 440 441 442/* 443** Add space for an instruction with 'n' slots and return its index. 444*/ 445static int nextinstruction (CompileState * compst ,int n ) { 446int size = compst -> p -> code [-1 ].codesize - 1 ; 447int ncode = compst -> ncode ; 448if (ncode > size - n ) { 449uint nsize = size + (size >>1 )+ n ; 450if (nsize >=INT_MAX ) 451luaL_error (compst -> L ,"pattern code too large" ); 452realloccode (compst -> L ,compst -> p ,nsize ); 453 } 454compst -> ncode = ncode + n ; 455return ncode ; 456} 457 458 459#define getinstr (cs ,i ) ((cs)->p->code[i]) 460 461 462static int addinstruction (CompileState * compst ,Opcode op ,int aux ) { 463int i = nextinstruction (compst ,1 ); 464getinstr (compst ,i ).i .code = op ; 465getinstr (compst ,i ).i .aux1 = aux ; 466return i ; 467} 468 469 470/* 471** Add an instruction followed by space for an offset (to be set later) 472*/ 473static int addoffsetinst (CompileState * compst ,Opcode op ) { 474int i = addinstruction (compst ,op ,0 );/* instruction */ 475addinstruction (compst , (Opcode )0 ,0 );/* open space for offset */ 476assert (op == ITestSet || sizei (& getinstr (compst ,i ))== 2 ); 477return i ; 478} 479 480 481/* 482** Set the offset of an instruction 483*/ 484static void setoffset (CompileState * compst ,int instruction ,int offset ) { 485getinstr (compst ,instruction + 1 ).offset = offset ; 486} 487 488 489static void codeutfr (CompileState * compst ,TTree * tree ) { 490int i = addoffsetinst (compst ,IUTFR ); 491int to = sib1 (tree )-> u .n ; 492assert (sib1 (tree )-> tag == TXInfo ); 493getinstr (compst ,i + 1 ).offset = tree -> u .n ; 494getinstr (compst ,i ).i .aux1 = to & 0xff ; 495getinstr (compst ,i ).i .aux2 .key = to >>8 ; 496} 497 498 499/* 500** Add a capture instruction: 501** 'op' is the capture instruction; 'cap' the capture kind; 502** 'key' the key into ktable; 'aux' is the optional capture offset 503** 504*/ 505static int addinstcap (CompileState * compst ,Opcode op ,int cap ,int key , 506int aux ) { 507int i = addinstruction (compst ,op ,joinkindoff (cap ,aux )); 508getinstr (compst ,i ).i .aux2 .key = key ; 509return i ; 510} 511 512 513#define gethere (compst ) ((compst)->ncode) 514 515#define target (code ,i ) ((i) + code[i + 1].offset) 516 517 518/* 519** Patch 'instruction' to jump to 'target' 520*/ 521static void jumptothere (CompileState * compst ,int instruction ,int target ) { 522if (instruction >=0 ) 523setoffset (compst ,instruction ,target - instruction ); 524} 525 526 527/* 528** Patch 'instruction' to jump to current position 529*/ 530static void jumptohere (CompileState * compst ,int instruction ) { 531jumptothere (compst ,instruction ,gethere (compst )); 532} 533 534 535/* 536** Code an IChar instruction, or IAny if there is an equivalent 537** test dominating it 538*/ 539static void codechar (CompileState * compst ,int c ,int tt ) { 540if (tt >=0 && getinstr (compst ,tt ).i .code == ITestChar && 541getinstr (compst ,tt ).i .aux1 == c ) 542addinstruction (compst ,IAny ,0 ); 543else 544addinstruction (compst ,IChar ,c ); 545} 546 547 548/* 549** Add a charset posfix to an instruction. 550*/ 551static void addcharset (CompileState * compst ,int inst ,charsetinfo * info ) { 552int p ; 553Instruction * I = & getinstr (compst ,inst ); 554byte * charset ; 555int isize = instsize (info -> size );/* size in instructions */ 556int i ; 557I -> i .aux2 .set .offset = info -> offset * 8 ;/* offset in bits */ 558I -> i .aux2 .set .size = isize ; 559I -> i .aux1 = info -> deflt ; 560p = nextinstruction (compst ,isize );/* space for charset */ 561charset = getinstr (compst ,p ).buff ;/* charset buffer */ 562for (i = 0 ;i < isize * (int )sizeof (Instruction );i ++ ) 563charset [i ]= getbytefromcharset (info ,i );/* copy the buffer */ 564} 565 566 567/* 568** Check whether charset 'info' is dominated by instruction 'p' 569*/ 570static int cs_equal (Instruction * p ,charsetinfo * info ) { 571if (p -> i .code != ITestSet ) 572return 0 ; 573else if (p -> i .aux2 .set .offset != info -> offset * 8 || 574p -> i .aux2 .set .size != instsize (info -> size )|| 575p -> i .aux1 != info -> deflt ) 576return 0 ; 577else { 578int i ; 579for (i = 0 ;i < instsize (info -> size )* (int )sizeof (Instruction );i ++ ) { 580if ((p + 2 )-> buff [i ]!= getbytefromcharset (info ,i )) 581return 0 ; 582 } 583 } 584return 1 ; 585} 586 587 588/* 589** Code a char set, using IAny when instruction is dominated by an 590** equivalent test. 591*/ 592static void codecharset (CompileState * compst ,TTree * tree ,int tt ) { 593charsetinfo info ; 594tree2cset (tree ,& info ); 595if (tt >=0 && cs_equal (& getinstr (compst ,tt ),& info )) 596addinstruction (compst ,IAny ,0 ); 597else { 598int i = addinstruction (compst ,ISet ,0 ); 599addcharset (compst ,i ,& info ); 600 } 601} 602 603 604/* 605** Code a test set, optimizing unit sets for ITestChar, "complete" 606** sets for ITestAny, and empty sets for IJmp (always fails). 607** 'e' is true iff test should accept the empty string. (Test 608** instructions in the current VM never accept the empty string.) 609*/ 610static int codetestset (CompileState * compst ,Charset * cs ,int e ) { 611if (e )return NOINST ;/* no test */ 612else { 613charsetinfo info ; 614Opcode op = charsettype (cs -> cs ,& info ); 615switch (op ) { 616case IFail :return addoffsetinst (compst ,IJmp );/* always jump */ 617case IAny :return addoffsetinst (compst ,ITestAny ); 618case IChar : { 619int i = addoffsetinst (compst ,ITestChar ); 620getinstr (compst ,i ).i .aux1 = info .offset ; 621return i ; 622 } 623default : {/* regular set */ 624int i = addoffsetinst (compst ,ITestSet ); 625addcharset (compst ,i ,& info ); 626assert (op == ISet ); 627return i ; 628 } 629 } 630 } 631} 632 633 634/* 635** Find the final destination of a sequence of jumps 636*/ 637static int finaltarget (Instruction * code ,int i ) { 638while (code [i ].i .code == IJmp ) 639i = target (code ,i ); 640return i ; 641} 642 643 644/* 645** final label (after traversing any jumps) 646*/ 647static int finallabel (Instruction * code ,int i ) { 648return finaltarget (code ,target (code ,i )); 649} 650 651 652/* 653** <behind(p)> == behind n; <p> (where n = fixedlen(p)) 654*/ 655static void codebehind (CompileState * compst ,TTree * tree ) { 656if (tree -> u .n > 0 ) 657addinstruction (compst ,IBehind ,tree -> u .n ); 658codegen (compst ,sib1 (tree ),0 ,NOINST ,fullset ); 659} 660 661 662/* 663** Choice; optimizations: 664** - when p1 is headfail or when first(p1) and first(p2) are disjoint, 665** than a character not in first(p1) cannot go to p1 and a character 666** in first(p1) cannot go to p2, either because p1 will accept 667** (headfail) or because it is not in first(p2) (disjoint). 668** (The second case is not valid if p1 accepts the empty string, 669** as then there is no character at all...) 670** - when p2 is empty and opt is true; a IPartialCommit can reuse 671** the Choice already active in the stack. 672*/ 673static void codechoice (CompileState * compst ,TTree * p1 ,TTree * p2 ,int opt , 674const Charset * fl ) { 675int emptyp2 = (p2 -> tag == TTrue ); 676Charset cs1 ,cs2 ; 677int e1 = getfirst (p1 ,fullset ,& cs1 ); 678if (headfail (p1 )|| 679 (!e1 && (getfirst (p2 ,fl ,& cs2 ),cs_disjoint (& cs1 ,& cs2 )))) { 680/* <p1 / p2> == test (fail(p1)) -> L1 ; p1 ; jmp L2; L1: p2; L2: */ 681int test = codetestset (compst ,& cs1 ,0 ); 682int jmp = NOINST ; 683codegen (compst ,p1 ,0 ,test ,fl ); 684if (!emptyp2 ) 685jmp = addoffsetinst (compst ,IJmp ); 686jumptohere (compst ,test ); 687codegen (compst ,p2 ,opt ,NOINST ,fl ); 688jumptohere (compst ,jmp ); 689 } 690else if (opt && emptyp2 ) { 691/* p1? == IPartialCommit; p1 */ 692jumptohere (compst ,addoffsetinst (compst ,IPartialCommit )); 693codegen (compst ,p1 ,1 ,NOINST ,fullset ); 694 } 695else { 696/* <p1 / p2> == 697test(first(p1)) -> L1; choice L1; <p1>; commit L2; L1: <p2>; L2: */ 698int pcommit ; 699int test = codetestset (compst ,& cs1 ,e1 ); 700int pchoice = addoffsetinst (compst ,IChoice ); 701codegen (compst ,p1 ,emptyp2 ,test ,fullset ); 702pcommit = addoffsetinst (compst ,ICommit ); 703jumptohere (compst ,pchoice ); 704jumptohere (compst ,test ); 705codegen (compst ,p2 ,opt ,NOINST ,fl ); 706jumptohere (compst ,pcommit ); 707 } 708} 709 710 711/* 712** And predicate 713** optimization: fixedlen(p) = n ==> <&p> == <p>; behind n 714** (valid only when 'p' has no captures) 715*/ 716static void codeand (CompileState * compst ,TTree * tree ,int tt ) { 717int n = fixedlen (tree ); 718if (n >=0 && n <=MAXBEHIND && !hascaptures (tree )) { 719codegen (compst ,tree ,0 ,tt ,fullset ); 720if (n > 0 ) 721addinstruction (compst ,IBehind ,n ); 722 } 723else {/* default: Choice L1; p1; BackCommit L2; L1: Fail; L2: */ 724int pcommit ; 725int pchoice = addoffsetinst (compst ,IChoice ); 726codegen (compst ,tree ,0 ,tt ,fullset ); 727pcommit = addoffsetinst (compst ,IBackCommit ); 728jumptohere (compst ,pchoice ); 729addinstruction (compst ,IFail ,0 ); 730jumptohere (compst ,pcommit ); 731 } 732} 733 734 735/* 736** Captures: if pattern has fixed (and not too big) length, and it 737** has no nested captures, use a single IFullCapture instruction 738** after the match; otherwise, enclose the pattern with OpenCapture - 739** CloseCapture. 740*/ 741static void codecapture (CompileState * compst ,TTree * tree ,int tt , 742const Charset * fl ) { 743int len = fixedlen (sib1 (tree )); 744if (len >=0 && len <=MAXOFF && !hascaptures (sib1 (tree ))) { 745codegen (compst ,sib1 (tree ),0 ,tt ,fl ); 746addinstcap (compst ,IFullCapture ,tree -> cap ,tree -> key ,len ); 747 } 748else { 749addinstcap (compst ,IOpenCapture ,tree -> cap ,tree -> key ,0 ); 750codegen (compst ,sib1 (tree ),0 ,tt ,fl ); 751addinstcap (compst ,ICloseCapture ,Cclose ,0 ,0 ); 752 } 753} 754 755 756static void coderuntime (CompileState * compst ,TTree * tree ,int tt ) { 757addinstcap (compst ,IOpenCapture ,Cgroup ,tree -> key ,0 ); 758codegen (compst ,sib1 (tree ),0 ,tt ,fullset ); 759addinstcap (compst ,ICloseRunTime ,Cclose ,0 ,0 ); 760} 761 762 763/* 764** Create a jump to 'test' and fix 'test' to jump to next instruction 765*/ 766static void closeloop (CompileState * compst ,int test ) { 767int jmp = addoffsetinst (compst ,IJmp ); 768jumptohere (compst ,test ); 769jumptothere (compst ,jmp ,test ); 770} 771 772 773/* 774** Try repetition of charsets: 775** For an empty set, repetition of fail is a no-op; 776** For any or char, code a tight loop; 777** For generic charset, use a span instruction. 778*/ 779static int coderepcharset (CompileState * compst ,TTree * tree ) { 780switch (tree -> tag ) { 781case TFalse :return 1 ;/* 'fail*' is a no-op */ 782case TAny : {/* L1: testany -> L2; any; jmp L1; L2: */ 783int test = addoffsetinst (compst ,ITestAny ); 784addinstruction (compst ,IAny ,0 ); 785closeloop (compst ,test ); 786return 1 ; 787 } 788case TChar : {/* L1: testchar c -> L2; any; jmp L1; L2: */ 789int test = addoffsetinst (compst ,ITestChar ); 790getinstr (compst ,test ).i .aux1 = tree -> u .n ; 791addinstruction (compst ,IAny ,0 ); 792closeloop (compst ,test ); 793return 1 ; 794 } 795case TSet : {/* regular set */ 796charsetinfo info ; 797int i = addinstruction (compst ,ISpan ,0 ); 798tree2cset (tree ,& info ); 799addcharset (compst ,i ,& info ); 800return 1 ; 801 } 802default :return 0 ;/* not a charset */ 803 } 804} 805 806 807/* 808** Repetion; optimizations: 809** When pattern is a charset, use special code. 810** When pattern is head fail, or if it starts with characters that 811** are disjoint from what follows the repetions, a simple test 812** is enough (a fail inside the repetition would backtrack to fail 813** again in the following pattern, so there is no need for a choice). 814** When 'opt' is true, the repetion can reuse the Choice already 815** active in the stack. 816*/ 817static void coderep (CompileState * compst ,TTree * tree ,int opt , 818const Charset * fl ) { 819if (!coderepcharset (compst ,tree )) { 820Charset st ; 821int e1 = getfirst (tree ,fullset ,& st ); 822if (headfail (tree )|| (!e1 && cs_disjoint (& st ,fl ))) { 823/* L1: test (fail(p1)) -> L2; <p>; jmp L1; L2: */ 824int test = codetestset (compst ,& st ,0 ); 825codegen (compst ,tree ,0 ,test ,fullset ); 826closeloop (compst ,test ); 827 } 828else { 829/* test(fail(p1)) -> L2; choice L2; L1: <p>; partialcommit L1; L2: */ 830/* or (if 'opt'): partialcommit L1; L1: <p>; partialcommit L1; */ 831int commit ,l2 ; 832int test = codetestset (compst ,& st ,e1 ); 833int pchoice = NOINST ; 834if (opt ) 835jumptohere (compst ,addoffsetinst (compst ,IPartialCommit )); 836else 837pchoice = addoffsetinst (compst ,IChoice ); 838l2 = gethere (compst ); 839codegen (compst ,tree ,0 ,NOINST ,fullset ); 840commit = addoffsetinst (compst ,IPartialCommit ); 841jumptothere (compst ,commit ,l2 ); 842jumptohere (compst ,pchoice ); 843jumptohere (compst ,test ); 844 } 845 } 846} 847 848 849/* 850** Not predicate; optimizations: 851** In any case, if first test fails, 'not' succeeds, so it can jump to 852** the end. If pattern is headfail, that is all (it cannot fail 853** in other parts); this case includes 'not' of simple sets. Otherwise, 854** use the default code (a choice plus a failtwice). 855*/ 856static void codenot (CompileState * compst ,TTree * tree ) { 857Charset st ; 858int e = getfirst (tree ,fullset ,& st ); 859int test = codetestset (compst ,& st ,e ); 860if (headfail (tree ))/* test (fail(p1)) -> L1; fail; L1: */ 861addinstruction (compst ,IFail ,0 ); 862else { 863/* test(fail(p))-> L1; choice L1; <p>; failtwice; L1: */ 864int pchoice = addoffsetinst (compst ,IChoice ); 865codegen (compst ,tree ,0 ,NOINST ,fullset ); 866addinstruction (compst ,IFailTwice ,0 ); 867jumptohere (compst ,pchoice ); 868 } 869jumptohere (compst ,test ); 870} 871 872 873/* 874** change open calls to calls, using list 'positions' to find 875** correct offsets; also optimize tail calls 876*/ 877static void correctcalls (CompileState * compst ,int * positions , 878int from ,int to ) { 879int i ; 880Instruction * code = compst -> p -> code ; 881for (i = from ;i < to ;i += sizei (& code [i ])) { 882if (code [i ].i .code == IOpenCall ) { 883int n = code [i ].i .aux2 .key ;/* rule number */ 884int rule = positions [n ];/* rule position */ 885assert (rule == from || code [rule - 1 ].i .code == IRet ); 886if (code [finaltarget (code ,i + 2 )].i .code == IRet )/* call; ret ? */ 887code [i ].i .code = IJmp ;/* tail call */ 888else 889code [i ].i .code = ICall ; 890jumptothere (compst ,i ,rule );/* call jumps to respective rule */ 891 } 892 } 893assert (i == to ); 894} 895 896 897/* 898** Code for a grammar: 899** call L1; jmp L2; L1: rule 1; ret; rule 2; ret; ...; L2: 900*/ 901static void codegrammar (CompileState * compst ,TTree * grammar ) { 902int positions [MAXRULES ]; 903int rulenumber = 0 ; 904TTree * rule ; 905int firstcall = addoffsetinst (compst ,ICall );/* call initial rule */ 906int jumptoend = addoffsetinst (compst ,IJmp );/* jump to the end */ 907int start = gethere (compst );/* here starts the initial rule */ 908jumptohere (compst ,firstcall ); 909for (rule = sib1 (grammar );rule -> tag == TRule ;rule = sib2 (rule )) { 910TTree * r = sib1 (rule ); 911assert (r -> tag == TXInfo ); 912positions [rulenumber ++ ]= gethere (compst );/* save rule position */ 913codegen (compst ,sib1 (r ),0 ,NOINST ,fullset );/* code rule */ 914addinstruction (compst ,IRet ,0 ); 915 } 916assert (rule -> tag == TTrue ); 917jumptohere (compst ,jumptoend ); 918correctcalls (compst ,positions ,start ,gethere (compst )); 919} 920 921 922static void codecall (CompileState * compst ,TTree * call ) { 923int c = addoffsetinst (compst ,IOpenCall );/* to be corrected later */ 924assert (sib1 (sib2 (call ))-> tag == TXInfo ); 925getinstr (compst ,c ).i .aux2 .key = sib1 (sib2 (call ))-> u .n ;/* rule number */ 926} 927 928 929/* 930** Code first child of a sequence 931** (second child is called in-place to allow tail call) 932** Return 'tt' for second child 933*/ 934static int codeseq1 (CompileState * compst ,TTree * p1 ,TTree * p2 , 935int tt ,const Charset * fl ) { 936if (needfollow (p1 )) { 937Charset fl1 ; 938getfirst (p2 ,fl ,& fl1 );/* p1 follow is p2 first */ 939codegen (compst ,p1 ,0 ,tt ,& fl1 ); 940 } 941else /* use 'fullset' as follow */ 942codegen (compst ,p1 ,0 ,tt ,fullset ); 943if (fixedlen (p1 )!= 0 )/* can 'p1' consume anything? */ 944return NOINST ;/* invalidate test */ 945else return tt ;/* else 'tt' still protects sib2 */ 946} 947 948 949/* 950** Main code-generation function: dispatch to auxiliar functions 951** according to kind of tree. ('needfollow' should return true 952** only for consructions that use 'fl'.) 953*/ 954static void codegen (CompileState * compst ,TTree * tree ,int opt ,int tt , 955const Charset * fl ) { 956tailcall : 957switch (tree -> tag ) { 958case TChar :codechar (compst ,tree -> u .n ,tt );break ; 959case TAny :addinstruction (compst ,IAny ,0 );break ; 960case TSet :codecharset (compst ,tree ,tt );break ; 961case TTrue :break ; 962case TFalse :addinstruction (compst ,IFail ,0 );break ; 963case TUTFR :codeutfr (compst ,tree );break ; 964case TChoice :codechoice (compst ,sib1 (tree ),sib2 (tree ),opt ,fl );break ; 965case TRep :coderep (compst ,sib1 (tree ),opt ,fl );break ; 966case TBehind :codebehind (compst ,tree );break ; 967case TNot :codenot (compst ,sib1 (tree ));break ; 968case TAnd :codeand (compst ,sib1 (tree ),tt );break ; 969case TCapture :codecapture (compst ,tree ,tt ,fl );break ; 970case TRunTime :coderuntime (compst ,tree ,tt );break ; 971case TGrammar :codegrammar (compst ,tree );break ; 972case TCall :codecall (compst ,tree );break ; 973case TSeq : { 974tt = codeseq1 (compst ,sib1 (tree ),sib2 (tree ),tt ,fl );/* code 'p1' */ 975/* codegen(compst, p2, opt, tt, fl); */ 976tree = sib2 (tree ); gototailcall ; 977 } 978default :assert (0 ); 979 } 980} 981 982 983/* 984** Optimize jumps and other jump-like instructions. 985** * Update labels of instructions with labels to their final 986** destinations (e.g., choice L1; ... L1: jmp L2: becomes 987** choice L2) 988** * Jumps to other instructions that do jumps become those 989** instructions (e.g., jump to return becomes a return; jump 990** to commit becomes a commit) 991*/ 992static void peephole (CompileState * compst ) { 993Instruction * code = compst -> p -> code ; 994int i ; 995for (i = 0 ;i < compst -> ncode ;i += sizei (& code [i ])) { 996redo : 997switch (code [i ].i .code ) { 998case IChoice :case ICall :case ICommit :case IPartialCommit : 999case IBackCommit :case ITestChar :case ITestSet : 1000case ITestAny : {/* instructions with labels */ 1001jumptothere (compst ,i ,finallabel (code ,i ));/* optimize label */ 1002break ; 1003 } 1004case IJmp : { 1005int ft = finaltarget (code ,i ); 1006switch (code [ft ].i .code ) {/* jumping to what? */ 1007case IRet :case IFail :case IFailTwice : 1008case IEnd : {/* instructions with unconditional implicit jumps */ 1009code [i ]= code [ft ];/* jump becomes that instruction */ 1010code [i + 1 ].i .code = IEmpty ;/* 'no-op' for target position */ 1011break ; 1012 } 1013case ICommit :case IPartialCommit : 1014case IBackCommit : {/* inst. with unconditional explicit jumps */ 1015int fft = finallabel (code ,ft ); 1016code [i ]= code [ft ];/* jump becomes that instruction... */ 1017jumptothere (compst ,i ,fft );/* but must correct its offset */ 1018 gotoredo ;/* reoptimize its label */ 1019 } 1020default : { 1021jumptothere (compst ,i ,ft );/* optimize label */ 1022break ; 1023 } 1024 } 1025break ; 1026 } 1027default :break ; 1028 } 1029 } 1030assert (code [i - 1 ].i .code == IEnd ); 1031} 1032 1033 1034/* 1035** Compile a pattern. 'size' is the size of the pattern's tree, 1036** which gives a hint for the size of the final code. 1037*/ 1038Instruction * compile (lua_State * L ,Pattern * p ,uint size ) { 1039CompileState compst ; 1040compst .p = p ;compst .ncode = 0 ;compst .L = L ; 1041newcode (L ,p ,size /2u + 2 );/* set initial size */ 1042codegen (& compst ,p -> tree ,0 ,NOINST ,fullset ); 1043addinstruction (& compst ,IEnd ,0 ); 1044realloccode (L ,p ,compst .ncode );/* set final size */ 1045peephole (& compst ); 1046return p -> code ; 1047} 1048 1049 1050/* }====================================================== */ 1051