pocketpy.h 227 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019
  1. /*
  2. * Copyright (c) 2022 blueloveTH
  3. * Distributed Under The LGPLv3 License
  4. */
  5. #ifndef POCKETPY_H
  6. #define POCKETPY_H
  7. #ifdef _MSC_VER
  8. #pragma warning (disable:4267)
  9. #pragma warning (disable:4101)
  10. #define _CRT_NONSTDC_NO_DEPRECATE
  11. #endif
  12. #include <sstream>
  13. #include <regex>
  14. #include <variant>
  15. #include <stack>
  16. #include <cmath>
  17. #include <stdexcept>
  18. #include <vector>
  19. #include <string>
  20. #include <cstring>
  21. #include <chrono>
  22. #include <string_view>
  23. #include <queue>
  24. #include <iomanip>
  25. #include <map>
  26. #include <thread>
  27. #include <atomic>
  28. #include <iostream>
  29. #ifdef POCKETPY_H
  30. #define UNREACHABLE() throw std::runtime_error( "L" + std::to_string(__LINE__) + " UNREACHABLE()! This should be a bug, please report it");
  31. #else
  32. #define UNREACHABLE() throw std::runtime_error( __FILE__ + std::string(":") + std::to_string(__LINE__) + " UNREACHABLE()!");
  33. #endif
  34. #define PK_VERSION "0.4.7"
  35. namespace pkpy{
  36. template <typename T>
  37. class shared_ptr {
  38. int* counter = nullptr;
  39. #define _t() ((T*)(counter + 1))
  40. #define _inc_counter() if(counter) ++(*counter)
  41. #define _dec_counter() if(counter && --(*counter) == 0){ _t()->~T(); free(counter); }
  42. public:
  43. shared_ptr() {}
  44. shared_ptr(int* block) : counter(block) {}
  45. shared_ptr(const shared_ptr& other) : counter(other.counter) {
  46. _inc_counter();
  47. }
  48. shared_ptr(shared_ptr&& other) : counter(other.counter) {
  49. other.counter = nullptr;
  50. }
  51. ~shared_ptr() {
  52. _dec_counter();
  53. }
  54. bool operator==(const shared_ptr& other) const {
  55. return counter == other.counter;
  56. }
  57. bool operator!=(const shared_ptr& other) const {
  58. return counter != other.counter;
  59. }
  60. bool operator==(std::nullptr_t) const {
  61. return counter == nullptr;
  62. }
  63. bool operator!=(std::nullptr_t) const {
  64. return counter != nullptr;
  65. }
  66. shared_ptr& operator=(const shared_ptr& other) {
  67. if (this != &other) {
  68. _dec_counter();
  69. counter = other.counter;
  70. _inc_counter();
  71. }
  72. return *this;
  73. }
  74. shared_ptr& operator=(shared_ptr&& other) {
  75. if (this != &other) {
  76. _dec_counter();
  77. counter = other.counter;
  78. other.counter = nullptr;
  79. }
  80. return *this;
  81. }
  82. T& operator*() const {
  83. return *_t();
  84. }
  85. T* operator->() const {
  86. return _t();
  87. }
  88. T* get() const {
  89. return _t();
  90. }
  91. int use_count() const {
  92. return counter ? *counter : 0;
  93. }
  94. void reset(){
  95. _dec_counter();
  96. counter = nullptr;
  97. }
  98. };
  99. #undef _t
  100. #undef _inc_counter
  101. #undef _dec_counter
  102. template <typename T, typename U, typename... Args>
  103. shared_ptr<T> make_shared(Args&&... args) {
  104. static_assert(std::is_base_of<T, U>::value, "U must be derived from T");
  105. int* p = (int*)malloc(sizeof(int) + sizeof(U));
  106. *p = 1;
  107. new(p+1) U(std::forward<Args>(args)...);
  108. return shared_ptr<T>(p);
  109. }
  110. template <typename T, typename... Args>
  111. shared_ptr<T> make_shared(Args&&... args) {
  112. int* p = (int*)malloc(sizeof(int) + sizeof(T));
  113. *p = 1;
  114. new(p+1) T(std::forward<Args>(args)...);
  115. return shared_ptr<T>(p);
  116. }
  117. template <typename T>
  118. class unique_ptr {
  119. T* ptr;
  120. public:
  121. unique_ptr() : ptr(nullptr) {}
  122. unique_ptr(T* ptr) : ptr(ptr) {}
  123. unique_ptr(const unique_ptr& other) = delete;
  124. unique_ptr(unique_ptr&& other) : ptr(other.ptr) {
  125. other.ptr = nullptr;
  126. }
  127. ~unique_ptr() {
  128. delete ptr;
  129. }
  130. bool operator==(const unique_ptr& other) const {
  131. return ptr == other.ptr;
  132. }
  133. bool operator!=(const unique_ptr& other) const {
  134. return ptr != other.ptr;
  135. }
  136. bool operator==(std::nullptr_t) const {
  137. return ptr == nullptr;
  138. }
  139. bool operator!=(std::nullptr_t) const {
  140. return ptr != nullptr;
  141. }
  142. unique_ptr& operator=(const unique_ptr& other) = delete;
  143. unique_ptr& operator=(unique_ptr&& other) {
  144. if (this != &other) {
  145. delete ptr;
  146. ptr = other.ptr;
  147. other.ptr = nullptr;
  148. }
  149. return *this;
  150. }
  151. T& operator*() const {
  152. return *ptr;
  153. }
  154. T* operator->() const {
  155. return ptr;
  156. }
  157. T* get() const {
  158. return ptr;
  159. }
  160. void reset(){
  161. delete ptr;
  162. ptr = nullptr;
  163. }
  164. };
  165. template <typename T, typename... Args>
  166. unique_ptr<T> make_unique(Args&&... args) {
  167. return unique_ptr<T>(new T(std::forward<Args>(args)...));
  168. }
  169. };
  170. typedef std::stringstream _StrStream;
  171. class _StrMemory : public std::string {
  172. mutable std::vector<uint16_t>* _u8_index = nullptr;
  173. mutable bool hash_initialized = false;
  174. mutable size_t _hash;
  175. void utf8_lazy_init() const{
  176. if(_u8_index != nullptr) return;
  177. _u8_index = new std::vector<uint16_t>();
  178. _u8_index->reserve(size());
  179. if(size() > 65535) throw std::runtime_error("String has more than 65535 bytes.");
  180. for(uint16_t i = 0; i < size(); i++){
  181. // https://stackoverflow.com/questions/3911536/utf-8-unicode-whats-with-0xc0-and-0x80
  182. if((at(i) & 0xC0) != 0x80)
  183. _u8_index->push_back(i);
  184. }
  185. }
  186. public:
  187. size_t hash() const{
  188. if(!hash_initialized){
  189. _hash = std::hash<std::string>()(*this);
  190. hash_initialized = true;
  191. }
  192. return _hash;
  193. }
  194. int u8_length() const {
  195. utf8_lazy_init();
  196. return _u8_index->size();
  197. }
  198. std::string u8_getitem(int i) const{
  199. return u8_substr(i, i+1);
  200. }
  201. std::string u8_substr(int start, int end) const{
  202. utf8_lazy_init();
  203. if(start >= end) return std::string();
  204. int c_end = end >= _u8_index->size() ? size() : _u8_index->at(end);
  205. return substr(_u8_index->at(start), c_end - _u8_index->at(start));
  206. }
  207. _StrMemory(const std::string& s) : std::string(s) {}
  208. _StrMemory(std::string&& s) : std::string(std::move(s)) {}
  209. ~_StrMemory(){
  210. if(_u8_index != nullptr) delete _u8_index;
  211. }
  212. };
  213. std::map<std::string, pkpy::shared_ptr<_StrMemory>, std::less<>> _strIntern;
  214. class _StrLiteral : public std::string_view {
  215. public:
  216. constexpr _StrLiteral(const char* str, size_t len) : std::string_view(str, len) {}
  217. };
  218. inline constexpr _StrLiteral operator "" _c(const char* str, size_t len){
  219. return _StrLiteral(str, len);
  220. }
  221. class _Str {
  222. private:
  223. pkpy::shared_ptr<_StrMemory> _s;
  224. bool interned = false;
  225. public:
  226. _Str(const _StrLiteral& s){
  227. construct(s);
  228. intern();
  229. }
  230. _Str(const char* s){
  231. construct(s);
  232. }
  233. _Str(const char* s, size_t len){
  234. construct(std::string_view(s, len));
  235. }
  236. _Str(){
  237. construct("");
  238. }
  239. _Str(const std::string& s){
  240. construct(s);
  241. }
  242. _Str(const _Str& s) : _s(s._s), interned(s.interned) {}
  243. // for move constructor, we do not check if the string is interned!!
  244. _Str(std::string&& s){
  245. this->_s = pkpy::make_shared<_StrMemory>(std::move(s));
  246. }
  247. void construct(const std::string_view& sv){
  248. auto it = _strIntern.find(sv);
  249. if(it != _strIntern.end()){
  250. this->_s = it->second;
  251. interned = true;
  252. }else{
  253. this->_s = pkpy::make_shared<_StrMemory>(std::string(sv));
  254. }
  255. }
  256. // force the string to be interned
  257. void intern(){
  258. if(interned) return;
  259. auto it = _strIntern.find(*this->_s);
  260. if(it == _strIntern.end()) _strIntern[*this->_s] = this->_s;
  261. else this->_s = it->second;
  262. interned = true;
  263. }
  264. inline int u8_length() const {
  265. return this->_s->u8_length();
  266. }
  267. inline _Str u8_getitem(int i) const{
  268. return _Str(this->_s->u8_getitem(i));
  269. }
  270. inline _Str u8_substr(int start, int end) const{
  271. return _Str(this->_s->u8_substr(start, end));
  272. }
  273. inline size_t hash() const{
  274. return _s->hash();
  275. }
  276. inline int size() const {
  277. return _s->size();
  278. }
  279. inline bool empty() const {
  280. return _s->empty();
  281. }
  282. bool operator==(const _Str& other) const {
  283. if(interned && other.interned) return _s == other._s;
  284. return *_s == *other._s;
  285. }
  286. bool operator!=(const _Str& other) const {
  287. if(interned && other.interned) return _s != other._s;
  288. return *_s != *other._s;
  289. }
  290. bool operator<(const _Str& other) const {
  291. return *_s < *other._s;
  292. }
  293. bool operator>(const _Str& other) const {
  294. return *_s > *other._s;
  295. }
  296. char operator[](int i) const {
  297. return _s->at(i);
  298. }
  299. friend std::ostream& operator<<(std::ostream& os, const _Str& s) {
  300. os << *s._s;
  301. return os;
  302. }
  303. _Str operator+(const _Str& other) const {
  304. return _Str(*_s + *other._s);
  305. }
  306. _Str operator+(const char* other) const {
  307. return _Str(*_s + other);
  308. }
  309. _Str operator+(const std::string& other) const {
  310. return _Str(*_s + other);
  311. }
  312. friend _Str operator+(const char* other, const _Str& s){
  313. return _Str(other + *s._s);
  314. }
  315. friend _Str operator+(const std::string& other, const _Str& s){
  316. return _Str(other + *s._s);
  317. }
  318. const std::string& str() const {
  319. return *_s;
  320. }
  321. const char* c_str() const {
  322. return _s->c_str();
  323. }
  324. static const std::size_t npos = std::string::npos;
  325. _Str __lstrip() const {
  326. std::string copy(*_s);
  327. copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), [](char c) {
  328. return !std::isspace(c);
  329. }));
  330. return _Str(copy);
  331. }
  332. _Str __escape(bool single_quote) const {
  333. _StrStream ss;
  334. ss << (single_quote ? '\'' : '"');
  335. for (auto c = _s->cbegin(); c != _s->cend(); c++) {
  336. switch (*c) {
  337. case '"':
  338. if(!single_quote) ss << '\\';
  339. ss << '"';
  340. break;
  341. case '\'':
  342. if(single_quote) ss << '\\';
  343. ss << '\'';
  344. break;
  345. case '\\': ss << '\\' << '\\'; break;
  346. case '\n': ss << "\\n"; break;
  347. case '\r': ss << "\\r"; break;
  348. case '\t': ss << "\\t"; break;
  349. default:
  350. if ('\x00' <= *c && *c <= '\x1f') {
  351. ss << "\\u"
  352. << std::hex << std::setw(4) << std::setfill('0') << static_cast<int>(*c);
  353. } else {
  354. ss << *c;
  355. }
  356. }
  357. }
  358. ss << (single_quote ? '\'' : '"');
  359. return ss.str();
  360. }
  361. };
  362. namespace std {
  363. template<>
  364. struct hash<_Str> {
  365. std::size_t operator()(const _Str& s) const {
  366. return s.hash();
  367. }
  368. };
  369. }
  370. // const _Str& __class__ = _Str("__class__"_c);
  371. const _Str& __base__ = _Str("__base__"_c);
  372. const _Str& __new__ = _Str("__new__"_c);
  373. const _Str& __iter__ = _Str("__iter__"_c);
  374. const _Str& __str__ = _Str("__str__"_c);
  375. const _Str& __repr__ = _Str("__repr__"_c);
  376. const _Str& __module__ = _Str("__module__"_c);
  377. const _Str& __getitem__ = _Str("__getitem__"_c);
  378. const _Str& __setitem__ = _Str("__setitem__"_c);
  379. const _Str& __delitem__ = _Str("__delitem__"_c);
  380. const _Str& __contains__ = _Str("__contains__"_c);
  381. const _Str& __init__ = _Str("__init__"_c);
  382. const _Str& __json__ = _Str("__json__"_c);
  383. const _Str& __name__ = _Str("__name__"_c);
  384. const _Str& __len__ = _Str("__len__"_c);
  385. const _Str CMP_SPECIAL_METHODS[] = {
  386. "__lt__"_c, "__le__"_c, "__eq__"_c, "__ne__"_c, "__gt__"_c, "__ge__"_c
  387. }; // __ne__ should not be used
  388. const _Str BINARY_SPECIAL_METHODS[] = {
  389. "__add__"_c, "__sub__"_c, "__mul__"_c, "__truediv__"_c, "__floordiv__"_c, "__mod__"_c, "__pow__"_c
  390. };
  391. const _Str BITWISE_SPECIAL_METHODS[] = {
  392. "__lshift__"_c, "__rshift__"_c, "__and__"_c, "__or__"_c, "__xor__"_c
  393. };
  394. const uint32_t __LoRangeA[] = {170,186,443,448,660,1488,1519,1568,1601,1646,1649,1749,1774,1786,1791,1808,1810,1869,1969,1994,2048,2112,2144,2208,2230,2308,2365,2384,2392,2418,2437,2447,2451,2474,2482,2486,2493,2510,2524,2527,2544,2556,2565,2575,2579,2602,2610,2613,2616,2649,2654,2674,2693,2703,2707,2730,2738,2741,2749,2768,2784,2809,2821,2831,2835,2858,2866,2869,2877,2908,2911,2929,2947,2949,2958,2962,2969,2972,2974,2979,2984,2990,3024,3077,3086,3090,3114,3133,3160,3168,3200,3205,3214,3218,3242,3253,3261,3294,3296,3313,3333,3342,3346,3389,3406,3412,3423,3450,3461,3482,3507,3517,3520,3585,3634,3648,3713,3716,3718,3724,3749,3751,3762,3773,3776,3804,3840,3904,3913,3976,4096,4159,4176,4186,4193,4197,4206,4213,4238,4352,4682,4688,4696,4698,4704,4746,4752,4786,4792,4800,4802,4808,4824,4882,4888,4992,5121,5743,5761,5792,5873,5888,5902,5920,5952,5984,5998,6016,6108,6176,6212,6272,6279,6314,6320,6400,6480,6512,6528,6576,6656,6688,6917,6981,7043,7086,7098,7168,7245,7258,7401,7406,7413,7418,8501,11568,11648,11680,11688,11696,11704,11712,11720,11728,11736,12294,12348,12353,12447,12449,12543,12549,12593,12704,12784,13312,19968,40960,40982,42192,42240,42512,42538,42606,42656,42895,42999,43003,43011,43015,43020,43072,43138,43250,43259,43261,43274,43312,43360,43396,43488,43495,43514,43520,43584,43588,43616,43633,43642,43646,43697,43701,43705,43712,43714,43739,43744,43762,43777,43785,43793,43808,43816,43968,44032,55216,55243,63744,64112,64285,64287,64298,64312,64318,64320,64323,64326,64467,64848,64914,65008,65136,65142,65382,65393,65440,65474,65482,65490,65498,65536,65549,65576,65596,65599,65616,65664,66176,66208,66304,66349,66370,66384,66432,66464,66504,66640,66816,66864,67072,67392,67424,67584,67592,67594,67639,67644,67647,67680,67712,67808,67828,67840,67872,67968,68030,68096,68112,68117,68121,68192,68224,68288,68297,68352,68416,68448,68480,68608,68864,69376,69415,69424,69600,69635,69763,69840,69891,69956,69968,70006,70019,70081,70106,70108,70144,70163,70272,70280,70282,70287,70303,70320,70405,70415,70419,70442,70450,70453,70461,70480,70493,70656,70727,70751,70784,70852,70855,71040,71128,71168,71236,71296,71352,71424,71680,71935,72096,72106,72161,72163,72192,72203,72250,72272,72284,72349,72384,72704,72714,72768,72818,72960,72968,72971,73030,73056,73063,73066,73112,73440,73728,74880,77824,82944,92160,92736,92880,92928,93027,93053,93952,94032,94208,100352,110592,110928,110948,110960,113664,113776,113792,113808,123136,123214,123584,124928,126464,126469,126497,126500,126503,126505,126516,126521,126523,126530,126535,126537,126539,126541,126545,126548,126551,126553,126555,126557,126559,126561,126564,126567,126572,126580,126585,126590,126592,126603,126625,126629,126635,131072,173824,177984,178208,183984,194560};
  395. const uint32_t __LoRangeB[] = {170,186,443,451,660,1514,1522,1599,1610,1647,1747,1749,1775,1788,1791,1808,1839,1957,1969,2026,2069,2136,2154,2228,2237,2361,2365,2384,2401,2432,2444,2448,2472,2480,2482,2489,2493,2510,2525,2529,2545,2556,2570,2576,2600,2608,2611,2614,2617,2652,2654,2676,2701,2705,2728,2736,2739,2745,2749,2768,2785,2809,2828,2832,2856,2864,2867,2873,2877,2909,2913,2929,2947,2954,2960,2965,2970,2972,2975,2980,2986,3001,3024,3084,3088,3112,3129,3133,3162,3169,3200,3212,3216,3240,3251,3257,3261,3294,3297,3314,3340,3344,3386,3389,3406,3414,3425,3455,3478,3505,3515,3517,3526,3632,3635,3653,3714,3716,3722,3747,3749,3760,3763,3773,3780,3807,3840,3911,3948,3980,4138,4159,4181,4189,4193,4198,4208,4225,4238,4680,4685,4694,4696,4701,4744,4749,4784,4789,4798,4800,4805,4822,4880,4885,4954,5007,5740,5759,5786,5866,5880,5900,5905,5937,5969,5996,6000,6067,6108,6210,6264,6276,6312,6314,6389,6430,6509,6516,6571,6601,6678,6740,6963,6987,7072,7087,7141,7203,7247,7287,7404,7411,7414,7418,8504,11623,11670,11686,11694,11702,11710,11718,11726,11734,11742,12294,12348,12438,12447,12538,12543,12591,12686,12730,12799,19893,40943,40980,42124,42231,42507,42527,42539,42606,42725,42895,42999,43009,43013,43018,43042,43123,43187,43255,43259,43262,43301,43334,43388,43442,43492,43503,43518,43560,43586,43595,43631,43638,43642,43695,43697,43702,43709,43712,43714,43740,43754,43762,43782,43790,43798,43814,43822,44002,55203,55238,55291,64109,64217,64285,64296,64310,64316,64318,64321,64324,64433,64829,64911,64967,65019,65140,65276,65391,65437,65470,65479,65487,65495,65500,65547,65574,65594,65597,65613,65629,65786,66204,66256,66335,66368,66377,66421,66461,66499,66511,66717,66855,66915,67382,67413,67431,67589,67592,67637,67640,67644,67669,67702,67742,67826,67829,67861,67897,68023,68031,68096,68115,68119,68149,68220,68252,68295,68324,68405,68437,68466,68497,68680,68899,69404,69415,69445,69622,69687,69807,69864,69926,69956,70002,70006,70066,70084,70106,70108,70161,70187,70278,70280,70285,70301,70312,70366,70412,70416,70440,70448,70451,70457,70461,70480,70497,70708,70730,70751,70831,70853,70855,71086,71131,71215,71236,71338,71352,71450,71723,71935,72103,72144,72161,72163,72192,72242,72250,72272,72329,72349,72440,72712,72750,72768,72847,72966,72969,73008,73030,73061,73064,73097,73112,73458,74649,75075,78894,83526,92728,92766,92909,92975,93047,93071,94026,94032,100343,101106,110878,110930,110951,111355,113770,113788,113800,113817,123180,123214,123627,125124,126467,126495,126498,126500,126503,126514,126519,126521,126523,126530,126535,126537,126539,126543,126546,126548,126551,126553,126555,126557,126559,126562,126564,126570,126578,126583,126588,126590,126601,126619,126627,126633,126651,173782,177972,178205,183969,191456,195101};
  396. bool __isLoChar(uint32_t c) {
  397. auto index = std::lower_bound(__LoRangeA, __LoRangeA + 476, c) - __LoRangeA;
  398. if(c == __LoRangeA[index]) return true;
  399. index -= 1;
  400. if(index < 0) return false;
  401. return c >= __LoRangeA[index] && c <= __LoRangeB[index];
  402. }
  403. // emhash8::HashMap for C++11/14/17
  404. // version 1.6.3
  405. //
  406. // Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  407. // SPDX-License-Identifier: MIT
  408. // Copyright (c) 2019-2022 Huang Yuanbing & bailuzhou AT 163.com
  409. //
  410. // Permission is hereby granted, free of charge, to any person obtaining a copy
  411. // of this software and associated documentation files (the "Software"), to deal
  412. // in the Software without restriction, including without limitation the rights
  413. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  414. // copies of the Software, and to permit persons to whom the Software is
  415. // furnished to do so, subject to the following conditions:
  416. //
  417. // The above copyright notice and this permission notice shall be included in all
  418. // copies or substantial portions of the Software.
  419. //
  420. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  421. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  422. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  423. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  424. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  425. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  426. // SOFTWARE
  427. #include <cstring>
  428. #include <string>
  429. #include <cstdlib>
  430. #include <type_traits>
  431. #include <cassert>
  432. #include <utility>
  433. #include <cstdint>
  434. #include <functional>
  435. #include <iterator>
  436. #include <algorithm>
  437. #ifdef EMH_KEY
  438. #undef EMH_KEY
  439. #undef EMH_VAL
  440. #undef EMH_KV
  441. #undef EMH_BUCKET
  442. #undef EMH_NEW
  443. #undef EMH_EMPTY
  444. #undef EMH_PREVET
  445. #undef EMH_LIKELY
  446. #undef EMH_UNLIKELY
  447. #endif
  448. // likely/unlikely
  449. #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__)
  450. # define EMH_LIKELY(condition) __builtin_expect(condition, 1)
  451. # define EMH_UNLIKELY(condition) __builtin_expect(condition, 0)
  452. #else
  453. # define EMH_LIKELY(condition) (condition)
  454. # define EMH_UNLIKELY(condition) (condition)
  455. #endif
  456. #define EMH_KEY(p, n) p[n].first
  457. #define EMH_VAL(p, n) p[n].second
  458. #define EMH_KV(p, n) p[n]
  459. #define EMH_INDEX(i, n) i[n]
  460. #define EMH_BUCKET(i, n) i[n].bucket
  461. #define EMH_HSLOT(i, n) i[n].slot
  462. #define EMH_SLOT(i, n) (i[n].slot & _mask)
  463. #define EMH_PREVET(i, n) i[n].slot
  464. #define EMH_KEYMASK(key, mask) ((size_type)(key) & ~mask)
  465. #define EMH_EQHASH(n, key_hash) (EMH_KEYMASK(key_hash, _mask) == (_index[n].slot & ~_mask))
  466. #define EMH_NEW(key, val, bucket, key_hash) \
  467. new(_pairs + _num_filled) value_type(key, val); \
  468. _etail = bucket; \
  469. _index[bucket] = {bucket, _num_filled++ | EMH_KEYMASK(key_hash, _mask)}
  470. #define EMH_EMPTY(i, n) (0 > (int)i[n].bucket)
  471. namespace emhash8 {
  472. #ifndef EMH_DEFAULT_LOAD_FACTOR
  473. constexpr static float EMH_DEFAULT_LOAD_FACTOR = 0.80f;
  474. constexpr static float EMH_MIN_LOAD_FACTOR = 0.25f; //< 0.5
  475. #endif
  476. #if EMH_CACHE_LINE_SIZE < 32
  477. constexpr static uint32_t EMH_CACHE_LINE_SIZE = 64;
  478. #endif
  479. template <typename KeyT, typename ValueT, typename HashT = std::hash<KeyT>, typename EqT = std::equal_to<KeyT>>
  480. class HashMap
  481. {
  482. public:
  483. using htype = HashMap<KeyT, ValueT, HashT, EqT>;
  484. using value_type = std::pair<KeyT, ValueT>;
  485. using key_type = KeyT;
  486. using mapped_type = ValueT;
  487. #ifdef EMH_SMALL_TYPE
  488. using size_type = uint16_t;
  489. #elif EMH_SIZE_TYPE == 0
  490. using size_type = uint32_t;
  491. #else
  492. using size_type = size_t;
  493. #endif
  494. using hasher = HashT;
  495. using key_equal = EqT;
  496. constexpr static size_type INACTIVE = 0-1u;
  497. //constexpr uint32_t END = 0-0x1u;
  498. constexpr static size_type EAD = 2;
  499. struct Index
  500. {
  501. size_type bucket;
  502. size_type slot;
  503. };
  504. class const_iterator;
  505. class iterator
  506. {
  507. public:
  508. using iterator_category = std::bidirectional_iterator_tag;
  509. using difference_type = std::ptrdiff_t;
  510. using value_type = typename htype::value_type;
  511. using pointer = value_type*;
  512. using const_pointer = const value_type* ;
  513. using reference = value_type&;
  514. using const_reference = const value_type&;
  515. iterator() : kv_(nullptr) {}
  516. iterator(const_iterator& cit) {
  517. kv_ = cit.kv_;
  518. }
  519. iterator(const htype* hash_map, size_type bucket) {
  520. kv_ = hash_map->_pairs + (int)bucket;
  521. }
  522. iterator& operator++()
  523. {
  524. kv_ ++;
  525. return *this;
  526. }
  527. iterator operator++(int)
  528. {
  529. auto cur = *this; kv_ ++;
  530. return cur;
  531. }
  532. iterator& operator--()
  533. {
  534. kv_ --;
  535. return *this;
  536. }
  537. iterator operator--(int)
  538. {
  539. auto cur = *this; kv_ --;
  540. return cur;
  541. }
  542. reference operator*() const { return *kv_; }
  543. pointer operator->() const { return kv_; }
  544. bool operator == (const iterator& rhs) const { return kv_ == rhs.kv_; }
  545. bool operator != (const iterator& rhs) const { return kv_ != rhs.kv_; }
  546. bool operator == (const const_iterator& rhs) const { return kv_ == rhs.kv_; }
  547. bool operator != (const const_iterator& rhs) const { return kv_ != rhs.kv_; }
  548. public:
  549. value_type* kv_;
  550. };
  551. class const_iterator
  552. {
  553. public:
  554. using iterator_category = std::bidirectional_iterator_tag;
  555. using value_type = typename htype::value_type;
  556. using difference_type = std::ptrdiff_t;
  557. using pointer = value_type*;
  558. using const_pointer = const value_type*;
  559. using reference = value_type&;
  560. using const_reference = const value_type&;
  561. const_iterator(const iterator& it) {
  562. kv_ = it.kv_;
  563. }
  564. const_iterator (const htype* hash_map, size_type bucket) {
  565. kv_ = hash_map->_pairs + (int)bucket;
  566. }
  567. const_iterator& operator++()
  568. {
  569. kv_ ++;
  570. return *this;
  571. }
  572. const_iterator operator++(int)
  573. {
  574. auto cur = *this; kv_ ++;
  575. return cur;
  576. }
  577. const_iterator& operator--()
  578. {
  579. kv_ --;
  580. return *this;
  581. }
  582. const_iterator operator--(int)
  583. {
  584. auto cur = *this; kv_ --;
  585. return cur;
  586. }
  587. const_reference operator*() const { return *kv_; }
  588. const_pointer operator->() const { return kv_; }
  589. bool operator == (const iterator& rhs) const { return kv_ == rhs.kv_; }
  590. bool operator != (const iterator& rhs) const { return kv_ != rhs.kv_; }
  591. bool operator == (const const_iterator& rhs) const { return kv_ == rhs.kv_; }
  592. bool operator != (const const_iterator& rhs) const { return kv_ != rhs.kv_; }
  593. public:
  594. const value_type* kv_;
  595. };
  596. void init(size_type bucket, float mlf = EMH_DEFAULT_LOAD_FACTOR)
  597. {
  598. _pairs = nullptr;
  599. _index = nullptr;
  600. _mask = _num_buckets = 0;
  601. _num_filled = 0;
  602. max_load_factor(mlf);
  603. rehash(bucket);
  604. }
  605. HashMap(size_type bucket = 2, float mlf = EMH_DEFAULT_LOAD_FACTOR)
  606. {
  607. init(bucket, mlf);
  608. }
  609. HashMap(const HashMap& rhs)
  610. {
  611. if (rhs.load_factor() > EMH_MIN_LOAD_FACTOR) {
  612. _pairs = alloc_bucket((size_type)(rhs._num_buckets * rhs.max_load_factor()) + 4);
  613. _index = alloc_index(rhs._num_buckets);
  614. clone(rhs);
  615. } else {
  616. init(rhs._num_filled + 2, EMH_DEFAULT_LOAD_FACTOR);
  617. for (auto it = rhs.begin(); it != rhs.end(); ++it)
  618. insert_unique(it->first, it->second);
  619. }
  620. }
  621. HashMap(HashMap&& rhs) noexcept
  622. {
  623. init(0);
  624. *this = std::move(rhs);
  625. }
  626. HashMap(std::initializer_list<value_type> ilist)
  627. {
  628. init((size_type)ilist.size());
  629. for (auto it = ilist.begin(); it != ilist.end(); ++it)
  630. do_insert(*it);
  631. }
  632. template<class InputIt>
  633. HashMap(InputIt first, InputIt last, size_type bucket_count=4)
  634. {
  635. init(std::distance(first, last) + bucket_count);
  636. for (; first != last; ++first)
  637. emplace(*first);
  638. }
  639. HashMap& operator=(const HashMap& rhs)
  640. {
  641. if (this == &rhs)
  642. return *this;
  643. if (rhs.load_factor() < EMH_MIN_LOAD_FACTOR) {
  644. clear(); free(_pairs); _pairs = nullptr;
  645. rehash(rhs._num_filled + 2);
  646. for (auto it = rhs.begin(); it != rhs.end(); ++it)
  647. insert_unique(it->first, it->second);
  648. return *this;
  649. }
  650. clearkv();
  651. if (_num_buckets != rhs._num_buckets) {
  652. free(_pairs); free(_index);
  653. _index = alloc_index(rhs._num_buckets);
  654. _pairs = alloc_bucket((size_type)(rhs._num_buckets * rhs.max_load_factor()) + 4);
  655. }
  656. clone(rhs);
  657. return *this;
  658. }
  659. HashMap& operator=(HashMap&& rhs) noexcept
  660. {
  661. if (this != &rhs) {
  662. swap(rhs);
  663. rhs.clear();
  664. }
  665. return *this;
  666. }
  667. template<typename Con>
  668. bool operator == (const Con& rhs) const
  669. {
  670. if (size() != rhs.size())
  671. return false;
  672. for (auto it = begin(), last = end(); it != last; ++it) {
  673. auto oi = rhs.find(it->first);
  674. if (oi == rhs.end() || it->second != oi->second)
  675. return false;
  676. }
  677. return true;
  678. }
  679. template<typename Con>
  680. bool operator != (const Con& rhs) const { return !(*this == rhs); }
  681. ~HashMap() noexcept
  682. {
  683. clearkv();
  684. free(_pairs);
  685. free(_index);
  686. }
  687. void clone(const HashMap& rhs)
  688. {
  689. _hasher = rhs._hasher;
  690. // _eq = rhs._eq;
  691. _num_buckets = rhs._num_buckets;
  692. _num_filled = rhs._num_filled;
  693. _mlf = rhs._mlf;
  694. _last = rhs._last;
  695. _mask = rhs._mask;
  696. #if EMH_HIGH_LOAD
  697. _ehead = rhs._ehead;
  698. #endif
  699. _etail = rhs._etail;
  700. auto opairs = rhs._pairs;
  701. memcpy((char*)_index, (char*)rhs._index, (_num_buckets + EAD) * sizeof(Index));
  702. if (is_copy_trivially()) {
  703. if (opairs)
  704. memcpy((char*)_pairs, (char*)opairs, _num_filled * sizeof(value_type));
  705. } else {
  706. for (size_type slot = 0; slot < _num_filled; slot++)
  707. new(_pairs + slot) value_type(opairs[slot]);
  708. }
  709. }
  710. void swap(HashMap& rhs)
  711. {
  712. // std::swap(_eq, rhs._eq);
  713. std::swap(_hasher, rhs._hasher);
  714. std::swap(_pairs, rhs._pairs);
  715. std::swap(_index, rhs._index);
  716. std::swap(_num_buckets, rhs._num_buckets);
  717. std::swap(_num_filled, rhs._num_filled);
  718. std::swap(_mask, rhs._mask);
  719. std::swap(_mlf, rhs._mlf);
  720. std::swap(_last, rhs._last);
  721. #if EMH_HIGH_LOAD
  722. std::swap(_ehead, rhs._ehead);
  723. #endif
  724. std::swap(_etail, rhs._etail);
  725. }
  726. // -------------------------------------------------------------
  727. inline iterator first() const { return {this, 0}; }
  728. inline iterator last() const { return {this, _num_filled - 1}; }
  729. inline iterator begin() { return first(); }
  730. inline const_iterator cbegin() const { return first(); }
  731. inline const_iterator begin() const { return first(); }
  732. inline iterator end() { return {this, _num_filled}; }
  733. inline const_iterator cend() const { return {this, _num_filled}; }
  734. inline const_iterator end() const { return cend(); }
  735. inline const value_type* values() const { return _pairs; }
  736. inline const Index* index() const { return _index; }
  737. inline size_type size() const { return _num_filled; }
  738. inline bool empty() const { return _num_filled == 0; }
  739. inline size_type bucket_count() const { return _num_buckets; }
  740. /// Returns average number of elements per bucket.
  741. inline float load_factor() const { return static_cast<float>(_num_filled) / (_mask + 1); }
  742. inline HashT& hash_function() const { return _hasher; }
  743. inline EqT& key_eq() const { return _eq; }
  744. void max_load_factor(float mlf)
  745. {
  746. if (mlf < 0.991 && mlf > EMH_MIN_LOAD_FACTOR) {
  747. _mlf = (uint32_t)((1 << 27) / mlf);
  748. if (_num_buckets > 0) rehash(_num_buckets);
  749. }
  750. }
  751. inline constexpr float max_load_factor() const { return (1 << 27) / (float)_mlf; }
  752. inline constexpr size_type max_size() const { return (1ull << (sizeof(size_type) * 8 - 1)); }
  753. inline constexpr size_type max_bucket_count() const { return max_size(); }
  754. #if EMH_STATIS
  755. //Returns the bucket number where the element with key k is located.
  756. size_type bucket(const KeyT& key) const
  757. {
  758. const auto bucket = hash_bucket(key);
  759. const auto next_bucket = EMH_BUCKET(_index, bucket);
  760. if ((int)next_bucket < 0)
  761. return 0;
  762. else if (bucket == next_bucket)
  763. return bucket + 1;
  764. return hash_main(bucket) + 1;
  765. }
  766. //Returns the number of elements in bucket n.
  767. size_type bucket_size(const size_type bucket) const
  768. {
  769. auto next_bucket = EMH_BUCKET(_index, bucket);
  770. if ((int)next_bucket < 0)
  771. return 0;
  772. next_bucket = hash_main(bucket);
  773. size_type ibucket_size = 1;
  774. //iterator each item in current main bucket
  775. while (true) {
  776. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  777. if (nbucket == next_bucket) {
  778. break;
  779. }
  780. ibucket_size ++;
  781. next_bucket = nbucket;
  782. }
  783. return ibucket_size;
  784. }
  785. size_type get_main_bucket(const size_type bucket) const
  786. {
  787. auto next_bucket = EMH_BUCKET(_index, bucket);
  788. if ((int)next_bucket < 0)
  789. return INACTIVE;
  790. return hash_main(bucket);
  791. }
  792. size_type get_diss(size_type bucket, size_type next_bucket, const size_type slots) const
  793. {
  794. auto pbucket = reinterpret_cast<uint64_t>(&_pairs[bucket]);
  795. auto pnext = reinterpret_cast<uint64_t>(&_pairs[next_bucket]);
  796. if (pbucket / EMH_CACHE_LINE_SIZE == pnext / EMH_CACHE_LINE_SIZE)
  797. return 0;
  798. size_type diff = pbucket > pnext ? (pbucket - pnext) : (pnext - pbucket);
  799. if (diff / EMH_CACHE_LINE_SIZE < slots - 1)
  800. return diff / EMH_CACHE_LINE_SIZE + 1;
  801. return slots - 1;
  802. }
  803. int get_bucket_info(const size_type bucket, size_type steps[], const size_type slots) const
  804. {
  805. auto next_bucket = EMH_BUCKET(_index, bucket);
  806. if ((int)next_bucket < 0)
  807. return -1;
  808. const auto main_bucket = hash_main(bucket);
  809. if (next_bucket == main_bucket)
  810. return 1;
  811. else if (main_bucket != bucket)
  812. return 0;
  813. steps[get_diss(bucket, next_bucket, slots)] ++;
  814. size_type ibucket_size = 2;
  815. //find a empty and linked it to tail
  816. while (true) {
  817. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  818. if (nbucket == next_bucket)
  819. break;
  820. steps[get_diss(nbucket, next_bucket, slots)] ++;
  821. ibucket_size ++;
  822. next_bucket = nbucket;
  823. }
  824. return (int)ibucket_size;
  825. }
  826. void dump_statics() const
  827. {
  828. const size_type slots = 128;
  829. size_type buckets[slots + 1] = {0};
  830. size_type steps[slots + 1] = {0};
  831. for (size_type bucket = 0; bucket < _num_buckets; ++bucket) {
  832. auto bsize = get_bucket_info(bucket, steps, slots);
  833. if (bsize > 0)
  834. buckets[bsize] ++;
  835. }
  836. size_type sumb = 0, collision = 0, sumc = 0, finds = 0, sumn = 0;
  837. puts("============== buckets size ration =========");
  838. for (size_type i = 0; i < sizeof(buckets) / sizeof(buckets[0]); i++) {
  839. const auto bucketsi = buckets[i];
  840. if (bucketsi == 0)
  841. continue;
  842. sumb += bucketsi;
  843. sumn += bucketsi * i;
  844. collision += bucketsi * (i - 1);
  845. finds += bucketsi * i * (i + 1) / 2;
  846. printf(" %2u %8u %2.2lf| %.2lf\n", i, bucketsi, bucketsi * 100.0 * i / _num_filled, sumn * 100.0 / _num_filled);
  847. }
  848. puts("========== collision miss ration ===========");
  849. for (size_type i = 0; i < sizeof(steps) / sizeof(steps[0]); i++) {
  850. sumc += steps[i];
  851. if (steps[i] <= 2)
  852. continue;
  853. printf(" %2u %8u %.2lf %.2lf\n", i, steps[i], steps[i] * 100.0 / collision, sumc * 100.0 / collision);
  854. }
  855. if (sumb == 0) return;
  856. printf(" _num_filled/bucket_size/packed collision/cache_miss/hit_find = %u/%.2lf/%zd/ %.2lf%%/%.2lf%%/%.2lf\n",
  857. _num_filled, _num_filled * 1.0 / sumb, sizeof(value_type), (collision * 100.0 / _num_filled), (collision - steps[0]) * 100.0 / _num_filled, finds * 1.0 / _num_filled);
  858. assert(sumn == _num_filled);
  859. assert(sumc == collision);
  860. puts("============== buckets size end =============");
  861. }
  862. #endif
  863. // ------------------------------------------------------------
  864. template<typename K=KeyT>
  865. inline iterator find(const K& key) noexcept
  866. {
  867. return {this, find_filled_slot(key)};
  868. }
  869. template<typename K=KeyT>
  870. inline const_iterator find(const K& key) const noexcept
  871. {
  872. return {this, find_filled_slot(key)};
  873. }
  874. template<typename K=KeyT>
  875. ValueT& at(const K& key)
  876. {
  877. const auto slot = find_filled_slot(key);
  878. //throw
  879. return EMH_VAL(_pairs, slot);
  880. }
  881. template<typename K=KeyT>
  882. const ValueT& at(const K& key) const
  883. {
  884. const auto slot = find_filled_slot(key);
  885. //throw
  886. return EMH_VAL(_pairs, slot);
  887. }
  888. template<typename K=KeyT>
  889. inline bool contains(const K& key) const noexcept
  890. {
  891. return find_filled_slot(key) != _num_filled;
  892. }
  893. template<typename K=KeyT>
  894. inline size_type count(const K& key) const noexcept
  895. {
  896. return find_filled_slot(key) == _num_filled ? 0 : 1;
  897. //return find_sorted_bucket(key) == END ? 0 : 1;
  898. //return find_hash_bucket(key) == END ? 0 : 1;
  899. }
  900. template<typename K=KeyT>
  901. std::pair<iterator, iterator> equal_range(const K& key)
  902. {
  903. const auto found = find(key);
  904. if (found.second == _num_filled)
  905. return { found, found };
  906. else
  907. return { found, std::next(found) };
  908. }
  909. void merge(HashMap& rhs)
  910. {
  911. if (empty()) {
  912. *this = std::move(rhs);
  913. return;
  914. }
  915. for (auto rit = rhs.begin(); rit != rhs.end(); ) {
  916. auto fit = find(rit->first);
  917. if (fit == end()) {
  918. insert_unique(rit->first, std::move(rit->second));
  919. rit = rhs.erase(rit);
  920. } else {
  921. ++rit;
  922. }
  923. }
  924. }
  925. /// Returns the matching ValueT or nullptr if k isn't found.
  926. bool try_get(const KeyT& key, ValueT& val) const noexcept
  927. {
  928. const auto slot = find_filled_slot(key);
  929. const auto found = slot != _num_filled;
  930. if (found) {
  931. val = EMH_VAL(_pairs, slot);
  932. }
  933. return found;
  934. }
  935. /// Returns the matching ValueT or nullptr if k isn't found.
  936. ValueT* try_get(const KeyT& key) noexcept
  937. {
  938. const auto slot = find_filled_slot(key);
  939. return slot != _num_filled ? &EMH_VAL(_pairs, slot) : nullptr;
  940. }
  941. /// Const version of the above
  942. ValueT* try_get(const KeyT& key) const noexcept
  943. {
  944. const auto slot = find_filled_slot(key);
  945. return slot != _num_filled ? &EMH_VAL(_pairs, slot) : nullptr;
  946. }
  947. /// set value if key exist
  948. bool try_set(const KeyT& key, const ValueT& val) noexcept
  949. {
  950. const auto slot = find_filled_slot(key);
  951. if (slot == _num_filled)
  952. return false;
  953. EMH_VAL(_pairs, slot) = val;
  954. return true;
  955. }
  956. /// set value if key exist
  957. bool try_set(const KeyT& key, ValueT&& val) noexcept
  958. {
  959. const auto slot = find_filled_slot(key);
  960. if (slot == _num_filled)
  961. return false;
  962. EMH_VAL(_pairs, slot) = std::move(val);
  963. return true;
  964. }
  965. /// Convenience function.
  966. ValueT get_or_return_default(const KeyT& key) const noexcept
  967. {
  968. const auto slot = find_filled_slot(key);
  969. return slot == _num_filled ? ValueT() : EMH_VAL(_pairs, slot);
  970. }
  971. // -----------------------------------------------------
  972. std::pair<iterator, bool> do_insert(const value_type& value) noexcept
  973. {
  974. const auto key_hash = hash_key(value.first);
  975. const auto bucket = find_or_allocate(value.first, key_hash);
  976. const auto bempty = EMH_EMPTY(_index, bucket);
  977. if (bempty) {
  978. EMH_NEW(value.first, value.second, bucket, key_hash);
  979. }
  980. const auto slot = EMH_SLOT(_index, bucket);
  981. return { {this, slot}, bempty };
  982. }
  983. std::pair<iterator, bool> do_insert(value_type&& value) noexcept
  984. {
  985. const auto key_hash = hash_key(value.first);
  986. const auto bucket = find_or_allocate(value.first, key_hash);
  987. const auto bempty = EMH_EMPTY(_index, bucket);
  988. if (bempty) {
  989. EMH_NEW(std::move(value.first), std::move(value.second), bucket, key_hash);
  990. }
  991. const auto slot = EMH_SLOT(_index, bucket);
  992. return { {this, slot}, bempty };
  993. }
  994. template<typename K, typename V>
  995. std::pair<iterator, bool> do_insert(K&& key, V&& val) noexcept
  996. {
  997. const auto key_hash = hash_key(key);
  998. const auto bucket = find_or_allocate(key, key_hash);
  999. const auto bempty = EMH_EMPTY(_index, bucket);
  1000. if (bempty) {
  1001. EMH_NEW(std::forward<K>(key), std::forward<V>(val), bucket, key_hash);
  1002. }
  1003. const auto slot = EMH_SLOT(_index, bucket);
  1004. return { {this, slot}, bempty };
  1005. }
  1006. template<typename K, typename V>
  1007. std::pair<iterator, bool> do_assign(K&& key, V&& val) noexcept
  1008. {
  1009. check_expand_need();
  1010. const auto key_hash = hash_key(key);
  1011. const auto bucket = find_or_allocate(key, key_hash);
  1012. const auto bempty = EMH_EMPTY(_index, bucket);
  1013. if (bempty) {
  1014. EMH_NEW(std::forward<K>(key), std::forward<V>(val), bucket, key_hash);
  1015. } else {
  1016. EMH_VAL(_pairs, EMH_SLOT(_index, bucket)) = std::move(val);
  1017. }
  1018. const auto slot = EMH_SLOT(_index, bucket);
  1019. return { {this, slot}, bempty };
  1020. }
  1021. std::pair<iterator, bool> insert(const value_type& p)
  1022. {
  1023. check_expand_need();
  1024. return do_insert(p);
  1025. }
  1026. std::pair<iterator, bool> insert(value_type && p)
  1027. {
  1028. check_expand_need();
  1029. return do_insert(std::move(p));
  1030. }
  1031. void insert(std::initializer_list<value_type> ilist)
  1032. {
  1033. reserve(ilist.size() + _num_filled, false);
  1034. for (auto it = ilist.begin(); it != ilist.end(); ++it)
  1035. do_insert(*it);
  1036. }
  1037. template <typename Iter>
  1038. void insert(Iter first, Iter last)
  1039. {
  1040. reserve(std::distance(first, last) + _num_filled, false);
  1041. for (; first != last; ++first)
  1042. do_insert(first->first, first->second);
  1043. }
  1044. #if 0
  1045. template <typename Iter>
  1046. void insert_unique(Iter begin, Iter end)
  1047. {
  1048. reserve(std::distance(begin, end) + _num_filled, false);
  1049. for (; begin != end; ++begin) {
  1050. insert_unique(*begin);
  1051. }
  1052. }
  1053. #endif
  1054. template<typename K, typename V>
  1055. size_type insert_unique(K&& key, V&& val)
  1056. {
  1057. check_expand_need();
  1058. const auto key_hash = hash_key(key);
  1059. auto bucket = find_unique_bucket(key_hash);
  1060. EMH_NEW(std::forward<K>(key), std::forward<V>(val), bucket, key_hash);
  1061. return bucket;
  1062. }
  1063. size_type insert_unique(value_type&& value)
  1064. {
  1065. return insert_unique(std::move(value.first), std::move(value.second));
  1066. }
  1067. inline size_type insert_unique(const value_type& value)
  1068. {
  1069. return insert_unique(value.first, value.second);
  1070. }
  1071. template <class... Args>
  1072. inline std::pair<iterator, bool> emplace(Args&&... args) noexcept
  1073. {
  1074. check_expand_need();
  1075. return do_insert(std::forward<Args>(args)...);
  1076. }
  1077. //no any optimize for position
  1078. template <class... Args>
  1079. iterator emplace_hint(const_iterator hint, Args&&... args)
  1080. {
  1081. (void)hint;
  1082. check_expand_need();
  1083. return do_insert(std::forward<Args>(args)...).first;
  1084. }
  1085. template<class... Args>
  1086. std::pair<iterator, bool> try_emplace(const KeyT& k, Args&&... args)
  1087. {
  1088. check_expand_need();
  1089. return do_insert(k, std::forward<Args>(args)...);
  1090. }
  1091. template<class... Args>
  1092. std::pair<iterator, bool> try_emplace(KeyT&& k, Args&&... args)
  1093. {
  1094. check_expand_need();
  1095. return do_insert(std::move(k), std::forward<Args>(args)...);
  1096. }
  1097. template <class... Args>
  1098. inline size_type emplace_unique(Args&&... args)
  1099. {
  1100. return insert_unique(std::forward<Args>(args)...);
  1101. }
  1102. std::pair<iterator, bool> insert_or_assign(const KeyT& key, ValueT&& val) { return do_assign(key, std::forward<ValueT>(val)); }
  1103. std::pair<iterator, bool> insert_or_assign(KeyT&& key, ValueT&& val) { return do_assign(std::move(key), std::forward<ValueT>(val)); }
  1104. /// Return the old value or ValueT() if it didn't exist.
  1105. ValueT set_get(const KeyT& key, const ValueT& val)
  1106. {
  1107. check_expand_need();
  1108. const auto key_hash = hash_key(key);
  1109. const auto bucket = find_or_allocate(key, key_hash);
  1110. if (EMH_EMPTY(_index, bucket)) {
  1111. EMH_NEW(key, val, bucket, key_hash);
  1112. return ValueT();
  1113. } else {
  1114. const auto slot = EMH_SLOT(_index, bucket);
  1115. ValueT old_value(val);
  1116. std::swap(EMH_VAL(_pairs, slot), old_value);
  1117. return old_value;
  1118. }
  1119. }
  1120. /// Like std::map<KeyT, ValueT>::operator[].
  1121. ValueT& operator[](const KeyT& key) noexcept
  1122. {
  1123. check_expand_need();
  1124. const auto key_hash = hash_key(key);
  1125. const auto bucket = find_or_allocate(key, key_hash);
  1126. if (EMH_EMPTY(_index, bucket)) {
  1127. /* Check if inserting a value rather than overwriting an old entry */
  1128. EMH_NEW(key, std::move(ValueT()), bucket, key_hash);
  1129. }
  1130. const auto slot = EMH_SLOT(_index, bucket);
  1131. return EMH_VAL(_pairs, slot);
  1132. }
  1133. ValueT& operator[](KeyT&& key) noexcept
  1134. {
  1135. check_expand_need();
  1136. const auto key_hash = hash_key(key);
  1137. const auto bucket = find_or_allocate(key, key_hash);
  1138. if (EMH_EMPTY(_index, bucket)) {
  1139. EMH_NEW(std::move(key), std::move(ValueT()), bucket, key_hash);
  1140. }
  1141. const auto slot = EMH_SLOT(_index, bucket);
  1142. return EMH_VAL(_pairs, slot);
  1143. }
  1144. /// Erase an element from the hash table.
  1145. /// return 0 if element was not found
  1146. size_type erase(const KeyT& key) noexcept
  1147. {
  1148. const auto key_hash = hash_key(key);
  1149. const auto sbucket = find_filled_bucket(key, key_hash);
  1150. if (sbucket == INACTIVE)
  1151. return 0;
  1152. const auto main_bucket = key_hash & _mask;
  1153. erase_slot(sbucket, (size_type)main_bucket);
  1154. return 1;
  1155. }
  1156. //iterator erase(const_iterator begin_it, const_iterator end_it)
  1157. iterator erase(const const_iterator& cit) noexcept
  1158. {
  1159. const auto slot = (size_type)(cit.kv_ - _pairs);
  1160. size_type main_bucket;
  1161. const auto sbucket = find_slot_bucket(slot, main_bucket); //TODO
  1162. erase_slot(sbucket, main_bucket);
  1163. return {this, slot};
  1164. }
  1165. //only last >= first
  1166. iterator erase(const_iterator first, const_iterator last) noexcept
  1167. {
  1168. auto esize = long(last.kv_ - first.kv_);
  1169. auto tsize = long((_pairs + _num_filled) - last.kv_); //last to tail size
  1170. auto next = first;
  1171. while (tsize -- > 0) {
  1172. if (esize-- <= 0)
  1173. break;
  1174. next = ++erase(next);
  1175. }
  1176. //fast erase from last
  1177. next = this->last();
  1178. while (esize -- > 0)
  1179. next = --erase(next);
  1180. return {this, size_type(next.kv_ - _pairs)};
  1181. }
  1182. template<typename Pred>
  1183. size_type erase_if(Pred pred)
  1184. {
  1185. auto old_size = size();
  1186. for (auto it = begin(); it != end();) {
  1187. if (pred(*it))
  1188. it = erase(it);
  1189. else
  1190. ++it;
  1191. }
  1192. return old_size - size();
  1193. }
  1194. static constexpr bool is_triviall_destructable()
  1195. {
  1196. #if __cplusplus >= 201402L || _MSC_VER > 1600
  1197. return !(std::is_trivially_destructible<KeyT>::value && std::is_trivially_destructible<ValueT>::value);
  1198. #else
  1199. return !(std::is_pod<KeyT>::value && std::is_pod<ValueT>::value);
  1200. #endif
  1201. }
  1202. static constexpr bool is_copy_trivially()
  1203. {
  1204. #if __cplusplus >= 201103L || _MSC_VER > 1600
  1205. return (std::is_trivially_copyable<KeyT>::value && std::is_trivially_copyable<ValueT>::value);
  1206. #else
  1207. return (std::is_pod<KeyT>::value && std::is_pod<ValueT>::value);
  1208. #endif
  1209. }
  1210. void clearkv()
  1211. {
  1212. if (is_triviall_destructable()) {
  1213. while (_num_filled --)
  1214. _pairs[_num_filled].~value_type();
  1215. }
  1216. }
  1217. /// Remove all elements, keeping full capacity.
  1218. void clear() noexcept
  1219. {
  1220. clearkv();
  1221. if (_num_filled > 0)
  1222. memset((char*)_index, INACTIVE, sizeof(_index[0]) * _num_buckets);
  1223. _last = _num_filled = 0;
  1224. _etail = INACTIVE;
  1225. #if EMH_HIGH_LOAD
  1226. _ehead = 0;
  1227. #endif
  1228. }
  1229. void shrink_to_fit(const float min_factor = EMH_DEFAULT_LOAD_FACTOR / 4)
  1230. {
  1231. if (load_factor() < min_factor && bucket_count() > 10) //safe guard
  1232. rehash(_num_filled + 1);
  1233. }
  1234. #if EMH_HIGH_LOAD
  1235. void set_empty()
  1236. {
  1237. auto prev = 0;
  1238. for (int32_t bucket = 1; bucket < _num_buckets; ++bucket) {
  1239. if (EMH_EMPTY(_index, bucket)) {
  1240. if (prev != 0) {
  1241. EMH_PREVET(_index, bucket) = prev;
  1242. EMH_BUCKET(_index, prev) = -bucket;
  1243. }
  1244. else
  1245. _ehead = bucket;
  1246. prev = bucket;
  1247. }
  1248. }
  1249. EMH_PREVET(_index, _ehead) = prev;
  1250. EMH_BUCKET(_index, prev) = 0-_ehead;
  1251. _ehead = 0-EMH_BUCKET(_index, _ehead);
  1252. }
  1253. void clear_empty()
  1254. {
  1255. auto prev = EMH_PREVET(_index, _ehead);
  1256. while (prev != _ehead) {
  1257. EMH_BUCKET(_index, prev) = INACTIVE;
  1258. prev = EMH_PREVET(_index, prev);
  1259. }
  1260. EMH_BUCKET(_index, _ehead) = INACTIVE;
  1261. _ehead = 0;
  1262. }
  1263. //prev-ehead->next
  1264. size_type pop_empty(const size_type bucket)
  1265. {
  1266. const auto prev_bucket = EMH_PREVET(_index, bucket);
  1267. const int next_bucket = 0-EMH_BUCKET(_index, bucket);
  1268. EMH_PREVET(_index, next_bucket) = prev_bucket;
  1269. EMH_BUCKET(_index, prev_bucket) = -next_bucket;
  1270. _ehead = next_bucket;
  1271. return bucket;
  1272. }
  1273. //ehead->bucket->next
  1274. void push_empty(const int32_t bucket)
  1275. {
  1276. const int next_bucket = 0-EMH_BUCKET(_index, _ehead);
  1277. assert(next_bucket > 0);
  1278. EMH_PREVET(_index, bucket) = _ehead;
  1279. EMH_BUCKET(_index, bucket) = -next_bucket;
  1280. EMH_PREVET(_index, next_bucket) = bucket;
  1281. EMH_BUCKET(_index, _ehead) = -bucket;
  1282. // _ehead = bucket;
  1283. }
  1284. #endif
  1285. /// Make room for this many elements
  1286. bool reserve(uint64_t num_elems, bool force)
  1287. {
  1288. (void)force;
  1289. #if EMH_HIGH_LOAD == 0
  1290. const auto required_buckets = num_elems * _mlf >> 27;
  1291. if (EMH_LIKELY(required_buckets < _mask)) // && !force
  1292. return false;
  1293. #elif EMH_HIGH_LOAD
  1294. const auto required_buckets = num_elems + num_elems * 1 / 9;
  1295. if (EMH_LIKELY(required_buckets < _mask))
  1296. return false;
  1297. else if (_num_buckets < 16 && _num_filled < _num_buckets)
  1298. return false;
  1299. else if (_num_buckets > EMH_HIGH_LOAD) {
  1300. if (_ehead == 0) {
  1301. set_empty();
  1302. return false;
  1303. } else if (/*_num_filled + 100 < _num_buckets && */EMH_BUCKET(_index, _ehead) != 0-_ehead) {
  1304. return false;
  1305. }
  1306. }
  1307. #endif
  1308. #if EMH_STATIS
  1309. if (_num_filled > EMH_STATIS) dump_statics();
  1310. #endif
  1311. //assert(required_buckets < max_size());
  1312. rehash(required_buckets + 2);
  1313. return true;
  1314. }
  1315. static value_type* alloc_bucket(size_type num_buckets)
  1316. {
  1317. auto new_pairs = (char*)malloc((uint64_t)num_buckets * sizeof(value_type));
  1318. return (value_type *)(new_pairs);
  1319. }
  1320. static Index* alloc_index(size_type num_buckets)
  1321. {
  1322. auto new_index = (char*)malloc((uint64_t)(EAD + num_buckets) * sizeof(Index));
  1323. return (Index *)(new_index);
  1324. }
  1325. bool reserve(size_type required_buckets) noexcept
  1326. {
  1327. if (_num_filled != required_buckets)
  1328. return reserve(required_buckets, true);
  1329. _last = 0;
  1330. #if EMH_HIGH_LOAD
  1331. _ehead = 0;
  1332. #endif
  1333. #if EMH_SORT
  1334. std::sort(_pairs, _pairs + _num_filled, [this](const value_type & l, const value_type & r) {
  1335. const auto hashl = (size_type)hash_key(l.first) & _mask, hashr = (size_type)hash_key(r.first) & _mask;
  1336. return hashl < hashr;
  1337. //return l.first < r.first;
  1338. });
  1339. #endif
  1340. memset((char*)_index, INACTIVE, sizeof(_index[0]) * _num_buckets);
  1341. for (size_type slot = 0; slot < _num_filled; slot++) {
  1342. const auto& key = EMH_KEY(_pairs, slot);
  1343. const auto key_hash = hash_key(key);
  1344. const auto bucket = size_type(key_hash & _mask);
  1345. auto& next_bucket = EMH_BUCKET(_index, bucket);
  1346. if ((int)next_bucket < 0)
  1347. EMH_INDEX(_index, bucket) = {1, slot | EMH_KEYMASK(key_hash, _mask)};
  1348. else {
  1349. EMH_HSLOT(_index, bucket) |= EMH_KEYMASK(key_hash, _mask);
  1350. next_bucket ++;
  1351. }
  1352. }
  1353. return true;
  1354. }
  1355. void rebuild(size_type num_buckets) noexcept
  1356. {
  1357. free(_index);
  1358. auto new_pairs = (value_type*)alloc_bucket((size_type)(num_buckets * max_load_factor()) + 4);
  1359. if (is_copy_trivially()) {
  1360. memcpy((char*)new_pairs, (char*)_pairs, _num_filled * sizeof(value_type));
  1361. } else {
  1362. for (size_type slot = 0; slot < _num_filled; slot++) {
  1363. new(new_pairs + slot) value_type(std::move(_pairs[slot]));
  1364. if (is_triviall_destructable())
  1365. _pairs[slot].~value_type();
  1366. }
  1367. }
  1368. free(_pairs);
  1369. _pairs = new_pairs;
  1370. _index = (Index*)alloc_index (num_buckets);
  1371. memset((char*)_index, INACTIVE, sizeof(_index[0]) * num_buckets);
  1372. memset((char*)(_index + num_buckets), 0, sizeof(_index[0]) * EAD);
  1373. }
  1374. void rehash(uint64_t required_buckets)
  1375. {
  1376. if (required_buckets < _num_filled)
  1377. return;
  1378. assert(required_buckets < max_size());
  1379. auto num_buckets = _num_filled > (1u << 16) ? (1u << 16) : 4u;
  1380. while (num_buckets < required_buckets) { num_buckets *= 2; }
  1381. #if EMH_REHASH_LOG
  1382. auto last = _last;
  1383. size_type collision = 0;
  1384. #endif
  1385. #if EMH_HIGH_LOAD
  1386. _ehead = 0;
  1387. #endif
  1388. _last = _mask / 4;
  1389. _mask = num_buckets - 1;
  1390. #if EMH_PACK_TAIL > 1
  1391. _last = _mask;
  1392. num_buckets += num_buckets * EMH_PACK_TAIL / 100; //add more 5-10%
  1393. #endif
  1394. _num_buckets = num_buckets;
  1395. rebuild(num_buckets);
  1396. #ifdef EMH_SORT
  1397. std::sort(_pairs, _pairs + _num_filled, [this](const value_type & l, const value_type & r) {
  1398. const auto hashl = hash_key(l.first), hashr = hash_key(r.first);
  1399. auto diff = int64_t((hashl & _mask) - (hashr & _mask));
  1400. if (diff != 0)
  1401. return diff < 0;
  1402. return hashl < hashr;
  1403. // return l.first < r.first;
  1404. });
  1405. #endif
  1406. _etail = INACTIVE;
  1407. for (size_type slot = 0; slot < _num_filled; ++slot) {
  1408. const auto& key = EMH_KEY(_pairs, slot);
  1409. const auto key_hash = hash_key(key);
  1410. const auto bucket = find_unique_bucket(key_hash);
  1411. EMH_INDEX(_index, bucket) = {bucket, slot | EMH_KEYMASK(key_hash, _mask)};
  1412. #if EMH_REHASH_LOG
  1413. if (bucket != hash_main(bucket))
  1414. collision ++;
  1415. #endif
  1416. }
  1417. #if EMH_REHASH_LOG
  1418. if (_num_filled > EMH_REHASH_LOG) {
  1419. auto mbucket = _num_filled - collision;
  1420. char buff[255] = {0};
  1421. sprintf(buff, " _num_filled/aver_size/K.V/pack/collision|last = %u/%.2lf/%s.%s/%zd|%.2lf%%,%.2lf%%",
  1422. _num_filled, double (_num_filled) / mbucket, typeid(KeyT).name(), typeid(ValueT).name(), sizeof(_pairs[0]), collision * 100.0 / _num_filled, last * 100.0 / _num_buckets);
  1423. #ifdef EMH_LOG
  1424. static uint32_t ihashs = 0; EMH_LOG() << "hash_nums = " << ihashs ++ << "|" <<__FUNCTION__ << "|" << buff << endl;
  1425. #else
  1426. puts(buff);
  1427. #endif
  1428. }
  1429. #endif
  1430. }
  1431. private:
  1432. // Can we fit another element?
  1433. inline bool check_expand_need()
  1434. {
  1435. return reserve(_num_filled, false);
  1436. }
  1437. size_type slot_to_bucket(const size_type slot) const noexcept
  1438. {
  1439. size_type main_bucket;
  1440. return find_slot_bucket(slot, main_bucket); //TODO
  1441. }
  1442. //very slow
  1443. void erase_slot(const size_type sbucket, const size_type main_bucket) noexcept
  1444. {
  1445. const auto slot = EMH_SLOT(_index, sbucket);
  1446. const auto ebucket = erase_bucket(sbucket, main_bucket);
  1447. const auto last_slot = --_num_filled;
  1448. if (EMH_LIKELY(slot != last_slot)) {
  1449. const auto last_bucket = (_etail == INACTIVE || ebucket == _etail)
  1450. ? slot_to_bucket(last_slot) : _etail;
  1451. EMH_KV(_pairs, slot) = std::move(EMH_KV(_pairs, last_slot));
  1452. EMH_HSLOT(_index, last_bucket) = slot | (EMH_HSLOT(_index, last_bucket) & ~_mask);
  1453. }
  1454. if (is_triviall_destructable())
  1455. _pairs[last_slot].~value_type();
  1456. _etail = INACTIVE;
  1457. EMH_INDEX(_index, ebucket) = {INACTIVE, 0};
  1458. #if EMH_HIGH_LOAD
  1459. if (_ehead) {
  1460. if (10 * _num_filled < 8 * _num_buckets)
  1461. clear_empty();
  1462. else if (ebucket)
  1463. push_empty(ebucket);
  1464. }
  1465. #endif
  1466. }
  1467. size_type erase_bucket(const size_type bucket, const size_type main_bucket) noexcept
  1468. {
  1469. const auto next_bucket = EMH_BUCKET(_index, bucket);
  1470. if (bucket == main_bucket) {
  1471. if (main_bucket != next_bucket) {
  1472. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  1473. EMH_INDEX(_index, main_bucket) = {
  1474. (nbucket == next_bucket) ? main_bucket : nbucket,
  1475. EMH_HSLOT(_index, next_bucket)
  1476. };
  1477. }
  1478. return next_bucket;
  1479. }
  1480. const auto prev_bucket = find_prev_bucket(main_bucket, bucket);
  1481. EMH_BUCKET(_index, prev_bucket) = (bucket == next_bucket) ? prev_bucket : next_bucket;
  1482. return bucket;
  1483. }
  1484. // Find the slot with this key, or return bucket size
  1485. size_type find_slot_bucket(const size_type slot, size_type& main_bucket) const
  1486. {
  1487. const auto key_hash = hash_key(EMH_KEY(_pairs, slot));
  1488. const auto bucket = main_bucket = size_type(key_hash & _mask);
  1489. if (slot == EMH_SLOT(_index, bucket))
  1490. return bucket;
  1491. auto next_bucket = EMH_BUCKET(_index, bucket);
  1492. while (true) {
  1493. if (EMH_LIKELY(slot == EMH_SLOT(_index, next_bucket)))
  1494. return next_bucket;
  1495. next_bucket = EMH_BUCKET(_index, next_bucket);
  1496. }
  1497. return INACTIVE;
  1498. }
  1499. // Find the slot with this key, or return bucket size
  1500. size_type find_filled_bucket(const KeyT& key, uint64_t key_hash) const noexcept
  1501. {
  1502. const auto bucket = size_type(key_hash & _mask);
  1503. auto next_bucket = EMH_BUCKET(_index, bucket);
  1504. if (EMH_UNLIKELY((int)next_bucket < 0))
  1505. return INACTIVE;
  1506. if (EMH_EQHASH(bucket, key_hash)) {
  1507. const auto slot = EMH_SLOT(_index, bucket);
  1508. if (EMH_LIKELY(_eq(key, EMH_KEY(_pairs, slot))))
  1509. return bucket;
  1510. }
  1511. if (next_bucket == bucket)
  1512. return INACTIVE;
  1513. while (true) {
  1514. if (EMH_EQHASH(next_bucket, key_hash)) {
  1515. const auto slot = EMH_SLOT(_index, next_bucket);
  1516. if (EMH_LIKELY(_eq(key, EMH_KEY(_pairs, slot))))
  1517. return next_bucket;
  1518. }
  1519. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  1520. if (nbucket == next_bucket)
  1521. return INACTIVE;
  1522. next_bucket = nbucket;
  1523. }
  1524. return INACTIVE;
  1525. }
  1526. // Find the slot with this key, or return bucket size
  1527. template<typename K=KeyT>
  1528. size_type find_filled_slot(const K& key) const noexcept
  1529. {
  1530. const auto key_hash = hash_key(key);
  1531. const auto bucket = size_type(key_hash & _mask);
  1532. auto next_bucket = EMH_BUCKET(_index, bucket);
  1533. if ((int)next_bucket < 0)
  1534. return _num_filled;
  1535. if (EMH_EQHASH(bucket, key_hash)) {
  1536. const auto slot = EMH_SLOT(_index, bucket);
  1537. if (EMH_LIKELY(_eq(key, EMH_KEY(_pairs, slot))))
  1538. return slot;
  1539. }
  1540. if (next_bucket == bucket)
  1541. return _num_filled;
  1542. while (true) {
  1543. if (EMH_EQHASH(next_bucket, key_hash)) {
  1544. const auto slot = EMH_SLOT(_index, next_bucket);
  1545. if (EMH_LIKELY(_eq(key, EMH_KEY(_pairs, slot))))
  1546. return slot;
  1547. }
  1548. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  1549. if (nbucket == next_bucket)
  1550. return _num_filled;
  1551. next_bucket = nbucket;
  1552. }
  1553. return _num_filled;
  1554. }
  1555. #if EMH_SORT
  1556. size_type find_hash_bucket(const KeyT& key) const noexcept
  1557. {
  1558. const auto key_hash = hash_key(key);
  1559. const auto bucket = size_type(key_hash & _mask);
  1560. const auto next_bucket = EMH_BUCKET(_index, bucket);
  1561. if ((int)next_bucket < 0)
  1562. return END;
  1563. auto slot = EMH_SLOT(_index, bucket);
  1564. if (_eq(key, EMH_KEY(_pairs, slot++)))
  1565. return slot;
  1566. else if (next_bucket == bucket)
  1567. return END;
  1568. while (true) {
  1569. const auto& okey = EMH_KEY(_pairs, slot++);
  1570. if (_eq(key, okey))
  1571. return slot;
  1572. const auto hasho = hash_key(okey);
  1573. if ((hasho & _mask) != bucket)
  1574. break;
  1575. else if (hasho > key_hash)
  1576. break;
  1577. else if (EMH_UNLIKELY(slot >= _num_filled))
  1578. break;
  1579. }
  1580. return END;
  1581. }
  1582. //only for find/can not insert
  1583. size_type find_sorted_bucket(const KeyT& key) const noexcept
  1584. {
  1585. const auto key_hash = hash_key(key);
  1586. const auto bucket = size_type(key_hash & _mask);
  1587. const auto slots = (int)(EMH_BUCKET(_index, bucket)); //TODO
  1588. if (slots < 0 /**|| key < EMH_KEY(_pairs, slot)*/)
  1589. return END;
  1590. const auto slot = EMH_SLOT(_index, bucket);
  1591. auto ormask = _index[bucket].slot & ~_mask;
  1592. auto hmask = EMH_KEYMASK(key_hash, _mask);
  1593. if ((hmask | ormask) != ormask)
  1594. return END;
  1595. if (_eq(key, EMH_KEY(_pairs, slot)))
  1596. return slot;
  1597. else if (slots == 1 || key < EMH_KEY(_pairs, slot))
  1598. return END;
  1599. #if EMH_SORT
  1600. if (key < EMH_KEY(_pairs, slot) || key > EMH_KEY(_pairs, slots + slot - 1))
  1601. return END;
  1602. #endif
  1603. for (size_type i = 1; i < slots; ++i) {
  1604. const auto& okey = EMH_KEY(_pairs, slot + i);
  1605. if (_eq(key, okey))
  1606. return slot + i;
  1607. // else if (okey > key)
  1608. // return END;
  1609. }
  1610. return END;
  1611. }
  1612. #endif
  1613. //kick out bucket and find empty to occpuy
  1614. //it will break the orgin link and relnik again.
  1615. //before: main_bucket-->prev_bucket --> bucket --> next_bucket
  1616. //atfer : main_bucket-->prev_bucket --> (removed)--> new_bucket--> next_bucket
  1617. size_type kickout_bucket(const size_type kmain, const size_type bucket) noexcept
  1618. {
  1619. const auto next_bucket = EMH_BUCKET(_index, bucket);
  1620. const auto new_bucket = find_empty_bucket(next_bucket, 2);
  1621. const auto prev_bucket = find_prev_bucket(kmain, bucket);
  1622. const auto last = next_bucket == bucket ? new_bucket : next_bucket;
  1623. EMH_INDEX(_index, new_bucket) = {last, EMH_HSLOT(_index, bucket)};
  1624. EMH_BUCKET(_index, prev_bucket) = new_bucket;
  1625. EMH_BUCKET(_index, bucket) = INACTIVE;
  1626. return bucket;
  1627. }
  1628. /*
  1629. ** inserts a new key into a hash table; first, check whether key's main
  1630. ** bucket/position is free. If not, check whether colliding node/bucket is in its main
  1631. ** position or not: if it is not, move colliding bucket to an empty place and
  1632. ** put new key in its main position; otherwise (colliding bucket is in its main
  1633. ** position), new key goes to an empty position.
  1634. */
  1635. template<typename K=KeyT>
  1636. size_type find_or_allocate(const K& key, uint64_t key_hash) noexcept
  1637. {
  1638. const auto bucket = size_type(key_hash & _mask);
  1639. auto next_bucket = EMH_BUCKET(_index, bucket);
  1640. if ((int)next_bucket < 0) {
  1641. #if EMH_HIGH_LOAD
  1642. if (next_bucket != INACTIVE)
  1643. pop_empty(bucket);
  1644. #endif
  1645. return bucket;
  1646. }
  1647. const auto slot = EMH_SLOT(_index, bucket);
  1648. if (EMH_EQHASH(bucket, key_hash))
  1649. if (EMH_LIKELY(_eq(key, EMH_KEY(_pairs, slot))))
  1650. return bucket;
  1651. //check current bucket_key is in main bucket or not
  1652. const auto kmain = hash_bucket(EMH_KEY(_pairs, slot));
  1653. if (kmain != bucket)
  1654. return kickout_bucket(kmain, bucket);
  1655. else if (next_bucket == bucket)
  1656. return EMH_BUCKET(_index, next_bucket) = find_empty_bucket(next_bucket, 1);
  1657. uint32_t csize = 1;
  1658. //find next linked bucket and check key
  1659. while (true) {
  1660. const auto eslot = EMH_SLOT(_index, next_bucket);
  1661. if (EMH_EQHASH(next_bucket, key_hash)) {
  1662. if (EMH_LIKELY(_eq(key, EMH_KEY(_pairs, eslot))))
  1663. return next_bucket;
  1664. }
  1665. csize += 1;
  1666. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  1667. if (nbucket == next_bucket)
  1668. break;
  1669. next_bucket = nbucket;
  1670. }
  1671. //find a empty and link it to tail
  1672. const auto new_bucket = find_empty_bucket(next_bucket, csize);
  1673. return EMH_BUCKET(_index, next_bucket) = new_bucket;
  1674. }
  1675. size_type find_unique_bucket(uint64_t key_hash) noexcept
  1676. {
  1677. const auto bucket = size_type(key_hash & _mask);
  1678. auto next_bucket = EMH_BUCKET(_index, bucket);
  1679. if ((int)next_bucket < 0) {
  1680. #if EMH_HIGH_LOAD
  1681. if (next_bucket != INACTIVE)
  1682. pop_empty(bucket);
  1683. #endif
  1684. return bucket;
  1685. }
  1686. //check current bucket_key is in main bucket or not
  1687. const auto kmain = hash_main(bucket);
  1688. if (EMH_UNLIKELY(kmain != bucket))
  1689. return kickout_bucket(kmain, bucket);
  1690. else if (EMH_UNLIKELY(next_bucket != bucket))
  1691. next_bucket = find_last_bucket(next_bucket);
  1692. return EMH_BUCKET(_index, next_bucket) = find_empty_bucket(next_bucket, 2);
  1693. }
  1694. /***
  1695. Different probing techniques usually provide a trade-off between memory locality and avoidance of clustering.
  1696. Since Robin Hood hashing is relatively resilient to clustering (both primary and secondary), linear probing is the most cache friendly alternativeis typically used.
  1697. It's the core algorithm of this hash map with highly optimization/benchmark.
  1698. normaly linear probing is inefficient with high load factor, it use a new 3-way linear
  1699. probing strategy to search empty slot. from benchmark even the load factor > 0.9, it's more 2-3 timer fast than
  1700. one-way search strategy.
  1701. 1. linear or quadratic probing a few cache line for less cache miss from input slot "bucket_from".
  1702. 2. the first search slot from member variant "_last", init with 0
  1703. 3. the second search slot from calculated pos "(_num_filled + _last) & _mask", it's like a rand value
  1704. */
  1705. // key is not in this mavalue. Find a place to put it.
  1706. size_type find_empty_bucket(const size_type bucket_from, uint32_t csize) noexcept
  1707. {
  1708. #if EMH_HIGH_LOAD
  1709. if (_ehead)
  1710. return pop_empty(_ehead);
  1711. #endif
  1712. auto bucket = bucket_from;
  1713. if (EMH_EMPTY(_index, ++bucket) || EMH_EMPTY(_index, ++bucket))
  1714. return bucket;
  1715. #ifdef EMH_QUADRATIC
  1716. constexpr size_type linear_probe_length = 2 * EMH_CACHE_LINE_SIZE / sizeof(Index);//16
  1717. for (size_type offset = csize + 2, step = 4; offset <= linear_probe_length; ) {
  1718. bucket = (bucket_from + offset) & _mask;
  1719. if (EMH_EMPTY(_index, bucket) || EMH_EMPTY(_index, ++bucket))
  1720. return bucket;
  1721. offset += step; //7/8. 12. 16
  1722. }
  1723. #else
  1724. constexpr size_type quadratic_probe_length = 6u;
  1725. for (size_type offset = 4u, step = 3u; step < quadratic_probe_length; ) {
  1726. bucket = (bucket_from + offset) & _mask;
  1727. if (EMH_EMPTY(_index, bucket) || EMH_EMPTY(_index, ++bucket))
  1728. return bucket;
  1729. offset += step++;//3.4.5
  1730. }
  1731. #endif
  1732. #if EMH_PREFETCH
  1733. __builtin_prefetch(static_cast<const void*>(_index + _last + 1), 0, EMH_PREFETCH);
  1734. #endif
  1735. for (;;) {
  1736. #if EMH_PACK_TAIL
  1737. //find empty bucket and skip next
  1738. if (EMH_EMPTY(_index, _last++))// || EMH_EMPTY(_index, _last++))
  1739. return _last++ - 1;
  1740. if (EMH_UNLIKELY(_last >= _num_buckets))
  1741. _last = 0;
  1742. auto medium = (_mask / 4 + _last++) & _mask;
  1743. if (EMH_EMPTY(_index, medium))
  1744. return medium;
  1745. #else
  1746. if (EMH_EMPTY(_index, ++_last))// || EMH_EMPTY(_index, ++_last))
  1747. return _last++;
  1748. _last &= _mask;
  1749. auto medium = (_num_buckets / 2 + _last) & _mask;
  1750. if (EMH_EMPTY(_index, medium))// || EMH_EMPTY(_index, ++medium))
  1751. return _last = medium;
  1752. #endif
  1753. }
  1754. return 0;
  1755. }
  1756. size_type find_last_bucket(size_type main_bucket) const
  1757. {
  1758. auto next_bucket = EMH_BUCKET(_index, main_bucket);
  1759. if (next_bucket == main_bucket)
  1760. return main_bucket;
  1761. while (true) {
  1762. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  1763. if (nbucket == next_bucket)
  1764. return next_bucket;
  1765. next_bucket = nbucket;
  1766. }
  1767. }
  1768. size_type find_prev_bucket(const size_type main_bucket, const size_type bucket) const
  1769. {
  1770. auto next_bucket = EMH_BUCKET(_index, main_bucket);
  1771. if (next_bucket == bucket)
  1772. return main_bucket;
  1773. while (true) {
  1774. const auto nbucket = EMH_BUCKET(_index, next_bucket);
  1775. if (nbucket == bucket)
  1776. return next_bucket;
  1777. next_bucket = nbucket;
  1778. }
  1779. }
  1780. inline size_type hash_bucket(const KeyT& key) const noexcept
  1781. {
  1782. return (size_type)hash_key(key) & _mask;
  1783. }
  1784. inline size_type hash_main(const size_type bucket) const noexcept
  1785. {
  1786. const auto slot = EMH_SLOT(_index, bucket);
  1787. return (size_type)hash_key(EMH_KEY(_pairs, slot)) & _mask;
  1788. }
  1789. #if EMH_INT_HASH
  1790. static constexpr uint64_t KC = UINT64_C(11400714819323198485);
  1791. static uint64_t hash64(uint64_t key)
  1792. {
  1793. #if __SIZEOF_INT128__ && EMH_INT_HASH == 1
  1794. __uint128_t r = key; r *= KC;
  1795. return (uint64_t)(r >> 64) + (uint64_t)r;
  1796. #elif EMH_INT_HASH == 2
  1797. //MurmurHash3Mixer
  1798. uint64_t h = key;
  1799. h ^= h >> 33;
  1800. h *= 0xff51afd7ed558ccd;
  1801. h ^= h >> 33;
  1802. h *= 0xc4ceb9fe1a85ec53;
  1803. h ^= h >> 33;
  1804. return h;
  1805. #elif _WIN64 && EMH_INT_HASH == 1
  1806. uint64_t high;
  1807. return _umul128(key, KC, &high) + high;
  1808. #elif EMH_INT_HASH == 3
  1809. auto ror = (key >> 32) | (key << 32);
  1810. auto low = key * 0xA24BAED4963EE407ull;
  1811. auto high = ror * 0x9FB21C651E98DF25ull;
  1812. auto mix = low + high;
  1813. return mix;
  1814. #elif EMH_INT_HASH == 1
  1815. uint64_t r = key * UINT64_C(0xca4bcaa75ec3f625);
  1816. return (r >> 32) + r;
  1817. #elif EMH_WYHASH64
  1818. return wyhash64(key, KC);
  1819. #else
  1820. uint64_t x = key;
  1821. x = (x ^ (x >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
  1822. x = (x ^ (x >> 27)) * UINT64_C(0x94d049bb133111eb);
  1823. x = x ^ (x >> 31);
  1824. return x;
  1825. #endif
  1826. }
  1827. #endif
  1828. #if EMH_WYHASH_HASH
  1829. //#define WYHASH_CONDOM 1
  1830. inline uint64_t wymix(uint64_t A, uint64_t B)
  1831. {
  1832. #if defined(__SIZEOF_INT128__)
  1833. __uint128_t r = A; r *= B;
  1834. #if WYHASH_CONDOM2
  1835. A ^= (uint64_t)r; B ^= (uint64_t)(r >> 64);
  1836. #else
  1837. A = (uint64_t)r; B = (uint64_t)(r >> 64);
  1838. #endif
  1839. #elif defined(_MSC_VER) && defined(_M_X64)
  1840. #if WYHASH_CONDOM2
  1841. uint64_t a, b;
  1842. a = _umul128(A, B, &b);
  1843. A ^= a; B ^= b;
  1844. #else
  1845. A = _umul128(A, B, &B);
  1846. #endif
  1847. #else
  1848. uint64_t ha = A >> 32, hb = B >> 32, la = (uint32_t)A, lb = (uint32_t)B, hi, lo;
  1849. uint64_t rh = ha * hb, rm0 = ha * lb, rm1 = hb * la, rl = la * lb, t = rl + (rm0 << 32), c = t < rl;
  1850. lo = t + (rm1 << 32); c += lo < t; hi = rh + (rm0 >> 32) + (rm1 >> 32) + c;
  1851. #if WYHASH_CONDOM2
  1852. A ^= lo; B ^= hi;
  1853. #else
  1854. A = lo; B = hi;
  1855. #endif
  1856. #endif
  1857. return A ^ B;
  1858. }
  1859. //multiply and xor mix function, aka MUM
  1860. static inline uint64_t wyr8(const uint8_t *p) { uint64_t v; memcpy(&v, p, 8); return v; }
  1861. static inline uint64_t wyr4(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; }
  1862. static inline uint64_t wyr3(const uint8_t *p, size_t k) {
  1863. return (((uint64_t)p[0]) << 16) | (((uint64_t)p[k >> 1]) << 8) | p[k - 1];
  1864. }
  1865. static constexpr uint64_t secret[4] = {
  1866. 0xa0761d6478bd642full, 0xe7037ed1a0b428dbull,
  1867. 0x8ebc6af09c88c6e3ull, 0x589965cc75374cc3ull};
  1868. public:
  1869. //wyhash main function https://github.com/wangyi-fudan/wyhash
  1870. static uint64_t wyhashstr(const char *key, const size_t len)
  1871. {
  1872. uint64_t a = 0, b = 0, seed = secret[0];
  1873. const uint8_t *p = (const uint8_t*)key;
  1874. if (EMH_LIKELY(len <= 16)) {
  1875. if (EMH_LIKELY(len >= 4)) {
  1876. const auto half = (len >> 3) << 2;
  1877. a = (wyr4(p) << 32U) | wyr4(p + half); p += len - 4;
  1878. b = (wyr4(p) << 32U) | wyr4(p - half);
  1879. } else if (len) {
  1880. a = wyr3(p, len);
  1881. }
  1882. } else {
  1883. size_t i = len;
  1884. if (EMH_UNLIKELY(i > 48)) {
  1885. uint64_t see1 = seed, see2 = seed;
  1886. do {
  1887. seed = wymix(wyr8(p + 0) ^ secret[1], wyr8(p + 8) ^ seed);
  1888. see1 = wymix(wyr8(p + 16) ^ secret[2], wyr8(p + 24) ^ see1);
  1889. see2 = wymix(wyr8(p + 32) ^ secret[3], wyr8(p + 40) ^ see2);
  1890. p += 48; i -= 48;
  1891. } while (EMH_LIKELY(i > 48));
  1892. seed ^= see1 ^ see2;
  1893. }
  1894. while (i > 16) {
  1895. seed = wymix(wyr8(p) ^ secret[1], wyr8(p + 8) ^ seed);
  1896. i -= 16; p += 16;
  1897. }
  1898. a = wyr8(p + i - 16);
  1899. b = wyr8(p + i - 8);
  1900. }
  1901. return wymix(secret[1] ^ len, wymix(a ^ secret[1], b ^ seed));
  1902. }
  1903. #endif
  1904. private:
  1905. template<typename UType, typename std::enable_if<std::is_integral<UType>::value, uint32_t>::type = 0>
  1906. inline uint64_t hash_key(const UType key) const
  1907. {
  1908. #if EMH_INT_HASH
  1909. return hash64(key);
  1910. #elif EMH_IDENTITY_HASH
  1911. return key + (key >> 24);
  1912. #else
  1913. return _hasher(key);
  1914. #endif
  1915. }
  1916. template<typename UType, typename std::enable_if<std::is_same<UType, std::string>::value, uint32_t>::type = 0>
  1917. inline uint64_t hash_key(const UType& key) const
  1918. {
  1919. #if EMH_WYHASH_HASH
  1920. return wyhashstr(key.data(), key.size());
  1921. #else
  1922. return _hasher(key);
  1923. #endif
  1924. }
  1925. template<typename UType, typename std::enable_if<!std::is_integral<UType>::value && !std::is_same<UType, std::string>::value, uint32_t>::type = 0>
  1926. inline uint64_t hash_key(const UType& key) const
  1927. {
  1928. return _hasher(key);
  1929. }
  1930. private:
  1931. Index* _index;
  1932. value_type*_pairs;
  1933. HashT _hasher;
  1934. EqT _eq;
  1935. uint32_t _mlf;
  1936. size_type _mask;
  1937. size_type _num_buckets;
  1938. size_type _num_filled;
  1939. size_type _last;
  1940. #if EMH_HIGH_LOAD
  1941. size_type _ehead;
  1942. #endif
  1943. size_type _etail;
  1944. };
  1945. } // namespace emhash
  1946. struct PyObject;
  1947. typedef pkpy::shared_ptr<PyObject> PyVar;
  1948. typedef PyVar PyVarOrNull;
  1949. class PyVarList: public std::vector<PyVar> {
  1950. PyVar& at(size_t) = delete;
  1951. inline void __checkIndex(size_t i) const {
  1952. if (i >= size()){
  1953. auto msg = "std::vector index out of range, " + std::to_string(i) + " not in [0, " + std::to_string(size()) + ")";
  1954. throw std::out_of_range(msg);
  1955. }
  1956. }
  1957. public:
  1958. PyVar& operator[](size_t i) {
  1959. __checkIndex(i);
  1960. return std::vector<PyVar>::operator[](i);
  1961. }
  1962. const PyVar& operator[](size_t i) const {
  1963. __checkIndex(i);
  1964. return std::vector<PyVar>::operator[](i);
  1965. }
  1966. // define constructors the same as std::vector
  1967. using std::vector<PyVar>::vector;
  1968. };
  1969. class PyVarDict: public emhash8::HashMap<_Str, PyVar> {
  1970. PyVar& at(const _Str&) = delete;
  1971. public:
  1972. PyVar& operator[](const _Str& key) {
  1973. return emhash8::HashMap<_Str, PyVar>::operator[](key);
  1974. }
  1975. const PyVar& operator[](const _Str& key) const {
  1976. auto it = find(key);
  1977. if (it == end()){
  1978. auto msg = "map key not found, '" + key.str() + "'";
  1979. throw std::out_of_range(msg);
  1980. }
  1981. return it->second;
  1982. }
  1983. using emhash8::HashMap<_Str, PyVar>::HashMap;
  1984. };
  1985. namespace pkpy {
  1986. const uint8_t MAX_POOLING_N = 10;
  1987. static std::vector<PyVar*>* _poolArgList = new std::vector<PyVar*>[MAX_POOLING_N];
  1988. class ArgList {
  1989. PyVar* _args = nullptr;
  1990. uint8_t _size = 0;
  1991. inline void __checkIndex(uint8_t i) const {
  1992. if (i >= _size){
  1993. auto msg = "pkpy:ArgList index out of range, " + std::to_string(i) + " not in [0, " + std::to_string(size()) + ")";
  1994. throw std::out_of_range(msg);
  1995. }
  1996. }
  1997. void __tryAlloc(uint8_t n){
  1998. if(n > 255) UNREACHABLE();
  1999. if(n >= MAX_POOLING_N || _poolArgList[n].empty()){
  2000. this->_size = n;
  2001. this->_args = new PyVar[n];
  2002. }else{
  2003. this->_args = _poolArgList[n].back();
  2004. this->_size = n;
  2005. _poolArgList[n].pop_back();
  2006. }
  2007. }
  2008. void __tryRelease(){
  2009. if(_size == 0 || _args == nullptr) return;
  2010. if(_size >= MAX_POOLING_N || _poolArgList[_size].size() > 32){
  2011. delete[] _args;
  2012. }else{
  2013. for(uint8_t i = 0; i < _size; i++) _args[i].reset();
  2014. _poolArgList[_size].push_back(_args);
  2015. }
  2016. }
  2017. public:
  2018. ArgList(uint8_t n){
  2019. if(n != 0) __tryAlloc(n);
  2020. }
  2021. ArgList(const ArgList& other){
  2022. __tryAlloc(other._size);
  2023. for(uint8_t i=0; i<_size; i++){
  2024. _args[i] = other._args[i];
  2025. }
  2026. }
  2027. ArgList(ArgList&& other){
  2028. this->_args = other._args;
  2029. this->_size = other._size;
  2030. other._args = nullptr;
  2031. other._size = 0;
  2032. }
  2033. ArgList(PyVarList&& other){
  2034. __tryAlloc(other.size());
  2035. for(uint8_t i=0; i<_size; i++){
  2036. _args[i] = std::move(other[i]);
  2037. }
  2038. other.clear();
  2039. }
  2040. // deprecated, this is very slow, do not use it!!!
  2041. ArgList(std::initializer_list<PyVar> args){
  2042. __tryAlloc(args.size());
  2043. uint8_t i = 0;
  2044. for(auto& arg: args) this->_args[i++] = arg;
  2045. }
  2046. PyVar& operator[](uint8_t i){
  2047. __checkIndex(i);
  2048. return _args[i];
  2049. }
  2050. const PyVar& operator[](uint8_t i) const {
  2051. __checkIndex(i);
  2052. return _args[i];
  2053. }
  2054. inline PyVar& _index(uint8_t i){
  2055. return _args[i];
  2056. }
  2057. // overload = for &&
  2058. ArgList& operator=(ArgList&& other){
  2059. if(this != &other){
  2060. __tryRelease();
  2061. this->_args = other._args;
  2062. this->_size = other._size;
  2063. other._args = nullptr;
  2064. other._size = 0;
  2065. }
  2066. return *this;
  2067. }
  2068. uint8_t size() const {
  2069. return _size;
  2070. }
  2071. ArgList subList(uint8_t start) const {
  2072. if(start >= _size) return ArgList(0);
  2073. ArgList ret(_size - start);
  2074. for(uint8_t i=start; i<_size; i++){
  2075. ret[i-start] = _args[i];
  2076. }
  2077. return ret;
  2078. }
  2079. PyVarList toList() const {
  2080. PyVarList ret(_size);
  2081. for(uint8_t i=0; i<_size; i++){
  2082. ret[i] = _args[i];
  2083. }
  2084. return ret;
  2085. }
  2086. ~ArgList(){
  2087. __tryRelease();
  2088. }
  2089. };
  2090. }
  2091. const char* __BUILTINS_CODE = R"(
  2092. def len(x):
  2093. return x.__len__()
  2094. str.__mul__ = lambda self, n: ''.join([self for _ in range(n)])
  2095. def __str4split(self, sep):
  2096. if sep == "":
  2097. return list(self)
  2098. res = []
  2099. i = 0
  2100. while i < len(self):
  2101. if self[i:i+len(sep)] == sep:
  2102. res.append(self[:i])
  2103. self = self[i+len(sep):]
  2104. i = 0
  2105. else:
  2106. i += 1
  2107. res.append(self)
  2108. return res
  2109. str.split = __str4split
  2110. del __str4split
  2111. def __str4index(self, sub):
  2112. for i in range(len(self) - len(sub) + 1):
  2113. if self[i:i+len(sub)] == sub:
  2114. return i
  2115. return -1
  2116. str.index = __str4index
  2117. del __str4index
  2118. list.__repr__ = lambda self: '[' + ', '.join([repr(i) for i in self]) + ']'
  2119. tuple.__repr__ = lambda self: '(' + ', '.join([repr(i) for i in self]) + ')'
  2120. list.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']'
  2121. tuple.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']'
  2122. def __list4extend(self, other):
  2123. for i in other:
  2124. self.append(i)
  2125. list.extend = __list4extend
  2126. del __list4extend
  2127. def __list4remove(self, value):
  2128. for i in range(len(self)):
  2129. if self[i] == value:
  2130. del self[i]
  2131. return True
  2132. return False
  2133. list.remove = __list4remove
  2134. del __list4remove
  2135. def __list4index(self, value):
  2136. for i in range(len(self)):
  2137. if self[i] == value:
  2138. return i
  2139. return -1
  2140. list.index = __list4index
  2141. del __list4index
  2142. def __list4__mul__(self, n):
  2143. a = []
  2144. for i in range(n):
  2145. a.extend(self)
  2146. return a
  2147. list.__mul__ = __list4__mul__
  2148. del __list4__mul__
  2149. def __iterable4__eq__(self, other):
  2150. if len(self) != len(other):
  2151. return False
  2152. for i in range(len(self)):
  2153. if self[i] != other[i]:
  2154. return False
  2155. return True
  2156. list.__eq__ = __iterable4__eq__
  2157. tuple.__eq__ = __iterable4__eq__
  2158. del __iterable4__eq__
  2159. def __iterable4count(self, x):
  2160. res = 0
  2161. for i in self:
  2162. if i == x:
  2163. res += 1
  2164. return res
  2165. list.count = __iterable4count
  2166. tuple.count = __iterable4count
  2167. del __iterable4count
  2168. def __iterable4__contains__(self, item):
  2169. for i in self:
  2170. if i == item:
  2171. return True
  2172. return False
  2173. list.__contains__ = __iterable4__contains__
  2174. tuple.__contains__ = __iterable4__contains__
  2175. del __iterable4__contains__
  2176. list.__new__ = lambda obj: [i for i in obj]
  2177. # https://github.com/python/cpython/blob/main/Objects/dictobject.c
  2178. class dict:
  2179. def __init__(self):
  2180. self._capacity = 8
  2181. self._a = [None] * self._capacity
  2182. self._len = 0
  2183. def __len__(self):
  2184. return self._len
  2185. def __probe(self, key):
  2186. i = hash(key) % self._capacity
  2187. while self._a[i] is not None:
  2188. if self._a[i][0] == key:
  2189. return True, i
  2190. i = ((5*i) + 1) % self._capacity
  2191. return False, i
  2192. def __getitem__(self, key):
  2193. ok, i = self.__probe(key)
  2194. if not ok:
  2195. raise KeyError(key)
  2196. return self._a[i][1]
  2197. def __contains__(self, key):
  2198. ok, i = self.__probe(key)
  2199. return ok
  2200. def __setitem__(self, key, value):
  2201. ok, i = self.__probe(key)
  2202. if ok:
  2203. self._a[i][1] = value
  2204. else:
  2205. self._a[i] = [key, value]
  2206. self._len += 1
  2207. if self._len > self._capacity * 0.6:
  2208. self.__resize_2x()
  2209. def __delitem__(self, key):
  2210. ok, i = self.__probe(key)
  2211. if not ok:
  2212. raise KeyError(key)
  2213. self._a[i] = None
  2214. self._len -= 1
  2215. def __resize_2x(self):
  2216. old_a = self._a
  2217. self._capacity *= 2
  2218. self._a = [None] * self._capacity
  2219. self._len = 0
  2220. for kv in old_a:
  2221. if kv is not None:
  2222. self[kv[0]] = kv[1]
  2223. def keys(self):
  2224. return [kv[0] for kv in self._a if kv is not None]
  2225. def values(self):
  2226. return [kv[1] for kv in self._a if kv is not None]
  2227. def items(self):
  2228. return [kv for kv in self._a if kv is not None]
  2229. def clear(self):
  2230. self._a = [None] * self._capacity
  2231. self._len = 0
  2232. def update(self, other):
  2233. for k, v in other.items():
  2234. self[k] = v
  2235. def copy(self):
  2236. d = dict()
  2237. for kv in self._a:
  2238. if kv is not None:
  2239. d[kv[0]] = kv[1]
  2240. return d
  2241. def __repr__(self):
  2242. a = [repr(k)+': '+repr(v) for k,v in self.items()]
  2243. return '{'+ ', '.join(a) + '}'
  2244. def __json__(self):
  2245. a = []
  2246. for k,v in self.items():
  2247. if type(k) is not str:
  2248. raise TypeError('json keys must be strings, got ' + repr(k) )
  2249. a.append(k.__json__()+': '+v.__json__())
  2250. return '{'+ ', '.join(a) + '}'
  2251. def round(x):
  2252. if x >= 0:
  2253. return int(x + 0.5)
  2254. else:
  2255. return int(x - 0.5)
  2256. def max(a, b):
  2257. if a > b:
  2258. return a
  2259. return b
  2260. def min(a, b):
  2261. if a < b:
  2262. return a
  2263. return b
  2264. def sum(iterable):
  2265. res = 0
  2266. for i in iterable:
  2267. res += i
  2268. return res
  2269. def map(f, iterable):
  2270. return [f(i) for i in iterable]
  2271. def zip(a, b):
  2272. return [(a[i], b[i]) for i in range(min(len(a), len(b)))]
  2273. def sorted(iterable, key=None, reverse=False):
  2274. if key is None:
  2275. key = lambda x: x
  2276. a = [key(i) for i in iterable]
  2277. b = list(iterable)
  2278. for i in range(len(a)):
  2279. for j in range(i+1, len(a)):
  2280. if (a[i] > a[j]) ^ reverse:
  2281. a[i], a[j] = a[j], a[i]
  2282. b[i], b[j] = b[j], b[i]
  2283. return b
  2284. import json as _json
  2285. def jsonrpc(method, params, raw=False):
  2286. assert type(method) is str
  2287. assert type(params) is list or type(params) is tuple
  2288. data = {
  2289. 'jsonrpc': '2.0',
  2290. 'method': method,
  2291. 'params': params,
  2292. }
  2293. ret = __string_channel_call(_json.dumps(data))
  2294. ret = _json.loads(ret)
  2295. if raw:
  2296. return ret
  2297. assert type(ret) is dict
  2298. if 'result' in ret:
  2299. return ret['result']
  2300. raise JsonRpcError(ret['error']['message'])
  2301. def input(prompt=None):
  2302. return jsonrpc('input', [prompt])
  2303. class FileIO:
  2304. def __init__(self, path, mode):
  2305. assert type(path) is str
  2306. assert type(mode) is str
  2307. assert mode in ['r', 'w']
  2308. self.path = path
  2309. self.mode = mode
  2310. self.fp = jsonrpc('fopen', [path, mode])
  2311. def read(self):
  2312. assert self.mode == 'r'
  2313. return jsonrpc('fread', [self.fp])
  2314. def write(self, s):
  2315. assert self.mode == 'w'
  2316. assert type(s) is str
  2317. jsonrpc('fwrite', [self.fp, s])
  2318. def close(self):
  2319. jsonrpc('fclose', [self.fp])
  2320. def __enter__(self):
  2321. pass
  2322. def __exit__(self):
  2323. self.close()
  2324. def open(path, mode='r'):
  2325. return FileIO(path, mode)
  2326. )";
  2327. const char* __OS_CODE = R"(
  2328. def listdir(path):
  2329. assert type(path) is str
  2330. return jsonrpc("os.listdir", [path])
  2331. def mkdir(path):
  2332. assert type(path) is str
  2333. return jsonrpc("os.mkdir", [path])
  2334. def rmdir(path):
  2335. assert type(path) is str
  2336. return jsonrpc("os.rmdir", [path])
  2337. def remove(path):
  2338. assert type(path) is str
  2339. return jsonrpc("os.remove", [path])
  2340. path = object()
  2341. def __path4exists(path):
  2342. assert type(path) is str
  2343. return jsonrpc("os.path.exists", [path])
  2344. path.exists = __path4exists
  2345. del __path4exists
  2346. )";
  2347. const char* __RANDOM_CODE = R"(
  2348. import time as _time
  2349. __all__ = ['Random', 'seed', 'random', 'randint', 'uniform']
  2350. def _int32(x):
  2351. return int(0xffffffff & x)
  2352. class Random:
  2353. def __init__(self, seed=None):
  2354. if seed is None:
  2355. seed = int(_time.time() * 1000000)
  2356. seed = _int32(seed)
  2357. self.mt = [0] * 624
  2358. self.mt[0] = seed
  2359. self.mti = 0
  2360. for i in range(1, 624):
  2361. self.mt[i] = _int32(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)
  2362. def extract_number(self):
  2363. if self.mti == 0:
  2364. self.twist()
  2365. y = self.mt[self.mti]
  2366. y = y ^ y >> 11
  2367. y = y ^ y << 7 & 2636928640
  2368. y = y ^ y << 15 & 4022730752
  2369. y = y ^ y >> 18
  2370. self.mti = (self.mti + 1) % 624
  2371. return _int32(y)
  2372. def twist(self):
  2373. for i in range(0, 624):
  2374. y = _int32((self.mt[i] & 0x80000000) + (self.mt[(i + 1) % 624] & 0x7fffffff))
  2375. self.mt[i] = (y >> 1) ^ self.mt[(i + 397) % 624]
  2376. if y % 2 != 0:
  2377. self.mt[i] = self.mt[i] ^ 0x9908b0df
  2378. def seed(self, x):
  2379. assert type(x) is int
  2380. self.mt = [0] * 624
  2381. self.mt[0] = _int32(x)
  2382. self.mti = 0
  2383. for i in range(1, 624):
  2384. self.mt[i] = _int32(1812433253 * (self.mt[i - 1] ^ self.mt[i - 1] >> 30) + i)
  2385. def random(self):
  2386. return self.extract_number() / 2 ** 32
  2387. def randint(self, a, b):
  2388. assert type(a) is int and type(b) is int
  2389. assert a <= b
  2390. return int(self.random() * (b - a + 1)) + a
  2391. def uniform(self, a, b):
  2392. assert type(a) is int or type(a) is float
  2393. assert type(b) is int or type(b) is float
  2394. if a > b:
  2395. a, b = b, a
  2396. return self.random() * (b - a) + a
  2397. def shuffle(self, L):
  2398. for i in range(len(L)):
  2399. j = self.randint(i, len(L) - 1)
  2400. L[i], L[j] = L[j], L[i]
  2401. def choice(self, L):
  2402. return L[self.randint(0, len(L) - 1)]
  2403. _inst = Random()
  2404. seed = _inst.seed
  2405. random = _inst.random
  2406. randint = _inst.randint
  2407. uniform = _inst.uniform
  2408. shuffle = _inst.shuffle
  2409. choice = _inst.choice
  2410. )";
  2411. class NeedMoreLines {
  2412. public:
  2413. NeedMoreLines(bool isClassDef) : isClassDef(isClassDef) {}
  2414. bool isClassDef;
  2415. };
  2416. enum CompileMode {
  2417. EXEC_MODE,
  2418. EVAL_MODE,
  2419. SINGLE_MODE, // for REPL
  2420. JSON_MODE,
  2421. };
  2422. struct SourceMetadata {
  2423. const char* source;
  2424. _Str filename;
  2425. std::vector<const char*> lineStarts;
  2426. CompileMode mode;
  2427. _Str getLine(int lineno) const {
  2428. if(lineno == -1) return "<?>";
  2429. const char* _start = lineStarts.at(lineno-1);
  2430. const char* i = _start;
  2431. while(*i != '\n' && *i != '\0') i++;
  2432. return _Str(_start, i-_start);
  2433. }
  2434. SourceMetadata(const char* source, _Str filename, CompileMode mode) {
  2435. source = strdup(source);
  2436. // Skip utf8 BOM if there is any.
  2437. if (strncmp(source, "\xEF\xBB\xBF", 3) == 0) source += 3;
  2438. this->filename = filename;
  2439. this->source = source;
  2440. lineStarts.push_back(source);
  2441. this->mode = mode;
  2442. }
  2443. _Str snapshot(int lineno){
  2444. _StrStream ss;
  2445. ss << " " << "File \"" << filename << "\", line " << lineno << '\n';
  2446. _Str line = getLine(lineno).__lstrip();
  2447. if(line.empty()) line = "<?>";
  2448. ss << " " << line << '\n';
  2449. return ss.str();
  2450. }
  2451. ~SourceMetadata(){
  2452. free((void*)source);
  2453. }
  2454. };
  2455. typedef pkpy::shared_ptr<SourceMetadata> _Source;
  2456. class _Error : public std::exception {
  2457. private:
  2458. _Str _what;
  2459. public:
  2460. _Error(_Str type, _Str msg, _Str desc){
  2461. _what = desc + type + ": " + msg;
  2462. }
  2463. const char* what() const noexcept override {
  2464. return _what.c_str();
  2465. }
  2466. };
  2467. class CompileError : public _Error {
  2468. public:
  2469. CompileError(_Str type, _Str msg, _Str snapshot)
  2470. : _Error(type, msg, snapshot) {}
  2471. };
  2472. class RuntimeError : public _Error {
  2473. private:
  2474. static _Str __concat(std::stack<_Str> snapshots){
  2475. _StrStream ss;
  2476. ss << "Traceback (most recent call last):" << '\n';
  2477. while(!snapshots.empty()){
  2478. ss << snapshots.top();
  2479. snapshots.pop();
  2480. }
  2481. return ss.str();
  2482. }
  2483. public:
  2484. RuntimeError(_Str type, _Str msg, const std::stack<_Str>& snapshots)
  2485. : _Error(type, msg, __concat(snapshots)) {}
  2486. };
  2487. typedef int64_t _Int;
  2488. typedef double _Float;
  2489. struct CodeObject;
  2490. struct BasePointer;
  2491. class VM;
  2492. class Frame;
  2493. typedef pkpy::shared_ptr<const BasePointer> _Pointer;
  2494. typedef PyVar (*_CppFunc)(VM*, const pkpy::ArgList&);
  2495. typedef pkpy::shared_ptr<CodeObject> _Code;
  2496. struct Function {
  2497. _Str name;
  2498. _Code code;
  2499. std::vector<_Str> args;
  2500. _Str starredArg; // empty if no *arg
  2501. PyVarDict kwArgs; // empty if no k=v
  2502. std::vector<_Str> kwArgsOrder;
  2503. bool hasName(const _Str& val) const {
  2504. bool _0 = std::find(args.begin(), args.end(), val) != args.end();
  2505. bool _1 = starredArg == val;
  2506. bool _2 = kwArgs.find(val) != kwArgs.end();
  2507. return _0 || _1 || _2;
  2508. }
  2509. };
  2510. struct _BoundedMethod {
  2511. PyVar obj;
  2512. PyVar method;
  2513. };
  2514. struct _Range {
  2515. _Int start = 0;
  2516. _Int stop = -1;
  2517. _Int step = 1;
  2518. };
  2519. struct _Slice {
  2520. int start = 0;
  2521. int stop = 0x7fffffff;
  2522. void normalize(int len){
  2523. if(start < 0) start += len;
  2524. if(stop < 0) stop += len;
  2525. if(start < 0) start = 0;
  2526. if(stop > len) stop = len;
  2527. }
  2528. };
  2529. class _Iterator {
  2530. protected:
  2531. VM* vm;
  2532. PyVar _ref; // keep a reference to the object so it will not be deleted while iterating
  2533. public:
  2534. virtual PyVar next() = 0;
  2535. virtual bool hasNext() = 0;
  2536. _Pointer var;
  2537. _Iterator(VM* vm, PyVar _ref) : vm(vm), _ref(_ref) {}
  2538. virtual ~_Iterator() = default;
  2539. };
  2540. typedef pkpy::shared_ptr<Function> _Func;
  2541. typedef std::variant<PyVar,_Int,_Float,bool,_Str,PyVarList,_CppFunc,_Func,pkpy::shared_ptr<_Iterator>,_BoundedMethod,_Range,_Slice,_Pointer> _Value;
  2542. const int VALUE_SIZE = sizeof(_Value);
  2543. struct PyObject {
  2544. PyVarDict attribs;
  2545. _Value _native;
  2546. PyVar _type;
  2547. inline bool isType(const PyVar& type){
  2548. return this->_type == type;
  2549. }
  2550. inline void setType(const PyVar& type){
  2551. this->_type = type;
  2552. // this->attribs[__class__] = type;
  2553. }
  2554. // currently __name__ is only used for 'type'
  2555. _Str getName(){
  2556. _Value val = attribs[__name__]->_native;
  2557. return std::get<_Str>(val);
  2558. }
  2559. _Str getTypeName(){
  2560. return _type->getName();
  2561. }
  2562. PyObject(const _Value& val): _native(val) {}
  2563. PyObject(_Value&& val): _native(std::move(val)) {}
  2564. };
  2565. class RangeIterator : public _Iterator {
  2566. private:
  2567. _Int current;
  2568. _Range r;
  2569. public:
  2570. RangeIterator(VM* vm, PyVar _ref) : _Iterator(vm, _ref) {
  2571. this->r = std::get<_Range>(_ref->_native);
  2572. this->current = r.start;
  2573. }
  2574. bool hasNext() override {
  2575. if(r.step > 0){
  2576. return current < r.stop;
  2577. }else{
  2578. return current > r.stop;
  2579. }
  2580. }
  2581. PyVar next() override;
  2582. };
  2583. class VectorIterator : public _Iterator {
  2584. private:
  2585. size_t index = 0;
  2586. const PyVarList* vec;
  2587. public:
  2588. VectorIterator(VM* vm, PyVar _ref) : _Iterator(vm, _ref) {
  2589. vec = &std::get<PyVarList>(_ref->_native);
  2590. }
  2591. bool hasNext(){
  2592. return index < vec->size();
  2593. }
  2594. PyVar next(){
  2595. return vec->operator[](index++);
  2596. }
  2597. };
  2598. class StringIterator : public _Iterator {
  2599. private:
  2600. int index = 0;
  2601. _Str str;
  2602. public:
  2603. StringIterator(VM* vm, PyVar _ref) : _Iterator(vm, _ref) {
  2604. str = std::get<_Str>(_ref->_native);
  2605. }
  2606. bool hasNext(){
  2607. return index < str.u8_length();
  2608. }
  2609. PyVar next();
  2610. };
  2611. typedef uint8_t _TokenType;
  2612. constexpr const char* __TOKENS[] = {
  2613. "@error", "@eof", "@eol", "@sof",
  2614. ".", ",", ":", ";", "#", "(", ")", "[", "]", "{", "}", "%",
  2615. "+", "-", "*", "/", "//", "**", "=", ">", "<", "...", "->",
  2616. "<<", ">>", "&", "|", "^", "?",
  2617. "==", "!=", ">=", "<=",
  2618. "+=", "-=", "*=", "/=", "//=",
  2619. /** KW_BEGIN **/
  2620. "class", "import", "as", "def", "lambda", "pass", "del", "from", "with",
  2621. "None", "in", "is", "and", "or", "not", "True", "False", "global",
  2622. "goto", "label", // extended keywords, not available in cpython
  2623. "while", "for", "if", "elif", "else", "break", "continue", "return", "assert", "raise",
  2624. /** KW_END **/
  2625. "is not", "not in",
  2626. "@id", "@num", "@str", "@fstr",
  2627. "@indent", "@dedent"
  2628. };
  2629. const _TokenType __TOKENS_LEN = sizeof(__TOKENS) / sizeof(__TOKENS[0]);
  2630. constexpr _TokenType TK(const char* const token) {
  2631. for(int k=0; k<__TOKENS_LEN; k++){
  2632. const char* i = __TOKENS[k];
  2633. const char* j = token;
  2634. while(*i && *j && *i == *j){
  2635. i++; j++;
  2636. }
  2637. if(*i == *j) return k;
  2638. }
  2639. return 0;
  2640. }
  2641. #define TK_STR(t) __TOKENS[t]
  2642. const _TokenType __KW_BEGIN = TK("class");
  2643. const _TokenType __KW_END = TK("raise");
  2644. const emhash8::HashMap<std::string_view, _TokenType> __KW_MAP = [](){
  2645. emhash8::HashMap<std::string_view, _TokenType> map;
  2646. for(int k=__KW_BEGIN; k<=__KW_END; k++) map[__TOKENS[k]] = k;
  2647. return map;
  2648. }();
  2649. struct Token{
  2650. _TokenType type;
  2651. const char* start; //< Begining of the token in the source.
  2652. int length; //< Number of chars of the token.
  2653. int line; //< Line number of the token (1 based).
  2654. PyVar value; //< Literal value of the token.
  2655. const _Str str() const {
  2656. return _Str(start, length);
  2657. }
  2658. const _Str info() const {
  2659. _StrStream ss;
  2660. _Str raw = str();
  2661. if (raw == _Str("\n")) raw = "\\n";
  2662. ss << line << ": " << TK_STR(type) << " '" << raw << "'";
  2663. return ss.str();
  2664. }
  2665. };
  2666. enum Precedence {
  2667. PREC_NONE,
  2668. PREC_ASSIGNMENT, // =
  2669. PREC_COMMA, // ,
  2670. PREC_TERNARY, // ?:
  2671. PREC_LOGICAL_OR, // or
  2672. PREC_LOGICAL_AND, // and
  2673. PREC_EQUALITY, // == !=
  2674. PREC_TEST, // in is
  2675. PREC_COMPARISION, // < > <= >=
  2676. PREC_BITWISE_OR, // |
  2677. PREC_BITWISE_XOR, // ^
  2678. PREC_BITWISE_AND, // &
  2679. PREC_BITWISE_SHIFT, // << >>
  2680. PREC_TERM, // + -
  2681. PREC_FACTOR, // * / % //
  2682. PREC_UNARY, // - not
  2683. PREC_EXPONENT, // **
  2684. PREC_CALL, // ()
  2685. PREC_SUBSCRIPT, // []
  2686. PREC_ATTRIB, // .index
  2687. PREC_PRIMARY,
  2688. };
  2689. // The context of the parsing phase for the compiler.
  2690. struct Parser {
  2691. _Source src;
  2692. const char* token_start;
  2693. const char* current_char;
  2694. int current_line = 1;
  2695. Token previous, current;
  2696. std::queue<Token> nexts;
  2697. std::stack<int> indents;
  2698. int brackets_level_0 = 0;
  2699. int brackets_level_1 = 0;
  2700. int brackets_level_2 = 0;
  2701. Token nextToken(){
  2702. if(nexts.empty()) return makeErrToken();
  2703. Token t = nexts.front();
  2704. if(t.type == TK("@eof") && indents.size()>1){
  2705. nexts.pop();
  2706. indents.pop();
  2707. return Token{TK("@dedent"), token_start, 0, current_line};
  2708. }
  2709. nexts.pop();
  2710. return t;
  2711. }
  2712. char peekChar() {
  2713. return *current_char;
  2714. }
  2715. char peekNextChar() {
  2716. if (peekChar() == '\0') return '\0';
  2717. return *(current_char + 1);
  2718. }
  2719. int eatSpaces(){
  2720. int count = 0;
  2721. while (true) {
  2722. switch (peekChar()) {
  2723. case ' ': count++; break;
  2724. case '\t': count+=4; break;
  2725. default: return count;
  2726. }
  2727. eatChar();
  2728. }
  2729. }
  2730. bool eatIndentation(){
  2731. if(brackets_level_0 > 0 || brackets_level_1 > 0 || brackets_level_2 > 0) return true;
  2732. int spaces = eatSpaces();
  2733. // https://docs.python.org/3/reference/lexical_analysis.html#indentation
  2734. if(spaces > indents.top()){
  2735. indents.push(spaces);
  2736. nexts.push(Token{TK("@indent"), token_start, 0, current_line});
  2737. } else if(spaces < indents.top()){
  2738. while(spaces < indents.top()){
  2739. indents.pop();
  2740. nexts.push(Token{TK("@dedent"), token_start, 0, current_line});
  2741. }
  2742. if(spaces != indents.top()){
  2743. return false;
  2744. }
  2745. }
  2746. return true;
  2747. }
  2748. char eatChar() {
  2749. char c = peekChar();
  2750. if(c == '\n') throw std::runtime_error("eatChar() cannot consume a newline");
  2751. current_char++;
  2752. return c;
  2753. }
  2754. char eatCharIncludeNewLine() {
  2755. char c = peekChar();
  2756. current_char++;
  2757. if (c == '\n'){
  2758. current_line++;
  2759. src->lineStarts.push_back(current_char);
  2760. }
  2761. return c;
  2762. }
  2763. inline bool isNameStart(char c){
  2764. if(isalpha(c) || c=='_') return true;
  2765. if(!isascii(c)) return true;
  2766. return false;
  2767. }
  2768. int eatName() {
  2769. current_char--;
  2770. while(true){
  2771. uint8_t c = peekChar();
  2772. int u8bytes = 0;
  2773. if((c & 0b10000000) == 0b00000000) u8bytes = 1;
  2774. else if((c & 0b11100000) == 0b11000000) u8bytes = 2;
  2775. else if((c & 0b11110000) == 0b11100000) u8bytes = 3;
  2776. else if((c & 0b11111000) == 0b11110000) u8bytes = 4;
  2777. else return 1;
  2778. if(u8bytes == 1){
  2779. if(isalpha(c) || c=='_' || isdigit(c)) {
  2780. current_char++;
  2781. continue;
  2782. }else{
  2783. break;
  2784. }
  2785. }
  2786. // handle multibyte char
  2787. std::string u8str(current_char, u8bytes);
  2788. if(u8str.size() != u8bytes) return 2;
  2789. uint32_t value = 0;
  2790. for(int k=0; k < u8bytes; k++){
  2791. uint8_t b = u8str[k];
  2792. if(k==0){
  2793. if(u8bytes == 2) value = (b & 0b00011111) << 6;
  2794. else if(u8bytes == 3) value = (b & 0b00001111) << 12;
  2795. else if(u8bytes == 4) value = (b & 0b00000111) << 18;
  2796. }else{
  2797. value |= (b & 0b00111111) << (6*(u8bytes-k-1));
  2798. }
  2799. }
  2800. if(__isLoChar(value)) current_char += u8bytes;
  2801. else break;
  2802. }
  2803. int length = (int)(current_char - token_start);
  2804. if(length == 0) return 3;
  2805. std::string_view name(token_start, length);
  2806. if(src->mode == JSON_MODE){
  2807. if(name == "true"){
  2808. setNextToken(TK("True"));
  2809. } else if(name == "false"){
  2810. setNextToken(TK("False"));
  2811. } else if(name == "null"){
  2812. setNextToken(TK("None"));
  2813. } else {
  2814. return 4;
  2815. }
  2816. return 0;
  2817. }
  2818. if(__KW_MAP.count(name)){
  2819. if(name == "not"){
  2820. if(strncmp(current_char, " in", 3) == 0){
  2821. current_char += 3;
  2822. setNextToken(TK("not in"));
  2823. return 0;
  2824. }
  2825. }else if(name == "is"){
  2826. if(strncmp(current_char, " not", 4) == 0){
  2827. current_char += 4;
  2828. setNextToken(TK("is not"));
  2829. return 0;
  2830. }
  2831. }
  2832. setNextToken(__KW_MAP.at(name));
  2833. } else {
  2834. setNextToken(TK("@id"));
  2835. }
  2836. return 0;
  2837. }
  2838. void skipLineComment() {
  2839. char c;
  2840. while ((c = peekChar()) != '\0') {
  2841. if (c == '\n') return;
  2842. eatChar();
  2843. }
  2844. }
  2845. // If the current char is [c] consume it and advance char by 1 and returns
  2846. // true otherwise returns false.
  2847. bool matchChar(char c) {
  2848. if (peekChar() != c) return false;
  2849. eatCharIncludeNewLine();
  2850. return true;
  2851. }
  2852. // Returns an error token from the current position for reporting error.
  2853. Token makeErrToken() {
  2854. return Token{TK("@error"), token_start, (int)(current_char - token_start), current_line};
  2855. }
  2856. // Initialize the next token as the type.
  2857. void setNextToken(_TokenType type, PyVar value=nullptr) {
  2858. switch(type){
  2859. case TK("("): brackets_level_0++; break;
  2860. case TK(")"): brackets_level_0--; break;
  2861. case TK("["): brackets_level_1++; break;
  2862. case TK("]"): brackets_level_1--; break;
  2863. case TK("{"): brackets_level_2++; break;
  2864. case TK("}"): brackets_level_2--; break;
  2865. }
  2866. nexts.push( Token{
  2867. type,
  2868. token_start,
  2869. (int)(current_char - token_start),
  2870. current_line - ((type == TK("@eol")) ? 1 : 0),
  2871. value
  2872. });
  2873. }
  2874. void setNextTwoCharToken(char c, _TokenType one, _TokenType two) {
  2875. if (matchChar(c)) setNextToken(two);
  2876. else setNextToken(one);
  2877. }
  2878. Parser(_Source src) {
  2879. this->src = src;
  2880. this->token_start = src->source;
  2881. this->current_char = src->source;
  2882. this->nexts.push(Token{TK("@sof"), token_start, 0, current_line});
  2883. this->indents.push(0);
  2884. }
  2885. };
  2886. class Frame;
  2887. struct BasePointer {
  2888. virtual PyVar get(VM*, Frame*) const = 0;
  2889. virtual void set(VM*, Frame*, PyVar) const = 0;
  2890. virtual void del(VM*, Frame*) const = 0;
  2891. virtual ~BasePointer() = default;
  2892. };
  2893. enum NameScope {
  2894. NAME_LOCAL = 0,
  2895. NAME_GLOBAL = 1,
  2896. NAME_ATTR = 2,
  2897. };
  2898. struct NamePointer : BasePointer {
  2899. const _Str name;
  2900. const NameScope scope;
  2901. NamePointer(const _Str& name, NameScope scope) : name(name), scope(scope) {}
  2902. bool operator==(const NamePointer& other) const {
  2903. return name == other.name && scope == other.scope;
  2904. }
  2905. PyVar get(VM* vm, Frame* frame) const;
  2906. void set(VM* vm, Frame* frame, PyVar val) const;
  2907. void del(VM* vm, Frame* frame) const;
  2908. };
  2909. struct AttrPointer : BasePointer {
  2910. mutable PyVar obj;
  2911. const NamePointer* attr;
  2912. AttrPointer(PyVar obj, const NamePointer* attr) : obj(obj), attr(attr) {}
  2913. PyVar get(VM* vm, Frame* frame) const;
  2914. void set(VM* vm, Frame* frame, PyVar val) const;
  2915. void del(VM* vm, Frame* frame) const;
  2916. };
  2917. struct IndexPointer : BasePointer {
  2918. mutable PyVar obj;
  2919. const PyVar index;
  2920. IndexPointer(PyVar obj, PyVar index) : obj(obj), index(index) {}
  2921. PyVar get(VM* vm, Frame* frame) const;
  2922. void set(VM* vm, Frame* frame, PyVar val) const;
  2923. void del(VM* vm, Frame* frame) const;
  2924. };
  2925. struct CompoundPointer : BasePointer {
  2926. const std::vector<_Pointer> pointers;
  2927. CompoundPointer(const std::vector<_Pointer>& pointers) : pointers(pointers) {}
  2928. CompoundPointer(std::vector<_Pointer>&& pointers) : pointers(pointers) {}
  2929. PyVar get(VM* vm, Frame* frame) const;
  2930. void set(VM* vm, Frame* frame, PyVar val) const;
  2931. void del(VM* vm, Frame* frame) const;
  2932. };
  2933. struct UserPointer : BasePointer {
  2934. const _Pointer p;
  2935. uint64_t f_id;
  2936. UserPointer(_Pointer p, uint64_t f_id) : p(p), f_id(f_id) {}
  2937. PyVar get(VM* vm, Frame* frame) const;
  2938. void set(VM* vm, Frame* frame, PyVar val) const;
  2939. void del(VM* vm, Frame* frame) const;
  2940. };
  2941. enum Opcode {
  2942. #define OPCODE(name) OP_##name,
  2943. #ifdef OPCODE
  2944. OPCODE(NO_OP)
  2945. OPCODE(DELETED_OP)
  2946. OPCODE(LOAD_CONST)
  2947. OPCODE(IMPORT_NAME)
  2948. OPCODE(PRINT_EXPR)
  2949. OPCODE(POP_TOP)
  2950. OPCODE(CALL)
  2951. OPCODE(RETURN_VALUE)
  2952. OPCODE(BINARY_OP)
  2953. OPCODE(COMPARE_OP)
  2954. OPCODE(BITWISE_OP)
  2955. OPCODE(IS_OP)
  2956. OPCODE(CONTAINS_OP)
  2957. OPCODE(UNARY_NEGATIVE)
  2958. OPCODE(UNARY_NOT)
  2959. OPCODE(DUP_TOP)
  2960. OPCODE(BUILD_LIST)
  2961. OPCODE(BUILD_MAP)
  2962. OPCODE(BUILD_SLICE)
  2963. OPCODE(LIST_APPEND)
  2964. OPCODE(GET_ITER)
  2965. OPCODE(FOR_ITER)
  2966. OPCODE(POP_JUMP_IF_FALSE)
  2967. OPCODE(JUMP_ABSOLUTE)
  2968. OPCODE(SAFE_JUMP_ABSOLUTE)
  2969. OPCODE(JUMP_IF_TRUE_OR_POP)
  2970. OPCODE(JUMP_IF_FALSE_OR_POP)
  2971. // non-standard python opcodes
  2972. OPCODE(LOAD_NONE)
  2973. OPCODE(LOAD_TRUE)
  2974. OPCODE(LOAD_FALSE)
  2975. OPCODE(LOAD_EVAL_FN) // load eval() callable into stack
  2976. OPCODE(LOAD_LAMBDA) // LOAD_CONST + set __module__ attr
  2977. OPCODE(LOAD_ELLIPSIS)
  2978. OPCODE(ASSERT)
  2979. OPCODE(RAISE_ERROR)
  2980. OPCODE(STORE_FUNCTION)
  2981. OPCODE(BUILD_CLASS)
  2982. OPCODE(LOAD_NAME_PTR) // no arg
  2983. OPCODE(BUILD_ATTR_PTR) // arg for the name_ptr, [ptr, name_ptr] -> (*ptr).name_ptr
  2984. OPCODE(BUILD_INDEX_PTR) // no arg, [ptr, expr] -> (*ptr)[expr]
  2985. OPCODE(STORE_NAME_PTR) // arg for the name_ptr, [expr], directly store to the name_ptr without pushing it to the stack
  2986. OPCODE(STORE_PTR) // no arg, [ptr, expr] -> *ptr = expr
  2987. OPCODE(DELETE_PTR) // no arg, [ptr] -> [] -> delete ptr
  2988. OPCODE(BUILD_ATTR_PTR_PTR) // arg for the name_ptr, [ptr, name_ptr] -> (*ptr)->name_ptr
  2989. OPCODE(BUILD_SMART_TUPLE) // if all elements are pointers, build a compound pointer, otherwise build a tuple
  2990. OPCODE(BUILD_STRING) // arg is the expr count, build a string from the top of the stack
  2991. OPCODE(GOTO)
  2992. OPCODE(UNARY_REF) // for &
  2993. OPCODE(UNARY_DEREF) // for *
  2994. OPCODE(WITH_ENTER)
  2995. OPCODE(WITH_EXIT)
  2996. #endif
  2997. #undef OPCODE
  2998. };
  2999. static const char* OP_NAMES[] = {
  3000. #define OPCODE(name) #name,
  3001. #ifdef OPCODE
  3002. OPCODE(NO_OP)
  3003. OPCODE(DELETED_OP)
  3004. OPCODE(LOAD_CONST)
  3005. OPCODE(IMPORT_NAME)
  3006. OPCODE(PRINT_EXPR)
  3007. OPCODE(POP_TOP)
  3008. OPCODE(CALL)
  3009. OPCODE(RETURN_VALUE)
  3010. OPCODE(BINARY_OP)
  3011. OPCODE(COMPARE_OP)
  3012. OPCODE(BITWISE_OP)
  3013. OPCODE(IS_OP)
  3014. OPCODE(CONTAINS_OP)
  3015. OPCODE(UNARY_NEGATIVE)
  3016. OPCODE(UNARY_NOT)
  3017. OPCODE(DUP_TOP)
  3018. OPCODE(BUILD_LIST)
  3019. OPCODE(BUILD_MAP)
  3020. OPCODE(BUILD_SLICE)
  3021. OPCODE(LIST_APPEND)
  3022. OPCODE(GET_ITER)
  3023. OPCODE(FOR_ITER)
  3024. OPCODE(POP_JUMP_IF_FALSE)
  3025. OPCODE(JUMP_ABSOLUTE)
  3026. OPCODE(SAFE_JUMP_ABSOLUTE)
  3027. OPCODE(JUMP_IF_TRUE_OR_POP)
  3028. OPCODE(JUMP_IF_FALSE_OR_POP)
  3029. // non-standard python opcodes
  3030. OPCODE(LOAD_NONE)
  3031. OPCODE(LOAD_TRUE)
  3032. OPCODE(LOAD_FALSE)
  3033. OPCODE(LOAD_EVAL_FN) // load eval() callable into stack
  3034. OPCODE(LOAD_LAMBDA) // LOAD_CONST + set __module__ attr
  3035. OPCODE(LOAD_ELLIPSIS)
  3036. OPCODE(ASSERT)
  3037. OPCODE(RAISE_ERROR)
  3038. OPCODE(STORE_FUNCTION)
  3039. OPCODE(BUILD_CLASS)
  3040. OPCODE(LOAD_NAME_PTR) // no arg
  3041. OPCODE(BUILD_ATTR_PTR) // arg for the name_ptr, [ptr, name_ptr] -> (*ptr).name_ptr
  3042. OPCODE(BUILD_INDEX_PTR) // no arg, [ptr, expr] -> (*ptr)[expr]
  3043. OPCODE(STORE_NAME_PTR) // arg for the name_ptr, [expr], directly store to the name_ptr without pushing it to the stack
  3044. OPCODE(STORE_PTR) // no arg, [ptr, expr] -> *ptr = expr
  3045. OPCODE(DELETE_PTR) // no arg, [ptr] -> [] -> delete ptr
  3046. OPCODE(BUILD_ATTR_PTR_PTR) // arg for the name_ptr, [ptr, name_ptr] -> (*ptr)->name_ptr
  3047. OPCODE(BUILD_SMART_TUPLE) // if all elements are pointers, build a compound pointer, otherwise build a tuple
  3048. OPCODE(BUILD_STRING) // arg is the expr count, build a string from the top of the stack
  3049. OPCODE(GOTO)
  3050. OPCODE(UNARY_REF) // for &
  3051. OPCODE(UNARY_DEREF) // for *
  3052. OPCODE(WITH_ENTER)
  3053. OPCODE(WITH_EXIT)
  3054. #endif
  3055. #undef OPCODE
  3056. };
  3057. struct ByteCode{
  3058. uint8_t op;
  3059. int arg;
  3060. uint16_t line;
  3061. };
  3062. _Str pad(const _Str& s, const int n){
  3063. return s + std::string(n - s.size(), ' ');
  3064. }
  3065. struct CodeObject {
  3066. _Source src;
  3067. _Str name;
  3068. CodeObject(_Source src, _Str name) {
  3069. this->src = src;
  3070. this->name = name;
  3071. }
  3072. CompileMode mode() const {
  3073. return src->mode;
  3074. }
  3075. std::vector<ByteCode> co_code;
  3076. PyVarList co_consts;
  3077. std::vector<NamePointer> co_names;
  3078. std::vector<_Str> co_global_names;
  3079. // for goto use
  3080. // note: some opcodes moves the bytecode, such as listcomp
  3081. // goto/label should be put at toplevel statements
  3082. emhash8::HashMap<_Str, int> co_labels;
  3083. void addLabel(const _Str& label){
  3084. if(co_labels.find(label) != co_labels.end()){
  3085. _Str msg = "label '" + label + "' already exists";
  3086. throw std::runtime_error(msg.c_str());
  3087. }
  3088. co_labels[label] = co_code.size();
  3089. }
  3090. int addName(_Str name, NameScope scope){
  3091. name.intern();
  3092. if(scope == NAME_LOCAL && std::find(co_global_names.begin(), co_global_names.end(), name) != co_global_names.end()){
  3093. scope = NAME_GLOBAL;
  3094. }
  3095. auto p = NamePointer(name, scope);
  3096. for(int i=0; i<co_names.size(); i++){
  3097. if(co_names[i] == p) return i;
  3098. }
  3099. co_names.push_back(p);
  3100. return co_names.size() - 1;
  3101. }
  3102. int addConst(PyVar v){
  3103. co_consts.push_back(v);
  3104. return co_consts.size() - 1;
  3105. }
  3106. void __moveToEnd(int start, int end){
  3107. auto _start = co_code.begin() + start;
  3108. auto _end = co_code.begin() + end;
  3109. co_code.insert(co_code.end(), _start, _end);
  3110. for(int i=start; i<end; i++) co_code[i].op = OP_DELETED_OP;
  3111. }
  3112. _Str toString(){
  3113. _StrStream ss;
  3114. int prev_line = -1;
  3115. for(int i=0; i<co_code.size(); i++){
  3116. const ByteCode& byte = co_code[i];
  3117. if(byte.op == OP_NO_OP) continue;
  3118. _Str line = std::to_string(byte.line);
  3119. if(byte.line == prev_line) line = "";
  3120. else{
  3121. if(prev_line != -1) ss << "\n";
  3122. prev_line = byte.line;
  3123. }
  3124. ss << pad(line, 12) << " " << pad(std::to_string(i), 3);
  3125. ss << " " << pad(OP_NAMES[byte.op], 20) << " ";
  3126. ss << (byte.arg == -1 ? "" : std::to_string(byte.arg));
  3127. if(i != co_code.size() - 1) ss << '\n';
  3128. }
  3129. _StrStream consts;
  3130. consts << "co_consts: ";
  3131. for(int i=0; i<co_consts.size(); i++){
  3132. consts << co_consts[i]->getTypeName();
  3133. if(i != co_consts.size() - 1) consts << ", ";
  3134. }
  3135. _StrStream names;
  3136. names << "co_names: ";
  3137. for(int i=0; i<co_names.size(); i++){
  3138. names << co_names[i].name;
  3139. if(i != co_names.size() - 1) names << ", ";
  3140. }
  3141. ss << '\n' << consts.str() << '\n' << names.str() << '\n';
  3142. for(int i=0; i<co_consts.size(); i++){
  3143. auto fn = std::get_if<_Func>(&co_consts[i]->_native);
  3144. if(fn) ss << '\n' << (*fn)->code->name << ":\n" << (*fn)->code->toString();
  3145. }
  3146. return _Str(ss.str());
  3147. }
  3148. };
  3149. class Frame {
  3150. private:
  3151. std::vector<PyVar> s_data;
  3152. int ip = 0;
  3153. std::stack<int> forLoops; // record the FOR_ITER bytecode index
  3154. public:
  3155. const CodeObject* code;
  3156. PyVar _module;
  3157. PyVarDict f_locals;
  3158. uint64_t id;
  3159. inline PyVarDict& f_globals(){
  3160. return _module->attribs;
  3161. }
  3162. Frame(const CodeObject* code, PyVar _module, const PyVarDict& locals)
  3163. : code(code), _module(_module), f_locals(locals) {
  3164. static uint64_t frame_id = 1;
  3165. id = frame_id++;
  3166. }
  3167. inline const ByteCode& readCode() {
  3168. return code->co_code[ip++];
  3169. }
  3170. _Str errorSnapshot(){
  3171. int line = code->co_code[ip-1].line;
  3172. return code->src->snapshot(line);
  3173. }
  3174. inline int stackSize() const {
  3175. return s_data.size();
  3176. }
  3177. inline bool isCodeEnd() const {
  3178. return ip >= code->co_code.size();
  3179. }
  3180. inline PyVar __pop(){
  3181. if(s_data.empty()) throw std::runtime_error("s_data.empty() is true");
  3182. PyVar v = std::move(s_data.back());
  3183. s_data.pop_back();
  3184. return v;
  3185. }
  3186. inline PyVar __deref_pointer(VM*, PyVar);
  3187. inline PyVar popValue(VM* vm){
  3188. return __deref_pointer(vm, __pop());
  3189. }
  3190. inline PyVar topValue(VM* vm){
  3191. if(s_data.empty()) throw std::runtime_error("s_data.empty() is true");
  3192. return __deref_pointer(vm, s_data.back());
  3193. }
  3194. inline PyVar& __top(){
  3195. if(s_data.empty()) throw std::runtime_error("s_data.empty() is true");
  3196. return s_data.back();
  3197. }
  3198. inline PyVar __topValueN(VM* vm, int n=-1){
  3199. return __deref_pointer(vm, s_data[s_data.size() + n]);
  3200. }
  3201. inline void push(const PyVar& v){
  3202. s_data.push_back(v);
  3203. }
  3204. inline void push(PyVar&& v){
  3205. s_data.emplace_back(std::move(v));
  3206. }
  3207. void __reportForIter(){
  3208. int lastIp = ip - 1;
  3209. if(forLoops.empty()) forLoops.push(lastIp);
  3210. else{
  3211. if(forLoops.top() == lastIp) return;
  3212. if(forLoops.top() < lastIp) forLoops.push(lastIp);
  3213. else UNREACHABLE();
  3214. }
  3215. }
  3216. inline void jump(int i){
  3217. this->ip = i;
  3218. }
  3219. void safeJump(int i){
  3220. this->ip = i;
  3221. while(!forLoops.empty()){
  3222. int start = forLoops.top();
  3223. int end = code->co_code[start].arg;
  3224. if(i < start || i >= end){
  3225. //printf("%d <- [%d, %d)\n", i, start, end);
  3226. __pop(); // pop the iterator
  3227. forLoops.pop();
  3228. }else{
  3229. break;
  3230. }
  3231. }
  3232. }
  3233. pkpy::ArgList popNValuesReversed(VM* vm, int n){
  3234. pkpy::ArgList v(n);
  3235. for(int i=n-1; i>=0; i--) v._index(i) = popValue(vm);
  3236. return v;
  3237. }
  3238. pkpy::ArgList __popNReversed(int n){
  3239. pkpy::ArgList v(n);
  3240. for(int i=n-1; i>=0; i--) v._index(i) = __pop();
  3241. return v;
  3242. }
  3243. };
  3244. #define __DEF_PY_AS_C(type, ctype, ptype) \
  3245. inline ctype& Py##type##_AS_C(const PyVar& obj) { \
  3246. __checkType(obj, ptype); \
  3247. return std::get<ctype>(obj->_native); \
  3248. }
  3249. #define __DEF_PY(type, ctype, ptype) \
  3250. inline PyVar Py##type(ctype value) { \
  3251. return newObject(ptype, value); \
  3252. }
  3253. #define DEF_NATIVE(type, ctype, ptype) \
  3254. __DEF_PY(type, ctype, ptype) \
  3255. __DEF_PY_AS_C(type, ctype, ptype)
  3256. typedef void(*PrintFn)(const VM*, const char*);
  3257. class VM {
  3258. std::atomic<bool> _stopFlag = false;
  3259. std::vector<PyVar> _smallIntegers; // [-5, 256]
  3260. protected:
  3261. std::deque< pkpy::unique_ptr<Frame> > callstack;
  3262. PyVarDict _modules; // loaded modules
  3263. std::map<_Str, _Code> _lazyModules; // lazy loaded modules
  3264. PyVar __py2py_call_signal;
  3265. void _checkStopFlag(){
  3266. if(_stopFlag){
  3267. _stopFlag = false;
  3268. _error("KeyboardInterrupt", "");
  3269. }
  3270. }
  3271. PyVar runFrame(Frame* frame){
  3272. while(!frame->isCodeEnd()){
  3273. const ByteCode& byte = frame->readCode();
  3274. //printf("[%d] %s (%d)\n", frame->stackSize(), OP_NAMES[byte.op], byte.arg);
  3275. //printf("%s\n", frame->code->src->getLine(byte.line).c_str());
  3276. _checkStopFlag();
  3277. switch (byte.op)
  3278. {
  3279. case OP_NO_OP: break; // do nothing
  3280. case OP_LOAD_CONST: frame->push(frame->code->co_consts[byte.arg]); break;
  3281. case OP_LOAD_LAMBDA: {
  3282. PyVar obj = frame->code->co_consts[byte.arg];
  3283. setAttr(obj, __module__, frame->_module);
  3284. frame->push(obj);
  3285. } break;
  3286. case OP_LOAD_NAME_PTR: {
  3287. frame->push(PyPointer(
  3288. pkpy::make_shared<const BasePointer, NamePointer>(frame->code->co_names[byte.arg])
  3289. ));
  3290. } break;
  3291. case OP_STORE_NAME_PTR: {
  3292. const auto& p = frame->code->co_names[byte.arg];
  3293. p.set(this, frame, frame->popValue(this));
  3294. } break;
  3295. case OP_BUILD_ATTR_PTR: {
  3296. const auto& attr = frame->code->co_names[byte.arg];
  3297. PyVar obj = frame->popValue(this);
  3298. frame->push(PyPointer(
  3299. pkpy::make_shared<const BasePointer, AttrPointer>(obj, &attr)
  3300. ));
  3301. } break;
  3302. case OP_BUILD_ATTR_PTR_PTR: {
  3303. const auto& attr = frame->code->co_names[byte.arg];
  3304. PyVar obj = frame->popValue(this);
  3305. __checkType(obj, _tp_user_pointer);
  3306. const _Pointer& p = std::get<_Pointer>(obj->_native);
  3307. frame->push(PyPointer(
  3308. pkpy::make_shared<const BasePointer, AttrPointer>(p->get(this, frame), &attr)
  3309. ));
  3310. } break;
  3311. case OP_BUILD_INDEX_PTR: {
  3312. PyVar index = frame->popValue(this);
  3313. PyVar obj = frame->popValue(this);
  3314. frame->push(PyPointer(
  3315. pkpy::make_shared<const BasePointer, IndexPointer>(obj, index)
  3316. ));
  3317. } break;
  3318. case OP_STORE_PTR: {
  3319. PyVar obj = frame->popValue(this);
  3320. const _Pointer p = PyPointer_AS_C(frame->__pop());
  3321. p->set(this, frame, std::move(obj));
  3322. } break;
  3323. case OP_DELETE_PTR: {
  3324. const _Pointer p = PyPointer_AS_C(frame->__pop());
  3325. p->del(this, frame);
  3326. } break;
  3327. case OP_BUILD_SMART_TUPLE:
  3328. {
  3329. pkpy::ArgList items = frame->__popNReversed(byte.arg);
  3330. bool done = false;
  3331. for(int i=0; i<items.size(); i++){
  3332. if(!items[i]->isType(_tp_pointer)) {
  3333. done = true;
  3334. PyVarList values(items.size());
  3335. for(int i=0; i<items.size(); i++){
  3336. values[i] = frame->__deref_pointer(this, items[i]);
  3337. }
  3338. frame->push(PyTuple(values));
  3339. break;
  3340. }
  3341. }
  3342. if(done) break;
  3343. std::vector<_Pointer> pointers(items.size());
  3344. for(int i=0; i<items.size(); i++)
  3345. pointers[i] = PyPointer_AS_C(items[i]);
  3346. frame->push(PyPointer(
  3347. pkpy::make_shared<const BasePointer, CompoundPointer>(std::move(pointers))
  3348. ));
  3349. } break;
  3350. case OP_BUILD_STRING:
  3351. {
  3352. pkpy::ArgList items = frame->popNValuesReversed(this, byte.arg);
  3353. _StrStream ss;
  3354. for(int i=0; i<items.size(); i++) ss << PyStr_AS_C(asStr(items[i]));
  3355. frame->push(PyStr(ss.str()));
  3356. } break;
  3357. case OP_LOAD_EVAL_FN: {
  3358. frame->push(builtins->attribs["eval"_c]);
  3359. } break;
  3360. case OP_LIST_APPEND: {
  3361. pkpy::ArgList args(2);
  3362. args[1] = frame->popValue(this); // obj
  3363. args[0] = frame->__topValueN(this, -2); // list
  3364. fastCall("append"_c, std::move(args));
  3365. } break;
  3366. case OP_STORE_FUNCTION:
  3367. {
  3368. PyVar obj = frame->popValue(this);
  3369. const _Func& fn = PyFunction_AS_C(obj);
  3370. setAttr(obj, __module__, frame->_module);
  3371. frame->f_globals()[fn->name] = obj;
  3372. } break;
  3373. case OP_BUILD_CLASS:
  3374. {
  3375. const _Str& clsName = frame->code->co_names[byte.arg].name;
  3376. PyVar clsBase = frame->popValue(this);
  3377. if(clsBase == None) clsBase = _tp_object;
  3378. __checkType(clsBase, _tp_type);
  3379. PyVar cls = newUserClassType(clsName, clsBase);
  3380. while(true){
  3381. PyVar fn = frame->popValue(this);
  3382. if(fn == None) break;
  3383. const _Func& f = PyFunction_AS_C(fn);
  3384. setAttr(fn, __module__, frame->_module);
  3385. setAttr(cls, f->name, fn);
  3386. }
  3387. frame->f_globals()[clsName] = cls;
  3388. } break;
  3389. case OP_RETURN_VALUE: return frame->popValue(this);
  3390. case OP_PRINT_EXPR:
  3391. {
  3392. const PyVar expr = frame->topValue(this);
  3393. if(expr == None) break;
  3394. *_stdout << PyStr_AS_C(asRepr(expr)) << '\n';
  3395. } break;
  3396. case OP_POP_TOP: frame->popValue(this); break;
  3397. case OP_BINARY_OP:
  3398. {
  3399. pkpy::ArgList args = frame->popNValuesReversed(this, 2);
  3400. frame->push(fastCall(BINARY_SPECIAL_METHODS[byte.arg], std::move(args)));
  3401. } break;
  3402. case OP_BITWISE_OP:
  3403. {
  3404. pkpy::ArgList args = frame->popNValuesReversed(this, 2);
  3405. frame->push(fastCall(BITWISE_SPECIAL_METHODS[byte.arg], std::move(args)));
  3406. } break;
  3407. case OP_COMPARE_OP:
  3408. {
  3409. pkpy::ArgList args = frame->popNValuesReversed(this, 2);
  3410. // for __ne__ we use the negation of __eq__
  3411. int op = byte.arg == 3 ? 2 : byte.arg;
  3412. PyVar res = fastCall(CMP_SPECIAL_METHODS[op], std::move(args));
  3413. if(op != byte.arg) res = PyBool(!PyBool_AS_C(res));
  3414. frame->push(std::move(res));
  3415. } break;
  3416. case OP_IS_OP:
  3417. {
  3418. bool ret_c = frame->popValue(this) == frame->popValue(this);
  3419. if(byte.arg == 1) ret_c = !ret_c;
  3420. frame->push(PyBool(ret_c));
  3421. } break;
  3422. case OP_CONTAINS_OP:
  3423. {
  3424. PyVar rhs = frame->popValue(this);
  3425. PyVar lhs = frame->popValue(this);
  3426. bool ret_c = PyBool_AS_C(call(rhs, __contains__, {std::move(lhs)}));
  3427. if(byte.arg == 1) ret_c = !ret_c;
  3428. frame->push(PyBool(ret_c));
  3429. } break;
  3430. case OP_UNARY_NEGATIVE:
  3431. {
  3432. PyVar obj = frame->popValue(this);
  3433. frame->push(numNegated(obj));
  3434. } break;
  3435. case OP_UNARY_NOT:
  3436. {
  3437. PyVar obj = frame->popValue(this);
  3438. const PyVar& obj_bool = asBool(obj);
  3439. frame->push(PyBool(!PyBool_AS_C(obj_bool)));
  3440. } break;
  3441. case OP_UNARY_REF:
  3442. {
  3443. // _pointer to pointer
  3444. const _Pointer p = PyPointer_AS_C(frame->__pop());
  3445. frame->push(newObject(
  3446. _tp_user_pointer,
  3447. pkpy::make_shared<const BasePointer, UserPointer>(p, frame->id)
  3448. ));
  3449. } break;
  3450. case OP_UNARY_DEREF:
  3451. {
  3452. // pointer to _pointer
  3453. PyVar obj = frame->popValue(this);
  3454. __checkType(obj, _tp_user_pointer);
  3455. frame->push(PyPointer(std::get<_Pointer>(obj->_native)));
  3456. } break;
  3457. case OP_POP_JUMP_IF_FALSE:
  3458. if(!PyBool_AS_C(asBool(frame->popValue(this)))) frame->jump(byte.arg);
  3459. break;
  3460. case OP_LOAD_NONE: frame->push(None); break;
  3461. case OP_LOAD_TRUE: frame->push(True); break;
  3462. case OP_LOAD_FALSE: frame->push(False); break;
  3463. case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); break;
  3464. case OP_ASSERT:
  3465. {
  3466. PyVar expr = frame->popValue(this);
  3467. _assert(PyBool_AS_C(expr), "assertion failed");
  3468. } break;
  3469. case OP_RAISE_ERROR:
  3470. {
  3471. _Str msg = PyStr_AS_C(asRepr(frame->popValue(this)));
  3472. _Str type = PyStr_AS_C(frame->popValue(this));
  3473. _error(type, msg);
  3474. } break;
  3475. case OP_BUILD_LIST:
  3476. {
  3477. pkpy::ArgList items = frame->popNValuesReversed(this, byte.arg);
  3478. frame->push(PyList(items.toList()));
  3479. } break;
  3480. case OP_BUILD_MAP:
  3481. {
  3482. pkpy::ArgList items = frame->popNValuesReversed(this, byte.arg*2);
  3483. PyVar obj = call(builtins->attribs["dict"], {});
  3484. for(int i=0; i<items.size(); i+=2){
  3485. call(obj, __setitem__, {items[i], items[i+1]});
  3486. }
  3487. frame->push(obj);
  3488. } break;
  3489. case OP_DUP_TOP: frame->push(frame->topValue(this)); break;
  3490. case OP_CALL:
  3491. {
  3492. pkpy::ArgList args = frame->popNValuesReversed(this, byte.arg);
  3493. PyVar callable = frame->popValue(this);
  3494. PyVar ret = call(std::move(callable), std::move(args), true);
  3495. if(ret == __py2py_call_signal) return ret;
  3496. frame->push(std::move(ret));
  3497. } break;
  3498. case OP_JUMP_ABSOLUTE: frame->jump(byte.arg); break;
  3499. case OP_SAFE_JUMP_ABSOLUTE: frame->safeJump(byte.arg); break;
  3500. case OP_GOTO: {
  3501. PyVar obj = frame->popValue(this);
  3502. const _Str& label = PyStr_AS_C(obj);
  3503. auto it = frame->code->co_labels.find(label);
  3504. if(it == frame->code->co_labels.end()){
  3505. _error("KeyError", "label '" + label + "' not found");
  3506. }
  3507. frame->safeJump(it->second);
  3508. } break;
  3509. case OP_GET_ITER:
  3510. {
  3511. PyVar obj = frame->popValue(this);
  3512. PyVarOrNull iter_fn = getAttr(obj, __iter__, false);
  3513. if(iter_fn != nullptr){
  3514. PyVar tmp = call(iter_fn, {obj});
  3515. PyIter_AS_C(tmp)->var = std::move(PyPointer_AS_C(frame->__pop()));
  3516. frame->push(std::move(tmp));
  3517. }else{
  3518. typeError("'" + obj->getTypeName() + "' object is not iterable");
  3519. }
  3520. } break;
  3521. case OP_FOR_ITER:
  3522. {
  3523. frame->__reportForIter();
  3524. // __top() must be PyIter, so no need to __deref()
  3525. auto& it = PyIter_AS_C(frame->__top());
  3526. if(it->hasNext()){
  3527. it->var->set(this, frame, it->next());
  3528. }
  3529. else{
  3530. frame->safeJump(byte.arg);
  3531. }
  3532. } break;
  3533. case OP_JUMP_IF_FALSE_OR_POP:
  3534. {
  3535. const PyVar expr = frame->topValue(this);
  3536. if(asBool(expr)==False) frame->jump(byte.arg);
  3537. else frame->popValue(this);
  3538. } break;
  3539. case OP_JUMP_IF_TRUE_OR_POP:
  3540. {
  3541. const PyVar expr = frame->topValue(this);
  3542. if(asBool(expr)==True) frame->jump(byte.arg);
  3543. else frame->popValue(this);
  3544. } break;
  3545. case OP_BUILD_SLICE:
  3546. {
  3547. PyVar stop = frame->popValue(this);
  3548. PyVar start = frame->popValue(this);
  3549. _Slice s;
  3550. if(start != None) {__checkType(start, _tp_int); s.start = (int)PyInt_AS_C(start);}
  3551. if(stop != None) {__checkType(stop, _tp_int); s.stop = (int)PyInt_AS_C(stop);}
  3552. frame->push(PySlice(s));
  3553. } break;
  3554. case OP_IMPORT_NAME:
  3555. {
  3556. const _Str& name = frame->code->co_names[byte.arg].name;
  3557. auto it = _modules.find(name);
  3558. if(it == _modules.end()){
  3559. auto it2 = _lazyModules.find(name);
  3560. if(it2 == _lazyModules.end()){
  3561. _error("ImportError", "module '" + name + "' not found");
  3562. }else{
  3563. _Code code = it2->second;
  3564. PyVar _m = newModule(name);
  3565. _exec(code, _m, {});
  3566. frame->push(_m);
  3567. _lazyModules.erase(it2);
  3568. }
  3569. }else{
  3570. frame->push(it->second);
  3571. }
  3572. } break;
  3573. case OP_WITH_ENTER:
  3574. {
  3575. PyVar obj = frame->popValue(this);
  3576. PyVar enter_fn = getAttr(obj, "__enter__"_c);
  3577. call(enter_fn, {});
  3578. } break;
  3579. case OP_WITH_EXIT:
  3580. {
  3581. PyVar obj = frame->popValue(this);
  3582. PyVar exit_fn = getAttr(obj, "__exit__"_c);
  3583. call(exit_fn, {});
  3584. } break;
  3585. default:
  3586. systemError(_Str("opcode ") + OP_NAMES[byte.op] + " is not implemented");
  3587. break;
  3588. }
  3589. }
  3590. if(frame->code->src->mode == EVAL_MODE || frame->code->src->mode == JSON_MODE){
  3591. if(frame->stackSize() != 1) systemError("stack size is not 1 in EVAL_MODE/JSON_MODE");
  3592. return frame->popValue(this);
  3593. }
  3594. if(frame->stackSize() != 0) systemError("stack not empty in EXEC_MODE");
  3595. return None;
  3596. }
  3597. public:
  3598. PyVarDict _types;
  3599. PyVar None, True, False, Ellipsis;
  3600. bool use_stdio;
  3601. std::ostream* _stdout;
  3602. std::ostream* _stderr;
  3603. PyVar builtins; // builtins module
  3604. PyVar _main; // __main__ module
  3605. int maxRecursionDepth = 1000;
  3606. VM(bool use_stdio){
  3607. this->use_stdio = use_stdio;
  3608. if(use_stdio){
  3609. std::cout.setf(std::ios::unitbuf);
  3610. std::cerr.setf(std::ios::unitbuf);
  3611. this->_stdout = &std::cout;
  3612. this->_stderr = &std::cerr;
  3613. }else{
  3614. this->_stdout = new _StrStream();
  3615. this->_stderr = new _StrStream();
  3616. }
  3617. initializeBuiltinClasses();
  3618. _smallIntegers.reserve(300);
  3619. for(_Int i=-5; i<=256; i++) _smallIntegers.push_back(newObject(_tp_int, i));
  3620. }
  3621. void keyboardInterrupt(){
  3622. _stopFlag = true;
  3623. }
  3624. void sleepForSecs(_Float sec){
  3625. _Int ms = (_Int)(sec * 1000);
  3626. for(_Int i=0; i<ms; i+=20){
  3627. _checkStopFlag();
  3628. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  3629. }
  3630. }
  3631. PyVar asStr(const PyVar& obj){
  3632. PyVarOrNull str_fn = getAttr(obj, __str__, false);
  3633. if(str_fn != nullptr) return call(str_fn, {});
  3634. return asRepr(obj);
  3635. }
  3636. Frame* __findFrame(uint64_t up_f_id){
  3637. for(auto it=callstack.crbegin(); it!=callstack.crend(); ++it){
  3638. uint64_t f_id = it->get()->id;
  3639. if(f_id == up_f_id) return it->get();
  3640. if(f_id < up_f_id) return nullptr;
  3641. }
  3642. return nullptr;
  3643. }
  3644. Frame* topFrame(){
  3645. if(callstack.size() == 0) UNREACHABLE();
  3646. return callstack.back().get();
  3647. }
  3648. PyVar asRepr(const PyVar& obj){
  3649. if(obj->isType(_tp_type)) return PyStr("<class '" + obj->getName() + "'>");
  3650. return call(obj, __repr__, {});
  3651. }
  3652. PyVar asJson(const PyVar& obj){
  3653. return call(obj, __json__, {});
  3654. }
  3655. const PyVar& asBool(const PyVar& obj){
  3656. if(obj == None) return False;
  3657. if(obj->_type == _tp_bool) return obj;
  3658. if(obj->_type == _tp_int) return PyBool(PyInt_AS_C(obj) != 0);
  3659. if(obj->_type == _tp_float) return PyBool(PyFloat_AS_C(obj) != 0.0);
  3660. PyVarOrNull len_fn = getAttr(obj, __len__, false);
  3661. if(len_fn != nullptr){
  3662. PyVar ret = call(std::move(len_fn), {});
  3663. return PyBool(PyInt_AS_C(ret) > 0);
  3664. }
  3665. return True;
  3666. }
  3667. PyVar fastCall(const _Str& name, pkpy::ArgList&& args){
  3668. const PyVar& obj = args[0];
  3669. PyObject* cls = obj->_type.get();
  3670. while(cls != None.get()) {
  3671. auto it = cls->attribs.find(name);
  3672. if(it != cls->attribs.end()){
  3673. return call(it->second, args);
  3674. }
  3675. cls = cls->attribs[__base__].get();
  3676. }
  3677. attributeError(obj, name);
  3678. return nullptr;
  3679. }
  3680. PyVar call(const PyVar& _callable, pkpy::ArgList args, bool opCall=false){
  3681. if(_callable->isType(_tp_type)){
  3682. auto it = _callable->attribs.find(__new__);
  3683. PyVar obj;
  3684. if(it != _callable->attribs.end()){
  3685. obj = call(it->second, args);
  3686. }else{
  3687. obj = newObject(_callable, (_Int)-1);
  3688. PyVarOrNull init_fn = getAttr(obj, __init__, false);
  3689. if (init_fn != nullptr) call(init_fn, args);
  3690. }
  3691. return obj;
  3692. }
  3693. const PyVar* callable = &_callable;
  3694. if((*callable)->isType(_tp_bounded_method)){
  3695. auto& bm = PyBoundedMethod_AS_C((*callable));
  3696. // TODO: avoid insertion here, bad performance
  3697. pkpy::ArgList new_args(args.size()+1);
  3698. new_args[0] = bm.obj;
  3699. for(int i=0; i<args.size(); i++) new_args[i+1] = args[i];
  3700. callable = &bm.method;
  3701. args = std::move(new_args);
  3702. }
  3703. if((*callable)->isType(_tp_native_function)){
  3704. const auto& f = std::get<_CppFunc>((*callable)->_native);
  3705. return f(this, args);
  3706. } else if((*callable)->isType(_tp_function)){
  3707. const _Func& fn = PyFunction_AS_C((*callable));
  3708. PyVarDict locals;
  3709. int i = 0;
  3710. for(const auto& name : fn->args){
  3711. if(i < args.size()) {
  3712. locals[name] = args[i++];
  3713. }else{
  3714. typeError("missing positional argument '" + name + "'");
  3715. }
  3716. }
  3717. // handle *args
  3718. if(!fn->starredArg.empty()){
  3719. PyVarList vargs;
  3720. while(i < args.size()) vargs.push_back(args[i++]);
  3721. locals[fn->starredArg] = PyTuple(vargs);
  3722. }
  3723. // handle keyword arguments
  3724. for(const _Str& name : fn->kwArgsOrder){
  3725. if(i < args.size()) {
  3726. locals[name] = args[i++];
  3727. }else{
  3728. locals[name] = fn->kwArgs[name];
  3729. }
  3730. }
  3731. if(i < args.size()) typeError("too many arguments");
  3732. auto it_m = (*callable)->attribs.find(__module__);
  3733. PyVar _module = it_m != (*callable)->attribs.end() ? it_m->second : topFrame()->_module;
  3734. if(opCall){
  3735. __pushNewFrame(fn->code, _module, locals);
  3736. return __py2py_call_signal;
  3737. }
  3738. return _exec(fn->code, _module, locals);
  3739. }
  3740. typeError("'" + (*callable)->getTypeName() + "' object is not callable");
  3741. return None;
  3742. }
  3743. inline PyVar call(const PyVar& obj, const _Str& func, const pkpy::ArgList& args){
  3744. return call(getAttr(obj, func), args);
  3745. }
  3746. inline PyVar call(const PyVar& obj, const _Str& func, pkpy::ArgList&& args){
  3747. return call(getAttr(obj, func), args);
  3748. }
  3749. // repl mode is only for setting `frame->id` to 0
  3750. virtual PyVarOrNull exec(const _Code& code, PyVar _module=nullptr){
  3751. if(_module == nullptr) _module = _main;
  3752. try {
  3753. return _exec(code, _module, {});
  3754. } catch (const std::exception& e) {
  3755. if(dynamic_cast<const _Error*>(&e)){
  3756. *_stderr << e.what() << '\n';
  3757. }else{
  3758. auto re = RuntimeError("UnexpectedError", e.what(), _cleanErrorAndGetSnapshots());
  3759. *_stderr << re.what() << '\n';
  3760. }
  3761. return nullptr;
  3762. }
  3763. }
  3764. virtual void execAsync(const _Code& code) {
  3765. exec(code);
  3766. }
  3767. Frame* __pushNewFrame(const _Code& code, PyVar _module, const PyVarDict& locals){
  3768. if(code == nullptr) UNREACHABLE();
  3769. if(callstack.size() > maxRecursionDepth){
  3770. throw RuntimeError("RecursionError", "maximum recursion depth exceeded", _cleanErrorAndGetSnapshots());
  3771. }
  3772. Frame* frame = new Frame(code.get(), _module, locals);
  3773. callstack.emplace_back(pkpy::unique_ptr<Frame>(frame));
  3774. return frame;
  3775. }
  3776. PyVar _exec(const _Code& code, PyVar _module, const PyVarDict& locals){
  3777. Frame* frame = __pushNewFrame(code, _module, locals);
  3778. if(code->mode() == SINGLE_MODE) frame->id = 0;
  3779. Frame* frameBase = frame;
  3780. PyVar ret = nullptr;
  3781. while(true){
  3782. ret = runFrame(frame);
  3783. if(ret != __py2py_call_signal){
  3784. if(frame == frameBase){ // [ frameBase<- ]
  3785. break;
  3786. }else{
  3787. callstack.pop_back();
  3788. frame = callstack.back().get();
  3789. frame->push(ret);
  3790. }
  3791. }else{
  3792. frame = callstack.back().get(); // [ frameBase, newFrame<- ]
  3793. }
  3794. }
  3795. callstack.pop_back();
  3796. return ret;
  3797. }
  3798. PyVar newUserClassType(_Str name, PyVar base){
  3799. PyVar obj = newClassType(name, base);
  3800. setAttr(obj, __name__, PyStr(name));
  3801. _types.erase(name);
  3802. return obj;
  3803. }
  3804. PyVar newClassType(_Str name, PyVar base=nullptr) {
  3805. if(base == nullptr) base = _tp_object;
  3806. PyVar obj = pkpy::make_shared<PyObject>((_Int)0);
  3807. obj->setType(_tp_type);
  3808. setAttr(obj, __base__, base);
  3809. _types[name] = obj;
  3810. return obj;
  3811. }
  3812. PyVar newObject(PyVar type, const _Value& _native) {
  3813. __checkType(type, _tp_type);
  3814. PyVar obj = pkpy::make_shared<PyObject>(_native);
  3815. obj->setType(type);
  3816. return obj;
  3817. }
  3818. PyVar newModule(_Str name) {
  3819. PyVar obj = newObject(_tp_module, (_Int)-2);
  3820. setAttr(obj, __name__, PyStr(name));
  3821. _modules[name] = obj;
  3822. return obj;
  3823. }
  3824. void addLazyModule(_Str name, _Code code){
  3825. _lazyModules[name] = code;
  3826. }
  3827. PyVarOrNull getAttr(const PyVar& obj, const _Str& name, bool throw_err=true) {
  3828. PyVarDict::iterator it;
  3829. PyObject* cls;
  3830. if(obj->isType(_tp_super)){
  3831. const PyVar* root = &obj;
  3832. int depth = 1;
  3833. while(true){
  3834. root = &std::get<PyVar>((*root)->_native);
  3835. if(!(*root)->isType(_tp_super)) break;
  3836. depth++;
  3837. }
  3838. cls = (*root)->_type.get();
  3839. for(int i=0; i<depth; i++) cls = cls->attribs[__base__].get();
  3840. it = (*root)->attribs.find(name);
  3841. if(it != (*root)->attribs.end()) return it->second;
  3842. }else{
  3843. it = obj->attribs.find(name);
  3844. if(it != obj->attribs.end()) return it->second;
  3845. cls = obj->_type.get();
  3846. }
  3847. while(cls != None.get()) {
  3848. it = cls->attribs.find(name);
  3849. if(it != cls->attribs.end()){
  3850. PyVar valueFromCls = it->second;
  3851. if(valueFromCls->isType(_tp_function) || valueFromCls->isType(_tp_native_function)){
  3852. return PyBoundedMethod({obj, std::move(valueFromCls)});
  3853. }else{
  3854. return valueFromCls;
  3855. }
  3856. }
  3857. cls = cls->attribs[__base__].get();
  3858. }
  3859. if(throw_err) attributeError(obj, name);
  3860. return nullptr;
  3861. }
  3862. void setAttr(PyVar& obj, const _Str& name, const PyVar& value) {
  3863. if(obj->isType(_tp_super)){
  3864. const PyVar* root = &obj;
  3865. while(true){
  3866. root = &std::get<PyVar>((*root)->_native);
  3867. if(!(*root)->isType(_tp_super)) break;
  3868. }
  3869. (*root)->attribs[name] = value;
  3870. }else{
  3871. obj->attribs[name] = value;
  3872. }
  3873. }
  3874. void setAttr(PyVar& obj, const _Str& name, PyVar&& value) {
  3875. if(obj->isType(_tp_super)){
  3876. const PyVar* root = &obj;
  3877. while(true){
  3878. root = &std::get<PyVar>((*root)->_native);
  3879. if(!(*root)->isType(_tp_super)) break;
  3880. }
  3881. (*root)->attribs[name] = std::move(value);
  3882. }else{
  3883. obj->attribs[name] = std::move(value);
  3884. }
  3885. }
  3886. void bindMethod(_Str typeName, _Str funcName, _CppFunc fn) {
  3887. funcName.intern();
  3888. PyVar type = _types[typeName];
  3889. PyVar func = PyNativeFunction(fn);
  3890. setAttr(type, funcName, func);
  3891. }
  3892. void bindMethodMulti(std::vector<_Str> typeNames, _Str funcName, _CppFunc fn) {
  3893. for(auto& typeName : typeNames){
  3894. bindMethod(typeName, funcName, fn);
  3895. }
  3896. }
  3897. void bindBuiltinFunc(_Str funcName, _CppFunc fn) {
  3898. bindFunc(builtins, funcName, fn);
  3899. }
  3900. void bindFunc(PyVar module, _Str funcName, _CppFunc fn) {
  3901. funcName.intern();
  3902. __checkType(module, _tp_module);
  3903. PyVar func = PyNativeFunction(fn);
  3904. setAttr(module, funcName, func);
  3905. }
  3906. bool isInstance(PyVar obj, PyVar type){
  3907. __checkType(type, _tp_type);
  3908. PyVar t = obj->_type;
  3909. while (t != None){
  3910. if (t == type) return true;
  3911. t = t->attribs[__base__];
  3912. }
  3913. return false;
  3914. }
  3915. inline bool isIntOrFloat(const PyVar& obj){
  3916. return obj->isType(_tp_int) || obj->isType(_tp_float);
  3917. }
  3918. inline bool isIntOrFloat(const PyVar& obj1, const PyVar& obj2){
  3919. return isIntOrFloat(obj1) && isIntOrFloat(obj2);
  3920. }
  3921. inline _Float numToFloat(const PyVar& obj){
  3922. if (obj->isType(_tp_int)){
  3923. return (_Float)PyInt_AS_C(obj);
  3924. }else if(obj->isType(_tp_float)){
  3925. return PyFloat_AS_C(obj);
  3926. }
  3927. UNREACHABLE();
  3928. }
  3929. PyVar numNegated(const PyVar& obj){
  3930. if (obj->isType(_tp_int)){
  3931. return PyInt(-PyInt_AS_C(obj));
  3932. }else if(obj->isType(_tp_float)){
  3933. return PyFloat(-PyFloat_AS_C(obj));
  3934. }
  3935. typeError("unsupported operand type(s) for -");
  3936. return nullptr;
  3937. }
  3938. int normalizedIndex(int index, int size){
  3939. if(index < 0) index += size;
  3940. if(index < 0 || index >= size){
  3941. indexError("index out of range, " + std::to_string(index) + " not in [0, " + std::to_string(size) + ")");
  3942. }
  3943. return index;
  3944. }
  3945. // for quick access
  3946. PyVar _tp_object, _tp_type, _tp_int, _tp_float, _tp_bool, _tp_str;
  3947. PyVar _tp_list, _tp_tuple;
  3948. PyVar _tp_function, _tp_native_function, _tp_native_iterator, _tp_bounded_method;
  3949. PyVar _tp_slice, _tp_range, _tp_module, _tp_pointer;
  3950. PyVar _tp_user_pointer, _tp_super;
  3951. __DEF_PY(Pointer, _Pointer, _tp_pointer)
  3952. inline _Pointer& PyPointer_AS_C(const PyVar& obj)
  3953. {
  3954. if(!obj->isType(_tp_pointer)) typeError("expected an l-value");
  3955. return std::get<_Pointer>(obj->_native);
  3956. }
  3957. __DEF_PY_AS_C(Int, _Int, _tp_int)
  3958. inline PyVar PyInt(_Int value) {
  3959. if(value >= -5 && value <= 256) return _smallIntegers[value + 5];
  3960. return newObject(_tp_int, value);
  3961. }
  3962. DEF_NATIVE(Float, _Float, _tp_float)
  3963. DEF_NATIVE(Str, _Str, _tp_str)
  3964. DEF_NATIVE(List, PyVarList, _tp_list)
  3965. DEF_NATIVE(Tuple, PyVarList, _tp_tuple)
  3966. DEF_NATIVE(Function, _Func, _tp_function)
  3967. DEF_NATIVE(NativeFunction, _CppFunc, _tp_native_function)
  3968. DEF_NATIVE(Iter, pkpy::shared_ptr<_Iterator>, _tp_native_iterator)
  3969. DEF_NATIVE(BoundedMethod, _BoundedMethod, _tp_bounded_method)
  3970. DEF_NATIVE(Range, _Range, _tp_range)
  3971. DEF_NATIVE(Slice, _Slice, _tp_slice)
  3972. // there is only one True/False, so no need to copy them!
  3973. inline bool PyBool_AS_C(const PyVar& obj){return obj == True;}
  3974. inline const PyVar& PyBool(bool value){return value ? True : False;}
  3975. void initializeBuiltinClasses(){
  3976. _tp_object = pkpy::make_shared<PyObject>((_Int)0);
  3977. _tp_type = pkpy::make_shared<PyObject>((_Int)0);
  3978. _types["object"] = _tp_object;
  3979. _types["type"] = _tp_type;
  3980. _tp_bool = newClassType("bool");
  3981. _tp_int = newClassType("int");
  3982. _tp_float = newClassType("float");
  3983. _tp_str = newClassType("str");
  3984. _tp_list = newClassType("list");
  3985. _tp_tuple = newClassType("tuple");
  3986. _tp_slice = newClassType("slice");
  3987. _tp_range = newClassType("range");
  3988. _tp_module = newClassType("module");
  3989. _tp_pointer = newClassType("_pointer");
  3990. _tp_user_pointer = newClassType("pointer");
  3991. newClassType("NoneType");
  3992. newClassType("ellipsis");
  3993. _tp_function = newClassType("function");
  3994. _tp_native_function = newClassType("_native_function");
  3995. _tp_native_iterator = newClassType("_native_iterator");
  3996. _tp_bounded_method = newClassType("_bounded_method");
  3997. _tp_super = newClassType("super");
  3998. this->None = newObject(_types["NoneType"], (_Int)0);
  3999. this->Ellipsis = newObject(_types["ellipsis"], (_Int)0);
  4000. this->True = newObject(_tp_bool, true);
  4001. this->False = newObject(_tp_bool, false);
  4002. this->builtins = newModule("builtins");
  4003. this->_main = newModule("__main__"_c);
  4004. setAttr(_tp_type, __base__, _tp_object);
  4005. _tp_type->setType(_tp_type);
  4006. setAttr(_tp_object, __base__, None);
  4007. _tp_object->setType(_tp_type);
  4008. for (auto& [name, type] : _types) {
  4009. setAttr(type, __name__, PyStr(name));
  4010. }
  4011. this->__py2py_call_signal = newObject(_tp_object, (_Int)7);
  4012. std::vector<_Str> publicTypes = {"type", "object", "bool", "int", "float", "str", "list", "tuple", "range"};
  4013. for (auto& name : publicTypes) {
  4014. setAttr(builtins, name, _types[name]);
  4015. }
  4016. }
  4017. _Int hash(const PyVar& obj){
  4018. if (obj->isType(_tp_int)) return PyInt_AS_C(obj);
  4019. if (obj->isType(_tp_bool)) return PyBool_AS_C(obj) ? 1 : 0;
  4020. if (obj->isType(_tp_float)){
  4021. _Float val = PyFloat_AS_C(obj);
  4022. return (_Int)std::hash<_Float>()(val);
  4023. }
  4024. if (obj->isType(_tp_str)) return PyStr_AS_C(obj).hash();
  4025. if (obj->isType(_tp_type)) return (_Int)obj.get();
  4026. if (obj->isType(_tp_tuple)) {
  4027. _Int x = 1000003;
  4028. for (const auto& item : PyTuple_AS_C(obj)) {
  4029. _Int y = hash(item);
  4030. // this is recommended by Github Copilot
  4031. // i am not sure whether it is a good idea
  4032. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2));
  4033. }
  4034. return x;
  4035. }
  4036. typeError("unhashable type: " + obj->getTypeName());
  4037. return 0;
  4038. }
  4039. /***** Error Reporter *****/
  4040. private:
  4041. void _error(const _Str& name, const _Str& msg){
  4042. throw RuntimeError(name, msg, _cleanErrorAndGetSnapshots());
  4043. }
  4044. std::stack<_Str> _cleanErrorAndGetSnapshots(){
  4045. std::stack<_Str> snapshots;
  4046. while (!callstack.empty()){
  4047. if(snapshots.size() < 8){
  4048. snapshots.push(callstack.back()->errorSnapshot());
  4049. }
  4050. callstack.pop_back();
  4051. }
  4052. return snapshots;
  4053. }
  4054. public:
  4055. void typeError(const _Str& msg){
  4056. _error("TypeError", msg);
  4057. }
  4058. void systemError(const _Str& msg){
  4059. _error("SystemError", msg);
  4060. }
  4061. void nullPointerError(){
  4062. _error("NullPointerError", "pointer is invalid");
  4063. }
  4064. void zeroDivisionError(){
  4065. _error("ZeroDivisionError", "division by zero");
  4066. }
  4067. void indexError(const _Str& msg){
  4068. _error("IndexError", msg);
  4069. }
  4070. void valueError(const _Str& msg){
  4071. _error("ValueError", msg);
  4072. }
  4073. void nameError(const _Str& name){
  4074. _error("NameError", "name '" + name + "' is not defined");
  4075. }
  4076. void attributeError(PyVar obj, const _Str& name){
  4077. _error("AttributeError", "type '" + obj->getTypeName() + "' has no attribute '" + name + "'");
  4078. }
  4079. inline void __checkType(const PyVar& obj, const PyVar& type){
  4080. if(!obj->isType(type)) typeError("expected '" + type->getName() + "', but got '" + obj->getTypeName() + "'");
  4081. }
  4082. inline void __checkArgSize(const pkpy::ArgList& args, int size, bool method=false){
  4083. if(args.size() == size) return;
  4084. if(method) typeError(args.size()>size ? "too many arguments" : "too few arguments");
  4085. else typeError("expected " + std::to_string(size) + " arguments, but got " + std::to_string(args.size()));
  4086. }
  4087. void _assert(bool val, const _Str& msg){
  4088. if (!val) _error("AssertionError", msg);
  4089. }
  4090. virtual ~VM() {
  4091. if(!use_stdio){
  4092. delete _stdout;
  4093. delete _stderr;
  4094. }
  4095. }
  4096. };
  4097. /***** Pointers' Impl *****/
  4098. PyVar NamePointer::get(VM* vm, Frame* frame) const{
  4099. auto it = frame->f_locals.find(name);
  4100. if(it != frame->f_locals.end()) return it->second;
  4101. it = frame->f_globals().find(name);
  4102. if(it != frame->f_globals().end()) return it->second;
  4103. it = vm->builtins->attribs.find(name);
  4104. if(it != vm->builtins->attribs.end()) return it->second;
  4105. vm->nameError(name);
  4106. return nullptr;
  4107. }
  4108. void NamePointer::set(VM* vm, Frame* frame, PyVar val) const{
  4109. switch(scope) {
  4110. case NAME_LOCAL: frame->f_locals[name] = std::move(val); break;
  4111. case NAME_GLOBAL:
  4112. {
  4113. if(frame->f_locals.count(name) > 0){
  4114. frame->f_locals[name] = std::move(val);
  4115. }else{
  4116. frame->f_globals()[name] = std::move(val);
  4117. }
  4118. } break;
  4119. default: UNREACHABLE();
  4120. }
  4121. }
  4122. void NamePointer::del(VM* vm, Frame* frame) const{
  4123. switch(scope) {
  4124. case NAME_LOCAL: {
  4125. if(frame->f_locals.count(name) > 0){
  4126. frame->f_locals.erase(name);
  4127. }else{
  4128. vm->nameError(name);
  4129. }
  4130. } break;
  4131. case NAME_GLOBAL:
  4132. {
  4133. if(frame->f_locals.count(name) > 0){
  4134. frame->f_locals.erase(name);
  4135. }else{
  4136. if(frame->f_globals().count(name) > 0){
  4137. frame->f_globals().erase(name);
  4138. }else{
  4139. vm->nameError(name);
  4140. }
  4141. }
  4142. } break;
  4143. default: UNREACHABLE();
  4144. }
  4145. }
  4146. PyVar AttrPointer::get(VM* vm, Frame* frame) const{
  4147. return vm->getAttr(obj, attr->name);
  4148. }
  4149. void AttrPointer::set(VM* vm, Frame* frame, PyVar val) const{
  4150. vm->setAttr(obj, attr->name, val);
  4151. }
  4152. void AttrPointer::del(VM* vm, Frame* frame) const{
  4153. vm->typeError("cannot delete attribute");
  4154. }
  4155. PyVar IndexPointer::get(VM* vm, Frame* frame) const{
  4156. return vm->call(obj, __getitem__, {index});
  4157. }
  4158. void IndexPointer::set(VM* vm, Frame* frame, PyVar val) const{
  4159. vm->call(obj, __setitem__, {index, val});
  4160. }
  4161. void IndexPointer::del(VM* vm, Frame* frame) const{
  4162. vm->call(obj, __delitem__, {index});
  4163. }
  4164. PyVar CompoundPointer::get(VM* vm, Frame* frame) const{
  4165. PyVarList args(pointers.size());
  4166. for (int i = 0; i < pointers.size(); i++) {
  4167. args[i] = pointers[i]->get(vm, frame);
  4168. }
  4169. return vm->PyTuple(args);
  4170. }
  4171. void CompoundPointer::set(VM* vm, Frame* frame, PyVar val) const{
  4172. if(!val->isType(vm->_tp_tuple) && !val->isType(vm->_tp_list)){
  4173. vm->typeError("only tuple or list can be unpacked");
  4174. }
  4175. const PyVarList& args = std::get<PyVarList>(val->_native);
  4176. if(args.size() > pointers.size()) vm->valueError("too many values to unpack");
  4177. if(args.size() < pointers.size()) vm->valueError("not enough values to unpack");
  4178. for (int i = 0; i < pointers.size(); i++) {
  4179. pointers[i]->set(vm, frame, args[i]);
  4180. }
  4181. }
  4182. void CompoundPointer::del(VM* vm, Frame* frame) const{
  4183. for (auto& ptr : pointers) ptr->del(vm, frame);
  4184. }
  4185. PyVar UserPointer::get(VM* vm, Frame* frame) const{
  4186. frame = vm->__findFrame(f_id);
  4187. if(frame == nullptr) vm->nullPointerError();
  4188. return p->get(vm, frame);
  4189. }
  4190. void UserPointer::set(VM* vm, Frame* frame, PyVar val) const{
  4191. frame = vm->__findFrame(f_id);
  4192. if(frame == nullptr) vm->nullPointerError();
  4193. p->set(vm, frame, val);
  4194. }
  4195. void UserPointer::del(VM* vm, Frame* frame) const{
  4196. vm->typeError("delete is unsupported");
  4197. }
  4198. /***** Frame's Impl *****/
  4199. inline PyVar Frame::__deref_pointer(VM* vm, PyVar v){
  4200. if(v->isType(vm->_tp_pointer)) return vm->PyPointer_AS_C(v)->get(vm, this);
  4201. return v;
  4202. }
  4203. /***** Iterators' Impl *****/
  4204. PyVar RangeIterator::next(){
  4205. PyVar val = vm->PyInt(current);
  4206. current += r.step;
  4207. return val;
  4208. }
  4209. PyVar StringIterator::next(){
  4210. return vm->PyStr(str.u8_getitem(index++));
  4211. }
  4212. enum ThreadState {
  4213. THREAD_READY,
  4214. THREAD_RUNNING,
  4215. THREAD_SUSPENDED,
  4216. THREAD_FINISHED
  4217. };
  4218. class ThreadedVM : public VM {
  4219. std::thread* _thread = nullptr;
  4220. std::atomic<ThreadState> _state = THREAD_READY;
  4221. _Str _sharedStr = ""_c;
  4222. void __deleteThread(){
  4223. if(_thread != nullptr){
  4224. terminate();
  4225. _thread->join();
  4226. delete _thread;
  4227. _thread = nullptr;
  4228. }
  4229. }
  4230. public:
  4231. ThreadedVM(bool use_stdio) : VM(use_stdio) {
  4232. bindBuiltinFunc("__string_channel_call", [](VM* vm, const pkpy::ArgList& args){
  4233. vm->__checkArgSize(args, 1);
  4234. _Str data = vm->PyStr_AS_C(args[0]);
  4235. ThreadedVM* tvm = (ThreadedVM*)vm;
  4236. tvm->_sharedStr = data;
  4237. tvm->suspend();
  4238. return tvm->PyStr(tvm->readJsonRpcRequest());
  4239. });
  4240. }
  4241. void terminate(){
  4242. if(_state == THREAD_RUNNING || _state == THREAD_SUSPENDED){
  4243. keyboardInterrupt();
  4244. while(_state != THREAD_FINISHED);
  4245. }
  4246. }
  4247. void suspend(){
  4248. if(_state != THREAD_RUNNING) UNREACHABLE();
  4249. _state = THREAD_SUSPENDED;
  4250. while(_state == THREAD_SUSPENDED) _checkStopFlag();
  4251. }
  4252. _Str readJsonRpcRequest(){
  4253. _Str copy = _sharedStr;
  4254. _sharedStr = ""_c;
  4255. return copy;
  4256. }
  4257. /***** For outer use *****/
  4258. ThreadState getState(){
  4259. return _state;
  4260. }
  4261. void writeJsonrpcResponse(const char* value){
  4262. if(_state != THREAD_SUSPENDED) UNREACHABLE();
  4263. _sharedStr = _Str(value);
  4264. _state = THREAD_RUNNING;
  4265. }
  4266. void execAsync(const _Code& code) override {
  4267. if(_state != THREAD_READY) UNREACHABLE();
  4268. __deleteThread();
  4269. _thread = new std::thread([this, code](){
  4270. this->_state = THREAD_RUNNING;
  4271. VM::exec(code);
  4272. this->_state = THREAD_FINISHED;
  4273. });
  4274. }
  4275. PyVarOrNull exec(const _Code& code, PyVar _module = nullptr) override {
  4276. if(_state == THREAD_READY) return VM::exec(code, _module);
  4277. auto callstackBackup = std::move(callstack);
  4278. callstack.clear();
  4279. PyVarOrNull ret = VM::exec(code, _module);
  4280. callstack = std::move(callstackBackup);
  4281. return ret;
  4282. }
  4283. void resetState(){
  4284. if(this->_state != THREAD_FINISHED) return;
  4285. this->_state = THREAD_READY;
  4286. }
  4287. ~ThreadedVM(){
  4288. __deleteThread();
  4289. }
  4290. };
  4291. class Compiler;
  4292. typedef void (Compiler::*GrammarFn)();
  4293. typedef void (Compiler::*CompilerAction)();
  4294. struct GrammarRule{
  4295. GrammarFn prefix;
  4296. GrammarFn infix;
  4297. Precedence precedence;
  4298. };
  4299. struct Loop {
  4300. int start;
  4301. std::vector<int> breaks;
  4302. Loop(int start) : start(start) {}
  4303. };
  4304. class Compiler {
  4305. public:
  4306. pkpy::unique_ptr<Parser> parser;
  4307. std::stack<_Code> codes;
  4308. std::stack<Loop> loops;
  4309. bool isCompilingClass = false;
  4310. VM* vm;
  4311. emhash8::HashMap<_TokenType, GrammarRule> rules;
  4312. _Code getCode() {
  4313. return codes.top();
  4314. }
  4315. CompileMode mode() {
  4316. return parser->src->mode;
  4317. }
  4318. Loop& getLoop() {
  4319. return loops.top();
  4320. }
  4321. Compiler(VM* vm, const char* source, _Str filename, CompileMode mode){
  4322. this->vm = vm;
  4323. this->parser = pkpy::make_unique<Parser>(
  4324. pkpy::make_shared<SourceMetadata>(source, filename, mode)
  4325. );
  4326. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  4327. #define METHOD(name) &Compiler::name
  4328. #define NO_INFIX nullptr, PREC_NONE
  4329. for(_TokenType i=0; i<__TOKENS_LEN; i++) rules[i] = { nullptr, NO_INFIX };
  4330. rules[TK(".")] = { nullptr, METHOD(exprAttrib), PREC_ATTRIB };
  4331. rules[TK("->")] = { nullptr, METHOD(exprAttribPtr), PREC_ATTRIB };
  4332. rules[TK("(")] = { METHOD(exprGrouping), METHOD(exprCall), PREC_CALL };
  4333. rules[TK("[")] = { METHOD(exprList), METHOD(exprSubscript), PREC_SUBSCRIPT };
  4334. rules[TK("{")] = { METHOD(exprMap), NO_INFIX };
  4335. rules[TK("%")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  4336. rules[TK("+")] = { nullptr, METHOD(exprBinaryOp), PREC_TERM };
  4337. rules[TK("-")] = { METHOD(exprUnaryOp), METHOD(exprBinaryOp), PREC_TERM };
  4338. rules[TK("*")] = { METHOD(exprUnaryOp), METHOD(exprBinaryOp), PREC_FACTOR };
  4339. rules[TK("/")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  4340. rules[TK("//")] = { nullptr, METHOD(exprBinaryOp), PREC_FACTOR };
  4341. rules[TK("**")] = { nullptr, METHOD(exprBinaryOp), PREC_EXPONENT };
  4342. rules[TK(">")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  4343. rules[TK("<")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  4344. rules[TK("==")] = { nullptr, METHOD(exprBinaryOp), PREC_EQUALITY };
  4345. rules[TK("!=")] = { nullptr, METHOD(exprBinaryOp), PREC_EQUALITY };
  4346. rules[TK(">=")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  4347. rules[TK("<=")] = { nullptr, METHOD(exprBinaryOp), PREC_COMPARISION };
  4348. rules[TK("in")] = { nullptr, METHOD(exprBinaryOp), PREC_TEST };
  4349. rules[TK("is")] = { nullptr, METHOD(exprBinaryOp), PREC_TEST };
  4350. rules[TK("not in")] = { nullptr, METHOD(exprBinaryOp), PREC_TEST };
  4351. rules[TK("is not")] = { nullptr, METHOD(exprBinaryOp), PREC_TEST };
  4352. rules[TK("and") ] = { nullptr, METHOD(exprAnd), PREC_LOGICAL_AND };
  4353. rules[TK("or")] = { nullptr, METHOD(exprOr), PREC_LOGICAL_OR };
  4354. rules[TK("not")] = { METHOD(exprUnaryOp), nullptr, PREC_UNARY };
  4355. rules[TK("True")] = { METHOD(exprValue), NO_INFIX };
  4356. rules[TK("False")] = { METHOD(exprValue), NO_INFIX };
  4357. rules[TK("lambda")] = { METHOD(exprLambda), NO_INFIX };
  4358. rules[TK("None")] = { METHOD(exprValue), NO_INFIX };
  4359. rules[TK("...")] = { METHOD(exprValue), NO_INFIX };
  4360. rules[TK("@id")] = { METHOD(exprName), NO_INFIX };
  4361. rules[TK("@num")] = { METHOD(exprLiteral), NO_INFIX };
  4362. rules[TK("@str")] = { METHOD(exprLiteral), NO_INFIX };
  4363. rules[TK("@fstr")] = { METHOD(exprFString), NO_INFIX };
  4364. rules[TK("?")] = { nullptr, METHOD(exprTernary), PREC_TERNARY };
  4365. rules[TK("=")] = { nullptr, METHOD(exprAssign), PREC_ASSIGNMENT };
  4366. rules[TK("+=")] = { nullptr, METHOD(exprAssign), PREC_ASSIGNMENT };
  4367. rules[TK("-=")] = { nullptr, METHOD(exprAssign), PREC_ASSIGNMENT };
  4368. rules[TK("*=")] = { nullptr, METHOD(exprAssign), PREC_ASSIGNMENT };
  4369. rules[TK("/=")] = { nullptr, METHOD(exprAssign), PREC_ASSIGNMENT };
  4370. rules[TK("//=")] = { nullptr, METHOD(exprAssign), PREC_ASSIGNMENT };
  4371. rules[TK(",")] = { nullptr, METHOD(exprComma), PREC_COMMA };
  4372. rules[TK("<<")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_SHIFT };
  4373. rules[TK(">>")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_SHIFT };
  4374. rules[TK("&")] = { METHOD(exprUnaryOp), METHOD(exprBinaryOp), PREC_BITWISE_AND };
  4375. rules[TK("|")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_OR };
  4376. rules[TK("^")] = { nullptr, METHOD(exprBinaryOp), PREC_BITWISE_XOR };
  4377. #undef METHOD
  4378. #undef NO_INFIX
  4379. #define EXPR() parsePrecedence(PREC_TERNARY) // no '=' and ',' just a simple expression
  4380. #define EXPR_TUPLE() parsePrecedence(PREC_COMMA) // no '=', but ',' is allowed
  4381. #define EXPR_ANY() parsePrecedence(PREC_ASSIGNMENT)
  4382. }
  4383. _Str eatStringUntil(char quote) {
  4384. std::vector<char> buff;
  4385. while (true) {
  4386. char c = parser->eatCharIncludeNewLine();
  4387. if (c == quote) break;
  4388. if (c == '\0' || c == '\n') syntaxError("EOL while scanning string literal");
  4389. if (c == '\\') {
  4390. switch (parser->eatCharIncludeNewLine()) {
  4391. case '"': buff.push_back('"'); break;
  4392. case '\'': buff.push_back('\''); break;
  4393. case '\\': buff.push_back('\\'); break;
  4394. case 'n': buff.push_back('\n'); break;
  4395. case 'r': buff.push_back('\r'); break;
  4396. case 't': buff.push_back('\t'); break;
  4397. case '\n': case '\r': break;
  4398. default: syntaxError("invalid escape character");
  4399. }
  4400. } else {
  4401. buff.push_back(c);
  4402. }
  4403. }
  4404. return _Str(buff.data(), buff.size());
  4405. }
  4406. void eatString(char quote, bool fstr) {
  4407. _Str s = eatStringUntil(quote);
  4408. if(fstr){
  4409. parser->setNextToken(TK("@fstr"), vm->PyStr(s));
  4410. }else{
  4411. parser->setNextToken(TK("@str"), vm->PyStr(s));
  4412. }
  4413. }
  4414. void eatNumber() {
  4415. static const std::regex pattern("^(0x)?[0-9a-f]+(\\.[0-9]+)?");
  4416. std::smatch m;
  4417. const char* i = parser->token_start;
  4418. while(*i != '\n' && *i != '\0') i++;
  4419. std::string s = std::string(parser->token_start, i);
  4420. try{
  4421. if (std::regex_search(s, m, pattern)) {
  4422. // here is m.length()-1, since the first char is eaten by lexToken()
  4423. for(int j=0; j<m.length()-1; j++) parser->eatChar();
  4424. int base = 10;
  4425. size_t size;
  4426. if (m[1].matched) base = 16;
  4427. if (m[2].matched) {
  4428. if(base == 16) syntaxError("hex literal should not contain a dot");
  4429. parser->setNextToken(TK("@num"), vm->PyFloat(std::stod(m[0], &size)));
  4430. } else {
  4431. parser->setNextToken(TK("@num"), vm->PyInt(std::stoll(m[0], &size, base)));
  4432. }
  4433. if (size != m.length()) throw std::runtime_error("length mismatch");
  4434. }
  4435. }catch(std::exception& _){
  4436. syntaxError("invalid number literal");
  4437. }
  4438. }
  4439. // Lex the next token and set it as the next token.
  4440. void lexToken() {
  4441. parser->previous = parser->current;
  4442. parser->current = parser->nextToken();
  4443. //_Str _info = parser->current.info(); printf("%s\n", (const char*)_info);
  4444. while (parser->peekChar() != '\0') {
  4445. parser->token_start = parser->current_char;
  4446. char c = parser->eatCharIncludeNewLine();
  4447. switch (c) {
  4448. case '\'': case '"': eatString(c, false); return;
  4449. case '#': parser->skipLineComment(); break;
  4450. case '{': parser->setNextToken(TK("{")); return;
  4451. case '}': parser->setNextToken(TK("}")); return;
  4452. case ',': parser->setNextToken(TK(",")); return;
  4453. case ':': parser->setNextToken(TK(":")); return;
  4454. case ';': parser->setNextToken(TK(";")); return;
  4455. case '(': parser->setNextToken(TK("(")); return;
  4456. case ')': parser->setNextToken(TK(")")); return;
  4457. case '[': parser->setNextToken(TK("[")); return;
  4458. case ']': parser->setNextToken(TK("]")); return;
  4459. case '%': parser->setNextToken(TK("%")); return;
  4460. case '&': parser->setNextToken(TK("&")); return;
  4461. case '|': parser->setNextToken(TK("|")); return;
  4462. case '^': parser->setNextToken(TK("^")); return;
  4463. case '?': parser->setNextToken(TK("?")); return;
  4464. case '.': {
  4465. if(parser->matchChar('.')) {
  4466. if(parser->matchChar('.')) {
  4467. parser->setNextToken(TK("..."));
  4468. } else {
  4469. syntaxError("invalid token '..'");
  4470. }
  4471. } else {
  4472. parser->setNextToken(TK("."));
  4473. }
  4474. return;
  4475. }
  4476. case '=': parser->setNextTwoCharToken('=', TK("="), TK("==")); return;
  4477. case '+': parser->setNextTwoCharToken('=', TK("+"), TK("+=")); return;
  4478. case '>': {
  4479. if(parser->matchChar('=')) parser->setNextToken(TK(">="));
  4480. else if(parser->matchChar('>')) parser->setNextToken(TK(">>"));
  4481. else parser->setNextToken(TK(">"));
  4482. return;
  4483. }
  4484. case '<': {
  4485. if(parser->matchChar('=')) parser->setNextToken(TK("<="));
  4486. else if(parser->matchChar('<')) parser->setNextToken(TK("<<"));
  4487. else parser->setNextToken(TK("<"));
  4488. return;
  4489. }
  4490. case '-': {
  4491. if(parser->matchChar('=')) parser->setNextToken(TK("-="));
  4492. else if(parser->matchChar('>')) parser->setNextToken(TK("->"));
  4493. else parser->setNextToken(TK("-"));
  4494. return;
  4495. }
  4496. case '!':
  4497. if(parser->matchChar('=')) parser->setNextToken(TK("!="));
  4498. else syntaxError("expected '=' after '!'");
  4499. break;
  4500. case '*':
  4501. if (parser->matchChar('*')) {
  4502. parser->setNextToken(TK("**")); // '**'
  4503. } else {
  4504. parser->setNextTwoCharToken('=', TK("*"), TK("*="));
  4505. }
  4506. return;
  4507. case '/':
  4508. if(parser->matchChar('/')) {
  4509. parser->setNextTwoCharToken('=', TK("//"), TK("//="));
  4510. } else {
  4511. parser->setNextTwoCharToken('=', TK("/"), TK("/="));
  4512. }
  4513. return;
  4514. case '\r': break; // just ignore '\r'
  4515. case ' ': case '\t': parser->eatSpaces(); break;
  4516. case '\n': {
  4517. parser->setNextToken(TK("@eol")); while(parser->matchChar('\n'));
  4518. if(!parser->eatIndentation()) indentationError("unindent does not match any outer indentation level");
  4519. return;
  4520. }
  4521. default: {
  4522. if(c == 'f'){
  4523. if(parser->matchChar('\'')) {eatString('\'', true); return;}
  4524. if(parser->matchChar('"')) {eatString('"', true); return;}
  4525. }
  4526. if (isdigit(c)) {
  4527. eatNumber();
  4528. } else if (parser->isNameStart(c)) {
  4529. int ret = parser->eatName();
  4530. if(ret!=0) syntaxError("identifier is illegal, err " + std::to_string(ret));
  4531. } else {
  4532. syntaxError("unknown character: " + std::string(1, c));
  4533. }
  4534. return;
  4535. }
  4536. }
  4537. }
  4538. parser->token_start = parser->current_char;
  4539. parser->setNextToken(TK("@eof"));
  4540. }
  4541. _TokenType peek() {
  4542. return parser->current.type;
  4543. }
  4544. bool match(_TokenType expected) {
  4545. if (peek() != expected) return false;
  4546. lexToken();
  4547. return true;
  4548. }
  4549. void consume(_TokenType expected) {
  4550. if (!match(expected)){
  4551. _StrStream ss;
  4552. ss << "expected '" << TK_STR(expected) << "', but got '" << TK_STR(peek()) << "'";
  4553. syntaxError(ss.str());
  4554. }
  4555. }
  4556. bool matchNewLines(bool repl_throw=false) {
  4557. bool consumed = false;
  4558. if (peek() == TK("@eol")) {
  4559. while (peek() == TK("@eol")) lexToken();
  4560. consumed = true;
  4561. }
  4562. if (repl_throw && peek() == TK("@eof")){
  4563. throw NeedMoreLines(isCompilingClass);
  4564. }
  4565. return consumed;
  4566. }
  4567. bool matchEndStatement() {
  4568. if (match(TK(";"))) {
  4569. matchNewLines();
  4570. return true;
  4571. }
  4572. if (matchNewLines() || peek() == TK("@eof"))
  4573. return true;
  4574. if (peek() == TK("@dedent")) return true;
  4575. return false;
  4576. }
  4577. void consumeEndStatement() {
  4578. if (!matchEndStatement()) syntaxError("expected statement end");
  4579. }
  4580. void exprLiteral() {
  4581. PyVar value = parser->previous.value;
  4582. int index = getCode()->addConst(value);
  4583. emitCode(OP_LOAD_CONST, index);
  4584. }
  4585. void exprFString() {
  4586. static const std::regex pattern(R"(\{(.*?)\})");
  4587. PyVar value = parser->previous.value;
  4588. std::string s = vm->PyStr_AS_C(value).str();
  4589. std::sregex_iterator begin(s.begin(), s.end(), pattern);
  4590. std::sregex_iterator end;
  4591. int size = 0;
  4592. int i = 0;
  4593. for(auto it = begin; it != end; it++) {
  4594. std::smatch m = *it;
  4595. if (i < m.position()) {
  4596. std::string literal = s.substr(i, m.position() - i);
  4597. emitCode(OP_LOAD_CONST, getCode()->addConst(vm->PyStr(literal)));
  4598. size++;
  4599. }
  4600. emitCode(OP_LOAD_EVAL_FN);
  4601. emitCode(OP_LOAD_CONST, getCode()->addConst(vm->PyStr(m[1].str())));
  4602. emitCode(OP_CALL, 1);
  4603. size++;
  4604. i = (int)(m.position() + m.length());
  4605. }
  4606. if (i < s.size()) {
  4607. std::string literal = s.substr(i, s.size() - i);
  4608. emitCode(OP_LOAD_CONST, getCode()->addConst(vm->PyStr(literal)));
  4609. size++;
  4610. }
  4611. emitCode(OP_BUILD_STRING, size);
  4612. }
  4613. void exprLambda() {
  4614. _Func func = pkpy::make_shared<Function>();
  4615. func->name = "<lambda>";
  4616. if(!match(TK(":"))){
  4617. __compileFunctionArgs(func);
  4618. consume(TK(":"));
  4619. }
  4620. func->code = pkpy::make_shared<CodeObject>(parser->src, func->name);
  4621. this->codes.push(func->code);
  4622. EXPR_TUPLE();
  4623. emitCode(OP_RETURN_VALUE);
  4624. this->codes.pop();
  4625. emitCode(OP_LOAD_LAMBDA, getCode()->addConst(vm->PyFunction(func)));
  4626. }
  4627. void exprAssign() {
  4628. _TokenType op = parser->previous.type;
  4629. if(op == TK("=")) { // a = (expr)
  4630. EXPR_TUPLE();
  4631. emitCode(OP_STORE_PTR);
  4632. }else{ // a += (expr) -> a = a + (expr)
  4633. // TODO: optimization is needed for inplace operators
  4634. emitCode(OP_DUP_TOP);
  4635. EXPR();
  4636. switch (op) {
  4637. case TK("+="): emitCode(OP_BINARY_OP, 0); break;
  4638. case TK("-="): emitCode(OP_BINARY_OP, 1); break;
  4639. case TK("*="): emitCode(OP_BINARY_OP, 2); break;
  4640. case TK("/="): emitCode(OP_BINARY_OP, 3); break;
  4641. case TK("//="): emitCode(OP_BINARY_OP, 4); break;
  4642. default: UNREACHABLE();
  4643. }
  4644. emitCode(OP_STORE_PTR);
  4645. }
  4646. }
  4647. void exprComma() {
  4648. int size = 1; // an expr is in the stack now
  4649. do {
  4650. EXPR(); // NOTE: "1," will fail, "1,2" will be ok
  4651. size++;
  4652. } while(match(TK(",")));
  4653. emitCode(OP_BUILD_SMART_TUPLE, size);
  4654. }
  4655. void exprOr() {
  4656. int patch = emitCode(OP_JUMP_IF_TRUE_OR_POP);
  4657. parsePrecedence(PREC_LOGICAL_OR);
  4658. patchJump(patch);
  4659. }
  4660. void exprAnd() {
  4661. int patch = emitCode(OP_JUMP_IF_FALSE_OR_POP);
  4662. parsePrecedence(PREC_LOGICAL_AND);
  4663. patchJump(patch);
  4664. }
  4665. void exprTernary() {
  4666. int patch = emitCode(OP_POP_JUMP_IF_FALSE);
  4667. EXPR(); // if true
  4668. int patch2 = emitCode(OP_JUMP_ABSOLUTE);
  4669. consume(TK(":"));
  4670. patchJump(patch);
  4671. EXPR(); // if false
  4672. patchJump(patch2);
  4673. }
  4674. void exprBinaryOp() {
  4675. _TokenType op = parser->previous.type;
  4676. parsePrecedence((Precedence)(rules[op].precedence + 1));
  4677. switch (op) {
  4678. case TK("+"): emitCode(OP_BINARY_OP, 0); break;
  4679. case TK("-"): emitCode(OP_BINARY_OP, 1); break;
  4680. case TK("*"): emitCode(OP_BINARY_OP, 2); break;
  4681. case TK("/"): emitCode(OP_BINARY_OP, 3); break;
  4682. case TK("//"): emitCode(OP_BINARY_OP, 4); break;
  4683. case TK("%"): emitCode(OP_BINARY_OP, 5); break;
  4684. case TK("**"): emitCode(OP_BINARY_OP, 6); break;
  4685. case TK("<"): emitCode(OP_COMPARE_OP, 0); break;
  4686. case TK("<="): emitCode(OP_COMPARE_OP, 1); break;
  4687. case TK("=="): emitCode(OP_COMPARE_OP, 2); break;
  4688. case TK("!="): emitCode(OP_COMPARE_OP, 3); break;
  4689. case TK(">"): emitCode(OP_COMPARE_OP, 4); break;
  4690. case TK(">="): emitCode(OP_COMPARE_OP, 5); break;
  4691. case TK("in"): emitCode(OP_CONTAINS_OP, 0); break;
  4692. case TK("not in"): emitCode(OP_CONTAINS_OP, 1); break;
  4693. case TK("is"): emitCode(OP_IS_OP, 0); break;
  4694. case TK("is not"): emitCode(OP_IS_OP, 1); break;
  4695. case TK("<<"): emitCode(OP_BITWISE_OP, 0); break;
  4696. case TK(">>"): emitCode(OP_BITWISE_OP, 1); break;
  4697. case TK("&"): emitCode(OP_BITWISE_OP, 2); break;
  4698. case TK("|"): emitCode(OP_BITWISE_OP, 3); break;
  4699. case TK("^"): emitCode(OP_BITWISE_OP, 4); break;
  4700. default: UNREACHABLE();
  4701. }
  4702. }
  4703. void exprUnaryOp() {
  4704. _TokenType op = parser->previous.type;
  4705. matchNewLines();
  4706. parsePrecedence((Precedence)(PREC_UNARY + 1));
  4707. switch (op) {
  4708. case TK("-"): emitCode(OP_UNARY_NEGATIVE); break;
  4709. case TK("not"): emitCode(OP_UNARY_NOT); break;
  4710. case TK("&"): emitCode(OP_UNARY_REF); break;
  4711. case TK("*"): emitCode(OP_UNARY_DEREF); break;
  4712. default: UNREACHABLE();
  4713. }
  4714. }
  4715. void exprGrouping() {
  4716. matchNewLines(mode()==SINGLE_MODE);
  4717. EXPR_TUPLE();
  4718. matchNewLines(mode()==SINGLE_MODE);
  4719. consume(TK(")"));
  4720. }
  4721. void exprList() {
  4722. int _patch = emitCode(OP_NO_OP);
  4723. int _body_start = getCode()->co_code.size();
  4724. int ARGC = 0;
  4725. do {
  4726. matchNewLines(mode()==SINGLE_MODE);
  4727. if (peek() == TK("]")) break;
  4728. EXPR(); ARGC++;
  4729. matchNewLines(mode()==SINGLE_MODE);
  4730. if(ARGC == 1 && match(TK("for"))) goto __LISTCOMP;
  4731. } while (match(TK(",")));
  4732. matchNewLines(mode()==SINGLE_MODE);
  4733. consume(TK("]"));
  4734. emitCode(OP_BUILD_LIST, ARGC);
  4735. return;
  4736. __LISTCOMP:
  4737. int _body_end = getCode()->co_code.size();
  4738. getCode()->co_code[_patch].op = OP_JUMP_ABSOLUTE;
  4739. getCode()->co_code[_patch].arg = _body_end;
  4740. emitCode(OP_BUILD_LIST, 0);
  4741. EXPR_FOR_VARS();consume(TK("in"));EXPR_TUPLE();
  4742. matchNewLines(mode()==SINGLE_MODE);
  4743. int _skipPatch = emitCode(OP_JUMP_ABSOLUTE);
  4744. int _cond_start = getCode()->co_code.size();
  4745. if(match(TK("if"))) EXPR_TUPLE();
  4746. int _cond_end = getCode()->co_code.size();
  4747. patchJump(_skipPatch);
  4748. emitCode(OP_GET_ITER);
  4749. Loop& loop = enterLoop();
  4750. int patch = emitCode(OP_FOR_ITER);
  4751. if(_cond_end != _cond_start) { // there is an if condition
  4752. getCode()->__moveToEnd(_cond_start, _cond_end);
  4753. int ifpatch = emitCode(OP_POP_JUMP_IF_FALSE);
  4754. getCode()->__moveToEnd(_body_start, _body_end);
  4755. emitCode(OP_LIST_APPEND);
  4756. patchJump(ifpatch);
  4757. }else{
  4758. getCode()->__moveToEnd(_body_start, _body_end);
  4759. emitCode(OP_LIST_APPEND);
  4760. }
  4761. emitCode(OP_JUMP_ABSOLUTE, loop.start); keepOpcodeLine();
  4762. patchJump(patch);
  4763. exitLoop();
  4764. matchNewLines(mode()==SINGLE_MODE);
  4765. consume(TK("]"));
  4766. }
  4767. void exprMap() {
  4768. int size = 0;
  4769. do {
  4770. matchNewLines(mode()==SINGLE_MODE);
  4771. if (peek() == TK("}")) break;
  4772. EXPR();consume(TK(":"));EXPR();
  4773. size++;
  4774. matchNewLines(mode()==SINGLE_MODE);
  4775. } while (match(TK(",")));
  4776. matchNewLines();
  4777. consume(TK("}"));
  4778. emitCode(OP_BUILD_MAP, size);
  4779. }
  4780. void exprCall() {
  4781. int ARGC = 0;
  4782. do {
  4783. matchNewLines(mode()==SINGLE_MODE);
  4784. if (peek() == TK(")")) break;
  4785. EXPR();
  4786. ARGC++;
  4787. matchNewLines(mode()==SINGLE_MODE);
  4788. } while (match(TK(",")));
  4789. consume(TK(")"));
  4790. emitCode(OP_CALL, ARGC);
  4791. }
  4792. void exprName() {
  4793. Token tkname = parser->previous;
  4794. int index = getCode()->addName(
  4795. tkname.str(),
  4796. codes.size()>1 ? NAME_LOCAL : NAME_GLOBAL
  4797. );
  4798. emitCode(OP_LOAD_NAME_PTR, index);
  4799. }
  4800. void exprAttrib() {
  4801. consume(TK("@id"));
  4802. const _Str& name = parser->previous.str();
  4803. int index = getCode()->addName(name, NAME_ATTR);
  4804. emitCode(OP_BUILD_ATTR_PTR, index);
  4805. }
  4806. void exprAttribPtr(){
  4807. consume(TK("@id"));
  4808. const _Str& name = parser->previous.str();
  4809. int index = getCode()->addName(name, NAME_ATTR);
  4810. emitCode(OP_BUILD_ATTR_PTR_PTR, index);
  4811. }
  4812. // [:], [:b]
  4813. // [a], [a:], [a:b]
  4814. void exprSubscript() {
  4815. if(match(TK(":"))){
  4816. emitCode(OP_LOAD_NONE);
  4817. if(match(TK("]"))){
  4818. emitCode(OP_LOAD_NONE);
  4819. }else{
  4820. EXPR();
  4821. consume(TK("]"));
  4822. }
  4823. emitCode(OP_BUILD_SLICE);
  4824. }else{
  4825. EXPR();
  4826. if(match(TK(":"))){
  4827. if(match(TK("]"))){
  4828. emitCode(OP_LOAD_NONE);
  4829. }else{
  4830. EXPR();
  4831. consume(TK("]"));
  4832. }
  4833. emitCode(OP_BUILD_SLICE);
  4834. }else{
  4835. consume(TK("]"));
  4836. }
  4837. }
  4838. emitCode(OP_BUILD_INDEX_PTR);
  4839. }
  4840. void exprValue() {
  4841. _TokenType op = parser->previous.type;
  4842. switch (op) {
  4843. case TK("None"): emitCode(OP_LOAD_NONE); break;
  4844. case TK("True"): emitCode(OP_LOAD_TRUE); break;
  4845. case TK("False"): emitCode(OP_LOAD_FALSE); break;
  4846. case TK("..."): emitCode(OP_LOAD_ELLIPSIS); break;
  4847. default: UNREACHABLE();
  4848. }
  4849. }
  4850. void keepOpcodeLine(){
  4851. int i = getCode()->co_code.size() - 1;
  4852. getCode()->co_code[i].line = getCode()->co_code[i-1].line;
  4853. }
  4854. int emitCode(Opcode opcode, int arg=-1) {
  4855. int line = parser->previous.line;
  4856. getCode()->co_code.push_back(
  4857. ByteCode{(uint8_t)opcode, arg, (uint16_t)line}
  4858. );
  4859. return getCode()->co_code.size() - 1;
  4860. }
  4861. inline void patchJump(int addr_index) {
  4862. int target = getCode()->co_code.size();
  4863. getCode()->co_code[addr_index].arg = target;
  4864. }
  4865. void compileBlockBody(){
  4866. __compileBlockBody(&Compiler::compileStatement);
  4867. }
  4868. void __compileBlockBody(CompilerAction action) {
  4869. consume(TK(":"));
  4870. if(!matchNewLines(mode()==SINGLE_MODE)){
  4871. syntaxError("expected a new line after ':'");
  4872. }
  4873. consume(TK("@indent"));
  4874. while (peek() != TK("@dedent")) {
  4875. matchNewLines();
  4876. (this->*action)();
  4877. matchNewLines();
  4878. }
  4879. consume(TK("@dedent"));
  4880. }
  4881. Token compileImportPath() {
  4882. consume(TK("@id"));
  4883. Token tkmodule = parser->previous;
  4884. int index = getCode()->addName(tkmodule.str(), NAME_GLOBAL);
  4885. emitCode(OP_IMPORT_NAME, index);
  4886. return tkmodule;
  4887. }
  4888. // import a as b
  4889. void compileRegularImport() {
  4890. do {
  4891. Token tkmodule = compileImportPath();
  4892. if (match(TK("as"))) {
  4893. consume(TK("@id"));
  4894. tkmodule = parser->previous;
  4895. }
  4896. int index = getCode()->addName(tkmodule.str(), NAME_GLOBAL);
  4897. emitCode(OP_STORE_NAME_PTR, index);
  4898. } while (match(TK(",")));
  4899. consumeEndStatement();
  4900. }
  4901. // from a import b as c, d as e
  4902. void compileFromImport() {
  4903. Token tkmodule = compileImportPath();
  4904. consume(TK("import"));
  4905. do {
  4906. emitCode(OP_DUP_TOP);
  4907. consume(TK("@id"));
  4908. Token tkname = parser->previous;
  4909. int index = getCode()->addName(tkname.str(), NAME_GLOBAL);
  4910. emitCode(OP_BUILD_ATTR_PTR, index);
  4911. if (match(TK("as"))) {
  4912. consume(TK("@id"));
  4913. tkname = parser->previous;
  4914. }
  4915. index = getCode()->addName(tkname.str(), NAME_GLOBAL);
  4916. emitCode(OP_STORE_NAME_PTR, index);
  4917. } while (match(TK(",")));
  4918. emitCode(OP_POP_TOP);
  4919. consumeEndStatement();
  4920. }
  4921. void parsePrecedence(Precedence precedence) {
  4922. lexToken();
  4923. GrammarFn prefix = rules[parser->previous.type].prefix;
  4924. if (prefix == nullptr) syntaxError(_Str("expected an expression, but got ") + TK_STR(parser->previous.type));
  4925. (this->*prefix)();
  4926. while (rules[peek()].precedence >= precedence) {
  4927. lexToken();
  4928. _TokenType op = parser->previous.type;
  4929. GrammarFn infix = rules[op].infix;
  4930. if(infix == nullptr) throw std::runtime_error("(infix == nullptr) is true");
  4931. (this->*infix)();
  4932. }
  4933. }
  4934. void compileIfStatement() {
  4935. matchNewLines();
  4936. EXPR_TUPLE();
  4937. int ifpatch = emitCode(OP_POP_JUMP_IF_FALSE);
  4938. compileBlockBody();
  4939. if (match(TK("elif"))) {
  4940. int exit_jump = emitCode(OP_JUMP_ABSOLUTE);
  4941. patchJump(ifpatch);
  4942. compileIfStatement();
  4943. patchJump(exit_jump);
  4944. } else if (match(TK("else"))) {
  4945. int exit_jump = emitCode(OP_JUMP_ABSOLUTE);
  4946. patchJump(ifpatch);
  4947. compileBlockBody();
  4948. patchJump(exit_jump);
  4949. } else {
  4950. patchJump(ifpatch);
  4951. }
  4952. }
  4953. Loop& enterLoop(){
  4954. Loop lp((int)getCode()->co_code.size());
  4955. loops.push(lp);
  4956. return loops.top();
  4957. }
  4958. void exitLoop(){
  4959. Loop& lp = loops.top();
  4960. for(int addr : lp.breaks) patchJump(addr);
  4961. loops.pop();
  4962. }
  4963. void compileWhileLoop() {
  4964. Loop& loop = enterLoop();
  4965. EXPR_TUPLE();
  4966. int patch = emitCode(OP_POP_JUMP_IF_FALSE);
  4967. compileBlockBody();
  4968. emitCode(OP_JUMP_ABSOLUTE, loop.start); keepOpcodeLine();
  4969. patchJump(patch);
  4970. exitLoop();
  4971. }
  4972. void EXPR_FOR_VARS(){
  4973. int size = 0;
  4974. do {
  4975. consume(TK("@id"));
  4976. exprName(); size++;
  4977. } while (match(TK(",")));
  4978. if(size > 1) emitCode(OP_BUILD_SMART_TUPLE, size);
  4979. }
  4980. void compileForLoop() {
  4981. EXPR_FOR_VARS();consume(TK("in"));EXPR_TUPLE();
  4982. emitCode(OP_GET_ITER);
  4983. Loop& loop = enterLoop();
  4984. int patch = emitCode(OP_FOR_ITER);
  4985. compileBlockBody();
  4986. emitCode(OP_JUMP_ABSOLUTE, loop.start); keepOpcodeLine();
  4987. patchJump(patch);
  4988. exitLoop();
  4989. }
  4990. void compileStatement() {
  4991. if (match(TK("break"))) {
  4992. if (loops.empty()) syntaxError("'break' outside loop");
  4993. consumeEndStatement();
  4994. int patch = emitCode(OP_SAFE_JUMP_ABSOLUTE);
  4995. getLoop().breaks.push_back(patch);
  4996. } else if (match(TK("continue"))) {
  4997. if (loops.empty()) syntaxError("'continue' not properly in loop");
  4998. consumeEndStatement();
  4999. emitCode(OP_JUMP_ABSOLUTE, getLoop().start);
  5000. } else if (match(TK("return"))) {
  5001. if (codes.size() == 1)
  5002. syntaxError("'return' outside function");
  5003. if(matchEndStatement()){
  5004. emitCode(OP_LOAD_NONE);
  5005. }else{
  5006. EXPR_TUPLE();
  5007. consumeEndStatement();
  5008. }
  5009. emitCode(OP_RETURN_VALUE);
  5010. } else if (match(TK("if"))) {
  5011. compileIfStatement();
  5012. } else if (match(TK("while"))) {
  5013. compileWhileLoop();
  5014. } else if (match(TK("for"))) {
  5015. compileForLoop();
  5016. } else if(match(TK("assert"))){
  5017. EXPR();
  5018. emitCode(OP_ASSERT);
  5019. consumeEndStatement();
  5020. } else if(match(TK("with"))){
  5021. EXPR();
  5022. consume(TK("as"));
  5023. consume(TK("@id"));
  5024. Token tkname = parser->previous;
  5025. int index = getCode()->addName(
  5026. tkname.str(),
  5027. codes.size()>1 ? NAME_LOCAL : NAME_GLOBAL
  5028. );
  5029. emitCode(OP_STORE_NAME_PTR, index);
  5030. emitCode(OP_LOAD_NAME_PTR, index);
  5031. emitCode(OP_WITH_ENTER);
  5032. compileBlockBody();
  5033. emitCode(OP_LOAD_NAME_PTR, index);
  5034. emitCode(OP_WITH_EXIT);
  5035. } else if(match(TK("label"))){
  5036. if(mode() != EXEC_MODE) syntaxError("'label' is only available in EXEC_MODE");
  5037. consume(TK(".")); consume(TK("@id"));
  5038. getCode()->addLabel(parser->previous.str());
  5039. consumeEndStatement();
  5040. } else if(match(TK("goto"))){
  5041. // https://entrian.com/goto/
  5042. if(mode() != EXEC_MODE) syntaxError("'goto' is only available in EXEC_MODE");
  5043. consume(TK(".")); consume(TK("@id"));
  5044. emitCode(OP_LOAD_CONST, getCode()->addConst(vm->PyStr(parser->previous.str())));
  5045. emitCode(OP_GOTO);
  5046. consumeEndStatement();
  5047. } else if(match(TK("raise"))){
  5048. consume(TK("@id")); // dummy exception type
  5049. emitCode(OP_LOAD_CONST, getCode()->addConst(vm->PyStr(parser->previous.str())));
  5050. consume(TK("("));EXPR();consume(TK(")"));
  5051. emitCode(OP_RAISE_ERROR);
  5052. consumeEndStatement();
  5053. } else if(match(TK("del"))){
  5054. EXPR();
  5055. emitCode(OP_DELETE_PTR);
  5056. consumeEndStatement();
  5057. } else if(match(TK("global"))){
  5058. consume(TK("@id"));
  5059. getCode()->co_global_names.push_back(parser->previous.str());
  5060. consumeEndStatement();
  5061. } else if(match(TK("pass"))){
  5062. consumeEndStatement();
  5063. } else {
  5064. EXPR_ANY();
  5065. consumeEndStatement();
  5066. // If last op is not an assignment, pop the result.
  5067. uint8_t lastOp = getCode()->co_code.back().op;
  5068. if( lastOp != OP_STORE_NAME_PTR && lastOp != OP_STORE_PTR){
  5069. if(mode()==SINGLE_MODE && parser->indents.top() == 0){
  5070. emitCode(OP_PRINT_EXPR);
  5071. }
  5072. emitCode(OP_POP_TOP);
  5073. }
  5074. }
  5075. }
  5076. void compileClass(){
  5077. consume(TK("@id"));
  5078. int clsNameIdx = getCode()->addName(parser->previous.str(), NAME_GLOBAL);
  5079. int superClsNameIdx = -1;
  5080. if(match(TK("("))){
  5081. consume(TK("@id"));
  5082. superClsNameIdx = getCode()->addName(parser->previous.str(), NAME_GLOBAL);
  5083. consume(TK(")"));
  5084. }
  5085. emitCode(OP_LOAD_NONE);
  5086. isCompilingClass = true;
  5087. __compileBlockBody(&Compiler::compileFunction);
  5088. isCompilingClass = false;
  5089. if(superClsNameIdx == -1) emitCode(OP_LOAD_NONE);
  5090. else emitCode(OP_LOAD_NAME_PTR, superClsNameIdx);
  5091. emitCode(OP_BUILD_CLASS, clsNameIdx);
  5092. }
  5093. void __compileFunctionArgs(_Func func){
  5094. int state = 0; // 0 for args, 1 for *args, 2 for k=v, 3 for **kwargs
  5095. do {
  5096. if(state == 3) syntaxError("**kwargs should be the last argument");
  5097. matchNewLines();
  5098. if(match(TK("*"))){
  5099. if(state < 1) state = 1;
  5100. else syntaxError("*args should be placed before **kwargs");
  5101. }
  5102. else if(match(TK("**"))){
  5103. state = 3;
  5104. }
  5105. consume(TK("@id"));
  5106. const _Str& name = parser->previous.str();
  5107. if(func->hasName(name)) syntaxError("duplicate argument name");
  5108. if(state == 0 && peek() == TK("=")) state = 2;
  5109. switch (state)
  5110. {
  5111. case 0: func->args.push_back(name); break;
  5112. case 1: func->starredArg = name; state+=1; break;
  5113. case 2: {
  5114. consume(TK("="));
  5115. PyVarOrNull value = readLiteral();
  5116. if(value == nullptr){
  5117. syntaxError(_Str("expect a literal, not ") + TK_STR(parser->current.type));
  5118. }
  5119. func->kwArgs[name] = value;
  5120. func->kwArgsOrder.push_back(name);
  5121. } break;
  5122. case 3: syntaxError("**kwargs is not supported yet"); break;
  5123. }
  5124. } while (match(TK(",")));
  5125. }
  5126. void compileFunction(){
  5127. if(isCompilingClass){
  5128. if(match(TK("pass"))) return;
  5129. consume(TK("def"));
  5130. }
  5131. _Func func = pkpy::make_shared<Function>();
  5132. consume(TK("@id"));
  5133. func->name = parser->previous.str();
  5134. if (match(TK("(")) && !match(TK(")"))) {
  5135. __compileFunctionArgs(func);
  5136. consume(TK(")"));
  5137. }
  5138. func->code = pkpy::make_shared<CodeObject>(parser->src, func->name);
  5139. this->codes.push(func->code);
  5140. compileBlockBody();
  5141. this->codes.pop();
  5142. emitCode(OP_LOAD_CONST, getCode()->addConst(vm->PyFunction(func)));
  5143. if(!isCompilingClass) emitCode(OP_STORE_FUNCTION);
  5144. }
  5145. PyVarOrNull readLiteral(){
  5146. if(match(TK("-"))){
  5147. consume(TK("@num"));
  5148. PyVar val = parser->previous.value;
  5149. return vm->numNegated(val);
  5150. }
  5151. if(match(TK("@num"))) return parser->previous.value;
  5152. if(match(TK("@str"))) return parser->previous.value;
  5153. if(match(TK("True"))) return vm->PyBool(true);
  5154. if(match(TK("False"))) return vm->PyBool(false);
  5155. if(match(TK("None"))) return vm->None;
  5156. if(match(TK("..."))) return vm->Ellipsis;
  5157. return nullptr;
  5158. }
  5159. void compileTopLevelStatement() {
  5160. if (match(TK("class"))) {
  5161. compileClass();
  5162. } else if (match(TK("def"))) {
  5163. compileFunction();
  5164. } else if (match(TK("import"))) {
  5165. compileRegularImport();
  5166. } else if (match(TK("from"))) {
  5167. compileFromImport();
  5168. } else {
  5169. compileStatement();
  5170. }
  5171. }
  5172. _Code __fillCode(){
  5173. _Code code = pkpy::make_shared<CodeObject>(parser->src, _Str("<module>"));
  5174. codes.push(code);
  5175. // Lex initial tokens. current <-- next.
  5176. lexToken();
  5177. lexToken();
  5178. matchNewLines();
  5179. if(mode()==EVAL_MODE) {
  5180. EXPR_TUPLE();
  5181. consume(TK("@eof"));
  5182. return code;
  5183. }else if(mode()==JSON_MODE){
  5184. PyVarOrNull value = readLiteral();
  5185. if(value != nullptr) emitCode(OP_LOAD_CONST, code->addConst(value));
  5186. else if(match(TK("{"))) exprMap();
  5187. else if(match(TK("["))) exprList();
  5188. else syntaxError("expect a JSON object or array");
  5189. consume(TK("@eof"));
  5190. return code;
  5191. }
  5192. while (!match(TK("@eof"))) {
  5193. compileTopLevelStatement();
  5194. matchNewLines();
  5195. }
  5196. return code;
  5197. }
  5198. /***** Error Reporter *****/
  5199. _Str getLineSnapshot(){
  5200. int lineno = parser->current_line;
  5201. if(parser->peekChar() == '\n') lineno--;
  5202. return parser->src->snapshot(lineno);
  5203. }
  5204. void syntaxError(_Str msg){
  5205. throw CompileError("SyntaxError", msg, getLineSnapshot());
  5206. }
  5207. void indentationError(_Str msg){
  5208. throw CompileError("IndentationError", msg, getLineSnapshot());
  5209. }
  5210. void unexpectedError(_Str msg){
  5211. throw CompileError("UnexpectedError", msg, getLineSnapshot());
  5212. }
  5213. };
  5214. _Code compile(VM* vm, const char* source, _Str filename, CompileMode mode=EXEC_MODE, bool noThrow=true) {
  5215. Compiler compiler(vm, source, filename, mode);
  5216. if(!noThrow) return compiler.__fillCode();
  5217. try{
  5218. return compiler.__fillCode();
  5219. }catch(std::exception& e){
  5220. if(dynamic_cast<const _Error*>(&e)){
  5221. (*vm->_stderr) << e.what() << '\n';
  5222. }else{
  5223. auto ce = CompileError("UnexpectedError", e.what(), compiler.getLineSnapshot());
  5224. (*vm->_stderr) << ce.what() << '\n';
  5225. }
  5226. return nullptr;
  5227. }
  5228. }
  5229. enum InputResult {
  5230. NEED_MORE_LINES = 0,
  5231. EXEC_DONE = 1,
  5232. EXEC_SKIPPED = 2,
  5233. };
  5234. class REPL {
  5235. protected:
  5236. int need_more_lines = 0;
  5237. std::string buffer;
  5238. VM* vm;
  5239. bool exited = false;
  5240. void _exit(){
  5241. exited = true;
  5242. exit(0);
  5243. }
  5244. public:
  5245. REPL(VM* vm) : vm(vm){
  5246. (*vm->_stdout) << ("pocketpy " PK_VERSION " (" __DATE__ ", " __TIME__ ")\n");
  5247. (*vm->_stdout) << ("https://github.com/blueloveTH/pocketpy" "\n");
  5248. (*vm->_stdout) << ("Type \"exit()\" to exit." "\n");
  5249. }
  5250. bool is_need_more_lines() const {
  5251. return need_more_lines;
  5252. }
  5253. InputResult input(std::string line){
  5254. if(exited) return EXEC_SKIPPED;
  5255. if(need_more_lines){
  5256. buffer += line;
  5257. buffer += '\n';
  5258. int n = buffer.size();
  5259. if(n>=need_more_lines){
  5260. for(int i=buffer.size()-need_more_lines; i<buffer.size(); i++){
  5261. if(buffer[i] != '\n') goto __NOT_ENOUGH_LINES;
  5262. }
  5263. need_more_lines = 0;
  5264. line = buffer;
  5265. buffer.clear();
  5266. }else{
  5267. __NOT_ENOUGH_LINES:
  5268. return NEED_MORE_LINES;
  5269. }
  5270. }else{
  5271. if(line == "exit()") _exit();
  5272. if(line.empty()) return EXEC_SKIPPED;
  5273. }
  5274. try{
  5275. _Code code = compile(vm, line.c_str(), "<stdin>", SINGLE_MODE);
  5276. if(code == nullptr) return EXEC_SKIPPED;
  5277. vm->execAsync(code);
  5278. return EXEC_DONE;
  5279. }catch(NeedMoreLines& ne){
  5280. buffer += line;
  5281. buffer += '\n';
  5282. need_more_lines = ne.isClassDef ? 3 : 2;
  5283. return NEED_MORE_LINES;
  5284. }
  5285. }
  5286. };
  5287. #define BIND_NUM_ARITH_OPT(name, op) \
  5288. _vm->bindMethodMulti({"int","float"}, #name, [](VM* vm, const pkpy::ArgList& args){ \
  5289. if(!vm->isIntOrFloat(args[0], args[1])) \
  5290. vm->typeError("unsupported operand type(s) for " #op ); \
  5291. if(args[0]->isType(vm->_tp_int) && args[1]->isType(vm->_tp_int)){ \
  5292. return vm->PyInt(vm->PyInt_AS_C(args[0]) op vm->PyInt_AS_C(args[1])); \
  5293. }else{ \
  5294. return vm->PyFloat(vm->numToFloat(args[0]) op vm->numToFloat(args[1])); \
  5295. } \
  5296. });
  5297. #define BIND_NUM_LOGICAL_OPT(name, op, is_eq) \
  5298. _vm->bindMethodMulti({"int","float"}, #name, [](VM* vm, const pkpy::ArgList& args){ \
  5299. if(!vm->isIntOrFloat(args[0], args[1])){ \
  5300. if constexpr(is_eq) return vm->PyBool(args[0] == args[1]); \
  5301. vm->typeError("unsupported operand type(s) for " #op ); \
  5302. } \
  5303. return vm->PyBool(vm->numToFloat(args[0]) op vm->numToFloat(args[1])); \
  5304. });
  5305. void __initializeBuiltinFunctions(VM* _vm) {
  5306. BIND_NUM_ARITH_OPT(__add__, +)
  5307. BIND_NUM_ARITH_OPT(__sub__, -)
  5308. BIND_NUM_ARITH_OPT(__mul__, *)
  5309. BIND_NUM_LOGICAL_OPT(__lt__, <, false)
  5310. BIND_NUM_LOGICAL_OPT(__le__, <=, false)
  5311. BIND_NUM_LOGICAL_OPT(__gt__, >, false)
  5312. BIND_NUM_LOGICAL_OPT(__ge__, >=, false)
  5313. BIND_NUM_LOGICAL_OPT(__eq__, ==, true)
  5314. #undef BIND_NUM_ARITH_OPT
  5315. #undef BIND_NUM_LOGICAL_OPT
  5316. _vm->bindBuiltinFunc("print", [](VM* vm, const pkpy::ArgList& args) {
  5317. _StrStream ss;
  5318. for(int i=0; i<args.size(); i++){
  5319. ss << vm->PyStr_AS_C(vm->asStr(args[i])) << " ";
  5320. }
  5321. (*vm->_stdout) << ss.str() << '\n';
  5322. return vm->None;
  5323. });
  5324. _vm->bindBuiltinFunc("super", [](VM* vm, const pkpy::ArgList& args) {
  5325. vm->__checkArgSize(args, 0);
  5326. auto it = vm->topFrame()->f_locals.find("self"_c);
  5327. if(it == vm->topFrame()->f_locals.end()) vm->typeError("super() can only be called in a class method");
  5328. return vm->newObject(vm->_tp_super, it->second);
  5329. });
  5330. _vm->bindBuiltinFunc("eval", [](VM* vm, const pkpy::ArgList& args) {
  5331. vm->__checkArgSize(args, 1);
  5332. const _Str& expr = vm->PyStr_AS_C(args[0]);
  5333. _Code code = compile(vm, expr.c_str(), "<eval>", EVAL_MODE, false);
  5334. return vm->_exec(code, vm->topFrame()->_module, vm->topFrame()->f_locals);
  5335. });
  5336. _vm->bindBuiltinFunc("isinstance", [](VM* vm, const pkpy::ArgList& args) {
  5337. vm->__checkArgSize(args, 2);
  5338. return vm->PyBool(vm->isInstance(args[0], args[1]));
  5339. });
  5340. _vm->bindBuiltinFunc("repr", [](VM* vm, const pkpy::ArgList& args) {
  5341. vm->__checkArgSize(args, 1);
  5342. return vm->asRepr(args[0]);
  5343. });
  5344. _vm->bindBuiltinFunc("hash", [](VM* vm, const pkpy::ArgList& args) {
  5345. vm->__checkArgSize(args, 1);
  5346. return vm->PyInt(vm->hash(args[0]));
  5347. });
  5348. _vm->bindBuiltinFunc("chr", [](VM* vm, const pkpy::ArgList& args) {
  5349. vm->__checkArgSize(args, 1);
  5350. _Int i = vm->PyInt_AS_C(args[0]);
  5351. if (i < 0 || i > 128) vm->valueError("chr() arg not in range(128)");
  5352. return vm->PyStr(std::string(1, (char)i));
  5353. });
  5354. _vm->bindBuiltinFunc("ord", [](VM* vm, const pkpy::ArgList& args) {
  5355. vm->__checkArgSize(args, 1);
  5356. _Str s = vm->PyStr_AS_C(args[0]);
  5357. if (s.size() != 1) vm->typeError("ord() expected an ASCII character");
  5358. return vm->PyInt((_Int)s[0]);
  5359. });
  5360. _vm->bindBuiltinFunc("globals", [](VM* vm, const pkpy::ArgList& args) {
  5361. vm->__checkArgSize(args, 0);
  5362. const auto& d = vm->topFrame()->f_globals();
  5363. PyVar obj = vm->call(vm->builtins->attribs["dict"], {});
  5364. for (const auto& [k, v] : d) {
  5365. vm->call(obj, __setitem__, {vm->PyStr(k), v});
  5366. }
  5367. return obj;
  5368. });
  5369. _vm->bindBuiltinFunc("locals", [](VM* vm, const pkpy::ArgList& args) {
  5370. vm->__checkArgSize(args, 0);
  5371. const auto& d = vm->topFrame()->f_locals;
  5372. PyVar obj = vm->call(vm->builtins->attribs["dict"], {});
  5373. for (const auto& [k, v] : d) {
  5374. vm->call(obj, __setitem__, {vm->PyStr(k), v});
  5375. }
  5376. return obj;
  5377. });
  5378. _vm->bindBuiltinFunc("dir", [](VM* vm, const pkpy::ArgList& args) {
  5379. vm->__checkArgSize(args, 1);
  5380. std::vector<_Str> names;
  5381. for (auto& [k, _] : args[0]->attribs) names.push_back(k);
  5382. for (auto& [k, _] : args[0]->_type->attribs) {
  5383. if (k.str().find("__") == 0) continue;
  5384. if (std::find(names.begin(), names.end(), k) == names.end()) names.push_back(k);
  5385. }
  5386. PyVarList ret;
  5387. for (const auto& name : names) ret.push_back(vm->PyStr(name));
  5388. return vm->PyList(ret);
  5389. });
  5390. _vm->bindMethod("object", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5391. PyVar _self = args[0];
  5392. _Str s = "<" + _self->getTypeName() + " object at " + std::to_string((uintptr_t)_self.get()) + ">";
  5393. return vm->PyStr(s);
  5394. });
  5395. _vm->bindMethod("type", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  5396. vm->__checkArgSize(args, 1);
  5397. return args[0]->_type;
  5398. });
  5399. _vm->bindMethod("range", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  5400. _Range r;
  5401. switch (args.size()) {
  5402. case 1: r.stop = vm->PyInt_AS_C(args[0]); break;
  5403. case 2: r.start = vm->PyInt_AS_C(args[0]); r.stop = vm->PyInt_AS_C(args[1]); break;
  5404. case 3: r.start = vm->PyInt_AS_C(args[0]); r.stop = vm->PyInt_AS_C(args[1]); r.step = vm->PyInt_AS_C(args[2]); break;
  5405. default: vm->typeError("expected 1-3 arguments, but got " + std::to_string(args.size()));
  5406. }
  5407. return vm->PyRange(r);
  5408. });
  5409. _vm->bindMethod("range", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  5410. vm->__checkType(args[0], vm->_tp_range);
  5411. return vm->PyIter(
  5412. pkpy::make_shared<_Iterator, RangeIterator>(vm, args[0])
  5413. );
  5414. });
  5415. _vm->bindMethod("NoneType", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5416. return vm->PyStr("None");
  5417. });
  5418. _vm->bindMethod("NoneType", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  5419. return vm->PyStr("null");
  5420. });
  5421. _vm->bindMethod("NoneType", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  5422. return vm->PyBool(args[0] == args[1]);
  5423. });
  5424. _vm->bindMethodMulti({"int", "float"}, "__truediv__", [](VM* vm, const pkpy::ArgList& args) {
  5425. if(!vm->isIntOrFloat(args[0], args[1]))
  5426. vm->typeError("unsupported operand type(s) for " "/" );
  5427. _Float rhs = vm->numToFloat(args[1]);
  5428. if (rhs == 0) vm->zeroDivisionError();
  5429. return vm->PyFloat(vm->numToFloat(args[0]) / rhs);
  5430. });
  5431. _vm->bindMethodMulti({"int", "float"}, "__pow__", [](VM* vm, const pkpy::ArgList& args) {
  5432. if(!vm->isIntOrFloat(args[0], args[1]))
  5433. vm->typeError("unsupported operand type(s) for " "**" );
  5434. if(args[0]->isType(vm->_tp_int) && args[1]->isType(vm->_tp_int)){
  5435. return vm->PyInt((_Int)round(pow(vm->PyInt_AS_C(args[0]), vm->PyInt_AS_C(args[1]))));
  5436. }else{
  5437. return vm->PyFloat((_Float)pow(vm->numToFloat(args[0]), vm->numToFloat(args[1])));
  5438. }
  5439. });
  5440. /************ PyInt ************/
  5441. _vm->bindMethod("int", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  5442. if(args.size() == 0) return vm->PyInt(0);
  5443. vm->__checkArgSize(args, 1);
  5444. if (args[0]->isType(vm->_tp_int)) return args[0];
  5445. if (args[0]->isType(vm->_tp_float)) return vm->PyInt((_Int)vm->PyFloat_AS_C(args[0]));
  5446. if (args[0]->isType(vm->_tp_bool)) return vm->PyInt(vm->PyBool_AS_C(args[0]) ? 1 : 0);
  5447. if (args[0]->isType(vm->_tp_str)) {
  5448. const _Str& s = vm->PyStr_AS_C(args[0]);
  5449. try{
  5450. _Int val = std::stoll(s.str());
  5451. return vm->PyInt(val);
  5452. }catch(std::invalid_argument&){
  5453. vm->valueError("invalid literal for int(): '" + s + "'");
  5454. }
  5455. }
  5456. vm->typeError("int() argument must be a int, float, bool or str");
  5457. return vm->None;
  5458. });
  5459. _vm->bindMethod("int", "__floordiv__", [](VM* vm, const pkpy::ArgList& args) {
  5460. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  5461. vm->typeError("unsupported operand type(s) for " "//" );
  5462. _Int rhs = vm->PyInt_AS_C(args[1]);
  5463. if(rhs == 0) vm->zeroDivisionError();
  5464. return vm->PyInt(vm->PyInt_AS_C(args[0]) / rhs);
  5465. });
  5466. _vm->bindMethod("int", "__mod__", [](VM* vm, const pkpy::ArgList& args) {
  5467. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  5468. vm->typeError("unsupported operand type(s) for " "%" );
  5469. _Int rhs = vm->PyInt_AS_C(args[1]);
  5470. if(rhs == 0) vm->zeroDivisionError();
  5471. return vm->PyInt(vm->PyInt_AS_C(args[0]) % rhs);
  5472. });
  5473. _vm->bindMethod("int", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5474. return vm->PyStr(std::to_string(vm->PyInt_AS_C(args[0])));
  5475. });
  5476. _vm->bindMethod("int", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  5477. return vm->PyStr(std::to_string((int)vm->PyInt_AS_C(args[0])));
  5478. });
  5479. #define __INT_BITWISE_OP(name,op) \
  5480. _vm->bindMethod("int", #name, [](VM* vm, const pkpy::ArgList& args) { \
  5481. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int)) \
  5482. vm->typeError("unsupported operand type(s) for " #op ); \
  5483. return vm->PyInt(vm->PyInt_AS_C(args[0]) op vm->PyInt_AS_C(args[1])); \
  5484. });
  5485. __INT_BITWISE_OP(__lshift__, <<)
  5486. __INT_BITWISE_OP(__rshift__, >>)
  5487. __INT_BITWISE_OP(__and__, &)
  5488. __INT_BITWISE_OP(__or__, |)
  5489. __INT_BITWISE_OP(__xor__, ^)
  5490. #undef __INT_BITWISE_OP
  5491. _vm->bindMethod("int", "__xor__", [](VM* vm, const pkpy::ArgList& args) {
  5492. if(!args[0]->isType(vm->_tp_int) || !args[1]->isType(vm->_tp_int))
  5493. vm->typeError("unsupported operand type(s) for " "^" );
  5494. return vm->PyInt(vm->PyInt_AS_C(args[0]) ^ vm->PyInt_AS_C(args[1]));
  5495. });
  5496. /************ PyFloat ************/
  5497. _vm->bindMethod("float", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  5498. if(args.size() == 0) return vm->PyFloat(0.0);
  5499. vm->__checkArgSize(args, 1);
  5500. if (args[0]->isType(vm->_tp_int)) return vm->PyFloat((_Float)vm->PyInt_AS_C(args[0]));
  5501. if (args[0]->isType(vm->_tp_float)) return args[0];
  5502. if (args[0]->isType(vm->_tp_bool)) return vm->PyFloat(vm->PyBool_AS_C(args[0]) ? 1.0 : 0.0);
  5503. if (args[0]->isType(vm->_tp_str)) {
  5504. const _Str& s = vm->PyStr_AS_C(args[0]);
  5505. if(s == "inf") return vm->PyFloat(INFINITY);
  5506. if(s == "-inf") return vm->PyFloat(-INFINITY);
  5507. try{
  5508. _Float val = std::stod(s.str());
  5509. return vm->PyFloat(val);
  5510. }catch(std::invalid_argument&){
  5511. vm->valueError("invalid literal for float(): '" + s + "'");
  5512. }
  5513. }
  5514. vm->typeError("float() argument must be a int, float, bool or str");
  5515. return vm->None;
  5516. });
  5517. _vm->bindMethod("float", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5518. _Float val = vm->PyFloat_AS_C(args[0]);
  5519. if(std::isinf(val) || std::isnan(val)) return vm->PyStr(std::to_string(val));
  5520. _StrStream ss;
  5521. ss << std::setprecision(std::numeric_limits<_Float>::max_digits10-1) << val;
  5522. std::string s = ss.str();
  5523. if(std::all_of(s.begin()+1, s.end(), isdigit)) s += ".0";
  5524. return vm->PyStr(s);
  5525. });
  5526. _vm->bindMethod("float", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  5527. return vm->PyStr(std::to_string((float)vm->PyFloat_AS_C(args[0])));
  5528. });
  5529. /************ PyString ************/
  5530. _vm->bindMethod("str", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  5531. vm->__checkArgSize(args, 1);
  5532. return vm->asStr(args[0]);
  5533. });
  5534. _vm->bindMethod("str", "__add__", [](VM* vm, const pkpy::ArgList& args) {
  5535. if(!args[0]->isType(vm->_tp_str) || !args[1]->isType(vm->_tp_str))
  5536. vm->typeError("unsupported operand type(s) for " "+" );
  5537. const _Str& lhs = vm->PyStr_AS_C(args[0]);
  5538. const _Str& rhs = vm->PyStr_AS_C(args[1]);
  5539. return vm->PyStr(lhs + rhs);
  5540. });
  5541. _vm->bindMethod("str", "__len__", [](VM* vm, const pkpy::ArgList& args) {
  5542. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5543. return vm->PyInt(_self.u8_length());
  5544. });
  5545. _vm->bindMethod("str", "__contains__", [](VM* vm, const pkpy::ArgList& args) {
  5546. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5547. const _Str& _other = vm->PyStr_AS_C(args[1]);
  5548. return vm->PyBool(_self.str().find(_other.str()) != _Str::npos);
  5549. });
  5550. _vm->bindMethod("str", "__str__", [](VM* vm, const pkpy::ArgList& args) {
  5551. return args[0]; // str is immutable
  5552. });
  5553. _vm->bindMethod("str", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  5554. return vm->PyIter(
  5555. pkpy::make_shared<_Iterator, StringIterator>(vm, args[0])
  5556. );
  5557. });
  5558. _vm->bindMethod("str", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5559. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5560. return vm->PyStr(_self.__escape(true));
  5561. });
  5562. _vm->bindMethod("str", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  5563. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5564. return vm->PyStr(_self.__escape(false));
  5565. });
  5566. _vm->bindMethod("str", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  5567. if(args[0]->isType(vm->_tp_str) && args[1]->isType(vm->_tp_str))
  5568. return vm->PyBool(vm->PyStr_AS_C(args[0]) == vm->PyStr_AS_C(args[1]));
  5569. return vm->PyBool(args[0] == args[1]); // fallback
  5570. });
  5571. _vm->bindMethod("str", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
  5572. const _Str& _self (vm->PyStr_AS_C(args[0]));
  5573. if(args[1]->isType(vm->_tp_slice)){
  5574. _Slice s = vm->PySlice_AS_C(args[1]);
  5575. s.normalize(_self.u8_length());
  5576. return vm->PyStr(_self.u8_substr(s.start, s.stop));
  5577. }
  5578. int _index = (int)vm->PyInt_AS_C(args[1]);
  5579. _index = vm->normalizedIndex(_index, _self.u8_length());
  5580. return vm->PyStr(_self.u8_getitem(_index));
  5581. });
  5582. _vm->bindMethod("str", "__gt__", [](VM* vm, const pkpy::ArgList& args) {
  5583. const _Str& _self (vm->PyStr_AS_C(args[0]));
  5584. const _Str& _obj (vm->PyStr_AS_C(args[1]));
  5585. return vm->PyBool(_self > _obj);
  5586. });
  5587. _vm->bindMethod("str", "__lt__", [](VM* vm, const pkpy::ArgList& args) {
  5588. const _Str& _self (vm->PyStr_AS_C(args[0]));
  5589. const _Str& _obj (vm->PyStr_AS_C(args[1]));
  5590. return vm->PyBool(_self < _obj);
  5591. });
  5592. _vm->bindMethod("str", "upper", [](VM* vm, const pkpy::ArgList& args) {
  5593. vm->__checkArgSize(args, 1, true);
  5594. const _Str& _self (vm->PyStr_AS_C(args[0]));
  5595. _StrStream ss;
  5596. for(auto c : _self.str()) ss << (char)toupper(c);
  5597. return vm->PyStr(ss.str());
  5598. });
  5599. _vm->bindMethod("str", "lower", [](VM* vm, const pkpy::ArgList& args) {
  5600. vm->__checkArgSize(args, 1, true);
  5601. const _Str& _self (vm->PyStr_AS_C(args[0]));
  5602. _StrStream ss;
  5603. for(auto c : _self.str()) ss << (char)tolower(c);
  5604. return vm->PyStr(ss.str());
  5605. });
  5606. _vm->bindMethod("str", "replace", [](VM* vm, const pkpy::ArgList& args) {
  5607. vm->__checkArgSize(args, 3, true);
  5608. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5609. const _Str& _old = vm->PyStr_AS_C(args[1]);
  5610. const _Str& _new = vm->PyStr_AS_C(args[2]);
  5611. std::string _copy = _self.str();
  5612. // replace all occurences of _old with _new in _copy
  5613. size_t pos = 0;
  5614. while ((pos = _copy.find(_old.str(), pos)) != std::string::npos) {
  5615. _copy.replace(pos, _old.str().length(), _new.str());
  5616. pos += _new.str().length();
  5617. }
  5618. return vm->PyStr(_copy);
  5619. });
  5620. _vm->bindMethod("str", "startswith", [](VM* vm, const pkpy::ArgList& args) {
  5621. vm->__checkArgSize(args, 2, true);
  5622. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5623. const _Str& _prefix = vm->PyStr_AS_C(args[1]);
  5624. return vm->PyBool(_self.str().find(_prefix.str()) == 0);
  5625. });
  5626. _vm->bindMethod("str", "endswith", [](VM* vm, const pkpy::ArgList& args) {
  5627. vm->__checkArgSize(args, 2, true);
  5628. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5629. const _Str& _suffix = vm->PyStr_AS_C(args[1]);
  5630. return vm->PyBool(_self.str().rfind(_suffix.str()) == _self.str().length() - _suffix.str().length());
  5631. });
  5632. _vm->bindMethod("str", "join", [](VM* vm, const pkpy::ArgList& args) {
  5633. vm->__checkArgSize(args, 2, true);
  5634. const _Str& _self = vm->PyStr_AS_C(args[0]);
  5635. PyVarList* _list;
  5636. if(args[1]->isType(vm->_tp_list)){
  5637. _list = &vm->PyList_AS_C(args[1]);
  5638. }else if(args[1]->isType(vm->_tp_tuple)){
  5639. _list = &vm->PyTuple_AS_C(args[1]);
  5640. }else{
  5641. vm->typeError("can only join a list or tuple");
  5642. }
  5643. _StrStream ss;
  5644. for(int i = 0; i < _list->size(); i++){
  5645. if(i > 0) ss << _self;
  5646. ss << vm->PyStr_AS_C(vm->asStr(_list->operator[](i)));
  5647. }
  5648. return vm->PyStr(ss.str());
  5649. });
  5650. /************ PyList ************/
  5651. _vm->bindMethod("list", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  5652. vm->__checkType(args[0], vm->_tp_list);
  5653. return vm->PyIter(
  5654. pkpy::make_shared<_Iterator, VectorIterator>(vm, args[0])
  5655. );
  5656. });
  5657. _vm->bindMethod("list", "append", [](VM* vm, const pkpy::ArgList& args) {
  5658. vm->__checkArgSize(args, 2, true);
  5659. PyVarList& _self = vm->PyList_AS_C(args[0]);
  5660. _self.push_back(args[1]);
  5661. return vm->None;
  5662. });
  5663. _vm->bindMethod("list", "insert", [](VM* vm, const pkpy::ArgList& args) {
  5664. vm->__checkArgSize(args, 3, true);
  5665. PyVarList& _self = vm->PyList_AS_C(args[0]);
  5666. int _index = (int)vm->PyInt_AS_C(args[1]);
  5667. if(_index < 0) _index += _self.size();
  5668. if(_index < 0) _index = 0;
  5669. if(_index > _self.size()) _index = _self.size();
  5670. _self.insert(_self.begin() + _index, args[2]);
  5671. return vm->None;
  5672. });
  5673. _vm->bindMethod("list", "clear", [](VM* vm, const pkpy::ArgList& args) {
  5674. vm->__checkArgSize(args, 1, true);
  5675. vm->PyList_AS_C(args[0]).clear();
  5676. return vm->None;
  5677. });
  5678. _vm->bindMethod("list", "copy", [](VM* vm, const pkpy::ArgList& args) {
  5679. vm->__checkArgSize(args, 1, true);
  5680. return vm->PyList(vm->PyList_AS_C(args[0]));
  5681. });
  5682. _vm->bindMethod("list", "pop", [](VM* vm, const pkpy::ArgList& args) {
  5683. vm->__checkArgSize(args, 1, true);
  5684. PyVarList& _self = vm->PyList_AS_C(args[0]);
  5685. if(_self.empty()) vm->indexError("pop from empty list");
  5686. PyVar ret = _self.back();
  5687. _self.pop_back();
  5688. return ret;
  5689. });
  5690. _vm->bindMethod("list", "__add__", [](VM* vm, const pkpy::ArgList& args) {
  5691. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  5692. const PyVarList& _obj = vm->PyList_AS_C(args[1]);
  5693. PyVarList _new_list = _self;
  5694. _new_list.insert(_new_list.end(), _obj.begin(), _obj.end());
  5695. return vm->PyList(_new_list);
  5696. });
  5697. _vm->bindMethod("list", "__len__", [](VM* vm, const pkpy::ArgList& args) {
  5698. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  5699. return vm->PyInt(_self.size());
  5700. });
  5701. _vm->bindMethod("list", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
  5702. const PyVarList& _self = vm->PyList_AS_C(args[0]);
  5703. if(args[1]->isType(vm->_tp_slice)){
  5704. _Slice s = vm->PySlice_AS_C(args[1]);
  5705. s.normalize(_self.size());
  5706. PyVarList _new_list;
  5707. for(size_t i = s.start; i < s.stop; i++)
  5708. _new_list.push_back(_self[i]);
  5709. return vm->PyList(_new_list);
  5710. }
  5711. int _index = (int)vm->PyInt_AS_C(args[1]);
  5712. _index = vm->normalizedIndex(_index, _self.size());
  5713. return _self[_index];
  5714. });
  5715. _vm->bindMethod("list", "__setitem__", [](VM* vm, const pkpy::ArgList& args) {
  5716. PyVarList& _self = vm->PyList_AS_C(args[0]);
  5717. int _index = (int)vm->PyInt_AS_C(args[1]);
  5718. _index = vm->normalizedIndex(_index, _self.size());
  5719. _self[_index] = args[2];
  5720. return vm->None;
  5721. });
  5722. _vm->bindMethod("list", "__delitem__", [](VM* vm, const pkpy::ArgList& args) {
  5723. PyVarList& _self = vm->PyList_AS_C(args[0]);
  5724. int _index = (int)vm->PyInt_AS_C(args[1]);
  5725. _index = vm->normalizedIndex(_index, _self.size());
  5726. _self.erase(_self.begin() + _index);
  5727. return vm->None;
  5728. });
  5729. /************ PyTuple ************/
  5730. _vm->bindMethod("tuple", "__new__", [](VM* vm, const pkpy::ArgList& args) {
  5731. vm->__checkArgSize(args, 1);
  5732. PyVarList _list = vm->PyList_AS_C(vm->call(vm->builtins->attribs["list"], args));
  5733. return vm->PyTuple(_list);
  5734. });
  5735. _vm->bindMethod("tuple", "__iter__", [](VM* vm, const pkpy::ArgList& args) {
  5736. vm->__checkType(args[0], vm->_tp_tuple);
  5737. return vm->PyIter(
  5738. pkpy::make_shared<_Iterator, VectorIterator>(vm, args[0])
  5739. );
  5740. });
  5741. _vm->bindMethod("tuple", "__len__", [](VM* vm, const pkpy::ArgList& args) {
  5742. const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
  5743. return vm->PyInt(_self.size());
  5744. });
  5745. _vm->bindMethod("tuple", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
  5746. const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
  5747. int _index = (int)vm->PyInt_AS_C(args[1]);
  5748. _index = vm->normalizedIndex(_index, _self.size());
  5749. return _self[_index];
  5750. });
  5751. /************ PyBool ************/
  5752. _vm->bindMethod("bool", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5753. bool val = vm->PyBool_AS_C(args[0]);
  5754. return vm->PyStr(val ? "True" : "False");
  5755. });
  5756. _vm->bindMethod("bool", "__json__", [](VM* vm, const pkpy::ArgList& args) {
  5757. bool val = vm->PyBool_AS_C(args[0]);
  5758. return vm->PyStr(val ? "true" : "false");
  5759. });
  5760. _vm->bindMethod("bool", "__eq__", [](VM* vm, const pkpy::ArgList& args) {
  5761. return vm->PyBool(args[0] == args[1]);
  5762. });
  5763. _vm->bindMethod("bool", "__xor__", [](VM* vm, const pkpy::ArgList& args) {
  5764. bool _self = vm->PyBool_AS_C(args[0]);
  5765. bool _obj = vm->PyBool_AS_C(args[1]);
  5766. return vm->PyBool(_self ^ _obj);
  5767. });
  5768. _vm->bindMethod("ellipsis", "__repr__", [](VM* vm, const pkpy::ArgList& args) {
  5769. return vm->PyStr("Ellipsis");
  5770. });
  5771. _vm->bindMethod("_native_function", "__call__", [](VM* vm, const pkpy::ArgList& args) {
  5772. const _CppFunc& _self = vm->PyNativeFunction_AS_C(args[0]);
  5773. return _self(vm, args.subList(1));
  5774. });
  5775. _vm->bindMethod("function", "__call__", [](VM* vm, const pkpy::ArgList& args) {
  5776. return vm->call(args[0], args.subList(1));
  5777. });
  5778. _vm->bindMethod("_bounded_method", "__call__", [](VM* vm, const pkpy::ArgList& args) {
  5779. vm->__checkType(args[0], vm->_tp_bounded_method);
  5780. const _BoundedMethod& _self = vm->PyBoundedMethod_AS_C(args[0]);
  5781. pkpy::ArgList newArgs(args.size());
  5782. newArgs[0] = _self.obj;
  5783. for(int i = 1; i < args.size(); i++) newArgs[i] = args[i];
  5784. return vm->call(_self.method, newArgs);
  5785. });
  5786. }
  5787. #ifdef _WIN32
  5788. #define __EXPORT __declspec(dllexport)
  5789. #elif __APPLE__
  5790. #define __EXPORT __attribute__((visibility("default"))) __attribute__((used))
  5791. #else
  5792. #define __EXPORT
  5793. #endif
  5794. void __addModuleTime(VM* vm){
  5795. PyVar mod = vm->newModule("time");
  5796. vm->bindFunc(mod, "time", [](VM* vm, const pkpy::ArgList& args) {
  5797. auto now = std::chrono::high_resolution_clock::now();
  5798. return vm->PyFloat(std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count() / 1000000.0);
  5799. });
  5800. vm->bindFunc(mod, "sleep", [](VM* vm, const pkpy::ArgList& args) {
  5801. vm->__checkArgSize(args, 1);
  5802. if(!vm->isIntOrFloat(args[0])){
  5803. vm->typeError("time.sleep() argument must be int or float");
  5804. }
  5805. double sec = vm->numToFloat(args[0]);
  5806. vm->sleepForSecs(sec);
  5807. return vm->None;
  5808. });
  5809. }
  5810. void __addModuleSys(VM* vm){
  5811. PyVar mod = vm->newModule("sys");
  5812. vm->bindFunc(mod, "getrefcount", [](VM* vm, const pkpy::ArgList& args) {
  5813. vm->__checkArgSize(args, 1);
  5814. return vm->PyInt(args[0].use_count());
  5815. });
  5816. vm->bindFunc(mod, "getrecursionlimit", [](VM* vm, const pkpy::ArgList& args) {
  5817. vm->__checkArgSize(args, 0);
  5818. return vm->PyInt(vm->maxRecursionDepth);
  5819. });
  5820. vm->bindFunc(mod, "setrecursionlimit", [](VM* vm, const pkpy::ArgList& args) {
  5821. vm->__checkArgSize(args, 1);
  5822. vm->maxRecursionDepth = (int)vm->PyInt_AS_C(args[0]);
  5823. return vm->None;
  5824. });
  5825. vm->setAttr(mod, "version", vm->PyStr(PK_VERSION));
  5826. }
  5827. void __addModuleJson(VM* vm){
  5828. PyVar mod = vm->newModule("json");
  5829. vm->bindFunc(mod, "loads", [](VM* vm, const pkpy::ArgList& args) {
  5830. vm->__checkArgSize(args, 1);
  5831. const _Str& expr = vm->PyStr_AS_C(args[0]);
  5832. _Code code = compile(vm, expr.c_str(), "<json>", JSON_MODE, false);
  5833. return vm->_exec(code, vm->topFrame()->_module, vm->topFrame()->f_locals);
  5834. });
  5835. vm->bindFunc(mod, "dumps", [](VM* vm, const pkpy::ArgList& args) {
  5836. vm->__checkArgSize(args, 1);
  5837. return vm->asJson(args[0]);
  5838. });
  5839. }
  5840. void __addModuleMath(VM* vm){
  5841. PyVar mod = vm->newModule("math");
  5842. vm->setAttr(mod, "pi", vm->PyFloat(3.1415926535897932384));
  5843. vm->setAttr(mod, "e" , vm->PyFloat(2.7182818284590452354));
  5844. vm->bindFunc(mod, "log", [](VM* vm, const pkpy::ArgList& args) {
  5845. vm->__checkArgSize(args, 1);
  5846. return vm->PyFloat(log(vm->numToFloat(args[0])));
  5847. });
  5848. vm->bindFunc(mod, "log10", [](VM* vm, const pkpy::ArgList& args) {
  5849. vm->__checkArgSize(args, 1);
  5850. return vm->PyFloat(log10(vm->numToFloat(args[0])));
  5851. });
  5852. vm->bindFunc(mod, "log2", [](VM* vm, const pkpy::ArgList& args) {
  5853. vm->__checkArgSize(args, 1);
  5854. return vm->PyFloat(log2(vm->numToFloat(args[0])));
  5855. });
  5856. vm->bindFunc(mod, "sin", [](VM* vm, const pkpy::ArgList& args) {
  5857. vm->__checkArgSize(args, 1);
  5858. return vm->PyFloat(sin(vm->numToFloat(args[0])));
  5859. });
  5860. vm->bindFunc(mod, "cos", [](VM* vm, const pkpy::ArgList& args) {
  5861. vm->__checkArgSize(args, 1);
  5862. return vm->PyFloat(cos(vm->numToFloat(args[0])));
  5863. });
  5864. vm->bindFunc(mod, "tan", [](VM* vm, const pkpy::ArgList& args) {
  5865. vm->__checkArgSize(args, 1);
  5866. return vm->PyFloat(tan(vm->numToFloat(args[0])));
  5867. });
  5868. vm->bindFunc(mod, "isclose", [](VM* vm, const pkpy::ArgList& args) {
  5869. vm->__checkArgSize(args, 2);
  5870. _Float a = vm->numToFloat(args[0]);
  5871. _Float b = vm->numToFloat(args[1]);
  5872. return vm->PyBool(fabs(a - b) < 1e-6);
  5873. });
  5874. }
  5875. class _PkExported{
  5876. public:
  5877. virtual ~_PkExported() = default;
  5878. virtual void* get() = 0;
  5879. };
  5880. static std::vector<_PkExported*> _pkLookupTable;
  5881. template<typename T>
  5882. class PkExported : public _PkExported{
  5883. T* _ptr;
  5884. public:
  5885. template<typename... Args>
  5886. PkExported(Args&&... args) {
  5887. _ptr = new T(std::forward<Args>(args)...);
  5888. _pkLookupTable.push_back(this);
  5889. }
  5890. ~PkExported() override { delete _ptr; }
  5891. void* get() override { return _ptr; }
  5892. operator T*() { return _ptr; }
  5893. };
  5894. #define pkpy_allocate(T, ...) *(new PkExported<T>(__VA_ARGS__))
  5895. extern "C" {
  5896. __EXPORT
  5897. /// Delete a pointer allocated by `pkpy_xxx_xxx`.
  5898. /// It can be `VM*`, `REPL*`, `ThreadedVM*`, `char*`, etc.
  5899. ///
  5900. /// !!!
  5901. /// If the pointer is not allocated by `pkpy_xxx_xxx`, the behavior is undefined.
  5902. /// For char*, you can also use trivial `delete` in your language.
  5903. /// !!!
  5904. void pkpy_delete(void* p){
  5905. for(int i = 0; i < _pkLookupTable.size(); i++){
  5906. if(_pkLookupTable[i]->get() == p){
  5907. delete _pkLookupTable[i];
  5908. _pkLookupTable.erase(_pkLookupTable.begin() + i);
  5909. return;
  5910. }
  5911. }
  5912. free(p);
  5913. }
  5914. __EXPORT
  5915. /// Run a given source on a virtual machine.
  5916. ///
  5917. /// Return `true` if there is no compile error.
  5918. bool pkpy_vm_exec(VM* vm, const char* source){
  5919. _Code code = compile(vm, source, "main.py");
  5920. if(code == nullptr) return false;
  5921. vm->exec(code);
  5922. return true;
  5923. }
  5924. __EXPORT
  5925. /// Get a global variable of a virtual machine.
  5926. ///
  5927. /// Return a json representing the result.
  5928. /// If the variable is not found, return `nullptr`.
  5929. char* pkpy_vm_get_global(VM* vm, const char* name){
  5930. auto it = vm->_main->attribs.find(name);
  5931. if(it == vm->_main->attribs.end()) return nullptr;
  5932. try{
  5933. _Str _json = vm->PyStr_AS_C(vm->asJson(it->second));
  5934. return strdup(_json.c_str());
  5935. }catch(...){
  5936. return nullptr;
  5937. }
  5938. }
  5939. __EXPORT
  5940. /// Evaluate an expression.
  5941. ///
  5942. /// Return a json representing the result.
  5943. /// If there is any error, return `nullptr`.
  5944. char* pkpy_vm_eval(VM* vm, const char* source){
  5945. _Code code = compile(vm, source, "<eval>", EVAL_MODE);
  5946. if(code == nullptr) return nullptr;
  5947. PyVarOrNull ret = vm->exec(code);
  5948. if(ret == nullptr) return nullptr;
  5949. try{
  5950. _Str _json = vm->PyStr_AS_C(vm->asJson(ret));
  5951. return strdup(_json.c_str());
  5952. }catch(...){
  5953. return nullptr;
  5954. }
  5955. }
  5956. __EXPORT
  5957. /// Create a REPL, using the given virtual machine as the backend.
  5958. REPL* pkpy_new_repl(VM* vm){
  5959. return pkpy_allocate(REPL, vm);
  5960. }
  5961. __EXPORT
  5962. /// Input a source line to an interactive console.
  5963. ///
  5964. /// Return `0` if need more lines,
  5965. /// `1` if execution happened,
  5966. /// `2` if execution skipped (compile error or empty input).
  5967. int pkpy_repl_input(REPL* r, const char* line){
  5968. return r->input(line);
  5969. }
  5970. __EXPORT
  5971. /// Add a source module into a virtual machine.
  5972. ///
  5973. /// Return `true` if there is no complie error.
  5974. bool pkpy_vm_add_module(VM* vm, const char* name, const char* source){
  5975. // compile the module but don't execute it
  5976. _Code code = compile(vm, source, name + _Str(".py"));
  5977. if(code == nullptr) return false;
  5978. vm->addLazyModule(name, code);
  5979. return true;
  5980. }
  5981. void __vm_init(VM* vm){
  5982. __initializeBuiltinFunctions(vm);
  5983. __addModuleSys(vm);
  5984. __addModuleTime(vm);
  5985. __addModuleJson(vm);
  5986. __addModuleMath(vm);
  5987. _Code code = compile(vm, __BUILTINS_CODE, "<builtins>");
  5988. if(code == nullptr) exit(1);
  5989. vm->_exec(code, vm->builtins, {});
  5990. pkpy_vm_add_module(vm, "random", __RANDOM_CODE);
  5991. pkpy_vm_add_module(vm, "os", __OS_CODE);
  5992. }
  5993. __EXPORT
  5994. /// Create a virtual machine.
  5995. VM* pkpy_new_vm(bool use_stdio){
  5996. VM* vm = pkpy_allocate(VM, use_stdio);
  5997. __vm_init(vm);
  5998. return vm;
  5999. }
  6000. __EXPORT
  6001. /// Create a virtual machine that supports asynchronous execution.
  6002. ThreadedVM* pkpy_new_tvm(bool use_stdio){
  6003. ThreadedVM* vm = pkpy_allocate(ThreadedVM, use_stdio);
  6004. __vm_init(vm);
  6005. return vm;
  6006. }
  6007. __EXPORT
  6008. /// Read the standard output and standard error as string of a virtual machine.
  6009. /// The `vm->use_stdio` should be `false`.
  6010. /// After this operation, both stream will be cleared.
  6011. ///
  6012. /// Return a json representing the result.
  6013. char* pkpy_vm_read_output(VM* vm){
  6014. if(vm->use_stdio) return nullptr;
  6015. _StrStream* s_out = dynamic_cast<_StrStream*>(vm->_stdout);
  6016. _StrStream* s_err = dynamic_cast<_StrStream*>(vm->_stderr);
  6017. _Str _stdout = s_out->str();
  6018. _Str _stderr = s_err->str();
  6019. _StrStream ss;
  6020. ss << '{' << "\"stdout\": " << _stdout.__escape(false);
  6021. ss << ", ";
  6022. ss << "\"stderr\": " << _stderr.__escape(false) << '}';
  6023. s_out->str("");
  6024. s_err->str("");
  6025. return strdup(ss.str().c_str());
  6026. }
  6027. __EXPORT
  6028. /// Get the current state of a threaded virtual machine.
  6029. ///
  6030. /// Return `0` for `THREAD_READY`,
  6031. /// `1` for `THREAD_RUNNING`,
  6032. /// `2` for `THREAD_SUSPENDED`,
  6033. /// `3` for `THREAD_FINISHED`.
  6034. int pkpy_tvm_get_state(ThreadedVM* vm){
  6035. return vm->getState();
  6036. }
  6037. __EXPORT
  6038. /// Set the state of a threaded virtual machine to `THREAD_READY`.
  6039. /// The current state should be `THREAD_FINISHED`.
  6040. void pkpy_tvm_reset_state(ThreadedVM* vm){
  6041. vm->resetState();
  6042. }
  6043. __EXPORT
  6044. /// Read the current JSONRPC request from shared string buffer.
  6045. char* pkpy_tvm_read_jsonrpc_request(ThreadedVM* vm){
  6046. _Str s = vm->readJsonRpcRequest();
  6047. return strdup(s.c_str());
  6048. }
  6049. __EXPORT
  6050. /// Write a JSONRPC response to shared string buffer.
  6051. void pkpy_tvm_write_jsonrpc_response(ThreadedVM* vm, const char* value){
  6052. vm->writeJsonrpcResponse(value);
  6053. }
  6054. __EXPORT
  6055. /// Emit a KeyboardInterrupt signal to stop a running threaded virtual machine.
  6056. void pkpy_tvm_terminate(ThreadedVM* vm){
  6057. vm->terminate();
  6058. }
  6059. __EXPORT
  6060. /// Run a given source on a threaded virtual machine.
  6061. /// The excution will be started in a new thread.
  6062. ///
  6063. /// Return `true` if there is no compile error.
  6064. bool pkpy_tvm_exec_async(VM* vm, const char* source){
  6065. // although this is a method of VM, it's only used in ThreadedVM
  6066. _Code code = compile(vm, source, "main.py");
  6067. if(code == nullptr) return false;
  6068. vm->execAsync(code);
  6069. return true;
  6070. }
  6071. }
  6072. #endif // POCKETPY_H