pocketpy.c 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035
  1. /*
  2. * Copyright (c) 2026 blueloveTH
  3. * Distributed Under The MIT License
  4. * https://github.com/pocketpy/pocketpy
  5. */
  6. #define PK_IS_AMALGAMATED_C
  7. #include "pocketpy.h"
  8. // LYNX: set by the host (src/core/Python.cpp) to interrupt a script that runs too long; checked once per opcode
  9. volatile int py_lynx_interrupt = 0;
  10. // LYNX heap: pocketpy's allocations, counted (all VMs run on the host's one Python thread). Past py_lynx_heap_limit
  11. // the script is interrupted (py_lynx_out_of_memory says why); an allocation past twice the limit fails.
  12. #include <stdlib.h>
  13. size_t py_lynx_heap_limit = (size_t)768 << 20;
  14. size_t py_lynx_heap_bytes = 0;
  15. volatile int py_lynx_out_of_memory = 0;
  16. #define LYNX_HEAP_HEADER 16
  17. static int py_lynx_heap_allows(size_t grow) {
  18. if(py_lynx_heap_bytes + grow > py_lynx_heap_limit) {
  19. py_lynx_out_of_memory = 1;
  20. py_lynx_interrupt = 1;
  21. if(py_lynx_heap_bytes + grow > py_lynx_heap_limit * 2) return 0;
  22. }
  23. return 1;
  24. }
  25. // LYNX: one operation that asks for more than the heap has left in a single go (a big repeat such as
  26. // 'x' * 2_000_000_000 or [0] * 300_000_000, list() of a long iterator) is stopped with the memory message before it
  27. // allocates: past twice the limit an allocation fails, and pocketpy's growth code aborts the process on a failed
  28. // allocation (c11_vector__reserve) or writes through the null pointer (a big string), taking the host down with it.
  29. static int py_lynx_heap_room(size_t bytes) {
  30. if(bytes > py_lynx_heap_limit || py_lynx_heap_bytes + bytes > py_lynx_heap_limit) {
  31. py_lynx_out_of_memory = 1;
  32. py_lynx_interrupt = 1;
  33. return 0;
  34. }
  35. return 1;
  36. }
  37. void* py_lynx_malloc(size_t size) {
  38. if(!py_lynx_heap_allows(size)) return NULL;
  39. size_t* p = (size_t*)malloc(size + LYNX_HEAP_HEADER);
  40. if(!p) return NULL;
  41. p[0] = size;
  42. py_lynx_heap_bytes += size;
  43. return (char*)p + LYNX_HEAP_HEADER;
  44. }
  45. void* py_lynx_realloc(void* ptr, size_t size) {
  46. if(!ptr) return py_lynx_malloc(size);
  47. size_t* base = (size_t*)((char*)ptr - LYNX_HEAP_HEADER);
  48. size_t old = base[0];
  49. if(size > old && !py_lynx_heap_allows(size - old)) return NULL;
  50. size_t* p = (size_t*)realloc(base, size + LYNX_HEAP_HEADER);
  51. if(!p) return NULL;
  52. p[0] = size;
  53. py_lynx_heap_bytes = py_lynx_heap_bytes - old + size;
  54. return (char*)p + LYNX_HEAP_HEADER;
  55. }
  56. void py_lynx_free(void* ptr) {
  57. if(!ptr) return;
  58. size_t* base = (size_t*)((char*)ptr - LYNX_HEAP_HEADER);
  59. py_lynx_heap_bytes -= base[0];
  60. free(base);
  61. }
  62. // common/_generated.h
  63. // generated by prebuild.py
  64. const char* load_kPythonLib(const char* name);
  65. extern const char kPythonLibs_bisect[];
  66. extern const char kPythonLibs_builtins[];
  67. extern const char kPythonLibs_cmath[];
  68. extern const char kPythonLibs_collections[];
  69. extern const char kPythonLibs_dataclasses[];
  70. extern const char kPythonLibs_datetime[];
  71. extern const char kPythonLibs_functools[];
  72. extern const char kPythonLibs_heapq[];
  73. extern const char kPythonLibs_inspect[];
  74. extern const char kPythonLibs_long_v1[];
  75. extern const char kPythonLibs_operator[];
  76. extern const char kPythonLibs_typing[];
  77. // common/_log_spline_tbl.h
  78. /*
  79. Copyright (c) 2012,2013 Axel Kohlmeyer <akohlmey@gmail.com>
  80. All rights reserved.
  81. Redistribution and use in source and binary forms, with or without
  82. modification, are permitted provided that the following conditions
  83. are met:
  84. * Redistributions of source code must retain the above copyright
  85. notice, this list of conditions and the following disclaimer.
  86. * Redistributions in binary form must reproduce the above copyright
  87. notice, this list of conditions and the following disclaimer in the
  88. documentation and/or other materials provided with the distribution.
  89. * Neither the name of the <organization> nor the
  90. names of its contributors may be used to endorse or promote products
  91. derived from this software without specific prior written permission.
  92. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  93. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  94. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  95. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  96. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  97. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  99. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  100. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  101. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  102. */
  103. static const double fm_log_dinv = 4.09600000000000000000e+03;
  104. static const double fm_log_dsq6 = 9.93410746256510361521e-09;
  105. static const double fm_log_q1[] = {
  106. 0.00000000000000000000e+00, 2.44110827527362707389e-04,
  107. 4.88162079501351187181e-04, 7.32153784993847520958e-04,
  108. 9.76085973055458924752e-04, 1.21995867271553880967e-03,
  109. 1.46377191298220740885e-03, 1.70752572284237243150e-03,
  110. 1.95122013126174933748e-03, 2.19485516718488302135e-03,
  111. 2.43843085953516754485e-03, 2.68194723721486717044e-03,
  112. 2.92540432910513587689e-03, 3.16880216406604034440e-03,
  113. 3.41214077093657773554e-03, 3.65542017853469781291e-03,
  114. 3.89864041565732288852e-03, 4.14180151108036864044e-03,
  115. 4.38490349355876492948e-03, 4.62794639182647314646e-03,
  116. 4.87093023459651223300e-03, 5.11385505056097429410e-03,
  117. 5.35672086839104454742e-03, 5.59952771673702821148e-03,
  118. 5.84227562422836091405e-03, 6.08496461947363731504e-03,
  119. 6.32759473106062758641e-03, 6.57016598755629822881e-03,
  120. 6.81267841750683115359e-03, 7.05513204943764623417e-03,
  121. 7.29752691185341952063e-03, 7.53986303323810405641e-03,
  122. 7.78214044205494896028e-03, 8.02435916674652111036e-03,
  123. 8.26651923573472682816e-03, 8.50862067742082402166e-03,
  124. 8.75066352018545254299e-03, 8.99264779238864719879e-03,
  125. 9.23457352236985856697e-03, 9.47644073844797554806e-03,
  126. 9.71824946892134618193e-03, 9.95999974206778979080e-03,
  127. 1.02016915861446264696e-02, 1.04433250293886909638e-02,
  128. 1.06849001000163534858e-02, 1.09264168262235422668e-02,
  129. 1.11678752361857574343e-02, 1.14092753580580970330e-02,
  130. 1.16506172199752743718e-02, 1.18919008500516353716e-02,
  131. 1.21331262763811845856e-02, 1.23742935270375938733e-02,
  132. 1.26154026300742353600e-02, 1.28564536135241883757e-02,
  133. 1.30974465054002689457e-02, 1.33383813336950454026e-02,
  134. 1.35792581263808539993e-02, 1.38200769114098266643e-02,
  135. 1.40608377167139014102e-02, 1.43015405702048535586e-02,
  136. 1.45421854997742992094e-02, 1.47827725332937282010e-02,
  137. 1.50233016986145197225e-02, 1.52637730235679579260e-02,
  138. 1.55041865359652544787e-02, 1.57445422635975676440e-02,
  139. 1.59848402342360230988e-02, 1.62250804756317243416e-02,
  140. 1.64652630155157908565e-02, 1.67053878815993511742e-02,
  141. 1.69454551015735914443e-02, 1.71854647031097450272e-02,
  142. 1.74254167138591341268e-02, 1.76653111614531801998e-02,
  143. 1.79051480735034213021e-02, 1.81449274776015329058e-02,
  144. 1.83846494013193521855e-02, 1.86243138722088884263e-02,
  145. 1.88639209178023438407e-02, 1.91034705656121447936e-02,
  146. 1.93429628431309348635e-02, 1.95823977778316234144e-02,
  147. 1.98217753971673821267e-02, 2.00610957285716796916e-02,
  148. 2.03003587994582852805e-02, 2.05395646372212997699e-02,
  149. 2.07787132692351730889e-02, 2.10178047228547111580e-02,
  150. 2.12568390254151175223e-02, 2.14958162042319829432e-02,
  151. 2.17347362866013270322e-02, 2.19735992997996155973e-02,
  152. 2.22124052710837606439e-02, 2.24511542276911585381e-02,
  153. 2.26898461968397004151e-02, 2.29284812057277964659e-02,
  154. 2.31670592815343794058e-02, 2.34055804514189426391e-02,
  155. 2.36440447425215437283e-02, 2.38824521819628390884e-02,
  156. 2.41208027968440805178e-02, 2.43590966142471533618e-02,
  157. 2.45973336612345834518e-02, 2.48355139648495648608e-02,
  158. 2.50736375521159599034e-02, 2.53117044500383477079e-02,
  159. 2.55497146856020138084e-02, 2.57876682857729813692e-02,
  160. 2.60255652774980320019e-02, 2.62634056877047161738e-02,
  161. 2.65011895433013774936e-02, 2.67389168711771700593e-02,
  162. 2.69765876982020758046e-02, 2.72142020512269183774e-02,
  163. 2.74517599570833874256e-02, 2.76892614425840594139e-02,
  164. 2.79267065345224080319e-02, 2.81640952596728215418e-02,
  165. 2.84014276447906305334e-02, 2.86387037166121183329e-02,
  166. 2.88759235018545418194e-02, 2.91130870272161487722e-02,
  167. 2.93501943193761917483e-02, 2.95872454049949593080e-02,
  168. 2.98242403107137760143e-02, 3.00611790631550336583e-02,
  169. 3.02980616889222051369e-02, 3.05348882145998617998e-02,
  170. 3.07716586667536873279e-02, 3.10083730719305089574e-02,
  171. 3.12450314566582974807e-02, 3.14816338474461984709e-02,
  172. 3.17181802707845392209e-02, 3.19546707531448703765e-02,
  173. 3.21911053209799416508e-02, 3.24274840007237608042e-02,
  174. 3.26638068187915936447e-02, 3.29000738015799848446e-02,
  175. 3.31362849754667510016e-02, 3.33724403668110569665e-02,
  176. 3.36085400019533672711e-02, 3.38445839072155085780e-02,
  177. 3.40805721089006696811e-02, 3.43165046332934153828e-02,
  178. 3.45523815066597350665e-02, 3.47882027552470010634e-02,
  179. 3.50239684052840449802e-02, 3.52596784829811438211e-02,
  180. 3.54953330145300408049e-02, 3.57309320261039800593e-02,
  181. 3.59664755438576927427e-02, 3.62019635939274456171e-02,
  182. 3.64373962024310479868e-02, 3.66727733954678516981e-02,
  183. 3.69080951991187997119e-02, 3.71433616394464122257e-02,
  184. 3.73785727424948352460e-02, 3.76137285342898197715e-02,
  185. 3.78488290408387842434e-02, 3.80838742881307937282e-02,
  186. 3.83188643021366015518e-02, 3.85537991088086354208e-02,
  187. 3.87886787340810668123e-02, 3.90235032038697762791e-02,
  188. 3.92582725440723950827e-02, 3.94929867805683190718e-02,
  189. 3.97276459392187364372e-02, 3.99622500458666138345e-02,
  190. 4.01967991263367518950e-02, 4.04312932064357782869e-02,
  191. 4.06657323119521615928e-02, 4.09001164686562529438e-02,
  192. 4.11344457023002721408e-02, 4.13687200386183492884e-02,
  193. 4.16029395033265247950e-02, 4.18371041221227840667e-02,
  194. 4.20712139206870575081e-02, 4.23052689246812343993e-02,
  195. 4.25392691597492184075e-02, 4.27732146515168790146e-02,
  196. 4.30071054255921278453e-02, 4.32409415075649117277e-02,
  197. 4.34747229230072265715e-02, 4.37084496974731243069e-02,
  198. 4.39421218564987614563e-02, 4.41757394256023921963e-02,
  199. 4.44093024302843961126e-02, 4.46428108960272643224e-02,
  200. 4.48762648482956758023e-02, 4.51096643125364488158e-02,
  201. 4.53430093141786172417e-02, 4.55762998786333820012e-02,
  202. 4.58095360312942012637e-02, 4.60427177975367488139e-02,
  203. 4.62758452027189418065e-02, 4.65089182721809893395e-02,
  204. 4.67419370312453785754e-02, 4.69749015052168886197e-02,
  205. 4.72078117193826252151e-02, 4.74406676990120346193e-02,
  206. 4.76734694693569036050e-02, 4.79062170556513941544e-02,
  207. 4.81389104831120573369e-02, 4.83715497769378263704e-02,
  208. 4.86041349623100790711e-02, 4.88366660643926031593e-02,
  209. 4.90691431083316448314e-02, 4.93015661192559226378e-02,
  210. 4.95339351222766274829e-02, 4.97662501424874642586e-02,
  211. 4.99985112049646240884e-02, 5.02307183347668675943e-02,
  212. 5.04628715569354693860e-02, 5.06949708964942874490e-02,
  213. 5.09270163784497562065e-02, 5.11590080277909073359e-02,
  214. 5.13909458694893697683e-02, 5.16228299284994252005e-02,
  215. 5.18546602297579733998e-02, 5.20864367981846085320e-02,
  216. 5.23181596586815636507e-02, 5.25498288361337939634e-02,
  217. 5.27814443554089490762e-02, 5.30130062413574076885e-02,
  218. 5.32445145188122845314e-02, 5.34759692125894581238e-02,
  219. 5.37073703474875707720e-02, 5.39387179482880632642e-02,
  220. 5.41700120397551818097e-02, 5.44012526466359849775e-02,
  221. 5.46324397936603645132e-02, 5.48635735055410730943e-02,
  222. 5.50946538069737382082e-02, 5.53256807226368482744e-02,
  223. 5.55566542771918150945e-02, 5.57875744952829599743e-02,
  224. 5.60184414015375206630e-02, 5.62492550205656929863e-02,
  225. 5.64800153769606447240e-02, 5.67107224952985156108e-02,
  226. 5.69413764001384242741e-02, 5.71719771160225237461e-02,
  227. 5.74025246674759737076e-02, 5.76330190790069890605e-02,
  228. 5.78634603751068329891e-02, 5.80938485802498377764e-02,
  229. 5.83241837188934394987e-02, 5.85544658154781641479e-02,
  230. 5.87846948944276553872e-02, 5.90148709801487023063e-02,
  231. 5.92449940970312324828e-02, 5.94750642694483605544e-02,
  232. 5.97050815217563465853e-02, 5.99350458782946862724e-02,
  233. 6.01649573633860623723e-02, 6.03948160013363932741e-02,
  234. 6.06246218164348399382e-02, 6.08543748329538267128e-02,
  235. 6.10840750751490343951e-02, 6.13137225672594557424e-02,
  236. 6.15433173335073746557e-02, 6.17728593980984008738e-02,
  237. 6.20023487852214699734e-02, 6.22317855190488850026e-02,
  238. 6.24611696237362887252e-02, 6.26905011234227399486e-02,
  239. 6.29197800422306580126e-02, 6.31490064042658921784e-02,
  240. 6.33781802336177285673e-02, 6.36073015543588693443e-02,
  241. 6.38363703905454882293e-02, 6.40653867662172443742e-02,
  242. 6.42943507053972546084e-02, 6.45232622320921628267e-02,
  243. 6.47521213702921261124e-02, 6.49809281439708147365e-02,
  244. 6.52096825770854676696e-02, 6.54383846935768787034e-02,
  245. 6.56670345173694380847e-02, 6.58956320723710908815e-02,
  246. 6.61241773824734202503e-02, 6.63526704715516196798e-02,
  247. 6.65811113634645346249e-02, 6.68095000820546486286e-02,
  248. 6.70378366511480972001e-02, 6.72661210945547510809e-02,
  249. 6.74943534360681191009e-02, 6.77225336994654592004e-02,
  250. 6.79506619085077506748e-02, 6.81787380869397080518e-02,
  251. 6.84067622584897949700e-02, 6.86347344468702658116e-02,
  252. 6.88626546757771518248e-02, 6.90905229688902888796e-02,
  253. 6.93183393498733174676e-02, 6.95461038423737382130e-02,
  254. 6.97738164700228424842e-02, 7.00014772564358511708e-02,
  255. 7.02290862252118036624e-02, 7.04566433999336549920e-02,
  256. 7.06841488041682619592e-02, 7.09116024614664108849e-02,
  257. 7.11390043953627759787e-02, 7.13663546293760442385e-02,
  258. 7.15936531870088183060e-02, 7.18209000917476997339e-02,
  259. 7.20480953670632612296e-02, 7.22752390364101160447e-02,
  260. 7.25023311232268624638e-02, 7.27293716509361670708e-02,
  261. 7.29563606429447231161e-02, 7.31832981226432782718e-02,
  262. 7.34101841134067040207e-02, 7.36370186385939123896e-02,
  263. 7.38638017215479669719e-02, 7.40905333855960135381e-02,
  264. 7.43172136540493771806e-02, 7.45438425502034929249e-02,
  265. 7.47704200973380028739e-02, 7.49969463187166729412e-02,
  266. 7.52234212375875316292e-02, 7.54498448771827451287e-02,
  267. 7.56762172607187699747e-02, 7.59025384113962420241e-02,
  268. 7.61288083524001013558e-02, 7.63550271068994951262e-02,
  269. 7.65811946980478885916e-02, 7.68073111489830512300e-02,
  270. 7.70333764828270151082e-02, 7.72593907226861720261e-02,
  271. 7.74853538916512596391e-02, 7.77112660127973059465e-02,
  272. 7.79371271091837819478e-02, 7.81629372038544767420e-02,
  273. 7.83886963198376085504e-02, 7.86144044801457830829e-02,
  274. 7.88400617077760212936e-02, 7.90656680257098148923e-02,
  275. 7.92912234569130569550e-02, 7.95167280243361529468e-02,
  276. 7.97421817509139374547e-02, 7.99675846595657713323e-02,
  277. 8.01929367731955139442e-02, 8.04182381146915231662e-02,
  278. 8.06434887069267247739e-02, 8.08686885727585569317e-02,
  279. 8.10938377350290395817e-02, 8.13189362165647605662e-02,
  280. 8.15439840401769033829e-02, 8.17689812286612333070e-02,
  281. 8.19939278047981806585e-02, 8.22188237913527297795e-02,
  282. 8.24436692110745855677e-02, 8.26684640866980763318e-02,
  283. 8.28932084409421815474e-02, 8.31179022965106151233e-02,
  284. 8.33425456760917421350e-02, 8.35671386023586620917e-02,
  285. 8.37916810979692228134e-02, 8.40161731855659649204e-02,
  286. 8.42406148877762328553e-02, 8.44650062272121054940e-02,
  287. 8.46893472264704516572e-02, 8.49136379081329439877e-02,
  288. 8.51378782947660450731e-02, 8.53620684089210490786e-02,
  289. 8.55862082731341095032e-02, 8.58102979099261975460e-02,
  290. 8.60343373418031576172e-02, 8.62583265912557073385e-02,
  291. 8.64822656807594791761e-02, 8.67061546327749649299e-02,
  292. 8.69299934697476128775e-02, 8.71537822141077861415e-02,
  293. 8.73775208882708043223e-02, 8.76012095146369157428e-02,
  294. 8.78248481155913807150e-02, 8.80484367135044021513e-02,
  295. 8.82719753307312088308e-02, 8.84954639896120276443e-02,
  296. 8.87189027124721391049e-02, 8.89422915216218218371e-02,
  297. 8.91656304393564219657e-02, 8.93889194879563669938e-02,
  298. 8.96121586896871380468e-02, 8.98353480667993115061e-02,
  299. 9.00584876415286006424e-02, 9.02815774360957862266e-02,
  300. 9.05046174727068136745e-02, 9.07276077735527791690e-02,
  301. 9.09505483608099157822e-02, 9.11734392566396351087e-02,
  302. 9.13962804831885272661e-02, 9.16190720625884025274e-02,
  303. 9.18418140169562635666e-02, 9.20645063683943332133e-02,
  304. 9.22871491389900822089e-02, 9.25097423508162430839e-02,
  305. 9.27322860259307685249e-02, 9.29547801863769285191e-02,
  306. 9.31772248541832964763e-02, 9.33996200513636798402e-02,
  307. 9.36219657999172727436e-02, 9.38442621218285727425e-02,
  308. 9.40665090390674085707e-02, 9.42887065735889817741e-02,
  309. 9.45108547473338389544e-02, 9.47329535822279272805e-02,
  310. 9.49550031001825944887e-02, 9.51770033230945750047e-02,
  311. 9.53989542728460315768e-02, 9.56208559713045552764e-02,
  312. 9.58427084403232071308e-02, 9.60645117017404626125e-02,
  313. 9.62862657773803226613e-02, 9.65079706890522165397e-02,
  314. 9.67296264585511128553e-02, 9.69512331076574779276e-02,
  315. 9.71727906581372896655e-02, 9.73942991317420792008e-02,
  316. 9.76157585502089170104e-02, 9.78371689352604545498e-02,
  317. 9.80585303086048687415e-02, 9.82798426919359729981e-02,
  318. 9.85011061069331617102e-02, 9.87223205752614380026e-02,
  319. 9.89434861185714414900e-02, 9.91646027584994482762e-02,
  320. 9.93856705166673570773e-02, 9.96066894146827863654e-02,
  321. 9.98276594741389772247e-02, 1.00048580716614876618e-01,
  322. 1.00269453163675151264e-01, 1.00490276836870159882e-01,
  323. 1.00711051757735994827e-01, 1.00931777947794482087e-01,
  324. 1.01152455428553222916e-01, 1.01373084221505552205e-01,
  325. 1.01593664348130593988e-01, 1.01814195829893261447e-01,
  326. 1.02034678688244284661e-01, 1.02255112944620182858e-01,
  327. 1.02475498620443319919e-01, 1.02695835737121890507e-01,
  328. 1.02916124316049961696e-01, 1.03136364378607417458e-01,
  329. 1.03356555946160069692e-01, 1.03576699040059588830e-01,
  330. 1.03796793681643559348e-01, 1.04016839892235493648e-01,
  331. 1.04236837693144804295e-01, 1.04456787105666845661e-01,
  332. 1.04676688151082941669e-01, 1.04896540850660371924e-01,
  333. 1.05116345225652385587e-01, 1.05336101297298229129e-01,
  334. 1.05555809086823132459e-01, 1.05775468615438378306e-01,
  335. 1.05995079904341218957e-01, 1.06214642974714987278e-01,
  336. 1.06434157847729041202e-01, 1.06653624544538833119e-01,
  337. 1.06873043086285854364e-01, 1.07092413494097690729e-01,
  338. 1.07311735789088050219e-01, 1.07531009992356721416e-01,
  339. 1.07750236124989628994e-01, 1.07969414208058833715e-01,
  340. 1.08188544262622546310e-01, 1.08407626309725127478e-01,
  341. 1.08626660370397129518e-01, 1.08845646465655254698e-01,
  342. 1.09064584616502438519e-01, 1.09283474843927794207e-01,
  343. 1.09502317168906668221e-01, 1.09721111612400654134e-01,
  344. 1.09939858195357564874e-01, 1.10158556938711474360e-01,
  345. 1.10377207863382731379e-01, 1.10595810990277973462e-01,
  346. 1.10814366340290113011e-01, 1.11032873934298378926e-01,
  347. 1.11251333793168288855e-01, 1.11469745937751746334e-01,
  348. 1.11688110388886929769e-01, 1.11906427167398417333e-01,
  349. 1.12124696294097117577e-01, 1.12342917789780338822e-01,
  350. 1.12561091675231775278e-01, 1.12779217971221507044e-01,
  351. 1.12997296698506041746e-01, 1.13215327877828272896e-01,
  352. 1.13433311529917590921e-01, 1.13651247675489786015e-01,
  353. 1.13869136335247131409e-01, 1.14086977529878327853e-01,
  354. 1.14304771280058628524e-01, 1.14522517606449728000e-01,
  355. 1.14740216529699845527e-01, 1.14957868070443711139e-01,
  356. 1.15175472249302593419e-01, 1.15393029086884285617e-01,
  357. 1.15610538603783147282e-01, 1.15828000820580104269e-01,
  358. 1.16045415757842648730e-01, 1.16262783436124880754e-01,
  359. 1.16480103875967480609e-01, 1.16697377097897722620e-01,
  360. 1.16914603122429544557e-01, 1.17131781970063506004e-01,
  361. 1.17348913661286788357e-01, 1.17565998216573264212e-01,
  362. 1.17783035656383455736e-01, 1.18000026001164562417e-01,
  363. 1.18216969271350488824e-01, 1.18433865487361844604e-01,
  364. 1.18650714669605930607e-01, 1.18867516838476808272e-01,
  365. 1.19084272014355257996e-01, 1.19300980217608820766e-01,
  366. 1.19517641468591770404e-01, 1.19734255787645210711e-01,
  367. 1.19950823195096950569e-01, 1.20167343711261670469e-01,
  368. 1.20383817356440825375e-01, 1.20600244150922672470e-01,
  369. 1.20816624114982326677e-01, 1.21032957268881732893e-01,
  370. 1.21249243632869679876e-01, 1.21465483227181855752e-01,
  371. 1.21681676072040778624e-01, 1.21897822187655879844e-01,
  372. 1.22113921594223476252e-01, 1.22329974311926811814e-01,
  373. 1.22545980360936043740e-01, 1.22761939761408242489e-01,
  374. 1.22977852533487461151e-01, 1.23193718697304666065e-01,
  375. 1.23409538272977806206e-01, 1.23625311280611813181e-01,
  376. 1.23841037740298615111e-01, 1.24056717672117122753e-01,
  377. 1.24272351096133243376e-01, 1.24487938032399964028e-01,
  378. 1.24703478500957240516e-01, 1.24918972521832094547e-01,
  379. 1.25134420115038641486e-01, 1.25349821300578007088e-01,
  380. 1.25565176098438396890e-01, 1.25780484528595165594e-01,
  381. 1.25995746611010733806e-01, 1.26210962365634615789e-01,
  382. 1.26426131812403447219e-01, 1.26641254971241012939e-01,
  383. 1.26856331862058274718e-01, 1.27071362504753287981e-01,
  384. 1.27286346919211340589e-01, 1.27501285125304814061e-01,
  385. 1.27716177142893322349e-01, 1.27931022991823739599e-01,
  386. 1.28145822691930033610e-01, 1.28360576263033487887e-01,
  387. 1.28575283724942590613e-01, 1.28789945097453034650e-01,
  388. 1.29004560400347856319e-01, 1.29219129653397241109e-01,
  389. 1.29433652876358717965e-01, 1.29648130088977159291e-01,
  390. 1.29862561310984586660e-01, 1.30076946562100476124e-01,
  391. 1.30291285862031563925e-01, 1.30505579230471902008e-01,
  392. 1.30719826687102885776e-01, 1.30934028251593309600e-01,
  393. 1.31148183943599283552e-01, 1.31362293782764316674e-01,
  394. 1.31576357788719261466e-01, 1.31790375981082452661e-01,
  395. 1.32004348379459540697e-01, 1.32218275003443658244e-01,
  396. 1.32432155872615309189e-01, 1.32645991006542507407e-01,
  397. 1.32859780424780610231e-01, 1.33073524146872568252e-01,
  398. 1.33287222192348703276e-01, 1.33500874580726874852e-01,
  399. 1.33714481331512369255e-01, 1.33928042464198038264e-01,
  400. 1.34141557998264243645e-01, 1.34355027953178857159e-01,
  401. 1.34568452348397260554e-01, 1.34781831203362401084e-01,
  402. 1.34995164537504819258e-01, 1.35208452370242593332e-01,
  403. 1.35421694720981339310e-01, 1.35634891609114321964e-01,
  404. 1.35848043054022371567e-01, 1.36061149075073939407e-01,
  405. 1.36274209691625097784e-01, 1.36487224923019567768e-01,
  406. 1.36700194788588663686e-01, 1.36913119307651376388e-01,
  407. 1.37125998499514401008e-01, 1.37338832383471998178e-01,
  408. 1.37551620978806243834e-01, 1.37764364304786807169e-01,
  409. 1.37977062380671117170e-01, 1.38189715225704279344e-01,
  410. 1.38402322859119131238e-01, 1.38614885300136297941e-01,
  411. 1.38827402567964081070e-01, 1.39039874681798569789e-01,
  412. 1.39252301660823613050e-01, 1.39464683524210875110e-01,
  413. 1.39677020291119724504e-01, 1.39889311980697400584e-01,
  414. 1.40101558612078930244e-01, 1.40313760204387127928e-01,
  415. 1.40525916776732706648e-01, 1.40738028348214166963e-01,
  416. 1.40950094937917824733e-01, 1.41162116564917949901e-01,
  417. 1.41374093248276627710e-01, 1.41586025007043814217e-01,
  418. 1.41797911860257336292e-01, 1.42009753826943030397e-01,
  419. 1.42221550926114520541e-01, 1.42433303176773412568e-01,
  420. 1.42645010597909210892e-01, 1.42856673208499401762e-01,
  421. 1.43068291027509425506e-01, 1.43279864073892648779e-01,
  422. 1.43491392366590420071e-01, 1.43702875924532069707e-01,
  423. 1.43914314766634937603e-01, 1.44125708911804373269e-01,
  424. 1.44337058378933680292e-01, 1.44548363186904282873e-01,
  425. 1.44759623354585531541e-01, 1.44970838900834897434e-01,
  426. 1.45182009844497889040e-01, 1.45393136204408079948e-01,
  427. 1.45604217999387053339e-01, 1.45815255248244596276e-01,
  428. 1.46026247969778477653e-01, 1.46237196182774614739e-01,
  429. 1.46448099906007073168e-01, 1.46658959158237983678e-01,
  430. 1.46869773958217680887e-01, 1.47080544324684536761e-01,
  431. 1.47291270276365154901e-01, 1.47501951831974315033e-01,
  432. 1.47712589010214945251e-01, 1.47923181829778122021e-01,
  433. 1.48133730309343181197e-01, 1.48344234467577607006e-01,
  434. 1.48554694323137143064e-01, 1.48765109894665709112e-01,
  435. 1.48975481200795512038e-01, 1.49185808260146962612e-01,
  436. 1.49396091091328730993e-01, 1.49606329712937774490e-01,
  437. 1.49816524143559282045e-01, 1.50026674401766757505e-01,
  438. 1.50236780506121964107e-01, 1.50446842475175063258e-01,
  439. 1.50656860327464364735e-01, 1.50866834081516687505e-01,
  440. 1.51076763755846998905e-01, 1.51286649368958775463e-01,
  441. 1.51496490939343725346e-01, 1.51706288485481954886e-01,
  442. 1.51916042025841968588e-01, 1.52125751578880641368e-01,
  443. 1.52335417163043190802e-01, 1.52545038796763288147e-01,
  444. 1.52754616498463030583e-01, 1.52964150286552857949e-01,
  445. 1.53173640179431691521e-01, 1.53383086195486906256e-01,
  446. 1.53592488353094303033e-01, 1.53801846670618136415e-01,
  447. 1.54011161166411142398e-01, 1.54220431858814510662e-01,
  448. 1.54429658766157940075e-01, 1.54638841906759666456e-01,
  449. 1.54847981298926323790e-01, 1.55057076960953166278e-01,
  450. 1.55266128911123957312e-01, 1.55475137167710913966e-01,
  451. 1.55684101748974929036e-01, 1.55893022673165321246e-01,
  452. 1.56101899958520057288e-01, 1.56310733623265640801e-01,
  453. 1.56519523685617195641e-01, 1.56728270163778410362e-01,
  454. 1.56936973075941565980e-01, 1.57145632440287563725e-01,
  455. 1.57354248274985952794e-01, 1.57562820598194874844e-01,
  456. 1.57771349428061147258e-01, 1.57979834782720207631e-01,
  457. 1.58188276680296169285e-01, 1.58396675138901821267e-01,
  458. 1.58605030176638572836e-01, 1.58813341811596647757e-01,
  459. 1.59021610061854806739e-01, 1.59229834945480652753e-01,
  460. 1.59438016480530436736e-01, 1.59646154685049140864e-01,
  461. 1.59854249577070506305e-01, 1.60062301174616977706e-01,
  462. 1.60270309495699786462e-01, 1.60478274558318922960e-01,
  463. 1.60686196380463164335e-01, 1.60894074980109991202e-01,
  464. 1.61101910375225781946e-01, 1.61309702583765646189e-01,
  465. 1.61517451623673535810e-01, 1.61725157512882217192e-01,
  466. 1.61932820269313243466e-01, 1.62140439910877065532e-01,
  467. 1.62348016455472948794e-01, 1.62555549920989028667e-01,
  468. 1.62763040325302282829e-01, 1.62970487686278558970e-01,
  469. 1.63177892021772658060e-01, 1.63385253349628167818e-01,
  470. 1.63592571687677657000e-01, 1.63799847053742592129e-01,
  471. 1.64007079465633337501e-01, 1.64214268941149182934e-01,
  472. 1.64421415498078399287e-01, 1.64628519154198182939e-01,
  473. 1.64835579927274655798e-01, 1.65042597835062948564e-01,
  474. 1.65249572895307172971e-01, 1.65456505125740366280e-01,
  475. 1.65663394544084602300e-01, 1.65870241168050991387e-01,
  476. 1.66077045015339569423e-01, 1.66283806103639492102e-01,
  477. 1.66490524450628840647e-01, 1.66697200073974843848e-01,
  478. 1.66903832991333683777e-01, 1.67110423220350634566e-01,
  479. 1.67316970778660090158e-01, 1.67523475683885425536e-01,
  480. 1.67729937953639163251e-01, 1.67936357605522890157e-01,
  481. 1.68142734657127340681e-01, 1.68349069126032285793e-01,
  482. 1.68555361029806671791e-01, 1.68761610386008564788e-01,
  483. 1.68967817212185178466e-01, 1.69173981525872818565e-01,
  484. 1.69380103344597049420e-01, 1.69586182685872471909e-01,
  485. 1.69792219567202973263e-01, 1.69998214006081560523e-01,
  486. 1.70204166019990471570e-01, 1.70410075626401119608e-01,
  487. 1.70615942842774093169e-01, 1.70821767686559267130e-01,
  488. 1.71027550175195747206e-01, 1.71233290326111786683e-01,
  489. 1.71438988156724952949e-01, 1.71644643684442071985e-01,
  490. 1.71850256926659228363e-01, 1.72055827900761737492e-01,
  491. 1.72261356624124201131e-01, 1.72466843114110590651e-01,
  492. 1.72672287388074080505e-01, 1.72877689463357187005e-01,
  493. 1.73083049357291768322e-01, 1.73288367087198941219e-01,
  494. 1.73493642670389247584e-01, 1.73698876124162460144e-01,
  495. 1.73904067465807832260e-01, 1.74109216712603848132e-01,
  496. 1.74314323881818417084e-01, 1.74519388990708873566e-01,
  497. 1.74724412056521866132e-01, 1.74929393096493468462e-01,
  498. 1.75134332127849151606e-01, 1.75339229167803783982e-01,
  499. 1.75544084233561659136e-01, 1.75748897342316551251e-01,
  500. 1.75953668511251576367e-01, 1.76158397757539414430e-01,
  501. 1.76363085098342059487e-01, 1.76567730550811097245e-01,
  502. 1.76772334132087538539e-01, 1.76976895859301847080e-01,
  503. 1.77181415749573994978e-01, 1.77385893820013462729e-01,
  504. 1.77590330087719266983e-01, 1.77794724569779849510e-01,
  505. 1.77999077283273271499e-01, 1.78203388245267047019e-01,
  506. 1.78407657472818309552e-01, 1.78611884982973673219e-01,
  507. 1.78816070792769343800e-01, 1.79020214919231090978e-01,
  508. 1.79224317379374276094e-01, 1.79428378190203796638e-01,
  509. 1.79632397368714169517e-01, 1.79836374931889531048e-01,
  510. 1.80040310896703609211e-01, 1.80244205280119751400e-01,
  511. 1.80448058099090896667e-01, 1.80651869370559686745e-01,
  512. 1.80855639111458355028e-01, 1.81059367338708782080e-01,
  513. 1.81263054069222551146e-01, 1.81466699319900892640e-01,
  514. 1.81670303107634684148e-01, 1.81873865449304533692e-01,
  515. 1.82077386361780724222e-01, 1.82280865861923213611e-01,
  516. 1.82484303966581717926e-01, 1.82687700692595655916e-01,
  517. 1.82891056056794149010e-01, 1.83094370075996104585e-01,
  518. 1.83297642767010077192e-01, 1.83500874146634490591e-01,
  519. 1.83704064231657471229e-01, 1.83907213038856875986e-01,
  520. 1.84110320585000403204e-01, 1.84313386886845537171e-01,
  521. 1.84516411961139520370e-01, 1.84719395824619381230e-01,
  522. 1.84922338494011989640e-01, 1.85125239986034056949e-01,
  523. 1.85328100317392080454e-01, 1.85530919504782398910e-01,
  524. 1.85733697564891192533e-01, 1.85936434514394538509e-01,
  525. 1.86139130369958299971e-01, 1.86341785148238237024e-01,
  526. 1.86544398865880034499e-01, 1.86746971539519163175e-01,
  527. 1.86949503185781101822e-01, 1.87151993821281115160e-01,
  528. 1.87354443462624475902e-01, 1.87556852126406298220e-01,
  529. 1.87759219829211676522e-01, 1.87961546587615574433e-01,
  530. 1.88163832418182991324e-01, 1.88366077337468768027e-01,
  531. 1.88568281362017808878e-01, 1.88770444508364887426e-01,
  532. 1.88972566793034812971e-01, 1.89174648232542347293e-01,
  533. 1.89376688843392260164e-01, 1.89578688642079329352e-01,
  534. 1.89780647645088312858e-01, 1.89982565868893976679e-01,
  535. 1.90184443329961150315e-01, 1.90386280044744643503e-01,
  536. 1.90588076029689357238e-01, 1.90789831301230172755e-01,
  537. 1.90991545875792090303e-01, 1.91193219769790145879e-01,
  538. 1.91394852999629466739e-01, 1.91596445581705188133e-01,
  539. 1.91797997532402592080e-01, 1.91999508868097079617e-01,
  540. 1.92200979605154115282e-01, 1.92402409759929254873e-01,
  541. 1.92603799348768200961e-01, 1.92805148388006802884e-01,
  542. 1.93006456893970973487e-01, 1.93207724882976855652e-01,
  543. 1.93408952371330711273e-01, 1.93610139375328893507e-01,
  544. 1.93811285911258013304e-01, 1.94012391995394828381e-01,
  545. 1.94213457644006270986e-01, 1.94414482873349420133e-01,
  546. 1.94615467699671668145e-01, 1.94816412139210470844e-01,
  547. 1.95017316208193597360e-01, 1.95218179922839019103e-01,
  548. 1.95419003299354882008e-01, 1.95619786353939673074e-01,
  549. 1.95820529102782026065e-01, 1.96021231562060860298e-01,
  550. 1.96221893747945352882e-01, 1.96422515676594994227e-01,
  551. 1.96623097364159477030e-01, 1.96823638826778835043e-01,
  552. 1.97024140080583359813e-01, 1.97224601141693656192e-01,
  553. 1.97425022026220642335e-01, 1.97625402750265521945e-01,
  554. 1.97825743329919867541e-01, 1.98026043781265564947e-01,
  555. 1.98226304120374813289e-01, 1.98426524363310180510e-01,
  556. 1.98626704526124575612e-01, 1.98826844624861304167e-01,
  557. 1.99026944675553985054e-01, 1.99227004694226633719e-01,
  558. 1.99427024696893717692e-01, 1.99627004699559990053e-01,
  559. 1.99826944718220655961e-01, 2.00026844768861317148e-01,
  560. 2.00226704867458055181e-01, 2.00426525029977237180e-01,
  561. 2.00626305272375821120e-01, 2.00826045610601050528e-01,
  562. 2.01025746060590732034e-01, 2.01225406638273096593e-01,
  563. 2.01425027359566771734e-01, 2.01624608240380948088e-01,
  564. 2.01824149296615212856e-01, 2.02023650544159688591e-01,
  565. 2.02223111998894977681e-01, 2.02422533676692190108e-01,
  566. 2.02621915593412915690e-01, 2.02821257764909251842e-01,
  567. 2.03020560207023886834e-01, 2.03219822935589961022e-01,
  568. 2.03419045966431177863e-01, 2.03618229315361776166e-01,
  569. 2.03817372998186613353e-01, 2.04016477030700998929e-01,
  570. 2.04215541428690888770e-01, 2.04414566207932774100e-01,
  571. 2.04613551384193764759e-01, 2.04812496973231533692e-01,
  572. 2.05011402990794316947e-01, 2.05210269452621052455e-01,
  573. 2.05409096374441185739e-01, 2.05607883771974836451e-01,
  574. 2.05806631660932742856e-01, 2.06005340057016289590e-01,
  575. 2.06204008975917452151e-01, 2.06402638433318963429e-01,
  576. 2.06601228444894063907e-01, 2.06799779026306806973e-01,
  577. 2.06998290193211781363e-01, 2.07196761961254388718e-01,
  578. 2.07395194346070593783e-01, 2.07593587363287118697e-01,
  579. 2.07791941028521415236e-01, 2.07990255357381581547e-01,
  580. 2.08188530365466473171e-01, 2.08386766068365619775e-01,
  581. 2.08584962481659336175e-01, 2.08783119620918666826e-01,
  582. 2.08981237501705385817e-01, 2.09179316139571996880e-01,
  583. 2.09377355550061788891e-01, 2.09575355748708863635e-01,
  584. 2.09773316751038024774e-01, 2.09971238572564861125e-01,
  585. 2.10169121228795829914e-01, 2.10366964735228090255e-01,
  586. 2.10564769107349641919e-01, 2.10762534360639325337e-01,
  587. 2.10960260510566738335e-01, 2.11157947572592374907e-01,
  588. 2.11355595562167514201e-01, 2.11553204494734276020e-01,
  589. 2.11750774385725648585e-01, 2.11948305250565460778e-01,
  590. 2.12145797104668409894e-01, 2.12343249963440033889e-01,
  591. 2.12540663842276822404e-01, 2.12738038756566050225e-01,
  592. 2.12935374721685971577e-01, 2.13132671753005653592e-01,
  593. 2.13329929865885142837e-01, 2.13527149075675354295e-01,
  594. 2.13724329397718126877e-01, 2.13921470847346278932e-01,
  595. 2.14118573439883469467e-01, 2.14315637190644364685e-01,
  596. 2.14512662114934554713e-01, 2.14709648228050609120e-01,
  597. 2.14906595545280021398e-01, 2.15103504081901292233e-01,
  598. 2.15300373853183873996e-01, 2.15497204874388170737e-01,
  599. 2.15693997160765676968e-01, 2.15890750727558783373e-01,
  600. 2.16087465590000943338e-01, 2.16284141763316617446e-01,
  601. 2.16480779262721245715e-01, 2.16677378103421303113e-01,
  602. 2.16873938300614355068e-01, 2.17070459869488946447e-01,
  603. 2.17266942825224712577e-01, 2.17463387182992295976e-01,
  604. 2.17659792957953429626e-01, 2.17856160165260909212e-01,
  605. 2.18052488820058593122e-01, 2.18248778937481485718e-01,
  606. 2.18445030532655570799e-01, 2.18641243620698005889e-01,
  607. 2.18837418216717038977e-01, 2.19033554335812036262e-01,
  608. 2.19229651993073426652e-01, 2.19425711203582840536e-01,
  609. 2.19621731982412998763e-01, 2.19817714344627740397e-01,
  610. 2.20013658305282105987e-01, 2.20209563879422226540e-01,
  611. 2.20405431082085434547e-01, 2.20601259928300208468e-01,
  612. 2.20797050433086200494e-01, 2.20992802611454264294e-01,
  613. 2.21188516478406399512e-01, 2.21384192048935862784e-01,
  614. 2.21579829338027028962e-01, 2.21775428360655529891e-01,
  615. 2.21970989131788226656e-01, 2.22166511666383154067e-01,
  616. 2.22361995979389603928e-01, 2.22557442085748097282e-01,
  617. 2.22752850000390412166e-01, 2.22948219738239528098e-01,
  618. 2.23143551314209764858e-01, 2.23338844743206588195e-01,
  619. 2.23534100040126831876e-01, 2.23729317219858586663e-01,
  620. 2.23924496297281144797e-01, 2.24119637287265222048e-01,
  621. 2.24314740204672707913e-01, 2.24509805064356859905e-01,
  622. 2.24704831881162248042e-01, 2.24899820669924727090e-01,
  623. 2.25094771445471492077e-01, 2.25289684222621078291e-01,
  624. 2.25484559016183333524e-01, 2.25679395840959445829e-01,
  625. 2.25874194711741999031e-01, 2.26068955643314889459e-01,
  626. 2.26263678650453381458e-01, 2.26458363747924135145e-01,
  627. 2.26653010950485178654e-01, 2.26847620272885880377e-01,
  628. 2.27042191729867087746e-01, 2.27236725336160932942e-01,
  629. 2.27431221106491082695e-01, 2.27625679055572488485e-01,
  630. 2.27820099198111608585e-01, 2.28014481548806269284e-01,
  631. 2.28208826122345775911e-01, 2.28403132933410801808e-01,
  632. 2.28597401996673554869e-01, 2.28791633326797638759e-01,
  633. 2.28985826938438108424e-01, 2.29179982846241497851e-01,
  634. 2.29374101064845820064e-01, 2.29568181608880567124e-01,
  635. 2.29762224492966654621e-01, 2.29956229731716588205e-01,
  636. 2.30150197339734297053e-01, 2.30344127331615244891e-01,
  637. 2.30538019721946374485e-01, 2.30731874525306190904e-01,
  638. 2.30925691756264706012e-01, 2.31119471429383438466e-01,
  639. 2.31313213559215469228e-01, 2.31506918160305386056e-01,
  640. 2.31700585247189394522e-01, 2.31894214834395206992e-01,
  641. 2.32087806936442098138e-01, 2.32281361567840904936e-01,
  642. 2.32474878743094054423e-01, 2.32668358476695591452e-01,
  643. 2.32861800783131095427e-01, 2.33055205676877763565e-01,
  644. 2.33248573172404383147e-01, 2.33441903284171359267e-01,
  645. 2.33635196026630714838e-01, 2.33828451414226118343e-01,
  646. 2.34021669461392772815e-01, 2.34214850182557637881e-01,
  647. 2.34407993592139235473e-01, 2.34601099704547760849e-01,
  648. 2.34794168534185027086e-01, 2.34987200095444576098e-01,
  649. 2.35180194402711567614e-01, 2.35373151470362834692e-01,
  650. 2.35566071312766911472e-01, 2.35758953944283977666e-01,
  651. 2.35951799379265969581e-01, 2.36144607632056469093e-01,
  652. 2.36337378716990786920e-01, 2.36530112648395907105e-01,
  653. 2.36722809440590598040e-01, 2.36915469107885301447e-01,
  654. 2.37108091664582215641e-01, 2.37300677124975240018e-01,
  655. 2.37493225503350030570e-01, 2.37685736813984055393e-01,
  656. 2.37878211071146455913e-01, 2.38070648289098130146e-01,
  657. 2.38263048482091843727e-01, 2.38455411664372063374e-01,
  658. 2.38647737850175012397e-01, 2.38840027053728753970e-01,
  659. 2.39032279289253135612e-01, 2.39224494570959789197e-01,
  660. 2.39416672913052186455e-01, 2.39608814329725555714e-01,
  661. 2.39800918835166965160e-01, 2.39992986443555350595e-01,
  662. 2.40185017169061459930e-01, 2.40377011025847825421e-01,
  663. 2.40568968028068902454e-01, 2.40760888189870903009e-01,
  664. 2.40952771525392017704e-01, 2.41144618048762221507e-01,
  665. 2.41336427774103329247e-01, 2.41528200715529106635e-01,
  666. 2.41719936887145159243e-01, 2.41911636303049015773e-01,
  667. 2.42103298977330017028e-01, 2.42294924924069510208e-01,
  668. 2.42486514157340682374e-01, 2.42678066691208643713e-01,
  669. 2.42869582539730455295e-01, 2.43061061716955018053e-01,
  670. 2.43252504236923267067e-01, 2.43443910113668032791e-01,
  671. 2.43635279361214096561e-01, 2.43826611993578135085e-01,
  672. 2.44017908024768859221e-01, 2.44209167468786902955e-01,
  673. 2.44400390339624878910e-01, 2.44591576651267350595e-01,
  674. 2.44782726417690915666e-01, 2.44973839652864094907e-01,
  675. 2.45164916370747443253e-01, 2.45355956585293522032e-01,
  676. 2.45546960310446843456e-01, 2.45737927560143981642e-01,
  677. 2.45928858348313489346e-01, 2.46119752688876008984e-01,
  678. 2.46310610595744133855e-01, 2.46501432082822546921e-01,
  679. 2.46692217164007937535e-01, 2.46882965853189056959e-01,
  680. 2.47073678164246746114e-01, 2.47264354111053824559e-01,
  681. 2.47454993707475257025e-01, 2.47645596967368042396e-01,
  682. 2.47836163904581269213e-01, 2.48026694532956060169e-01,
  683. 2.48217188866325710883e-01, 2.48407646918515578882e-01,
  684. 2.48598068703343083596e-01, 2.48788454234617817384e-01,
  685. 2.48978803526141462266e-01, 2.49169116591707789921e-01,
  686. 2.49359393445102717202e-01, 2.49549634100104333889e-01,
  687. 2.49739838570482819424e-01, 2.49930006870000470665e-01,
  688. 2.50120139012411812907e-01, 2.50310235011463488863e-01,
  689. 2.50500294880894314176e-01, 2.50690318634435249656e-01,
  690. 2.50880306285809429045e-01, 2.51070257848732159012e-01,
  691. 2.51260173336910974662e-01, 2.51450052764045639542e-01,
  692. 2.51639896143827923591e-01, 2.51829703489942047234e-01,
  693. 2.52019474816064292799e-01, 2.52209210135863171054e-01,
  694. 2.52398909462999421205e-01, 2.52588572811126066409e-01,
  695. 2.52778200193888302749e-01, 2.52967791624923554750e-01,
  696. 2.53157347117861530883e-01, 2.53346866686324168061e-01,
  697. 2.53536350343925687145e-01, 2.53725798104272537437e-01,
  698. 2.53915209980963452185e-01, 2.54104585987589448592e-01,
  699. 2.54293926137733827808e-01, 2.54483230444972119422e-01,
  700. 2.54672498922872247995e-01, 2.54861731584994311017e-01,
  701. 2.55050928444890800950e-01, 2.55240089516106494205e-01,
  702. 2.55429214812178506655e-01, 2.55618304346636182611e-01,
  703. 2.55807358133001372380e-01, 2.55996376184787988173e-01,
  704. 2.56185358515502614729e-01, 2.56374305138643843183e-01,
  705. 2.56563216067702881684e-01, 2.56752091316163111312e-01,
  706. 2.56940930897500419139e-01, 2.57129734825182976188e-01,
  707. 2.57318503112671292943e-01, 2.57507235773418385882e-01,
  708. 2.57695932820869499924e-01, 2.57884594268462385980e-01,
  709. 2.58073220129627134423e-01, 2.58261810417786286109e-01,
  710. 2.58450365146354721357e-01, 2.58638884328739770968e-01,
  711. 2.58827367978341271737e-01, 2.59015816108551233388e-01,
  712. 2.59204228732754393683e-01, 2.59392605864327774334e-01,
  713. 2.59580947516640792028e-01, 2.59769253703055424953e-01,
  714. 2.59957524436926046274e-01, 2.60145759731599535147e-01,
  715. 2.60333959600415110192e-01, 2.60522124056704607042e-01,
  716. 2.60710253113792256308e-01, 2.60898346784994794589e-01,
  717. 2.61086405083621408973e-01, 2.61274428022973848051e-01,
  718. 2.61462415616346366409e-01, 2.61650367877025558094e-01,
  719. 2.61838284818290800704e-01, 2.62026166453413700275e-01,
  720. 2.62214012795658535371e-01, 2.62401823858282146062e-01,
  721. 2.62589599654533822903e-01, 2.62777340197655417953e-01,
  722. 2.62965045500881344775e-01, 2.63152715577438522931e-01,
  723. 2.63340350440546488997e-01, 2.63527950103417285543e-01,
  724. 2.63715514579255572158e-01, 2.63903043881258514425e-01,
  725. 2.64090538022615839431e-01, 2.64277997016510002304e-01,
  726. 2.64465420876115908655e-01, 2.64652809614601136623e-01,
  727. 2.64840163245125714830e-01, 2.65027481780842510961e-01,
  728. 2.65214765234896787671e-01, 2.65402013620426591167e-01,
  729. 2.65589226950562473650e-01, 2.65776405238427604338e-01,
  730. 2.65963548497137936000e-01, 2.66150656739801871886e-01,
  731. 2.66337729979520598800e-01, 2.66524768229387865048e-01,
  732. 2.66711771502490091468e-01, 2.66898739811906371422e-01,
  733. 2.67085673170708526314e-01, 2.67272571591960883541e-01,
  734. 2.67459435088720665075e-01, 2.67646263674037598879e-01,
  735. 2.67833057360954085446e-01, 2.68019816162505419843e-01,
  736. 2.68206540091719403129e-01, 2.68393229161616619916e-01,
  737. 2.68579883385210327340e-01, 2.68766502775506566092e-01,
  738. 2.68953087345503938366e-01, 2.69139637108193996440e-01,
  739. 2.69326152076560909610e-01, 2.69512632263581464187e-01,
  740. 2.69699077682225452079e-01, 2.69885488345455115677e-01,
  741. 2.70071864266225758477e-01, 2.70258205457485134460e-01,
  742. 2.70444511932174003199e-01, 2.70630783703225796799e-01,
  743. 2.70817020783566675401e-01, 2.71003223186115638210e-01,
  744. 2.71189390923784467979e-01, 2.71375524009477731013e-01,
  745. 2.71561622456092832678e-01, 2.71747686276519850868e-01,
  746. 2.71933715483641758048e-01, 2.72119710090334365749e-01,
  747. 2.72305670109466269047e-01, 2.72491595553898846571e-01,
  748. 2.72677486436486371524e-01, 2.72863342770075956167e-01,
  749. 2.73049164567507385293e-01, 2.73234951841613560308e-01,
  750. 2.73420704605219999639e-01, 2.73606422871145227305e-01,
  751. 2.73792106652200495365e-01, 2.73977755961190061473e-01,
  752. 2.74163370810910911324e-01, 2.74348951214152980693e-01,
  753. 2.74534497183699099931e-01, 2.74720008732324993961e-01,
  754. 2.74905485872799226765e-01, 2.75090928617883312413e-01,
  755. 2.75276336980331548521e-01, 2.75461710972891293814e-01,
  756. 2.75647050608302801589e-01, 2.75832355899299108692e-01,
  757. 2.76017626858606257567e-01, 2.76202863498943240739e-01,
  758. 2.76388065833022056328e-01, 2.76573233873547430495e-01,
  759. 2.76758367633217150505e-01, 2.76943467124722064732e-01,
  760. 2.77128532360745749585e-01, 2.77313563353964953606e-01,
  761. 2.77498560117049208884e-01, 2.77683522662661164127e-01,
  762. 2.77868451003456307102e-01, 2.78053345152083242198e-01,
  763. 2.78238205121183468371e-01, 2.78423030923391545688e-01,
  764. 2.78607822571334928785e-01, 2.78792580077634188918e-01,
  765. 2.78977303454902791913e-01, 2.79161992715747264704e-01,
  766. 2.79346647872767195331e-01, 2.79531268938555177428e-01,
  767. 2.79715855925696699202e-01, 2.79900408846770476501e-01,
  768. 2.80084927714348175254e-01, 2.80269412540994466987e-01,
  769. 2.80453863339267139843e-01, 2.80638280121716932047e-01,
  770. 2.80822662900887809467e-01, 2.81007011689316577030e-01,
  771. 2.81191326499533322814e-01, 2.81375607344061084980e-01,
  772. 2.81559854235416073820e-01, 2.81744067186107394196e-01,
  773. 2.81928246208637434123e-01, 2.82112391315501587208e-01,
  774. 2.82296502519188363678e-01, 2.82480579832179334865e-01,
  775. 2.82664623266949355251e-01, 2.82848632835966118382e-01,
  776. 2.83032608551690600951e-01, 2.83216550426576951782e-01,
  777. 2.83400458473072325294e-01, 2.83584332703617048033e-01,
  778. 2.83768173130644618674e-01, 2.83951979766581652509e-01,
  779. 2.84135752623847881448e-01, 2.84319491714856320552e-01,
  780. 2.84503197052012990476e-01, 2.84686868647717139513e-01,
  781. 2.84870506514361188088e-01, 2.85054110664330728753e-01,
  782. 2.85237681110004581697e-01, 2.85421217863754628219e-01,
  783. 2.85604720937946032766e-01, 2.85788190344937187426e-01,
  784. 2.85971626097079545392e-01, 2.86155028206717843009e-01,
  785. 2.86338396686190099771e-01, 2.86521731547827507303e-01,
  786. 2.86705032803954318332e-01, 2.86888300466888235274e-01,
  787. 2.87071534548940077158e-01, 2.87254735062413890656e-01,
  788. 2.87437902019607005588e-01, 2.87621035432809979415e-01,
  789. 2.87804135314306597238e-01, 2.87987201676373927306e-01,
  790. 2.88170234531282265511e-01, 2.88353233891295246405e-01,
  791. 2.88536199768669621157e-01, 2.88719132175655535111e-01,
  792. 2.88902031124496472270e-01, 2.89084896627429033256e-01,
  793. 2.89267728696683157352e-01, 2.89450527344482233527e-01,
  794. 2.89633292583042656343e-01, 2.89816024424574436580e-01,
  795. 2.89998722881280646124e-01, 2.90181387965357862058e-01,
  796. 2.90364019688995778079e-01, 2.90546618064377593083e-01,
  797. 2.90729183103679733602e-01, 2.90911714819072020344e-01,
  798. 2.91094213222717501655e-01, 2.91276678326772675565e-01,
  799. 2.91459110143387378766e-01, 2.91641508684704731102e-01,
  800. 2.91823873962861302100e-01, 2.92006205989986888927e-01,
  801. 2.92188504778204849455e-01, 2.92370770339631658175e-01,
  802. 2.92553002686377461306e-01, 2.92735201830545521684e-01,
  803. 2.92917367784232607342e-01, 2.93099500559528880483e-01,
  804. 2.93281600168517952998e-01, 2.93463666623276664414e-01,
  805. 2.93645699935875470477e-01, 2.93827700118377999061e-01,
  806. 2.94009667182841549771e-01, 2.94191601141316649848e-01,
  807. 2.94373502005847331731e-01, 2.94555369788470966519e-01,
  808. 2.94737204501218597041e-01, 2.94919006156114382744e-01,
  809. 2.95100774765176154801e-01, 2.95282510340415083050e-01,
  810. 2.95464212893835898033e-01, 2.95645882437436613444e-01,
  811. 2.95827518983208914705e-01, 2.96009122543137770389e-01,
  812. 2.96190693129201765288e-01, 2.96372230753372822853e-01,
  813. 2.96553735427616482756e-01, 2.96735207163891623328e-01,
  814. 2.96916645974150794629e-01, 2.97098051870339885383e-01,
  815. 2.97279424864398345019e-01, 2.97460764968259128160e-01,
  816. 2.97642072193848694628e-01, 2.97823346553087064947e-01,
  817. 2.98004588057887653818e-01, 2.98185796720157547668e-01,
  818. 2.98366972551797282609e-01, 2.98548115564700899949e-01,
  819. 2.98729225770756001701e-01, 2.98910303181843861609e-01,
  820. 2.99091347809839036564e-01, 2.99272359666609866213e-01,
  821. 2.99453338764018139884e-01, 2.99634285113919263122e-01,
  822. 2.99815198728162091157e-01, 2.99996079618589261973e-01,
  823. 3.00176927797036752210e-01, 3.00357743275334321265e-01,
  824. 3.00538526065305122703e-01, 3.00719276178766037333e-01,
  825. 3.00899993627527506668e-01, 3.01080678423393532928e-01,
  826. 3.01261330578161790061e-01, 3.01441950103623457213e-01,
  827. 3.01622537011563440768e-01, 3.01803091313760207814e-01,
  828. 3.01983613021985786151e-01, 3.02164102148005930815e-01,
  829. 3.02344558703580013059e-01, 3.02524982700460964846e-01,
  830. 3.02705374150395445376e-01, 3.02885733065123674557e-01,
  831. 3.03066059456379655046e-01, 3.03246353335890839187e-01,
  832. 3.03426614715378517584e-01, 3.03606843606557541548e-01,
  833. 3.03787040021136489631e-01, 3.03967203970817556602e-01,
  834. 3.04147335467296719980e-01, 3.04327434522263462480e-01,
  835. 3.04507501147401160591e-01, 3.04687535354386640485e-01,
  836. 3.04867537154890677620e-01, 3.05047506560577552648e-01,
  837. 3.05227443583105328972e-01, 3.05407348234125741726e-01,
  838. 3.05587220525284364303e-01, 3.05767060468220275293e-01,
  839. 3.05946868074566447060e-01, 3.06126643355949523695e-01,
  840. 3.06306386323989821019e-01, 3.06486096990301493115e-01,
  841. 3.06665775366492365794e-01, 3.06845421464164047620e-01,
  842. 3.07025035294911874395e-01, 3.07204616870324909161e-01,
  843. 3.07384166201985997713e-01, 3.07563683301471768594e-01,
  844. 3.07743168180352633101e-01, 3.07922620850192618747e-01,
  845. 3.08102041322549813351e-01, 3.08281429608975809931e-01,
  846. 3.08460785721016095273e-01, 3.08640109670209994430e-01,
  847. 3.08819401468090559693e-01, 3.08998661126184626102e-01,
  848. 3.09177888656012922475e-01, 3.09357084069089849354e-01,
  849. 3.09536247376923756569e-01, 3.09715378591016721188e-01,
  850. 3.09894477722864714053e-01, 3.10073544783957377735e-01,
  851. 3.10252579785778359600e-01, 3.10431582739805034254e-01,
  852. 3.10610553657508725589e-01, 3.10789492550354429223e-01,
  853. 3.10968399429801145573e-01, 3.11147274307301602292e-01,
  854. 3.11326117194302476321e-01, 3.11504928102244282861e-01,
  855. 3.11683707042561319867e-01, 3.11862454026681890085e-01,
  856. 3.12041169066028079015e-01, 3.12219852172015865932e-01,
  857. 3.12398503356055123881e-01, 3.12577122629549564170e-01,
  858. 3.12755710003896902904e-01, 3.12934265490488583428e-01,
  859. 3.13112789100710109391e-01, 3.13291280845940822708e-01,
  860. 3.13469740737553903553e-01, 3.13648168786916592410e-01,
  861. 3.13826565005389856999e-01, 3.14004929404328836373e-01,
  862. 3.14183261995082285800e-01, 3.14361562788993187390e-01,
  863. 3.14539831797398306001e-01, 3.14718069031628300269e-01,
  864. 3.14896274503007833623e-01, 3.15074448222855574286e-01,
  865. 3.15252590202484084259e-01, 3.15430700453199819311e-01,
  866. 3.15608778986303351033e-01, 3.15786825813089033765e-01,
  867. 3.15964840944845282156e-01, 3.16142824392854515647e-01,
  868. 3.16320776168393047456e-01, 3.16498696282731251106e-01,
  869. 3.16676584747133449405e-01, 3.16854441572857969955e-01,
  870. 3.17032266771157145158e-01, 3.17210060353277145673e-01,
  871. 3.17387822330458424513e-01, 3.17565552713935272955e-01,
  872. 3.17743251514935987068e-01, 3.17920918744682867718e-01,
  873. 3.18098554414392331591e-01, 3.18276158535274800165e-01,
  874. 3.18453731118534588695e-01, 3.18631272175370239275e-01,
  875. 3.18808781716974187770e-01, 3.18986259754532985866e-01,
  876. 3.19163706299227134533e-01, 3.19341121362231306069e-01,
  877. 3.19518504954714122057e-01, 3.19695857087838430921e-01,
  878. 3.19873177772760863835e-01, 3.20050467020632389836e-01,
  879. 3.20227724842597871735e-01, 3.20404951249796343671e-01,
  880. 3.20582146253360900090e-01, 3.20759309864418695746e-01,
  881. 3.20936442094090945698e-01, 3.21113542953492980825e-01,
  882. 3.21290612453734303333e-01, 3.21467650605918364715e-01,
  883. 3.21644657421142898812e-01, 3.21821632910499588753e-01,
  884. 3.21998577085074344506e-01, 3.22175489955947080833e-01,
  885. 3.22352371534191939340e-01, 3.22529221830877121935e-01,
  886. 3.22706040857064946348e-01, 3.22882828623812012658e-01,
  887. 3.23059585142168759209e-01, 3.23236310423180128737e-01,
  888. 3.23413004477884902244e-01, 3.23589667317316198591e-01,
  889. 3.23766298952501196950e-01, 3.23942899394461303331e-01,
  890. 3.24119468654211984049e-01, 3.24296006742762987773e-01,
  891. 3.24472513671118123479e-01, 3.24648989450275538005e-01,
  892. 3.24825434091227327471e-01, 3.25001847604959981375e-01,
  893. 3.25178230002454049519e-01, 3.25354581294684308546e-01,
  894. 3.25530901492619706428e-01, 3.25707190607223473489e-01,
  895. 3.25883448649452955870e-01, 3.26059675630259726553e-01,
  896. 3.26235871560589585361e-01, 3.26412036451382503444e-01,
  897. 3.26588170313572789816e-01, 3.26764273158088813798e-01,
  898. 3.26940344995853338084e-01, 3.27116385837783185675e-01,
  899. 3.27292395694789517435e-01, 3.27468374577777776580e-01,
  900. 3.27644322497647522141e-01, 3.27820239465292706527e-01,
  901. 3.27996125491601397961e-01, 3.28171980587455947020e-01,
  902. 3.28347804763733097655e-01, 3.28523598031303654121e-01,
  903. 3.28699360401032869561e-01, 3.28875091883780168445e-01,
  904. 3.29050792490399257595e-01, 3.29226462231738181696e-01,
  905. 3.29402101118639156763e-01, 3.29577709161938792182e-01,
  906. 3.29753286372467979692e-01, 3.29928832761051837874e-01,
  907. 3.30104348338509878680e-01, 3.30279833115655840903e-01,
  908. 3.30455287103297801199e-01, 3.30630710312238174087e-01,
  909. 3.30806102753273600925e-01, 3.30981464437195116446e-01,
  910. 3.31156795374788148756e-01, 3.31332095576832297290e-01,
  911. 3.31507365054101610369e-01, 3.31682603817364363152e-01,
  912. 3.31857811877383335197e-01, 3.32032989244915477389e-01,
  913. 3.32208135930712189499e-01, 3.32383251945519209158e-01,
  914. 3.32558337300076611864e-01, 3.32733392005118810975e-01,
  915. 3.32908416071374668732e-01, 3.33083409509567329732e-01,
  916. 3.33258372330414331941e-01, 3.33433304544627551191e-01,
  917. 3.33608206162913423221e-01, 3.33783077195972499585e-01,
  918. 3.33957917654499891746e-01, 3.34132727549185049032e-01,
  919. 3.34307506890711869652e-01, 3.34482255689758534167e-01,
  920. 3.34656973956997838560e-01, 3.34831661703096694627e-01,
  921. 3.35006318938716629585e-01, 3.35180945674513619537e-01,
  922. 3.35355541921137811912e-01, 3.35530107689234080581e-01,
  923. 3.35704642989441526257e-01, 3.35879147832393754047e-01,
  924. 3.36053622228718762432e-01, 3.36228066189038998779e-01,
  925. 3.36402479723971414849e-01, 3.36576862844127355778e-01,
  926. 3.36751215560112560077e-01, 3.36925537882527326161e-01,
  927. 3.37099829821966401333e-01, 3.37274091389018870757e-01,
  928. 3.37448322594268379504e-01, 3.37622523448293077042e-01,
  929. 3.37796693961665561723e-01, 3.37970834144952825273e-01,
  930. 3.38144944008716419326e-01, 3.38319023563512344399e-01,
  931. 3.38493072819891160918e-01, 3.38667091788397822683e-01,
  932. 3.38841080479571843398e-01, 3.39015038903947185656e-01,
  933. 3.39188967072052427465e-01, 3.39362864994410484698e-01,
  934. 3.39536732681538888645e-01, 3.39710570143949730504e-01,
  935. 3.39884377392149494845e-01, 3.40058154436639281659e-01,
  936. 3.40231901287914695331e-01, 3.40405617956465900154e-01,
  937. 3.40579304452777453793e-01, 3.40752960787328640357e-01,
  938. 3.40926586970593192838e-01, 3.41100183013039404134e-01,
  939. 3.41273748925130071541e-01, 3.41447284717322607772e-01,
  940. 3.41620790400068985448e-01, 3.41794265983815681587e-01,
  941. 3.41967711479003788622e-01, 3.42141126896068903385e-01,
  942. 3.42314512245441293636e-01, 3.42487867537545731533e-01,
  943. 3.42661192782801549139e-01, 3.42834487991622693936e-01,
  944. 3.43007753174417784336e-01, 3.43180988341589887636e-01,
  945. 3.43354193503536686549e-01, 3.43527368670650590232e-01,
  946. 3.43700513853318456725e-01, 3.43873629061921814998e-01,
  947. 3.44046714306836864949e-01, 3.44219769598434255364e-01,
  948. 3.44392794947079416978e-01, 3.44565790363132395946e-01,
  949. 3.44738755856947631795e-01, 3.44911691438874568050e-01,
  950. 3.45084597119256875075e-01, 3.45257472908433227232e-01,
  951. 3.45430318816736692256e-01, 3.45603134854495064321e-01,
  952. 3.45775921032030753022e-01, 3.45948677359660894393e-01,
  953. 3.46121403847697239886e-01, 3.46294100506446100862e-01,
  954. 3.46466767346208570633e-01, 3.46639404377280413438e-01,
  955. 3.46812011609952008939e-01, 3.46984589054508352213e-01,
  956. 3.47157136721229275800e-01, 3.47329654620389172148e-01,
  957. 3.47502142762257104636e-01, 3.47674601157096863080e-01,
  958. 3.47847029815167019251e-01, 3.48019428746720593804e-01,
  959. 3.48191797962005611389e-01, 3.48364137471264545542e-01,
  960. 3.48536447284734762775e-01, 3.48708727412648133992e-01,
  961. 3.48880977865231478585e-01, 3.49053198652706175853e-01,
  962. 3.49225389785288331534e-01, 3.49397551273188777810e-01,
  963. 3.49569683126613184321e-01, 3.49741785355761836129e-01,
  964. 3.49913857970829800248e-01, 3.50085900982006870130e-01,
  965. 3.50257914399477510159e-01, 3.50429898233421077691e-01,
  966. 3.50601852494011601014e-01, 3.50773777191417779342e-01,
  967. 3.50945672335803204867e-01, 3.51117537937326196218e-01,
  968. 3.51289374006139798468e-01, 3.51461180552391783127e-01,
  969. 3.51632957586224814683e-01, 3.51804705117776228551e-01,
  970. 3.51976423157178197609e-01, 3.52148111714557621177e-01,
  971. 3.52319770800036180525e-01, 3.52491400423730505409e-01,
  972. 3.52663000595751729982e-01, 3.52834571326206047903e-01,
  973. 3.53006112625194323762e-01, 3.53177624502812259610e-01,
  974. 3.53349106969150339452e-01, 3.53520560034293884755e-01,
  975. 3.53691983708322998936e-01, 3.53863378001312622878e-01,
  976. 3.54034742923332534925e-01, 3.54206078484447295374e-01,
  977. 3.54377384694716357494e-01, 3.54548661564193900997e-01,
  978. 3.54719909102929054079e-01, 3.54891127320965671377e-01,
  979. 3.55062316228342556013e-01, 3.55233475835093293060e-01,
  980. 3.55404606151246360568e-01, 3.55575707186825074047e-01,
  981. 3.55746778951847530958e-01, 3.55917821456326777252e-01,
  982. 3.56088834710270696338e-01, 3.56259818723682064601e-01,
  983. 3.56430773506558440378e-01, 3.56601699068892386002e-01,
  984. 3.56772595420671190247e-01, 3.56943462571877201395e-01,
  985. 3.57114300532487438655e-01, 3.57285109312473980747e-01,
  986. 3.57455888921803799363e-01, 3.57626639370438537124e-01,
  987. 3.57797360668335062694e-01, 3.57968052825444915666e-01,
  988. 3.58138715851714584115e-01, 3.58309349757085504606e-01,
  989. 3.58479954551494006676e-01, 3.58650530244871368346e-01,
  990. 3.58821076847143705102e-01, 3.58991594368232136425e-01,
  991. 3.59162082818052619260e-01, 3.59332542206516170058e-01,
  992. 3.59502972543528642735e-01, 3.59673373838990784179e-01,
  993. 3.59843746102798400788e-01, 3.60014089344842191931e-01,
  994. 3.60184403575007805465e-01, 3.60354688803175782219e-01,
  995. 3.60524945039221667020e-01, 3.60695172293016008691e-01,
  996. 3.60865370574424193517e-01, 3.61035539893306722803e-01,
  997. 3.61205680259518935316e-01, 3.61375791682911229330e-01,
  998. 3.61545874173328896095e-01, 3.61715927740612286367e-01,
  999. 3.61885952394596643877e-01, 3.62055948145112271863e-01,
  1000. 3.62225915001984422048e-01, 3.62395852975033405663e-01,
  1001. 3.62565762074074371402e-01, 3.62735642308917638488e-01,
  1002. 3.62905493689368474630e-01, 3.63075316225227040512e-01,
  1003. 3.63245109926288667346e-01, 3.63414874802343634830e-01,
  1004. 3.63584610863177171147e-01, 3.63754318118569619500e-01,
  1005. 3.63923996578296327087e-01, 3.64093646252127589591e-01,
  1006. 3.64263267149828817715e-01, 3.64432859281160426157e-01,
  1007. 3.64602422655877833613e-01, 3.64771957283731573796e-01,
  1008. 3.64941463174467128905e-01, 3.65110940337825040647e-01,
  1009. 3.65280388783541021258e-01, 3.65449808521345675949e-01,
  1010. 3.65619199560964724949e-01, 3.65788561912118947994e-01,
  1011. 3.65957895584524239840e-01, 3.66127200587891499239e-01,
  1012. 3.66296476931926684451e-01, 3.66465724626330868752e-01,
  1013. 3.66634943680800184929e-01, 3.66804134105025769763e-01,
  1014. 3.66973295908693986078e-01, 3.67142429101486200693e-01,
  1015. 3.67311533693078839935e-01, 3.67480609693143445149e-01,
  1016. 3.67649657111346728211e-01, 3.67818675957350349481e-01,
  1017. 3.67987666240811250873e-01, 3.68156627971381322784e-01,
  1018. 3.68325561158707626142e-01, 3.68494465812432392404e-01,
  1019. 3.68663341942192857026e-01, 3.68832189557621481502e-01,
  1020. 3.69001008668345675812e-01, 3.69169799283988242511e-01,
  1021. 3.69338561414166821617e-01, 3.69507295068494445722e-01,
  1022. 3.69676000256579095904e-01, 3.69844676988023979280e-01,
  1023. 3.70013325272427417989e-01, 3.70181945119382904696e-01,
  1024. 3.70350536538478991577e-01, 3.70519099539299512358e-01,
  1025. 3.70687634131423415784e-01, 3.70856140324424710109e-01,
  1026. 3.71024618127872685136e-01, 3.71193067551331690179e-01,
  1027. 3.71361488604361411614e-01, 3.71529881296516484301e-01,
  1028. 3.71698245637346880166e-01, 3.71866581636397741661e-01,
  1029. 3.72034889303209215239e-01, 3.72203168647316895434e-01,
  1030. 3.72371419678251380780e-01, 3.72539642405538495851e-01,
  1031. 3.72707836838699291260e-01, 3.72876002987249988152e-01,
  1032. 3.73044140860701978202e-01, 3.73212250468561934635e-01,
  1033. 3.73380331820331756720e-01, 3.73548384925508347720e-01,
  1034. 3.73716409793584058985e-01, 3.73884406434046412393e-01,
  1035. 3.74052374856377989332e-01, 3.74220315070056763762e-01,
  1036. 3.74388227084555880175e-01, 3.74556110909343709103e-01,
  1037. 3.74723966553883902630e-01, 3.74891794027635172348e-01,
  1038. 3.75059593340051733446e-01, 3.75227364500582805107e-01,
  1039. 3.75395107518673054603e-01, 3.75562822403762208712e-01,
  1040. 3.75730509165285331274e-01, 3.75898167812672767685e-01,
  1041. 3.76065798355350089377e-01, 3.76233400802738204849e-01,
  1042. 3.76400975164253082106e-01, 3.76568521449306137239e-01,
  1043. 3.76736039667304067891e-01, 3.76903529827648686723e-01,
  1044. 3.77070991939737309995e-01, 3.77238426012962257960e-01,
  1045. 3.77405832056711409983e-01, 3.77573210080367704933e-01,
  1046. 3.77740560093309529766e-01, 3.77907882104910441967e-01,
  1047. 3.78075176124539447109e-01, 3.78242442161560721292e-01,
  1048. 3.78409680225333722170e-01, 3.78576890325213299970e-01,
  1049. 3.78744072470549641984e-01, 3.78911226670688106033e-01,
  1050. 3.79078352934969442511e-01, 3.79245451272729794390e-01,
  1051. 3.79412521693300530679e-01, 3.79579564206008357452e-01,
  1052. 3.79746578820175262337e-01, 3.79913565545118681044e-01,
  1053. 3.80080524390151330838e-01, 3.80247455364581210535e-01,
  1054. 3.80414358477711711526e-01, 3.80581233738841562264e-01,
  1055. 3.80748081157264828267e-01, 3.80914900742270912115e-01,
  1056. 3.81081692503144608963e-01, 3.81248456449166051030e-01,
  1057. 3.81415192589610707596e-01, 3.81581900933749385008e-01,
  1058. 3.81748581490848337694e-01, 3.81915234270169157149e-01,
  1059. 3.82081859280968716419e-01, 3.82248456532499392146e-01,
  1060. 3.82415026034008842526e-01, 3.82581567794740229349e-01,
  1061. 3.82748081823931884937e-01, 3.82914568130817700720e-01,
  1062. 3.83081026724626960700e-01, 3.83247457614584230434e-01,
  1063. 3.83413860809909523564e-01, 3.83580236319818357327e-01,
  1064. 3.83746584153521419491e-01, 3.83912904320224956933e-01,
  1065. 3.84079196829130664614e-01, 3.84245461689435519048e-01,
  1066. 3.84411698910332055856e-01, 3.84577908501008036701e-01,
  1067. 3.84744090470646837865e-01, 3.84910244828427117181e-01,
  1068. 3.85076371583523036080e-01, 3.85242470745104093055e-01,
  1069. 3.85408542322335401220e-01, 3.85574586324377355240e-01,
  1070. 3.85740602760385797865e-01, 3.85906591639512019931e-01,
  1071. 3.86072552970902815872e-01, 3.86238486763700372695e-01,
  1072. 3.86404393027042381004e-01, 3.86570271770061868466e-01,
  1073. 3.86736123001887421857e-01, 3.86901946731643076038e-01,
  1074. 3.87067742968448313956e-01, 3.87233511721418011131e-01,
  1075. 3.87399252999662713215e-01, 3.87564966812288136389e-01,
  1076. 3.87730653168395777985e-01, 3.87896312077082416891e-01,
  1077. 3.88061943547440391100e-01, 3.88227547588557486691e-01,
  1078. 3.88393124209516937828e-01, 3.88558673419397537785e-01,
  1079. 3.88724195227273583431e-01, 3.88889689642214819720e-01,
  1080. 3.89055156673286495206e-01, 3.89220596329549362036e-01,
  1081. 3.89386008620059675955e-01, 3.89551393553869196307e-01,
  1082. 3.89716751140025186029e-01, 3.89882081387570522679e-01,
  1083. 3.90047384305543420879e-01, 3.90212659902977765380e-01,
  1084. 3.90377908188902833508e-01, 3.90543129172343517208e-01,
  1085. 3.90708322862320267532e-01, 3.90873489267848928108e-01,
  1086. 3.91038628397941012693e-01, 3.91203740261603483130e-01,
  1087. 3.91368824867838915882e-01, 3.91533882225645335495e-01,
  1088. 3.91698912344016436649e-01, 3.91863915231941306594e-01,
  1089. 3.92028890898404758225e-01, 3.92193839352386997010e-01,
  1090. 3.92358760602863898548e-01, 3.92523654658806786522e-01,
  1091. 3.92688521529182710257e-01, 3.92853361222954111653e-01,
  1092. 3.93018173749079158252e-01, 3.93182959116511465680e-01,
  1093. 3.93347717334200208672e-01, 3.93512448411090343114e-01,
  1094. 3.93677152356122161958e-01, 3.93841829178231628283e-01,
  1095. 3.94006478886350375301e-01, 3.94171101489405484308e-01,
  1096. 3.94335696996319762242e-01, 3.94500265416011519637e-01,
  1097. 3.94664806757394681647e-01, 3.94829321029378788044e-01,
  1098. 3.94993808240868993220e-01, 3.95158268400766010675e-01,
  1099. 3.95322701517966224039e-01, 3.95487107601361631559e-01,
  1100. 3.95651486659839735083e-01, 3.95815838702283817607e-01,
  1101. 3.95980163737572665728e-01, 3.96144461774580736169e-01,
  1102. 3.96308732822178044763e-01, 3.96472976889230388498e-01,
  1103. 3.96637193984599012442e-01, 3.96801384117140887309e-01,
  1104. 3.96965547295708709452e-01, 3.97129683529150678822e-01,
  1105. 3.97293792826310665500e-01, 3.97457875196028209697e-01,
  1106. 3.97621930647138466242e-01, 3.97785959188472371117e-01,
  1107. 3.97949960828856363904e-01, 3.98113935577112609820e-01,
  1108. 3.98277883442058888708e-01, 3.98441804432508706046e-01,
  1109. 3.98605698557271237448e-01, 3.98769565825151217631e-01,
  1110. 3.98933406244949217978e-01, 3.99097219825461368981e-01,
  1111. 3.99261006575479415748e-01, 3.99424766503791051075e-01,
  1112. 3.99588499619179360334e-01, 3.99752205930423210045e-01,
  1113. 3.99915885446297303396e-01, 4.00079538175571791658e-01,
  1114. 4.00243164127012718279e-01, 4.00406763309381685811e-01,
  1115. 4.00570335731436077964e-01, 4.00733881401929004085e-01,
  1116. 4.00897400329609188141e-01, 4.01060892523221135253e-01,
  1117. 4.01224357991505076182e-01, 4.01387796743196800797e-01,
  1118. 4.01551208787028046654e-01, 4.01714594131726110415e-01,
  1119. 4.01877952786014125408e-01, 4.02041284758610784067e-01,
  1120. 4.02204590058230671001e-01, 4.02367868693584040951e-01,
  1121. 4.02531120673376818786e-01, 4.02694346006310877062e-01,
  1122. 4.02857544701083536420e-01, 4.03020716766388009678e-01,
  1123. 4.03183862210913346313e-01, 4.03346981043344210427e-01,
  1124. 4.03510073272361047270e-01, 4.03673138906640027734e-01,
  1125. 4.03836177954853103866e-01, 4.03999190425668119886e-01,
  1126. 4.04162176327748423610e-01, 4.04325135669753310541e-01,
  1127. 4.04488068460337746313e-01, 4.04650974708152644244e-01,
  1128. 4.04813854421844421250e-01, 4.04976707610055497444e-01,
  1129. 4.05139534281423963069e-01, 4.05302334444583689521e-01,
  1130. 4.05465108108164384859e-01, 4.05627855280791482784e-01,
  1131. 4.05790575971086253659e-01, 4.05953270187665749003e-01,
  1132. 4.06115937939142745972e-01, 4.06278579234125969410e-01,
  1133. 4.06441194081219814294e-01, 4.06603782489024567770e-01,
  1134. 4.06766344466136187119e-01, 4.06928880021146577306e-01,
  1135. 4.07091389162643424449e-01, 4.07253871899210195817e-01,
  1136. 4.07416328239426139834e-01, 4.07578758191866397098e-01,
  1137. 4.07741161765101944869e-01, 4.07903538967699541562e-01,
  1138. 4.08065889808221726742e-01, 4.08228214295226987662e-01,
  1139. 4.08390512437269537216e-01, 4.08552784242899424960e-01,
  1140. 4.08715029720662648138e-01, 4.08877248879100985146e-01,
  1141. 4.09039441726751940021e-01, 4.09201608272149075507e-01,
  1142. 4.09363748523821679992e-01, 4.09525862490294934037e-01,
  1143. 4.09687950180089799357e-01, 4.09850011601723129839e-01,
  1144. 4.10012046763707727060e-01, 4.10174055674552173745e-01,
  1145. 4.10336038342760889286e-01, 4.10497994776834240760e-01,
  1146. 4.10659924985268376396e-01, 4.10821828976555447621e-01,
  1147. 4.10983706759183275992e-01, 4.11145558341635852795e-01,
  1148. 4.11307383732392728426e-01, 4.11469182939929623011e-01,
  1149. 4.11630955972717926805e-01, 4.11792702839225033262e-01,
  1150. 4.11954423547914172499e-01, 4.12116118107244577828e-01,
  1151. 4.12277786525671208206e-01, 4.12439428811645081296e-01,
  1152. 4.12601044973613051425e-01, 4.12762635020017809584e-01,
  1153. 4.12924198959298049960e-01, 4.13085736799888414428e-01,
  1154. 4.13247248550219326013e-01, 4.13408734218717210940e-01,
  1155. 4.13570193813804387606e-01, 4.13731627343899122096e-01,
  1156. 4.13893034817415517157e-01, 4.14054416242763789757e-01,
  1157. 4.14215771628349826994e-01, 4.14377100982575685695e-01,
  1158. 4.14538404313839203841e-01, 4.14699681630534222609e-01,
  1159. 4.14860932941050530864e-01, 4.15022158253773809644e-01,
  1160. 4.15183357577085743184e-01, 4.15344530919363852384e-01,
  1161. 4.15505678288981772361e-01, 4.15666799694309030411e-01,
  1162. 4.15827895143710990489e-01, 4.15988964645549075261e-01,
  1163. 4.16150008208180710589e-01, 4.16311025839959270023e-01,
  1164. 4.16472017549233963774e-01, 4.16632983344350116273e-01,
  1165. 4.16793923233648999638e-01, 4.16954837225467778161e-01,
  1166. 4.17115725328139674843e-01, 4.17276587549993804860e-01,
  1167. 4.17437423899355397605e-01, 4.17598234384545574649e-01,
  1168. 4.17759019013881405247e-01, 4.17919777795676072873e-01,
  1169. 4.18080510738238597668e-01, 4.18241217849874169499e-01,
  1170. 4.18401899138883814899e-01, 4.18562554613564674622e-01,
  1171. 4.18723184282209781593e-01, 4.18883788153108282959e-01,
  1172. 4.19044366234545218042e-01, 4.19204918534801795893e-01,
  1173. 4.19365445062155117739e-01, 4.19525945824878288004e-01,
  1174. 4.19686420831240469820e-01, 4.19846870089506885027e-01,
  1175. 4.20007293607938703150e-01, 4.20167691394793096915e-01,
  1176. 4.20328063458323408774e-01, 4.20488409806778928868e-01,
  1177. 4.20648730448404839510e-01, 4.20809025391442659281e-01,
  1178. 4.20969294644129632399e-01, 4.21129538214699283838e-01,
  1179. 4.21289756111381030745e-01, 4.21449948342400404488e-01,
  1180. 4.21610114915978995143e-01, 4.21770255840334340469e-01,
  1181. 4.21930371123680147960e-01, 4.22090460774226183815e-01,
  1182. 4.22250524800178161922e-01, 4.22410563209737965895e-01,
  1183. 4.22570576011103482550e-01, 4.22730563212468657408e-01,
  1184. 4.22890524822023494700e-01, 4.23050460847954223897e-01,
  1185. 4.23210371298442855625e-01, 4.23370256181667792283e-01,
  1186. 4.23530115505803272935e-01, 4.23689949279019761885e-01,
  1187. 4.23849757509483726636e-01, 4.24009540205357748910e-01,
  1188. 4.24169297374800524647e-01, 4.24329029025966752986e-01,
  1189. 4.24488735167007302795e-01, 4.24648415806069157163e-01,
  1190. 4.24808070951295302375e-01, 4.24967700610824949958e-01,
  1191. 4.25127304792793314636e-01, 4.25286883505331780864e-01,
  1192. 4.25446436756567736293e-01, 4.25605964554624793816e-01,
  1193. 4.25765466907622680548e-01, 4.25924943823677126797e-01,
  1194. 4.26084395310900088116e-01, 4.26243821377399578765e-01,
  1195. 4.26403222031279727222e-01, 4.26562597280640942721e-01,
  1196. 4.26721947133579471156e-01, 4.26881271598188005711e-01,
  1197. 4.27040570682555131743e-01, 4.27199844394765715361e-01,
  1198. 4.27359092742900625872e-01, 4.27518315735037068848e-01,
  1199. 4.27677513379248142034e-01, 4.27836685683603279440e-01,
  1200. 4.27995832656168084807e-01, 4.28154954305004109560e-01,
  1201. 4.28314050638169185881e-01, 4.28473121663717371188e-01,
  1202. 4.28632167389698781612e-01, 4.28791187824159647501e-01,
  1203. 4.28950182975142479957e-01, 4.29109152850685904301e-01,
  1204. 4.29268097458824715584e-01, 4.29427016807589878589e-01,
  1205. 4.29585910905008472316e-01, 4.29744779759103801009e-01,
  1206. 4.29903623377895449664e-01, 4.30062441769398950964e-01,
  1207. 4.30221234941626229364e-01, 4.30380002902585323543e-01,
  1208. 4.30538745660280330885e-01, 4.30697463222711796060e-01,
  1209. 4.30856155597876211427e-01, 4.31014822793766405606e-01,
  1210. 4.31173464818371321439e-01, 4.31332081679676238029e-01,
  1211. 4.31490673385662437678e-01, 4.31649239944307483441e-01,
  1212. 4.31807781363585274637e-01, 4.31966297651465769292e-01,
  1213. 4.32124788815915150675e-01, 4.32283254864895827296e-01,
  1214. 4.32441695806366432908e-01, 4.32600111648281937526e-01,
  1215. 4.32758502398593258853e-01, 4.32916868065247761876e-01,
  1216. 4.33075208656188981315e-01, 4.33233524179356677131e-01,
  1217. 4.33391814642686779013e-01, 4.33550080054111552919e-01,
  1218. 4.33708320421559379021e-01, 4.33866535752955029270e-01,
  1219. 4.34024726056219334325e-01, 4.34182891339269516617e-01,
  1220. 4.34341031610018912801e-01, 4.34499146876377251303e-01,
  1221. 4.34657237146250430282e-01, 4.34815302427540573138e-01,
  1222. 4.34973342728146084024e-01, 4.35131358055961647846e-01,
  1223. 4.35289348418878174751e-01, 4.35447313824782800129e-01,
  1224. 4.35605254281559051144e-01, 4.35763169797086569179e-01,
  1225. 4.35921060379241387395e-01, 4.36078926035895708679e-01,
  1226. 4.36236766774918072187e-01, 4.36394582604173242313e-01,
  1227. 4.36552373531522319716e-01, 4.36710139564822685809e-01,
  1228. 4.36867880711927891735e-01, 4.37025596980687935922e-01,
  1229. 4.37183288378948931019e-01, 4.37340954914553436961e-01,
  1230. 4.37498596595340183413e-01, 4.37656213429144347327e-01,
  1231. 4.37813805423797164362e-01, 4.37971372587126372977e-01,
  1232. 4.38128914926955992382e-01, 4.38286432451106211516e-01,
  1233. 4.38443925167393611098e-01, 4.38601393083631108105e-01,
  1234. 4.38758836207627955783e-01, 4.38916254547189521595e-01,
  1235. 4.39073648110117731314e-01, 4.39231016904210735952e-01,
  1236. 4.39388360937262911765e-01, 4.39545680217065026785e-01,
  1237. 4.39702974751404296327e-01, 4.39860244548064049930e-01,
  1238. 4.40017489614824119926e-01, 4.40174709959460508379e-01,
  1239. 4.40331905589745720153e-01, 4.40489076513448429839e-01,
  1240. 4.40646222738333759317e-01, 4.40803344272163166728e-01,
  1241. 4.40960441122694446481e-01, 4.41117513297681618223e-01,
  1242. 4.41274560804875204401e-01, 4.41431583652022063724e-01,
  1243. 4.41588581846865335656e-01, 4.41745555397144495924e-01,
  1244. 4.41902504310595412029e-01, 4.42059428594950398761e-01,
  1245. 4.42216328257937996149e-01, 4.42373203307283191510e-01,
  1246. 4.42530053750707252913e-01, 4.42686879595927895714e-01,
  1247. 4.42843680850659227044e-01, 4.43000457522611579275e-01,
  1248. 4.43157209619491843089e-01, 4.43313937149003189919e-01,
  1249. 4.43470640118845127464e-01, 4.43627318536713610708e-01,
  1250. 4.43783972410300986411e-01, 4.43940601747295937596e-01,
  1251. 4.44097206555383594573e-01, 4.44253786842245423916e-01,
  1252. 4.44410342615559339485e-01, 4.44566873882999535894e-01,
  1253. 4.44723380652236766064e-01, 4.44879862930938063670e-01,
  1254. 4.45036320726766909672e-01, 4.45192754047383121296e-01,
  1255. 4.45349162900443018565e-01, 4.45505547293599368786e-01,
  1256. 4.45661907234501164510e-01, 4.45818242730793901085e-01,
  1257. 4.45974553790119576657e-01, 4.46130840420116525635e-01,
  1258. 4.46287102628419529715e-01, 4.46443340422659651345e-01,
  1259. 4.46599553810464677817e-01, 4.46755742799458455128e-01,
  1260. 4.46911907397261609631e-01, 4.47068047611490881899e-01,
  1261. 4.47224163449759737343e-01, 4.47380254919677866621e-01,
  1262. 4.47536322028851463184e-01, 4.47692364784883112261e-01,
  1263. 4.47848383195372012899e-01, 4.48004377267913589389e-01,
  1264. 4.48160347010099879839e-01, 4.48316292429519203111e-01,
  1265. 4.48472213533756491888e-01, 4.48628110330393070626e-01,
  1266. 4.48783982827006711069e-01, 4.48939831031171632247e-01,
  1267. 4.49095654950458444965e-01, 4.49251454592434429358e-01,
  1268. 4.49407229964663146315e-01, 4.49562981074704659523e-01,
  1269. 4.49718707930115535465e-01, 4.49874410538448787911e-01,
  1270. 4.50030088907253877917e-01, 4.50185743044076824848e-01,
  1271. 4.50341372956460039845e-01, 4.50496978651942492355e-01,
  1272. 4.50652560138059488093e-01, 4.50808117422343002101e-01,
  1273. 4.50963650512321345687e-01, 4.51119159415519443979e-01,
  1274. 4.51274644139458558367e-01, 4.51430104691656619575e-01,
  1275. 4.51585541079627950101e-01, 4.51740953310883319727e-01,
  1276. 4.51896341392930112058e-01, 4.52051705333272157983e-01,
  1277. 4.52207045139409735679e-01, 4.52362360818839792653e-01,
  1278. 4.52517652379055612677e-01, 4.52672919827546982319e-01,
  1279. 4.52828163171800412989e-01, 4.52983382419298696853e-01,
  1280. 4.53138577577521295403e-01, 4.53293748653944061910e-01,
  1281. 4.53448895656039463464e-01, 4.53604018591276414440e-01,
  1282. 4.53759117467120498546e-01, 4.53914192291033691262e-01,
  1283. 4.54069243070474470869e-01, 4.54224269812897984977e-01,
  1284. 4.54379272525755772971e-01, 4.54534251216496043568e-01,
  1285. 4.54689205892563397260e-01, 4.54844136561399159380e-01,
  1286. 4.54999043230440991525e-01, 4.55153925907123280137e-01,
  1287. 4.55308784598876803429e-01, 4.55463619313129008948e-01,
  1288. 4.55618430057303847036e-01, 4.55773216838821770835e-01,
  1289. 4.55927979665099847306e-01, 4.56082718543551757229e-01,
  1290. 4.56237433481587573159e-01, 4.56392124486614148005e-01,
  1291. 4.56546791566034670939e-01, 4.56701434727249055978e-01,
  1292. 4.56856053977653775444e-01, 4.57010649324641693436e-01,
  1293. 4.57165220775602509917e-01, 4.57319768337922372137e-01,
  1294. 4.57474292018983930141e-01, 4.57628791826166447798e-01,
  1295. 4.57783267766845969327e-01, 4.57937719848394764188e-01,
  1296. 4.58092148078182048732e-01, 4.58246552463573320058e-01,
  1297. 4.58400933011930911132e-01, 4.58555289730613546695e-01,
  1298. 4.58709622626976676329e-01, 4.58863931708372252416e-01,
  1299. 4.59018216982148952177e-01, 4.59172478455651955631e-01,
  1300. 4.59326716136223001108e-01, 4.59480930031200551777e-01,
  1301. 4.59635120147919573608e-01, 4.59789286493711701898e-01,
  1302. 4.59943429075905130254e-01, 4.60097547901824721617e-01,
  1303. 4.60251642978791952743e-01, 4.60405714314124858699e-01,
  1304. 4.60559761915138143884e-01, 4.60713785789143015492e-01,
  1305. 4.60867785943447572095e-01, 4.61021762385356193015e-01,
  1306. 4.61175715122170148952e-01, 4.61329644161187268914e-01,
  1307. 4.61483549509701884705e-01, 4.61637431175005163997e-01,
  1308. 4.61791289164384777255e-01, 4.61945123485125008767e-01,
  1309. 4.62098934144506923172e-01, 4.62252721149808087908e-01,
  1310. 4.62406484508302795255e-01, 4.62560224227261951313e-01,
  1311. 4.62713940313953076000e-01, 4.62867632775640358567e-01,
  1312. 4.63021301619584713105e-01, 4.63174946853043612016e-01,
  1313. 4.63328568483271197032e-01, 4.63482166517518334725e-01,
  1314. 4.63635740963032505491e-01, 4.63789291827057803541e-01,
  1315. 4.63942819116835103443e-01, 4.64096322839601782562e-01,
  1316. 4.64249803002592054124e-01, 4.64403259613036689668e-01,
  1317. 4.64556692678163130061e-01, 4.64710102205195596525e-01,
  1318. 4.64863488201354924101e-01, 4.65016850673858561649e-01,
  1319. 4.65170189629920738383e-01, 4.65323505076752297338e-01,
  1320. 4.65476797021560750878e-01, 4.65630065471550447231e-01,
  1321. 4.65783310433922237426e-01, 4.65936531915873697329e-01,
  1322. 4.66089729924599238675e-01, 4.66242904467289775994e-01,
  1323. 4.66396055551133059680e-01, 4.66549183183313398438e-01,
  1324. 4.66702287371011992345e-01, 4.66855368121406655302e-01,
  1325. 4.67008425441671759515e-01, 4.67161459338978624078e-01,
  1326. 4.67314469820495126395e-01, 4.67467456893385868710e-01,
  1327. 4.67620420564812233621e-01, 4.67773360841932217546e-01,
  1328. 4.67926277731900652768e-01, 4.68079171241869040898e-01,
  1329. 4.68232041378985497371e-01, 4.68384888150395028994e-01,
  1330. 4.68537711563239256396e-01, 4.68690511624656580558e-01,
  1331. 4.68843288341782127304e-01, 4.68996041721747636277e-01,
  1332. 4.69148771771681794007e-01, 4.69301478498709900844e-01,
  1333. 4.69454161909953870957e-01, 4.69606822012532620914e-01,
  1334. 4.69759458813561625590e-01, 4.69912072320153140215e-01,
  1335. 4.70064662539416200371e-01, 4.70217229478456510972e-01,
  1336. 4.70369773144376612795e-01, 4.70522293544275715949e-01,
  1337. 4.70674790685249866407e-01, 4.70827264574391779473e-01,
  1338. 4.70979715218791006315e-01, 4.71132142625533822944e-01,
  1339. 4.71284546801703230212e-01, 4.71436927754379064837e-01,
  1340. 4.71589285490637777354e-01, 4.71741620017552876210e-01,
  1341. 4.71893931342194261624e-01, 4.72046219471628891728e-01,
  1342. 4.72198484412920449493e-01, 4.72350726173129231711e-01,
  1343. 4.72502944759312482059e-01, 4.72655140178524169059e-01,
  1344. 4.72807312437814986072e-01, 4.72959461544232517838e-01,
  1345. 4.73111587504821018424e-01, 4.73263690326621577764e-01,
  1346. 4.73415770016672121656e-01, 4.73567826582007300740e-01,
  1347. 4.73719860029658546008e-01, 4.73871870366654179829e-01,
  1348. 4.74023857600019193903e-01, 4.74175821736775415793e-01,
  1349. 4.74327762783941508928e-01, 4.74479680748532972601e-01,
  1350. 4.74631575637562030945e-01, 4.74783447458037688449e-01,
  1351. 4.74935296216965896487e-01, 4.75087121921349220255e-01,
  1352. 4.75238924578187227343e-01, 4.75390704194476154676e-01,
  1353. 4.75542460777209186062e-01, 4.75694194333376174644e-01,
  1354. 4.75845904869963920447e-01, 4.75997592393955948342e-01,
  1355. 4.76149256912332674574e-01, 4.76300898432071240229e-01,
  1356. 4.76452516960145788794e-01, 4.76604112503527188593e-01,
  1357. 4.76755685069183032798e-01, 4.76907234664077916975e-01,
  1358. 4.77058761295173217043e-01, 4.77210264969427089277e-01,
  1359. 4.77361745693794636836e-01, 4.77513203475227632211e-01,
  1360. 4.77664638320674905803e-01, 4.77816050237081957341e-01,
  1361. 4.77967439231391233445e-01, 4.78118805310541961084e-01,
  1362. 4.78270148481470258606e-01, 4.78421468751109080220e-01,
  1363. 4.78572766126388271513e-01, 4.78724040614234402913e-01,
  1364. 4.78875292221571102758e-01, 4.79026520955318668715e-01,
  1365. 4.79177726822394400852e-01, 4.79328909829712324076e-01,
  1366. 4.79480069984183521203e-01, 4.79631207292715744384e-01,
  1367. 4.79782321762213748162e-01, 4.79933413399579067438e-01,
  1368. 4.80084482211710183996e-01, 4.80235528205502359977e-01,
  1369. 4.80386551387847859917e-01, 4.80537551765635728707e-01,
  1370. 4.80688529345751902611e-01, 4.80839484135079264782e-01,
  1371. 4.80990416140497478725e-01, 4.81141325368883154834e-01,
  1372. 4.81292211827109794875e-01, 4.81443075522047847503e-01,
  1373. 4.81593916460564486215e-01, 4.81744734649523886905e-01,
  1374. 4.81895530095787172353e-01, 4.82046302806212301206e-01,
  1375. 4.82197052787654012462e-01, 4.82347780046964158540e-01,
  1376. 4.82498484590991372212e-01, 4.82649166426581233136e-01,
  1377. 4.82799825560576212347e-01, 4.82950461999815616743e-01,
  1378. 4.83101075751135811132e-01, 4.83251666821369940674e-01,
  1379. 4.83402235217348152929e-01, 4.83552780945897431319e-01,
  1380. 4.83703304013841761666e-01, 4.83853804428001965654e-01,
  1381. 4.84004282195195867367e-01, 4.84154737322238126751e-01,
  1382. 4.84305169815940406153e-01, 4.84455579683111259293e-01,
  1383. 4.84605966930556131267e-01, 4.84756331565077469570e-01,
  1384. 4.84906673593474557560e-01, 4.85056993022543792016e-01,
  1385. 4.85207289859078350069e-01, 4.85357564109868300228e-01,
  1386. 4.85507815781700824420e-01, 4.85658044881359884926e-01,
  1387. 4.85808251415626557446e-01, 4.85958435391278642523e-01,
  1388. 4.86108596815091109633e-01, 4.86258735693835708602e-01,
  1389. 4.86408852034281247168e-01, 4.86558945843193424441e-01,
  1390. 4.86709017127334886421e-01, 4.86859065893465337016e-01,
  1391. 4.87009092148341260486e-01, 4.87159095898716310025e-01,
  1392. 4.87309077151340919176e-01, 4.87459035912962579395e-01,
  1393. 4.87608972190325673512e-01, 4.87758885990171697777e-01,
  1394. 4.87908777319238984305e-01, 4.88058646184262812096e-01,
  1395. 4.88208492591975629082e-01, 4.88358316549106552529e-01,
  1396. 4.88508118062381979652e-01, 4.88657897138525088021e-01,
  1397. 4.88807653784256113116e-01, 4.88957388006292237304e-01,
  1398. 4.89107099811347700857e-01, 4.89256789206133579917e-01,
  1399. 4.89406456197358119553e-01, 4.89556100791726400701e-01,
  1400. 4.89705722995940617714e-01, 4.89855322816699856325e-01,
  1401. 4.90004900260700204662e-01, 4.90154455334634808761e-01,
  1402. 4.90303988045193817058e-01, 4.90453498399064324875e-01,
  1403. 4.90602986402930429932e-01, 4.90752452063473232347e-01,
  1404. 4.90901895387370890145e-01, 4.91051316381298508240e-01,
  1405. 4.91200715051928193944e-01, 4.91350091405929167987e-01,
  1406. 4.91499445449967542476e-01, 4.91648777190706487428e-01,
  1407. 4.91798086634806175255e-01, 4.91947373788923836280e-01,
  1408. 4.92096638659713703223e-01, 4.92245881253827011204e-01,
  1409. 4.92395101577911997737e-01, 4.92544299638613958248e-01,
  1410. 4.92693475442575246070e-01, 4.92842628996435161426e-01,
  1411. 4.92991760306830117955e-01, 4.93140869380393531696e-01,
  1412. 4.93289956223755765574e-01, 4.93439020843544351447e-01,
  1413. 4.93588063246383768057e-01, 4.93737083438895607568e-01,
  1414. 4.93886081427698409030e-01, 4.94035057219407824913e-01,
  1415. 4.94184010820636510086e-01, 4.94332942237994232837e-01,
  1416. 4.94481851478087708340e-01, 4.94630738547520820703e-01,
  1417. 4.94779603452894345406e-01, 4.94928446200806226862e-01,
  1418. 4.95077266797851522906e-01, 4.95226065250622127234e-01,
  1419. 4.95374841565707269009e-01, 4.95523595749692957746e-01,
  1420. 4.95672327809162538426e-01, 4.95821037750696136381e-01,
  1421. 4.95969725580871212411e-01, 4.96118391306262063178e-01,
  1422. 4.96267034933440265299e-01, 4.96415656468974286764e-01,
  1423. 4.96564255919429764496e-01, 4.96712833291369393329e-01,
  1424. 4.96861388591352926003e-01, 4.97009921825937173168e-01,
  1425. 4.97158433001676058893e-01, 4.97306922125120620670e-01,
  1426. 4.97455389202818953898e-01, 4.97603834241316156373e-01,
  1427. 4.97752257247154494824e-01, 4.97900658226873293888e-01,
  1428. 4.98049037187008991623e-01, 4.98197394134095139506e-01,
  1429. 4.98345729074662346925e-01, 4.98494042015238225662e-01,
  1430. 4.98642332962347667458e-01, 4.98790601922512566446e-01,
  1431. 4.98938848902251819162e-01, 4.99087073908081657603e-01,
  1432. 4.99235276946515205143e-01, 4.99383458024062754088e-01,
  1433. 4.99531617147231821185e-01, 4.99679754322526759047e-01,
  1434. 4.99827869556449311261e-01, 4.99975962855498223814e-01,
  1435. 5.00124034226169245088e-01, 5.00272083674955569954e-01,
  1436. 5.00420111208346951592e-01, 5.00568116832830867224e-01,
  1437. 5.00716100554891574426e-01, 5.00864062381010444192e-01,
  1438. 5.01012002317666071960e-01, 5.01159920371334166589e-01,
  1439. 5.01307816548487550357e-01, 5.01455690855596269984e-01,
  1440. 5.01603543299127152544e-01, 5.01751373885544693643e-01,
  1441. 5.01899182621310058217e-01, 5.02046969512881746667e-01,
  1442. 5.02194734566715483837e-01, 5.02342477789263885946e-01,
  1443. 5.02490199186977015700e-01, 5.02637898766301716158e-01,
  1444. 5.02785576533682276867e-01, 5.02933232495559989772e-01,
  1445. 5.03080866658373260236e-01, 5.03228479028557940111e-01,
  1446. 5.03376069612546661602e-01, 5.03523638416769281356e-01,
  1447. 5.03671185447652880462e-01, 5.03818710711621875475e-01,
  1448. 5.03966214215097574325e-01, 5.04113695964498398361e-01,
  1449. 5.04261155966240215420e-01, 5.04408594226735784716e-01,
  1450. 5.04556010752395311947e-01, 5.04703405549625783166e-01,
  1451. 5.04850778624831741936e-01, 5.04998129984414623195e-01,
  1452. 5.05145459634773197344e-01, 5.05292767582303348206e-01,
  1453. 5.05440053833398073024e-01, 5.05587318394447704506e-01,
  1454. 5.05734561271839577756e-01, 5.05881782471958252323e-01,
  1455. 5.06028982001185512196e-01, 5.06176159865900365808e-01,
  1456. 5.06323316072478935013e-01, 5.06470450627294455082e-01,
  1457. 5.06617563536717607775e-01, 5.06764654807115966229e-01,
  1458. 5.06911724444854328020e-01, 5.07058772456294937214e-01,
  1459. 5.07205798847797040274e-01, 5.07352803625717108105e-01,
  1460. 5.07499786796408614009e-01, 5.07646748366222699822e-01,
  1461. 5.07793688341507287731e-01, 5.07940606728607746412e-01,
  1462. 5.08087503533866335914e-01, 5.08234378763622984820e-01,
  1463. 5.08381232424214291044e-01, 5.08528064521974632051e-01,
  1464. 5.08674875063235165662e-01, 5.08821664054324496185e-01,
  1465. 5.08968431501568119302e-01, 5.09115177411289310250e-01,
  1466. 5.09261901789807902574e-01, 5.09408604643441509374e-01,
  1467. 5.09555285978504746147e-01, 5.09701945801309230788e-01,
  1468. 5.09848584118164027679e-01, 5.09995200935375647688e-01,
  1469. 5.10141796259247382039e-01, 5.10288370096079968441e-01,
  1470. 5.10434922452171369045e-01, 5.10581453333816770446e-01,
  1471. 5.10727962747308583680e-01, 5.10874450698936555249e-01,
  1472. 5.11020917194987545074e-01, 5.11167362241745526497e-01,
  1473. 5.11313785845492030369e-01, 5.11460188012505589938e-01,
  1474. 5.11606568749062073920e-01, 5.11752928061434575469e-01,
  1475. 5.11899265955893412183e-01, 5.12045582438706237127e-01,
  1476. 5.12191877516137816784e-01, 5.12338151194450253101e-01,
  1477. 5.12484403479902872469e-01, 5.12630634378752336744e-01,
  1478. 5.12776843897252421201e-01, 5.12923032041654236579e-01,
  1479. 5.13069198818206229085e-01, 5.13215344233153958342e-01,
  1480. 5.13361468292740430464e-01, 5.13507571003205542937e-01,
  1481. 5.13653652370786972803e-01, 5.13799712401719177457e-01,
  1482. 5.13945751102234282826e-01, 5.14091768478561528255e-01,
  1483. 5.14237764536927266512e-01, 5.14383739283555296851e-01,
  1484. 5.14529692724666865011e-01, 5.14675624866479997088e-01,
  1485. 5.14821535715210387707e-01, 5.14967425277071066958e-01,
  1486. 5.15113293558271956307e-01, 5.15259140565020756775e-01,
  1487. 5.15404966303521949733e-01, 5.15550770779977685088e-01,
  1488. 5.15696554000587226163e-01, 5.15842315971547171749e-01,
  1489. 5.15988056699051345078e-01, 5.16133776189290904846e-01,
  1490. 5.16279474448454456237e-01, 5.16425151482727717855e-01,
  1491. 5.16570807298293632748e-01, 5.16716441901332701470e-01,
  1492. 5.16862055298022426975e-01, 5.17007647494537869726e-01,
  1493. 5.17153218497051314628e-01, 5.17298768311732271030e-01,
  1494. 5.17444296944747583744e-01, 5.17589804402261544070e-01,
  1495. 5.17735290690435445704e-01, 5.17880755815428361899e-01,
  1496. 5.18026199783396146259e-01, 5.18171622600492431943e-01,
  1497. 5.18317024272867854506e-01, 5.18462404806670384971e-01,
  1498. 5.18607764208045662890e-01, 5.18753102483136108170e-01,
  1499. 5.18898419638082031291e-01, 5.19043715679020523091e-01,
  1500. 5.19188990612086342935e-01, 5.19334244443411474634e-01,
  1501. 5.19479477179125348485e-01, 5.19624688825354508204e-01,
  1502. 5.19769879388223055017e-01, 5.19915048873852092548e-01,
  1503. 5.20060197288360503975e-01, 5.20205324637864174875e-01,
  1504. 5.20350430928476548331e-01, 5.20495516166308069828e-01,
  1505. 5.20640580357466964401e-01, 5.20785623508058459485e-01,
  1506. 5.20930645624185340026e-01, 5.21075646711947504386e-01,
  1507. 5.21220626777442519462e-01, 5.21365585826764954547e-01,
  1508. 5.21510523866007047467e-01, 5.21655440901258149466e-01,
  1509. 5.21800336938605058279e-01, 5.21945211984131907101e-01,
  1510. 5.22090066043920164596e-01, 5.22234899124048745911e-01,
  1511. 5.22379711230593901661e-01, 5.22524502369629217924e-01,
  1512. 5.22669272547225505221e-01, 5.22814021769451131583e-01,
  1513. 5.22958750042371911526e-01, 5.23103457372050661967e-01,
  1514. 5.23248143764547868351e-01, 5.23392809225921240568e-01,
  1515. 5.23537453762226157039e-01, 5.23682077379514887561e-01,
  1516. 5.23826680083837370461e-01, 5.23971261881240990554e-01,
  1517. 5.24115822777770357099e-01, 5.24260362779467303795e-01,
  1518. 5.24404881892371554919e-01, 5.24549380122519615099e-01,
  1519. 5.24693857475945879543e-01, 5.24838313958681745852e-01,
  1520. 5.24982749576756169141e-01, 5.25127164336195551009e-01,
  1521. 5.25271558243023517498e-01, 5.25415931303261363183e-01,
  1522. 5.25560283522927385036e-01, 5.25704614908037548560e-01,
  1523. 5.25848925464605154723e-01, 5.25993215198640950980e-01,
  1524. 5.26137484116153020253e-01, 5.26281732223146669902e-01,
  1525. 5.26425959525624986846e-01, 5.26570166029588282441e-01,
  1526. 5.26714351741034092491e-01, 5.26858516665957621328e-01,
  1527. 5.27002660810351297727e-01, 5.27146784180205107972e-01,
  1528. 5.27290886781506484837e-01, 5.27434968620239974513e-01,
  1529. 5.27579029702387902745e-01, 5.27723070033929708700e-01,
  1530. 5.27867089620842389053e-01, 5.28011088469100386966e-01,
  1531. 5.28155066584675592090e-01, 5.28299023973537229537e-01,
  1532. 5.28442960641651859888e-01, 5.28586876594983601230e-01,
  1533. 5.28730771839494129161e-01, 5.28874646381142232698e-01,
  1534. 5.29018500225884258370e-01, 5.29162333379674110212e-01,
  1535. 5.29306145848463027725e-01, 5.29449937638199585876e-01,
  1536. 5.29593708754829917140e-01, 5.29737459204297600479e-01,
  1537. 5.29881188992543661342e-01, 5.30024898125506349622e-01,
  1538. 5.30168586609121583741e-01, 5.30312254449322728611e-01,
  1539. 5.30455901652040484606e-01, 5.30599528223202998589e-01,
  1540. 5.30743134168735974932e-01, 5.30886719494562342447e-01,
  1541. 5.31030284206602809505e-01, 5.31173828310775197892e-01,
  1542. 5.31317351812994997928e-01, 5.31460854719175146421e-01,
  1543. 5.31604337035225804620e-01, 5.31747798767055024349e-01,
  1544. 5.31891239920567859834e-01, 5.32034660501667033827e-01,
  1545. 5.32178060516252715573e-01, 5.32321439970222631821e-01,
  1546. 5.32464798869471844789e-01, 5.32608137219892863179e-01,
  1547. 5.32751455027375753204e-01, 5.32894752297807916541e-01,
  1548. 5.33038029037074423400e-01, 5.33181285251057679453e-01,
  1549. 5.33324520945637647884e-01, 5.33467736126691627341e-01,
  1550. 5.33610930800094473980e-01, 5.33754104971718490447e-01,
  1551. 5.33897258647433536893e-01, 5.34040391833106919961e-01,
  1552. 5.34183504534603503799e-01, 5.34326596757785265979e-01,
  1553. 5.34469668508512185667e-01, 5.34612719792641466476e-01,
  1554. 5.34755750616027647482e-01, 5.34898760984523158335e-01,
  1555. 5.35041750903977431086e-01, 5.35184720380237788362e-01,
  1556. 5.35327669419148999275e-01, 5.35470598026553057380e-01,
  1557. 5.35613506208289624766e-01, 5.35756393970195921028e-01,
  1558. 5.35899261318106612251e-01, 5.36042108257853922026e-01,
  1559. 5.36184934795267298391e-01, 5.36327740936173968933e-01,
  1560. 5.36470526686398718752e-01, 5.36613292051763668411e-01,
  1561. 5.36756037038088384961e-01, 5.36898761651190215005e-01,
  1562. 5.37041465896883618569e-01, 5.37184149780981057276e-01,
  1563. 5.37326813309292106169e-01, 5.37469456487623897800e-01,
  1564. 5.37612079321781455299e-01, 5.37754681817566693169e-01,
  1565. 5.37897263980779749559e-01, 5.38039825817217653992e-01,
  1566. 5.38182367332675215543e-01, 5.38324888532945022845e-01,
  1567. 5.38467389423816666927e-01, 5.38609870011077740415e-01,
  1568. 5.38752330300513060379e-01, 5.38894770297905112422e-01,
  1569. 5.39037190009033828630e-01, 5.39179589439676698603e-01,
  1570. 5.39321968595608880470e-01, 5.39464327482602756803e-01,
  1571. 5.39606666106428600749e-01, 5.39748984472854020922e-01,
  1572. 5.39891282587644072422e-01, 5.40033560456561589902e-01,
  1573. 5.40175818085366854504e-01, 5.40318055479817593856e-01,
  1574. 5.40460272645669204117e-01, 5.40602469588674527934e-01,
  1575. 5.40744646314584076485e-01, 5.40886802829145696414e-01,
  1576. 5.41028939138105124940e-01, 5.41171055247205212702e-01,
  1577. 5.41313151162186700915e-01, 5.41455226888787888306e-01,
  1578. 5.41597282432744409064e-01, 5.41739317799789454888e-01,
  1579. 5.41881332995654108053e-01, 5.42023328026066675278e-01,
  1580. 5.42165302896753020789e-01, 5.42307257613436899391e-01,
  1581. 5.42449192181839179305e-01, 5.42591106607678730356e-01,
  1582. 5.42733000896671757829e-01, 5.42874875054531913499e-01,
  1583. 5.43016729086970628693e-01, 5.43158562999696892248e-01,
  1584. 5.43300376798417139490e-01, 5.43442170488835474274e-01,
  1585. 5.43583944076653557964e-01, 5.43725697567570720459e-01,
  1586. 5.43867430967283516097e-01, 5.44009144281486500816e-01,
  1587. 5.44150837515871677041e-01, 5.44292510676128493685e-01,
  1588. 5.44434163767944068191e-01, 5.44575796797003186533e-01,
  1589. 5.44717409768987970153e-01, 5.44859002689578542089e-01,
  1590. 5.45000575564452249822e-01, 5.45142128399284109364e-01,
  1591. 5.45283661199746805259e-01, 5.45425173971510579563e-01,
  1592. 5.45566666720243342859e-01, 5.45708139451610341197e-01,
  1593. 5.45849592171274711205e-01, 5.45991024884897147018e-01,
  1594. 5.46132437598135678236e-01, 5.46273830316646225036e-01,
  1595. 5.46415203046082265104e-01, 5.46556555792094611590e-01,
  1596. 5.46697888560332190266e-01, 5.46839201356441040325e-01,
  1597. 5.46980494186064980511e-01, 5.47121767054845498102e-01,
  1598. 5.47263019968421748906e-01, 5.47404252932430224199e-01,
  1599. 5.47545465952505305829e-01, 5.47686659034278933156e-01,
  1600. 5.47827832183380492026e-01, 5.47968985405437147840e-01,
  1601. 5.48110118706073623507e-01, 5.48251232090912310468e-01,
  1602. 5.48392325565573157675e-01, 5.48533399135673782610e-01,
  1603. 5.48674452806829471285e-01, 5.48815486584652956203e-01,
  1604. 5.48956500474754749419e-01, 5.49097494482743031519e-01,
  1605. 5.49238468614223429576e-01, 5.49379422874799350218e-01,
  1606. 5.49520357270071757583e-01, 5.49661271805639173316e-01,
  1607. 5.49802166487098009640e-01, 5.49943041320042236286e-01,
  1608. 5.50083896310063047430e-01, 5.50224731462749860889e-01,
  1609. 5.50365546783689540966e-01, 5.50506342278466287432e-01,
  1610. 5.50647117952662301654e-01, 5.50787873811857342510e-01,
  1611. 5.50928609861628726385e-01, 5.51069326107551438199e-01,
  1612. 5.51210022555198242422e-01, 5.51350699210139350015e-01,
  1613. 5.51491356077942862512e-01, 5.51631993164174216915e-01,
  1614. 5.51772610474396740798e-01, 5.51913208014171430271e-01,
  1615. 5.52053785789056838951e-01, 5.52194343804609077964e-01,
  1616. 5.52334882066382037991e-01, 5.52475400579927389266e-01,
  1617. 5.52615899350794248512e-01, 5.52756378384529512005e-01,
  1618. 5.52896837686677744550e-01, 5.53037277262781068465e-01,
  1619. 5.53177697118379274599e-01, 5.53318097259010044375e-01,
  1620. 5.53458477690208505706e-01, 5.53598838417507566056e-01,
  1621. 5.53739179446437690402e-01, 5.53879500782527012248e-01,
  1622. 5.54019802431301555679e-01, 5.54160084398284791263e-01,
  1623. 5.54300346688997858102e-01, 5.54440589308959896897e-01,
  1624. 5.54580812263687272790e-01, 5.54721015558694352521e-01,
  1625. 5.54861199199493171363e-01, 5.55001363191593100055e-01,
  1626. 5.55141507540501621953e-01, 5.55281632251723666904e-01,
  1627. 5.55421737330761944307e-01, 5.55561822783116832092e-01,
  1628. 5.55701888614286376722e-01, 5.55841934829766293191e-01,
  1629. 5.55981961435050076048e-01, 5.56121968435628777350e-01,
  1630. 5.56261955836991228708e-01, 5.56401923644624041287e-01,
  1631. 5.56541871864011383764e-01, 5.56681800500635093343e-01,
  1632. 5.56821709559974897807e-01, 5.56961599047508082450e-01,
  1633. 5.57101468968709601093e-01, 5.57241319329052187115e-01,
  1634. 5.57381150134006353447e-01, 5.57520961389040059508e-01,
  1635. 5.57660753099619377338e-01, 5.57800525271207603417e-01,
  1636. 5.57940277909266035827e-01, 5.58080011019253752202e-01,
  1637. 5.58219724606627387686e-01, 5.58359418676841245954e-01,
  1638. 5.58499093235347632280e-01, 5.58638748287596076381e-01,
  1639. 5.58778383839034331615e-01, 5.58917999895107486807e-01,
  1640. 5.59057596461258632381e-01, 5.59197173542928527290e-01,
  1641. 5.59336731145555376976e-01, 5.59476269274575499502e-01,
  1642. 5.59615787935422659416e-01, 5.59755287133528511845e-01,
  1643. 5.59894766874322380446e-01, 5.60034227163231146385e-01,
  1644. 5.60173668005679803450e-01, 5.60313089407090680893e-01,
  1645. 5.60452491372884220588e-01, 5.60591873908478199873e-01,
  1646. 5.60731237019288286660e-01, 5.60870580710728150464e-01,
  1647. 5.61009904988208907284e-01, 5.61149209857139341651e-01,
  1648. 5.61288495322926128672e-01, 5.61427761390973834033e-01,
  1649. 5.61567008066684469902e-01, 5.61706235355457939029e-01,
  1650. 5.61845443262691812691e-01, 5.61984631793781552744e-01,
  1651. 5.62123800954120289575e-01, 5.62262950749098933123e-01,
  1652. 5.62402081184105950840e-01, 5.62541192264527811773e-01,
  1653. 5.62680283995748653503e-01, 5.62819356383150282142e-01,
  1654. 5.62958409432112505399e-01, 5.63097443148012466452e-01,
  1655. 5.63236457536225532117e-01, 5.63375452602124515700e-01,
  1656. 5.63514428351080010060e-01, 5.63653384788460498633e-01,
  1657. 5.63792321919632244409e-01, 5.63931239749959178909e-01,
  1658. 5.64070138284803013207e-01, 5.64209017529523126910e-01,
  1659. 5.64347877489476790203e-01, 5.64486718170019163843e-01,
  1660. 5.64625539576502966099e-01, 5.64764341714278694795e-01,
  1661. 5.64903124588694849351e-01, 5.65041888205097375675e-01,
  1662. 5.65180632568830110252e-01, 5.65319357685234891164e-01,
  1663. 5.65458063559651002983e-01, 5.65596750197415842898e-01,
  1664. 5.65735417603864143565e-01, 5.65874065784328972306e-01,
  1665. 5.66012694744140620884e-01, 5.66151304488627493683e-01,
  1666. 5.66289895023115885664e-01, 5.66428466352929538274e-01,
  1667. 5.66567018483390194561e-01, 5.66705551419817266101e-01,
  1668. 5.66844065167528166072e-01, 5.66982559731837976180e-01,
  1669. 5.67121035118059335645e-01, 5.67259491331503107325e-01,
  1670. 5.67397928377477600570e-01, 5.67536346261289237347e-01,
  1671. 5.67674744988241775090e-01, 5.67813124563637305897e-01,
  1672. 5.67951484992775368355e-01, 5.68089826280953391624e-01,
  1673. 5.68228148433466695444e-01, 5.68366451455608157062e-01,
  1674. 5.68504735352668766346e-01, 5.68643000129937070675e-01,
  1675. 5.68781245792699508002e-01, 5.68919472346240517879e-01,
  1676. 5.69057679795841986348e-01, 5.69195868146784023089e-01,
  1677. 5.69334037404344073252e-01, 5.69472187573797694604e-01,
  1678. 5.69610318660418335490e-01, 5.69748430669477001764e-01,
  1679. 5.69886523606242811901e-01, 5.70024597475982330863e-01,
  1680. 5.70162652283960236232e-01, 5.70300688035438985146e-01,
  1681. 5.70438704735678814295e-01, 5.70576702389937739923e-01,
  1682. 5.70714681003471557830e-01, 5.70852640581534065412e-01,
  1683. 5.70990581129376728597e-01, 5.71128502652249014915e-01,
  1684. 5.71266405155397949400e-01, 5.71404288644068669711e-01,
  1685. 5.71542153123503982037e-01, 5.71679998598944472121e-01,
  1686. 5.71817825075628838327e-01, 5.71955632558793225506e-01,
  1687. 5.72093421053671891130e-01, 5.72231190565496872225e-01,
  1688. 5.72368941099498096392e-01, 5.72506672660903048744e-01,
  1689. 5.72644385254937327012e-01, 5.72782078886824419506e-01,
  1690. 5.72919753561785483065e-01, 5.73057409285039565106e-01,
  1691. 5.73195046061803492599e-01, 5.73332663897292205135e-01,
  1692. 5.73470262796718088794e-01, 5.73607842765291753295e-01,
  1693. 5.73745403808221365871e-01, 5.73882945930713095350e-01,
  1694. 5.74020469137971001139e-01, 5.74157973435197033218e-01,
  1695. 5.74295458827590588058e-01, 5.74432925320349507814e-01,
  1696. 5.74570372918669192153e-01, 5.74707801627742709272e-01,
  1697. 5.74845211452761462034e-01, 5.74982602398914188768e-01,
  1698. 5.75119974471387962467e-01, 5.75257327675367413633e-01,
  1699. 5.75394662016035063345e-01, 5.75531977498571434282e-01,
  1700. 5.75669274128154828674e-01, 5.75806551909961439328e-01,
  1701. 5.75943810849165349630e-01, 5.76081050950938422517e-01,
  1702. 5.76218272220450522525e-01, 5.76355474662869182723e-01,
  1703. 5.76492658283360159821e-01, 5.76629823087086545996e-01,
  1704. 5.76766969079209990134e-01, 5.76904096264889365564e-01,
  1705. 5.77041204649281769257e-01, 5.77178294237542299783e-01,
  1706. 5.77315365034823613222e-01, 5.77452417046276367252e-01,
  1707. 5.77589450277049221150e-01, 5.77726464732288613746e-01,
  1708. 5.77863460417138763425e-01, 5.78000437336742001193e-01,
  1709. 5.78137395496238437609e-01, 5.78274334900766073808e-01,
  1710. 5.78411255555460690481e-01, 5.78548157465456180937e-01,
  1711. 5.78685040635884107019e-01, 5.78821905071874143189e-01,
  1712. 5.78958750778553632443e-01, 5.79095577761048030396e-01,
  1713. 5.79232386024480461195e-01, 5.79369175573972161608e-01,
  1714. 5.79505946414642258979e-01, 5.79642698551607438162e-01,
  1715. 5.79779431989982829698e-01, 5.79916146734881010616e-01,
  1716. 5.80052842791412559542e-01, 5.80189520164686278747e-01,
  1717. 5.80326178859808416988e-01, 5.80462818881883446664e-01,
  1718. 5.80599440236013508709e-01, 5.80736042927298967697e-01,
  1719. 5.80872626960837856736e-01, 5.81009192341726099507e-01,
  1720. 5.81145739075057621292e-01, 5.81282267165924348973e-01,
  1721. 5.81418776619415988982e-01, 5.81555267440620138331e-01,
  1722. 5.81691739634622506649e-01, 5.81828193206506472102e-01,
  1723. 5.81964628161353414448e-01, 5.82101044504242826072e-01,
  1724. 5.82237442240251867887e-01, 5.82373821374455813427e-01,
  1725. 5.82510181911927604759e-01, 5.82646523857738407592e-01,
  1726. 5.82782847216957056169e-01, 5.82919151994650497350e-01,
  1727. 5.83055438195883679597e-01, 5.83191705825719108880e-01,
  1728. 5.83327954889217514811e-01, 5.83464185391437628603e-01,
  1729. 5.83600397337435849998e-01, 5.83736590732266802384e-01,
  1730. 5.83872765580982666656e-01, 5.84008921888633958375e-01,
  1731. 5.84145059660268861634e-01, 5.84281178900933673148e-01,
  1732. 5.84417279615672580206e-01, 5.84553361809527549653e-01,
  1733. 5.84689425487538660953e-01, 5.84825470654743884147e-01,
  1734. 5.84961497316179301897e-01, 5.85097505476878554376e-01,
  1735. 5.85233495141873616419e-01, 5.85369466316194131394e-01,
  1736. 5.85505419004867966315e-01, 5.85641353212920767746e-01,
  1737. 5.85777268945375961806e-01, 5.85913166207255309281e-01,
  1738. 5.86049045003578239488e-01, 5.86184905339362183341e-01,
  1739. 5.86320747219622684376e-01, 5.86456570649373176707e-01,
  1740. 5.86592375633624762976e-01, 5.86728162177386880494e-01,
  1741. 5.86863930285666857145e-01, 5.86999679963469911392e-01,
  1742. 5.87135411215799041251e-01, 5.87271124047655579403e-01,
  1743. 5.87406818464038527061e-01, 5.87542494469945109081e-01,
  1744. 5.87678152070370218851e-01, 5.87813791270306862380e-01,
  1745. 5.87949412074746158297e-01, 5.88085014488676893762e-01,
  1746. 5.88220598517086079582e-01, 5.88356164164958506113e-01,
  1747. 5.88491711437277187358e-01, 5.88627240339022916871e-01,
  1748. 5.88762750875174489806e-01, 5.88898243050708591895e-01,
  1749. 5.89033716870600132509e-01, 5.89169172339821800577e-01,
  1750. 5.89304609463344397646e-01, 5.89440028246136504819e-01,
  1751. 5.89575428693164815819e-01, 5.89710810809394025966e-01,
  1752. 5.89846174599786832182e-01, 5.89981520069303932985e-01,
  1753. 5.90116847222903695425e-01, 5.90252156065543043262e-01,
  1754. 5.90387446602176346744e-01, 5.90522718837756310784e-01,
  1755. 5.90657972777233530870e-01, 5.90793208425556493069e-01,
  1756. 5.90928425787671796066e-01, 5.91063624868523929123e-01,
  1757. 5.91198805673055605148e-01, 5.91333968206207205576e-01,
  1758. 5.91469112472917446510e-01, 5.91604238478122712586e-01,
  1759. 5.91739346226757612079e-01, 5.91874435723754643845e-01,
  1760. 5.92009506974044419358e-01, 5.92144559982555440669e-01,
  1761. 5.92279594754214322450e-01, 5.92414611293945458925e-01,
  1762. 5.92549609606671578987e-01, 5.92684589697313191081e-01,
  1763. 5.92819551570788805250e-01, 5.92954495232015155182e-01,
  1764. 5.93089420685906643094e-01, 5.93224327937376005870e-01,
  1765. 5.93359216991333870972e-01, 5.93494087852688756435e-01,
  1766. 5.93628940526347403939e-01, 5.93763775017214334717e-01,
  1767. 5.93898591330192404669e-01, 5.94033389470182138226e-01,
  1768. 5.94168169442082394482e-01, 5.94302931250789812090e-01,
  1769. 5.94437674901199142319e-01, 5.94572400398203249061e-01,
  1770. 5.94707107746692775763e-01, 5.94841796951556700535e-01,
  1771. 5.94976468017681670020e-01, 5.95111120949952776549e-01,
  1772. 5.95245755753252669962e-01, 5.95380372432462556809e-01,
  1773. 5.95514970992461090127e-01, 5.95649551438125590686e-01,
  1774. 5.95784113774330714719e-01, 5.95918658005949786194e-01,
  1775. 5.96053184137853686586e-01, 5.96187692174911743059e-01,
  1776. 5.96322182121990951309e-01, 5.96456653983956530674e-01,
  1777. 5.96591107765671591068e-01, 5.96725543471997688094e-01,
  1778. 5.96859961107793823842e-01, 5.96994360677917557112e-01,
  1779. 5.97128742187224115234e-01, 5.97263105640566949184e-01,
  1780. 5.97397451042797622556e-01, 5.97531778398765700544e-01,
  1781. 5.97666087713318527896e-01, 5.97800378991301784026e-01,
  1782. 5.97934652237559260968e-01, 5.98068907456932641331e-01,
  1783. 5.98203144654261498303e-01, 5.98337363834383739736e-01,
  1784. 5.98471565002135386102e-01, 5.98605748162350126407e-01,
  1785. 5.98739913319859984320e-01, 5.98874060479495096132e-01,
  1786. 5.99008189646083377689e-01, 5.99142300824451079500e-01,
  1787. 5.99276394019422453674e-01, 5.99410469235819531875e-01,
  1788. 5.99544526478462791452e-01, 5.99678565752170600334e-01,
  1789. 5.99812587061759439067e-01, 5.99946590412043678775e-01,
  1790. 6.00080575807836025248e-01, 6.00214543253947074852e-01,
  1791. 6.00348492755185425551e-01, 6.00482424316358009975e-01,
  1792. 6.00616337942269540306e-01, 6.00750233637722952373e-01,
  1793. 6.00884111407519294623e-01, 6.01017971256457506080e-01,
  1794. 6.01151813189334860432e-01, 6.01285637210946410924e-01,
  1795. 6.01419443326085545465e-01, 6.01553231539543431516e-01,
  1796. 6.01687001856109793252e-01, 6.01820754280571801331e-01,
  1797. 6.01954488817715294147e-01, 6.02088205472323889644e-01,
  1798. 6.02221904249179207369e-01, 6.02355585153061201531e-01,
  1799. 6.02489248188747716917e-01, 6.02622893361014821956e-01,
  1800. 6.02756520674636475654e-01, 6.02890130134384971683e-01,
  1801. 6.03023721745030605312e-01, 6.03157295511341451366e-01,
  1802. 6.03290851438084252401e-01, 6.03424389530023419503e-01,
  1803. 6.03557909791921476383e-01, 6.03691412228539170393e-01,
  1804. 6.03824896844635472526e-01, 6.03958363644967022310e-01,
  1805. 6.04091812634289015982e-01, 6.04225243817354318310e-01,
  1806. 6.04358657198914350772e-01, 6.04492052783718314402e-01,
  1807. 6.04625430576513633874e-01, 6.04758790582045624440e-01,
  1808. 6.04892132805058047040e-01, 6.05025457250292553191e-01,
  1809. 6.05158763922488907028e-01, 6.05292052826384985309e-01,
  1810. 6.05425323966716888435e-01, 6.05558577348218607384e-01,
  1811. 6.05691812975622467796e-01, 6.05825030853658685892e-01,
  1812. 6.05958230987055701533e-01, 6.06091413380540178224e-01,
  1813. 6.06224578038836670046e-01, 6.06357724966668065747e-01,
  1814. 6.06490854168755144649e-01, 6.06623965649816909718e-01,
  1815. 6.06757059414570476541e-01, 6.06890135467731184349e-01,
  1816. 6.07023193814012262948e-01, 6.07156234458125165787e-01,
  1817. 6.07289257404779569960e-01, 6.07422262658683154157e-01,
  1818. 6.07555250224541820714e-01, 6.07688220107059362540e-01,
  1819. 6.07821172310938018235e-01, 6.07954106840877805951e-01,
  1820. 6.08087023701577300550e-01, 6.08219922897732745426e-01,
  1821. 6.08352804434038829662e-01, 6.08485668315188243938e-01,
  1822. 6.08618514545871902577e-01, 6.08751343130778610480e-01,
  1823. 6.08884154074595507211e-01, 6.09016947382007955980e-01,
  1824. 6.09149723057699321593e-01, 6.09282481106350970457e-01,
  1825. 6.09415221532642714664e-01, 6.09547944341252145861e-01,
  1826. 6.09680649536855301385e-01, 6.09813337124126220168e-01,
  1827. 6.09946007107737053765e-01, 6.10078659492358177374e-01,
  1828. 6.10211294282658078814e-01, 6.10343911483303358523e-01,
  1829. 6.10476511098958729562e-01, 6.10609093134287128635e-01,
  1830. 6.10741657593949716087e-01, 6.10874204482605542843e-01,
  1831. 6.11006733804912105512e-01, 6.11139245565524680259e-01,
  1832. 6.11271739769097099959e-01, 6.11404216420281088062e-01,
  1833. 6.11536675523726702686e-01, 6.11669117084081892521e-01,
  1834. 6.11801541105992940928e-01, 6.11933947594104243883e-01,
  1835. 6.12066336553058421011e-01, 6.12198707987496204552e-01,
  1836. 6.12331061902056439372e-01, 6.12463398301376193977e-01,
  1837. 6.12595717190090538473e-01, 6.12728018572832988653e-01,
  1838. 6.12860302454234950886e-01, 6.12992568838926166208e-01,
  1839. 6.13124817731534488274e-01, 6.13257049136685772339e-01,
  1840. 6.13389263059004430367e-01, 6.13521459503112542855e-01,
  1841. 6.13653638473630858030e-01, 6.13785799975177903676e-01,
  1842. 6.13917944012370542239e-01, 6.14050070589823748790e-01,
  1843. 6.14182179712150722040e-01, 6.14314271383962884343e-01,
  1844. 6.14446345609869770676e-01, 6.14578402394478917614e-01,
  1845. 6.14710441742396418441e-01, 6.14842463658226145995e-01,
  1846. 6.14974468146570418803e-01, 6.15106455212029668012e-01,
  1847. 6.15238424859202437389e-01, 6.15370377092685383325e-01,
  1848. 6.15502311917073607894e-01, 6.15634229336960214773e-01,
  1849. 6.15766129356936420258e-01, 6.15898011981591775310e-01,
  1850. 6.16029877215514054534e-01, 6.16161725063288923110e-01,
  1851. 6.16293555529500491907e-01, 6.16425368618731095438e-01,
  1852. 6.16557164335561069812e-01, 6.16688942684569085806e-01,
  1853. 6.16820703670331926816e-01, 6.16952447297424488859e-01,
  1854. 6.17084173570420113641e-01, 6.17215882493890033444e-01,
  1855. 6.17347574072403926237e-01, 6.17479248310529471588e-01,
  1856. 6.17610905212832794753e-01, 6.17742544783877911563e-01,
  1857. 6.17874167028227172516e-01, 6.18005771950441151752e-01,
  1858. 6.18137359555078758078e-01, 6.18268929846696679853e-01,
  1859. 6.18400482829850384192e-01, 6.18532018509092895719e-01,
  1860. 6.18663536888976017813e-01, 6.18795037974049555451e-01,
  1861. 6.18926521768861204187e-01, 6.19057988277957438328e-01,
  1862. 6.19189437505882511736e-01, 6.19320869457179012940e-01,
  1863. 6.19452284136387754110e-01, 6.19583681548047882082e-01,
  1864. 6.19715061696696434268e-01, 6.19846424586868893769e-01,
  1865. 6.19977770223098967328e-01, 6.20109098609918474310e-01,
  1866. 6.20240409751857568743e-01, 6.20371703653444406257e-01,
  1867. 6.20502980319205588167e-01, 6.20634239753665939432e-01,
  1868. 6.20765481961348286610e-01, 6.20896706946773790925e-01,
  1869. 6.21027914714461837242e-01, 6.21159105268930034072e-01,
  1870. 6.21290278614694324588e-01, 6.21421434756268653565e-01,
  1871. 6.21552573698165300442e-01, 6.21683695444894879323e-01,
  1872. 6.21814800000966005911e-01, 6.21945887370885630574e-01,
  1873. 6.22076957559158927324e-01, 6.22208010570289515861e-01,
  1874. 6.22339046408778795438e-01, 6.22470065079126610996e-01,
  1875. 6.22601066585831364186e-01, 6.22732050933389125191e-01,
  1876. 6.22863018126294520904e-01, 6.22993968169040401861e-01,
  1877. 6.23124901066117842241e-01, 6.23255816822016028844e-01,
  1878. 6.23386715441222483136e-01, 6.23517596928222950226e-01,
  1879. 6.23648461287501509887e-01, 6.23779308523540354514e-01,
  1880. 6.23910138640819900147e-01, 6.24040951643819008510e-01,
  1881. 6.24171747537014431906e-01, 6.24302526324881368325e-01,
  1882. 6.24433288011893461444e-01, 6.24564032602522356541e-01,
  1883. 6.24694760101237811512e-01, 6.24825470512508140963e-01,
  1884. 6.24956163840799772125e-01, 6.25086840090577355866e-01,
  1885. 6.25217499266303877725e-01, 6.25348141372440435859e-01,
  1886. 6.25478766413446463091e-01, 6.25609374393779726908e-01,
  1887. 6.25739965317896107422e-01, 6.25870539190249819406e-01,
  1888. 6.26001096015293301278e-01, 6.26131635797477215100e-01,
  1889. 6.26262158541250557597e-01, 6.26392664251060549141e-01,
  1890. 6.26523152931352744766e-01, 6.26653624586570812127e-01,
  1891. 6.26784079221156642525e-01, 6.26914516839550683969e-01,
  1892. 6.27044937446191386066e-01, 6.27175341045515533089e-01,
  1893. 6.27305727641958132956e-01, 6.27436097239952639271e-01,
  1894. 6.27566449843930396213e-01, 6.27696785458321526718e-01,
  1895. 6.27827104087553933276e-01, 6.27957405736054186107e-01,
  1896. 6.28087690408246857032e-01, 6.28217958108554741514e-01,
  1897. 6.28348208841399302749e-01, 6.28478442611199783485e-01,
  1898. 6.28608659422374094206e-01, 6.28738859279338258013e-01,
  1899. 6.28869042186506410630e-01, 6.28999208148291244491e-01,
  1900. 6.29129357169103564651e-01, 6.29259489253352510829e-01,
  1901. 6.29389604405445557411e-01, 6.29519702629788291404e-01,
  1902. 6.29649783930784745500e-01, 6.29779848312837065016e-01,
  1903. 6.29909895780345951977e-01, 6.30039926337710110005e-01,
  1904. 6.30169939989326688412e-01, 6.30299936739590949131e-01,
  1905. 6.30429916592896710803e-01, 6.30559879553635904692e-01,
  1906. 6.30689825626198685704e-01, 6.30819754814973654433e-01,
  1907. 6.30949667124347746139e-01, 6.31079562558705897679e-01,
  1908. 6.31209441122431491600e-01, 6.31339302819906356135e-01,
  1909. 6.31469147655510432138e-01, 6.31598975633622106152e-01,
  1910. 6.31728786758617766317e-01, 6.31858581034872357485e-01,
  1911. 6.31988358466759159171e-01, 6.32118119058649563513e-01,
  1912. 6.32247862814913297314e-01, 6.32377589739918422040e-01,
  1913. 6.32507299838031444850e-01, 6.32636993113616874496e-01,
  1914. 6.32766669571037776443e-01, 6.32896329214655439799e-01,
  1915. 6.33025972048829377314e-01, 6.33155598077917547428e-01,
  1916. 6.33285207306276021200e-01, 6.33414799738259315376e-01,
  1917. 6.33544375378220392392e-01, 6.33673934230510105259e-01,
  1918. 6.33803476299478196765e-01, 6.33933001589472078230e-01,
  1919. 6.34062510104837939728e-01, 6.34192001849920194978e-01,
  1920. 6.34321476829061370317e-01, 6.34450935046602548795e-01,
  1921. 6.34580376506882926080e-01, 6.34709801214240143530e-01,
  1922. 6.34839209173010177167e-01, 6.34968600387527226658e-01,
  1923. 6.35097974862123937356e-01, 6.35227332601131067236e-01,
  1924. 6.35356673608877819959e-01, 6.35485997889691733853e-01,
  1925. 6.35615305447898681912e-01, 6.35744596287822760772e-01,
  1926. 6.35873870413786512756e-01, 6.36003127830110703833e-01,
  1927. 6.36132368541114545657e-01, 6.36261592551115362504e-01,
  1928. 6.36390799864429035360e-01, 6.36519990485369668853e-01,
  1929. 6.36649164418249702280e-01, 6.36778321667379798576e-01,
  1930. 6.36907462237069177391e-01, 6.37036586131625282015e-01,
  1931. 6.37165693355353779381e-01, 6.37294783912558782113e-01,
  1932. 6.37423857807542737497e-01, 6.37552915044606427486e-01,
  1933. 6.37681955628048968698e-01, 6.37810979562167701395e-01,
  1934. 6.37939986851258411527e-01, 6.38068977499615330728e-01,
  1935. 6.38197951511530692237e-01, 6.38326908891295508042e-01,
  1936. 6.38455849643198680710e-01, 6.38584773771527891562e-01,
  1937. 6.38713681280568712495e-01, 6.38842572174605605184e-01,
  1938. 6.38971446457920699835e-01, 6.39100304134795127453e-01,
  1939. 6.39229145209507909620e-01, 6.39357969686336624626e-01,
  1940. 6.39486777569557185430e-01, 6.39615568863443728631e-01,
  1941. 6.39744343572268947540e-01, 6.39873101700303648087e-01,
  1942. 6.40001843251817081892e-01, 6.40130568231077057284e-01,
  1943. 6.40259276642349384190e-01, 6.40387968489898540270e-01,
  1944. 6.40516643777987004782e-01, 6.40645302510875924717e-01,
  1945. 6.40773944692824781733e-01, 6.40902570328091170104e-01,
  1946. 6.41031179420931240820e-01, 6.41159771975599590554e-01,
  1947. 6.41288347996348928604e-01, 6.41416907487430409951e-01,
  1948. 6.41545450453093524246e-01, 6.41673976897586428869e-01,
  1949. 6.41802486825155171779e-01, 6.41930980240044468665e-01,
  1950. 6.42059457146497258861e-01, 6.42187917548755038410e-01,
  1951. 6.42316361451057304954e-01, 6.42444788857642334889e-01,
  1952. 6.42573199772746628256e-01, 6.42701594200604797713e-01,
  1953. 6.42829972145450234677e-01, 6.42958333611514443184e-01,
  1954. 6.43086678603027261936e-01, 6.43215007124217197365e-01,
  1955. 6.43343319179310868527e-01, 6.43471614772533229143e-01,
  1956. 6.43599893908107678620e-01, 6.43728156590256284098e-01,
  1957. 6.43856402823198892271e-01, 6.43984632611154350634e-01,
  1958. 6.44112845958339397257e-01, 6.44241042868969437940e-01,
  1959. 6.44369223347258102130e-01, 6.44497387397417575983e-01,
  1960. 6.44625535023658158273e-01, 6.44753666230188704489e-01,
  1961. 6.44881781021216515803e-01, 6.45009879400947228056e-01,
  1962. 6.45137961373584700731e-01, 6.45266026943331350019e-01,
  1963. 6.45394076114387926779e-01, 6.45522108890953627558e-01,
  1964. 6.45650125277225872544e-01, 6.45778125277400638637e-01,
  1965. 6.45906108895672126380e-01, 6.46034076136233315069e-01,
  1966. 6.46162027003274963555e-01, 6.46289961500986720466e-01,
  1967. 6.46417879633556458074e-01, 6.46545781405170272294e-01,
  1968. 6.46673666820013037793e-01, 6.46801535882267741862e-01,
  1969. 6.46929388596115706456e-01, 6.47057224965736921263e-01,
  1970. 6.47185044995309599614e-01, 6.47312848689010289505e-01,
  1971. 6.47440636051014095642e-01, 6.47568407085494457398e-01,
  1972. 6.47696161796623148810e-01, 6.47823900188570500625e-01,
  1973. 6.47951622265505067233e-01, 6.48079328031593959736e-01,
  1974. 6.48207017491002623899e-01, 6.48334690647894840154e-01,
  1975. 6.48462347506432945643e-01, 6.48589988070777501150e-01,
  1976. 6.48717612345087624171e-01, 6.48845220333520877887e-01,
  1977. 6.48972812040233049125e-01, 6.49100387469378481420e-01,
  1978. 6.49227946625109852974e-01, 6.49355489511578287676e-01,
  1979. 6.49483016132933244080e-01, 6.49610526493322737451e-01,
  1980. 6.49738020596893228742e-01, 6.49865498447789291525e-01,
  1981. 6.49992960050154167106e-01, 6.50120405408129542479e-01,
  1982. 6.50247834525855328280e-01, 6.50375247407469991856e-01,
  1983. 6.50502644057110446241e-01, 6.50630024478911828112e-01,
  1984. 6.50757388677007941880e-01, 6.50884736655530926619e-01,
  1985. 6.51012068418611256071e-01, 6.51139383970377849664e-01,
  1986. 6.51266683314958072515e-01, 6.51393966456477846450e-01,
  1987. 6.51521233399061316938e-01, 6.51648484146831186159e-01,
  1988. 6.51775718703908490959e-01, 6.51902937074412824892e-01,
  1989. 6.52030139262461894134e-01, 6.52157325272172294639e-01,
  1990. 6.52284495107658734980e-01, 6.52411648773034480442e-01,
  1991. 6.52538786272411130973e-01, 6.52665907609898732211e-01,
  1992. 6.52793012789605997526e-01, 6.52920101815639641885e-01,
  1993. 6.53047174692105159011e-01, 6.53174231423106488315e-01,
  1994. 6.53301272012745681828e-01, 6.53428296465123459313e-01,
  1995. 6.53555304784339097246e-01, 6.53682296974490095742e-01,
  1996. 6.53809273039672400607e-01, 6.53936232983980625377e-01,
  1997. 6.54063176811507496211e-01, 6.54190104526344406999e-01,
  1998. 6.54317016132581086296e-01, 6.54443911634305819369e-01,
  1999. 6.54570791035605337171e-01, 6.54697654340564483277e-01,
  2000. 6.54824501553267102061e-01, 6.54951332677795039494e-01,
  2001. 6.55078147718228809282e-01, 6.55204946678647148772e-01,
  2002. 6.55331729563127685090e-01, 6.55458496375745935936e-01,
  2003. 6.55585247120576197766e-01, 6.55711981801691323746e-01,
  2004. 6.55838700423162279662e-01, 6.55965402989058699035e-01,
  2005. 6.56092089503448661070e-01, 6.56218759970398801684e-01,
  2006. 6.56345414393973758393e-01, 6.56472052778237280535e-01,
  2007. 6.56598675127251008021e-01, 6.56725281445075359521e-01,
  2008. 6.56851871735769199390e-01, 6.56978446003389615626e-01,
  2009. 6.57105004251992363962e-01, 6.57231546485631645815e-01,
  2010. 6.57358072708359997272e-01, 6.57484582924228733170e-01,
  2011. 6.57611077137287058925e-01, 6.57737555351583291774e-01,
  2012. 6.57864017571163861575e-01, 6.57990463800073532852e-01,
  2013. 6.58116894042355848882e-01, 6.58243308302052687608e-01,
  2014. 6.58369706583204372663e-01, 6.58496088889849673365e-01,
  2015. 6.58622455226025915742e-01, 6.58748805595768760490e-01,
  2016. 6.58875140003112647058e-01, 6.59001458452090016493e-01,
  2017. 6.59127760946732199621e-01, 6.59254047491068750908e-01,
  2018. 6.59380318089127781533e-01, 6.59506572744935959385e-01,
  2019. 6.59632811462518287016e-01, 6.59759034245898212667e-01,
  2020. 6.59885241099097852313e-01, 6.60011432026137656592e-01,
  2021. 6.60137607031036632854e-01, 6.60263766117812123113e-01,
  2022. 6.60389909290480248139e-01, 6.60516036553055130298e-01,
  2023. 6.60642147909550003781e-01, 6.60768243363975882332e-01,
  2024. 6.60894322920342891514e-01, 6.61020386582659269514e-01,
  2025. 6.61146434354931700206e-01, 6.61272466241165757239e-01,
  2026. 6.61398482245365015864e-01, 6.61524482371531830083e-01,
  2027. 6.61650466623666999588e-01, 6.61776435005769658737e-01,
  2028. 6.61902387521837720641e-01, 6.62028324175867211032e-01,
  2029. 6.62154244971853045421e-01, 6.62280149913788362959e-01,
  2030. 6.62406039005664859509e-01, 6.62531912251472676623e-01,
  2031. 6.62657769655200512560e-01, 6.62783611220835733313e-01,
  2032. 6.62909436952363706475e-01, 6.63035246853768911457e-01,
  2033. 6.63161040929033829272e-01, 6.63286819182139719686e-01,
  2034. 6.63412581617066288153e-01, 6.63538328237791463771e-01,
  2035. 6.63664059048292176435e-01, 6.63789774052543579685e-01,
  2036. 6.63915473254519050705e-01, 6.64041156658191078499e-01,
  2037. 6.64166824267530264692e-01, 6.64292476086505656596e-01,
  2038. 6.64418112119084969258e-01, 6.64543732369234474433e-01,
  2039. 6.64669336840918778542e-01, 6.64794925538101155738e-01,
  2040. 6.64920498464743214839e-01, 6.65046055624805232398e-01,
  2041. 6.65171597022245819630e-01, 6.65297122661022366508e-01,
  2042. 6.65422632545090486644e-01, 6.65548126678404461387e-01,
  2043. 6.65673605064917017771e-01, 6.65799067708579439540e-01,
  2044. 6.65924514613341678171e-01, 6.66049945783151686740e-01,
  2045. 6.66175361221956641167e-01, 6.66300760933701607946e-01,
  2046. 6.66426144922330543352e-01, 6.66551513191785738321e-01,
  2047. 6.66676865746008262548e-01, 6.66802202588937187322e-01,
  2048. 6.66927523724510695757e-01, 6.67052829156665194610e-01,
  2049. 6.67178118889335536323e-01, 6.67303392926455130052e-01,
  2050. 6.67428651271956163704e-01, 6.67553893929769048832e-01,
  2051. 6.67679120903822864719e-01, 6.67804332198045247360e-01,
  2052. 6.67929527816362167414e-01, 6.68054707762698263274e-01,
  2053. 6.68179872040976619019e-01, 6.68305020655119097484e-01,
  2054. 6.68430153609045785146e-01, 6.68555270906675325193e-01,
  2055. 6.68680372551925139568e-01, 6.68805458548710873856e-01,
  2056. 6.68930528900946952398e-01, 6.69055583612546245220e-01,
  2057. 6.69180622687419957018e-01, 6.69305646129478182260e-01,
  2058. 6.69430653942629239062e-01, 6.69555646130780224290e-01,
  2059. 6.69680622697836569479e-01, 6.69805583647702484917e-01,
  2060. 6.69930528984280293514e-01, 6.70055458711471318978e-01,
  2061. 6.70180372833175219682e-01, 6.70305271353290099690e-01,
  2062. 6.70430154275712841816e-01, 6.70555021604338552521e-01,
  2063. 6.70679873343061228042e-01, 6.70804709495773088257e-01,
  2064. 6.70929530066365131802e-01, 6.71054335058726802998e-01,
  2065. 6.71179124476746102879e-01, 6.71303898324309589185e-01,
  2066. 6.71428656605302376370e-01, 6.71553399323607913551e-01,
  2067. 6.71678126483108539624e-01, 6.71802838087684928148e-01,
  2068. 6.71927534141216420416e-01, 6.72052214647580803408e-01,
  2069. 6.72176879610654420816e-01, 6.72301529034312284061e-01,
  2070. 6.72426162922427739232e-01, 6.72550781278872911173e-01,
  2071. 6.72675384107518370413e-01, 6.72799971412233133172e-01,
  2072. 6.72924543196884994423e-01, 6.73049099465340305848e-01,
  2073. 6.73173640221463642774e-01, 6.73298165469118470305e-01,
  2074. 6.73422675212166699232e-01, 6.73547169454468797056e-01,
  2075. 6.73671648199883787989e-01, 6.73796111452269252950e-01,
  2076. 6.73920559215481329574e-01, 6.74044991493374712199e-01,
  2077. 6.74169408289802651879e-01, 6.74293809608617067397e-01,
  2078. 6.74418195453668323225e-01, 6.74542565828805340544e-01,
  2079. 6.74666920737875597247e-01, 6.74791260184725238958e-01,
  2080. 6.74915584173198968010e-01, 6.75039892707139821404e-01,
  2081. 6.75164185790389836939e-01, 6.75288463426789165034e-01,
  2082. 6.75412725620176734864e-01, 6.75536972374390143337e-01,
  2083. 6.75661203693265322023e-01, 6.75785419580636981252e-01,
  2084. 6.75909620040338388058e-01, 6.76033805076201144146e-01,
  2085. 6.76157974692055740995e-01, 6.76282128891731004749e-01,
  2086. 6.76406267679054540309e-01, 6.76530391057852287240e-01,
  2087. 6.76654499031948852839e-01, 6.76778591605167623158e-01,
  2088. 6.76902668781330207892e-01, 6.77026730564257217537e-01,
  2089. 6.77150776957767375208e-01, 6.77274807965678293797e-01,
  2090. 6.77398823591806142908e-01, 6.77522823839965537829e-01,
  2091. 6.77646808713969761584e-01, 6.77770778217630653906e-01,
  2092. 6.77894732354758722259e-01, 6.78018671129162808775e-01,
  2093. 6.78142594544650756383e-01, 6.78266502605028631656e-01,
  2094. 6.78390395314101168900e-01, 6.78514272675671770152e-01,
  2095. 6.78638134693542394160e-01, 6.78761981371513556383e-01,
  2096. 6.78885812713384440009e-01, 6.79009628722952562896e-01,
  2097. 6.79133429404014443698e-01, 6.79257214760364935735e-01,
  2098. 6.79380984795797338016e-01, 6.79504739514103950349e-01,
  2099. 6.79628478919075296183e-01, 6.79752203014500677725e-01,
  2100. 6.79875911804167953889e-01, 6.79999605291863540302e-01,
  2101. 6.80123283481372520320e-01, 6.80246946376478422991e-01,
  2102. 6.80370593980963667136e-01, 6.80494226298608895220e-01,
  2103. 6.80617843333193639488e-01, 6.80741445088495988891e-01,
  2104. 6.80865031568292367048e-01, 6.80988602776358198376e-01,
  2105. 6.81112158716467130937e-01, 6.81235699392391813589e-01,
  2106. 6.81359224807903118837e-01, 6.81482734966770586915e-01,
  2107. 6.81606229872762758859e-01, 6.81729709529646177302e-01,
  2108. 6.81853173941186385676e-01, 6.81976623111147484124e-01,
  2109. 6.82100057043292129499e-01, 6.82223475741381535364e-01,
  2110. 6.82346879209175583014e-01, 6.82470267450432710454e-01,
  2111. 6.82593640468910134445e-01, 6.82716998268363406410e-01,
  2112. 6.82840340852546967554e-01, 6.82963668225213593743e-01,
  2113. 6.83086980390114839601e-01, 6.83210277351001038504e-01,
  2114. 6.83333559111620636450e-01, 6.83456825675721302282e-01,
  2115. 6.83580077047048817462e-01, 6.83703313229347853230e-01,
  2116. 6.83826534226361637536e-01, 6.83949740041831955040e-01,
  2117. 6.84072930679499369155e-01, 6.84196106143102777963e-01,
  2118. 6.84319266436379969321e-01, 6.84442411563067176772e-01,
  2119. 6.84565541526899412617e-01, 6.84688656331610134842e-01,
  2120. 6.84811755980931580190e-01, 6.84934840478594542112e-01,
  2121. 6.85057909828328370772e-01, 6.85180964033861084062e-01,
  2122. 6.85304003098919367609e-01, 6.85427027027228574774e-01,
  2123. 6.85550035822512615624e-01, 6.85673029488493845918e-01,
  2124. 6.85796008028893511188e-01, 6.85918971447431524702e-01,
  2125. 6.86041919747826134390e-01, 6.86164852933794477963e-01,
  2126. 6.86287771009052138815e-01, 6.86410673977313590122e-01,
  2127. 6.86533561842291528698e-01, 6.86656434607697763184e-01,
  2128. 6.86779292277242214837e-01, 6.86902134854634027761e-01,
  2129. 6.87024962343580458679e-01, 6.87147774747787654093e-01,
  2130. 6.87270572070960317212e-01, 6.87393354316801818982e-01,
  2131. 6.87516121489014198076e-01, 6.87638873591298049881e-01,
  2132. 6.87761610627352748537e-01, 6.87884332600876113872e-01,
  2133. 6.88007039515564633447e-01, 6.88129731375113684599e-01,
  2134. 6.88252408183216979332e-01, 6.88375069943567119424e-01,
  2135. 6.88497716659855041321e-01, 6.88620348335770571246e-01,
  2136. 6.88742964975002092132e-01, 6.88865566581236654642e-01,
  2137. 6.88988153158160088196e-01, 6.89110724709456445858e-01,
  2138. 6.89233281238809003533e-01, 6.89355822749899149748e-01,
  2139. 6.89478349246407273831e-01, 6.89600860732012321819e-01,
  2140. 6.89723357210391685435e-01, 6.89845838685221757203e-01,
  2141. 6.89968305160177375335e-01, 6.90090756638931934752e-01,
  2142. 6.90213193125157720154e-01, 6.90335614622525572948e-01,
  2143. 6.90458021134704891253e-01, 6.90580412665363740921e-01,
  2144. 6.90702789218168966556e-01, 6.90825150796785969476e-01,
  2145. 6.90947497404878929750e-01, 6.91069829046110473136e-01,
  2146. 6.91192145724142004148e-01, 6.91314447442633595031e-01,
  2147. 6.91436734205243874740e-01, 6.91559006015630362008e-01,
  2148. 6.91681262877449021254e-01, 6.91803504794354484631e-01,
  2149. 6.91925731770000163046e-01, 6.92047943808038024116e-01,
  2150. 6.92170140912118703191e-01, 6.92292323085891614376e-01,
  2151. 6.92414490333004617462e-01, 6.92536642657104462018e-01,
  2152. 6.92658780061836454323e-01, 6.92780902550844568388e-01,
  2153. 6.92903010127771445958e-01, 6.93025102796258285487e-01,
  2154. 6.93147180559945286227e-01
  2155. };
  2156. static const double fm_log_q2[] = {
  2157. -9.99999970204339394542e-01, -9.99511867731007974669e-01,
  2158. -9.99024122545299819720e-01, -9.98536734292937211421e-01,
  2159. -9.98049702617656908643e-01, -9.97563027181486594586e-01,
  2160. -9.97076707618930857535e-01, -9.96590743612639662352e-01,
  2161. -9.96105134789343704682e-01, -9.95619880820340474870e-01,
  2162. -9.95134981341887603357e-01, -9.94650436042181285146e-01,
  2163. -9.94166244524016029516e-01, -9.93682406505230209071e-01,
  2164. -9.93198921590821237615e-01, -9.92715789460176134540e-01,
  2165. -9.92233009782583330605e-01, -9.91750582106026845608e-01,
  2166. -9.91268506386495218408e-01, -9.90786781855067077984e-01,
  2167. -9.90305408488223459784e-01, -9.89824385926602934305e-01,
  2168. -9.89343713535692392824e-01, -9.88863391418940196331e-01,
  2169. -9.88383418923948875445e-01, -9.87903795762894443300e-01,
  2170. -9.87424521643993191589e-01, -9.86945596275973890954e-01,
  2171. -9.86467019194852801078e-01, -9.85988790103114798313e-01,
  2172. -9.85510908733950863336e-01, -9.85033374705881481503e-01,
  2173. -9.84556187716159159073e-01, -9.84079347261778369926e-01,
  2174. -9.83602853387407938257e-01, -9.83126705195018768535e-01,
  2175. -9.82650902914219859241e-01, -9.82175445826114934533e-01,
  2176. -9.81700333782709821939e-01, -9.81225566348648436943e-01,
  2177. -9.80751143317876161731e-01, -9.80277064203733838887e-01,
  2178. -9.79803328714193400018e-01, -9.79329936757795227464e-01,
  2179. -9.78856887595422442416e-01, -9.78384181131788044361e-01,
  2180. -9.77911817090174495526e-01, -9.77439794926507898865e-01,
  2181. -9.76968114649079621969e-01, -9.76496775371813452438e-01,
  2182. -9.76025777487512291586e-01, -9.75555119961791561423e-01,
  2183. -9.75084803046927794945e-01, -9.74614826069708173328e-01,
  2184. -9.74145188676739381961e-01, -9.73675890859331483185e-01,
  2185. -9.73206931957900756025e-01, -9.72738311825502188768e-01,
  2186. -9.72270029963272386375e-01, -9.71802086418131150225e-01,
  2187. -9.71334480453526993848e-01, -9.70867211825531484237e-01,
  2188. -9.70400280500180012488e-01, -9.69933685809522216914e-01,
  2189. -9.69467427665356984434e-01, -9.69001505342206970184e-01,
  2190. -9.68535919385462573672e-01, -9.68070668339039097638e-01,
  2191. -9.67605752941687047297e-01, -9.67141171694490986432e-01,
  2192. -9.66676925663408237455e-01, -9.66213013480509586017e-01,
  2193. -9.65749435360603869505e-01, -9.65286190415398870357e-01,
  2194. -9.64823279189289229052e-01, -9.64360700392987491014e-01,
  2195. -9.63898454448297248298e-01, -9.63436540957292031351e-01,
  2196. -9.62974958994398444467e-01, -9.62513709167376330100e-01,
  2197. -9.62052789970760380278e-01, -9.61592202627699954576e-01,
  2198. -9.61131945148046229477e-01, -9.60672018681310024846e-01,
  2199. -9.60212422016580413597e-01, -9.59753154657040807862e-01,
  2200. -9.59294217705390250828e-01, -9.58835608644634573849e-01,
  2201. -9.58377329455130544389e-01, -9.57919378224905693209e-01,
  2202. -9.57461755033558459260e-01, -9.57004460077683027919e-01,
  2203. -9.56547492491304551798e-01, -9.56090852049268358215e-01,
  2204. -9.55634538422690971160e-01, -9.55178551755278659741e-01,
  2205. -9.54722891102598336666e-01, -9.54267556606214206738e-01,
  2206. -9.53812547247320785537e-01, -9.53357864165607526985e-01,
  2207. -9.52903505218105184582e-01, -9.52449471550573356637e-01,
  2208. -9.51995762119929311851e-01, -9.51542377158775654067e-01,
  2209. -9.51089315382799949106e-01, -9.50636577505697299983e-01,
  2210. -9.50184162655493436134e-01, -9.49732070812421613759e-01,
  2211. -9.49280301530538883625e-01, -9.48828854517908548694e-01,
  2212. -9.48377729292745219603e-01, -9.47926925978650358751e-01,
  2213. -9.47476443864510908810e-01, -9.47026282877210912048e-01,
  2214. -9.46576442623344060934e-01, -9.46126922654174640215e-01,
  2215. -9.45677723062576136570e-01, -9.45228843227299053709e-01,
  2216. -9.44780282746499722180e-01, -9.44332041753326523192e-01,
  2217. -9.43884119418537004265e-01, -9.43436516131986646627e-01,
  2218. -9.42989230465001604387e-01, -9.42542263551472636607e-01,
  2219. -9.42095613681492860536e-01, -9.41649281671355309342e-01,
  2220. -9.41203266664289106558e-01, -9.40757568477113448324e-01,
  2221. -9.40312186603849187172e-01, -9.39867121156116924752e-01,
  2222. -9.39422371494921693014e-01, -9.38977937969146747577e-01,
  2223. -9.38533818425270727204e-01, -9.38090015540559929441e-01,
  2224. -9.37646526347406972235e-01, -9.37203351657070138359e-01,
  2225. -9.36760491192124566950e-01, -9.36317945251011529706e-01,
  2226. -9.35875711520406383670e-01, -9.35433791970248562642e-01,
  2227. -9.34992185225055116859e-01, -9.34550890625867491934e-01,
  2228. -9.34109909390034354182e-01, -9.33669238704104120785e-01,
  2229. -9.33228881619615147081e-01, -9.32788834331801042232e-01,
  2230. -9.32349099229301314651e-01, -9.31909674753276684456e-01,
  2231. -9.31470560559493843122e-01, -9.31031756789755693404e-01,
  2232. -9.30593263221085265080e-01, -9.30155079206603119246e-01,
  2233. -9.29717204762836368914e-01, -9.29279639073573582309e-01,
  2234. -9.28842382593162874116e-01, -9.28405434320425215766e-01,
  2235. -9.27968795011759772784e-01, -9.27532462642750910042e-01,
  2236. -9.27096438966723779274e-01, -9.26660721788762020701e-01,
  2237. -9.26225312547271695252e-01, -9.25790209080529336028e-01,
  2238. -9.25355413009083083153e-01, -9.24920922806437006969e-01,
  2239. -9.24486738767070992395e-01, -9.24052859842579898952e-01,
  2240. -9.23619287138135014459e-01, -9.23186018678442410490e-01,
  2241. -9.22753055671568844787e-01, -9.22320396657525742867e-01,
  2242. -9.21888042077250058348e-01, -9.21455991626982218179e-01,
  2243. -9.21024244683838921866e-01, -9.20592801249144221387e-01,
  2244. -9.20161660543504122955e-01, -9.19730822889199606252e-01,
  2245. -9.19300287776504854165e-01, -9.18870054128069879695e-01,
  2246. -9.18440123969056387843e-01, -9.18010494467117244000e-01,
  2247. -9.17581166544576887212e-01, -9.17152139344484806927e-01,
  2248. -9.16723413975333523140e-01, -9.16294988257087883454e-01,
  2249. -9.15866862816476667852e-01, -9.15439037326621463109e-01,
  2250. -9.15011512468304366585e-01, -9.14584285845278177618e-01,
  2251. -9.14157359376828626552e-01, -9.13730730576027161405e-01,
  2252. -9.13304401883368921489e-01, -9.12878370214750711753e-01,
  2253. -9.12452637084189110972e-01, -9.12027202313689278057e-01,
  2254. -9.11602063704228360308e-01, -9.11177223244973188976e-01,
  2255. -9.10752679369231765705e-01, -9.10328432163654999165e-01,
  2256. -9.09904481451345503729e-01, -9.09480826456257163137e-01,
  2257. -9.09057467665507212828e-01, -9.08634403906669829709e-01,
  2258. -9.08211636588364790157e-01, -9.07789162645522784700e-01,
  2259. -9.07366984547896548996e-01, -9.06945101069483228251e-01,
  2260. -9.06523510453585923408e-01, -9.06102215365062191310e-01,
  2261. -9.05681212489113374176e-01, -9.05260504038174707020e-01,
  2262. -9.04840087271269188918e-01, -9.04419965351935140063e-01,
  2263. -9.04000133954933060565e-01, -9.03580596041809180896e-01,
  2264. -9.03161349679556746395e-01, -9.02742395447701850841e-01,
  2265. -9.02323731564164344121e-01, -9.01905360386788146343e-01,
  2266. -9.01487278457227647621e-01, -9.01069488869118639940e-01,
  2267. -9.00651988294198790896e-01, -9.00234778569980020890e-01,
  2268. -8.99817858468642706171e-01, -8.99401228269987029762e-01,
  2269. -8.98984886685647799354e-01, -8.98568834398333571301e-01,
  2270. -8.98153071362558952373e-01, -8.97737595680574984591e-01,
  2271. -8.97322409400924114742e-01, -8.96907510418140430097e-01,
  2272. -8.96492899517607799709e-01, -8.96078575663256993167e-01,
  2273. -8.95664539420013672277e-01, -8.95250789564243198981e-01,
  2274. -8.94837326234608987363e-01, -8.94424150100090686877e-01,
  2275. -8.94011259743090591634e-01, -8.93598654577083761907e-01,
  2276. -8.93186335571800604782e-01, -8.92774302228811822424e-01,
  2277. -8.92362552778136142173e-01, -8.91951089210193392987e-01,
  2278. -8.91539909524236673377e-01, -8.91129014144898534688e-01,
  2279. -8.90718403374395006900e-01, -8.90308075579229751817e-01,
  2280. -8.89898031403237421699e-01, -8.89488271301558164339e-01,
  2281. -8.89078792809798290619e-01, -8.88669598345472655510e-01,
  2282. -8.88260684893865892775e-01, -8.87852055111406412991e-01,
  2283. -8.87443705578046637683e-01, -8.87035638935646852943e-01,
  2284. -8.86627853624748274441e-01, -8.86220349050373723543e-01,
  2285. -8.85813124960938669261e-01, -8.85406182957758969287e-01,
  2286. -8.84999519681124224846e-01, -8.84593137189672695797e-01,
  2287. -8.84187034799512772132e-01, -8.83781211790588994148e-01,
  2288. -8.83375667536064224095e-01, -8.82970403866355613154e-01,
  2289. -8.82565416880603970107e-01, -8.82160710572937767360e-01,
  2290. -8.81756281249608142581e-01, -8.81352129912593151850e-01,
  2291. -8.80948257644714738390e-01, -8.80544661906674352991e-01,
  2292. -8.80141343390940522617e-01, -8.79738301866938576801e-01,
  2293. -8.79335537564497671248e-01, -8.78933049794877185867e-01,
  2294. -8.78530838289241611250e-01, -8.78128902017706214345e-01,
  2295. -8.77727242574676602693e-01, -8.77325857406385578585e-01,
  2296. -8.76924749545558213093e-01, -8.76523915002998088575e-01,
  2297. -8.76123355526894909140e-01, -8.75723070907653888817e-01,
  2298. -8.75323060235463579204e-01, -8.74923324565198612390e-01,
  2299. -8.74523860587170576153e-01, -8.74124672103355093711e-01,
  2300. -8.73725755597443032308e-01, -8.73327112950790240831e-01,
  2301. -8.72928742948249847267e-01, -8.72530645775088542493e-01,
  2302. -8.72132819111415824587e-01, -8.71735266463592339825e-01,
  2303. -8.71337984507970064740e-01, -8.70940974650877608454e-01,
  2304. -8.70544234590646004435e-01, -8.70147769333657672419e-01,
  2305. -8.69751569537952962108e-01, -8.69355645213247596459e-01,
  2306. -8.68959988014379680621e-01, -8.68564601754506560027e-01,
  2307. -8.68169485114097416734e-01, -8.67774639558116844817e-01,
  2308. -8.67380060546237952046e-01, -8.66985753598933484021e-01,
  2309. -8.66591712350508802665e-01, -8.66197942773432094654e-01,
  2310. -8.65804438519395369589e-01, -8.65411205039324338273e-01,
  2311. -8.65018238053694155099e-01, -8.64625538053809039596e-01,
  2312. -8.64233107353976737208e-01, -8.63840941793596828191e-01,
  2313. -8.63449044524892350694e-01, -8.63057412687507463644e-01,
  2314. -8.62666048982706823445e-01, -8.62274948259755036339e-01,
  2315. -8.61884117244458014540e-01, -8.61493548154168120590e-01,
  2316. -8.61103248629860429375e-01, -8.60713209860124339734e-01,
  2317. -8.60323439891849783834e-01, -8.59933932112696530758e-01,
  2318. -8.59544690955295176416e-01, -8.59155710889400126007e-01,
  2319. -8.58766998427491934365e-01, -8.58378547019733151302e-01,
  2320. -8.57990359589185458411e-01, -8.57602436581375471292e-01,
  2321. -8.57214776085103435932e-01, -8.56827376917738359197e-01,
  2322. -8.56440242927035244591e-01, -8.56053368286509908103e-01,
  2323. -8.55666758484504463844e-01, -8.55280408570004979651e-01,
  2324. -8.54894321682854507749e-01, -8.54508495802631440341e-01,
  2325. -8.54122930283242931537e-01, -8.53737626935513915782e-01,
  2326. -8.53352581956205002989e-01, -8.52967800365546313657e-01,
  2327. -8.52583277061727651258e-01, -8.52199013461921284218e-01,
  2328. -8.51815011793214615921e-01, -8.51431267318022655388e-01,
  2329. -8.51047782789758122668e-01, -8.50664557520292130555e-01,
  2330. -8.50281591508726952711e-01, -8.49898882652814657845e-01,
  2331. -8.49516433774509360788e-01, -8.49134241276175760760e-01,
  2332. -8.48752308344500772108e-01, -8.48370631418307152849e-01,
  2333. -8.47989213173712008675e-01, -8.47608052055359939558e-01,
  2334. -8.47227146020622434719e-01, -8.46846499207430714051e-01,
  2335. -8.46466108282560192322e-01, -8.46085971265107983363e-01,
  2336. -8.45706093823972659962e-01, -8.45326469234303878864e-01,
  2337. -8.44947101962797320063e-01, -8.44567989249422446107e-01,
  2338. -8.44189132079671167297e-01, -8.43810529271607157042e-01,
  2339. -8.43432181773515310397e-01, -8.43054086974192373738e-01,
  2340. -8.42676248782231018808e-01, -8.42298662556367427889e-01,
  2341. -8.41921331777192527568e-01, -8.41544252751542209978e-01,
  2342. -8.41167428389579807657e-01, -8.40790856331749880681e-01,
  2343. -8.40414537518176185671e-01, -8.40038470547919358111e-01,
  2344. -8.39662657290645486619e-01, -8.39287094462596861000e-01,
  2345. -8.38911784947234617782e-01, -8.38536726082408478966e-01,
  2346. -8.38161920045321418016e-01, -8.37787363583282096435e-01,
  2347. -8.37413059147947502758e-01, -8.37039005773316913128e-01,
  2348. -8.36665202077768510591e-01, -8.36291648965855838327e-01,
  2349. -8.35918346994952599083e-01, -8.35545293031011770957e-01,
  2350. -8.35172490670944567270e-01, -8.34799937043055217956e-01,
  2351. -8.34427631655312529446e-01, -8.34055576553571542675e-01,
  2352. -8.33683769634376070634e-01, -8.33312211677761704998e-01,
  2353. -8.32940901667041044831e-01, -8.32569840094962154708e-01,
  2354. -8.32199026007219733181e-01, -8.31828459934317754332e-01,
  2355. -8.31458140708547288611e-01, -8.31088069676270801978e-01,
  2356. -8.30718245413716971370e-01, -8.30348666681671510048e-01,
  2357. -8.29979337066795830324e-01, -8.29610251843562407359e-01,
  2358. -8.29241412357579754655e-01, -8.28872820745909844042e-01,
  2359. -8.28504472702632721592e-01, -8.28136372138494003536e-01,
  2360. -8.27768516098335127573e-01, -8.27400904110141666159e-01,
  2361. -8.27033538223160613612e-01, -8.26666416300355200164e-01,
  2362. -8.26299539252689507762e-01, -8.25932905573345754746e-01,
  2363. -8.25566517584661041518e-01, -8.25200370298072694020e-01,
  2364. -8.24834470169624522917e-01, -8.24468810333541246571e-01,
  2365. -8.24103395033075170062e-01, -8.23738222542895748290e-01,
  2366. -8.23373292727103800459e-01, -8.23008605060659648167e-01,
  2367. -8.22644158985652573790e-01, -8.22279957258766014405e-01,
  2368. -8.21915994999112275998e-01, -8.21552275003720078317e-01,
  2369. -8.21188796553297462033e-01, -8.20825559727983877778e-01,
  2370. -8.20462562132544981353e-01, -8.20099807679844250430e-01,
  2371. -8.19737291495564845967e-01, -8.19375017988239751077e-01,
  2372. -8.19012982779956599799e-01, -8.18651187797961865655e-01,
  2373. -8.18289632505148967212e-01, -8.17928317122697978725e-01,
  2374. -8.17567241302996294827e-01, -8.17206403421344873550e-01,
  2375. -8.16845804736217262487e-01, -8.16485444632387147301e-01,
  2376. -8.16125324312285349571e-01, -8.15765439581415341408e-01,
  2377. -8.15405794839461406376e-01, -8.15046387858052834297e-01,
  2378. -8.14687217563053955871e-01, -8.14328284891442821802e-01,
  2379. -8.13969589963410289357e-01, -8.13611131361214212632e-01,
  2380. -8.13252909047697203349e-01, -8.12894924589232403811e-01,
  2381. -8.12537174551450025461e-01, -8.12179662723554018910e-01,
  2382. -8.11822385765001985902e-01, -8.11465344866855842199e-01,
  2383. -8.11108538605410545053e-01, -8.10751968690456070732e-01,
  2384. -8.10395632500506502005e-01, -8.10039533223778640547e-01,
  2385. -8.09683666316827421738e-01, -8.09328035589345851086e-01,
  2386. -8.08972638727908588407e-01, -8.08617475588590539637e-01,
  2387. -8.08262546266548476126e-01, -8.07907850525080184489e-01,
  2388. -8.07553389215838191006e-01, -8.07199159168914714968e-01,
  2389. -8.06845163830385736503e-01, -8.06491400967756844054e-01,
  2390. -8.06137870476995033187e-01, -8.05784572212759564458e-01,
  2391. -8.05431506860445400875e-01, -8.05078671823814207009e-01,
  2392. -8.04726071214487803651e-01, -8.04373699564121635852e-01,
  2393. -8.04021560664633705429e-01, -8.03669653198598288313e-01,
  2394. -8.03317975849833776358e-01, -8.02966529612556545459e-01,
  2395. -8.02615314620049424832e-01, -8.02264329344965387847e-01,
  2396. -8.01913574175475818429e-01, -8.01563049086241208308e-01,
  2397. -8.01212753790446652324e-01, -8.00862689460692500631e-01,
  2398. -8.00512851693393034935e-01, -8.00163245754418328559e-01,
  2399. -7.99813866159745590068e-01, -7.99464718403725238538e-01,
  2400. -7.99115797168848507326e-01, -7.98767104260962645945e-01,
  2401. -7.98418640568153703541e-01, -7.98070403526198957067e-01,
  2402. -7.97722396915967246755e-01, -7.97374613766141382420e-01,
  2403. -7.97027061417315940695e-01, -7.96679734242235038089e-01,
  2404. -7.96332636233457291652e-01, -7.95985762635938898235e-01,
  2405. -7.95639117301425558004e-01, -7.95292697959882555203e-01,
  2406. -7.94946504251766716820e-01, -7.94600537091318392946e-01,
  2407. -7.94254795975086080873e-01, -7.93909279208667828520e-01,
  2408. -7.93563988485189275579e-01, -7.93218924314483708748e-01,
  2409. -7.92874082964091897452e-01, -7.92529467678147581111e-01,
  2410. -7.92185077594477093932e-01, -7.91840910123675190135e-01,
  2411. -7.91496968103633014024e-01, -7.91153251154092851394e-01,
  2412. -7.90809755164228800339e-01, -7.90466485781729399918e-01,
  2413. -7.90123438496507235485e-01, -7.89780614525349644595e-01,
  2414. -7.89438013511196468031e-01, -7.89095635665502115330e-01,
  2415. -7.88753480499506887114e-01, -7.88411546962827891605e-01,
  2416. -7.88069836951789781665e-01, -7.87728349519411286117e-01,
  2417. -7.87387080969357722182e-01, -7.87046038652046253681e-01,
  2418. -7.86705213625948918121e-01, -7.86364611955018277811e-01,
  2419. -7.86024232294810998312e-01, -7.85684071165180464291e-01,
  2420. -7.85344132655284687949e-01, -7.85004415064510130406e-01,
  2421. -7.84664915518216821155e-01, -7.84325638833675120587e-01,
  2422. -7.83986579792315119164e-01, -7.83647743275274089036e-01,
  2423. -7.83309123358476799837e-01, -7.82970724887247948587e-01,
  2424. -7.82632545580235650107e-01, -7.82294584129585413024e-01,
  2425. -7.81956842460133971784e-01, -7.81619319768323217446e-01,
  2426. -7.81282014549579795215e-01, -7.80944928037821894939e-01,
  2427. -7.80608059595917502804e-01, -7.80271410538476040131e-01,
  2428. -7.79934976244191724426e-01, -7.79598762707806702821e-01,
  2429. -7.79262764541498231807e-01, -7.78926983331975741898e-01,
  2430. -7.78591420914192311464e-01, -7.78256073949561311132e-01,
  2431. -7.77920942781604729532e-01, -7.77586029374822684801e-01,
  2432. -7.77251331115626831192e-01, -7.76916850905936318128e-01,
  2433. -7.76582585339597120111e-01, -7.76248533963435183303e-01,
  2434. -7.75914701996302635933e-01, -7.75581080191833582838e-01,
  2435. -7.75247677964898906922e-01, -7.74914489254122762496e-01,
  2436. -7.74581512126330751222e-01, -7.74248754787661197518e-01,
  2437. -7.73916208698477214867e-01, -7.73583877459445679037e-01,
  2438. -7.73251760795472087295e-01, -7.72919856206266908671e-01,
  2439. -7.72588168380147766179e-01, -7.72256692240005038208e-01,
  2440. -7.71925426642152245904e-01, -7.71594381238445370386e-01,
  2441. -7.71263540916888867827e-01, -7.70932917358060021407e-01,
  2442. -7.70602506891323590921e-01, -7.70272306930707917338e-01,
  2443. -7.69942320314862649333e-01, -7.69612543863097631203e-01,
  2444. -7.69282981871587834277e-01, -7.68953631512193758191e-01,
  2445. -7.68624488625428980981e-01, -7.68295561501506463209e-01,
  2446. -7.67966843490803574568e-01, -7.67638336137790866509e-01,
  2447. -7.67310039914208652512e-01, -7.66981956976561352057e-01,
  2448. -7.66654078227090418629e-01, -7.66326415548583939064e-01,
  2449. -7.65998958447325462018e-01, -7.65671714663651137300e-01,
  2450. -7.65344680493737494764e-01, -7.65017851836673590249e-01,
  2451. -7.64691237624055331068e-01, -7.64364828582150601655e-01,
  2452. -7.64038630522551276414e-01, -7.63712640648493090723e-01,
  2453. -7.63386858747504670752e-01, -7.63061288466236553596e-01,
  2454. -7.62735921018492635248e-01, -7.62410765550665892043e-01,
  2455. -7.62085816615121647288e-01, -7.61761075680135402166e-01,
  2456. -7.61436542320239606596e-01, -7.61112216769028959718e-01,
  2457. -7.60788098517591659942e-01, -7.60464183780045210881e-01,
  2458. -7.60140482620896840160e-01, -7.59816980919740148082e-01,
  2459. -7.59493691566082151923e-01, -7.59170605061977532557e-01,
  2460. -7.58847724157959091507e-01, -7.58525052937777277684e-01,
  2461. -7.58202583491767168056e-01, -7.57880321023096881206e-01,
  2462. -7.57558263804628873039e-01, -7.57236413541746422595e-01,
  2463. -7.56914765140053291681e-01, -7.56593326095880147619e-01,
  2464. -7.56272088282107901591e-01, -7.55951054359139007488e-01,
  2465. -7.55630227400418519323e-01, -7.55309603627635328671e-01,
  2466. -7.54989183904718030860e-01, -7.54668968554262464821e-01,
  2467. -7.54348955421957012568e-01, -7.54029147214517081466e-01,
  2468. -7.53709540847328773872e-01, -7.53390140364195159961e-01,
  2469. -7.53070938262454747658e-01, -7.52751943745142870767e-01,
  2470. -7.52433149854522587141e-01, -7.52114558454699100309e-01,
  2471. -7.51796169046989537499e-01, -7.51477981762019409118e-01,
  2472. -7.51159996575969213239e-01, -7.50842213453493112496e-01,
  2473. -7.50524632559792070907e-01, -7.50207253269409068963e-01,
  2474. -7.49890072331035217879e-01, -7.49573097787428865857e-01,
  2475. -7.49256317482670186614e-01, -7.48939744058004119864e-01,
  2476. -7.48623367044046972296e-01, -7.48307193325348007917e-01,
  2477. -7.47991217008963427126e-01, -7.47675443606249379158e-01,
  2478. -7.47359868140595740016e-01, -7.47044493831215072888e-01,
  2479. -7.46729318365803806934e-01, -7.46414342186427659520e-01,
  2480. -7.46099565837127109980e-01, -7.45784986699675633837e-01,
  2481. -7.45470609115002180722e-01, -7.45156429513488927086e-01,
  2482. -7.44842446656806989047e-01, -7.44528663479954389004e-01,
  2483. -7.44215080657139260722e-01, -7.43901692556530491629e-01,
  2484. -7.43588504267438610285e-01, -7.43275512240322511204e-01,
  2485. -7.42962719996102194386e-01, -7.42650122588572991766e-01,
  2486. -7.42337725105762458178e-01, -7.42025523317636936937e-01,
  2487. -7.41713517880432493534e-01, -7.41401710399238300653e-01,
  2488. -7.41090099385395939535e-01, -7.40778683600515686081e-01,
  2489. -7.40467463898880073891e-01, -7.40156443689682697062e-01,
  2490. -7.39845614069802537394e-01, -7.39534984890788393841e-01,
  2491. -7.39224548001308101597e-01, -7.38914309391334400701e-01,
  2492. -7.38604264428180834479e-01, -7.38294414476748039888e-01,
  2493. -7.37984758710120813952e-01, -7.37675299071058887534e-01,
  2494. -7.37366034203374987044e-01, -7.37056962001121251937e-01,
  2495. -7.36748086656342393574e-01, -7.36439404682677878355e-01,
  2496. -7.36130914657654233935e-01, -7.35822620169590324579e-01,
  2497. -7.35514519463555171974e-01, -7.35206610383018932531e-01,
  2498. -7.34898897721095401003e-01, -7.34591375637730692461e-01,
  2499. -7.34284045936220541861e-01, -7.33976912831370453816e-01,
  2500. -7.33669968836534902579e-01, -7.33363217331747141436e-01,
  2501. -7.33056663459391577575e-01, -7.32750294445768779461e-01,
  2502. -7.32444122715677270463e-01, -7.32138139283301514482e-01,
  2503. -7.31832350903298456402e-01, -7.31526750718727192258e-01,
  2504. -7.31221342638886384613e-01, -7.30916129059394292788e-01,
  2505. -7.30611102076414442585e-01, -7.30306268557933346841e-01,
  2506. -7.30001625699647327394e-01, -7.29697172262848026136e-01,
  2507. -7.29392910418738549261e-01, -7.29088838309150055750e-01,
  2508. -7.28784955607618689655e-01, -7.28481265478169826011e-01,
  2509. -7.28177761179099825029e-01, -7.27874449749392971043e-01,
  2510. -7.27571326538621221403e-01, -7.27268391933642233127e-01,
  2511. -7.26965649037452310566e-01, -7.26663090639144915173e-01,
  2512. -7.26360725715543331660e-01, -7.26058547922002528452e-01,
  2513. -7.25756556896473670193e-01, -7.25454754843860794011e-01,
  2514. -7.25153144482468259291e-01, -7.24851718322109705994e-01,
  2515. -7.24550481253484202071e-01, -7.24249432379852731145e-01,
  2516. -7.23948570397473178950e-01, -7.23647895830116794080e-01,
  2517. -7.23347407886440363356e-01, -7.23047109208045823969e-01,
  2518. -7.22746995607804532114e-01, -7.22447070016758230437e-01,
  2519. -7.22147330485803817801e-01, -7.21847776292375953311e-01,
  2520. -7.21548412275839101682e-01, -7.21249230977172972601e-01,
  2521. -7.20950235041350917520e-01, -7.20651426935435934773e-01,
  2522. -7.20352805322073797001e-01, -7.20054367495683189659e-01,
  2523. -7.19756114440071592675e-01, -7.19458050513526736758e-01,
  2524. -7.19160168474960670437e-01, -7.18862470578696011181e-01,
  2525. -7.18564960636466132371e-01, -7.18267632322884708174e-01,
  2526. -7.17970490363957880575e-01, -7.17673533356917969783e-01,
  2527. -7.17376756598895437556e-01, -7.17080169128263444911e-01,
  2528. -7.16783761846141453944e-01, -7.16487539757937441642e-01,
  2529. -7.16191503116768934945e-01, -7.15895645904759847511e-01,
  2530. -7.15599975176490210593e-01, -7.15304485495321218380e-01,
  2531. -7.15009180377358166680e-01, -7.14714056782754569852e-01,
  2532. -7.14419117766853850604e-01, -7.14124359736066027793e-01,
  2533. -7.13829782833535930742e-01, -7.13535390080274445346e-01,
  2534. -7.13241180424964205109e-01, -7.12947149463927454249e-01,
  2535. -7.12653304687322797228e-01, -7.12359637301999693015e-01,
  2536. -7.12066152638659022323e-01, -7.11772849343519586895e-01,
  2537. -7.11479727501005188017e-01, -7.11186788127201818810e-01,
  2538. -7.10894027073341483458e-01, -7.10601448742539276715e-01,
  2539. -7.10309050846974154858e-01, -7.10016832546879306243e-01,
  2540. -7.09724793901207129387e-01, -7.09432935513915619019e-01,
  2541. -7.09141260498156178471e-01, -7.08849761385299537153e-01,
  2542. -7.08558442584971137634e-01, -7.08267305103167377212e-01,
  2543. -7.07976346094213448978e-01, -7.07685564758942065033e-01,
  2544. -7.07394967139696184688e-01, -7.07104541042143486251e-01,
  2545. -7.06814301261591060310e-01, -7.06524234338757661789e-01,
  2546. -7.06234351375782054561e-01, -7.05944643775133773289e-01,
  2547. -7.05655112473053125477e-01, -7.05365762322110345650e-01,
  2548. -7.05076589739588643901e-01, -7.04787593027915937327e-01,
  2549. -7.04498776972161788734e-01, -7.04210135305489814961e-01,
  2550. -7.03921671546370086858e-01, -7.03633389063629932636e-01,
  2551. -7.03345276451424861186e-01, -7.03057348024629158445e-01,
  2552. -7.02769591457201636686e-01, -7.02482013798756299572e-01,
  2553. -7.02194610352749770676e-01, -7.01907387267804994124e-01,
  2554. -7.01620335821844576252e-01, -7.01333462402813800907e-01,
  2555. -7.01046766944815602507e-01, -7.00760243323492182377e-01,
  2556. -7.00473899338366345901e-01, -7.00187726679509570005e-01,
  2557. -6.99901734023308352839e-01, -6.99615911737950901816e-01,
  2558. -6.99330267322555876319e-01, -6.99044797176266552441e-01,
  2559. -6.98759502615456606911e-01, -6.98474381975487834673e-01,
  2560. -6.98189435010603598464e-01, -6.97904664368468763413e-01,
  2561. -6.97620065292115398847e-01, -6.97335642985881021261e-01,
  2562. -6.97051392565252503353e-01, -6.96767317188075163692e-01,
  2563. -6.96483414695416080953e-01, -6.96199684977226063154e-01,
  2564. -6.95916130632634022390e-01, -6.95632746963111059380e-01,
  2565. -6.95349538987770743326e-01, -6.95066502504559258213e-01,
  2566. -6.94783638126708624760e-01, -6.94500947603343021797e-01,
  2567. -6.94218428912669494046e-01, -6.93936082804800791202e-01,
  2568. -6.93653908301078647725e-01, -6.93371908566022487896e-01,
  2569. -6.93090077508149882135e-01, -6.92808419565063893231e-01,
  2570. -6.92526934253705372946e-01, -6.92245619068708628596e-01,
  2571. -6.91964473338724017637e-01, -6.91683502254516024976e-01,
  2572. -6.91402702488182807627e-01, -6.91122070984696024176e-01,
  2573. -6.90841612116200654015e-01, -6.90561322625015239218e-01,
  2574. -6.90281205581785073377e-01, -6.90001257549546886949e-01,
  2575. -6.89721478029636569929e-01, -6.89441872453674942101e-01,
  2576. -6.89162436357648067187e-01, -6.88883165402184860504e-01,
  2577. -6.88604070232913700877e-01, -6.88325140546367397754e-01,
  2578. -6.88046384559045987039e-01, -6.87767790884287189002e-01,
  2579. -6.87489374500497851805e-01, -6.87211120408326436859e-01,
  2580. -6.86933040099159009095e-01, -6.86655124958544749170e-01,
  2581. -6.86377381189093749292e-01, -6.86099803770688687621e-01,
  2582. -6.85822395405317086770e-01, -6.85545155893080848664e-01,
  2583. -6.85268083331586397300e-01, -6.84991179942370131961e-01,
  2584. -6.84714444329615257168e-01, -6.84437874267117551952e-01,
  2585. -6.84161474467574581837e-01, -6.83885239482271423128e-01,
  2586. -6.83609175217499309696e-01, -6.83333274672679680251e-01,
  2587. -6.83057543180028203800e-01, -6.82781977587132438146e-01,
  2588. -6.82506579583491368446e-01, -6.82231345563520275022e-01,
  2589. -6.81956282672124491917e-01, -6.81681382699073523668e-01,
  2590. -6.81406648988642449360e-01, -6.81132081961896229672e-01,
  2591. -6.80857682178235834591e-01, -6.80583446978993089616e-01,
  2592. -6.80309375263567606140e-01, -6.80035474093030112286e-01,
  2593. -6.79761733087503428052e-01, -6.79488158765748972989e-01,
  2594. -6.79214752196404480955e-01, -6.78941508174092933636e-01,
  2595. -6.78668429687879326551e-01, -6.78395515574814367277e-01,
  2596. -6.78122767497631007139e-01, -6.77850179968347288373e-01,
  2597. -6.77577762100286307145e-01, -6.77305505279880759595e-01,
  2598. -6.77033412496333641961e-01, -6.76761485994335831862e-01,
  2599. -6.76489719393857269480e-01, -6.76218119206519308051e-01,
  2600. -6.75946682529674824913e-01, -6.75675408874354177513e-01,
  2601. -6.75404297511148055122e-01, -6.75133351846663343210e-01,
  2602. -6.74862564571817591386e-01, -6.74591944752526595508e-01,
  2603. -6.74321485785951746372e-01, -6.74051188253726119015e-01,
  2604. -6.73781056432154912272e-01, -6.73511083810255595239e-01,
  2605. -6.73241275391847304732e-01, -6.72971628848506364662e-01,
  2606. -6.72702142902172117722e-01, -6.72432819405576420735e-01,
  2607. -6.72163657813787729367e-01, -6.71894658453800697195e-01,
  2608. -6.71625820562567810157e-01, -6.71357141277348468122e-01,
  2609. -6.71088627224218470246e-01, -6.70820271525421008008e-01,
  2610. -6.70552078302100618146e-01, -6.70284043535372409117e-01,
  2611. -6.70016173591694408351e-01, -6.69748458199992402484e-01,
  2612. -6.69480909726361872458e-01, -6.69213516917172568377e-01,
  2613. -6.68946284481173658598e-01, -6.68679216012868060659e-01,
  2614. -6.68412303601367385752e-01, -6.68145552943979481597e-01,
  2615. -6.67878960338233018668e-01, -6.67612529308768909431e-01,
  2616. -6.67346255047431613505e-01, -6.67080142086330152296e-01,
  2617. -6.66814188281055542085e-01, -6.66548392089199914778e-01,
  2618. -6.66282756236867390598e-01, -6.66017276949984693424e-01,
  2619. -6.65751961010806025953e-01, -6.65486796240258193791e-01,
  2620. -6.65221796632702977448e-01, -6.64956951917378802364e-01,
  2621. -6.64692266831228506518e-01, -6.64427738285177982291e-01,
  2622. -6.64163368310645152448e-01, -6.63899157458967215106e-01,
  2623. -6.63635101493379009341e-01, -6.63371205633731642060e-01,
  2624. -6.63107464413257408076e-01, -6.62843883303304792776e-01,
  2625. -6.62580457061119010298e-01, -6.62317190010498935138e-01,
  2626. -6.62054075686940191048e-01, -6.61791124448790291090e-01,
  2627. -6.61528323678905905147e-01, -6.61265685547834380920e-01,
  2628. -6.61003196342271448493e-01, -6.60740870805210378514e-01,
  2629. -6.60478697205595710606e-01, -6.60216679784977111822e-01,
  2630. -6.59954818896147266116e-01, -6.59693114474321662399e-01,
  2631. -6.59431566425846660273e-01, -6.59170169602183664281e-01,
  2632. -6.58908933515271577619e-01, -6.58647847617634174533e-01,
  2633. -6.58386922235495664069e-01, -6.58126148963177781681e-01,
  2634. -6.57865528745428029822e-01, -6.57605066208932775851e-01,
  2635. -6.57344758666007500381e-01, -6.57084601064832130035e-01,
  2636. -6.56824605124500249254e-01, -6.56564756960135609276e-01,
  2637. -6.56305066864535935345e-01, -6.56045529903129254201e-01,
  2638. -6.55786144345534061095e-01, -6.55526916459913788771e-01,
  2639. -6.55267839667802221015e-01, -6.55008917251094002765e-01,
  2640. -6.54750148248612329205e-01, -6.54491533223170662836e-01,
  2641. -6.54233070884690626201e-01, -6.53974760242737929161e-01,
  2642. -6.53716606549127665637e-01, -6.53458600962904423426e-01,
  2643. -6.53200751244333299717e-01, -6.52943051957115550010e-01,
  2644. -6.52685505910310381772e-01, -6.52428112891914491200e-01,
  2645. -6.52170870940882663191e-01, -6.51913782525463059159e-01,
  2646. -6.51656845321644140334e-01, -6.51400060569288341661e-01,
  2647. -6.51143425632956684979e-01, -6.50886944226608088471e-01,
  2648. -6.50630615305716641927e-01, -6.50374433746492064401e-01,
  2649. -6.50118409912749273261e-01, -6.49862529824762003017e-01,
  2650. -6.49606805510006379833e-01, -6.49351230777982735276e-01,
  2651. -6.49095807187341833355e-01, -6.48840534693980175440e-01,
  2652. -6.48585411915660881021e-01, -6.48330438837500522276e-01,
  2653. -6.48075616901269135894e-01, -6.47820945942705561649e-01,
  2654. -6.47566425177083959674e-01, -6.47312052319633957076e-01,
  2655. -6.47057831706227326585e-01, -6.46803759454018356578e-01,
  2656. -6.46549835582646559295e-01, -6.46296063896400263538e-01,
  2657. -6.46042440334356982135e-01, -6.45788966160048438780e-01,
  2658. -6.45535640380269004623e-01, -6.45282465704309915466e-01,
  2659. -6.45029437876147415665e-01, -6.44776560034714729674e-01,
  2660. -6.44523829468238051987e-01, -6.44271248296943266354e-01,
  2661. -6.44018816339636313018e-01, -6.43766532200867991342e-01,
  2662. -6.43514396055693715937e-01, -6.43262408599340806958e-01,
  2663. -6.43010566875844125079e-01, -6.42758876425902569984e-01,
  2664. -6.42507329218555911510e-01, -6.42255935073139161418e-01,
  2665. -6.42004685095015736884e-01, -6.41753582691653279291e-01,
  2666. -6.41502628715755141009e-01, -6.41251821936975163752e-01,
  2667. -6.41001160836058181403e-01, -6.40750647132437567421e-01,
  2668. -6.40500281055568221333e-01, -6.40250059968197837712e-01,
  2669. -6.39999988601946290245e-01, -6.39750061843456507837e-01,
  2670. -6.39500278650730780150e-01, -6.39250648305116686565e-01,
  2671. -6.39001157074963743732e-01, -6.38751817077913619514e-01,
  2672. -6.38502621514727142227e-01, -6.38253568700912876643e-01,
  2673. -6.38004666585740953799e-01, -6.37755907408363187372e-01,
  2674. -6.37507291911161622089e-01, -6.37258824885454600029e-01,
  2675. -6.37010503187394161451e-01, -6.36762323425182796832e-01,
  2676. -6.36514291133987608617e-01, -6.36266404328743595542e-01,
  2677. -6.36018659826609211727e-01, -6.35771061168143747366e-01,
  2678. -6.35523608549822371927e-01, -6.35276297645185561436e-01,
  2679. -6.35029134387725902045e-01, -6.34782110545802358281e-01,
  2680. -6.34535236348681808138e-01, -6.34288501462677678511e-01,
  2681. -6.34041914641527926122e-01, -6.33795467967775083551e-01,
  2682. -6.33549167593703055346e-01, -6.33303008003505141232e-01,
  2683. -6.33056993932254119528e-01, -6.32811123131335140357e-01,
  2684. -6.32565394272199932324e-01, -6.32319809329721316260e-01,
  2685. -6.32074367320891727928e-01, -6.31829070202868159356e-01,
  2686. -6.31583911130030539738e-01, -6.31338898763895817190e-01,
  2687. -6.31094027655757727757e-01, -6.30849299763053705803e-01,
  2688. -6.30604712704740499873e-01, -6.30360268459618455772e-01,
  2689. -6.30115967081463446142e-01, -6.29871806376373299940e-01,
  2690. -6.29627789478244714871e-01, -6.29383911633328185786e-01,
  2691. -6.29140177546854029167e-01, -6.28896584327522600866e-01,
  2692. -6.28653133247365936143e-01, -6.28409822109554871972e-01,
  2693. -6.28166652841440020794e-01, -6.27923625518381989252e-01,
  2694. -6.27680737911588959577e-01, -6.27437993272931704425e-01,
  2695. -6.27195386411654398628e-01, -6.26952923663039451974e-01,
  2696. -6.26710596052582280535e-01, -6.26468416379213244305e-01,
  2697. -6.26226370361392947750e-01, -6.25984468798736148898e-01,
  2698. -6.25742705126064335808e-01, -6.25501083628606235898e-01,
  2699. -6.25259599318561232195e-01, -6.25018256686031725700e-01,
  2700. -6.24777053934279402725e-01, -6.24535988172220113412e-01,
  2701. -6.24295067172993101146e-01, -6.24054279498932329417e-01,
  2702. -6.23813635187884907296e-01, -6.23573127877870336810e-01,
  2703. -6.23332761803093160502e-01, -6.23092531976650820802e-01,
  2704. -6.22852442936077554947e-01, -6.22612492694010200012e-01,
  2705. -6.22372679074432388902e-01, -6.22133007180836417049e-01,
  2706. -6.21893469951140587249e-01, -6.21654073766373604926e-01,
  2707. -6.21414816928307800481e-01, -6.21175694260889921239e-01,
  2708. -6.20936711402754637490e-01, -6.20697867739223418937e-01,
  2709. -6.20459160090374717278e-01, -6.20220590614702582677e-01,
  2710. -6.19982159446087810473e-01, -6.19743863890513058124e-01,
  2711. -6.19505709002232674010e-01, -6.19267688434115282092e-01,
  2712. -6.19029805756627693469e-01, -6.18792058622968155213e-01,
  2713. -6.18554452849878200205e-01, -6.18316978693062901939e-01,
  2714. -6.18079646961219419943e-01, -6.17842446515595722367e-01,
  2715. -6.17605383162825982701e-01, -6.17368461578931437828e-01,
  2716. -6.17131668429063418024e-01, -6.16895018848982901183e-01,
  2717. -6.16658499158108108773e-01, -6.16422121003326939359e-01,
  2718. -6.16185873829411923097e-01, -6.15949765858643694116e-01,
  2719. -6.15713791520932085533e-01, -6.15477953698487789680e-01,
  2720. -6.15242252020492652598e-01, -6.15006685088008708817e-01,
  2721. -6.14771253279671636705e-01, -6.14535956479875133951e-01,
  2722. -6.14300794772409064493e-01, -6.14065767937721718184e-01,
  2723. -6.13830876770228073269e-01, -6.13596118311820704072e-01,
  2724. -6.13361498012579442474e-01, -6.13127008206162837922e-01,
  2725. -6.12892657344050406643e-01, -6.12658436050471988388e-01,
  2726. -6.12424351025287472261e-01, -6.12190401608632028818e-01,
  2727. -6.11956583740106974112e-01, -6.11722903145300644923e-01,
  2728. -6.11489352158128496306e-01, -6.11255938953534583291e-01,
  2729. -6.11022655261633462764e-01, -6.10789509223216509071e-01,
  2730. -6.10556493308809900000e-01, -6.10323612731711540036e-01,
  2731. -6.10090865344073973731e-01, -6.09858248936054225808e-01,
  2732. -6.09625768906936205127e-01, -6.09393417045297591805e-01,
  2733. -6.09161204033737857522e-01, -6.08929117705023448259e-01,
  2734. -6.08697168105810870742e-01, -6.08465349568450442064e-01,
  2735. -6.08233663541013047649e-01, -6.08002109898864828708e-01,
  2736. -6.07770687692471445196e-01, -6.07539400844602006657e-01,
  2737. -6.07308240201651194923e-01, -6.07077216103529160307e-01,
  2738. -6.06846324283877858186e-01, -6.06615560292348421356e-01,
  2739. -6.06384929432888464262e-01, -6.06154431703861962255e-01,
  2740. -6.05924061807866065621e-01, -6.05693829760275859186e-01,
  2741. -6.05463723148737864577e-01, -6.05233748079676781018e-01,
  2742. -6.05003903715618296388e-01, -6.04774198475906521466e-01,
  2743. -6.04544610696509998604e-01, -6.04315162734855082505e-01,
  2744. -6.04085842704623399158e-01, -6.03856653441919410952e-01,
  2745. -6.03627595488644308475e-01, -6.03398663841088644944e-01,
  2746. -6.03169866796318343560e-01, -6.02941198521520616005e-01,
  2747. -6.02712662875009685948e-01, -6.02484250256341447027e-01,
  2748. -6.02255972857237198426e-01, -6.02027825038867536733e-01,
  2749. -6.01799805988958325109e-01, -6.01571913419564285874e-01,
  2750. -6.01344157294740888631e-01, -6.01116522397953101375e-01,
  2751. -6.00889026103673673518e-01, -6.00661647658158770469e-01,
  2752. -6.00434407998426733499e-01, -6.00207288833633056946e-01,
  2753. -5.99980308862523514790e-01, -5.99753445108572424971e-01,
  2754. -5.99526726075654492476e-01, -5.99300116604148724875e-01,
  2755. -5.99073650597569562493e-01, -5.98847305832576282114e-01,
  2756. -5.98621092595534198821e-01, -5.98395003140193559865e-01,
  2757. -5.98169046989315500440e-01, -5.97943216149849243735e-01,
  2758. -5.97717510719493860805e-01, -5.97491938300504732418e-01,
  2759. -5.97266490737901722952e-01, -5.97041170697608758466e-01,
  2760. -5.96815975670910492390e-01, -5.96590913026744495973e-01,
  2761. -5.96365978149817177467e-01, -5.96141159780623763886e-01,
  2762. -5.95916485220735703265e-01, -5.95691923578596127520e-01,
  2763. -5.95467492887766125520e-01, -5.95243196609040237099e-01,
  2764. -5.95019014041551219663e-01, -5.94794968648619137852e-01,
  2765. -5.94571043157184897510e-01, -5.94347249668552901625e-01,
  2766. -5.94123579402305201924e-01, -5.93900033027068730007e-01,
  2767. -5.93676616648752819572e-01, -5.93453327526834439887e-01,
  2768. -5.93230159341627150127e-01, -5.93007117760657065375e-01,
  2769. -5.92784208785247512807e-01, -5.92561413918450186067e-01,
  2770. -5.92338756443251623907e-01, -5.92116217604009120734e-01,
  2771. -5.91893804436822379422e-01, -5.91671518728806522525e-01,
  2772. -5.91449357471272030295e-01, -5.91227319735991518890e-01,
  2773. -5.91005412244563821389e-01, -5.90783620214691107542e-01,
  2774. -5.90561962526354289338e-01, -5.90340423145411241634e-01,
  2775. -5.90119013800835201522e-01, -5.89897725962619245976e-01,
  2776. -5.89676559670074262876e-01, -5.89455523295964733954e-01,
  2777. -5.89234605661662969034e-01, -5.89013820757174455522e-01,
  2778. -5.88793146152845503494e-01, -5.88572612873802136768e-01,
  2779. -5.88352186304420876617e-01, -5.88131895650970792921e-01,
  2780. -5.87911725759226233556e-01, -5.87691674512207162806e-01,
  2781. -5.87471754356189146407e-01, -5.87251951150662199197e-01,
  2782. -5.87032275483777565839e-01, -5.86812721495183042819e-01,
  2783. -5.86593290862264971075e-01, -5.86373982735830190371e-01,
  2784. -5.86154798835264334578e-01, -5.85935733132218805608e-01,
  2785. -5.85716796844832021662e-01, -5.85497984656510039869e-01,
  2786. -5.85279284263748866834e-01, -5.85060716669546732049e-01,
  2787. -5.84842266044768188671e-01, -5.84623941175344330468e-01,
  2788. -5.84405733922557346638e-01, -5.84187656879476824301e-01,
  2789. -5.83969690164282795308e-01, -5.83751856007703295859e-01,
  2790. -5.83534141248000293167e-01, -5.83316542773784973974e-01,
  2791. -5.83099075016479395650e-01, -5.82881716889396495063e-01,
  2792. -5.82664493604380329117e-01, -5.82447381280095655143e-01,
  2793. -5.82230394350684243854e-01, -5.82013532488527274289e-01,
  2794. -5.81796782569958814690e-01, -5.81580163889648171782e-01,
  2795. -5.81363657096067520946e-01, -5.81147275597175272388e-01,
  2796. -5.80931018640279073217e-01, -5.80714875828189036611e-01,
  2797. -5.80498855974745042730e-01, -5.80282956573518804433e-01,
  2798. -5.80067178836383479101e-01, -5.79851520422275057420e-01,
  2799. -5.79635978307705301837e-01, -5.79420566927691282899e-01,
  2800. -5.79205265093265642129e-01, -5.78990087245926599024e-01,
  2801. -5.78775030336261320230e-01, -5.78560092120421365358e-01,
  2802. -5.78345273447344543349e-01, -5.78130573165126393498e-01,
  2803. -5.77915995032448615021e-01, -5.77701536342358656917e-01,
  2804. -5.77487192988114461656e-01, -5.77272972927765581908e-01,
  2805. -5.77058870787597544272e-01, -5.76844888928548904516e-01,
  2806. -5.76631023280578580703e-01, -5.76417276587042004543e-01,
  2807. -5.76203653120429537537e-01, -5.75990144223295308379e-01,
  2808. -5.75776757901189761846e-01, -5.75563481965228884718e-01,
  2809. -5.75350334813656383304e-01, -5.75137299745865471223e-01,
  2810. -5.74924380462553563653e-01, -5.74711590037412012322e-01,
  2811. -5.74498906002588793918e-01, -5.74286349276446173029e-01,
  2812. -5.74073903356870807180e-01, -5.73861579806341892684e-01,
  2813. -5.73649371228796445266e-01, -5.73437284470137975667e-01,
  2814. -5.73225310718684766265e-01, -5.73013456023520051374e-01,
  2815. -5.72801716175861619362e-01, -5.72590101961756081650e-01,
  2816. -5.72378596797541217001e-01, -5.72167211528335384330e-01,
  2817. -5.71955941709068382828e-01, -5.71744794274904322151e-01,
  2818. -5.71533757106126860670e-01, -5.71322838218824013978e-01,
  2819. -5.71112040020102962323e-01, -5.70901356041317420420e-01,
  2820. -5.70690787398203669412e-01, -5.70480336096462870010e-01,
  2821. -5.70270004173424105431e-01, -5.70059781474071325391e-01,
  2822. -5.69849684229397412949e-01, -5.69639691198059239241e-01,
  2823. -5.69429826410952522053e-01, -5.69220070865192440124e-01,
  2824. -5.69010431837938868149e-01, -5.68800910399309023191e-01,
  2825. -5.68591506167543392358e-01, -5.68382208423693136012e-01,
  2826. -5.68173038073570446649e-01, -5.67963978092230536987e-01,
  2827. -5.67755030970157004155e-01, -5.67546203770359025675e-01,
  2828. -5.67337488102058862260e-01, -5.67128888113616835831e-01,
  2829. -5.66920406778240515422e-01, -5.66712039230608977114e-01,
  2830. -5.66503779607057222911e-01, -5.66295645051695717420e-01,
  2831. -5.66087617555229849486e-01, -5.65879707307245127801e-01,
  2832. -5.65671913910436696682e-01, -5.65464228764436582786e-01,
  2833. -5.65256664316280965643e-01, -5.65049212905805120499e-01,
  2834. -5.64841870374890531181e-01, -5.64634649840305424817e-01,
  2835. -5.64427536520706540912e-01, -5.64220542897088006562e-01,
  2836. -5.64013656178556255227e-01, -5.63806892695951078487e-01,
  2837. -5.63600233444419784767e-01, -5.63393693409048657017e-01,
  2838. -5.63187265181959162419e-01, -5.62980952233706921639e-01,
  2839. -5.62774748089948873009e-01, -5.62568664001630525107e-01,
  2840. -5.62362683791054585036e-01, -5.62156827390452251691e-01,
  2841. -5.61951075952079159848e-01, -5.61745440231198656100e-01,
  2842. -5.61539918406243399041e-01, -5.61334507008219185664e-01,
  2843. -5.61129210558799051967e-01, -5.60924025616156063379e-01,
  2844. -5.60718950250054470885e-01, -5.60513995623263650003e-01,
  2845. -5.60309141366683527430e-01, -5.60104413090462549540e-01,
  2846. -5.59899784602460259819e-01, -5.59695279181735561025e-01,
  2847. -5.59490874607678101427e-01, -5.59286591780185582401e-01,
  2848. -5.59082414023761575805e-01, -5.58878353612881406676e-01,
  2849. -5.58674400476881993782e-01, -5.58470560272198546237e-01,
  2850. -5.58266831619624648297e-01, -5.58063214379549865640e-01,
  2851. -5.57859710489623239482e-01, -5.57656312338858040079e-01,
  2852. -5.57453037257682026961e-01, -5.57249857062983466882e-01,
  2853. -5.57046800101556049967e-01, -5.56843848224561788207e-01,
  2854. -5.56641012152947034508e-01, -5.56438278327634150422e-01,
  2855. -5.56235667912246767308e-01, -5.56033154514851135630e-01,
  2856. -5.55830766660204256269e-01, -5.55628472520565130921e-01,
  2857. -5.55426303826917155959e-01, -5.55224232538292339356e-01,
  2858. -5.55022283208224775919e-01, -5.54820430367028993857e-01,
  2859. -5.54618706636430314205e-01, -5.54417074054438074882e-01,
  2860. -5.54215562440321773963e-01, -5.54014157534220008650e-01,
  2861. -5.53812864204566768223e-01, -5.53611677237488386538e-01,
  2862. -5.53410601444173755326e-01, -5.53209633969611869198e-01,
  2863. -5.53008781422658302063e-01, -5.52808031398771770881e-01,
  2864. -5.52607393379650480014e-01, -5.52406864194784130717e-01,
  2865. -5.52206447044515491562e-01, -5.52006132297983898027e-01,
  2866. -5.51805932926547226813e-01, -5.51605840203247654863e-01,
  2867. -5.51405853712816806933e-01, -5.51205983843285340917e-01,
  2868. -5.51006211809542234548e-01, -5.50806557660515672126e-01,
  2869. -5.50607004689088852523e-01, -5.50407566147187443661e-01,
  2870. -5.50208228085966921661e-01, -5.50009010697139366641e-01,
  2871. -5.49809891866183120257e-01, -5.49610883980118702929e-01,
  2872. -5.49411981957127704135e-01, -5.49213193737463911681e-01,
  2873. -5.49014503817799592866e-01, -5.48815932743580869868e-01,
  2874. -5.48617458539834013109e-01, -5.48419103857524015133e-01,
  2875. -5.48220844771248438931e-01, -5.48022698452298229199e-01,
  2876. -5.47824664844393738328e-01, -5.47626727001364610459e-01,
  2877. -5.47428908060687779980e-01, -5.47231188297979453949e-01,
  2878. -5.47033578769815509446e-01, -5.46836077326017133693e-01,
  2879. -5.46638681510724033785e-01, -5.46441392121685520777e-01,
  2880. -5.46244208423764421312e-01, -5.46047132559760117765e-01,
  2881. -5.45850167869482705285e-01, -5.45653298850893309080e-01,
  2882. -5.45456550644724424970e-01, -5.45259894069439088327e-01,
  2883. -5.45063353655226401351e-01, -5.44866916342223062131e-01,
  2884. -5.44670587487950941252e-01, -5.44474358722185636239e-01,
  2885. -5.44278246992432546136e-01, -5.44082226406505276017e-01,
  2886. -5.43886327706291639039e-01, -5.43690520871651483681e-01,
  2887. -5.43494828186031564421e-01, -5.43299235239269484588e-01,
  2888. -5.43103755036826063574e-01, -5.42908372318762322273e-01,
  2889. -5.42713101591759894404e-01, -5.42517933616644687511e-01,
  2890. -5.42322868491689424886e-01, -5.42127915062977416838e-01,
  2891. -5.41933060199644156540e-01, -5.41738314051451785858e-01,
  2892. -5.41543671501958590042e-01, -5.41349131691297391633e-01,
  2893. -5.41154703175379503399e-01, -5.40960374942168753520e-01,
  2894. -5.40766148956284276039e-01, -5.40572028371287816029e-01,
  2895. -5.40378020960053717658e-01, -5.40184103653394309674e-01,
  2896. -5.39990305075831233950e-01, -5.39796600853690300426e-01,
  2897. -5.39603003977793482804e-01, -5.39409509210268311996e-01,
  2898. -5.39216124511781913498e-01, -5.39022834453409704913e-01,
  2899. -5.38829659262570759282e-01, -5.38636578161997059411e-01,
  2900. -5.38443609329856687218e-01, -5.38250734358359017584e-01,
  2901. -5.38057975172885782911e-01, -5.37865307183183372075e-01,
  2902. -5.37672750945531352507e-01, -5.37480293528547869997e-01,
  2903. -5.37287943749739205224e-01, -5.37095690446331985868e-01,
  2904. -5.36903547100173295092e-01, -5.36711504474260636677e-01,
  2905. -5.36519563683013567257e-01, -5.36327729505757688777e-01,
  2906. -5.36135992886641155053e-01, -5.35944362918005068330e-01,
  2907. -5.35752834638077879426e-01, -5.35561407625734231530e-01,
  2908. -5.35370088527245657772e-01, -5.35178862354523610101e-01,
  2909. -5.34987748886039060636e-01, -5.34796728699478363112e-01,
  2910. -5.34605815002141993020e-01, -5.34415007914754935925e-01,
  2911. -5.34224293747115996922e-01, -5.34033693611692839021e-01,
  2912. -5.33843181452299697654e-01, -5.33652784501857047061e-01,
  2913. -5.33462475764223453822e-01, -5.33272280111689811477e-01,
  2914. -5.33082180930588456214e-01, -5.32892186275686574604e-01,
  2915. -5.32702291717452758313e-01, -5.32512495743376668145e-01,
  2916. -5.32322808833029625930e-01, -5.32133212932378696358e-01,
  2917. -5.31943725074500606276e-01, -5.31754339884605298217e-01,
  2918. -5.31565050652905601858e-01, -5.31375867241598021096e-01,
  2919. -5.31186779263425279396e-01, -5.30997796053478632317e-01,
  2920. -5.30808913010392569021e-01, -5.30620128028665871689e-01,
  2921. -5.30431454131669366525e-01, -5.30242863683162979349e-01,
  2922. -5.30054387149510808364e-01, -5.29866008532592913660e-01,
  2923. -5.29677727830911937446e-01, -5.29489549872706133371e-01,
  2924. -5.29301466522391517167e-01, -5.29113494318193988697e-01,
  2925. -5.28925608770407507109e-01, -5.28737835420275414933e-01,
  2926. -5.28550152471884304717e-01, -5.28362576864161215262e-01,
  2927. -5.28175096164924973152e-01, -5.27987720812230887368e-01,
  2928. -5.27800432661909901810e-01, -5.27613260324969468584e-01,
  2929. -5.27426174556774984836e-01, -5.27239196669631482450e-01,
  2930. -5.27052315362437129309e-01, -5.26865532175552986338e-01,
  2931. -5.26678852248636530931e-01, -5.26492264658567798996e-01,
  2932. -5.26305785606426601575e-01, -5.26119394738626899866e-01,
  2933. -5.25933112564948679335e-01, -5.25746922103342950727e-01,
  2934. -5.25560837244612333308e-01, -5.25374841759336907998e-01,
  2935. -5.25188953146781378756e-01, -5.25003162342790208328e-01,
  2936. -5.24817465752979828153e-01, -5.24631875643167933099e-01,
  2937. -5.24446368896209325072e-01, -5.24260981011384075146e-01,
  2938. -5.24075671339813808913e-01, -5.23890477570763124504e-01,
  2939. -5.23705367827149603777e-01, -5.23520364872812615786e-01,
  2940. -5.23335454232961572174e-01, -5.23150648691175557126e-01,
  2941. -5.22965933939672056319e-01, -5.22781320898389578744e-01,
  2942. -5.22596802547097949443e-01, -5.22412384870908130807e-01,
  2943. -5.22228062125477787703e-01, -5.22043840127194180845e-01,
  2944. -5.21859712530721830959e-01, -5.21675687725144388018e-01,
  2945. -5.21491749675332627589e-01, -5.21307920605108998657e-01,
  2946. -5.21124183533665741308e-01, -5.20940539456928863871e-01,
  2947. -5.20757001372001870898e-01, -5.20573549822157310984e-01,
  2948. -5.20390204933718125702e-01, -5.20206950361603026600e-01,
  2949. -5.20023797832201872815e-01, -5.19840739136778307028e-01,
  2950. -5.19657773032146108605e-01, -5.19474912699786184334e-01,
  2951. -5.19292140184574591011e-01, -5.19109469422041946984e-01,
  2952. -5.18926896152802741291e-01, -5.18744412302997615072e-01,
  2953. -5.18562032075707168843e-01, -5.18379740260081822711e-01,
  2954. -5.18197549968825610378e-01, -5.18015457489585662287e-01,
  2955. -5.17833453383197195308e-01, -5.17651556766932641196e-01,
  2956. -5.17469745314348417153e-01, -5.17288033334592833867e-01,
  2957. -5.17106419445129028567e-01, -5.16924894866955919603e-01,
  2958. -5.16743473746873793750e-01, -5.16562141804293717406e-01,
  2959. -5.16380908487159562270e-01, -5.16199772636025677741e-01,
  2960. -5.16018729440732126790e-01, -5.15837776949621074074e-01,
  2961. -5.15656927779485463326e-01, -5.15476166942422153738e-01,
  2962. -5.15295508245639188871e-01, -5.15114933799949437088e-01,
  2963. -5.14934467827279918062e-01, -5.14754087208464383707e-01,
  2964. -5.14573804318886995901e-01, -5.14393615127918146790e-01,
  2965. -5.14213523382693216135e-01, -5.14033518125299626611e-01,
  2966. -5.13853617088510961075e-01, -5.13673805002628713900e-01,
  2967. -5.13494091686059750401e-01, -5.13314464310747786691e-01,
  2968. -5.13134942018768192007e-01, -5.12955505773359687893e-01,
  2969. -5.12776167876007660240e-01, -5.12596920509274522892e-01,
  2970. -5.12417771465554672261e-01, -5.12238708568578005043e-01,
  2971. -5.12059750379289191358e-01, -5.11880879533663235570e-01,
  2972. -5.11702102223372312650e-01, -5.11523422221623169648e-01,
  2973. -5.11344829419787094693e-01, -5.11166338127431063576e-01,
  2974. -5.10987934742527905030e-01, -5.10809625836007308308e-01,
  2975. -5.10631409902048583049e-01, -5.10453286393003913268e-01,
  2976. -5.10275259005286696556e-01, -5.10097324676761276763e-01,
  2977. -5.09919480783686318581e-01, -5.09741729707290813778e-01,
  2978. -5.09564075722271581093e-01, -5.09386510524484137363e-01,
  2979. -5.09209040704066917549e-01, -5.09031659380481893429e-01,
  2980. -5.08854376309871736517e-01, -5.08677181699944691573e-01,
  2981. -5.08500082611985537717e-01, -5.08323071769016254784e-01,
  2982. -5.08146160041792915862e-01, -5.07969333576011261577e-01,
  2983. -5.07792603390520680406e-01, -5.07615961615968891429e-01,
  2984. -5.07439417535044401397e-01, -5.07262964238087699087e-01,
  2985. -5.07086597729305976756e-01, -5.06910329725660746547e-01,
  2986. -5.06734150882708900276e-01, -5.06558064509521788210e-01,
  2987. -5.06382066714256118267e-01, -5.06206169755213153394e-01,
  2988. -5.06030350842774145903e-01, -5.05854632997757347468e-01,
  2989. -5.05679002805864419301e-01, -5.05503468551726342639e-01,
  2990. -5.05328021686990758177e-01, -5.05152665768693220905e-01,
  2991. -5.04977406292914432484e-01, -5.04802228894167148709e-01,
  2992. -5.04627152010708512897e-01, -5.04452160958478557085e-01,
  2993. -5.04277262507847989781e-01, -5.04102455437264618254e-01,
  2994. -5.03927737862568170257e-01, -5.03753107366079477814e-01,
  2995. -5.03578575502675152009e-01, -5.03404131998141490811e-01,
  2996. -5.03229772866844449197e-01, -5.03055513149661570615e-01,
  2997. -5.02881341372201307038e-01, -5.02707254863539287904e-01,
  2998. -5.02533264605894314236e-01, -5.02359362868927239454e-01,
  2999. -5.02185547240035057293e-01, -5.02011835099967607121e-01,
  3000. -5.01838192865942445131e-01, -5.01664659257242795398e-01,
  3001. -5.01491202386485701581e-01, -5.01317844028692949365e-01,
  3002. -5.01144573674645599226e-01, -5.00971389234455277695e-01,
  3003. -5.00798298401023855853e-01, -5.00625294844373347480e-01,
  3004. -5.00452385015643708144e-01, -5.00279560616122997985e-01,
  3005. -5.00106826037778007255e-01, -4.99934183187324188147e-01,
  3006. -4.99761631221804392133e-01, -4.99589160430459866546e-01,
  3007. -4.99416788147540702258e-01, -4.99244499450290479814e-01,
  3008. -4.99072303167870379159e-01, -4.98900190082264438640e-01,
  3009. -4.98728177060504151985e-01, -4.98556239380091414937e-01,
  3010. -4.98384403184633395512e-01, -4.98212644501553447718e-01,
  3011. -4.98040988374067628008e-01, -4.97869403305372104640e-01,
  3012. -4.97697923184240553773e-01, -4.97526522183478925321e-01,
  3013. -4.97355213843734156320e-01, -4.97183992181355394191e-01,
  3014. -4.97012856414427717233e-01, -4.96841815654261997892e-01,
  3015. -4.96670856589271125792e-01, -4.96499989826879928323e-01,
  3016. -4.96329208600718163602e-01, -4.96158518192971298433e-01,
  3017. -4.95987915417138214291e-01, -4.95817396561167578195e-01,
  3018. -4.95646968483893668456e-01, -4.95476629813774605005e-01,
  3019. -4.95306379178141298336e-01, -4.95136212263342589956e-01,
  3020. -4.94966136520781141428e-01, -4.94796148810238756166e-01,
  3021. -4.94626243065314996628e-01, -4.94456435515959080718e-01,
  3022. -4.94286700836386871938e-01, -4.94117068220431165937e-01,
  3023. -4.93947513273770733022e-01, -4.93778048500503219387e-01,
  3024. -4.93608670630300450100e-01, -4.93439380240378033804e-01,
  3025. -4.93270178292201766368e-01, -4.93101060362692411587e-01,
  3026. -4.92932032006830334048e-01, -4.92763086603644373529e-01,
  3027. -4.92594233906167910941e-01, -4.92425463874980429146e-01,
  3028. -4.92256784562988658482e-01, -4.92088184973856646032e-01,
  3029. -4.91919678688281070134e-01, -4.91751255907422357705e-01,
  3030. -4.91582919894200887079e-01, -4.91414667395775106584e-01,
  3031. -4.91246508160590455994e-01, -4.91078428799448130082e-01,
  3032. -4.90910439593086167509e-01, -4.90742535159492621055e-01,
  3033. -4.90574715570106012485e-01, -4.90406985921184590538e-01,
  3034. -4.90239336932127289792e-01, -4.90071778277338720997e-01,
  3035. -4.89904302891543297349e-01, -4.89736918185567804418e-01,
  3036. -4.89569612757251415580e-01, -4.89402391276797965602e-01,
  3037. -4.89235268817294621790e-01, -4.89068213943802065913e-01,
  3038. -4.88901259091894080377e-01, -4.88734384185310899440e-01,
  3039. -4.88567592390033778038e-01, -4.88400891118397850743e-01,
  3040. -4.88234269906823503682e-01, -4.88067740845552044959e-01,
  3041. -4.87901288388939091689e-01, -4.87734929101708958310e-01,
  3042. -4.87568645798221456111e-01, -4.87402457128699562183e-01,
  3043. -4.87236350381375693530e-01, -4.87070324225484241332e-01,
  3044. -4.86904385519984495012e-01, -4.86738530511547085045e-01,
  3045. -4.86572767354529089889e-01, -4.86407078360703515330e-01,
  3046. -4.86241481425138122319e-01, -4.86075967359270388890e-01,
  3047. -4.85910532670543182654e-01, -4.85745189341874772371e-01,
  3048. -4.85579926461763289325e-01, -4.85414753341555094135e-01,
  3049. -4.85249654823238341095e-01, -4.85084648699901588298e-01,
  3050. -4.84919723660684809374e-01, -4.84754884804198205028e-01,
  3051. -4.84590123046861998013e-01, -4.84425458448513146514e-01,
  3052. -4.84260864556867121067e-01, -4.84096360065999875566e-01,
  3053. -4.83931941355376094016e-01, -4.83767604213061086504e-01,
  3054. -4.83603346755586915862e-01, -4.83439180728759743122e-01,
  3055. -4.83275094560436269120e-01, -4.83111089265769844125e-01,
  3056. -4.82947172356291476447e-01, -4.82783335122464629663e-01,
  3057. -4.82619582539163261004e-01, -4.82455914592298529264e-01,
  3058. -4.82292326363351897545e-01, -4.82128826364616291933e-01,
  3059. -4.81965407817179114502e-01, -4.81802066972656928279e-01,
  3060. -4.81638814427624573078e-01, -4.81475645071778979300e-01,
  3061. -4.81312557573886912188e-01, -4.81149551193313373965e-01,
  3062. -4.80986630223831979070e-01, -4.80823789406853552286e-01,
  3063. -4.80661034307090506701e-01, -4.80498359100152816481e-01,
  3064. -4.80335770343018442219e-01, -4.80173258808035297029e-01,
  3065. -4.80010832497092865268e-01, -4.79848490982026310014e-01,
  3066. -4.79686227973605716635e-01, -4.79524046705174122884e-01,
  3067. -4.79361951708459965715e-01, -4.79199932799077243928e-01,
  3068. -4.79038003831099401530e-01, -4.78876153100232238025e-01,
  3069. -4.78714380041965981150e-01, -4.78552698618633920447e-01,
  3070. -4.78391087073025467191e-01, -4.78229573768165938663e-01,
  3071. -4.78068122888519353442e-01, -4.77906771102107552629e-01,
  3072. -4.77745485783475642982e-01, -4.77584293711196150589e-01,
  3073. -4.77423176275788341272e-01, -4.77262147608990328074e-01,
  3074. -4.77101192145071517636e-01, -4.76940324487603428683e-01,
  3075. -4.76779535315644098503e-01, -4.76618824957646625151e-01,
  3076. -4.76458201420741689347e-01, -4.76297654699695649505e-01,
  3077. -4.76137194456570100876e-01, -4.75976803224222311250e-01,
  3078. -4.75816507681549927256e-01, -4.75656285635331022021e-01,
  3079. -4.75496143300199403114e-01, -4.75336089186713772747e-01,
  3080. -4.75176105389747416297e-01, -4.75016210315764575434e-01,
  3081. -4.74856392947519134751e-01, -4.74696656595788579747e-01,
  3082. -4.74536999034709916501e-01, -4.74377425856956969064e-01,
  3083. -4.74217928093568941161e-01, -4.74058513675973014490e-01,
  3084. -4.73899182199162827267e-01, -4.73739927351737866168e-01,
  3085. -4.73580752432562757104e-01, -4.73421661733451903942e-01,
  3086. -4.73262645964154682332e-01, -4.73103715642114674989e-01,
  3087. -4.72944860339552519690e-01, -4.72786088898399126101e-01,
  3088. -4.72627398730451619979e-01, -4.72468780170721247558e-01,
  3089. -4.72310252115622830615e-01, -4.72151793347969528369e-01,
  3090. -4.71993425136610800230e-01, -4.71835128326818731281e-01,
  3091. -4.71676913565172273302e-01, -4.71518779771825324865e-01,
  3092. -4.71360720619582784785e-01, -4.71202751321201207535e-01,
  3093. -4.71044850880461440923e-01, -4.70887032190129728448e-01,
  3094. -4.70729298202972046283e-01, -4.70571635391029530204e-01,
  3095. -4.70414061385758586198e-01, -4.70256552716906972567e-01,
  3096. -4.70099140930541448125e-01, -4.69941790367873535317e-01,
  3097. -4.69784533886893507226e-01, -4.69627342769655231614e-01,
  3098. -4.69470243150597432713e-01, -4.69313215089266821956e-01,
  3099. -4.69156267509552749040e-01, -4.68999395832224053038e-01,
  3100. -4.68842609450314307118e-01, -4.68685897722662947462e-01,
  3101. -4.68529260293265359394e-01, -4.68372709227301453616e-01,
  3102. -4.68216230147668388550e-01, -4.68059834969985155695e-01,
  3103. -4.67903512760620088340e-01, -4.67747272986739126566e-01,
  3104. -4.67591111065052189577e-01, -4.67435024685682654066e-01,
  3105. -4.67279016495556198674e-01, -4.67123089392717960600e-01,
  3106. -4.66967240313931553075e-01, -4.66811467438227656324e-01,
  3107. -4.66655769936848929813e-01, -4.66500152945792889714e-01,
  3108. -4.66344619101570212472e-01, -4.66189152722139621421e-01,
  3109. -4.66033769195671743191e-01, -4.65878467355010317252e-01,
  3110. -4.65723236480608038246e-01, -4.65568087090199089761e-01,
  3111. -4.65413010184134667835e-01, -4.65258020067406741216e-01,
  3112. -4.65103102047306760092e-01, -4.64948255886194261599e-01,
  3113. -4.64793497227340202116e-01, -4.64638808438783912358e-01,
  3114. -4.64484199701613809097e-01, -4.64329670275179240413e-01,
  3115. -4.64175212940993731081e-01, -4.64020834961912320704e-01,
  3116. -4.63866536856742783801e-01, -4.63712309287399704338e-01,
  3117. -4.63558166735674515024e-01, -4.63404094140099642729e-01,
  3118. -4.63250103737141538662e-01, -4.63096183994143872908e-01,
  3119. -4.62942346453523445593e-01, -4.62788578830010732812e-01,
  3120. -4.62634896370526571552e-01, -4.62481283900268602682e-01,
  3121. -4.62327753343912351003e-01, -4.62174294529301699086e-01,
  3122. -4.62020913868642191247e-01, -4.61867607061139495706e-01,
  3123. -4.61714384897765395266e-01, -4.61561230867168159619e-01,
  3124. -4.61408155520300011787e-01, -4.61255155516445081165e-01,
  3125. -4.61102233667515015725e-01, -4.60949382066578872141e-01,
  3126. -4.60796618353578379956e-01, -4.60643913403289584352e-01,
  3127. -4.60491299021441868877e-01, -4.60338755341436867141e-01,
  3128. -4.60186285320456245351e-01, -4.60033896996370872401e-01,
  3129. -4.59881577612257952392e-01, -4.59729336630324780799e-01,
  3130. -4.59577171310406873417e-01, -4.59425083150955204658e-01,
  3131. -4.59273068898329361875e-01, -4.59121128892770402619e-01,
  3132. -4.58969265026953621156e-01, -4.58817480565808177850e-01,
  3133. -4.58665760556941526360e-01, -4.58514128017382727176e-01,
  3134. -4.58362561710762062006e-01, -4.58211078862046317095e-01,
  3135. -4.58059665335349530668e-01, -4.57908326921637853779e-01,
  3136. -4.57757065768802040573e-01, -4.57605878670184207380e-01,
  3137. -4.57454765128654905482e-01, -4.57303730339389313819e-01,
  3138. -4.57152765194686672157e-01, -4.57001878578433717859e-01,
  3139. -4.56851066414525497361e-01, -4.56700324947624303196e-01,
  3140. -4.56549662099315856079e-01, -4.56399072290335383606e-01,
  3141. -4.56248558740286580537e-01, -4.56098114150018663082e-01,
  3142. -4.55947753320660786880e-01, -4.55797457874459521765e-01,
  3143. -4.55647241817815684684e-01, -4.55497101030491791107e-01,
  3144. -4.55347026811166788463e-01, -4.55197035733620636311e-01,
  3145. -4.55047114907537797457e-01, -4.54897265792787275362e-01,
  3146. -4.54747495440209426043e-01, -4.54597796538315446213e-01,
  3147. -4.54448168930477292005e-01, -4.54298620554697607510e-01,
  3148. -4.54149142167335262421e-01, -4.53999740453209232882e-01,
  3149. -4.53850409092556528190e-01, -4.53701155503739850250e-01,
  3150. -4.53551967508941333840e-01, -4.53402864049327503082e-01,
  3151. -4.53253826241534985009e-01, -4.53104865974366610715e-01,
  3152. -4.52955976927715830982e-01, -4.52807161317335338246e-01,
  3153. -4.52658416600321633627e-01, -4.52509750732534687945e-01,
  3154. -4.52361156785181017792e-01, -4.52212632165832073561e-01,
  3155. -4.52064182997125807439e-01, -4.51915809732679141231e-01,
  3156. -4.51767504435387212691e-01, -4.51619276048310869243e-01,
  3157. -4.51471119088053707280e-01, -4.51323035369269209838e-01,
  3158. -4.51175023116738904694e-01, -4.51027087616684640992e-01,
  3159. -4.50879220675307723631e-01, -4.50731427429839681675e-01,
  3160. -4.50583706701023323227e-01, -4.50436058068656608455e-01,
  3161. -4.50288484392804111422e-01, -4.50140985829281470298e-01,
  3162. -4.49993547718889774778e-01, -4.49846195014996619310e-01,
  3163. -4.49698909618556408319e-01, -4.49551694268899182383e-01,
  3164. -4.49404556107751540495e-01, -4.49257486180618614835e-01,
  3165. -4.49110490812010820783e-01, -4.48963564834253037183e-01,
  3166. -4.48816711417663771755e-01, -4.48669934224515287724e-01,
  3167. -4.48523226611271530473e-01, -4.48376589138061998341e-01,
  3168. -4.48230026207904586055e-01, -4.48083530824469000731e-01,
  3169. -4.47937115394188400952e-01, -4.47790759639401680925e-01,
  3170. -4.47644487560837300855e-01, -4.47498279312596392021e-01,
  3171. -4.47352145574061499378e-01, -4.47206085825344268336e-01,
  3172. -4.47060091466615849853e-01, -4.46914175065337260229e-01,
  3173. -4.46768328479106580087e-01, -4.46622549358328568836e-01,
  3174. -4.46476844067914602210e-01, -4.46331211849556985793e-01,
  3175. -4.46185649371574566402e-01, -4.46040159543129255404e-01,
  3176. -4.45894734059254282954e-01, -4.45749392054783755146e-01,
  3177. -4.45604109998832320638e-01, -4.45458907000752302174e-01,
  3178. -4.45313763681632224234e-01, -4.45168704920153035509e-01,
  3179. -4.45023706459857115725e-01, -4.44878784568539797917e-01,
  3180. -4.44733931959089667796e-01, -4.44589150336285765519e-01,
  3181. -4.44444440168124510482e-01, -4.44299797877839797167e-01,
  3182. -4.44155226128629454507e-01, -4.44010729020339223183e-01,
  3183. -4.43866298666259206929e-01, -4.43721940161641459355e-01,
  3184. -4.43577652188057836025e-01, -4.43433434923970193342e-01,
  3185. -4.43289288973958195417e-01, -4.43145211741241440428e-01,
  3186. -4.43001201832491808830e-01, -4.42857267417801292453e-01,
  3187. -4.42713399561871723265e-01, -4.42569603484062712440e-01,
  3188. -4.42425878418105156253e-01, -4.42282222209714359629e-01,
  3189. -4.42138633066428476948e-01, -4.41995120312379197181e-01,
  3190. -4.41851670795243789414e-01, -4.41708294272568247063e-01,
  3191. -4.41564987218233395705e-01, -4.41421753979170328197e-01,
  3192. -4.41278580693772737309e-01, -4.41135484933924015838e-01,
  3193. -4.40992454977177983366e-01, -4.40849497789696342931e-01,
  3194. -4.40706608405147748364e-01, -4.40563788546826096137e-01,
  3195. -4.40421036287886535909e-01, -4.40278357612415072175e-01,
  3196. -4.40135741686783155124e-01, -4.39993203509676911178e-01,
  3197. -4.39850727447593570218e-01, -4.39708327508245289117e-01,
  3198. -4.39565985646027390654e-01, -4.39423726508034517835e-01,
  3199. -4.39281525430847197278e-01, -4.39139400541693647462e-01,
  3200. -4.38997337522693764633e-01, -4.38855353166397843534e-01,
  3201. -4.38713428148096995507e-01, -4.38571578270592898896e-01,
  3202. -4.38429793175001303318e-01, -4.38288076142315019545e-01,
  3203. -4.38146435583318394347e-01, -4.38004856925622299002e-01,
  3204. -4.37863345344516097235e-01, -4.37721905887101636612e-01,
  3205. -4.37580535541424453516e-01, -4.37439230132329770484e-01,
  3206. -4.37297998196520043557e-01, -4.37156832114081794760e-01,
  3207. -4.37015731476225077756e-01, -4.36874705538022933826e-01,
  3208. -4.36733740039714768422e-01, -4.36592849237657620876e-01,
  3209. -4.36452023893796947629e-01, -4.36311264352250760545e-01,
  3210. -4.36170578474602832486e-01, -4.36029956822141295802e-01,
  3211. -4.35889406936388223990e-01, -4.35748919265838252635e-01,
  3212. -4.35608502123248308990e-01, -4.35468154160838893940e-01,
  3213. -4.35327872456970021986e-01, -4.35187658870110516407e-01,
  3214. -4.35047508888025347140e-01, -4.34907438701185977692e-01,
  3215. -4.34767421587553992701e-01, -4.34627481189585829213e-01,
  3216. -4.34487605538849241960e-01, -4.34347796514875039708e-01,
  3217. -4.34208058567971622033e-01, -4.34068383193245921348e-01,
  3218. -4.33928777608219518047e-01, -4.33789243799441504024e-01,
  3219. -4.33649766603194375403e-01, -4.33510371160185314920e-01,
  3220. -4.33371027950657794481e-01, -4.33231762857705704484e-01,
  3221. -4.33092557748064654888e-01, -4.32953425744085129701e-01,
  3222. -4.32814354841371762284e-01, -4.32675357583413688900e-01,
  3223. -4.32536418152391188841e-01, -4.32397553748481100477e-01,
  3224. -4.32258756092280593819e-01, -4.32120018749481138443e-01,
  3225. -4.31981353384978172816e-01, -4.31842753301111881292e-01,
  3226. -4.31704222447754082381e-01, -4.31565751723078538937e-01,
  3227. -4.31427351232775313505e-01, -4.31289023183523967386e-01,
  3228. -4.31150748642916026299e-01, -4.31012556430421800435e-01,
  3229. -4.30874417255794339709e-01, -4.30736352405325817472e-01,
  3230. -4.30598350727577461328e-01, -4.30460413190271118378e-01,
  3231. -4.30322547073958339148e-01, -4.30184744640451977027e-01,
  3232. -4.30047007210207721251e-01, -4.29909337239590294555e-01,
  3233. -4.29771734758555123967e-01, -4.29634197190916888864e-01,
  3234. -4.29496723635589494616e-01, -4.29359320273103528542e-01,
  3235. -4.29221974458292798715e-01, -4.29084708239550083331e-01,
  3236. -4.28947490771954986766e-01, -4.28810356331569053623e-01,
  3237. -4.28673276890164822728e-01, -4.28536263229363001415e-01,
  3238. -4.28399322602652121716e-01, -4.28262437566197862182e-01,
  3239. -4.28125625938365672596e-01, -4.27988878593011767837e-01,
  3240. -4.27852191864603992322e-01, -4.27715578365543303008e-01,
  3241. -4.27579024839372157096e-01, -4.27442538171905417332e-01,
  3242. -4.27306115252213791766e-01, -4.27169761638197587050e-01,
  3243. -4.27033469385057595780e-01, -4.26897242362347606459e-01,
  3244. -4.26761084212522345815e-01, -4.26624987672080846490e-01,
  3245. -4.26488955800829794285e-01, -4.26352994798914308738e-01,
  3246. -4.26217087981818953946e-01, -4.26081262359846446586e-01,
  3247. -4.25945482455656998511e-01, -4.25809784937209889755e-01,
  3248. -4.25674136841104333584e-01, -4.25538566297759102142e-01,
  3249. -4.25403049628253704384e-01, -4.25267608714368750000e-01,
  3250. -4.25132224411385206686e-01, -4.24996906712915012427e-01,
  3251. -4.24861657140971293867e-01, -4.24726470789760501834e-01,
  3252. -4.24591343408701860085e-01, -4.24456285730042126580e-01,
  3253. -4.24321292602986122056e-01, -4.24186362722597742891e-01,
  3254. -4.24051495283545076820e-01, -4.23916694812093208800e-01,
  3255. -4.23781955184383107849e-01, -4.23647285193715694707e-01,
  3256. -4.23512678142488330213e-01, -4.23378129676068470921e-01,
  3257. -4.23243652734718089903e-01, -4.23109233439634191409e-01,
  3258. -4.22974880838154820850e-01, -4.22840594971471805952e-01,
  3259. -4.22706366627480289999e-01, -4.22572210261666414421e-01,
  3260. -4.22438110791802323707e-01, -4.22304080563701000894e-01,
  3261. -4.22170107628079882556e-01, -4.22036205084515114727e-01,
  3262. -4.21902366011597140805e-01, -4.21768582643646250396e-01,
  3263. -4.21634870613048051702e-01, -4.21501219859424458569e-01,
  3264. -4.21367632640160527657e-01, -4.21234109986093563371e-01,
  3265. -4.21100645516489680009e-01, -4.20967252547576220589e-01,
  3266. -4.20833917722789996319e-01, -4.20700647624544010750e-01,
  3267. -4.20567440455620111806e-01, -4.20434296822478292821e-01,
  3268. -4.20301216096496510488e-01, -4.20168200185702556126e-01,
  3269. -4.20035242086608417988e-01, -4.19902356729265902047e-01,
  3270. -4.19769524924569870095e-01, -4.19636763795404710287e-01,
  3271. -4.19504057566950971925e-01, -4.19371418687989383489e-01,
  3272. -4.19238846665829001381e-01, -4.19106331022453093560e-01,
  3273. -4.18973880635006290518e-01, -4.18841492824669647810e-01,
  3274. -4.18709169429573591081e-01, -4.18576905776015473215e-01,
  3275. -4.18444707544804173072e-01, -4.18312567862278439357e-01,
  3276. -4.18180497366403225445e-01, -4.18048482730721870926e-01,
  3277. -4.17916533095482711779e-01, -4.17784647577891687931e-01,
  3278. -4.17652820568875982055e-01, -4.17521064211650472231e-01,
  3279. -4.17389357894170531793e-01, -4.17257727217915985740e-01,
  3280. -4.17126146268366360115e-01, -4.16994637222769082285e-01,
  3281. -4.16863181990139164412e-01, -4.16731797229556111262e-01,
  3282. -4.16600467923299966344e-01, -4.16469203955557143448e-01,
  3283. -4.16338003159045233481e-01, -4.16206864318706237782e-01,
  3284. -4.16075783286184552878e-01, -4.15944766694088974290e-01,
  3285. -4.15813814512082768893e-01, -4.15682920228903296511e-01,
  3286. -4.15552087568195671619e-01, -4.15421319322513860062e-01,
  3287. -4.15290611773867390788e-01, -4.15159965825792676153e-01,
  3288. -4.15029381582135814543e-01, -4.14898857723975444944e-01,
  3289. -4.14768399423150135874e-01, -4.14637998487099423972e-01,
  3290. -4.14507660162483249078e-01, -4.14377382831094154270e-01,
  3291. -4.14247167719101527794e-01, -4.14117011540035551143e-01,
  3292. -4.13986926213605943570e-01, -4.13856889699186047960e-01,
  3293. -4.13726922360217130858e-01, -4.13597009487045419451e-01,
  3294. -4.13467167203102670126e-01, -4.13337379251928205282e-01,
  3295. -4.13207649832448620231e-01, -4.13077989581290716536e-01,
  3296. -4.12948385280632379590e-01, -4.12818845637522802150e-01,
  3297. -4.12689360217458056646e-01, -4.12559939699663091872e-01,
  3298. -4.12430585329354448820e-01, -4.12301281446441181266e-01,
  3299. -4.12172044742586951571e-01, -4.12042868814711638059e-01,
  3300. -4.11913751407601558263e-01, -4.11784696769319558118e-01,
  3301. -4.11655701338700052982e-01, -4.11526763936471140504e-01,
  3302. -4.11397892840885515131e-01, -4.11269078469947424459e-01,
  3303. -4.11140328521643949600e-01, -4.11011632961894024518e-01,
  3304. -4.10883001877293430049e-01, -4.10754427307281178017e-01,
  3305. -4.10625919831635100010e-01, -4.10497467443546093513e-01,
  3306. -4.10369074062860494934e-01, -4.10240747192873400628e-01,
  3307. -4.10112475252298658290e-01, -4.09984263535373982812e-01,
  3308. -4.09856113622305340272e-01, -4.09728025073901991338e-01,
  3309. -4.09599998066721149304e-01, -4.09472021157853860451e-01,
  3310. -4.09344117590636047410e-01, -4.09216261713988505022e-01,
  3311. -4.09088477009537043738e-01, -4.08960739905341819078e-01,
  3312. -4.08833076504052150835e-01, -4.08705461846365136758e-01,
  3313. -4.08577913787489366282e-01, -4.08450419393505292920e-01,
  3314. -4.08322990193140944459e-01, -4.08195615357145324964e-01,
  3315. -4.08068304322052877176e-01, -4.07941052522718949902e-01,
  3316. -4.07813857607316032627e-01, -4.07686722372428311800e-01,
  3317. -4.07559649159417780595e-01, -4.07432636982122509117e-01,
  3318. -4.07305676267957994519e-01, -4.07178783941681832204e-01,
  3319. -4.07051946580331669434e-01, -4.06925167423387412757e-01,
  3320. -4.06798446935890845033e-01, -4.06671791194066489794e-01,
  3321. -4.06545186603844865836e-01, -4.06418647937667909531e-01,
  3322. -4.06292163227448155371e-01, -4.06165743221352681935e-01,
  3323. -4.06039379246542819768e-01, -4.05913072894464155294e-01,
  3324. -4.05786826472172346136e-01, -4.05660640335870792406e-01,
  3325. -4.05534510753690069507e-01, -4.05408441121033802368e-01,
  3326. -4.05282432764027089611e-01, -4.05156476982766022843e-01,
  3327. -4.05030584899000456467e-01, -4.04904754253246346174e-01,
  3328. -4.04778971785819452478e-01, -4.04653259267328757609e-01,
  3329. -4.04527598754375772305e-01, -4.04401995546463499664e-01,
  3330. -4.04276457564847535586e-01, -4.04150970176745560902e-01,
  3331. -4.04025550464417959606e-01, -4.03900178259218922694e-01,
  3332. -4.03774872449987054512e-01, -4.03649622353497550264e-01,
  3333. -4.03524429462068900953e-01, -4.03399298489652113897e-01,
  3334. -4.03274220263995841762e-01, -4.03149204408413008860e-01,
  3335. -4.03024243953643779292e-01, -4.02899345977544842690e-01,
  3336. -4.02774500313819894259e-01, -4.02649718198055062146e-01,
  3337. -4.02524987205944762003e-01, -4.02400323447383079234e-01,
  3338. -4.02275708434712164774e-01, -4.02151155305185303845e-01,
  3339. -4.02026663525060001803e-01, -4.01902222092053285074e-01,
  3340. -4.01777842021426634389e-01, -4.01653523782029453493e-01,
  3341. -4.01529254483203368320e-01, -4.01405051691118952562e-01,
  3342. -4.01280902735236921774e-01, -4.01156807203930376726e-01,
  3343. -4.01032779414245976746e-01, -4.00908796037237169507e-01,
  3344. -4.00784880192289361123e-01, -4.00661018610160790665e-01,
  3345. -4.00537218896692692738e-01, -4.00413463897760724119e-01,
  3346. -4.00289781096409003069e-01, -4.00166144769810827597e-01,
  3347. -4.00042574446873522298e-01, -3.99919051262408564718e-01,
  3348. -3.99795597620649201254e-01, -3.99672187473334661334e-01,
  3349. -3.99548846729920414944e-01, -3.99425553680199330042e-01,
  3350. -3.99302324552061438379e-01, -3.99179149671766264618e-01,
  3351. -3.99056029154643832069e-01, -3.98932972213114744875e-01,
  3352. -3.98809964233907909836e-01, -3.98687020930074687008e-01,
  3353. -3.98564127590293748593e-01, -3.98441293819186026504e-01,
  3354. -3.98318518261330523078e-01, -3.98195796733791018696e-01,
  3355. -3.98073136147862105538e-01, -3.97950524217172363350e-01,
  3356. -3.97827980824171201224e-01, -3.97705483428916706234e-01,
  3357. -3.97583046429371866903e-01, -3.97460668301239106182e-01,
  3358. -3.97338340743746409878e-01, -3.97216076132537621035e-01,
  3359. -3.97093866793421013117e-01, -3.96971708695779135212e-01,
  3360. -3.96849614460402178029e-01, -3.96727571162359238244e-01,
  3361. -3.96605584352971551887e-01, -3.96483655927755584969e-01,
  3362. -3.96361783929194744225e-01, -3.96239963115969096030e-01,
  3363. -3.96118205235003517650e-01, -3.95996502067531230828e-01,
  3364. -3.95874852389952291976e-01, -3.95753258139562358320e-01,
  3365. -3.95631723966650583613e-01, -3.95510240508634480783e-01,
  3366. -3.95388818213813331148e-01, -3.95267447003314842391e-01,
  3367. -3.95146134392586834139e-01, -3.95024882750451555857e-01,
  3368. -3.94903675086172745168e-01, -3.94782532290389842622e-01,
  3369. -3.94661443670635547765e-01, -3.94540408754397275981e-01,
  3370. -3.94419428948322492445e-01, -3.94298510274204649928e-01,
  3371. -3.94177638414093090002e-01, -3.94056831090384751537e-01,
  3372. -3.93936076434925896983e-01, -3.93815370670321740487e-01,
  3373. -3.93694729598434378648e-01, -3.93574138492694181046e-01,
  3374. -3.93453606929904053935e-01, -3.93333122505293453219e-01,
  3375. -3.93212702909399636209e-01, -3.93092334488327865838e-01,
  3376. -3.92972020639507368944e-01, -3.92851761427115364622e-01,
  3377. -3.92731564372885089131e-01, -3.92611410501577051679e-01,
  3378. -3.92491323488932619679e-01, -3.92371283486580180178e-01,
  3379. -3.92251301508781347049e-01, -3.92131375698602735458e-01,
  3380. -3.92011502469516659453e-01, -3.91891686848696019219e-01,
  3381. -3.91771923489848072908e-01, -3.91652217575099825808e-01,
  3382. -3.91532564898107005025e-01, -3.91412965926249023507e-01,
  3383. -3.91293422996351725196e-01, -3.91173937469604160455e-01,
  3384. -3.91054501564423617754e-01, -3.90935122694210157590e-01,
  3385. -3.90815801338688262323e-01, -3.90696528165559997525e-01,
  3386. -3.90577317672550716754e-01, -3.90458154728669848410e-01,
  3387. -3.90339051832541139575e-01, -3.90219996472402241849e-01,
  3388. -3.90101003844937177512e-01, -3.89982059202784614449e-01,
  3389. -3.89863172811093283698e-01, -3.89744340708371272974e-01,
  3390. -3.89625557299567049085e-01, -3.89506837750507151075e-01,
  3391. -3.89388160520550086208e-01, -3.89269551902951205236e-01,
  3392. -3.89150984144685740951e-01, -3.89032474909371484006e-01,
  3393. -3.88914025999045953608e-01, -3.88795623717812122155e-01,
  3394. -3.88677276343736721742e-01, -3.88558986812192252991e-01,
  3395. -3.88440746279492155058e-01, -3.88322564833268879525e-01,
  3396. -3.88204433318420472077e-01, -3.88086355915981284781e-01,
  3397. -3.87968336232786370488e-01, -3.87850366836331561515e-01,
  3398. -3.87732451498057573147e-01, -3.87614593740575663627e-01,
  3399. -3.87496786877871923771e-01, -3.87379031779648164147e-01,
  3400. -3.87261331653111495754e-01, -3.87143683975602670433e-01,
  3401. -3.87026095630551292270e-01, -3.86908552782769032952e-01,
  3402. -3.86791070361966748958e-01, -3.86673636012102694970e-01,
  3403. -3.86556261875890649904e-01, -3.86438934090259422760e-01,
  3404. -3.86321662437166923887e-01, -3.86204444003594771218e-01,
  3405. -3.86087280659658360626e-01, -3.85970167837914435172e-01,
  3406. -3.85853110762150119939e-01, -3.85736104280530900379e-01,
  3407. -3.85619152600736536662e-01, -3.85502255219753564575e-01,
  3408. -3.85385409941956580404e-01, -3.85268614876988935158e-01,
  3409. -3.85151879781903239142e-01, -3.85035189870587046812e-01,
  3410. -3.84918561002825287964e-01, -3.84801978053202931029e-01,
  3411. -3.84685452135982874911e-01, -3.84568976271269957756e-01,
  3412. -3.84452556088511587795e-01, -3.84336187225683634239e-01,
  3413. -3.84219870325564816227e-01, -3.84103607179063666344e-01,
  3414. -3.83987401155638841121e-01, -3.83871236986547181846e-01,
  3415. -3.83755138849689481084e-01, -3.83639081181560870348e-01,
  3416. -3.83523086178925165513e-01, -3.83407135321715386578e-01,
  3417. -3.83291246965823451109e-01, -3.83175399735360855402e-01,
  3418. -3.83059616074506559258e-01, -3.82943872285916475651e-01,
  3419. -3.82828196011304522361e-01, -3.82712556260513536710e-01,
  3420. -3.82596982297232990344e-01, -3.82481455112087642689e-01,
  3421. -3.82365976775404958765e-01, -3.82250558015250652133e-01,
  3422. -3.82135187376646978663e-01, -3.82019866423826903734e-01,
  3423. -3.81904600354835643827e-01, -3.81789389165001602500e-01,
  3424. -3.81674227674965782509e-01, -3.81559114255094145030e-01,
  3425. -3.81444060603281509536e-01, -3.81329055085196044761e-01,
  3426. -3.81214099012656737475e-01, -3.81099198772719693906e-01,
  3427. -3.80984349857083404167e-01, -3.80869552736027128237e-01,
  3428. -3.80754810036734891998e-01, -3.80640110780191776030e-01,
  3429. -3.80525473903531141762e-01, -3.80410879340718488528e-01,
  3430. -3.80296343715274709485e-01, -3.80181854126763640878e-01,
  3431. -3.80067423201666698684e-01, -3.79953035686236617607e-01,
  3432. -3.79838706441368301192e-01, -3.79724424804841864667e-01,
  3433. -3.79610196212900707913e-01, -3.79496020758661178895e-01,
  3434. -3.79381892633415152005e-01, -3.79267823803007442240e-01,
  3435. -3.79153794564509094567e-01, -3.79039827060307366047e-01,
  3436. -3.78925908303136715904e-01, -3.78812034572059530557e-01,
  3437. -3.78698222562220077059e-01, -3.78584453917463370498e-01,
  3438. -3.78470740663781501922e-01, -3.78357075405102438737e-01,
  3439. -3.78243464523851213865e-01, -3.78129901062271123191e-01,
  3440. -3.78016395293092943852e-01, -3.77902935434891784627e-01,
  3441. -3.77789524813024024663e-01, -3.77676173083359656424e-01,
  3442. -3.77562860648804621277e-01, -3.77449611538380969122e-01,
  3443. -3.77336405112449480015e-01, -3.77223255197060902688e-01,
  3444. -3.77110149479393752525e-01, -3.76997101032941372978e-01,
  3445. -3.76884103404164561013e-01, -3.76771146981984883517e-01,
  3446. -3.76658254312513096629e-01, -3.76545400701739807481e-01,
  3447. -3.76432606500236743852e-01, -3.76319859703210468638e-01,
  3448. -3.76207165627520656592e-01, -3.76094515010522989495e-01,
  3449. -3.75981928410063170887e-01, -3.75869377560886674949e-01,
  3450. -3.75756887910940862163e-01, -3.75644441813044516199e-01,
  3451. -3.75532050880362955336e-01, -3.75419708659158191111e-01,
  3452. -3.75307418175345186562e-01, -3.75195173779002910663e-01,
  3453. -3.75082983868028740915e-01, -3.74970842852496988318e-01,
  3454. -3.74858753518341469846e-01, -3.74746710311752939671e-01,
  3455. -3.74634721486163280169e-01, -3.74522781933396164966e-01,
  3456. -3.74410892656854399352e-01, -3.74299054751102588945e-01,
  3457. -3.74187262834480116602e-01, -3.74075526163193505802e-01,
  3458. -3.73963835445819015035e-01, -3.73852196240103518132e-01,
  3459. -3.73740606782354212179e-01, -3.73629068569595379490e-01,
  3460. -3.73517577377422416163e-01, -3.73406137430558726642e-01,
  3461. -3.73294747230386358972e-01, -3.73183408546653716531e-01,
  3462. -3.73072115798985137758e-01, -3.72960878363263692581e-01,
  3463. -3.72849686668074831175e-01, -3.72738547271451448051e-01,
  3464. -3.72627454688548187534e-01, -3.72516413124841627713e-01,
  3465. -3.72405422419142928536e-01, -3.72294479010730039459e-01,
  3466. -3.72183586127809384880e-01, -3.72072745594147935577e-01,
  3467. -3.71961946886472105689e-01, -3.71851207922366477909e-01,
  3468. -3.71740512258250443978e-01, -3.71629863047378439234e-01,
  3469. -3.71519275296183892898e-01, -3.71408719353291283394e-01,
  3470. -3.71298231762544284074e-01, -3.71187774231039768758e-01,
  3471. -3.71077385155450356624e-01, -3.70967027473084853817e-01,
  3472. -3.70856732806939093372e-01, -3.70746478782946531361e-01,
  3473. -3.70636278570893540341e-01, -3.70526124217443408870e-01,
  3474. -3.70416023190285881306e-01, -3.70305964747868754383e-01,
  3475. -3.70195962036970249720e-01, -3.70086006739641537600e-01,
  3476. -3.69976096629158424101e-01, -3.69866237754495619239e-01,
  3477. -3.69756430498219990088e-01, -3.69646667281089635892e-01,
  3478. -3.69536955685763390811e-01, -3.69427295312589665244e-01,
  3479. -3.69317680177515983431e-01, -3.69208112264662047242e-01,
  3480. -3.69098600797472087276e-01, -3.68989129249791547593e-01,
  3481. -3.68879709799311061857e-01, -3.68770343789034893422e-01,
  3482. -3.68661013669255632763e-01, -3.68551743592315017573e-01,
  3483. -3.68442521553778989940e-01, -3.68333337891429413169e-01,
  3484. -3.68224220906830435052e-01, -3.68115134111169917119e-01,
  3485. -3.68006105751164325213e-01, -3.67897126383986028397e-01,
  3486. -3.67788183182486683176e-01, -3.67679314546345559211e-01,
  3487. -3.67570457935090466606e-01, -3.67461679824609310785e-01,
  3488. -3.67352933314014973298e-01, -3.67244250124000692903e-01,
  3489. -3.67135594976164825187e-01, -3.67027010208194726104e-01,
  3490. -3.66918451154709834849e-01, -3.66809964732578319691e-01,
  3491. -3.66701497346674842870e-01, -3.66593104701923799826e-01,
  3492. -3.66484751684203469146e-01, -3.66376433638109233470e-01,
  3493. -3.66268181947639936968e-01, -3.66159965139171650339e-01,
  3494. -3.66051810667975985325e-01, -3.65943684890073561711e-01,
  3495. -3.65835627870885249369e-01, -3.65727602399674167621e-01,
  3496. -3.65619627846999917242e-01, -3.65511708644844168781e-01,
  3497. -3.65403830046463040659e-01, -3.65296001903366029939e-01,
  3498. -3.65188221908001264815e-01, -3.65080489439066679935e-01,
  3499. -3.64972809289322408510e-01, -3.64865162909030149585e-01,
  3500. -3.64757575000899281203e-01, -3.64650032359055575881e-01,
  3501. -3.64542540752545218830e-01, -3.64435090311057752199e-01,
  3502. -3.64327692395046587315e-01, -3.64220333784750771589e-01,
  3503. -3.64113033647018968786e-01, -3.64005773237700502865e-01,
  3504. -3.63898563663066054730e-01, -3.63791401593925867175e-01,
  3505. -3.63684289240767788520e-01, -3.63577221090830182693e-01,
  3506. -3.63470194632930121426e-01, -3.63363225424560787324e-01,
  3507. -3.63256298450416181822e-01, -3.63149413510743368505e-01,
  3508. -3.63042586419860147107e-01, -3.62935798823731892160e-01,
  3509. -3.62829063620695724257e-01, -3.62722369923179577267e-01,
  3510. -3.62615726031392693329e-01, -3.62509131983811849764e-01,
  3511. -3.62402579326320917197e-01, -3.62296079485166233614e-01,
  3512. -3.62189617561219312503e-01, -3.62083219373006803821e-01,
  3513. -3.61976841249034064774e-01, -3.61870542649785575939e-01,
  3514. -3.61764263515268802429e-01, -3.61658050514519047169e-01,
  3515. -3.61551866438354907451e-01, -3.61445746399240541713e-01,
  3516. -3.61339654211726535316e-01, -3.61233632449921238106e-01,
  3517. -3.61127636409807606377e-01, -3.61021690574636122673e-01,
  3518. -3.60915808770648049997e-01, -3.60809955913110880221e-01,
  3519. -3.60704146756004706553e-01, -3.60598402071625190324e-01,
  3520. -3.60492691072034687760e-01, -3.60387026729721449136e-01,
  3521. -3.60281410294411297279e-01, -3.60175846146454869956e-01,
  3522. -3.60070315514724181849e-01, -3.59964844399896066740e-01,
  3523. -3.59859414625616935712e-01, -3.59754028193141062175e-01,
  3524. -3.59648695273804441808e-01, -3.59543395532750997834e-01,
  3525. -3.59438155434585460135e-01, -3.59332956510969636632e-01,
  3526. -3.59227801467168927907e-01, -3.59122697950459535132e-01,
  3527. -3.59017635018213099318e-01, -3.58912626441924731413e-01,
  3528. -3.58807650429984748008e-01, -3.58702735673852635134e-01,
  3529. -3.58597856254525837461e-01, -3.58493020101329329385e-01,
  3530. -3.58388243767708281062e-01, -3.58283497814040119422e-01,
  3531. -3.58178816390144483250e-01, -3.58074159391590651769e-01,
  3532. -3.57969563679315316840e-01, -3.57865011320968928743e-01,
  3533. -3.57760492481530301134e-01, -3.57656042081691105672e-01,
  3534. -3.57551619680673171686e-01, -3.57447240362188889407e-01,
  3535. -3.57342928935650006039e-01, -3.57238638134922736889e-01,
  3536. -3.57134398104680117481e-01, -3.57030224939330231848e-01,
  3537. -3.56926068820051678454e-01, -3.56821978817270957229e-01,
  3538. -3.56717920226812923445e-01, -3.56613915739726006215e-01,
  3539. -3.56509953999475215358e-01, -3.56406035389410180692e-01,
  3540. -3.56302169732667595170e-01, -3.56198339705092570373e-01,
  3541. -3.56094560076684607530e-01, -3.55990833795084338220e-01,
  3542. -3.55887134299729290809e-01, -3.55783497830003514473e-01,
  3543. -3.55679895395900946831e-01, -3.55576339662835527733e-01,
  3544. -3.55472831310899628487e-01, -3.55369377306052169896e-01,
  3545. -3.55265949104364819888e-01, -3.55162586860366058517e-01,
  3546. -3.55059247906838293396e-01, -3.54955973351155584794e-01,
  3547. -3.54852730838006835690e-01, -3.54749541626036890563e-01,
  3548. -3.54646397739461272103e-01, -3.54543287471030810210e-01,
  3549. -3.54440243273785093869e-01, -3.54337214098040198529e-01,
  3550. -3.54234259930783779158e-01, -3.54131325984198830348e-01,
  3551. -3.54028459663857986151e-01, -3.53925615542254046186e-01,
  3552. -3.53822838516876625459e-01, -3.53720083832240850263e-01,
  3553. -3.53617396205830325506e-01, -3.53514730930161669153e-01,
  3554. -3.53412132710718696060e-01, -3.53309556840015970280e-01,
  3555. -3.53207048035544479703e-01, -3.53104561541793093848e-01,
  3556. -3.53002142256347628546e-01, -3.52899744751343780180e-01,
  3557. -3.52797416433685007142e-01, -3.52695102510589719724e-01,
  3558. -3.52592862987571531441e-01, -3.52490646745808322571e-01,
  3559. -3.52388486496365838097e-01, -3.52286369569029089721e-01,
  3560. -3.52184291581849773234e-01, -3.52082260381094913626e-01,
  3561. -3.51980271315386394892e-01, -3.51878335143969156462e-01,
  3562. -3.51776435832983791485e-01, -3.51674582055139683945e-01,
  3563. -3.51572777505199940418e-01, -3.51470998731403250215e-01,
  3564. -3.51369291142547612861e-01, -3.51267608313911683382e-01,
  3565. -3.51165978776873832778e-01, -3.51064379534125281523e-01,
  3566. -3.50962851691780874930e-01, -3.50861343229657896003e-01,
  3567. -3.50759887011921178690e-01, -3.50658470657319421004e-01,
  3568. -3.50557110826692830408e-01, -3.50455775609674113902e-01,
  3569. -3.50354508931666697169e-01, -3.50253256408391167032e-01,
  3570. -3.50152079892852796661e-01, -3.50050920467760762200e-01,
  3571. -3.49949817838822341276e-01, -3.49848761507466687881e-01,
  3572. -3.49747731410527840090e-01, -3.49646773595756688024e-01,
  3573. -3.49545835694024864537e-01, -3.49444947023644092443e-01,
  3574. -3.49344109735721275456e-01, -3.49243308259259088722e-01,
  3575. -3.49142558023655735777e-01, -3.49041835234058184234e-01,
  3576. -3.48941174936996667544e-01, -3.48840550148169781242e-01,
  3577. -3.48739966703028425599e-01, -3.48639428244070015417e-01,
  3578. -3.48538936717595504433e-01, -3.48438480695904329032e-01,
  3579. -3.48338081591755166500e-01, -3.48237709885298063472e-01,
  3580. -3.48137395187948728292e-01, -3.48037115629119542248e-01,
  3581. -3.47936884376261690299e-01, -3.47836692981899731070e-01,
  3582. -3.47736539716742620865e-01, -3.47636439945430031351e-01,
  3583. -3.47536378642177512521e-01, -3.47436355842000332839e-01,
  3584. -3.47336386430620702725e-01, -3.47236455533619481351e-01,
  3585. -3.47136563059466607406e-01, -3.47036724248701466955e-01,
  3586. -3.46936922934180436151e-01, -3.46837163840455153796e-01,
  3587. -3.46737444236461800351e-01, -3.46637770321905347437e-01,
  3588. -3.46538142380770852746e-01, -3.46438553077413002868e-01,
  3589. -3.46339009118686147470e-01, -3.46239513364560103081e-01,
  3590. -3.46140047668301253925e-01, -3.46040637053390887079e-01,
  3591. -3.45941266627862842320e-01, -3.45841926232616447834e-01,
  3592. -3.45742649044279204418e-01, -3.45643401922408499694e-01,
  3593. -3.45544194845180674402e-01, -3.45445043392074546684e-01,
  3594. -3.45345919970482029271e-01, -3.45246852316131280780e-01,
  3595. -3.45147824133942959790e-01, -3.45048828165022802850e-01,
  3596. -3.44949887388285747480e-01, -3.44850984202191124250e-01,
  3597. -3.44752121330503147334e-01, -3.44653305479706351111e-01,
  3598. -3.44554529451839786081e-01, -3.44455792980520536517e-01,
  3599. -3.44357104329241270335e-01, -3.44258453062156466462e-01,
  3600. -3.44159850307413472947e-01, -3.44061284340010375971e-01,
  3601. -3.43962768580065580970e-01, -3.43864283423849115273e-01,
  3602. -3.43765849162678938100e-01, -3.43667448938496766786e-01,
  3603. -3.43569107540475926488e-01, -3.43470787373464980785e-01,
  3604. -3.43372524621929409161e-01, -3.43274301550125615634e-01,
  3605. -3.43176108213079089637e-01, -3.43077979774689567627e-01,
  3606. -3.42979874931300110497e-01, -3.42881811974929173736e-01,
  3607. -3.42783803744644011147e-01, -3.42685825295640233978e-01,
  3608. -3.42587896512843437247e-01, -3.42490007504838600561e-01,
  3609. -3.42392155600618419697e-01, -3.42294361375627742561e-01,
  3610. -3.42196589902577508191e-01, -3.42098870908211949438e-01,
  3611. -3.42001187468069178799e-01, -3.41903555201509778971e-01,
  3612. -3.41805950907295763574e-01, -3.41708407067534913892e-01,
  3613. -3.41610884010259296950e-01, -3.41513418534265589255e-01,
  3614. -3.41415992523302125328e-01, -3.41318596940095919656e-01,
  3615. -3.41221263698247956331e-01, -3.41123941235853045395e-01,
  3616. -3.41026692128222064238e-01, -3.40929474098209284172e-01,
  3617. -3.40832281920377677675e-01, -3.40735156421879237243e-01,
  3618. -3.40638051278251974274e-01, -3.40540999201483007841e-01,
  3619. -3.40443982723311333594e-01, -3.40347016653051559487e-01,
  3620. -3.40250081573448603933e-01, -3.40153195640724492765e-01,
  3621. -3.40056350350729230669e-01, -3.39959539212099759453e-01,
  3622. -3.39862774342696183361e-01, -3.39766058465924336573e-01,
  3623. -3.39669368570301832833e-01, -3.39572726923125789433e-01,
  3624. -3.39476134521916550479e-01, -3.39379565109294734082e-01,
  3625. -3.39283055662032762001e-01, -3.39186573937387048083e-01,
  3626. -3.39090144874334475933e-01, -3.38993745663194734341e-01,
  3627. -3.38897397900228047884e-01, -3.38801082713558243675e-01,
  3628. -3.38704809290945374478e-01, -3.38608582104967581472e-01,
  3629. -3.38512396429294426525e-01, -3.38416244344927230614e-01,
  3630. -3.38320139902449357194e-01, -3.38224079522009613008e-01,
  3631. -3.38128041120687727883e-01, -3.38032071906532505245e-01,
  3632. -3.37936116888977844397e-01, -3.37840214711788655588e-01,
  3633. -3.37744355197438450578e-01, -3.37648540412268438615e-01,
  3634. -3.37552749916698147103e-01, -3.37457018699225064218e-01,
  3635. -3.37361316652406650896e-01, -3.37265662162290202897e-01,
  3636. -3.37170034143870922527e-01, -3.37074476199379025054e-01,
  3637. -3.36978924411865332633e-01, -3.36883434384704194553e-01,
  3638. -3.36787981731797914087e-01, -3.36692563690679236288e-01,
  3639. -3.36597193345572975876e-01, -3.36501865825531210064e-01,
  3640. -3.36406565178378635927e-01, -3.36311315380280917431e-01,
  3641. -3.36216103533976129469e-01, -3.36120934900604684259e-01,
  3642. -3.36025801332866413951e-01, -3.35930707807079897975e-01,
  3643. -3.35835664917012943764e-01, -3.35740647663017532931e-01,
  3644. -3.35645678394692614788e-01, -3.35550759768515505233e-01,
  3645. -3.35455858808978324426e-01, -3.35361015354667779675e-01,
  3646. -3.35266214785454208513e-01, -3.35171431039785638895e-01,
  3647. -3.35076715928774748754e-01, -3.34982022379972488313e-01,
  3648. -3.34887375113354646139e-01, -3.34792767024950199684e-01,
  3649. -3.34698201810667450573e-01, -3.34603671790843826273e-01,
  3650. -3.34509181636480468214e-01, -3.34414742694976452331e-01,
  3651. -3.34320327257476346272e-01, -3.34225967756777042617e-01,
  3652. -3.34131629225772386338e-01, -3.34037352044864510603e-01,
  3653. -3.33943099066518034324e-01, -3.33848889093505241110e-01,
  3654. -3.33754728765755959152e-01, -3.33660595072520660409e-01,
  3655. -3.33566506361641812450e-01, -3.33472456955982987648e-01,
  3656. -3.33378451216247595479e-01, -3.33284477376757704015e-01,
  3657. -3.33190555787780562369e-01, -3.33096661517408021425e-01,
  3658. -3.33002806887780833378e-01, -3.32909012245727220503e-01,
  3659. -3.32815228585277400608e-01, -3.32721497473031146974e-01,
  3660. -3.32627813407268324575e-01, -3.32534156828269700235e-01,
  3661. -3.32440544421407024878e-01, -3.32346973708396109526e-01,
  3662. -3.32253437917002014679e-01, -3.32159944262706452456e-01,
  3663. -3.32066493007559804251e-01, -3.31973075887878610324e-01,
  3664. -3.31879703344604704007e-01, -3.31786364229395891456e-01,
  3665. -3.31693070342937157413e-01, -3.31599807982572825082e-01,
  3666. -3.31506597806498937153e-01, -3.31413415588069915074e-01,
  3667. -3.31320270520447546225e-01, -3.31227172409371162232e-01,
  3668. -3.31134117542206174445e-01, -3.31041088612008760350e-01,
  3669. -3.30948113855706105291e-01, -3.30855164687758329656e-01,
  3670. -3.30762260158172449742e-01, -3.30669397355943583960e-01,
  3671. -3.30576568875084519927e-01, -3.30483784898807253505e-01,
  3672. -3.30391034451992582355e-01, -3.30298328900163806754e-01,
  3673. -3.30205656108088330125e-01, -3.30113030899431780796e-01,
  3674. -3.30020428466505866272e-01, -3.29927888512914768704e-01,
  3675. -3.29835366438896882002e-01, -3.29742889181185772074e-01,
  3676. -3.29650460647833876138e-01, -3.29558060621639892229e-01,
  3677. -3.29465699008131440717e-01, -3.29373378754140522240e-01,
  3678. -3.29281100518553915268e-01, -3.29188858718991950170e-01,
  3679. -3.29096652674345069300e-01, -3.29004490691431061844e-01,
  3680. -3.28912362575830508060e-01, -3.28820278446660896332e-01,
  3681. -3.28728230373613705684e-01, -3.28636217607063907398e-01,
  3682. -3.28544251075820137320e-01, -3.28452310166014393999e-01,
  3683. -3.28360421700826687896e-01, -3.28268566056630073380e-01,
  3684. -3.28176750201269351592e-01, -3.28084965886991819506e-01,
  3685. -3.27993239136963599112e-01, -3.27901518809756153949e-01,
  3686. -3.27809871689208831569e-01, -3.27718238243585369140e-01,
  3687. -3.27626655705541003361e-01, -3.27535101731415645432e-01,
  3688. -3.27443606111453289209e-01, -3.27352116731821241036e-01,
  3689. -3.27260700498897660893e-01, -3.27169298363194804846e-01,
  3690. -3.27077945505835132600e-01, -3.26986627307041588519e-01,
  3691. -3.26895344713058144670e-01, -3.26804108558686245978e-01,
  3692. -3.26712896910217709401e-01, -3.26621741964200240638e-01,
  3693. -3.26530603923376738784e-01, -3.26439520373260516628e-01,
  3694. -3.26348470176022864564e-01, -3.26257455593981449127e-01,
  3695. -3.26166488715694480316e-01, -3.26075541276352964815e-01,
  3696. -3.25984647191409737665e-01, -3.25893788470829282033e-01,
  3697. -3.25802958455817581740e-01, -3.25712179419843927963e-01,
  3698. -3.25621435983050988572e-01, -3.25530722687914997326e-01,
  3699. -3.25440054392646616055e-01, -3.25349421825410378695e-01,
  3700. -3.25258824863596140986e-01, -3.25168273269479446430e-01,
  3701. -3.25077750468310389120e-01, -3.24987268293329634172e-01,
  3702. -3.24896818338065385134e-01, -3.24806422395165106387e-01,
  3703. -3.24716046403993874314e-01, -3.24625715407476533869e-01,
  3704. -3.24535430349774611791e-01, -3.24445162411316823103e-01,
  3705. -3.24354958871001297638e-01, -3.24264771191515699389e-01,
  3706. -3.24174634484502677267e-01, -3.24084523895929232928e-01,
  3707. -3.23994459026800851742e-01, -3.23904431030612116604e-01,
  3708. -3.23814433340637919390e-01, -3.23724478718542041378e-01,
  3709. -3.23634567387877880584e-01, -3.23544685692768452245e-01,
  3710. -3.23454843329684382791e-01, -3.23365037520362053058e-01,
  3711. -3.23275269681385146736e-01, -3.23185536924682992321e-01,
  3712. -3.23095849385954259070e-01, -3.23006191762216565699e-01,
  3713. -3.22916570426217852674e-01, -3.22826997541689753035e-01,
  3714. -3.22737440432700029014e-01, -3.22647950584020293263e-01,
  3715. -3.22558466491205841908e-01, -3.22469048576812467033e-01,
  3716. -3.22379650765513003918e-01, -3.22290285177351309986e-01,
  3717. -3.22200971759220133883e-01, -3.22111685658731161652e-01,
  3718. -3.22022439283318862024e-01, -3.21933230207375298271e-01,
  3719. -3.21844055725898692266e-01, -3.21754929084502649950e-01,
  3720. -3.21665822357477593219e-01, -3.21576766946822134585e-01,
  3721. -3.21487732225476996462e-01, -3.21398764596197317189e-01,
  3722. -3.21309798481988706520e-01, -3.21220893325880607616e-01,
  3723. -3.21132011043201326395e-01, -3.21043177474382601666e-01,
  3724. -3.20954372045852032169e-01, -3.20865606507984679752e-01,
  3725. -3.20776876784593933944e-01, -3.20688187430051785398e-01,
  3726. -3.20599524303056493402e-01, -3.20510917062701183866e-01,
  3727. -3.20422328269140743728e-01, -3.20333788615695058688e-01,
  3728. -3.20245279824155071324e-01, -3.20156799610553932656e-01,
  3729. -3.20068375388967318873e-01, -3.19979966842285912243e-01,
  3730. -3.19891618417902812155e-01, -3.19803282050323323116e-01,
  3731. -3.19714993795423230161e-01, -3.19626746902161973374e-01,
  3732. -3.19538532318825452272e-01, -3.19450348299827324716e-01,
  3733. -3.19362210879227226279e-01, -3.19274102369856094263e-01,
  3734. -3.19186032782846962341e-01, -3.19098002112579104406e-01,
  3735. -3.19010000370401891612e-01, -3.18922045164797218764e-01,
  3736. -3.18834120753971106410e-01, -3.18746227793134551121e-01,
  3737. -3.18658379403236935445e-01, -3.18570567148754091313e-01,
  3738. -3.18482789299091129109e-01, -3.18395038860409540504e-01,
  3739. -3.18307345538659025586e-01, -3.18219664559104442603e-01,
  3740. -3.18132033556027371546e-01, -3.18044436174004130358e-01,
  3741. -3.17956877848706076506e-01, -3.17869353192871351155e-01,
  3742. -3.17781855968134130386e-01, -3.17694416515219568709e-01,
  3743. -3.17606986764818577385e-01, -3.17519616894733069934e-01,
  3744. -3.17432266021773434872e-01, -3.17344958093929208065e-01,
  3745. -3.17257682905915439076e-01, -3.17170457330882504809e-01,
  3746. -3.17083246433255361296e-01, -3.16996083675216477893e-01,
  3747. -3.16908959550578739339e-01, -3.16821856270166013481e-01,
  3748. -3.16734809793386418164e-01, -3.16647783478750832753e-01,
  3749. -3.16560798525840403350e-01, -3.16473851481303192212e-01,
  3750. -3.16386934958965637676e-01, -3.16300059605132577456e-01,
  3751. -3.16213212572499902109e-01, -3.16126412252237365408e-01,
  3752. -3.16039642630453532224e-01, -3.15952904668060474691e-01,
  3753. -3.15866210535302172069e-01, -3.15779532942031593290e-01,
  3754. -3.15692924175109912444e-01, -3.15606314135948418098e-01,
  3755. -3.15519774469847580356e-01, -3.15433245156387542796e-01,
  3756. -3.15346760521496294327e-01, -3.15260310337106552936e-01,
  3757. -3.15173901189560234926e-01, -3.15087516961556401984e-01,
  3758. -3.15001170832473698091e-01, -3.14914870905581789629e-01,
  3759. -3.14828593940165324394e-01, -3.14742357740590783521e-01,
  3760. -3.14656159033590621110e-01, -3.14569993107869316784e-01,
  3761. -3.14483859730134152066e-01, -3.14397764544851576751e-01,
  3762. -3.14311707559190467443e-01, -3.14225683100008756909e-01,
  3763. -3.14139691500964324256e-01, -3.14053737100567498253e-01,
  3764. -3.13967824562860597926e-01, -3.13881930893164406982e-01,
  3765. -3.13796098702669945535e-01, -3.13710269948259234951e-01,
  3766. -3.13624500080762536047e-01, -3.13538759450427528819e-01,
  3767. -3.13453044150207804641e-01, -3.13367377106299582756e-01,
  3768. -3.13281737576189989181e-01, -3.13196140900250385997e-01,
  3769. -3.13110568811249823096e-01, -3.13025034334257767910e-01,
  3770. -3.12939548339710438274e-01, -3.12854076672535452719e-01,
  3771. -3.12768655675618789669e-01, -3.12683263539456357538e-01,
  3772. -3.12597906455694685146e-01, -3.12512581467251693290e-01,
  3773. -3.12427294210809725072e-01, -3.12342047448462556414e-01,
  3774. -3.12256824495153240129e-01, -3.12171644625531874429e-01,
  3775. -3.12086492129538983775e-01, -3.12001388221020192759e-01,
  3776. -3.11916308458136226633e-01, -3.11831262339173298503e-01,
  3777. -3.11746258664567232888e-01, -3.11661275086031142045e-01,
  3778. -3.11576347492792116167e-01, -3.11491444083196455939e-01,
  3779. -3.11406566767664649831e-01, -3.11321739706168554296e-01,
  3780. -3.11236931403625127768e-01, -3.11152176625169918367e-01,
  3781. -3.11067434860568758914e-01, -3.10982743978655606920e-01,
  3782. -3.10898082421296351185e-01, -3.10813453848709397853e-01,
  3783. -3.10728865178155511106e-01, -3.10644307432114907819e-01,
  3784. -3.10559787251664443097e-01, -3.10475287050015869017e-01,
  3785. -3.10390848181504308556e-01, -3.10306412222544181212e-01,
  3786. -3.10222037402692107921e-01, -3.10137683337757430468e-01,
  3787. -3.10053363927979830361e-01, -3.09969086308332530955e-01,
  3788. -3.09884830390425081159e-01, -3.09800624689362036346e-01,
  3789. -3.09716442288341387012e-01, -3.09632295284240965927e-01,
  3790. -3.09548184558093242291e-01, -3.09464116840632463834e-01,
  3791. -3.09380064327889392484e-01, -3.09296064449780638839e-01,
  3792. -3.09212084697576772285e-01, -3.09128150621053421343e-01,
  3793. -3.09044237233321195113e-01, -3.08960374228678003039e-01,
  3794. -3.08876534872047248115e-01, -3.08792729354212536208e-01,
  3795. -3.08708965998856610380e-01, -3.08625223672207793513e-01,
  3796. -3.08541533882186080895e-01, -3.08457858786108374272e-01,
  3797. -3.08374228839820352377e-01, -3.08290627117847271244e-01,
  3798. -3.08207068514500914791e-01, -3.08123532729750682080e-01,
  3799. -3.08040041365923500383e-01, -3.07956573017225843092e-01,
  3800. -3.07873147001021363334e-01, -3.07789752157132778798e-01,
  3801. -3.07706391457163164205e-01, -3.07623064174878169119e-01,
  3802. -3.07539770243611898515e-01, -3.07456510656262227421e-01,
  3803. -3.07373281507903273191e-01, -3.07290097425341190984e-01,
  3804. -3.07206926158018700512e-01, -3.07123815026133561989e-01,
  3805. -3.07040718758160802171e-01, -3.06957659361293877520e-01,
  3806. -3.06874638781767350437e-01, -3.06791649579191139097e-01,
  3807. -3.06708697217149606207e-01, -3.06625767281695216226e-01,
  3808. -3.06542889613291458240e-01, -3.06460026319258171945e-01,
  3809. -3.06377209722884624732e-01, -3.06294415478919834772e-01,
  3810. -3.06211663941594436356e-01, -3.06128942742720511205e-01,
  3811. -3.06046258649077307368e-01, -3.05963596961736250535e-01,
  3812. -3.05880987357890266054e-01, -3.05798392882921377112e-01,
  3813. -3.05715842271141458042e-01, -3.05633324595146305125e-01,
  3814. -3.05550832478499623246e-01, -3.05468384002608395189e-01,
  3815. -3.05385958921764844032e-01, -3.05303575433909624159e-01,
  3816. -3.05221225696471032407e-01, -3.05138900530053658322e-01,
  3817. -3.05056622143069278152e-01, -3.04974355584749501347e-01,
  3818. -3.04892151394531185638e-01, -3.04809954124143744902e-01,
  3819. -3.04727800916781976781e-01, -3.04645688054904606457e-01,
  3820. -3.04563593265481658001e-01, -3.04481542302949492740e-01,
  3821. -3.04399521477817680548e-01, -3.04317537441869623294e-01,
  3822. -3.04235577277462310164e-01, -3.04153663651642758303e-01,
  3823. -3.04071763517348936379e-01, -3.03989919340557523952e-01,
  3824. -3.03908083711389997994e-01, -3.03826314396417218600e-01,
  3825. -3.03744539497943111250e-01, -3.03662832377988356480e-01,
  3826. -3.03581127948359397184e-01, -3.03499479089358148443e-01,
  3827. -3.03417851126680404583e-01, -3.03336262822015090279e-01,
  3828. -3.03254696154652281237e-01, -3.03173182094001791853e-01,
  3829. -3.03091681838359272572e-01, -3.03010230218165088623e-01,
  3830. -3.02928793768587167889e-01, -3.02847404463288505383e-01,
  3831. -3.02766034927674398958e-01, -3.02684717982977136153e-01,
  3832. -3.02603416774087974339e-01, -3.02522156493241933806e-01,
  3833. -3.02440917930091424104e-01, -3.02359730382049940456e-01,
  3834. -3.02278562925036298203e-01, -3.02197420550994855226e-01,
  3835. -3.02116336567971321969e-01, -3.02035262158805495325e-01,
  3836. -3.01954225173641788160e-01, -3.01873230084287569319e-01,
  3837. -3.01792253505111407463e-01, -3.01711317451606231277e-01,
  3838. -3.01630424302656741098e-01, -3.01549542527231539957e-01,
  3839. -3.01468706463603908219e-01, -3.01387899696680117145e-01,
  3840. -3.01307131196819122376e-01, -3.01226381497679440713e-01,
  3841. -3.01145674790784356745e-01, -3.01065000831607143539e-01,
  3842. -3.00984354054990355110e-01, -3.00903744614347823383e-01,
  3843. -3.00823159812924179057e-01, -3.00742617932585165619e-01,
  3844. -3.00662103246106759968e-01, -3.00581615677035562939e-01,
  3845. -3.00501171258409083276e-01, -3.00420750638014544265e-01,
  3846. -3.00340370488181684916e-01, -3.00260005823546505255e-01,
  3847. -3.00179695209751074003e-01, -3.00099398776559167512e-01,
  3848. -3.00019148032305449370e-01, -2.99938923869113693854e-01,
  3849. -2.99858726506670170142e-01, -2.99778574174106249295e-01,
  3850. -2.99698438438693370856e-01, -2.99618347746989255320e-01,
  3851. -2.99538283800717064498e-01, -2.99458246642942627069e-01,
  3852. -2.99378254399679799569e-01, -2.99298279227290464632e-01,
  3853. -2.99218347319087918379e-01, -2.99138448800683021123e-01,
  3854. -2.99058574624576745116e-01, -2.98978726151670703981e-01,
  3855. -2.98898929337599650324e-01, -2.98819146054147666280e-01,
  3856. -2.98739413451577451308e-01, -2.98659688112279053662e-01,
  3857. -2.98580017149462251247e-01, -2.98500367286606671513e-01,
  3858. -2.98420757461358987506e-01, -2.98341167551394614854e-01,
  3859. -2.98261614404881969520e-01, -2.98182095454955109481e-01,
  3860. -2.98102604120909442376e-01, -2.98023146940687377882e-01,
  3861. -2.97943726694965937973e-01, -2.97864325723094292009e-01,
  3862. -2.97784967183515603129e-01, -2.97705643158333255194e-01,
  3863. -2.97626339808948758847e-01, -2.97547075704168939581e-01,
  3864. -2.97467835110848732860e-01, -2.97388640041019391980e-01,
  3865. -2.97309462883185438020e-01, -2.97230325016071161848e-01,
  3866. -2.97151213239759015572e-01, -2.97072136623453109117e-01,
  3867. -2.96993094441996230426e-01, -2.96914080526812951266e-01,
  3868. -2.96835097925620905457e-01, -2.96756140616124208798e-01,
  3869. -2.96677229639789485915e-01, -2.96598331556529593023e-01,
  3870. -2.96519492030000386684e-01, -2.96440651252633635693e-01,
  3871. -2.96361868680595386127e-01, -2.96283100407240262975e-01,
  3872. -2.96204373196016779168e-01, -2.96125668603260061573e-01,
  3873. -2.96047011288438355336e-01, -2.95968365760827856192e-01,
  3874. -2.95889759916888317459e-01, -2.95811184716729846933e-01,
  3875. -2.95732648423452593178e-01, -2.95654127024545076985e-01,
  3876. -2.95575663603469929175e-01, -2.95497199245855601824e-01,
  3877. -2.95418792415274189533e-01, -2.95340402282260605649e-01,
  3878. -2.95262044294134995415e-01, -2.95183719842823877322e-01,
  3879. -2.95105430265042822935e-01, -2.95027168822003471593e-01,
  3880. -2.94948938780401348492e-01, -2.94870733812242991068e-01,
  3881. -2.94792575962806668866e-01, -2.94714428082456292302e-01,
  3882. -2.94636327317490787081e-01, -2.94558251639318091630e-01,
  3883. -2.94480207312523167840e-01, -2.94402191307359006878e-01,
  3884. -2.94324209478228515646e-01, -2.94246263789008088985e-01,
  3885. -2.94168340529790128812e-01, -2.94090447872844884536e-01,
  3886. -2.94012589190740691869e-01, -2.93934765172675471767e-01,
  3887. -2.93856969689289537762e-01, -2.93779204217081924000e-01,
  3888. -2.93701468979416069338e-01, -2.93623761606339073182e-01,
  3889. -2.93546091354298932519e-01, -2.93468445919199183436e-01,
  3890. -2.93390842909234894620e-01, -2.93313246547464823166e-01,
  3891. -2.93235715278232778047e-01, -2.93158185211556288063e-01,
  3892. -2.93080697000828283016e-01, -2.93003241329427011053e-01,
  3893. -2.92925814810446050185e-01, -2.92848417956391993133e-01,
  3894. -2.92771052104143891803e-01, -2.92693711393679945054e-01,
  3895. -2.92616417928207417365e-01, -2.92539133858402689015e-01,
  3896. -2.92461899071386643989e-01, -2.92384681274965418929e-01,
  3897. -2.92307502695569265683e-01, -2.92230351423153955626e-01,
  3898. -2.92153230519724305125e-01, -2.92076139647305721425e-01,
  3899. -2.91999077095791370606e-01, -2.91922050043583569678e-01,
  3900. -2.91845053838921175693e-01, -2.91768077558705263286e-01,
  3901. -2.91691147195350442001e-01, -2.91614236757522626853e-01,
  3902. -2.91537357162918120412e-01, -2.91460513083827865710e-01,
  3903. -2.91383697265133412291e-01, -2.91306911703275495107e-01,
  3904. -2.91230155667610457471e-01, -2.91153430084271469536e-01,
  3905. -2.91076731979369673908e-01, -2.91000072322327330010e-01,
  3906. -2.90923432561086381387e-01, -2.90846831230972657778e-01,
  3907. -2.90770257446225033338e-01, -2.90693713862819946847e-01,
  3908. -2.90617200742612991071e-01, -2.90540714382205189636e-01,
  3909. -2.90464269333337077317e-01, -2.90387833444186949095e-01,
  3910. -2.90311453715076384086e-01, -2.90235086055248836523e-01,
  3911. -2.90158748068700511613e-01, -2.90082458133686604818e-01,
  3912. -2.90006169836673932672e-01, -2.89929938694830635626e-01,
  3913. -2.89853723163468357527e-01, -2.89777544497205108431e-01,
  3914. -2.89701381573999106056e-01, -2.89625275275657623197e-01,
  3915. -2.89549172603960458527e-01, -2.89473110559530621977e-01,
  3916. -2.89397083545063105170e-01, -2.89321076949155042701e-01,
  3917. -2.89245110111239545070e-01, -2.89169164988470173139e-01,
  3918. -2.89093249709316657547e-01, -2.89017372154488083602e-01,
  3919. -2.88941515024419282032e-01, -2.88865694933179373294e-01,
  3920. -2.88789907427540515350e-01, -2.88714131354602387969e-01,
  3921. -2.88638411075711198706e-01, -2.88562702057091502450e-01,
  3922. -2.88487026313789418630e-01, -2.88411385022879718232e-01,
  3923. -2.88335773812758988655e-01, -2.88260186641024429566e-01,
  3924. -2.88184629697148420036e-01, -2.88109106617386423466e-01,
  3925. -2.88033619018986331017e-01, -2.87958134444958546716e-01,
  3926. -2.87882714050788857119e-01, -2.87807302133715914305e-01,
  3927. -2.87731926238848467747e-01, -2.87656576591996948622e-01,
  3928. -2.87581264744810216616e-01, -2.87505976616624470132e-01,
  3929. -2.87430712274962751884e-01, -2.87355485530396581595e-01,
  3930. -2.87280285776600030623e-01, -2.87205119276563780595e-01,
  3931. -2.87129971584651144667e-01, -2.87054871868676564350e-01,
  3932. -2.86979784958243722137e-01, -2.86904732960156783061e-01,
  3933. -2.86829707321078597460e-01, -2.86754720147553709975e-01,
  3934. -2.86679753918483326558e-01, -2.86604821908234108641e-01,
  3935. -2.86529910892180106341e-01, -2.86455038142716500449e-01,
  3936. -2.86380192498372043719e-01, -2.86305378980894975616e-01,
  3937. -2.86230588664763641038e-01, -2.86155829878574685665e-01,
  3938. -2.86081100585204695097e-01, -2.86006400604550847788e-01,
  3939. -2.85931732694147622276e-01, -2.85857086003960036980e-01,
  3940. -2.85782478824851915444e-01, -2.85707893546886637637e-01,
  3941. -2.85633337615462501446e-01, -2.85558821210665669810e-01,
  3942. -2.85484318518494484263e-01, -2.85409855559644154432e-01,
  3943. -2.85335421120561150143e-01, -2.85261011683021981078e-01,
  3944. -2.85186630181732847511e-01, -2.85112290747834062898e-01,
  3945. -2.85037956273799741869e-01, -2.84963671651626282433e-01,
  3946. -2.84889406179563264843e-01, -2.84815170717389598565e-01,
  3947. -2.84740974879482466875e-01, -2.84666791700296184509e-01,
  3948. -2.84592652372410381822e-01, -2.84518526146278427635e-01,
  3949. -2.84444437772280900312e-01, -2.84370386053668045001e-01,
  3950. -2.84296351027058247229e-01, -2.84222346687502624984e-01,
  3951. -2.84148381721661014154e-01, -2.84074429739585632149e-01,
  3952. -2.84000520559181790503e-01, -2.83926628354001953092e-01,
  3953. -2.83852781908446982762e-01, -2.83778936614844545794e-01,
  3954. -2.83705152712516173175e-01, -2.83631367962298708285e-01,
  3955. -2.83557636971072390963e-01, -2.83483915309188483356e-01,
  3956. -2.83410236681394867020e-01, -2.83336577753573792826e-01,
  3957. -2.83262953453964461126e-01, -2.83189349755469832459e-01,
  3958. -2.83115785486497573142e-01, -2.83042244063997028292e-01,
  3959. -2.82968728288279902650e-01, -2.82895243541149921107e-01,
  3960. -2.82821787846822048085e-01, -2.82748363726633200610e-01,
  3961. -2.82674963071020246552e-01, -2.82601593445157617257e-01,
  3962. -2.82528255049651622066e-01, -2.82454939516903369423e-01,
  3963. -2.82381657764960047885e-01, -2.82308396840973641062e-01,
  3964. -2.82235175286546957629e-01, -2.82161976591600693887e-01,
  3965. -2.82088803551365452371e-01, -2.82015661494998293168e-01,
  3966. -2.81942548662382108660e-01, -2.81869466764828491279e-01,
  3967. -2.81796410717207790331e-01, -2.81723376796985280901e-01,
  3968. -2.81650384979429901922e-01, -2.81577403789483815544e-01,
  3969. -2.81504472096883839871e-01, -2.81431555304708314047e-01,
  3970. -2.81358663523939900308e-01, -2.81285813259310846224e-01,
  3971. -2.81212973084393191847e-01, -2.81140185144941545659e-01,
  3972. -2.81067401691332485747e-01, -2.80994659817595748841e-01,
  3973. -2.80921948304203306090e-01, -2.80849252583495911928e-01,
  3974. -2.80776597442154440820e-01, -2.80703965356340401360e-01,
  3975. -2.80631356931243525210e-01, -2.80558787269943044063e-01,
  3976. -2.80486240058415603471e-01, -2.80413720746192474120e-01,
  3977. -2.80341223849171372606e-01, -2.80268765854230661461e-01,
  3978. -2.80196331001442144881e-01, -2.80123921140157272625e-01,
  3979. -2.80051544632897941867e-01, -2.79979188531967460030e-01,
  3980. -2.79906873913888409877e-01, -2.79834574123750678964e-01,
  3981. -2.79762307649446984037e-01, -2.79690071897800485168e-01,
  3982. -2.79617858753625214696e-01, -2.79545680919100536510e-01,
  3983. -2.79473518052436586956e-01, -2.79401394115129930729e-01,
  3984. -2.79329300658209156438e-01, -2.79257225164321998268e-01,
  3985. -2.79185181448365571377e-01, -2.79113171471586540839e-01,
  3986. -2.79041173574101741828e-01, -2.78969227730713253965e-01,
  3987. -2.78897285109063419739e-01, -2.78825389305071169588e-01,
  3988. -2.78753504174386379511e-01, -2.78681663643264965202e-01,
  3989. -2.78609835206258815710e-01, -2.78538047903678309680e-01,
  3990. -2.78466285134956692549e-01, -2.78394539558566300741e-01,
  3991. -2.78322834789442918879e-01, -2.78251150764596166809e-01,
  3992. -2.78179499417568476538e-01, -2.78107875428922401984e-01,
  3993. -2.78036265791123227142e-01, -2.77964705502005637872e-01,
  3994. -2.77893156984732658810e-01, -2.77821646141850175926e-01,
  3995. -2.77750151643495701848e-01, -2.77678688203089274467e-01,
  3996. -2.77607263000297366240e-01, -2.77535854954775007553e-01,
  3997. -2.77464474153011120272e-01, -2.77393123681135944647e-01,
  3998. -2.77321803459881777165e-01, -2.77250510720189358160e-01,
  3999. -2.77179234265821305971e-01, -2.77107999299044949204e-01,
  4000. -2.77036783262253505367e-01, -2.76965606480123249789e-01,
  4001. -2.76894432563297876460e-01, -2.76823319689300406665e-01,
  4002. -2.76752205647846361014e-01, -2.76681124640357545275e-01,
  4003. -2.76610091478398878451e-01, -2.76539057417772293768e-01,
  4004. -2.76468068513254561225e-01, -2.76397101048645399413e-01,
  4005. -2.76326159130485415893e-01, -2.76255250048812850405e-01,
  4006. -2.76184362888675982717e-01, -2.76113511668101052621e-01,
  4007. -2.76042673581677333594e-01, -2.75971881129537299771e-01,
  4008. -2.75901094171787597542e-01, -2.75830351360901726565e-01,
  4009. -2.75759627633846315931e-01, -2.75688939886797879097e-01,
  4010. -2.75618267949825468399e-01, -2.75547630902992390922e-01,
  4011. -2.75477017299460613664e-01, -2.75406431494776671176e-01,
  4012. -2.75335867513592791322e-01, -2.75265344901753472584e-01,
  4013. -2.75194836154711519605e-01, -2.75124364689586453636e-01,
  4014. -2.75053909045930800037e-01, -2.74983486944931576623e-01,
  4015. -2.74913093665771546270e-01, -2.74842730370532195572e-01,
  4016. -2.74772374779963690639e-01, -2.74702070145500243381e-01,
  4017. -2.74631777499363627371e-01, -2.74561520054265151281e-01,
  4018. -2.74491288630621499411e-01, -2.74421074382313445739e-01,
  4019. -2.74350899521658420088e-01, -2.74280751100732245185e-01,
  4020. -2.74210613995430008138e-01, -2.74140516946612011751e-01,
  4021. -2.74070449521909065282e-01, -2.74000402358196282204e-01,
  4022. -2.73930378636858429253e-01, -2.73860397347223338826e-01,
  4023. -2.73790424054078607163e-01, -2.73720488101978187689e-01,
  4024. -2.73650573603144597890e-01, -2.73580692412392134649e-01,
  4025. -2.73510835349982106557e-01, -2.73441004928314412847e-01,
  4026. -2.73371200277527037770e-01, -2.73301422364668755716e-01,
  4027. -2.73231668191406429358e-01, -2.73161948784023778103e-01,
  4028. -2.73092245387460519357e-01, -2.73022577292190926634e-01,
  4029. -2.72952930794861547970e-01, -2.72883319066670071429e-01,
  4030. -2.72813725477921487084e-01, -2.72744158672713621350e-01,
  4031. -2.72674623056092968465e-01, -2.72605114715516849699e-01,
  4032. -2.72535622544367805986e-01, -2.72466172529916839107e-01,
  4033. -2.72396738884922551271e-01, -2.72327331715854548122e-01,
  4034. -2.72257958735816929519e-01, -2.72188601337665814217e-01,
  4035. -2.72119281533388934768e-01, -2.72049974585663156823e-01,
  4036. -2.71980712728309426129e-01, -2.71911458818592688402e-01,
  4037. -2.71842239786664607859e-01, -2.71773052109879453830e-01,
  4038. -2.71703882948668151709e-01, -2.71634742480469149051e-01,
  4039. -2.71565625186839798566e-01, -2.71496542964112241858e-01,
  4040. -2.71427476097141573419e-01, -2.71358446846692968890e-01,
  4041. -2.71289430588333102534e-01, -2.71220458855547019716e-01,
  4042. -2.71151497194053625606e-01, -2.71082562480524313919e-01,
  4043. -2.71013666366038519229e-01, -2.70944790073090580051e-01,
  4044. -2.70875930005398501965e-01, -2.70807119325596090675e-01,
  4045. -2.70738318386396559223e-01, -2.70669540855605239571e-01,
  4046. -2.70600794061028715465e-01, -2.70532079727119401102e-01,
  4047. -2.70463383628260722880e-01, -2.70394716238982646406e-01,
  4048. -2.70326072238524450775e-01, -2.70257462435398387868e-01,
  4049. -2.70188871268058794506e-01, -2.70120305470691102201e-01,
  4050. -2.70051776019842759702e-01, -2.69983254626878887983e-01,
  4051. -2.69914776414566681684e-01, -2.69846318587439903958e-01,
  4052. -2.69777892501111837831e-01, -2.69709475528596143157e-01,
  4053. -2.69641102118741149418e-01, -2.69572746510107319473e-01,
  4054. -2.69504410244378711514e-01, -2.69436112916259018490e-01,
  4055. -2.69367841660474394150e-01, -2.69299583639932893497e-01,
  4056. -2.69231358364793171845e-01, -2.69163167686737425655e-01,
  4057. -2.69094984688878380297e-01, -2.69026848131857065916e-01,
  4058. -2.68958719296964632317e-01, -2.68890624891427842957e-01,
  4059. -2.68822563860274088565e-01, -2.68754513716166654191e-01,
  4060. -2.68686498408199803123e-01, -2.68618511682558958054e-01,
  4061. -2.68550532253665763527e-01, -2.68482606814164914688e-01,
  4062. -2.68414681637764829247e-01, -2.68346790826536729657e-01,
  4063. -2.68278941105454360461e-01, -2.68211093824292923227e-01,
  4064. -2.68143285100269301857e-01, -2.68075498521707644706e-01,
  4065. -2.68007741266353127774e-01, -2.67940001034900732169e-01,
  4066. -2.67872297495083122598e-01, -2.67804608978758684756e-01,
  4067. -2.67736957787277685128e-01, -2.67669321086863643000e-01,
  4068. -2.67601723207789465864e-01, -2.67534134366222919876e-01,
  4069. -2.67466582311995049182e-01, -2.67399052884839394384e-01,
  4070. -2.67331552624248569572e-01, -2.67264069532518910854e-01,
  4071. -2.67196622709230169335e-01, -2.67129192457251085635e-01,
  4072. -2.67061793762043198086e-01, -2.66994408730633570048e-01,
  4073. -2.66927071597710174888e-01, -2.66859730372719650138e-01,
  4074. -2.66792447024478796003e-01, -2.66725159778724463244e-01,
  4075. -2.66657919653241259894e-01, -2.66590696109862967944e-01,
  4076. -2.66523493228245089703e-01, -2.66456325227931167809e-01,
  4077. -2.66389175854575221969e-01, -2.66322051202534382242e-01,
  4078. -2.66254965500467566386e-01, -2.66187878091123653057e-01,
  4079. -2.66120847967881601903e-01, -2.66053813924927218260e-01,
  4080. -2.65986827681687298952e-01, -2.65919855324977860711e-01,
  4081. -2.65852913732882611964e-01, -2.65785991657992881620e-01,
  4082. -2.65719094860117854839e-01, -2.65652233899170586717e-01,
  4083. -2.65585383127432239636e-01, -2.65518567520639292567e-01,
  4084. -2.65451779878790095069e-01, -2.65385001674412923656e-01,
  4085. -2.65318269513913018720e-01, -2.65251544906108194244e-01,
  4086. -2.65184855802354790821e-01, -2.65118195943634726852e-01,
  4087. -2.65051540062922641461e-01, -2.64984928432112298857e-01,
  4088. -2.64918336989363401024e-01, -2.64851777006659072633e-01,
  4089. -2.64785227457907834658e-01, -2.64718716472008730456e-01,
  4090. -2.64652219614681993853e-01, -2.64585761790664397708e-01,
  4091. -2.64519312518772475862e-01, -2.64452901763777392663e-01,
  4092. -2.64386507203004050837e-01, -2.64320143458897371946e-01,
  4093. -2.64253796716094724317e-01, -2.64187485261860310892e-01,
  4094. -2.64121194465983144539e-01, -2.64054919858559333790e-01,
  4095. -2.63988693949415653695e-01, -2.63922458224374323343e-01,
  4096. -2.63856280119868835676e-01, -2.63790104866535146666e-01,
  4097. -2.63723972346687929313e-01, -2.63657844855657130800e-01,
  4098. -2.63591766274582917085e-01, -2.63525688190542506373e-01,
  4099. -2.63459648615377350911e-01, -2.63393633321611475573e-01,
  4100. -2.63327638855565759890e-01, -2.63261670907691203158e-01,
  4101. -2.63195732521604275345e-01, -2.63129805832387764220e-01,
  4102. -2.63063914552611355369e-01, -2.62998048752138335882e-01,
  4103. -2.62932202087204025531e-01, -2.62866387511262566967e-01,
  4104. -2.62800581906003083432e-01, -2.62734820087732301452e-01,
  4105. -2.62669075316500522099e-01, -2.62603352680575163891e-01,
  4106. -2.62537658566835474527e-01, -2.62471984691239335064e-01,
  4107. -2.62406335451333905251e-01, -2.62340723892714733356e-01,
  4108. -2.62275115787194479378e-01, -2.62209545594959014814e-01,
  4109. -2.62143999110420133913e-01, -2.62078476344002386789e-01,
  4110. -2.62012969107854654105e-01, -2.61947510142956141443e-01,
  4111. -2.61882043728466684662e-01, -2.61816625896317489719e-01,
  4112. -2.61751222350074252976e-01, -2.61685847188317666223e-01,
  4113. -2.61620500664901001198e-01, -2.61555167665830534673e-01,
  4114. -2.61489863689744250763e-01, -2.61424586559567295740e-01,
  4115. -2.61359329484961766532e-01, -2.61294099452612282874e-01,
  4116. -2.61228897657859171488e-01, -2.61163712332657116377e-01,
  4117. -2.61098567002105375057e-01, -2.61033424037335481938e-01,
  4118. -2.60968321021755156330e-01, -2.60903234657569038646e-01,
  4119. -2.60838175849067432921e-01, -2.60773146628625773769e-01,
  4120. -2.60708127962452462789e-01, -2.60643149249854877425e-01,
  4121. -2.60578178982620423110e-01, -2.60513246739066617330e-01,
  4122. -2.60448332769361301509e-01, -2.60383441791032177459e-01,
  4123. -2.60318574683800485481e-01, -2.60253745562995741913e-01,
  4124. -2.60188919439319599203e-01, -2.60124132747669434274e-01,
  4125. -2.60059364144720972511e-01, -2.59994617865390797995e-01,
  4126. -2.59929898313336460447e-01, -2.59865205990752967669e-01,
  4127. -2.59800534485202572199e-01, -2.59735886592499798375e-01,
  4128. -2.59671257541824240800e-01, -2.59606663620642774681e-01,
  4129. -2.59542089153392552259e-01, -2.59477535851373675158e-01,
  4130. -2.59413012544949028726e-01, -2.59348504553108316628e-01,
  4131. -2.59284039417788769732e-01, -2.59219566355734731822e-01,
  4132. -2.59155149199322865083e-01, -2.59090739864494823408e-01,
  4133. -2.59026355096398042122e-01, -2.58961998350243305378e-01,
  4134. -2.58897661411781720986e-01, -2.58833351331056227274e-01,
  4135. -2.58769070473885531847e-01, -2.58704802326952476577e-01,
  4136. -2.58640565874222572162e-01, -2.58576346396635348146e-01,
  4137. -2.58512161434724663245e-01, -2.58448000248899634190e-01,
  4138. -2.58383843553506298285e-01, -2.58319734527267641511e-01,
  4139. -2.58255631499654580985e-01, -2.58191568567093354680e-01,
  4140. -2.58127518069633854481e-01, -2.58063489495424180920e-01,
  4141. -2.57999494903564385861e-01, -2.57935521272989909392e-01,
  4142. -2.57871563925374303050e-01, -2.57807632243347462087e-01,
  4143. -2.57743738078198836305e-01, -2.57679846993883299167e-01,
  4144. -2.57615995476324077806e-01, -2.57552161424840830861e-01,
  4145. -2.57488352052748226129e-01, -2.57424560607467600715e-01,
  4146. -2.57360806885999326976e-01, -2.57297063156403882367e-01,
  4147. -2.57233353494213945467e-01, -2.57169654032721739512e-01,
  4148. -2.57105991459742000416e-01, -2.57042349945948600531e-01,
  4149. -2.56978721417348343614e-01, -2.56915131647498573564e-01,
  4150. -2.56851552671387484139e-01, -2.56788003520280194714e-01,
  4151. -2.56724480737611615577e-01, -2.56660979118377152730e-01,
  4152. -2.56597500587418092532e-01, -2.56534042650374050076e-01,
  4153. -2.56470613359845278634e-01, -2.56407205351532829773e-01,
  4154. -2.56343817678290730733e-01, -2.56280461493001709972e-01,
  4155. -2.56217115483022284117e-01, -2.56153809042560520748e-01,
  4156. -2.56090512962653060747e-01, -2.56027247629719512112e-01,
  4157. -2.55964005410528327999e-01, -2.55900774099844519061e-01,
  4158. -2.55837587800097965296e-01, -2.55774411713771132604e-01,
  4159. -2.55711261521537225327e-01, -2.55648131649962473411e-01,
  4160. -2.55585028712108974780e-01, -2.55521954180903843046e-01,
  4161. -2.55458895551576692373e-01, -2.55395856666797982371e-01,
  4162. -2.55332857012398051211e-01, -2.55269859505869389782e-01,
  4163. -2.55206903584443867139e-01, -2.55143957988668623749e-01,
  4164. -2.55081041263898300464e-01, -2.55018155191650386371e-01,
  4165. -2.54955274100500506318e-01, -2.54892431839403521554e-01,
  4166. -2.54829608090931025721e-01, -2.54766805572358312482e-01,
  4167. -2.54704033732013002123e-01, -2.54641274411050722026e-01,
  4168. -2.54578546093037649811e-01, -2.54515837706037417743e-01,
  4169. -2.54453152702487472858e-01, -2.54390488344574172697e-01,
  4170. -2.54327852131114695577e-01, -2.54265239156395761455e-01,
  4171. -2.54202639192711965510e-01, -2.54140075704855583627e-01,
  4172. -2.54077532116588844513e-01, -2.54015006564586975912e-01,
  4173. -2.53952500726644714302e-01, -2.53890032106650342936e-01,
  4174. -2.53827573714738630173e-01, -2.53765148951257568655e-01,
  4175. -2.53702735908163778955e-01, -2.53640354113799260105e-01,
  4176. -2.53577992066322810416e-01, -2.53515653893015502351e-01,
  4177. -2.53453334586594525302e-01, -2.53391050048909827197e-01,
  4178. -2.53328764031586106675e-01, -2.53266538571049248940e-01,
  4179. -2.53204295880422258769e-01, -2.53142106256852073010e-01,
  4180. -2.53079922760821030003e-01, -2.53017773446285620942e-01,
  4181. -2.52955637740421068749e-01, -2.52893525177086520017e-01,
  4182. -2.52831440545411512133e-01, -2.52769377506761316887e-01,
  4183. -2.52707334274802852825e-01, -2.52645324333503284997e-01,
  4184. -2.52583317885069102982e-01, -2.52521353581481644568e-01,
  4185. -2.52459396019576121084e-01, -2.52397481104805143648e-01,
  4186. -2.52335567673748484285e-01, -2.52273695067666836600e-01,
  4187. -2.52211836491905649904e-01, -2.52149992728596172853e-01,
  4188. -2.52088187443868294579e-01, -2.52026392246296748745e-01,
  4189. -2.51964629980227339257e-01, -2.51902882363185642856e-01,
  4190. -2.51841154977239800594e-01, -2.51779466128333406783e-01,
  4191. -2.51717781714107968760e-01, -2.51656130431086255683e-01,
  4192. -2.51594498650761222436e-01, -2.51532889838896656087e-01,
  4193. -2.51471303760944120409e-01, -2.51409737889333739780e-01,
  4194. -2.51348202568893563935e-01, -2.51286681299622782770e-01,
  4195. -2.51225185033213394004e-01, -2.51163708814639563549e-01,
  4196. -2.51102261512313018610e-01, -2.51040834959354253186e-01,
  4197. -2.50979430603127828814e-01, -2.50918050821055227395e-01,
  4198. -2.50856684656085349161e-01, -2.50795351207259931137e-01,
  4199. -2.50734029738946484489e-01, -2.50672739391149534960e-01,
  4200. -2.50611469042967272003e-01, -2.50550221686260676801e-01,
  4201. -2.50488996474487024546e-01, -2.50427793801956899422e-01,
  4202. -2.50366612937970467456e-01, -2.50305456411016258311e-01,
  4203. -2.50244314837840708954e-01, -2.50183200871226807394e-01,
  4204. -2.50122117986780634347e-01, -2.50061039629294101783e-01,
  4205. -2.50000001488768275326e-01
  4206. };
  4207. // common/dmath.h
  4208. #define DMATH_INFINITY ((float)((1e+300 * 1e+300)))
  4209. #define DMATH_NAN ((float)(DMATH_INFINITY * 0.0F))
  4210. #define DMATH_PI 3.1415926535897932384
  4211. #define DMATH_E 2.7182818284590452354
  4212. #define DMATH_DEG2RAD 0.017453292519943295
  4213. #define DMATH_RAD2DEG 57.29577951308232
  4214. #define DMATH_EPSILON 1e-10
  4215. #define DMATH_LOG2_E 1.4426950408889634
  4216. double dmath_exp2(double x);
  4217. double dmath_log2(double x);
  4218. double dmath_exp(double x);
  4219. double dmath_exp10(double x);
  4220. double dmath_log(double x);
  4221. double dmath_log10(double x);
  4222. double dmath_pow(double base, double exp);
  4223. double dmath_sqrt(double x);
  4224. double dmath_cbrt(double x);
  4225. void dmath_sincos(double x, double* sin, double* cos);
  4226. double dmath_sin(double x);
  4227. double dmath_cos(double x);
  4228. double dmath_tan(double x);
  4229. double dmath_asin(double x);
  4230. double dmath_acos(double x);
  4231. double dmath_atan(double x);
  4232. double dmath_atan2(double y, double x);
  4233. int dmath_isinf(double x);
  4234. int dmath_isnan(double x);
  4235. int dmath_isnormal(double x);
  4236. int dmath_isfinite(double x);
  4237. double dmath_fmod(double x, double y);
  4238. double dmath_copysign(double x, double y);
  4239. double dmath_fabs(double x);
  4240. double dmath_ceil(double x);
  4241. double dmath_floor(double x);
  4242. double dmath_trunc(double x);
  4243. double dmath_modf(double x, double* intpart);
  4244. double dmath_fmin(double x, double y);
  4245. double dmath_fmax(double x, double y);
  4246. // common/memorypool.h
  4247. typedef struct FixedMemoryPool {
  4248. int BlockSize;
  4249. int BlockCount;
  4250. char* data;
  4251. char* data_end;
  4252. int exceeded_bytes;
  4253. char** _free_list;
  4254. int _free_list_length;
  4255. } FixedMemoryPool;
  4256. void FixedMemoryPool__ctor(FixedMemoryPool* self, int BlockSize, int BlockCount);
  4257. void FixedMemoryPool__dtor(FixedMemoryPool* self);
  4258. void* FixedMemoryPool__alloc(FixedMemoryPool* self);
  4259. void FixedMemoryPool__dealloc(FixedMemoryPool* self, void* p);
  4260. // common/name.h
  4261. #ifdef __cplusplus
  4262. extern "C" {
  4263. #endif
  4264. void pk_names_initialize();
  4265. void pk_names_finalize();
  4266. #define MAGIC_METHOD(x) extern py_Name x;
  4267. #ifdef MAGIC_METHOD
  4268. // math operators
  4269. MAGIC_METHOD(__lt__)
  4270. MAGIC_METHOD(__le__)
  4271. MAGIC_METHOD(__gt__)
  4272. MAGIC_METHOD(__ge__)
  4273. /////////////////////////////
  4274. MAGIC_METHOD(__neg__)
  4275. MAGIC_METHOD(__abs__)
  4276. MAGIC_METHOD(__round__)
  4277. MAGIC_METHOD(__divmod__)
  4278. /////////////////////////////
  4279. MAGIC_METHOD(__add__)
  4280. MAGIC_METHOD(__radd__)
  4281. MAGIC_METHOD(__sub__)
  4282. MAGIC_METHOD(__rsub__)
  4283. MAGIC_METHOD(__mul__)
  4284. MAGIC_METHOD(__rmul__)
  4285. MAGIC_METHOD(__truediv__)
  4286. MAGIC_METHOD(__rtruediv__)
  4287. MAGIC_METHOD(__floordiv__)
  4288. MAGIC_METHOD(__rfloordiv__)
  4289. MAGIC_METHOD(__mod__)
  4290. MAGIC_METHOD(__rmod__)
  4291. MAGIC_METHOD(__pow__)
  4292. MAGIC_METHOD(__rpow__)
  4293. MAGIC_METHOD(__matmul__)
  4294. MAGIC_METHOD(__lshift__)
  4295. MAGIC_METHOD(__rshift__)
  4296. MAGIC_METHOD(__and__)
  4297. MAGIC_METHOD(__or__)
  4298. MAGIC_METHOD(__xor__)
  4299. /////////////////////////////
  4300. MAGIC_METHOD(__repr__)
  4301. MAGIC_METHOD(__str__)
  4302. MAGIC_METHOD(__hash__)
  4303. MAGIC_METHOD(__len__)
  4304. MAGIC_METHOD(__iter__)
  4305. MAGIC_METHOD(__next__)
  4306. MAGIC_METHOD(__contains__)
  4307. MAGIC_METHOD(__bool__)
  4308. MAGIC_METHOD(__invert__)
  4309. /////////////////////////////
  4310. MAGIC_METHOD(__eq__)
  4311. MAGIC_METHOD(__ne__)
  4312. // indexer
  4313. MAGIC_METHOD(__getitem__)
  4314. MAGIC_METHOD(__setitem__)
  4315. MAGIC_METHOD(__delitem__)
  4316. // specials
  4317. MAGIC_METHOD(__new__)
  4318. MAGIC_METHOD(__init__)
  4319. MAGIC_METHOD(__call__)
  4320. MAGIC_METHOD(__enter__)
  4321. MAGIC_METHOD(__exit__)
  4322. MAGIC_METHOD(__name__)
  4323. MAGIC_METHOD(__all__)
  4324. MAGIC_METHOD(__package__)
  4325. MAGIC_METHOD(__class__)
  4326. MAGIC_METHOD(__getattr__)
  4327. MAGIC_METHOD(__reduce__)
  4328. MAGIC_METHOD(__missing__)
  4329. #endif
  4330. #undef MAGIC_METHOD
  4331. py_Name py_namev(c11_sv name);
  4332. c11_sv py_name2sv(py_Name index);
  4333. py_Name py_name(const char* name);
  4334. const char* py_name2str(py_Name index);
  4335. #ifdef __cplusplus
  4336. } // extern "C"
  4337. #endif
  4338. // common/socket.h
  4339. #include <stdint.h>
  4340. #if PK_ENABLE_OS
  4341. typedef void* c11_socket_handler;
  4342. enum c11_address_family { C11_AF_INET = 2 };
  4343. enum c11_socket_kind { C11_SOCK_STREAM = 1 };
  4344. c11_socket_handler c11_socket_create(int family, int type, int protocol);
  4345. int c11_socket_bind(c11_socket_handler socket, const char* hostname, unsigned short port);
  4346. int c11_socket_listen(c11_socket_handler socket, int backlog);
  4347. c11_socket_handler
  4348. c11_socket_accept(c11_socket_handler socket, char* client_ip, unsigned short* client_port);
  4349. int c11_socket_connect(c11_socket_handler socket,
  4350. const char* server_ip,
  4351. unsigned short server_port);
  4352. int c11_socket_recv(c11_socket_handler socket, char* buffer, int maxsize);
  4353. int c11_socket_send(c11_socket_handler socket, const char* senddata, int datalen);
  4354. int c11_socket_close(c11_socket_handler socket);
  4355. int c11_socket_set_block(c11_socket_handler socket, int flag);
  4356. c11_socket_handler c11_socket_invalid_socket_handler();
  4357. int c11_socket_get_last_error();
  4358. #endif // PK_ENABLE_OS
  4359. // common/threads.h
  4360. #if PK_ENABLE_THREADS
  4361. #include <stdatomic.h>
  4362. #include <stdbool.h>
  4363. #if __EMSCRIPTEN__ || __APPLE__ || __linux__ || __MINGW32__
  4364. #include <pthread.h>
  4365. #define PK_USE_PTHREADS 1
  4366. typedef pthread_t c11_thrd_t;
  4367. typedef void* c11_thrd_retval_t;
  4368. typedef pthread_mutex_t c11_mutex_t;
  4369. typedef pthread_cond_t c11_cond_t;
  4370. #else
  4371. #include <threads.h>
  4372. #define PK_USE_PTHREADS 0
  4373. typedef thrd_t c11_thrd_t;
  4374. typedef int c11_thrd_retval_t;
  4375. typedef mtx_t c11_mutex_t;
  4376. typedef cnd_t c11_cond_t;
  4377. #endif
  4378. typedef c11_thrd_retval_t (*c11_thrd_func_t)(void*);
  4379. bool c11_thrd__create(c11_thrd_t* thrd, c11_thrd_func_t func, void* arg);
  4380. void c11_thrd__yield();
  4381. void c11_thrd__join(c11_thrd_t thrd);
  4382. c11_thrd_t c11_thrd__current();
  4383. bool c11_thrd__equal(c11_thrd_t a, c11_thrd_t b);
  4384. void c11_mutex__ctor(c11_mutex_t* mutex);
  4385. void c11_mutex__dtor(c11_mutex_t* mutex);
  4386. void c11_mutex__lock(c11_mutex_t* mutex);
  4387. void c11_mutex__unlock(c11_mutex_t* mutex);
  4388. void c11_cond__ctor(c11_cond_t* cond);
  4389. void c11_cond__dtor(c11_cond_t* cond);
  4390. void c11_cond__wait(c11_cond_t* cond, c11_mutex_t* mutex);
  4391. void c11_cond__signal(c11_cond_t* cond);
  4392. void c11_cond__broadcast(c11_cond_t* cond);
  4393. typedef void (*c11_thrdpool_func_t)(void* arg);
  4394. typedef struct c11_thrdpool_tasks {
  4395. atomic_int sync_val;
  4396. c11_thrdpool_func_t func;
  4397. void** args;
  4398. int length;
  4399. atomic_int current_index;
  4400. atomic_int completed_count;
  4401. } c11_thrdpool_tasks;
  4402. typedef struct c11_thrdpool_worker {
  4403. int index;
  4404. atomic_int* p_ready_workers_num;
  4405. c11_mutex_t* p_mutex;
  4406. c11_cond_t* p_cond;
  4407. c11_thrdpool_tasks* p_tasks;
  4408. c11_thrd_t thread;
  4409. } c11_thrdpool_worker;
  4410. typedef struct c11_thrdpool {
  4411. int length;
  4412. atomic_int ready_workers_num;
  4413. c11_thrdpool_worker* workers;
  4414. c11_mutex_t workers_mutex;
  4415. c11_cond_t workers_cond;
  4416. c11_thrdpool_tasks tasks;
  4417. } c11_thrdpool;
  4418. void c11_thrdpool__ctor(c11_thrdpool* pool, int length);
  4419. void c11_thrdpool__dtor(c11_thrdpool* pool);
  4420. void c11_thrdpool__map(c11_thrdpool* pool, c11_thrdpool_func_t func, void** args, int num_tasks);
  4421. void c11_thrdpool__join(c11_thrdpool* pool);
  4422. #endif
  4423. // common/utils.h
  4424. #include <stdio.h>
  4425. #include <stdlib.h>
  4426. #include <assert.h>
  4427. #define PK_REGION(name) 1
  4428. #define PK_SLICE_LOOP(i, start, stop, step) \
  4429. for(int i = start; step > 0 ? i < stop : i > stop; i += step)
  4430. // global constants
  4431. #define PK_HEX_TABLE "0123456789abcdef"
  4432. #ifdef _MSC_VER
  4433. #define c11__unreachable() __assume(0)
  4434. #else
  4435. #define c11__unreachable() __builtin_unreachable()
  4436. #endif
  4437. #define c11__abort(...) \
  4438. do { \
  4439. fprintf(stderr, __VA_ARGS__); \
  4440. putchar('\n'); \
  4441. abort(); \
  4442. } while(0)
  4443. #define c11__rtassert(cond) \
  4444. if(!(cond)) c11__abort("assertion failed: %s", #cond)
  4445. #define c11__min(a, b) ((a) < (b) ? (a) : (b))
  4446. #define c11__max(a, b) ((a) > (b) ? (a) : (b))
  4447. #define c11__count_array(a) (sizeof(a) / sizeof(a[0]))
  4448. // ref counting
  4449. typedef struct RefCounted {
  4450. int count;
  4451. void (*dtor)(void*);
  4452. } RefCounted;
  4453. #define PK_INCREF(obj) (obj)->rc.count++
  4454. #define PK_DECREF(obj) \
  4455. do { \
  4456. if(--(obj)->rc.count == 0) { \
  4457. (obj)->rc.dtor(obj); \
  4458. PK_FREE(obj); \
  4459. } \
  4460. } while(0)
  4461. // common/algorithm.h
  4462. #include <stdbool.h>
  4463. #define c11__less(a, b) ((a) < (b))
  4464. #define c11__lower_bound(T, ptr, count, key, less, out_index) \
  4465. do { \
  4466. T* __first = ptr; \
  4467. int __len = count; \
  4468. while(__len >= 8) { \
  4469. int __l2 = __len >> 1; \
  4470. T* __m = __first + __l2; \
  4471. if(less((*__m), (key))) { \
  4472. __first = ++__m; \
  4473. __len -= __l2 + 1; \
  4474. } else { \
  4475. __len = __l2; \
  4476. } \
  4477. } \
  4478. switch(__len) { \
  4479. case 7: \
  4480. if(less(*__first, (key))) __first++; \
  4481. case 6: \
  4482. if(less(*__first, (key))) __first++; \
  4483. case 5: \
  4484. if(less(*__first, (key))) __first++; \
  4485. case 4: \
  4486. if(less(*__first, (key))) __first++; \
  4487. case 3: \
  4488. if(less(*__first, (key))) __first++; \
  4489. case 2: \
  4490. if(less(*__first, (key))) __first++; \
  4491. case 1: \
  4492. if(less(*__first, (key))) __first++; \
  4493. case 0: break; \
  4494. default: c11__unreachable(); \
  4495. } \
  4496. *(out_index) = __first - (T*)(ptr); \
  4497. } while(0)
  4498. /**
  4499. * @brief Sorts an array of elements of the same type, using the given comparison function.
  4500. * @param ptr Pointer to the first element of the array.
  4501. * @param count Number of elements in the array.
  4502. * @param elem_size Size of each element in the array.
  4503. * @param cmp Comparison function that takes two elements and returns an integer similar to
  4504. * `strcmp`.
  4505. */
  4506. bool c11__stable_sort(void* ptr,
  4507. int length,
  4508. int elem_size,
  4509. int (*f_lt)(const void* a, const void* b, void* extra),
  4510. void* extra);
  4511. int c11__bit_length(unsigned long x);
  4512. // common/vector.h
  4513. #include <string.h>
  4514. #include <stdbool.h>
  4515. typedef struct c11_vector {
  4516. void* data;
  4517. int length;
  4518. int capacity;
  4519. int elem_size;
  4520. } c11_vector;
  4521. void c11_vector__ctor(c11_vector* self, int elem_size);
  4522. void c11_vector__dtor(c11_vector* self);
  4523. c11_vector c11_vector__copy(const c11_vector* self);
  4524. void c11_vector__reserve(c11_vector* self, int capacity);
  4525. void c11_vector__clear(c11_vector* self);
  4526. void* c11_vector__emplace(c11_vector* self);
  4527. bool c11_vector__contains(const c11_vector* self, void* elem);
  4528. void* c11_vector__submit(c11_vector* self, int* length);
  4529. void c11_vector__swap(c11_vector* self, c11_vector* other);
  4530. int c11_vector__nextcap(c11_vector* self);
  4531. void c11_vector__extend(c11_vector* self, const void* p, int size);
  4532. #define c11__getitem(T, self, index) (((T*)(self)->data)[index])
  4533. #define c11__setitem(T, self, index, value) ((T*)(self)->data)[index] = value;
  4534. #define c11__at(T, self, index) ((T*)(self)->data + index)
  4535. #define c11_vector__push(T, self, elem) \
  4536. do { \
  4537. if((self)->length == (self)->capacity) { \
  4538. c11_vector__reserve((self), c11_vector__nextcap((self))); \
  4539. } \
  4540. ((T*)(self)->data)[(self)->length] = (elem); \
  4541. (self)->length++; \
  4542. } while(0)
  4543. #define c11_vector__pop(self) (--(self)->length)
  4544. #define c11_vector__back(T, self) (((T*)(self)->data)[(self)->length - 1])
  4545. #define c11_vector__insert(T, self, index, elem) \
  4546. do { \
  4547. if((self)->length == (self)->capacity) { \
  4548. c11_vector__reserve((self), c11_vector__nextcap(self)); \
  4549. } \
  4550. T* p = (T*)(self)->data + (index); \
  4551. memmove(p + 1, p, ((self)->length - (index)) * sizeof(T)); \
  4552. *p = (elem); \
  4553. (self)->length++; \
  4554. } while(0)
  4555. #define c11_vector__erase(T, self, index) \
  4556. do { \
  4557. T* p = (T*)(self)->data + (index); \
  4558. memmove(p, p + 1, ((self)->length - (index)-1) * sizeof(T)); \
  4559. (self)->length--; \
  4560. } while(0)
  4561. #define c11__reverse(T, self) \
  4562. do { \
  4563. if(!self->data) break; \
  4564. T* p = (T*)(self)->data; \
  4565. T* q = (T*)(self)->data + (self)->length - 1; \
  4566. while(p < q) { \
  4567. T tmp = *p; \
  4568. *p = *q; \
  4569. *q = tmp; \
  4570. p++; \
  4571. q--; \
  4572. } \
  4573. } while(0)
  4574. // NOTE: here we do an extra NULL check for it to avoid UB
  4575. #define c11__foreach(T, self, it) \
  4576. for(T* it = (self)->data; it && it != (T*)(self)->data + (self)->length; it++)
  4577. // common/chunkedvector.h
  4578. typedef struct c11_chunkedvector_chunk {
  4579. int length;
  4580. int capacity;
  4581. void* data;
  4582. } c11_chunkedvector_chunk;
  4583. typedef struct c11_chunkedvector {
  4584. c11_vector /*T=c11_chunkedvector_chunk*/ chunks;
  4585. int length;
  4586. int capacity;
  4587. int elem_size;
  4588. int initial_chunks;
  4589. } c11_chunkedvector;
  4590. // chunks[0]: size=1, total_capacity=1
  4591. // chunks[1]: size=2, total_capacity=3
  4592. // chunks[2]: size=4, total_capacity=7
  4593. // chunks[3]: size=8, total_capacity=15
  4594. // chunks[4]: size=16, total_capacity=31
  4595. // chunks[5]: size=32, total_capacity=63
  4596. // ...
  4597. // chunks[n]: size=2^n, total_capacity=2^(n+1)-1
  4598. void c11_chunkedvector__ctor(c11_chunkedvector* self, int elem_size, int initial_chunks);
  4599. void c11_chunkedvector__dtor(c11_chunkedvector* self);
  4600. void* c11_chunkedvector__emplace(c11_chunkedvector* self);
  4601. void* c11_chunkedvector__at(c11_chunkedvector* self, int index);
  4602. // common/str.h
  4603. #include <stdarg.h>
  4604. /* string */
  4605. typedef struct c11_string {
  4606. // int size | char[] | '\0'
  4607. int size;
  4608. char data[]; // flexible array member
  4609. } c11_string;
  4610. c11_string* pk_tostr(py_Ref self);
  4611. /* bytes */
  4612. typedef struct c11_bytes {
  4613. int size;
  4614. unsigned char data[]; // flexible array member
  4615. } c11_bytes;
  4616. typedef struct {
  4617. int start;
  4618. int end;
  4619. char data[4];
  4620. } c11_u32_range;
  4621. bool c11_bytes__eq(c11_bytes* self, c11_bytes* other);
  4622. int c11_sv__cmp(c11_sv self, c11_sv other);
  4623. int c11_sv__cmp2(c11_sv self, const char* other);
  4624. bool c11__streq(const char* a, const char* b);
  4625. bool c11__sveq(c11_sv a, c11_sv b);
  4626. bool c11__sveq2(c11_sv a, const char* b);
  4627. c11_string* c11_string__new(const char* data);
  4628. c11_string* c11_string__new2(const char* data, int size);
  4629. c11_string* c11_string__new3(const char* fmt, ...);
  4630. void c11_string__ctor(c11_string* self, const char* data);
  4631. void c11_string__ctor2(c11_string* self, const char* data, int size);
  4632. void c11_string__ctor3(c11_string* self, int size);
  4633. c11_string* c11_string__copy(c11_string* self);
  4634. void c11_string__delete(c11_string* self);
  4635. c11_sv c11_string__sv(c11_string* self);
  4636. int c11_sv__u8_length(c11_sv self);
  4637. c11_sv c11_sv__u8_getitem(c11_sv self, int i);
  4638. c11_string* c11_sv__u8_slice(c11_sv self, int start, int stop, int step);
  4639. // general string operations
  4640. c11_sv c11_sv__slice(c11_sv sv, int start);
  4641. c11_sv c11_sv__slice2(c11_sv sv, int start, int stop);
  4642. c11_sv c11_sv__strip(c11_sv sv, c11_sv chars, bool left, bool right);
  4643. int c11_sv__index(c11_sv self, char c);
  4644. int c11_sv__rindex(c11_sv self, char c);
  4645. c11_sv c11_sv__filename(c11_sv self);
  4646. int c11_sv__index2(c11_sv self, c11_sv sub, int start);
  4647. int c11_sv__count(c11_sv self, c11_sv sub);
  4648. bool c11_sv__startswith(c11_sv self, c11_sv prefix);
  4649. bool c11_sv__endswith(c11_sv self, c11_sv suffix);
  4650. uint64_t c11_sv__hash(c11_sv self);
  4651. c11_string* c11_sv__replace(c11_sv self, char old, char new_);
  4652. c11_string* c11_sv__replace2(c11_sv self, c11_sv old, c11_sv new_);
  4653. c11_vector /* T=c11_sv */ c11_sv__split(c11_sv self, char sep);
  4654. c11_vector /* T=c11_sv */ c11_sv__split2(c11_sv self, c11_sv sep);
  4655. c11_vector /* T=c11_sv */ c11_sv__splitwhitespace(c11_sv self);
  4656. c11_vector /* T=c11_sv */ c11_sv__splitlines(c11_sv self, bool keepends);
  4657. // misc
  4658. int c11__unicode_index_to_byte(const char* data, int i);
  4659. int c11__byte_index_to_unicode(const char* data, int n);
  4660. bool c11__is_unicode_Lo_char(int c);
  4661. const char* c11__search_u32_ranges(int c, const c11_u32_range* p, int n_ranges);
  4662. int c11__u8_header(unsigned char c, bool suppress);
  4663. int c11__u8_value(int u8bytes, const char* data);
  4664. int c11__u32_to_u8(uint32_t utf32_char, char utf8_output[4]);
  4665. char* c11_strdup(const char* str);
  4666. unsigned char* c11_memdup(const unsigned char* data, int size);
  4667. typedef enum IntParsingResult {
  4668. IntParsing_SUCCESS,
  4669. IntParsing_FAILURE,
  4670. IntParsing_OVERFLOW,
  4671. } IntParsingResult;
  4672. IntParsingResult c11__parse_uint(c11_sv text, int64_t* out, int base);
  4673. // common/serialize.h
  4674. #include <stdint.h>
  4675. typedef struct c11_serializer {
  4676. c11_vector data;
  4677. } c11_serializer;
  4678. void c11_serializer__ctor(c11_serializer* self, int16_t magic, int8_t major_ver, int8_t minor_ver);
  4679. void c11_serializer__dtor(c11_serializer* self);
  4680. void c11_serializer__write_mark(c11_serializer* self, char mark);
  4681. void c11_serializer__write_cstr(c11_serializer* self, const char*);
  4682. void c11_serializer__write_bytes(c11_serializer* self, const void* data, int size);
  4683. void* c11_serializer__submit(c11_serializer* self, int* size);
  4684. typedef struct c11_deserializer {
  4685. char error_msg[64];
  4686. const uint8_t* data;
  4687. int size;
  4688. int index;
  4689. int8_t major_ver;
  4690. int8_t minor_ver;
  4691. } c11_deserializer;
  4692. void c11_deserializer__ctor(c11_deserializer* self, const void* data, int size);
  4693. void c11_deserializer__dtor(c11_deserializer* self);
  4694. void c11_deserializer__consume_mark(c11_deserializer* self, char expected);
  4695. bool c11_deserializer__check_header(c11_deserializer* self, int16_t magic, int8_t major_ver, int8_t minor_ver_min);
  4696. const char* c11_deserializer__read_cstr(c11_deserializer* self);
  4697. void* c11_deserializer__read_bytes(c11_deserializer* self, int size);
  4698. #define DEF_ATOMIC_INLINE_RW(name, T) \
  4699. static inline void c11_serializer__write_##name(c11_serializer* self, T value){ \
  4700. c11_serializer__write_bytes(self, &value, sizeof(T)); \
  4701. } \
  4702. static inline T c11_deserializer__read_##name(c11_deserializer* self){ \
  4703. const void* p = self->data + self->index; \
  4704. self->index += sizeof(T); \
  4705. T retval;\
  4706. memcpy(&retval, p, sizeof(T)); \
  4707. return retval; \
  4708. }
  4709. DEF_ATOMIC_INLINE_RW(i8, int8_t)
  4710. DEF_ATOMIC_INLINE_RW(i16, int16_t)
  4711. DEF_ATOMIC_INLINE_RW(i32, int32_t)
  4712. DEF_ATOMIC_INLINE_RW(i64, int64_t)
  4713. DEF_ATOMIC_INLINE_RW(f32, float)
  4714. DEF_ATOMIC_INLINE_RW(f64, double)
  4715. DEF_ATOMIC_INLINE_RW(type, py_Type)
  4716. #undef DEF_ATOMIC_INLINE_RW
  4717. // common/smallmap.h
  4718. #include <stdint.h>
  4719. #define SMALLMAP_T__HEADER
  4720. #define K py_Name
  4721. #define V int
  4722. #define NAME c11_smallmap_n2d
  4723. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  4724. #include "pocketpy/common/vector.h"
  4725. #include "pocketpy/common/utils.h"
  4726. #include "pocketpy/config.h"
  4727. #define SMALLMAP_T__HEADER
  4728. #define SMALLMAP_T__SOURCE
  4729. /* Input */
  4730. #define K int
  4731. #define V float
  4732. #define NAME c11_smallmap_d2f
  4733. #endif
  4734. /* Optional Input */
  4735. #ifndef less
  4736. #define less(a, b) ((a) < (b))
  4737. #endif
  4738. #ifndef equal
  4739. #define equal(a, b) ((a) == (b))
  4740. #endif
  4741. /* Temporary macros */
  4742. #define partial_less(a, b) less((a).key, (b))
  4743. #define CONCAT(A, B) CONCAT_(A, B)
  4744. #define CONCAT_(A, B) A##B
  4745. #define KV CONCAT(NAME, _KV)
  4746. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  4747. #ifdef SMALLMAP_T__HEADER
  4748. /* Declaration */
  4749. typedef struct {
  4750. K key;
  4751. V value;
  4752. } KV;
  4753. typedef c11_vector NAME;
  4754. void METHOD(ctor)(NAME* self);
  4755. void METHOD(dtor)(NAME* self);
  4756. NAME* METHOD(new)();
  4757. void METHOD(delete)(NAME* self);
  4758. void METHOD(set)(NAME* self, K key, V value);
  4759. V* METHOD(try_get)(const NAME* self, K key);
  4760. V METHOD(get)(const NAME* self, K key, V default_value);
  4761. bool METHOD(contains)(const NAME* self, K key);
  4762. bool METHOD(del)(NAME* self, K key);
  4763. void METHOD(clear)(NAME* self);
  4764. #endif
  4765. #ifdef SMALLMAP_T__SOURCE
  4766. /* Implementation */
  4767. void METHOD(ctor)(NAME* self) {
  4768. c11_vector__ctor(self, sizeof(KV));
  4769. c11_vector__reserve(self, 4);
  4770. }
  4771. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  4772. NAME* METHOD(new)() {
  4773. NAME* self = PK_MALLOC(sizeof(NAME));
  4774. METHOD(ctor)(self);
  4775. return self;
  4776. }
  4777. void METHOD(delete)(NAME* self) {
  4778. METHOD(dtor)(self);
  4779. PK_FREE(self);
  4780. }
  4781. void METHOD(set)(NAME* self, K key, V value) {
  4782. int index;
  4783. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  4784. if(index != self->length) {
  4785. KV* it = c11__at(KV, self, index);
  4786. if(equal(it->key, key)) {
  4787. it->value = value;
  4788. return;
  4789. }
  4790. }
  4791. KV kv = {key, value};
  4792. c11_vector__insert(KV, self, index, kv);
  4793. }
  4794. V* METHOD(try_get)(const NAME* self, K key) {
  4795. int index;
  4796. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  4797. if(index != self->length) {
  4798. KV* it = c11__at(KV, self, index);
  4799. if(equal(it->key, key)) return &it->value;
  4800. }
  4801. return NULL;
  4802. }
  4803. V METHOD(get)(const NAME* self, K key, V default_value) {
  4804. V* p = METHOD(try_get)(self, key);
  4805. return p ? *p : default_value;
  4806. }
  4807. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  4808. bool METHOD(del)(NAME* self, K key) {
  4809. int index;
  4810. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  4811. if(index != self->length) {
  4812. KV* it = c11__at(KV, self, index);
  4813. if(equal(it->key, key)) {
  4814. c11_vector__erase(KV, self, index);
  4815. return true;
  4816. }
  4817. }
  4818. return false;
  4819. }
  4820. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  4821. #endif
  4822. /* Undefine all macros */
  4823. #undef KV
  4824. #undef METHOD
  4825. #undef CONCAT
  4826. #undef CONCAT_
  4827. #undef K
  4828. #undef V
  4829. #undef NAME
  4830. #undef less
  4831. #undef partial_less
  4832. #undef equal
  4833. #undef SMALLMAP_T__HEADER
  4834. #define SMALLMAP_T__HEADER
  4835. #define K int
  4836. #define V int
  4837. #define NAME c11_smallmap_d2d
  4838. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  4839. #include "pocketpy/common/vector.h"
  4840. #include "pocketpy/common/utils.h"
  4841. #include "pocketpy/config.h"
  4842. #define SMALLMAP_T__HEADER
  4843. #define SMALLMAP_T__SOURCE
  4844. /* Input */
  4845. #define K int
  4846. #define V float
  4847. #define NAME c11_smallmap_d2f
  4848. #endif
  4849. /* Optional Input */
  4850. #ifndef less
  4851. #define less(a, b) ((a) < (b))
  4852. #endif
  4853. #ifndef equal
  4854. #define equal(a, b) ((a) == (b))
  4855. #endif
  4856. /* Temporary macros */
  4857. #define partial_less(a, b) less((a).key, (b))
  4858. #define CONCAT(A, B) CONCAT_(A, B)
  4859. #define CONCAT_(A, B) A##B
  4860. #define KV CONCAT(NAME, _KV)
  4861. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  4862. #ifdef SMALLMAP_T__HEADER
  4863. /* Declaration */
  4864. typedef struct {
  4865. K key;
  4866. V value;
  4867. } KV;
  4868. typedef c11_vector NAME;
  4869. void METHOD(ctor)(NAME* self);
  4870. void METHOD(dtor)(NAME* self);
  4871. NAME* METHOD(new)();
  4872. void METHOD(delete)(NAME* self);
  4873. void METHOD(set)(NAME* self, K key, V value);
  4874. V* METHOD(try_get)(const NAME* self, K key);
  4875. V METHOD(get)(const NAME* self, K key, V default_value);
  4876. bool METHOD(contains)(const NAME* self, K key);
  4877. bool METHOD(del)(NAME* self, K key);
  4878. void METHOD(clear)(NAME* self);
  4879. #endif
  4880. #ifdef SMALLMAP_T__SOURCE
  4881. /* Implementation */
  4882. void METHOD(ctor)(NAME* self) {
  4883. c11_vector__ctor(self, sizeof(KV));
  4884. c11_vector__reserve(self, 4);
  4885. }
  4886. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  4887. NAME* METHOD(new)() {
  4888. NAME* self = PK_MALLOC(sizeof(NAME));
  4889. METHOD(ctor)(self);
  4890. return self;
  4891. }
  4892. void METHOD(delete)(NAME* self) {
  4893. METHOD(dtor)(self);
  4894. PK_FREE(self);
  4895. }
  4896. void METHOD(set)(NAME* self, K key, V value) {
  4897. int index;
  4898. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  4899. if(index != self->length) {
  4900. KV* it = c11__at(KV, self, index);
  4901. if(equal(it->key, key)) {
  4902. it->value = value;
  4903. return;
  4904. }
  4905. }
  4906. KV kv = {key, value};
  4907. c11_vector__insert(KV, self, index, kv);
  4908. }
  4909. V* METHOD(try_get)(const NAME* self, K key) {
  4910. int index;
  4911. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  4912. if(index != self->length) {
  4913. KV* it = c11__at(KV, self, index);
  4914. if(equal(it->key, key)) return &it->value;
  4915. }
  4916. return NULL;
  4917. }
  4918. V METHOD(get)(const NAME* self, K key, V default_value) {
  4919. V* p = METHOD(try_get)(self, key);
  4920. return p ? *p : default_value;
  4921. }
  4922. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  4923. bool METHOD(del)(NAME* self, K key) {
  4924. int index;
  4925. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  4926. if(index != self->length) {
  4927. KV* it = c11__at(KV, self, index);
  4928. if(equal(it->key, key)) {
  4929. c11_vector__erase(KV, self, index);
  4930. return true;
  4931. }
  4932. }
  4933. return false;
  4934. }
  4935. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  4936. #endif
  4937. /* Undefine all macros */
  4938. #undef KV
  4939. #undef METHOD
  4940. #undef CONCAT
  4941. #undef CONCAT_
  4942. #undef K
  4943. #undef V
  4944. #undef NAME
  4945. #undef less
  4946. #undef partial_less
  4947. #undef equal
  4948. #undef SMALLMAP_T__HEADER
  4949. #define SMALLMAP_T__HEADER
  4950. #define K c11_sv
  4951. #define V int
  4952. #define NAME c11_smallmap_v2d
  4953. #define less(a, b) (c11_sv__cmp((a), (b)) < 0)
  4954. #define equal(a, b) c11__sveq((a), (b))
  4955. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  4956. #include "pocketpy/common/vector.h"
  4957. #include "pocketpy/common/utils.h"
  4958. #include "pocketpy/config.h"
  4959. #define SMALLMAP_T__HEADER
  4960. #define SMALLMAP_T__SOURCE
  4961. /* Input */
  4962. #define K int
  4963. #define V float
  4964. #define NAME c11_smallmap_d2f
  4965. #endif
  4966. /* Optional Input */
  4967. #ifndef less
  4968. #define less(a, b) ((a) < (b))
  4969. #endif
  4970. #ifndef equal
  4971. #define equal(a, b) ((a) == (b))
  4972. #endif
  4973. /* Temporary macros */
  4974. #define partial_less(a, b) less((a).key, (b))
  4975. #define CONCAT(A, B) CONCAT_(A, B)
  4976. #define CONCAT_(A, B) A##B
  4977. #define KV CONCAT(NAME, _KV)
  4978. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  4979. #ifdef SMALLMAP_T__HEADER
  4980. /* Declaration */
  4981. typedef struct {
  4982. K key;
  4983. V value;
  4984. } KV;
  4985. typedef c11_vector NAME;
  4986. void METHOD(ctor)(NAME* self);
  4987. void METHOD(dtor)(NAME* self);
  4988. NAME* METHOD(new)();
  4989. void METHOD(delete)(NAME* self);
  4990. void METHOD(set)(NAME* self, K key, V value);
  4991. V* METHOD(try_get)(const NAME* self, K key);
  4992. V METHOD(get)(const NAME* self, K key, V default_value);
  4993. bool METHOD(contains)(const NAME* self, K key);
  4994. bool METHOD(del)(NAME* self, K key);
  4995. void METHOD(clear)(NAME* self);
  4996. #endif
  4997. #ifdef SMALLMAP_T__SOURCE
  4998. /* Implementation */
  4999. void METHOD(ctor)(NAME* self) {
  5000. c11_vector__ctor(self, sizeof(KV));
  5001. c11_vector__reserve(self, 4);
  5002. }
  5003. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  5004. NAME* METHOD(new)() {
  5005. NAME* self = PK_MALLOC(sizeof(NAME));
  5006. METHOD(ctor)(self);
  5007. return self;
  5008. }
  5009. void METHOD(delete)(NAME* self) {
  5010. METHOD(dtor)(self);
  5011. PK_FREE(self);
  5012. }
  5013. void METHOD(set)(NAME* self, K key, V value) {
  5014. int index;
  5015. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5016. if(index != self->length) {
  5017. KV* it = c11__at(KV, self, index);
  5018. if(equal(it->key, key)) {
  5019. it->value = value;
  5020. return;
  5021. }
  5022. }
  5023. KV kv = {key, value};
  5024. c11_vector__insert(KV, self, index, kv);
  5025. }
  5026. V* METHOD(try_get)(const NAME* self, K key) {
  5027. int index;
  5028. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5029. if(index != self->length) {
  5030. KV* it = c11__at(KV, self, index);
  5031. if(equal(it->key, key)) return &it->value;
  5032. }
  5033. return NULL;
  5034. }
  5035. V METHOD(get)(const NAME* self, K key, V default_value) {
  5036. V* p = METHOD(try_get)(self, key);
  5037. return p ? *p : default_value;
  5038. }
  5039. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  5040. bool METHOD(del)(NAME* self, K key) {
  5041. int index;
  5042. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5043. if(index != self->length) {
  5044. KV* it = c11__at(KV, self, index);
  5045. if(equal(it->key, key)) {
  5046. c11_vector__erase(KV, self, index);
  5047. return true;
  5048. }
  5049. }
  5050. return false;
  5051. }
  5052. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  5053. #endif
  5054. /* Undefine all macros */
  5055. #undef KV
  5056. #undef METHOD
  5057. #undef CONCAT
  5058. #undef CONCAT_
  5059. #undef K
  5060. #undef V
  5061. #undef NAME
  5062. #undef less
  5063. #undef partial_less
  5064. #undef equal
  5065. #undef SMALLMAP_T__HEADER
  5066. #define SMALLMAP_T__HEADER
  5067. #define K void*
  5068. #define V py_i64
  5069. #define NAME c11_smallmap_p2i
  5070. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  5071. #include "pocketpy/common/vector.h"
  5072. #include "pocketpy/common/utils.h"
  5073. #include "pocketpy/config.h"
  5074. #define SMALLMAP_T__HEADER
  5075. #define SMALLMAP_T__SOURCE
  5076. /* Input */
  5077. #define K int
  5078. #define V float
  5079. #define NAME c11_smallmap_d2f
  5080. #endif
  5081. /* Optional Input */
  5082. #ifndef less
  5083. #define less(a, b) ((a) < (b))
  5084. #endif
  5085. #ifndef equal
  5086. #define equal(a, b) ((a) == (b))
  5087. #endif
  5088. /* Temporary macros */
  5089. #define partial_less(a, b) less((a).key, (b))
  5090. #define CONCAT(A, B) CONCAT_(A, B)
  5091. #define CONCAT_(A, B) A##B
  5092. #define KV CONCAT(NAME, _KV)
  5093. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  5094. #ifdef SMALLMAP_T__HEADER
  5095. /* Declaration */
  5096. typedef struct {
  5097. K key;
  5098. V value;
  5099. } KV;
  5100. typedef c11_vector NAME;
  5101. void METHOD(ctor)(NAME* self);
  5102. void METHOD(dtor)(NAME* self);
  5103. NAME* METHOD(new)();
  5104. void METHOD(delete)(NAME* self);
  5105. void METHOD(set)(NAME* self, K key, V value);
  5106. V* METHOD(try_get)(const NAME* self, K key);
  5107. V METHOD(get)(const NAME* self, K key, V default_value);
  5108. bool METHOD(contains)(const NAME* self, K key);
  5109. bool METHOD(del)(NAME* self, K key);
  5110. void METHOD(clear)(NAME* self);
  5111. #endif
  5112. #ifdef SMALLMAP_T__SOURCE
  5113. /* Implementation */
  5114. void METHOD(ctor)(NAME* self) {
  5115. c11_vector__ctor(self, sizeof(KV));
  5116. c11_vector__reserve(self, 4);
  5117. }
  5118. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  5119. NAME* METHOD(new)() {
  5120. NAME* self = PK_MALLOC(sizeof(NAME));
  5121. METHOD(ctor)(self);
  5122. return self;
  5123. }
  5124. void METHOD(delete)(NAME* self) {
  5125. METHOD(dtor)(self);
  5126. PK_FREE(self);
  5127. }
  5128. void METHOD(set)(NAME* self, K key, V value) {
  5129. int index;
  5130. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5131. if(index != self->length) {
  5132. KV* it = c11__at(KV, self, index);
  5133. if(equal(it->key, key)) {
  5134. it->value = value;
  5135. return;
  5136. }
  5137. }
  5138. KV kv = {key, value};
  5139. c11_vector__insert(KV, self, index, kv);
  5140. }
  5141. V* METHOD(try_get)(const NAME* self, K key) {
  5142. int index;
  5143. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5144. if(index != self->length) {
  5145. KV* it = c11__at(KV, self, index);
  5146. if(equal(it->key, key)) return &it->value;
  5147. }
  5148. return NULL;
  5149. }
  5150. V METHOD(get)(const NAME* self, K key, V default_value) {
  5151. V* p = METHOD(try_get)(self, key);
  5152. return p ? *p : default_value;
  5153. }
  5154. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  5155. bool METHOD(del)(NAME* self, K key) {
  5156. int index;
  5157. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5158. if(index != self->length) {
  5159. KV* it = c11__at(KV, self, index);
  5160. if(equal(it->key, key)) {
  5161. c11_vector__erase(KV, self, index);
  5162. return true;
  5163. }
  5164. }
  5165. return false;
  5166. }
  5167. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  5168. #endif
  5169. /* Undefine all macros */
  5170. #undef KV
  5171. #undef METHOD
  5172. #undef CONCAT
  5173. #undef CONCAT_
  5174. #undef K
  5175. #undef V
  5176. #undef NAME
  5177. #undef less
  5178. #undef partial_less
  5179. #undef equal
  5180. #undef SMALLMAP_T__HEADER
  5181. // common/sstream.h
  5182. #include <stdint.h>
  5183. typedef struct c11_sbuf {
  5184. c11_vector data;
  5185. } c11_sbuf;
  5186. void c11_sbuf__ctor(c11_sbuf* self);
  5187. void c11_sbuf__dtor(c11_sbuf* self);
  5188. void c11_sbuf__write_int(c11_sbuf* self, int);
  5189. void c11_sbuf__write_i64(c11_sbuf* self, int64_t);
  5190. void c11_sbuf__write_f64(c11_sbuf* self, double, int precision);
  5191. void c11_sbuf__write_char(c11_sbuf* self, char);
  5192. void c11_sbuf__write_pad(c11_sbuf* self, int count, char pad);
  5193. void c11_sbuf__write_sv(c11_sbuf* self, c11_sv);
  5194. void c11_sbuf__write_cstr(c11_sbuf* self, const char*);
  5195. void c11_sbuf__write_cstrn(c11_sbuf* self, const char*, int);
  5196. void c11_sbuf__write_quoted(c11_sbuf* self, c11_sv, char quote);
  5197. void c11_sbuf__write_hex(c11_sbuf* self, unsigned char, bool non_zero);
  5198. void c11_sbuf__write_ptr(c11_sbuf* self, void*);
  5199. // Submit the stream and return the final string. The stream becomes invalid after this call
  5200. c11_string* c11_sbuf__submit(c11_sbuf* self);
  5201. void c11_sbuf__py_submit(c11_sbuf* self, py_Ref out);
  5202. void pk_vsprintf(c11_sbuf* ss, const char* fmt, va_list args);
  5203. void pk_sprintf(c11_sbuf* ss, const char* fmt, ...);
  5204. // debugger/core.h
  5205. #if PK_ENABLE_OS
  5206. typedef enum { C11_STEP_IN, C11_STEP_OVER, C11_STEP_OUT, C11_STEP_CONTINUE } C11_STEP_MODE;
  5207. typedef enum { C11_DEBUGGER_NOSTOP, C11_DEBUGGER_STEP, C11_DEBUGGER_EXCEPTION, C11_DEBUGGER_BP} C11_STOP_REASON;
  5208. typedef enum {
  5209. C11_DEBUGGER_SUCCESS = 0,
  5210. C11_DEBUGGER_EXIT = 1,
  5211. C11_DEBUGGER_UNKNOW_ERROR = 3,
  5212. C11_DEBUGGER_FILEPATH_ERROR = 7
  5213. } C11_DEBUGGER_STATUS;
  5214. void c11_debugger_init(void);
  5215. void c11_debugger_set_step_mode(C11_STEP_MODE mode);
  5216. void c11_debugger_exception_on_trace(py_Ref exc);
  5217. C11_DEBUGGER_STATUS c11_debugger_on_trace(py_Frame* frame, enum py_TraceEvent event);
  5218. const char* c11_debugger_excinfo(const char ** message);
  5219. void c11_debugger_frames(c11_sbuf* buffer);
  5220. void c11_debugger_scopes(int frameid, c11_sbuf* buffer);
  5221. bool c11_debugger_unfold_var(int var_id, c11_sbuf* buffer);
  5222. int c11_debugger_setbreakpoint(const char* filename, int lineno);
  5223. int c11_debugger_reset_breakpoints_by_source(const char* sourcesname);
  5224. C11_STOP_REASON c11_debugger_should_pause(void);
  5225. int c11_debugger_should_keep_pause(void);
  5226. #endif // PK_ENABLE_OS
  5227. // interpreter/bindings.h
  5228. bool generator__next__(int argc, py_Ref argv);
  5229. bool array2d_like_iterator__next__(int argc, py_Ref argv);
  5230. bool list_iterator__next__(int argc, py_Ref argv);
  5231. bool tuple_iterator__next__(int argc, py_Ref argv);
  5232. bool dict_items__next__(int argc, py_Ref argv);
  5233. bool range_iterator__next__(int argc, py_Ref argv);
  5234. bool str_iterator__next__(int argc, py_Ref argv);
  5235. // interpreter/modules.h
  5236. void pk__add_module_os();
  5237. void pk__add_module_sys();
  5238. void pk__add_module_io();
  5239. void pk__add_module_math();
  5240. void pk__add_module_dis();
  5241. void pk__add_module_random();
  5242. void pk__add_module_json();
  5243. void pk__add_module_gc();
  5244. void pk__add_module_time();
  5245. void pk__add_module_easing();
  5246. void pk__add_module_traceback();
  5247. void pk__add_module_enum();
  5248. void pk__add_module_inspect();
  5249. void pk__add_module_pickle();
  5250. void pk__add_module_base64();
  5251. void pk__add_module_importlib();
  5252. void pk__add_module_unicodedata();
  5253. void pk__add_module_stdc();
  5254. void pk__add_module_vmath();
  5255. void pk__add_module_array2d();
  5256. void pk__add_module_colorcvt();
  5257. void pk__add_module_conio();
  5258. void pk__add_module_lz4();
  5259. void pk__add_module_pkpy();
  5260. void pk__add_module_picoterm();
  5261. #ifdef PK_BUILD_MODULE_CUTE_PNG
  5262. void pk__add_module_cute_png();
  5263. #else
  5264. #define pk__add_module_cute_png()
  5265. #endif
  5266. #ifdef PK_BUILD_MODULE_MSGPACK
  5267. void pk__add_module_msgpack();
  5268. #else
  5269. #define pk__add_module_msgpack()
  5270. #endif
  5271. #ifdef PK_BUILD_MODULE_PERIPHERY
  5272. void py__add_module_periphery();
  5273. #else
  5274. #define py__add_module_periphery()
  5275. #endif
  5276. // interpreter/objectpool.h
  5277. #define kPoolArenaSize (120 * 1024)
  5278. #define kMultiPoolCount 5
  5279. // #define kPoolMaxBlockSize (32 * kMultiPoolCount)
  5280. typedef struct PoolArena {
  5281. int block_size;
  5282. int block_count;
  5283. int unused_length;
  5284. union {
  5285. char data[kPoolArenaSize];
  5286. int64_t _align64;
  5287. };
  5288. int unused[];
  5289. } PoolArena;
  5290. typedef struct Pool {
  5291. c11_vector /* PoolArena* */ arenas;
  5292. int available_index;
  5293. int block_size;
  5294. } Pool;
  5295. typedef struct MultiPool {
  5296. Pool pools[kMultiPoolCount];
  5297. } MultiPool;
  5298. void* MultiPool__alloc(MultiPool* self, int size);
  5299. int MultiPool__sweep_dealloc(MultiPool* self, int* out_types);
  5300. void MultiPool__ctor(MultiPool* self);
  5301. void MultiPool__dtor(MultiPool* self);
  5302. size_t MultiPool__total_allocated_bytes(MultiPool* self);
  5303. c11_string* MultiPool__summary(MultiPool* self);
  5304. // objects/base.h
  5305. typedef struct PyObject PyObject;
  5306. typedef struct VM VM;
  5307. extern PK_THREAD_LOCAL VM* pk_current_vm;
  5308. typedef struct py_TValue {
  5309. py_Type type;
  5310. bool is_ptr;
  5311. int extra;
  5312. union {
  5313. int64_t _i64;
  5314. double _f64;
  5315. bool _bool;
  5316. py_CFunction _cfunc;
  5317. PyObject* _obj;
  5318. c11_vec2 _vec2;
  5319. c11_vec2i _vec2i;
  5320. c11_vec3 _vec3;
  5321. c11_vec3i _vec3i;
  5322. c11_vec4i _vec4i;
  5323. c11_color32 _color32;
  5324. void* _ptr;
  5325. char _chars[16];
  5326. };
  5327. } py_TValue;
  5328. // interpreter/array2d.h
  5329. typedef struct c11_array2d_like {
  5330. int n_cols;
  5331. int n_rows;
  5332. int numel;
  5333. py_Ref (*f_get)(struct c11_array2d_like* self, int col, int row);
  5334. bool (*f_set)(struct c11_array2d_like* self, int col, int row, py_Ref value);
  5335. } c11_array2d_like;
  5336. typedef struct c11_array2d_like_iterator {
  5337. c11_array2d_like* array;
  5338. int j;
  5339. int i;
  5340. } c11_array2d_like_iterator;
  5341. typedef struct c11_array2d {
  5342. c11_array2d_like header;
  5343. py_TValue* data; // slots
  5344. } c11_array2d;
  5345. typedef struct c11_array2d_view {
  5346. c11_array2d_like header;
  5347. void* ctx;
  5348. py_Ref (*f_get)(void* ctx, int col, int row);
  5349. bool (*f_set)(void* ctx, int col, int row, py_Ref value);
  5350. c11_vec2i origin;
  5351. } c11_array2d_view;
  5352. c11_array2d* c11_newarray2d(py_OutRef out, int n_cols, int n_rows);
  5353. /* chunked_array2d */
  5354. #define SMALLMAP_T__HEADER
  5355. #define K c11_vec2i
  5356. #define V py_TValue*
  5357. #define NAME c11_chunked_array2d_chunks
  5358. #define less(a, b) (a._i64 < b._i64)
  5359. #define equal(a, b) (a._i64 == b._i64)
  5360. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  5361. #include "pocketpy/common/vector.h"
  5362. #include "pocketpy/common/utils.h"
  5363. #include "pocketpy/config.h"
  5364. #define SMALLMAP_T__HEADER
  5365. #define SMALLMAP_T__SOURCE
  5366. /* Input */
  5367. #define K int
  5368. #define V float
  5369. #define NAME c11_smallmap_d2f
  5370. #endif
  5371. /* Optional Input */
  5372. #ifndef less
  5373. #define less(a, b) ((a) < (b))
  5374. #endif
  5375. #ifndef equal
  5376. #define equal(a, b) ((a) == (b))
  5377. #endif
  5378. /* Temporary macros */
  5379. #define partial_less(a, b) less((a).key, (b))
  5380. #define CONCAT(A, B) CONCAT_(A, B)
  5381. #define CONCAT_(A, B) A##B
  5382. #define KV CONCAT(NAME, _KV)
  5383. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  5384. #ifdef SMALLMAP_T__HEADER
  5385. /* Declaration */
  5386. typedef struct {
  5387. K key;
  5388. V value;
  5389. } KV;
  5390. typedef c11_vector NAME;
  5391. void METHOD(ctor)(NAME* self);
  5392. void METHOD(dtor)(NAME* self);
  5393. NAME* METHOD(new)();
  5394. void METHOD(delete)(NAME* self);
  5395. void METHOD(set)(NAME* self, K key, V value);
  5396. V* METHOD(try_get)(const NAME* self, K key);
  5397. V METHOD(get)(const NAME* self, K key, V default_value);
  5398. bool METHOD(contains)(const NAME* self, K key);
  5399. bool METHOD(del)(NAME* self, K key);
  5400. void METHOD(clear)(NAME* self);
  5401. #endif
  5402. #ifdef SMALLMAP_T__SOURCE
  5403. /* Implementation */
  5404. void METHOD(ctor)(NAME* self) {
  5405. c11_vector__ctor(self, sizeof(KV));
  5406. c11_vector__reserve(self, 4);
  5407. }
  5408. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  5409. NAME* METHOD(new)() {
  5410. NAME* self = PK_MALLOC(sizeof(NAME));
  5411. METHOD(ctor)(self);
  5412. return self;
  5413. }
  5414. void METHOD(delete)(NAME* self) {
  5415. METHOD(dtor)(self);
  5416. PK_FREE(self);
  5417. }
  5418. void METHOD(set)(NAME* self, K key, V value) {
  5419. int index;
  5420. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5421. if(index != self->length) {
  5422. KV* it = c11__at(KV, self, index);
  5423. if(equal(it->key, key)) {
  5424. it->value = value;
  5425. return;
  5426. }
  5427. }
  5428. KV kv = {key, value};
  5429. c11_vector__insert(KV, self, index, kv);
  5430. }
  5431. V* METHOD(try_get)(const NAME* self, K key) {
  5432. int index;
  5433. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5434. if(index != self->length) {
  5435. KV* it = c11__at(KV, self, index);
  5436. if(equal(it->key, key)) return &it->value;
  5437. }
  5438. return NULL;
  5439. }
  5440. V METHOD(get)(const NAME* self, K key, V default_value) {
  5441. V* p = METHOD(try_get)(self, key);
  5442. return p ? *p : default_value;
  5443. }
  5444. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  5445. bool METHOD(del)(NAME* self, K key) {
  5446. int index;
  5447. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  5448. if(index != self->length) {
  5449. KV* it = c11__at(KV, self, index);
  5450. if(equal(it->key, key)) {
  5451. c11_vector__erase(KV, self, index);
  5452. return true;
  5453. }
  5454. }
  5455. return false;
  5456. }
  5457. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  5458. #endif
  5459. /* Undefine all macros */
  5460. #undef KV
  5461. #undef METHOD
  5462. #undef CONCAT
  5463. #undef CONCAT_
  5464. #undef K
  5465. #undef V
  5466. #undef NAME
  5467. #undef less
  5468. #undef partial_less
  5469. #undef equal
  5470. #undef SMALLMAP_T__HEADER
  5471. typedef struct c11_chunked_array2d {
  5472. c11_chunked_array2d_chunks chunks;
  5473. int chunk_size;
  5474. int chunk_size_log2;
  5475. int chunk_size_mask;
  5476. c11_chunked_array2d_chunks_KV last_visited;
  5477. py_TValue default_T;
  5478. bool auto_add_chunk;
  5479. } c11_chunked_array2d;
  5480. py_Ref c11_chunked_array2d__get(c11_chunked_array2d* self, int col, int row);
  5481. bool c11_chunked_array2d__set(c11_chunked_array2d* self, int col, int row, py_Ref value);
  5482. // interpreter/types.h
  5483. #include <stdio.h>
  5484. typedef struct {
  5485. uint64_t hash;
  5486. py_TValue key;
  5487. py_TValue val;
  5488. } DictEntry;
  5489. typedef struct {
  5490. int length;
  5491. uint32_t capacity;
  5492. uint32_t null_index_value;
  5493. bool index_is_short;
  5494. void* indices;
  5495. c11_vector /*T=DictEntry*/ entries;
  5496. } Dict;
  5497. typedef c11_vector List;
  5498. void c11_chunked_array2d__mark(void* ud, c11_vector* p_stack);
  5499. void function__gc_mark(void* ud, c11_vector* p_stack);
  5500. typedef struct {
  5501. FILE* file; // cute_png will cast the whole userdata to FILE**
  5502. const char* path;
  5503. const char* mode;
  5504. } io_FileIO;
  5505. // objects/bintree.h
  5506. typedef struct BinTreeConfig {
  5507. int (*f_cmp)(void* lhs, void* rhs);
  5508. bool need_free_key;
  5509. } BinTreeConfig;
  5510. typedef struct BinTree {
  5511. void* key;
  5512. py_TValue value;
  5513. const BinTreeConfig* config;
  5514. struct BinTree* left;
  5515. struct BinTree* right;
  5516. } BinTree;
  5517. void BinTree__ctor(BinTree* self, void* key, py_Ref value, const BinTreeConfig* config);
  5518. void BinTree__dtor(BinTree* self);
  5519. void BinTree__set(BinTree* self, void* key, py_Ref value);
  5520. py_Ref BinTree__try_get(BinTree* self, void* key);
  5521. bool BinTree__contains(BinTree* self, void* key);
  5522. void BinTree__apply_mark(BinTree* self, c11_vector* p_stack);
  5523. // objects/container.h
  5524. #include <stdint.h>
  5525. #define FIXEDHASH_T__HEADER
  5526. #define K py_Name
  5527. #define V py_TValue
  5528. #define NAME CachedNames
  5529. #if !defined(FIXEDHASH_T__HEADER) && !defined(FIXEDHASH_T__SOURCE)
  5530. #include "pocketpy/common/chunkedvector.h"
  5531. #include "pocketpy/config.h"
  5532. #include <stdint.h>
  5533. #define FIXEDHASH_T__HEADER
  5534. #define FIXEDHASH_T__SOURCE
  5535. /* Input */
  5536. #define K int
  5537. #define V float
  5538. #define NAME c11_fixedhash_d2f
  5539. #endif
  5540. /* Optional Input */
  5541. #ifndef hash
  5542. #define hash(a) ((uint64_t)(a))
  5543. #endif
  5544. #ifndef equal
  5545. #define equal(a, b) ((a) == (b))
  5546. #endif
  5547. /* Temporary macros */
  5548. #define CONCAT(A, B) CONCAT_(A, B)
  5549. #define CONCAT_(A, B) A##B
  5550. #define KV CONCAT(NAME, _KV)
  5551. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  5552. #ifdef FIXEDHASH_T__HEADER
  5553. /* Declaration */
  5554. typedef struct {
  5555. uint64_t hash;
  5556. K key;
  5557. V val;
  5558. } KV;
  5559. typedef struct {
  5560. int length;
  5561. uint16_t indices[0x10000];
  5562. c11_chunkedvector /*T=FixedHashEntry*/ entries;
  5563. } NAME;
  5564. void METHOD(ctor)(NAME* self);
  5565. void METHOD(dtor)(NAME* self);
  5566. NAME* METHOD(new)();
  5567. void METHOD(delete)(NAME* self);
  5568. void METHOD(set)(NAME* self, K key, V* value);
  5569. V* METHOD(try_get)(NAME* self, K key);
  5570. bool METHOD(contains)(NAME* self, K key);
  5571. #endif
  5572. #ifdef FIXEDHASH_T__SOURCE
  5573. /* Implementation */
  5574. void METHOD(ctor)(NAME* self) {
  5575. self->length = 0;
  5576. memset(self->indices, 0xFF, sizeof(self->indices));
  5577. c11_chunkedvector__ctor(&self->entries, sizeof(KV), 0);
  5578. }
  5579. void METHOD(dtor)(NAME* self) { c11_chunkedvector__dtor(&self->entries); }
  5580. NAME* METHOD(new)() {
  5581. NAME* self = PK_MALLOC(sizeof(NAME));
  5582. METHOD(ctor)(self);
  5583. return self;
  5584. }
  5585. void METHOD(delete)(NAME* self) {
  5586. METHOD(dtor)(self);
  5587. PK_FREE(self);
  5588. }
  5589. void METHOD(set)(NAME* self, K key, V* value) {
  5590. uint64_t hash_value = hash(key);
  5591. int index = (uint16_t)(hash_value & 0xFFFF);
  5592. while(self->indices[index] != 0xFFFF) {
  5593. KV* entry = c11_chunkedvector__at(&self->entries, self->indices[index]);
  5594. if(equal(entry->key, key)) {
  5595. entry->val = *value;
  5596. return;
  5597. }
  5598. index = ((5 * index) + 1) & 0xFFFF;
  5599. }
  5600. if(self->length >= 65000) abort();
  5601. KV* kv = c11_chunkedvector__emplace(&self->entries);
  5602. kv->hash = hash_value;
  5603. kv->key = key;
  5604. kv->val = *value;
  5605. self->indices[index] = self->entries.length - 1;
  5606. self->length++;
  5607. }
  5608. V* METHOD(try_get)(NAME* self, K key) {
  5609. uint64_t hash_value = hash(key);
  5610. int index = (uint16_t)(hash_value & 0xFFFF);
  5611. while(self->indices[index] != 0xFFFF) {
  5612. KV* entry = c11_chunkedvector__at(&self->entries, self->indices[index]);
  5613. if(equal(entry->key, key)) return &entry->val;
  5614. index = ((5 * index) + 1) & 0xFFFF;
  5615. }
  5616. return NULL;
  5617. }
  5618. bool METHOD(contains)(NAME* self, K key) {
  5619. V* value = METHOD(try_get)(self, key);
  5620. return value != NULL;
  5621. }
  5622. #endif
  5623. /* Undefine all macros */
  5624. #undef KV
  5625. #undef METHOD
  5626. #undef CONCAT
  5627. #undef CONCAT_
  5628. #undef K
  5629. #undef V
  5630. #undef NAME
  5631. #undef less
  5632. #undef partial_less
  5633. #undef equal
  5634. #undef hash
  5635. #undef FIXEDHASH_T__HEADER
  5636. // objects/iterator.h
  5637. typedef struct tuple_iterator {
  5638. py_TValue* p;
  5639. int length;
  5640. int index;
  5641. } tuple_iterator;
  5642. typedef struct list_iterator {
  5643. c11_vector* vec;
  5644. int index;
  5645. } list_iterator;
  5646. // objects/namedict.h
  5647. typedef struct NameDict_KV {
  5648. py_Name key;
  5649. py_TValue value;
  5650. } NameDict_KV;
  5651. // https://github.com/pocketpy/pocketpy/blob/v1.x/include/pocketpy/namedict.h
  5652. typedef struct NameDict {
  5653. int length;
  5654. float load_factor;
  5655. int capacity;
  5656. int critical_size;
  5657. uintptr_t mask;
  5658. NameDict_KV* items;
  5659. } NameDict;
  5660. NameDict* NameDict__new(float load_factor);
  5661. void NameDict__delete(NameDict* self);
  5662. void NameDict__ctor(NameDict* self, float load_factor);
  5663. void NameDict__dtor(NameDict* self);
  5664. py_TValue* NameDict__try_get(NameDict* self, py_Name key);
  5665. bool NameDict__contains(NameDict* self, py_Name key);
  5666. void NameDict__set(NameDict* self, py_Name key, py_TValue* value);
  5667. bool NameDict__del(NameDict* self, py_Name key);
  5668. void NameDict__clear(NameDict* self);
  5669. // objects/object.h
  5670. typedef struct PyObject {
  5671. py_Type type; // we have a duplicated type here for convenience
  5672. uint8_t size_8b;
  5673. uint8_t gc_marked; // lsb (self is marked), 2nd lsb (no recursively mark)
  5674. int slots; // number of slots in the object
  5675. char flex[];
  5676. } PyObject;
  5677. // slots >= 0, allocate N slots
  5678. // slots == -1, allocate a dict
  5679. // | HEADER | <N slots> | <userdata>
  5680. // | HEADER | <dict> | <userdata>
  5681. py_TValue* PyObject__slots(PyObject* self);
  5682. NameDict* PyObject__dict(PyObject* self);
  5683. void* PyObject__userdata(PyObject* self);
  5684. #define PK_OBJ_SLOTS_SIZE(slots) ((slots) >= 0 ? sizeof(py_TValue) * (slots) : sizeof(NameDict))
  5685. void PyObject__dtor(PyObject* self);
  5686. #define pk__mark_value(val) \
  5687. if((val)->is_ptr) { \
  5688. PyObject* obj = (val)->_obj; \
  5689. if(!(obj->gc_marked & 0b01)) { \
  5690. obj->gc_marked |= 0b01; \
  5691. if(!(obj->gc_marked & 0b10)) { c11_vector__push(PyObject*, p_stack, obj); } \
  5692. } \
  5693. }
  5694. // interpreter/heap.h
  5695. #include <time.h>
  5696. typedef struct ManagedHeap {
  5697. MultiPool small_objects;
  5698. c11_vector /* PyObject_p */ large_objects;
  5699. c11_vector /* PyObject_p */ gc_roots;
  5700. size_t large_total_size;
  5701. int freed_ma[3];
  5702. int gc_threshold; // threshold for gc_counter
  5703. int gc_counter; // objects created since last gc
  5704. bool gc_enabled;
  5705. py_TValue debug_callback;
  5706. } ManagedHeap;
  5707. typedef struct {
  5708. int64_t start_ns;
  5709. int64_t mark_end_ns;
  5710. int64_t swpet_end_ns;
  5711. int types_length;
  5712. int* small_types;
  5713. int* large_types;
  5714. int small_freed;
  5715. int large_freed;
  5716. struct {
  5717. int before;
  5718. int after;
  5719. int upper;
  5720. int lower;
  5721. int avg_freed;
  5722. float free_ratio;
  5723. } auto_thres;
  5724. } ManagedHeapSwpetInfo;
  5725. void ManagedHeap__ctor(ManagedHeap* self);
  5726. void ManagedHeap__dtor(ManagedHeap* self);
  5727. ManagedHeapSwpetInfo* ManagedHeapSwpetInfo__new();
  5728. void ManagedHeapSwpetInfo__delete(ManagedHeapSwpetInfo* self);
  5729. int ManagedHeap__collect_hint(ManagedHeap* self);
  5730. int ManagedHeap__collect(ManagedHeap* self);
  5731. int ManagedHeap__sweep(ManagedHeap* self, ManagedHeapSwpetInfo* out_info);
  5732. #define ManagedHeap__new(self, type, slots, udsize) \
  5733. ManagedHeap__gcnew((self), (type), (slots), (udsize))
  5734. PyObject* ManagedHeap__gcnew(ManagedHeap* self, py_Type type, int slots, int udsize);
  5735. // external implementation
  5736. void ManagedHeap__mark(ManagedHeap* self);
  5737. // interpreter/typeinfo.h
  5738. typedef struct py_TypeInfo {
  5739. py_Name name;
  5740. py_Type index;
  5741. py_Type base;
  5742. struct py_TypeInfo* base_ti;
  5743. py_TValue self;
  5744. py_GlobalRef module;
  5745. bool is_python; // is it a python class? (not derived from c object)
  5746. bool is_final; // can it be subclassed?
  5747. bool (*getattribute)(py_Ref self, py_Name name) PY_RAISE PY_RETURN;
  5748. bool (*setattribute)(py_Ref self, py_Name name, py_Ref val) PY_RAISE PY_RETURN;
  5749. bool (*delattribute)(py_Ref self, py_Name name) PY_RAISE;
  5750. bool (*getunboundmethod)(py_Ref self, py_Name name) PY_RETURN;
  5751. py_TValue annotations;
  5752. py_Dtor dtor; // destructor for this type, NULL if no dtor
  5753. void (*on_end_subclass)(struct py_TypeInfo*); // backdoor for enum module
  5754. } py_TypeInfo;
  5755. py_TypeInfo* pk_typeinfo(py_Type type);
  5756. py_ItemRef pk_tpfindname(py_TypeInfo* ti, py_Name name);
  5757. #define pk_tpfindmagic pk_tpfindname
  5758. py_Type pk_newtype(const char* name,
  5759. py_Type base,
  5760. const py_GlobalRef module,
  5761. void (*dtor)(void*),
  5762. bool is_python,
  5763. bool is_final);
  5764. py_Type pk_newtypewithmode(py_Name name,
  5765. py_Type base,
  5766. const py_GlobalRef module,
  5767. void (*dtor)(void*),
  5768. bool is_python,
  5769. bool is_final, enum py_CompileMode mode);
  5770. // objects/sourcedata.h
  5771. #include <stdbool.h>
  5772. struct SourceData {
  5773. RefCounted rc;
  5774. enum py_CompileMode mode;
  5775. bool is_dynamic; // for exec() and eval()
  5776. c11_string* filename;
  5777. c11_string* source;
  5778. c11_vector /*T=const char* */ line_starts;
  5779. };
  5780. typedef struct SourceData* SourceData_;
  5781. SourceData_ SourceData__rcnew(const char* source,
  5782. const char* filename,
  5783. enum py_CompileMode mode,
  5784. bool is_dynamic);
  5785. bool SourceData__get_line(const struct SourceData* self,
  5786. int lineno,
  5787. const char** st,
  5788. const char** ed);
  5789. void SourceData__snapshot(const struct SourceData* self,
  5790. c11_sbuf* ss,
  5791. int lineno,
  5792. const char* cursor,
  5793. const char* name);
  5794. // objects/codeobject.h
  5795. #include <stdbool.h>
  5796. #include <stdint.h>
  5797. #define BC_NOARG 0
  5798. #define BC_KEEPLINE -1
  5799. #define BC_RETURN_VIRTUAL 5
  5800. typedef enum FuncType {
  5801. FuncType_UNSET,
  5802. FuncType_NORMAL,
  5803. FuncType_SIMPLE,
  5804. FuncType_GENERATOR,
  5805. } FuncType;
  5806. typedef enum NameScope {
  5807. NAME_LOCAL,
  5808. NAME_GLOBAL,
  5809. } NameScope;
  5810. typedef enum CodeBlockType {
  5811. CodeBlockType_NO_BLOCK,
  5812. CodeBlockType_WHILE_LOOP,
  5813. CodeBlockType_TRY,
  5814. /* context blocks (stack-based) */
  5815. CodeBlockType_FOR_LOOP,
  5816. CodeBlockType_WITH,
  5817. /* context blocks (flag-based) */
  5818. CodeBlockType_EXCEPT,
  5819. } CodeBlockType;
  5820. typedef enum Opcode {
  5821. #define OPCODE(name) OP_##name,
  5822. #ifdef OPCODE
  5823. /**************************/
  5824. OPCODE(NO_OP)
  5825. /**************************/
  5826. OPCODE(POP_TOP)
  5827. OPCODE(DUP_TOP)
  5828. OPCODE(DUP_TOP_TWO)
  5829. OPCODE(ROT_TWO)
  5830. OPCODE(ROT_THREE)
  5831. OPCODE(PRINT_EXPR)
  5832. /**************************/
  5833. OPCODE(LOAD_CONST)
  5834. OPCODE(LOAD_NONE)
  5835. OPCODE(LOAD_TRUE)
  5836. OPCODE(LOAD_FALSE)
  5837. /**************************/
  5838. OPCODE(LOAD_SMALL_INT)
  5839. OPCODE(LOAD_NAME_AS_INT)
  5840. /**************************/
  5841. OPCODE(LOAD_ELLIPSIS)
  5842. OPCODE(LOAD_FUNCTION)
  5843. OPCODE(LOAD_NULL)
  5844. /**************************/
  5845. OPCODE(LOAD_FAST)
  5846. OPCODE(LOAD_NAME)
  5847. OPCODE(LOAD_NONLOCAL)
  5848. OPCODE(LOAD_GLOBAL)
  5849. OPCODE(LOAD_ATTR)
  5850. OPCODE(LOAD_SELF_ATTR)
  5851. OPCODE(LOAD_CLASS_GLOBAL)
  5852. OPCODE(LOAD_METHOD)
  5853. OPCODE(LOAD_SUBSCR)
  5854. OPCODE(STORE_FAST)
  5855. OPCODE(STORE_NAME)
  5856. OPCODE(STORE_GLOBAL)
  5857. OPCODE(STORE_ATTR)
  5858. OPCODE(STORE_SELF_ATTR)
  5859. OPCODE(STORE_SUBSCR)
  5860. OPCODE(DELETE_FAST)
  5861. OPCODE(DELETE_NAME)
  5862. OPCODE(DELETE_GLOBAL)
  5863. OPCODE(DELETE_ATTR)
  5864. OPCODE(DELETE_SUBSCR)
  5865. /**************************/
  5866. OPCODE(BUILD_IMAG)
  5867. OPCODE(BUILD_BYTES)
  5868. OPCODE(BUILD_TUPLE)
  5869. OPCODE(BUILD_LIST)
  5870. OPCODE(BUILD_DICT)
  5871. OPCODE(BUILD_SET)
  5872. OPCODE(BUILD_SLICE)
  5873. OPCODE(BUILD_STRING)
  5874. /**************************/
  5875. OPCODE(BINARY_ADD)
  5876. OPCODE(BINARY_SUB)
  5877. OPCODE(BINARY_MUL)
  5878. OPCODE(BINARY_TRUEDIV)
  5879. OPCODE(BINARY_FLOORDIV)
  5880. OPCODE(BINARY_MOD)
  5881. OPCODE(BINARY_POW)
  5882. OPCODE(BINARY_LSHIFT)
  5883. OPCODE(BINARY_RSHIFT)
  5884. OPCODE(BINARY_AND)
  5885. OPCODE(BINARY_OR)
  5886. OPCODE(BINARY_XOR)
  5887. OPCODE(BINARY_MATMUL)
  5888. OPCODE(COMPARE_LT)
  5889. OPCODE(COMPARE_LE)
  5890. OPCODE(COMPARE_EQ)
  5891. OPCODE(COMPARE_NE)
  5892. OPCODE(COMPARE_GT)
  5893. OPCODE(COMPARE_GE)
  5894. OPCODE(IS_OP)
  5895. OPCODE(CONTAINS_OP)
  5896. /**************************/
  5897. OPCODE(JUMP_FORWARD)
  5898. OPCODE(POP_JUMP_IF_NOT_MATCH)
  5899. OPCODE(POP_JUMP_IF_FALSE)
  5900. OPCODE(POP_JUMP_IF_TRUE)
  5901. OPCODE(JUMP_IF_TRUE_OR_POP)
  5902. OPCODE(JUMP_IF_FALSE_OR_POP)
  5903. OPCODE(SHORTCUT_IF_FALSE_OR_POP)
  5904. OPCODE(LOOP_CONTINUE)
  5905. OPCODE(LOOP_BREAK)
  5906. /**************************/
  5907. OPCODE(CALL)
  5908. OPCODE(CALL_VARGS)
  5909. /**************************/
  5910. OPCODE(RETURN_VALUE)
  5911. OPCODE(YIELD_VALUE)
  5912. OPCODE(FOR_ITER_YIELD_VALUE)
  5913. /**************************/
  5914. OPCODE(LIST_APPEND)
  5915. OPCODE(DICT_ADD)
  5916. OPCODE(SET_ADD)
  5917. /**************************/
  5918. OPCODE(UNARY_NEGATIVE)
  5919. OPCODE(UNARY_NOT)
  5920. OPCODE(UNARY_STAR)
  5921. OPCODE(UNARY_INVERT)
  5922. /**************************/
  5923. OPCODE(GET_ITER)
  5924. OPCODE(FOR_ITER)
  5925. /**************************/
  5926. OPCODE(IMPORT_PATH)
  5927. OPCODE(POP_IMPORT_STAR)
  5928. /**************************/
  5929. OPCODE(UNPACK_SEQUENCE)
  5930. OPCODE(UNPACK_EX)
  5931. /**************************/
  5932. OPCODE(BEGIN_CLASS)
  5933. OPCODE(END_CLASS)
  5934. OPCODE(STORE_CLASS_ATTR)
  5935. OPCODE(ADD_CLASS_ANNOTATION)
  5936. /**************************/
  5937. OPCODE(WITH_ENTER)
  5938. OPCODE(WITH_EXIT)
  5939. /**************************/
  5940. OPCODE(BEGIN_TRY)
  5941. OPCODE(END_TRY)
  5942. OPCODE(EXCEPTION_MATCH)
  5943. OPCODE(HANDLE_EXCEPTION)
  5944. OPCODE(RAISE)
  5945. OPCODE(RAISE_ASSERT)
  5946. OPCODE(RE_RAISE)
  5947. OPCODE(PUSH_EXCEPTION)
  5948. /**************************/
  5949. OPCODE(FORMAT_STRING)
  5950. /**************************/
  5951. #endif
  5952. #undef OPCODE
  5953. } Opcode;
  5954. typedef struct Bytecode {
  5955. uint16_t op;
  5956. uint16_t arg;
  5957. } Bytecode;
  5958. void Bytecode__set_signed_arg(Bytecode* self, int arg);
  5959. bool Bytecode__is_forward_jump(const Bytecode* self);
  5960. typedef struct BytecodeEx {
  5961. int32_t lineno; // line number for each bytecode
  5962. int32_t iblock; // block index
  5963. } BytecodeEx;
  5964. typedef struct CodeBlock {
  5965. int32_t type;
  5966. int32_t parent; // parent index in blocks
  5967. int32_t start; // start index of this block in codes, inclusive
  5968. int32_t end; // end index of this block in codes, exclusive
  5969. int32_t end2; // ...
  5970. } CodeBlock;
  5971. typedef struct CodeObject {
  5972. SourceData_ src;
  5973. c11_string* name;
  5974. c11_vector /*T=Bytecode*/ codes;
  5975. c11_vector /*T=CodeObjectByteCodeEx*/ codes_ex;
  5976. c11_vector /*T=py_TValue*/ consts; // constants
  5977. c11_vector /*T=py_Name*/ varnames; // local variables
  5978. c11_vector /*T=py_Name*/ names; // non-local names
  5979. int nlocals; // number of local variables
  5980. c11_smallmap_n2d varnames_inv;
  5981. c11_smallmap_n2d names_inv;
  5982. c11_vector /*T=CodeBlock*/ blocks;
  5983. c11_vector /*T=FuncDecl_*/ func_decls;
  5984. int start_line;
  5985. int end_line;
  5986. } CodeObject;
  5987. void CodeObject__ctor(CodeObject* self, SourceData_ src, c11_sv name);
  5988. void CodeObject__dtor(CodeObject* self);
  5989. int CodeObject__add_varname(CodeObject* self, py_Name name);
  5990. int CodeObject__add_name(CodeObject* self, py_Name name);
  5991. void CodeObject__gc_mark(const CodeObject* self, c11_vector* p_stack);
  5992. // Serialization
  5993. void* CodeObject__dumps(const CodeObject* co, int* size);
  5994. char* CodeObject__loads(const void* data, int size, const char* filename, CodeObject* out);
  5995. typedef struct FuncDeclKwArg {
  5996. int index; // index in co->varnames
  5997. py_Name key; // name of this argument
  5998. py_TValue value; // default value
  5999. } FuncDeclKwArg;
  6000. typedef struct FuncDecl {
  6001. RefCounted rc;
  6002. CodeObject code; // strong ref
  6003. c11_vector /*T=int32_t*/ args; // indices in co->varnames
  6004. c11_vector /*T=FuncDeclKwArg*/ kwargs; // indices in co->varnames
  6005. int starred_arg; // index in co->varnames, -1 if no *arg
  6006. int starred_kwarg; // index in co->varnames, -1 if no **kwarg
  6007. bool nested; // whether this function is nested
  6008. char* docstring;
  6009. FuncType type;
  6010. c11_smallmap_n2d kw_to_index;
  6011. } FuncDecl;
  6012. typedef FuncDecl* FuncDecl_;
  6013. FuncDecl_ FuncDecl__rcnew(SourceData_ src, c11_sv name);
  6014. bool FuncDecl__is_duplicated_arg(const FuncDecl* self, py_Name name);
  6015. void FuncDecl__add_arg(FuncDecl* self, py_Name name);
  6016. void FuncDecl__add_kwarg(FuncDecl* self, py_Name name, const py_TValue* value);
  6017. void FuncDecl__add_starred_arg(FuncDecl* self, py_Name name);
  6018. void FuncDecl__add_starred_kwarg(FuncDecl* self, py_Name name);
  6019. void FuncDecl__gc_mark(const FuncDecl* self, c11_vector* p_stack);
  6020. void FuncDecl__dtor(void* p);
  6021. // runtime function
  6022. typedef struct Function {
  6023. FuncDecl_ decl;
  6024. py_GlobalRef module; // maybe NULL, weak ref
  6025. py_TValue globals; // maybe nil, strong ref
  6026. NameDict* closure; // maybe NULL, strong ref
  6027. PyObject* clazz; // weak ref; for super()
  6028. py_CFunction cfunc; // wrapped C function; for decl-based binding
  6029. } Function;
  6030. void Function__ctor(Function* self, FuncDecl_ decl, py_GlobalRef module, py_Ref globals);
  6031. void Function__dtor(Function* self);
  6032. // https://github.com/pocketpy/pocketpy/issues/456
  6033. // Function may be created from `execdyn` and return
  6034. // Weakrefs like `.globals` and `.clazz` may invalidate
  6035. // interpreter/frame.h
  6036. void FastLocals__to_dict(py_TValue* locals, const CodeObject* co) PY_RETURN;
  6037. NameDict* FastLocals__to_namedict(py_TValue* locals, const CodeObject* co);
  6038. typedef struct ValueStack {
  6039. py_TValue* sp;
  6040. py_TValue* end;
  6041. // We allocate extra places to keep `_sp` valid to detect stack overflow
  6042. py_TValue begin[PK_VM_STACK_SIZE + PK_MAX_CO_VARNAMES];
  6043. } ValueStack;
  6044. typedef struct FrameExcInfo {
  6045. int iblock; // try block index
  6046. int offset; // stack offset from p0
  6047. py_TValue exc; // handled exception
  6048. } FrameExcInfo;
  6049. typedef struct py_Frame {
  6050. struct py_Frame* f_back;
  6051. const CodeObject* co;
  6052. py_StackRef p0; // unwinding base
  6053. py_GlobalRef module;
  6054. py_Ref globals; // a module object or a dict object
  6055. py_Ref locals;
  6056. bool is_locals_special;
  6057. int ip;
  6058. c11_vector /*T=FrameExcInfo*/ exc_stack;
  6059. } py_Frame;
  6060. typedef struct SourceLocation {
  6061. SourceData_ src;
  6062. int lineno;
  6063. } SourceLocation;
  6064. py_Frame* Frame__new(const CodeObject* co,
  6065. py_StackRef p0,
  6066. py_GlobalRef module,
  6067. py_Ref globals,
  6068. py_Ref locals,
  6069. bool is_locals_special);
  6070. void Frame__delete(py_Frame* self);
  6071. int Frame__lineno(const py_Frame* self);
  6072. int Frame__iblock(const py_Frame* self);
  6073. int Frame__getglobal(py_Frame* self, py_Name name) PY_RAISE PY_RETURN;
  6074. bool Frame__setglobal(py_Frame* self, py_Name name, py_TValue* val) PY_RAISE;
  6075. int Frame__delglobal(py_Frame* self, py_Name name) PY_RAISE;
  6076. py_Ref Frame__getclosure(py_Frame* self, py_Name name);
  6077. py_StackRef Frame__getlocal_noproxy(py_Frame* self, py_Name name);
  6078. int Frame__goto_exception_handler(py_Frame* self, ValueStack*, py_Ref);
  6079. void Frame__begin_try(py_Frame* self, py_TValue* sp);
  6080. FrameExcInfo* Frame__top_exc_info(py_Frame* self);
  6081. void Frame__gc_mark(py_Frame* self, c11_vector* p_stack);
  6082. SourceLocation Frame__source_location(py_Frame* self);
  6083. // interpreter/generator.h
  6084. typedef struct Generator{
  6085. py_Frame* frame;
  6086. int state;
  6087. } Generator;
  6088. void pk_newgenerator(py_Ref out, py_Frame* frame, py_TValue* begin, py_TValue* end);
  6089. void Generator__dtor(Generator* ud);
  6090. // interpreter/line_profiler.h
  6091. #include <time.h>
  6092. typedef struct LineRecord {
  6093. py_i64 hits;
  6094. clock_t time;
  6095. } LineRecord;
  6096. typedef struct FrameRecord {
  6097. py_Frame* frame;
  6098. clock_t prev_time;
  6099. LineRecord* prev_line;
  6100. bool is_lambda;
  6101. } FrameRecord;
  6102. typedef struct LineProfiler {
  6103. c11_smallmap_p2i records; // SourceData* -> LineRecord[]
  6104. c11_vector /*T=FrameRecord*/ frame_records; // FrameRecord[]
  6105. bool enabled;
  6106. } LineProfiler;
  6107. void LineProfiler__ctor(LineProfiler* self);
  6108. void LineProfiler__dtor(LineProfiler* self);
  6109. LineRecord* LineProfiler__get_record(LineProfiler* self, SourceLocation loc);
  6110. void LineProfiler__begin(LineProfiler* self);
  6111. void LineProfiler__tracefunc_internal(LineProfiler* self, py_Frame* frame, enum py_TraceEvent event);
  6112. void LineProfiler__end(LineProfiler* self);
  6113. void LineProfiler__reset(LineProfiler* self);
  6114. c11_string* LineProfiler__get_report(LineProfiler* self);
  6115. void LineProfiler_tracefunc(py_Frame* frame, enum py_TraceEvent event);
  6116. // interpreter/vm.h
  6117. #include <time.h>
  6118. // TODO:
  6119. // 1. __eq__ and __ne__ fallbacks
  6120. // 2. un-cleared exception detection
  6121. // 3. super()
  6122. // 4. stack balance guanrantee
  6123. // 5. stack effect of each opcode
  6124. // 6. py_TypeInfo
  6125. typedef struct TraceInfo {
  6126. SourceLocation prev_loc;
  6127. py_TraceFunc func;
  6128. } TraceInfo;
  6129. typedef struct WatchdogInfo {
  6130. clock_t max_reset_time;
  6131. } WatchdogInfo;
  6132. typedef struct TypePointer {
  6133. py_TypeInfo* ti;
  6134. py_Dtor dtor;
  6135. } TypePointer;
  6136. typedef struct py_ModuleInfo {
  6137. c11_string* package;
  6138. c11_string* path;
  6139. py_GlobalRef self; // weakref to the original module object
  6140. } py_ModuleInfo;
  6141. typedef struct VM {
  6142. py_Frame* top_frame;
  6143. BinTree modules;
  6144. c11_vector /*TypePointer*/ types;
  6145. py_GlobalRef builtins; // builtins module
  6146. py_GlobalRef main; // __main__ module
  6147. py_Callbacks callbacks;
  6148. py_TValue last_retval;
  6149. py_TValue unhandled_exc;
  6150. int recursion_depth;
  6151. int max_recursion_depth;
  6152. py_TValue reg[14]; // users' registers
  6153. void* ctx; // user-defined context
  6154. CachedNames cached_names;
  6155. py_StackRef curr_class;
  6156. py_StackRef curr_function;
  6157. TraceInfo trace_info;
  6158. WatchdogInfo watchdog_info;
  6159. LineProfiler line_profiler;
  6160. py_TValue vectorcall_buffer[PK_MAX_CO_VARNAMES];
  6161. FixedMemoryPool pool_frame;
  6162. ManagedHeap heap;
  6163. ValueStack stack; // put `stack` at the end for better cache locality
  6164. } VM;
  6165. void VM__ctor(VM* self);
  6166. void VM__dtor(VM* self);
  6167. int VM__index(VM* self);
  6168. void VM__push_frame(VM* self, py_Frame* frame);
  6169. void VM__pop_frame(VM* self);
  6170. bool pk__parse_int_slice(py_Ref slice,
  6171. int length,
  6172. int* restrict start,
  6173. int* restrict stop,
  6174. int* restrict step);
  6175. bool pk__normalize_index(int* index, int length);
  6176. bool pk__object_new(int argc, py_Ref argv);
  6177. bool pk_wrapper__self(int argc, py_Ref argv);
  6178. const char* pk_op2str(py_Name op);
  6179. typedef enum FrameResult {
  6180. RES_ERROR = 0,
  6181. RES_RETURN = 1,
  6182. RES_CALL = 2,
  6183. RES_YIELD = 3,
  6184. } FrameResult;
  6185. FrameResult VM__run_top_frame(VM* self);
  6186. FrameResult VM__vectorcall(VM* self, uint16_t argc, uint16_t kwargc, bool opcall);
  6187. const char* pk_opname(Opcode op);
  6188. int pk_arrayview(py_Ref self, py_TValue** p);
  6189. bool pk_wrapper__arrayequal(py_Type type, int argc, py_Ref argv);
  6190. bool pk_arraycontains(py_Ref self, py_Ref val);
  6191. bool pk_loadmethod(py_StackRef self, py_Name name);
  6192. bool pk_callmagic(py_Name name, int argc, py_Ref argv);
  6193. bool pk_exec(CodeObject* co, py_Ref module);
  6194. bool pk_execdyn(CodeObject* co, py_Ref module, py_Ref globals, py_Ref locals);
  6195. /// Assumes [a, b] are on the stack, performs a binary op.
  6196. /// The result is stored in `self->last_retval`.
  6197. /// The stack remains unchanged.
  6198. bool pk_stack_binaryop(VM* self, py_Name op, py_Name rop);
  6199. void pk_print_stack(VM* self, py_Frame* frame, Bytecode byte);
  6200. bool pk_format_object(VM* self, py_Ref val, c11_sv spec);
  6201. // type registration
  6202. void pk_object__register();
  6203. void pk_number__register();
  6204. py_Type pk_str__register();
  6205. py_Type pk_str_iterator__register();
  6206. py_Type pk_bytes__register();
  6207. py_Type pk_bytes_iterator__register();
  6208. py_Type pk_dict__register();
  6209. py_Type pk_dict_items__register();
  6210. py_Type pk_list__register();
  6211. py_Type pk_tuple__register();
  6212. py_Type pk_list_iterator__register();
  6213. py_Type pk_tuple_iterator__register();
  6214. py_Type pk_slice__register();
  6215. py_Type pk_function__register();
  6216. py_Type pk_nativefunc__register();
  6217. py_Type pk_boundmethod__register();
  6218. py_Type pk_range__register();
  6219. py_Type pk_range_iterator__register();
  6220. py_Type pk_module__register();
  6221. py_Type pk_BaseException__register();
  6222. py_Type pk_Exception__register();
  6223. py_Type pk_StopIteration__register();
  6224. py_Type pk_super__register();
  6225. py_Type pk_property__register();
  6226. py_Type pk_staticmethod__register();
  6227. py_Type pk_classmethod__register();
  6228. py_Type pk_generator__register();
  6229. py_Type pk_namedict__register();
  6230. py_Type pk_code__register();
  6231. py_GlobalRef pk_builtins__register();
  6232. /* mappingproxy */
  6233. void pk_mappingproxy__namedict(py_Ref out, py_Ref object);
  6234. // objects/error.h
  6235. typedef struct{
  6236. SourceData_ src;
  6237. int lineno;
  6238. char msg[512];
  6239. } Error;
  6240. void py_BaseException__stpush(py_Frame* frame, py_Ref, SourceData_ src, int lineno, const char* func_name);
  6241. // compiler/lexer.h
  6242. #include <stdint.h>
  6243. extern const char* TokenSymbols[];
  6244. typedef enum TokenIndex {
  6245. TK_EOF,
  6246. TK_EOL,
  6247. TK_SOF,
  6248. TK_ID,
  6249. TK_NUM,
  6250. TK_STR,
  6251. TK_FSTR_BEGIN,
  6252. TK_FSTR_CPNT,
  6253. TK_FSTR_SPEC,
  6254. TK_FSTR_END,
  6255. TK_BYTES,
  6256. TK_IMAG,
  6257. TK_INDENT,
  6258. TK_DEDENT,
  6259. /***************/
  6260. TK_IS_NOT,
  6261. TK_NOT_IN,
  6262. TK_YIELD_FROM,
  6263. /***************/
  6264. TK_ADD,
  6265. TK_IADD,
  6266. TK_SUB,
  6267. TK_ISUB,
  6268. TK_MUL,
  6269. TK_IMUL,
  6270. TK_DIV,
  6271. TK_IDIV,
  6272. TK_FLOORDIV,
  6273. TK_IFLOORDIV,
  6274. TK_MOD,
  6275. TK_IMOD,
  6276. TK_AND,
  6277. TK_IAND,
  6278. TK_OR,
  6279. TK_IOR,
  6280. TK_XOR,
  6281. TK_IXOR,
  6282. TK_LSHIFT,
  6283. TK_ILSHIFT,
  6284. TK_RSHIFT,
  6285. TK_IRSHIFT,
  6286. /***************/
  6287. TK_LPAREN,
  6288. TK_RPAREN,
  6289. TK_LBRACKET,
  6290. TK_RBRACKET,
  6291. TK_LBRACE,
  6292. TK_RBRACE,
  6293. TK_DOT,
  6294. TK_DOTDOT,
  6295. TK_DOTDOTDOT,
  6296. TK_COMMA,
  6297. TK_COLON,
  6298. TK_SEMICOLON,
  6299. TK_POW,
  6300. TK_ARROW,
  6301. TK_HASH,
  6302. TK_DECORATOR,
  6303. TK_GT,
  6304. TK_LT,
  6305. TK_ASSIGN,
  6306. TK_EQ,
  6307. TK_NE,
  6308. TK_GE,
  6309. TK_LE,
  6310. TK_INVERT,
  6311. TK_WALRUS,
  6312. /***************/
  6313. TK_FALSE,
  6314. TK_NONE,
  6315. TK_TRUE,
  6316. TK_AND_KW,
  6317. TK_AS,
  6318. TK_ASSERT,
  6319. TK_BREAK,
  6320. TK_CLASS,
  6321. TK_CONTINUE,
  6322. TK_DEF,
  6323. TK_DEL,
  6324. TK_ELIF,
  6325. TK_ELSE,
  6326. TK_EXCEPT,
  6327. TK_FINALLY,
  6328. TK_FOR,
  6329. TK_FROM,
  6330. TK_GLOBAL,
  6331. TK_IF,
  6332. TK_IMPORT,
  6333. TK_IN,
  6334. TK_IS,
  6335. TK_LAMBDA,
  6336. TK_MATCH,
  6337. TK_NOT_KW,
  6338. TK_OR_KW,
  6339. TK_PASS,
  6340. TK_RAISE,
  6341. TK_RETURN,
  6342. TK_TRY,
  6343. TK_WHILE,
  6344. TK_WITH,
  6345. TK_YIELD,
  6346. /***************/
  6347. TK__COUNT__
  6348. } TokenIndex;
  6349. enum TokenValueIndex {
  6350. TokenValue_EMPTY = 0,
  6351. TokenValue_I64 = 1,
  6352. TokenValue_F64 = 2,
  6353. TokenValue_STR = 3,
  6354. };
  6355. typedef struct TokenValue {
  6356. enum TokenValueIndex index; // 0: empty
  6357. union {
  6358. int64_t _i64; // 1
  6359. double _f64; // 2
  6360. c11_string* _str; // 3
  6361. };
  6362. } TokenValue;
  6363. typedef struct Token {
  6364. TokenIndex type;
  6365. const char* start;
  6366. int length;
  6367. int line;
  6368. int brackets_level;
  6369. TokenValue value;
  6370. } Token;
  6371. // https://docs.python.org/3/reference/expressions.html#operator-precedence
  6372. enum Precedence {
  6373. PREC_LOWEST = 0,
  6374. PREC_NAMED_EXPR, // :=
  6375. PREC_LAMBDA, // lambda
  6376. PREC_TERNARY, // ?:
  6377. PREC_LOGICAL_OR, // or
  6378. PREC_LOGICAL_AND, // and
  6379. PREC_LOGICAL_NOT, // not
  6380. /* https://docs.python.org/3/reference/expressions.html#comparisons
  6381. * Unlike C, all comparison operations in Python have the same priority,
  6382. * which is lower than that of any arithmetic, shifting or bitwise operation.
  6383. * Also unlike C, expressions like a < b < c have the interpretation that is conventional in
  6384. * mathematics.
  6385. */
  6386. PREC_COMPARISION, // < > <= >= != ==, in / is / is not / not in
  6387. PREC_BITWISE_OR, // |
  6388. PREC_BITWISE_XOR, // ^
  6389. PREC_BITWISE_AND, // &
  6390. PREC_BITWISE_SHIFT, // << >>
  6391. PREC_TERM, // + -
  6392. PREC_FACTOR, // * / % // @
  6393. PREC_UNARY, // - not ~
  6394. PREC_EXPONENT, // **
  6395. PREC_PRIMARY, // f() x[] a.b 1:2
  6396. PREC_HIGHEST,
  6397. };
  6398. Error* Lexer__process(SourceData_ src, Token** out_tokens, int* out_length);
  6399. void destruct_tokens(Token* tokens, int length);
  6400. #define Token__sv(self) \
  6401. (c11_sv) { (self)->start, (self)->length }
  6402. // compiler/compiler.h
  6403. Error* pk_compile(SourceData_ src, CodeObject* out);
  6404. // objects/exception.h
  6405. typedef struct BaseExceptionFrame {
  6406. SourceData_ src;
  6407. int lineno;
  6408. c11_string* name;
  6409. py_TValue locals; // for debugger only
  6410. py_TValue globals; // for debugger only
  6411. } BaseExceptionFrame;
  6412. typedef struct BaseException {
  6413. py_TValue args;
  6414. py_TValue inner_exc;
  6415. c11_vector /*T=BaseExceptionFrame*/ stacktrace;
  6416. } BaseException;
  6417. char* safe_stringify_exception(py_Ref exc);
  6418. char* formatexc_internal(py_Ref exc);
  6419. // src/bindings\py_array.c
  6420. int pk_arrayview(py_Ref self, py_TValue** p) {
  6421. if(self->type == tp_list) {
  6422. *p = py_list_data(self);
  6423. return py_list_len(self);
  6424. }
  6425. if(self->type == tp_tuple) {
  6426. *p = PyObject__slots(self->_obj);
  6427. return py_tuple_len(self);
  6428. }
  6429. return -1;
  6430. }
  6431. bool pk_wrapper__arrayequal(py_Type type, int argc, py_Ref argv) {
  6432. PY_CHECK_ARGC(2);
  6433. if(!py_istype(py_arg(1), type)) {
  6434. py_newnotimplemented(py_retval());
  6435. return true;
  6436. }
  6437. py_TValue *p0, *p1;
  6438. int lhs_length = pk_arrayview(py_arg(0), &p0);
  6439. int rhs_length = pk_arrayview(py_arg(1), &p1);
  6440. assert(lhs_length != -1 && rhs_length != -1);
  6441. if(lhs_length != rhs_length) {
  6442. py_newbool(py_retval(), false);
  6443. return true;
  6444. }
  6445. for(int i = 0; i < lhs_length; i++) {
  6446. int res = py_equal(p0 + i, p1 + i);
  6447. if(res == -1) return false;
  6448. if(!res) {
  6449. py_newbool(py_retval(), false);
  6450. return true;
  6451. }
  6452. }
  6453. py_newbool(py_retval(), true);
  6454. return true;
  6455. }
  6456. bool pk_arraycontains(py_Ref self, py_Ref val) {
  6457. py_TValue* p;
  6458. int length = pk_arrayview(self, &p);
  6459. if(length == -1) return TypeError("expected list or tuple, got %t", self->type);
  6460. for(int i = 0; i < length; i++) {
  6461. int res = py_equal(p + i, val);
  6462. if(res == -1) return false;
  6463. if(res) {
  6464. py_newbool(py_retval(), true);
  6465. return true;
  6466. }
  6467. }
  6468. py_newbool(py_retval(), false);
  6469. return true;
  6470. }
  6471. bool list_iterator__next__(int argc, py_Ref argv) {
  6472. PY_CHECK_ARGC(1);
  6473. list_iterator* ud = py_touserdata(argv);
  6474. if(ud->index < ud->vec->length) {
  6475. py_TValue* res = c11__at(py_TValue, ud->vec, ud->index);
  6476. py_assign(py_retval(), res);
  6477. ud->index++;
  6478. return true;
  6479. }
  6480. return StopIteration();
  6481. }
  6482. bool tuple_iterator__next__(int argc, py_Ref argv) {
  6483. PY_CHECK_ARGC(1);
  6484. tuple_iterator* ud = py_touserdata(argv);
  6485. if(ud->index < ud->length) {
  6486. py_assign(py_retval(), ud->p + ud->index);
  6487. ud->index++;
  6488. return true;
  6489. }
  6490. return StopIteration();
  6491. }
  6492. py_Type pk_list_iterator__register() {
  6493. py_Type type = pk_newtype("list_iterator", tp_object, NULL, NULL, false, true);
  6494. py_bindmagic(type, __iter__, pk_wrapper__self);
  6495. py_bindmagic(type, __next__, list_iterator__next__);
  6496. return type;
  6497. }
  6498. py_Type pk_tuple_iterator__register() {
  6499. py_Type type = pk_newtype("tuple_iterator", tp_object, NULL, NULL, false, true);
  6500. py_bindmagic(type, __iter__, pk_wrapper__self);
  6501. py_bindmagic(type, __next__, tuple_iterator__next__);
  6502. return type;
  6503. }
  6504. // src/bindings\py_mappingproxy.c
  6505. #include <stdbool.h>
  6506. void pk_mappingproxy__namedict(py_Ref out, py_Ref object) {
  6507. py_newobject(out, tp_namedict, 1, 0);
  6508. assert(object->is_ptr && object->_obj->slots == -1);
  6509. py_setslot(out, 0, object);
  6510. }
  6511. static bool namedict__getitem__(int argc, py_Ref argv) {
  6512. PY_CHECK_ARGC(2);
  6513. PY_CHECK_ARG_TYPE(1, tp_str);
  6514. py_Name name = py_namev(py_tosv(py_arg(1)));
  6515. py_Ref res = py_getdict(py_getslot(argv, 0), name);
  6516. if(!res) return KeyError(py_arg(1));
  6517. py_assign(py_retval(), res);
  6518. return true;
  6519. }
  6520. static bool namedict__get(int argc, py_Ref argv) {
  6521. PY_CHECK_ARGC(3);
  6522. PY_CHECK_ARG_TYPE(1, tp_str);
  6523. py_Name name = py_namev(py_tosv(py_arg(1)));
  6524. py_Ref res = py_getdict(py_getslot(argv, 0), name);
  6525. py_assign(py_retval(), res ? res : py_arg(2));
  6526. return true;
  6527. }
  6528. static bool namedict__setitem__(int argc, py_Ref argv) {
  6529. PY_CHECK_ARGC(3);
  6530. PY_CHECK_ARG_TYPE(1, tp_str);
  6531. py_Name name = py_namev(py_tosv(py_arg(1)));
  6532. py_setdict(py_getslot(argv, 0), name, py_arg(2));
  6533. py_newnone(py_retval());
  6534. return true;
  6535. }
  6536. static bool namedict__delitem__(int argc, py_Ref argv) {
  6537. PY_CHECK_ARGC(2);
  6538. PY_CHECK_ARG_TYPE(1, tp_str);
  6539. py_Name name = py_namev(py_tosv(py_arg(1)));
  6540. if(!py_deldict(py_getslot(argv, 0), name)) return KeyError(py_arg(1));
  6541. py_newnone(py_retval());
  6542. return true;
  6543. }
  6544. static bool namedict__contains__(int argc, py_Ref argv) {
  6545. PY_CHECK_ARGC(2);
  6546. PY_CHECK_ARG_TYPE(1, tp_str);
  6547. py_Name name = py_namev(py_tosv(py_arg(1)));
  6548. py_Ref res = py_getdict(py_getslot(argv, 0), name);
  6549. py_newbool(py_retval(), res != NULL);
  6550. return true;
  6551. }
  6552. static bool namedict_items(int argc, py_Ref argv) {
  6553. PY_CHECK_ARGC(1);
  6554. py_Ref object = py_getslot(argv, 0);
  6555. NameDict* dict = PyObject__dict(object->_obj);
  6556. py_newlist(py_retval());
  6557. for(int i = 0; i < dict->capacity; i++) {
  6558. NameDict_KV* kv = &dict->items[i];
  6559. if(kv->key == NULL) continue;
  6560. py_Ref slot = py_list_emplace(py_retval());
  6561. py_Ref p = py_newtuple(slot, 2);
  6562. p[0] = *py_name2ref(kv->key);
  6563. p[1] = kv->value;
  6564. }
  6565. return true;
  6566. }
  6567. static bool namedict_clear(int argc, py_Ref argv) {
  6568. PY_CHECK_ARGC(1);
  6569. py_Ref object = py_getslot(argv, 0);
  6570. NameDict* dict = PyObject__dict(object->_obj);
  6571. NameDict__clear(dict);
  6572. py_newnone(py_retval());
  6573. return true;
  6574. }
  6575. py_Type pk_namedict__register() {
  6576. py_Type type = pk_newtype("namedict", tp_object, NULL, NULL, false, true);
  6577. py_bindmagic(type, __getitem__, namedict__getitem__);
  6578. py_bindmagic(type, __setitem__, namedict__setitem__);
  6579. py_bindmagic(type, __delitem__, namedict__delitem__);
  6580. py_bindmagic(type, __contains__, namedict__contains__);
  6581. py_setdict(py_tpobject(type), __hash__, py_None());
  6582. py_bindmethod(type, "items", namedict_items);
  6583. py_bindmethod(type, "clear", namedict_clear);
  6584. py_bindmethod(type, "get", namedict__get);
  6585. return type;
  6586. }
  6587. // src/bindings\py_method.c
  6588. /* staticmethod */
  6589. static bool staticmethod__new__(int argc, py_Ref argv) {
  6590. PY_CHECK_ARGC(2);
  6591. py_newobject(py_retval(), tp_staticmethod, 1, 0);
  6592. py_setslot(py_retval(), 0, py_arg(1));
  6593. return true;
  6594. }
  6595. py_Type pk_staticmethod__register() {
  6596. py_Type type = pk_newtype("staticmethod", tp_object, NULL, NULL, false, true);
  6597. py_bindmagic(type, __new__, staticmethod__new__);
  6598. return type;
  6599. }
  6600. /* classmethod */
  6601. static bool classmethod__new__(int argc, py_Ref argv) {
  6602. PY_CHECK_ARGC(2);
  6603. py_newobject(py_retval(), tp_classmethod, 1, 0);
  6604. py_setslot(py_retval(), 0, py_arg(1));
  6605. return true;
  6606. }
  6607. py_Type pk_classmethod__register() {
  6608. py_Type type = pk_newtype("classmethod", tp_object, NULL, NULL, false, true);
  6609. py_bindmagic(type, __new__, classmethod__new__);
  6610. return type;
  6611. }
  6612. /* boundmethod */
  6613. static bool boundmethod__self__(int argc, py_Ref argv) {
  6614. PY_CHECK_ARGC(1);
  6615. py_assign(py_retval(), py_getslot(argv, 0));
  6616. return true;
  6617. }
  6618. static bool boundmethod__func__(int argc, py_Ref argv) {
  6619. PY_CHECK_ARGC(1);
  6620. py_assign(py_retval(), py_getslot(argv, 1));
  6621. return true;
  6622. }
  6623. static bool boundmethod__eq__(int argc, py_Ref argv) {
  6624. PY_CHECK_ARGC(2);
  6625. if(!py_istype(py_arg(1), tp_boundmethod)) {
  6626. py_newbool(py_retval(), false);
  6627. return true;
  6628. }
  6629. for(int i = 0; i < 2; i++) {
  6630. int res = py_equal(py_getslot(&argv[0], i), py_getslot(&argv[1], i));
  6631. if(res == -1) return false;
  6632. if(!res) {
  6633. py_newbool(py_retval(), false);
  6634. return true;
  6635. }
  6636. }
  6637. py_newbool(py_retval(), true);
  6638. return true;
  6639. }
  6640. static bool boundmethod__ne__(int argc, py_Ref argv) {
  6641. bool ok = boundmethod__eq__(argc, argv);
  6642. if(!ok) return false;
  6643. bool res = py_tobool(py_retval());
  6644. py_newbool(py_retval(), !res);
  6645. return true;
  6646. }
  6647. py_Type pk_boundmethod__register() {
  6648. py_Type type = pk_newtype("boundmethod", tp_object, NULL, NULL, false, true);
  6649. py_bindproperty(type, "__self__", boundmethod__self__, NULL);
  6650. py_bindproperty(type, "__func__", boundmethod__func__, NULL);
  6651. py_bindmagic(type, __eq__, boundmethod__eq__);
  6652. py_bindmagic(type, __ne__, boundmethod__ne__);
  6653. return type;
  6654. }
  6655. // src/bindings\py_number.c
  6656. static bool try_castfloat(py_Ref self, double* out) {
  6657. switch(self->type) {
  6658. case tp_int: *out = (double)self->_i64; return true;
  6659. case tp_float: *out = self->_f64; return true;
  6660. default: return false;
  6661. }
  6662. }
  6663. #define DEF_NUM_BINARY_OP(name, op, rint, rfloat) \
  6664. static bool int##name(int argc, py_Ref argv) { \
  6665. PY_CHECK_ARGC(2); \
  6666. if(py_isint(&argv[1])) { \
  6667. py_i64 lhs = py_toint(&argv[0]); \
  6668. py_i64 rhs = py_toint(&argv[1]); \
  6669. rint(py_retval(), lhs op rhs); \
  6670. } else if(py_isfloat(&argv[1])) { \
  6671. py_i64 lhs = py_toint(&argv[0]); \
  6672. py_f64 rhs = py_tofloat(&argv[1]); \
  6673. rfloat(py_retval(), lhs op rhs); \
  6674. } else { \
  6675. py_newnotimplemented(py_retval()); \
  6676. } \
  6677. return true; \
  6678. } \
  6679. static bool float##name(int argc, py_Ref argv) { \
  6680. PY_CHECK_ARGC(2); \
  6681. py_f64 lhs = py_tofloat(&argv[0]); \
  6682. py_f64 rhs; \
  6683. if(try_castfloat(&argv[1], &rhs)) { \
  6684. rfloat(py_retval(), lhs op rhs); \
  6685. } else { \
  6686. py_newnotimplemented(py_retval()); \
  6687. } \
  6688. return true; \
  6689. }
  6690. DEF_NUM_BINARY_OP(__add__, +, py_newint, py_newfloat)
  6691. DEF_NUM_BINARY_OP(__sub__, -, py_newint, py_newfloat)
  6692. DEF_NUM_BINARY_OP(__mul__, *, py_newint, py_newfloat)
  6693. DEF_NUM_BINARY_OP(__eq__, ==, py_newbool, py_newbool)
  6694. DEF_NUM_BINARY_OP(__ne__, !=, py_newbool, py_newbool)
  6695. DEF_NUM_BINARY_OP(__lt__, <, py_newbool, py_newbool)
  6696. DEF_NUM_BINARY_OP(__le__, <=, py_newbool, py_newbool)
  6697. DEF_NUM_BINARY_OP(__gt__, >, py_newbool, py_newbool)
  6698. DEF_NUM_BINARY_OP(__ge__, >=, py_newbool, py_newbool)
  6699. static bool int__neg__(int argc, py_Ref argv) {
  6700. PY_CHECK_ARGC(1);
  6701. py_i64 val = py_toint(&argv[0]);
  6702. py_newint(py_retval(), -val);
  6703. return true;
  6704. }
  6705. static bool float__neg__(int argc, py_Ref argv) {
  6706. PY_CHECK_ARGC(1);
  6707. py_f64 val = py_tofloat(&argv[0]);
  6708. py_newfloat(py_retval(), -val);
  6709. return true;
  6710. }
  6711. static bool int__truediv__(int argc, py_Ref argv) {
  6712. PY_CHECK_ARGC(2);
  6713. py_i64 lhs = py_toint(&argv[0]);
  6714. py_f64 rhs;
  6715. if(try_castfloat(&argv[1], &rhs)) {
  6716. if(rhs == 0.0) return ZeroDivisionError("float division by zero");
  6717. py_newfloat(py_retval(), lhs / rhs);
  6718. } else {
  6719. py_newnotimplemented(py_retval());
  6720. }
  6721. return true;
  6722. }
  6723. static bool float__truediv__(int argc, py_Ref argv) {
  6724. PY_CHECK_ARGC(2);
  6725. py_f64 lhs = py_tofloat(&argv[0]);
  6726. py_f64 rhs;
  6727. if(try_castfloat(&argv[1], &rhs)) {
  6728. if(rhs == 0.0) return ZeroDivisionError("float division by zero");
  6729. py_newfloat(py_retval(), lhs / rhs);
  6730. } else {
  6731. py_newnotimplemented(py_retval());
  6732. }
  6733. return true;
  6734. }
  6735. static bool number__pow__(int argc, py_Ref argv) {
  6736. PY_CHECK_ARGC(2);
  6737. if(py_isint(&argv[0]) && py_isint(&argv[1])) {
  6738. py_i64 lhs = py_toint(&argv[0]);
  6739. py_i64 rhs = py_toint(&argv[1]);
  6740. if(rhs < 0) {
  6741. if(lhs == 0) {
  6742. return ZeroDivisionError("0.0 cannot be raised to a negative power");
  6743. } else {
  6744. py_newfloat(py_retval(), dmath_pow(lhs, rhs));
  6745. }
  6746. } else {
  6747. // rhs >= 0
  6748. py_i64 ret = 1;
  6749. while(true) {
  6750. if(rhs & 1) ret *= lhs;
  6751. rhs >>= 1;
  6752. if(!rhs) break;
  6753. lhs *= lhs; // place this here to avoid overflow
  6754. }
  6755. py_newint(py_retval(), ret);
  6756. }
  6757. } else {
  6758. py_f64 lhs, rhs;
  6759. if(!py_castfloat(&argv[0], &lhs)) return false;
  6760. if(try_castfloat(&argv[1], &rhs)) {
  6761. py_newfloat(py_retval(), dmath_pow(lhs, rhs));
  6762. } else {
  6763. py_newnotimplemented(py_retval());
  6764. }
  6765. }
  6766. return true;
  6767. }
  6768. static py_i64 i64_abs(py_i64 x) { return x < 0 ? -x : x; }
  6769. py_i64 cpy312__int_floordiv(py_i64 a, py_i64 b) {
  6770. assert(b != 0);
  6771. if(a == 0) return 0;
  6772. if((a < 0) == (b < 0)) {
  6773. return i64_abs(a) / i64_abs(b);
  6774. } else {
  6775. return -1 - (i64_abs(a) - 1) / i64_abs(b);
  6776. }
  6777. }
  6778. py_i64 cpy312__int_mod(py_i64 a, py_i64 b) {
  6779. assert(b != 0);
  6780. if(a == 0) return 0;
  6781. py_i64 res;
  6782. if((a < 0) == (b < 0)) {
  6783. res = i64_abs(a) % i64_abs(b);
  6784. } else {
  6785. res = i64_abs(b) - 1 - (i64_abs(a) - 1) % i64_abs(b);
  6786. }
  6787. return b < 0 ? -res : res;
  6788. }
  6789. // https://github.com/python/cpython/blob/3.11/Objects/floatobject.c#L677
  6790. void cpy312__float_divmod(double vx, double wx, double *floordiv, double *mod)
  6791. {
  6792. double div;
  6793. *mod = dmath_fmod(vx, wx);
  6794. /* fmod is typically exact, so vx-mod is *mathematically* an
  6795. exact multiple of wx. But this is fp arithmetic, and fp
  6796. vx - mod is an approximation; the result is that div may
  6797. not be an exact integral value after the division, although
  6798. it will always be very close to one.
  6799. */
  6800. div = (vx - *mod) / wx;
  6801. if (*mod) {
  6802. /* ensure the remainder has the same sign as the denominator */
  6803. if ((wx < 0) != (*mod < 0)) {
  6804. *mod += wx;
  6805. div -= 1.0;
  6806. }
  6807. }
  6808. else {
  6809. /* the remainder is zero, and in the presence of signed zeroes
  6810. fmod returns different results across platforms; ensure
  6811. it has the same sign as the denominator. */
  6812. *mod = dmath_copysign(0.0, wx);
  6813. }
  6814. /* snap quotient to nearest integral value */
  6815. if (div) {
  6816. *floordiv = dmath_floor(div);
  6817. if (div - *floordiv > 0.5) {
  6818. *floordiv += 1.0;
  6819. }
  6820. }
  6821. else {
  6822. /* div is zero - get the same sign as the true quotient */
  6823. *floordiv = dmath_copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
  6824. }
  6825. }
  6826. static bool int__floordiv__(int argc, py_Ref argv) {
  6827. PY_CHECK_ARGC(2);
  6828. py_i64 lhs = py_toint(&argv[0]);
  6829. if(py_isint(&argv[1])) {
  6830. py_i64 rhs = py_toint(&argv[1]);
  6831. if(rhs == 0) return ZeroDivisionError("integer division by zero");
  6832. py_newint(py_retval(), cpy312__int_floordiv(lhs, rhs));
  6833. } else {
  6834. py_newnotimplemented(py_retval());
  6835. }
  6836. return true;
  6837. }
  6838. static bool int__mod__(int argc, py_Ref argv) {
  6839. PY_CHECK_ARGC(2);
  6840. py_i64 lhs = py_toint(&argv[0]);
  6841. if(py_isint(&argv[1])) {
  6842. py_i64 rhs = py_toint(&argv[1]);
  6843. if(rhs == 0) return ZeroDivisionError("integer modulo by zero");
  6844. py_newint(py_retval(), cpy312__int_mod(lhs, rhs));
  6845. } else {
  6846. py_newnotimplemented(py_retval());
  6847. }
  6848. return true;
  6849. }
  6850. static bool float__floordiv__(int argc, py_Ref argv) {
  6851. PY_CHECK_ARGC(2);
  6852. py_f64 lhs = py_tofloat(&argv[0]);
  6853. py_f64 rhs;
  6854. if(try_castfloat(&argv[1], &rhs)) {
  6855. if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
  6856. double q, r;
  6857. cpy312__float_divmod(lhs, rhs, &q, &r);
  6858. py_newfloat(py_retval(), q);
  6859. return true;
  6860. }
  6861. py_newnotimplemented(py_retval());
  6862. return true;
  6863. }
  6864. static bool float__rfloordiv__(int argc, py_Ref argv) {
  6865. PY_CHECK_ARGC(2);
  6866. py_f64 rhs = py_tofloat(&argv[0]);
  6867. py_f64 lhs;
  6868. if(try_castfloat(&argv[1], &lhs)) {
  6869. if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
  6870. double q, r;
  6871. cpy312__float_divmod(lhs, rhs, &q, &r);
  6872. py_newfloat(py_retval(), q);
  6873. return true;
  6874. }
  6875. py_newnotimplemented(py_retval());
  6876. return true;
  6877. }
  6878. static bool float__mod__(int argc, py_Ref argv) {
  6879. PY_CHECK_ARGC(2);
  6880. py_f64 lhs = py_tofloat(&argv[0]);
  6881. py_f64 rhs;
  6882. if(try_castfloat(&argv[1], &rhs)) {
  6883. if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
  6884. double q, r;
  6885. cpy312__float_divmod(lhs, rhs, &q, &r);
  6886. py_newfloat(py_retval(), r);
  6887. return true;
  6888. }
  6889. py_newnotimplemented(py_retval());
  6890. return true;
  6891. }
  6892. static bool float__rmod__(int argc, py_Ref argv) {
  6893. PY_CHECK_ARGC(2);
  6894. py_f64 rhs = py_tofloat(&argv[0]);
  6895. py_f64 lhs;
  6896. if(try_castfloat(&argv[1], &lhs)) {
  6897. if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
  6898. double q, r;
  6899. cpy312__float_divmod(lhs, rhs, &q, &r);
  6900. py_newfloat(py_retval(), r);
  6901. return true;
  6902. }
  6903. py_newnotimplemented(py_retval());
  6904. return true;
  6905. }
  6906. static bool float__divmod__(int argc, py_Ref argv) {
  6907. PY_CHECK_ARGC(2);
  6908. py_f64 lhs = py_tofloat(&argv[0]);
  6909. py_f64 rhs;
  6910. if(try_castfloat(&argv[1], &rhs)) {
  6911. if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
  6912. double q, r;
  6913. cpy312__float_divmod(lhs, rhs, &q, &r);
  6914. py_Ref p = py_newtuple(py_retval(), 2);
  6915. py_newfloat(&p[0], q);
  6916. py_newfloat(&p[1], r);
  6917. return true;
  6918. }
  6919. return TypeError("divmod() expects int or float as divisor");
  6920. }
  6921. static bool int__divmod__(int argc, py_Ref argv) {
  6922. PY_CHECK_ARGC(2);
  6923. PY_CHECK_ARG_TYPE(1, tp_int);
  6924. py_i64 lhs = py_toint(&argv[0]);
  6925. py_i64 rhs = py_toint(&argv[1]);
  6926. if(rhs == 0) return ZeroDivisionError("integer division or modulo by zero");
  6927. py_Ref p = py_newtuple(py_retval(), 2);
  6928. py_newint(&p[0], cpy312__int_floordiv(lhs, rhs));
  6929. py_newint(&p[1], cpy312__int_mod(lhs, rhs));
  6930. return true;
  6931. }
  6932. static bool int__invert__(int argc, py_Ref argv) {
  6933. PY_CHECK_ARGC(1);
  6934. py_i64 val = py_toint(&argv[0]);
  6935. py_newint(py_retval(), ~val);
  6936. return true;
  6937. }
  6938. static bool int_bit_length(int argc, py_Ref argv) {
  6939. PY_CHECK_ARGC(1);
  6940. py_i64 x = py_toint(py_arg(0));
  6941. if(x < 0) x = -x;
  6942. int bits = 0;
  6943. while(x) {
  6944. x >>= 1;
  6945. bits++;
  6946. }
  6947. py_newint(py_retval(), bits);
  6948. return true;
  6949. }
  6950. #define DEF_INT_BITWISE_OP(name, op) \
  6951. static bool int##name(int argc, py_Ref argv) { \
  6952. PY_CHECK_ARGC(2); \
  6953. py_i64 lhs = py_toint(&argv[0]); \
  6954. if(py_isint(&argv[1])) { \
  6955. py_i64 rhs = py_toint(&argv[1]); \
  6956. py_newint(py_retval(), lhs op rhs); \
  6957. } else { \
  6958. py_newnotimplemented(py_retval()); \
  6959. } \
  6960. return true; \
  6961. }
  6962. DEF_INT_BITWISE_OP(__and__, &)
  6963. DEF_INT_BITWISE_OP(__or__, |)
  6964. DEF_INT_BITWISE_OP(__xor__, ^)
  6965. DEF_INT_BITWISE_OP(__lshift__, <<)
  6966. DEF_INT_BITWISE_OP(__rshift__, >>)
  6967. static bool int__repr__(int argc, py_Ref argv) {
  6968. PY_CHECK_ARGC(1);
  6969. py_i64 val = py_toint(&argv[0]);
  6970. char buf[32];
  6971. int size = snprintf(buf, sizeof(buf), "%lld", (long long)val);
  6972. py_newstrv(py_retval(), (c11_sv){buf, size});
  6973. return true;
  6974. }
  6975. static bool float__repr__(int argc, py_Ref argv) {
  6976. PY_CHECK_ARGC(1);
  6977. py_f64 val = py_tofloat(&argv[0]);
  6978. c11_sbuf buf;
  6979. c11_sbuf__ctor(&buf);
  6980. c11_sbuf__write_f64(&buf, val, -1);
  6981. c11_sbuf__py_submit(&buf, py_retval());
  6982. return true;
  6983. }
  6984. static bool int__hash__(int argc, py_Ref argv) {
  6985. PY_CHECK_ARGC(1);
  6986. py_assign(py_retval(), argv);
  6987. return true;
  6988. }
  6989. static bool float__hash__(int argc, py_Ref argv) {
  6990. PY_CHECK_ARGC(1);
  6991. py_f64 val = py_tofloat(&argv[0]);
  6992. py_i64 h_user;
  6993. memcpy(&h_user, &val, sizeof(py_f64));
  6994. py_newint(py_retval(), h_user);
  6995. return true;
  6996. }
  6997. static bool int__abs__(int argc, py_Ref argv) {
  6998. PY_CHECK_ARGC(1);
  6999. py_i64 val = py_toint(&argv[0]);
  7000. py_newint(py_retval(), val < 0 ? -val : val);
  7001. return true;
  7002. }
  7003. static bool float__abs__(int argc, py_Ref argv) {
  7004. PY_CHECK_ARGC(1);
  7005. py_f64 val = py_tofloat(&argv[0]);
  7006. py_newfloat(py_retval(), dmath_fabs(val));
  7007. return true;
  7008. }
  7009. static bool int__new__(int argc, py_Ref argv) {
  7010. if(argc == 1 + 0) {
  7011. // int() == 0
  7012. py_newint(py_retval(), 0);
  7013. return true;
  7014. }
  7015. // 1 arg
  7016. if(argc == 1 + 1) {
  7017. switch(argv[1].type) {
  7018. case tp_float: {
  7019. // int(1.1) == 1
  7020. py_newint(py_retval(), (py_i64)py_tofloat(&argv[1]));
  7021. return true;
  7022. }
  7023. case tp_int: {
  7024. // int(1) == 1
  7025. *py_retval() = argv[1];
  7026. return true;
  7027. }
  7028. case tp_bool: {
  7029. // int(True) == 1
  7030. py_newint(py_retval(), (py_i64)py_tobool(&argv[1]));
  7031. return true;
  7032. }
  7033. case tp_str: break; // leave to the next block
  7034. default: return TypeError("int() argument must be a string, number or boolean");
  7035. }
  7036. }
  7037. // 2+ args -> error
  7038. if(argc > 1 + 2) return TypeError("int() takes at most 2 arguments");
  7039. // 1 or 2 args with str
  7040. int base = 10;
  7041. if(argc == 1 + 2) {
  7042. PY_CHECK_ARG_TYPE(2, tp_int);
  7043. base = py_toint(py_arg(2));
  7044. }
  7045. PY_CHECK_ARG_TYPE(1, tp_str);
  7046. c11_sv sv = py_tosv(py_arg(1));
  7047. bool negative = false;
  7048. if(sv.size && (sv.data[0] == '+' || sv.data[0] == '-')) {
  7049. negative = sv.data[0] == '-';
  7050. sv.data++;
  7051. sv.size--;
  7052. }
  7053. py_i64 val;
  7054. if(c11__parse_uint(sv, &val, base) != IntParsing_SUCCESS) {
  7055. return ValueError("invalid literal for int() with base %d: %q", base, sv);
  7056. }
  7057. py_newint(py_retval(), negative ? -val : val);
  7058. return true;
  7059. }
  7060. static bool float__new__(int argc, py_Ref argv) {
  7061. if(argc == 1 + 0) {
  7062. // float() == 0.0
  7063. py_newfloat(py_retval(), 0.0);
  7064. return true;
  7065. }
  7066. if(argc > 1 + 1) return TypeError("float() takes at most 1 argument");
  7067. // 1 arg
  7068. switch(argv[1].type) {
  7069. case tp_int: {
  7070. // float(1) == 1.0
  7071. py_newfloat(py_retval(), py_toint(&argv[1]));
  7072. return true;
  7073. }
  7074. case tp_float: {
  7075. // float(1.1) == 1.1
  7076. *py_retval() = argv[1];
  7077. return true;
  7078. }
  7079. case tp_bool: {
  7080. // float(True) == 1.0
  7081. py_newfloat(py_retval(), py_tobool(&argv[1]));
  7082. return true;
  7083. }
  7084. case tp_str: {
  7085. // str to float
  7086. c11_sv sv = py_tosv(py_arg(1));
  7087. if(c11__sveq2(sv, "inf")) {
  7088. py_newfloat(py_retval(), DMATH_INFINITY);
  7089. return true;
  7090. }
  7091. if(c11__sveq2(sv, "-inf")) {
  7092. py_newfloat(py_retval(), -DMATH_INFINITY);
  7093. return true;
  7094. }
  7095. char* p_end;
  7096. py_f64 float_out = strtod(sv.data, &p_end);
  7097. if(p_end != sv.data + sv.size) return ValueError("invalid literal for float(): %q", sv);
  7098. py_newfloat(py_retval(), float_out);
  7099. return true;
  7100. }
  7101. default: return TypeError("float() argument must be a string or a real number");
  7102. }
  7103. }
  7104. // tp_bool
  7105. static bool bool__new__(int argc, py_Ref argv) {
  7106. assert(argc > 0);
  7107. if(argc == 1) {
  7108. py_newbool(py_retval(), false);
  7109. return true;
  7110. }
  7111. if(argc == 2) {
  7112. int res = py_bool(py_arg(1));
  7113. if(res == -1) return false;
  7114. py_newbool(py_retval(), res);
  7115. return true;
  7116. }
  7117. return TypeError("bool() takes at most 1 argument");
  7118. }
  7119. static bool bool__hash__(int argc, py_Ref argv) {
  7120. PY_CHECK_ARGC(1);
  7121. bool res = py_tobool(argv);
  7122. py_newint(py_retval(), res);
  7123. return true;
  7124. }
  7125. static bool bool__repr__(int argc, py_Ref argv) {
  7126. PY_CHECK_ARGC(1);
  7127. bool res = py_tobool(argv);
  7128. py_newstr(py_retval(), res ? "True" : "False");
  7129. return true;
  7130. }
  7131. static bool bool__eq__(int argc, py_Ref argv) {
  7132. PY_CHECK_ARGC(2);
  7133. bool lhs = py_tobool(&argv[0]);
  7134. if(argv[1].type == tp_bool) {
  7135. bool rhs = py_tobool(&argv[1]);
  7136. py_newbool(py_retval(), lhs == rhs);
  7137. } else {
  7138. py_newnotimplemented(py_retval());
  7139. }
  7140. return true;
  7141. }
  7142. static bool bool__ne__(int argc, py_Ref argv) {
  7143. PY_CHECK_ARGC(2);
  7144. bool lhs = py_tobool(&argv[0]);
  7145. if(argv[1].type == tp_bool) {
  7146. bool rhs = py_tobool(&argv[1]);
  7147. py_newbool(py_retval(), lhs != rhs);
  7148. } else {
  7149. py_newnotimplemented(py_retval());
  7150. }
  7151. return true;
  7152. }
  7153. #define DEF_BOOL_BITWISE(name, op) \
  7154. static bool bool##name(int argc, py_Ref argv) { \
  7155. PY_CHECK_ARGC(2); \
  7156. bool lhs = py_tobool(&argv[0]); \
  7157. if(argv[1].type == tp_bool) { \
  7158. bool rhs = py_tobool(&argv[1]); \
  7159. py_newbool(py_retval(), lhs op rhs); \
  7160. } else { \
  7161. py_newnotimplemented(py_retval()); \
  7162. } \
  7163. return true; \
  7164. }
  7165. DEF_BOOL_BITWISE(__and__, &&)
  7166. DEF_BOOL_BITWISE(__or__, ||)
  7167. DEF_BOOL_BITWISE(__xor__, !=)
  7168. static bool bool__invert__(int argc, py_Ref argv) {
  7169. PY_CHECK_ARGC(1);
  7170. bool val = py_tobool(&argv[0]);
  7171. py_newbool(py_retval(), !val);
  7172. return true;
  7173. }
  7174. static bool bool_try_cast_i64(py_Ref arg, py_i64* out) {
  7175. if (arg->type == tp_int) {
  7176. *out = py_toint(arg);
  7177. return true;
  7178. } else if (arg->type == tp_bool) {
  7179. *out = py_tobool(arg);
  7180. return true;
  7181. } else {
  7182. return false;
  7183. }
  7184. }
  7185. static bool bool__add__(int argc, py_Ref argv) {
  7186. PY_CHECK_ARGC(2);
  7187. py_i64 lhs = py_tobool(py_arg(0));
  7188. py_i64 rhs;
  7189. if (bool_try_cast_i64(py_arg(1), &rhs)) {
  7190. py_newint(py_retval(), lhs + rhs);
  7191. } else {
  7192. py_newnotimplemented(py_retval());
  7193. }
  7194. return true;
  7195. }
  7196. static bool bool__sub__(int argc, py_Ref argv) {
  7197. PY_CHECK_ARGC(2);
  7198. py_i64 lhs = py_tobool(py_arg(0));
  7199. py_i64 rhs;
  7200. if (bool_try_cast_i64(py_arg(1), &rhs)) {
  7201. py_newint(py_retval(), lhs - rhs);
  7202. } else {
  7203. py_newnotimplemented(py_retval());
  7204. }
  7205. return true;
  7206. }
  7207. static bool bool__rsub__(int argc, py_Ref argv) {
  7208. PY_CHECK_ARGC(2);
  7209. py_i64 lhs = py_tobool(py_arg(0));
  7210. py_i64 rhs;
  7211. if (bool_try_cast_i64(py_arg(1), &rhs)) {
  7212. py_newint(py_retval(), rhs - lhs);
  7213. } else {
  7214. py_newnotimplemented(py_retval());
  7215. }
  7216. return true;
  7217. }
  7218. static bool bool__mul__(int argc, py_Ref argv) {
  7219. PY_CHECK_ARGC(2);
  7220. py_i64 lhs = py_tobool(py_arg(0));
  7221. py_i64 rhs;
  7222. if (bool_try_cast_i64(py_arg(1), &rhs)) {
  7223. py_newint(py_retval(), lhs * rhs);
  7224. } else {
  7225. py_newnotimplemented(py_retval());
  7226. }
  7227. return true;
  7228. }
  7229. void pk_number__register() {
  7230. /****** tp_int & tp_float ******/
  7231. py_bindmagic(tp_int, __add__, int__add__);
  7232. py_bindmagic(tp_float, __add__, float__add__);
  7233. py_bindmagic(tp_int, __sub__, int__sub__);
  7234. py_bindmagic(tp_float, __sub__, float__sub__);
  7235. py_bindmagic(tp_int, __mul__, int__mul__);
  7236. py_bindmagic(tp_float, __mul__, float__mul__);
  7237. py_bindmagic(tp_int, __eq__, int__eq__);
  7238. py_bindmagic(tp_float, __eq__, float__eq__);
  7239. py_bindmagic(tp_int, __ne__, int__ne__);
  7240. py_bindmagic(tp_float, __ne__, float__ne__);
  7241. py_bindmagic(tp_int, __lt__, int__lt__);
  7242. py_bindmagic(tp_float, __lt__, float__lt__);
  7243. py_bindmagic(tp_int, __le__, int__le__);
  7244. py_bindmagic(tp_float, __le__, float__le__);
  7245. py_bindmagic(tp_int, __gt__, int__gt__);
  7246. py_bindmagic(tp_float, __gt__, float__gt__);
  7247. py_bindmagic(tp_int, __ge__, int__ge__);
  7248. py_bindmagic(tp_float, __ge__, float__ge__);
  7249. // __neg__
  7250. py_bindmagic(tp_int, __neg__, int__neg__);
  7251. py_bindmagic(tp_float, __neg__, float__neg__);
  7252. // __repr__
  7253. py_bindmagic(tp_int, __repr__, int__repr__);
  7254. py_bindmagic(tp_float, __repr__, float__repr__);
  7255. // __hash__
  7256. py_bindmagic(tp_int, __hash__, int__hash__);
  7257. py_bindmagic(tp_float, __hash__, float__hash__);
  7258. // __abs__
  7259. py_bindmagic(tp_int, __abs__, int__abs__);
  7260. py_bindmagic(tp_float, __abs__, float__abs__);
  7261. // __new__
  7262. py_bindmagic(tp_int, __new__, int__new__);
  7263. py_bindmagic(tp_float, __new__, float__new__);
  7264. // __truediv__
  7265. py_bindmagic(tp_int, __truediv__, int__truediv__);
  7266. py_bindmagic(tp_float, __truediv__, float__truediv__);
  7267. // __pow__
  7268. py_bindmagic(tp_int, __pow__, number__pow__);
  7269. py_bindmagic(tp_float, __pow__, number__pow__);
  7270. // __floordiv__ & __mod__ & __divmod__
  7271. py_bindmagic(tp_int, __floordiv__, int__floordiv__);
  7272. py_bindmagic(tp_int, __mod__, int__mod__);
  7273. py_bindmagic(tp_int, __divmod__, int__divmod__);
  7274. // fmod
  7275. py_bindmagic(tp_float, __floordiv__, float__floordiv__);
  7276. py_bindmagic(tp_float, __rfloordiv__, float__rfloordiv__);
  7277. py_bindmagic(tp_float, __mod__, float__mod__);
  7278. py_bindmagic(tp_float, __rmod__, float__rmod__);
  7279. py_bindmagic(tp_float, __divmod__, float__divmod__);
  7280. // int.__invert__ & int.<BITWISE OP>
  7281. py_bindmagic(tp_int, __invert__, int__invert__);
  7282. py_bindmagic(tp_int, __and__, int__and__);
  7283. py_bindmagic(tp_int, __or__, int__or__);
  7284. py_bindmagic(tp_int, __xor__, int__xor__);
  7285. py_bindmagic(tp_int, __lshift__, int__lshift__);
  7286. py_bindmagic(tp_int, __rshift__, int__rshift__);
  7287. // int.bit_length
  7288. py_bindmethod(tp_int, "bit_length", int_bit_length);
  7289. /* tp_bool */
  7290. py_bindmagic(tp_bool, __new__, bool__new__);
  7291. py_bindmagic(tp_bool, __hash__, bool__hash__);
  7292. py_bindmagic(tp_bool, __repr__, bool__repr__);
  7293. py_bindmagic(tp_bool, __eq__, bool__eq__);
  7294. py_bindmagic(tp_bool, __ne__, bool__ne__);
  7295. py_bindmagic(tp_bool, __and__, bool__and__);
  7296. py_bindmagic(tp_bool, __or__, bool__or__);
  7297. py_bindmagic(tp_bool, __xor__, bool__xor__);
  7298. py_bindmagic(tp_bool, __invert__, bool__invert__);
  7299. py_bindmagic(tp_bool, __add__, bool__add__);
  7300. py_bindmagic(tp_bool, __sub__, bool__sub__);
  7301. py_bindmagic(tp_bool, __mul__, bool__mul__);
  7302. py_bindmagic(tp_bool, __radd__, bool__add__);
  7303. py_bindmagic(tp_bool, __rsub__, bool__rsub__);
  7304. py_bindmagic(tp_bool, __rmul__, bool__mul__);
  7305. }
  7306. #undef DEF_NUM_BINARY_OP
  7307. #undef DEF_INT_BITWISE_OP
  7308. #undef DEF_BOOL_BITWISE
  7309. // src/bindings\py_object.c
  7310. bool pk__object_new(int argc, py_Ref argv) {
  7311. if(argc == 0) return TypeError("object.__new__(): not enough arguments");
  7312. py_TypeInfo* ti = py_touserdata(argv);
  7313. py_Type cls = ti->index;
  7314. if(!ti->is_python) {
  7315. return TypeError("object.__new__(%t) is not safe, use %t.__new__() instead", cls, cls);
  7316. }
  7317. py_newobject(py_retval(), cls, -1, 0);
  7318. return true;
  7319. }
  7320. static bool object__hash__(int argc, py_Ref argv) {
  7321. PY_CHECK_ARGC(1);
  7322. assert(argv->is_ptr);
  7323. py_newint(py_retval(), (intptr_t)argv->_obj);
  7324. return true;
  7325. }
  7326. static bool object__eq__(int argc, py_Ref argv) {
  7327. PY_CHECK_ARGC(2);
  7328. bool res = py_isidentical(py_arg(0), py_arg(1));
  7329. py_newbool(py_retval(), res);
  7330. return true;
  7331. }
  7332. static bool object__ne__(int argc, py_Ref argv) {
  7333. PY_CHECK_ARGC(2);
  7334. bool res = py_isidentical(py_arg(0), py_arg(1));
  7335. py_newbool(py_retval(), !res);
  7336. return true;
  7337. }
  7338. static bool object__repr__(int argc, py_Ref argv) {
  7339. PY_CHECK_ARGC(1);
  7340. c11_sbuf buf;
  7341. c11_sbuf__ctor(&buf);
  7342. if(argv->is_ptr) {
  7343. pk_sprintf(&buf, "<%t object at %p>", argv->type, argv->_obj);
  7344. } else {
  7345. pk_sprintf(&buf, "<%t trivial object>", argv->type);
  7346. }
  7347. c11_sbuf__py_submit(&buf, py_retval());
  7348. return true;
  7349. }
  7350. static bool object__dict__(int argc, py_Ref argv) {
  7351. PY_CHECK_ARGC(1);
  7352. if(argv->is_ptr && argv->_obj->slots == -1) {
  7353. pk_mappingproxy__namedict(py_retval(), argv);
  7354. } else {
  7355. py_newnone(py_retval());
  7356. }
  7357. return true;
  7358. }
  7359. static bool type__repr__(int argc, py_Ref argv) {
  7360. PY_CHECK_ARGC(1);
  7361. c11_sbuf buf;
  7362. c11_sbuf__ctor(&buf);
  7363. pk_sprintf(&buf, "<class '%t'>", py_totype(argv));
  7364. c11_sbuf__py_submit(&buf, py_retval());
  7365. return true;
  7366. }
  7367. static bool type__new__(int argc, py_Ref argv) {
  7368. PY_CHECK_ARGC(2);
  7369. py_Type type = py_typeof(py_arg(1));
  7370. py_assign(py_retval(), py_tpobject(type));
  7371. return true;
  7372. }
  7373. static bool type__base__(int argc, py_Ref argv) {
  7374. PY_CHECK_ARGC(1);
  7375. py_TypeInfo* ti = py_touserdata(argv);
  7376. if(ti->base) {
  7377. py_assign(py_retval(), &ti->base_ti->self);
  7378. } else {
  7379. py_newnone(py_retval());
  7380. }
  7381. return true;
  7382. }
  7383. static bool type__name__(int argc, py_Ref argv) {
  7384. PY_CHECK_ARGC(1);
  7385. py_TypeInfo* ti = py_touserdata(argv);
  7386. py_assign(py_retval(), py_name2ref(ti->name));
  7387. return true;
  7388. }
  7389. static bool type__getitem__(int argc, py_Ref argv) {
  7390. py_assign(py_retval(), argv);
  7391. return true;
  7392. }
  7393. static bool type__or__(int argc, py_Ref argv) {
  7394. py_assign(py_retval(), argv);
  7395. return true;
  7396. }
  7397. static bool type__module__(int argc, py_Ref argv) {
  7398. PY_CHECK_ARGC(1);
  7399. py_TypeInfo* ti = py_touserdata(argv);
  7400. if(py_isnil(ti->module)) {
  7401. py_newnone(py_retval());
  7402. } else {
  7403. py_ModuleInfo* mi = py_touserdata(ti->module);
  7404. py_newstrv(py_retval(), c11_string__sv(mi->path));
  7405. }
  7406. return true;
  7407. }
  7408. static bool type__annotations__(int argc, py_Ref argv) {
  7409. PY_CHECK_ARGC(1);
  7410. py_TypeInfo* ti = py_touserdata(argv);
  7411. if(py_isnil(&ti->annotations)) {
  7412. py_newdict(py_retval());
  7413. } else {
  7414. py_assign(py_retval(), &ti->annotations);
  7415. }
  7416. return true;
  7417. }
  7418. static bool type__subclasses__(int argc, py_Ref argv) {
  7419. PY_CHECK_ARGC(1);
  7420. py_TypeInfo* base_ti = py_touserdata(argv);
  7421. py_newlist(py_retval());
  7422. for(py_Type i = 1; i < pk_current_vm->types.length; i++) {
  7423. py_TypeInfo* ti = pk_typeinfo(i);
  7424. if(ti->base == base_ti->index) {
  7425. py_list_append(py_retval(), &ti->self);
  7426. }
  7427. }
  7428. return true;
  7429. }
  7430. void pk_object__register() {
  7431. py_bindmagic(tp_object, __new__, pk__object_new);
  7432. py_bindmagic(tp_object, __hash__, object__hash__);
  7433. py_bindmagic(tp_object, __eq__, object__eq__);
  7434. py_bindmagic(tp_object, __ne__, object__ne__);
  7435. py_bindmagic(tp_object, __repr__, object__repr__);
  7436. py_bindmagic(tp_type, __repr__, type__repr__);
  7437. py_bindmagic(tp_type, __new__, type__new__);
  7438. py_bindmagic(tp_type, __getitem__, type__getitem__);
  7439. py_bindmagic(tp_type, __or__, type__or__);
  7440. py_bindproperty(tp_type, "__module__", type__module__, NULL);
  7441. py_bindproperty(tp_type, "__base__", type__base__, NULL);
  7442. py_bindproperty(tp_type, "__name__", type__name__, NULL);
  7443. py_bindproperty(tp_object, "__dict__", object__dict__, NULL);
  7444. py_bindproperty(tp_type, "__annotations__", type__annotations__, NULL);
  7445. py_bindmethod(tp_type, "__subclasses__", type__subclasses__);
  7446. }
  7447. // src/bindings\py_property.c
  7448. static bool property__new__(int argc, py_Ref argv) {
  7449. py_newobject(py_retval(), tp_property, 2, 0);
  7450. if(argc == 1 + 1) {
  7451. py_setslot(py_retval(), 0, py_arg(1));
  7452. py_setslot(py_retval(), 1, py_None());
  7453. } else if(argc == 1 + 2) {
  7454. py_setslot(py_retval(), 0, py_arg(1));
  7455. py_setslot(py_retval(), 1, py_arg(2));
  7456. } else {
  7457. return TypeError("property() expected 1 or 2 arguments, got %d", argc - 1);
  7458. }
  7459. return true;
  7460. }
  7461. static bool property_setter(int argc, py_Ref argv) {
  7462. PY_CHECK_ARGC(2);
  7463. py_setslot(argv, 1, py_arg(1));
  7464. py_assign(py_retval(), argv);
  7465. return true;
  7466. }
  7467. static bool property_fget(int argc, py_Ref argv) {
  7468. PY_CHECK_ARGC(1);
  7469. py_Ref fget = py_getslot(argv, 0);
  7470. py_assign(py_retval(), fget);
  7471. return true;
  7472. }
  7473. static bool property_fset(int argc, py_Ref argv) {
  7474. PY_CHECK_ARGC(1);
  7475. py_Ref fset = py_getslot(argv, 1);
  7476. py_assign(py_retval(), fset);
  7477. return true;
  7478. }
  7479. py_Type pk_property__register() {
  7480. py_Type type = pk_newtype("property", tp_object, NULL, NULL, false, true);
  7481. py_bindmagic(type, __new__, property__new__);
  7482. py_bindmethod(type, "setter", property_setter);
  7483. py_bindproperty(type, "fget", property_fget, NULL);
  7484. py_bindproperty(type, "fset", property_fset, NULL);
  7485. return type;
  7486. }
  7487. // src/bindings\py_range.c
  7488. typedef struct Range {
  7489. py_i64 start;
  7490. py_i64 stop;
  7491. py_i64 step;
  7492. } Range;
  7493. static bool range__new__(int argc, py_Ref argv) {
  7494. Range* ud = py_newobject(py_retval(), tp_range, 0, sizeof(Range));
  7495. switch(argc - 1) { // skip cls
  7496. case 1: {
  7497. PY_CHECK_ARG_TYPE(1, tp_int);
  7498. ud->start = 0;
  7499. ud->stop = py_toint(py_arg(1));
  7500. ud->step = 1;
  7501. break;
  7502. }
  7503. case 2:
  7504. PY_CHECK_ARG_TYPE(1, tp_int);
  7505. PY_CHECK_ARG_TYPE(2, tp_int);
  7506. ud->start = py_toint(py_arg(1));
  7507. ud->stop = py_toint(py_arg(2));
  7508. ud->step = 1;
  7509. break;
  7510. case 3:
  7511. PY_CHECK_ARG_TYPE(1, tp_int);
  7512. PY_CHECK_ARG_TYPE(2, tp_int);
  7513. PY_CHECK_ARG_TYPE(3, tp_int);
  7514. ud->start = py_toint(py_arg(1));
  7515. ud->stop = py_toint(py_arg(2));
  7516. ud->step = py_toint(py_arg(3));
  7517. break;
  7518. default: return TypeError("range() expected at most 3 arguments, got %d", argc - 1);
  7519. }
  7520. if(ud->step == 0) return ValueError("range() step must not be zero");
  7521. return true;
  7522. }
  7523. static bool range__iter__(int argc, py_Ref argv) {
  7524. PY_CHECK_ARGC(1);
  7525. return py_tpcall(tp_range_iterator, 1, argv);
  7526. }
  7527. py_Type pk_range__register() {
  7528. py_Type type = pk_newtype("range", tp_object, NULL, NULL, false, true);
  7529. py_bindmagic(type, __new__, range__new__);
  7530. py_bindmagic(type, __iter__, range__iter__);
  7531. return type;
  7532. }
  7533. typedef struct RangeIterator {
  7534. Range range;
  7535. py_i64 current;
  7536. } RangeIterator;
  7537. static bool range_iterator__new__(int argc, py_Ref argv) {
  7538. PY_CHECK_ARGC(2);
  7539. PY_CHECK_ARG_TYPE(1, tp_range);
  7540. RangeIterator* ud = py_newobject(py_retval(), tp_range_iterator, 0, sizeof(RangeIterator));
  7541. ud->range = *(Range*)py_touserdata(py_arg(1));
  7542. ud->current = ud->range.start;
  7543. return true;
  7544. }
  7545. bool range_iterator__next__(int argc, py_Ref argv) {
  7546. PY_CHECK_ARGC(1);
  7547. RangeIterator* ud = py_touserdata(argv);
  7548. if(ud->range.step > 0) {
  7549. if(ud->current >= ud->range.stop) return StopIteration();
  7550. } else {
  7551. if(ud->current <= ud->range.stop) return StopIteration();
  7552. }
  7553. py_newint(py_retval(), ud->current);
  7554. ud->current += ud->range.step;
  7555. return true;
  7556. }
  7557. py_Type pk_range_iterator__register() {
  7558. py_Type type = pk_newtype("range_iterator", tp_object, NULL, NULL, false, true);
  7559. py_bindmagic(type, __new__, range_iterator__new__);
  7560. py_bindmagic(type, __iter__, pk_wrapper__self);
  7561. py_bindmagic(type, __next__, range_iterator__next__);
  7562. return type;
  7563. }
  7564. // src/bindings\py_str.c
  7565. #include <stdbool.h>
  7566. c11_string* pk_tostr(py_Ref self) {
  7567. assert(self->type == tp_str);
  7568. if(!self->is_ptr) {
  7569. return (c11_string*)(&self->extra);
  7570. } else {
  7571. return PyObject__userdata(self->_obj);
  7572. }
  7573. }
  7574. ////////////////////////////////
  7575. static bool str__new__(int argc, py_Ref argv) {
  7576. assert(argc >= 1);
  7577. if(argc == 1) {
  7578. py_newstr(py_retval(), "");
  7579. return true;
  7580. }
  7581. if(argc > 2) return TypeError("str() takes at most 1 argument");
  7582. return py_str(py_arg(1));
  7583. }
  7584. static bool str__hash__(int argc, py_Ref argv) {
  7585. PY_CHECK_ARGC(1);
  7586. uint64_t res = c11_sv__hash(py_tosv(argv));
  7587. py_newint(py_retval(), (py_i64)res);
  7588. return true;
  7589. }
  7590. static bool str__len__(int argc, py_Ref argv) {
  7591. PY_CHECK_ARGC(1);
  7592. c11_string* self = pk_tostr(&argv[0]);
  7593. py_newint(py_retval(), c11_sv__u8_length((c11_sv){self->data, self->size}));
  7594. return true;
  7595. }
  7596. static bool str__mod__(int argc, py_Ref argv) {
  7597. PY_CHECK_ARGC(2);
  7598. c11_string* self = pk_tostr(&argv[0]);
  7599. // %s
  7600. // %d %i
  7601. // %f
  7602. // %r
  7603. // %%
  7604. py_TValue* args;
  7605. int args_count;
  7606. if(py_istype(&argv[1], tp_tuple)) {
  7607. args_count = py_tuple_len(&argv[1]);
  7608. args = py_tuple_data(&argv[1]);
  7609. } else {
  7610. args_count = 1;
  7611. args = &argv[1];
  7612. }
  7613. int arg_index = 0;
  7614. const char* p = self->data;
  7615. const char* p_end = self->data + self->size;
  7616. c11_sbuf buf;
  7617. c11_sbuf__ctor(&buf);
  7618. while(p < p_end) {
  7619. if(*p == '%') {
  7620. p++;
  7621. if(p >= p_end) {
  7622. c11_sbuf__dtor(&buf);
  7623. return ValueError("incomplete format");
  7624. }
  7625. char spec = *p;
  7626. p++;
  7627. if(spec == '%') {
  7628. // %% -> %
  7629. c11_sbuf__write_char(&buf, '%');
  7630. } else if(spec == 's') {
  7631. // %s -> string
  7632. if(arg_index >= args_count) {
  7633. c11_sbuf__dtor(&buf);
  7634. return TypeError("not enough arguments for format string");
  7635. }
  7636. if(!py_str(&args[arg_index])) {
  7637. c11_sbuf__dtor(&buf);
  7638. return false;
  7639. }
  7640. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  7641. arg_index++;
  7642. } else if(spec == 'd' || spec == 'i') {
  7643. // %d or %i -> integer
  7644. if(arg_index >= args_count) {
  7645. c11_sbuf__dtor(&buf);
  7646. return TypeError("not enough arguments for format string");
  7647. }
  7648. if(!py_checktype(&args[arg_index], tp_int)) {
  7649. c11_sbuf__dtor(&buf);
  7650. return false;
  7651. }
  7652. py_i64 val = py_toint(&args[arg_index]);
  7653. c11_sbuf__write_i64(&buf, val);
  7654. arg_index++;
  7655. } else if(spec == 'f') {
  7656. // %f -> float
  7657. if(arg_index >= args_count) {
  7658. c11_sbuf__dtor(&buf);
  7659. return TypeError("not enough arguments for format string");
  7660. }
  7661. py_f64 val;
  7662. if(py_istype(&args[arg_index], tp_float)) {
  7663. val = py_tofloat(&args[arg_index]);
  7664. } else if(py_istype(&args[arg_index], tp_int)) {
  7665. val = (py_f64)py_toint(&args[arg_index]);
  7666. } else {
  7667. c11_sbuf__dtor(&buf);
  7668. return TypeError("a float is required");
  7669. }
  7670. c11_sbuf__write_f64(&buf, val, 6);
  7671. arg_index++;
  7672. } else if(spec == 'r') {
  7673. // %r -> repr
  7674. if(arg_index >= args_count) {
  7675. c11_sbuf__dtor(&buf);
  7676. return TypeError("not enough arguments for format string");
  7677. }
  7678. if(!py_repr(&args[arg_index])) {
  7679. c11_sbuf__dtor(&buf);
  7680. return false;
  7681. }
  7682. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  7683. arg_index++;
  7684. } else {
  7685. c11_sbuf__dtor(&buf);
  7686. return ValueError("unsupported format character '%c'", spec);
  7687. }
  7688. } else {
  7689. c11_sbuf__write_char(&buf, *p);
  7690. p++;
  7691. }
  7692. }
  7693. if(arg_index != args_count) {
  7694. c11_sbuf__dtor(&buf);
  7695. return TypeError("not all arguments converted during string formatting");
  7696. }
  7697. c11_sbuf__py_submit(&buf, py_retval());
  7698. return true;
  7699. }
  7700. static bool str__add__(int argc, py_Ref argv) {
  7701. PY_CHECK_ARGC(2);
  7702. c11_string* self = pk_tostr(&argv[0]);
  7703. if(py_arg(1)->type != tp_str) {
  7704. py_newnotimplemented(py_retval());
  7705. } else {
  7706. c11_string* other = pk_tostr(&argv[1]);
  7707. char* p = py_newstrn(py_retval(), self->size + other->size);
  7708. memcpy(p, self->data, self->size);
  7709. memcpy(p + self->size, other->data, other->size);
  7710. }
  7711. return true;
  7712. }
  7713. static bool str__mul__(int argc, py_Ref argv) {
  7714. PY_CHECK_ARGC(2);
  7715. c11_string* self = pk_tostr(&argv[0]);
  7716. if(py_arg(1)->type != tp_int) {
  7717. py_newnotimplemented(py_retval());
  7718. } else {
  7719. py_i64 n = py_toint(py_arg(1));
  7720. if(n <= 0) {
  7721. py_newstr(py_retval(), "");
  7722. } else {
  7723. // LYNX: the whole result is one allocation (and its size an int): asked for before it is made
  7724. const size_t bytes = n > (py_i64)(0x7fffffff / (self->size > 0 ? self->size : 1)) ? (size_t)-1
  7725. : (size_t)self->size * (size_t)n;
  7726. if(!py_lynx_heap_room(bytes)) return RuntimeError("out of memory");
  7727. char* p = py_newstrn(py_retval(), self->size * n);
  7728. for(int i = 0; i < n; i++) {
  7729. memcpy(p + i * self->size, self->data, self->size);
  7730. }
  7731. }
  7732. }
  7733. return true;
  7734. }
  7735. static bool str__rmul__(int argc, py_Ref argv) { return str__mul__(argc, argv); }
  7736. static bool str__contains__(int argc, py_Ref argv) {
  7737. PY_CHECK_ARGC(2);
  7738. c11_string* self = pk_tostr(&argv[0]);
  7739. if(py_arg(1)->type != tp_str) {
  7740. py_newnotimplemented(py_retval());
  7741. } else {
  7742. c11_string* other = pk_tostr(&argv[1]);
  7743. const char* p = strstr(self->data, other->data);
  7744. py_newbool(py_retval(), p != NULL);
  7745. }
  7746. return true;
  7747. }
  7748. static bool str__str__(int argc, py_Ref argv) {
  7749. PY_CHECK_ARGC(1);
  7750. *py_retval() = argv[0];
  7751. return true;
  7752. }
  7753. static bool str__repr__(int argc, py_Ref argv) {
  7754. PY_CHECK_ARGC(1);
  7755. c11_sbuf buf;
  7756. c11_sbuf__ctor(&buf);
  7757. c11_sbuf__write_quoted(&buf, py_tosv(&argv[0]), '\'');
  7758. c11_sbuf__py_submit(&buf, py_retval());
  7759. return true;
  7760. }
  7761. static bool str__iter__(int argc, py_Ref argv) {
  7762. PY_CHECK_ARGC(1);
  7763. int* ud = py_newobject(py_retval(), tp_str_iterator, 1, sizeof(int));
  7764. *ud = 0;
  7765. py_setslot(py_retval(), 0, argv); // keep a reference to the string
  7766. return true;
  7767. }
  7768. static bool str__getitem__(int argc, py_Ref argv) {
  7769. PY_CHECK_ARGC(2);
  7770. c11_sv self = c11_string__sv(pk_tostr(&argv[0]));
  7771. py_Ref _1 = py_arg(1);
  7772. if(_1->type == tp_int) {
  7773. int index = py_toint(py_arg(1));
  7774. int u8_len = c11_sv__u8_length(self);
  7775. if(!pk__normalize_index(&index, u8_len)) return false;
  7776. c11_sv res = c11_sv__u8_getitem(self, index);
  7777. py_newstrv(py_retval(), res);
  7778. return true;
  7779. } else if(_1->type == tp_slice) {
  7780. int start, stop, step;
  7781. bool ok = pk__parse_int_slice(_1, c11_sv__u8_length(self), &start, &stop, &step);
  7782. if(!ok) return false;
  7783. c11_string* res = c11_sv__u8_slice(self, start, stop, step);
  7784. py_newstrv(py_retval(), (c11_sv){res->data, res->size});
  7785. c11_string__delete(res);
  7786. return true;
  7787. } else {
  7788. return TypeError("string indices must be integers");
  7789. }
  7790. }
  7791. #define DEF_STR_CMP_OP(op, __f, __cond) \
  7792. static bool str##op(int argc, py_Ref argv) { \
  7793. PY_CHECK_ARGC(2); \
  7794. c11_string* self = pk_tostr(&argv[0]); \
  7795. if(py_arg(1)->type != tp_str) { \
  7796. py_newnotimplemented(py_retval()); \
  7797. } else { \
  7798. c11_string* other = pk_tostr(&argv[1]); \
  7799. int res = __f(c11_string__sv(self), c11_string__sv(other)); \
  7800. py_newbool(py_retval(), __cond); \
  7801. } \
  7802. return true; \
  7803. }
  7804. DEF_STR_CMP_OP(__eq__, c11__sveq, res)
  7805. DEF_STR_CMP_OP(__ne__, c11__sveq, !res)
  7806. DEF_STR_CMP_OP(__lt__, c11_sv__cmp, res < 0)
  7807. DEF_STR_CMP_OP(__le__, c11_sv__cmp, res <= 0)
  7808. DEF_STR_CMP_OP(__gt__, c11_sv__cmp, res > 0)
  7809. DEF_STR_CMP_OP(__ge__, c11_sv__cmp, res >= 0)
  7810. #undef DEF_STR_CMP_OP
  7811. static bool str_lower(int argc, py_Ref argv) {
  7812. PY_CHECK_ARGC(1);
  7813. c11_string* self = pk_tostr(&argv[0]);
  7814. char* p = py_newstrn(py_retval(), self->size);
  7815. for(int i = 0; i < self->size; i++) {
  7816. char c = self->data[i];
  7817. p[i] = c >= 'A' && c <= 'Z' ? c + 32 : c;
  7818. }
  7819. return true;
  7820. }
  7821. static bool str_upper(int argc, py_Ref argv) {
  7822. PY_CHECK_ARGC(1);
  7823. c11_string* self = pk_tostr(&argv[0]);
  7824. char* p = py_newstrn(py_retval(), self->size);
  7825. for(int i = 0; i < self->size; i++) {
  7826. char c = self->data[i];
  7827. p[i] = c >= 'a' && c <= 'z' ? c - 32 : c;
  7828. }
  7829. return true;
  7830. }
  7831. static bool str_startswith(int argc, py_Ref argv) {
  7832. PY_CHECK_ARGC(2);
  7833. c11_string* self = pk_tostr(&argv[0]);
  7834. PY_CHECK_ARG_TYPE(1, tp_str);
  7835. c11_string* other = pk_tostr(&argv[1]);
  7836. py_newbool(py_retval(), c11_sv__startswith(c11_string__sv(self), c11_string__sv(other)));
  7837. return true;
  7838. }
  7839. static bool str_endswith(int argc, py_Ref argv) {
  7840. PY_CHECK_ARGC(2);
  7841. c11_string* self = pk_tostr(&argv[0]);
  7842. PY_CHECK_ARG_TYPE(1, tp_str);
  7843. c11_string* other = pk_tostr(&argv[1]);
  7844. py_newbool(py_retval(), c11_sv__endswith(c11_string__sv(self), c11_string__sv(other)));
  7845. return true;
  7846. }
  7847. static bool str_join(int argc, py_Ref argv) {
  7848. PY_CHECK_ARGC(2);
  7849. c11_sv self = c11_string__sv(pk_tostr(argv));
  7850. if(!py_iter(py_arg(1))) return false;
  7851. py_push(py_retval()); // iter
  7852. c11_sbuf buf;
  7853. c11_sbuf__ctor(&buf);
  7854. bool first = true;
  7855. while(true) {
  7856. int res = py_next(py_peek(-1));
  7857. if(res == -1) {
  7858. c11_sbuf__dtor(&buf);
  7859. return false;
  7860. }
  7861. if(res == 0) break;
  7862. if(!first) c11_sbuf__write_sv(&buf, self);
  7863. if(!py_checkstr(py_retval())) {
  7864. c11_sbuf__dtor(&buf);
  7865. return false;
  7866. }
  7867. c11_string* item = pk_tostr(py_retval());
  7868. c11_sbuf__write_cstrn(&buf, item->data, item->size);
  7869. first = false;
  7870. }
  7871. py_pop(); // iter
  7872. c11_sbuf__py_submit(&buf, py_retval());
  7873. return true;
  7874. }
  7875. static bool str_replace(int argc, py_Ref argv) {
  7876. PY_CHECK_ARGC(3);
  7877. c11_string* self = pk_tostr(&argv[0]);
  7878. PY_CHECK_ARG_TYPE(1, tp_str);
  7879. PY_CHECK_ARG_TYPE(2, tp_str);
  7880. c11_string* old = pk_tostr(&argv[1]);
  7881. c11_string* new_ = pk_tostr(&argv[2]);
  7882. c11_string* res =
  7883. c11_sv__replace2(c11_string__sv(self), c11_string__sv(old), c11_string__sv(new_));
  7884. py_newstrv(py_retval(), (c11_sv){res->data, res->size});
  7885. c11_string__delete(res);
  7886. return true;
  7887. }
  7888. static bool str_split(int argc, py_Ref argv) {
  7889. c11_sv self = c11_string__sv(pk_tostr(&argv[0]));
  7890. c11_vector res;
  7891. bool discard_empty = false;
  7892. if(argc > 2) return TypeError("split() takes at most 2 arguments");
  7893. if(argc == 1) {
  7894. // sep = None
  7895. res = c11_sv__splitwhitespace(self);
  7896. discard_empty = true;
  7897. }
  7898. if(argc == 2) {
  7899. // sep = argv[1]
  7900. if(!py_checkstr(&argv[1])) return false;
  7901. c11_sv sep = c11_string__sv(pk_tostr(&argv[1]));
  7902. if(sep.size == 0) return ValueError("empty separator");
  7903. res = c11_sv__split2(self, sep);
  7904. }
  7905. py_newlist(py_retval());
  7906. for(int i = 0; i < res.length; i++) {
  7907. c11_sv part = c11__getitem(c11_sv, &res, i);
  7908. if(discard_empty && part.size == 0) continue;
  7909. py_newstrv(py_list_emplace(py_retval()), part);
  7910. }
  7911. c11_vector__dtor(&res);
  7912. return true;
  7913. }
  7914. static bool str_splitlines(int argc, py_Ref argv) {
  7915. c11_sv self = c11_string__sv(pk_tostr(&argv[0]));
  7916. c11_vector res;
  7917. bool keepends = false;
  7918. if(argc > 2) return TypeError("splitlines() takes at most 2 arguments");
  7919. if(argc == 2) {
  7920. if(!py_checkbool(&argv[1])) return false;
  7921. keepends = py_tobool(&argv[1]);
  7922. }
  7923. res = c11_sv__splitlines(self, keepends);
  7924. py_newlist(py_retval());
  7925. for(int i = 0; i < res.length; i++) {
  7926. c11_sv part = c11__getitem(c11_sv, &res, i);
  7927. py_newstrv(py_list_emplace(py_retval()), part);
  7928. }
  7929. c11_vector__dtor(&res);
  7930. return true;
  7931. }
  7932. static bool str_count(int argc, py_Ref argv) {
  7933. PY_CHECK_ARGC(2);
  7934. c11_string* self = pk_tostr(&argv[0]);
  7935. PY_CHECK_ARG_TYPE(1, tp_str);
  7936. c11_string* sub = pk_tostr(&argv[1]);
  7937. int res = c11_sv__count(c11_string__sv(self), c11_string__sv(sub));
  7938. py_newint(py_retval(), res);
  7939. return true;
  7940. }
  7941. static bool str__strip_impl(bool left, bool right, int argc, py_Ref argv) {
  7942. c11_sv self = c11_string__sv(pk_tostr(&argv[0]));
  7943. c11_sv chars;
  7944. if(argc == 1) {
  7945. chars = (c11_sv){" \t\n\r", 4};
  7946. } else if(argc == 2) {
  7947. if(!py_checkstr(&argv[1])) return false;
  7948. chars = c11_string__sv(pk_tostr(&argv[1]));
  7949. } else {
  7950. return TypeError("strip() takes at most 2 arguments");
  7951. }
  7952. c11_sv res = c11_sv__strip(self, chars, left, right);
  7953. py_newstrv(py_retval(), res);
  7954. return true;
  7955. }
  7956. static bool str_strip(int argc, py_Ref argv) { return str__strip_impl(true, true, argc, argv); }
  7957. static bool str_lstrip(int argc, py_Ref argv) { return str__strip_impl(true, false, argc, argv); }
  7958. static bool str_rstrip(int argc, py_Ref argv) { return str__strip_impl(false, true, argc, argv); }
  7959. static bool str_zfill(int argc, py_Ref argv) {
  7960. PY_CHECK_ARGC(2);
  7961. c11_sv self = c11_string__sv(pk_tostr(&argv[0]));
  7962. PY_CHECK_ARG_TYPE(1, tp_int);
  7963. int width = py_toint(py_arg(1));
  7964. int delta = width - c11_sv__u8_length(self);
  7965. if(delta <= 0) {
  7966. *py_retval() = argv[0];
  7967. return true;
  7968. }
  7969. c11_sbuf buf;
  7970. c11_sbuf__ctor(&buf);
  7971. // a leading sign is kept in front; the padding goes after it
  7972. if(self.size > 0 && (self.data[0] == '+' || self.data[0] == '-')) {
  7973. c11_sbuf__write_char(&buf, self.data[0]);
  7974. self.data++;
  7975. self.size--;
  7976. }
  7977. for(int i = 0; i < delta; i++) {
  7978. c11_sbuf__write_char(&buf, '0');
  7979. }
  7980. c11_sbuf__write_sv(&buf, self);
  7981. c11_sbuf__py_submit(&buf, py_retval());
  7982. return true;
  7983. }
  7984. static bool str__widthjust_impl(bool left, int argc, py_Ref argv) {
  7985. if(argc > 1 + 2) return TypeError("expected at most 2 arguments");
  7986. char pad;
  7987. if(argc == 1 + 1) {
  7988. pad = ' ';
  7989. } else {
  7990. if(!py_checkstr(&argv[2])) return false;
  7991. c11_string* padstr = pk_tostr(&argv[2]);
  7992. if(padstr->size != 1)
  7993. return TypeError("The fill character must be exactly one character long");
  7994. pad = padstr->data[0];
  7995. }
  7996. c11_sv self = c11_string__sv(pk_tostr(&argv[0]));
  7997. PY_CHECK_ARG_TYPE(1, tp_int);
  7998. int width = py_toint(py_arg(1));
  7999. if(width <= self.size) {
  8000. *py_retval() = argv[0];
  8001. return true;
  8002. }
  8003. c11_sbuf buf;
  8004. c11_sbuf__ctor(&buf);
  8005. if(left) {
  8006. c11_sbuf__write_sv(&buf, self);
  8007. for(int i = 0; i < width - self.size; i++) {
  8008. c11_sbuf__write_char(&buf, pad);
  8009. }
  8010. } else {
  8011. for(int i = 0; i < width - self.size; i++) {
  8012. c11_sbuf__write_char(&buf, pad);
  8013. }
  8014. c11_sbuf__write_sv(&buf, self);
  8015. }
  8016. c11_sbuf__py_submit(&buf, py_retval());
  8017. return true;
  8018. }
  8019. static bool str_ljust(int argc, py_Ref argv) { return str__widthjust_impl(true, argc, argv); }
  8020. static bool str_rjust(int argc, py_Ref argv) { return str__widthjust_impl(false, argc, argv); }
  8021. static bool str_find(int argc, py_Ref argv) {
  8022. if(argc > 3) return TypeError("find() takes at most 3 arguments");
  8023. c11_string* self = pk_tostr(&argv[0]);
  8024. int start = 0;
  8025. if(argc == 3) {
  8026. PY_CHECK_ARG_TYPE(2, tp_int);
  8027. start = py_toint(py_arg(2));
  8028. if(start < 0) start += c11_sv__u8_length(c11_string__sv(self));
  8029. if(start < 0) start = 0;
  8030. }
  8031. PY_CHECK_ARG_TYPE(1, tp_str);
  8032. c11_string* sub = pk_tostr(&argv[1]);
  8033. int res = c11_sv__index2(c11_string__sv(self), c11_string__sv(sub), start);
  8034. py_newint(py_retval(), res);
  8035. return true;
  8036. }
  8037. static bool str_index(int argc, py_Ref argv) {
  8038. bool ok = str_find(argc, argv);
  8039. if(!ok) return false;
  8040. if(py_toint(py_retval()) == -1) return ValueError("substring not found");
  8041. return true;
  8042. }
  8043. static bool str_encode(int argc, py_Ref argv) {
  8044. PY_CHECK_ARGC(1);
  8045. int size;
  8046. const char* data = py_tostrn(argv, &size);
  8047. unsigned char* p = py_newbytes(py_retval(), size);
  8048. memcpy(p, data, size);
  8049. return true;
  8050. }
  8051. static bool str_format(int argc, py_Ref argv) {
  8052. c11_sv self = py_tosv(argv);
  8053. py_Ref args = argv + 1;
  8054. int64_t auto_field_index = -1;
  8055. bool manual_field_used = false;
  8056. const char* p_begin = self.data;
  8057. const char* p_end = self.data + self.size;
  8058. const char* p = p_begin;
  8059. c11_sbuf buf;
  8060. c11_sbuf__ctor(&buf);
  8061. while(p < p_end) {
  8062. if(*p == '{') {
  8063. if((p + 1) < p_end && p[1] == '{') {
  8064. // '{{' -> '{'
  8065. c11_sbuf__write_char(&buf, '{');
  8066. p += 2;
  8067. } else {
  8068. if((p + 1) >= p_end) {
  8069. c11_sbuf__dtor(&buf);
  8070. return ValueError("single '{' encountered in format string");
  8071. }
  8072. p++;
  8073. // parse field
  8074. c11_sv field = {p, 0};
  8075. while(p < p_end && *p != '}' && *p != ':') {
  8076. p++;
  8077. }
  8078. if(p < p_end) field.size = p - field.data;
  8079. // parse spec
  8080. c11_sv spec = {p, 0};
  8081. if(*p == ':') {
  8082. while(p < p_end && *p != '}') {
  8083. p++;
  8084. }
  8085. if(p < p_end) spec.size = p - spec.data;
  8086. }
  8087. if(p < p_end) {
  8088. c11__rtassert(*p == '}');
  8089. } else {
  8090. c11_sbuf__dtor(&buf);
  8091. return ValueError("expected '}' before end of string");
  8092. }
  8093. // parse auto field
  8094. int64_t arg_index;
  8095. if(field.size > 0) { // {0}
  8096. if(auto_field_index >= 0) {
  8097. c11_sbuf__dtor(&buf);
  8098. return ValueError(
  8099. "cannot switch from automatic field numbering to manual field specification");
  8100. }
  8101. IntParsingResult res = c11__parse_uint(field, &arg_index, 10);
  8102. if(res != IntParsing_SUCCESS) {
  8103. c11_sbuf__dtor(&buf);
  8104. return ValueError("only integer field name is supported");
  8105. }
  8106. manual_field_used = true;
  8107. } else { // {}
  8108. if(manual_field_used) {
  8109. c11_sbuf__dtor(&buf);
  8110. return ValueError(
  8111. "cannot switch from manual field specification to automatic field numbering");
  8112. }
  8113. auto_field_index++;
  8114. arg_index = auto_field_index;
  8115. }
  8116. // do format
  8117. if(arg_index < 0 || arg_index >= (argc - 1)) {
  8118. c11_sbuf__dtor(&buf);
  8119. return IndexError("replacement index %i out of range for positional args tuple",
  8120. arg_index);
  8121. }
  8122. bool ok = pk_format_object(pk_current_vm, &args[arg_index], spec);
  8123. if(!ok) {
  8124. c11_sbuf__dtor(&buf);
  8125. return false;
  8126. }
  8127. // append to buf
  8128. c11__rtassert(py_isstr(py_retval()));
  8129. c11_sv formatted = py_tosv(py_retval());
  8130. c11_sbuf__write_sv(&buf, formatted);
  8131. p++; // skip '}'
  8132. }
  8133. } else if(*p == '}') {
  8134. if((p + 1) < p_end && p[1] == '}') {
  8135. // '}}' -> '}'
  8136. c11_sbuf__write_char(&buf, '}');
  8137. p += 2;
  8138. } else {
  8139. c11_sbuf__dtor(&buf);
  8140. return ValueError("single '}' encountered in format string");
  8141. }
  8142. } else {
  8143. c11_sbuf__write_char(&buf, *p);
  8144. p++;
  8145. }
  8146. }
  8147. c11_sbuf__py_submit(&buf, py_retval());
  8148. return true;
  8149. }
  8150. py_Type pk_str__register() {
  8151. py_Type type = pk_newtype("str", tp_object, NULL, NULL, false, true);
  8152. // no need to dtor because the memory is controlled by the object
  8153. py_bindmagic(tp_str, __new__, str__new__);
  8154. py_bindmagic(tp_str, __hash__, str__hash__);
  8155. py_bindmagic(tp_str, __len__, str__len__);
  8156. py_bindmagic(tp_str, __mod__, str__mod__);
  8157. py_bindmagic(tp_str, __add__, str__add__);
  8158. py_bindmagic(tp_str, __mul__, str__mul__);
  8159. py_bindmagic(tp_str, __rmul__, str__rmul__);
  8160. py_bindmagic(tp_str, __contains__, str__contains__);
  8161. py_bindmagic(tp_str, __str__, str__str__);
  8162. py_bindmagic(tp_str, __repr__, str__repr__);
  8163. py_bindmagic(tp_str, __iter__, str__iter__);
  8164. py_bindmagic(tp_str, __getitem__, str__getitem__);
  8165. py_bindmagic(tp_str, __eq__, str__eq__);
  8166. py_bindmagic(tp_str, __ne__, str__ne__);
  8167. py_bindmagic(tp_str, __lt__, str__lt__);
  8168. py_bindmagic(tp_str, __le__, str__le__);
  8169. py_bindmagic(tp_str, __gt__, str__gt__);
  8170. py_bindmagic(tp_str, __ge__, str__ge__);
  8171. py_bindmethod(tp_str, "lower", str_lower);
  8172. py_bindmethod(tp_str, "upper", str_upper);
  8173. py_bindmethod(tp_str, "startswith", str_startswith);
  8174. py_bindmethod(tp_str, "endswith", str_endswith);
  8175. py_bindmethod(tp_str, "join", str_join);
  8176. py_bindmethod(tp_str, "replace", str_replace);
  8177. py_bindmethod(tp_str, "split", str_split);
  8178. py_bindmethod(tp_str, "splitlines", str_splitlines);
  8179. py_bindmethod(tp_str, "count", str_count);
  8180. py_bindmethod(tp_str, "strip", str_strip);
  8181. py_bindmethod(tp_str, "lstrip", str_lstrip);
  8182. py_bindmethod(tp_str, "rstrip", str_rstrip);
  8183. py_bindmethod(tp_str, "zfill", str_zfill);
  8184. py_bindmethod(tp_str, "ljust", str_ljust);
  8185. py_bindmethod(tp_str, "rjust", str_rjust);
  8186. py_bindmethod(tp_str, "find", str_find);
  8187. py_bindmethod(tp_str, "index", str_index);
  8188. py_bindmethod(tp_str, "encode", str_encode);
  8189. py_bindmethod(tp_str, "format", str_format);
  8190. return type;
  8191. }
  8192. bool str_iterator__next__(int argc, py_Ref argv) {
  8193. PY_CHECK_ARGC(1);
  8194. int* ud = py_touserdata(&argv[0]);
  8195. int size;
  8196. const char* data = py_tostrn(py_getslot(argv, 0), &size);
  8197. if(*ud == size) return StopIteration();
  8198. int start = *ud;
  8199. int len = c11__u8_header(data[*ud], false);
  8200. *ud += len;
  8201. py_newstrv(py_retval(), (c11_sv){data + start, len});
  8202. return true;
  8203. }
  8204. py_Type pk_str_iterator__register() {
  8205. py_Type type = pk_newtype("str_iterator", tp_object, NULL, NULL, false, true);
  8206. py_bindmagic(type, __iter__, pk_wrapper__self);
  8207. py_bindmagic(type, __next__, str_iterator__next__);
  8208. return type;
  8209. }
  8210. static bool bytes__new__(int argc, py_Ref argv) {
  8211. if(argc == 1) {
  8212. py_newbytes(py_retval(), 0);
  8213. return true;
  8214. }
  8215. if(argc > 2) return TypeError("bytes() takes at most 1 argument");
  8216. py_TValue* p;
  8217. int length = pk_arrayview(&argv[1], &p);
  8218. if(length == -1) return TypeError("bytes() argument must be a list or tuple");
  8219. unsigned char* data = py_newbytes(py_retval(), length);
  8220. for(int i = 0; i < length; i++) {
  8221. if(!py_checktype(&p[i], tp_int)) return false;
  8222. py_i64 v = py_toint(&p[i]);
  8223. if(v < 0 || v > 255) return ValueError("bytes must be in range(0, 256)");
  8224. data[i] = v;
  8225. }
  8226. return true;
  8227. }
  8228. static bool bytes__repr__(int argc, py_Ref argv) {
  8229. PY_CHECK_ARGC(1);
  8230. c11_bytes* self = py_touserdata(&argv[0]);
  8231. c11_sbuf buf;
  8232. c11_sbuf__ctor(&buf);
  8233. c11_sbuf__write_char(&buf, 'b');
  8234. c11_sbuf__write_quoted(&buf, (c11_sv){(const char*)self->data, self->size}, '\'');
  8235. c11_sbuf__py_submit(&buf, py_retval());
  8236. return true;
  8237. }
  8238. static bool bytes__getitem__(int argc, py_Ref argv) {
  8239. PY_CHECK_ARGC(2);
  8240. int size;
  8241. unsigned char* data = py_tobytes(&argv[0], &size);
  8242. py_Ref _1 = py_arg(1);
  8243. if(_1->type == tp_int) {
  8244. int index = py_toint(_1);
  8245. if(!pk__normalize_index(&index, size)) return false;
  8246. py_newint(py_retval(), data[index]);
  8247. return true;
  8248. } else if(_1->type == tp_slice) {
  8249. int start, stop, step;
  8250. bool ok = pk__parse_int_slice(_1, size, &start, &stop, &step);
  8251. if(!ok) return false;
  8252. c11_vector res;
  8253. c11_vector__ctor(&res, sizeof(unsigned char));
  8254. for(int i = start; step > 0 ? i < stop : i > stop; i += step) {
  8255. c11_vector__push(unsigned char, &res, data[i]);
  8256. }
  8257. unsigned char* p = py_newbytes(py_retval(), res.length);
  8258. memcpy(p, res.data, res.length);
  8259. c11_vector__dtor(&res);
  8260. return true;
  8261. } else {
  8262. return TypeError("bytes indices must be integers");
  8263. }
  8264. }
  8265. static bool bytes__eq__(int argc, py_Ref argv) {
  8266. PY_CHECK_ARGC(2);
  8267. c11_bytes* self = py_touserdata(&argv[0]);
  8268. if(!py_istype(&argv[1], tp_bytes)) {
  8269. py_newnotimplemented(py_retval());
  8270. } else {
  8271. c11_bytes* other = py_touserdata(&argv[1]);
  8272. py_newbool(py_retval(), c11_bytes__eq(self, other));
  8273. }
  8274. return true;
  8275. }
  8276. static bool bytes__ne__(int argc, py_Ref argv) {
  8277. PY_CHECK_ARGC(2);
  8278. c11_bytes* self = py_touserdata(&argv[0]);
  8279. if(!py_istype(&argv[1], tp_bytes)) {
  8280. py_newnotimplemented(py_retval());
  8281. } else {
  8282. c11_bytes* other = py_touserdata(&argv[1]);
  8283. py_newbool(py_retval(), !c11_bytes__eq(self, other));
  8284. }
  8285. return true;
  8286. }
  8287. static bool bytes__hash__(int argc, py_Ref argv) {
  8288. PY_CHECK_ARGC(1);
  8289. c11_bytes* self = py_touserdata(&argv[0]);
  8290. uint64_t res = 0;
  8291. for(int i = 0; i < self->size; i++) {
  8292. res = res * 31 + self->data[i];
  8293. }
  8294. py_newint(py_retval(), res);
  8295. return true;
  8296. }
  8297. static bool bytes__add__(int argc, py_Ref argv) {
  8298. PY_CHECK_ARGC(2);
  8299. c11_bytes* self = py_touserdata(&argv[0]);
  8300. if(py_arg(1)->type != tp_bytes) {
  8301. py_newnotimplemented(py_retval());
  8302. } else {
  8303. c11_bytes* other = py_touserdata(&argv[1]);
  8304. unsigned char* p = py_newbytes(py_retval(), self->size + other->size);
  8305. memcpy(p, self->data, self->size);
  8306. memcpy(p + self->size, other->data, other->size);
  8307. }
  8308. return true;
  8309. }
  8310. static bool bytes_decode(int argc, py_Ref argv) {
  8311. PY_CHECK_ARGC(1);
  8312. int size;
  8313. unsigned char* data = py_tobytes(&argv[0], &size);
  8314. py_newstrv(py_retval(), (c11_sv){(const char*)data, size});
  8315. return true;
  8316. }
  8317. static bool bytes__len__(int argc, py_Ref argv) {
  8318. PY_CHECK_ARGC(1);
  8319. c11_bytes* self = py_touserdata(&argv[0]);
  8320. py_newint(py_retval(), self->size);
  8321. return true;
  8322. }
  8323. static bool bytes__iter__(int argc, py_Ref argv) {
  8324. PY_CHECK_ARGC(1);
  8325. int* ud = py_newobject(py_retval(), tp_bytes_iterator, 1, sizeof(int));
  8326. *ud = 0;
  8327. py_setslot(py_retval(), 0, argv);
  8328. return true;
  8329. }
  8330. bool bytes_iterator__next__(int argc, py_Ref argv) {
  8331. PY_CHECK_ARGC(1);
  8332. int* index = py_touserdata(&argv[0]);
  8333. int size;
  8334. unsigned char* data =
  8335. py_tobytes(py_getslot(argv,0), &size);
  8336. if(*index == size)
  8337. return StopIteration();
  8338. py_newint(py_retval(), data[*index]);
  8339. (*index)++;
  8340. return true;
  8341. }
  8342. py_Type pk_bytes_iterator__register() {
  8343. py_Type type =
  8344. pk_newtype("bytes_iterator", tp_object, NULL, NULL, false, true);
  8345. py_bindmagic(type, __iter__, pk_wrapper__self);
  8346. py_bindmagic(type, __next__, bytes_iterator__next__);
  8347. return type;
  8348. }
  8349. py_Type pk_bytes__register() {
  8350. py_Type type = pk_newtype("bytes", tp_object, NULL, NULL, false, true);
  8351. // no need to dtor because the memory is controlled by the object
  8352. py_bindmagic(tp_bytes, __new__, bytes__new__);
  8353. py_bindmagic(tp_bytes, __repr__, bytes__repr__);
  8354. py_bindmagic(tp_bytes, __getitem__, bytes__getitem__);
  8355. py_bindmagic(tp_bytes, __eq__, bytes__eq__);
  8356. py_bindmagic(tp_bytes, __ne__, bytes__ne__);
  8357. py_bindmagic(tp_bytes, __add__, bytes__add__);
  8358. py_bindmagic(tp_bytes, __hash__, bytes__hash__);
  8359. py_bindmagic(tp_bytes, __len__, bytes__len__);
  8360. py_bindmagic(tp_bytes, __iter__, bytes__iter__);
  8361. py_bindmethod(tp_bytes, "decode", bytes_decode);
  8362. return type;
  8363. }
  8364. #undef DEF_STR_CMP_OP
  8365. // src/common\algorithm.c
  8366. #include <string.h>
  8367. static bool _stable_sort_merge(char* a,
  8368. char* a_end,
  8369. char* b,
  8370. char* b_end,
  8371. char* r,
  8372. int elem_size,
  8373. int (*f_lt)(const void* a, const void* b, void* extra),
  8374. void* extra) {
  8375. while(a < a_end && b < b_end) {
  8376. int res = f_lt(b, a, extra);
  8377. // check error
  8378. if(res == -1) return false;
  8379. if(res == 0) { // !(b<a) -> (b>=a) -> (a<=b)
  8380. memcpy(r, a, elem_size);
  8381. a += elem_size;
  8382. } else {
  8383. memcpy(r, b, elem_size);
  8384. b += elem_size;
  8385. }
  8386. r += elem_size;
  8387. }
  8388. // one of the arrays is empty
  8389. for(; a < a_end; a += elem_size, r += elem_size)
  8390. memcpy(r, a, elem_size);
  8391. for(; b < b_end; b += elem_size, r += elem_size)
  8392. memcpy(r, b, elem_size);
  8393. return true;
  8394. }
  8395. bool c11__stable_sort(void* ptr_,
  8396. int length,
  8397. int elem_size,
  8398. int (*f_lt)(const void* a, const void* b, void* extra),
  8399. void* extra) {
  8400. // merge sort
  8401. char *ptr = ptr_, *tmp = PK_MALLOC(length * elem_size);
  8402. for(int seg = 1; seg < length; seg *= 2) {
  8403. for(char* a = ptr; a < ptr + (length - seg) * elem_size; a += 2 * seg * elem_size) {
  8404. char *b = a + seg * elem_size, *a_end = b, *b_end = b + seg * elem_size;
  8405. if(b_end > ptr + length * elem_size) b_end = ptr + length * elem_size;
  8406. bool ok = _stable_sort_merge(a, a_end, b, b_end, tmp, elem_size, f_lt, extra);
  8407. if(!ok) {
  8408. PK_FREE(tmp);
  8409. return false;
  8410. }
  8411. memcpy(a, tmp, b_end - a);
  8412. }
  8413. }
  8414. PK_FREE(tmp);
  8415. return true;
  8416. }
  8417. // src/common\chunkedvector.c
  8418. #include <assert.h>
  8419. #if defined(_MSC_VER)
  8420. #include <intrin.h>
  8421. #endif
  8422. PK_INLINE int c11__bit_length(unsigned long x) {
  8423. #if(defined(__clang__) || defined(__GNUC__))
  8424. return x == 0 ? 0 : (int)sizeof(unsigned long) * 8 - __builtin_clzl(x);
  8425. #elif defined(_MSC_VER)
  8426. _Static_assert(sizeof(unsigned long) <= 4, "unsigned long is greater than 4 bytes");
  8427. unsigned long msb;
  8428. if(_BitScanReverse(&msb, x)) { return (int)msb + 1; }
  8429. return 0;
  8430. #else
  8431. const int BIT_LENGTH_TABLE[32] = {0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  8432. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5};
  8433. int msb = 0;
  8434. while(x >= 32) {
  8435. msb += 6;
  8436. x >>= 6;
  8437. }
  8438. msb += BIT_LENGTH_TABLE[x];
  8439. return msb;
  8440. #endif
  8441. }
  8442. void c11_chunkedvector__ctor(c11_chunkedvector* self, int elem_size, int initial_chunks) {
  8443. if(initial_chunks < 5) initial_chunks = 5;
  8444. c11_vector__ctor(&self->chunks, sizeof(c11_chunkedvector_chunk));
  8445. self->length = 0;
  8446. self->capacity = (1U << (unsigned int)initial_chunks) - 1U;
  8447. self->elem_size = elem_size;
  8448. self->initial_chunks = initial_chunks;
  8449. void* chunks_data = PK_MALLOC(elem_size * ((1U << (unsigned int)initial_chunks) - 1));
  8450. for(int i = 0; i < initial_chunks; i++) {
  8451. c11_chunkedvector_chunk chunk = {.length = 0,
  8452. .capacity = 1U << i,
  8453. .data = (char*)chunks_data + elem_size * ((1U << i) - 1U)};
  8454. c11_vector__push(c11_chunkedvector_chunk, &self->chunks, chunk);
  8455. }
  8456. }
  8457. void c11_chunkedvector__dtor(c11_chunkedvector* self) {
  8458. for(int index = self->initial_chunks; index < self->chunks.length; index++) {
  8459. c11_chunkedvector_chunk* chunk = c11__at(c11_chunkedvector_chunk, &self->chunks, index);
  8460. PK_FREE(chunk->data);
  8461. }
  8462. c11_chunkedvector_chunk* initial_chunk = c11__at(c11_chunkedvector_chunk, &self->chunks, 0);
  8463. PK_FREE(initial_chunk->data);
  8464. c11_vector__dtor(&self->chunks);
  8465. }
  8466. void* c11_chunkedvector__emplace(c11_chunkedvector* self) {
  8467. if(self->length == self->capacity) {
  8468. #ifndef NDEBUG
  8469. c11_chunkedvector_chunk last_chunk =
  8470. c11_vector__back(c11_chunkedvector_chunk, &self->chunks);
  8471. assert(last_chunk.capacity == last_chunk.length);
  8472. #endif
  8473. c11_chunkedvector_chunk chunk = {
  8474. .length = 0,
  8475. .capacity = 1U << (unsigned int)self->chunks.length,
  8476. .data = PK_MALLOC(self->elem_size * ((1U << (unsigned int)self->chunks.length)))};
  8477. self->capacity += chunk.capacity;
  8478. c11_vector__push(c11_chunkedvector_chunk, &self->chunks, chunk);
  8479. }
  8480. #if 1
  8481. int last_chunk_index = c11__bit_length(self->length + 1) - 1;
  8482. c11_chunkedvector_chunk* last_chunk =
  8483. c11__at(c11_chunkedvector_chunk, &self->chunks, last_chunk_index);
  8484. #else
  8485. // This is not correct, because there is some pre-allocated chunks
  8486. c11_chunkedvector_chunk* last_chunk = &c11_vector__back(c11_chunkedvector_chunk, &self->chunks);
  8487. #endif
  8488. void* p = (char*)last_chunk->data + self->elem_size * last_chunk->length;
  8489. last_chunk->length++;
  8490. self->length++;
  8491. return p;
  8492. }
  8493. void* c11_chunkedvector__at(c11_chunkedvector* self, int index) {
  8494. int chunk_index = c11__bit_length(index + 1) - 1;
  8495. c11_chunkedvector_chunk* chunk = c11__at(c11_chunkedvector_chunk, &self->chunks, chunk_index);
  8496. return (char*)chunk->data + (index + 1 - (1U << (unsigned int)chunk_index)) * self->elem_size;
  8497. }
  8498. // src/common\dmath.c
  8499. #include <stdint.h>
  8500. union Float64Bits {
  8501. double f;
  8502. uint64_t i;
  8503. };
  8504. /* IEEE 754 double precision floating point data manipulation */
  8505. typedef union
  8506. {
  8507. double f;
  8508. uint64_t u;
  8509. struct {int32_t i0,i1;} s;
  8510. } udi_t;
  8511. // https://github.com/akohlmey/fastermath/blob/master/src/exp.c#L63
  8512. double dmath_exp2(double x) {
  8513. if (x > 1000) return DMATH_INFINITY;
  8514. if (x < -1000) return 0;
  8515. if (dmath_isnan(x)) return DMATH_NAN;
  8516. const int FM_DOUBLE_BIAS = 1023;
  8517. static const double fm_exp2_q[] = {
  8518. /* 1.00000000000000000000e0, */
  8519. 2.33184211722314911771e2,
  8520. 4.36821166879210612817e3
  8521. };
  8522. static const double fm_exp2_p[] = {
  8523. 2.30933477057345225087e-2,
  8524. 2.02020656693165307700e1,
  8525. 1.51390680115615096133e3
  8526. };
  8527. double ipart, fpart, px, qx;
  8528. udi_t epart;
  8529. ipart = dmath_floor(x+0.5);
  8530. fpart = x - ipart;
  8531. // FM_DOUBLE_INIT_EXP(epart,ipart);
  8532. epart.s.i0 = 0;
  8533. epart.s.i1 = (((int) ipart) + FM_DOUBLE_BIAS) << 20;
  8534. x = fpart*fpart;
  8535. px = fm_exp2_p[0];
  8536. px = px*x + fm_exp2_p[1];
  8537. qx = x + fm_exp2_q[0];
  8538. px = px*x + fm_exp2_p[2];
  8539. qx = qx*x + fm_exp2_q[1];
  8540. px = px * fpart;
  8541. x = 1.0 + 2.0*(px/(qx-px));
  8542. return epart.f*x;
  8543. }
  8544. double dmath_log2(double x) {
  8545. if(x < 0) return DMATH_NAN;
  8546. if(x == 0) return -DMATH_INFINITY;
  8547. if(x == DMATH_INFINITY) return DMATH_INFINITY;
  8548. if(dmath_isnan(x)) return DMATH_NAN;
  8549. const double fm_log_dinv = 4.09600000000000000000e+03;
  8550. const double fm_log_dsq6 = 9.93410746256510361521e-09;
  8551. const int FM_DOUBLE_BIAS = 1023;
  8552. const int FM_DOUBLE_EMASK = 2146435072;
  8553. const int FM_DOUBLE_MBITS = 20;
  8554. const int FM_DOUBLE_MMASK = 1048575;
  8555. const int FM_DOUBLE_EZERO = 1072693248;
  8556. const int FM_SPLINE_SHIFT = 8;
  8557. udi_t val;
  8558. double a,b,y;
  8559. int32_t hx, ipart;
  8560. val.f = x;
  8561. hx = val.s.i1;
  8562. /* extract exponent and subtract bias */
  8563. ipart = (((hx & FM_DOUBLE_EMASK) >> FM_DOUBLE_MBITS) - FM_DOUBLE_BIAS);
  8564. /* mask out exponent to get the prefactor to 2**ipart */
  8565. hx &= FM_DOUBLE_MMASK;
  8566. val.s.i1 = hx | FM_DOUBLE_EZERO;
  8567. x = val.f;
  8568. /* table index */
  8569. hx >>= FM_SPLINE_SHIFT;
  8570. /* compute x value matching table index */
  8571. val.s.i0 = 0;
  8572. val.s.i1 = FM_DOUBLE_EZERO | (hx << FM_SPLINE_SHIFT);
  8573. b = (x - val.f) * fm_log_dinv;
  8574. a = 1.0 - b;
  8575. /* evaluate spline */
  8576. y = a * fm_log_q1[hx] + b * fm_log_q1[hx+1];
  8577. a = (a*a*a-a) * fm_log_q2[hx];
  8578. b = (b*b*b-b) * fm_log_q2[hx+1];
  8579. y += (a + b) * fm_log_dsq6;
  8580. return ((double) ipart) + (y * DMATH_LOG2_E);
  8581. }
  8582. double dmath_exp(double x) {
  8583. return dmath_exp2(x * DMATH_LOG2_E); // log2(e)
  8584. }
  8585. double dmath_exp10(double x) {
  8586. return dmath_exp2(x * 3.321928094887362); // log2(10)
  8587. }
  8588. double dmath_log(double x) {
  8589. return dmath_log2(x) / DMATH_LOG2_E; // log2(e)
  8590. }
  8591. double dmath_log10(double x) {
  8592. return dmath_log2(x) / 3.321928094887362; // log2(10)
  8593. }
  8594. double dmath_pow(double base, double exp) {
  8595. int64_t exp_int = (int64_t)exp;
  8596. if(exp_int == exp) {
  8597. if(exp_int == 0) return 1;
  8598. if(exp_int < 0) {
  8599. if(base == 0) return DMATH_NAN;
  8600. base = 1 / base;
  8601. exp_int = -exp_int;
  8602. }
  8603. double res = 1;
  8604. while(exp_int > 0) {
  8605. if(exp_int & 1) res *= base;
  8606. base *= base;
  8607. exp_int >>= 1;
  8608. }
  8609. return res;
  8610. }
  8611. if (base > 0) {
  8612. if(base == 1.0) return 1.0;
  8613. return dmath_exp(exp * dmath_log(base));
  8614. }
  8615. if (base == 0) {
  8616. if (exp > 0) return 0;
  8617. if (exp == 0) return 1;
  8618. }
  8619. return DMATH_NAN;
  8620. }
  8621. double dmath_sqrt(double x) {
  8622. return dmath_pow(x, 0.5);
  8623. }
  8624. double dmath_cbrt(double x) {
  8625. return dmath_pow(x, 1.0 / 3.0);
  8626. }
  8627. // https://github.com/kraj/musl/blob/kraj/master/src/math/sincos.c
  8628. static double __sin(double x, double y, int iy)
  8629. {
  8630. static const double
  8631. S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */
  8632. S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */
  8633. S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */
  8634. S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */
  8635. S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */
  8636. S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */
  8637. double z,r,v,w;
  8638. z = x*x;
  8639. w = z*z;
  8640. r = S2 + z*(S3 + z*S4) + z*w*(S5 + z*S6);
  8641. v = z*x;
  8642. if (iy == 0)
  8643. return x + v*(S1 + z*r);
  8644. else
  8645. return x - ((z*(0.5*y - v*r) - y) - v*S1);
  8646. }
  8647. static double __cos(double x, double y)
  8648. {
  8649. static const double
  8650. C1 = 4.16666666666666019037e-02, /* 0x3FA55555, 0x5555554C */
  8651. C2 = -1.38888888888741095749e-03, /* 0xBF56C16C, 0x16C15177 */
  8652. C3 = 2.48015872894767294178e-05, /* 0x3EFA01A0, 0x19CB1590 */
  8653. C4 = -2.75573143513906633035e-07, /* 0xBE927E4F, 0x809C52AD */
  8654. C5 = 2.08757232129817482790e-09, /* 0x3E21EE9E, 0xBDB4B1C4 */
  8655. C6 = -1.13596475577881948265e-11; /* 0xBDA8FAE9, 0xBE8838D4 */
  8656. double hz,z,r,w;
  8657. z = x*x;
  8658. w = z*z;
  8659. r = z*(C1+z*(C2+z*C3)) + w*w*(C4+z*(C5+z*C6));
  8660. hz = 0.5*z;
  8661. w = 1.0-hz;
  8662. return w + (((1.0-w)-hz) + (z*r-x*y));
  8663. }
  8664. int __rem_pio2(double x, double *y)
  8665. {
  8666. static const double
  8667. toint = 1.5/2.22044604925031308085e-16,
  8668. pio4 = 0x1.921fb54442d18p-1,
  8669. invpio2 = 6.36619772367581382433e-01, /* 0x3FE45F30, 0x6DC9C883 */
  8670. pio2_1 = 1.57079632673412561417e+00, /* 0x3FF921FB, 0x54400000 */
  8671. pio2_1t = 6.07710050650619224932e-11, /* 0x3DD0B461, 0x1A626331 */
  8672. pio2_2 = 6.07710050630396597660e-11, /* 0x3DD0B461, 0x1A600000 */
  8673. pio2_2t = 2.02226624879595063154e-21, /* 0x3BA3198A, 0x2E037073 */
  8674. pio2_3 = 2.02226624871116645580e-21, /* 0x3BA3198A, 0x2E000000 */
  8675. pio2_3t = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */
  8676. union Float64Bits u = { .f = x };
  8677. double z,w,t,r,fn;
  8678. double tx[3],ty[2];
  8679. uint32_t ix;
  8680. int sign, n, ex, ey, i;
  8681. sign = u.i>>63;
  8682. ix = u.i>>32 & 0x7fffffff;
  8683. if (ix <= 0x400f6a7a) { /* |x| ~<= 5pi/4 */
  8684. if ((ix & 0xfffff) == 0x921fb) /* |x| ~= pi/2 or 2pi/2 */
  8685. goto medium; /* cancellation -- use medium case */
  8686. if (ix <= 0x4002d97c) { /* |x| ~<= 3pi/4 */
  8687. if (!sign) {
  8688. z = x - pio2_1; /* one round good to 85 bits */
  8689. y[0] = z - pio2_1t;
  8690. y[1] = (z-y[0]) - pio2_1t;
  8691. return 1;
  8692. } else {
  8693. z = x + pio2_1;
  8694. y[0] = z + pio2_1t;
  8695. y[1] = (z-y[0]) + pio2_1t;
  8696. return -1;
  8697. }
  8698. } else {
  8699. if (!sign) {
  8700. z = x - 2*pio2_1;
  8701. y[0] = z - 2*pio2_1t;
  8702. y[1] = (z-y[0]) - 2*pio2_1t;
  8703. return 2;
  8704. } else {
  8705. z = x + 2*pio2_1;
  8706. y[0] = z + 2*pio2_1t;
  8707. y[1] = (z-y[0]) + 2*pio2_1t;
  8708. return -2;
  8709. }
  8710. }
  8711. }
  8712. if (ix <= 0x401c463b) { /* |x| ~<= 9pi/4 */
  8713. if (ix <= 0x4015fdbc) { /* |x| ~<= 7pi/4 */
  8714. if (ix == 0x4012d97c) /* |x| ~= 3pi/2 */
  8715. goto medium;
  8716. if (!sign) {
  8717. z = x - 3*pio2_1;
  8718. y[0] = z - 3*pio2_1t;
  8719. y[1] = (z-y[0]) - 3*pio2_1t;
  8720. return 3;
  8721. } else {
  8722. z = x + 3*pio2_1;
  8723. y[0] = z + 3*pio2_1t;
  8724. y[1] = (z-y[0]) + 3*pio2_1t;
  8725. return -3;
  8726. }
  8727. } else {
  8728. if (ix == 0x401921fb) /* |x| ~= 4pi/2 */
  8729. goto medium;
  8730. if (!sign) {
  8731. z = x - 4*pio2_1;
  8732. y[0] = z - 4*pio2_1t;
  8733. y[1] = (z-y[0]) - 4*pio2_1t;
  8734. return 4;
  8735. } else {
  8736. z = x + 4*pio2_1;
  8737. y[0] = z + 4*pio2_1t;
  8738. y[1] = (z-y[0]) + 4*pio2_1t;
  8739. return -4;
  8740. }
  8741. }
  8742. }
  8743. if (ix < 0x413921fb) { /* |x| ~< 2^20*(pi/2), medium size */
  8744. medium:
  8745. /* rint(x/(pi/2)) */
  8746. fn = (double)x*invpio2 + toint - toint;
  8747. n = (int32_t)fn;
  8748. r = x - fn*pio2_1;
  8749. w = fn*pio2_1t; /* 1st round, good to 85 bits */
  8750. /* Matters with directed rounding. */
  8751. if ((r - w < -pio4)) {
  8752. n--;
  8753. fn--;
  8754. r = x - fn*pio2_1;
  8755. w = fn*pio2_1t;
  8756. } else if ((r - w > pio4)) {
  8757. n++;
  8758. fn++;
  8759. r = x - fn*pio2_1;
  8760. w = fn*pio2_1t;
  8761. }
  8762. y[0] = r - w;
  8763. u.f = y[0];
  8764. ey = u.i>>52 & 0x7ff;
  8765. ex = ix>>20;
  8766. if (ex - ey > 16) { /* 2nd round, good to 118 bits */
  8767. t = r;
  8768. w = fn*pio2_2;
  8769. r = t - w;
  8770. w = fn*pio2_2t - ((t-r)-w);
  8771. y[0] = r - w;
  8772. u.f = y[0];
  8773. ey = u.i>>52 & 0x7ff;
  8774. if (ex - ey > 49) { /* 3rd round, good to 151 bits, covers all cases */
  8775. t = r;
  8776. w = fn*pio2_3;
  8777. r = t - w;
  8778. w = fn*pio2_3t - ((t-r)-w);
  8779. y[0] = r - w;
  8780. }
  8781. }
  8782. y[1] = (r - y[0]) - w;
  8783. return n;
  8784. }
  8785. (void)tx;
  8786. (void)ty;
  8787. (void)i;
  8788. return 0;
  8789. #if 0
  8790. /*
  8791. * all other (large) arguments
  8792. */
  8793. if (ix >= 0x7ff00000) { /* x is inf or NaN */
  8794. y[0] = y[1] = x - x;
  8795. return 0;
  8796. }
  8797. /* set z = scalbn(|x|,-ilogb(x)+23) */
  8798. u.f = x;
  8799. u.i &= (uint64_t)-1>>12;
  8800. u.i |= (uint64_t)(0x3ff + 23)<<52;
  8801. z = u.f;
  8802. for (i=0; i < 2; i++) {
  8803. tx[i] = (double)(int32_t)z;
  8804. z = (z-tx[i])*0x1p24;
  8805. }
  8806. tx[i] = z;
  8807. /* skip zero terms, first term is non-zero */
  8808. while (tx[i] == 0.0)
  8809. i--;
  8810. n = __rem_pio2_large(tx,ty,(int)(ix>>20)-(0x3ff+23),i+1,1);
  8811. if (sign) {
  8812. y[0] = -ty[0];
  8813. y[1] = -ty[1];
  8814. return -n;
  8815. }
  8816. y[0] = ty[0];
  8817. y[1] = ty[1];
  8818. return n;
  8819. #endif
  8820. }
  8821. void dmath_sincos(double x, double *sin, double *cos) {
  8822. double y[2], s, c;
  8823. uint32_t ix;
  8824. unsigned n;
  8825. //GET_HIGH_WORD(ix, x);
  8826. union Float64Bits u = { .f = x };
  8827. ix = (uint32_t)(u.i >> 32);
  8828. ix &= 0x7fffffff;
  8829. /* |x| ~< pi/4 */
  8830. if (ix <= 0x3fe921fb) {
  8831. /* if |x| < 2**-27 * sqrt(2) */
  8832. if (ix < 0x3e46a09e) {
  8833. /* raise inexact if x!=0 and underflow if subnormal */
  8834. // FORCE_EVAL(ix < 0x00100000 ? x/0x1p120f : x+0x1p120f);
  8835. volatile double y_force_eval;
  8836. y_force_eval = ix < 0x00100000 ? x/0x1p120f : x+0x1p120f;
  8837. (void)y_force_eval;
  8838. *sin = x;
  8839. *cos = 1.0;
  8840. return;
  8841. }
  8842. *sin = __sin(x, 0.0, 0);
  8843. *cos = __cos(x, 0.0);
  8844. return;
  8845. }
  8846. /* sincos(Inf or NaN) is NaN */
  8847. if (ix >= 0x7ff00000) {
  8848. *sin = *cos = x - x;
  8849. return;
  8850. }
  8851. /* argument reduction needed */
  8852. n = __rem_pio2(x, y);
  8853. s = __sin(y[0], y[1], 1);
  8854. c = __cos(y[0], y[1]);
  8855. switch (n&3) {
  8856. case 0:
  8857. *sin = s;
  8858. *cos = c;
  8859. break;
  8860. case 1:
  8861. *sin = c;
  8862. *cos = -s;
  8863. break;
  8864. case 2:
  8865. *sin = -s;
  8866. *cos = -c;
  8867. break;
  8868. case 3:
  8869. default:
  8870. *sin = -c;
  8871. *cos = s;
  8872. break;
  8873. }
  8874. }
  8875. double dmath_sin(double x) {
  8876. double s, c;
  8877. dmath_sincos(x, &s, &c);
  8878. return s;
  8879. }
  8880. double dmath_cos(double x) {
  8881. double s, c;
  8882. dmath_sincos(x, &s, &c);
  8883. return c;
  8884. }
  8885. double dmath_tan(double x) {
  8886. double s, c;
  8887. dmath_sincos(x, &s, &c);
  8888. return s / c;
  8889. }
  8890. static double zig_r64(double z) {
  8891. const double pS0 = 1.66666666666666657415e-01;
  8892. const double pS1 = -3.25565818622400915405e-01;
  8893. const double pS2 = 2.01212532134862925881e-01;
  8894. const double pS3 = -4.00555345006794114027e-02;
  8895. const double pS4 = 7.91534994289814532176e-04;
  8896. const double pS5 = 3.47933107596021167570e-05;
  8897. const double qS1 = -2.40339491173441421878e+00;
  8898. const double qS2 = 2.02094576023350569471e+00;
  8899. const double qS3 = -6.88283971605453293030e-01;
  8900. const double qS4 = 7.70381505559019352791e-02;
  8901. double p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5)))));
  8902. double q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4)));
  8903. return p / q;
  8904. }
  8905. // https://github.com/ziglang/zig/blob/master/lib/std/math/asin.zig
  8906. double dmath_asin(double x) {
  8907. if(!(x >= -1 && x <= 1)) return DMATH_NAN;
  8908. const double pio2_hi = 1.57079632679489655800e+00;
  8909. const double pio2_lo = 6.12323399573676603587e-17;
  8910. union Float64Bits ux_union;
  8911. ux_union.f = x;
  8912. uint64_t ux = ux_union.i;
  8913. uint32_t hx = (uint32_t)(ux >> 32);
  8914. uint32_t ix = hx & 0x7FFFFFFF;
  8915. /* |x| >= 1 or nan */
  8916. if (ix >= 0x3FF00000) {
  8917. uint32_t lx = (uint32_t)(ux & 0xFFFFFFFF);
  8918. /* asin(1) = +-pi/2 with inexact */
  8919. if (((ix - 0x3FF00000) | lx) == 0) {
  8920. return x * pio2_hi + 0x1.0p-120;
  8921. } else {
  8922. return DMATH_NAN;
  8923. }
  8924. }
  8925. /* |x| < 0.5 */
  8926. if (ix < 0x3FE00000) {
  8927. /* if 0x1p-1022 <= |x| < 0x1p-26 avoid raising overflow */
  8928. if (ix < 0x3E500000 && ix >= 0x00100000) {
  8929. return x;
  8930. } else {
  8931. return x + x * zig_r64(x * x);
  8932. }
  8933. }
  8934. /* 1 > |x| >= 0.5 */
  8935. double z = (1 - dmath_fabs(x)) * 0.5;
  8936. double s = dmath_sqrt(z);
  8937. double r = zig_r64(z);
  8938. double fx;
  8939. /* |x| > 0.975 */
  8940. if (ix >= 0x3FEF3333) {
  8941. fx = pio2_hi - 2 * (s + s * r);
  8942. } else {
  8943. union Float64Bits jx_union = { .f = s };
  8944. uint64_t jx = jx_union.i;
  8945. union Float64Bits df_union = { .i = jx & 0xFFFFFFFF00000000ULL };
  8946. double df = df_union.f;
  8947. double c = (z - df * df) / (s + df);
  8948. fx = 0.5 * pio2_hi - (2 * s * r - (pio2_lo - 2 * c) - (0.5 * pio2_hi - 2 * df));
  8949. }
  8950. if (hx >> 31 != 0) {
  8951. return -fx;
  8952. } else {
  8953. return fx;
  8954. }
  8955. }
  8956. double dmath_acos(double x) {
  8957. return DMATH_PI / 2 - dmath_asin(x);
  8958. }
  8959. double dmath_atan(double x) {
  8960. return dmath_asin(x / dmath_sqrt(1 + x * x));
  8961. }
  8962. double dmath_atan2(double y, double x)
  8963. {
  8964. const double
  8965. pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */
  8966. pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */
  8967. double z;
  8968. uint32_t m,lx,ly,ix,iy;
  8969. if (dmath_isnan(x) || dmath_isnan(y))
  8970. return x+y;
  8971. // EXTRACT_WORDS(ix, lx, x);
  8972. // EXTRACT_WORDS(iy, ly, y);
  8973. union Float64Bits ux = { .f = x }, uy = { .f = y };
  8974. ix = (uint32_t)(ux.i >> 32);
  8975. iy = (uint32_t)(uy.i >> 32);
  8976. lx = (uint32_t)(ux.i & 0xFFFFFFFF);
  8977. ly = (uint32_t)(uy.i & 0xFFFFFFFF);
  8978. if ((ix-0x3ff00000 | lx) == 0) /* x = 1.0 */
  8979. return dmath_atan(y);
  8980. m = ((iy>>31)&1) | ((ix>>30)&2); /* 2*sign(x)+sign(y) */
  8981. ix = ix & 0x7fffffff;
  8982. iy = iy & 0x7fffffff;
  8983. /* when y = 0 */
  8984. if ((iy|ly) == 0) {
  8985. switch(m) {
  8986. case 0:
  8987. case 1: return y; /* atan(+-0,+anything)=+-0 */
  8988. case 2: return pi; /* atan(+0,-anything) = pi */
  8989. case 3: return -pi; /* atan(-0,-anything) =-pi */
  8990. }
  8991. }
  8992. /* when x = 0 */
  8993. if ((ix|lx) == 0)
  8994. return m&1 ? -pi/2 : pi/2;
  8995. /* when x is INF */
  8996. if (ix == 0x7ff00000) {
  8997. if (iy == 0x7ff00000) {
  8998. switch(m) {
  8999. case 0: return pi/4; /* atan(+INF,+INF) */
  9000. case 1: return -pi/4; /* atan(-INF,+INF) */
  9001. case 2: return 3*pi/4; /* atan(+INF,-INF) */
  9002. case 3: return -3*pi/4; /* atan(-INF,-INF) */
  9003. }
  9004. } else {
  9005. switch(m) {
  9006. case 0: return 0.0; /* atan(+...,+INF) */
  9007. case 1: return -0.0; /* atan(-...,+INF) */
  9008. case 2: return pi; /* atan(+...,-INF) */
  9009. case 3: return -pi; /* atan(-...,-INF) */
  9010. }
  9011. }
  9012. }
  9013. /* |y/x| > 0x1p64 */
  9014. if (ix+(64<<20) < iy || iy == 0x7ff00000)
  9015. return m&1 ? -pi/2 : pi/2;
  9016. /* z = atan(|y/x|) without spurious underflow */
  9017. if ((m&2) && iy+(64<<20) < ix) /* |y/x| < 0x1p-64, x<0 */
  9018. z = 0;
  9019. else
  9020. z = dmath_atan(dmath_fabs(y/x));
  9021. switch (m) {
  9022. case 0: return z; /* atan(+,+) */
  9023. case 1: return -z; /* atan(-,+) */
  9024. case 2: return pi - (z-pi_lo); /* atan(+,-) */
  9025. default: /* case 3 */
  9026. return (z-pi_lo) - pi; /* atan(-,-) */
  9027. }
  9028. }
  9029. ////////////////////////////////////////////////////////////////////
  9030. int dmath_isinf(double x) {
  9031. union Float64Bits u = { .f = x };
  9032. return (u.i & -1ULL>>1) == 0x7ffULL<<52;
  9033. }
  9034. int dmath_isnan(double x) {
  9035. union Float64Bits u = { .f = x };
  9036. return (u.i & -1ULL>>1) > 0x7ffULL<<52;
  9037. }
  9038. int dmath_isnormal(double x) {
  9039. union Float64Bits u = { .f = x };
  9040. return ((u.i+(1ULL<<52)) & -1ULL>>1) >= 1ULL<<53;
  9041. }
  9042. int dmath_isfinite(double x) {
  9043. union Float64Bits u = { .f = x };
  9044. return (u.i & -1ULL>>1) < 0x7ffULL<<52;
  9045. }
  9046. // https://github.com/kraj/musl/blob/kraj/master/src/math/fmod.c
  9047. double dmath_fmod(double x, double y) {
  9048. if(y == 0) return DMATH_NAN;
  9049. union Float64Bits ux = { .f = x }, uy = { .f = y };
  9050. int ex = ux.i>>52 & 0x7ff;
  9051. int ey = uy.i>>52 & 0x7ff;
  9052. int sx = ux.i>>63;
  9053. uint64_t i;
  9054. /* in the followings uxi should be ux.i, but then gcc wrongly adds */
  9055. /* float load/store to inner loops ruining performance and code size */
  9056. uint64_t uxi = ux.i;
  9057. if (uy.i<<1 == 0 || dmath_isnan(y) || ex == 0x7ff)
  9058. return (x*y)/(x*y);
  9059. if (uxi<<1 <= uy.i<<1) {
  9060. if (uxi<<1 == uy.i<<1)
  9061. return 0*x;
  9062. return x;
  9063. }
  9064. /* normalize x and y */
  9065. if (!ex) {
  9066. for (i = uxi<<12; i>>63 == 0; ex--, i <<= 1);
  9067. uxi <<= -ex + 1;
  9068. } else {
  9069. uxi &= -1ULL >> 12;
  9070. uxi |= 1ULL << 52;
  9071. }
  9072. if (!ey) {
  9073. for (i = uy.i<<12; i>>63 == 0; ey--, i <<= 1);
  9074. uy.i <<= -ey + 1;
  9075. } else {
  9076. uy.i &= -1ULL >> 12;
  9077. uy.i |= 1ULL << 52;
  9078. }
  9079. /* x mod y */
  9080. for (; ex > ey; ex--) {
  9081. i = uxi - uy.i;
  9082. if (i >> 63 == 0) {
  9083. if (i == 0)
  9084. return 0*x;
  9085. uxi = i;
  9086. }
  9087. uxi <<= 1;
  9088. }
  9089. i = uxi - uy.i;
  9090. if (i >> 63 == 0) {
  9091. if (i == 0)
  9092. return 0*x;
  9093. uxi = i;
  9094. }
  9095. for (; uxi>>52 == 0; uxi <<= 1, ex--);
  9096. /* scale result */
  9097. if (ex > 0) {
  9098. uxi -= 1ULL << 52;
  9099. uxi |= (uint64_t)ex << 52;
  9100. } else {
  9101. uxi >>= -ex + 1;
  9102. }
  9103. uxi |= (uint64_t)sx << 63;
  9104. ux.i = uxi;
  9105. return ux.f;
  9106. }
  9107. // https://github.com/kraj/musl/blob/kraj/master/src/math/copysign.c
  9108. double dmath_copysign(double x, double y) {
  9109. union Float64Bits ux = { .f = x }, uy = { .f = y };
  9110. ux.i &= -1ULL/2;
  9111. ux.i |= uy.i & 1ULL<<63;
  9112. return ux.f;
  9113. }
  9114. // https://github.com/kraj/musl/blob/kraj/master/src/math/fabs.c
  9115. double dmath_fabs(double x) {
  9116. union Float64Bits u = { .f = x };
  9117. u.i &= -1ULL/2;
  9118. return u.f;
  9119. }
  9120. double dmath_ceil(double x) {
  9121. if(!dmath_isfinite(x)) return x;
  9122. int64_t int_part = (int64_t)x;
  9123. if (x > 0 && x != (double)int_part) {
  9124. return (double)(int_part + 1);
  9125. }
  9126. return (double)int_part;
  9127. }
  9128. double dmath_floor(double x) {
  9129. if(!dmath_isfinite(x)) return x;
  9130. int64_t int_part = (int64_t)x;
  9131. if (x < 0 && x != (double)int_part) {
  9132. return (double)(int_part - 1);
  9133. }
  9134. return (double)int_part;
  9135. }
  9136. double dmath_trunc(double x) {
  9137. return (double)((int64_t)x);
  9138. }
  9139. // https://github.com/kraj/musl/blob/kraj/master/src/math/modf.c
  9140. double dmath_modf(double x, double* iptr) {
  9141. union Float64Bits u = { .f = x };
  9142. uint64_t mask;
  9143. int e = (int)(u.i>>52 & 0x7ff) - 0x3ff;
  9144. /* no fractional part */
  9145. if (e >= 52) {
  9146. *iptr = x;
  9147. if (e == 0x400 && u.i<<12 != 0) /* nan */
  9148. return x;
  9149. u.i &= 1ULL<<63;
  9150. return u.f;
  9151. }
  9152. /* no integral part*/
  9153. if (e < 0) {
  9154. u.i &= 1ULL<<63;
  9155. *iptr = u.f;
  9156. return x;
  9157. }
  9158. mask = -1ULL>>12>>e;
  9159. if ((u.i & mask) == 0) {
  9160. *iptr = x;
  9161. u.i &= 1ULL<<63;
  9162. return u.f;
  9163. }
  9164. u.i &= ~mask;
  9165. *iptr = u.f;
  9166. return x - u.f;
  9167. }
  9168. double dmath_fmin(double x, double y) {
  9169. return (x < y) ? x : y;
  9170. }
  9171. double dmath_fmax(double x, double y) {
  9172. return (x > y) ? x : y;
  9173. }
  9174. // src/common\memorypool.c
  9175. #include <stdbool.h>
  9176. void FixedMemoryPool__ctor(FixedMemoryPool* self, int BlockSize, int BlockCount) {
  9177. self->BlockSize = BlockSize;
  9178. self->BlockCount = BlockCount;
  9179. self->exceeded_bytes = 0;
  9180. self->data = PK_MALLOC(BlockSize * BlockCount);
  9181. self->data_end = self->data + BlockSize * BlockCount;
  9182. self->_free_list = PK_MALLOC(sizeof(void*) * BlockCount);
  9183. self->_free_list_length = BlockCount;
  9184. for(int i = 0; i < BlockCount; i++) {
  9185. self->_free_list[i] = self->data + i * BlockSize;
  9186. }
  9187. }
  9188. void FixedMemoryPool__dtor(FixedMemoryPool* self) {
  9189. PK_FREE(self->_free_list);
  9190. PK_FREE(self->data);
  9191. }
  9192. void* FixedMemoryPool__alloc(FixedMemoryPool* self) {
  9193. if(self->_free_list_length > 0) {
  9194. self->_free_list_length--;
  9195. return self->_free_list[self->_free_list_length];
  9196. } else {
  9197. self->exceeded_bytes += self->BlockSize;
  9198. return PK_MALLOC(self->BlockSize);
  9199. }
  9200. }
  9201. void FixedMemoryPool__dealloc(FixedMemoryPool* self, void* p) {
  9202. bool is_valid = (char*)p >= self->data && (char*)p < self->data_end;
  9203. if(is_valid) {
  9204. self->_free_list[self->_free_list_length] = p;
  9205. self->_free_list_length++;
  9206. } else {
  9207. self->exceeded_bytes -= self->BlockSize;
  9208. PK_FREE(p);
  9209. }
  9210. }
  9211. // static int FixedMemoryPool__used_bytes(FixedMemoryPool* self) {
  9212. // return (self->_free_list_end - self->_free_list) * self->BlockSize;
  9213. // }
  9214. // static int FixedMemoryPool__total_bytes(FixedMemoryPool* self) {
  9215. // return self->BlockCount * self->BlockSize;
  9216. // }
  9217. // src/common\name.c
  9218. #if PK_ENABLE_CUSTOM_SNAME == 0
  9219. #include <assert.h>
  9220. typedef struct NameBucket NameBucket;
  9221. typedef struct NameBucket {
  9222. NameBucket* next;
  9223. uint64_t hash;
  9224. int size; // size of the data excluding the null-terminator
  9225. char data[]; // null-terminated data
  9226. } NameBucket;
  9227. static struct {
  9228. NameBucket* table[0x10000];
  9229. #if PK_ENABLE_THREADS
  9230. atomic_flag lock;
  9231. #endif
  9232. } pk_string_table;
  9233. #define MAGIC_METHOD(x) py_Name x;
  9234. #ifdef MAGIC_METHOD
  9235. // math operators
  9236. MAGIC_METHOD(__lt__)
  9237. MAGIC_METHOD(__le__)
  9238. MAGIC_METHOD(__gt__)
  9239. MAGIC_METHOD(__ge__)
  9240. /////////////////////////////
  9241. MAGIC_METHOD(__neg__)
  9242. MAGIC_METHOD(__abs__)
  9243. MAGIC_METHOD(__round__)
  9244. MAGIC_METHOD(__divmod__)
  9245. /////////////////////////////
  9246. MAGIC_METHOD(__add__)
  9247. MAGIC_METHOD(__radd__)
  9248. MAGIC_METHOD(__sub__)
  9249. MAGIC_METHOD(__rsub__)
  9250. MAGIC_METHOD(__mul__)
  9251. MAGIC_METHOD(__rmul__)
  9252. MAGIC_METHOD(__truediv__)
  9253. MAGIC_METHOD(__rtruediv__)
  9254. MAGIC_METHOD(__floordiv__)
  9255. MAGIC_METHOD(__rfloordiv__)
  9256. MAGIC_METHOD(__mod__)
  9257. MAGIC_METHOD(__rmod__)
  9258. MAGIC_METHOD(__pow__)
  9259. MAGIC_METHOD(__rpow__)
  9260. MAGIC_METHOD(__matmul__)
  9261. MAGIC_METHOD(__lshift__)
  9262. MAGIC_METHOD(__rshift__)
  9263. MAGIC_METHOD(__and__)
  9264. MAGIC_METHOD(__or__)
  9265. MAGIC_METHOD(__xor__)
  9266. /////////////////////////////
  9267. MAGIC_METHOD(__repr__)
  9268. MAGIC_METHOD(__str__)
  9269. MAGIC_METHOD(__hash__)
  9270. MAGIC_METHOD(__len__)
  9271. MAGIC_METHOD(__iter__)
  9272. MAGIC_METHOD(__next__)
  9273. MAGIC_METHOD(__contains__)
  9274. MAGIC_METHOD(__bool__)
  9275. MAGIC_METHOD(__invert__)
  9276. /////////////////////////////
  9277. MAGIC_METHOD(__eq__)
  9278. MAGIC_METHOD(__ne__)
  9279. // indexer
  9280. MAGIC_METHOD(__getitem__)
  9281. MAGIC_METHOD(__setitem__)
  9282. MAGIC_METHOD(__delitem__)
  9283. // specials
  9284. MAGIC_METHOD(__new__)
  9285. MAGIC_METHOD(__init__)
  9286. MAGIC_METHOD(__call__)
  9287. MAGIC_METHOD(__enter__)
  9288. MAGIC_METHOD(__exit__)
  9289. MAGIC_METHOD(__name__)
  9290. MAGIC_METHOD(__all__)
  9291. MAGIC_METHOD(__package__)
  9292. MAGIC_METHOD(__class__)
  9293. MAGIC_METHOD(__getattr__)
  9294. MAGIC_METHOD(__reduce__)
  9295. MAGIC_METHOD(__missing__)
  9296. #endif
  9297. #undef MAGIC_METHOD
  9298. void pk_names_initialize() {
  9299. #define MAGIC_METHOD(x) x = py_name(#x);
  9300. #ifdef MAGIC_METHOD
  9301. // math operators
  9302. MAGIC_METHOD(__lt__)
  9303. MAGIC_METHOD(__le__)
  9304. MAGIC_METHOD(__gt__)
  9305. MAGIC_METHOD(__ge__)
  9306. /////////////////////////////
  9307. MAGIC_METHOD(__neg__)
  9308. MAGIC_METHOD(__abs__)
  9309. MAGIC_METHOD(__round__)
  9310. MAGIC_METHOD(__divmod__)
  9311. /////////////////////////////
  9312. MAGIC_METHOD(__add__)
  9313. MAGIC_METHOD(__radd__)
  9314. MAGIC_METHOD(__sub__)
  9315. MAGIC_METHOD(__rsub__)
  9316. MAGIC_METHOD(__mul__)
  9317. MAGIC_METHOD(__rmul__)
  9318. MAGIC_METHOD(__truediv__)
  9319. MAGIC_METHOD(__rtruediv__)
  9320. MAGIC_METHOD(__floordiv__)
  9321. MAGIC_METHOD(__rfloordiv__)
  9322. MAGIC_METHOD(__mod__)
  9323. MAGIC_METHOD(__rmod__)
  9324. MAGIC_METHOD(__pow__)
  9325. MAGIC_METHOD(__rpow__)
  9326. MAGIC_METHOD(__matmul__)
  9327. MAGIC_METHOD(__lshift__)
  9328. MAGIC_METHOD(__rshift__)
  9329. MAGIC_METHOD(__and__)
  9330. MAGIC_METHOD(__or__)
  9331. MAGIC_METHOD(__xor__)
  9332. /////////////////////////////
  9333. MAGIC_METHOD(__repr__)
  9334. MAGIC_METHOD(__str__)
  9335. MAGIC_METHOD(__hash__)
  9336. MAGIC_METHOD(__len__)
  9337. MAGIC_METHOD(__iter__)
  9338. MAGIC_METHOD(__next__)
  9339. MAGIC_METHOD(__contains__)
  9340. MAGIC_METHOD(__bool__)
  9341. MAGIC_METHOD(__invert__)
  9342. /////////////////////////////
  9343. MAGIC_METHOD(__eq__)
  9344. MAGIC_METHOD(__ne__)
  9345. // indexer
  9346. MAGIC_METHOD(__getitem__)
  9347. MAGIC_METHOD(__setitem__)
  9348. MAGIC_METHOD(__delitem__)
  9349. // specials
  9350. MAGIC_METHOD(__new__)
  9351. MAGIC_METHOD(__init__)
  9352. MAGIC_METHOD(__call__)
  9353. MAGIC_METHOD(__enter__)
  9354. MAGIC_METHOD(__exit__)
  9355. MAGIC_METHOD(__name__)
  9356. MAGIC_METHOD(__all__)
  9357. MAGIC_METHOD(__package__)
  9358. MAGIC_METHOD(__class__)
  9359. MAGIC_METHOD(__getattr__)
  9360. MAGIC_METHOD(__reduce__)
  9361. MAGIC_METHOD(__missing__)
  9362. #endif
  9363. #undef MAGIC_METHOD
  9364. }
  9365. void pk_names_finalize() {
  9366. for(int i = 0; i < 0x10000; i++) {
  9367. NameBucket* p = pk_string_table.table[i];
  9368. while(p) {
  9369. NameBucket* next = p->next;
  9370. PK_FREE(p);
  9371. p = next;
  9372. }
  9373. pk_string_table.table[i] = NULL;
  9374. }
  9375. }
  9376. py_Name py_namev(c11_sv name) {
  9377. #if PK_ENABLE_THREADS
  9378. while(atomic_flag_test_and_set(&pk_string_table.lock)) {
  9379. c11_thrd__yield();
  9380. }
  9381. #endif
  9382. uint64_t hash = c11_sv__hash(name);
  9383. int index = hash & 0xFFFF;
  9384. NameBucket* p = pk_string_table.table[index];
  9385. NameBucket* prev = NULL;
  9386. bool found = false;
  9387. while(p) {
  9388. c11_sv p_sv = {p->data, p->size};
  9389. if(p->hash == hash && c11__sveq(p_sv, name)) {
  9390. found = true;
  9391. break;
  9392. }
  9393. prev = p;
  9394. p = p->next;
  9395. }
  9396. if(found) {
  9397. #if PK_ENABLE_THREADS
  9398. atomic_flag_clear(&pk_string_table.lock);
  9399. #endif
  9400. return (py_Name)p;
  9401. }
  9402. // generate new index
  9403. NameBucket* bucket = PK_MALLOC(sizeof(NameBucket) + name.size + 1);
  9404. bucket->next = NULL;
  9405. bucket->hash = hash;
  9406. bucket->size = name.size;
  9407. memcpy(bucket->data, name.data, name.size);
  9408. bucket->data[name.size] = '\0';
  9409. if(prev == NULL) {
  9410. pk_string_table.table[index] = bucket;
  9411. } else {
  9412. assert(prev->next == NULL);
  9413. prev->next = bucket;
  9414. }
  9415. #if PK_ENABLE_THREADS
  9416. atomic_flag_clear(&pk_string_table.lock);
  9417. #endif
  9418. return (py_Name)bucket;
  9419. }
  9420. c11_sv py_name2sv(py_Name index) {
  9421. NameBucket* p = (NameBucket*)index;
  9422. return (c11_sv){p->data, p->size};
  9423. }
  9424. py_Name py_name(const char* name) {
  9425. c11_sv sv;
  9426. sv.data = name;
  9427. sv.size = strlen(name);
  9428. return py_namev(sv);
  9429. }
  9430. const char* py_name2str(py_Name index) {
  9431. NameBucket* p = (NameBucket*)index;
  9432. return p->data;
  9433. }
  9434. #endif
  9435. // src/common\serialize.c
  9436. // >>> ord('🥕')
  9437. // 129365
  9438. // >>> ord('🍋')
  9439. // 127819
  9440. static uint32_t c11__checksum_32bit(const void* data, int size){
  9441. const uint8_t* p = (const uint8_t*)data;
  9442. uint32_t res = 0;
  9443. for(int i = 0; i < size; i++){
  9444. res = res * 31 + p[i];
  9445. }
  9446. return res;
  9447. }
  9448. void c11_serializer__ctor(c11_serializer* self, int16_t magic, int8_t major_ver, int8_t minor_ver){
  9449. c11_vector__ctor(&self->data, 1);
  9450. c11_serializer__write_i16(self, magic);
  9451. c11_serializer__write_i8(self, major_ver);
  9452. c11_serializer__write_i8(self, minor_ver);
  9453. }
  9454. void c11_serializer__dtor(c11_serializer* self){
  9455. c11_vector__dtor(&self->data);
  9456. }
  9457. void c11_serializer__write_mark(c11_serializer *self, char mark) {
  9458. c11_serializer__write_i8(self, (int8_t)mark);
  9459. }
  9460. void c11_serializer__write_cstr(c11_serializer *self, const char* cstr) {
  9461. int len = (int)strlen(cstr);
  9462. c11_serializer__write_bytes(self, cstr, len + 1);
  9463. }
  9464. void c11_serializer__write_bytes(c11_serializer* self, const void* data, int size){
  9465. c11_vector__extend(&self->data, data, size);
  9466. }
  9467. void* c11_serializer__submit(c11_serializer* self, int* size){
  9468. uint32_t checksum = c11__checksum_32bit(self->data.data, self->data.length);
  9469. c11_serializer__write_bytes(self, &checksum, sizeof(uint32_t));
  9470. return c11_vector__submit(&self->data, size);
  9471. }
  9472. void c11_deserializer__ctor(c11_deserializer* self, const void* data, int size){
  9473. self->data = (const uint8_t*)data;
  9474. self->size = size;
  9475. self->index = 0;
  9476. self->error_msg[0] = '\0';
  9477. }
  9478. void c11_deserializer__dtor(c11_deserializer* self){
  9479. // nothing to do
  9480. }
  9481. bool c11_deserializer__error(c11_deserializer* self, const char* msg){
  9482. snprintf(self->error_msg, sizeof(self->error_msg), "%s", msg);
  9483. return false;
  9484. }
  9485. void c11_deserializer__consume_mark(c11_deserializer* self, char expected) {
  9486. int8_t mark = c11_deserializer__read_i8(self);
  9487. if (mark != (int8_t)expected) {
  9488. c11__abort("internal error: deserialize mark mismatch: expected %c but got %c", expected, (char)mark);
  9489. }
  9490. }
  9491. bool c11_deserializer__check_header(c11_deserializer* self, int16_t magic, int8_t major_ver, int8_t minor_ver_min){
  9492. if(self->size < 8){
  9493. return c11_deserializer__error(self, "bad header: size < 8");
  9494. }
  9495. // read 16bit magic
  9496. int16_t file_magic = c11_deserializer__read_i16(self);
  9497. if(file_magic != magic){
  9498. return c11_deserializer__error(self, "bad header: magic mismatch");
  9499. }
  9500. // read 16bit version
  9501. self->major_ver = c11_deserializer__read_i8(self);
  9502. self->minor_ver = c11_deserializer__read_i8(self);
  9503. // check checksum
  9504. uint32_t checksum;
  9505. memcpy(&checksum, self->data + self->size - 4, sizeof(uint32_t));
  9506. uint32_t actual_checksum = c11__checksum_32bit(self->data, self->size - 4);
  9507. if(checksum != actual_checksum){
  9508. return c11_deserializer__error(self, "bad header: checksum mismatch");
  9509. }
  9510. // check version
  9511. if(self->major_ver != major_ver){
  9512. return c11_deserializer__error(self, "bad header: major version mismatch");
  9513. }
  9514. if(self->minor_ver < minor_ver_min){
  9515. // file_ver: 1.1, require_ver: 1.0 => ok
  9516. // file_ver: 1.1, require_ver: 1.1 => ok
  9517. // file_ver: 1.1, require_ver: 1.2 => error
  9518. return c11_deserializer__error(self, "bad header: minor version mismatch");
  9519. }
  9520. return true;
  9521. }
  9522. const char* c11_deserializer__read_cstr(c11_deserializer* self){
  9523. const char* p = (const char*)(self->data + self->index);
  9524. self->index += (strlen(p) + 1);
  9525. return p;
  9526. }
  9527. void* c11_deserializer__read_bytes(c11_deserializer* self, int size){
  9528. void* p = (void*)(self->data + self->index);
  9529. self->index += size;
  9530. return p;
  9531. }
  9532. // src/common\smallmap.c
  9533. #define SMALLMAP_T__SOURCE
  9534. #define K py_Name
  9535. #define V int
  9536. #define NAME c11_smallmap_n2d
  9537. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  9538. #include "pocketpy/common/vector.h"
  9539. #include "pocketpy/common/utils.h"
  9540. #include "pocketpy/config.h"
  9541. #define SMALLMAP_T__HEADER
  9542. #define SMALLMAP_T__SOURCE
  9543. /* Input */
  9544. #define K int
  9545. #define V float
  9546. #define NAME c11_smallmap_d2f
  9547. #endif
  9548. /* Optional Input */
  9549. #ifndef less
  9550. #define less(a, b) ((a) < (b))
  9551. #endif
  9552. #ifndef equal
  9553. #define equal(a, b) ((a) == (b))
  9554. #endif
  9555. /* Temporary macros */
  9556. #define partial_less(a, b) less((a).key, (b))
  9557. #define CONCAT(A, B) CONCAT_(A, B)
  9558. #define CONCAT_(A, B) A##B
  9559. #define KV CONCAT(NAME, _KV)
  9560. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  9561. #ifdef SMALLMAP_T__HEADER
  9562. /* Declaration */
  9563. typedef struct {
  9564. K key;
  9565. V value;
  9566. } KV;
  9567. typedef c11_vector NAME;
  9568. void METHOD(ctor)(NAME* self);
  9569. void METHOD(dtor)(NAME* self);
  9570. NAME* METHOD(new)();
  9571. void METHOD(delete)(NAME* self);
  9572. void METHOD(set)(NAME* self, K key, V value);
  9573. V* METHOD(try_get)(const NAME* self, K key);
  9574. V METHOD(get)(const NAME* self, K key, V default_value);
  9575. bool METHOD(contains)(const NAME* self, K key);
  9576. bool METHOD(del)(NAME* self, K key);
  9577. void METHOD(clear)(NAME* self);
  9578. #endif
  9579. #ifdef SMALLMAP_T__SOURCE
  9580. /* Implementation */
  9581. void METHOD(ctor)(NAME* self) {
  9582. c11_vector__ctor(self, sizeof(KV));
  9583. c11_vector__reserve(self, 4);
  9584. }
  9585. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  9586. NAME* METHOD(new)() {
  9587. NAME* self = PK_MALLOC(sizeof(NAME));
  9588. METHOD(ctor)(self);
  9589. return self;
  9590. }
  9591. void METHOD(delete)(NAME* self) {
  9592. METHOD(dtor)(self);
  9593. PK_FREE(self);
  9594. }
  9595. void METHOD(set)(NAME* self, K key, V value) {
  9596. int index;
  9597. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9598. if(index != self->length) {
  9599. KV* it = c11__at(KV, self, index);
  9600. if(equal(it->key, key)) {
  9601. it->value = value;
  9602. return;
  9603. }
  9604. }
  9605. KV kv = {key, value};
  9606. c11_vector__insert(KV, self, index, kv);
  9607. }
  9608. V* METHOD(try_get)(const NAME* self, K key) {
  9609. int index;
  9610. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9611. if(index != self->length) {
  9612. KV* it = c11__at(KV, self, index);
  9613. if(equal(it->key, key)) return &it->value;
  9614. }
  9615. return NULL;
  9616. }
  9617. V METHOD(get)(const NAME* self, K key, V default_value) {
  9618. V* p = METHOD(try_get)(self, key);
  9619. return p ? *p : default_value;
  9620. }
  9621. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  9622. bool METHOD(del)(NAME* self, K key) {
  9623. int index;
  9624. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9625. if(index != self->length) {
  9626. KV* it = c11__at(KV, self, index);
  9627. if(equal(it->key, key)) {
  9628. c11_vector__erase(KV, self, index);
  9629. return true;
  9630. }
  9631. }
  9632. return false;
  9633. }
  9634. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  9635. #endif
  9636. /* Undefine all macros */
  9637. #undef KV
  9638. #undef METHOD
  9639. #undef CONCAT
  9640. #undef CONCAT_
  9641. #undef K
  9642. #undef V
  9643. #undef NAME
  9644. #undef less
  9645. #undef partial_less
  9646. #undef equal
  9647. #undef SMALLMAP_T__SOURCE
  9648. #define SMALLMAP_T__SOURCE
  9649. #define K int
  9650. #define V int
  9651. #define NAME c11_smallmap_d2d
  9652. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  9653. #include "pocketpy/common/vector.h"
  9654. #include "pocketpy/common/utils.h"
  9655. #include "pocketpy/config.h"
  9656. #define SMALLMAP_T__HEADER
  9657. #define SMALLMAP_T__SOURCE
  9658. /* Input */
  9659. #define K int
  9660. #define V float
  9661. #define NAME c11_smallmap_d2f
  9662. #endif
  9663. /* Optional Input */
  9664. #ifndef less
  9665. #define less(a, b) ((a) < (b))
  9666. #endif
  9667. #ifndef equal
  9668. #define equal(a, b) ((a) == (b))
  9669. #endif
  9670. /* Temporary macros */
  9671. #define partial_less(a, b) less((a).key, (b))
  9672. #define CONCAT(A, B) CONCAT_(A, B)
  9673. #define CONCAT_(A, B) A##B
  9674. #define KV CONCAT(NAME, _KV)
  9675. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  9676. #ifdef SMALLMAP_T__HEADER
  9677. /* Declaration */
  9678. typedef struct {
  9679. K key;
  9680. V value;
  9681. } KV;
  9682. typedef c11_vector NAME;
  9683. void METHOD(ctor)(NAME* self);
  9684. void METHOD(dtor)(NAME* self);
  9685. NAME* METHOD(new)();
  9686. void METHOD(delete)(NAME* self);
  9687. void METHOD(set)(NAME* self, K key, V value);
  9688. V* METHOD(try_get)(const NAME* self, K key);
  9689. V METHOD(get)(const NAME* self, K key, V default_value);
  9690. bool METHOD(contains)(const NAME* self, K key);
  9691. bool METHOD(del)(NAME* self, K key);
  9692. void METHOD(clear)(NAME* self);
  9693. #endif
  9694. #ifdef SMALLMAP_T__SOURCE
  9695. /* Implementation */
  9696. void METHOD(ctor)(NAME* self) {
  9697. c11_vector__ctor(self, sizeof(KV));
  9698. c11_vector__reserve(self, 4);
  9699. }
  9700. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  9701. NAME* METHOD(new)() {
  9702. NAME* self = PK_MALLOC(sizeof(NAME));
  9703. METHOD(ctor)(self);
  9704. return self;
  9705. }
  9706. void METHOD(delete)(NAME* self) {
  9707. METHOD(dtor)(self);
  9708. PK_FREE(self);
  9709. }
  9710. void METHOD(set)(NAME* self, K key, V value) {
  9711. int index;
  9712. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9713. if(index != self->length) {
  9714. KV* it = c11__at(KV, self, index);
  9715. if(equal(it->key, key)) {
  9716. it->value = value;
  9717. return;
  9718. }
  9719. }
  9720. KV kv = {key, value};
  9721. c11_vector__insert(KV, self, index, kv);
  9722. }
  9723. V* METHOD(try_get)(const NAME* self, K key) {
  9724. int index;
  9725. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9726. if(index != self->length) {
  9727. KV* it = c11__at(KV, self, index);
  9728. if(equal(it->key, key)) return &it->value;
  9729. }
  9730. return NULL;
  9731. }
  9732. V METHOD(get)(const NAME* self, K key, V default_value) {
  9733. V* p = METHOD(try_get)(self, key);
  9734. return p ? *p : default_value;
  9735. }
  9736. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  9737. bool METHOD(del)(NAME* self, K key) {
  9738. int index;
  9739. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9740. if(index != self->length) {
  9741. KV* it = c11__at(KV, self, index);
  9742. if(equal(it->key, key)) {
  9743. c11_vector__erase(KV, self, index);
  9744. return true;
  9745. }
  9746. }
  9747. return false;
  9748. }
  9749. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  9750. #endif
  9751. /* Undefine all macros */
  9752. #undef KV
  9753. #undef METHOD
  9754. #undef CONCAT
  9755. #undef CONCAT_
  9756. #undef K
  9757. #undef V
  9758. #undef NAME
  9759. #undef less
  9760. #undef partial_less
  9761. #undef equal
  9762. #undef SMALLMAP_T__SOURCE
  9763. #define SMALLMAP_T__SOURCE
  9764. #define K c11_sv
  9765. #define V int
  9766. #define NAME c11_smallmap_v2d
  9767. #define less(a, b) (c11_sv__cmp((a), (b)) < 0)
  9768. #define equal(a, b) (c11_sv__cmp((a), (b)) == 0)
  9769. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  9770. #include "pocketpy/common/vector.h"
  9771. #include "pocketpy/common/utils.h"
  9772. #include "pocketpy/config.h"
  9773. #define SMALLMAP_T__HEADER
  9774. #define SMALLMAP_T__SOURCE
  9775. /* Input */
  9776. #define K int
  9777. #define V float
  9778. #define NAME c11_smallmap_d2f
  9779. #endif
  9780. /* Optional Input */
  9781. #ifndef less
  9782. #define less(a, b) ((a) < (b))
  9783. #endif
  9784. #ifndef equal
  9785. #define equal(a, b) ((a) == (b))
  9786. #endif
  9787. /* Temporary macros */
  9788. #define partial_less(a, b) less((a).key, (b))
  9789. #define CONCAT(A, B) CONCAT_(A, B)
  9790. #define CONCAT_(A, B) A##B
  9791. #define KV CONCAT(NAME, _KV)
  9792. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  9793. #ifdef SMALLMAP_T__HEADER
  9794. /* Declaration */
  9795. typedef struct {
  9796. K key;
  9797. V value;
  9798. } KV;
  9799. typedef c11_vector NAME;
  9800. void METHOD(ctor)(NAME* self);
  9801. void METHOD(dtor)(NAME* self);
  9802. NAME* METHOD(new)();
  9803. void METHOD(delete)(NAME* self);
  9804. void METHOD(set)(NAME* self, K key, V value);
  9805. V* METHOD(try_get)(const NAME* self, K key);
  9806. V METHOD(get)(const NAME* self, K key, V default_value);
  9807. bool METHOD(contains)(const NAME* self, K key);
  9808. bool METHOD(del)(NAME* self, K key);
  9809. void METHOD(clear)(NAME* self);
  9810. #endif
  9811. #ifdef SMALLMAP_T__SOURCE
  9812. /* Implementation */
  9813. void METHOD(ctor)(NAME* self) {
  9814. c11_vector__ctor(self, sizeof(KV));
  9815. c11_vector__reserve(self, 4);
  9816. }
  9817. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  9818. NAME* METHOD(new)() {
  9819. NAME* self = PK_MALLOC(sizeof(NAME));
  9820. METHOD(ctor)(self);
  9821. return self;
  9822. }
  9823. void METHOD(delete)(NAME* self) {
  9824. METHOD(dtor)(self);
  9825. PK_FREE(self);
  9826. }
  9827. void METHOD(set)(NAME* self, K key, V value) {
  9828. int index;
  9829. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9830. if(index != self->length) {
  9831. KV* it = c11__at(KV, self, index);
  9832. if(equal(it->key, key)) {
  9833. it->value = value;
  9834. return;
  9835. }
  9836. }
  9837. KV kv = {key, value};
  9838. c11_vector__insert(KV, self, index, kv);
  9839. }
  9840. V* METHOD(try_get)(const NAME* self, K key) {
  9841. int index;
  9842. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9843. if(index != self->length) {
  9844. KV* it = c11__at(KV, self, index);
  9845. if(equal(it->key, key)) return &it->value;
  9846. }
  9847. return NULL;
  9848. }
  9849. V METHOD(get)(const NAME* self, K key, V default_value) {
  9850. V* p = METHOD(try_get)(self, key);
  9851. return p ? *p : default_value;
  9852. }
  9853. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  9854. bool METHOD(del)(NAME* self, K key) {
  9855. int index;
  9856. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9857. if(index != self->length) {
  9858. KV* it = c11__at(KV, self, index);
  9859. if(equal(it->key, key)) {
  9860. c11_vector__erase(KV, self, index);
  9861. return true;
  9862. }
  9863. }
  9864. return false;
  9865. }
  9866. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  9867. #endif
  9868. /* Undefine all macros */
  9869. #undef KV
  9870. #undef METHOD
  9871. #undef CONCAT
  9872. #undef CONCAT_
  9873. #undef K
  9874. #undef V
  9875. #undef NAME
  9876. #undef less
  9877. #undef partial_less
  9878. #undef equal
  9879. #undef SMALLMAP_T__SOURCE
  9880. #define SMALLMAP_T__SOURCE
  9881. #define K void*
  9882. #define V py_i64
  9883. #define NAME c11_smallmap_p2i
  9884. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  9885. #include "pocketpy/common/vector.h"
  9886. #include "pocketpy/common/utils.h"
  9887. #include "pocketpy/config.h"
  9888. #define SMALLMAP_T__HEADER
  9889. #define SMALLMAP_T__SOURCE
  9890. /* Input */
  9891. #define K int
  9892. #define V float
  9893. #define NAME c11_smallmap_d2f
  9894. #endif
  9895. /* Optional Input */
  9896. #ifndef less
  9897. #define less(a, b) ((a) < (b))
  9898. #endif
  9899. #ifndef equal
  9900. #define equal(a, b) ((a) == (b))
  9901. #endif
  9902. /* Temporary macros */
  9903. #define partial_less(a, b) less((a).key, (b))
  9904. #define CONCAT(A, B) CONCAT_(A, B)
  9905. #define CONCAT_(A, B) A##B
  9906. #define KV CONCAT(NAME, _KV)
  9907. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  9908. #ifdef SMALLMAP_T__HEADER
  9909. /* Declaration */
  9910. typedef struct {
  9911. K key;
  9912. V value;
  9913. } KV;
  9914. typedef c11_vector NAME;
  9915. void METHOD(ctor)(NAME* self);
  9916. void METHOD(dtor)(NAME* self);
  9917. NAME* METHOD(new)();
  9918. void METHOD(delete)(NAME* self);
  9919. void METHOD(set)(NAME* self, K key, V value);
  9920. V* METHOD(try_get)(const NAME* self, K key);
  9921. V METHOD(get)(const NAME* self, K key, V default_value);
  9922. bool METHOD(contains)(const NAME* self, K key);
  9923. bool METHOD(del)(NAME* self, K key);
  9924. void METHOD(clear)(NAME* self);
  9925. #endif
  9926. #ifdef SMALLMAP_T__SOURCE
  9927. /* Implementation */
  9928. void METHOD(ctor)(NAME* self) {
  9929. c11_vector__ctor(self, sizeof(KV));
  9930. c11_vector__reserve(self, 4);
  9931. }
  9932. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  9933. NAME* METHOD(new)() {
  9934. NAME* self = PK_MALLOC(sizeof(NAME));
  9935. METHOD(ctor)(self);
  9936. return self;
  9937. }
  9938. void METHOD(delete)(NAME* self) {
  9939. METHOD(dtor)(self);
  9940. PK_FREE(self);
  9941. }
  9942. void METHOD(set)(NAME* self, K key, V value) {
  9943. int index;
  9944. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9945. if(index != self->length) {
  9946. KV* it = c11__at(KV, self, index);
  9947. if(equal(it->key, key)) {
  9948. it->value = value;
  9949. return;
  9950. }
  9951. }
  9952. KV kv = {key, value};
  9953. c11_vector__insert(KV, self, index, kv);
  9954. }
  9955. V* METHOD(try_get)(const NAME* self, K key) {
  9956. int index;
  9957. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9958. if(index != self->length) {
  9959. KV* it = c11__at(KV, self, index);
  9960. if(equal(it->key, key)) return &it->value;
  9961. }
  9962. return NULL;
  9963. }
  9964. V METHOD(get)(const NAME* self, K key, V default_value) {
  9965. V* p = METHOD(try_get)(self, key);
  9966. return p ? *p : default_value;
  9967. }
  9968. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  9969. bool METHOD(del)(NAME* self, K key) {
  9970. int index;
  9971. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  9972. if(index != self->length) {
  9973. KV* it = c11__at(KV, self, index);
  9974. if(equal(it->key, key)) {
  9975. c11_vector__erase(KV, self, index);
  9976. return true;
  9977. }
  9978. }
  9979. return false;
  9980. }
  9981. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  9982. #endif
  9983. /* Undefine all macros */
  9984. #undef KV
  9985. #undef METHOD
  9986. #undef CONCAT
  9987. #undef CONCAT_
  9988. #undef K
  9989. #undef V
  9990. #undef NAME
  9991. #undef less
  9992. #undef partial_less
  9993. #undef equal
  9994. #undef SMALLMAP_T__SOURCE
  9995. // src/common\socket.c
  9996. #if PK_ENABLE_OS
  9997. #include <stddef.h>
  9998. #if defined (_WIN32) || defined (_WIN64)
  9999. #include <WinSock2.h>
  10000. #include <ws2tcpip.h>
  10001. typedef SOCKET socket_fd;
  10002. #else
  10003. #include <sys/types.h>
  10004. #include <sys/socket.h>
  10005. #include <netinet/in.h>
  10006. #include <arpa/inet.h>
  10007. #include <fcntl.h>
  10008. #include <unistd.h>
  10009. #include <errno.h>
  10010. typedef int socket_fd;
  10011. #endif
  10012. #define SOCKET_HANDLERTOFD(handler) (socket_fd)(uintptr_t)(handler)
  10013. #define SOCKET_FDTOHANDLER(fd) (c11_socket_handler)(uintptr_t)(fd)
  10014. static int c11_socket_init(){
  10015. #if defined (_WIN32) || defined (_WIN64)
  10016. WORD sockVersion = MAKEWORD(2,2);
  10017. WSADATA wsaData;
  10018. return WSAStartup(sockVersion, &wsaData);
  10019. #endif
  10020. return 0;
  10021. }
  10022. c11_socket_handler c11_socket_create(int family, int type, int protocol){
  10023. static int is_initialized = 0;
  10024. if(is_initialized == 0)
  10025. {
  10026. c11_socket_init();
  10027. is_initialized = 1;
  10028. }
  10029. return SOCKET_FDTOHANDLER(socket(family, type, protocol));
  10030. }
  10031. int c11_socket_bind(c11_socket_handler socket, const char* hostname, unsigned short port){
  10032. struct sockaddr_in bind_addr;
  10033. bind_addr.sin_family = AF_INET;
  10034. bind_addr.sin_port = htons(port);
  10035. inet_pton(AF_INET,hostname,&bind_addr.sin_addr);
  10036. if(bind(SOCKET_HANDLERTOFD(socket), (const struct sockaddr*)&bind_addr, sizeof(bind_addr)) == -1){
  10037. return -1;
  10038. }
  10039. return 0;
  10040. }
  10041. int c11_socket_listen(c11_socket_handler socket, int backlog){
  10042. listen(SOCKET_HANDLERTOFD(socket), backlog);
  10043. return 0;
  10044. }
  10045. c11_socket_handler c11_socket_accept(c11_socket_handler socket, char* client_ip, unsigned short* client_port){
  10046. struct sockaddr_in client_addr;
  10047. socklen_t sockaddr_len = sizeof(client_addr);
  10048. socket_fd client_socket = accept(SOCKET_HANDLERTOFD(socket), (struct sockaddr*)&client_addr, &sockaddr_len);
  10049. if(client_ip != NULL){
  10050. inet_ntop(AF_INET, &client_addr.sin_addr,client_ip,sizeof("255.255.255.255"));
  10051. }
  10052. if(client_port != NULL){
  10053. *client_port = ntohs(client_addr.sin_port);
  10054. }
  10055. return SOCKET_FDTOHANDLER(client_socket);
  10056. }
  10057. int c11_socket_connect(c11_socket_handler socket, const char* server_ip, unsigned short server_port){
  10058. struct sockaddr_in server_addr;
  10059. server_addr.sin_family = AF_INET;
  10060. server_addr.sin_port = htons(server_port);
  10061. inet_pton(AF_INET, server_ip, &server_addr.sin_addr);
  10062. if(connect(SOCKET_HANDLERTOFD(socket), (const struct sockaddr*)&server_addr, sizeof(server_addr)) == -1){
  10063. return -1;
  10064. }
  10065. return 0;
  10066. }
  10067. int c11_socket_recv(c11_socket_handler socket, char* buffer, int maxsize){
  10068. return recv(SOCKET_HANDLERTOFD(socket), buffer, maxsize,0);
  10069. }
  10070. int c11_socket_send(c11_socket_handler socket, const char* senddata, int datalen){
  10071. return send(SOCKET_HANDLERTOFD(socket), senddata, datalen, 0);
  10072. }
  10073. int c11_socket_close(c11_socket_handler socket){
  10074. #if defined (_WIN32) || defined (_WIN64)
  10075. return closesocket(SOCKET_HANDLERTOFD(socket));
  10076. #else
  10077. return close(SOCKET_HANDLERTOFD(socket));
  10078. #endif
  10079. }
  10080. int c11_socket_set_block(c11_socket_handler socket,int flag){
  10081. #if defined (_WIN32) || defined (_WIN64)
  10082. u_long mode = flag == 1 ? 0 : 1;
  10083. return ioctlsocket(SOCKET_HANDLERTOFD(socket), FIONBIO, &mode);
  10084. #else
  10085. int flags = fcntl(SOCKET_HANDLERTOFD(socket), F_GETFL, 0);
  10086. return fcntl(SOCKET_HANDLERTOFD(socket), F_SETFL, flags | O_NONBLOCK);
  10087. #endif
  10088. }
  10089. c11_socket_handler c11_socket_invalid_socket_handler(){
  10090. return (void*)(uintptr_t)(-1);
  10091. }
  10092. int c11_socket_get_last_error(){
  10093. #if defined (_WIN32) || defined (_WIN64)
  10094. return WSAGetLastError();
  10095. #else
  10096. return errno;
  10097. #endif
  10098. }
  10099. #undef SOCKET_HANDLERTOFD
  10100. #undef SOCKET_FDTOHANDLER
  10101. #endif // PK_ENABLE_OS
  10102. // src/common\sourcedata.c
  10103. #include <ctype.h>
  10104. #include <string.h>
  10105. static void SourceData__ctor(struct SourceData* self,
  10106. const char* source,
  10107. const char* filename,
  10108. enum py_CompileMode mode,
  10109. bool is_dynamic) {
  10110. self->mode = mode;
  10111. self->is_dynamic = is_dynamic;
  10112. self->filename = c11_string__new(filename);
  10113. c11_vector__ctor(&self->line_starts, sizeof(const char*));
  10114. if(!source) {
  10115. self->source = NULL;
  10116. return;
  10117. }
  10118. // Skip utf8 BOM if there is any.
  10119. if(strncmp(source, "\xEF\xBB\xBF", 3) == 0) source += 3;
  10120. // Drop all '\r'
  10121. c11_sbuf ss;
  10122. c11_sbuf__ctor(&ss);
  10123. while(true) {
  10124. char c = *source;
  10125. if(c == '\0') break;
  10126. if(c != '\r') c11_sbuf__write_char(&ss, c);
  10127. source++;
  10128. }
  10129. self->source = c11_sbuf__submit(&ss);
  10130. // remove trailing newline
  10131. int last_index = self->source->size - 1;
  10132. while(last_index >= 0 && isspace((unsigned char)self->source->data[last_index])) {
  10133. last_index--;
  10134. }
  10135. if(last_index >= 0) {
  10136. self->source->size = last_index + 1;
  10137. self->source->data[last_index + 1] = '\0';
  10138. }
  10139. c11_vector__push(const char*, &self->line_starts, self->source->data);
  10140. }
  10141. static void SourceData__dtor(void* p) {
  10142. struct SourceData* self = p;
  10143. c11_string__delete(self->filename);
  10144. if(self->source) c11_string__delete(self->source);
  10145. c11_vector__dtor(&self->line_starts);
  10146. }
  10147. SourceData_ SourceData__rcnew(const char* source,
  10148. const char* filename,
  10149. enum py_CompileMode mode,
  10150. bool is_dynamic) {
  10151. SourceData_ self = PK_MALLOC(sizeof(struct SourceData));
  10152. SourceData__ctor(self, source, filename, mode, is_dynamic);
  10153. self->rc.count = 1;
  10154. self->rc.dtor = SourceData__dtor;
  10155. return self;
  10156. }
  10157. bool SourceData__get_line(const struct SourceData* self,
  10158. int lineno,
  10159. const char** st,
  10160. const char** ed) {
  10161. if(lineno < 0 || !self->source) return false;
  10162. lineno -= 1;
  10163. if(lineno < 0) lineno = 0;
  10164. const char* _start = c11__getitem(const char*, &self->line_starts, lineno);
  10165. const char* i = _start;
  10166. // max 300 chars
  10167. while(*i != '\n' && *i != '\0' && i - _start < 300)
  10168. i++;
  10169. *st = _start;
  10170. *ed = i;
  10171. return true;
  10172. }
  10173. void SourceData__snapshot(const struct SourceData* self,
  10174. c11_sbuf* ss,
  10175. int lineno,
  10176. const char* cursor,
  10177. const char* name) {
  10178. pk_sprintf(ss, " File \"%s\", line %d", self->filename->data, lineno);
  10179. if(name && *name) {
  10180. c11_sbuf__write_cstr(ss, ", in ");
  10181. c11_sbuf__write_cstr(ss, name);
  10182. }
  10183. const char *st = NULL, *ed;
  10184. if(SourceData__get_line(self, lineno, &st, &ed)) {
  10185. c11_sbuf__write_char(ss, '\n');
  10186. while(st < ed && isblank(*st))
  10187. ++st;
  10188. if(st < ed) {
  10189. c11_sbuf__write_cstr(ss, " ");
  10190. c11_sbuf__write_cstrn(ss, st, ed - st);
  10191. if(cursor && st <= cursor && cursor <= ed) {
  10192. c11_sbuf__write_cstr(ss, "\n ");
  10193. for(int i = 0; i < (cursor - st); ++i)
  10194. c11_sbuf__write_char(ss, ' ');
  10195. c11_sbuf__write_cstr(ss, "^");
  10196. }
  10197. } else {
  10198. st = NULL;
  10199. }
  10200. }
  10201. // if(!st) { c11_sbuf__write_cstr(ss, " <?>"); }
  10202. }
  10203. // src/common\sstream.c
  10204. #include <stdarg.h>
  10205. #include <assert.h>
  10206. #include <stdio.h>
  10207. #include <stdlib.h>
  10208. #include <ctype.h>
  10209. void c11_sbuf__ctor(c11_sbuf* self) {
  10210. c11_vector__ctor(&self->data, sizeof(char));
  10211. c11_vector__reserve(&self->data, sizeof(c11_string) + 64);
  10212. self->data.length = sizeof(c11_string);
  10213. }
  10214. void c11_sbuf__dtor(c11_sbuf* self) { c11_vector__dtor(&self->data); }
  10215. void c11_sbuf__write_char(c11_sbuf* self, char c) { c11_vector__push(char, &self->data, c); }
  10216. void c11_sbuf__write_pad(c11_sbuf* self, int count, char pad) {
  10217. for(int i = 0; i < count; i++) {
  10218. c11_sbuf__write_char(self, pad);
  10219. }
  10220. }
  10221. void c11_sbuf__write_int(c11_sbuf* self, int i) {
  10222. // len('-2147483648') == 11
  10223. c11_vector__reserve(&self->data, self->data.length + 11 + 1);
  10224. char* p = (char*)self->data.data + self->data.length;
  10225. int n = snprintf(p, 11 + 1, "%d", i);
  10226. self->data.length += n;
  10227. }
  10228. void c11_sbuf__write_i64(c11_sbuf* self, int64_t val) {
  10229. // len('-9223372036854775808') == 20
  10230. c11_vector__reserve(&self->data, self->data.length + 20 + 1);
  10231. char* p = (char*)self->data.data + self->data.length;
  10232. int n = snprintf(p, 20 + 1, "%lld", (long long)val);
  10233. self->data.length += n;
  10234. }
  10235. void c11_sbuf__write_f64(c11_sbuf* self, double val, int precision) {
  10236. if(dmath_isinf(val)) {
  10237. c11_sbuf__write_cstr(self, val > 0 ? "inf" : "-inf");
  10238. return;
  10239. }
  10240. if(dmath_isnan(val)) {
  10241. c11_sbuf__write_cstr(self, "nan");
  10242. return;
  10243. }
  10244. char b[32];
  10245. int size;
  10246. if(precision < 0) {
  10247. for(int g = 15; g <= 17; g++) {
  10248. size = snprintf(b, sizeof(b), "%.*g", g, val);
  10249. if(strtod(b, NULL) == val) break;
  10250. }
  10251. c11_sbuf__write_cstr(self, b);
  10252. bool all_is_digit = true;
  10253. for(int i = 1; i < size; i++) {
  10254. if(!isdigit(b[i])) {
  10255. all_is_digit = false;
  10256. break;
  10257. }
  10258. }
  10259. if(all_is_digit) c11_sbuf__write_cstr(self, ".0");
  10260. } else {
  10261. size = snprintf(b, sizeof(b), "%.*f", precision, val);
  10262. c11_sbuf__write_cstr(self, b);
  10263. }
  10264. }
  10265. void c11_sbuf__write_sv(c11_sbuf* self, c11_sv sv) {
  10266. c11_sbuf__write_cstrn(self, sv.data, sv.size);
  10267. }
  10268. void c11_sbuf__write_cstr(c11_sbuf* self, const char* str) {
  10269. c11_sbuf__write_cstrn(self, str, strlen(str));
  10270. }
  10271. void c11_sbuf__write_cstrn(c11_sbuf* self, const char* str, int n) {
  10272. c11_vector__extend(&self->data, str, n);
  10273. }
  10274. void c11_sbuf__write_quoted(c11_sbuf* self, c11_sv sv, char quote) {
  10275. assert(quote == '"' || quote == '\'');
  10276. c11_sbuf__write_char(self, quote);
  10277. for(int i = 0; i < sv.size; i++) {
  10278. char c = sv.data[i];
  10279. switch(c) {
  10280. case '"':
  10281. case '\'':
  10282. if(c == quote) c11_sbuf__write_char(self, '\\');
  10283. c11_sbuf__write_char(self, c);
  10284. break;
  10285. case '\\': c11_sbuf__write_cstrn(self, "\\\\", 2); break;
  10286. case '\n': c11_sbuf__write_cstrn(self, "\\n", 2); break;
  10287. case '\r': c11_sbuf__write_cstrn(self, "\\r", 2); break;
  10288. case '\t': c11_sbuf__write_cstrn(self, "\\t", 2); break;
  10289. case '\b': c11_sbuf__write_cstrn(self, "\\b", 2); break;
  10290. default: {
  10291. int u8bytes = c11__u8_header(c, true);
  10292. if(i + u8bytes > sv.size) u8bytes = 0; // invalid utf8
  10293. if(u8bytes <= 1) {
  10294. // not a valid utf8 char, or ascii
  10295. if(!isprint((unsigned char)c)) {
  10296. unsigned char uc = (unsigned char)c;
  10297. c11_sbuf__write_cstrn(self, "\\x", 2);
  10298. c11_sbuf__write_char(self, PK_HEX_TABLE[uc >> 4]);
  10299. c11_sbuf__write_char(self, PK_HEX_TABLE[uc & 0xf]);
  10300. } else {
  10301. c11_sbuf__write_char(self, c);
  10302. }
  10303. } else {
  10304. for(int j = 0; j < u8bytes; j++) {
  10305. c11_sbuf__write_char(self, sv.data[i + j]);
  10306. }
  10307. i += u8bytes - 1;
  10308. }
  10309. break;
  10310. }
  10311. }
  10312. }
  10313. c11_sbuf__write_char(self, quote);
  10314. }
  10315. void c11_sbuf__write_hex(c11_sbuf* self, unsigned char c, bool non_zero) {
  10316. unsigned char high = c >> 4;
  10317. unsigned char low = c & 0xf;
  10318. if(non_zero) {
  10319. if(high) c11_sbuf__write_char(self, PK_HEX_TABLE[high]);
  10320. if(high || low) c11_sbuf__write_char(self, PK_HEX_TABLE[low]);
  10321. } else {
  10322. c11_sbuf__write_char(self, PK_HEX_TABLE[high]);
  10323. c11_sbuf__write_char(self, PK_HEX_TABLE[low]);
  10324. }
  10325. }
  10326. void c11_sbuf__write_ptr(c11_sbuf* self, void* p) {
  10327. if(p == NULL) {
  10328. c11_sbuf__write_cstr(self, "0x0");
  10329. return;
  10330. }
  10331. c11_sbuf__write_cstr(self, "0x");
  10332. uintptr_t p_t = (uintptr_t)(p);
  10333. bool non_zero = true;
  10334. for(int i = sizeof(void*) - 1; i >= 0; i--) {
  10335. unsigned char cpnt = (p_t >> (i * 8)) & 0xff;
  10336. c11_sbuf__write_hex(self, cpnt, non_zero);
  10337. if(cpnt != 0) non_zero = false;
  10338. }
  10339. }
  10340. c11_string* c11_sbuf__submit(c11_sbuf* self) {
  10341. c11_vector__push(char, &self->data, '\0');
  10342. int arr_length;
  10343. c11_string* retval = c11_vector__submit(&self->data, &arr_length);
  10344. retval->size = arr_length - sizeof(c11_string) - 1;
  10345. return retval;
  10346. }
  10347. void c11_sbuf__py_submit(c11_sbuf* self, py_Ref out) {
  10348. c11_string* res = c11_sbuf__submit(self);
  10349. py_newstrv(out, (c11_sv){res->data, res->size});
  10350. c11_string__delete(res);
  10351. }
  10352. void pk_vsprintf(c11_sbuf* ss, const char* fmt, va_list args) {
  10353. while(*fmt) {
  10354. char c = *fmt;
  10355. if(c != '%') {
  10356. c11_sbuf__write_char(ss, c);
  10357. fmt++;
  10358. continue;
  10359. }
  10360. fmt++;
  10361. c = *fmt;
  10362. switch(c) {
  10363. case 'd': {
  10364. int i = va_arg(args, int);
  10365. c11_sbuf__write_int(ss, i);
  10366. break;
  10367. }
  10368. case 'i': {
  10369. int64_t i = va_arg(args, int64_t);
  10370. c11_sbuf__write_i64(ss, i);
  10371. break;
  10372. }
  10373. case 'f': {
  10374. double d = va_arg(args, double);
  10375. c11_sbuf__write_f64(ss, d, -1);
  10376. break;
  10377. }
  10378. case 's': {
  10379. const char* s = va_arg(args, const char*);
  10380. c11_sbuf__write_cstr(ss, s);
  10381. break;
  10382. }
  10383. case 'q': {
  10384. c11_sv sv = va_arg(args, c11_sv);
  10385. c11_sbuf__write_quoted(ss, sv, '\'');
  10386. break;
  10387. }
  10388. case 'Q': {
  10389. c11_sv sv = va_arg(args, c11_sv);
  10390. c11_sbuf__write_quoted(ss, sv, '"');
  10391. break;
  10392. }
  10393. case 'v': {
  10394. c11_sv sv = va_arg(args, c11_sv);
  10395. c11_sbuf__write_sv(ss, sv);
  10396. break;
  10397. }
  10398. case 'c': {
  10399. char c = va_arg(args, int);
  10400. c11_sbuf__write_char(ss, c);
  10401. break;
  10402. }
  10403. case 'p': {
  10404. void* p = va_arg(args, void*);
  10405. c11_sbuf__write_ptr(ss, p);
  10406. break;
  10407. }
  10408. case 't': {
  10409. py_Type t = va_arg(args, int);
  10410. c11_sbuf__write_cstr(ss, py_tpname(t));
  10411. break;
  10412. }
  10413. case 'n': {
  10414. py_Name n = va_arg(args, void*);
  10415. c11_sbuf__write_cstr(ss, py_name2str(n));
  10416. break;
  10417. }
  10418. case '%': c11_sbuf__write_char(ss, '%'); break;
  10419. default:
  10420. c11_sbuf__write_char(ss, c);
  10421. assert(false); // invalid format
  10422. break;
  10423. }
  10424. fmt++;
  10425. }
  10426. }
  10427. void pk_sprintf(c11_sbuf* ss, const char* fmt, ...) {
  10428. va_list args;
  10429. va_start(args, fmt);
  10430. pk_vsprintf(ss, fmt, args);
  10431. va_end(args);
  10432. }
  10433. // src/common\str.c
  10434. #include <ctype.h>
  10435. #include <string.h>
  10436. #include <stdio.h>
  10437. #include <assert.h>
  10438. c11_string* c11_string__new(const char* data) { return c11_string__new2(data, strlen(data)); }
  10439. c11_string* c11_string__new2(const char* data, int size) {
  10440. c11_string* retval = PK_MALLOC(sizeof(c11_string) + size + 1);
  10441. c11_string__ctor2(retval, data, size);
  10442. return retval;
  10443. }
  10444. c11_string* c11_string__new3(const char* fmt, ...) {
  10445. c11_sbuf buf;
  10446. c11_sbuf__ctor(&buf);
  10447. va_list args;
  10448. va_start(args, fmt);
  10449. // c11_sbuf__write_vfmt(&buf, fmt, args);
  10450. pk_vsprintf(&buf, fmt, args);
  10451. va_end(args);
  10452. return c11_sbuf__submit(&buf);
  10453. }
  10454. void c11_string__ctor(c11_string* self, const char* data) {
  10455. c11_string__ctor2(self, data, strlen(data));
  10456. }
  10457. void c11_string__ctor2(c11_string* self, const char* data, int size) {
  10458. self->size = size;
  10459. char* p = (char*)self->data;
  10460. memcpy(p, data, size);
  10461. p[size] = '\0';
  10462. }
  10463. void c11_string__ctor3(c11_string* self, int size) {
  10464. self->size = size;
  10465. char* p = (char*)self->data;
  10466. p[size] = '\0';
  10467. }
  10468. c11_string* c11_string__copy(c11_string* self) {
  10469. int total_size = sizeof(c11_string) + self->size + 1;
  10470. c11_string* retval = PK_MALLOC(total_size);
  10471. memcpy(retval, self, total_size);
  10472. return retval;
  10473. }
  10474. void c11_string__delete(c11_string* self) { PK_FREE(self); }
  10475. c11_sv c11_string__sv(c11_string* self) { return (c11_sv){self->data, self->size}; }
  10476. c11_string* c11_sv__replace(c11_sv self, char old, char new_) {
  10477. c11_string* retval = c11_string__new2(self.data, self.size);
  10478. char* p = (char*)retval->data;
  10479. for(int i = 0; i < retval->size; i++) {
  10480. if(p[i] == old) p[i] = new_;
  10481. }
  10482. return retval;
  10483. }
  10484. c11_string* c11_sv__replace2(c11_sv self, c11_sv old, c11_sv new_) {
  10485. c11_sbuf buf;
  10486. c11_sbuf__ctor(&buf);
  10487. int start = 0;
  10488. while(true) {
  10489. int i = c11_sv__index2(self, old, start);
  10490. if(i == -1) break;
  10491. c11_sv tmp = c11_sv__slice2(self, start, i);
  10492. c11_sbuf__write_sv(&buf, tmp);
  10493. c11_sbuf__write_sv(&buf, new_);
  10494. start = i + old.size;
  10495. }
  10496. c11_sv tmp = c11_sv__slice2(self, start, self.size);
  10497. c11_sbuf__write_sv(&buf, tmp);
  10498. return c11_sbuf__submit(&buf);
  10499. }
  10500. int c11_sv__u8_length(c11_sv sv) { return c11__byte_index_to_unicode(sv.data, sv.size); }
  10501. c11_sv c11_sv__u8_getitem(c11_sv sv, int i) {
  10502. i = c11__unicode_index_to_byte(sv.data, i);
  10503. int size = c11__u8_header(sv.data[i], false);
  10504. return c11_sv__slice2(sv, i, i + size);
  10505. }
  10506. c11_string* c11_sv__u8_slice(c11_sv sv, int start, int stop, int step) {
  10507. c11_sbuf ss;
  10508. c11_sbuf__ctor(&ss);
  10509. assert(step != 0);
  10510. for(int i = start; step > 0 ? i < stop : i > stop; i += step) {
  10511. c11_sv unicode = c11_sv__u8_getitem(sv, i);
  10512. c11_sbuf__write_sv(&ss, unicode);
  10513. }
  10514. return c11_sbuf__submit(&ss);
  10515. }
  10516. /////////////////////////////////////////
  10517. c11_sv c11_sv__slice(c11_sv sv, int start) { return c11_sv__slice2(sv, start, sv.size); }
  10518. c11_sv c11_sv__slice2(c11_sv sv, int start, int stop) {
  10519. if(start < 0) start = 0;
  10520. if(start > sv.size) start = sv.size;
  10521. if(stop < 0) stop = 0;
  10522. if(stop > sv.size) stop = sv.size;
  10523. if(stop < start) stop = start;
  10524. return (c11_sv){sv.data + start, stop - start};
  10525. }
  10526. c11_sv c11_sv__strip(c11_sv sv, c11_sv chars, bool left, bool right) {
  10527. int L = 0;
  10528. int R = c11_sv__u8_length(sv);
  10529. if(left) {
  10530. while(L < R) {
  10531. c11_sv tmp = c11_sv__u8_getitem(sv, L);
  10532. bool found = c11_sv__index2(chars, tmp, 0) != -1;
  10533. if(!found) break;
  10534. L++;
  10535. }
  10536. }
  10537. if(right) {
  10538. while(L < R) {
  10539. c11_sv tmp = c11_sv__u8_getitem(sv, R - 1);
  10540. bool found = c11_sv__index2(chars, tmp, 0) != -1;
  10541. if(!found) break;
  10542. R--;
  10543. }
  10544. }
  10545. int start = c11__unicode_index_to_byte(sv.data, L);
  10546. int stop = c11__unicode_index_to_byte(sv.data, R);
  10547. return c11_sv__slice2(sv, start, stop);
  10548. }
  10549. int c11_sv__index(c11_sv self, char c) {
  10550. for(int i = 0; i < self.size; i++) {
  10551. if(self.data[i] == c) return i;
  10552. }
  10553. return -1;
  10554. }
  10555. int c11_sv__rindex(c11_sv self, char c) {
  10556. for(int i = self.size - 1; i >= 0; i--) {
  10557. if(self.data[i] == c) return i;
  10558. }
  10559. return -1;
  10560. }
  10561. c11_sv c11_sv__filename(c11_sv self) {
  10562. int sep_index_1 = c11_sv__rindex(self, '/');
  10563. int sep_index_2 = c11_sv__rindex(self, '\\');
  10564. int sep_index = c11__max(sep_index_1, sep_index_2);
  10565. if(sep_index == -1) return self;
  10566. return c11_sv__slice(self, sep_index + 1);
  10567. }
  10568. int c11_sv__index2(c11_sv self, c11_sv sub, int start) {
  10569. if(sub.size == 0) return start;
  10570. int max_end = self.size - sub.size;
  10571. for(int i = start; i <= max_end; i++) {
  10572. int res = memcmp(self.data + i, sub.data, sub.size);
  10573. if(res == 0) return i;
  10574. }
  10575. return -1;
  10576. }
  10577. int c11_sv__count(c11_sv self, c11_sv sub) {
  10578. if(sub.size == 0) return self.size + 1;
  10579. int cnt = 0;
  10580. int start = 0;
  10581. while(true) {
  10582. int i = c11_sv__index2(self, sub, start);
  10583. if(i == -1) break;
  10584. cnt++;
  10585. start = i + sub.size;
  10586. }
  10587. return cnt;
  10588. }
  10589. bool c11_sv__startswith(c11_sv self, c11_sv prefix) {
  10590. if(prefix.size > self.size) return false;
  10591. return memcmp(self.data, prefix.data, prefix.size) == 0;
  10592. }
  10593. bool c11_sv__endswith(c11_sv self, c11_sv suffix) {
  10594. if(suffix.size > self.size) return false;
  10595. return memcmp(self.data + self.size - suffix.size, suffix.data, suffix.size) == 0;
  10596. }
  10597. uint64_t c11_sv__hash(c11_sv self) {
  10598. uint64_t hash = 5381;
  10599. for(int i = 0; i < self.size; i++) {
  10600. // hash * 33 + c
  10601. hash = ((hash << 5) + hash) + (unsigned char)self.data[i];
  10602. }
  10603. return hash;
  10604. }
  10605. c11_vector /* T=c11_sv */ c11_sv__splitwhitespace(c11_sv self) {
  10606. c11_vector retval;
  10607. c11_vector__ctor(&retval, sizeof(c11_sv));
  10608. const char* data = self.data;
  10609. int i = 0;
  10610. for(int j = 0; j < self.size; j++) {
  10611. if(isspace(data[j])) {
  10612. assert(j >= i);
  10613. c11_sv tmp = {data + i, j - i};
  10614. c11_vector__push(c11_sv, &retval, tmp);
  10615. i = j + 1;
  10616. }
  10617. }
  10618. if(i <= self.size) {
  10619. c11_sv tmp = {data + i, self.size - i};
  10620. c11_vector__push(c11_sv, &retval, tmp);
  10621. }
  10622. return retval;
  10623. }
  10624. c11_vector /* T=c11_sv */ c11_sv__splitlines(c11_sv self, bool keepends) {
  10625. c11_vector retval;
  10626. c11_vector__ctor(&retval, sizeof(c11_sv));
  10627. const char* data = self.data;
  10628. int i = 0;
  10629. int eol = 0;
  10630. int eol_size = 1;
  10631. for(int j = 0; j < self.size; ) {
  10632. while(j < self.size) {
  10633. const char c = data[j];
  10634. eol_size = c11__u8_header(c, false);
  10635. if(c == '\n' || c == '\r' || c == '\v' || c == '\f' || c == '\x1c' || c == '\x1d' || c == '\x1e')
  10636. break;
  10637. else if(eol_size == 2 && j + 1 < self.size) {
  10638. if(c == '\xc2' && data[j+1] == '\x85')
  10639. break;
  10640. }
  10641. else if(eol_size == 3 && j + 2 < self.size) {
  10642. if(c == '\xe2' && data[j+1] == '\x80' && (data[j+2] == '\xa8' || data[j+2] == '\xa9'))
  10643. break;
  10644. }
  10645. j += eol_size;
  10646. }
  10647. eol = j;
  10648. if(j < self.size) {
  10649. // CRLF treated as one line break
  10650. if(data[j] == '\r' && j + 1 < self.size && data[j+1] == '\n')
  10651. j += 2;
  10652. else
  10653. j += eol_size;
  10654. if(keepends)
  10655. eol = j;
  10656. }
  10657. c11_sv tmp = {data + i, eol - i};
  10658. c11_vector__push(c11_sv, &retval, tmp);
  10659. i = j;
  10660. }
  10661. return retval;
  10662. }
  10663. c11_vector /* T=c11_sv */ c11_sv__split(c11_sv self, char sep) {
  10664. c11_vector retval;
  10665. c11_vector__ctor(&retval, sizeof(c11_sv));
  10666. const char* data = self.data;
  10667. int i = 0;
  10668. for(int j = 0; j < self.size; j++) {
  10669. if(data[j] == sep) {
  10670. assert(j >= i);
  10671. c11_sv tmp = {data + i, j - i};
  10672. c11_vector__push(c11_sv, &retval, tmp);
  10673. i = j + 1;
  10674. }
  10675. }
  10676. if(i <= self.size) {
  10677. c11_sv tmp = {data + i, self.size - i};
  10678. c11_vector__push(c11_sv, &retval, tmp);
  10679. }
  10680. return retval;
  10681. }
  10682. c11_vector /* T=c11_sv */ c11_sv__split2(c11_sv self, c11_sv sep) {
  10683. if(sep.size == 1) return c11_sv__split(self, sep.data[0]);
  10684. c11_vector retval;
  10685. c11_vector__ctor(&retval, sizeof(c11_sv));
  10686. int start = 0;
  10687. const char* data = self.data;
  10688. while(true) {
  10689. int i = c11_sv__index2(self, sep, start);
  10690. if(i == -1) break;
  10691. c11_sv tmp = {data + start, i - start};
  10692. c11_vector__push(c11_sv, &retval, tmp);
  10693. start = i + sep.size;
  10694. }
  10695. c11_sv tmp = {data + start, self.size - start};
  10696. c11_vector__push(c11_sv, &retval, tmp);
  10697. return retval;
  10698. }
  10699. int c11__unicode_index_to_byte(const char* data, int i) {
  10700. int j = 0;
  10701. while(i > 0) {
  10702. j += c11__u8_header(data[j], false);
  10703. i--;
  10704. }
  10705. return j;
  10706. }
  10707. int c11__byte_index_to_unicode(const char* data, int n) {
  10708. int cnt = 0;
  10709. for(int i = 0; i < n; i++) {
  10710. if((data[i] & 0xC0) != 0x80) cnt++;
  10711. }
  10712. return cnt;
  10713. }
  10714. //////////////
  10715. bool c11_bytes__eq(c11_bytes* self, c11_bytes* other) {
  10716. if(self->size != other->size) return false;
  10717. return memcmp(self->data, other->data, self->size) == 0;
  10718. }
  10719. int c11_sv__cmp(c11_sv self, c11_sv other) {
  10720. int res = strncmp(self.data, other.data, c11__min(self.size, other.size));
  10721. if(res != 0) return res;
  10722. return self.size - other.size;
  10723. }
  10724. int c11_sv__cmp2(c11_sv self, const char* other) {
  10725. int size = strlen(other);
  10726. int res = strncmp(self.data, other, c11__min(self.size, size));
  10727. if(res != 0) return res;
  10728. return self.size - size;
  10729. }
  10730. bool c11__streq(const char* a, const char* b) { return strcmp(a, b) == 0; }
  10731. bool c11__sveq(c11_sv a, c11_sv b) {
  10732. if(a.size != b.size) return false;
  10733. return memcmp(a.data, b.data, a.size) == 0;
  10734. }
  10735. bool c11__sveq2(c11_sv a, const char* b) {
  10736. int size = strlen(b);
  10737. if(a.size != size) return false;
  10738. return memcmp(a.data, b, size) == 0;
  10739. }
  10740. int c11__u8_header(unsigned char c, bool suppress) {
  10741. if((c & 0b10000000) == 0) return 1;
  10742. if((c & 0b11100000) == 0b11000000) return 2;
  10743. if((c & 0b11110000) == 0b11100000) return 3;
  10744. if((c & 0b11111000) == 0b11110000) return 4;
  10745. if((c & 0b11111100) == 0b11111000) return 5;
  10746. if((c & 0b11111110) == 0b11111100) return 6;
  10747. if(!suppress) c11__abort("invalid utf8 char");
  10748. return 0;
  10749. }
  10750. int c11__u8_value(int u8bytes, const char* data) {
  10751. assert(u8bytes != 0);
  10752. if(u8bytes == 1) return (int)data[0];
  10753. uint32_t value = 0;
  10754. for(int k = 0; k < u8bytes; k++) {
  10755. uint8_t b = data[k];
  10756. if(k == 0) {
  10757. if(u8bytes == 2)
  10758. value = (b & 0b00011111) << 6;
  10759. else if(u8bytes == 3)
  10760. value = (b & 0b00001111) << 12;
  10761. else if(u8bytes == 4)
  10762. value = (b & 0b00000111) << 18;
  10763. } else {
  10764. value |= (b & 0b00111111) << (6 * (u8bytes - k - 1));
  10765. }
  10766. }
  10767. return (int)value;
  10768. }
  10769. int c11__u32_to_u8(uint32_t utf32_char, char utf8_output[4]) {
  10770. int length = 0;
  10771. if(utf32_char <= 0x7F) {
  10772. // 1-byte UTF-8
  10773. utf8_output[0] = (char)utf32_char;
  10774. length = 1;
  10775. } else if(utf32_char <= 0x7FF) {
  10776. // 2-byte UTF-8
  10777. utf8_output[0] = (char)(0xC0 | ((utf32_char >> 6) & 0x1F));
  10778. utf8_output[1] = (char)(0x80 | (utf32_char & 0x3F));
  10779. length = 2;
  10780. } else if(utf32_char <= 0xFFFF) {
  10781. // 3-byte UTF-8
  10782. utf8_output[0] = (char)(0xE0 | ((utf32_char >> 12) & 0x0F));
  10783. utf8_output[1] = (char)(0x80 | ((utf32_char >> 6) & 0x3F));
  10784. utf8_output[2] = (char)(0x80 | (utf32_char & 0x3F));
  10785. length = 3;
  10786. } else if(utf32_char <= 0x10FFFF) {
  10787. // 4-byte UTF-8
  10788. utf8_output[0] = (char)(0xF0 | ((utf32_char >> 18) & 0x07));
  10789. utf8_output[1] = (char)(0x80 | ((utf32_char >> 12) & 0x3F));
  10790. utf8_output[2] = (char)(0x80 | ((utf32_char >> 6) & 0x3F));
  10791. utf8_output[3] = (char)(0x80 | (utf32_char & 0x3F));
  10792. length = 4;
  10793. } else {
  10794. // Invalid UTF-32 character
  10795. return -1;
  10796. }
  10797. return length;
  10798. }
  10799. char* c11_strdup(const char* str) {
  10800. int len = strlen(str);
  10801. char* dst = PK_MALLOC(len + 1);
  10802. memcpy(dst, str, len);
  10803. dst[len] = '\0';
  10804. return dst;
  10805. }
  10806. unsigned char* c11_memdup(const unsigned char* src, int size) {
  10807. unsigned char* dst = PK_MALLOC(size);
  10808. memcpy(dst, src, size);
  10809. return dst;
  10810. }
  10811. IntParsingResult c11__parse_uint(c11_sv text, int64_t* out, int base) {
  10812. *out = 0;
  10813. c11_sv prefix = {.data = text.data, .size = c11__min(2, text.size)};
  10814. if(base == -1) {
  10815. if(c11__sveq2(prefix, "0b"))
  10816. base = 2;
  10817. else if(c11__sveq2(prefix, "0o"))
  10818. base = 8;
  10819. else if(c11__sveq2(prefix, "0x"))
  10820. base = 16;
  10821. else
  10822. base = 10;
  10823. }
  10824. if(base == 10) {
  10825. // 10-base 12334
  10826. if(text.size == 0) return IntParsing_FAILURE;
  10827. for(int i = 0; i < text.size; i++) {
  10828. char c = text.data[i];
  10829. if(c >= '0' && c <= '9') {
  10830. *out = (*out * 10) + (c - '0');
  10831. } else {
  10832. return IntParsing_FAILURE;
  10833. }
  10834. }
  10835. // "9223372036854775807".__len__() == 19
  10836. if(text.size > 19) return IntParsing_OVERFLOW;
  10837. return IntParsing_SUCCESS;
  10838. } else if(base == 2) {
  10839. // 2-base 0b101010
  10840. if(c11__sveq2(prefix, "0b")) {
  10841. // text.remove_prefix(2);
  10842. text = (c11_sv){text.data + 2, text.size - 2};
  10843. }
  10844. if(text.size == 0) return IntParsing_FAILURE;
  10845. for(int i = 0; i < text.size; i++) {
  10846. char c = text.data[i];
  10847. if(c == '0' || c == '1') {
  10848. *out = (*out << 1) | (c - '0');
  10849. } else {
  10850. return IntParsing_FAILURE;
  10851. }
  10852. }
  10853. // "111111111111111111111111111111111111111111111111111111111111111".__len__() == 63
  10854. if(text.size > 63) return IntParsing_OVERFLOW;
  10855. return IntParsing_SUCCESS;
  10856. } else if(base == 8) {
  10857. // 8-base 0o123
  10858. if(c11__sveq2(prefix, "0o")) {
  10859. // text.remove_prefix(2);
  10860. text = (c11_sv){text.data + 2, text.size - 2};
  10861. }
  10862. if(text.size == 0) return IntParsing_FAILURE;
  10863. for(int i = 0; i < text.size; i++) {
  10864. char c = text.data[i];
  10865. if(c >= '0' && c <= '7') {
  10866. *out = (*out << 3) | (c - '0');
  10867. } else {
  10868. return IntParsing_FAILURE;
  10869. }
  10870. }
  10871. // "777777777777777777777".__len__() == 21
  10872. if(text.size > 21) return IntParsing_OVERFLOW;
  10873. return IntParsing_SUCCESS;
  10874. } else if(base == 16) {
  10875. // 16-base 0x123
  10876. if(c11__sveq2(prefix, "0x")) {
  10877. // text.remove_prefix(2);
  10878. text = (c11_sv){text.data + 2, text.size - 2};
  10879. }
  10880. if(text.size == 0) return IntParsing_FAILURE;
  10881. for(int i = 0; i < text.size; i++) {
  10882. char c = text.data[i];
  10883. if(c >= '0' && c <= '9') {
  10884. *out = (*out << 4) | (c - '0');
  10885. } else if(c >= 'a' && c <= 'f') {
  10886. *out = (*out << 4) | (c - 'a' + 10);
  10887. } else if(c >= 'A' && c <= 'F') {
  10888. *out = (*out << 4) | (c - 'A' + 10);
  10889. } else {
  10890. return IntParsing_FAILURE;
  10891. }
  10892. }
  10893. // "7fffffffffffffff".__len__() == 16
  10894. if(text.size > 16) return IntParsing_OVERFLOW;
  10895. return IntParsing_SUCCESS;
  10896. }
  10897. return IntParsing_FAILURE;
  10898. }
  10899. const char* c11__search_u32_ranges(int c, const c11_u32_range* p, int n_ranges) {
  10900. int lbound = 0;
  10901. int ubound = n_ranges - 1;
  10902. if(c < p[0].start || c > p[ubound].end) return NULL;
  10903. while(ubound >= lbound) {
  10904. int mid = (lbound + ubound) / 2;
  10905. if(c > p[mid].end) {
  10906. lbound = mid + 1;
  10907. } else if(c < p[mid].start) {
  10908. ubound = mid - 1;
  10909. } else {
  10910. return p[mid].data;
  10911. }
  10912. }
  10913. return NULL;
  10914. }
  10915. // clang-format off
  10916. const static c11_u32_range kLoRanges[] = {
  10917. { 170, 170 },
  10918. { 186, 186 },
  10919. { 443, 443 },
  10920. { 448, 451 },
  10921. { 660, 660 },
  10922. { 1488, 1514 },
  10923. { 1519, 1522 },
  10924. { 1568, 1599 },
  10925. { 1601, 1610 },
  10926. { 1646, 1647 },
  10927. { 1649, 1747 },
  10928. { 1749, 1749 },
  10929. { 1774, 1775 },
  10930. { 1786, 1788 },
  10931. { 1791, 1791 },
  10932. { 1808, 1808 },
  10933. { 1810, 1839 },
  10934. { 1869, 1957 },
  10935. { 1969, 1969 },
  10936. { 1994, 2026 },
  10937. { 2048, 2069 },
  10938. { 2112, 2136 },
  10939. { 2144, 2154 },
  10940. { 2160, 2183 },
  10941. { 2185, 2190 },
  10942. { 2208, 2248 },
  10943. { 2308, 2361 },
  10944. { 2365, 2365 },
  10945. { 2384, 2384 },
  10946. { 2392, 2401 },
  10947. { 2418, 2432 },
  10948. { 2437, 2444 },
  10949. { 2447, 2448 },
  10950. { 2451, 2472 },
  10951. { 2474, 2480 },
  10952. { 2482, 2482 },
  10953. { 2486, 2489 },
  10954. { 2493, 2493 },
  10955. { 2510, 2510 },
  10956. { 2524, 2525 },
  10957. { 2527, 2529 },
  10958. { 2544, 2545 },
  10959. { 2556, 2556 },
  10960. { 2565, 2570 },
  10961. { 2575, 2576 },
  10962. { 2579, 2600 },
  10963. { 2602, 2608 },
  10964. { 2610, 2611 },
  10965. { 2613, 2614 },
  10966. { 2616, 2617 },
  10967. { 2649, 2652 },
  10968. { 2654, 2654 },
  10969. { 2674, 2676 },
  10970. { 2693, 2701 },
  10971. { 2703, 2705 },
  10972. { 2707, 2728 },
  10973. { 2730, 2736 },
  10974. { 2738, 2739 },
  10975. { 2741, 2745 },
  10976. { 2749, 2749 },
  10977. { 2768, 2768 },
  10978. { 2784, 2785 },
  10979. { 2809, 2809 },
  10980. { 2821, 2828 },
  10981. { 2831, 2832 },
  10982. { 2835, 2856 },
  10983. { 2858, 2864 },
  10984. { 2866, 2867 },
  10985. { 2869, 2873 },
  10986. { 2877, 2877 },
  10987. { 2908, 2909 },
  10988. { 2911, 2913 },
  10989. { 2929, 2929 },
  10990. { 2947, 2947 },
  10991. { 2949, 2954 },
  10992. { 2958, 2960 },
  10993. { 2962, 2965 },
  10994. { 2969, 2970 },
  10995. { 2972, 2972 },
  10996. { 2974, 2975 },
  10997. { 2979, 2980 },
  10998. { 2984, 2986 },
  10999. { 2990, 3001 },
  11000. { 3024, 3024 },
  11001. { 3077, 3084 },
  11002. { 3086, 3088 },
  11003. { 3090, 3112 },
  11004. { 3114, 3129 },
  11005. { 3133, 3133 },
  11006. { 3160, 3162 },
  11007. { 3165, 3165 },
  11008. { 3168, 3169 },
  11009. { 3200, 3200 },
  11010. { 3205, 3212 },
  11011. { 3214, 3216 },
  11012. { 3218, 3240 },
  11013. { 3242, 3251 },
  11014. { 3253, 3257 },
  11015. { 3261, 3261 },
  11016. { 3293, 3294 },
  11017. { 3296, 3297 },
  11018. { 3313, 3314 },
  11019. { 3332, 3340 },
  11020. { 3342, 3344 },
  11021. { 3346, 3386 },
  11022. { 3389, 3389 },
  11023. { 3406, 3406 },
  11024. { 3412, 3414 },
  11025. { 3423, 3425 },
  11026. { 3450, 3455 },
  11027. { 3461, 3478 },
  11028. { 3482, 3505 },
  11029. { 3507, 3515 },
  11030. { 3517, 3517 },
  11031. { 3520, 3526 },
  11032. { 3585, 3632 },
  11033. { 3634, 3635 },
  11034. { 3648, 3653 },
  11035. { 3713, 3714 },
  11036. { 3716, 3716 },
  11037. { 3718, 3722 },
  11038. { 3724, 3747 },
  11039. { 3749, 3749 },
  11040. { 3751, 3760 },
  11041. { 3762, 3763 },
  11042. { 3773, 3773 },
  11043. { 3776, 3780 },
  11044. { 3804, 3807 },
  11045. { 3840, 3840 },
  11046. { 3904, 3911 },
  11047. { 3913, 3948 },
  11048. { 3976, 3980 },
  11049. { 4096, 4138 },
  11050. { 4159, 4159 },
  11051. { 4176, 4181 },
  11052. { 4186, 4189 },
  11053. { 4193, 4193 },
  11054. { 4197, 4198 },
  11055. { 4206, 4208 },
  11056. { 4213, 4225 },
  11057. { 4238, 4238 },
  11058. { 4352, 4680 },
  11059. { 4682, 4685 },
  11060. { 4688, 4694 },
  11061. { 4696, 4696 },
  11062. { 4698, 4701 },
  11063. { 4704, 4744 },
  11064. { 4746, 4749 },
  11065. { 4752, 4784 },
  11066. { 4786, 4789 },
  11067. { 4792, 4798 },
  11068. { 4800, 4800 },
  11069. { 4802, 4805 },
  11070. { 4808, 4822 },
  11071. { 4824, 4880 },
  11072. { 4882, 4885 },
  11073. { 4888, 4954 },
  11074. { 4992, 5007 },
  11075. { 5121, 5740 },
  11076. { 5743, 5759 },
  11077. { 5761, 5786 },
  11078. { 5792, 5866 },
  11079. { 5873, 5880 },
  11080. { 5888, 5905 },
  11081. { 5919, 5937 },
  11082. { 5952, 5969 },
  11083. { 5984, 5996 },
  11084. { 5998, 6000 },
  11085. { 6016, 6067 },
  11086. { 6108, 6108 },
  11087. { 6176, 6210 },
  11088. { 6212, 6264 },
  11089. { 6272, 6276 },
  11090. { 6279, 6312 },
  11091. { 6314, 6314 },
  11092. { 6320, 6389 },
  11093. { 6400, 6430 },
  11094. { 6480, 6509 },
  11095. { 6512, 6516 },
  11096. { 6528, 6571 },
  11097. { 6576, 6601 },
  11098. { 6656, 6678 },
  11099. { 6688, 6740 },
  11100. { 6917, 6963 },
  11101. { 6981, 6988 },
  11102. { 7043, 7072 },
  11103. { 7086, 7087 },
  11104. { 7098, 7141 },
  11105. { 7168, 7203 },
  11106. { 7245, 7247 },
  11107. { 7258, 7287 },
  11108. { 7401, 7404 },
  11109. { 7406, 7411 },
  11110. { 7413, 7414 },
  11111. { 7418, 7418 },
  11112. { 8501, 8504 },
  11113. { 11568, 11623 },
  11114. { 11648, 11670 },
  11115. { 11680, 11686 },
  11116. { 11688, 11694 },
  11117. { 11696, 11702 },
  11118. { 11704, 11710 },
  11119. { 11712, 11718 },
  11120. { 11720, 11726 },
  11121. { 11728, 11734 },
  11122. { 11736, 11742 },
  11123. { 12294, 12294 },
  11124. { 12348, 12348 },
  11125. { 12353, 12438 },
  11126. { 12447, 12447 },
  11127. { 12449, 12538 },
  11128. { 12543, 12543 },
  11129. { 12549, 12591 },
  11130. { 12593, 12686 },
  11131. { 12704, 12735 },
  11132. { 12784, 12799 },
  11133. { 13312, 19903 },
  11134. { 19968, 40980 },
  11135. { 40982, 42124 },
  11136. { 42192, 42231 },
  11137. { 42240, 42507 },
  11138. { 42512, 42527 },
  11139. { 42538, 42539 },
  11140. { 42606, 42606 },
  11141. { 42656, 42725 },
  11142. { 42895, 42895 },
  11143. { 42999, 42999 },
  11144. { 43003, 43009 },
  11145. { 43011, 43013 },
  11146. { 43015, 43018 },
  11147. { 43020, 43042 },
  11148. { 43072, 43123 },
  11149. { 43138, 43187 },
  11150. { 43250, 43255 },
  11151. { 43259, 43259 },
  11152. { 43261, 43262 },
  11153. { 43274, 43301 },
  11154. { 43312, 43334 },
  11155. { 43360, 43388 },
  11156. { 43396, 43442 },
  11157. { 43488, 43492 },
  11158. { 43495, 43503 },
  11159. { 43514, 43518 },
  11160. { 43520, 43560 },
  11161. { 43584, 43586 },
  11162. { 43588, 43595 },
  11163. { 43616, 43631 },
  11164. { 43633, 43638 },
  11165. { 43642, 43642 },
  11166. { 43646, 43695 },
  11167. { 43697, 43697 },
  11168. { 43701, 43702 },
  11169. { 43705, 43709 },
  11170. { 43712, 43712 },
  11171. { 43714, 43714 },
  11172. { 43739, 43740 },
  11173. { 43744, 43754 },
  11174. { 43762, 43762 },
  11175. { 43777, 43782 },
  11176. { 43785, 43790 },
  11177. { 43793, 43798 },
  11178. { 43808, 43814 },
  11179. { 43816, 43822 },
  11180. { 43968, 44002 },
  11181. { 44032, 55203 },
  11182. { 55216, 55238 },
  11183. { 55243, 55291 },
  11184. { 63744, 64109 },
  11185. { 64112, 64217 },
  11186. { 64285, 64285 },
  11187. { 64287, 64296 },
  11188. { 64298, 64310 },
  11189. { 64312, 64316 },
  11190. { 64318, 64318 },
  11191. { 64320, 64321 },
  11192. { 64323, 64324 },
  11193. { 64326, 64433 },
  11194. { 64467, 64829 },
  11195. { 64848, 64911 },
  11196. { 64914, 64967 },
  11197. { 65008, 65019 },
  11198. { 65136, 65140 },
  11199. { 65142, 65276 },
  11200. { 65382, 65391 },
  11201. { 65393, 65437 },
  11202. { 65440, 65470 },
  11203. { 65474, 65479 },
  11204. { 65482, 65487 },
  11205. { 65490, 65495 },
  11206. { 65498, 65500 },
  11207. { 65536, 65547 },
  11208. { 65549, 65574 },
  11209. { 65576, 65594 },
  11210. { 65596, 65597 },
  11211. { 65599, 65613 },
  11212. { 65616, 65629 },
  11213. { 65664, 65786 },
  11214. { 66176, 66204 },
  11215. { 66208, 66256 },
  11216. { 66304, 66335 },
  11217. { 66349, 66368 },
  11218. { 66370, 66377 },
  11219. { 66384, 66421 },
  11220. { 66432, 66461 },
  11221. { 66464, 66499 },
  11222. { 66504, 66511 },
  11223. { 66640, 66717 },
  11224. { 66816, 66855 },
  11225. { 66864, 66915 },
  11226. { 67072, 67382 },
  11227. { 67392, 67413 },
  11228. { 67424, 67431 },
  11229. { 67584, 67589 },
  11230. { 67592, 67592 },
  11231. { 67594, 67637 },
  11232. { 67639, 67640 },
  11233. { 67644, 67644 },
  11234. { 67647, 67669 },
  11235. { 67680, 67702 },
  11236. { 67712, 67742 },
  11237. { 67808, 67826 },
  11238. { 67828, 67829 },
  11239. { 67840, 67861 },
  11240. { 67872, 67897 },
  11241. { 67968, 68023 },
  11242. { 68030, 68031 },
  11243. { 68096, 68096 },
  11244. { 68112, 68115 },
  11245. { 68117, 68119 },
  11246. { 68121, 68149 },
  11247. { 68192, 68220 },
  11248. { 68224, 68252 },
  11249. { 68288, 68295 },
  11250. { 68297, 68324 },
  11251. { 68352, 68405 },
  11252. { 68416, 68437 },
  11253. { 68448, 68466 },
  11254. { 68480, 68497 },
  11255. { 68608, 68680 },
  11256. { 68864, 68899 },
  11257. { 69248, 69289 },
  11258. { 69296, 69297 },
  11259. { 69376, 69404 },
  11260. { 69415, 69415 },
  11261. { 69424, 69445 },
  11262. { 69488, 69505 },
  11263. { 69552, 69572 },
  11264. { 69600, 69622 },
  11265. { 69635, 69687 },
  11266. { 69745, 69746 },
  11267. { 69749, 69749 },
  11268. { 69763, 69807 },
  11269. { 69840, 69864 },
  11270. { 69891, 69926 },
  11271. { 69956, 69956 },
  11272. { 69959, 69959 },
  11273. { 69968, 70002 },
  11274. { 70006, 70006 },
  11275. { 70019, 70066 },
  11276. { 70081, 70084 },
  11277. { 70106, 70106 },
  11278. { 70108, 70108 },
  11279. { 70144, 70161 },
  11280. { 70163, 70187 },
  11281. { 70272, 70278 },
  11282. { 70280, 70280 },
  11283. { 70282, 70285 },
  11284. { 70287, 70301 },
  11285. { 70303, 70312 },
  11286. { 70320, 70366 },
  11287. { 70405, 70412 },
  11288. { 70415, 70416 },
  11289. { 70419, 70440 },
  11290. { 70442, 70448 },
  11291. { 70450, 70451 },
  11292. { 70453, 70457 },
  11293. { 70461, 70461 },
  11294. { 70480, 70480 },
  11295. { 70493, 70497 },
  11296. { 70656, 70708 },
  11297. { 70727, 70730 },
  11298. { 70751, 70753 },
  11299. { 70784, 70831 },
  11300. { 70852, 70853 },
  11301. { 70855, 70855 },
  11302. { 71040, 71086 },
  11303. { 71128, 71131 },
  11304. { 71168, 71215 },
  11305. { 71236, 71236 },
  11306. { 71296, 71338 },
  11307. { 71352, 71352 },
  11308. { 71424, 71450 },
  11309. { 71488, 71494 },
  11310. { 71680, 71723 },
  11311. { 71935, 71942 },
  11312. { 71945, 71945 },
  11313. { 71948, 71955 },
  11314. { 71957, 71958 },
  11315. { 71960, 71983 },
  11316. { 71999, 71999 },
  11317. { 72001, 72001 },
  11318. { 72096, 72103 },
  11319. { 72106, 72144 },
  11320. { 72161, 72161 },
  11321. { 72163, 72163 },
  11322. { 72192, 72192 },
  11323. { 72203, 72242 },
  11324. { 72250, 72250 },
  11325. { 72272, 72272 },
  11326. { 72284, 72329 },
  11327. { 72349, 72349 },
  11328. { 72368, 72440 },
  11329. { 72704, 72712 },
  11330. { 72714, 72750 },
  11331. { 72768, 72768 },
  11332. { 72818, 72847 },
  11333. { 72960, 72966 },
  11334. { 72968, 72969 },
  11335. { 72971, 73008 },
  11336. { 73030, 73030 },
  11337. { 73056, 73061 },
  11338. { 73063, 73064 },
  11339. { 73066, 73097 },
  11340. { 73112, 73112 },
  11341. { 73440, 73458 },
  11342. { 73648, 73648 },
  11343. { 73728, 74649 },
  11344. { 74880, 75075 },
  11345. { 77712, 77808 },
  11346. { 77824, 78894 },
  11347. { 82944, 83526 },
  11348. { 92160, 92728 },
  11349. { 92736, 92766 },
  11350. { 92784, 92862 },
  11351. { 92880, 92909 },
  11352. { 92928, 92975 },
  11353. { 93027, 93047 },
  11354. { 93053, 93071 },
  11355. { 93952, 94026 },
  11356. { 94032, 94032 },
  11357. { 94208, 100343 },
  11358. { 100352, 101589 },
  11359. { 101632, 101640 },
  11360. { 110592, 110882 },
  11361. { 110928, 110930 },
  11362. { 110948, 110951 },
  11363. { 110960, 111355 },
  11364. { 113664, 113770 },
  11365. { 113776, 113788 },
  11366. { 113792, 113800 },
  11367. { 113808, 113817 },
  11368. { 122634, 122634 },
  11369. { 123136, 123180 },
  11370. { 123214, 123214 },
  11371. { 123536, 123565 },
  11372. { 123584, 123627 },
  11373. { 124896, 124902 },
  11374. { 124904, 124907 },
  11375. { 124909, 124910 },
  11376. { 124912, 124926 },
  11377. { 124928, 125124 },
  11378. { 126464, 126467 },
  11379. { 126469, 126495 },
  11380. { 126497, 126498 },
  11381. { 126500, 126500 },
  11382. { 126503, 126503 },
  11383. { 126505, 126514 },
  11384. { 126516, 126519 },
  11385. { 126521, 126521 },
  11386. { 126523, 126523 },
  11387. { 126530, 126530 },
  11388. { 126535, 126535 },
  11389. { 126537, 126537 },
  11390. { 126539, 126539 },
  11391. { 126541, 126543 },
  11392. { 126545, 126546 },
  11393. { 126548, 126548 },
  11394. { 126551, 126551 },
  11395. { 126553, 126553 },
  11396. { 126555, 126555 },
  11397. { 126557, 126557 },
  11398. { 126559, 126559 },
  11399. { 126561, 126562 },
  11400. { 126564, 126564 },
  11401. { 126567, 126570 },
  11402. { 126572, 126578 },
  11403. { 126580, 126583 },
  11404. { 126585, 126588 },
  11405. { 126590, 126590 },
  11406. { 126592, 126601 },
  11407. { 126603, 126619 },
  11408. { 126625, 126627 },
  11409. { 126629, 126633 },
  11410. { 126635, 126651 },
  11411. { 131072, 173791 },
  11412. { 173824, 177976 },
  11413. { 177984, 178205 },
  11414. { 178208, 183969 },
  11415. { 183984, 191456 },
  11416. { 194560, 195101 },
  11417. { 196608, 201546 },
  11418. };
  11419. // clang-format on
  11420. bool c11__is_unicode_Lo_char(int c) {
  11421. const char* data =
  11422. c11__search_u32_ranges(c, kLoRanges, sizeof(kLoRanges) / sizeof(c11_u32_range));
  11423. return data != NULL;
  11424. }
  11425. // src/common\threads.c
  11426. #include <stdarg.h>
  11427. #if PK_ENABLE_THREADS
  11428. #if PK_USE_PTHREADS
  11429. bool c11_thrd__create(c11_thrd_t* thrd, c11_thrd_func_t func, void* arg) {
  11430. int res = pthread_create(thrd, NULL, func, arg);
  11431. return res == 0;
  11432. }
  11433. void c11_thrd__yield() { sched_yield(); }
  11434. void c11_thrd__join(c11_thrd_t thrd) { pthread_join(thrd, NULL); }
  11435. c11_thrd_t c11_thrd__current() { return pthread_self(); }
  11436. bool c11_thrd__equal(c11_thrd_t a, c11_thrd_t b) { return pthread_equal(a, b); }
  11437. void c11_mutex__ctor(c11_mutex_t* mutex) { pthread_mutex_init(mutex, NULL); }
  11438. void c11_mutex__dtor(c11_mutex_t* mutex) { pthread_mutex_destroy(mutex); }
  11439. void c11_mutex__lock(c11_mutex_t* mutex) { pthread_mutex_lock(mutex); }
  11440. void c11_mutex__unlock(c11_mutex_t* mutex) { pthread_mutex_unlock(mutex); }
  11441. void c11_cond__ctor(c11_cond_t* cond) { pthread_cond_init(cond, NULL); }
  11442. void c11_cond__dtor(c11_cond_t* cond) { pthread_cond_destroy(cond); }
  11443. void c11_cond__wait(c11_cond_t* cond, c11_mutex_t* mutex) { pthread_cond_wait(cond, mutex); }
  11444. void c11_cond__signal(c11_cond_t* cond) { pthread_cond_signal(cond); }
  11445. void c11_cond__broadcast(c11_cond_t* cond) { pthread_cond_broadcast(cond); }
  11446. #else
  11447. bool c11_thrd__create(c11_thrd_t* thrd, c11_thrd_func_t func, void* arg) {
  11448. int res = thrd_create(thrd, func, arg);
  11449. return res == thrd_success;
  11450. }
  11451. void c11_thrd__yield() { thrd_yield(); }
  11452. void c11_thrd__join(c11_thrd_t thrd) { thrd_join(thrd, NULL); }
  11453. c11_thrd_t c11_thrd__current() { return thrd_current(); }
  11454. bool c11_thrd__equal(c11_thrd_t a, c11_thrd_t b) { return thrd_equal(a, b); }
  11455. void c11_mutex__ctor(c11_mutex_t* mutex) { mtx_init(mutex, mtx_plain); }
  11456. void c11_mutex__dtor(c11_mutex_t* mutex) { mtx_destroy(mutex); }
  11457. void c11_mutex__lock(c11_mutex_t* mutex) { mtx_lock(mutex); }
  11458. void c11_mutex__unlock(c11_mutex_t* mutex) { mtx_unlock(mutex); }
  11459. void c11_cond__ctor(c11_cond_t* cond) { cnd_init(cond); }
  11460. void c11_cond__dtor(c11_cond_t* cond) { cnd_destroy(cond); }
  11461. void c11_cond__wait(c11_cond_t* cond, c11_mutex_t* mutex) { cnd_wait(cond, mutex); }
  11462. void c11_cond__signal(c11_cond_t* cond) { cnd_signal(cond); }
  11463. void c11_cond__broadcast(c11_cond_t* cond) { cnd_broadcast(cond); }
  11464. #endif
  11465. #define C11_THRDPOOL_DEBUG 0
  11466. #if C11_THRDPOOL_DEBUG
  11467. static void c11_thrdpool_debug_log(int index, const char* format, ...) {
  11468. va_list args;
  11469. va_start(args, format);
  11470. char buf[512];
  11471. int n = sprintf(buf, "[%.6f - Worker %2d] ", time_ns() / 1e9, index);
  11472. vsprintf(buf + n, format, args);
  11473. printf("%s\n", buf);
  11474. va_end(args);
  11475. }
  11476. #else
  11477. #define c11_thrdpool_debug_log(...) \
  11478. do { \
  11479. } while(0)
  11480. #endif
  11481. static c11_thrd_retval_t _thrdpool_worker(void* arg) {
  11482. c11_thrdpool_worker* p_worker = (c11_thrdpool_worker*)arg;
  11483. c11_thrdpool_tasks* p_tasks = p_worker->p_tasks;
  11484. while(true) {
  11485. c11_thrdpool_debug_log(p_worker->index, "Waiting for mutex lock...");
  11486. c11_mutex__lock(p_worker->p_mutex);
  11487. atomic_fetch_add_explicit(p_worker->p_ready_workers_num, 1, memory_order_relaxed);
  11488. c11_thrdpool_debug_log(p_worker->index, "Mutex locked, checking for tasks...");
  11489. if(atomic_load_explicit(&p_tasks->sync_val, memory_order_relaxed) == -1) {
  11490. c11_mutex__unlock(p_worker->p_mutex);
  11491. return 0; // force kill
  11492. }
  11493. while(true) {
  11494. c11_cond__wait(p_worker->p_cond, p_worker->p_mutex);
  11495. int sync_val = atomic_load_explicit(&p_tasks->sync_val, memory_order_relaxed);
  11496. c11_thrdpool_debug_log(p_worker->index,
  11497. "Woke up from condition variable, sync_val=%d",
  11498. sync_val);
  11499. if(sync_val == 1) break;
  11500. if(sync_val == -1) {
  11501. c11_mutex__unlock(p_worker->p_mutex);
  11502. return 0; // force kill
  11503. }
  11504. }
  11505. atomic_fetch_sub_explicit(p_worker->p_ready_workers_num, 1, memory_order_relaxed);
  11506. c11_mutex__unlock(p_worker->p_mutex);
  11507. c11_thrdpool_debug_log(p_worker->index, "Received tasks, starting execution...");
  11508. // execute tasks
  11509. int completed_count = 0;
  11510. while(true) {
  11511. int arg_index =
  11512. atomic_fetch_add_explicit(&p_tasks->current_index, 1, memory_order_relaxed);
  11513. if(arg_index < p_tasks->length) {
  11514. void* arg = p_tasks->args[arg_index];
  11515. p_tasks->func(arg);
  11516. completed_count++;
  11517. } else {
  11518. break;
  11519. }
  11520. }
  11521. // sync point
  11522. atomic_fetch_add_explicit(&p_tasks->completed_count, completed_count, memory_order_release);
  11523. c11_thrdpool_debug_log(p_worker->index,
  11524. "Execution complete, waiting for `sync_val` reset...");
  11525. while(true) {
  11526. int sync_val = atomic_load_explicit(&p_tasks->sync_val, memory_order_relaxed);
  11527. if(sync_val == 0) break;
  11528. if(sync_val == -1) return 0; // force kill
  11529. c11_thrd__yield();
  11530. }
  11531. c11_thrdpool_debug_log(p_worker->index,
  11532. "`sync_val` reset detected, waiting for next tasks...");
  11533. }
  11534. return 0;
  11535. }
  11536. void c11_thrdpool__ctor(c11_thrdpool* pool, int length) {
  11537. pool->length = length;
  11538. atomic_store_explicit(&pool->ready_workers_num, 0, memory_order_relaxed);
  11539. pool->workers = PK_MALLOC(sizeof(c11_thrdpool_worker) * length);
  11540. c11_mutex__ctor(&pool->workers_mutex);
  11541. c11_cond__ctor(&pool->workers_cond);
  11542. atomic_store_explicit(&pool->tasks.sync_val, 0, memory_order_relaxed);
  11543. for(int i = 0; i < length; i++) {
  11544. c11_thrdpool_worker* p_worker = &pool->workers[i];
  11545. p_worker->index = i;
  11546. p_worker->p_ready_workers_num = &pool->ready_workers_num;
  11547. p_worker->p_mutex = &pool->workers_mutex;
  11548. p_worker->p_cond = &pool->workers_cond;
  11549. p_worker->p_tasks = &pool->tasks;
  11550. bool ok = c11_thrd__create(&p_worker->thread, _thrdpool_worker, p_worker);
  11551. c11__rtassert(ok);
  11552. }
  11553. }
  11554. void c11_thrdpool__dtor(c11_thrdpool* pool) {
  11555. c11_mutex__lock(&pool->workers_mutex);
  11556. atomic_store_explicit(&pool->tasks.sync_val, -1, memory_order_relaxed);
  11557. c11_thrdpool_debug_log(-1, "Terminating all workers...");
  11558. c11_cond__broadcast(&pool->workers_cond);
  11559. c11_mutex__unlock(&pool->workers_mutex);
  11560. for(int i = 0; i < pool->length; i++) {
  11561. c11_thrdpool_worker* p_worker = &pool->workers[i];
  11562. c11_thrd__join(p_worker->thread);
  11563. }
  11564. c11_mutex__dtor(&pool->workers_mutex);
  11565. c11_cond__dtor(&pool->workers_cond);
  11566. PK_FREE(pool->workers);
  11567. }
  11568. void c11_thrdpool__map(c11_thrdpool* pool, c11_thrdpool_func_t func, void** args, int num_tasks) {
  11569. c11_thrdpool_debug_log(-1, "c11_thrdpool__map() called on %d tasks...", num_tasks);
  11570. while(atomic_load_explicit(&pool->ready_workers_num, memory_order_relaxed) < pool->length) {
  11571. c11_thrd__yield();
  11572. }
  11573. c11_thrdpool_debug_log(-1, "All %d workers are ready.", pool->length);
  11574. // assign tasks
  11575. c11_mutex__lock(&pool->workers_mutex);
  11576. pool->tasks.func = func;
  11577. pool->tasks.args = args;
  11578. pool->tasks.length = num_tasks;
  11579. atomic_store_explicit(&pool->tasks.sync_val, 1, memory_order_relaxed);
  11580. atomic_store_explicit(&pool->tasks.current_index, 0, memory_order_relaxed);
  11581. atomic_store_explicit(&pool->tasks.completed_count, 0, memory_order_relaxed);
  11582. c11_cond__broadcast(&pool->workers_cond);
  11583. c11_mutex__unlock(&pool->workers_mutex);
  11584. }
  11585. void c11_thrdpool__join(c11_thrdpool *pool) {
  11586. // wait for complete
  11587. int num_tasks = pool->tasks.length;
  11588. c11_thrdpool_debug_log(-1, "Waiting for %d tasks to complete...", num_tasks);
  11589. while(atomic_load_explicit(&pool->tasks.completed_count, memory_order_acquire) < num_tasks) {
  11590. c11_thrd__yield();
  11591. }
  11592. atomic_store_explicit(&pool->tasks.sync_val, 0, memory_order_relaxed);
  11593. c11_thrdpool_debug_log(-1, "All %d tasks completed, `sync_val` was reset.", num_tasks);
  11594. }
  11595. #undef C11_THRDPOOL_DEBUG
  11596. #ifdef c11_thrdpool_debug_log
  11597. #undef c11_thrdpool_debug_log
  11598. #endif
  11599. #endif // PK_ENABLE_THREADS
  11600. // src/common\vector.c
  11601. #include <string.h>
  11602. void c11_vector__ctor(c11_vector* self, int elem_size) {
  11603. self->data = NULL;
  11604. self->length = 0;
  11605. self->capacity = 0;
  11606. self->elem_size = elem_size;
  11607. }
  11608. void c11_vector__dtor(c11_vector* self) {
  11609. if(self->data) PK_FREE(self->data);
  11610. self->data = NULL;
  11611. self->length = 0;
  11612. self->capacity = 0;
  11613. }
  11614. c11_vector c11_vector__copy(const c11_vector* self) {
  11615. c11_vector retval;
  11616. c11_vector__ctor(&retval, self->elem_size);
  11617. c11_vector__reserve(&retval, self->capacity);
  11618. memcpy(retval.data, self->data, (size_t)self->elem_size * (size_t)self->length);
  11619. retval.length = self->length;
  11620. return retval;
  11621. }
  11622. void c11_vector__reserve(c11_vector* self, int capacity) {
  11623. if(capacity < 4) capacity = 4;
  11624. if(capacity <= self->capacity) return;
  11625. // self->elem_size * capacity may overflow
  11626. self->data = PK_REALLOC(self->data, (size_t)self->elem_size * (size_t)capacity);
  11627. if(self->data == NULL) c11__abort("c11_vector__reserve(): out of memory");
  11628. self->capacity = capacity;
  11629. }
  11630. void c11_vector__clear(c11_vector* self) { self->length = 0; }
  11631. void* c11_vector__emplace(c11_vector* self) {
  11632. if(self->length == self->capacity) { c11_vector__reserve(self, c11_vector__nextcap(self)); }
  11633. void* p = (char*)self->data + (size_t)self->elem_size * (size_t)self->length;
  11634. self->length++;
  11635. return p;
  11636. }
  11637. bool c11_vector__contains(const c11_vector* self, void* elem) {
  11638. for(int i = 0; i < self->length; i++) {
  11639. void* p = (char*)self->data + (size_t)self->elem_size * (size_t)i;
  11640. if(memcmp(p, elem, self->elem_size) == 0) return true;
  11641. }
  11642. return false;
  11643. }
  11644. void* c11_vector__submit(c11_vector* self, int* length) {
  11645. void* retval = self->data;
  11646. *length = self->length;
  11647. self->data = NULL;
  11648. self->length = 0;
  11649. self->capacity = 0;
  11650. return retval;
  11651. }
  11652. void c11_vector__swap(c11_vector* self, c11_vector* other) {
  11653. c11_vector tmp = *self;
  11654. *self = *other;
  11655. *other = tmp;
  11656. }
  11657. int c11_vector__nextcap(c11_vector* self) {
  11658. if(self->capacity < 1024) {
  11659. return self->capacity * 2;
  11660. } else {
  11661. // increase by 25%
  11662. return self->capacity + (self->capacity >> 2);
  11663. }
  11664. }
  11665. void c11_vector__extend(c11_vector* self, const void* p, int size) {
  11666. if (size <= 0) return;
  11667. int min_capacity = self->length + size;
  11668. if(self->capacity < min_capacity) {
  11669. int nextcap = c11_vector__nextcap(self);
  11670. c11_vector__reserve((self), c11__max(nextcap, min_capacity));
  11671. }
  11672. void* dst = (char*)self->data + self->length * self->elem_size;
  11673. memcpy(dst, p, size * self->elem_size);
  11674. self->length += size;
  11675. }
  11676. // src/common\_generated.c
  11677. // generated by prebuild.py
  11678. #include <string.h>
  11679. const char kPythonLibs_bisect[] = "\"\"\"Bisection algorithms.\"\"\"\n\ndef insort_right(a, x, lo=0, hi=None):\n \"\"\"Insert item x in list a, and keep it sorted assuming a is sorted.\n\n If x is already in a, insert it to the right of the rightmost x.\n\n Optional args lo (default 0) and hi (default len(a)) bound the\n slice of a to be searched.\n \"\"\"\n\n lo = bisect_right(a, x, lo, hi)\n a.insert(lo, x)\n\ndef bisect_right(a, x, lo=0, hi=None):\n \"\"\"Return the index where to insert item x in list a, assuming a is sorted.\n\n The return value i is such that all e in a[:i] have e <= x, and all e in\n a[i:] have e > x. So if x already appears in the list, a.insert(x) will\n insert just after the rightmost x already there.\n\n Optional args lo (default 0) and hi (default len(a)) bound the\n slice of a to be searched.\n \"\"\"\n\n if lo < 0:\n raise ValueError('lo must be non-negative')\n if hi is None:\n hi = len(a)\n while lo < hi:\n mid = (lo+hi)//2\n if x < a[mid]: hi = mid\n else: lo = mid+1\n return lo\n\ndef insort_left(a, x, lo=0, hi=None):\n \"\"\"Insert item x in list a, and keep it sorted assuming a is sorted.\n\n If x is already in a, insert it to the left of the leftmost x.\n\n Optional args lo (default 0) and hi (default len(a)) bound the\n slice of a to be searched.\n \"\"\"\n\n lo = bisect_left(a, x, lo, hi)\n a.insert(lo, x)\n\n\ndef bisect_left(a, x, lo=0, hi=None):\n \"\"\"Return the index where to insert item x in list a, assuming a is sorted.\n\n The return value i is such that all e in a[:i] have e < x, and all e in\n a[i:] have e >= x. So if x already appears in the list, a.insert(x) will\n insert just before the leftmost x already there.\n\n Optional args lo (default 0) and hi (default len(a)) bound the\n slice of a to be searched.\n \"\"\"\n\n if lo < 0:\n raise ValueError('lo must be non-negative')\n if hi is None:\n hi = len(a)\n while lo < hi:\n mid = (lo+hi)//2\n if a[mid] < x: lo = mid+1\n else: hi = mid\n return lo\n\n# Create aliases\nbisect = bisect_right\ninsort = insort_right\n";
  11680. const char kPythonLibs_builtins[] = "def all(iterable):\n for i in iterable:\n if not i:\n return False\n return True\n\ndef any(iterable):\n for i in iterable:\n if i:\n return True\n return False\n\ndef enumerate(iterable, start=0):\n n = start\n for elem in iterable:\n yield n, elem\n n += 1\n\ndef __minmax_reduce(op, args):\n if len(args) == 2: # min(1, 2)\n return args[0] if op(args[0], args[1]) else args[1]\n if len(args) == 0: # min()\n raise TypeError('expected 1 arguments, got 0')\n if len(args) == 1: # min([1, 2, 3, 4]) -> min(1, 2, 3, 4)\n args = args[0]\n args = iter(args)\n try:\n res = next(args)\n except StopIteration:\n raise ValueError('args is an empty sequence')\n while True:\n try:\n i = next(args)\n except StopIteration:\n break\n if op(i, res):\n res = i\n return res\n\ndef min(*args, key=None):\n key = key or (lambda x: x)\n return __minmax_reduce(lambda x,y: key(x)<key(y), args)\n\ndef max(*args, key=None):\n key = key or (lambda x: x)\n return __minmax_reduce(lambda x,y: key(x)>key(y), args)\n\ndef sum(iterable):\n res = 0\n for i in iterable:\n res += i\n return res\n\ndef map(f, iterable):\n for i in iterable:\n yield f(i)\n\ndef filter(f, iterable):\n for i in iterable:\n if f(i):\n yield i\n\nclass zip:\n def __init__(self, *iterables):\n self.iterables = [iter(it) for it in iterables]\n\n def __iter__(self):\n return self\n\n def __next__(self):\n result = []\n for it in self.iterables:\n result.append(next(it))\n return tuple(result)\n\ndef reversed(iterable):\n a = list(iterable)\n a.reverse()\n return a\n\ndef sorted(iterable, key=None, reverse=False):\n a = list(iterable)\n a.sort(key=key, reverse=reverse)\n return a\n\n\ndef help(obj):\n if hasattr(obj, '__func__'):\n obj = obj.__func__\n # print(obj.__signature__)\n if obj.__doc__:\n print(obj.__doc__)\n\ndef complex(real, imag=0):\n import cmath\n return cmath.complex(real, imag) # type: ignore\n\ndef dir(obj) -> list[str]:\n tp_module = type(__import__('math'))\n if isinstance(obj, tp_module):\n return [k for k, _ in obj.__dict__.items()]\n names = set()\n if not isinstance(obj, type):\n obj_d = obj.__dict__\n if obj_d is not None:\n names.update([k for k, _ in obj_d.items()])\n cls = type(obj)\n else:\n cls = obj\n while cls is not None:\n names.update([k for k, _ in cls.__dict__.items()])\n cls = cls.__base__\n return sorted(list(names))\n\nclass set:\n def __init__(self, iterable=None):\n iterable = iterable or []\n self._a = {}\n self.update(iterable)\n\n def add(self, elem):\n self._a[elem] = None\n \n def discard(self, elem):\n self._a.pop(elem, None)\n\n def remove(self, elem):\n del self._a[elem]\n \n def clear(self):\n self._a.clear()\n\n def update(self, other):\n for elem in other:\n self.add(elem)\n\n def __len__(self):\n return len(self._a)\n \n def copy(self):\n return set(self._a.keys())\n \n def __and__(self, other):\n return {elem for elem in self if elem in other}\n\n def __sub__(self, other):\n return {elem for elem in self if elem not in other}\n \n def __or__(self, other):\n ret = self.copy()\n ret.update(other)\n return ret\n\n def __xor__(self, other): \n _0 = self - other\n _1 = other - self\n return _0 | _1\n\n def union(self, other):\n return self | other\n\n def intersection(self, other):\n return self & other\n\n def difference(self, other):\n return self - other\n\n def symmetric_difference(self, other): \n return self ^ other\n \n def __eq__(self, other):\n if not isinstance(other, set):\n return NotImplemented\n return len(self ^ other) == 0\n \n def __ne__(self, other):\n if not isinstance(other, set):\n return NotImplemented\n return len(self ^ other) != 0\n\n def isdisjoint(self, other):\n return len(self & other) == 0\n \n def issubset(self, other):\n return len(self - other) == 0\n \n def issuperset(self, other):\n return len(other - self) == 0\n\n def __contains__(self, elem):\n return elem in self._a\n \n def __repr__(self):\n if len(self) == 0:\n return 'set()'\n return '{'+ ', '.join([repr(i) for i in self._a.keys()]) + '}'\n \n def __iter__(self):\n return iter(self._a.keys())";
  11681. const char kPythonLibs_cmath[] = "import math\n\nclass complex:\n def __init__(self, real, imag=0):\n self._real = float(real)\n self._imag = float(imag)\n\n @property\n def real(self):\n return self._real\n \n @property\n def imag(self):\n return self._imag\n\n def conjugate(self):\n return complex(self.real, -self.imag)\n \n def __repr__(self):\n s = ['(', str(self.real)]\n s.append('-' if self.imag < 0 else '+')\n s.append(str(abs(self.imag)))\n s.append('j)')\n return ''.join(s)\n \n def __eq__(self, other):\n if type(other) is complex:\n return self.real == other.real and self.imag == other.imag\n if type(other) in (int, float):\n return self.real == other and self.imag == 0\n return NotImplemented\n \n def __ne__(self, other):\n res = self == other\n if res is NotImplemented:\n return res\n return not res\n \n def __add__(self, other):\n if type(other) is complex:\n return complex(self.real + other.real, self.imag + other.imag)\n if type(other) in (int, float):\n return complex(self.real + other, self.imag)\n return NotImplemented\n \n def __radd__(self, other):\n return self.__add__(other)\n \n def __sub__(self, other):\n if type(other) is complex:\n return complex(self.real - other.real, self.imag - other.imag)\n if type(other) in (int, float):\n return complex(self.real - other, self.imag)\n return NotImplemented\n \n def __rsub__(self, other):\n if type(other) is complex:\n return complex(other.real - self.real, other.imag - self.imag)\n if type(other) in (int, float):\n return complex(other - self.real, -self.imag)\n return NotImplemented\n \n def __mul__(self, other):\n if type(other) is complex:\n return complex(self.real * other.real - self.imag * other.imag,\n self.real * other.imag + self.imag * other.real)\n if type(other) in (int, float):\n return complex(self.real * other, self.imag * other)\n return NotImplemented\n \n def __rmul__(self, other):\n return self.__mul__(other)\n \n def __truediv__(self, other):\n if type(other) is complex:\n denominator = other.real ** 2 + other.imag ** 2\n real_part = (self.real * other.real + self.imag * other.imag) / denominator\n imag_part = (self.imag * other.real - self.real * other.imag) / denominator\n return complex(real_part, imag_part)\n if type(other) in (int, float):\n return complex(self.real / other, self.imag / other)\n return NotImplemented\n \n def __pow__(self, other: int | float):\n if type(other) in (int, float):\n return complex(self.__abs__() ** other * math.cos(other * phase(self)),\n self.__abs__() ** other * math.sin(other * phase(self)))\n return NotImplemented\n \n def __abs__(self) -> float:\n return math.sqrt(self.real ** 2 + self.imag ** 2)\n\n def __neg__(self):\n return complex(-self.real, -self.imag)\n \n def __hash__(self):\n return hash((self.real, self.imag))\n\n\n# Conversions to and from polar coordinates\n\ndef phase(z: complex):\n return math.atan2(z.imag, z.real)\n\ndef polar(z: complex):\n return z.__abs__(), phase(z)\n\ndef rect(r: float, phi: float):\n return r * math.cos(phi) + r * math.sin(phi) * 1j\n\n# Power and logarithmic functions\n\ndef exp(z: complex):\n return math.exp(z.real) * rect(1, z.imag)\n\ndef log(z: complex, base=2.718281828459045):\n return math.log(z.__abs__(), base) + phase(z) * 1j\n\ndef log10(z: complex):\n return log(z, 10)\n\ndef sqrt(z: complex):\n return z ** 0.5\n\n# Trigonometric functions\n\ndef acos(z: complex):\n return -1j * log(z + sqrt(z * z - 1))\n\ndef asin(z: complex):\n return -1j * log(1j * z + sqrt(1 - z * z))\n\ndef atan(z: complex):\n return 1j / 2 * log((1 - 1j * z) / (1 + 1j * z))\n\ndef cos(z: complex):\n return (exp(1j * z) + exp(-1j * z)) / 2\n\ndef sin(z: complex):\n return (exp(1j * z) - exp(-1j * z)) / (2 * 1j)\n\ndef tan(z: complex):\n return sin(z) / cos(z)\n\n# Hyperbolic functions\n\ndef acosh(z: complex):\n return log(z + sqrt(z * z - 1))\n\ndef asinh(z: complex):\n return log(z + sqrt(z * z + 1))\n\ndef atanh(z: complex):\n return 1 / 2 * log((1 + z) / (1 - z))\n\ndef cosh(z: complex):\n return (exp(z) + exp(-z)) / 2\n\ndef sinh(z: complex):\n return (exp(z) - exp(-z)) / 2\n\ndef tanh(z: complex):\n return sinh(z) / cosh(z)\n\n# Classification functions\n\ndef isfinite(z: complex):\n return math.isfinite(z.real) and math.isfinite(z.imag)\n\ndef isinf(z: complex):\n return math.isinf(z.real) or math.isinf(z.imag)\n\ndef isnan(z: complex):\n return math.isnan(z.real) or math.isnan(z.imag)\n\ndef isclose(a: complex, b: complex):\n return math.isclose(a.real, b.real) and math.isclose(a.imag, b.imag)\n\n# Constants\n\npi = math.pi\ne = math.e\ntau = 2 * pi\ninf = math.inf\ninfj = complex(0, inf)\nnan = math.nan\nnanj = complex(0, nan)\n";
  11682. const char kPythonLibs_collections[] = "from typing import TypeVar, Iterable\n\ndef Counter[T](iterable: Iterable[T]):\n a: dict[T, int] = {}\n for x in iterable:\n if x in a:\n a[x] += 1\n else:\n a[x] = 1\n return a\n\n\nclass defaultdict(dict):\n def __init__(self, default_factory, *args):\n super().__init__(*args)\n self.default_factory = default_factory\n\n def __missing__(self, key):\n self[key] = self.default_factory()\n return self[key]\n\n def __repr__(self) -> str:\n return f\"defaultdict({self.default_factory}, {super().__repr__()})\"\n\n def copy(self):\n return defaultdict(self.default_factory, self)\n\n\nclass deque[T]:\n _head: int\n _tail: int\n _maxlen: int | None\n _capacity: int\n _data: list[T]\n\n def __init__(self, iterable: Iterable[T] = None, maxlen: int | None = None):\n if maxlen is not None:\n assert maxlen > 0\n\n self._head = 0\n self._tail = 0\n self._maxlen = maxlen\n self._capacity = 8 if maxlen is None else maxlen + 1\n self._data = [None] * self._capacity # type: ignore\n\n if iterable is not None:\n self.extend(iterable)\n\n @property\n def maxlen(self) -> int | None:\n return self._maxlen\n\n def __resize_2x(self):\n backup = list(self)\n self._capacity *= 2\n self._head = 0\n self._tail = len(backup)\n self._data.clear()\n self._data.extend(backup)\n self._data.extend([None] * (self._capacity - len(backup)))\n\n def append(self, x: T):\n if (self._tail + 1) % self._capacity == self._head:\n if self._maxlen is None:\n self.__resize_2x()\n else:\n self.popleft()\n self._data[self._tail] = x\n self._tail = (self._tail + 1) % self._capacity\n\n def appendleft(self, x: T):\n if (self._tail + 1) % self._capacity == self._head:\n if self._maxlen is None:\n self.__resize_2x()\n else:\n self.pop()\n self._head = (self._head - 1) % self._capacity\n self._data[self._head] = x\n\n def copy(self):\n return deque(self, maxlen=self.maxlen)\n \n def count(self, x: T) -> int:\n n = 0\n for item in self:\n if item == x:\n n += 1\n return n\n \n def extend(self, iterable: Iterable[T]):\n for x in iterable:\n self.append(x)\n\n def extendleft(self, iterable: Iterable[T]):\n for x in iterable:\n self.appendleft(x)\n \n def pop(self) -> T:\n if self._head == self._tail:\n raise IndexError(\"pop from an empty deque\")\n self._tail = (self._tail - 1) % self._capacity\n x = self._data[self._tail]\n self._data[self._tail] = None\n return x\n \n def popleft(self) -> T:\n if self._head == self._tail:\n raise IndexError(\"pop from an empty deque\")\n x = self._data[self._head]\n self._data[self._head] = None\n self._head = (self._head + 1) % self._capacity\n return x\n \n def clear(self):\n i = self._head\n while i != self._tail:\n self._data[i] = None # type: ignore\n i = (i + 1) % self._capacity\n self._head = 0\n self._tail = 0\n\n def rotate(self, n: int = 1):\n if len(self) == 0:\n return\n if n > 0:\n n = n % len(self)\n for _ in range(n):\n self.appendleft(self.pop())\n elif n < 0:\n n = -n % len(self)\n for _ in range(n):\n self.append(self.popleft())\n\n def __len__(self) -> int:\n return (self._tail - self._head) % self._capacity\n\n def __contains__(self, x: object) -> bool:\n for item in self:\n if item == x:\n return True\n return False\n \n def __iter__(self):\n i = self._head\n while i != self._tail:\n yield self._data[i]\n i = (i + 1) % self._capacity\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, deque):\n return NotImplemented\n if len(self) != len(other):\n return False\n for x, y in zip(self, other):\n if x != y:\n return False\n return True\n \n def __ne__(self, other: object) -> bool:\n if not isinstance(other, deque):\n return NotImplemented\n return not self == other\n \n def __repr__(self) -> str:\n if self.maxlen is None:\n return f\"deque({list(self)!r})\"\n return f\"deque({list(self)!r}, maxlen={self.maxlen})\"\n\n";
  11683. const char kPythonLibs_dataclasses[] = "def _get_annotations(cls: type):\n inherits = []\n while cls is not object:\n inherits.append(cls)\n cls = cls.__base__\n inherits.reverse()\n res = {}\n for cls in inherits:\n res.update(cls.__annotations__)\n return res.keys()\n\ndef _wrapped__init__(self, *args, **kwargs):\n cls = type(self)\n cls_d = cls.__dict__\n fields = _get_annotations(cls)\n i = 0 # index into args\n for field in fields:\n if field in kwargs:\n setattr(self, field, kwargs.pop(field))\n else:\n if i < len(args):\n setattr(self, field, args[i])\n i += 1\n elif field in cls_d: # has default value\n setattr(self, field, cls_d[field])\n else:\n raise TypeError(f\"{cls.__name__} missing required argument {field!r}\")\n if len(args) > i:\n raise TypeError(f\"{cls.__name__} takes {len(fields)} positional arguments but {len(args)} were given\")\n if len(kwargs) > 0:\n raise TypeError(f\"{cls.__name__} got an unexpected keyword argument {next(iter(kwargs))!r}\")\n\ndef _wrapped__repr__(self):\n fields = _get_annotations(type(self))\n obj_d = self.__dict__\n args: list = [f\"{field}={obj_d[field]!r}\" for field in fields]\n return f\"{type(self).__name__}({', '.join(args)})\"\n\ndef _wrapped__eq__(self, other):\n if type(self) is not type(other):\n return False\n fields = _get_annotations(type(self))\n for field in fields:\n if getattr(self, field) != getattr(other, field):\n return False\n return True\n\ndef _wrapped__ne__(self, other):\n return not self.__eq__(other)\n\ndef dataclass(cls: type):\n assert type(cls) is type\n cls_d = cls.__dict__\n if '__init__' not in cls_d:\n cls.__init__ = _wrapped__init__\n if '__repr__' not in cls_d:\n cls.__repr__ = _wrapped__repr__\n if '__eq__' not in cls_d:\n cls.__eq__ = _wrapped__eq__\n if '__ne__' not in cls_d:\n cls.__ne__ = _wrapped__ne__\n fields = _get_annotations(cls)\n has_default = False\n for field in fields:\n if field in cls_d:\n has_default = True\n else:\n if has_default:\n raise TypeError(f\"non-default argument {field!r} follows default argument\")\n return cls\n\ndef asdict(obj) -> dict:\n fields = _get_annotations(type(obj))\n obj_d = obj.__dict__\n return {field: obj_d[field] for field in fields}";
  11684. const char kPythonLibs_datetime[] = "from time import localtime\nimport operator\n\nclass timedelta:\n def __init__(self, days=0, seconds=0):\n self.days = days\n self.seconds = seconds\n\n def __repr__(self):\n return f\"datetime.timedelta(days={self.days}, seconds={self.seconds})\"\n\n def __eq__(self, other) -> bool:\n if not isinstance(other, timedelta):\n return NotImplemented\n return (self.days, self.seconds) == (other.days, other.seconds)\n\n def __ne__(self, other) -> bool:\n if not isinstance(other, timedelta):\n return NotImplemented\n return (self.days, self.seconds) != (other.days, other.seconds)\n\n\nclass date:\n def __init__(self, year: int, month: int, day: int):\n self.year = year\n self.month = month\n self.day = day\n\n @staticmethod\n def today():\n t = localtime()\n return date(t.tm_year, t.tm_mon, t.tm_mday)\n \n def __cmp(self, other, op):\n if not isinstance(other, date):\n return NotImplemented\n if self.year != other.year:\n return op(self.year, other.year)\n if self.month != other.month:\n return op(self.month, other.month)\n return op(self.day, other.day)\n\n def __eq__(self, other) -> bool:\n return self.__cmp(other, operator.eq)\n \n def __ne__(self, other) -> bool:\n return self.__cmp(other, operator.ne)\n\n def __lt__(self, other: 'date') -> bool:\n return self.__cmp(other, operator.lt)\n\n def __le__(self, other: 'date') -> bool:\n return self.__cmp(other, operator.le)\n\n def __gt__(self, other: 'date') -> bool:\n return self.__cmp(other, operator.gt)\n\n def __ge__(self, other: 'date') -> bool:\n return self.__cmp(other, operator.ge)\n\n def __str__(self):\n return f\"{self.year}-{self.month:02}-{self.day:02}\"\n\n def __repr__(self):\n return f\"datetime.date({self.year}, {self.month}, {self.day})\"\n\n\nclass datetime(date):\n def __init__(self, year: int, month: int, day: int, hour: int, minute: int, second: int):\n super().__init__(year, month, day)\n # Validate and set hour, minute, and second\n if not 0 <= hour <= 23:\n raise ValueError(\"Hour must be between 0 and 23\")\n self.hour = hour\n if not 0 <= minute <= 59:\n raise ValueError(\"Minute must be between 0 and 59\")\n self.minute = minute\n if not 0 <= second <= 59:\n raise ValueError(\"Second must be between 0 and 59\")\n self.second = second\n\n def date(self) -> date:\n return date(self.year, self.month, self.day)\n\n @staticmethod\n def now():\n t = localtime()\n tm_sec = t.tm_sec\n if tm_sec == 60:\n tm_sec = 59\n return datetime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, tm_sec)\n\n def __str__(self):\n return f\"{self.year}-{self.month:02}-{self.day:02} {self.hour:02}:{self.minute:02}:{self.second:02}\"\n\n def __repr__(self):\n return f\"datetime.datetime({self.year}, {self.month}, {self.day}, {self.hour}, {self.minute}, {self.second})\"\n\n def __cmp(self, other, op):\n if not isinstance(other, datetime):\n return NotImplemented\n if self.year != other.year:\n return op(self.year, other.year)\n if self.month != other.month:\n return op(self.month, other.month)\n if self.day != other.day:\n return op(self.day, other.day)\n if self.hour != other.hour:\n return op(self.hour, other.hour)\n if self.minute != other.minute:\n return op(self.minute, other.minute)\n return op(self.second, other.second)\n\n def __eq__(self, other) -> bool:\n return self.__cmp(other, operator.eq)\n \n def __ne__(self, other) -> bool:\n return self.__cmp(other, operator.ne)\n \n def __lt__(self, other) -> bool:\n return self.__cmp(other, operator.lt)\n \n def __le__(self, other) -> bool:\n return self.__cmp(other, operator.le)\n \n def __gt__(self, other) -> bool:\n return self.__cmp(other, operator.gt)\n \n def __ge__(self, other) -> bool:\n return self.__cmp(other, operator.ge)\n\n\n";
  11685. const char kPythonLibs_functools[] = "class cache:\n def __init__(self, f):\n self.f = f\n self.cache = {}\n\n def __call__(self, *args):\n if args not in self.cache:\n self.cache[args] = self.f(*args)\n return self.cache[args]\n \nclass lru_cache:\n def __init__(self, maxsize=128):\n self.maxsize = maxsize\n self.cache = {}\n\n def __call__(self, f):\n def wrapped(*args):\n if args in self.cache:\n res = self.cache.pop(args)\n self.cache[args] = res\n return res\n \n res = f(*args)\n if len(self.cache) >= self.maxsize:\n first_key = next(iter(self.cache))\n self.cache.pop(first_key)\n self.cache[args] = res\n return res\n return wrapped\n \ndef reduce(function, sequence, initial=...):\n it = iter(sequence)\n if initial is ...:\n try:\n value = next(it)\n except StopIteration:\n raise TypeError(\"reduce() of empty sequence with no initial value\")\n else:\n value = initial\n for element in it:\n value = function(value, element)\n return value\n\nclass partial:\n def __init__(self, f, *args, **kwargs):\n self.f = f\n if not callable(f):\n raise TypeError(\"the first argument must be callable\")\n self.args = args\n self.kwargs = kwargs\n\n def __call__(self, *args, **kwargs):\n kwargs.update(self.kwargs)\n return self.f(*self.args, *args, **kwargs)\n\n";
  11686. const char kPythonLibs_heapq[] = "# Heap queue algorithm (a.k.a. priority queue)\ndef heappush(heap, item):\n \"\"\"Push item onto heap, maintaining the heap invariant.\"\"\"\n heap.append(item)\n _siftdown(heap, 0, len(heap)-1)\n\ndef heappop(heap):\n \"\"\"Pop the smallest item off the heap, maintaining the heap invariant.\"\"\"\n lastelt = heap.pop() # raises appropriate IndexError if heap is empty\n if heap:\n returnitem = heap[0]\n heap[0] = lastelt\n _siftup(heap, 0)\n return returnitem\n return lastelt\n\ndef heapreplace(heap, item):\n \"\"\"Pop and return the current smallest value, and add the new item.\n\n This is more efficient than heappop() followed by heappush(), and can be\n more appropriate when using a fixed-size heap. Note that the value\n returned may be larger than item! That constrains reasonable uses of\n this routine unless written as part of a conditional replacement:\n\n if item > heap[0]:\n item = heapreplace(heap, item)\n \"\"\"\n returnitem = heap[0] # raises appropriate IndexError if heap is empty\n heap[0] = item\n _siftup(heap, 0)\n return returnitem\n\ndef heappushpop(heap, item):\n \"\"\"Fast version of a heappush followed by a heappop.\"\"\"\n if heap and heap[0] < item:\n item, heap[0] = heap[0], item\n _siftup(heap, 0)\n return item\n\ndef heapify(x):\n \"\"\"Transform list into a heap, in-place, in O(len(x)) time.\"\"\"\n n = len(x)\n # Transform bottom-up. The largest index there's any point to looking at\n # is the largest with a child index in-range, so must have 2*i + 1 < n,\n # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so\n # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is\n # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.\n for i in reversed(range(n//2)):\n _siftup(x, i)\n\n# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos\n# is the index of a leaf with a possibly out-of-order value. Restore the\n# heap invariant.\ndef _siftdown(heap, startpos, pos):\n newitem = heap[pos]\n # Follow the path to the root, moving parents down until finding a place\n # newitem fits.\n while pos > startpos:\n parentpos = (pos - 1) >> 1\n parent = heap[parentpos]\n if newitem < parent:\n heap[pos] = parent\n pos = parentpos\n continue\n break\n heap[pos] = newitem\n\ndef _siftup(heap, pos):\n endpos = len(heap)\n startpos = pos\n newitem = heap[pos]\n # Bubble up the smaller child until hitting a leaf.\n childpos = 2*pos + 1 # leftmost child position\n while childpos < endpos:\n # Set childpos to index of smaller child.\n rightpos = childpos + 1\n if rightpos < endpos and not heap[childpos] < heap[rightpos]:\n childpos = rightpos\n # Move the smaller child up.\n heap[pos] = heap[childpos]\n pos = childpos\n childpos = 2*pos + 1\n # The leaf at pos is empty now. Put newitem there, and bubble it up\n # to its final resting place (by sifting its parents down).\n heap[pos] = newitem\n _siftdown(heap, startpos, pos)";
  11687. const char kPythonLibs_inspect[] = "class _empty:\n pass\n\n\nclass Parameter:\n POSITIONAL_ONLY = 0\n POSITIONAL_OR_KEYWORD = 1\n VAR_POSITIONAL = 2\n KEYWORD_ONLY = 3\n VAR_KEYWORD = 4\n\n empty = _empty\n\n def __init__(self, name, kind, *default):\n self.name = name\n self.kind = kind\n # pocketpy only allows literal defaults, so use *default as sentinel\n self.default = default[0] if default else _empty\n\n def __str__(self):\n res = self.name\n if self.default is not _empty:\n res += '=' + repr(self.default)\n if self.kind == Parameter.VAR_POSITIONAL:\n res = '*' + res\n elif self.kind == Parameter.VAR_KEYWORD:\n res = '**' + res\n return res\n\n def __repr__(self):\n return '<Parameter \"' + str(self) + '\">'\n\n\nclass Signature:\n empty = _empty\n\n def __init__(self, parameters):\n self.parameters = {p.name: p for p in parameters}\n\n def __str__(self):\n return '(' + ', '.join([str(p) for p in self.parameters.values()]) + ')'\n\n def __repr__(self):\n return '<Signature ' + str(self) + '>'\n\n\ndef _make_params(func):\n return [Parameter(*entry) for entry in _signature_data(func)]\n\n\ndef signature(obj):\n if not callable(obj):\n raise TypeError(repr(obj) + ' is not a callable object')\n if isinstance(obj, type):\n return Signature(_make_params(obj.__init__)[1:])\n if hasattr(obj, '__func__'):\n return Signature(_make_params(obj.__func__)[1:])\n return Signature(_make_params(obj))\n";
  11688. const char kPythonLibs_long_v1[] = "# after v1.2.2, int is always 64-bit\nPyLong_SHIFT = 60//2 - 1\n\nPyLong_BASE = 2 ** PyLong_SHIFT\nPyLong_MASK = PyLong_BASE - 1\nPyLong_DECIMAL_SHIFT = 4\nPyLong_DECIMAL_BASE = 10 ** PyLong_DECIMAL_SHIFT\n\n##############################################################\n\ndef ulong_fromint(x: int):\n # return a list of digits and sign\n if x == 0: return [0], 1\n sign = 1 if x > 0 else -1\n if sign < 0: x = -x\n res = []\n while x:\n res.append(x & PyLong_MASK)\n x >>= PyLong_SHIFT\n return res, sign\n\ndef ulong_cmp(a: list, b: list) -> int:\n # return 1 if a>b, -1 if a<b, 0 if a==b\n if len(a) > len(b): return 1\n if len(a) < len(b): return -1\n for i in range(len(a)-1, -1, -1):\n if a[i] > b[i]: return 1\n if a[i] < b[i]: return -1\n return 0\n\ndef ulong_pad_(a: list, size: int):\n # pad leading zeros to have `size` digits\n delta = size - len(a)\n if delta > 0:\n a.extend([0] * delta)\n\ndef ulong_unpad_(a: list):\n # remove leading zeros\n while len(a)>1 and a[-1]==0:\n a.pop()\n\ndef ulong_add(a: list, b: list) -> list:\n res = [0] * max(len(a), len(b))\n ulong_pad_(a, len(res))\n ulong_pad_(b, len(res))\n carry = 0\n for i in range(len(res)):\n carry += a[i] + b[i]\n res[i] = carry & PyLong_MASK\n carry >>= PyLong_SHIFT\n if carry > 0:\n res.append(carry)\n return res\n\ndef ulong_inc_(a: list):\n a[0] += 1\n for i in range(len(a)):\n if a[i] < PyLong_BASE: break\n a[i] -= PyLong_BASE\n if i+1 == len(a):\n a.append(1)\n else:\n a[i+1] += 1\n \n\ndef ulong_sub(a: list, b: list) -> list:\n # a >= b\n res = []\n borrow = 0\n for i in range(len(b)):\n tmp = a[i] - b[i] - borrow\n if tmp < 0:\n tmp += PyLong_BASE\n borrow = 1\n else:\n borrow = 0\n res.append(tmp)\n for i in range(len(b), len(a)):\n tmp = a[i] - borrow\n if tmp < 0:\n tmp += PyLong_BASE\n borrow = 1\n else:\n borrow = 0\n res.append(tmp)\n ulong_unpad_(res)\n return res\n\ndef ulong_divmodi(a: list, b: int):\n # b > 0\n res = []\n carry = 0\n for i in range(len(a)-1, -1, -1):\n carry <<= PyLong_SHIFT\n carry += a[i]\n res.append(carry // b)\n carry %= b\n res.reverse()\n ulong_unpad_(res)\n return res, carry\n\n\ndef ulong_divmod(a: list, b: list):\n\n if ulong_cmp(a, b) < 0:\n return [0], a\n\n if len(b) == 1:\n q, r = ulong_divmodi(a, b[0])\n r, _ = ulong_fromint(r)\n return q, r\n\n max = (len(a) - len(b)) * PyLong_SHIFT + \x5c\n (a[-1].bit_length() - b[-1].bit_length())\n\n low = [0]\n\n high = (max // PyLong_SHIFT) * [0] + \x5c\n [(2**(max % PyLong_SHIFT)) & PyLong_MASK]\n\n while ulong_cmp(low, high) < 0:\n ulong_inc_(high)\n mid, r = ulong_divmodi(ulong_add(low, high), 2)\n if ulong_cmp(a, ulong_mul(b, mid)) >= 0:\n low = mid\n else:\n high = ulong_sub(mid, [1])\n\n q = [0] * (len(a) - len(b) + 1)\n while ulong_cmp(a, ulong_mul(b, low)) >= 0:\n q = ulong_add(q, low)\n a = ulong_sub(a, ulong_mul(b, low))\n ulong_unpad_(q)\n return q, a\n\ndef ulong_floordivi(a: list, b: int):\n # b > 0\n return ulong_divmodi(a, b)[0]\n\ndef ulong_muli(a: list, b: int):\n # b >= 0\n res = [0] * len(a)\n carry = 0\n for i in range(len(a)):\n carry += a[i] * b\n res[i] = carry & PyLong_MASK\n carry >>= PyLong_SHIFT\n if carry > 0:\n res.append(carry)\n return res\n\ndef ulong_mul(a: list, b: list):\n N = len(a) + len(b)\n # use grade-school multiplication\n res = [0] * N\n for i in range(len(a)):\n carry = 0\n for j in range(len(b)):\n carry += res[i+j] + a[i] * b[j]\n res[i+j] = carry & PyLong_MASK\n carry >>= PyLong_SHIFT\n res[i+len(b)] = carry\n ulong_unpad_(res)\n return res\n\ndef ulong_powi(a: list, b: int):\n # b >= 0\n if b == 0: return [1]\n res = [1]\n while b:\n if b & 1:\n res = ulong_mul(res, a)\n a = ulong_mul(a, a)\n b >>= 1\n return res\n\ndef ulong_repr(x: list) -> str:\n res = []\n while len(x)>1 or x[0]>0: # non-zero\n x, r = ulong_divmodi(x, PyLong_DECIMAL_BASE)\n res.append(str(r).zfill(PyLong_DECIMAL_SHIFT))\n res.reverse()\n s = ''.join(res)\n if len(s) == 0: return '0'\n if len(s) > 1: s = s.lstrip('0')\n return s\n\ndef ulong_fromstr(s: str):\n if s[-1] == 'L':\n s = s[:-1]\n res, base = [0], [1]\n if s[0] == '-':\n sign = -1\n s = s[1:]\n else:\n sign = 1\n s = s[::-1]\n for c in s:\n c = ord(c) - 48\n assert 0 <= c <= 9\n res = ulong_add(res, ulong_muli(base, c))\n base = ulong_muli(base, 10)\n return res, sign\n\nclass long:\n def __init__(self, x):\n if type(x) is tuple:\n self.digits, self.sign = x\n elif type(x) is int:\n self.digits, self.sign = ulong_fromint(x)\n elif type(x) is float:\n self.digits, self.sign = ulong_fromint(int(x))\n elif type(x) is str:\n self.digits, self.sign = ulong_fromstr(x)\n elif type(x) is long:\n self.digits, self.sign = x.digits.copy(), x.sign\n else:\n raise TypeError('expected int or str')\n \n def __len__(self):\n return len(self.digits)\n\n def __add__(self, other):\n if type(other) is int:\n other = long(other)\n elif type(other) is not long:\n return NotImplemented\n if self.sign == other.sign:\n return long((ulong_add(self.digits, other.digits), self.sign))\n else:\n cmp = ulong_cmp(self.digits, other.digits)\n if cmp == 0:\n return long(0)\n if cmp > 0:\n return long((ulong_sub(self.digits, other.digits), self.sign))\n else:\n return long((ulong_sub(other.digits, self.digits), other.sign))\n \n def __radd__(self, other):\n return self.__add__(other)\n \n def __sub__(self, other):\n if type(other) is int:\n other = long(other)\n elif type(other) is not long:\n return NotImplemented\n if self.sign != other.sign:\n return long((ulong_add(self.digits, other.digits), self.sign))\n cmp = ulong_cmp(self.digits, other.digits)\n if cmp == 0:\n return long(0)\n if cmp > 0:\n return long((ulong_sub(self.digits, other.digits), self.sign))\n else:\n return long((ulong_sub(other.digits, self.digits), -other.sign))\n \n def __rsub__(self, other):\n if type(other) is int:\n other = long(other)\n elif type(other) is not long:\n return NotImplemented\n return other.__sub__(self)\n \n def __mul__(self, other):\n if type(other) is int:\n return long((\n ulong_muli(self.digits, abs(other)),\n self.sign * (1 if other >= 0 else -1)\n ))\n elif type(other) is long:\n return long((\n ulong_mul(self.digits, other.digits),\n self.sign * other.sign\n ))\n return NotImplemented\n \n def __rmul__(self, other):\n return self.__mul__(other)\n \n #######################################################\n def __divmod__(self, other):\n if type(other) is int:\n assert self.sign == 1 and other > 0\n q, r = ulong_divmodi(self.digits, other)\n return long((q, 1)), r\n if type(other) is long:\n assert self.sign == 1 and other.sign == 1\n q, r = ulong_divmod(self.digits, other.digits)\n assert len(other)>1 or other.digits[0]>0\n return long((q, 1)), long((r, 1))\n raise NotImplementedError\n\n def __floordiv__(self, other):\n return self.__divmod__(other)[0]\n\n def __mod__(self, other):\n return self.__divmod__(other)[1]\n\n def __pow__(self, other: int):\n assert type(other) is int and other >= 0\n if self.sign == -1 and other & 1:\n sign = -1\n else:\n sign = 1\n return long((ulong_powi(self.digits, other), sign))\n \n def __lshift__(self, other: int):\n assert type(other) is int and other >= 0\n x = self.digits.copy()\n q, r = divmod(other, PyLong_SHIFT)\n x = [0]*q + x\n for _ in range(r): x = ulong_muli(x, 2)\n return long((x, self.sign))\n \n def __rshift__(self, other: int):\n assert type(other) is int and other >= 0\n x = self.digits.copy()\n q, r = divmod(other, PyLong_SHIFT)\n x = x[q:]\n if not x: return long(0)\n for _ in range(r): x = ulong_floordivi(x, 2)\n return long((x, self.sign))\n \n def __neg__(self):\n return long((self.digits, -self.sign))\n \n def __cmp__(self, other):\n if type(other) is int:\n other = long(other)\n elif type(other) is not long:\n return NotImplemented\n if self.sign > other.sign:\n return 1\n elif self.sign < other.sign:\n return -1\n else:\n return ulong_cmp(self.digits, other.digits)\n \n def __eq__(self, other):\n return self.__cmp__(other) == 0\n def __ne__(self, other):\n return self.__cmp__(other) != 0\n def __lt__(self, other):\n return self.__cmp__(other) < 0\n def __le__(self, other):\n return self.__cmp__(other) <= 0\n def __gt__(self, other):\n return self.__cmp__(other) > 0\n def __ge__(self, other):\n return self.__cmp__(other) >= 0\n \n def __repr__(self):\n prefix = '-' if self.sign < 0 else ''\n return prefix + ulong_repr(self.digits) + 'L'";
  11689. const char kPythonLibs_operator[] = "# https://docs.python.org/3/library/operator.html#mapping-operators-to-functions\n\ndef le(a, b): return a <= b\ndef lt(a, b): return a < b\ndef ge(a, b): return a >= b\ndef gt(a, b): return a > b\ndef eq(a, b): return a == b\ndef ne(a, b): return a != b\n\ndef and_(a, b): return a & b\ndef or_(a, b): return a | b\ndef xor(a, b): return a ^ b\ndef invert(a): return ~a\ndef lshift(a, b): return a << b\ndef rshift(a, b): return a >> b\n\ndef is_(a, b): return a is b\ndef is_not(a, b): return a is not b\ndef not_(a): return not a\ndef truth(a): return bool(a)\ndef contains(a, b): return b in a\n\ndef add(a, b): return a + b\ndef sub(a, b): return a - b\ndef mul(a, b): return a * b\ndef truediv(a, b): return a / b\ndef floordiv(a, b): return a // b\ndef mod(a, b): return a % b\ndef pow(a, b): return a ** b\ndef neg(a): return -a\ndef matmul(a, b): return a @ b\n\ndef getitem(a, b): return a[b]\ndef setitem(a, b, c): a[b] = c\ndef delitem(a, b): del a[b]\n\ndef iadd(a, b): a += b; return a\ndef isub(a, b): a -= b; return a\ndef imul(a, b): a *= b; return a\ndef itruediv(a, b): a /= b; return a\ndef ifloordiv(a, b): a //= b; return a\ndef imod(a, b): a %= b; return a\n# def ipow(a, b): a **= b; return a\n# def imatmul(a, b): a @= b; return a\ndef iand(a, b): a &= b; return a\ndef ior(a, b): a |= b; return a\ndef ixor(a, b): a ^= b; return a\ndef ilshift(a, b): a <<= b; return a\ndef irshift(a, b): a >>= b; return a\n\nclass attrgetter:\n def __init__(self, attr):\n self.attr = attr\n def __call__(self, obj):\n return getattr(obj, self.attr)\n\nclass itemgetter:\n def __init__(self, item):\n self.item = item\n def __call__(self, obj):\n return obj[self.item]\n";
  11690. const char kPythonLibs_typing[] = "class _Placeholder:\n def __init__(self, *args, **kwargs):\n pass\n def __getitem__(self, *args):\n return self\n def __call__(self, *args, **kwargs):\n return self\n def __and__(self, other):\n return self\n def __or__(self, other):\n return self\n def __xor__(self, other):\n return self\n\n\n_PLACEHOLDER = _Placeholder()\n\nSequence = _PLACEHOLDER\nList = _PLACEHOLDER\nDict = _PLACEHOLDER\nTuple = _PLACEHOLDER\nSet = _PLACEHOLDER\nAny = _PLACEHOLDER\nUnion = _PLACEHOLDER\nOptional = _PLACEHOLDER\nCallable = _PLACEHOLDER\nType = _PLACEHOLDER\nTypeAlias = _PLACEHOLDER\nNewType = _PLACEHOLDER\n\nClassVar = _PLACEHOLDER\n\nLiteral = _PLACEHOLDER\nLiteralString = _PLACEHOLDER\n\nIterable = _PLACEHOLDER\nGenerator = _PLACEHOLDER\nIterator = _PLACEHOLDER\n\nHashable = _PLACEHOLDER\n\nTypeVar = _PLACEHOLDER\nParamSpec = _PLACEHOLDER\nSelf = _PLACEHOLDER\n\nProtocol = object\nGeneric = object\nNever = object\n\nTYPE_CHECKING = False\n\n# decorators\noverload = lambda x: x\noverride = lambda x: x\nfinal = lambda x: x\n\n# exhaustiveness checking\nassert_never = lambda x: x\n\nTypedDict = dict\nNotRequired = _PLACEHOLDER\nReadOnly = _PLACEHOLDER\nRequired = _PLACEHOLDER\nTypeIs = _PLACEHOLDER\nTypeGuard = _PLACEHOLDER\n\ncast = lambda _, val: val\n";
  11691. const char* load_kPythonLib(const char* name) {
  11692. if (strchr(name, '.') != NULL) return NULL;
  11693. if (strcmp(name, "bisect") == 0) return kPythonLibs_bisect;
  11694. if (strcmp(name, "builtins") == 0) return kPythonLibs_builtins;
  11695. if (strcmp(name, "cmath") == 0) return kPythonLibs_cmath;
  11696. if (strcmp(name, "collections") == 0) return kPythonLibs_collections;
  11697. if (strcmp(name, "dataclasses") == 0) return kPythonLibs_dataclasses;
  11698. if (strcmp(name, "datetime") == 0) return kPythonLibs_datetime;
  11699. if (strcmp(name, "functools") == 0) return kPythonLibs_functools;
  11700. if (strcmp(name, "heapq") == 0) return kPythonLibs_heapq;
  11701. if (strcmp(name, "inspect") == 0) return kPythonLibs_inspect;
  11702. if (strcmp(name, "long_v1") == 0) return kPythonLibs_long_v1;
  11703. if (strcmp(name, "operator") == 0) return kPythonLibs_operator;
  11704. if (strcmp(name, "typing") == 0) return kPythonLibs_typing;
  11705. return NULL;
  11706. }
  11707. // src/compiler\compiler.c
  11708. #include <assert.h>
  11709. #include <stdbool.h>
  11710. /* expr.h */
  11711. typedef struct Expr Expr;
  11712. typedef struct Ctx Ctx;
  11713. typedef struct ExprVt {
  11714. /* emit */
  11715. void (*emit_)(Expr*, Ctx*);
  11716. bool (*emit_del)(Expr*, Ctx*);
  11717. bool (*emit_store)(Expr*, Ctx*);
  11718. void (*emit_inplace)(Expr*, Ctx*);
  11719. bool (*emit_istore)(Expr*, Ctx*);
  11720. /* reflections */
  11721. bool is_literal;
  11722. bool is_name; // NameExpr
  11723. bool is_tuple; // TupleExpr
  11724. bool is_attrib; // AttribExpr
  11725. bool is_subscr; // SubscrExpr
  11726. bool is_starred; // StarredExpr
  11727. bool is_binary; // BinaryExpr
  11728. bool is_ternary; // TernaryExpr
  11729. void (*dtor)(Expr*);
  11730. } ExprVt;
  11731. #define vtcall(f, self, ctx) ((self)->vt->f((self), (ctx)))
  11732. #define vtemit_(self, ctx) vtcall(emit_, (self), (ctx))
  11733. #define vtemit_del(self, ctx) ((self)->vt->emit_del ? vtcall(emit_del, self, ctx) : false)
  11734. #define vtemit_store(self, ctx) ((self)->vt->emit_store ? vtcall(emit_store, self, ctx) : false)
  11735. #define vtemit_inplace(self, ctx) \
  11736. ((self)->vt->emit_inplace ? vtcall(emit_inplace, self, ctx) : vtemit_(self, ctx))
  11737. #define vtemit_istore(self, ctx) \
  11738. ((self)->vt->emit_istore ? vtcall(emit_istore, self, ctx) : vtemit_store(self, ctx))
  11739. #define vtdelete(self) \
  11740. do { \
  11741. if(self) { \
  11742. if((self)->vt->dtor) (self)->vt->dtor(self); \
  11743. PK_FREE(self); \
  11744. } \
  11745. } while(0)
  11746. #define EXPR_COMMON_HEADER \
  11747. const ExprVt* vt; \
  11748. int line;
  11749. typedef struct Expr {
  11750. EXPR_COMMON_HEADER
  11751. } Expr;
  11752. /* context.h */
  11753. typedef struct Ctx {
  11754. CodeObject* co; // 1 CodeEmitContext <=> 1 CodeObject*
  11755. FuncDecl* func; // optional, weakref
  11756. py_Name n_self;
  11757. int level;
  11758. int curr_iblock;
  11759. bool is_compiling_class;
  11760. c11_vector /*T=Expr_p*/ s_expr;
  11761. c11_smallmap_n2d global_names;
  11762. c11_smallmap_v2d co_consts_string_dedup_map; // this stores 0-based index instead of pointer
  11763. } Ctx;
  11764. typedef struct Expr Expr;
  11765. static void Ctx__ctor(Ctx* self, CodeObject* co, FuncDecl* func, int level, py_Name n_self);
  11766. static void Ctx__dtor(Ctx* self);
  11767. static int Ctx__prepare_loop_divert(Ctx* self, int line, bool is_break);
  11768. static int Ctx__enter_block(Ctx* self, CodeBlockType type);
  11769. static void Ctx__exit_block(Ctx* self);
  11770. static int Ctx__emit_(Ctx* self, Opcode opcode, uint16_t arg, int line);
  11771. static int Ctx__emit_int(Ctx* self, int64_t value, int line);
  11772. static int Ctx__emit_name(Ctx* self, py_Name name, int line);
  11773. static void Ctx__patch_jump(Ctx* self, int index);
  11774. static void Ctx__emit_jump(Ctx* self, int target, int line);
  11775. static int Ctx__add_varname(Ctx* self, py_Name name);
  11776. static int Ctx__add_name(Ctx* self, py_Name name);
  11777. static int Ctx__add_const(Ctx* self, py_Ref);
  11778. static int Ctx__add_const_string(Ctx* self, c11_sv);
  11779. static void Ctx__emit_store_name(Ctx* self, NameScope scope, py_Name name, int line);
  11780. static void Ctx__s_emit_top(Ctx*); // emit top -> pop -> delete
  11781. static void Ctx__s_push(Ctx*, Expr*); // push
  11782. static Expr* Ctx__s_top(Ctx*); // top
  11783. static int Ctx__s_size(Ctx*); // size
  11784. static void Ctx__s_pop(Ctx*); // pop -> delete
  11785. static Expr* Ctx__s_popx(Ctx*); // pop move
  11786. static void Ctx__s_emit_decorators(Ctx*, int count);
  11787. /* expr.c */
  11788. typedef struct NameExpr {
  11789. EXPR_COMMON_HEADER
  11790. py_Name name;
  11791. NameScope scope;
  11792. } NameExpr;
  11793. void NameExpr__emit_(Expr* self_, Ctx* ctx) {
  11794. NameExpr* self = (NameExpr*)self_;
  11795. int index = c11_smallmap_n2d__get(&ctx->co->varnames_inv, self->name, -1);
  11796. if(self->scope == NAME_LOCAL && index >= 0) {
  11797. // we know this is a local variable
  11798. Ctx__emit_(ctx, OP_LOAD_FAST, index, self->line);
  11799. } else {
  11800. Opcode op = ctx->level <= 1 ? OP_LOAD_GLOBAL : OP_LOAD_NONLOCAL;
  11801. if(self->scope == NAME_GLOBAL) {
  11802. if(ctx->co->src->is_dynamic) {
  11803. op = OP_LOAD_NAME;
  11804. } else {
  11805. if(ctx->is_compiling_class) {
  11806. // if we are compiling a class, we should use `OP_LOAD_CLASS_GLOBAL`
  11807. // this is for @property.setter
  11808. op = OP_LOAD_CLASS_GLOBAL;
  11809. }
  11810. }
  11811. }
  11812. Ctx__emit_(ctx, op, Ctx__add_name(ctx, self->name), self->line);
  11813. }
  11814. }
  11815. bool NameExpr__emit_del(Expr* self_, Ctx* ctx) {
  11816. NameExpr* self = (NameExpr*)self_;
  11817. switch(self->scope) {
  11818. case NAME_LOCAL:
  11819. Ctx__emit_(ctx, OP_DELETE_FAST, Ctx__add_varname(ctx, self->name), self->line);
  11820. break;
  11821. case NAME_GLOBAL: {
  11822. Opcode op = ctx->co->src->is_dynamic ? OP_DELETE_NAME : OP_DELETE_GLOBAL;
  11823. Ctx__emit_(ctx, op, Ctx__add_name(ctx, self->name), self->line);
  11824. break;
  11825. }
  11826. default: c11__unreachable();
  11827. }
  11828. return true;
  11829. }
  11830. bool NameExpr__emit_store(Expr* self_, Ctx* ctx) {
  11831. NameExpr* self = (NameExpr*)self_;
  11832. if(ctx->is_compiling_class) {
  11833. Ctx__emit_(ctx, OP_STORE_CLASS_ATTR, Ctx__add_name(ctx, self->name), self->line);
  11834. return true;
  11835. }
  11836. Ctx__emit_store_name(ctx, self->scope, self->name, self->line);
  11837. return true;
  11838. }
  11839. NameExpr* NameExpr__new(int line, py_Name name, NameScope scope) {
  11840. const static ExprVt Vt = {.emit_ = NameExpr__emit_,
  11841. .emit_del = NameExpr__emit_del,
  11842. .emit_store = NameExpr__emit_store,
  11843. .is_name = true};
  11844. NameExpr* self = PK_MALLOC(sizeof(NameExpr));
  11845. self->vt = &Vt;
  11846. self->line = line;
  11847. self->name = name;
  11848. self->scope = scope;
  11849. return self;
  11850. }
  11851. typedef struct StarredExpr {
  11852. EXPR_COMMON_HEADER
  11853. Expr* child;
  11854. int level;
  11855. } StarredExpr;
  11856. void StarredExpr__emit_(Expr* self_, Ctx* ctx) {
  11857. StarredExpr* self = (StarredExpr*)self_;
  11858. vtemit_(self->child, ctx);
  11859. Ctx__emit_(ctx, OP_UNARY_STAR, self->level, self->line);
  11860. }
  11861. bool StarredExpr__emit_store(Expr* self_, Ctx* ctx) {
  11862. StarredExpr* self = (StarredExpr*)self_;
  11863. if(self->level != 1) return false;
  11864. // simply proxy to child
  11865. return vtemit_store(self->child, ctx);
  11866. }
  11867. void StarredExpr__dtor(Expr* self_) {
  11868. StarredExpr* self = (StarredExpr*)self_;
  11869. vtdelete(self->child);
  11870. }
  11871. StarredExpr* StarredExpr__new(int line, Expr* child, int level) {
  11872. const static ExprVt Vt = {.emit_ = StarredExpr__emit_,
  11873. .emit_store = StarredExpr__emit_store,
  11874. .is_starred = true,
  11875. .dtor = StarredExpr__dtor};
  11876. StarredExpr* self = PK_MALLOC(sizeof(StarredExpr));
  11877. self->vt = &Vt;
  11878. self->line = line;
  11879. self->child = child;
  11880. self->level = level;
  11881. return self;
  11882. }
  11883. // InvertExpr, NotExpr, NegatedExpr
  11884. // NOTE: NegatedExpr always contains a non-const child. Should not generate -1 or -0.1
  11885. typedef struct UnaryExpr {
  11886. EXPR_COMMON_HEADER
  11887. Expr* child;
  11888. Opcode opcode;
  11889. } UnaryExpr;
  11890. void UnaryExpr__dtor(Expr* self_) {
  11891. UnaryExpr* self = (UnaryExpr*)self_;
  11892. vtdelete(self->child);
  11893. }
  11894. static void UnaryExpr__emit_(Expr* self_, Ctx* ctx) {
  11895. UnaryExpr* self = (UnaryExpr*)self_;
  11896. vtemit_(self->child, ctx);
  11897. Ctx__emit_(ctx, self->opcode, BC_NOARG, self->line);
  11898. }
  11899. UnaryExpr* UnaryExpr__new(int line, Expr* child, Opcode opcode) {
  11900. const static ExprVt Vt = {.emit_ = UnaryExpr__emit_, .dtor = UnaryExpr__dtor};
  11901. UnaryExpr* self = PK_MALLOC(sizeof(UnaryExpr));
  11902. self->vt = &Vt;
  11903. self->line = line;
  11904. self->child = child;
  11905. self->opcode = opcode;
  11906. return self;
  11907. }
  11908. typedef struct FStringSpecExpr {
  11909. EXPR_COMMON_HEADER
  11910. Expr* child;
  11911. c11_sv spec;
  11912. } FStringSpecExpr;
  11913. void FStringSpecExpr__emit_(Expr* self_, Ctx* ctx) {
  11914. FStringSpecExpr* self = (FStringSpecExpr*)self_;
  11915. vtemit_(self->child, ctx);
  11916. int index = Ctx__add_const_string(ctx, self->spec);
  11917. Ctx__emit_(ctx, OP_FORMAT_STRING, index, self->line);
  11918. }
  11919. FStringSpecExpr* FStringSpecExpr__new(int line, Expr* child, c11_sv spec) {
  11920. const static ExprVt Vt = {.emit_ = FStringSpecExpr__emit_, .dtor = UnaryExpr__dtor};
  11921. FStringSpecExpr* self = PK_MALLOC(sizeof(FStringSpecExpr));
  11922. self->vt = &Vt;
  11923. self->line = line;
  11924. self->child = child;
  11925. self->spec = spec;
  11926. return self;
  11927. }
  11928. typedef struct RawStringExpr {
  11929. EXPR_COMMON_HEADER
  11930. c11_sv value;
  11931. Opcode opcode;
  11932. } RawStringExpr;
  11933. void RawStringExpr__emit_(Expr* self_, Ctx* ctx) {
  11934. RawStringExpr* self = (RawStringExpr*)self_;
  11935. int index = Ctx__add_const_string(ctx, self->value);
  11936. Ctx__emit_(ctx, self->opcode, index, self->line);
  11937. }
  11938. RawStringExpr* RawStringExpr__new(int line, c11_sv value, Opcode opcode) {
  11939. const static ExprVt Vt = {.emit_ = RawStringExpr__emit_};
  11940. RawStringExpr* self = PK_MALLOC(sizeof(RawStringExpr));
  11941. self->vt = &Vt;
  11942. self->line = line;
  11943. self->value = value;
  11944. self->opcode = opcode;
  11945. return self;
  11946. }
  11947. typedef struct ImagExpr {
  11948. EXPR_COMMON_HEADER
  11949. double value;
  11950. } ImagExpr;
  11951. void ImagExpr__emit_(Expr* self_, Ctx* ctx) {
  11952. ImagExpr* self = (ImagExpr*)self_;
  11953. py_TValue value;
  11954. py_newfloat(&value, self->value);
  11955. int index = Ctx__add_const(ctx, &value);
  11956. Ctx__emit_(ctx, OP_LOAD_CONST, index, self->line);
  11957. Ctx__emit_(ctx, OP_BUILD_IMAG, BC_NOARG, self->line);
  11958. }
  11959. ImagExpr* ImagExpr__new(int line, double value) {
  11960. const static ExprVt Vt = {.emit_ = ImagExpr__emit_};
  11961. ImagExpr* self = PK_MALLOC(sizeof(ImagExpr));
  11962. self->vt = &Vt;
  11963. self->line = line;
  11964. self->value = value;
  11965. return self;
  11966. }
  11967. typedef struct LiteralExpr {
  11968. EXPR_COMMON_HEADER
  11969. const TokenValue* value;
  11970. bool negated;
  11971. } LiteralExpr;
  11972. void LiteralExpr__emit_(Expr* self_, Ctx* ctx) {
  11973. LiteralExpr* self = (LiteralExpr*)self_;
  11974. switch(self->value->index) {
  11975. case TokenValue_I64: {
  11976. py_i64 val = self->value->_i64;
  11977. if(self->negated) val = -val;
  11978. Ctx__emit_int(ctx, val, self->line);
  11979. break;
  11980. }
  11981. case TokenValue_F64: {
  11982. py_TValue value;
  11983. py_f64 val = self->value->_f64;
  11984. if(self->negated) val = -val;
  11985. py_newfloat(&value, val);
  11986. int index = Ctx__add_const(ctx, &value);
  11987. Ctx__emit_(ctx, OP_LOAD_CONST, index, self->line);
  11988. break;
  11989. }
  11990. case TokenValue_STR: {
  11991. assert(!self->negated);
  11992. c11_sv sv = c11_string__sv(self->value->_str);
  11993. int index = Ctx__add_const_string(ctx, sv);
  11994. Ctx__emit_(ctx, OP_LOAD_CONST, index, self->line);
  11995. break;
  11996. }
  11997. default: c11__unreachable();
  11998. }
  11999. }
  12000. LiteralExpr* LiteralExpr__new(int line, const TokenValue* value) {
  12001. const static ExprVt Vt = {.emit_ = LiteralExpr__emit_, .is_literal = true};
  12002. LiteralExpr* self = PK_MALLOC(sizeof(LiteralExpr));
  12003. self->vt = &Vt;
  12004. self->line = line;
  12005. self->value = value;
  12006. self->negated = false;
  12007. return self;
  12008. }
  12009. typedef struct Literal0Expr {
  12010. EXPR_COMMON_HEADER
  12011. TokenIndex token;
  12012. } Literal0Expr;
  12013. void Literal0Expr__emit_(Expr* self_, Ctx* ctx) {
  12014. Literal0Expr* self = (Literal0Expr*)self_;
  12015. Opcode opcode;
  12016. switch(self->token) {
  12017. case TK_NONE: opcode = OP_LOAD_NONE; break;
  12018. case TK_TRUE: opcode = OP_LOAD_TRUE; break;
  12019. case TK_FALSE: opcode = OP_LOAD_FALSE; break;
  12020. case TK_DOTDOTDOT: opcode = OP_LOAD_ELLIPSIS; break;
  12021. default: c11__unreachable();
  12022. }
  12023. Ctx__emit_(ctx, opcode, BC_NOARG, self->line);
  12024. }
  12025. Literal0Expr* Literal0Expr__new(int line, TokenIndex token) {
  12026. const static ExprVt Vt = {.emit_ = Literal0Expr__emit_};
  12027. Literal0Expr* self = PK_MALLOC(sizeof(Literal0Expr));
  12028. self->vt = &Vt;
  12029. self->line = line;
  12030. self->token = token;
  12031. return self;
  12032. }
  12033. typedef struct LoadConstExpr {
  12034. EXPR_COMMON_HEADER
  12035. int index;
  12036. } LoadConstExpr;
  12037. void LoadConstExpr__emit_(Expr* self_, Ctx* ctx) {
  12038. LoadConstExpr* self = (LoadConstExpr*)self_;
  12039. Ctx__emit_(ctx, OP_LOAD_CONST, self->index, self->line);
  12040. }
  12041. LoadConstExpr* LoadConstExpr__new(int line, int index) {
  12042. const static ExprVt Vt = {.emit_ = LoadConstExpr__emit_};
  12043. LoadConstExpr* self = PK_MALLOC(sizeof(LoadConstExpr));
  12044. self->vt = &Vt;
  12045. self->line = line;
  12046. self->index = index;
  12047. return self;
  12048. }
  12049. typedef struct SliceExpr {
  12050. EXPR_COMMON_HEADER
  12051. Expr* start;
  12052. Expr* stop;
  12053. Expr* step;
  12054. } SliceExpr;
  12055. void SliceExpr__dtor(Expr* self_) {
  12056. SliceExpr* self = (SliceExpr*)self_;
  12057. vtdelete(self->start);
  12058. vtdelete(self->stop);
  12059. vtdelete(self->step);
  12060. }
  12061. void SliceExpr__emit_(Expr* self_, Ctx* ctx) {
  12062. SliceExpr* self = (SliceExpr*)self_;
  12063. if(self->start)
  12064. vtemit_(self->start, ctx);
  12065. else
  12066. Ctx__emit_(ctx, OP_LOAD_NONE, BC_NOARG, self->line);
  12067. if(self->stop)
  12068. vtemit_(self->stop, ctx);
  12069. else
  12070. Ctx__emit_(ctx, OP_LOAD_NONE, BC_NOARG, self->line);
  12071. if(self->step)
  12072. vtemit_(self->step, ctx);
  12073. else
  12074. Ctx__emit_(ctx, OP_LOAD_NONE, BC_NOARG, self->line);
  12075. Ctx__emit_(ctx, OP_BUILD_SLICE, BC_NOARG, self->line);
  12076. }
  12077. SliceExpr* SliceExpr__new(int line) {
  12078. const static ExprVt Vt = {.dtor = SliceExpr__dtor, .emit_ = SliceExpr__emit_};
  12079. SliceExpr* self = PK_MALLOC(sizeof(SliceExpr));
  12080. self->vt = &Vt;
  12081. self->line = line;
  12082. self->start = NULL;
  12083. self->stop = NULL;
  12084. self->step = NULL;
  12085. return self;
  12086. }
  12087. typedef struct DictItemExpr {
  12088. EXPR_COMMON_HEADER
  12089. Expr* key;
  12090. Expr* value;
  12091. } DictItemExpr;
  12092. static void DictItemExpr__dtor(Expr* self_) {
  12093. DictItemExpr* self = (DictItemExpr*)self_;
  12094. vtdelete(self->key);
  12095. vtdelete(self->value);
  12096. }
  12097. static void DictItemExpr__emit_(Expr* self_, Ctx* ctx) {
  12098. DictItemExpr* self = (DictItemExpr*)self_;
  12099. vtemit_(self->key, ctx);
  12100. vtemit_(self->value, ctx);
  12101. }
  12102. static DictItemExpr* DictItemExpr__new(int line) {
  12103. const static ExprVt Vt = {.dtor = DictItemExpr__dtor, .emit_ = DictItemExpr__emit_};
  12104. DictItemExpr* self = PK_MALLOC(sizeof(DictItemExpr));
  12105. self->vt = &Vt;
  12106. self->line = line;
  12107. self->key = NULL;
  12108. self->value = NULL;
  12109. return self;
  12110. }
  12111. // ListExpr, DictExpr, SetExpr, TupleExpr
  12112. typedef struct SequenceExpr {
  12113. EXPR_COMMON_HEADER
  12114. Expr** items;
  12115. int itemCount;
  12116. Opcode opcode;
  12117. } SequenceExpr;
  12118. static void SequenceExpr__emit_(Expr* self_, Ctx* ctx) {
  12119. SequenceExpr* self = (SequenceExpr*)self_;
  12120. for(int i = 0; i < self->itemCount; i++) {
  12121. Expr* item = self->items[i];
  12122. vtemit_(item, ctx);
  12123. }
  12124. Ctx__emit_(ctx, self->opcode, self->itemCount, self->line);
  12125. }
  12126. void SequenceExpr__dtor(Expr* self_) {
  12127. SequenceExpr* self = (SequenceExpr*)self_;
  12128. for(int i = 0; i < self->itemCount; i++) {
  12129. vtdelete(self->items[i]);
  12130. }
  12131. PK_FREE(self->items);
  12132. }
  12133. bool TupleExpr__emit_store(Expr* self_, Ctx* ctx) {
  12134. SequenceExpr* self = (SequenceExpr*)self_;
  12135. // TOS is an iterable
  12136. // items may contain StarredExpr, we should check it
  12137. int starred_i = -1;
  12138. for(int i = 0; i < self->itemCount; i++) {
  12139. Expr* e = self->items[i];
  12140. if(e->vt->is_starred) {
  12141. if(((StarredExpr*)e)->level > 0) {
  12142. if(starred_i == -1)
  12143. starred_i = i;
  12144. else
  12145. return false; // multiple StarredExpr not allowed
  12146. }
  12147. }
  12148. }
  12149. if(starred_i == -1) {
  12150. Ctx__emit_(ctx, OP_UNPACK_SEQUENCE, self->itemCount, self->line);
  12151. } else {
  12152. // starred assignment target must be in a tuple
  12153. if(self->itemCount == 1) return false;
  12154. // starred assignment target must be the last one (differ from cpython)
  12155. if(starred_i != self->itemCount - 1) return false;
  12156. // a,*b = [1,2,3]
  12157. // stack is [1,2,3] -> [1,[2,3]]
  12158. Ctx__emit_(ctx, OP_UNPACK_EX, self->itemCount - 1, self->line);
  12159. }
  12160. // do reverse emit
  12161. for(int i = self->itemCount - 1; i >= 0; i--) {
  12162. Expr* e = self->items[i];
  12163. bool ok = vtemit_store(e, ctx);
  12164. if(!ok) return false;
  12165. }
  12166. return true;
  12167. }
  12168. bool TupleExpr__emit_del(Expr* self_, Ctx* ctx) {
  12169. SequenceExpr* self = (SequenceExpr*)self_;
  12170. for(int i = 0; i < self->itemCount; i++) {
  12171. Expr* e = self->items[i];
  12172. bool ok = vtemit_del(e, ctx);
  12173. if(!ok) return false;
  12174. }
  12175. return true;
  12176. }
  12177. static SequenceExpr* SequenceExpr__new(int line, const ExprVt* vt, int count, Opcode opcode) {
  12178. SequenceExpr* self = PK_MALLOC(sizeof(SequenceExpr));
  12179. self->vt = vt;
  12180. self->line = line;
  12181. self->opcode = opcode;
  12182. self->items = PK_MALLOC(sizeof(Expr*) * count);
  12183. self->itemCount = count;
  12184. return self;
  12185. }
  12186. SequenceExpr* FStringExpr__new(int line, int count) {
  12187. const static ExprVt ListExprVt = {.dtor = SequenceExpr__dtor, .emit_ = SequenceExpr__emit_};
  12188. return SequenceExpr__new(line, &ListExprVt, count, OP_BUILD_STRING);
  12189. }
  12190. SequenceExpr* ListExpr__new(int line, int count) {
  12191. const static ExprVt ListExprVt = {.dtor = SequenceExpr__dtor, .emit_ = SequenceExpr__emit_};
  12192. return SequenceExpr__new(line, &ListExprVt, count, OP_BUILD_LIST);
  12193. }
  12194. SequenceExpr* DictExpr__new(int line, int count) {
  12195. const static ExprVt DictExprVt = {.dtor = SequenceExpr__dtor, .emit_ = SequenceExpr__emit_};
  12196. return SequenceExpr__new(line, &DictExprVt, count, OP_BUILD_DICT);
  12197. }
  12198. SequenceExpr* SetExpr__new(int line, int count) {
  12199. const static ExprVt SetExprVt = {
  12200. .dtor = SequenceExpr__dtor,
  12201. .emit_ = SequenceExpr__emit_,
  12202. };
  12203. return SequenceExpr__new(line, &SetExprVt, count, OP_BUILD_SET);
  12204. }
  12205. SequenceExpr* TupleExpr__new(int line, int count) {
  12206. const static ExprVt TupleExprVt = {.dtor = SequenceExpr__dtor,
  12207. .emit_ = SequenceExpr__emit_,
  12208. .is_tuple = true,
  12209. .emit_store = TupleExpr__emit_store,
  12210. .emit_del = TupleExpr__emit_del};
  12211. return SequenceExpr__new(line, &TupleExprVt, count, OP_BUILD_TUPLE);
  12212. }
  12213. typedef struct CompExpr {
  12214. EXPR_COMMON_HEADER
  12215. Expr* expr; // loop expr
  12216. Expr* vars; // loop vars
  12217. Expr* iter; // loop iter
  12218. Expr* cond; // optional if condition
  12219. Opcode op0;
  12220. Opcode op1;
  12221. bool as_iter; // LYNX: a generator expression (evaluated eagerly as a list, then iter())
  12222. } CompExpr;
  12223. void CompExpr__dtor(Expr* self_) {
  12224. CompExpr* self = (CompExpr*)self_;
  12225. vtdelete(self->expr);
  12226. vtdelete(self->vars);
  12227. vtdelete(self->iter);
  12228. vtdelete(self->cond);
  12229. }
  12230. void CompExpr__emit_(Expr* self_, Ctx* ctx) {
  12231. CompExpr* self = (CompExpr*)self_;
  12232. Ctx__emit_(ctx, self->op0, 0, self->line);
  12233. vtemit_(self->iter, ctx);
  12234. Ctx__emit_(ctx, OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  12235. int block = Ctx__enter_block(ctx, CodeBlockType_FOR_LOOP);
  12236. int block_start = Ctx__emit_(ctx, OP_FOR_ITER, block, BC_KEEPLINE);
  12237. bool ok = vtemit_store(self->vars, ctx);
  12238. // this error occurs in `vars` instead of this line, but...nevermind
  12239. assert(ok); // this should raise a SyntaxError, but we just assert it
  12240. if(self->cond) {
  12241. vtemit_(self->cond, ctx);
  12242. int patch = Ctx__emit_(ctx, OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  12243. vtemit_(self->expr, ctx);
  12244. Ctx__emit_(ctx, self->op1, BC_NOARG, BC_KEEPLINE);
  12245. Ctx__patch_jump(ctx, patch);
  12246. } else {
  12247. vtemit_(self->expr, ctx);
  12248. Ctx__emit_(ctx, self->op1, BC_NOARG, BC_KEEPLINE);
  12249. }
  12250. Ctx__emit_jump(ctx, block_start, BC_KEEPLINE);
  12251. Ctx__exit_block(ctx);
  12252. if(self->as_iter) Ctx__emit_(ctx, OP_GET_ITER, BC_NOARG, BC_KEEPLINE); // LYNX
  12253. }
  12254. CompExpr* CompExpr__new(int line, Opcode op0, Opcode op1) {
  12255. const static ExprVt Vt = {.dtor = CompExpr__dtor, .emit_ = CompExpr__emit_};
  12256. CompExpr* self = PK_MALLOC(sizeof(CompExpr));
  12257. self->vt = &Vt;
  12258. self->line = line;
  12259. self->op0 = op0;
  12260. self->op1 = op1;
  12261. self->expr = NULL;
  12262. self->vars = NULL;
  12263. self->iter = NULL;
  12264. self->cond = NULL;
  12265. self->as_iter = false;
  12266. return self;
  12267. }
  12268. typedef struct LambdaExpr {
  12269. EXPR_COMMON_HEADER
  12270. int index;
  12271. } LambdaExpr;
  12272. static void LambdaExpr__emit_(Expr* self_, Ctx* ctx) {
  12273. LambdaExpr* self = (LambdaExpr*)self_;
  12274. Ctx__emit_(ctx, OP_LOAD_FUNCTION, self->index, self->line);
  12275. }
  12276. LambdaExpr* LambdaExpr__new(int line, int index) {
  12277. const static ExprVt Vt = {.emit_ = LambdaExpr__emit_};
  12278. LambdaExpr* self = PK_MALLOC(sizeof(LambdaExpr));
  12279. self->vt = &Vt;
  12280. self->line = line;
  12281. self->index = index;
  12282. return self;
  12283. }
  12284. // AndExpr, OrExpr
  12285. typedef struct LogicBinaryExpr {
  12286. EXPR_COMMON_HEADER
  12287. Expr* lhs;
  12288. Expr* rhs;
  12289. Opcode opcode;
  12290. } LogicBinaryExpr;
  12291. void LogicBinaryExpr__dtor(Expr* self_) {
  12292. LogicBinaryExpr* self = (LogicBinaryExpr*)self_;
  12293. vtdelete(self->lhs);
  12294. vtdelete(self->rhs);
  12295. }
  12296. void LogicBinaryExpr__emit_(Expr* self_, Ctx* ctx) {
  12297. LogicBinaryExpr* self = (LogicBinaryExpr*)self_;
  12298. vtemit_(self->lhs, ctx);
  12299. int patch = Ctx__emit_(ctx, self->opcode, BC_NOARG, self->line);
  12300. vtemit_(self->rhs, ctx);
  12301. Ctx__patch_jump(ctx, patch);
  12302. }
  12303. LogicBinaryExpr* LogicBinaryExpr__new(int line, Opcode opcode) {
  12304. const static ExprVt Vt = {.emit_ = LogicBinaryExpr__emit_, .dtor = LogicBinaryExpr__dtor};
  12305. LogicBinaryExpr* self = PK_MALLOC(sizeof(LogicBinaryExpr));
  12306. self->vt = &Vt;
  12307. self->line = line;
  12308. self->lhs = NULL;
  12309. self->rhs = NULL;
  12310. self->opcode = opcode;
  12311. return self;
  12312. }
  12313. typedef struct GroupedExpr {
  12314. EXPR_COMMON_HEADER
  12315. Expr* child;
  12316. } GroupedExpr;
  12317. void GroupedExpr__dtor(Expr* self_) {
  12318. GroupedExpr* self = (GroupedExpr*)self_;
  12319. vtdelete(self->child);
  12320. }
  12321. void GroupedExpr__emit_(Expr* self_, Ctx* ctx) {
  12322. GroupedExpr* self = (GroupedExpr*)self_;
  12323. vtemit_(self->child, ctx);
  12324. }
  12325. bool GroupedExpr__emit_del(Expr* self_, Ctx* ctx) {
  12326. GroupedExpr* self = (GroupedExpr*)self_;
  12327. return vtemit_del(self->child, ctx);
  12328. }
  12329. bool GroupedExpr__emit_store(Expr* self_, Ctx* ctx) {
  12330. GroupedExpr* self = (GroupedExpr*)self_;
  12331. return vtemit_store(self->child, ctx);
  12332. }
  12333. GroupedExpr* GroupedExpr__new(int line, Expr* child) {
  12334. const static ExprVt Vt = {.dtor = GroupedExpr__dtor,
  12335. .emit_ = GroupedExpr__emit_,
  12336. .emit_del = GroupedExpr__emit_del,
  12337. .emit_store = GroupedExpr__emit_store};
  12338. GroupedExpr* self = PK_MALLOC(sizeof(GroupedExpr));
  12339. self->vt = &Vt;
  12340. self->line = line;
  12341. self->child = child;
  12342. return self;
  12343. }
  12344. // NamedExpr: walrus operator (x := expr)
  12345. typedef struct NamedExpr {
  12346. EXPR_COMMON_HEADER
  12347. NameExpr* name;
  12348. Expr* rhs;
  12349. } NamedExpr;
  12350. static void NamedExpr__dtor(Expr* self_) {
  12351. NamedExpr* self = (NamedExpr*)self_;
  12352. vtdelete((Expr*)self->name);
  12353. vtdelete(self->rhs);
  12354. }
  12355. static void NamedExpr__emit_(Expr* self_, Ctx* ctx) {
  12356. NamedExpr* self = (NamedExpr*)self_;
  12357. vtemit_(self->rhs, ctx); // [value]
  12358. Ctx__emit_(ctx, OP_DUP_TOP, BC_NOARG, self->line); // [value, value]
  12359. vtemit_store((Expr*)self->name, ctx); // [value]
  12360. }
  12361. static NamedExpr* NamedExpr__new(int line, NameExpr* name, Expr* rhs) {
  12362. const static ExprVt Vt = {.dtor = NamedExpr__dtor, .emit_ = NamedExpr__emit_};
  12363. NamedExpr* self = PK_MALLOC(sizeof(NamedExpr));
  12364. self->vt = &Vt;
  12365. self->line = line;
  12366. self->name = name;
  12367. self->rhs = rhs;
  12368. return self;
  12369. }
  12370. typedef struct BinaryExpr {
  12371. EXPR_COMMON_HEADER
  12372. Expr* lhs;
  12373. Expr* rhs;
  12374. TokenIndex op;
  12375. bool inplace;
  12376. } BinaryExpr;
  12377. static void BinaryExpr__dtor(Expr* self_) {
  12378. BinaryExpr* self = (BinaryExpr*)self_;
  12379. vtdelete(self->lhs);
  12380. vtdelete(self->rhs);
  12381. }
  12382. static Opcode cmp_token2op(TokenIndex token) {
  12383. switch(token) {
  12384. case TK_LT: return OP_COMPARE_LT;
  12385. case TK_LE: return OP_COMPARE_LE;
  12386. case TK_EQ: return OP_COMPARE_EQ;
  12387. case TK_NE: return OP_COMPARE_NE;
  12388. case TK_GT: return OP_COMPARE_GT;
  12389. case TK_GE: return OP_COMPARE_GE;
  12390. default: return 0;
  12391. }
  12392. }
  12393. #define is_compare_expr(e) ((e)->vt->is_binary && cmp_token2op(((BinaryExpr*)(e))->op))
  12394. static void _emit_compare(BinaryExpr* self, Ctx* ctx, c11_vector* jmps) {
  12395. if(is_compare_expr(self->lhs)) {
  12396. _emit_compare((BinaryExpr*)self->lhs, ctx, jmps);
  12397. } else {
  12398. vtemit_(self->lhs, ctx); // [a]
  12399. }
  12400. vtemit_(self->rhs, ctx); // [a, b]
  12401. Ctx__emit_(ctx, OP_DUP_TOP, BC_NOARG, self->line); // [a, b, b]
  12402. Ctx__emit_(ctx, OP_ROT_THREE, BC_NOARG, self->line); // [b, a, b]
  12403. Ctx__emit_(ctx, cmp_token2op(self->op), BC_NOARG, self->line);
  12404. // [b, RES]
  12405. int index = Ctx__emit_(ctx, OP_SHORTCUT_IF_FALSE_OR_POP, BC_NOARG, self->line);
  12406. c11_vector__push(int, jmps, index);
  12407. }
  12408. static void BinaryExpr__emit_(Expr* self_, Ctx* ctx) {
  12409. BinaryExpr* self = (BinaryExpr*)self_;
  12410. c11_vector /*T=int*/ jmps;
  12411. c11_vector__ctor(&jmps, sizeof(int));
  12412. if(cmp_token2op(self->op) && is_compare_expr(self->lhs)) {
  12413. // (a < b) < c
  12414. BinaryExpr* e = (BinaryExpr*)self->lhs;
  12415. _emit_compare(e, ctx, &jmps);
  12416. // [b, RES]
  12417. } else {
  12418. // (1 + 2) < c
  12419. if(self->inplace) {
  12420. vtemit_inplace(self->lhs, ctx);
  12421. } else {
  12422. vtemit_(self->lhs, ctx);
  12423. }
  12424. }
  12425. vtemit_(self->rhs, ctx);
  12426. Opcode opcode;
  12427. uint16_t arg = BC_NOARG;
  12428. switch(self->op) {
  12429. case TK_ADD: opcode = OP_BINARY_ADD; break;
  12430. case TK_SUB: opcode = OP_BINARY_SUB; break;
  12431. case TK_MUL: opcode = OP_BINARY_MUL; break;
  12432. case TK_DIV: opcode = OP_BINARY_TRUEDIV; break;
  12433. case TK_FLOORDIV: opcode = OP_BINARY_FLOORDIV; break;
  12434. case TK_MOD: opcode = OP_BINARY_MOD; break;
  12435. case TK_POW: opcode = OP_BINARY_POW; break;
  12436. case TK_LT: opcode = OP_COMPARE_LT; break;
  12437. case TK_LE: opcode = OP_COMPARE_LE; break;
  12438. case TK_EQ: opcode = OP_COMPARE_EQ; break;
  12439. case TK_NE: opcode = OP_COMPARE_NE; break;
  12440. case TK_GT: opcode = OP_COMPARE_GT; break;
  12441. case TK_GE: opcode = OP_COMPARE_GE; break;
  12442. case TK_IN:
  12443. opcode = OP_CONTAINS_OP;
  12444. arg = 0;
  12445. break;
  12446. case TK_NOT_IN:
  12447. opcode = OP_CONTAINS_OP;
  12448. arg = 1;
  12449. break;
  12450. case TK_IS:
  12451. opcode = OP_IS_OP;
  12452. arg = 0;
  12453. break;
  12454. case TK_IS_NOT:
  12455. opcode = OP_IS_OP;
  12456. arg = 1;
  12457. break;
  12458. case TK_LSHIFT: opcode = OP_BINARY_LSHIFT; break;
  12459. case TK_RSHIFT: opcode = OP_BINARY_RSHIFT; break;
  12460. case TK_AND: opcode = OP_BINARY_AND; break;
  12461. case TK_OR: opcode = OP_BINARY_OR; break;
  12462. case TK_XOR: opcode = OP_BINARY_XOR; break;
  12463. case TK_DECORATOR: opcode = OP_BINARY_MATMUL; break;
  12464. default: c11__unreachable();
  12465. }
  12466. Ctx__emit_(ctx, opcode, arg, self->line);
  12467. for(int i = 0; i < jmps.length; i++) {
  12468. Ctx__patch_jump(ctx, c11__getitem(int, &jmps, i));
  12469. }
  12470. c11_vector__dtor(&jmps);
  12471. }
  12472. BinaryExpr* BinaryExpr__new(int line, TokenIndex op, bool inplace) {
  12473. const static ExprVt Vt = {.emit_ = BinaryExpr__emit_,
  12474. .dtor = BinaryExpr__dtor,
  12475. .is_binary = true};
  12476. BinaryExpr* self = PK_MALLOC(sizeof(BinaryExpr));
  12477. self->vt = &Vt;
  12478. self->line = line;
  12479. self->lhs = NULL;
  12480. self->rhs = NULL;
  12481. self->op = op;
  12482. self->inplace = inplace;
  12483. return self;
  12484. }
  12485. typedef struct TernaryExpr {
  12486. EXPR_COMMON_HEADER
  12487. Expr* cond;
  12488. Expr* true_expr;
  12489. Expr* false_expr;
  12490. } TernaryExpr;
  12491. void TernaryExpr__dtor(Expr* self_) {
  12492. TernaryExpr* self = (TernaryExpr*)self_;
  12493. vtdelete(self->cond);
  12494. vtdelete(self->true_expr);
  12495. vtdelete(self->false_expr);
  12496. }
  12497. void TernaryExpr__emit_(Expr* self_, Ctx* ctx) {
  12498. TernaryExpr* self = (TernaryExpr*)self_;
  12499. vtemit_(self->cond, ctx);
  12500. int patch = Ctx__emit_(ctx, OP_POP_JUMP_IF_FALSE, BC_NOARG, self->cond->line);
  12501. vtemit_(self->true_expr, ctx);
  12502. int patch_2 = Ctx__emit_(ctx, OP_JUMP_FORWARD, BC_NOARG, self->true_expr->line);
  12503. Ctx__patch_jump(ctx, patch);
  12504. vtemit_(self->false_expr, ctx);
  12505. Ctx__patch_jump(ctx, patch_2);
  12506. }
  12507. TernaryExpr* TernaryExpr__new(int line) {
  12508. const static ExprVt Vt = {
  12509. .dtor = TernaryExpr__dtor,
  12510. .emit_ = TernaryExpr__emit_,
  12511. .is_ternary = true,
  12512. };
  12513. TernaryExpr* self = PK_MALLOC(sizeof(TernaryExpr));
  12514. self->vt = &Vt;
  12515. self->line = line;
  12516. self->cond = NULL;
  12517. self->true_expr = NULL;
  12518. self->false_expr = NULL;
  12519. return self;
  12520. }
  12521. typedef struct SubscrExpr {
  12522. EXPR_COMMON_HEADER
  12523. Expr* lhs;
  12524. Expr* rhs;
  12525. } SubscrExpr;
  12526. void SubscrExpr__dtor(Expr* self_) {
  12527. SubscrExpr* self = (SubscrExpr*)self_;
  12528. vtdelete(self->lhs);
  12529. vtdelete(self->rhs);
  12530. }
  12531. void SubscrExpr__emit_(Expr* self_, Ctx* ctx) {
  12532. SubscrExpr* self = (SubscrExpr*)self_;
  12533. vtemit_(self->lhs, ctx);
  12534. vtemit_(self->rhs, ctx);
  12535. Ctx__emit_(ctx, OP_LOAD_SUBSCR, BC_NOARG, self->line);
  12536. }
  12537. bool SubscrExpr__emit_store(Expr* self_, Ctx* ctx) {
  12538. SubscrExpr* self = (SubscrExpr*)self_;
  12539. vtemit_(self->lhs, ctx);
  12540. vtemit_(self->rhs, ctx);
  12541. Ctx__emit_(ctx, OP_STORE_SUBSCR, BC_NOARG, self->line);
  12542. return true;
  12543. }
  12544. void SubscrExpr__emit_inplace(Expr* self_, Ctx* ctx) {
  12545. SubscrExpr* self = (SubscrExpr*)self_;
  12546. vtemit_(self->lhs, ctx);
  12547. vtemit_(self->rhs, ctx);
  12548. Ctx__emit_(ctx, OP_DUP_TOP_TWO, BC_NOARG, self->line);
  12549. Ctx__emit_(ctx, OP_LOAD_SUBSCR, BC_NOARG, self->line);
  12550. }
  12551. bool SubscrExpr__emit_istore(Expr* self_, Ctx* ctx) {
  12552. SubscrExpr* self = (SubscrExpr*)self_;
  12553. // [a, b, val] -> [val, a, b]
  12554. Ctx__emit_(ctx, OP_ROT_THREE, BC_NOARG, self->line);
  12555. Ctx__emit_(ctx, OP_STORE_SUBSCR, BC_NOARG, self->line);
  12556. return true;
  12557. }
  12558. bool SubscrExpr__emit_del(Expr* self_, Ctx* ctx) {
  12559. SubscrExpr* self = (SubscrExpr*)self_;
  12560. vtemit_(self->lhs, ctx);
  12561. vtemit_(self->rhs, ctx);
  12562. Ctx__emit_(ctx, OP_DELETE_SUBSCR, BC_NOARG, self->line);
  12563. return true;
  12564. }
  12565. SubscrExpr* SubscrExpr__new(int line) {
  12566. const static ExprVt Vt = {
  12567. .dtor = SubscrExpr__dtor,
  12568. .emit_ = SubscrExpr__emit_,
  12569. .emit_store = SubscrExpr__emit_store,
  12570. .emit_inplace = SubscrExpr__emit_inplace,
  12571. .emit_istore = SubscrExpr__emit_istore,
  12572. .emit_del = SubscrExpr__emit_del,
  12573. .is_subscr = true,
  12574. };
  12575. SubscrExpr* self = PK_MALLOC(sizeof(SubscrExpr));
  12576. self->vt = &Vt;
  12577. self->line = line;
  12578. self->lhs = NULL;
  12579. self->rhs = NULL;
  12580. return self;
  12581. }
  12582. typedef struct AttribExpr {
  12583. EXPR_COMMON_HEADER
  12584. Expr* child;
  12585. py_Name name;
  12586. } AttribExpr;
  12587. void AttribExpr__dtor(Expr* self_) {
  12588. AttribExpr* self = (AttribExpr*)self_;
  12589. vtdelete(self->child);
  12590. }
  12591. static bool is_self_xxx(Expr* child, Ctx* ctx) {
  12592. if(child->vt->is_name) {
  12593. NameExpr* ne = (NameExpr*)child;
  12594. if(ne->scope == NAME_LOCAL && ne->name == ctx->n_self) {
  12595. int index = c11_smallmap_n2d__get(&ctx->co->varnames_inv, ne->name, -1);
  12596. if(index == 0) return true;
  12597. }
  12598. }
  12599. return false;
  12600. }
  12601. void AttribExpr__emit_(Expr* self_, Ctx* ctx) {
  12602. AttribExpr* self = (AttribExpr*)self_;
  12603. if(is_self_xxx(self->child, ctx)) {
  12604. Ctx__emit_(ctx, OP_LOAD_SELF_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12605. return;
  12606. }
  12607. vtemit_(self->child, ctx);
  12608. Ctx__emit_(ctx, OP_LOAD_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12609. }
  12610. bool AttribExpr__emit_del(Expr* self_, Ctx* ctx) {
  12611. AttribExpr* self = (AttribExpr*)self_;
  12612. vtemit_(self->child, ctx);
  12613. Ctx__emit_(ctx, OP_DELETE_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12614. return true;
  12615. }
  12616. bool AttribExpr__emit_store(Expr* self_, Ctx* ctx) {
  12617. AttribExpr* self = (AttribExpr*)self_;
  12618. if(is_self_xxx(self->child, ctx)) {
  12619. Ctx__emit_(ctx, OP_STORE_SELF_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12620. return true;
  12621. }
  12622. vtemit_(self->child, ctx);
  12623. Ctx__emit_(ctx, OP_STORE_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12624. return true;
  12625. }
  12626. void AttribExpr__emit_inplace(Expr* self_, Ctx* ctx) {
  12627. AttribExpr* self = (AttribExpr*)self_;
  12628. vtemit_(self->child, ctx);
  12629. Ctx__emit_(ctx, OP_DUP_TOP, BC_NOARG, self->line);
  12630. Ctx__emit_(ctx, OP_LOAD_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12631. }
  12632. bool AttribExpr__emit_istore(Expr* self_, Ctx* ctx) {
  12633. // [a, val] -> [val, a]
  12634. AttribExpr* self = (AttribExpr*)self_;
  12635. Ctx__emit_(ctx, OP_ROT_TWO, BC_NOARG, self->line);
  12636. Ctx__emit_(ctx, OP_STORE_ATTR, Ctx__add_name(ctx, self->name), self->line);
  12637. return true;
  12638. }
  12639. AttribExpr* AttribExpr__new(int line, Expr* child, py_Name name) {
  12640. const static ExprVt Vt = {.emit_ = AttribExpr__emit_,
  12641. .emit_del = AttribExpr__emit_del,
  12642. .emit_store = AttribExpr__emit_store,
  12643. .emit_inplace = AttribExpr__emit_inplace,
  12644. .emit_istore = AttribExpr__emit_istore,
  12645. .dtor = AttribExpr__dtor,
  12646. .is_attrib = true};
  12647. AttribExpr* self = PK_MALLOC(sizeof(AttribExpr));
  12648. self->vt = &Vt;
  12649. self->line = line;
  12650. self->child = child;
  12651. self->name = name;
  12652. return self;
  12653. }
  12654. typedef struct CallExprKwArg {
  12655. py_Name key;
  12656. Expr* val;
  12657. } CallExprKwArg;
  12658. typedef struct CallExpr {
  12659. EXPR_COMMON_HEADER
  12660. Expr* callable;
  12661. c11_vector /*T=Expr* */ args;
  12662. // **a will be interpreted as a special keyword argument: {{0}: a}
  12663. c11_vector /*T=CallExprKwArg */ kwargs;
  12664. } CallExpr;
  12665. void CallExpr__dtor(Expr* self_) {
  12666. CallExpr* self = (CallExpr*)self_;
  12667. vtdelete(self->callable);
  12668. c11__foreach(Expr*, &self->args, e) vtdelete(*e);
  12669. c11__foreach(CallExprKwArg, &self->kwargs, e) vtdelete(e->val);
  12670. c11_vector__dtor(&self->args);
  12671. c11_vector__dtor(&self->kwargs);
  12672. }
  12673. void CallExpr__emit_(Expr* self_, Ctx* ctx) {
  12674. CallExpr* self = (CallExpr*)self_;
  12675. bool vargs = false; // whether there is *args as input
  12676. bool vkwargs = false; // whether there is **kwargs as input
  12677. c11__foreach(Expr*, &self->args, e) {
  12678. if((*e)->vt->is_starred) vargs = true;
  12679. }
  12680. c11__foreach(CallExprKwArg, &self->kwargs, e) {
  12681. if(e->val->vt->is_starred) vkwargs = true;
  12682. }
  12683. // if callable is a AttrExpr, we should try to use `fast_call` instead of use `boundmethod`
  12684. if(self->callable->vt->is_attrib) {
  12685. AttribExpr* p = (AttribExpr*)self->callable;
  12686. vtemit_(p->child, ctx);
  12687. Ctx__emit_(ctx, OP_LOAD_METHOD, Ctx__add_name(ctx, p->name), p->line);
  12688. } else {
  12689. vtemit_(self->callable, ctx);
  12690. Ctx__emit_(ctx, OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE);
  12691. }
  12692. Opcode opcode = OP_CALL;
  12693. if(vargs || vkwargs) {
  12694. // in this case, there is at least one *args or **kwargs as StarredExpr
  12695. // OP_CALL_VARGS needs to unpack them via vectorcall_buffer
  12696. opcode = OP_CALL_VARGS;
  12697. }
  12698. c11__foreach(Expr*, &self->args, e) { vtemit_(*e, ctx); }
  12699. c11__foreach(CallExprKwArg, &self->kwargs, e) {
  12700. if(e->key == 0) {
  12701. // special key for **kwargs
  12702. Ctx__emit_int(ctx, 0, self->line);
  12703. } else {
  12704. Ctx__emit_name(ctx, e->key, self->line);
  12705. }
  12706. vtemit_(e->val, ctx);
  12707. }
  12708. int KWARGC = self->kwargs.length;
  12709. int ARGC = self->args.length;
  12710. assert(KWARGC < 256 && ARGC < 256);
  12711. Ctx__emit_(ctx, opcode, (KWARGC << 8) | ARGC, self->line);
  12712. }
  12713. CallExpr* CallExpr__new(int line, Expr* callable) {
  12714. const static ExprVt Vt = {.dtor = CallExpr__dtor, .emit_ = CallExpr__emit_};
  12715. CallExpr* self = PK_MALLOC(sizeof(CallExpr));
  12716. self->vt = &Vt;
  12717. self->line = line;
  12718. self->callable = callable;
  12719. c11_vector__ctor(&self->args, sizeof(Expr*));
  12720. c11_vector__ctor(&self->kwargs, sizeof(CallExprKwArg));
  12721. return self;
  12722. }
  12723. /* context.c */
  12724. static void Ctx__ctor(Ctx* self, CodeObject* co, FuncDecl* func, int level, py_Name n_self) {
  12725. self->co = co;
  12726. self->func = func;
  12727. self->n_self = n_self;
  12728. self->level = level;
  12729. self->curr_iblock = 0;
  12730. self->is_compiling_class = false;
  12731. c11_vector__ctor(&self->s_expr, sizeof(Expr*));
  12732. c11_smallmap_n2d__ctor(&self->global_names);
  12733. c11_smallmap_v2d__ctor(&self->co_consts_string_dedup_map);
  12734. }
  12735. static void Ctx__dtor(Ctx* self) {
  12736. // clean the expr stack
  12737. for(int i = 0; i < self->s_expr.length; i++) {
  12738. vtdelete(c11__getitem(Expr*, &self->s_expr, i));
  12739. }
  12740. c11_vector__dtor(&self->s_expr);
  12741. c11_smallmap_n2d__dtor(&self->global_names);
  12742. // free the dedup map
  12743. c11__foreach(c11_smallmap_v2d_KV, &self->co_consts_string_dedup_map, p_kv) {
  12744. const char* p = p_kv->key.data;
  12745. PK_FREE((void*)p);
  12746. }
  12747. c11_smallmap_v2d__dtor(&self->co_consts_string_dedup_map);
  12748. }
  12749. static int Ctx__prepare_loop_divert(Ctx* self, int line, bool is_break) {
  12750. int index = self->curr_iblock;
  12751. while(index >= 0) {
  12752. CodeBlock* block = c11__at(CodeBlock, &self->co->blocks, index);
  12753. switch(block->type) {
  12754. case CodeBlockType_WHILE_LOOP: return index;
  12755. case CodeBlockType_FOR_LOOP: {
  12756. if(is_break) Ctx__emit_(self, OP_POP_TOP, BC_NOARG, line);
  12757. return index;
  12758. }
  12759. case CodeBlockType_WITH: {
  12760. Ctx__emit_(self, OP_POP_TOP, BC_NOARG, line);
  12761. break;
  12762. }
  12763. case CodeBlockType_TRY: {
  12764. Ctx__emit_(self, OP_END_TRY, BC_NOARG, line);
  12765. break;
  12766. }
  12767. case CodeBlockType_EXCEPT: {
  12768. Ctx__emit_(self, OP_END_TRY, BC_NOARG, line);
  12769. break;
  12770. }
  12771. default: break;
  12772. }
  12773. index = block->parent;
  12774. }
  12775. return index;
  12776. }
  12777. static int Ctx__enter_block(Ctx* self, CodeBlockType type) {
  12778. CodeBlock block = {type, self->curr_iblock, self->co->codes.length, -1, -1};
  12779. c11_vector__push(CodeBlock, &self->co->blocks, block);
  12780. self->curr_iblock = self->co->blocks.length - 1;
  12781. return self->curr_iblock;
  12782. }
  12783. static void Ctx__exit_block(Ctx* self) {
  12784. CodeBlock* block = c11__at(CodeBlock, &self->co->blocks, self->curr_iblock);
  12785. block->end = self->co->codes.length;
  12786. self->curr_iblock = block->parent;
  12787. assert(self->curr_iblock >= 0);
  12788. }
  12789. static void Ctx__s_emit_decorators(Ctx* self, int count) {
  12790. if(count == 0) return;
  12791. assert(Ctx__s_size(self) >= count);
  12792. // [obj]
  12793. for(int i = 0; i < count; i++) {
  12794. Expr* deco = Ctx__s_popx(self);
  12795. vtemit_(deco, self); // [obj, f]
  12796. Ctx__emit_(self, OP_ROT_TWO, BC_NOARG, deco->line); // [f, obj]
  12797. Ctx__emit_(self, OP_LOAD_NULL, BC_NOARG, BC_KEEPLINE); // [f, obj, NULL]
  12798. Ctx__emit_(self, OP_ROT_TWO, BC_NOARG, BC_KEEPLINE); // [obj, NULL, f]
  12799. Ctx__emit_(self, OP_CALL, 1, deco->line); // [obj]
  12800. vtdelete(deco);
  12801. }
  12802. }
  12803. static int Ctx__emit_(Ctx* self, Opcode opcode, uint16_t arg, int line) {
  12804. Bytecode bc = {(uint16_t)opcode, arg};
  12805. BytecodeEx bcx = {line, self->curr_iblock};
  12806. c11_vector__push(Bytecode, &self->co->codes, bc);
  12807. c11_vector__push(BytecodeEx, &self->co->codes_ex, bcx);
  12808. int i = self->co->codes.length - 1;
  12809. BytecodeEx* codes_ex = (BytecodeEx*)self->co->codes_ex.data;
  12810. if(line == BC_KEEPLINE) { codes_ex[i].lineno = i >= 1 ? codes_ex[i - 1].lineno : 1; }
  12811. return i;
  12812. }
  12813. static int Ctx__emit_int(Ctx* self, int64_t value, int line) {
  12814. if(INT16_MIN <= value && value <= INT16_MAX) {
  12815. return Ctx__emit_(self, OP_LOAD_SMALL_INT, (uint16_t)value, line);
  12816. } else {
  12817. py_TValue tmp;
  12818. py_newint(&tmp, value);
  12819. return Ctx__emit_(self, OP_LOAD_CONST, Ctx__add_const(self, &tmp), line);
  12820. }
  12821. }
  12822. static int Ctx__emit_name(Ctx* self, py_Name name, int line) {
  12823. int index = Ctx__add_name(self, name);
  12824. assert(index <= UINT16_MAX);
  12825. return Ctx__emit_(self, OP_LOAD_NAME_AS_INT, (uint16_t)index, line);
  12826. }
  12827. static void Ctx__patch_jump(Ctx* self, int index) {
  12828. Bytecode* co_codes = (Bytecode*)self->co->codes.data;
  12829. int target = self->co->codes.length;
  12830. Bytecode__set_signed_arg(&co_codes[index], target - index);
  12831. }
  12832. static void Ctx__emit_jump(Ctx* self, int target, int line) {
  12833. int index = Ctx__emit_(self, OP_JUMP_FORWARD, BC_NOARG, line);
  12834. // should place after Ctx__emit_ because of realloc
  12835. Bytecode* co_codes = (Bytecode*)self->co->codes.data;
  12836. Bytecode__set_signed_arg(&co_codes[index], target - index);
  12837. }
  12838. static int Ctx__add_varname(Ctx* self, py_Name name) {
  12839. // PK_MAX_CO_VARNAMES will be checked when pop_context(), not here
  12840. return CodeObject__add_varname(self->co, name);
  12841. }
  12842. static int Ctx__add_name(Ctx* self, py_Name name) {
  12843. assert(name != 0);
  12844. return CodeObject__add_name(self->co, name);
  12845. }
  12846. static int Ctx__add_const_string(Ctx* self, c11_sv key) {
  12847. if(key.size > 100) {
  12848. py_Ref tmp = c11_vector__emplace(&self->co->consts);
  12849. py_newstrv(tmp, key);
  12850. int index = self->co->consts.length - 1;
  12851. return index;
  12852. }
  12853. int* val = c11_smallmap_v2d__try_get(&self->co_consts_string_dedup_map, key);
  12854. if(val) {
  12855. return *val;
  12856. } else {
  12857. py_Ref tmp = c11_vector__emplace(&self->co->consts);
  12858. py_newstrv(tmp, key);
  12859. int index = self->co->consts.length - 1;
  12860. // dedup
  12861. char* new_buf = PK_MALLOC(key.size + 1);
  12862. memcpy(new_buf, key.data, key.size);
  12863. new_buf[key.size] = 0;
  12864. c11_smallmap_v2d__set(&self->co_consts_string_dedup_map,
  12865. (c11_sv){new_buf, key.size},
  12866. index);
  12867. return index;
  12868. }
  12869. }
  12870. static int Ctx__add_const(Ctx* self, py_Ref v) {
  12871. assert(v->type != tp_str);
  12872. c11_vector__push(py_TValue, &self->co->consts, *v);
  12873. return self->co->consts.length - 1;
  12874. }
  12875. static void Ctx__emit_store_name(Ctx* self, NameScope scope, py_Name name, int line) {
  12876. if(name == py_name("_")) {
  12877. Ctx__emit_(self, OP_POP_TOP, BC_NOARG, line);
  12878. return;
  12879. }
  12880. switch(scope) {
  12881. case NAME_LOCAL: Ctx__emit_(self, OP_STORE_FAST, Ctx__add_varname(self, name), line); break;
  12882. case NAME_GLOBAL: {
  12883. Opcode op = self->co->src->is_dynamic ? OP_STORE_NAME : OP_STORE_GLOBAL;
  12884. Ctx__emit_(self, op, Ctx__add_name(self, name), line);
  12885. } break;
  12886. default: c11__unreachable();
  12887. }
  12888. }
  12889. // emit top -> pop -> delete
  12890. static void Ctx__s_emit_top(Ctx* self) {
  12891. assert(self->s_expr.length);
  12892. Expr* top = c11_vector__back(Expr*, &self->s_expr);
  12893. vtemit_(top, self);
  12894. vtdelete(top);
  12895. c11_vector__pop(&self->s_expr);
  12896. }
  12897. // push
  12898. static void Ctx__s_push(Ctx* self, Expr* expr) { c11_vector__push(Expr*, &self->s_expr, expr); }
  12899. // top
  12900. static Expr* Ctx__s_top(Ctx* self) {
  12901. assert(self->s_expr.length);
  12902. return c11_vector__back(Expr*, &self->s_expr);
  12903. }
  12904. // size
  12905. static int Ctx__s_size(Ctx* self) { return self->s_expr.length; }
  12906. // pop -> delete
  12907. static void Ctx__s_pop(Ctx* self) {
  12908. assert(self->s_expr.length);
  12909. Expr* top = c11_vector__back(Expr*, &self->s_expr);
  12910. vtdelete(top);
  12911. c11_vector__pop(&self->s_expr);
  12912. }
  12913. // pop move
  12914. static Expr* Ctx__s_popx(Ctx* self) {
  12915. assert(self->s_expr.length);
  12916. Expr* top = c11_vector__back(Expr*, &self->s_expr);
  12917. c11_vector__pop(&self->s_expr);
  12918. return top;
  12919. }
  12920. /* compiler.c */
  12921. typedef struct Compiler Compiler;
  12922. typedef Error* (*PrattCallback)(Compiler* self);
  12923. typedef struct PrattRule {
  12924. PrattCallback prefix;
  12925. PrattCallback infix;
  12926. enum Precedence precedence;
  12927. } PrattRule;
  12928. const static PrattRule rules[TK__COUNT__];
  12929. typedef struct Compiler {
  12930. SourceData_ src; // weakref
  12931. Token* tokens;
  12932. int tokens_length;
  12933. py_Name n_self;
  12934. int i; // current token index
  12935. c11_vector /*T=CodeEmitContext*/ contexts;
  12936. } Compiler;
  12937. static void Compiler__ctor(Compiler* self, SourceData_ src, Token* tokens, int tokens_length) {
  12938. self->src = src;
  12939. self->tokens = tokens;
  12940. self->tokens_length = tokens_length;
  12941. self->n_self = py_name("self");
  12942. self->i = 0;
  12943. c11_vector__ctor(&self->contexts, sizeof(Ctx));
  12944. }
  12945. static void Compiler__dtor(Compiler* self) {
  12946. // free tokens
  12947. destruct_tokens(self->tokens, self->tokens_length);
  12948. PK_FREE(self->tokens);
  12949. // free contexts
  12950. c11__foreach(Ctx, &self->contexts, ctx) Ctx__dtor(ctx);
  12951. c11_vector__dtor(&self->contexts);
  12952. }
  12953. /**************************************/
  12954. #define tk(i) (&self->tokens[i])
  12955. #define prev() (&self->tokens[self->i - 1])
  12956. #define curr() (&self->tokens[self->i])
  12957. #define next() (&self->tokens[self->i + 1])
  12958. #define advance() self->i++
  12959. #define mode() self->src->mode
  12960. #define ctx() (&c11_vector__back(Ctx, &self->contexts))
  12961. #define match_newlines() match_newlines_impl(self)
  12962. #define consume(expected) \
  12963. if(!match(expected)) \
  12964. return SyntaxError(self, \
  12965. "expected '%s', got '%s'", \
  12966. TokenSymbols[expected], \
  12967. TokenSymbols[curr()->type]);
  12968. #define consume_end_stmt() \
  12969. if(!match_end_stmt(self)) return SyntaxError(self, "expected statement end")
  12970. #define check(B) \
  12971. if((err = B)) return err
  12972. static NameScope name_scope(Compiler* self) {
  12973. return self->contexts.length > 1 ? NAME_LOCAL : NAME_GLOBAL;
  12974. }
  12975. Error* SyntaxError(Compiler* self, const char* fmt, ...) {
  12976. Error* err = PK_MALLOC(sizeof(Error));
  12977. err->src = self->src;
  12978. PK_INCREF(self->src);
  12979. Token* t = self->i == self->tokens_length ? prev() : curr();
  12980. err->lineno = t->line;
  12981. va_list args;
  12982. va_start(args, fmt);
  12983. vsnprintf(err->msg, sizeof(err->msg), fmt, args);
  12984. va_end(args);
  12985. return err;
  12986. }
  12987. /* Matchers */
  12988. static bool is_expression(Compiler* self, bool allow_slice) {
  12989. PrattCallback prefix = rules[curr()->type].prefix;
  12990. return prefix && (allow_slice || curr()->type != TK_COLON);
  12991. }
  12992. #define match(expected) (curr()->type == expected ? (++self->i) : 0)
  12993. static bool match_id_by_str(Compiler* self, const char* name) {
  12994. if(curr()->type == TK_ID) {
  12995. bool ok = c11__sveq2(Token__sv(curr()), name);
  12996. if(ok) advance();
  12997. return ok;
  12998. }
  12999. return false;
  13000. }
  13001. static bool match_newlines_impl(Compiler* self) {
  13002. bool consumed = false;
  13003. if(curr()->type == TK_EOL) {
  13004. while(curr()->type == TK_EOL)
  13005. advance();
  13006. consumed = true;
  13007. }
  13008. return consumed;
  13009. }
  13010. static bool match_end_stmt(Compiler* self) {
  13011. if(match(TK_SEMICOLON)) {
  13012. match_newlines();
  13013. return true;
  13014. }
  13015. if(match_newlines() || curr()->type == TK_EOF) return true;
  13016. if(curr()->type == TK_DEDENT) return true;
  13017. return false;
  13018. }
  13019. /* Expression */
  13020. /// Parse an expression and push it onto the stack.
  13021. static Error* parse_expression(Compiler* self, int precedence, bool allow_slice) {
  13022. PrattCallback prefix = rules[curr()->type].prefix;
  13023. if(!prefix || (curr()->type == TK_COLON && !allow_slice)) {
  13024. return SyntaxError(self, "expected an expression, got %s", TokenSymbols[curr()->type]);
  13025. }
  13026. advance();
  13027. Error* err;
  13028. check(prefix(self));
  13029. while(rules[curr()->type].precedence >= precedence &&
  13030. (allow_slice || curr()->type != TK_COLON)) {
  13031. TokenIndex op = curr()->type;
  13032. advance();
  13033. PrattCallback infix = rules[op].infix;
  13034. if(infix == NULL) {
  13035. return SyntaxError(self, "expected an infix operator, got %s", TokenSymbols[op]);
  13036. }
  13037. check(infix(self));
  13038. }
  13039. return NULL;
  13040. }
  13041. static Error* EXPR_TUPLE_ALLOW_SLICE(Compiler* self, bool allow_slice) {
  13042. Error* err;
  13043. check(parse_expression(self, PREC_LOWEST + 1, allow_slice));
  13044. if(!match(TK_COMMA)) return NULL;
  13045. // tuple expression // (a, )
  13046. int count = 1;
  13047. do {
  13048. if(!is_expression(self, allow_slice)) break;
  13049. check(parse_expression(self, PREC_LOWEST + 1, allow_slice));
  13050. count += 1;
  13051. } while(match(TK_COMMA));
  13052. // pop `count` expressions from the stack and merge them into a TupleExpr
  13053. SequenceExpr* e = TupleExpr__new(prev()->line, count);
  13054. for(int i = count - 1; i >= 0; i--) {
  13055. e->items[i] = Ctx__s_popx(ctx());
  13056. }
  13057. Ctx__s_push(ctx(), (Expr*)e);
  13058. return NULL;
  13059. }
  13060. /// Parse a simple expression.
  13061. static Error* EXPR(Compiler* self) { return parse_expression(self, PREC_LOWEST + 1, false); }
  13062. /// Parse a simple expression or a tuple of expressions.
  13063. static Error* EXPR_TUPLE(Compiler* self) { return EXPR_TUPLE_ALLOW_SLICE(self, false); }
  13064. // special case for `for loop` and `comp`
  13065. static Error* EXPR_VARS(Compiler* self) {
  13066. int count = 0;
  13067. do {
  13068. consume(TK_ID);
  13069. py_Name name = py_namev(Token__sv(prev()));
  13070. NameExpr* e = NameExpr__new(prev()->line, name, name_scope(self));
  13071. Ctx__s_push(ctx(), (Expr*)e);
  13072. count += 1;
  13073. } while(match(TK_COMMA));
  13074. if(count > 1) {
  13075. SequenceExpr* e = TupleExpr__new(prev()->line, count);
  13076. for(int i = count - 1; i >= 0; i--) {
  13077. e->items[i] = Ctx__s_popx(ctx());
  13078. }
  13079. Ctx__s_push(ctx(), (Expr*)e);
  13080. }
  13081. return NULL;
  13082. }
  13083. /* Misc */
  13084. static void push_global_context(Compiler* self, CodeObject* co) {
  13085. co->start_line = self->i == 0 ? 1 : prev()->line;
  13086. Ctx* ctx = c11_vector__emplace(&self->contexts);
  13087. Ctx__ctor(ctx, co, NULL, self->contexts.length, self->n_self);
  13088. }
  13089. static Error* pop_context(Compiler* self) {
  13090. // add a `return None` in the end as a guard
  13091. // previously, we only do this if the last opcode is not a return
  13092. // however, this is buggy...since there may be a jump to the end (out of bound) even if the last
  13093. // opcode is a return
  13094. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_RETURN_VIRTUAL, BC_KEEPLINE);
  13095. CodeObject* co = ctx()->co;
  13096. // find the last valid token
  13097. int j = self->i - 1;
  13098. while(tk(j)->type == TK_EOL || tk(j)->type == TK_DEDENT || tk(j)->type == TK_EOF)
  13099. j--;
  13100. co->end_line = tk(j)->line;
  13101. // some check here
  13102. c11_vector* codes = &co->codes;
  13103. if(co->nlocals > PK_MAX_CO_VARNAMES) {
  13104. return SyntaxError(self, "maximum number of local variables exceeded");
  13105. }
  13106. if(co->consts.length > 65530) {
  13107. return SyntaxError(self, "maximum number of constants exceeded");
  13108. }
  13109. // pre-compute block.end or block.end2
  13110. for(int i = 0; i < codes->length; i++) {
  13111. Bytecode* bc = c11__at(Bytecode, codes, i);
  13112. if(bc->op == OP_LOOP_CONTINUE) {
  13113. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  13114. Bytecode__set_signed_arg(bc, block->start - i);
  13115. } else if(bc->op == OP_LOOP_BREAK) {
  13116. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  13117. Bytecode__set_signed_arg(bc, (block->end2 != -1 ? block->end2 : block->end) - i);
  13118. } else if(bc->op == OP_FOR_ITER || bc->op == OP_FOR_ITER_YIELD_VALUE) {
  13119. CodeBlock* block = c11__at(CodeBlock, &ctx()->co->blocks, bc->arg);
  13120. Bytecode__set_signed_arg(bc, block->end - i);
  13121. }
  13122. }
  13123. // pre-compute func->is_simple
  13124. FuncDecl* func = ctx()->func;
  13125. if(func) {
  13126. // check generator
  13127. Bytecode* codes = func->code.codes.data;
  13128. int codes_length = func->code.codes.length;
  13129. for(int i = 0; i < codes_length; i++) {
  13130. if(codes[i].op == OP_YIELD_VALUE || codes[i].op == OP_FOR_ITER_YIELD_VALUE) {
  13131. func->type = FuncType_GENERATOR;
  13132. break;
  13133. }
  13134. }
  13135. if(func->type == FuncType_UNSET) {
  13136. bool is_simple = true;
  13137. if(func->kwargs.length > 0) is_simple = false;
  13138. if(func->starred_arg >= 0) is_simple = false;
  13139. if(func->starred_kwarg >= 0) is_simple = false;
  13140. if(is_simple) {
  13141. func->type = FuncType_SIMPLE;
  13142. } else {
  13143. func->type = FuncType_NORMAL;
  13144. }
  13145. }
  13146. assert(func->type != FuncType_UNSET);
  13147. }
  13148. Ctx__dtor(ctx());
  13149. c11_vector__pop(&self->contexts);
  13150. return NULL;
  13151. }
  13152. /* Expression Callbacks */
  13153. static Error* exprLiteral(Compiler* self) {
  13154. LiteralExpr* e = LiteralExpr__new(prev()->line, &prev()->value);
  13155. Ctx__s_push(ctx(), (Expr*)e);
  13156. return NULL;
  13157. }
  13158. static Error* exprBytes(Compiler* self) {
  13159. c11_sv sv = c11_string__sv(prev()->value._str);
  13160. Ctx__s_push(ctx(), (Expr*)RawStringExpr__new(prev()->line, sv, OP_BUILD_BYTES));
  13161. return NULL;
  13162. }
  13163. static Error* exprFString(Compiler* self) {
  13164. // @fstr-begin, [@fstr-cpnt | <expr>]*, @fstr-end
  13165. int count = 0;
  13166. int line = prev()->line;
  13167. while(true) {
  13168. if(match(TK_FSTR_END)) {
  13169. SequenceExpr* e = FStringExpr__new(line, count);
  13170. for(int i = count - 1; i >= 0; i--) {
  13171. e->items[i] = Ctx__s_popx(ctx());
  13172. }
  13173. Ctx__s_push(ctx(), (Expr*)e);
  13174. return NULL;
  13175. } else if(match(TK_FSTR_CPNT)) {
  13176. // OP_LOAD_CONST
  13177. LiteralExpr* e = LiteralExpr__new(prev()->line, &prev()->value);
  13178. Ctx__s_push(ctx(), (Expr*)e);
  13179. count++;
  13180. } else {
  13181. // {a!r:.2f}
  13182. Error* err = EXPR(self);
  13183. if(err) return err;
  13184. count++;
  13185. if(match(TK_FSTR_SPEC)) {
  13186. c11_sv spec = Token__sv(prev());
  13187. // ':.2f}' -> ':.2f'
  13188. spec.size--;
  13189. Expr* child = Ctx__s_popx(ctx());
  13190. FStringSpecExpr* e = FStringSpecExpr__new(prev()->line, child, spec);
  13191. Ctx__s_push(ctx(), (Expr*)e);
  13192. }
  13193. }
  13194. }
  13195. }
  13196. static Error* exprImag(Compiler* self) {
  13197. Ctx__s_push(ctx(), (Expr*)ImagExpr__new(prev()->line, prev()->value._f64));
  13198. return NULL;
  13199. }
  13200. static FuncDecl_ push_f_context(Compiler* self, c11_sv name, int* out_index);
  13201. static Error* _compile_f_args(Compiler* self, FuncDecl* decl, bool is_lambda);
  13202. static Error* exprLambda(Compiler* self) {
  13203. Error* err;
  13204. int line = prev()->line;
  13205. int decl_index;
  13206. FuncDecl_ decl = push_f_context(self, (c11_sv){"<lambda>", 8}, &decl_index);
  13207. if(!match(TK_COLON)) {
  13208. check(_compile_f_args(self, decl, true));
  13209. consume(TK_COLON);
  13210. }
  13211. // https://github.com/pocketpy/pocketpy/issues/37
  13212. check(parse_expression(self, PREC_LAMBDA + 1, false));
  13213. Ctx__s_emit_top(ctx());
  13214. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  13215. check(pop_context(self));
  13216. LambdaExpr* e = LambdaExpr__new(line, decl_index);
  13217. Ctx__s_push(ctx(), (Expr*)e);
  13218. return NULL;
  13219. }
  13220. static Error* exprOr(Compiler* self) {
  13221. Error* err;
  13222. int line = prev()->line;
  13223. check(parse_expression(self, PREC_LOGICAL_OR + 1, false));
  13224. LogicBinaryExpr* e = LogicBinaryExpr__new(line, OP_JUMP_IF_TRUE_OR_POP);
  13225. e->rhs = Ctx__s_popx(ctx());
  13226. e->lhs = Ctx__s_popx(ctx());
  13227. Ctx__s_push(ctx(), (Expr*)e);
  13228. return NULL;
  13229. }
  13230. static Error* exprAnd(Compiler* self) {
  13231. Error* err;
  13232. int line = prev()->line;
  13233. check(parse_expression(self, PREC_LOGICAL_AND + 1, false));
  13234. LogicBinaryExpr* e = LogicBinaryExpr__new(line, OP_JUMP_IF_FALSE_OR_POP);
  13235. e->rhs = Ctx__s_popx(ctx());
  13236. e->lhs = Ctx__s_popx(ctx());
  13237. Ctx__s_push(ctx(), (Expr*)e);
  13238. return NULL;
  13239. }
  13240. static Error* exprWalrus(Compiler* self) {
  13241. Error* err;
  13242. int line = prev()->line;
  13243. // LHS is on the stack; verify it's a simple name
  13244. Expr* lhs = Ctx__s_top(ctx());
  13245. if(!lhs->vt->is_name) { return SyntaxError(self, "':=' target must be a simple name"); }
  13246. check(parse_expression(self, PREC_NAMED_EXPR + 1, false));
  13247. Expr* rhs = Ctx__s_popx(ctx());
  13248. NameExpr* name = (NameExpr*)Ctx__s_popx(ctx());
  13249. NamedExpr* e = NamedExpr__new(line, name, rhs);
  13250. Ctx__s_push(ctx(), (Expr*)e);
  13251. return NULL;
  13252. }
  13253. static Error* exprTernary(Compiler* self) {
  13254. // [true_expr]
  13255. Error* err;
  13256. int line = prev()->line;
  13257. check(parse_expression(self, PREC_TERNARY + 1, false)); // [true_expr, cond]
  13258. consume(TK_ELSE);
  13259. check(parse_expression(self, PREC_TERNARY + 1, false)); // [true_expr, cond, false_expr]
  13260. TernaryExpr* e = TernaryExpr__new(line);
  13261. e->false_expr = Ctx__s_popx(ctx());
  13262. e->cond = Ctx__s_popx(ctx());
  13263. e->true_expr = Ctx__s_popx(ctx());
  13264. Ctx__s_push(ctx(), (Expr*)e);
  13265. if(e->cond->vt->is_ternary || e->false_expr->vt->is_ternary || e->true_expr->vt->is_ternary) {
  13266. return SyntaxError(self, "nested ternary expressions without `()` are ambiguous");
  13267. }
  13268. return NULL;
  13269. }
  13270. static Error* exprBinaryOp(Compiler* self) {
  13271. Error* err;
  13272. int line = prev()->line;
  13273. TokenIndex op = prev()->type;
  13274. int precedence = rules[op].precedence;
  13275. if(op != TK_POW) {
  13276. // if not right associative, increase precedence
  13277. precedence += 1;
  13278. }
  13279. check(parse_expression(self, precedence, false));
  13280. BinaryExpr* e = BinaryExpr__new(line, op, false);
  13281. if(op == TK_IN || op == TK_NOT_IN) {
  13282. e->lhs = Ctx__s_popx(ctx());
  13283. e->rhs = Ctx__s_popx(ctx());
  13284. } else {
  13285. e->rhs = Ctx__s_popx(ctx());
  13286. e->lhs = Ctx__s_popx(ctx());
  13287. }
  13288. Ctx__s_push(ctx(), (Expr*)e);
  13289. return NULL;
  13290. }
  13291. static Error* exprNot(Compiler* self) {
  13292. Error* err;
  13293. int line = prev()->line;
  13294. check(parse_expression(self, PREC_LOGICAL_NOT + 1, false));
  13295. UnaryExpr* e = UnaryExpr__new(line, Ctx__s_popx(ctx()), OP_UNARY_NOT);
  13296. Ctx__s_push(ctx(), (Expr*)e);
  13297. return NULL;
  13298. }
  13299. static Error* exprUnaryOp(Compiler* self) {
  13300. Error* err;
  13301. int line = prev()->line;
  13302. TokenIndex op = prev()->type;
  13303. check(parse_expression(self, PREC_UNARY + 1, false));
  13304. Expr* e = Ctx__s_popx(ctx());
  13305. switch(op) {
  13306. case TK_SUB: {
  13307. // constant fold
  13308. if(e->vt->is_literal) {
  13309. LiteralExpr* le = (LiteralExpr*)e;
  13310. if(le->value->index == TokenValue_I64 || le->value->index == TokenValue_F64) {
  13311. le->negated = true;
  13312. }
  13313. Ctx__s_push(ctx(), e);
  13314. } else {
  13315. Ctx__s_push(ctx(), (Expr*)UnaryExpr__new(line, e, OP_UNARY_NEGATIVE));
  13316. }
  13317. break;
  13318. }
  13319. case TK_INVERT: Ctx__s_push(ctx(), (Expr*)UnaryExpr__new(line, e, OP_UNARY_INVERT)); break;
  13320. case TK_MUL: Ctx__s_push(ctx(), (Expr*)StarredExpr__new(line, e, 1)); break;
  13321. case TK_POW: Ctx__s_push(ctx(), (Expr*)StarredExpr__new(line, e, 2)); break;
  13322. default: assert(false);
  13323. }
  13324. return NULL;
  13325. }
  13326. static Error* consume_comp(Compiler* self, Opcode op0, Opcode op1); // LYNX
  13327. static Error* exprGroup(Compiler* self) {
  13328. Error* err;
  13329. int line = prev()->line;
  13330. if(match(TK_RPAREN)) {
  13331. // empty tuple
  13332. Ctx__s_push(ctx(), (Expr*)TupleExpr__new(line, 0));
  13333. return NULL;
  13334. }
  13335. check(EXPR_TUPLE(self)); // () is just for change precedence
  13336. if(match(TK_FOR)) { // LYNX: (x for x in y), a generator expression evaluated eagerly
  13337. check(consume_comp(self, OP_BUILD_LIST, OP_LIST_APPEND));
  13338. ((CompExpr*)Ctx__s_top(ctx()))->as_iter = true;
  13339. consume(TK_RPAREN);
  13340. return NULL;
  13341. }
  13342. consume(TK_RPAREN);
  13343. if(Ctx__s_top(ctx())->vt->is_tuple) return NULL;
  13344. GroupedExpr* g = GroupedExpr__new(line, Ctx__s_popx(ctx()));
  13345. Ctx__s_push(ctx(), (Expr*)g);
  13346. return NULL;
  13347. }
  13348. static Error* exprName(Compiler* self) {
  13349. py_Name name = py_namev(Token__sv(prev()));
  13350. NameScope scope = name_scope(self);
  13351. // promote this name to global scope if needed
  13352. if(c11_smallmap_n2d__contains(&ctx()->global_names, name)) {
  13353. if(self->src->is_dynamic) return SyntaxError(self, "cannot use global keyword here");
  13354. scope = NAME_GLOBAL;
  13355. }
  13356. NameExpr* e = NameExpr__new(prev()->line, name, scope);
  13357. Ctx__s_push(ctx(), (Expr*)e);
  13358. return NULL;
  13359. }
  13360. static Error* exprAttrib(Compiler* self) {
  13361. consume(TK_ID);
  13362. py_Name name = py_namev(Token__sv(prev()));
  13363. AttribExpr* e = AttribExpr__new(prev()->line, Ctx__s_popx(ctx()), name);
  13364. Ctx__s_push(ctx(), (Expr*)e);
  13365. return NULL;
  13366. }
  13367. static Error* exprLiteral0(Compiler* self) {
  13368. Literal0Expr* e = Literal0Expr__new(prev()->line, prev()->type);
  13369. Ctx__s_push(ctx(), (Expr*)e);
  13370. return NULL;
  13371. }
  13372. static Error* consume_comp(Compiler* self, Opcode op0, Opcode op1) {
  13373. // [expr]
  13374. Error* err;
  13375. int line = prev()->line;
  13376. bool has_cond = false;
  13377. check(EXPR_VARS(self)); // [expr, vars]
  13378. consume(TK_IN);
  13379. check(parse_expression(self, PREC_TERNARY + 1, false)); // [expr, vars, iter]
  13380. if(match(TK_IF)) {
  13381. check(parse_expression(self, PREC_TERNARY + 1, false)); // [expr, vars, iter, cond]
  13382. has_cond = true;
  13383. }
  13384. CompExpr* ce = CompExpr__new(line, op0, op1);
  13385. if(has_cond) ce->cond = Ctx__s_popx(ctx());
  13386. ce->iter = Ctx__s_popx(ctx());
  13387. ce->vars = Ctx__s_popx(ctx());
  13388. ce->expr = Ctx__s_popx(ctx());
  13389. Ctx__s_push(ctx(), (Expr*)ce);
  13390. return NULL;
  13391. }
  13392. static Error* exprList(Compiler* self) {
  13393. Error* err;
  13394. int line = prev()->line;
  13395. int count = 0;
  13396. do {
  13397. if(curr()->type == TK_RBRACKET) break;
  13398. check(EXPR(self));
  13399. count += 1;
  13400. if(count == 1 && match(TK_FOR)) {
  13401. check(consume_comp(self, OP_BUILD_LIST, OP_LIST_APPEND));
  13402. consume(TK_RBRACKET);
  13403. return NULL;
  13404. }
  13405. } while(match(TK_COMMA));
  13406. consume(TK_RBRACKET);
  13407. SequenceExpr* e = ListExpr__new(line, count);
  13408. for(int i = count - 1; i >= 0; i--) {
  13409. e->items[i] = Ctx__s_popx(ctx());
  13410. }
  13411. Ctx__s_push(ctx(), (Expr*)e);
  13412. return NULL;
  13413. }
  13414. static Error* exprMap(Compiler* self) {
  13415. Error* err;
  13416. int line = prev()->line;
  13417. bool parsing_dict = false; // {...} may be dict or set
  13418. int count = 0;
  13419. do {
  13420. if(curr()->type == TK_RBRACE) break;
  13421. check(EXPR(self)); // [key]
  13422. if(curr()->type == TK_COLON) { parsing_dict = true; }
  13423. if(parsing_dict) {
  13424. consume(TK_COLON);
  13425. check(EXPR(self)); // [key, value] -> [item]
  13426. DictItemExpr* item = DictItemExpr__new(prev()->line);
  13427. item->value = Ctx__s_popx(ctx());
  13428. item->key = Ctx__s_popx(ctx());
  13429. Ctx__s_push(ctx(), (Expr*)item);
  13430. }
  13431. count += 1; // key-value pair count
  13432. if(count == 1 && match(TK_FOR)) {
  13433. if(parsing_dict) {
  13434. check(consume_comp(self, OP_BUILD_DICT, OP_DICT_ADD));
  13435. } else {
  13436. check(consume_comp(self, OP_BUILD_SET, OP_SET_ADD));
  13437. }
  13438. consume(TK_RBRACE);
  13439. return NULL;
  13440. }
  13441. } while(match(TK_COMMA));
  13442. consume(TK_RBRACE);
  13443. SequenceExpr* se;
  13444. if(count == 0 || parsing_dict) {
  13445. se = DictExpr__new(line, count);
  13446. } else {
  13447. se = SetExpr__new(line, count);
  13448. }
  13449. for(int i = count - 1; i >= 0; i--) {
  13450. se->items[i] = Ctx__s_popx(ctx());
  13451. }
  13452. Ctx__s_push(ctx(), (Expr*)se);
  13453. return NULL;
  13454. }
  13455. static Error* read_literal(Compiler* self, py_Ref out);
  13456. static Error* exprCall(Compiler* self) {
  13457. Error* err;
  13458. Expr* callable = Ctx__s_popx(ctx());
  13459. int line = prev()->line;
  13460. CallExpr* e = CallExpr__new(line, callable);
  13461. Ctx__s_push(ctx(), (Expr*)e); // push onto the stack in advance
  13462. do {
  13463. if(curr()->type == TK_RPAREN) break;
  13464. if(curr()->type == TK_ID && next()->type == TK_ASSIGN) {
  13465. consume(TK_ID);
  13466. py_Name key = py_namev(Token__sv(prev()));
  13467. consume(TK_ASSIGN);
  13468. check(EXPR(self));
  13469. CallExprKwArg kw = {key, Ctx__s_popx(ctx())};
  13470. c11_vector__push(CallExprKwArg, &e->kwargs, kw);
  13471. } else {
  13472. check(EXPR(self));
  13473. if(e->args.length == 0 && e->kwargs.length == 0 && match(TK_FOR)) { // LYNX: f(x for x in y)
  13474. check(consume_comp(self, OP_BUILD_LIST, OP_LIST_APPEND));
  13475. ((CompExpr*)Ctx__s_top(ctx()))->as_iter = true;
  13476. c11_vector__push(Expr*, &e->args, Ctx__s_popx(ctx()));
  13477. consume(TK_RPAREN);
  13478. return NULL;
  13479. }
  13480. int star_level = 0;
  13481. Expr* top = Ctx__s_top(ctx());
  13482. if(top->vt->is_starred) star_level = ((StarredExpr*)top)->level;
  13483. if(star_level == 2) {
  13484. // **kwargs
  13485. CallExprKwArg kw = {0, Ctx__s_popx(ctx())};
  13486. c11_vector__push(CallExprKwArg, &e->kwargs, kw);
  13487. } else {
  13488. // positional argument
  13489. if(e->kwargs.length > 0) {
  13490. return SyntaxError(self, "positional argument follows keyword argument");
  13491. }
  13492. c11_vector__push(Expr*, &e->args, Ctx__s_popx(ctx()));
  13493. }
  13494. }
  13495. } while(match(TK_COMMA));
  13496. consume(TK_RPAREN);
  13497. return NULL;
  13498. }
  13499. static Error* exprSlice0(Compiler* self) {
  13500. Error* err;
  13501. SliceExpr* slice = SliceExpr__new(prev()->line);
  13502. Ctx__s_push(ctx(), (Expr*)slice); // push onto the stack in advance
  13503. if(is_expression(self, false)) { // :<stop>
  13504. check(EXPR(self));
  13505. slice->stop = Ctx__s_popx(ctx());
  13506. // try optional step
  13507. if(match(TK_COLON)) { // :<stop>:<step>
  13508. check(EXPR(self));
  13509. slice->step = Ctx__s_popx(ctx());
  13510. }
  13511. } else if(match(TK_COLON)) {
  13512. if(is_expression(self, false)) { // ::<step>
  13513. check(EXPR(self));
  13514. slice->step = Ctx__s_popx(ctx());
  13515. } // else ::
  13516. } // else :
  13517. return NULL;
  13518. }
  13519. static Error* exprSlice1(Compiler* self) {
  13520. Error* err;
  13521. SliceExpr* slice = SliceExpr__new(prev()->line);
  13522. slice->start = Ctx__s_popx(ctx());
  13523. Ctx__s_push(ctx(), (Expr*)slice); // push onto the stack in advance
  13524. if(is_expression(self, false)) { // <start>:<stop>
  13525. check(EXPR(self));
  13526. slice->stop = Ctx__s_popx(ctx());
  13527. // try optional step
  13528. if(match(TK_COLON)) { // <start>:<stop>:<step>
  13529. check(EXPR(self));
  13530. slice->step = Ctx__s_popx(ctx());
  13531. }
  13532. } else if(match(TK_COLON)) { // <start>::<step>
  13533. check(EXPR(self));
  13534. slice->step = Ctx__s_popx(ctx());
  13535. } // else <start>:
  13536. return NULL;
  13537. }
  13538. static Error* exprSubscr(Compiler* self) {
  13539. Error* err;
  13540. int line = prev()->line;
  13541. check(EXPR_TUPLE_ALLOW_SLICE(self, true));
  13542. consume(TK_RBRACKET); // [lhs, rhs]
  13543. SubscrExpr* e = SubscrExpr__new(line);
  13544. e->rhs = Ctx__s_popx(ctx()); // [lhs]
  13545. e->lhs = Ctx__s_popx(ctx()); // []
  13546. Ctx__s_push(ctx(), (Expr*)e);
  13547. return NULL;
  13548. }
  13549. ////////////////
  13550. static Error* consume_type_hints(Compiler* self) {
  13551. Error* err;
  13552. check(EXPR(self));
  13553. Ctx__s_pop(ctx());
  13554. return NULL;
  13555. }
  13556. static Error* consume_type_hints_sv(Compiler* self, c11_sv* out) {
  13557. Error* err;
  13558. const char* start = curr()->start;
  13559. check(EXPR(self));
  13560. const char* end = prev()->start + prev()->length;
  13561. *out = (c11_sv){start, end - start};
  13562. Ctx__s_pop(ctx());
  13563. return NULL;
  13564. }
  13565. static Error* compile_stmt(Compiler* self);
  13566. static Error* compile_block_body(Compiler* self) {
  13567. Error* err;
  13568. consume(TK_COLON);
  13569. if(curr()->type != TK_EOL && curr()->type != TK_EOF) {
  13570. while(true) {
  13571. check(compile_stmt(self));
  13572. bool possible = curr()->type != TK_EOL && curr()->type != TK_EOF;
  13573. if(prev()->type != TK_SEMICOLON || !possible) break;
  13574. }
  13575. return NULL;
  13576. }
  13577. bool consumed = match_newlines();
  13578. if(!consumed) return SyntaxError(self, "expected a new line after ':'");
  13579. consume(TK_INDENT);
  13580. while(curr()->type != TK_DEDENT) {
  13581. match_newlines();
  13582. check(compile_stmt(self));
  13583. match_newlines();
  13584. }
  13585. consume(TK_DEDENT);
  13586. return NULL;
  13587. }
  13588. static Error* compile_if_stmt(Compiler* self) {
  13589. Error* err;
  13590. check(EXPR(self)); // condition
  13591. Ctx__s_emit_top(ctx());
  13592. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, prev()->line);
  13593. err = compile_block_body(self);
  13594. if(err) return err;
  13595. if(match(TK_ELIF)) {
  13596. int exit_patch = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, prev()->line);
  13597. Ctx__patch_jump(ctx(), patch);
  13598. check(compile_if_stmt(self));
  13599. Ctx__patch_jump(ctx(), exit_patch);
  13600. } else if(match(TK_ELSE)) {
  13601. int exit_patch = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, prev()->line);
  13602. Ctx__patch_jump(ctx(), patch);
  13603. check(compile_block_body(self));
  13604. Ctx__patch_jump(ctx(), exit_patch);
  13605. } else {
  13606. Ctx__patch_jump(ctx(), patch);
  13607. }
  13608. return NULL;
  13609. }
  13610. static Error* compile_match_case(Compiler* self, c11_vector* patches) {
  13611. Error* err;
  13612. bool is_case_default = false;
  13613. check(EXPR(self)); // condition
  13614. Ctx__s_emit_top(ctx());
  13615. consume(TK_COLON);
  13616. bool consumed = match_newlines();
  13617. if(!consumed) return SyntaxError(self, "expected a new line after ':'");
  13618. consume(TK_INDENT);
  13619. while(curr()->type != TK_DEDENT) {
  13620. match_newlines();
  13621. if(match_id_by_str(self, "case")) {
  13622. if(is_case_default) return SyntaxError(self, "case _: must be the last one");
  13623. is_case_default = match_id_by_str(self, "_");
  13624. if(!is_case_default) {
  13625. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, prev()->line);
  13626. check(EXPR(self)); // expr
  13627. Ctx__s_emit_top(ctx());
  13628. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_NOT_MATCH, BC_NOARG, prev()->line);
  13629. check(compile_block_body(self));
  13630. int break_patch = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, prev()->line);
  13631. c11_vector__push(int, patches, break_patch);
  13632. Ctx__patch_jump(ctx(), patch);
  13633. } else {
  13634. check(compile_block_body(self));
  13635. }
  13636. } else {
  13637. return SyntaxError(self, "expected 'case', got '%s'", TokenSymbols[curr()->type]);
  13638. }
  13639. match_newlines();
  13640. }
  13641. consume(TK_DEDENT);
  13642. for(int i = 0; i < patches->length; i++) {
  13643. int patch = c11__getitem(int, patches, i);
  13644. Ctx__patch_jump(ctx(), patch);
  13645. }
  13646. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, prev()->line);
  13647. return NULL;
  13648. }
  13649. static Error* compile_while_loop(Compiler* self) {
  13650. Error* err;
  13651. int block = Ctx__enter_block(ctx(), CodeBlockType_WHILE_LOOP);
  13652. int block_start = c11__at(CodeBlock, &ctx()->co->blocks, block)->start;
  13653. check(EXPR(self)); // condition
  13654. Ctx__s_emit_top(ctx());
  13655. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, prev()->line);
  13656. check(compile_block_body(self));
  13657. Ctx__emit_jump(ctx(), block_start, BC_KEEPLINE);
  13658. Ctx__patch_jump(ctx(), patch);
  13659. Ctx__exit_block(ctx());
  13660. // optional else clause
  13661. if(match(TK_ELSE)) {
  13662. check(compile_block_body(self));
  13663. CodeBlock* p_block = c11__at(CodeBlock, &ctx()->co->blocks, block);
  13664. p_block->end2 = ctx()->co->codes.length;
  13665. }
  13666. return NULL;
  13667. }
  13668. static Error* compile_for_loop(Compiler* self) {
  13669. Error* err;
  13670. check(EXPR_VARS(self)); // [vars]
  13671. consume(TK_IN);
  13672. check(EXPR_TUPLE(self)); // [vars, iter]
  13673. Ctx__s_emit_top(ctx()); // [vars]
  13674. Ctx__emit_(ctx(), OP_GET_ITER, BC_NOARG, BC_KEEPLINE);
  13675. int block = Ctx__enter_block(ctx(), CodeBlockType_FOR_LOOP);
  13676. int block_start = Ctx__emit_(ctx(), OP_FOR_ITER, block, BC_KEEPLINE);
  13677. Expr* vars = Ctx__s_popx(ctx());
  13678. bool ok = vtemit_store(vars, ctx());
  13679. vtdelete(vars);
  13680. if(!ok) {
  13681. // this error occurs in `vars` instead of this line, but...nevermind
  13682. return SyntaxError(self, "invalid syntax");
  13683. }
  13684. check(compile_block_body(self));
  13685. Ctx__emit_jump(ctx(), block_start, BC_KEEPLINE);
  13686. Ctx__exit_block(ctx());
  13687. // optional else clause
  13688. if(match(TK_ELSE)) {
  13689. check(compile_block_body(self));
  13690. CodeBlock* p_block = c11__at(CodeBlock, &ctx()->co->blocks, block);
  13691. p_block->end2 = ctx()->co->codes.length;
  13692. }
  13693. return NULL;
  13694. }
  13695. static Error* compile_yield_from(Compiler* self, int kw_line) {
  13696. Error* err;
  13697. if(self->contexts.length <= 1) return SyntaxError(self, "'yield from' outside function");
  13698. check(EXPR_TUPLE(self));
  13699. Ctx__s_emit_top(ctx());
  13700. Ctx__emit_(ctx(), OP_GET_ITER, BC_NOARG, kw_line);
  13701. int block = Ctx__enter_block(ctx(), CodeBlockType_FOR_LOOP);
  13702. int block_start = Ctx__emit_(ctx(), OP_FOR_ITER_YIELD_VALUE, block, kw_line);
  13703. Ctx__emit_jump(ctx(), block_start, BC_KEEPLINE);
  13704. Ctx__exit_block(ctx());
  13705. // StopIteration.value will be pushed onto the stack
  13706. return NULL;
  13707. }
  13708. Error* try_compile_assignment(Compiler* self, bool* is_assign) {
  13709. Error* err;
  13710. switch(curr()->type) {
  13711. case TK_IADD:
  13712. case TK_ISUB:
  13713. case TK_IMUL:
  13714. case TK_IDIV:
  13715. case TK_IFLOORDIV:
  13716. case TK_IMOD:
  13717. case TK_ILSHIFT:
  13718. case TK_IRSHIFT:
  13719. case TK_IAND:
  13720. case TK_IOR:
  13721. case TK_IXOR: {
  13722. if(Ctx__s_top(ctx())->vt->is_starred)
  13723. return SyntaxError(self, "can't use inplace operator with starred expression");
  13724. if(ctx()->is_compiling_class)
  13725. return SyntaxError(self, "can't use inplace operator in class definition");
  13726. advance();
  13727. // a[x] += 1; a and x should be evaluated only once
  13728. // a.x += 1; a should be evaluated only once
  13729. // -1 to remove =; inplace=true
  13730. int line = prev()->line;
  13731. TokenIndex op = (TokenIndex)(prev()->type - 1);
  13732. // [lhs]
  13733. check(EXPR_TUPLE(self)); // [lhs, rhs]
  13734. if(Ctx__s_top(ctx())->vt->is_starred)
  13735. return SyntaxError(self, "can't use starred expression here");
  13736. BinaryExpr* e = BinaryExpr__new(line, op, true);
  13737. e->rhs = Ctx__s_popx(ctx()); // [lhs]
  13738. e->lhs = Ctx__s_popx(ctx()); // []
  13739. vtemit_((Expr*)e, ctx());
  13740. bool ok = vtemit_istore(e->lhs, ctx());
  13741. vtdelete((Expr*)e);
  13742. if(!ok) return SyntaxError(self, "invalid syntax");
  13743. *is_assign = true;
  13744. return NULL;
  13745. }
  13746. case TK_ASSIGN: {
  13747. consume(TK_ASSIGN);
  13748. int n = 0; // assignment count
  13749. if(match(TK_YIELD_FROM)) {
  13750. check(compile_yield_from(self, prev()->line));
  13751. n = 1;
  13752. } else {
  13753. do {
  13754. check(EXPR_TUPLE(self));
  13755. n += 1;
  13756. } while(match(TK_ASSIGN));
  13757. // stack size is n+1
  13758. Ctx__s_emit_top(ctx());
  13759. for(int j = 1; j < n; j++)
  13760. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  13761. }
  13762. for(int j = 0; j < n; j++) {
  13763. if(Ctx__s_top(ctx())->vt->is_starred)
  13764. return SyntaxError(self, "can't use starred expression here");
  13765. Expr* e = Ctx__s_top(ctx());
  13766. bool ok = vtemit_store(e, ctx());
  13767. Ctx__s_pop(ctx());
  13768. if(!ok) return SyntaxError(self, "invalid syntax");
  13769. }
  13770. *is_assign = true;
  13771. return NULL;
  13772. }
  13773. default: *is_assign = false;
  13774. }
  13775. return NULL;
  13776. }
  13777. static FuncDecl_ push_f_context(Compiler* self, c11_sv name, int* out_index) {
  13778. FuncDecl_ decl = FuncDecl__rcnew(self->src, name);
  13779. decl->code.start_line = self->i == 0 ? 1 : prev()->line;
  13780. decl->nested = name_scope(self) == NAME_LOCAL;
  13781. // add_func_decl
  13782. Ctx* top_ctx = ctx();
  13783. c11_vector__push(FuncDecl_, &top_ctx->co->func_decls, decl);
  13784. *out_index = top_ctx->co->func_decls.length - 1;
  13785. // push new context
  13786. top_ctx = c11_vector__emplace(&self->contexts);
  13787. Ctx__ctor(top_ctx, &decl->code, decl, self->contexts.length, self->n_self);
  13788. return decl;
  13789. }
  13790. static Error* read_literal(Compiler* self, py_Ref out) {
  13791. Error* err;
  13792. advance();
  13793. const TokenValue* value = &prev()->value;
  13794. bool negated = false;
  13795. switch(prev()->type) {
  13796. case TK_SUB:
  13797. consume(TK_NUM);
  13798. value = &prev()->value;
  13799. negated = true;
  13800. case TK_NUM: {
  13801. if(value->index == TokenValue_I64) {
  13802. py_newint(out, negated ? -value->_i64 : value->_i64);
  13803. } else if(value->index == TokenValue_F64) {
  13804. py_newfloat(out, negated ? -value->_f64 : value->_f64);
  13805. } else {
  13806. c11__unreachable();
  13807. }
  13808. return NULL;
  13809. }
  13810. case TK_STR: py_newstr(out, value->_str->data); return NULL;
  13811. case TK_TRUE: py_newbool(out, true); return NULL;
  13812. case TK_FALSE: py_newbool(out, false); return NULL;
  13813. case TK_NONE: py_newnone(out); return NULL;
  13814. case TK_DOTDOTDOT: py_newellipsis(out); return NULL;
  13815. case TK_LPAREN: {
  13816. py_TValue cpnts[4];
  13817. int count = 0;
  13818. while(true) {
  13819. if(count == 4)
  13820. return SyntaxError(self, "default argument tuple exceeds 4 elements");
  13821. check(read_literal(self, &cpnts[count]));
  13822. count += 1;
  13823. if(curr()->type == TK_RPAREN) break;
  13824. consume(TK_COMMA);
  13825. if(curr()->type == TK_RPAREN) break;
  13826. }
  13827. consume(TK_RPAREN);
  13828. py_Ref p = py_newtuple(out, count);
  13829. for(int i = 0; i < count; i++) {
  13830. p[i] = cpnts[i];
  13831. }
  13832. return NULL;
  13833. }
  13834. default: {
  13835. return SyntaxError(self, "expected a literal, got '%s'", TokenSymbols[prev()->type]);
  13836. }
  13837. }
  13838. }
  13839. static Error* _compile_f_args(Compiler* self, FuncDecl* decl, bool is_lambda) {
  13840. int state = 0; // 0 for args, 1 for *args, 2 for k=v, 3 for **kwargs
  13841. Error* err;
  13842. do {
  13843. // allow trailing comma
  13844. if(!is_lambda && curr()->type == TK_RPAREN) break;
  13845. if(state >= 3) return SyntaxError(self, "**kwargs should be the last argument");
  13846. if(match(TK_MUL)) {
  13847. if(state < 1)
  13848. state = 1;
  13849. else
  13850. return SyntaxError(self, "*args should be placed before **kwargs");
  13851. } else if(match(TK_POW)) {
  13852. state = 3;
  13853. }
  13854. consume(TK_ID);
  13855. py_Name name = py_namev(Token__sv(prev()));
  13856. // check duplicate argument name
  13857. if(FuncDecl__is_duplicated_arg(decl, name)) {
  13858. return SyntaxError(self, "duplicate argument name");
  13859. }
  13860. // eat type hints
  13861. if(!is_lambda && match(TK_COLON)) check(consume_type_hints(self));
  13862. if(state == 0 && curr()->type == TK_ASSIGN) state = 2;
  13863. switch(state) {
  13864. case 0: FuncDecl__add_arg(decl, name); break;
  13865. case 1:
  13866. FuncDecl__add_starred_arg(decl, name);
  13867. state += 1;
  13868. break;
  13869. case 2: {
  13870. consume(TK_ASSIGN);
  13871. py_TValue value;
  13872. check(read_literal(self, &value));
  13873. FuncDecl__add_kwarg(decl, name, &value);
  13874. } break;
  13875. case 3:
  13876. FuncDecl__add_starred_kwarg(decl, name);
  13877. state += 1;
  13878. break;
  13879. }
  13880. } while(match(TK_COMMA));
  13881. return NULL;
  13882. }
  13883. static Error* consume_pep695_py312(Compiler* self) {
  13884. // https://peps.python.org/pep-0695/
  13885. Error* err;
  13886. if(match(TK_LBRACKET)) {
  13887. do {
  13888. if(match(TK_POW)) {
  13889. // **P
  13890. consume(TK_ID);
  13891. } else {
  13892. // T: int
  13893. consume(TK_ID);
  13894. if(match(TK_COLON)) check(consume_type_hints(self));
  13895. }
  13896. } while(match(TK_COMMA));
  13897. consume(TK_RBRACKET);
  13898. }
  13899. return NULL;
  13900. }
  13901. static Error* compile_function(Compiler* self, int decorators) {
  13902. Error* err;
  13903. int def_line = prev()->line;
  13904. consume(TK_ID);
  13905. c11_sv decl_name_sv = Token__sv(prev());
  13906. int decl_index;
  13907. FuncDecl_ decl = push_f_context(self, decl_name_sv, &decl_index);
  13908. consume_pep695_py312(self);
  13909. consume(TK_LPAREN);
  13910. if(!match(TK_RPAREN)) {
  13911. check(_compile_f_args(self, decl, false));
  13912. consume(TK_RPAREN);
  13913. }
  13914. if(match(TK_ARROW)) check(consume_type_hints(self));
  13915. check(compile_block_body(self));
  13916. check(pop_context(self));
  13917. if(decl->code.codes.length >= 2) {
  13918. Bytecode* codes = (Bytecode*)decl->code.codes.data;
  13919. if(codes[0].op == OP_LOAD_CONST && codes[1].op == OP_POP_TOP) {
  13920. // handle optional docstring
  13921. py_TValue* consts = decl->code.consts.data;
  13922. py_TValue* c = &consts[codes[0].arg];
  13923. if(py_isstr(c)) {
  13924. decl->docstring = c11_strdup(py_tostr(c));
  13925. codes[0].op = OP_NO_OP;
  13926. codes[1].op = OP_NO_OP;
  13927. }
  13928. }
  13929. }
  13930. Ctx__emit_(ctx(), OP_LOAD_FUNCTION, decl_index, def_line);
  13931. Ctx__s_emit_decorators(ctx(), decorators);
  13932. py_Name decl_name = py_namev(decl_name_sv);
  13933. if(ctx()->is_compiling_class) {
  13934. if(decl_name == __new__ || decl_name == __init__) {
  13935. if(decl->args.length == 0) {
  13936. return SyntaxError(self,
  13937. "%s() should have at least one positional argument",
  13938. py_name2str(decl_name));
  13939. }
  13940. }
  13941. Ctx__emit_(ctx(), OP_STORE_CLASS_ATTR, Ctx__add_name(ctx(), decl_name), def_line);
  13942. } else {
  13943. NameExpr* e = NameExpr__new(def_line, decl_name, name_scope(self));
  13944. vtemit_store((Expr*)e, ctx());
  13945. vtdelete((Expr*)e);
  13946. }
  13947. return NULL;
  13948. }
  13949. static Error* compile_class(Compiler* self, int decorators) {
  13950. Error* err;
  13951. if(ctx()->level > 1) return SyntaxError(self, "class definition not allowed here");
  13952. consume(TK_ID);
  13953. py_Name name = py_namev(Token__sv(prev()));
  13954. bool has_base = false;
  13955. consume_pep695_py312(self);
  13956. if(match(TK_LPAREN)) {
  13957. if(is_expression(self, false)) {
  13958. check(EXPR(self));
  13959. has_base = true; // [base]
  13960. }
  13961. while(match(TK_COMMA)) {
  13962. // ignore extra bases
  13963. check(consume_type_hints(self));
  13964. }
  13965. consume(TK_RPAREN);
  13966. }
  13967. if(!has_base) {
  13968. Ctx__emit_(ctx(), OP_LOAD_NONE, BC_NOARG, prev()->line);
  13969. } else {
  13970. Ctx__s_emit_top(ctx()); // []
  13971. }
  13972. Ctx__emit_(ctx(), OP_BEGIN_CLASS, Ctx__add_name(ctx(), name), BC_KEEPLINE);
  13973. c11__foreach(Ctx, &self->contexts, it) {
  13974. if(it->is_compiling_class) return SyntaxError(self, "nested class is not allowed");
  13975. }
  13976. ctx()->is_compiling_class = true;
  13977. check(compile_block_body(self));
  13978. ctx()->is_compiling_class = false;
  13979. Ctx__s_emit_decorators(ctx(), decorators);
  13980. Ctx__emit_(ctx(), OP_END_CLASS, Ctx__add_name(ctx(), name), BC_KEEPLINE);
  13981. return NULL;
  13982. }
  13983. static Error* compile_decorated(Compiler* self) {
  13984. Error* err;
  13985. int count = 0;
  13986. do {
  13987. check(EXPR(self));
  13988. count += 1;
  13989. if(!match_newlines()) return SyntaxError(self, "expected a newline after '@'");
  13990. } while(match(TK_DECORATOR));
  13991. if(match(TK_CLASS)) {
  13992. check(compile_class(self, count));
  13993. } else {
  13994. consume(TK_DEF);
  13995. check(compile_function(self, count));
  13996. }
  13997. return NULL;
  13998. }
  13999. // import a [as b]
  14000. // import a [as b], c [as d]
  14001. static Error* compile_normal_import(Compiler* self, c11_sbuf* buf) {
  14002. do {
  14003. consume(TK_ID);
  14004. c11_sv name = Token__sv(prev());
  14005. c11_sbuf__write_sv(buf, name);
  14006. bool has_sub_cpnt = false;
  14007. while(match(TK_DOT)) {
  14008. has_sub_cpnt = true;
  14009. consume(TK_ID);
  14010. c11_sbuf__write_char(buf, '.');
  14011. c11_sbuf__write_sv(buf, Token__sv(prev()));
  14012. }
  14013. c11_string* path = c11_sbuf__submit(buf);
  14014. c11_sbuf__ctor(buf);
  14015. int path_index = Ctx__add_const_string(ctx(), c11_string__sv(path));
  14016. c11_string__delete(path);
  14017. NameScope scope = name_scope(self);
  14018. Ctx__emit_(ctx(), OP_IMPORT_PATH, path_index, prev()->line);
  14019. // [module <path>]
  14020. if(!has_sub_cpnt) {
  14021. if(match(TK_AS)) {
  14022. // import a as x
  14023. consume(TK_ID);
  14024. name = Token__sv(prev());
  14025. } else {
  14026. // import a
  14027. }
  14028. } else {
  14029. if(match(TK_AS)) {
  14030. // import a.b as x
  14031. consume(TK_ID);
  14032. name = Token__sv(prev());
  14033. } else {
  14034. // import a.b
  14035. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  14036. int index = Ctx__add_const_string(ctx(), name);
  14037. Ctx__emit_(ctx(), OP_IMPORT_PATH, index, BC_KEEPLINE);
  14038. }
  14039. }
  14040. Ctx__emit_store_name(ctx(), scope, py_namev(name), BC_KEEPLINE);
  14041. } while(match(TK_COMMA));
  14042. consume_end_stmt();
  14043. return NULL;
  14044. }
  14045. // from a import b [as c], d [as e]
  14046. // from a.b import c [as d]
  14047. // from . import a [as b]
  14048. // from .a import b [as c]
  14049. // from ..a import b [as c]
  14050. // from .a.b import c [as d]
  14051. // from xxx import *
  14052. static Error* compile_from_import(Compiler* self, c11_sbuf* buf) {
  14053. int dots = 0;
  14054. while(true) {
  14055. switch(curr()->type) {
  14056. case TK_DOT: dots += 1; break;
  14057. case TK_DOTDOT: dots += 2; break;
  14058. case TK_DOTDOTDOT: dots += 3; break;
  14059. default: goto __EAT_DOTS_END;
  14060. }
  14061. advance();
  14062. }
  14063. __EAT_DOTS_END:
  14064. for(int i = 0; i < dots; i++) {
  14065. c11_sbuf__write_char(buf, '.');
  14066. }
  14067. if(dots > 0) {
  14068. // @id is optional if dots > 0
  14069. if(match(TK_ID)) {
  14070. c11_sbuf__write_sv(buf, Token__sv(prev()));
  14071. while(match(TK_DOT)) {
  14072. consume(TK_ID);
  14073. c11_sbuf__write_char(buf, '.');
  14074. c11_sbuf__write_sv(buf, Token__sv(prev()));
  14075. }
  14076. }
  14077. } else {
  14078. // @id is required if dots == 0
  14079. consume(TK_ID);
  14080. c11_sbuf__write_sv(buf, Token__sv(prev()));
  14081. while(match(TK_DOT)) {
  14082. consume(TK_ID);
  14083. c11_sbuf__write_char(buf, '.');
  14084. c11_sbuf__write_sv(buf, Token__sv(prev()));
  14085. }
  14086. }
  14087. c11_string* path = c11_sbuf__submit(buf);
  14088. Ctx__emit_(ctx(),
  14089. OP_IMPORT_PATH,
  14090. Ctx__add_const_string(ctx(), c11_string__sv(path)),
  14091. prev()->line);
  14092. c11_string__delete(path);
  14093. consume(TK_IMPORT);
  14094. if(match(TK_MUL)) {
  14095. if(name_scope(self) != NAME_GLOBAL)
  14096. return SyntaxError(self, "from <module> import * can only be used in global scope");
  14097. // pop the module and import __all__
  14098. Ctx__emit_(ctx(), OP_POP_IMPORT_STAR, BC_NOARG, prev()->line);
  14099. consume_end_stmt();
  14100. return NULL;
  14101. }
  14102. bool has_bracket = match(TK_LPAREN);
  14103. do {
  14104. Ctx__emit_(ctx(), OP_DUP_TOP, BC_NOARG, BC_KEEPLINE);
  14105. consume(TK_ID);
  14106. c11_sv name = Token__sv(prev());
  14107. Ctx__emit_(ctx(), OP_LOAD_ATTR, Ctx__add_name(ctx(), py_namev(name)), prev()->line);
  14108. if(match(TK_AS)) {
  14109. consume(TK_ID);
  14110. name = Token__sv(prev());
  14111. }
  14112. Ctx__emit_store_name(ctx(), name_scope(self), py_namev(name), prev()->line);
  14113. } while(match(TK_COMMA));
  14114. if(has_bracket) { consume(TK_RPAREN); }
  14115. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  14116. consume_end_stmt();
  14117. return NULL;
  14118. }
  14119. static Error* compile_try_except(Compiler* self) {
  14120. Error* err;
  14121. int patches[8];
  14122. int patches_length = 0;
  14123. Ctx__enter_block(ctx(), CodeBlockType_TRY);
  14124. Ctx__emit_(ctx(), OP_BEGIN_TRY, BC_NOARG, prev()->line);
  14125. check(compile_block_body(self));
  14126. Ctx__emit_(ctx(), OP_END_TRY, BC_NOARG, BC_KEEPLINE);
  14127. // https://docs.python.org/3/reference/compound_stmts.html#finally-clause
  14128. /* If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed,
  14129. * including any except and else clauses. If an exception occurs in any of the clauses and is
  14130. * not handled, the exception is temporarily saved. The finally clause is executed. If there is
  14131. * a saved exception it is re-raised at the end of the finally clause. If the finally clause
  14132. * raises another exception, the saved exception is set as the context of the new exception. If
  14133. * the finally clause executes a return, break or continue statement, the saved exception is
  14134. * discarded.
  14135. */
  14136. // known issue:
  14137. // A return, break, continue in try/except block will make the finally block not executed
  14138. bool has_finally = curr()->type == TK_FINALLY;
  14139. if(has_finally) return SyntaxError(self, "finally clause is not supported yet");
  14140. patches[patches_length++] = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  14141. Ctx__exit_block(ctx());
  14142. do {
  14143. if(patches_length == 8) {
  14144. return SyntaxError(self, "maximum number of except clauses reached");
  14145. }
  14146. py_Name as_name = 0;
  14147. consume(TK_EXCEPT);
  14148. if(is_expression(self, false)) {
  14149. // except <expr>:
  14150. check(EXPR(self));
  14151. Ctx__s_emit_top(ctx());
  14152. Ctx__emit_(ctx(), OP_EXCEPTION_MATCH, BC_NOARG, prev()->line);
  14153. if(match(TK_AS)) {
  14154. // except <expr> as <name>:
  14155. consume(TK_ID);
  14156. as_name = py_namev(Token__sv(prev()));
  14157. }
  14158. } else {
  14159. // except:
  14160. Ctx__emit_(ctx(), OP_LOAD_TRUE, BC_NOARG, BC_KEEPLINE);
  14161. }
  14162. int patch = Ctx__emit_(ctx(), OP_POP_JUMP_IF_FALSE, BC_NOARG, BC_KEEPLINE);
  14163. // on match
  14164. Ctx__emit_(ctx(), OP_HANDLE_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  14165. if(as_name) {
  14166. Ctx__emit_(ctx(), OP_PUSH_EXCEPTION, BC_NOARG, BC_KEEPLINE);
  14167. Ctx__emit_store_name(ctx(), name_scope(self), as_name, BC_KEEPLINE);
  14168. }
  14169. Ctx__enter_block(ctx(), CodeBlockType_EXCEPT);
  14170. check(compile_block_body(self));
  14171. Ctx__exit_block(ctx());
  14172. Ctx__emit_(ctx(), OP_END_TRY, BC_NOARG, BC_KEEPLINE);
  14173. patches[patches_length++] = Ctx__emit_(ctx(), OP_JUMP_FORWARD, BC_NOARG, BC_KEEPLINE);
  14174. Ctx__patch_jump(ctx(), patch);
  14175. } while(curr()->type == TK_EXCEPT);
  14176. // no match, re-raise
  14177. Ctx__emit_(ctx(), OP_RE_RAISE, BC_NOARG, BC_KEEPLINE);
  14178. // match one & handled, jump to the end
  14179. for(int i = 0; i < patches_length; i++) {
  14180. Ctx__patch_jump(ctx(), patches[i]);
  14181. }
  14182. if(match(TK_FINALLY)) return SyntaxError(self, "finally clause is not supported yet");
  14183. return NULL;
  14184. }
  14185. static Error* compile_stmt(Compiler* self) {
  14186. Error* err;
  14187. if(match(TK_CLASS)) {
  14188. check(compile_class(self, 0));
  14189. return NULL;
  14190. }
  14191. advance();
  14192. int kw_line = prev()->line; // backup line number
  14193. switch(prev()->type) {
  14194. case TK_BREAK: {
  14195. int curr_loop_block = Ctx__prepare_loop_divert(ctx(), kw_line, true);
  14196. if(curr_loop_block < 0) return SyntaxError(self, "'break' outside loop");
  14197. Ctx__emit_(ctx(), OP_LOOP_BREAK, curr_loop_block, kw_line);
  14198. consume_end_stmt();
  14199. break;
  14200. }
  14201. case TK_CONTINUE: {
  14202. int curr_loop_block = Ctx__prepare_loop_divert(ctx(), kw_line, false);
  14203. if(curr_loop_block < 0) return SyntaxError(self, "'continue' not properly in loop");
  14204. Ctx__emit_(ctx(), OP_LOOP_CONTINUE, curr_loop_block, kw_line);
  14205. consume_end_stmt();
  14206. break;
  14207. }
  14208. case TK_YIELD:
  14209. if(self->contexts.length <= 1) return SyntaxError(self, "'yield' outside function");
  14210. if(match_end_stmt(self)) {
  14211. Ctx__emit_(ctx(), OP_YIELD_VALUE, 1, kw_line);
  14212. } else {
  14213. check(EXPR_TUPLE(self));
  14214. Ctx__s_emit_top(ctx());
  14215. Ctx__emit_(ctx(), OP_YIELD_VALUE, BC_NOARG, kw_line);
  14216. consume_end_stmt();
  14217. }
  14218. break;
  14219. case TK_YIELD_FROM:
  14220. check(compile_yield_from(self, kw_line));
  14221. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, kw_line);
  14222. consume_end_stmt();
  14223. break;
  14224. case TK_RETURN:
  14225. if(self->contexts.length <= 1) return SyntaxError(self, "'return' outside function");
  14226. if(match_end_stmt(self)) {
  14227. Ctx__emit_(ctx(), OP_RETURN_VALUE, 1, kw_line);
  14228. } else {
  14229. check(EXPR_TUPLE(self));
  14230. Ctx__s_emit_top(ctx());
  14231. consume_end_stmt();
  14232. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, kw_line);
  14233. }
  14234. break;
  14235. /*************************************************/
  14236. case TK_IF: check(compile_if_stmt(self)); break;
  14237. case TK_MATCH: {
  14238. c11_vector patches;
  14239. c11_vector__ctor(&patches, sizeof(int));
  14240. check(compile_match_case(self, &patches));
  14241. c11_vector__dtor(&patches);
  14242. break;
  14243. }
  14244. case TK_WHILE: check(compile_while_loop(self)); break;
  14245. case TK_FOR: check(compile_for_loop(self)); break;
  14246. case TK_IMPORT: {
  14247. c11_sbuf buf;
  14248. c11_sbuf__ctor(&buf);
  14249. err = compile_normal_import(self, &buf);
  14250. c11_sbuf__dtor(&buf);
  14251. if(err) return err;
  14252. break;
  14253. }
  14254. case TK_FROM: {
  14255. c11_sbuf buf;
  14256. c11_sbuf__ctor(&buf);
  14257. err = compile_from_import(self, &buf);
  14258. c11_sbuf__dtor(&buf);
  14259. if(err) return err;
  14260. break;
  14261. }
  14262. case TK_DEF: check(compile_function(self, 0)); break;
  14263. case TK_DECORATOR: check(compile_decorated(self)); break;
  14264. case TK_TRY: check(compile_try_except(self)); break;
  14265. case TK_PASS: consume_end_stmt(); break;
  14266. /*************************************************/
  14267. case TK_ASSERT: {
  14268. check(EXPR(self)); // condition
  14269. Ctx__s_emit_top(ctx());
  14270. int index = Ctx__emit_(ctx(), OP_POP_JUMP_IF_TRUE, BC_NOARG, kw_line);
  14271. int has_msg = 0;
  14272. if(match(TK_COMMA)) {
  14273. check(EXPR(self)); // message
  14274. Ctx__s_emit_top(ctx());
  14275. has_msg = 1;
  14276. }
  14277. Ctx__emit_(ctx(), OP_RAISE_ASSERT, has_msg, kw_line);
  14278. Ctx__patch_jump(ctx(), index);
  14279. consume_end_stmt();
  14280. break;
  14281. }
  14282. case TK_GLOBAL:
  14283. do {
  14284. consume(TK_ID);
  14285. py_Name name = py_namev(Token__sv(prev()));
  14286. c11_smallmap_n2d__set(&ctx()->global_names, name, 0);
  14287. } while(match(TK_COMMA));
  14288. consume_end_stmt();
  14289. break;
  14290. case TK_RAISE: {
  14291. if(is_expression(self, false)) {
  14292. check(EXPR(self));
  14293. Ctx__s_emit_top(ctx());
  14294. Ctx__emit_(ctx(), OP_RAISE, BC_NOARG, kw_line);
  14295. } else {
  14296. int iblock = ctx()->curr_iblock;
  14297. CodeBlock* blocks = (CodeBlock*)ctx()->co->blocks.data;
  14298. if(blocks[iblock].type != CodeBlockType_EXCEPT) {
  14299. return SyntaxError(self,
  14300. "raise without exception is only allowed in except block");
  14301. }
  14302. Ctx__emit_(ctx(), OP_RE_RAISE, BC_NOARG, kw_line);
  14303. }
  14304. consume_end_stmt();
  14305. } break;
  14306. case TK_DEL: {
  14307. check(EXPR_TUPLE(self));
  14308. Expr* e = Ctx__s_top(ctx());
  14309. if(!vtemit_del(e, ctx())) return SyntaxError(self, "invalid syntax");
  14310. Ctx__s_pop(ctx());
  14311. consume_end_stmt();
  14312. } break;
  14313. case TK_WITH: {
  14314. check(EXPR(self)); // [ <expr> ]
  14315. Ctx__s_emit_top(ctx());
  14316. Ctx__enter_block(ctx(), CodeBlockType_WITH);
  14317. NameExpr* as_name = NULL;
  14318. if(match(TK_AS)) {
  14319. consume(TK_ID);
  14320. py_Name name = py_namev(Token__sv(prev()));
  14321. as_name = NameExpr__new(prev()->line, name, name_scope(self));
  14322. }
  14323. Ctx__emit_(ctx(), OP_WITH_ENTER, BC_NOARG, prev()->line);
  14324. // [ <expr> <expr>.__enter__() ]
  14325. if(as_name) {
  14326. bool ok = vtemit_store((Expr*)as_name, ctx());
  14327. vtdelete((Expr*)as_name);
  14328. if(!ok) return SyntaxError(self, "invalid syntax");
  14329. } else {
  14330. // discard `__enter__()`'s return value
  14331. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  14332. }
  14333. check(compile_block_body(self));
  14334. Ctx__emit_(ctx(), OP_WITH_EXIT, BC_NOARG, prev()->line);
  14335. Ctx__exit_block(ctx());
  14336. } break;
  14337. /*************************************************/
  14338. // handle dangling expression or assignment
  14339. default: {
  14340. // do revert since we have pre-called advance() at the beginning
  14341. --self->i;
  14342. check(EXPR_TUPLE(self));
  14343. bool is_typed_name = false; // e.g. x: int
  14344. // eat variable's type hint if it is a single name
  14345. const ExprVt* top_vt = Ctx__s_top(ctx())->vt;
  14346. if(top_vt->is_name || top_vt->is_attrib) {
  14347. if(match(TK_COLON)) {
  14348. c11_sv type_hint;
  14349. check(consume_type_hints_sv(self, &type_hint));
  14350. is_typed_name = true;
  14351. if(ctx()->is_compiling_class && top_vt->is_name) {
  14352. NameExpr* ne = (NameExpr*)Ctx__s_top(ctx());
  14353. int index = Ctx__add_const_string(ctx(), type_hint);
  14354. Ctx__emit_(ctx(), OP_LOAD_CONST, index, BC_KEEPLINE);
  14355. Ctx__emit_(ctx(),
  14356. OP_ADD_CLASS_ANNOTATION,
  14357. Ctx__add_name(ctx(), ne->name),
  14358. BC_KEEPLINE);
  14359. }
  14360. }
  14361. }
  14362. bool is_assign = false;
  14363. check(try_compile_assignment(self, &is_assign));
  14364. if(!is_assign) {
  14365. if(Ctx__s_size(ctx()) > 0 && Ctx__s_top(ctx())->vt->is_starred) {
  14366. return SyntaxError(self, "can't use starred expression here");
  14367. }
  14368. if(!is_typed_name) {
  14369. Ctx__s_emit_top(ctx());
  14370. if((mode() == SINGLE_MODE) && name_scope(self) == NAME_GLOBAL) {
  14371. Ctx__emit_(ctx(), OP_PRINT_EXPR, BC_NOARG, BC_KEEPLINE);
  14372. } else {
  14373. Ctx__emit_(ctx(), OP_POP_TOP, BC_NOARG, BC_KEEPLINE);
  14374. }
  14375. } else {
  14376. Ctx__s_pop(ctx());
  14377. }
  14378. }
  14379. consume_end_stmt();
  14380. break;
  14381. }
  14382. }
  14383. return NULL;
  14384. }
  14385. /////////////////////////////////////////////////////////////////
  14386. Error* Compiler__compile(Compiler* self, CodeObject* out) {
  14387. // make sure it is the first time to compile
  14388. assert(self->i == 0);
  14389. // make sure the first token is @sof
  14390. assert(tk(0)->type == TK_SOF);
  14391. push_global_context(self, out);
  14392. advance(); // skip @sof, so prev() is always valid
  14393. match_newlines(); // skip possible leading '\n'
  14394. Error* err;
  14395. if(mode() == EVAL_MODE) {
  14396. check(EXPR_TUPLE(self));
  14397. Ctx__s_emit_top(ctx());
  14398. consume(TK_EOF);
  14399. Ctx__emit_(ctx(), OP_RETURN_VALUE, BC_NOARG, BC_KEEPLINE);
  14400. check(pop_context(self));
  14401. return NULL;
  14402. }
  14403. while(!match(TK_EOF)) {
  14404. check(compile_stmt(self));
  14405. match_newlines();
  14406. }
  14407. check(pop_context(self));
  14408. return NULL;
  14409. }
  14410. Error* pk_compile(SourceData_ src, CodeObject* out) {
  14411. Token* tokens;
  14412. int tokens_length;
  14413. Error* err = Lexer__process(src, &tokens, &tokens_length);
  14414. if(err) return err;
  14415. #if 0
  14416. Token* data = (Token*)tokens.data;
  14417. printf("%s\n", src->filename->data);
  14418. for(int i = 0; i < tokens.length; i++) {
  14419. Token* t = data + i;
  14420. c11_string* tmp = c11_string__new2(t->start, t->length);
  14421. if(t->value.index == TokenValue_STR) {
  14422. const char* value_str = t->value._str->data;
  14423. printf("[%d] %s: %s (value._str=%s)\n",
  14424. t->line,
  14425. TokenSymbols[t->type],
  14426. tmp->data,
  14427. value_str);
  14428. } else {
  14429. printf("[%d] %s: %s\n", t->line, TokenSymbols[t->type], tmp->data);
  14430. }
  14431. c11_string__delete(tmp);
  14432. }
  14433. #endif
  14434. Compiler compiler;
  14435. Compiler__ctor(&compiler, src, tokens, tokens_length);
  14436. CodeObject__ctor(out, src, c11_string__sv(src->filename));
  14437. err = Compiler__compile(&compiler, out);
  14438. if(err) {
  14439. // dispose the code object if error occurs
  14440. CodeObject__dtor(out);
  14441. }
  14442. Compiler__dtor(&compiler);
  14443. return err;
  14444. }
  14445. // clang-format off
  14446. const static PrattRule rules[TK__COUNT__] = {
  14447. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  14448. [TK_DOT] = { NULL, exprAttrib, PREC_PRIMARY },
  14449. [TK_LPAREN] = { exprGroup, exprCall, PREC_PRIMARY },
  14450. [TK_LBRACKET] = { exprList, exprSubscr, PREC_PRIMARY },
  14451. [TK_MOD] = { NULL, exprBinaryOp, PREC_FACTOR },
  14452. [TK_ADD] = { NULL, exprBinaryOp, PREC_TERM },
  14453. [TK_SUB] = { exprUnaryOp, exprBinaryOp, PREC_TERM },
  14454. [TK_MUL] = { exprUnaryOp, exprBinaryOp, PREC_FACTOR },
  14455. [TK_INVERT] = { exprUnaryOp, NULL, PREC_UNARY },
  14456. [TK_DIV] = { NULL, exprBinaryOp, PREC_FACTOR },
  14457. [TK_FLOORDIV] = { NULL, exprBinaryOp, PREC_FACTOR },
  14458. [TK_POW] = { exprUnaryOp, exprBinaryOp, PREC_EXPONENT },
  14459. [TK_GT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14460. [TK_LT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14461. [TK_EQ] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14462. [TK_NE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14463. [TK_GE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14464. [TK_LE] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14465. [TK_IN] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14466. [TK_IS] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14467. [TK_LSHIFT] = { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
  14468. [TK_RSHIFT] = { NULL, exprBinaryOp, PREC_BITWISE_SHIFT },
  14469. [TK_AND] = { NULL, exprBinaryOp, PREC_BITWISE_AND },
  14470. [TK_OR] = { NULL, exprBinaryOp, PREC_BITWISE_OR },
  14471. [TK_XOR] = { NULL, exprBinaryOp, PREC_BITWISE_XOR },
  14472. [TK_DECORATOR] = { NULL, exprBinaryOp, PREC_FACTOR },
  14473. [TK_IF] = { NULL, exprTernary, PREC_TERNARY },
  14474. [TK_NOT_IN] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14475. [TK_IS_NOT] = { NULL, exprBinaryOp, PREC_COMPARISION },
  14476. [TK_AND_KW ] = { NULL, exprAnd, PREC_LOGICAL_AND },
  14477. [TK_OR_KW] = { NULL, exprOr, PREC_LOGICAL_OR },
  14478. [TK_NOT_KW] = { exprNot, NULL, PREC_LOGICAL_NOT },
  14479. [TK_WALRUS] = { NULL, exprWalrus, PREC_NAMED_EXPR },
  14480. [TK_TRUE] = { exprLiteral0 },
  14481. [TK_FALSE] = { exprLiteral0 },
  14482. [TK_NONE] = { exprLiteral0 },
  14483. [TK_DOTDOTDOT] = { exprLiteral0 },
  14484. [TK_LAMBDA] = { exprLambda, },
  14485. [TK_ID] = { exprName, },
  14486. [TK_NUM] = { exprLiteral, },
  14487. [TK_STR] = { exprLiteral, },
  14488. [TK_FSTR_BEGIN] = { exprFString, },
  14489. [TK_IMAG] = { exprImag, },
  14490. [TK_BYTES] = { exprBytes, },
  14491. [TK_LBRACE] = { exprMap },
  14492. [TK_COLON] = { exprSlice0, exprSlice1, PREC_PRIMARY }
  14493. };
  14494. // clang-format on
  14495. #undef vtcall
  14496. #undef vtemit_
  14497. #undef vtemit_del
  14498. #undef vtemit_store
  14499. #undef vtemit_inplace
  14500. #undef vtemit_istore
  14501. #undef vtdelete
  14502. #undef EXPR_COMMON_HEADER
  14503. #undef is_compare_expr
  14504. #undef tk
  14505. #undef prev
  14506. #undef curr
  14507. #undef next
  14508. #undef advance
  14509. #undef mode
  14510. #undef ctx
  14511. #undef match_newlines
  14512. #undef consume
  14513. #undef consume_end_stmt
  14514. #undef check
  14515. #undef match
  14516. // src/compiler\lexer.c
  14517. #include <ctype.h>
  14518. #define is_raw_string_used(t) ((t) == TK_ID)
  14519. typedef struct Lexer {
  14520. SourceData_ src;
  14521. const char* token_start;
  14522. const char* curr_char;
  14523. int current_line;
  14524. int brackets_level;
  14525. c11_vector /*T=Token*/ nexts;
  14526. c11_vector /*T=int*/ indents;
  14527. } Lexer;
  14528. const static TokenValue EmptyTokenValue;
  14529. static Error* lex_one_token(Lexer* self, bool* eof, bool is_fstring);
  14530. static void Lexer__ctor(Lexer* self, SourceData_ src) {
  14531. PK_INCREF(src);
  14532. self->src = src;
  14533. self->curr_char = self->token_start = src->source->data;
  14534. self->current_line = 1;
  14535. self->brackets_level = 0;
  14536. c11_vector__ctor(&self->nexts, sizeof(Token));
  14537. c11_vector__ctor(&self->indents, sizeof(int));
  14538. }
  14539. static void Lexer__dtor(Lexer* self) {
  14540. PK_DECREF(self->src);
  14541. c11_vector__dtor(&self->nexts);
  14542. c11_vector__dtor(&self->indents);
  14543. }
  14544. static char eatchar(Lexer* self) {
  14545. char c = *self->curr_char;
  14546. assert(c != '\n'); // eatchar() cannot consume a newline
  14547. self->curr_char++;
  14548. return c;
  14549. }
  14550. static char eatchar_include_newline(Lexer* self) {
  14551. char c = *self->curr_char;
  14552. self->curr_char++;
  14553. if(c == '\n') {
  14554. self->current_line++;
  14555. c11_vector__push(const char*, &self->src->line_starts, self->curr_char);
  14556. }
  14557. return c;
  14558. }
  14559. static int eat_spaces(Lexer* self) {
  14560. int count = 0;
  14561. while(true) {
  14562. switch(*self->curr_char) {
  14563. case ' ': count += 1; break;
  14564. case '\t': count += 4; break;
  14565. default: return count;
  14566. }
  14567. eatchar(self);
  14568. }
  14569. }
  14570. static bool matchchar(Lexer* self, char c) {
  14571. if(*self->curr_char != c) return false;
  14572. eatchar_include_newline(self);
  14573. return true;
  14574. }
  14575. static bool match_n_chars(Lexer* self, int n, char c0) {
  14576. const char* c = self->curr_char;
  14577. for(int i = 0; i < n; i++) {
  14578. if(*c == '\0') return false;
  14579. if(*c != c0) return false;
  14580. c++;
  14581. }
  14582. for(int i = 0; i < n; i++)
  14583. eatchar_include_newline(self);
  14584. return true;
  14585. }
  14586. static void skip_line_comment(Lexer* self) {
  14587. while(*self->curr_char) {
  14588. if(*self->curr_char == '\n') return;
  14589. eatchar(self);
  14590. }
  14591. }
  14592. static void add_token_with_value(Lexer* self, TokenIndex type, TokenValue value) {
  14593. switch(type) {
  14594. case TK_LBRACE:
  14595. case TK_LBRACKET:
  14596. case TK_LPAREN: self->brackets_level++; break;
  14597. case TK_RPAREN:
  14598. case TK_RBRACKET:
  14599. case TK_RBRACE: self->brackets_level--; break;
  14600. default: break;
  14601. }
  14602. Token token = {type,
  14603. self->token_start,
  14604. (int)(self->curr_char - self->token_start),
  14605. self->current_line - ((type == TK_EOL) ? 1 : 0),
  14606. self->brackets_level,
  14607. value};
  14608. // handle "not in", "is not", "yield from"
  14609. if(self->nexts.length > 0) {
  14610. Token* back = &c11_vector__back(Token, &self->nexts);
  14611. if(back->type == TK_NOT_KW && type == TK_IN) {
  14612. back->type = TK_NOT_IN;
  14613. return;
  14614. }
  14615. if(back->type == TK_IS && type == TK_NOT_KW) {
  14616. back->type = TK_IS_NOT;
  14617. return;
  14618. }
  14619. if(back->type == TK_YIELD && type == TK_FROM) {
  14620. back->type = TK_YIELD_FROM;
  14621. return;
  14622. }
  14623. c11_vector__push(Token, &self->nexts, token);
  14624. }
  14625. }
  14626. static void add_token(Lexer* self, TokenIndex type) {
  14627. add_token_with_value(self, type, EmptyTokenValue);
  14628. }
  14629. static void add_token_2(Lexer* self, char c, TokenIndex one, TokenIndex two) {
  14630. if(matchchar(self, c))
  14631. add_token(self, two);
  14632. else
  14633. add_token(self, one);
  14634. }
  14635. static bool eat_indentation(Lexer* self) {
  14636. if(self->brackets_level > 0) return true;
  14637. int spaces = eat_spaces(self);
  14638. if(*self->curr_char == '#') skip_line_comment(self);
  14639. if(*self->curr_char == '\0' || *self->curr_char == '\n') { return true; }
  14640. // https://docs.python.org/3/reference/lexical_analysis.html#indentation
  14641. int indents_back = c11_vector__back(int, &self->indents);
  14642. if(spaces > indents_back) {
  14643. c11_vector__push(int, &self->indents, spaces);
  14644. Token t = {TK_INDENT,
  14645. self->token_start,
  14646. 0,
  14647. self->current_line,
  14648. self->brackets_level,
  14649. EmptyTokenValue};
  14650. c11_vector__push(Token, &self->nexts, t);
  14651. } else if(spaces < indents_back) {
  14652. do {
  14653. c11_vector__pop(&self->indents);
  14654. Token t = {TK_DEDENT,
  14655. self->token_start,
  14656. 0,
  14657. self->current_line,
  14658. self->brackets_level,
  14659. EmptyTokenValue};
  14660. c11_vector__push(Token, &self->nexts, t);
  14661. indents_back = c11_vector__back(int, &self->indents);
  14662. } while(spaces < indents_back);
  14663. if(spaces != indents_back) { return false; }
  14664. }
  14665. return true;
  14666. }
  14667. static bool is_possible_number_char(char c) {
  14668. switch(c) {
  14669. // clang-format off
  14670. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
  14671. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  14672. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  14673. case '.': case 'x': case 'o': case 'j':
  14674. return true;
  14675. default: return false;
  14676. // clang-format on
  14677. }
  14678. }
  14679. /******************************/
  14680. static Error* LexerError(Lexer* self, const char* fmt, ...) {
  14681. Error* err = PK_MALLOC(sizeof(Error));
  14682. err->src = self->src;
  14683. PK_INCREF(self->src);
  14684. err->lineno = self->current_line;
  14685. const char* p_end = self->src->source->data + self->src->source->size;
  14686. if(self->curr_char <= p_end && *self->curr_char == '\n') { err->lineno--; }
  14687. va_list args;
  14688. va_start(args, fmt);
  14689. vsnprintf(err->msg, sizeof(err->msg), fmt, args);
  14690. va_end(args);
  14691. return err;
  14692. }
  14693. static Error* eat_name(Lexer* self) {
  14694. self->curr_char--;
  14695. while(true) {
  14696. unsigned char c = *self->curr_char;
  14697. int u8bytes = c11__u8_header(c, true);
  14698. if(u8bytes == 0) return LexerError(self, "invalid char: %c", c);
  14699. if(u8bytes == 1) {
  14700. if(isalnum(c) || c == '_') {
  14701. self->curr_char++;
  14702. continue;
  14703. } else {
  14704. break;
  14705. }
  14706. }
  14707. int value = c11__u8_value(u8bytes, self->curr_char);
  14708. if(c11__is_unicode_Lo_char(value)) {
  14709. self->curr_char += u8bytes;
  14710. } else {
  14711. break;
  14712. }
  14713. }
  14714. int length = (int)(self->curr_char - self->token_start);
  14715. if(length == 0) return LexerError(self, "@id contains invalid char");
  14716. c11_sv name = {self->token_start, length};
  14717. const char** KW_BEGIN = TokenSymbols + TK_FALSE;
  14718. int KW_COUNT = TK__COUNT__ - TK_FALSE;
  14719. #define less(a, b) (c11_sv__cmp2(b, a) > 0)
  14720. int out;
  14721. c11__lower_bound(const char*, KW_BEGIN, KW_COUNT, name, less, &out);
  14722. #undef less
  14723. if(out != KW_COUNT && c11__sveq2(name, KW_BEGIN[out]) && (out + TK_FALSE) == TK_MATCH) {
  14724. // LYNX: "match" is a soft keyword (CPython): a name unless it starts a statement and is not followed by
  14725. // ".", "=", "(", ")", ",", ":" or "]" (re.match(...), match = ..., def match(...))
  14726. TokenIndex prev = self->nexts.length > 0 ? c11_vector__back(Token, &self->nexts).type : TK_SOF;
  14727. const char* p = self->curr_char;
  14728. while(*p == ' ' || *p == '\t') p++;
  14729. bool at_start = prev == TK_EOL || prev == TK_SOF || prev == TK_INDENT || prev == TK_DEDENT;
  14730. bool name_like = *p == '.' || *p == '=' || *p == '(' || *p == ')' || *p == ',' || *p == ':' || *p == ']';
  14731. add_token(self, at_start && !name_like ? TK_MATCH : TK_ID);
  14732. } else if(out != KW_COUNT && c11__sveq2(name, KW_BEGIN[out])) {
  14733. add_token(self, (TokenIndex)(out + TK_FALSE));
  14734. } else {
  14735. add_token(self, TK_ID);
  14736. }
  14737. return NULL;
  14738. }
  14739. enum StringType { NORMAL_STRING, RAW_STRING, F_STRING, NORMAL_BYTES };
  14740. static Error* _eat_string(Lexer* self, c11_sbuf* buff, char quote, enum StringType type) {
  14741. bool is_raw = type == RAW_STRING;
  14742. bool is_fstring = type == F_STRING;
  14743. if(is_fstring) { add_token(self, TK_FSTR_BEGIN); }
  14744. // previous char is quote
  14745. bool quote3 = match_n_chars(self, 2, quote);
  14746. while(true) {
  14747. char c = eatchar_include_newline(self);
  14748. if(c == quote) {
  14749. if(quote3 && !match_n_chars(self, 2, quote)) {
  14750. c11_sbuf__write_char(buff, c);
  14751. continue;
  14752. }
  14753. // end of string
  14754. break;
  14755. }
  14756. if(c == '\0') { return LexerError(self, "EOL while scanning string literal"); }
  14757. if(c == '\n') {
  14758. if(!quote3)
  14759. return LexerError(self, "EOL while scanning string literal");
  14760. else {
  14761. c11_sbuf__write_char(buff, c);
  14762. continue;
  14763. }
  14764. }
  14765. if(!is_raw && c == '\\') {
  14766. switch(eatchar_include_newline(self)) {
  14767. // For the list of available escape sequences see
  14768. // https://docs.python.org/3/reference/lexical_analysis.html#escape-sequences
  14769. case '\n': break; // LYNX: a backslash before a line break continues the line
  14770. case '"': c11_sbuf__write_char(buff, '"'); break;
  14771. case '\'': c11_sbuf__write_char(buff, '\''); break;
  14772. case '\\': c11_sbuf__write_char(buff, '\\'); break;
  14773. case 'n': c11_sbuf__write_char(buff, '\n'); break;
  14774. case 'r': c11_sbuf__write_char(buff, '\r'); break;
  14775. case 't': c11_sbuf__write_char(buff, '\t'); break;
  14776. case 'a': c11_sbuf__write_char(buff, '\a'); break;
  14777. case 'b': c11_sbuf__write_char(buff, '\b'); break;
  14778. case 'f': c11_sbuf__write_char(buff, '\f'); break;
  14779. case 'v': c11_sbuf__write_char(buff, '\v'); break;
  14780. // Special case for the often used \0 while we don't have full support for octal
  14781. // literals.
  14782. case '0': c11_sbuf__write_char(buff, '\0'); break;
  14783. case 'x': {
  14784. // check there are at least 2 chars can read
  14785. const char* p_end = self->src->source->data + self->src->source->size;
  14786. if(p_end - self->curr_char < 2) {
  14787. return LexerError(self, "invalid hex escape");
  14788. }
  14789. char hex[3] = {eatchar(self), eatchar(self), '\0'};
  14790. int code;
  14791. if(sscanf(hex, "%x", &code) != 1 || code > 0xFF) {
  14792. return LexerError(self, "invalid hex escape");
  14793. }
  14794. if(type == NORMAL_BYTES) {
  14795. // Bytes literals: write raw byte
  14796. c11_sbuf__write_char(buff, (char)code);
  14797. } else {
  14798. // Regular strings: encode as UTF-8
  14799. if(code <= 0x7F) {
  14800. c11_sbuf__write_char(buff, (char)code);
  14801. } else {
  14802. // Encode as 2-byte UTF-8 for code points 0x80-0xFF
  14803. c11_sbuf__write_char(buff, 0xC0 | (code >> 6)); // Leading byte
  14804. c11_sbuf__write_char(buff, 0x80 | (code & 0x3F)); // Continuation byte
  14805. }
  14806. }
  14807. } break;
  14808. default: return LexerError(self, "invalid escape char");
  14809. }
  14810. } else {
  14811. if(is_fstring) {
  14812. if(c == '{') {
  14813. if(matchchar(self, '{')) {
  14814. // '{{' -> '{'
  14815. c11_sbuf__write_char(buff, '{');
  14816. } else {
  14817. // submit previous string
  14818. c11_string* res = c11_sbuf__submit(buff);
  14819. if(res->size > 0) {
  14820. TokenValue value = {TokenValue_STR, ._str = res};
  14821. add_token_with_value(self, TK_FSTR_CPNT, value);
  14822. } else {
  14823. c11_string__delete(res);
  14824. }
  14825. c11_sbuf__ctor(buff); // re-init buffer
  14826. // submit {expr} tokens
  14827. bool eof = false;
  14828. int token_count = self->nexts.length;
  14829. while(!eof) {
  14830. Error* err = lex_one_token(self, &eof, true);
  14831. if(err) return err;
  14832. }
  14833. if(self->nexts.length == token_count) {
  14834. // f'{}' is not allowed
  14835. return LexerError(self, "f-string: empty expression not allowed");
  14836. }
  14837. }
  14838. } else if(c == '}') {
  14839. if(matchchar(self, '}')) {
  14840. // '}}' -> '}'
  14841. c11_sbuf__write_char(buff, '}');
  14842. } else {
  14843. return LexerError(self, "f-string: single '}' is not allowed");
  14844. }
  14845. } else {
  14846. c11_sbuf__write_char(buff, c);
  14847. }
  14848. } else {
  14849. c11_sbuf__write_char(buff, c);
  14850. }
  14851. }
  14852. }
  14853. c11_string* res = c11_sbuf__submit(buff);
  14854. TokenValue value = {TokenValue_STR, ._str = res};
  14855. if(is_fstring) {
  14856. if(res->size > 0) {
  14857. add_token_with_value(self, TK_FSTR_CPNT, value);
  14858. } else {
  14859. c11_string__delete(res);
  14860. }
  14861. add_token(self, TK_FSTR_END);
  14862. return NULL;
  14863. }
  14864. if(type == NORMAL_BYTES) {
  14865. add_token_with_value(self, TK_BYTES, value);
  14866. } else {
  14867. add_token_with_value(self, TK_STR, value);
  14868. }
  14869. return NULL;
  14870. }
  14871. static Error* eat_string(Lexer* self, char quote, enum StringType type) {
  14872. c11_sbuf buff;
  14873. c11_sbuf__ctor(&buff);
  14874. Error* err = _eat_string(self, &buff, quote, type);
  14875. c11_sbuf__dtor(&buff);
  14876. return err;
  14877. }
  14878. static Error* eat_number(Lexer* self) {
  14879. const char* i = self->token_start;
  14880. while(is_possible_number_char(*i))
  14881. i++;
  14882. bool is_scientific_notation = false;
  14883. if(*(i - 1) == 'e' && (*i == '+' || *i == '-')) {
  14884. i++;
  14885. while(isdigit(*i) || *i == 'j')
  14886. i++;
  14887. is_scientific_notation = true;
  14888. }
  14889. c11_sv text = {self->token_start, i - self->token_start};
  14890. self->curr_char = i;
  14891. if(text.data[0] != '.' && !is_scientific_notation) {
  14892. // try integer
  14893. TokenValue value = {.index = TokenValue_I64};
  14894. switch(c11__parse_uint(text, &value._i64, -1)) {
  14895. case IntParsing_SUCCESS: add_token_with_value(self, TK_NUM, value); return NULL;
  14896. case IntParsing_OVERFLOW: return LexerError(self, "int literal is too large");
  14897. case IntParsing_FAILURE: break; // do nothing
  14898. }
  14899. }
  14900. // try float
  14901. double float_out;
  14902. char* p_end;
  14903. float_out = strtod(text.data, &p_end);
  14904. if(p_end == text.data + text.size) {
  14905. TokenValue value = {.index = TokenValue_F64, ._f64 = float_out};
  14906. add_token_with_value(self, TK_NUM, value);
  14907. return NULL;
  14908. }
  14909. if(i[-1] == 'j' && p_end == text.data + text.size - 1) {
  14910. TokenValue value = {.index = TokenValue_F64, ._f64 = float_out};
  14911. add_token_with_value(self, TK_IMAG, value);
  14912. return NULL;
  14913. }
  14914. return LexerError(self, "invalid number literal");
  14915. }
  14916. static Error* eat_fstring_spec(Lexer* self, bool* eof) {
  14917. while(true) {
  14918. char c = eatchar_include_newline(self);
  14919. if(c == '\n' || c == '\0') {
  14920. return LexerError(self, "EOL while scanning f-string format spec");
  14921. }
  14922. if(c == '}') {
  14923. add_token(self, TK_FSTR_SPEC);
  14924. *eof = true;
  14925. break;
  14926. }
  14927. }
  14928. return NULL;
  14929. }
  14930. static Error* lex_one_token(Lexer* self, bool* eof, bool is_fstring) {
  14931. *eof = false;
  14932. while(*self->curr_char) {
  14933. self->token_start = self->curr_char;
  14934. char c = eatchar_include_newline(self);
  14935. switch(c) {
  14936. case '\'':
  14937. case '"': {
  14938. Error* err = eat_string(self, c, NORMAL_STRING);
  14939. if(err) return err;
  14940. return NULL;
  14941. }
  14942. case '#': skip_line_comment(self); break;
  14943. case '~': add_token(self, TK_INVERT); return NULL;
  14944. case '{': add_token(self, TK_LBRACE); return NULL;
  14945. case '}': {
  14946. if(is_fstring) {
  14947. *eof = true;
  14948. return NULL;
  14949. }
  14950. add_token(self, TK_RBRACE);
  14951. return NULL;
  14952. }
  14953. case ',': add_token(self, TK_COMMA); return NULL;
  14954. case ':': {
  14955. if(is_fstring) {
  14956. // BUG: f"{stack[2:]}"
  14957. return eat_fstring_spec(self, eof);
  14958. }
  14959. if(matchchar(self, '=')) {
  14960. add_token(self, TK_WALRUS);
  14961. } else {
  14962. add_token(self, TK_COLON);
  14963. }
  14964. return NULL;
  14965. }
  14966. case ';': add_token(self, TK_SEMICOLON); return NULL;
  14967. case '(': add_token(self, TK_LPAREN); return NULL;
  14968. case ')': add_token(self, TK_RPAREN); return NULL;
  14969. case '[': add_token(self, TK_LBRACKET); return NULL;
  14970. case ']': add_token(self, TK_RBRACKET); return NULL;
  14971. case '@': add_token(self, TK_DECORATOR); return NULL;
  14972. case '\\': {
  14973. // line continuation character
  14974. char c = eatchar_include_newline(self);
  14975. if(c != '\n') {
  14976. return LexerError(self, "expected newline after line continuation character");
  14977. }
  14978. eat_spaces(self);
  14979. return NULL;
  14980. }
  14981. case '%': add_token_2(self, '=', TK_MOD, TK_IMOD); return NULL;
  14982. case '&': add_token_2(self, '=', TK_AND, TK_IAND); return NULL;
  14983. case '|': add_token_2(self, '=', TK_OR, TK_IOR); return NULL;
  14984. case '^': add_token_2(self, '=', TK_XOR, TK_IXOR); return NULL;
  14985. case '.': {
  14986. if(matchchar(self, '.')) {
  14987. if(matchchar(self, '.')) {
  14988. add_token(self, TK_DOTDOTDOT);
  14989. } else {
  14990. add_token(self, TK_DOTDOT);
  14991. }
  14992. } else {
  14993. char next_char = *self->curr_char;
  14994. if(next_char >= '0' && next_char <= '9') {
  14995. Error* err = eat_number(self);
  14996. if(err) return err;
  14997. } else {
  14998. add_token(self, TK_DOT);
  14999. }
  15000. }
  15001. return NULL;
  15002. }
  15003. case '=': add_token_2(self, '=', TK_ASSIGN, TK_EQ); return NULL;
  15004. case '+': add_token_2(self, '=', TK_ADD, TK_IADD); return NULL;
  15005. case '>': {
  15006. if(matchchar(self, '='))
  15007. add_token(self, TK_GE);
  15008. else if(matchchar(self, '>'))
  15009. add_token_2(self, '=', TK_RSHIFT, TK_IRSHIFT);
  15010. else
  15011. add_token(self, TK_GT);
  15012. return NULL;
  15013. }
  15014. case '<': {
  15015. if(matchchar(self, '='))
  15016. add_token(self, TK_LE);
  15017. else if(matchchar(self, '<'))
  15018. add_token_2(self, '=', TK_LSHIFT, TK_ILSHIFT);
  15019. else
  15020. add_token(self, TK_LT);
  15021. return NULL;
  15022. }
  15023. case '-': {
  15024. if(matchchar(self, '='))
  15025. add_token(self, TK_ISUB);
  15026. else if(matchchar(self, '>'))
  15027. add_token(self, TK_ARROW);
  15028. else
  15029. add_token(self, TK_SUB);
  15030. return NULL;
  15031. }
  15032. case '!':
  15033. if(is_fstring) {
  15034. if(matchchar(self, 'r')) { return eat_fstring_spec(self, eof); }
  15035. }
  15036. if(matchchar(self, '=')) {
  15037. add_token(self, TK_NE);
  15038. return NULL;
  15039. } else {
  15040. return LexerError(self, "expected '=' after '!'");
  15041. }
  15042. case '*':
  15043. if(matchchar(self, '*')) {
  15044. add_token(self, TK_POW); // '**'
  15045. } else {
  15046. add_token_2(self, '=', TK_MUL, TK_IMUL);
  15047. }
  15048. return NULL;
  15049. case '/':
  15050. if(matchchar(self, '/')) {
  15051. add_token_2(self, '=', TK_FLOORDIV, TK_IFLOORDIV);
  15052. } else {
  15053. add_token_2(self, '=', TK_DIV, TK_IDIV);
  15054. }
  15055. return NULL;
  15056. case ' ':
  15057. case '\t': eat_spaces(self); break;
  15058. case '\n': {
  15059. if(self->brackets_level > 0) return NULL;
  15060. add_token(self, TK_EOL);
  15061. if(!eat_indentation(self)) {
  15062. return LexerError(self, "unindent does not match any outer indentation level");
  15063. }
  15064. return NULL;
  15065. }
  15066. default: {
  15067. if(c == 'f') {
  15068. if(matchchar(self, '\'')) return eat_string(self, '\'', F_STRING);
  15069. if(matchchar(self, '"')) return eat_string(self, '"', F_STRING);
  15070. } else if(c == 'r') {
  15071. if(matchchar(self, '\'')) return eat_string(self, '\'', RAW_STRING);
  15072. if(matchchar(self, '"')) return eat_string(self, '"', RAW_STRING);
  15073. } else if(c == 'b') {
  15074. if(matchchar(self, '\'')) return eat_string(self, '\'', NORMAL_BYTES);
  15075. if(matchchar(self, '"')) return eat_string(self, '"', NORMAL_BYTES);
  15076. }
  15077. if(c >= '0' && c <= '9') return eat_number(self);
  15078. return eat_name(self);
  15079. }
  15080. }
  15081. }
  15082. if(is_fstring) return LexerError(self, "unterminated f-string expression");
  15083. self->token_start = self->curr_char;
  15084. while(self->indents.length > 1) {
  15085. c11_vector__pop(&self->indents);
  15086. add_token(self, TK_DEDENT);
  15087. return NULL;
  15088. }
  15089. add_token(self, TK_EOF);
  15090. *eof = true;
  15091. return NULL;
  15092. }
  15093. Error* Lexer__process(SourceData_ src, Token** out_tokens, int* out_length) {
  15094. Lexer lexer;
  15095. Lexer__ctor(&lexer, src);
  15096. // push initial tokens
  15097. Token sof =
  15098. {TK_SOF, lexer.token_start, 0, lexer.current_line, lexer.brackets_level, EmptyTokenValue};
  15099. c11_vector__push(Token, &lexer.nexts, sof);
  15100. c11_vector__push(int, &lexer.indents, 0);
  15101. bool eof = false;
  15102. while(!eof) {
  15103. void* err = lex_one_token(&lexer, &eof, false);
  15104. if(err) {
  15105. destruct_tokens(lexer.nexts.data, lexer.nexts.length);
  15106. Lexer__dtor(&lexer);
  15107. return err;
  15108. }
  15109. }
  15110. // set out_tokens
  15111. *out_tokens = c11_vector__submit(&lexer.nexts, out_length);
  15112. Lexer__dtor(&lexer);
  15113. return NULL;
  15114. }
  15115. void destruct_tokens(Token* tokens, int length) {
  15116. // free tokens
  15117. for(int i = 0; i < length; i++) {
  15118. if(tokens[i].value.index == TokenValue_STR) {
  15119. // PK_FREE internal string
  15120. c11_string__delete(tokens[i].value._str);
  15121. }
  15122. }
  15123. }
  15124. const char* TokenSymbols[] = {
  15125. "@eof",
  15126. "@eol",
  15127. "@sof",
  15128. "@id",
  15129. "@num",
  15130. "@str",
  15131. "@fstr-begin", // TK_FSTR_BEGIN
  15132. "@fstr-cpnt", // TK_FSTR_CPNT
  15133. "@fstr-spec", // TK_FSTR_SPEC
  15134. "@fstr-end", // TK_FSTR_END
  15135. "@bytes",
  15136. "@imag",
  15137. "@indent",
  15138. "@dedent",
  15139. // These 3 are compound keywords which are generated on the fly
  15140. "is not",
  15141. "not in",
  15142. "yield from",
  15143. /*****************************************/
  15144. "+",
  15145. "+=",
  15146. "-",
  15147. "-=", // (INPLACE_OP - 1) can get '=' removed
  15148. "*",
  15149. "*=",
  15150. "/",
  15151. "/=",
  15152. "//",
  15153. "//=",
  15154. "%",
  15155. "%=",
  15156. "&",
  15157. "&=",
  15158. "|",
  15159. "|=",
  15160. "^",
  15161. "^=",
  15162. "<<",
  15163. "<<=",
  15164. ">>",
  15165. ">>=",
  15166. /*****************************************/
  15167. "(",
  15168. ")",
  15169. "[",
  15170. "]",
  15171. "{",
  15172. "}",
  15173. ".",
  15174. "..",
  15175. "...",
  15176. ",",
  15177. ":",
  15178. ";",
  15179. "**",
  15180. "->",
  15181. "#",
  15182. "@",
  15183. ">",
  15184. "<",
  15185. "=",
  15186. "==",
  15187. "!=",
  15188. ">=",
  15189. "<=",
  15190. "~",
  15191. ":=",
  15192. /** KW_BEGIN **/
  15193. // NOTE: These keywords should be sorted in ascending order!!
  15194. "False",
  15195. "None",
  15196. "True",
  15197. "and",
  15198. "as",
  15199. "assert",
  15200. "break",
  15201. "class",
  15202. "continue",
  15203. "def",
  15204. "del",
  15205. "elif",
  15206. "else",
  15207. "except",
  15208. "finally",
  15209. "for",
  15210. "from",
  15211. "global",
  15212. "if",
  15213. "import",
  15214. "in",
  15215. "is",
  15216. "lambda",
  15217. "match",
  15218. "not",
  15219. "or",
  15220. "pass",
  15221. "raise",
  15222. "return",
  15223. "try",
  15224. "while",
  15225. "with",
  15226. "yield",
  15227. };
  15228. #undef is_raw_string_used
  15229. // src/debugger\core.c
  15230. #include <ctype.h>
  15231. #if PK_ENABLE_OS
  15232. typedef struct c11_debugger_breakpoint {
  15233. const char* sourcename;
  15234. int lineno;
  15235. } c11_debugger_breakpoint;
  15236. typedef struct c11_debugger_scope_index {
  15237. int locals_ref;
  15238. int globals_ref;
  15239. } c11_debugger_scope_index;
  15240. #define SMALLMAP_T__HEADER
  15241. #define SMALLMAP_T__SOURCE
  15242. #define K int
  15243. #define V c11_debugger_scope_index
  15244. #define NAME c11_smallmap_d2index
  15245. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  15246. #include "pocketpy/common/vector.h"
  15247. #include "pocketpy/common/utils.h"
  15248. #include "pocketpy/config.h"
  15249. #define SMALLMAP_T__HEADER
  15250. #define SMALLMAP_T__SOURCE
  15251. /* Input */
  15252. #define K int
  15253. #define V float
  15254. #define NAME c11_smallmap_d2f
  15255. #endif
  15256. /* Optional Input */
  15257. #ifndef less
  15258. #define less(a, b) ((a) < (b))
  15259. #endif
  15260. #ifndef equal
  15261. #define equal(a, b) ((a) == (b))
  15262. #endif
  15263. /* Temporary macros */
  15264. #define partial_less(a, b) less((a).key, (b))
  15265. #define CONCAT(A, B) CONCAT_(A, B)
  15266. #define CONCAT_(A, B) A##B
  15267. #define KV CONCAT(NAME, _KV)
  15268. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  15269. #ifdef SMALLMAP_T__HEADER
  15270. /* Declaration */
  15271. typedef struct {
  15272. K key;
  15273. V value;
  15274. } KV;
  15275. typedef c11_vector NAME;
  15276. void METHOD(ctor)(NAME* self);
  15277. void METHOD(dtor)(NAME* self);
  15278. NAME* METHOD(new)();
  15279. void METHOD(delete)(NAME* self);
  15280. void METHOD(set)(NAME* self, K key, V value);
  15281. V* METHOD(try_get)(const NAME* self, K key);
  15282. V METHOD(get)(const NAME* self, K key, V default_value);
  15283. bool METHOD(contains)(const NAME* self, K key);
  15284. bool METHOD(del)(NAME* self, K key);
  15285. void METHOD(clear)(NAME* self);
  15286. #endif
  15287. #ifdef SMALLMAP_T__SOURCE
  15288. /* Implementation */
  15289. void METHOD(ctor)(NAME* self) {
  15290. c11_vector__ctor(self, sizeof(KV));
  15291. c11_vector__reserve(self, 4);
  15292. }
  15293. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  15294. NAME* METHOD(new)() {
  15295. NAME* self = PK_MALLOC(sizeof(NAME));
  15296. METHOD(ctor)(self);
  15297. return self;
  15298. }
  15299. void METHOD(delete)(NAME* self) {
  15300. METHOD(dtor)(self);
  15301. PK_FREE(self);
  15302. }
  15303. void METHOD(set)(NAME* self, K key, V value) {
  15304. int index;
  15305. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  15306. if(index != self->length) {
  15307. KV* it = c11__at(KV, self, index);
  15308. if(equal(it->key, key)) {
  15309. it->value = value;
  15310. return;
  15311. }
  15312. }
  15313. KV kv = {key, value};
  15314. c11_vector__insert(KV, self, index, kv);
  15315. }
  15316. V* METHOD(try_get)(const NAME* self, K key) {
  15317. int index;
  15318. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  15319. if(index != self->length) {
  15320. KV* it = c11__at(KV, self, index);
  15321. if(equal(it->key, key)) return &it->value;
  15322. }
  15323. return NULL;
  15324. }
  15325. V METHOD(get)(const NAME* self, K key, V default_value) {
  15326. V* p = METHOD(try_get)(self, key);
  15327. return p ? *p : default_value;
  15328. }
  15329. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  15330. bool METHOD(del)(NAME* self, K key) {
  15331. int index;
  15332. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  15333. if(index != self->length) {
  15334. KV* it = c11__at(KV, self, index);
  15335. if(equal(it->key, key)) {
  15336. c11_vector__erase(KV, self, index);
  15337. return true;
  15338. }
  15339. }
  15340. return false;
  15341. }
  15342. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  15343. #endif
  15344. /* Undefine all macros */
  15345. #undef KV
  15346. #undef METHOD
  15347. #undef CONCAT
  15348. #undef CONCAT_
  15349. #undef K
  15350. #undef V
  15351. #undef NAME
  15352. #undef less
  15353. #undef partial_less
  15354. #undef equal
  15355. #undef SMALLMAP_T__SOURCE
  15356. #undef SMALLMAP_T__HEADER
  15357. static struct c11_debugger {
  15358. py_Frame* current_frame;
  15359. const char* current_filename;
  15360. const char* current_excname;
  15361. const char* current_excmessage;
  15362. enum py_TraceEvent current_event;
  15363. int curr_stack_depth;
  15364. int current_line;
  15365. int pause_allowed_depth;
  15366. int step_line;
  15367. C11_STEP_MODE step_mode;
  15368. bool keep_suspend;
  15369. bool isexceptionmode;
  15370. c11_vector* exception_stacktrace;
  15371. c11_vector breakpoints;
  15372. c11_vector py_frames;
  15373. c11_smallmap_d2index scopes_query_cache;
  15374. #define python_vars py_sysr0()
  15375. } debugger;
  15376. inline static void init_structures() {
  15377. c11_vector__ctor(&debugger.breakpoints, sizeof(c11_debugger_breakpoint));
  15378. c11_vector__ctor(&debugger.py_frames, sizeof(py_Frame*));
  15379. c11_smallmap_d2index__ctor(&debugger.scopes_query_cache);
  15380. py_newlist(python_vars);
  15381. py_newnone(py_list_emplace(python_vars));
  15382. }
  15383. inline static void clear_structures() {
  15384. c11_vector__clear(&debugger.py_frames);
  15385. c11_smallmap_d2index__clear(&debugger.scopes_query_cache);
  15386. py_list_clear(python_vars);
  15387. py_newnone(py_list_emplace(python_vars));
  15388. }
  15389. inline static py_Ref get_variable(int var_ref) {
  15390. assert(var_ref < py_list_len(python_vars) && var_ref > 0);
  15391. return py_list_getitem(python_vars, var_ref);
  15392. }
  15393. const inline static char* format_filepath(const char* path) {
  15394. if(strstr(path, "..")) { return NULL; }
  15395. if(strstr(path + 1, "./") || strstr(path + 1, ".\\")) { return NULL; }
  15396. if(path[0] == '.' && (path[1] == '/' || path[1] == '\\')) { return path + 2; }
  15397. return path;
  15398. }
  15399. void c11_debugger_init() {
  15400. debugger.curr_stack_depth = 0;
  15401. debugger.current_line = -1;
  15402. debugger.pause_allowed_depth = -1;
  15403. debugger.step_line = -1;
  15404. debugger.keep_suspend = false;
  15405. debugger.isexceptionmode = false;
  15406. debugger.step_mode = C11_STEP_CONTINUE;
  15407. init_structures();
  15408. }
  15409. C11_DEBUGGER_STATUS c11_debugger_on_trace(py_Frame* frame, enum py_TraceEvent event) {
  15410. debugger.current_frame = frame;
  15411. debugger.current_event = event;
  15412. const char* source_name = py_Frame_sourceloc(debugger.current_frame, &debugger.current_line);
  15413. debugger.current_filename = format_filepath(source_name);
  15414. if(debugger.current_filename == NULL) { return C11_DEBUGGER_FILEPATH_ERROR; }
  15415. clear_structures();
  15416. switch(event) {
  15417. case TRACE_EVENT_PUSH: debugger.curr_stack_depth++; break;
  15418. case TRACE_EVENT_POP: debugger.curr_stack_depth--; break;
  15419. default: break;
  15420. }
  15421. // if(debugger.curr_stack_depth == 0) return C11_DEBUGGER_EXIT;
  15422. return C11_DEBUGGER_SUCCESS;
  15423. }
  15424. void c11_debugger_exception_on_trace(py_Ref exc) {
  15425. BaseException* ud = py_touserdata(exc);
  15426. c11_vector* stacktrace = &ud->stacktrace;
  15427. const char* name = py_tpname(exc->type);
  15428. const char* message = safe_stringify_exception(exc);
  15429. debugger.exception_stacktrace = stacktrace;
  15430. debugger.isexceptionmode = true;
  15431. debugger.current_excname = name;
  15432. debugger.current_excmessage = message;
  15433. clear_structures();
  15434. py_assign(py_list_getitem(python_vars, 0), exc);
  15435. py_clearexc(NULL);
  15436. }
  15437. const char* c11_debugger_excinfo(const char** message) {
  15438. *message = debugger.current_excmessage;
  15439. return debugger.current_excname;
  15440. }
  15441. void c11_debugger_set_step_mode(C11_STEP_MODE mode) {
  15442. switch(mode) {
  15443. case C11_STEP_IN: debugger.pause_allowed_depth = INT32_MAX; break;
  15444. case C11_STEP_OVER:
  15445. debugger.pause_allowed_depth = debugger.curr_stack_depth;
  15446. debugger.step_line = debugger.current_line;
  15447. break;
  15448. case C11_STEP_OUT: debugger.pause_allowed_depth = debugger.curr_stack_depth - 1; break;
  15449. case C11_STEP_CONTINUE: debugger.pause_allowed_depth = -1; break;
  15450. default: break;
  15451. }
  15452. debugger.step_mode = mode;
  15453. debugger.keep_suspend = false;
  15454. }
  15455. int c11_debugger_setbreakpoint(const char* filename, int lineno) {
  15456. c11_debugger_breakpoint breakpoint = {.sourcename = c11_strdup(filename), .lineno = lineno};
  15457. c11_vector__push(c11_debugger_breakpoint, &debugger.breakpoints, breakpoint);
  15458. return debugger.breakpoints.length;
  15459. }
  15460. int c11_debugger_reset_breakpoints_by_source(const char* sourcesname) {
  15461. c11_vector tmp_breakpoints;
  15462. c11_vector__ctor(&tmp_breakpoints, sizeof(c11_debugger_breakpoint));
  15463. c11__foreach(c11_debugger_breakpoint, &debugger.breakpoints, it) {
  15464. if(strcmp(it->sourcename, sourcesname) != 0) {
  15465. c11_debugger_breakpoint* dst =
  15466. (c11_debugger_breakpoint*)c11_vector__emplace(&tmp_breakpoints);
  15467. *dst = *it;
  15468. } else {
  15469. PK_FREE((void*)it->sourcename);
  15470. }
  15471. }
  15472. c11_vector__swap(&tmp_breakpoints, &debugger.breakpoints);
  15473. c11_vector__dtor(&tmp_breakpoints);
  15474. return debugger.breakpoints.length;
  15475. }
  15476. bool c11_debugger_path_equal(const char* path1, const char* path2) {
  15477. if(path1 == NULL || path2 == NULL) return false;
  15478. while(*path1 && *path2) {
  15479. char c1 = (*path1 == '\\') ? '/' : *path1;
  15480. char c2 = (*path2 == '\\') ? '/' : *path2;
  15481. c1 = (char)tolower((unsigned char)c1);
  15482. c2 = (char)tolower((unsigned char)c2);
  15483. if(c1 != c2) return false;
  15484. path1++;
  15485. path2++;
  15486. }
  15487. return *path1 == *path2;
  15488. }
  15489. C11_STOP_REASON c11_debugger_should_pause() {
  15490. if(debugger.current_event == TRACE_EVENT_POP && !debugger.isexceptionmode)
  15491. return C11_DEBUGGER_NOSTOP;
  15492. if(py_checkexc() && debugger.isexceptionmode == false)
  15493. return C11_DEBUGGER_NOSTOP;
  15494. C11_STOP_REASON pause_resaon = C11_DEBUGGER_NOSTOP;
  15495. int is_out = debugger.curr_stack_depth <= debugger.pause_allowed_depth;
  15496. int is_new_line = debugger.current_line != debugger.step_line;
  15497. switch(debugger.step_mode) {
  15498. case C11_STEP_IN: pause_resaon = C11_DEBUGGER_STEP; break;
  15499. case C11_STEP_OVER:
  15500. if(is_new_line && is_out) pause_resaon = C11_DEBUGGER_STEP;
  15501. break;
  15502. case C11_STEP_OUT:
  15503. if(is_out) pause_resaon = C11_DEBUGGER_STEP;
  15504. break;
  15505. case C11_STEP_CONTINUE:
  15506. default: break;
  15507. }
  15508. if(debugger.step_mode == C11_STEP_CONTINUE) {
  15509. c11__foreach(c11_debugger_breakpoint, &debugger.breakpoints, bp) {
  15510. if(c11_debugger_path_equal(debugger.current_filename, bp->sourcename) &&
  15511. debugger.current_line == bp->lineno) {
  15512. pause_resaon = C11_DEBUGGER_BP;
  15513. break;
  15514. }
  15515. }
  15516. }
  15517. if(debugger.isexceptionmode) pause_resaon = C11_DEBUGGER_EXCEPTION;
  15518. if(pause_resaon != C11_DEBUGGER_NOSTOP) { debugger.keep_suspend = true; }
  15519. return pause_resaon;
  15520. }
  15521. int c11_debugger_should_keep_pause(void) { return debugger.keep_suspend; }
  15522. inline static c11_sv sv_from_cstr(const char* str) {
  15523. c11_sv sv = {.data = str, .size = strlen(str)};
  15524. return sv;
  15525. }
  15526. const inline static char* get_basename(const char* path) {
  15527. const char* last_slash = strrchr(path, '/');
  15528. #if defined(_WIN32) || defined(_WIN64)
  15529. const char* last_backslash = strrchr(path, '\\');
  15530. if(!last_slash || (last_backslash && last_backslash > last_slash)) {
  15531. last_slash = last_backslash;
  15532. }
  15533. #endif
  15534. return last_slash ? last_slash + 1 : path;
  15535. }
  15536. void c11_debugger_normal_frames(c11_sbuf* buffer) {
  15537. c11_sbuf__write_cstr(buffer, "{\"stackFrames\": [");
  15538. int idx = 0;
  15539. py_Frame* now_frame = debugger.current_frame;
  15540. debugger.py_frames.length = 0;
  15541. while(now_frame) {
  15542. if(idx > 0) c11_sbuf__write_char(buffer, ',');
  15543. int line;
  15544. const char* filename = py_Frame_sourceloc(now_frame, &line);
  15545. const char* basename = get_basename(filename);
  15546. const char* modname = now_frame->co->name->data;
  15547. pk_sprintf(
  15548. buffer,
  15549. "{\"id\": %d, \"name\": %Q, \"line\": %d, \"column\": 1, \"source\": {\"name\": %Q, \"path\": %Q}}",
  15550. idx,
  15551. sv_from_cstr(modname),
  15552. line,
  15553. sv_from_cstr(basename),
  15554. sv_from_cstr(filename));
  15555. c11_vector__push(py_Frame*, &debugger.py_frames, now_frame);
  15556. now_frame = now_frame->f_back;
  15557. idx++;
  15558. }
  15559. pk_sprintf(buffer, "], \"totalFrames\": %d}", idx);
  15560. }
  15561. void c11_debugger_exception_frames(c11_sbuf* buffer) {
  15562. c11_sbuf__write_cstr(buffer, "{\"stackFrames\": [");
  15563. int idx = 0;
  15564. c11__foreach(BaseExceptionFrame, debugger.exception_stacktrace, it) {
  15565. if(idx > 0) c11_sbuf__write_char(buffer, ',');
  15566. int line = it->lineno;
  15567. const char* filename = it->src->filename->data;
  15568. const char* basename = get_basename(filename);
  15569. const char* modname = it->name == NULL ? basename : it->name->data;
  15570. pk_sprintf(
  15571. buffer,
  15572. "{\"id\": %d, \"name\": %Q, \"line\": %d, \"column\": 1, \"source\": {\"name\": %Q, \"path\": %Q}}",
  15573. idx,
  15574. sv_from_cstr(modname),
  15575. line,
  15576. sv_from_cstr(basename),
  15577. sv_from_cstr(filename));
  15578. idx++;
  15579. }
  15580. pk_sprintf(buffer, "], \"totalFrames\": %d}", idx);
  15581. }
  15582. void c11_debugger_frames(c11_sbuf* buffer) {
  15583. debugger.isexceptionmode ? c11_debugger_exception_frames(buffer)
  15584. : c11_debugger_normal_frames(buffer);
  15585. }
  15586. inline static c11_debugger_scope_index append_new_scope(int frameid) {
  15587. assert(frameid < debugger.py_frames.length);
  15588. py_Frame* requested_frame = c11__getitem(py_Frame*, &debugger.py_frames, frameid);
  15589. int base_index = py_list_len(python_vars);
  15590. py_Ref new_locals = py_list_emplace(python_vars);
  15591. py_Frame_newlocals(requested_frame, new_locals);
  15592. py_Ref new_globals = py_list_emplace(python_vars);
  15593. py_Frame_newglobals(requested_frame, new_globals);
  15594. c11_debugger_scope_index result = {.locals_ref = base_index, .globals_ref = base_index + 1};
  15595. return result;
  15596. }
  15597. inline static c11_debugger_scope_index append_new_exception_scope(int frameid) {
  15598. assert(frameid < debugger.exception_stacktrace->length);
  15599. BaseExceptionFrame* requested_frame =
  15600. c11__at(BaseExceptionFrame, debugger.exception_stacktrace, frameid);
  15601. int base_index = py_list_len(python_vars);
  15602. py_list_append(python_vars, &requested_frame->locals);
  15603. py_list_append(python_vars, &requested_frame->globals);
  15604. c11_debugger_scope_index result = {.locals_ref = base_index, .globals_ref = base_index + 1};
  15605. return result;
  15606. }
  15607. void c11_debugger_scopes(int frameid, c11_sbuf* buffer) {
  15608. // query cache
  15609. c11_debugger_scope_index* result =
  15610. c11_smallmap_d2index__try_get(&debugger.scopes_query_cache, frameid);
  15611. c11_sbuf__write_cstr(buffer, "{\"scopes\":");
  15612. const char* scopes_fmt =
  15613. "[{\"name\": \"locals\", \"variablesReference\": %d, \"expensive\": false}, "
  15614. "{\"name\": \"globals\", \"variablesReference\": %d, \"expensive\": true}]";
  15615. if(result != NULL) {
  15616. pk_sprintf(buffer, scopes_fmt, result->locals_ref, result->globals_ref);
  15617. } else {
  15618. c11_debugger_scope_index new_record = debugger.isexceptionmode
  15619. ? append_new_exception_scope(frameid)
  15620. : append_new_scope(frameid);
  15621. c11_smallmap_d2index__set(&debugger.scopes_query_cache, frameid, new_record);
  15622. pk_sprintf(buffer, scopes_fmt, new_record.locals_ref, new_record.globals_ref);
  15623. }
  15624. c11_sbuf__write_char(buffer, '}');
  15625. }
  15626. bool c11_debugger_unfold_var(int var_id, c11_sbuf* buffer) {
  15627. py_Ref var = get_variable(var_id);
  15628. if(!var) return false;
  15629. // 1. extend
  15630. const char* expand_code = NULL;
  15631. switch(py_typeof(var)) {
  15632. case tp_dict:
  15633. case tp_namedict: expand_code = "[(k,v) for k,v in _0.items()]"; break;
  15634. case tp_list:
  15635. case tp_tuple: expand_code = "[(f'[{i}]',v) for i,v in enumerate(_0)]"; break;
  15636. default: expand_code = "[(k,v) for k,v in _0.__dict__.items()]"; break;
  15637. }
  15638. if(!py_smarteval(expand_code, NULL, var)) {
  15639. py_printexc();
  15640. return false;
  15641. }
  15642. py_Ref kv_list = py_pushtmp();
  15643. py_assign(kv_list, py_retval());
  15644. // 2. prepare base_ref
  15645. int base_index = py_list_len(python_vars);
  15646. py_Ref base_var_ref = py_pushtmp();
  15647. py_newint(base_var_ref, base_index);
  15648. // 3. construct DAP JSON and extend python_vars
  15649. py_Ref dap_obj = py_pushtmp();
  15650. py_newdict(dap_obj);
  15651. const char* dap_code =
  15652. "_2['variables'] = []\n"
  15653. "var_ref = _1\n"
  15654. "for k, v in _0:\n"
  15655. " has_children = isinstance(v, (dict, list, tuple)) or v.__dict__ is not None\n"
  15656. " _2['variables'].append({\n"
  15657. " 'name': k if type(k) == str else str(k),\n"
  15658. " 'value': repr(v) if type(v) == str else str(v),\n"
  15659. " 'variablesReference': var_ref if has_children else 0,\n"
  15660. " 'type': type(v).__name__\n"
  15661. " })\n"
  15662. " if has_children: var_ref += 1\n";
  15663. if(!py_smartexec(dap_code, NULL, kv_list, base_var_ref, dap_obj)) {
  15664. py_printexc();
  15665. return false;
  15666. }
  15667. // 4. extend python_vars
  15668. if(!py_smartexec(
  15669. "_0.extend([v for k, v in _1 if isinstance(v, (dict, list, tuple)) or v.__dict__ is not None])",
  15670. NULL,
  15671. python_vars,
  15672. kv_list)) {
  15673. py_printexc();
  15674. return false;
  15675. }
  15676. // 5. dump & write
  15677. if(!py_json_dumps(dap_obj, 0)) {
  15678. // printf("dap_obj: %s\n", py_tpname(py_typeof(dap_obj)));
  15679. py_printexc();
  15680. return false;
  15681. }
  15682. c11_sbuf__write_cstr(buffer, py_tostr(py_retval()));
  15683. // 6. clear
  15684. py_pop(); // dap_obj
  15685. py_pop(); // base_var_ref
  15686. py_pop(); // kv_list
  15687. return true;
  15688. }
  15689. #undef python_vars
  15690. #endif // PK_ENABLE_OS
  15691. // src/debugger\dap.c
  15692. #include <stdbool.h>
  15693. #include <stdio.h>
  15694. #if PK_ENABLE_OS
  15695. #define DAP_COMMAND_LIST(X) \
  15696. X(initialize) \
  15697. X(setBreakpoints) \
  15698. X(attach) \
  15699. X(launch) \
  15700. X(next) \
  15701. X(stepIn) \
  15702. X(stepOut) \
  15703. X(continue) \
  15704. X(stackTrace) \
  15705. X(scopes) \
  15706. X(variables) \
  15707. X(threads) \
  15708. X(configurationDone) \
  15709. X(ready) \
  15710. X(evaluate) \
  15711. X(exceptionInfo)
  15712. #define DECLARE_HANDLE_FN(name) void c11_dap_handle_##name(py_Ref arguments, c11_sbuf*);
  15713. DAP_COMMAND_LIST(DECLARE_HANDLE_FN)
  15714. #undef DECLARE_HANDLE_FN
  15715. typedef void (*c11_dap_arg_parser_fn)(py_Ref, c11_sbuf*);
  15716. typedef struct {
  15717. const char* command;
  15718. c11_dap_arg_parser_fn parser;
  15719. } dap_command_entry;
  15720. #define DAP_ENTRY(name) {#name, c11_dap_handle_##name},
  15721. static dap_command_entry dap_command_table[] = {
  15722. DAP_COMMAND_LIST(DAP_ENTRY){NULL, NULL}
  15723. };
  15724. #undef DAP_ENTRY
  15725. #undef DAP_COMMAND_LIST
  15726. static struct c11_dap_server {
  15727. int dap_next_seq;
  15728. char buffer_data[1024];
  15729. char* buffer_begin;
  15730. int buffer_length;
  15731. c11_socket_handler server;
  15732. c11_socket_handler toclient;
  15733. bool isconfiguredone;
  15734. bool isfirstatttach;
  15735. bool isUserCode;
  15736. bool isAttached;
  15737. bool isclientready;
  15738. } server;
  15739. void c11_dap_handle_initialize(py_Ref arguments, c11_sbuf* buffer) {
  15740. c11_sbuf__write_cstr(buffer,
  15741. "\"body\":{"
  15742. "\"supportsConfigurationDoneRequest\":true,"
  15743. "\"supportsExceptionInfoRequest\":true"
  15744. "}");
  15745. c11_sbuf__write_char(buffer, ',');
  15746. }
  15747. void c11_dap_handle_attach(py_Ref arguments, c11_sbuf* buffer) { server.isfirstatttach = true; }
  15748. void c11_dap_handle_launch(py_Ref arguments, c11_sbuf* buffer) { server.isfirstatttach = true; }
  15749. void c11_dap_handle_ready(py_Ref arguments, c11_sbuf* buffer) { server.isclientready = true; }
  15750. void c11_dap_handle_next(py_Ref arguments, c11_sbuf* buffer) {
  15751. c11_debugger_set_step_mode(C11_STEP_OVER);
  15752. }
  15753. void c11_dap_handle_stepIn(py_Ref arguments, c11_sbuf* buffer) {
  15754. c11_debugger_set_step_mode(C11_STEP_IN);
  15755. }
  15756. void c11_dap_handle_stepOut(py_Ref arguments, c11_sbuf* buffer) {
  15757. c11_debugger_set_step_mode(C11_STEP_OUT);
  15758. }
  15759. void c11_dap_handle_continue(py_Ref arguments, c11_sbuf* buffer) {
  15760. c11_debugger_set_step_mode(C11_STEP_CONTINUE);
  15761. }
  15762. void c11_dap_handle_threads(py_Ref arguments, c11_sbuf* buffer) {
  15763. c11_sbuf__write_cstr(buffer,
  15764. "\"body\":{\"threads\":["
  15765. "{\"id\":1,\"name\":\"MainThread\"}"
  15766. "]}");
  15767. c11_sbuf__write_char(buffer, ',');
  15768. }
  15769. void c11_dap_handle_configurationDone(py_Ref arguments, c11_sbuf* buffer) {
  15770. server.isconfiguredone = true;
  15771. }
  15772. inline static void c11_dap_build_Breakpoint(int id, int line, c11_sbuf* buffer) {
  15773. pk_sprintf(buffer, "{\"id\":%d,\"verified\":true,\"line\":%d}", id, line);
  15774. }
  15775. void c11_dap_handle_setBreakpoints(py_Ref arguments, c11_sbuf* buffer) {
  15776. if(!py_smarteval("_0['source']['path']", NULL, arguments)) {
  15777. py_printexc();
  15778. return;
  15779. }
  15780. const char* sourcename = c11_strdup(py_tostr(py_retval()));
  15781. if(!py_smarteval("[bp['line'] for bp in _0['breakpoints']]", NULL, arguments)) {
  15782. py_printexc();
  15783. PK_FREE((void*)sourcename);
  15784. return;
  15785. }
  15786. int bp_numbers = c11_debugger_reset_breakpoints_by_source(sourcename);
  15787. c11_sbuf__write_cstr(buffer, "\"body\":");
  15788. c11_sbuf__write_cstr(buffer, "{\"breakpoints\":[");
  15789. for(int i = 0; i < py_list_len(py_retval()); i++) {
  15790. if(i != 0) c11_sbuf__write_char(buffer, ',');
  15791. int line = py_toint(py_list_getitem(py_retval(), i));
  15792. c11_debugger_setbreakpoint(sourcename, line);
  15793. c11_dap_build_Breakpoint(i + bp_numbers, line, buffer);
  15794. }
  15795. c11_sbuf__write_cstr(buffer, "]}");
  15796. c11_sbuf__write_char(buffer, ',');
  15797. PK_FREE((void*)sourcename);
  15798. }
  15799. static void c11_dap_build_ExceptionInfo(const char* exc_type, const char* exc_message, c11_sbuf* buffer) {
  15800. const char* safe_type = exc_type ? exc_type : "UnknownException";
  15801. const char* safe_message = exc_message ? exc_message : "No additional details available";
  15802. c11_sv type_sv = {.data = safe_type, .size = strlen(safe_type)};
  15803. c11_sbuf combined_buffer;
  15804. c11_sbuf__ctor(&combined_buffer);
  15805. pk_sprintf(&combined_buffer, "%s: %s", safe_type, safe_message);
  15806. c11_string* combined_details = c11_sbuf__submit(&combined_buffer);
  15807. pk_sprintf(buffer,
  15808. "{\"exceptionId\":%Q,"
  15809. "\"description\":%Q,"
  15810. "\"breakMode\":\"unhandled\"}",
  15811. type_sv,
  15812. (c11_sv){.data = combined_details->data, .size = combined_details->size}
  15813. );
  15814. c11_string__delete(combined_details);
  15815. }
  15816. void c11_dap_handle_exceptionInfo(py_Ref arguments, c11_sbuf* buffer) {
  15817. const char* message;
  15818. const char* name = c11_debugger_excinfo(&message);
  15819. c11_sbuf__write_cstr(buffer, "\"body\":");
  15820. c11_dap_build_ExceptionInfo(name, message, buffer);
  15821. c11_sbuf__write_char(buffer, ',');
  15822. }
  15823. void c11_dap_handle_stackTrace(py_Ref arguments, c11_sbuf* buffer) {
  15824. c11_sbuf__write_cstr(buffer, "\"body\":");
  15825. c11_debugger_frames(buffer);
  15826. c11_sbuf__write_char(buffer, ',');
  15827. }
  15828. void c11_dap_handle_evaluate(py_Ref arguments, c11_sbuf* buffer) {
  15829. int res = py_dict_getitem_by_str(arguments, "expression");
  15830. if(res <= 0) {
  15831. py_printexc();
  15832. c11__abort("[DEBUGGER ERROR] no expression found in evaluate request");
  15833. }
  15834. // [eval, nil, expression, globals, locals]
  15835. // vectorcall would pop the above 5 items
  15836. // so we don't need to pop them manually
  15837. py_StackRef p0 = py_peek(0);
  15838. py_Ref py_eval = py_pushtmp();
  15839. py_pushnil();
  15840. py_Ref expression = py_pushtmp();
  15841. py_assign(expression, py_retval());
  15842. py_assign(py_eval, py_getbuiltin(py_name("eval")));
  15843. py_newglobals(py_pushtmp());
  15844. py_newlocals(py_pushtmp());
  15845. bool ok = py_vectorcall(3, 0);
  15846. char* result = NULL;
  15847. c11_sbuf__write_cstr(buffer, "\"body\":");
  15848. if(!ok) {
  15849. result = py_formatexc();
  15850. py_clearexc(p0);
  15851. } else {
  15852. py_Ref py_result = py_pushtmp();
  15853. py_assign(py_result, py_retval());
  15854. py_str(py_result);
  15855. py_assign(py_result, py_retval());
  15856. result = c11_strdup(py_tostr(py_result));
  15857. py_pop();
  15858. }
  15859. c11_sv result_sv = {.data = result, .size = strlen(result)};
  15860. pk_sprintf(buffer, "{\"result\":%Q,\"variablesReference\":0}", result_sv);
  15861. PK_FREE((void*)result);
  15862. c11_sbuf__write_char(buffer, ',');
  15863. }
  15864. void c11_dap_handle_scopes(py_Ref arguments, c11_sbuf* buffer) {
  15865. int res = py_dict_getitem_by_str(arguments, "frameId");
  15866. if(res <= 0) {
  15867. if(res == 0) {
  15868. c11__abort("[DEBUGGER ERROR] no frameID found in scopes request");
  15869. } else {
  15870. py_printexc();
  15871. c11__abort("[DEBUGGER ERROR] an error occurred while parsing request frameId");
  15872. }
  15873. return;
  15874. }
  15875. int frameid = py_toint(py_retval());
  15876. c11_sbuf__write_cstr(buffer, "\"body\":");
  15877. c11_debugger_scopes(frameid, buffer);
  15878. c11_sbuf__write_char(buffer, ',');
  15879. }
  15880. void c11_dap_handle_variables(py_Ref arguments, c11_sbuf* buffer) {
  15881. int res = py_dict_getitem_by_str(arguments, "variablesReference");
  15882. if(res <= 0) {
  15883. if(res == 0) {
  15884. printf("[DEBUGGER ERROR] no frameID found\n");
  15885. } else {
  15886. py_printexc();
  15887. }
  15888. return;
  15889. }
  15890. int variablesReference = py_toint(py_retval());
  15891. c11_sbuf__write_cstr(buffer, "\"body\":");
  15892. c11_debugger_unfold_var(variablesReference, buffer);
  15893. c11_sbuf__write_char(buffer, ',');
  15894. }
  15895. const char* c11_dap_handle_request(const char* message) {
  15896. if(!py_json_loads(message)) {
  15897. py_printexc();
  15898. c11__abort("[DEBUGGER ERROR] invalid JSON request");
  15899. }
  15900. py_Ref py_request = py_pushtmp();
  15901. py_Ref py_arguments = py_pushtmp();
  15902. py_Ref py_command = py_pushtmp();
  15903. py_assign(py_request, py_retval());
  15904. int res = py_dict_getitem_by_str(py_request, "command");
  15905. if(res == -1) {
  15906. py_printexc();
  15907. c11__abort("[DEBUGGER ERROR] an error occurred while parsing request");
  15908. } else if(res == 0) {
  15909. c11__abort("[DEBUGGER ERROR] no command found in request");
  15910. }
  15911. py_assign(py_command, py_retval());
  15912. const char* command = py_tostr(py_command);
  15913. res = py_dict_getitem_by_str(py_request, "arguments");
  15914. if(res == -1) {
  15915. py_printexc();
  15916. c11__abort("[DEBUGGER ERROR] an error occurred while parsing request arguments");
  15917. }
  15918. py_assign(py_arguments, py_retval());
  15919. res = py_dict_getitem_by_str(py_request, "seq");
  15920. if(res == -1) {
  15921. py_printexc();
  15922. c11__abort("[DEBUGGER ERROR] an error occurred while parsing request sequence number");
  15923. }
  15924. int request_seq = (res == 1) ? py_toint(py_retval()) : 0;
  15925. c11_sbuf response_buffer;
  15926. c11_sbuf__ctor(&response_buffer);
  15927. pk_sprintf(&response_buffer,
  15928. "{\"seq\":%d,\"type\":\"response\",\"request_seq\":%d,\"command\":\"%s\",",
  15929. server.dap_next_seq++,
  15930. request_seq,
  15931. command);
  15932. for(dap_command_entry* entry = dap_command_table; entry->command != NULL; entry++) {
  15933. if(strcmp(entry->command, command) == 0) {
  15934. entry->parser(py_arguments, &response_buffer);
  15935. break;
  15936. }
  15937. }
  15938. c11_sbuf__write_cstr(&response_buffer, "\"success\":true}");
  15939. c11_string* c11_string_response = c11_sbuf__submit(&response_buffer);
  15940. const char* response = c11_strdup(c11_string_response->data);
  15941. c11_string__delete(c11_string_response);
  15942. py_pop(); // py_arguments
  15943. py_pop(); // py_request
  15944. py_pop(); // py_command
  15945. return response;
  15946. }
  15947. void c11_dap_send_event(const char* event_name, const char* body_json) {
  15948. c11_sbuf buffer;
  15949. char header[64];
  15950. c11_sbuf__ctor(&buffer);
  15951. pk_sprintf(&buffer,
  15952. "{\"seq\":%d,\"type\":\"event\",\"event\":\"%s\",\"body\":%s}",
  15953. server.dap_next_seq++,
  15954. event_name,
  15955. body_json);
  15956. c11_string* json = c11_sbuf__submit(&buffer);
  15957. int json_len = json->size;
  15958. int header_len = snprintf(header, sizeof(header), "Content-Length: %d\r\n\r\n", json_len);
  15959. c11_socket_send(server.toclient, header, header_len);
  15960. c11_socket_send(server.toclient, json->data, json_len);
  15961. c11_string__delete(json);
  15962. }
  15963. void c11_dap_send_output_event(const char* category, const char* fmt, ...) {
  15964. va_list args;
  15965. va_start(args, fmt);
  15966. c11_sbuf output;
  15967. c11_sbuf__ctor(&output);
  15968. pk_vsprintf(&output, fmt, args);
  15969. va_end(args);
  15970. c11_sbuf buffer;
  15971. c11_string* output_json = c11_sbuf__submit(&output);
  15972. c11_sv sv_output = {.data = output_json->data, .size = output_json->size};
  15973. c11_sbuf__ctor(&buffer);
  15974. pk_sprintf(&buffer, "{\"category\":\"%s\",\"output\":%Q}", category, sv_output);
  15975. c11_string* body_json = c11_sbuf__submit(&buffer);
  15976. c11_dap_send_event("output", body_json->data);
  15977. c11_string__delete(body_json);
  15978. c11_string__delete(output_json);
  15979. }
  15980. void c11_dap_send_stop_event(C11_STOP_REASON reason) {
  15981. if(reason == C11_DEBUGGER_NOSTOP) return;
  15982. const char* reason_str = "unknown";
  15983. switch(reason) {
  15984. case C11_DEBUGGER_STEP: reason_str = "step"; break;
  15985. case C11_DEBUGGER_EXCEPTION: reason_str = "exception"; break;
  15986. case C11_DEBUGGER_BP: reason_str = "breakpoint"; break;
  15987. default: break;
  15988. }
  15989. c11_sbuf buf;
  15990. c11_sbuf__ctor(&buf);
  15991. pk_sprintf(&buf, "{\"reason\":\"%s\",\"threadId\":1,\"allThreadsStopped\":true", reason_str);
  15992. c11_sbuf__write_char(&buf, '}');
  15993. c11_string* body_json = c11_sbuf__submit(&buf);
  15994. c11_dap_send_event("stopped", body_json->data);
  15995. c11_string__delete(body_json);
  15996. }
  15997. void c11_dap_send_exited_event(int exitCode) {
  15998. char body[64];
  15999. snprintf(body, sizeof(body), "{\"exitCode\":%d}", exitCode);
  16000. c11_dap_send_event("exited", body);
  16001. }
  16002. void c11_dap_send_fatal_event(const char* message) {
  16003. char body[128];
  16004. snprintf(body, sizeof(body), "{\"message\":\"%s\"}", message);
  16005. c11_dap_send_event("pkpy/fatalError", body);
  16006. }
  16007. void c11_dap_send_initialized_event() { c11_dap_send_event("initialized", "{}"); }
  16008. int c11_dap_read_content_length(const char* buffer, int* header_length) {
  16009. const char* length_begin = strstr(buffer, "Content-Length: ");
  16010. if(!length_begin) {
  16011. printf("[DEBUGGER ERROR] : no Content-Length filed found\n");
  16012. *header_length = 0;
  16013. return -1;
  16014. }
  16015. length_begin += strlen("Content-Length: ");
  16016. const char* length_end = strstr(length_begin, "\r\n\r\n");
  16017. if(!length_end) {
  16018. printf("[DEBUGGER ERROR] : the seperator should br \\r\\n\\r\\n\n");
  16019. *header_length = 0;
  16020. return -1;
  16021. }
  16022. char* endptr = NULL;
  16023. long value = strtol(length_begin, &endptr, 10);
  16024. if(endptr == length_begin) {
  16025. printf("[DEBUGGER EORRO] : the length field is empty\n");
  16026. *header_length = 0;
  16027. return -1;
  16028. }
  16029. *header_length = (int)(endptr - buffer) + 4;
  16030. return (int)value;
  16031. }
  16032. const char* c11_dap_read_message() {
  16033. int message_length =
  16034. c11_socket_recv(server.toclient, server.buffer_begin, 1024 - server.buffer_length);
  16035. if(message_length == 0) {
  16036. printf("[DEBUGGER INFO] : client quit\n");
  16037. exit(0);
  16038. }
  16039. if(message_length < 0) { return NULL; }
  16040. server.buffer_length += message_length;
  16041. if(server.buffer_length == 0) return NULL;
  16042. int header_length;
  16043. int content_length = c11_dap_read_content_length(server.buffer_begin, &header_length);
  16044. if(content_length <= 0 || header_length <= 0) {
  16045. printf("[DEBUGGER ERROR]: invalid DAP header\n");
  16046. server.buffer_length = 0;
  16047. server.buffer_begin = server.buffer_data;
  16048. return NULL;
  16049. }
  16050. server.buffer_begin += header_length;
  16051. server.buffer_length -= header_length;
  16052. c11_sbuf result;
  16053. c11_sbuf__ctor(&result);
  16054. while(content_length > server.buffer_length) {
  16055. c11_sbuf__write_cstrn(&result, server.buffer_begin, server.buffer_length);
  16056. content_length -= server.buffer_length;
  16057. message_length = c11_socket_recv(server.toclient, server.buffer_data, 1024);
  16058. if(message_length == 0) {
  16059. printf("[DEBUGGER INFO] : client quit\n");
  16060. exit(0);
  16061. }
  16062. if(message_length < 0) continue;
  16063. server.buffer_begin = server.buffer_data;
  16064. server.buffer_length = message_length;
  16065. }
  16066. c11_sbuf__write_cstrn(&result, server.buffer_begin, content_length);
  16067. server.buffer_begin += content_length;
  16068. server.buffer_length -= content_length;
  16069. memmove(server.buffer_data, server.buffer_begin, server.buffer_length);
  16070. server.buffer_begin = server.buffer_data;
  16071. c11_string* tmp_result = c11_sbuf__submit(&result);
  16072. const char* dap_message = c11_strdup(tmp_result->data);
  16073. c11_string__delete(tmp_result);
  16074. return dap_message;
  16075. }
  16076. void c11_dap_init_server(const char* hostname, unsigned short port) {
  16077. server.dap_next_seq = 1;
  16078. server.isconfiguredone = false;
  16079. server.isclientready = false;
  16080. server.isfirstatttach = false;
  16081. server.isUserCode = false;
  16082. server.isAttached = false;
  16083. server.buffer_begin = server.buffer_data;
  16084. server.server = c11_socket_create(C11_AF_INET, C11_SOCK_STREAM, 0);
  16085. c11_socket_bind(server.server, hostname, port);
  16086. c11_socket_listen(server.server, 0);
  16087. // c11_dap_send_output_event("console", "[DEBUGGER INFO] : listen on %s:%hu\n",hostname,port);
  16088. printf("[DEBUGGER INFO] : listen on %s:%hu\n", hostname, port);
  16089. }
  16090. void c11_dap_waitforclient(const char* hostname, unsigned short port) {
  16091. server.toclient = c11_socket_accept(server.server, NULL, NULL);
  16092. }
  16093. inline static void c11_dap_handle_message() {
  16094. const char* message = c11_dap_read_message();
  16095. if(message == NULL) { return; }
  16096. // c11_dap_send_output_event("console", "[DEBUGGER LOG] : read request %s\n", message);
  16097. const char* response_content = c11_dap_handle_request(message);
  16098. if(response_content != NULL) {
  16099. // c11_dap_send_output_event("console",
  16100. // "[DEBUGGER LOG] : send response %s\n",
  16101. // response_content);
  16102. }
  16103. c11_sbuf buffer;
  16104. c11_sbuf__ctor(&buffer);
  16105. pk_sprintf(&buffer, "Content-Length: %d\r\n\r\n%s", strlen(response_content), response_content);
  16106. c11_string* response = c11_sbuf__submit(&buffer);
  16107. c11_socket_send(server.toclient, response->data, response->size);
  16108. PK_FREE((void*)message);
  16109. PK_FREE((void*)response_content);
  16110. c11_string__delete(response);
  16111. }
  16112. void c11_dap_configure_debugger() {
  16113. while(server.isconfiguredone == false) {
  16114. c11_dap_handle_message();
  16115. if(server.isfirstatttach) {
  16116. c11_dap_send_initialized_event();
  16117. server.isfirstatttach = false;
  16118. server.isAttached = true;
  16119. server.isUserCode = true;
  16120. } else if(server.isclientready) {
  16121. server.isclientready = false;
  16122. return;
  16123. }
  16124. }
  16125. // c11_dap_send_output_event("console", "[DEBUGGER INFO] : client configure done\n");
  16126. }
  16127. void c11_dap_tracefunc(py_Frame* frame, enum py_TraceEvent event) {
  16128. py_sys_settrace(NULL, false);
  16129. server.isUserCode = false;
  16130. C11_DEBUGGER_STATUS result = c11_debugger_on_trace(frame, event);
  16131. if(result == C11_DEBUGGER_EXIT) {
  16132. // c11_dap_send_output_event("console", "[DEBUGGER INFO] : program exit\n");
  16133. c11_dap_send_exited_event(0);
  16134. exit(0);
  16135. }
  16136. if(result != C11_DEBUGGER_SUCCESS) {
  16137. const char* message = NULL;
  16138. switch(result) {
  16139. case C11_DEBUGGER_FILEPATH_ERROR:
  16140. message = "Invalid py_file path: '..' forbidden, './' only allowed at start.";
  16141. break;
  16142. case C11_DEBUGGER_UNKNOW_ERROR:
  16143. default: message = "Unknown debugger failure."; break;
  16144. }
  16145. if(message) { c11_dap_send_fatal_event(message); }
  16146. c11_dap_send_exited_event(1);
  16147. exit(1);
  16148. }
  16149. c11_dap_handle_message();
  16150. C11_STOP_REASON reason = c11_debugger_should_pause();
  16151. if(reason == C11_DEBUGGER_NOSTOP) {
  16152. py_sys_settrace(c11_dap_tracefunc, false);
  16153. server.isUserCode = true;
  16154. return;
  16155. }
  16156. c11_dap_send_stop_event(reason);
  16157. while(c11_debugger_should_keep_pause()) {
  16158. c11_dap_handle_message();
  16159. }
  16160. server.isUserCode = true;
  16161. py_sys_settrace(c11_dap_tracefunc, false);
  16162. }
  16163. void py_debugger_waitforattach(const char* hostname, unsigned short port) {
  16164. c11_debugger_init();
  16165. c11_dap_init_server(hostname, port);
  16166. while(!server.isconfiguredone) {
  16167. c11_dap_waitforclient(hostname, port);
  16168. c11_dap_configure_debugger();
  16169. if(!server.isconfiguredone) {
  16170. c11_socket_close(server.toclient);
  16171. // c11_dap_send_output_event("console", "[DEBUGGER INFO] : An clinet is ready\n");
  16172. }
  16173. }
  16174. c11_socket_set_block(server.toclient, 0);
  16175. py_sys_settrace(c11_dap_tracefunc, true);
  16176. }
  16177. void py_debugger_exit(int exitCode) { c11_dap_send_exited_event(exitCode); }
  16178. int py_debugger_status() {
  16179. if(!server.isAttached) {
  16180. return 0;
  16181. }
  16182. return server.isUserCode ? 1 : 2;
  16183. }
  16184. void py_debugger_exceptionbreakpoint(py_Ref exc) {
  16185. assert(py_isinstance(exc, tp_BaseException));
  16186. py_sys_settrace(NULL, true);
  16187. server.isUserCode = false;
  16188. c11_debugger_exception_on_trace(exc);
  16189. for(;;) {
  16190. C11_STOP_REASON reason = c11_debugger_should_pause();
  16191. c11_dap_send_stop_event(reason);
  16192. while(c11_debugger_should_keep_pause()) {
  16193. c11_dap_handle_message();
  16194. }
  16195. }
  16196. }
  16197. #endif // PK_ENABLE_OS
  16198. // src/interpreter\ceval.c
  16199. #include <stdbool.h>
  16200. #include <assert.h>
  16201. #include <time.h>
  16202. #define DISPATCH() \
  16203. do { \
  16204. frame->ip++; \
  16205. goto __NEXT_STEP; \
  16206. } while(0)
  16207. #define DISPATCH_JUMP(__offset) \
  16208. do { \
  16209. frame->ip += __offset; \
  16210. goto __NEXT_STEP; \
  16211. } while(0)
  16212. #define DISPATCH_JUMP_ABSOLUTE(__target) \
  16213. do { \
  16214. frame->ip = __target; \
  16215. goto __NEXT_STEP; \
  16216. } while(0)
  16217. #define RESET_CO_CACHE() \
  16218. do { \
  16219. co_codes = frame->co->codes.data; \
  16220. co_names = frame->co->names.data; \
  16221. } while(0)
  16222. /* Stack manipulation macros */
  16223. // https://github.com/python/cpython/blob/3.9/Python/ceval.c#L1123
  16224. #define TOP() (self->stack.sp - 1)
  16225. #define SECOND() (self->stack.sp - 2)
  16226. #define THIRD() (self->stack.sp - 3)
  16227. #define FOURTH() (self->stack.sp - 4)
  16228. #define STACK_SHRINK(n) (self->stack.sp -= n)
  16229. #define STACK_GROW(n) (self->stack.sp += n)
  16230. #define PUSH(v) \
  16231. do { \
  16232. *self->stack.sp = *(v); \
  16233. self->stack.sp++; \
  16234. } while(0)
  16235. #define POP() (--self->stack.sp)
  16236. #define POPX() (*--self->stack.sp)
  16237. #define SP() (self->stack.sp)
  16238. // [a, b] -> [?, a, b]
  16239. #define INSERT_THIRD() \
  16240. do { \
  16241. PUSH(TOP()); \
  16242. *SECOND() = *THIRD(); \
  16243. } while(0)
  16244. // Must use a DISPATCH() after vectorcall_opcall() immediately!
  16245. #define vectorcall_opcall(argc, kwargc) \
  16246. do { \
  16247. FrameResult res = VM__vectorcall(self, (argc), (kwargc), true); \
  16248. switch(res) { \
  16249. case RES_RETURN: PUSH(&self->last_retval); break; \
  16250. case RES_CALL: frame = self->top_frame; goto __NEXT_FRAME; \
  16251. case RES_ERROR: goto __ERROR; \
  16252. default: c11__unreachable(); \
  16253. } \
  16254. } while(0)
  16255. static bool unpack_dict_to_buffer(py_Ref key, py_Ref val, void* ctx) {
  16256. py_TValue** p = ctx;
  16257. if(py_isstr(key)) {
  16258. py_Name name = py_namev(py_tosv(key));
  16259. py_newint(*p, (uintptr_t)name);
  16260. py_assign(*p + 1, val);
  16261. (*p) += 2;
  16262. return true;
  16263. }
  16264. return TypeError("keywords must be strings, not '%t'", key->type);
  16265. }
  16266. FrameResult VM__run_top_frame(VM* self) {
  16267. py_Frame* frame = self->top_frame;
  16268. Bytecode* co_codes;
  16269. py_Name* co_names;
  16270. Bytecode byte;
  16271. const py_Frame* base_frame = frame;
  16272. __NEXT_FRAME:
  16273. if(self->recursion_depth >= self->max_recursion_depth) {
  16274. py_exception(tp_RecursionError, "maximum recursion depth exceeded");
  16275. goto __ERROR;
  16276. }
  16277. RESET_CO_CACHE();
  16278. frame->ip++;
  16279. __NEXT_STEP:
  16280. byte = co_codes[frame->ip];
  16281. if(self->trace_info.func) {
  16282. bool is_virtual = byte.op == OP_RETURN_VALUE && byte.arg == BC_RETURN_VIRTUAL;
  16283. if(!is_virtual) {
  16284. SourceLocation loc = Frame__source_location(frame);
  16285. SourceLocation prev_loc = self->trace_info.prev_loc;
  16286. if(loc.lineno != prev_loc.lineno || loc.src != prev_loc.src) {
  16287. if(prev_loc.src) PK_DECREF(prev_loc.src);
  16288. PK_INCREF(loc.src);
  16289. self->trace_info.prev_loc = loc;
  16290. self->trace_info.func(frame, TRACE_EVENT_LINE);
  16291. }
  16292. }
  16293. }
  16294. #if PK_ENABLE_WATCHDOG
  16295. // LYNX: the host's supervisor thread raises a flag when the script runs past its time (no clock() per opcode);
  16296. // it stays raised until the host clears it, so an `except:` in the script cannot swallow it
  16297. if(py_lynx_interrupt) {
  16298. TimeoutError("the script took too long");
  16299. goto __ERROR;
  16300. }
  16301. #endif
  16302. #ifndef NDEBUG
  16303. pk_print_stack(self, frame, byte);
  16304. #endif
  16305. switch((Opcode)byte.op) {
  16306. case OP_NO_OP: DISPATCH();
  16307. /*****************************************/
  16308. case OP_POP_TOP: POP(); DISPATCH();
  16309. case OP_DUP_TOP: PUSH(TOP()); DISPATCH();
  16310. case OP_DUP_TOP_TWO:
  16311. // [a, b]
  16312. PUSH(SECOND()); // [a, b, a]
  16313. PUSH(SECOND()); // [a, b, a, b]
  16314. DISPATCH();
  16315. case OP_ROT_TWO: {
  16316. py_TValue tmp = *TOP();
  16317. *TOP() = *SECOND();
  16318. *SECOND() = tmp;
  16319. DISPATCH();
  16320. }
  16321. case OP_ROT_THREE: {
  16322. // [a, b, c] -> [c, a, b]
  16323. py_TValue tmp = *TOP();
  16324. *TOP() = *SECOND();
  16325. *SECOND() = *THIRD();
  16326. *THIRD() = tmp;
  16327. DISPATCH();
  16328. }
  16329. case OP_PRINT_EXPR: {
  16330. if(self->callbacks.displayhook) {
  16331. bool ok = self->callbacks.displayhook(TOP());
  16332. if(!ok) goto __ERROR;
  16333. } else {
  16334. if(TOP()->type != tp_NoneType) {
  16335. bool ok = py_repr(TOP());
  16336. if(!ok) goto __ERROR;
  16337. self->callbacks.print(py_tostr(&self->last_retval));
  16338. self->callbacks.print("\n");
  16339. }
  16340. }
  16341. POP();
  16342. DISPATCH();
  16343. }
  16344. /*****************************************/
  16345. case OP_LOAD_CONST: {
  16346. PUSH(c11__at(py_TValue, &frame->co->consts, byte.arg));
  16347. DISPATCH();
  16348. }
  16349. case OP_LOAD_NONE: {
  16350. py_newnone(SP()++);
  16351. DISPATCH();
  16352. }
  16353. case OP_LOAD_TRUE: {
  16354. py_newbool(SP()++, true);
  16355. DISPATCH();
  16356. }
  16357. case OP_LOAD_FALSE: {
  16358. py_newbool(SP()++, false);
  16359. DISPATCH();
  16360. }
  16361. /*****************************************/
  16362. case OP_LOAD_SMALL_INT: {
  16363. py_newint(SP()++, (int16_t)byte.arg);
  16364. DISPATCH();
  16365. }
  16366. case OP_LOAD_NAME_AS_INT: {
  16367. py_Name name = co_names[byte.arg];
  16368. py_newint(SP()++, (uintptr_t)name);
  16369. DISPATCH();
  16370. }
  16371. /*****************************************/
  16372. case OP_LOAD_ELLIPSIS: {
  16373. py_newellipsis(SP()++);
  16374. DISPATCH();
  16375. }
  16376. case OP_LOAD_FUNCTION: {
  16377. FuncDecl_ decl = c11__getitem(FuncDecl_, &frame->co->func_decls, byte.arg);
  16378. Function* ud = py_newobject(SP(), tp_function, 0, sizeof(Function));
  16379. Function__ctor(ud, decl, frame->module, frame->globals);
  16380. if(decl->nested) {
  16381. if(frame->is_locals_special) {
  16382. RuntimeError("cannot create closure from special locals");
  16383. goto __ERROR;
  16384. }
  16385. ud->closure = FastLocals__to_namedict(frame->locals, frame->co);
  16386. py_Name name = py_name(decl->code.name->data);
  16387. // capture itself to allow recursion
  16388. NameDict__set(ud->closure, name, SP());
  16389. } else {
  16390. if(self->curr_class) ud->clazz = self->curr_class->_obj;
  16391. }
  16392. SP()++;
  16393. DISPATCH();
  16394. }
  16395. case OP_LOAD_NULL:
  16396. py_newnil(SP()++);
  16397. DISPATCH();
  16398. /*****************************************/
  16399. case OP_LOAD_FAST: {
  16400. assert(!frame->is_locals_special);
  16401. py_Ref val = &frame->locals[byte.arg];
  16402. if(!py_isnil(val)) {
  16403. PUSH(val);
  16404. DISPATCH();
  16405. }
  16406. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  16407. UnboundLocalError(name);
  16408. goto __ERROR;
  16409. }
  16410. case OP_LOAD_NAME: {
  16411. assert(frame->is_locals_special);
  16412. py_Name name = co_names[byte.arg];
  16413. // locals
  16414. switch(frame->locals->type) {
  16415. case tp_locals: {
  16416. py_Frame* noproxy = frame->locals->_ptr;
  16417. py_Ref slot = Frame__getlocal_noproxy(noproxy, name);
  16418. if(slot == NULL) break;
  16419. if(py_isnil(slot)) {
  16420. UnboundLocalError(name);
  16421. goto __ERROR;
  16422. }
  16423. PUSH(slot);
  16424. DISPATCH();
  16425. }
  16426. case tp_dict: {
  16427. int res = py_dict_getitem(frame->locals, py_name2ref(name));
  16428. if(res == 1) {
  16429. PUSH(&self->last_retval);
  16430. DISPATCH();
  16431. }
  16432. if(res == 0) break;
  16433. assert(res == -1);
  16434. goto __ERROR;
  16435. }
  16436. case tp_nil: break;
  16437. default: c11__unreachable();
  16438. }
  16439. // globals
  16440. int res = Frame__getglobal(frame, name);
  16441. if(res == 1) {
  16442. PUSH(&self->last_retval);
  16443. DISPATCH();
  16444. }
  16445. if(res == -1) goto __ERROR;
  16446. // builtins
  16447. py_Ref tmp = py_getdict(self->builtins, name);
  16448. if(tmp != NULL) {
  16449. PUSH(tmp);
  16450. DISPATCH();
  16451. }
  16452. NameError(name);
  16453. goto __ERROR;
  16454. }
  16455. case OP_LOAD_NONLOCAL: {
  16456. py_Name name = co_names[byte.arg];
  16457. py_Ref tmp = Frame__getclosure(frame, name);
  16458. if(tmp != NULL) {
  16459. PUSH(tmp);
  16460. DISPATCH();
  16461. }
  16462. int res = Frame__getglobal(frame, name);
  16463. if(res == 1) {
  16464. PUSH(&self->last_retval);
  16465. DISPATCH();
  16466. }
  16467. if(res == -1) goto __ERROR;
  16468. tmp = py_getdict(self->builtins, name);
  16469. if(tmp != NULL) {
  16470. PUSH(tmp);
  16471. DISPATCH();
  16472. }
  16473. NameError(name);
  16474. goto __ERROR;
  16475. }
  16476. case OP_LOAD_GLOBAL: {
  16477. py_Name name = co_names[byte.arg];
  16478. int res = Frame__getglobal(frame, name);
  16479. if(res == 1) {
  16480. PUSH(&self->last_retval);
  16481. DISPATCH();
  16482. }
  16483. if(res == -1) goto __ERROR;
  16484. py_Ref tmp = py_getdict(self->builtins, name);
  16485. if(tmp != NULL) {
  16486. PUSH(tmp);
  16487. DISPATCH();
  16488. }
  16489. NameError(name);
  16490. goto __ERROR;
  16491. }
  16492. case OP_LOAD_ATTR: {
  16493. py_Name name = co_names[byte.arg];
  16494. if(py_getattr(TOP(), name)) {
  16495. py_assign(TOP(), py_retval());
  16496. } else {
  16497. goto __ERROR;
  16498. }
  16499. DISPATCH();
  16500. }
  16501. case OP_LOAD_SELF_ATTR: {
  16502. assert(!frame->is_locals_special);
  16503. py_Ref val = &frame->locals[0];
  16504. if(!py_isnil(val)) {
  16505. // LOAD_ATTR
  16506. py_Name name = co_names[byte.arg];
  16507. if(py_getattr(val, name)) {
  16508. PUSH(py_retval());
  16509. } else {
  16510. goto __ERROR;
  16511. }
  16512. DISPATCH();
  16513. }
  16514. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  16515. UnboundLocalError(name);
  16516. goto __ERROR;
  16517. }
  16518. case OP_LOAD_CLASS_GLOBAL: {
  16519. assert(self->curr_class);
  16520. py_Name name = co_names[byte.arg];
  16521. py_Ref tmp = py_getdict(self->curr_class, name);
  16522. if(tmp) {
  16523. PUSH(tmp);
  16524. DISPATCH();
  16525. }
  16526. // load global if attribute not found
  16527. int res = Frame__getglobal(frame, name);
  16528. if(res == 1) {
  16529. PUSH(&self->last_retval);
  16530. DISPATCH();
  16531. }
  16532. if(res == -1) goto __ERROR;
  16533. tmp = py_getdict(self->builtins, name);
  16534. if(tmp) {
  16535. PUSH(tmp);
  16536. DISPATCH();
  16537. }
  16538. NameError(name);
  16539. goto __ERROR;
  16540. }
  16541. case OP_LOAD_METHOD: {
  16542. // [self] -> [unbound, self]
  16543. py_Name name = co_names[byte.arg];
  16544. bool ok = py_pushmethod(name);
  16545. if(!ok) {
  16546. // fallback to getattr
  16547. if(py_getattr(TOP(), name)) {
  16548. py_assign(TOP(), py_retval());
  16549. py_newnil(SP()++);
  16550. } else {
  16551. goto __ERROR;
  16552. }
  16553. }
  16554. DISPATCH();
  16555. }
  16556. case OP_LOAD_SUBSCR: {
  16557. // [a, b] -> a[b]
  16558. py_Ref magic = py_tpfindmagic(SECOND()->type, __getitem__);
  16559. if(magic) {
  16560. if(magic->type == tp_nativefunc) {
  16561. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  16562. POP();
  16563. py_assign(TOP(), py_retval());
  16564. } else {
  16565. INSERT_THIRD(); // [?, a, b]
  16566. *THIRD() = *magic; // [__getitem__, a, b]
  16567. vectorcall_opcall(1, 0);
  16568. }
  16569. DISPATCH();
  16570. }
  16571. TypeError("'%t' object is not subscriptable", SECOND()->type);
  16572. goto __ERROR;
  16573. }
  16574. case OP_STORE_FAST: {
  16575. assert(!frame->is_locals_special);
  16576. frame->locals[byte.arg] = POPX();
  16577. DISPATCH();
  16578. }
  16579. case OP_STORE_NAME: {
  16580. assert(frame->is_locals_special);
  16581. py_Name name = co_names[byte.arg];
  16582. switch(frame->locals->type) {
  16583. case tp_locals: {
  16584. py_Frame* noproxy = frame->locals->_ptr;
  16585. py_Ref slot = Frame__getlocal_noproxy(noproxy, name);
  16586. if(slot == NULL) {
  16587. UnboundLocalError(name);
  16588. goto __ERROR;
  16589. }
  16590. *slot = POPX();
  16591. DISPATCH();
  16592. }
  16593. case tp_dict: {
  16594. if(!py_dict_setitem(frame->locals, py_name2ref(name), TOP())) goto __ERROR;
  16595. POP();
  16596. DISPATCH();
  16597. }
  16598. case tp_nil: {
  16599. // globals
  16600. if(!Frame__setglobal(frame, name, TOP())) goto __ERROR;
  16601. POP();
  16602. DISPATCH();
  16603. }
  16604. default: c11__unreachable();
  16605. }
  16606. }
  16607. case OP_STORE_GLOBAL: {
  16608. py_Name name = co_names[byte.arg];
  16609. if(!Frame__setglobal(frame, name, TOP())) goto __ERROR;
  16610. POP();
  16611. DISPATCH();
  16612. }
  16613. case OP_STORE_ATTR: {
  16614. // [val, a] -> a.b = val
  16615. py_Name name = co_names[byte.arg];
  16616. if(!py_setattr(TOP(), name, SECOND())) goto __ERROR;
  16617. STACK_SHRINK(2);
  16618. DISPATCH();
  16619. }
  16620. case OP_STORE_SELF_ATTR: {
  16621. assert(!frame->is_locals_special);
  16622. py_Ref val = &frame->locals[0];
  16623. if(!py_isnil(val)) {
  16624. // [val, a] -> a.b = val
  16625. py_Name name = co_names[byte.arg];
  16626. if(!py_setattr(val, name, TOP())) goto __ERROR;
  16627. POP();
  16628. DISPATCH();
  16629. }
  16630. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  16631. UnboundLocalError(name);
  16632. goto __ERROR;
  16633. }
  16634. case OP_STORE_SUBSCR: {
  16635. // [val, a, b] -> a[b] = val
  16636. py_Ref magic = py_tpfindmagic(SECOND()->type, __setitem__);
  16637. if(magic) {
  16638. PUSH(THIRD()); // [val, a, b, val]
  16639. if(magic->type == tp_nativefunc) {
  16640. if(!py_callcfunc(magic->_cfunc, 3, THIRD())) goto __ERROR;
  16641. STACK_SHRINK(4);
  16642. } else {
  16643. *FOURTH() = *magic; // [__setitem__, a, b, val]
  16644. if(!py_vectorcall(2, 0)) goto __ERROR;
  16645. }
  16646. DISPATCH();
  16647. }
  16648. TypeError("'%t' object does not support item assignment", SECOND()->type);
  16649. goto __ERROR;
  16650. }
  16651. case OP_DELETE_FAST: {
  16652. assert(!frame->is_locals_special);
  16653. py_Ref tmp = &frame->locals[byte.arg];
  16654. if(py_isnil(tmp)) {
  16655. py_Name name = c11__getitem(py_Name, &frame->co->varnames, byte.arg);
  16656. UnboundLocalError(name);
  16657. goto __ERROR;
  16658. }
  16659. py_newnil(tmp);
  16660. DISPATCH();
  16661. }
  16662. case OP_DELETE_NAME: {
  16663. assert(frame->is_locals_special);
  16664. py_Name name = co_names[byte.arg];
  16665. switch(frame->locals->type) {
  16666. case tp_locals: {
  16667. py_Frame* noproxy = frame->locals->_ptr;
  16668. py_Ref slot = Frame__getlocal_noproxy(noproxy, name);
  16669. if(slot == NULL || py_isnil(slot)) {
  16670. UnboundLocalError(name);
  16671. goto __ERROR;
  16672. }
  16673. py_newnil(slot);
  16674. DISPATCH();
  16675. }
  16676. case tp_dict: {
  16677. int res = py_dict_delitem(frame->locals, py_name2ref(name));
  16678. if(res == 1) DISPATCH();
  16679. if(res == 0) UnboundLocalError(name);
  16680. goto __ERROR;
  16681. }
  16682. case tp_nil: {
  16683. // globals
  16684. int res = Frame__delglobal(frame, name);
  16685. if(res == 1) DISPATCH();
  16686. if(res == 0) NameError(name);
  16687. goto __ERROR;
  16688. }
  16689. default: c11__unreachable();
  16690. }
  16691. }
  16692. case OP_DELETE_GLOBAL: {
  16693. py_Name name = co_names[byte.arg];
  16694. int res = Frame__delglobal(frame, name);
  16695. if(res == 1) DISPATCH();
  16696. if(res == -1) goto __ERROR;
  16697. NameError(name);
  16698. goto __ERROR;
  16699. }
  16700. case OP_DELETE_ATTR: {
  16701. py_Name name = co_names[byte.arg];
  16702. if(!py_delattr(TOP(), name)) goto __ERROR;
  16703. DISPATCH();
  16704. }
  16705. case OP_DELETE_SUBSCR: {
  16706. // [a, b] -> del a[b]
  16707. py_Ref magic = py_tpfindmagic(SECOND()->type, __delitem__);
  16708. if(magic) {
  16709. if(magic->type == tp_nativefunc) {
  16710. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  16711. STACK_SHRINK(2);
  16712. } else {
  16713. INSERT_THIRD(); // [?, a, b]
  16714. *THIRD() = *magic; // [__delitem__, a, b]
  16715. if(!py_vectorcall(1, 0)) goto __ERROR;
  16716. }
  16717. DISPATCH();
  16718. }
  16719. TypeError("'%t' object does not support item deletion", SECOND()->type);
  16720. goto __ERROR;
  16721. }
  16722. /*****************************************/
  16723. case OP_BUILD_IMAG: {
  16724. // [x]
  16725. py_Ref f = py_getdict(self->builtins, py_name("complex"));
  16726. assert(f != NULL);
  16727. py_TValue tmp = *TOP();
  16728. *TOP() = *f; // [complex]
  16729. py_newnil(SP()++); // [complex, NULL]
  16730. py_newint(SP()++, 0); // [complex, NULL, 0]
  16731. *SP()++ = tmp; // [complex, NULL, 0, x]
  16732. vectorcall_opcall(2, 0);
  16733. DISPATCH();
  16734. }
  16735. case OP_BUILD_BYTES: {
  16736. int size;
  16737. py_Ref string = c11__at(py_TValue, &frame->co->consts, byte.arg);
  16738. const char* data = py_tostrn(string, &size);
  16739. unsigned char* p = py_newbytes(SP()++, size);
  16740. memcpy(p, data, size);
  16741. DISPATCH();
  16742. }
  16743. case OP_BUILD_TUPLE: {
  16744. bool need_track = false;
  16745. py_TValue tmp;
  16746. py_Ref p = py_newtuple(&tmp, byte.arg);
  16747. py_TValue* begin = SP() - byte.arg;
  16748. for(int i = 0; i < byte.arg; i++) {
  16749. p[i] = begin[i];
  16750. if(p[i].is_ptr) need_track = true;
  16751. }
  16752. if(!need_track) tmp._obj->gc_marked |= 0b10;
  16753. SP() = begin;
  16754. PUSH(&tmp);
  16755. DISPATCH();
  16756. }
  16757. case OP_BUILD_LIST: {
  16758. py_TValue tmp;
  16759. py_newlistn(&tmp, byte.arg);
  16760. py_TValue* begin = SP() - byte.arg;
  16761. for(int i = 0; i < byte.arg; i++) {
  16762. py_list_setitem(&tmp, i, begin + i);
  16763. }
  16764. SP() = begin;
  16765. PUSH(&tmp);
  16766. DISPATCH();
  16767. }
  16768. case OP_BUILD_DICT: {
  16769. py_TValue* begin = SP() - byte.arg * 2;
  16770. py_Ref tmp = py_pushtmp();
  16771. py_newdict(tmp);
  16772. for(int i = 0; i < byte.arg * 2; i += 2) {
  16773. bool ok = py_dict_setitem(tmp, begin + i, begin + i + 1);
  16774. if(!ok) goto __ERROR;
  16775. }
  16776. SP() = begin;
  16777. PUSH(tmp);
  16778. DISPATCH();
  16779. }
  16780. case OP_BUILD_SET: {
  16781. py_TValue* begin = SP() - byte.arg;
  16782. py_Ref typeobject_set = py_getdict(self->builtins, py_name("set"));
  16783. assert(typeobject_set != NULL);
  16784. py_push(typeobject_set);
  16785. py_pushnil();
  16786. if(!py_vectorcall(0, 0)) goto __ERROR;
  16787. py_push(py_retval()); // empty set
  16788. py_Name id_add = py_name("add");
  16789. for(int i = 0; i < byte.arg; i++) {
  16790. py_push(TOP());
  16791. if(!py_pushmethod(id_add)) {
  16792. c11__abort("OP_BUILD_SET: failed to load method 'add'");
  16793. }
  16794. py_push(begin + i);
  16795. if(!py_vectorcall(1, 0)) goto __ERROR;
  16796. }
  16797. py_TValue tmp = *TOP();
  16798. SP() = begin;
  16799. PUSH(&tmp);
  16800. DISPATCH();
  16801. }
  16802. case OP_BUILD_SLICE: {
  16803. // [start, stop, step]
  16804. py_TValue tmp;
  16805. py_ObjectRef slots = py_newslice(&tmp);
  16806. slots[0] = *THIRD();
  16807. slots[1] = *SECOND();
  16808. slots[2] = *TOP();
  16809. STACK_SHRINK(3);
  16810. PUSH(&tmp);
  16811. DISPATCH();
  16812. }
  16813. case OP_BUILD_STRING: {
  16814. py_TValue* begin = SP() - byte.arg;
  16815. c11_sbuf ss;
  16816. c11_sbuf__ctor(&ss);
  16817. for(int i = 0; i < byte.arg; i++) {
  16818. if(!py_str(begin + i)) goto __ERROR;
  16819. c11_sbuf__write_sv(&ss, py_tosv(&self->last_retval));
  16820. }
  16821. SP() = begin;
  16822. c11_sbuf__py_submit(&ss, SP()++);
  16823. DISPATCH();
  16824. }
  16825. /*****************************/
  16826. #define CASE_BINARY_OP(label, op, rop) \
  16827. case label: { \
  16828. if(!pk_stack_binaryop(self, op, rop)) goto __ERROR; \
  16829. POP(); \
  16830. *TOP() = self->last_retval; \
  16831. DISPATCH(); \
  16832. }
  16833. CASE_BINARY_OP(OP_BINARY_ADD, __add__, __radd__)
  16834. CASE_BINARY_OP(OP_BINARY_SUB, __sub__, __rsub__)
  16835. CASE_BINARY_OP(OP_BINARY_MUL, __mul__, __rmul__)
  16836. CASE_BINARY_OP(OP_BINARY_TRUEDIV, __truediv__, __rtruediv__)
  16837. CASE_BINARY_OP(OP_BINARY_FLOORDIV, __floordiv__, __rfloordiv__)
  16838. CASE_BINARY_OP(OP_BINARY_MOD, __mod__, __rmod__)
  16839. CASE_BINARY_OP(OP_BINARY_POW, __pow__, __rpow__)
  16840. CASE_BINARY_OP(OP_BINARY_LSHIFT, __lshift__, 0)
  16841. CASE_BINARY_OP(OP_BINARY_RSHIFT, __rshift__, 0)
  16842. CASE_BINARY_OP(OP_BINARY_AND, __and__, 0)
  16843. CASE_BINARY_OP(OP_BINARY_OR, __or__, 0)
  16844. CASE_BINARY_OP(OP_BINARY_XOR, __xor__, 0)
  16845. CASE_BINARY_OP(OP_BINARY_MATMUL, __matmul__, 0)
  16846. CASE_BINARY_OP(OP_COMPARE_LT, __lt__, __gt__)
  16847. CASE_BINARY_OP(OP_COMPARE_LE, __le__, __ge__)
  16848. CASE_BINARY_OP(OP_COMPARE_EQ, __eq__, __eq__)
  16849. CASE_BINARY_OP(OP_COMPARE_NE, __ne__, __ne__)
  16850. CASE_BINARY_OP(OP_COMPARE_GT, __gt__, __lt__)
  16851. CASE_BINARY_OP(OP_COMPARE_GE, __ge__, __le__)
  16852. #undef CASE_BINARY_OP
  16853. case OP_IS_OP: {
  16854. bool res = py_isidentical(SECOND(), TOP());
  16855. POP();
  16856. if(byte.arg) res = !res;
  16857. py_newbool(TOP(), res);
  16858. DISPATCH();
  16859. }
  16860. case OP_CONTAINS_OP: {
  16861. // [b, a] -> b __contains__ a (a in b) -> [retval]
  16862. py_Ref magic = py_tpfindmagic(SECOND()->type, __contains__);
  16863. if(magic) {
  16864. if(magic->type == tp_nativefunc) {
  16865. if(!py_callcfunc(magic->_cfunc, 2, SECOND())) goto __ERROR;
  16866. STACK_SHRINK(2);
  16867. } else {
  16868. INSERT_THIRD(); // [?, b, a]
  16869. *THIRD() = *magic; // [__contains__, a, b]
  16870. if(!py_vectorcall(1, 0)) goto __ERROR;
  16871. }
  16872. bool res = py_tobool(py_retval());
  16873. if(byte.arg) res = !res;
  16874. py_newbool(SP()++, res);
  16875. DISPATCH();
  16876. }
  16877. TypeError("'%t' type does not support '__contains__'", SECOND()->type);
  16878. goto __ERROR;
  16879. }
  16880. /*****************************************/
  16881. case OP_JUMP_FORWARD: DISPATCH_JUMP((int16_t)byte.arg);
  16882. case OP_POP_JUMP_IF_NOT_MATCH: {
  16883. int res = py_equal(SECOND(), TOP());
  16884. if(res < 0) goto __ERROR;
  16885. STACK_SHRINK(2);
  16886. if(!res) DISPATCH_JUMP((int16_t)byte.arg);
  16887. DISPATCH();
  16888. }
  16889. case OP_POP_JUMP_IF_FALSE: {
  16890. int res = py_bool(TOP());
  16891. if(res < 0) goto __ERROR;
  16892. POP();
  16893. if(!res) DISPATCH_JUMP((int16_t)byte.arg);
  16894. DISPATCH();
  16895. }
  16896. case OP_POP_JUMP_IF_TRUE: {
  16897. int res = py_bool(TOP());
  16898. if(res < 0) goto __ERROR;
  16899. POP();
  16900. if(res) DISPATCH_JUMP((int16_t)byte.arg);
  16901. DISPATCH();
  16902. }
  16903. case OP_JUMP_IF_TRUE_OR_POP: {
  16904. int res = py_bool(TOP());
  16905. if(res < 0) goto __ERROR;
  16906. if(res) {
  16907. DISPATCH_JUMP((int16_t)byte.arg);
  16908. } else {
  16909. POP();
  16910. DISPATCH();
  16911. }
  16912. }
  16913. case OP_JUMP_IF_FALSE_OR_POP: {
  16914. int res = py_bool(TOP());
  16915. if(res < 0) goto __ERROR;
  16916. if(!res) {
  16917. DISPATCH_JUMP((int16_t)byte.arg);
  16918. } else {
  16919. POP();
  16920. DISPATCH();
  16921. }
  16922. }
  16923. case OP_SHORTCUT_IF_FALSE_OR_POP: {
  16924. int res = py_bool(TOP());
  16925. if(res < 0) goto __ERROR;
  16926. if(!res) { // [b, False]
  16927. STACK_SHRINK(2); // []
  16928. py_newbool(SP()++, false); // [False]
  16929. DISPATCH_JUMP((int16_t)byte.arg);
  16930. } else {
  16931. POP(); // [b]
  16932. DISPATCH();
  16933. }
  16934. }
  16935. case OP_LOOP_CONTINUE: {
  16936. DISPATCH_JUMP((int16_t)byte.arg);
  16937. }
  16938. case OP_LOOP_BREAK: {
  16939. DISPATCH_JUMP((int16_t)byte.arg);
  16940. }
  16941. /*****************************************/
  16942. case OP_CALL: {
  16943. if(self->heap.gc_enabled) ManagedHeap__collect_hint(&self->heap);
  16944. vectorcall_opcall(byte.arg & 0xFF, byte.arg >> 8);
  16945. DISPATCH();
  16946. }
  16947. case OP_CALL_VARGS: {
  16948. // [_0, _1, _2 | k1, v1, k2, v2]
  16949. uint16_t argc = byte.arg & 0xFF;
  16950. uint16_t kwargc = byte.arg >> 8;
  16951. int n = 0;
  16952. py_TValue* sp = SP();
  16953. py_TValue* p1 = sp - kwargc * 2;
  16954. py_TValue* base = p1 - argc;
  16955. py_TValue* buf = self->vectorcall_buffer;
  16956. for(py_TValue* curr = base; curr != p1; curr++) {
  16957. if(curr->type != tp_star_wrapper) {
  16958. buf[n++] = *curr;
  16959. } else {
  16960. py_TValue* args = py_getslot(curr, 0);
  16961. py_TValue* p;
  16962. int length = pk_arrayview(args, &p);
  16963. if(length != -1) {
  16964. for(int j = 0; j < length; j++) {
  16965. buf[n++] = p[j];
  16966. }
  16967. argc += length - 1;
  16968. } else {
  16969. TypeError("*args must be a list or tuple, got '%t'", args->type);
  16970. goto __ERROR;
  16971. }
  16972. }
  16973. }
  16974. for(py_TValue* curr = p1; curr != sp; curr += 2) {
  16975. if(curr[1].type != tp_star_wrapper) {
  16976. buf[n++] = curr[0];
  16977. buf[n++] = curr[1];
  16978. } else {
  16979. assert(py_toint(&curr[0]) == 0);
  16980. py_TValue* kwargs = py_getslot(&curr[1], 0);
  16981. if(kwargs->type == tp_dict) {
  16982. py_TValue* p = buf + n;
  16983. if(!py_dict_apply(kwargs, unpack_dict_to_buffer, &p)) goto __ERROR;
  16984. n = p - buf;
  16985. kwargc += py_dict_len(kwargs) - 1;
  16986. } else {
  16987. TypeError("**kwargs must be a dict, got '%t'", kwargs->type);
  16988. goto __ERROR;
  16989. }
  16990. }
  16991. }
  16992. memcpy(base, buf, n * sizeof(py_TValue));
  16993. SP() = base + n;
  16994. vectorcall_opcall(argc, kwargc);
  16995. DISPATCH();
  16996. }
  16997. case OP_RETURN_VALUE: {
  16998. if(byte.arg == BC_NOARG) {
  16999. self->last_retval = POPX();
  17000. } else {
  17001. py_newnone(&self->last_retval);
  17002. }
  17003. VM__pop_frame(self);
  17004. if(frame == base_frame) { // [ frameBase<- ]
  17005. return RES_RETURN;
  17006. } else {
  17007. frame = self->top_frame;
  17008. PUSH(&self->last_retval);
  17009. goto __NEXT_FRAME;
  17010. }
  17011. DISPATCH();
  17012. }
  17013. case OP_YIELD_VALUE: {
  17014. if(byte.arg == 1) {
  17015. py_newnone(py_retval());
  17016. } else {
  17017. py_assign(py_retval(), TOP());
  17018. POP();
  17019. }
  17020. return RES_YIELD;
  17021. }
  17022. case OP_FOR_ITER_YIELD_VALUE: {
  17023. int res = py_next(TOP());
  17024. if(res == -1) goto __ERROR;
  17025. if(res) {
  17026. return RES_YIELD;
  17027. } else {
  17028. assert(self->last_retval.type == tp_StopIteration);
  17029. BaseException* ud = py_touserdata(py_retval());
  17030. py_ObjectRef value = &ud->args;
  17031. if(py_isnil(value)) value = py_None();
  17032. *TOP() = *value; // [iter] -> [retval]
  17033. DISPATCH_JUMP((int16_t)byte.arg);
  17034. }
  17035. }
  17036. /////////
  17037. case OP_LIST_APPEND: {
  17038. // [list, iter, value]
  17039. py_list_append(THIRD(), TOP());
  17040. POP();
  17041. DISPATCH();
  17042. }
  17043. case OP_DICT_ADD: {
  17044. // [dict, iter, key, value]
  17045. bool ok = py_dict_setitem(FOURTH(), SECOND(), TOP());
  17046. if(!ok) goto __ERROR;
  17047. STACK_SHRINK(2);
  17048. DISPATCH();
  17049. }
  17050. case OP_SET_ADD: {
  17051. // [set, iter, value]
  17052. py_push(THIRD()); // [| set]
  17053. if(!py_pushmethod(py_name("add"))) {
  17054. c11__abort("OP_SET_ADD: failed to load method 'add'");
  17055. } // [|add() set]
  17056. py_push(THIRD());
  17057. if(!py_vectorcall(1, 0)) goto __ERROR;
  17058. POP();
  17059. DISPATCH();
  17060. }
  17061. /////////
  17062. case OP_UNARY_NEGATIVE: {
  17063. if(!pk_callmagic(__neg__, 1, TOP())) goto __ERROR;
  17064. *TOP() = self->last_retval;
  17065. DISPATCH();
  17066. }
  17067. case OP_UNARY_NOT: {
  17068. int res = py_bool(TOP());
  17069. if(res < 0) goto __ERROR;
  17070. py_newbool(TOP(), !res);
  17071. DISPATCH();
  17072. }
  17073. case OP_UNARY_STAR: {
  17074. py_TValue value = POPX();
  17075. int* level = py_newobject(SP()++, tp_star_wrapper, 1, sizeof(int));
  17076. *level = byte.arg;
  17077. py_setslot(TOP(), 0, &value);
  17078. DISPATCH();
  17079. }
  17080. case OP_UNARY_INVERT: {
  17081. if(!pk_callmagic(__invert__, 1, TOP())) goto __ERROR;
  17082. *TOP() = self->last_retval;
  17083. DISPATCH();
  17084. }
  17085. ////////////////
  17086. case OP_GET_ITER: {
  17087. if(!py_iter(TOP())) goto __ERROR;
  17088. *TOP() = *py_retval();
  17089. DISPATCH();
  17090. }
  17091. case OP_FOR_ITER: {
  17092. int res = py_next(TOP());
  17093. if(res == -1) goto __ERROR;
  17094. if(res) {
  17095. PUSH(py_retval());
  17096. DISPATCH();
  17097. } else {
  17098. assert(self->last_retval.type == tp_StopIteration);
  17099. POP(); // [iter] -> []
  17100. DISPATCH_JUMP((int16_t)byte.arg);
  17101. }
  17102. }
  17103. ////////
  17104. case OP_IMPORT_PATH: {
  17105. py_Ref path_object = c11__at(py_TValue, &frame->co->consts, byte.arg);
  17106. const char* path = py_tostr(path_object);
  17107. int res = py_import(path);
  17108. if(res == -1) goto __ERROR;
  17109. if(res == 0) {
  17110. ImportError("No module named '%s'", path);
  17111. goto __ERROR;
  17112. }
  17113. PUSH(py_retval());
  17114. DISPATCH();
  17115. }
  17116. case OP_POP_IMPORT_STAR: {
  17117. // [module]
  17118. NameDict* dict = PyObject__dict(TOP()->_obj);
  17119. py_ItemRef all = NameDict__try_get(dict, __all__);
  17120. if(all) {
  17121. py_TValue* p;
  17122. int length = pk_arrayview(all, &p);
  17123. if(length == -1) {
  17124. TypeError("'__all__' must be a list or tuple, got '%t'", all->type);
  17125. goto __ERROR;
  17126. }
  17127. for(int i = 0; i < length; i++) {
  17128. py_Name name = py_namev(py_tosv(p + i));
  17129. py_ItemRef value = NameDict__try_get(dict, name);
  17130. if(value == NULL) {
  17131. ImportError("cannot import name '%n'", name);
  17132. goto __ERROR;
  17133. } else {
  17134. if(!Frame__setglobal(frame, name, value)) goto __ERROR;
  17135. }
  17136. }
  17137. } else {
  17138. for(int i = 0; i < dict->capacity; i++) {
  17139. NameDict_KV* kv = &dict->items[i];
  17140. if(kv->key == NULL) continue;
  17141. c11_sv name = py_name2sv(kv->key);
  17142. if(name.size == 0 || name.data[0] == '_') continue;
  17143. if(!Frame__setglobal(frame, kv->key, &kv->value)) goto __ERROR;
  17144. }
  17145. }
  17146. POP();
  17147. DISPATCH();
  17148. }
  17149. ////////
  17150. case OP_UNPACK_SEQUENCE: {
  17151. py_TValue* p;
  17152. int length;
  17153. switch(TOP()->type) {
  17154. case tp_tuple: {
  17155. length = py_tuple_len(TOP());
  17156. p = py_tuple_data(TOP());
  17157. break;
  17158. }
  17159. case tp_list: {
  17160. length = py_list_len(TOP());
  17161. p = py_list_data(TOP());
  17162. break;
  17163. }
  17164. case tp_vec2i: {
  17165. length = 2;
  17166. if(byte.arg != length) break;
  17167. c11_vec2i val = py_tovec2i(TOP());
  17168. POP();
  17169. py_newint(SP()++, val.x);
  17170. py_newint(SP()++, val.y);
  17171. DISPATCH();
  17172. }
  17173. case tp_vec2: {
  17174. length = 2;
  17175. if(byte.arg != length) break;
  17176. c11_vec2 val = py_tovec2(TOP());
  17177. POP();
  17178. py_newfloat(SP()++, val.x);
  17179. py_newfloat(SP()++, val.y);
  17180. DISPATCH();
  17181. }
  17182. case tp_vec3i: {
  17183. length = 3;
  17184. if(byte.arg != length) break;
  17185. c11_vec3i val = py_tovec3i(TOP());
  17186. POP();
  17187. py_newint(SP()++, val.x);
  17188. py_newint(SP()++, val.y);
  17189. py_newint(SP()++, val.z);
  17190. DISPATCH();
  17191. }
  17192. case tp_vec3: {
  17193. length = 3;
  17194. if(byte.arg != length) break;
  17195. c11_vec3 val = py_tovec3(TOP());
  17196. POP();
  17197. py_newfloat(SP()++, val.x);
  17198. py_newfloat(SP()++, val.y);
  17199. py_newfloat(SP()++, val.z);
  17200. DISPATCH();
  17201. }
  17202. default: {
  17203. TypeError("expected list or tuple to unpack, got %t", TOP()->type);
  17204. goto __ERROR;
  17205. }
  17206. }
  17207. if(length != byte.arg) {
  17208. ValueError("expected %d values to unpack, got %d", byte.arg, length);
  17209. goto __ERROR;
  17210. }
  17211. POP();
  17212. for(int i = 0; i < length; i++) {
  17213. PUSH(p + i);
  17214. }
  17215. DISPATCH();
  17216. }
  17217. case OP_UNPACK_EX: {
  17218. py_TValue* p;
  17219. int length = pk_arrayview(TOP(), &p);
  17220. if(length == -1) {
  17221. TypeError("expected list or tuple to unpack, got %t", TOP()->type);
  17222. goto __ERROR;
  17223. }
  17224. int exceed = length - byte.arg;
  17225. if(exceed < 0) {
  17226. ValueError("not enough values to unpack");
  17227. goto __ERROR;
  17228. }
  17229. POP();
  17230. for(int i = 0; i < byte.arg; i++) {
  17231. PUSH(p + i);
  17232. }
  17233. py_newlistn(SP()++, exceed);
  17234. for(int i = 0; i < exceed; i++) {
  17235. py_list_setitem(TOP(), i, p + byte.arg + i);
  17236. }
  17237. DISPATCH();
  17238. }
  17239. ///////////
  17240. case OP_BEGIN_CLASS: {
  17241. // [base]
  17242. py_Name name = co_names[byte.arg];
  17243. py_Type base;
  17244. if(py_isnone(TOP())) {
  17245. base = tp_object;
  17246. } else {
  17247. if(!py_checktype(TOP(), tp_type)) goto __ERROR;
  17248. base = py_totype(TOP());
  17249. }
  17250. POP();
  17251. py_TypeInfo* base_ti = pk_typeinfo(base);
  17252. if(base_ti->is_final) {
  17253. TypeError("type '%t' is not an acceptable base type", base);
  17254. goto __ERROR;
  17255. }
  17256. py_Type type = pk_newtypewithmode(name,
  17257. base,
  17258. frame->module,
  17259. NULL,
  17260. base_ti->is_python,
  17261. false,
  17262. frame->co->src->mode);
  17263. PUSH(py_tpobject(type));
  17264. self->curr_class = TOP();
  17265. DISPATCH();
  17266. }
  17267. case OP_END_CLASS: {
  17268. // [cls or decorated]
  17269. py_Name name = co_names[byte.arg];
  17270. if(!Frame__setglobal(frame, name, TOP())) goto __ERROR;
  17271. if(py_istype(TOP(), tp_type)) {
  17272. // call on_end_subclass
  17273. py_TypeInfo* ti = py_touserdata(TOP());
  17274. if(ti->base != tp_object) {
  17275. py_TypeInfo* base_ti = ti->base_ti;
  17276. if(base_ti->on_end_subclass) base_ti->on_end_subclass(ti);
  17277. }
  17278. py_TValue* slot_eq = py_getdict(&ti->self, __eq__);
  17279. py_TValue* slot_ne = py_getdict(&ti->self, __ne__);
  17280. if(slot_eq && !slot_ne) {
  17281. TypeError("'%n' implements '__eq__' but not '__ne__'", ti->name);
  17282. goto __ERROR;
  17283. }
  17284. }
  17285. // class with decorator is unsafe currently
  17286. // it skips the above check
  17287. POP();
  17288. self->curr_class = NULL;
  17289. DISPATCH();
  17290. }
  17291. case OP_STORE_CLASS_ATTR: {
  17292. assert(self->curr_class);
  17293. py_Name name = co_names[byte.arg];
  17294. // TOP() can be a function, classmethod or custom decorator
  17295. py_setdict(self->curr_class, name, TOP());
  17296. POP();
  17297. DISPATCH();
  17298. }
  17299. case OP_ADD_CLASS_ANNOTATION: {
  17300. assert(self->curr_class);
  17301. // [type_hint string]
  17302. py_TypeInfo* ti = py_touserdata(self->curr_class);
  17303. if(py_isnil(&ti->annotations)) py_newdict(&ti->annotations);
  17304. py_Name name = co_names[byte.arg];
  17305. bool ok = py_dict_setitem_by_str(&ti->annotations, py_name2str(name), TOP());
  17306. if(!ok) goto __ERROR;
  17307. POP();
  17308. DISPATCH();
  17309. }
  17310. ///////////
  17311. case OP_WITH_ENTER: {
  17312. // [expr]
  17313. py_push(TOP());
  17314. if(!py_pushmethod(__enter__)) {
  17315. TypeError("'%t' object does not support the context manager protocol", TOP()->type);
  17316. goto __ERROR;
  17317. }
  17318. vectorcall_opcall(0, 0);
  17319. DISPATCH();
  17320. }
  17321. case OP_WITH_EXIT: {
  17322. // [expr]
  17323. py_push(TOP());
  17324. if(!py_pushmethod(__exit__)) {
  17325. TypeError("'%t' object does not support the context manager protocol", TOP()->type);
  17326. goto __ERROR;
  17327. }
  17328. if(!py_vectorcall(0, 0)) goto __ERROR;
  17329. POP();
  17330. DISPATCH();
  17331. }
  17332. ///////////
  17333. case OP_BEGIN_TRY: {
  17334. Frame__begin_try(frame, SP());
  17335. DISPATCH();
  17336. }
  17337. case OP_END_TRY: {
  17338. c11_vector__pop(&frame->exc_stack);
  17339. DISPATCH();
  17340. }
  17341. case OP_EXCEPTION_MATCH: {
  17342. bool ok = false;
  17343. bool has_invalid = false;
  17344. if(TOP()->type == tp_type) {
  17345. ok = py_isinstance(&self->unhandled_exc, py_totype(TOP()));
  17346. } else if(TOP()->type == tp_tuple) {
  17347. int len = py_tuple_len(TOP());
  17348. py_ObjectRef data = py_tuple_data(TOP());
  17349. for(int i = 0; i < len; i++) {
  17350. if((data + i)->type != tp_type) {
  17351. has_invalid = true;
  17352. break;
  17353. }
  17354. }
  17355. if(!has_invalid) {
  17356. for(int i = 0; i < len; i++) {
  17357. if(py_isinstance(&self->unhandled_exc, py_totype(data + i))) {
  17358. ok = true;
  17359. break;
  17360. }
  17361. }
  17362. }
  17363. } else {
  17364. has_invalid = true;
  17365. }
  17366. if(has_invalid) {
  17367. py_newnil(&self->unhandled_exc);
  17368. TypeError("catching classes that do not inherit from BaseException is not allowed");
  17369. c11_vector__pop(&frame->exc_stack);
  17370. goto __ERROR;
  17371. } else {
  17372. py_newbool(TOP(), ok);
  17373. DISPATCH();
  17374. }
  17375. }
  17376. case OP_HANDLE_EXCEPTION: {
  17377. FrameExcInfo* info = Frame__top_exc_info(frame);
  17378. assert(info != NULL && py_isnil(&info->exc));
  17379. info->exc = self->unhandled_exc;
  17380. py_newnil(&self->unhandled_exc);
  17381. DISPATCH();
  17382. }
  17383. case OP_RAISE: {
  17384. // [exception]
  17385. if(py_istype(TOP(), tp_type)) {
  17386. if(!py_tpcall(py_totype(TOP()), 0, NULL)) goto __ERROR;
  17387. py_assign(TOP(), py_retval());
  17388. }
  17389. if(!py_isinstance(TOP(), tp_BaseException)) {
  17390. TypeError("exceptions must derive from BaseException");
  17391. goto __ERROR;
  17392. }
  17393. py_raise(TOP());
  17394. goto __ERROR;
  17395. }
  17396. case OP_RAISE_ASSERT: {
  17397. if(byte.arg) {
  17398. if(!py_str(TOP())) goto __ERROR;
  17399. POP();
  17400. py_exception(tp_AssertionError, "%s", py_tostr(py_retval()));
  17401. } else {
  17402. py_exception(tp_AssertionError, "");
  17403. }
  17404. goto __ERROR;
  17405. }
  17406. case OP_RE_RAISE: {
  17407. if(py_isnil(&self->unhandled_exc)) {
  17408. FrameExcInfo* info = Frame__top_exc_info(frame);
  17409. assert(info != NULL && !py_isnil(&info->exc));
  17410. self->unhandled_exc = info->exc;
  17411. }
  17412. c11_vector__pop(&frame->exc_stack);
  17413. goto __ERROR_RE_RAISE;
  17414. }
  17415. case OP_PUSH_EXCEPTION: {
  17416. FrameExcInfo* info = Frame__top_exc_info(frame);
  17417. assert(info != NULL && !py_isnil(&info->exc));
  17418. PUSH(&info->exc);
  17419. DISPATCH();
  17420. }
  17421. //////////////////
  17422. case OP_FORMAT_STRING: {
  17423. py_Ref spec = c11__at(py_TValue, &frame->co->consts, byte.arg);
  17424. bool ok = pk_format_object(self, TOP(), py_tosv(spec));
  17425. if(!ok) goto __ERROR;
  17426. py_assign(TOP(), py_retval());
  17427. DISPATCH();
  17428. }
  17429. default: c11__unreachable();
  17430. }
  17431. c11__unreachable();
  17432. __ERROR:
  17433. assert(!py_isnil(&self->unhandled_exc));
  17434. py_BaseException__stpush(frame,
  17435. &self->unhandled_exc,
  17436. frame->co->src,
  17437. Frame__lineno(frame),
  17438. !frame->is_locals_special ? frame->co->name->data : NULL);
  17439. __ERROR_RE_RAISE:
  17440. do {
  17441. self->curr_class = NULL;
  17442. self->curr_function = NULL;
  17443. } while(0);
  17444. #if PK_ENABLE_WATCHDOG
  17445. // LYNX: a script stopped for running too long is not given to its own `except:` / `finally:` handlers (an
  17446. // `except:` in a loop would catch the TimeoutError of every opcode again and again, growing without end)
  17447. int target = py_lynx_interrupt ? -1 : Frame__goto_exception_handler(frame, &self->stack, &self->unhandled_exc);
  17448. #else
  17449. int target = Frame__goto_exception_handler(frame, &self->stack, &self->unhandled_exc);
  17450. #endif
  17451. if(target >= 0) {
  17452. // 1. Exception can be handled inside the current frame
  17453. DISPATCH_JUMP_ABSOLUTE(target);
  17454. } else {
  17455. // 2. Exception need to be propagated to the upper frame
  17456. bool is_base_frame_to_be_popped = frame == base_frame;
  17457. VM__pop_frame(self);
  17458. if(self->top_frame == NULL || is_base_frame_to_be_popped) {
  17459. // propagate to the top level
  17460. return RES_ERROR;
  17461. }
  17462. frame = self->top_frame;
  17463. RESET_CO_CACHE();
  17464. goto __ERROR;
  17465. }
  17466. c11__unreachable();
  17467. }
  17468. const char* pk_op2str(py_Name op) {
  17469. if(__eq__ == op) return "==";
  17470. if(__ne__ == op) return "!=";
  17471. if(__lt__ == op) return "<";
  17472. if(__le__ == op) return "<=";
  17473. if(__gt__ == op) return ">";
  17474. if(__ge__ == op) return ">=";
  17475. if(__add__ == op) return "+";
  17476. if(__sub__ == op) return "-";
  17477. if(__mul__ == op) return "*";
  17478. if(__truediv__ == op) return "/";
  17479. if(__floordiv__ == op) return "//";
  17480. if(__mod__ == op) return "%";
  17481. if(__pow__ == op) return "**";
  17482. if(__lshift__ == op) return "<<";
  17483. if(__rshift__ == op) return ">>";
  17484. if(__and__ == op) return "&";
  17485. if(__or__ == op) return "|";
  17486. if(__xor__ == op) return "^";
  17487. if(__neg__ == op) return "-";
  17488. if(__invert__ == op) return "~";
  17489. if(__matmul__ == op) return "@";
  17490. return py_name2str(op);
  17491. }
  17492. bool pk_stack_binaryop(VM* self, py_Name op, py_Name rop) {
  17493. // [a, b]
  17494. py_Ref magic = py_tpfindmagic(SECOND()->type, op);
  17495. if(magic) {
  17496. bool ok = py_call(magic, 2, SECOND());
  17497. if(!ok) return false;
  17498. if(self->last_retval.type != tp_NotImplementedType) return true;
  17499. }
  17500. // try reverse operation
  17501. if(rop) {
  17502. // [a, b] -> [b, a]
  17503. py_TValue tmp = *TOP();
  17504. *TOP() = *SECOND();
  17505. *SECOND() = tmp;
  17506. magic = py_tpfindmagic(SECOND()->type, rop);
  17507. if(magic) {
  17508. bool ok = py_call(magic, 2, SECOND());
  17509. if(!ok) return false;
  17510. if(self->last_retval.type != tp_NotImplementedType) return true;
  17511. }
  17512. }
  17513. // eq/ne op never fails
  17514. bool res = py_isidentical(SECOND(), TOP());
  17515. if(op == __eq__) {
  17516. py_newbool(py_retval(), res);
  17517. return true;
  17518. }
  17519. if(op == __ne__) {
  17520. py_newbool(py_retval(), !res);
  17521. return true;
  17522. }
  17523. py_Type lhs_t = rop ? TOP()->type : SECOND()->type;
  17524. py_Type rhs_t = rop ? SECOND()->type : TOP()->type;
  17525. return TypeError("unsupported operand type(s) for '%s': '%t' and '%t'",
  17526. pk_op2str(op),
  17527. lhs_t,
  17528. rhs_t);
  17529. }
  17530. bool pk_format_object(VM* self, py_Ref val, c11_sv spec) {
  17531. // format TOS via `spec` inplace
  17532. // spec: '!r:.2f', ':.2f', '.2f'
  17533. if(spec.size == 0) return py_str(val);
  17534. if(spec.data[0] == '!') {
  17535. if(c11_sv__startswith(spec, (c11_sv){"!r", 2})) {
  17536. spec.data += 2;
  17537. spec.size -= 2;
  17538. if(!py_repr(val)) return false;
  17539. py_assign(val, py_retval());
  17540. if(spec.size == 0) return true;
  17541. } else {
  17542. return ValueError("invalid conversion specifier (only !r is supported)");
  17543. }
  17544. }
  17545. assert(spec.size > 0);
  17546. if(spec.data[0] == ':') {
  17547. spec.data++;
  17548. spec.size--;
  17549. }
  17550. char type;
  17551. switch(spec.data[spec.size - 1]) {
  17552. case 'f':
  17553. case 'd':
  17554. case 's':
  17555. type = spec.data[spec.size - 1];
  17556. spec.size--; // remove last char
  17557. break;
  17558. default: type = ' '; break;
  17559. }
  17560. char pad_c = ' ';
  17561. if(strchr("0-=*#@!~", spec.data[0])) {
  17562. pad_c = spec.data[0];
  17563. spec = c11_sv__slice(spec, 1);
  17564. }
  17565. char align;
  17566. if(spec.data[0] == '^') {
  17567. align = '^';
  17568. spec = c11_sv__slice(spec, 1);
  17569. } else if(spec.data[0] == '>') {
  17570. align = '>';
  17571. spec = c11_sv__slice(spec, 1);
  17572. } else if(spec.data[0] == '<') {
  17573. align = '<';
  17574. spec = c11_sv__slice(spec, 1);
  17575. } else {
  17576. align = (py_isint(val) || py_isfloat(val)) ? '>' : '<';
  17577. }
  17578. int dot = c11_sv__index(spec, '.');
  17579. py_i64 width, precision;
  17580. if(dot >= 0) {
  17581. if(dot == 0) {
  17582. // {.2f}
  17583. width = -1;
  17584. } else {
  17585. // {10.2f}
  17586. IntParsingResult res = c11__parse_uint(c11_sv__slice2(spec, 0, dot), &width, 10);
  17587. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifier");
  17588. }
  17589. IntParsingResult res = c11__parse_uint(c11_sv__slice(spec, dot + 1), &precision, 10);
  17590. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifier");
  17591. } else {
  17592. // {10s}
  17593. IntParsingResult res = c11__parse_uint(spec, &width, 10);
  17594. if(res != IntParsing_SUCCESS) return ValueError("invalid format specifier");
  17595. precision = -1;
  17596. }
  17597. if(type != 'f' && dot >= 0) {
  17598. return ValueError("precision not allowed in the format specifier");
  17599. }
  17600. c11_sbuf buf;
  17601. c11_sbuf__ctor(&buf);
  17602. if(type == 'f') {
  17603. py_f64 x;
  17604. if(!py_castfloat(val, &x)) {
  17605. c11_sbuf__dtor(&buf);
  17606. return false;
  17607. }
  17608. if(precision < 0) precision = 6;
  17609. c11_sbuf__write_f64(&buf, x, precision);
  17610. } else if(type == 'd') {
  17611. if(!py_checkint(val)) {
  17612. c11_sbuf__dtor(&buf);
  17613. return false;
  17614. }
  17615. c11_sbuf__write_i64(&buf, py_toint(val));
  17616. } else if(type == 's') {
  17617. if(!py_checkstr(val)) {
  17618. c11_sbuf__dtor(&buf);
  17619. return false;
  17620. }
  17621. c11_sbuf__write_sv(&buf, py_tosv(val));
  17622. } else {
  17623. if(!py_str(val)) {
  17624. c11_sbuf__dtor(&buf);
  17625. return false;
  17626. }
  17627. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  17628. }
  17629. c11_string* body = c11_sbuf__submit(&buf);
  17630. int length = c11_sv__u8_length(c11_string__sv(body));
  17631. c11_sbuf__ctor(&buf); // reinit sbuf
  17632. if(width != -1 && width > length) {
  17633. switch(align) {
  17634. case '>': {
  17635. c11_sbuf__write_pad(&buf, width - length, pad_c);
  17636. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  17637. break;
  17638. }
  17639. case '<': {
  17640. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  17641. c11_sbuf__write_pad(&buf, width - length, pad_c);
  17642. break;
  17643. }
  17644. case '^': {
  17645. int pad_left = (width - length) / 2;
  17646. int pad_right = (width - length) - pad_left;
  17647. c11_sbuf__write_pad(&buf, pad_left, pad_c);
  17648. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  17649. c11_sbuf__write_pad(&buf, pad_right, pad_c);
  17650. break;
  17651. }
  17652. default: c11__unreachable();
  17653. }
  17654. } else {
  17655. c11_sbuf__write_sv(&buf, c11_string__sv(body));
  17656. }
  17657. c11_string__delete(body);
  17658. // inplace update
  17659. c11_sbuf__py_submit(&buf, py_retval());
  17660. return true;
  17661. }
  17662. #undef DISPATCH
  17663. #undef DISPATCH_JUMP
  17664. #undef DISPATCH_JUMP_ABSOLUTE
  17665. #undef TOP
  17666. #undef SECOND
  17667. #undef THIRD
  17668. #undef FOURTH
  17669. #undef STACK_SHRINK
  17670. #undef STACK_GROW
  17671. #undef PUSH
  17672. #undef POP
  17673. #undef POPX
  17674. #undef SP
  17675. #undef INSERT_THIRD
  17676. #undef vectorcall_opcall
  17677. #undef RESET_CO_CACHE
  17678. // src/interpreter\dll.c
  17679. #if PK_IS_DESKTOP_PLATFORM && PK_ENABLE_OS && PK_ENABLE_DLL
  17680. #ifdef _WIN32
  17681. #define WIN32_LEAN_AND_MEAN
  17682. #include <windows.h>
  17683. #undef WIN32_LEAN_AND_MEAN
  17684. #else
  17685. #include <dlfcn.h>
  17686. #include <stdlib.h>
  17687. #include <string.h>
  17688. #endif
  17689. typedef bool (*py_module_initialize_t)() PY_RAISE PY_RETURN;
  17690. int load_module_from_dll_desktop_only(const char* path) PY_RAISE PY_RETURN {
  17691. const char* f_init_name = "py_module_initialize";
  17692. #ifdef _WIN32
  17693. void* dll = LoadLibraryA(path);
  17694. if(dll == NULL) return 0;
  17695. py_module_initialize_t f_init = (py_module_initialize_t)GetProcAddress(dll, f_init_name);
  17696. #else
  17697. void* dll = NULL;
  17698. // On Linux, dlopen doesn't automatically add .so suffix like Windows does with .dll
  17699. // Also, CMake typically generates libXxx.so instead of Xxx.so
  17700. // Try: path.so, libpath.so, then the original path
  17701. char* path_with_so = NULL;
  17702. char* path_with_lib = NULL;
  17703. size_t path_len = strlen(path);
  17704. // Try path.so
  17705. path_with_so = py_malloc(path_len + 4); // .so + null terminator
  17706. if(path_with_so != NULL) {
  17707. strcpy(path_with_so, path);
  17708. strcat(path_with_so, ".so");
  17709. dll = dlopen(path_with_so, RTLD_LAZY);
  17710. py_free(path_with_so);
  17711. }
  17712. // Try libpath.so if path.so didn't work
  17713. if(dll == NULL) {
  17714. path_with_lib = py_malloc(path_len + 7); // lib + .so + null terminator
  17715. if(path_with_lib != NULL) {
  17716. strcpy(path_with_lib, "lib");
  17717. strcat(path_with_lib, path);
  17718. strcat(path_with_lib, ".so");
  17719. dll = dlopen(path_with_lib, RTLD_LAZY);
  17720. py_free(path_with_lib);
  17721. }
  17722. }
  17723. // Fallback to original path
  17724. if(dll == NULL) {
  17725. dll = dlopen(path, RTLD_LAZY);
  17726. }
  17727. if(dll == NULL) return 0;
  17728. py_module_initialize_t f_init = (py_module_initialize_t)dlsym(dll, f_init_name);
  17729. #endif
  17730. if(f_init == NULL) return 0;
  17731. bool success = f_init();
  17732. if(!success) return -1;
  17733. return 1;
  17734. }
  17735. #else
  17736. int load_module_from_dll_desktop_only(const char* path) PY_RAISE PY_RETURN {
  17737. return 0;
  17738. }
  17739. #endif
  17740. // src/interpreter\frame.c
  17741. #include <stdbool.h>
  17742. #include <assert.h>
  17743. void FastLocals__to_dict(py_TValue* locals, const CodeObject* co) {
  17744. py_StackRef dict = py_pushtmp();
  17745. py_newdict(dict);
  17746. c11__foreach(c11_smallmap_n2d_KV, &co->varnames_inv, entry) {
  17747. py_TValue* value = &locals[entry->value];
  17748. if(!py_isnil(value)) {
  17749. bool ok = py_dict_setitem(dict, py_name2ref(entry->key), value);
  17750. assert(ok);
  17751. (void)ok;
  17752. }
  17753. }
  17754. py_assign(py_retval(), dict);
  17755. py_pop();
  17756. }
  17757. NameDict* FastLocals__to_namedict(py_TValue* locals, const CodeObject* co) {
  17758. NameDict* dict = NameDict__new(PK_INST_ATTR_LOAD_FACTOR);
  17759. c11__foreach(c11_smallmap_n2d_KV, &co->varnames_inv, entry) {
  17760. py_Ref val = &locals[entry->value];
  17761. if(!py_isnil(val)) NameDict__set(dict, entry->key, val);
  17762. }
  17763. return dict;
  17764. }
  17765. py_Frame* Frame__new(const CodeObject* co,
  17766. py_StackRef p0,
  17767. py_GlobalRef module,
  17768. py_Ref globals,
  17769. py_Ref locals,
  17770. bool is_locals_special) {
  17771. assert(module->type == tp_module);
  17772. assert(globals->type == tp_module || globals->type == tp_dict);
  17773. if(is_locals_special) {
  17774. assert(locals->type == tp_nil || locals->type == tp_locals || locals->type == tp_dict);
  17775. }
  17776. py_Frame* self = FixedMemoryPool__alloc(&pk_current_vm->pool_frame);
  17777. self->f_back = NULL;
  17778. self->co = co;
  17779. self->p0 = p0;
  17780. self->module = module;
  17781. self->globals = globals;
  17782. self->locals = locals;
  17783. self->is_locals_special = is_locals_special;
  17784. self->ip = -1;
  17785. c11_vector__ctor(&self->exc_stack, sizeof(FrameExcInfo));
  17786. return self;
  17787. }
  17788. void Frame__delete(py_Frame* self) {
  17789. c11_vector__dtor(&self->exc_stack);
  17790. FixedMemoryPool__dealloc(&pk_current_vm->pool_frame, self);
  17791. }
  17792. int Frame__goto_exception_handler(py_Frame* self, ValueStack* value_stack, py_Ref exc) {
  17793. FrameExcInfo* p = self->exc_stack.data;
  17794. for(int i = self->exc_stack.length - 1; i >= 0; i--) {
  17795. if(py_isnil(&p[i].exc)) {
  17796. value_stack->sp = (self->p0 + p[i].offset); // unwind the stack
  17797. return c11__at(CodeBlock, &self->co->blocks, p[i].iblock)->end;
  17798. } else {
  17799. self->exc_stack.length--;
  17800. }
  17801. }
  17802. return -1;
  17803. }
  17804. void Frame__begin_try(py_Frame* self, py_TValue* sp) {
  17805. int iblock = Frame__iblock(self);
  17806. assert(iblock >= 0);
  17807. FrameExcInfo* info = c11_vector__emplace(&self->exc_stack);
  17808. info->iblock = iblock;
  17809. info->offset = (int)(sp - self->p0);
  17810. py_newnil(&info->exc);
  17811. }
  17812. FrameExcInfo* Frame__top_exc_info(py_Frame* self) {
  17813. if(self->exc_stack.length == 0) return NULL;
  17814. return &c11_vector__back(FrameExcInfo, &self->exc_stack);
  17815. }
  17816. void Frame__gc_mark(py_Frame* self, c11_vector* p_stack) {
  17817. pk__mark_value(self->globals);
  17818. if(self->is_locals_special) pk__mark_value(self->locals);
  17819. CodeObject__gc_mark(self->co, p_stack);
  17820. c11__foreach(FrameExcInfo, &self->exc_stack, info) { pk__mark_value(&info->exc); }
  17821. }
  17822. int Frame__lineno(const py_Frame* self) {
  17823. int ip = self->ip;
  17824. if(ip >= 0) {
  17825. BytecodeEx* ex = c11__at(BytecodeEx, &self->co->codes_ex, ip);
  17826. return ex->lineno;
  17827. }
  17828. if(!self->is_locals_special) return self->co->start_line;
  17829. return 0;
  17830. }
  17831. int Frame__iblock(const py_Frame* self) {
  17832. int ip = self->ip;
  17833. if(ip < 0) return -1;
  17834. return c11__getitem(BytecodeEx, &self->co->codes_ex, ip).iblock;
  17835. }
  17836. int Frame__getglobal(py_Frame* self, py_Name name) {
  17837. if(self->globals->type == tp_module) {
  17838. py_ItemRef item = py_getdict(self->globals, name);
  17839. if(item != NULL) {
  17840. py_assign(py_retval(), item);
  17841. return 1;
  17842. }
  17843. return 0;
  17844. } else {
  17845. return py_dict_getitem(self->globals, py_name2ref(name));
  17846. }
  17847. }
  17848. bool Frame__setglobal(py_Frame* self, py_Name name, py_TValue* val) {
  17849. if(self->globals->type == tp_module) {
  17850. py_setdict(self->globals, name, val);
  17851. return true;
  17852. } else {
  17853. return py_dict_setitem(self->globals, py_name2ref(name), val);
  17854. }
  17855. }
  17856. int Frame__delglobal(py_Frame* self, py_Name name) {
  17857. if(self->globals->type == tp_module) {
  17858. bool found = py_deldict(self->globals, name);
  17859. return found ? 1 : 0;
  17860. } else {
  17861. return py_dict_delitem(self->globals, py_name2ref(name));
  17862. }
  17863. }
  17864. py_StackRef Frame__getlocal_noproxy(py_Frame* self, py_Name name) {
  17865. assert(!self->is_locals_special);
  17866. int index = c11_smallmap_n2d__get(&self->co->varnames_inv, name, -1);
  17867. if(index == -1) return NULL;
  17868. return &self->locals[index];
  17869. }
  17870. py_Ref Frame__getclosure(py_Frame* self, py_Name name) {
  17871. if(self->is_locals_special) return NULL;
  17872. assert(self->p0->type == tp_function);
  17873. Function* ud = py_touserdata(self->p0);
  17874. if(ud->closure == NULL) return NULL;
  17875. return NameDict__try_get(ud->closure, name);
  17876. }
  17877. SourceLocation Frame__source_location(py_Frame* self) {
  17878. SourceLocation loc;
  17879. loc.lineno = Frame__lineno(self);
  17880. loc.src = self->co->src;
  17881. return loc;
  17882. }
  17883. // src/interpreter\generator.c
  17884. #include <stdbool.h>
  17885. #include <assert.h>
  17886. void pk_newgenerator(py_Ref out, py_Frame* frame, py_TValue* begin, py_TValue* end) {
  17887. Generator* ud = py_newobject(out, tp_generator, 1, sizeof(Generator));
  17888. ud->frame = frame;
  17889. ud->state = 0;
  17890. py_Ref tmp = py_getslot(out, 0);
  17891. py_newlist(tmp);
  17892. for(py_TValue* p = begin; p != end; p++) {
  17893. py_list_append(tmp, p);
  17894. }
  17895. }
  17896. void Generator__dtor(Generator* ud) {
  17897. if(ud->frame) Frame__delete(ud->frame);
  17898. }
  17899. bool generator__next__(int argc, py_Ref argv) {
  17900. PY_CHECK_ARGC(1);
  17901. Generator* ud = py_touserdata(argv);
  17902. py_StackRef p0 = py_peek(0);
  17903. VM* vm = pk_current_vm;
  17904. if(ud->state == 2) return StopIteration();
  17905. // reset frame->p0
  17906. assert(!ud->frame->is_locals_special);
  17907. int locals_offset = ud->frame->locals - ud->frame->p0;
  17908. ud->frame->p0 = py_peek(0);
  17909. ud->frame->locals = ud->frame->p0 + locals_offset;
  17910. // restore the context
  17911. py_Ref backup = py_getslot(argv, 0);
  17912. int length = py_list_len(backup);
  17913. py_TValue* p = py_list_data(backup);
  17914. for(int i = 0; i < length; i++)
  17915. py_push(&p[i]);
  17916. py_list_clear(backup);
  17917. // push frame
  17918. VM__push_frame(vm, ud->frame);
  17919. ud->frame = NULL;
  17920. FrameResult res = VM__run_top_frame(vm);
  17921. if(res == RES_ERROR) {
  17922. ud->state = 2; // end this generator immediately on error
  17923. if(py_matchexc(tp_StopIteration)) {
  17924. py_clearexc(p0);
  17925. return true;
  17926. }
  17927. return false;
  17928. }
  17929. if(res == RES_YIELD) {
  17930. // backup the context
  17931. ud->frame = vm->top_frame;
  17932. for(py_StackRef p = ud->frame->p0; p != vm->stack.sp; p++) {
  17933. py_list_append(backup, p);
  17934. }
  17935. vm->stack.sp = ud->frame->p0;
  17936. vm->top_frame = vm->top_frame->f_back;
  17937. vm->recursion_depth--;
  17938. ud->state = 1;
  17939. return true;
  17940. } else {
  17941. assert(res == RES_RETURN);
  17942. ud->state = 2;
  17943. // raise StopIteration(<retval>)
  17944. bool ok = py_tpcall(tp_StopIteration, 1, py_retval());
  17945. if(!ok) return false;
  17946. return py_raise(py_retval());
  17947. }
  17948. }
  17949. py_Type pk_generator__register() {
  17950. py_Type type = pk_newtype("generator", tp_object, NULL, (py_Dtor)Generator__dtor, false, true);
  17951. py_bindmagic(type, __iter__, pk_wrapper__self);
  17952. py_bindmagic(type, __next__, generator__next__);
  17953. return type;
  17954. }
  17955. // src/interpreter\heap.c
  17956. #include <assert.h>
  17957. static uint8_t encode_size_8b(int size, int* out_size) {
  17958. int bit_length = c11__bit_length(size);
  17959. int min_val = 1 << (bit_length - 1);
  17960. int gap = min_val;
  17961. float ratio = (float)(size - min_val) / gap;
  17962. int ratio_3bit = (int)(ratio * 7.999f);
  17963. *out_size = min_val + (int)(gap * ((float)ratio_3bit / 7.999f));
  17964. return (uint8_t)((bit_length << 3) | ratio_3bit);
  17965. }
  17966. static int decode_size_8b(uint8_t byte) {
  17967. int bit_length = byte >> 3;
  17968. int ratio_3bit = byte & 0x07;
  17969. int min_val = 1 << (bit_length - 1);
  17970. int gap = min_val;
  17971. float ratio = (float)ratio_3bit / 7.999f;
  17972. return min_val + (int)(gap * ratio);
  17973. }
  17974. void ManagedHeap__ctor(ManagedHeap* self) {
  17975. MultiPool__ctor(&self->small_objects);
  17976. c11_vector__ctor(&self->large_objects, sizeof(PyObject*));
  17977. c11_vector__ctor(&self->gc_roots, sizeof(PyObject*));
  17978. self->large_total_size = 0;
  17979. for(int i = 0; i < c11__count_array(self->freed_ma); i++) {
  17980. self->freed_ma[i] = PK_GC_MIN_THRESHOLD;
  17981. }
  17982. self->gc_threshold = PK_GC_MIN_THRESHOLD;
  17983. self->gc_counter = 0;
  17984. self->gc_enabled = true;
  17985. self->debug_callback = *py_None();
  17986. }
  17987. void ManagedHeap__dtor(ManagedHeap* self) {
  17988. // small_objects
  17989. MultiPool__dtor(&self->small_objects);
  17990. // large_objects
  17991. for(int i = 0; i < self->large_objects.length; i++) {
  17992. PyObject* obj = c11__getitem(PyObject*, &self->large_objects, i);
  17993. PyObject__dtor(obj);
  17994. PK_FREE(obj);
  17995. }
  17996. c11_vector__dtor(&self->large_objects);
  17997. c11_vector__dtor(&self->gc_roots);
  17998. }
  17999. static void ManagedHeap__fire_debug_callback_start(ManagedHeap* self) {
  18000. py_push(&self->debug_callback);
  18001. py_pushnil();
  18002. py_newstr(py_pushtmp(), "start");
  18003. py_newstr(py_pushtmp(), "");
  18004. bool ok = py_vectorcall(2, 0);
  18005. if(!ok) {
  18006. char* msg = py_formatexc();
  18007. c11__abort("gc_debug_callback error!!\n%s", msg);
  18008. }
  18009. }
  18010. static void ManagedHeap__fire_debug_callback_stop(ManagedHeap* self,
  18011. ManagedHeapSwpetInfo* out_info) {
  18012. assert(out_info != NULL);
  18013. c11_sbuf buf;
  18014. c11_sbuf__ctor(&buf);
  18015. const int64_t NANOS_PER_MS = 1000000000 / 1000;
  18016. const char* DIVIDER = "------------------------------------------------------------\n";
  18017. int64_t mark_ms = (out_info->mark_end_ns - out_info->start_ns) / NANOS_PER_MS;
  18018. int64_t swpet_ms = (out_info->swpet_end_ns - out_info->mark_end_ns) / NANOS_PER_MS;
  18019. c11_sbuf__write_cstr(&buf, DIVIDER);
  18020. pk_sprintf(&buf, "start: %f\n", out_info->start_ns / 1e9);
  18021. pk_sprintf(&buf, "mark_ms: %i\n", (py_i64)mark_ms);
  18022. pk_sprintf(&buf, "swpet_ms: %i\n", (py_i64)swpet_ms);
  18023. pk_sprintf(&buf, "total_ms: %i\n", (py_i64)(mark_ms + swpet_ms));
  18024. c11_sbuf__write_cstr(&buf, DIVIDER);
  18025. pk_sprintf(&buf, "types_length: %d\n", out_info->types_length);
  18026. pk_sprintf(&buf, "small_freed: %d\n", out_info->small_freed);
  18027. pk_sprintf(&buf, "large_freed: %d\n", out_info->large_freed);
  18028. c11_sbuf__write_cstr(&buf, DIVIDER);
  18029. if(out_info->small_freed != 0 || out_info->large_freed != 0) {
  18030. char line_buf[256];
  18031. for(int i = 0; i < out_info->types_length; i++) {
  18032. const char* type_name = py_tpname(i);
  18033. int s_freed = out_info->small_types[i];
  18034. int l_freed = out_info->large_types[i];
  18035. if(s_freed == 0 && l_freed == 0) continue;
  18036. snprintf(line_buf,
  18037. sizeof(line_buf),
  18038. "[%-24s] small: %6d large: %6d\n",
  18039. type_name,
  18040. s_freed,
  18041. l_freed);
  18042. c11_sbuf__write_cstr(&buf, line_buf);
  18043. }
  18044. c11_sbuf__write_cstr(&buf, DIVIDER);
  18045. }
  18046. pk_sprintf(&buf, "auto_thres.before: %d\n", out_info->auto_thres.before);
  18047. pk_sprintf(&buf, "auto_thres.after: %d\n", out_info->auto_thres.after);
  18048. pk_sprintf(&buf, "auto_thres.upper: %d\n", out_info->auto_thres.upper);
  18049. pk_sprintf(&buf, "auto_thres.lower: %d\n", out_info->auto_thres.lower);
  18050. pk_sprintf(&buf, "auto_thres.avg_freed: %d\n", out_info->auto_thres.avg_freed);
  18051. pk_sprintf(&buf, "auto_thres.free_ratio: %f\n", out_info->auto_thres.free_ratio);
  18052. c11_sbuf__write_cstr(&buf, DIVIDER);
  18053. py_push(&self->debug_callback);
  18054. py_pushnil();
  18055. py_newstr(py_pushtmp(), "stop");
  18056. py_StackRef arg = py_pushtmp();
  18057. c11_sbuf__py_submit(&buf, arg);
  18058. bool ok = py_vectorcall(2, 0);
  18059. if(!ok) {
  18060. char* msg = py_formatexc();
  18061. c11__abort("gc_debug_callback error!!\n%s", msg);
  18062. }
  18063. }
  18064. int ManagedHeap__collect_hint(ManagedHeap* self) {
  18065. if(self->gc_counter < self->gc_threshold) return 0;
  18066. self->gc_counter = 0;
  18067. ManagedHeapSwpetInfo* out_info = NULL;
  18068. if(!py_isnone(&self->debug_callback)) {
  18069. out_info = ManagedHeapSwpetInfo__new();
  18070. ManagedHeap__fire_debug_callback_start(self);
  18071. }
  18072. ManagedHeap__mark(self);
  18073. if(out_info) out_info->mark_end_ns = time_ns();
  18074. int freed = ManagedHeap__sweep(self, out_info);
  18075. if(out_info) out_info->swpet_end_ns = time_ns();
  18076. // adjust `gc_threshold` based on `freed_ma`
  18077. self->freed_ma[0] = self->freed_ma[1];
  18078. self->freed_ma[1] = self->freed_ma[2];
  18079. self->freed_ma[2] = freed;
  18080. int avg_freed = (self->freed_ma[0] + self->freed_ma[1] + self->freed_ma[2]) / 3;
  18081. const int upper = PK_GC_MIN_THRESHOLD * 8;
  18082. const int lower = PK_GC_MIN_THRESHOLD / 2;
  18083. float free_ratio = (float)avg_freed / self->gc_threshold;
  18084. int new_threshold = self->gc_threshold * (1.5f / free_ratio);
  18085. if(out_info) {
  18086. out_info->auto_thres.before = self->gc_threshold;
  18087. out_info->auto_thres.after = new_threshold;
  18088. out_info->auto_thres.upper = upper;
  18089. out_info->auto_thres.lower = lower;
  18090. out_info->auto_thres.avg_freed = avg_freed;
  18091. out_info->auto_thres.free_ratio = free_ratio;
  18092. }
  18093. self->gc_threshold = c11__min(c11__max(new_threshold, lower), upper);
  18094. if(!py_isnone(&self->debug_callback)) {
  18095. ManagedHeap__fire_debug_callback_stop(self, out_info);
  18096. ManagedHeapSwpetInfo__delete(out_info);
  18097. }
  18098. return freed;
  18099. }
  18100. int ManagedHeap__collect(ManagedHeap* self) {
  18101. self->gc_counter = 0;
  18102. ManagedHeapSwpetInfo* out_info = NULL;
  18103. if(!py_isnone(&self->debug_callback)) {
  18104. out_info = ManagedHeapSwpetInfo__new();
  18105. ManagedHeap__fire_debug_callback_start(self);
  18106. }
  18107. ManagedHeap__mark(self);
  18108. if(out_info) out_info->mark_end_ns = time_ns();
  18109. int freed = ManagedHeap__sweep(self, out_info);
  18110. if(out_info) out_info->swpet_end_ns = time_ns();
  18111. if(out_info) {
  18112. out_info->auto_thres.before = self->gc_threshold;
  18113. out_info->auto_thres.after = self->gc_threshold;
  18114. }
  18115. if(!py_isnone(&self->debug_callback)) {
  18116. ManagedHeap__fire_debug_callback_stop(self, out_info);
  18117. ManagedHeapSwpetInfo__delete(out_info);
  18118. }
  18119. return freed;
  18120. }
  18121. int ManagedHeap__sweep(ManagedHeap* self, ManagedHeapSwpetInfo* out_info) {
  18122. // small_objects
  18123. int small_freed =
  18124. MultiPool__sweep_dealloc(&self->small_objects, out_info ? out_info->small_types : NULL);
  18125. // large_objects
  18126. int large_living_count = 0;
  18127. for(int i = 0; i < self->large_objects.length; i++) {
  18128. PyObject* obj = c11__getitem(PyObject*, &self->large_objects, i);
  18129. if(obj->gc_marked & 0b01) {
  18130. obj->gc_marked &= 0b10;
  18131. c11__setitem(PyObject*, &self->large_objects, large_living_count, obj);
  18132. large_living_count++;
  18133. } else {
  18134. if(out_info) out_info->large_types[obj->type]++;
  18135. self->large_total_size -= decode_size_8b(obj->size_8b);
  18136. PyObject__dtor(obj);
  18137. PK_FREE(obj);
  18138. }
  18139. }
  18140. // shrink `self->large_objects`
  18141. int large_freed = self->large_objects.length - large_living_count;
  18142. self->large_objects.length = large_living_count;
  18143. if(out_info) {
  18144. out_info->small_freed = small_freed;
  18145. out_info->large_freed = large_freed;
  18146. }
  18147. return small_freed + large_freed;
  18148. }
  18149. PyObject* ManagedHeap__gcnew(ManagedHeap* self, py_Type type, int slots, int udsize) {
  18150. assert(slots >= 0 || slots == -1);
  18151. // header + slots + udsize
  18152. int size = sizeof(PyObject) + PK_OBJ_SLOTS_SIZE(slots) + udsize;
  18153. PyObject* obj = MultiPool__alloc(&self->small_objects, size);
  18154. uint8_t size_8b = 0;
  18155. if(obj == NULL) {
  18156. obj = PK_MALLOC(size);
  18157. int quantized_size;
  18158. size_8b = encode_size_8b(size, &quantized_size);
  18159. self->large_total_size += quantized_size;
  18160. c11_vector__push(PyObject*, &self->large_objects, obj);
  18161. }
  18162. obj->type = type;
  18163. obj->size_8b = size_8b;
  18164. obj->gc_marked = 0;
  18165. obj->slots = slots;
  18166. // initialize slots or dict
  18167. if(slots >= 0) {
  18168. memset(obj->flex, 0, slots * sizeof(py_TValue));
  18169. } else {
  18170. float load_factor = (type == tp_type || type == tp_module) ? PK_TYPE_ATTR_LOAD_FACTOR
  18171. : PK_INST_ATTR_LOAD_FACTOR;
  18172. NameDict__ctor((void*)obj->flex, load_factor);
  18173. }
  18174. self->gc_counter++;
  18175. return obj;
  18176. }
  18177. // src/interpreter\line_profiler.c
  18178. #include <assert.h>
  18179. void LineProfiler__ctor(LineProfiler* self) {
  18180. c11_smallmap_p2i__ctor(&self->records);
  18181. c11_vector__ctor(&self->frame_records, sizeof(FrameRecord));
  18182. self->enabled = false;
  18183. }
  18184. void LineProfiler__dtor(LineProfiler* self) {
  18185. for(int i = 0; i < self->records.length; i++) {
  18186. c11_smallmap_p2i_KV kv = c11__getitem(c11_smallmap_p2i_KV, &self->records, i);
  18187. SourceData_ src = (SourceData_)kv.key;
  18188. PK_DECREF(src);
  18189. PK_FREE((void*)kv.value);
  18190. }
  18191. c11_smallmap_p2i__dtor(&self->records);
  18192. c11_vector__dtor(&self->frame_records);
  18193. }
  18194. LineRecord* LineProfiler__get_record(LineProfiler* self, SourceLocation loc) {
  18195. LineRecord* lines = (LineRecord*)c11_smallmap_p2i__get(&self->records, loc.src, 0);
  18196. if(lines == NULL) {
  18197. int max_lineno = loc.src->line_starts.length;
  18198. lines = PK_MALLOC(sizeof(LineRecord) * (max_lineno + 1));
  18199. memset(lines, 0, sizeof(LineRecord) * (max_lineno + 1));
  18200. c11_smallmap_p2i__set(&self->records, loc.src, (py_i64)lines);
  18201. PK_INCREF(loc.src);
  18202. }
  18203. return &lines[loc.lineno];
  18204. }
  18205. void LineProfiler__begin(LineProfiler* self) {
  18206. assert(!self->enabled);
  18207. self->enabled = true;
  18208. }
  18209. static void LineProfiler__increment_now(LineProfiler* self, clock_t now, LineRecord* curr_line) {
  18210. FrameRecord* top_frame_record = &c11_vector__back(FrameRecord, &self->frame_records);
  18211. if(!top_frame_record->is_lambda) {
  18212. LineRecord* prev_line = top_frame_record->prev_line;
  18213. clock_t delta = now - top_frame_record->prev_time;
  18214. top_frame_record->prev_time = now;
  18215. prev_line->hits++;
  18216. prev_line->time += delta;
  18217. // printf(" ==> increment_now: delta: %ld, hits: %lld\n", delta, prev_line->hits);
  18218. }
  18219. top_frame_record->prev_line = curr_line;
  18220. }
  18221. void LineProfiler__tracefunc_internal(LineProfiler* self,
  18222. py_Frame* frame,
  18223. enum py_TraceEvent event) {
  18224. assert(self->enabled);
  18225. clock_t now = clock();
  18226. // SourceLocation curr_loc = Frame__source_location(frame);
  18227. // printf("==> frame: %p:%d, event: %d, now: %ld\n", frame, curr_loc.lineno, event, now);
  18228. SourceLocation curr_loc = Frame__source_location(frame);
  18229. LineRecord* curr_line = LineProfiler__get_record(self, curr_loc);
  18230. if(event == TRACE_EVENT_LINE) {
  18231. LineProfiler__increment_now(self, now, curr_line);
  18232. } else {
  18233. if(event == TRACE_EVENT_PUSH) {
  18234. FrameRecord f_record = {.frame = frame,
  18235. .prev_time = now,
  18236. .prev_line = curr_line,
  18237. .is_lambda = false};
  18238. if(!frame->is_locals_special && py_istype(frame->p0, tp_function)) {
  18239. Function* fn = py_touserdata(frame->p0);
  18240. c11_string* fn_name = fn->decl->code.name;
  18241. f_record.is_lambda = fn_name->size > 0 && fn_name->data[0] == '<';
  18242. }
  18243. c11_vector__push(FrameRecord, &self->frame_records, f_record);
  18244. } else if(event == TRACE_EVENT_POP) {
  18245. LineProfiler__increment_now(self, now, NULL);
  18246. assert(self->frame_records.length > 0);
  18247. c11_vector__pop(&self->frame_records);
  18248. }
  18249. }
  18250. }
  18251. void LineProfiler__end(LineProfiler* self) {
  18252. assert(self->enabled);
  18253. if(self->frame_records.length > 0) LineProfiler__increment_now(self, clock(), NULL);
  18254. self->enabled = false;
  18255. }
  18256. void LineProfiler__reset(LineProfiler* self) {
  18257. LineProfiler__dtor(self);
  18258. LineProfiler__ctor(self);
  18259. }
  18260. c11_string* LineProfiler__get_report(LineProfiler* self) {
  18261. c11_sbuf sbuf;
  18262. c11_sbuf__ctor(&sbuf);
  18263. c11_sbuf__write_char(&sbuf, '{');
  18264. c11_sbuf__write_cstr(&sbuf, "\"CLOCKS_PER_SEC\": ");
  18265. c11_sbuf__write_i64(&sbuf, CLOCKS_PER_SEC);
  18266. c11_sbuf__write_cstr(&sbuf, ", \"records\": ");
  18267. c11_sbuf__write_char(&sbuf, '{');
  18268. for(int i = 0; i < self->records.length; i++) {
  18269. c11_smallmap_p2i_KV kv = c11__getitem(c11_smallmap_p2i_KV, &self->records, i);
  18270. SourceData_ src = (SourceData_)kv.key;
  18271. int line_record_length = src->line_starts.length + 1;
  18272. c11_sv src_name = c11_string__sv(src->filename);
  18273. c11_sbuf__write_quoted(&sbuf, src_name, '"');
  18274. c11_sbuf__write_cstr(&sbuf, ": [");
  18275. LineRecord* lines = (LineRecord*)kv.value;
  18276. bool is_first = true;
  18277. for(int j = 1; j < line_record_length; j++) {
  18278. // [<j>, <hits>, <time>]
  18279. if(lines[j].hits == 0 && lines[j].time == 0) continue;
  18280. if(!is_first) c11_sbuf__write_cstr(&sbuf, ", ");
  18281. c11_sbuf__write_char(&sbuf, '[');
  18282. c11_sbuf__write_int(&sbuf, j);
  18283. c11_sbuf__write_cstr(&sbuf, ", ");
  18284. c11_sbuf__write_i64(&sbuf, lines[j].hits);
  18285. c11_sbuf__write_cstr(&sbuf, ", ");
  18286. c11_sbuf__write_i64(&sbuf, lines[j].time);
  18287. c11_sbuf__write_char(&sbuf, ']');
  18288. is_first = false;
  18289. }
  18290. c11_sbuf__write_cstr(&sbuf, "]");
  18291. if(i < self->records.length - 1) c11_sbuf__write_cstr(&sbuf, ", ");
  18292. }
  18293. c11_sbuf__write_char(&sbuf, '}');
  18294. c11_sbuf__write_char(&sbuf, '}');
  18295. return c11_sbuf__submit(&sbuf);
  18296. }
  18297. // src/interpreter\objectpool.c
  18298. #include <assert.h>
  18299. #include <stdbool.h>
  18300. #include <string.h>
  18301. static PoolArena* PoolArena__new(int block_size) {
  18302. assert(kPoolArenaSize % block_size == 0);
  18303. int block_count = kPoolArenaSize / block_size;
  18304. PoolArena* self = PK_MALLOC(sizeof(PoolArena) + sizeof(int) * block_count);
  18305. self->block_size = block_size;
  18306. self->block_count = block_count;
  18307. self->unused_length = block_count;
  18308. for(int i = 0; i < block_count; i++) {
  18309. self->unused[i] = i;
  18310. }
  18311. memset(self->data, 0, kPoolArenaSize);
  18312. return self;
  18313. }
  18314. static void* PoolArena__alloc(PoolArena* self) {
  18315. assert(self->unused_length > 0);
  18316. int index = self->unused[self->unused_length - 1];
  18317. self->unused_length--;
  18318. return self->data + index * self->block_size;
  18319. }
  18320. static int PoolArena__sweep_dealloc(PoolArena* self, int* out_types) {
  18321. int unused_length_before = self->unused_length;
  18322. self->unused_length = 0;
  18323. for(int i = 0; i < self->block_count; i++) {
  18324. PyObject* obj = (PyObject*)(self->data + i * self->block_size);
  18325. if(obj->type == 0) {
  18326. // free slot
  18327. self->unused[self->unused_length] = i;
  18328. self->unused_length++;
  18329. } else {
  18330. if(obj->gc_marked & 0b01) {
  18331. // marked, clear mark
  18332. obj->gc_marked &= 0b10;
  18333. } else {
  18334. // not marked, need to free
  18335. if(out_types) out_types[obj->type]++;
  18336. PyObject__dtor(obj);
  18337. obj->type = 0;
  18338. self->unused[self->unused_length] = i;
  18339. self->unused_length++;
  18340. }
  18341. }
  18342. }
  18343. return self->unused_length - unused_length_before;
  18344. }
  18345. static void Pool__ctor(Pool* self, int block_size) {
  18346. c11_vector__ctor(&self->arenas, sizeof(PoolArena*));
  18347. self->available_index = 0;
  18348. self->block_size = block_size;
  18349. }
  18350. static void Pool__dtor(Pool* self) {
  18351. for(int i = 0; i < self->arenas.length; i++) {
  18352. PoolArena* arena = c11__getitem(PoolArena*, &self->arenas, i);
  18353. for(int i = 0; i < arena->block_count; i++) {
  18354. PyObject* obj = (PyObject*)(arena->data + i * self->block_size);
  18355. if(obj->type != 0) PyObject__dtor(obj);
  18356. }
  18357. PK_FREE(arena);
  18358. }
  18359. c11_vector__dtor(&self->arenas);
  18360. }
  18361. static void* Pool__alloc(Pool* self) {
  18362. PoolArena* arena;
  18363. if(self->available_index < self->arenas.length) {
  18364. arena = c11__getitem(PoolArena*, &self->arenas, self->available_index);
  18365. } else {
  18366. arena = PoolArena__new(self->block_size);
  18367. c11_vector__push(PoolArena*, &self->arenas, arena);
  18368. self->available_index = self->arenas.length - 1;
  18369. }
  18370. void* ptr = PoolArena__alloc(arena);
  18371. if(arena->unused_length == 0) self->available_index++;
  18372. return ptr;
  18373. }
  18374. static int Pool__sweep_dealloc(Pool* self, int* out_types) {
  18375. PoolArena** p = self->arenas.data;
  18376. int freed = 0;
  18377. for(int i = 0; i < self->arenas.length; i++) {
  18378. freed += PoolArena__sweep_dealloc(p[i], out_types);
  18379. }
  18380. // move arenas with `unused_length == 0` to the front
  18381. int j = 0;
  18382. for(int i = 0; i < self->arenas.length; i++) {
  18383. if(p[i]->unused_length == 0) {
  18384. PoolArena* tmp = p[i];
  18385. p[i] = p[j];
  18386. p[j] = tmp;
  18387. j++;
  18388. }
  18389. }
  18390. // move arenas with `unused_length < block_count` to the front
  18391. int k = j;
  18392. for(int i = j; i < self->arenas.length; i++) {
  18393. if(p[i]->unused_length < p[i]->block_count) {
  18394. PoolArena* tmp = p[i];
  18395. p[i] = p[k];
  18396. p[k] = tmp;
  18397. k++;
  18398. }
  18399. }
  18400. // free excess free arenas
  18401. int free_quota = self->arenas.length / 2;
  18402. int min_length = c11__max(free_quota, j + 1);
  18403. while(self->arenas.length > min_length) {
  18404. PoolArena* back_arena = c11_vector__back(PoolArena*, &self->arenas);
  18405. if(back_arena->unused_length == back_arena->block_count) {
  18406. PK_FREE(back_arena);
  18407. c11_vector__pop(&self->arenas);
  18408. } else {
  18409. break;
  18410. }
  18411. }
  18412. // [[0, 0, 0, 0, 0, 1], 1, 1, 1, 2, 2]
  18413. // ^j=5 ^k
  18414. self->available_index = j;
  18415. return freed;
  18416. }
  18417. void* MultiPool__alloc(MultiPool* self, int size) {
  18418. assert(size > 0);
  18419. int index = (size - 1) >> 5;
  18420. if(index < kMultiPoolCount) {
  18421. Pool* pool = &self->pools[index];
  18422. return Pool__alloc(pool);
  18423. }
  18424. return NULL;
  18425. }
  18426. int MultiPool__sweep_dealloc(MultiPool* self, int* out_types) {
  18427. int freed = 0;
  18428. for(int i = 0; i < kMultiPoolCount; i++) {
  18429. Pool* item = &self->pools[i];
  18430. freed += Pool__sweep_dealloc(item, out_types);
  18431. }
  18432. return freed;
  18433. }
  18434. void MultiPool__ctor(MultiPool* self) {
  18435. for(int i = 0; i < kMultiPoolCount; i++) {
  18436. Pool__ctor(&self->pools[i], 32 * (i + 1));
  18437. }
  18438. }
  18439. void MultiPool__dtor(MultiPool* self) {
  18440. for(int i = 0; i < kMultiPoolCount; i++) {
  18441. Pool__dtor(&self->pools[i]);
  18442. }
  18443. }
  18444. size_t MultiPool__total_allocated_bytes(MultiPool* self) {
  18445. size_t total = 0;
  18446. for(int i = 0; i < kMultiPoolCount; i++) {
  18447. Pool* item = &self->pools[i];
  18448. total += (size_t)item->arenas.length * kPoolArenaSize;
  18449. }
  18450. return total;
  18451. }
  18452. c11_string* MultiPool__summary(MultiPool* self) {
  18453. c11_sbuf sbuf;
  18454. c11_sbuf__ctor(&sbuf);
  18455. int arena_count = 0;
  18456. char buf[256];
  18457. for(int i = 0; i < kMultiPoolCount; i++) {
  18458. Pool* item = &self->pools[i];
  18459. arena_count += item->arenas.length;
  18460. int total_bytes = item->arenas.length * kPoolArenaSize;
  18461. int used_bytes = 0;
  18462. for(int j = 0; j < item->arenas.length; j++) {
  18463. PoolArena* arena = c11__getitem(PoolArena*, &item->arenas, j);
  18464. used_bytes += (arena->block_count - arena->unused_length) * arena->block_size;
  18465. }
  18466. float used_pct = (float)used_bytes / total_bytes * 100;
  18467. if(total_bytes == 0) used_pct = 0.0f;
  18468. snprintf(buf,
  18469. sizeof(buf),
  18470. "Pool %3d: len(arenas)=%d (%d full), size=%d/%d (%.1f%% used)\n",
  18471. item->block_size,
  18472. item->arenas.length,
  18473. item->available_index,
  18474. used_bytes,
  18475. total_bytes,
  18476. used_pct);
  18477. c11_sbuf__write_cstr(&sbuf, buf);
  18478. }
  18479. long long total_size = arena_count * kPoolArenaSize;
  18480. double total_size_mb = (long long)(total_size / 1024) / 1024.0;
  18481. snprintf(buf, sizeof(buf), "Total: %.2f MB\n", total_size_mb);
  18482. c11_sbuf__write_cstr(&sbuf, buf);
  18483. return c11_sbuf__submit(&sbuf);
  18484. }
  18485. // src/interpreter\py_compile.c
  18486. #include <errno.h>
  18487. bool py_compilefile(const char* src_path, const char* dst_path) {
  18488. // read
  18489. FILE* fp = fopen(src_path, "rb");
  18490. if(fp == NULL) {
  18491. const char* msg = strerror(errno);
  18492. return OSError("[Errno %d] %s: '%s'", errno, msg, src_path);
  18493. }
  18494. fseek(fp, 0, SEEK_END);
  18495. long size = ftell(fp);
  18496. fseek(fp, 0, SEEK_SET);
  18497. char* buffer = PK_MALLOC(size + 1);
  18498. size = fread(buffer, 1, size, fp);
  18499. buffer[size] = 0;
  18500. fclose(fp);
  18501. // compile
  18502. bool ok = py_compile(buffer, src_path, EXEC_MODE, false);
  18503. PK_FREE(buffer);
  18504. if(!ok) return false;
  18505. // dump
  18506. py_assign(py_pushtmp(), py_retval());
  18507. int bc_size;
  18508. void* bc_data = CodeObject__dumps(py_touserdata(py_peek(-1)), &bc_size);
  18509. py_pop();
  18510. // write
  18511. fp = fopen(dst_path, "wb");
  18512. if(fp == NULL) {
  18513. PK_FREE(bc_data);
  18514. const char* msg = strerror(errno);
  18515. return OSError("[Errno %d] %s: '%s'", errno, msg, dst_path);
  18516. }
  18517. fwrite(bc_data, 1, bc_size, fp);
  18518. fclose(fp);
  18519. PK_FREE(bc_data);
  18520. return true;
  18521. }
  18522. // src/interpreter\typeinfo.c
  18523. #include <assert.h>
  18524. py_ItemRef pk_tpfindname(py_TypeInfo* ti, py_Name name) {
  18525. assert(ti != NULL);
  18526. do {
  18527. py_Ref res = py_getdict(&ti->self, name);
  18528. if(res) return res;
  18529. ti = ti->base_ti;
  18530. } while(ti);
  18531. return NULL;
  18532. }
  18533. PK_INLINE py_TypeInfo* pk_typeinfo(py_Type type) {
  18534. #ifndef NDEBUG
  18535. int length = pk_current_vm->types.length;
  18536. if(type <= 0 || type >= length) {
  18537. c11__abort("type index %d is out of bounds (0, %d)", type, length);
  18538. }
  18539. #endif
  18540. return c11__getitem(TypePointer, &pk_current_vm->types, type).ti;
  18541. }
  18542. static void py_TypeInfo__common_init(py_Name name,
  18543. py_Type base,
  18544. py_Type index,
  18545. const py_GlobalRef module,
  18546. void (*dtor)(void*),
  18547. bool is_python,
  18548. bool is_final,
  18549. py_TypeInfo* self,
  18550. py_TValue* typeobject) {
  18551. py_TypeInfo* base_ti = base ? pk_typeinfo(base) : NULL;
  18552. if(base_ti && base_ti->is_final) {
  18553. c11__abort("type '%s' is not an acceptable base type", py_name2str(base_ti->name));
  18554. }
  18555. self->name = name;
  18556. self->index = index;
  18557. self->base = base;
  18558. self->base_ti = base_ti;
  18559. py_assign(&self->self, typeobject);
  18560. self->module = module ? module : py_NIL();
  18561. if(!dtor && base) dtor = base_ti->dtor;
  18562. self->is_python = is_python;
  18563. self->is_final = is_final;
  18564. self->getattribute = NULL;
  18565. self->setattribute = NULL;
  18566. self->delattribute = NULL;
  18567. self->getunboundmethod = NULL;
  18568. self->annotations = *py_NIL();
  18569. self->dtor = dtor;
  18570. self->on_end_subclass = NULL;
  18571. }
  18572. py_Type pk_newtype(const char* name,
  18573. py_Type base,
  18574. const py_GlobalRef module,
  18575. void (*dtor)(void*),
  18576. bool is_python,
  18577. bool is_final) {
  18578. py_Type index = pk_current_vm->types.length;
  18579. py_TypeInfo* self = py_newobject(py_retval(), tp_type, -1, sizeof(py_TypeInfo));
  18580. py_TypeInfo__common_init(py_name(name),
  18581. base,
  18582. index,
  18583. module,
  18584. dtor,
  18585. is_python,
  18586. is_final,
  18587. self,
  18588. py_retval());
  18589. TypePointer* pointer = c11_vector__emplace(&pk_current_vm->types);
  18590. pointer->ti = self;
  18591. pointer->dtor = self->dtor;
  18592. return index;
  18593. }
  18594. py_Type pk_newtypewithmode(py_Name name,
  18595. py_Type base,
  18596. const py_GlobalRef module,
  18597. void (*dtor)(void*),
  18598. bool is_python,
  18599. bool is_final,
  18600. enum py_CompileMode mode) {
  18601. if(mode == RELOAD_MODE && module != NULL) {
  18602. py_ItemRef old_class = py_getdict(module, name);
  18603. if(old_class != NULL && py_istype(old_class, tp_type)) {
  18604. #ifndef NDEBUG
  18605. const char* name_cstr = py_name2str(name);
  18606. (void)name_cstr; // avoid unused warning
  18607. #endif
  18608. py_cleardict(old_class);
  18609. py_TypeInfo* self = py_touserdata(old_class);
  18610. py_Type index = self->index;
  18611. py_TypeInfo__common_init(name,
  18612. base,
  18613. index,
  18614. module,
  18615. dtor,
  18616. is_python,
  18617. is_final,
  18618. self,
  18619. &self->self);
  18620. TypePointer* pointer = c11__at(TypePointer, &pk_current_vm->types, index);
  18621. pointer->ti = self;
  18622. pointer->dtor = self->dtor;
  18623. return index;
  18624. }
  18625. }
  18626. return pk_newtype(py_name2str(name), base, module, dtor, is_python, is_final);
  18627. }
  18628. // src/interpreter\vm.c
  18629. #include <stdbool.h>
  18630. #include <assert.h>
  18631. static char* pk_default_importfile(const char* path, int* data_size) {
  18632. #if PK_ENABLE_OS
  18633. FILE* f = fopen(path, "rb");
  18634. if(f == NULL) return NULL;
  18635. fseek(f, 0, SEEK_END);
  18636. long size = ftell(f);
  18637. fseek(f, 0, SEEK_SET);
  18638. char* buffer = PK_MALLOC(size + 1);
  18639. size = fread(buffer, 1, size, f);
  18640. buffer[size] = 0;
  18641. fclose(f);
  18642. if(data_size) *data_size = (int)size;
  18643. return buffer;
  18644. #else
  18645. return NULL;
  18646. #endif
  18647. }
  18648. static void pk_default_print(const char* data) { printf("%s", data); }
  18649. static void pk_default_flush() { fflush(stdout); }
  18650. static int pk_default_getchr() { return getchar(); }
  18651. void py_profiler_begin() {
  18652. LineProfiler* lp = &pk_current_vm->line_profiler;
  18653. TraceInfo* trace_info = &pk_current_vm->trace_info;
  18654. if(trace_info->func == NULL) py_sys_settrace(LineProfiler_tracefunc, true);
  18655. c11__rtassert(trace_info->func == LineProfiler_tracefunc);
  18656. LineProfiler__begin(lp);
  18657. }
  18658. void py_profiler_end() {
  18659. LineProfiler* lp = &pk_current_vm->line_profiler;
  18660. LineProfiler__end(lp);
  18661. }
  18662. void py_profiler_reset() {
  18663. LineProfiler* lp = &pk_current_vm->line_profiler;
  18664. LineProfiler__reset(lp);
  18665. }
  18666. char* py_profiler_report() {
  18667. LineProfiler* lp = &pk_current_vm->line_profiler;
  18668. if(lp->enabled) LineProfiler__end(lp);
  18669. c11_string* s = LineProfiler__get_report(lp);
  18670. char* s_dup = c11_strdup(s->data);
  18671. c11_string__delete(s);
  18672. return s_dup;
  18673. }
  18674. void LineProfiler_tracefunc(py_Frame* frame, enum py_TraceEvent event) {
  18675. LineProfiler* lp = &pk_current_vm->line_profiler;
  18676. if(lp->enabled) LineProfiler__tracefunc_internal(lp, frame, event);
  18677. }
  18678. static int BinTree__cmp_cstr(void* lhs, void* rhs) {
  18679. const char* l = (const char*)lhs;
  18680. const char* r = (const char*)rhs;
  18681. return strcmp(l, r);
  18682. }
  18683. void VM__ctor(VM* self) {
  18684. self->top_frame = NULL;
  18685. const static BinTreeConfig modules_config = {
  18686. .f_cmp = BinTree__cmp_cstr,
  18687. .need_free_key = false,
  18688. };
  18689. BinTree__ctor(&self->modules, "", py_NIL(), &modules_config);
  18690. c11_vector__ctor(&self->types, sizeof(TypePointer));
  18691. self->builtins = NULL;
  18692. self->main = NULL;
  18693. self->callbacks.importfile = pk_default_importfile;
  18694. self->callbacks.lazyimport = NULL;
  18695. self->callbacks.print = pk_default_print;
  18696. self->callbacks.flush = pk_default_flush;
  18697. self->callbacks.getchr = pk_default_getchr;
  18698. self->last_retval = *py_NIL();
  18699. self->unhandled_exc = *py_NIL();
  18700. self->recursion_depth = 0;
  18701. self->max_recursion_depth = 1000;
  18702. memset(self->reg, 0, sizeof(self->reg));
  18703. self->ctx = NULL;
  18704. self->curr_class = NULL;
  18705. self->curr_function = NULL;
  18706. memset(&self->trace_info, 0, sizeof(TraceInfo));
  18707. memset(&self->watchdog_info, 0, sizeof(WatchdogInfo));
  18708. LineProfiler__ctor(&self->line_profiler);
  18709. FixedMemoryPool__ctor(&self->pool_frame, sizeof(py_Frame), 32);
  18710. ManagedHeap__ctor(&self->heap);
  18711. self->stack.sp = self->stack.begin;
  18712. self->stack.end = self->stack.begin + PK_VM_STACK_SIZE;
  18713. CachedNames__ctor(&self->cached_names);
  18714. /* Init Builtin Types */
  18715. // 0: unused
  18716. TypePointer* placeholder = c11_vector__emplace(&self->types);
  18717. placeholder->ti = NULL;
  18718. placeholder->dtor = NULL;
  18719. #define validate(t, expr) \
  18720. if(t != (expr)) abort()
  18721. validate(tp_object, pk_newtype("object", tp_nil, NULL, NULL, true, false));
  18722. validate(tp_type, pk_newtype("type", tp_object, NULL, NULL, false, true));
  18723. pk_object__register();
  18724. validate(tp_int, pk_newtype("int", tp_object, NULL, NULL, false, true));
  18725. validate(tp_float, pk_newtype("float", tp_object, NULL, NULL, false, true));
  18726. validate(tp_bool, pk_newtype("bool", tp_object, NULL, NULL, false, true));
  18727. pk_number__register();
  18728. validate(tp_str, pk_str__register());
  18729. validate(tp_str_iterator, pk_str_iterator__register());
  18730. validate(tp_list, pk_list__register());
  18731. validate(tp_tuple, pk_tuple__register());
  18732. validate(tp_list_iterator, pk_list_iterator__register());
  18733. validate(tp_tuple_iterator, pk_tuple_iterator__register());
  18734. validate(tp_slice, pk_slice__register());
  18735. validate(tp_range, pk_range__register());
  18736. validate(tp_range_iterator, pk_range_iterator__register());
  18737. validate(tp_module, pk_module__register());
  18738. validate(tp_function, pk_function__register());
  18739. validate(tp_nativefunc, pk_nativefunc__register());
  18740. validate(tp_boundmethod, pk_boundmethod__register());
  18741. validate(tp_super, pk_super__register());
  18742. validate(tp_BaseException, pk_BaseException__register());
  18743. validate(tp_Exception, pk_Exception__register());
  18744. validate(tp_bytes, pk_bytes__register());
  18745. validate(tp_bytes_iterator, pk_bytes_iterator__register());
  18746. validate(tp_namedict, pk_namedict__register());
  18747. validate(tp_locals, pk_newtype("locals", tp_object, NULL, NULL, false, true));
  18748. validate(tp_code, pk_code__register());
  18749. validate(tp_dict, pk_dict__register());
  18750. validate(tp_dict_iterator, pk_dict_items__register());
  18751. validate(tp_property, pk_property__register());
  18752. validate(tp_star_wrapper, pk_newtype("star_wrapper", tp_object, NULL, NULL, false, true));
  18753. validate(tp_staticmethod, pk_staticmethod__register());
  18754. validate(tp_classmethod, pk_classmethod__register());
  18755. validate(tp_NoneType, pk_newtype("NoneType", tp_object, NULL, NULL, false, true));
  18756. validate(tp_NotImplementedType,
  18757. pk_newtype("NotImplementedType", tp_object, NULL, NULL, false, true));
  18758. validate(tp_ellipsis, pk_newtype("ellipsis", tp_object, NULL, NULL, false, true));
  18759. validate(tp_generator, pk_generator__register());
  18760. self->builtins = pk_builtins__register();
  18761. // inject some builtin exceptions
  18762. #define INJECT_BUILTIN_EXC(name, TBase) \
  18763. do { \
  18764. py_Type type = pk_newtype(#name, TBase, self->builtins, NULL, false, true); \
  18765. py_setdict(self->builtins, py_name(#name), py_tpobject(type)); \
  18766. validate(tp_##name, type); \
  18767. } while(0)
  18768. INJECT_BUILTIN_EXC(SystemExit, tp_BaseException);
  18769. INJECT_BUILTIN_EXC(KeyboardInterrupt, tp_BaseException);
  18770. validate(tp_StopIteration, pk_StopIteration__register());
  18771. py_setdict(self->builtins, py_name("StopIteration"), py_tpobject(tp_StopIteration));
  18772. INJECT_BUILTIN_EXC(SyntaxError, tp_Exception);
  18773. INJECT_BUILTIN_EXC(RecursionError, tp_Exception);
  18774. INJECT_BUILTIN_EXC(OSError, tp_Exception);
  18775. INJECT_BUILTIN_EXC(PermissionError, tp_Exception);
  18776. INJECT_BUILTIN_EXC(NotImplementedError, tp_Exception);
  18777. INJECT_BUILTIN_EXC(TypeError, tp_Exception);
  18778. INJECT_BUILTIN_EXC(IndexError, tp_Exception);
  18779. INJECT_BUILTIN_EXC(ValueError, tp_Exception);
  18780. INJECT_BUILTIN_EXC(RuntimeError, tp_Exception);
  18781. INJECT_BUILTIN_EXC(TimeoutError, tp_Exception);
  18782. INJECT_BUILTIN_EXC(ZeroDivisionError, tp_Exception);
  18783. INJECT_BUILTIN_EXC(NameError, tp_Exception);
  18784. INJECT_BUILTIN_EXC(UnboundLocalError, tp_Exception);
  18785. INJECT_BUILTIN_EXC(AttributeError, tp_Exception);
  18786. INJECT_BUILTIN_EXC(ImportError, tp_Exception);
  18787. INJECT_BUILTIN_EXC(AssertionError, tp_Exception);
  18788. INJECT_BUILTIN_EXC(KeyError, tp_Exception);
  18789. #undef INJECT_BUILTIN_EXC
  18790. #undef validate
  18791. /* Setup Public Builtin Types */
  18792. py_Type public_types[] = {
  18793. tp_object,
  18794. tp_type,
  18795. tp_int,
  18796. tp_float,
  18797. tp_bool,
  18798. tp_str,
  18799. tp_list,
  18800. tp_tuple,
  18801. tp_slice,
  18802. tp_range,
  18803. tp_bytes,
  18804. tp_dict,
  18805. tp_property,
  18806. tp_staticmethod,
  18807. tp_classmethod,
  18808. tp_super,
  18809. tp_BaseException,
  18810. tp_Exception,
  18811. };
  18812. for(int i = 0; i < c11__count_array(public_types); i++) {
  18813. py_TypeInfo* ti = pk_typeinfo(public_types[i]);
  18814. py_setdict(self->builtins, ti->name, &ti->self);
  18815. }
  18816. py_newnotimplemented(py_emplacedict(self->builtins, py_name("NotImplemented")));
  18817. pk__add_module_stdc();
  18818. pk__add_module_vmath();
  18819. pk__add_module_array2d();
  18820. // pk__add_module_colorcvt();
  18821. // add modules
  18822. pk__add_module_os();
  18823. pk__add_module_sys();
  18824. pk__add_module_io();
  18825. pk__add_module_math();
  18826. pk__add_module_dis();
  18827. pk__add_module_random();
  18828. pk__add_module_json();
  18829. pk__add_module_gc();
  18830. pk__add_module_time();
  18831. pk__add_module_easing();
  18832. pk__add_module_traceback();
  18833. pk__add_module_enum();
  18834. pk__add_module_inspect();
  18835. pk__add_module_pickle();
  18836. pk__add_module_base64();
  18837. pk__add_module_importlib();
  18838. pk__add_module_unicodedata();
  18839. pk__add_module_conio();
  18840. pk__add_module_lz4(); // optional
  18841. pk__add_module_cute_png(); // optional
  18842. pk__add_module_msgpack(); // optional
  18843. py__add_module_periphery(); // optional
  18844. pk__add_module_pkpy();
  18845. pk__add_module_picoterm();
  18846. // add python builtins
  18847. do {
  18848. bool ok;
  18849. ok = py_exec(kPythonLibs_builtins, "<builtins>", EXEC_MODE, self->builtins);
  18850. if(!ok) goto __ABORT;
  18851. break;
  18852. __ABORT:
  18853. py_printexc();
  18854. c11__abort("failed to load python builtins!");
  18855. } while(0);
  18856. self->main = py_newmodule("__main__");
  18857. if(py_appcallbacks()->on_vm_ctor) {
  18858. int index = VM__index(self);
  18859. py_appcallbacks()->on_vm_ctor(index);
  18860. }
  18861. }
  18862. void VM__dtor(VM* self) {
  18863. if(py_appcallbacks()->on_vm_dtor) {
  18864. int index = VM__index(self);
  18865. py_appcallbacks()->on_vm_dtor(index);
  18866. }
  18867. // reset traceinfo
  18868. py_sys_settrace(NULL, true);
  18869. LineProfiler__dtor(&self->line_profiler);
  18870. // destroy all objects
  18871. ManagedHeap__dtor(&self->heap);
  18872. // clear frames
  18873. while(self->top_frame) {
  18874. VM__pop_frame(self);
  18875. }
  18876. BinTree__dtor(&self->modules);
  18877. FixedMemoryPool__dtor(&self->pool_frame);
  18878. CachedNames__dtor(&self->cached_names);
  18879. c11_vector__dtor(&self->types);
  18880. }
  18881. void VM__push_frame(VM* self, py_Frame* frame) {
  18882. frame->f_back = self->top_frame;
  18883. self->top_frame = frame;
  18884. self->recursion_depth++;
  18885. if(self->trace_info.func) self->trace_info.func(frame, TRACE_EVENT_PUSH);
  18886. }
  18887. void VM__pop_frame(VM* self) {
  18888. assert(self->top_frame);
  18889. py_Frame* frame = self->top_frame;
  18890. if(self->trace_info.func) self->trace_info.func(frame, TRACE_EVENT_POP);
  18891. // reset stack pointer
  18892. self->stack.sp = frame->p0;
  18893. // pop frame and delete
  18894. self->top_frame = frame->f_back;
  18895. Frame__delete(frame);
  18896. self->recursion_depth--;
  18897. }
  18898. static void _clip_int(int* value, int min, int max) {
  18899. if(*value < min) *value = min;
  18900. if(*value > max) *value = max;
  18901. }
  18902. bool pk__parse_int_slice(py_Ref slice,
  18903. int length,
  18904. int* restrict start,
  18905. int* restrict stop,
  18906. int* restrict step) {
  18907. if(py_isint(slice)) {
  18908. int index = py_toint(slice);
  18909. bool ok = pk__normalize_index(&index, length);
  18910. if(!ok) return false;
  18911. *start = index;
  18912. *stop = index + 1;
  18913. *step = 1;
  18914. return true;
  18915. }
  18916. if(!py_istype(slice, tp_slice)) c11__abort("pk__parse_int_slice(): not a slice object");
  18917. py_Ref s_start = py_getslot(slice, 0);
  18918. py_Ref s_stop = py_getslot(slice, 1);
  18919. py_Ref s_step = py_getslot(slice, 2);
  18920. if(py_isnone(s_step))
  18921. *step = 1;
  18922. else {
  18923. if(!py_checkint(s_step)) return false;
  18924. *step = py_toint(s_step);
  18925. }
  18926. if(*step == 0) return ValueError("slice step cannot be zero");
  18927. if(*step > 0) {
  18928. if(py_isnone(s_start))
  18929. *start = 0;
  18930. else {
  18931. if(!py_checkint(s_start)) return false;
  18932. *start = py_toint(s_start);
  18933. if(*start < 0) *start += length;
  18934. _clip_int(start, 0, length);
  18935. }
  18936. if(py_isnone(s_stop))
  18937. *stop = length;
  18938. else {
  18939. if(!py_checkint(s_stop)) return false;
  18940. *stop = py_toint(s_stop);
  18941. if(*stop < 0) *stop += length;
  18942. _clip_int(stop, 0, length);
  18943. }
  18944. } else {
  18945. if(py_isnone(s_start))
  18946. *start = length - 1;
  18947. else {
  18948. if(!py_checkint(s_start)) return false;
  18949. *start = py_toint(s_start);
  18950. if(*start < 0) *start += length;
  18951. _clip_int(start, -1, length - 1);
  18952. }
  18953. if(py_isnone(s_stop))
  18954. *stop = -1;
  18955. else {
  18956. if(!py_checkint(s_stop)) return false;
  18957. *stop = py_toint(s_stop);
  18958. if(*stop < 0) *stop += length;
  18959. _clip_int(stop, -1, length - 1);
  18960. }
  18961. }
  18962. return true;
  18963. }
  18964. bool pk__normalize_index(int* index, int length) {
  18965. if(*index < 0) *index += length;
  18966. if(*index < 0 || *index >= length) return IndexError("%d not in [0, %d)", *index, length);
  18967. return true;
  18968. }
  18969. static bool
  18970. prepare_py_call(py_TValue* buffer, py_Ref argv, py_Ref p1, int kwargc, const FuncDecl* decl) {
  18971. const CodeObject* co = &decl->code;
  18972. int decl_argc = decl->args.length;
  18973. if(p1 - argv < decl_argc) {
  18974. return TypeError("%s() takes %d positional arguments but %d were given",
  18975. co->name->data,
  18976. decl_argc,
  18977. (int)(p1 - argv));
  18978. }
  18979. py_TValue* t = argv;
  18980. // prepare args
  18981. memset(buffer, 0, co->nlocals * sizeof(py_TValue));
  18982. c11__foreach(int, &decl->args, index) buffer[*index] = *t++;
  18983. // prepare kwdefaults
  18984. c11__foreach(FuncDeclKwArg, &decl->kwargs, kv) buffer[kv->index] = kv->value;
  18985. // handle *args
  18986. if(decl->starred_arg != -1) {
  18987. int exceed_argc = p1 - t;
  18988. py_Ref vargs = &buffer[decl->starred_arg];
  18989. py_Ref data = py_newtuple(vargs, exceed_argc);
  18990. for(int j = 0; j < exceed_argc; j++) {
  18991. data[j] = *t++;
  18992. }
  18993. } else {
  18994. // kwdefaults override
  18995. // def f(a, b, c=None)
  18996. // f(1, 2, 3) -> c=3
  18997. c11__foreach(FuncDeclKwArg, &decl->kwargs, kv) {
  18998. if(t >= p1) break;
  18999. buffer[kv->index] = *t++;
  19000. }
  19001. // not able to consume all args
  19002. if(t < p1) return TypeError("too many arguments (%s)", co->name->data);
  19003. }
  19004. if(decl->starred_kwarg != -1) py_newdict(&buffer[decl->starred_kwarg]);
  19005. for(int j = 0; j < kwargc; j++) {
  19006. py_Name key = (py_Name)py_toint(&p1[2 * j]);
  19007. int index = c11_smallmap_n2d__get(&decl->kw_to_index, key, -1);
  19008. // if key is an explicit key, set as local variable
  19009. if(index >= 0) {
  19010. buffer[index] = p1[2 * j + 1];
  19011. } else {
  19012. // otherwise, set as **kwargs if possible
  19013. if(decl->starred_kwarg == -1) {
  19014. return TypeError("'%n' is an invalid keyword argument for %s()",
  19015. key,
  19016. co->name->data);
  19017. } else {
  19018. // add to **kwargs
  19019. bool ok =
  19020. py_dict_setitem(&buffer[decl->starred_kwarg], py_name2ref(key), &p1[2 * j + 1]);
  19021. if(!ok) return false;
  19022. }
  19023. }
  19024. }
  19025. return true;
  19026. }
  19027. FrameResult VM__vectorcall(VM* self, uint16_t argc, uint16_t kwargc, bool opcall) {
  19028. #ifndef NDEBUG
  19029. pk_print_stack(self, self->top_frame, (Bytecode){0});
  19030. if(py_checkexc()) {
  19031. const char* name = py_tpname(self->unhandled_exc.type);
  19032. c11__abort("unhandled exception `%s` was set!", name);
  19033. }
  19034. #endif
  19035. py_StackRef p1 = self->stack.sp - kwargc * 2;
  19036. py_StackRef p0 = p1 - argc - 2;
  19037. // [callable, <self>, args..., kwargs...]
  19038. // ^p0 ^p1 ^_sp
  19039. // handle boundmethod, do a patch
  19040. if(p0->type == tp_boundmethod) {
  19041. assert(py_isnil(p0 + 1)); // self must be NULL
  19042. py_TValue* slots = PyObject__slots(p0->_obj);
  19043. p0[0] = slots[1]; // callable
  19044. p0[1] = slots[0]; // self
  19045. // [unbound, self, args..., kwargs...]
  19046. }
  19047. py_StackRef argv = p0 + 1 + (int)py_isnil(p0 + 1);
  19048. self->curr_function = p0; // set current function for inspection
  19049. if(p0->type == tp_function) {
  19050. Function* fn = py_touserdata(p0);
  19051. const CodeObject* co = &fn->decl->code;
  19052. switch(fn->decl->type) {
  19053. case FuncType_NORMAL: {
  19054. bool ok = prepare_py_call(self->vectorcall_buffer, argv, p1, kwargc, fn->decl);
  19055. if(!ok) return RES_ERROR;
  19056. // copy buffer back to stack
  19057. self->stack.sp = argv + co->nlocals;
  19058. memcpy(argv, self->vectorcall_buffer, co->nlocals * sizeof(py_TValue));
  19059. // submit the call
  19060. if(!fn->cfunc) {
  19061. // python function
  19062. VM__push_frame(self, Frame__new(co, p0, fn->module, &fn->globals, argv, false));
  19063. return opcall ? RES_CALL : VM__run_top_frame(self);
  19064. } else {
  19065. // decl-based binding
  19066. bool ok = py_callcfunc(fn->cfunc, co->nlocals, argv);
  19067. self->stack.sp = p0;
  19068. return ok ? RES_RETURN : RES_ERROR;
  19069. }
  19070. }
  19071. case FuncType_SIMPLE:
  19072. if(p1 - argv != fn->decl->args.length) {
  19073. const char* fmt = "%s() takes %d positional arguments but %d were given";
  19074. TypeError(fmt, co->name->data, fn->decl->args.length, (int)(p1 - argv));
  19075. return RES_ERROR;
  19076. }
  19077. if(kwargc) {
  19078. TypeError("%s() takes no keyword arguments", co->name->data);
  19079. return RES_ERROR;
  19080. }
  19081. // [callable, <self>, args..., local_vars...]
  19082. // ^p0 ^p1 ^_sp
  19083. self->stack.sp = argv + co->nlocals;
  19084. // initialize local variables to py_NIL
  19085. memset(p1, 0, (char*)self->stack.sp - (char*)p1);
  19086. // submit the call
  19087. if(!fn->cfunc) {
  19088. // python function
  19089. VM__push_frame(self, Frame__new(co, p0, fn->module, &fn->globals, argv, false));
  19090. return opcall ? RES_CALL : VM__run_top_frame(self);
  19091. } else {
  19092. // decl-based binding
  19093. bool ok = py_callcfunc(fn->cfunc, co->nlocals, argv);
  19094. self->stack.sp = p0;
  19095. return ok ? RES_RETURN : RES_ERROR;
  19096. }
  19097. case FuncType_GENERATOR: {
  19098. bool ok = prepare_py_call(self->vectorcall_buffer, argv, p1, kwargc, fn->decl);
  19099. if(!ok) return RES_ERROR;
  19100. // copy buffer back to stack
  19101. self->stack.sp = argv + co->nlocals;
  19102. memcpy(argv, self->vectorcall_buffer, co->nlocals * sizeof(py_TValue));
  19103. py_Frame* frame = Frame__new(co, p0, fn->module, &fn->globals, argv, false);
  19104. pk_newgenerator(py_retval(), frame, p0, self->stack.sp);
  19105. self->stack.sp = p0; // reset the stack
  19106. return RES_RETURN;
  19107. }
  19108. default: c11__unreachable();
  19109. };
  19110. c11__unreachable();
  19111. /*****************_py_call*****************/
  19112. }
  19113. if(p0->type == tp_nativefunc) {
  19114. if(kwargc && p0->_cfunc != pk__object_new) {
  19115. TypeError("nativefunc does not accept keyword arguments");
  19116. return RES_ERROR;
  19117. }
  19118. bool ok = py_callcfunc(p0->_cfunc, p1 - argv, argv);
  19119. self->stack.sp = p0;
  19120. return ok ? RES_RETURN : RES_ERROR;
  19121. }
  19122. if(p0->type == tp_type) {
  19123. py_Type p0_type = py_totype(p0);
  19124. // [cls, NULL, args..., kwargs...]
  19125. py_Ref new_f = py_tpfindmagic(p0_type, __new__);
  19126. assert(new_f && py_isnil(p0 + 1));
  19127. bool is_default_new = new_f->type == tp_nativefunc && new_f->_cfunc == pk__object_new;
  19128. // prepare a copy of args and kwargs
  19129. int span = self->stack.sp - argv;
  19130. *self->stack.sp++ = *new_f; // push __new__
  19131. *self->stack.sp++ = *p0; // push cls
  19132. memcpy(self->stack.sp, argv, span * sizeof(py_TValue));
  19133. self->stack.sp += span;
  19134. // [new_f, cls, args..., kwargs...]
  19135. if(VM__vectorcall(self, argc, kwargc, false) == RES_ERROR) return RES_ERROR;
  19136. // by recursively using vectorcall, args and kwargs are consumed
  19137. // try __init__
  19138. // NOTE: previously we use `get_unbound_method` but here we just use `tpfindmagic`
  19139. // >> [cls, NULL, args..., kwargs...]
  19140. // >> py_retval() is the new instance
  19141. py_Ref init_f = py_tpfindmagic(p0_type, __init__);
  19142. if(init_f) {
  19143. if(py_isinstance(py_retval(), p0_type)) {
  19144. // do an inplace patch
  19145. *p0 = *init_f; // __init__
  19146. p0[1] = self->last_retval; // self
  19147. // [__init__, self, args..., kwargs...]
  19148. if(VM__vectorcall(self, argc, kwargc, false) == RES_ERROR) return RES_ERROR;
  19149. *py_retval() = p0[1]; // restore the new instance
  19150. }
  19151. } else {
  19152. if(is_default_new) {
  19153. if(argc != 0 || kwargc != 0) {
  19154. TypeError("%t() takes no arguments", py_totype(p0));
  19155. return RES_ERROR;
  19156. }
  19157. }
  19158. }
  19159. // reset the stack
  19160. self->stack.sp = p0;
  19161. return RES_RETURN;
  19162. }
  19163. // handle `__call__` overload
  19164. if(pk_loadmethod(p0, __call__)) {
  19165. // [__call__, self, args..., kwargs...]
  19166. return VM__vectorcall(self, argc, kwargc, opcall);
  19167. }
  19168. TypeError("'%t' object is not callable", p0->type);
  19169. return RES_ERROR;
  19170. }
  19171. /****************************************/
  19172. void FuncDecl__gc_mark(const FuncDecl* self, c11_vector* p_stack) {
  19173. CodeObject__gc_mark(&self->code, p_stack);
  19174. for(int j = 0; j < self->kwargs.length; j++) {
  19175. FuncDeclKwArg* kw = c11__at(FuncDeclKwArg, &self->kwargs, j);
  19176. pk__mark_value(&kw->value);
  19177. }
  19178. }
  19179. void CodeObject__gc_mark(const CodeObject* self, c11_vector* p_stack) {
  19180. for(int i = 0; i < self->consts.length; i++) {
  19181. py_TValue* p = c11__at(py_TValue, &self->consts, i);
  19182. pk__mark_value(p);
  19183. }
  19184. for(int i = 0; i < self->func_decls.length; i++) {
  19185. FuncDecl_ decl = c11__getitem(FuncDecl_, &self->func_decls, i);
  19186. FuncDecl__gc_mark(decl, p_stack);
  19187. }
  19188. }
  19189. static void pk__mark_value_func(py_Ref val, void* ctx) {
  19190. c11_vector* p_stack = ctx;
  19191. pk__mark_value(val);
  19192. }
  19193. void ManagedHeap__mark(ManagedHeap* self) {
  19194. VM* vm = pk_current_vm;
  19195. c11_vector* p_stack = &self->gc_roots;
  19196. assert(p_stack->length == 0);
  19197. // mark value stack
  19198. for(py_TValue* p = vm->stack.begin; p < vm->stack.sp; p++) {
  19199. // assert(p->type != tp_nil);
  19200. pk__mark_value(p);
  19201. }
  19202. // mark modules
  19203. BinTree__apply_mark(&vm->modules, p_stack);
  19204. // mark cached names
  19205. for(int i = 0; i < vm->cached_names.entries.length; i++) {
  19206. CachedNames_KV* kv = c11_chunkedvector__at(&vm->cached_names.entries, i);
  19207. pk__mark_value(&kv->val);
  19208. }
  19209. // mark types
  19210. int types_length = vm->types.length;
  19211. // 0-th type is placeholder
  19212. for(py_Type i = 1; i < types_length; i++) {
  19213. py_TypeInfo* ti = c11__getitem(TypePointer, &vm->types, i).ti;
  19214. pk__mark_value(&ti->self);
  19215. pk__mark_value(&ti->annotations);
  19216. }
  19217. // mark frame
  19218. for(py_Frame* frame = vm->top_frame; frame; frame = frame->f_back) {
  19219. Frame__gc_mark(frame, p_stack);
  19220. }
  19221. // mark vm's registers
  19222. pk__mark_value(&vm->last_retval);
  19223. pk__mark_value(&vm->unhandled_exc);
  19224. for(int i = 0; i < c11__count_array(vm->reg); i++) {
  19225. pk__mark_value(&vm->reg[i]);
  19226. }
  19227. // mark gc debug callback
  19228. pk__mark_value(&vm->heap.debug_callback);
  19229. // mark user func
  19230. if(vm->callbacks.gc_mark) vm->callbacks.gc_mark(pk__mark_value_func, p_stack);
  19231. /*****************************/
  19232. while(p_stack->length > 0) {
  19233. PyObject* obj = c11_vector__back(PyObject*, p_stack);
  19234. c11_vector__pop(p_stack);
  19235. assert(obj->gc_marked & 0b01);
  19236. if(obj->slots > 0) {
  19237. py_TValue* p = PyObject__slots(obj);
  19238. for(int i = 0; i < obj->slots; i++)
  19239. pk__mark_value(p + i);
  19240. } else if(obj->slots == -1) {
  19241. NameDict* dict = PyObject__dict(obj);
  19242. for(int i = 0; i < dict->capacity; i++) {
  19243. NameDict_KV* kv = &dict->items[i];
  19244. if(kv->key == NULL) continue;
  19245. pk__mark_value(&kv->value);
  19246. }
  19247. }
  19248. if(obj->type > tp_object) {
  19249. // NOTE: `defaultdict` -> `dict` -> `object`
  19250. // NOTE: native types must extend from `object`.
  19251. py_TypeInfo* ti = pk_typeinfo(obj->type);
  19252. while(ti->base != tp_object) {
  19253. ti = ti->base_ti;
  19254. }
  19255. void* ud = PyObject__userdata(obj);
  19256. switch(ti->index) {
  19257. case tp_list: {
  19258. List* self = ud;
  19259. for(int i = 0; i < self->length; i++) {
  19260. py_TValue* val = c11__at(py_TValue, self, i);
  19261. pk__mark_value(val);
  19262. }
  19263. break;
  19264. }
  19265. case tp_dict: {
  19266. Dict* self = ud;
  19267. for(int i = 0; i < self->entries.length; i++) {
  19268. DictEntry* entry = c11__at(DictEntry, &self->entries, i);
  19269. if(py_isnil(&entry->key)) continue;
  19270. pk__mark_value(&entry->key);
  19271. pk__mark_value(&entry->val);
  19272. }
  19273. break;
  19274. }
  19275. case tp_generator: {
  19276. Generator* self = ud;
  19277. if(self->frame) Frame__gc_mark(self->frame, p_stack);
  19278. break;
  19279. }
  19280. case tp_function: {
  19281. function__gc_mark(ud, p_stack);
  19282. break;
  19283. }
  19284. case tp_BaseException: {
  19285. BaseException* self = ud;
  19286. pk__mark_value(&self->args);
  19287. pk__mark_value(&self->inner_exc);
  19288. c11__foreach(BaseExceptionFrame, &self->stacktrace, frame) {
  19289. pk__mark_value(&frame->locals);
  19290. pk__mark_value(&frame->globals);
  19291. }
  19292. break;
  19293. }
  19294. case tp_code: {
  19295. CodeObject* self = ud;
  19296. CodeObject__gc_mark(self, p_stack);
  19297. break;
  19298. }
  19299. case tp_chunked_array2d: {
  19300. c11_chunked_array2d__mark(ud, p_stack);
  19301. break;
  19302. }
  19303. }
  19304. }
  19305. }
  19306. }
  19307. // src/interpreter\vmx.c
  19308. #include <assert.h>
  19309. void pk_print_stack(VM* self, py_Frame* frame, Bytecode byte) {
  19310. return;
  19311. if(frame == NULL || !self->main || py_isnil(self->main)) return;
  19312. py_TValue* sp = self->stack.sp;
  19313. c11_sbuf buf;
  19314. c11_sbuf__ctor(&buf);
  19315. for(py_Ref p = self->stack.begin; p != sp; p++) {
  19316. switch(p->type) {
  19317. case tp_nil: c11_sbuf__write_cstr(&buf, "nil"); break;
  19318. case tp_int: c11_sbuf__write_i64(&buf, p->_i64); break;
  19319. case tp_float: c11_sbuf__write_f64(&buf, p->_f64, -1); break;
  19320. case tp_bool: c11_sbuf__write_cstr(&buf, p->_bool ? "True" : "False"); break;
  19321. case tp_NoneType: c11_sbuf__write_cstr(&buf, "None"); break;
  19322. case tp_list: {
  19323. pk_sprintf(&buf, "list(%d)", py_list_len(p));
  19324. break;
  19325. }
  19326. case tp_tuple: {
  19327. pk_sprintf(&buf, "tuple(%d)", py_tuple_len(p));
  19328. break;
  19329. }
  19330. case tp_function: {
  19331. Function* ud = py_touserdata(p);
  19332. c11_sbuf__write_cstr(&buf, ud->decl->code.name->data);
  19333. c11_sbuf__write_cstr(&buf, "()");
  19334. break;
  19335. }
  19336. case tp_type: {
  19337. pk_sprintf(&buf, "<class '%t'>", py_totype(p));
  19338. break;
  19339. }
  19340. case tp_str: {
  19341. pk_sprintf(&buf, "%q", py_tosv(p));
  19342. break;
  19343. }
  19344. case tp_module: {
  19345. py_ModuleInfo* mi = py_touserdata(p);
  19346. pk_sprintf(&buf, "<module '%v'>", c11_string__sv(mi->path));
  19347. break;
  19348. }
  19349. default: {
  19350. pk_sprintf(&buf, "(%t)", p->type);
  19351. break;
  19352. }
  19353. }
  19354. if(p != &sp[-1]) c11_sbuf__write_cstr(&buf, ", ");
  19355. }
  19356. c11_string* stack_str = c11_sbuf__submit(&buf);
  19357. printf("%s:%-3d: %-25s %-6d [%s]\n",
  19358. frame->co->src->filename->data,
  19359. Frame__lineno(frame),
  19360. pk_opname(byte.op),
  19361. byte.arg,
  19362. stack_str->data);
  19363. c11_string__delete(stack_str);
  19364. }
  19365. bool pk_wrapper__self(int argc, py_Ref argv) {
  19366. PY_CHECK_ARGC(1);
  19367. py_assign(py_retval(), argv);
  19368. return true;
  19369. }
  19370. int py_replinput(char* buf, int max_size) {
  19371. buf[0] = '\0'; // reset first char because we check '@' at the beginning
  19372. int size = 0;
  19373. bool multiline = false;
  19374. printf(">>> ");
  19375. while(true) {
  19376. int c = pk_current_vm->callbacks.getchr();
  19377. if(c == EOF) return -1;
  19378. if(c == '\n') {
  19379. char last = '\0';
  19380. if(size > 0) last = buf[size - 1];
  19381. if(multiline) {
  19382. if(last == '\n') {
  19383. break; // 2 consecutive newlines to end multiline input
  19384. } else {
  19385. printf("... ");
  19386. }
  19387. } else {
  19388. if(last == ':' || last == '(' || last == '[' || last == '{' || buf[0] == '@') {
  19389. printf("... ");
  19390. multiline = true;
  19391. } else {
  19392. break;
  19393. }
  19394. }
  19395. }
  19396. if(size == max_size - 1) {
  19397. buf[size] = '\0';
  19398. return size;
  19399. }
  19400. buf[size++] = c;
  19401. }
  19402. buf[size] = '\0';
  19403. return size;
  19404. }
  19405. py_Ref py_name2ref(py_Name name) {
  19406. assert(name != NULL);
  19407. CachedNames* d = &pk_current_vm->cached_names;
  19408. py_Ref res = CachedNames__try_get(d, name);
  19409. if(res != NULL) return res;
  19410. // not found, create a new one
  19411. py_newstrv(py_tmpr0(), py_name2sv(name));
  19412. CachedNames__set(d, name, py_tmpr0());
  19413. return CachedNames__try_get(d, name);
  19414. }
  19415. void PyObject__dtor(PyObject* self) {
  19416. py_Dtor dtor = c11__getitem(TypePointer, &pk_current_vm->types, self->type).dtor;
  19417. if(dtor) dtor(PyObject__userdata(self));
  19418. if(self->slots == -1) {
  19419. NameDict* dict = PyObject__dict(self);
  19420. NameDict__dtor(dict);
  19421. }
  19422. }
  19423. ManagedHeapSwpetInfo* ManagedHeapSwpetInfo__new() {
  19424. ManagedHeapSwpetInfo* self = py_malloc(sizeof(ManagedHeapSwpetInfo));
  19425. memset(self, 0, sizeof(ManagedHeapSwpetInfo));
  19426. self->types_length = pk_current_vm->types.length;
  19427. self->small_types = py_malloc(sizeof(int) * self->types_length);
  19428. self->large_types = py_malloc(sizeof(int) * self->types_length);
  19429. for(int i = 0; i < self->types_length; i++) {
  19430. self->small_types[i] = 0;
  19431. self->large_types[i] = 0;
  19432. }
  19433. self->start_ns = time_ns();
  19434. return self;
  19435. }
  19436. void ManagedHeapSwpetInfo__delete(ManagedHeapSwpetInfo* self) {
  19437. py_free(self->small_types);
  19438. py_free(self->large_types);
  19439. memset(self, 0, sizeof(ManagedHeapSwpetInfo));
  19440. py_free(self);
  19441. }
  19442. // src/modules\array2d.c
  19443. #include <limits.h>
  19444. static bool c11_array2d_like_is_valid(c11_array2d_like* self, int col, int row) {
  19445. return col >= 0 && col < self->n_cols && row >= 0 && row < self->n_rows;
  19446. }
  19447. static py_Ref c11_array2d__get(c11_array2d* self, int col, int row) {
  19448. return self->data + row * self->header.n_cols + col;
  19449. }
  19450. static bool c11_array2d__set(c11_array2d* self, int col, int row, py_Ref value) {
  19451. self->data[row * self->header.n_cols + col] = *value;
  19452. return true;
  19453. }
  19454. c11_array2d* c11_newarray2d(py_OutRef out, int n_cols, int n_rows) {
  19455. int numel = n_cols * n_rows;
  19456. c11_array2d* ud = py_newobject(out, tp_array2d, numel, sizeof(c11_array2d));
  19457. ud->header.n_cols = n_cols;
  19458. ud->header.n_rows = n_rows;
  19459. ud->header.numel = numel;
  19460. ud->header.f_get = (py_Ref (*)(c11_array2d_like*, int, int))c11_array2d__get;
  19461. ud->header.f_set = (bool (*)(c11_array2d_like*, int, int, py_Ref))c11_array2d__set;
  19462. ud->data = py_getslot(out, 0);
  19463. return ud;
  19464. }
  19465. /* array2d_like bindings */
  19466. static bool array2d_like_n_cols(int argc, py_Ref argv) {
  19467. PY_CHECK_ARGC(1);
  19468. c11_array2d_like* self = py_touserdata(argv);
  19469. py_newint(py_retval(), self->n_cols);
  19470. return true;
  19471. }
  19472. static bool array2d_like_n_rows(int argc, py_Ref argv) {
  19473. PY_CHECK_ARGC(1);
  19474. c11_array2d_like* self = py_touserdata(argv);
  19475. py_newint(py_retval(), self->n_rows);
  19476. return true;
  19477. }
  19478. static bool array2d_like_shape(int argc, py_Ref argv) {
  19479. PY_CHECK_ARGC(1);
  19480. c11_array2d_like* self = py_touserdata(argv);
  19481. c11_vec2i shape;
  19482. shape.x = self->n_cols;
  19483. shape.y = self->n_rows;
  19484. py_newvec2i(py_retval(), shape);
  19485. return true;
  19486. }
  19487. static bool array2d_like_numel(int argc, py_Ref argv) {
  19488. PY_CHECK_ARGC(1);
  19489. c11_array2d_like* self = py_touserdata(argv);
  19490. py_newint(py_retval(), self->numel);
  19491. return true;
  19492. }
  19493. static bool array2d_like_is_valid(int argc, py_Ref argv) {
  19494. c11_array2d_like* self = py_touserdata(argv);
  19495. int col, row;
  19496. if(argc == 2) {
  19497. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  19498. c11_vec2i pos = py_tovec2i(py_arg(1));
  19499. col = pos.x;
  19500. row = pos.y;
  19501. } else if(argc == 3) {
  19502. PY_CHECK_ARG_TYPE(1, tp_int);
  19503. PY_CHECK_ARG_TYPE(2, tp_int);
  19504. col = py_toint(py_arg(1));
  19505. row = py_toint(py_arg(2));
  19506. } else {
  19507. return TypeError("is_valid() expected 2 or 3 arguments");
  19508. }
  19509. py_newbool(py_retval(), c11_array2d_like_is_valid(self, col, row));
  19510. return true;
  19511. }
  19512. static bool array2d_like_get(int argc, py_Ref argv) {
  19513. PY_CHECK_ARG_TYPE(1, tp_int);
  19514. PY_CHECK_ARG_TYPE(2, tp_int);
  19515. py_Ref default_;
  19516. c11_array2d_like* self = py_touserdata(argv);
  19517. if(argc == 3) {
  19518. default_ = py_None();
  19519. } else if(argc == 4) {
  19520. default_ = py_arg(3);
  19521. } else {
  19522. return TypeError("get() expected 2 or 3 arguments");
  19523. }
  19524. int col = py_toint(py_arg(1));
  19525. int row = py_toint(py_arg(2));
  19526. if(c11_array2d_like_is_valid(self, col, row)) {
  19527. py_assign(py_retval(), self->f_get(self, col, row));
  19528. } else {
  19529. py_assign(py_retval(), default_);
  19530. }
  19531. return true;
  19532. }
  19533. static bool array2d_like_index(int argc, py_Ref argv) {
  19534. PY_CHECK_ARGC(2);
  19535. c11_array2d_like* self = py_touserdata(argv);
  19536. py_Ref value = py_arg(1);
  19537. for(int j = 0; j < self->n_rows; j++) {
  19538. for(int i = 0; i < self->n_cols; i++) {
  19539. py_Ref item = self->f_get(self, i, j);
  19540. int code = py_equal(item, value);
  19541. if(code == -1) return false;
  19542. if(code == 1) {
  19543. py_newvec2i(py_retval(),
  19544. (c11_vec2i){
  19545. {i, j}
  19546. });
  19547. return true;
  19548. }
  19549. }
  19550. }
  19551. return ValueError("value not found");
  19552. }
  19553. static bool array2d_like_render(int argc, py_Ref argv) {
  19554. PY_CHECK_ARGC(1);
  19555. c11_sbuf buf;
  19556. c11_sbuf__ctor(&buf);
  19557. c11_array2d_like* self = py_touserdata(argv);
  19558. for(int j = 0; j < self->n_rows; j++) {
  19559. for(int i = 0; i < self->n_cols; i++) {
  19560. py_Ref item = self->f_get(self, i, j);
  19561. if(!py_str(item)) {
  19562. c11_sbuf__dtor(&buf);
  19563. return false;
  19564. }
  19565. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  19566. }
  19567. if(j < self->n_rows - 1) c11_sbuf__write_char(&buf, '\n');
  19568. }
  19569. c11_sbuf__py_submit(&buf, py_retval());
  19570. return true;
  19571. }
  19572. void c11_color32_premult(c11_color32* color);
  19573. static bool array2d_like_render_with_color(int argc, py_Ref argv) {
  19574. PY_CHECK_ARGC(3);
  19575. c11_sbuf buf;
  19576. c11_sbuf__ctor(&buf);
  19577. c11_array2d_like* self = py_touserdata(argv);
  19578. if(!py_checkinstance(py_arg(1), tp_array2d_like)) return false;
  19579. if(!py_checkinstance(py_arg(2), tp_array2d_like)) return false;
  19580. c11_array2d_like* fg_colors = py_touserdata(py_arg(1));
  19581. c11_array2d_like* bg_colors = py_touserdata(py_arg(2));
  19582. c11_color32 curr_fg, curr_bg;
  19583. curr_fg.u32 = 0;
  19584. curr_bg.u32 = 0;
  19585. for(int j = 0; j < self->n_rows; j++) {
  19586. for(int i = 0; i < self->n_cols; i++) {
  19587. py_Ref item = self->f_get(self, i, j);
  19588. if(!py_str(item)) {
  19589. c11_sbuf__dtor(&buf);
  19590. return false;
  19591. }
  19592. py_Ref fg_item = fg_colors->f_get(fg_colors, i, j);
  19593. py_Ref bg_item = bg_colors->f_get(bg_colors, i, j);
  19594. c11_color32 new_fg, new_bg;
  19595. if(py_isnone(fg_item)) {
  19596. new_fg.u32 = 0;
  19597. } else {
  19598. if(!py_checktype(fg_item, tp_color32)) {
  19599. c11_sbuf__dtor(&buf);
  19600. return false;
  19601. }
  19602. new_fg = py_tocolor32(fg_item);
  19603. }
  19604. if(py_isnone(bg_item)) {
  19605. new_bg.u32 = 0;
  19606. } else {
  19607. if(!py_checktype(bg_item, tp_color32)) {
  19608. c11_sbuf__dtor(&buf);
  19609. return false;
  19610. }
  19611. new_bg = py_tocolor32(bg_item);
  19612. }
  19613. if(curr_fg.u32 != new_fg.u32 || curr_bg.u32 != new_bg.u32) {
  19614. if(curr_fg.u32 != 0 || curr_bg.u32 != 0) c11_sbuf__write_cstr(&buf, "\x1b[0m");
  19615. curr_fg = new_fg;
  19616. curr_bg = new_bg;
  19617. if(curr_fg.u32 != 0) {
  19618. c11_color32_premult(&curr_fg);
  19619. pk_sprintf(&buf, "\x1b[38;2;%d;%d;%dm", curr_fg.r, curr_fg.g, curr_fg.b);
  19620. }
  19621. if(curr_bg.u32 != 0) {
  19622. c11_color32_premult(&curr_bg);
  19623. pk_sprintf(&buf, "\x1b[48;2;%d;%d;%dm", curr_bg.r, curr_bg.g, curr_bg.b);
  19624. }
  19625. }
  19626. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  19627. }
  19628. // newline
  19629. if(j < self->n_rows - 1) {
  19630. curr_fg.u32 = 0;
  19631. curr_bg.u32 = 0;
  19632. c11_sbuf__write_cstr(&buf, "\x1b[0m\n");
  19633. } else {
  19634. c11_sbuf__write_cstr(&buf, "\x1b[0m");
  19635. }
  19636. }
  19637. c11_sbuf__py_submit(&buf, py_retval());
  19638. return true;
  19639. }
  19640. static bool array2d_like_all(int argc, py_Ref argv) {
  19641. PY_CHECK_ARGC(1);
  19642. c11_array2d_like* self = py_touserdata(argv);
  19643. for(int j = 0; j < self->n_rows; j++) {
  19644. for(int i = 0; i < self->n_cols; i++) {
  19645. py_Ref item = self->f_get(self, i, j);
  19646. if(!py_checkbool(item)) return false;
  19647. if(!py_tobool(item)) {
  19648. py_newbool(py_retval(), false);
  19649. return true;
  19650. }
  19651. }
  19652. }
  19653. py_newbool(py_retval(), true);
  19654. return true;
  19655. }
  19656. static bool array2d_like_any(int argc, py_Ref argv) {
  19657. PY_CHECK_ARGC(1);
  19658. c11_array2d_like* self = py_touserdata(argv);
  19659. for(int j = 0; j < self->n_rows; j++) {
  19660. for(int i = 0; i < self->n_cols; i++) {
  19661. py_Ref item = self->f_get(self, i, j);
  19662. if(!py_checkbool(item)) return false;
  19663. if(py_tobool(item)) {
  19664. py_newbool(py_retval(), true);
  19665. return true;
  19666. }
  19667. }
  19668. }
  19669. py_newbool(py_retval(), false);
  19670. return true;
  19671. }
  19672. static bool array2d_like_map(int argc, py_Ref argv) {
  19673. // def map(self, f: Callable[[T], Any]) -> 'array2d': ...
  19674. PY_CHECK_ARGC(2);
  19675. c11_array2d_like* self = py_touserdata(argv);
  19676. py_Ref f = py_arg(1);
  19677. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  19678. for(int j = 0; j < self->n_rows; j++) {
  19679. for(int i = 0; i < self->n_cols; i++) {
  19680. py_Ref item = self->f_get(self, i, j);
  19681. if(!py_call(f, 1, item)) return false;
  19682. res->data[j * self->n_cols + i] = *py_retval();
  19683. }
  19684. }
  19685. py_assign(py_retval(), py_peek(-1));
  19686. py_pop();
  19687. return true;
  19688. }
  19689. static bool array2d_like_apply(int argc, py_Ref argv) {
  19690. // def apply_(self, f: Callable[[T], T]) -> None: ...
  19691. PY_CHECK_ARGC(2);
  19692. c11_array2d_like* self = py_touserdata(argv);
  19693. py_Ref f = py_arg(1);
  19694. for(int j = 0; j < self->n_rows; j++) {
  19695. for(int i = 0; i < self->n_cols; i++) {
  19696. py_Ref item = self->f_get(self, i, j);
  19697. if(!py_call(f, 1, item)) return false;
  19698. bool ok = self->f_set(self, i, j, py_retval());
  19699. if(!ok) return false;
  19700. }
  19701. }
  19702. py_newnone(py_retval());
  19703. return true;
  19704. }
  19705. static bool _check_same_shape(int colA, int rowA, int colB, int rowB) {
  19706. if(colA != colB || rowA != rowB) {
  19707. const char* fmt = "expected the same shape: (%d, %d) != (%d, %d)";
  19708. return ValueError(fmt, colA, rowA, colB, rowB);
  19709. }
  19710. return true;
  19711. }
  19712. static bool _array2d_like_check_same_shape(c11_array2d_like* self, c11_array2d_like* other) {
  19713. return _check_same_shape(self->n_cols, self->n_rows, other->n_cols, other->n_rows);
  19714. }
  19715. static bool _array2d_like_broadcasted_zip_with(int argc, py_Ref argv, py_Name op, py_Name rop) {
  19716. PY_CHECK_ARGC(2);
  19717. c11_array2d_like* self = py_touserdata(argv);
  19718. c11_array2d_like* other;
  19719. if(py_isinstance(py_arg(1), tp_array2d_like)) {
  19720. other = py_touserdata(py_arg(1));
  19721. if(!_array2d_like_check_same_shape(self, other)) return false;
  19722. } else {
  19723. other = NULL;
  19724. }
  19725. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  19726. for(int j = 0; j < self->n_rows; j++) {
  19727. for(int i = 0; i < self->n_cols; i++) {
  19728. py_Ref lhs = self->f_get(self, i, j);
  19729. py_Ref rhs;
  19730. if(other != NULL) {
  19731. rhs = other->f_get(other, i, j);
  19732. } else {
  19733. rhs = py_arg(1); // broadcast
  19734. }
  19735. if(!py_binaryop(lhs, rhs, op, rop)) return false;
  19736. c11_array2d__set(res, i, j, py_retval());
  19737. }
  19738. }
  19739. py_assign(py_retval(), py_peek(-1));
  19740. py_pop();
  19741. return true;
  19742. }
  19743. static bool array2d_like_zip_with(int argc, py_Ref argv) {
  19744. PY_CHECK_ARGC(3);
  19745. c11_array2d_like* self = py_touserdata(argv);
  19746. if(!py_checkinstance(py_arg(1), tp_array2d_like)) return false;
  19747. c11_array2d_like* other = py_touserdata(py_arg(1));
  19748. py_Ref f = py_arg(2);
  19749. if(!_array2d_like_check_same_shape(self, other)) return false;
  19750. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  19751. for(int j = 0; j < self->n_rows; j++) {
  19752. for(int i = 0; i < self->n_cols; i++) {
  19753. py_push(f);
  19754. py_pushnil();
  19755. py_push(self->f_get(self, i, j));
  19756. py_push(other->f_get(other, i, j));
  19757. if(!py_vectorcall(2, 0)) return false;
  19758. c11_array2d__set(res, i, j, py_retval());
  19759. }
  19760. }
  19761. py_assign(py_retval(), py_peek(-1));
  19762. py_pop();
  19763. return true;
  19764. }
  19765. #define DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(name, op, rop) \
  19766. static bool array2d_like##name(int argc, py_Ref argv) { \
  19767. return _array2d_like_broadcasted_zip_with(argc, argv, op, rop); \
  19768. }
  19769. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__le__, __le__, __ge__)
  19770. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__lt__, __lt__, __gt__)
  19771. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__ge__, __ge__, __le__)
  19772. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__gt__, __gt__, __lt__)
  19773. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__eq__, __eq__, __eq__)
  19774. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__ne__, __ne__, __ne__)
  19775. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__add__, __add__, __radd__)
  19776. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__sub__, __sub__, __rsub__)
  19777. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__mul__, __mul__, __rmul__)
  19778. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__truediv__, __truediv__, __rtruediv__)
  19779. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__floordiv__, __floordiv__, __rfloordiv__)
  19780. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__mod__, __mod__, __rmod__)
  19781. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__pow__, __pow__, __rpow__)
  19782. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__and__, __and__, 0)
  19783. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__or__, __or__, 0)
  19784. DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH(__xor__, __xor__, 0)
  19785. #undef DEF_ARRAY2D_LIKE__MAGIC_ZIP_WITH
  19786. static bool array2d_like__invert__(int argc, py_Ref argv) {
  19787. PY_CHECK_ARGC(1);
  19788. c11_array2d_like* self = py_touserdata(argv);
  19789. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  19790. for(int j = 0; j < self->n_rows; j++) {
  19791. for(int i = 0; i < self->n_cols; i++) {
  19792. py_Ref item = self->f_get(self, i, j);
  19793. if(!pk_callmagic(__invert__, 1, item)) return false;
  19794. c11_array2d__set(res, i, j, py_retval());
  19795. }
  19796. }
  19797. py_assign(py_retval(), py_peek(-1));
  19798. py_pop();
  19799. return true;
  19800. }
  19801. static bool array2d_like_copy(int argc, py_Ref argv) {
  19802. // def copy(self) -> 'array2d': ...
  19803. PY_CHECK_ARGC(1);
  19804. c11_array2d_like* self = py_touserdata(argv);
  19805. c11_array2d* res = c11_newarray2d(py_retval(), self->n_cols, self->n_rows);
  19806. for(int j = 0; j < self->n_rows; j++) {
  19807. for(int i = 0; i < self->n_cols; i++) {
  19808. py_Ref item = self->f_get(self, i, j);
  19809. res->data[j * self->n_cols + i] = *item;
  19810. }
  19811. }
  19812. return true;
  19813. }
  19814. static bool array2d_like_tolist(int argc, py_Ref argv) {
  19815. PY_CHECK_ARGC(1);
  19816. c11_array2d_like* self = py_touserdata(argv);
  19817. py_newlistn(py_retval(), self->n_rows);
  19818. for(int j = 0; j < self->n_rows; j++) {
  19819. py_Ref row_j = py_list_getitem(py_retval(), j);
  19820. py_newlistn(row_j, self->n_cols);
  19821. for(int i = 0; i < self->n_cols; i++) {
  19822. py_Ref item = self->f_get(self, i, j);
  19823. py_list_setitem(row_j, i, item);
  19824. }
  19825. }
  19826. return true;
  19827. }
  19828. static bool array2d_like__iter__(int argc, py_Ref argv) {
  19829. PY_CHECK_ARGC(1);
  19830. c11_array2d_like* self = py_touserdata(argv);
  19831. c11_array2d_like_iterator* ud =
  19832. py_newobject(py_retval(), tp_array2d_like_iterator, 1, sizeof(c11_array2d_like_iterator));
  19833. py_setslot(py_retval(), 0, argv); // keep the array alive
  19834. ud->array = self;
  19835. ud->j = 0;
  19836. ud->i = 0;
  19837. return true;
  19838. }
  19839. static bool array2d_like__repr__(int argc, py_Ref argv) {
  19840. PY_CHECK_ARGC(1);
  19841. c11_array2d_like* self = py_touserdata(argv);
  19842. char buf[256];
  19843. snprintf(buf,
  19844. sizeof(buf),
  19845. "%s(%d, %d)",
  19846. py_tpname(py_typeof(argv)),
  19847. self->n_cols,
  19848. self->n_rows);
  19849. py_newstr(py_retval(), buf);
  19850. return true;
  19851. }
  19852. #define HANDLE_SLICE() \
  19853. int start_col, stop_col, step_col; \
  19854. int start_row, stop_row, step_row; \
  19855. if(!pk__parse_int_slice(x, self->n_cols, &start_col, &stop_col, &step_col)) return false; \
  19856. if(!pk__parse_int_slice(y, self->n_rows, &start_row, &stop_row, &step_row)) return false; \
  19857. if(step_col != 1 || step_row != 1) return ValueError("slice step must be 1"); \
  19858. int slice_width = stop_col - start_col; \
  19859. int slice_height = stop_row - start_row;
  19860. static bool _array2d_like_IndexError(c11_array2d_like* self, int col, int row) {
  19861. return IndexError("(%d, %d) is not a valid index of array2d_like(%d, %d)",
  19862. col,
  19863. row,
  19864. self->n_cols,
  19865. self->n_rows);
  19866. }
  19867. static py_Ref c11_array2d_view__get(c11_array2d_view* self, int col, int row) {
  19868. return self->f_get(self->ctx, col + self->origin.x, row + self->origin.y);
  19869. }
  19870. static bool c11_array2d_view__set(c11_array2d_view* self, int col, int row, py_Ref value) {
  19871. return self->f_set(self->ctx, col + self->origin.x, row + self->origin.y, value);
  19872. }
  19873. static c11_array2d_view* _array2d_view__new(py_OutRef out,
  19874. py_Ref keepalive,
  19875. int start_col,
  19876. int start_row,
  19877. int width,
  19878. int height) {
  19879. c11_array2d_view* res = py_newobject(out, tp_array2d_view, 1, sizeof(c11_array2d_view));
  19880. if(width <= 0 || height <= 0) {
  19881. ValueError("width and height must be positive");
  19882. return NULL;
  19883. }
  19884. res->header.n_cols = width;
  19885. res->header.n_rows = height;
  19886. res->header.numel = width * height;
  19887. res->header.f_get = (py_Ref (*)(c11_array2d_like*, int, int))c11_array2d_view__get;
  19888. res->header.f_set = (bool (*)(c11_array2d_like*, int, int, py_Ref))c11_array2d_view__set;
  19889. res->origin.x = start_col;
  19890. res->origin.y = start_row;
  19891. py_setslot(out, 0, keepalive);
  19892. return res;
  19893. }
  19894. static bool _array2d_view(py_OutRef out,
  19895. py_Ref keepalive,
  19896. c11_array2d_like* array,
  19897. int start_col,
  19898. int start_row,
  19899. int width,
  19900. int height) {
  19901. c11_array2d_view* res = _array2d_view__new(out, keepalive, start_col, start_row, width, height);
  19902. if(res == NULL) return false;
  19903. res->ctx = array;
  19904. res->f_get = (py_Ref (*)(void*, int, int))array->f_get;
  19905. res->f_set = (bool (*)(void*, int, int, py_Ref))array->f_set;
  19906. return true;
  19907. }
  19908. static bool _chunked_array2d_view(py_OutRef out,
  19909. py_Ref keepalive,
  19910. c11_chunked_array2d* array,
  19911. int start_col,
  19912. int start_row,
  19913. int width,
  19914. int height) {
  19915. c11_array2d_view* res = _array2d_view__new(out, keepalive, start_col, start_row, width, height);
  19916. if(res == NULL) return false;
  19917. res->ctx = array;
  19918. res->f_get = (py_Ref (*)(void*, int, int))c11_chunked_array2d__get;
  19919. res->f_set = (bool (*)(void*, int, int, py_Ref))c11_chunked_array2d__set;
  19920. return true;
  19921. }
  19922. static bool array2d_like__getitem__(int argc, py_Ref argv) {
  19923. PY_CHECK_ARGC(2);
  19924. c11_array2d_like* self = py_touserdata(argv);
  19925. if(argv[1].type == tp_vec2i) {
  19926. c11_vec2i pos = py_tovec2i(&argv[1]);
  19927. if(c11_array2d_like_is_valid(self, pos.x, pos.y)) {
  19928. py_assign(py_retval(), self->f_get(self, pos.x, pos.y));
  19929. return true;
  19930. }
  19931. return _array2d_like_IndexError(self, pos.x, pos.y);
  19932. }
  19933. if(py_isinstance(&argv[1], tp_array2d_like)) {
  19934. c11_array2d_like* mask = py_touserdata(&argv[1]);
  19935. if(!_array2d_like_check_same_shape(self, mask)) return false;
  19936. py_newlist(py_retval());
  19937. for(int j = 0; j < self->n_rows; j++) {
  19938. for(int i = 0; i < self->n_cols; i++) {
  19939. py_Ref item = self->f_get(self, i, j);
  19940. py_Ref cond = mask->f_get(mask, i, j);
  19941. if(!py_checkbool(cond)) return false;
  19942. if(py_tobool(cond)) py_list_append(py_retval(), item);
  19943. }
  19944. }
  19945. return true;
  19946. }
  19947. PY_CHECK_ARG_TYPE(1, tp_tuple);
  19948. if(py_tuple_len(&argv[1]) != 2) return TypeError("expected a tuple of 2 elements");
  19949. py_Ref x = py_tuple_getitem(&argv[1], 0);
  19950. py_Ref y = py_tuple_getitem(&argv[1], 1);
  19951. if(py_isint(x) && py_isint(y)) {
  19952. int col = py_toint(x);
  19953. int row = py_toint(y);
  19954. if(c11_array2d_like_is_valid(self, col, row)) {
  19955. py_assign(py_retval(), self->f_get(self, col, row));
  19956. return true;
  19957. }
  19958. return _array2d_like_IndexError(self, col, row);
  19959. }
  19960. bool _1 = py_istype(x, tp_slice) && py_istype(y, tp_slice);
  19961. bool _2 = py_istype(x, tp_int) && py_istype(y, tp_slice);
  19962. bool _3 = py_istype(x, tp_slice) && py_istype(y, tp_int);
  19963. if(_1 || _2 || _3) {
  19964. HANDLE_SLICE();
  19965. return _array2d_view(py_retval(),
  19966. argv,
  19967. self,
  19968. start_col,
  19969. start_row,
  19970. slice_width,
  19971. slice_height);
  19972. }
  19973. return TypeError("expected tuple[int, int] or tuple[slice, slice]");
  19974. }
  19975. static bool array2d_like__setitem__(int argc, py_Ref argv) {
  19976. PY_CHECK_ARGC(3);
  19977. c11_array2d_like* self = py_touserdata(argv);
  19978. py_Ref value = &argv[2];
  19979. if(argv[1].type == tp_vec2i) {
  19980. c11_vec2i pos = py_tovec2i(&argv[1]);
  19981. if(c11_array2d_like_is_valid(self, pos.x, pos.y)) {
  19982. bool ok = self->f_set(self, pos.x, pos.y, value);
  19983. if(!ok) return false;
  19984. py_newnone(py_retval());
  19985. return true;
  19986. }
  19987. return _array2d_like_IndexError(self, pos.x, pos.y);
  19988. }
  19989. if(py_isinstance(&argv[1], tp_array2d_like)) {
  19990. c11_array2d_like* mask = py_touserdata(&argv[1]);
  19991. if(!_array2d_like_check_same_shape(self, mask)) return false;
  19992. for(int j = 0; j < self->n_rows; j++) {
  19993. for(int i = 0; i < self->n_cols; i++) {
  19994. py_Ref cond = mask->f_get(mask, i, j);
  19995. if(!py_checkbool(cond)) return false;
  19996. if(py_tobool(cond)) {
  19997. bool ok = self->f_set(self, i, j, value);
  19998. if(!ok) return false;
  19999. }
  20000. }
  20001. }
  20002. py_newnone(py_retval());
  20003. return true;
  20004. }
  20005. PY_CHECK_ARG_TYPE(1, tp_tuple);
  20006. if(py_tuple_len(py_arg(1)) != 2) return TypeError("expected a tuple of 2 elements");
  20007. py_Ref x = py_tuple_getitem(py_arg(1), 0);
  20008. py_Ref y = py_tuple_getitem(py_arg(1), 1);
  20009. if(py_isint(x) && py_isint(y)) {
  20010. int col = py_toint(x);
  20011. int row = py_toint(y);
  20012. if(c11_array2d_like_is_valid(self, col, row)) {
  20013. bool ok = self->f_set(self, col, row, value);
  20014. if(!ok) return false;
  20015. py_newnone(py_retval());
  20016. return true;
  20017. }
  20018. return _array2d_like_IndexError(self, col, row);
  20019. }
  20020. bool _1 = py_istype(x, tp_slice) && py_istype(y, tp_slice);
  20021. bool _2 = py_istype(x, tp_int) && py_istype(y, tp_slice);
  20022. bool _3 = py_istype(x, tp_slice) && py_istype(y, tp_int);
  20023. if(_1 || _2 || _3) {
  20024. HANDLE_SLICE();
  20025. if(py_isinstance(value, tp_array2d_like)) {
  20026. c11_array2d_like* values = py_touserdata(value);
  20027. if(!_check_same_shape(slice_width, slice_height, values->n_cols, values->n_rows))
  20028. return false;
  20029. for(int j = 0; j < slice_height; j++) {
  20030. for(int i = 0; i < slice_width; i++) {
  20031. py_Ref item = values->f_get(values, i, j);
  20032. bool ok = self->f_set(self, start_col + i, start_row + j, item);
  20033. if(!ok) return false;
  20034. }
  20035. }
  20036. } else {
  20037. for(int j = 0; j < slice_height; j++) {
  20038. for(int i = 0; i < slice_width; i++) {
  20039. bool ok = self->f_set(self, start_col + i, start_row + j, value);
  20040. if(!ok) return false;
  20041. }
  20042. }
  20043. }
  20044. py_newnone(py_retval());
  20045. return true;
  20046. }
  20047. return TypeError("expected tuple[int, int] or tuple[slice, slice]");
  20048. }
  20049. // count(self, value: T) -> int
  20050. static bool array2d_like_count(int argc, py_Ref argv) {
  20051. PY_CHECK_ARGC(2);
  20052. c11_array2d_like* self = py_touserdata(argv);
  20053. int count = 0;
  20054. for(int j = 0; j < self->n_rows; j++) {
  20055. for(int i = 0; i < self->n_cols; i++) {
  20056. int code = py_equal(self->f_get(self, i, j), py_arg(1));
  20057. if(code == -1) return false;
  20058. count += code;
  20059. }
  20060. }
  20061. py_newint(py_retval(), count);
  20062. return true;
  20063. }
  20064. // get_bounding_rect(self, value: T) -> tuple[int, int, int, int]
  20065. static bool array2d_like_get_bounding_rect(int argc, py_Ref argv) {
  20066. PY_CHECK_ARGC(2);
  20067. c11_array2d_like* self = py_touserdata(argv);
  20068. py_Ref value = py_arg(1);
  20069. int left = self->n_cols;
  20070. int top = self->n_rows;
  20071. int right = 0;
  20072. int bottom = 0;
  20073. for(int j = 0; j < self->n_rows; j++) {
  20074. for(int i = 0; i < self->n_cols; i++) {
  20075. py_Ref item = self->f_get(self, i, j);
  20076. int res = py_equal(item, value);
  20077. if(res == -1) return false;
  20078. if(res == 1) {
  20079. left = c11__min(left, i);
  20080. top = c11__min(top, j);
  20081. right = c11__max(right, i);
  20082. bottom = c11__max(bottom, j);
  20083. }
  20084. }
  20085. }
  20086. int width = right - left + 1;
  20087. int height = bottom - top + 1;
  20088. if(width <= 0 || height <= 0) {
  20089. return ValueError("value not found");
  20090. } else {
  20091. py_TValue* data = py_newtuple(py_retval(), 4);
  20092. py_newint(&data[0], left);
  20093. py_newint(&data[1], top);
  20094. py_newint(&data[2], width);
  20095. py_newint(&data[3], height);
  20096. }
  20097. return true;
  20098. }
  20099. // count_neighbors(self, value: T, neighborhood: Neighborhood) -> array2d[int]
  20100. static bool array2d_like_count_neighbors(int argc, py_Ref argv) {
  20101. PY_CHECK_ARGC(3);
  20102. c11_array2d_like* self = py_touserdata(argv);
  20103. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  20104. py_Ref value = py_arg(1);
  20105. const char* neighborhood = py_tostr(py_arg(2));
  20106. const static c11_vec2i Moore[] = {
  20107. {{-1, -1}},
  20108. {{0, -1}},
  20109. {{1, -1}},
  20110. {{-1, 0}},
  20111. {{1, 0}},
  20112. {{-1, 1}},
  20113. {{0, 1}},
  20114. {{1, 1}},
  20115. };
  20116. const static c11_vec2i von_Neumann[] = {
  20117. {{0, -1}},
  20118. {{-1, 0}},
  20119. {{1, 0}},
  20120. {{0, 1}},
  20121. };
  20122. const c11_vec2i* offsets;
  20123. int n_offsets;
  20124. if(strcmp(neighborhood, "Moore") == 0) {
  20125. offsets = Moore;
  20126. n_offsets = c11__count_array(Moore);
  20127. } else if(strcmp(neighborhood, "von Neumann") == 0) {
  20128. offsets = von_Neumann;
  20129. n_offsets = c11__count_array(von_Neumann);
  20130. } else {
  20131. return ValueError("neighborhood must be 'Moore' or 'von Neumann'");
  20132. }
  20133. for(int j = 0; j < self->n_rows; j++) {
  20134. for(int i = 0; i < self->n_cols; i++) {
  20135. py_i64 count = 0;
  20136. for(int k = 0; k < n_offsets; k++) {
  20137. int x = i + offsets[k].x;
  20138. int y = j + offsets[k].y;
  20139. if(x >= 0 && x < self->n_cols && y >= 0 && y < self->n_rows) {
  20140. py_Ref item = self->f_get(self, x, y);
  20141. int code = py_equal(item, value);
  20142. if(code == -1) return false;
  20143. count += code;
  20144. }
  20145. }
  20146. py_newint(c11_array2d__get(res, i, j), count);
  20147. }
  20148. }
  20149. py_assign(py_retval(), py_peek(-1));
  20150. py_pop();
  20151. return true;
  20152. }
  20153. // convolve(self: array2d_like[int], kernel: array2d_like[int], padding: int) -> array2d[int]
  20154. static bool array2d_like_convolve(int argc, py_Ref argv) {
  20155. PY_CHECK_ARGC(3);
  20156. if(!py_checkinstance(&argv[1], tp_array2d_like)) return false;
  20157. PY_CHECK_ARG_TYPE(2, tp_int);
  20158. c11_array2d_like* self = py_touserdata(&argv[0]);
  20159. c11_array2d_like* kernel = py_touserdata(&argv[1]);
  20160. int padding = py_toint(py_arg(2));
  20161. if(kernel->n_cols != kernel->n_rows) return ValueError("kernel must be square");
  20162. int ksize = kernel->n_cols;
  20163. if(ksize % 2 == 0) return ValueError("kernel size must be odd");
  20164. int ksize_half = ksize / 2;
  20165. c11_array2d* res = c11_newarray2d(py_pushtmp(), self->n_cols, self->n_rows);
  20166. for(int j = 0; j < self->n_rows; j++) {
  20167. for(int i = 0; i < self->n_cols; i++) {
  20168. py_i64 sum = 0;
  20169. for(int jj = 0; jj < ksize; jj++) {
  20170. for(int ii = 0; ii < ksize; ii++) {
  20171. int x = i + ii - ksize_half;
  20172. int y = j + jj - ksize_half;
  20173. py_i64 _0, _1;
  20174. if(x < 0 || x >= self->n_cols || y < 0 || y >= self->n_rows) {
  20175. _0 = padding;
  20176. } else {
  20177. py_Ref item = self->f_get(self, x, y);
  20178. if(!py_checkint(item)) return false;
  20179. _0 = py_toint(item);
  20180. }
  20181. py_Ref kitem = kernel->f_get(kernel, ii, jj);
  20182. if(!py_checkint(kitem)) return false;
  20183. _1 = py_toint(kitem);
  20184. sum += _0 * _1;
  20185. }
  20186. }
  20187. py_newint(c11_array2d__get(res, i, j), sum);
  20188. }
  20189. }
  20190. py_assign(py_retval(), py_peek(-1));
  20191. py_pop();
  20192. return true;
  20193. }
  20194. #undef HANDLE_SLICE
  20195. static void register_array2d_like(py_Ref mod) {
  20196. py_Type type = py_newtype("array2d_like", tp_object, mod, NULL);
  20197. assert(type == tp_array2d_like);
  20198. py_bindproperty(type, "n_cols", array2d_like_n_cols, NULL);
  20199. py_bindproperty(type, "n_rows", array2d_like_n_rows, NULL);
  20200. py_bindproperty(type, "width", array2d_like_n_cols, NULL);
  20201. py_bindproperty(type, "height", array2d_like_n_rows, NULL);
  20202. py_bindproperty(type, "shape", array2d_like_shape, NULL);
  20203. py_bindproperty(type, "numel", array2d_like_numel, NULL);
  20204. py_bindmethod(type, "is_valid", array2d_like_is_valid);
  20205. py_bindmethod(type, "get", array2d_like_get);
  20206. py_bindmethod(type, "index", array2d_like_index);
  20207. py_bindmethod(type, "render", array2d_like_render);
  20208. py_bindmethod(type, "render_with_color", array2d_like_render_with_color);
  20209. py_bindmethod(type, "all", array2d_like_all);
  20210. py_bindmethod(type, "any", array2d_like_any);
  20211. py_bindmethod(type, "map", array2d_like_map);
  20212. py_bindmethod(type, "apply", array2d_like_apply);
  20213. py_bindmethod(type, "zip_with", array2d_like_zip_with);
  20214. py_bindmethod(type, "copy", array2d_like_copy);
  20215. py_bindmethod(type, "tolist", array2d_like_tolist);
  20216. py_bindmagic(type, __le__, array2d_like__le__);
  20217. py_bindmagic(type, __lt__, array2d_like__lt__);
  20218. py_bindmagic(type, __ge__, array2d_like__ge__);
  20219. py_bindmagic(type, __gt__, array2d_like__gt__);
  20220. py_bindmagic(type, __eq__, array2d_like__eq__);
  20221. py_bindmagic(type, __ne__, array2d_like__ne__);
  20222. py_bindmagic(type, __add__, array2d_like__add__);
  20223. py_bindmagic(type, __sub__, array2d_like__sub__);
  20224. py_bindmagic(type, __mul__, array2d_like__mul__);
  20225. py_bindmagic(type, __truediv__, array2d_like__truediv__);
  20226. py_bindmagic(type, __floordiv__, array2d_like__floordiv__);
  20227. py_bindmagic(type, __mod__, array2d_like__mod__);
  20228. py_bindmagic(type, __pow__, array2d_like__pow__);
  20229. py_bindmagic(type, __and__, array2d_like__and__);
  20230. py_bindmagic(type, __or__, array2d_like__or__);
  20231. py_bindmagic(type, __xor__, array2d_like__xor__);
  20232. py_bindmagic(type, __invert__, array2d_like__invert__);
  20233. py_bindmagic(type, __iter__, array2d_like__iter__);
  20234. py_bindmagic(type, __repr__, array2d_like__repr__);
  20235. py_bindmagic(type, __getitem__, array2d_like__getitem__);
  20236. py_bindmagic(type, __setitem__, array2d_like__setitem__);
  20237. py_bindmethod(type, "count", array2d_like_count);
  20238. py_bindmethod(type, "get_bounding_rect", array2d_like_get_bounding_rect);
  20239. py_bindmethod(type, "count_neighbors", array2d_like_count_neighbors);
  20240. py_bindmethod(type, "convolve", array2d_like_convolve);
  20241. const char* scc =
  20242. "\ndef get_connected_components(self, value: T, neighborhood: Neighborhood) -> tuple[array2d[int], int]:\n from collections import deque\n from vmath import vec2i\n\n DIRS = [vec2i.LEFT, vec2i.RIGHT, vec2i.UP, vec2i.DOWN]\n assert neighborhood in ['Moore', 'von Neumann']\n\n if neighborhood == 'Moore':\n DIRS.extend([\n vec2i.LEFT+vec2i.UP,\n vec2i.RIGHT+vec2i.UP,\n vec2i.LEFT+vec2i.DOWN,\n vec2i.RIGHT+vec2i.DOWN\n ])\n\n visited = array2d[int](self.width, self.height, default=0)\n queue = deque()\n count = 0\n for y in range(self.height):\n for x in range(self.width):\n if visited[x, y] or self[x, y] != value:\n continue\n count += 1\n queue.append((x, y))\n visited[x, y] = count\n while queue:\n cx, cy = queue.popleft()\n for dx, dy in DIRS:\n nx, ny = cx+dx, cy+dy\n if self.is_valid(nx, ny) and not visited[nx, ny] and self[nx, ny] == value:\n queue.append((nx, ny))\n visited[nx, ny] = count\n return visited, count\n\narray2d_like.get_connected_components = get_connected_components\ndel get_connected_components\n";
  20243. if(!py_exec(scc, "array2d.py", EXEC_MODE, mod)) {
  20244. py_printexc();
  20245. c11__abort("failed to execute array2d.py");
  20246. }
  20247. }
  20248. bool array2d_like_iterator__next__(int argc, py_Ref argv) {
  20249. PY_CHECK_ARGC(1);
  20250. c11_array2d_like_iterator* self = py_touserdata(argv);
  20251. if(self->j >= self->array->n_rows) return StopIteration();
  20252. py_TValue* data = py_newtuple(py_retval(), 2);
  20253. py_newvec2i(&data[0],
  20254. (c11_vec2i){
  20255. {self->i, self->j}
  20256. });
  20257. py_assign(&data[1], self->array->f_get(self->array, self->i, self->j));
  20258. self->i++;
  20259. if(self->i >= self->array->n_cols) {
  20260. self->i = 0;
  20261. self->j++;
  20262. }
  20263. return true;
  20264. }
  20265. static void register_array2d_like_iterator(py_Ref mod) {
  20266. py_Type type = py_newtype("array2d_like_iterator", tp_object, mod, NULL);
  20267. assert(type == tp_array2d_like_iterator);
  20268. py_bindmagic(type, __iter__, pk_wrapper__self);
  20269. py_bindmagic(type, __next__, array2d_like_iterator__next__);
  20270. }
  20271. static bool array2d__new__(int argc, py_Ref argv) {
  20272. // __new__(cls, n_cols: int, n_rows: int, default: Callable[[vec2i], T] = None)
  20273. py_Ref default_ = py_arg(3);
  20274. PY_CHECK_ARG_TYPE(0, tp_type);
  20275. PY_CHECK_ARG_TYPE(1, tp_int);
  20276. PY_CHECK_ARG_TYPE(2, tp_int);
  20277. int n_cols = argv[1]._i64;
  20278. int n_rows = argv[2]._i64;
  20279. if(n_cols <= 0 || n_rows <= 0) return ValueError("array2d() expected positive dimensions");
  20280. c11_array2d* ud = c11_newarray2d(py_pushtmp(), n_cols, n_rows);
  20281. // setup initial values
  20282. if(py_callable(default_)) {
  20283. for(int j = 0; j < n_rows; j++) {
  20284. for(int i = 0; i < n_cols; i++) {
  20285. py_TValue tmp;
  20286. py_newvec2i(&tmp,
  20287. (c11_vec2i){
  20288. {i, j}
  20289. });
  20290. if(!py_call(default_, 1, &tmp)) return false;
  20291. ud->data[j * n_cols + i] = *py_retval();
  20292. }
  20293. }
  20294. } else {
  20295. for(int i = 0; i < ud->header.numel; i++) {
  20296. ud->data[i] = *default_;
  20297. }
  20298. }
  20299. py_assign(py_retval(), py_peek(-1));
  20300. py_pop();
  20301. return true;
  20302. }
  20303. // fromlist(data: list[list[T]]) -> array2d[T]
  20304. static bool array2d_fromlist_STATIC(int argc, py_Ref argv) {
  20305. PY_CHECK_ARGC(1);
  20306. if(!py_checktype(argv, tp_list)) return false;
  20307. int n_rows = py_list_len(argv);
  20308. if(n_rows == 0) return ValueError("fromlist() expected a non-empty list");
  20309. int n_cols = -1;
  20310. for(int j = 0; j < n_rows; j++) {
  20311. py_Ref row_j = py_list_getitem(argv, j);
  20312. if(!py_checktype(row_j, tp_list)) return false;
  20313. int n_cols_j = py_list_len(row_j);
  20314. if(n_cols == -1) {
  20315. if(n_cols_j == 0) return ValueError("fromlist() expected a non-empty list");
  20316. n_cols = n_cols_j;
  20317. } else if(n_cols != n_cols_j) {
  20318. return ValueError("fromlist() expected a list of lists with the same length");
  20319. }
  20320. }
  20321. c11_array2d* res = c11_newarray2d(py_retval(), n_cols, n_rows);
  20322. for(int j = 0; j < n_rows; j++) {
  20323. py_Ref row_j = py_list_getitem(argv, j);
  20324. for(int i = 0; i < n_cols; i++) {
  20325. c11_array2d__set(res, i, j, py_list_getitem(row_j, i));
  20326. }
  20327. }
  20328. return true;
  20329. }
  20330. static void register_array2d(py_Ref mod) {
  20331. py_Type type = py_newtype("array2d", tp_array2d_like, mod, NULL);
  20332. assert(type == tp_array2d);
  20333. py_bind(py_tpobject(type),
  20334. "__new__(cls, n_cols: int, n_rows: int, default=None)",
  20335. array2d__new__);
  20336. py_bindstaticmethod(type, "fromlist", array2d_fromlist_STATIC);
  20337. }
  20338. static bool array2d_view_origin(int argc, py_Ref argv) {
  20339. PY_CHECK_ARGC(1);
  20340. c11_array2d_view* self = py_touserdata(argv);
  20341. py_newvec2i(py_retval(), self->origin);
  20342. return true;
  20343. }
  20344. static void register_array2d_view(py_Ref mod) {
  20345. py_Type type = py_newtype("array2d_view", tp_array2d_like, mod, NULL);
  20346. assert(type == tp_array2d_view);
  20347. py_bindproperty(type, "origin", array2d_view_origin, NULL);
  20348. }
  20349. /* chunked_array2d */
  20350. #define SMALLMAP_T__SOURCE
  20351. #define K c11_vec2i
  20352. #define V py_TValue*
  20353. #define NAME c11_chunked_array2d_chunks
  20354. #define less(a, b) (a._i64 < b._i64)
  20355. #define equal(a, b) (a._i64 == b._i64)
  20356. #if !defined(SMALLMAP_T__HEADER) && !defined(SMALLMAP_T__SOURCE)
  20357. #include "pocketpy/common/vector.h"
  20358. #include "pocketpy/common/utils.h"
  20359. #include "pocketpy/config.h"
  20360. #define SMALLMAP_T__HEADER
  20361. #define SMALLMAP_T__SOURCE
  20362. /* Input */
  20363. #define K int
  20364. #define V float
  20365. #define NAME c11_smallmap_d2f
  20366. #endif
  20367. /* Optional Input */
  20368. #ifndef less
  20369. #define less(a, b) ((a) < (b))
  20370. #endif
  20371. #ifndef equal
  20372. #define equal(a, b) ((a) == (b))
  20373. #endif
  20374. /* Temporary macros */
  20375. #define partial_less(a, b) less((a).key, (b))
  20376. #define CONCAT(A, B) CONCAT_(A, B)
  20377. #define CONCAT_(A, B) A##B
  20378. #define KV CONCAT(NAME, _KV)
  20379. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  20380. #ifdef SMALLMAP_T__HEADER
  20381. /* Declaration */
  20382. typedef struct {
  20383. K key;
  20384. V value;
  20385. } KV;
  20386. typedef c11_vector NAME;
  20387. void METHOD(ctor)(NAME* self);
  20388. void METHOD(dtor)(NAME* self);
  20389. NAME* METHOD(new)();
  20390. void METHOD(delete)(NAME* self);
  20391. void METHOD(set)(NAME* self, K key, V value);
  20392. V* METHOD(try_get)(const NAME* self, K key);
  20393. V METHOD(get)(const NAME* self, K key, V default_value);
  20394. bool METHOD(contains)(const NAME* self, K key);
  20395. bool METHOD(del)(NAME* self, K key);
  20396. void METHOD(clear)(NAME* self);
  20397. #endif
  20398. #ifdef SMALLMAP_T__SOURCE
  20399. /* Implementation */
  20400. void METHOD(ctor)(NAME* self) {
  20401. c11_vector__ctor(self, sizeof(KV));
  20402. c11_vector__reserve(self, 4);
  20403. }
  20404. void METHOD(dtor)(NAME* self) { c11_vector__dtor(self); }
  20405. NAME* METHOD(new)() {
  20406. NAME* self = PK_MALLOC(sizeof(NAME));
  20407. METHOD(ctor)(self);
  20408. return self;
  20409. }
  20410. void METHOD(delete)(NAME* self) {
  20411. METHOD(dtor)(self);
  20412. PK_FREE(self);
  20413. }
  20414. void METHOD(set)(NAME* self, K key, V value) {
  20415. int index;
  20416. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  20417. if(index != self->length) {
  20418. KV* it = c11__at(KV, self, index);
  20419. if(equal(it->key, key)) {
  20420. it->value = value;
  20421. return;
  20422. }
  20423. }
  20424. KV kv = {key, value};
  20425. c11_vector__insert(KV, self, index, kv);
  20426. }
  20427. V* METHOD(try_get)(const NAME* self, K key) {
  20428. int index;
  20429. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  20430. if(index != self->length) {
  20431. KV* it = c11__at(KV, self, index);
  20432. if(equal(it->key, key)) return &it->value;
  20433. }
  20434. return NULL;
  20435. }
  20436. V METHOD(get)(const NAME* self, K key, V default_value) {
  20437. V* p = METHOD(try_get)(self, key);
  20438. return p ? *p : default_value;
  20439. }
  20440. bool METHOD(contains)(const NAME* self, K key) { return METHOD(try_get)(self, key) != NULL; }
  20441. bool METHOD(del)(NAME* self, K key) {
  20442. int index;
  20443. c11__lower_bound(KV, self->data, self->length, key, partial_less, &index);
  20444. if(index != self->length) {
  20445. KV* it = c11__at(KV, self, index);
  20446. if(equal(it->key, key)) {
  20447. c11_vector__erase(KV, self, index);
  20448. return true;
  20449. }
  20450. }
  20451. return false;
  20452. }
  20453. void METHOD(clear)(NAME* self) { c11_vector__clear(self); }
  20454. #endif
  20455. /* Undefine all macros */
  20456. #undef KV
  20457. #undef METHOD
  20458. #undef CONCAT
  20459. #undef CONCAT_
  20460. #undef K
  20461. #undef V
  20462. #undef NAME
  20463. #undef less
  20464. #undef partial_less
  20465. #undef equal
  20466. #undef SMALLMAP_T__SOURCE
  20467. static py_TValue* c11_chunked_array2d__new_chunk(c11_chunked_array2d* self, c11_vec2i pos, py_Ref context) {
  20468. bool exists = c11_chunked_array2d_chunks__contains(&self->chunks, pos);
  20469. if(exists) {
  20470. ValueError("chunk already exists at pos (%d, %d)", pos.x, pos.y);
  20471. return NULL;
  20472. }
  20473. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  20474. py_TValue* data = PK_MALLOC(sizeof(py_TValue) * chunk_numel);
  20475. data[0] = *context;
  20476. memset(&data[1], 0, sizeof(py_TValue) * (chunk_numel - 1));
  20477. c11_chunked_array2d_chunks__set(&self->chunks, pos, data);
  20478. self->last_visited.key = pos;
  20479. self->last_visited.value = data;
  20480. // init data with default value
  20481. for(int i = 1; i < chunk_numel; i++) {
  20482. data[i] = self->default_T;
  20483. }
  20484. return data;
  20485. }
  20486. static void
  20487. cpy312__divmod_int_uint(int a, int b_log2, int b_mask, int* restrict q, int* restrict r) {
  20488. if(a >= 0) {
  20489. *q = a >> b_log2;
  20490. *r = a & b_mask;
  20491. } else {
  20492. *q = -1 - ((-a - 1) >> b_log2);
  20493. *r = b_mask - ((-a - 1) & b_mask);
  20494. }
  20495. }
  20496. static void c11_chunked_array2d__world_to_chunk(c11_chunked_array2d* self,
  20497. int col,
  20498. int row,
  20499. c11_vec2i* restrict chunk_pos,
  20500. c11_vec2i* restrict local_pos) {
  20501. cpy312__divmod_int_uint(col,
  20502. self->chunk_size_log2,
  20503. self->chunk_size_mask,
  20504. &chunk_pos->x,
  20505. &local_pos->x);
  20506. cpy312__divmod_int_uint(row,
  20507. self->chunk_size_log2,
  20508. self->chunk_size_mask,
  20509. &chunk_pos->y,
  20510. &local_pos->y);
  20511. }
  20512. static py_TValue* c11_chunked_array2d__parse_col_row(c11_chunked_array2d* self,
  20513. int col,
  20514. int row,
  20515. c11_vec2i* restrict chunk_pos,
  20516. c11_vec2i* restrict local_pos) {
  20517. c11_chunked_array2d__world_to_chunk(self, col, row, chunk_pos, local_pos);
  20518. py_TValue* data;
  20519. if(self->last_visited.value != NULL && chunk_pos->_i64 == self->last_visited.key._i64) {
  20520. data = self->last_visited.value;
  20521. } else {
  20522. data = c11_chunked_array2d_chunks__get(&self->chunks, *chunk_pos, NULL);
  20523. }
  20524. if(data != NULL) {
  20525. self->last_visited.key = *chunk_pos;
  20526. self->last_visited.value = data;
  20527. }
  20528. return data;
  20529. }
  20530. py_Ref c11_chunked_array2d__get(c11_chunked_array2d* self, int col, int row) {
  20531. c11_vec2i chunk_pos, local_pos;
  20532. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  20533. if(data == NULL) return NULL;
  20534. return &data[1 + local_pos.y * self->chunk_size + local_pos.x];
  20535. }
  20536. bool c11_chunked_array2d__set(c11_chunked_array2d* self, int col, int row, py_Ref value) {
  20537. c11_vec2i chunk_pos, local_pos;
  20538. py_TValue* data = c11_chunked_array2d__parse_col_row(self, col, row, &chunk_pos, &local_pos);
  20539. if(data == NULL) {
  20540. if(self->auto_add_chunk) {
  20541. data = c11_chunked_array2d__new_chunk(self, chunk_pos, py_None());
  20542. if(data == NULL) return false;
  20543. } else {
  20544. return IndexError("(%d, %d) is out of bounds and !auto_add_chunk", col, row);
  20545. }
  20546. }
  20547. data[1 + local_pos.y * self->chunk_size + local_pos.x] = *value;
  20548. return true;
  20549. }
  20550. static bool chunked_array2d__new__(int argc, py_Ref argv) {
  20551. PY_CHECK_ARGC(4);
  20552. PY_CHECK_ARG_TYPE(1, tp_int);
  20553. PY_CHECK_ARG_TYPE(3, tp_bool);
  20554. py_Type cls = py_totype(argv);
  20555. c11_chunked_array2d* self = py_newobject(py_retval(), cls, 0, sizeof(c11_chunked_array2d));
  20556. int chunk_size = py_toint(&argv[1]);
  20557. self->default_T = argv[2];
  20558. self->auto_add_chunk = py_tobool(&argv[3]);
  20559. c11_chunked_array2d_chunks__ctor(&self->chunks);
  20560. self->chunk_size = chunk_size;
  20561. switch(chunk_size) {
  20562. case 2: self->chunk_size_log2 = 1; break;
  20563. case 4: self->chunk_size_log2 = 2; break;
  20564. case 8: self->chunk_size_log2 = 3; break;
  20565. case 16: self->chunk_size_log2 = 4; break;
  20566. case 32: self->chunk_size_log2 = 5; break;
  20567. case 64: self->chunk_size_log2 = 6; break;
  20568. case 128: self->chunk_size_log2 = 7; break;
  20569. case 256: self->chunk_size_log2 = 8; break;
  20570. case 512: self->chunk_size_log2 = 9; break;
  20571. case 1024: self->chunk_size_log2 = 10; break;
  20572. case 2048: self->chunk_size_log2 = 11; break;
  20573. case 4096: self->chunk_size_log2 = 12; break;
  20574. default: return ValueError("invalid chunk_size: %d, not power of 2", chunk_size);
  20575. }
  20576. self->chunk_size_mask = chunk_size - 1;
  20577. memset(&self->last_visited, 0, sizeof(c11_chunked_array2d_chunks_KV));
  20578. return true;
  20579. }
  20580. static bool chunked_array2d_chunk_size(int argc, py_Ref argv) {
  20581. PY_CHECK_ARGC(1);
  20582. c11_chunked_array2d* self = py_touserdata(argv);
  20583. py_newint(py_retval(), self->chunk_size);
  20584. return true;
  20585. }
  20586. static bool chunked_array2d__getitem__(int argc, py_Ref argv) {
  20587. PY_CHECK_ARGC(2);
  20588. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20589. c11_chunked_array2d* self = py_touserdata(argv);
  20590. c11_vec2i pos = py_tovec2i(&argv[1]);
  20591. py_Ref res = c11_chunked_array2d__get(self, pos.x, pos.y);
  20592. if(res == NULL) return IndexError("(%d, %d) is out of bounds", pos.x, pos.y);
  20593. py_assign(py_retval(), res);
  20594. return true;
  20595. }
  20596. static bool chunked_array2d__setitem__(int argc, py_Ref argv) {
  20597. PY_CHECK_ARGC(3);
  20598. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20599. c11_chunked_array2d* self = py_touserdata(argv);
  20600. c11_vec2i pos = py_tovec2i(&argv[1]);
  20601. bool ok = c11_chunked_array2d__set(self, pos.x, pos.y, &argv[2]);
  20602. if(!ok) return false;
  20603. py_newnone(py_retval());
  20604. return true;
  20605. }
  20606. static bool chunked_array2d__iter__(int argc, py_Ref argv) {
  20607. PY_CHECK_ARGC(1);
  20608. c11_chunked_array2d* self = py_touserdata(argv);
  20609. py_Ref data = py_newtuple(py_pushtmp(), self->chunks.length);
  20610. for(int i = 0; i < self->chunks.length; i++) {
  20611. c11_chunked_array2d_chunks_KV* kv =
  20612. c11__at(c11_chunked_array2d_chunks_KV, &self->chunks, i);
  20613. py_Ref p = py_newtuple(&data[i], 2);
  20614. py_newvec2i(&p[0], kv->key); // pos
  20615. p[1] = kv->value[0]; // context
  20616. }
  20617. bool ok = py_iter(py_peek(-1));
  20618. if(!ok) return false;
  20619. py_pop();
  20620. return true;
  20621. }
  20622. static bool chunked_array2d__len__(int argc, py_Ref argv) {
  20623. PY_CHECK_ARGC(1);
  20624. c11_chunked_array2d* self = py_touserdata(argv);
  20625. py_newint(py_retval(), self->chunks.length);
  20626. return true;
  20627. }
  20628. static bool chunked_array2d_clear(int argc, py_Ref argv) {
  20629. PY_CHECK_ARGC(1);
  20630. c11_chunked_array2d* self = py_touserdata(argv);
  20631. c11__foreach(c11_chunked_array2d_chunks_KV, &self->chunks, p_kv) PK_FREE(p_kv->value);
  20632. c11_chunked_array2d_chunks__clear(&self->chunks);
  20633. self->last_visited.value = NULL;
  20634. py_newnone(py_retval());
  20635. return true;
  20636. }
  20637. static bool chunked_array2d_copy(int argc, py_Ref argv) {
  20638. PY_CHECK_ARGC(1);
  20639. c11_chunked_array2d* self = py_touserdata(argv);
  20640. c11_chunked_array2d* res =
  20641. py_newobject(py_retval(), tp_chunked_array2d, 0, sizeof(c11_chunked_array2d));
  20642. // copy basic data
  20643. memcpy(res, self, sizeof(c11_chunked_array2d));
  20644. // invalidate last_visited cache
  20645. self->last_visited.value = NULL;
  20646. // copy chunks
  20647. memset(&res->chunks, 0, sizeof(c11_chunked_array2d_chunks));
  20648. c11_chunked_array2d_chunks__ctor(&res->chunks);
  20649. c11_vector__reserve(&res->chunks, self->chunks.capacity);
  20650. for(int i = 0; i < self->chunks.length; i++) {
  20651. c11_chunked_array2d_chunks_KV* kv =
  20652. c11__at(c11_chunked_array2d_chunks_KV, &self->chunks, i);
  20653. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  20654. py_TValue* data = PK_MALLOC(sizeof(py_TValue) * chunk_numel);
  20655. memcpy(data, kv->value, sizeof(py_TValue) * chunk_numel);
  20656. // construct new KV
  20657. c11_chunked_array2d_chunks_KV new_kv;
  20658. new_kv.key = kv->key;
  20659. new_kv.value = data;
  20660. c11_vector__push(c11_chunked_array2d_chunks_KV, &res->chunks, new_kv);
  20661. }
  20662. return true;
  20663. }
  20664. static bool chunked_array2d_world_to_chunk(int argc, py_Ref argv) {
  20665. PY_CHECK_ARGC(2);
  20666. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20667. c11_chunked_array2d* self = py_touserdata(argv);
  20668. c11_vec2i pos = py_tovec2i(&argv[1]);
  20669. c11_vec2i chunk_pos, local_pos;
  20670. c11_chunked_array2d__world_to_chunk(self, pos.x, pos.y, &chunk_pos, &local_pos);
  20671. py_TValue* p = py_newtuple(py_retval(), 2);
  20672. py_newvec2i(&p[0], chunk_pos);
  20673. py_newvec2i(&p[1], local_pos);
  20674. return true;
  20675. }
  20676. static bool chunked_array2d_add_chunk(int argc, py_Ref argv) {
  20677. PY_CHECK_ARGC(3);
  20678. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20679. c11_chunked_array2d* self = py_touserdata(argv);
  20680. c11_vec2i pos = py_tovec2i(&argv[1]);
  20681. py_TValue* data = c11_chunked_array2d__new_chunk(self, pos, &argv[2]);
  20682. if(data == NULL) return false;
  20683. py_newnone(py_retval());
  20684. return true;
  20685. }
  20686. static bool chunked_array2d_remove_chunk(int argc, py_Ref argv) {
  20687. PY_CHECK_ARGC(2);
  20688. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20689. c11_chunked_array2d* self = py_touserdata(argv);
  20690. c11_vec2i pos = py_tovec2i(&argv[1]);
  20691. py_TValue* data = c11_chunked_array2d_chunks__get(&self->chunks, pos, NULL);
  20692. if(data != NULL) {
  20693. PK_FREE(data);
  20694. bool ok = c11_chunked_array2d_chunks__del(&self->chunks, pos);
  20695. assert(ok);
  20696. self->last_visited.value = NULL;
  20697. py_newbool(py_retval(), ok);
  20698. } else {
  20699. py_newbool(py_retval(), false);
  20700. }
  20701. return true;
  20702. }
  20703. static bool chunked_array2d_move_chunk(int argc, py_Ref argv) {
  20704. PY_CHECK_ARGC(3);
  20705. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20706. PY_CHECK_ARG_TYPE(2, tp_vec2i);
  20707. c11_chunked_array2d* self = py_touserdata(argv);
  20708. c11_vec2i src = py_tovec2i(&argv[1]);
  20709. c11_vec2i dst = py_tovec2i(&argv[2]);
  20710. py_TValue* src_data = c11_chunked_array2d_chunks__get(&self->chunks, src, NULL);
  20711. py_TValue* dst_data = c11_chunked_array2d_chunks__get(&self->chunks, dst, NULL);
  20712. if(src_data == NULL || dst_data != NULL) {
  20713. py_newbool(py_retval(), false);
  20714. return true;
  20715. }
  20716. c11_chunked_array2d_chunks__del(&self->chunks, src);
  20717. c11_chunked_array2d_chunks__set(&self->chunks, dst, src_data);
  20718. self->last_visited.value = NULL;
  20719. py_newbool(py_retval(), true);
  20720. return true;
  20721. }
  20722. static bool chunked_array2d_get_context(int argc, py_Ref argv) {
  20723. PY_CHECK_ARGC(2);
  20724. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20725. c11_chunked_array2d* self = py_touserdata(argv);
  20726. c11_vec2i pos = py_tovec2i(&argv[1]);
  20727. py_TValue* data = c11_chunked_array2d_chunks__get(&self->chunks, pos, NULL);
  20728. if(data == NULL) {
  20729. return IndexError("no chunk found at (%d, %d)", pos.x, pos.y);
  20730. } else {
  20731. py_assign(py_retval(), &data[0]);
  20732. }
  20733. return true;
  20734. }
  20735. void c11_chunked_array2d__dtor(c11_chunked_array2d* self) {
  20736. c11__foreach(c11_chunked_array2d_chunks_KV, &self->chunks, p_kv) PK_FREE(p_kv->value);
  20737. c11_chunked_array2d_chunks__dtor(&self->chunks);
  20738. }
  20739. void c11_chunked_array2d__mark(void* ud, c11_vector* p_stack) {
  20740. c11_chunked_array2d* self = ud;
  20741. pk__mark_value(&self->default_T);
  20742. int chunk_numel = self->chunk_size * self->chunk_size + 1;
  20743. for(int i = 0; i < self->chunks.length; i++) {
  20744. py_TValue* data = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).value;
  20745. for(int j = 0; j < chunk_numel; j++) {
  20746. pk__mark_value(data + j);
  20747. }
  20748. }
  20749. }
  20750. static bool chunked_array2d_view(int argc, py_Ref argv) {
  20751. PY_CHECK_ARGC(1);
  20752. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  20753. if(self->chunks.length == 0) { return ValueError("chunked_array2d is empty"); }
  20754. int min_chunk_x = INT_MAX;
  20755. int min_chunk_y = INT_MAX;
  20756. int max_chunk_x = INT_MIN;
  20757. int max_chunk_y = INT_MIN;
  20758. for(int i = 0; i < self->chunks.length; i++) {
  20759. c11_vec2i chunk_pos = c11__getitem(c11_chunked_array2d_chunks_KV, &self->chunks, i).key;
  20760. min_chunk_x = c11__min(min_chunk_x, chunk_pos.x);
  20761. min_chunk_y = c11__min(min_chunk_y, chunk_pos.y);
  20762. max_chunk_x = c11__max(max_chunk_x, chunk_pos.x);
  20763. max_chunk_y = c11__max(max_chunk_y, chunk_pos.y);
  20764. }
  20765. int start_col = min_chunk_x * self->chunk_size;
  20766. int start_row = min_chunk_y * self->chunk_size;
  20767. int width = (max_chunk_x - min_chunk_x + 1) * self->chunk_size;
  20768. int height = (max_chunk_y - min_chunk_y + 1) * self->chunk_size;
  20769. return _chunked_array2d_view(py_retval(), argv, self, start_col, start_row, width, height);
  20770. }
  20771. static bool chunked_array2d_view_rect(int argc, py_Ref argv) {
  20772. PY_CHECK_ARGC(4);
  20773. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20774. PY_CHECK_ARG_TYPE(2, tp_int);
  20775. PY_CHECK_ARG_TYPE(3, tp_int);
  20776. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  20777. c11_vec2i pos = py_tovec2i(&argv[1]);
  20778. int width = py_toint(&argv[2]);
  20779. int height = py_toint(&argv[3]);
  20780. return _chunked_array2d_view(py_retval(), argv, self, pos.x, pos.y, width, height);
  20781. }
  20782. static bool chunked_array2d_view_chunk(int argc, py_Ref argv) {
  20783. PY_CHECK_ARGC(2);
  20784. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20785. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  20786. c11_vec2i chunk_pos = py_tovec2i(&argv[1]);
  20787. int start_col = chunk_pos.x * self->chunk_size;
  20788. int start_row = chunk_pos.y * self->chunk_size;
  20789. return _chunked_array2d_view(py_retval(),
  20790. argv,
  20791. self,
  20792. start_col,
  20793. start_row,
  20794. self->chunk_size,
  20795. self->chunk_size);
  20796. }
  20797. static bool chunked_array2d_view_chunks(int argc, py_Ref argv) {
  20798. PY_CHECK_ARGC(4);
  20799. PY_CHECK_ARG_TYPE(1, tp_vec2i);
  20800. PY_CHECK_ARG_TYPE(2, tp_int);
  20801. PY_CHECK_ARG_TYPE(3, tp_int);
  20802. c11_chunked_array2d* self = py_touserdata(&argv[0]);
  20803. c11_vec2i chunk_pos = py_tovec2i(&argv[1]);
  20804. int width = py_toint(&argv[2]) * self->chunk_size;
  20805. int height = py_toint(&argv[3]) * self->chunk_size;
  20806. int start_col = chunk_pos.x * self->chunk_size;
  20807. int start_row = chunk_pos.y * self->chunk_size;
  20808. return _chunked_array2d_view(py_retval(), argv, self, start_col, start_row, width, height);
  20809. }
  20810. static void register_chunked_array2d(py_Ref mod) {
  20811. py_Type type =
  20812. py_newtype("chunked_array2d", tp_object, mod, (py_Dtor)c11_chunked_array2d__dtor);
  20813. assert(type == tp_chunked_array2d);
  20814. py_bind(py_tpobject(type),
  20815. "__new__(cls, chunk_size, default=None, auto_add_chunk=True)",
  20816. chunked_array2d__new__);
  20817. py_bindproperty(type, "chunk_size", chunked_array2d_chunk_size, NULL);
  20818. py_bindmagic(type, __getitem__, chunked_array2d__getitem__);
  20819. py_bindmagic(type, __setitem__, chunked_array2d__setitem__);
  20820. py_bindmagic(type, __iter__, chunked_array2d__iter__);
  20821. py_bindmagic(type, __len__, chunked_array2d__len__);
  20822. py_bindmethod(type, "clear", chunked_array2d_clear);
  20823. py_bindmethod(type, "copy", chunked_array2d_copy);
  20824. py_bindmethod(type, "world_to_chunk", chunked_array2d_world_to_chunk);
  20825. py_bindmethod(type, "add_chunk", chunked_array2d_add_chunk);
  20826. py_bindmethod(type, "remove_chunk", chunked_array2d_remove_chunk);
  20827. py_bindmethod(type, "move_chunk", chunked_array2d_move_chunk);
  20828. py_bindmethod(type, "get_context", chunked_array2d_get_context);
  20829. py_bindmethod(type, "view", chunked_array2d_view);
  20830. py_bindmethod(type, "view_rect", chunked_array2d_view_rect);
  20831. py_bindmethod(type, "view_chunk", chunked_array2d_view_chunk);
  20832. py_bindmethod(type, "view_chunks", chunked_array2d_view_chunks);
  20833. }
  20834. void pk__add_module_array2d() {
  20835. py_GlobalRef mod = py_newmodule("array2d");
  20836. register_array2d_like(mod);
  20837. register_array2d_like_iterator(mod);
  20838. register_array2d(mod);
  20839. register_array2d_view(mod);
  20840. register_chunked_array2d(mod);
  20841. }
  20842. void py_newarray2d(py_OutRef out, int width, int height) { c11_newarray2d(out, width, height); }
  20843. int py_array2d_getwidth(py_Ref self) {
  20844. assert(self->type == tp_array2d);
  20845. c11_array2d* ud = py_touserdata(self);
  20846. return ud->header.n_cols;
  20847. }
  20848. int py_array2d_getheight(py_Ref self) {
  20849. assert(self->type == tp_array2d);
  20850. c11_array2d* ud = py_touserdata(self);
  20851. return ud->header.n_rows;
  20852. }
  20853. py_ObjectRef py_array2d_getitem(py_Ref self, int x, int y) {
  20854. assert(self->type == tp_array2d);
  20855. c11_array2d* ud = py_touserdata(self);
  20856. return c11_array2d__get(ud, x, y);
  20857. }
  20858. void py_array2d_setitem(py_Ref self, int x, int y, py_Ref value) {
  20859. assert(self->type == tp_array2d);
  20860. c11_array2d* ud = py_touserdata(self);
  20861. c11_array2d__set(ud, x, y, value);
  20862. }
  20863. // src/modules\base64.c
  20864. #include <limits.h>
  20865. // https://github.com/zhicheng/base64/blob/master/base64.c
  20866. const char BASE64_PAD = '=';
  20867. const char BASE64DE_FIRST = '+';
  20868. const char BASE64DE_LAST = 'z';
  20869. /* BASE 64 encode table */
  20870. const char base64en[] = {
  20871. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
  20872. 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
  20873. 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
  20874. 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
  20875. 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
  20876. 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  20877. 'w', 'x', 'y', 'z', '0', '1', '2', '3',
  20878. '4', '5', '6', '7', '8', '9', '+', '/',
  20879. };
  20880. /* ASCII order for BASE 64 decode, 255 in unused character */
  20881. const unsigned char base64de[] = {
  20882. /* nul, soh, stx, etx, eot, enq, ack, bel, */
  20883. 255, 255, 255, 255, 255, 255, 255, 255,
  20884. /* bs, ht, nl, vt, np, cr, so, si, */
  20885. 255, 255, 255, 255, 255, 255, 255, 255,
  20886. /* dle, dc1, dc2, dc3, dc4, nak, syn, etb, */
  20887. 255, 255, 255, 255, 255, 255, 255, 255,
  20888. /* can, em, sub, esc, fs, gs, rs, us, */
  20889. 255, 255, 255, 255, 255, 255, 255, 255,
  20890. /* sp, '!', '"', '#', '$', '%', '&', ''', */
  20891. 255, 255, 255, 255, 255, 255, 255, 255,
  20892. /* '(', ')', '*', '+', ',', '-', '.', '/', */
  20893. 255, 255, 255, 62, 255, 255, 255, 63,
  20894. /* '0', '1', '2', '3', '4', '5', '6', '7', */
  20895. 52, 53, 54, 55, 56, 57, 58, 59,
  20896. /* '8', '9', ':', ';', '<', '=', '>', '?', */
  20897. 60, 61, 255, 255, 255, 255, 255, 255,
  20898. /* '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', */
  20899. 255, 0, 1, 2, 3, 4, 5, 6,
  20900. /* 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', */
  20901. 7, 8, 9, 10, 11, 12, 13, 14,
  20902. /* 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', */
  20903. 15, 16, 17, 18, 19, 20, 21, 22,
  20904. /* 'X', 'Y', 'Z', '[', '\', ']', '^', '_', */
  20905. 23, 24, 25, 255, 255, 255, 255, 255,
  20906. /* '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', */
  20907. 255, 26, 27, 28, 29, 30, 31, 32,
  20908. /* 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', */
  20909. 33, 34, 35, 36, 37, 38, 39, 40,
  20910. /* 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', */
  20911. 41, 42, 43, 44, 45, 46, 47, 48,
  20912. /* 'x', 'y', 'z', '{', '|', '}', '~', del, */
  20913. 49, 50, 51, 255, 255, 255, 255, 255
  20914. };
  20915. static unsigned int
  20916. base64_encode(const unsigned char *in, unsigned int inlen, char *out)
  20917. {
  20918. int s;
  20919. unsigned int i;
  20920. unsigned int j;
  20921. unsigned char c;
  20922. unsigned char l;
  20923. s = 0;
  20924. l = 0;
  20925. for (i = j = 0; i < inlen; i++) {
  20926. c = in[i];
  20927. switch (s) {
  20928. case 0:
  20929. s = 1;
  20930. out[j++] = base64en[(c >> 2) & 0x3F];
  20931. break;
  20932. case 1:
  20933. s = 2;
  20934. out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xF)];
  20935. break;
  20936. case 2:
  20937. s = 0;
  20938. out[j++] = base64en[((l & 0xF) << 2) | ((c >> 6) & 0x3)];
  20939. out[j++] = base64en[c & 0x3F];
  20940. break;
  20941. }
  20942. l = c;
  20943. }
  20944. switch (s) {
  20945. case 1:
  20946. out[j++] = base64en[(l & 0x3) << 4];
  20947. out[j++] = BASE64_PAD;
  20948. out[j++] = BASE64_PAD;
  20949. break;
  20950. case 2:
  20951. out[j++] = base64en[(l & 0xF) << 2];
  20952. out[j++] = BASE64_PAD;
  20953. break;
  20954. }
  20955. out[j] = 0;
  20956. return j;
  20957. }
  20958. static unsigned int
  20959. base64_decode(const char *in, unsigned int inlen, unsigned char *out)
  20960. {
  20961. unsigned int i;
  20962. unsigned int j;
  20963. unsigned char c;
  20964. if (inlen & 0x3) {
  20965. return 0;
  20966. }
  20967. for (i = j = 0; i < inlen; i++) {
  20968. if (in[i] == BASE64_PAD) {
  20969. break;
  20970. }
  20971. if (in[i] < BASE64DE_FIRST || in[i] > BASE64DE_LAST) {
  20972. return 0;
  20973. }
  20974. c = base64de[(unsigned char)in[i]];
  20975. if (c == 255) {
  20976. return 0;
  20977. }
  20978. switch (i & 0x3) {
  20979. case 0:
  20980. out[j] = (c << 2) & 0xFF;
  20981. break;
  20982. case 1:
  20983. out[j++] |= (c >> 4) & 0x3;
  20984. out[j] = (c & 0xF) << 4;
  20985. break;
  20986. case 2:
  20987. out[j++] |= (c >> 2) & 0xF;
  20988. out[j] = (c & 0x3) << 6;
  20989. break;
  20990. case 3:
  20991. out[j++] |= c;
  20992. break;
  20993. }
  20994. }
  20995. return j;
  20996. }
  20997. static bool base64_b64encode(int argc, py_Ref argv) {
  20998. PY_CHECK_ARGC(1);
  20999. PY_CHECK_ARG_TYPE(0, tp_bytes);
  21000. int src_size;
  21001. unsigned char* src_data = py_tobytes(argv, &src_size);
  21002. unsigned char* dst_data = py_newbytes(py_retval(), src_size * 4 / 3 + 4);
  21003. int size = base64_encode(src_data, src_size, (char*)dst_data);
  21004. py_bytes_resize(py_retval(), size);
  21005. return true;
  21006. }
  21007. static bool base64_b64decode(int argc, py_Ref argv) {
  21008. PY_CHECK_ARGC(1);
  21009. int src_size;
  21010. void* src_data;
  21011. if(py_istype(argv, tp_str)) {
  21012. c11_sv sv = py_tosv(argv);
  21013. src_data = (void*)sv.data;
  21014. src_size = sv.size;
  21015. } else if(py_istype(argv, tp_bytes)) {
  21016. src_data = py_tobytes(argv, &src_size);
  21017. } else {
  21018. return TypeError("expect bytes or str, got %t", argv->type);
  21019. }
  21020. unsigned char* dst_data = py_newbytes(py_retval(), src_size);
  21021. int size = base64_decode((const char*)src_data, src_size, dst_data);
  21022. py_bytes_resize(py_retval(), size);
  21023. return true;
  21024. }
  21025. void pk__add_module_base64(){
  21026. py_GlobalRef mod = py_newmodule("base64");
  21027. py_bindfunc(mod, "b64encode", base64_b64encode);
  21028. py_bindfunc(mod, "b64decode", base64_b64decode);
  21029. }
  21030. // src/modules\builtins.c
  21031. static bool builtins_exit(int argc, py_Ref argv) {
  21032. int code = 0;
  21033. if(argc > 1) return TypeError("exit() takes at most 1 argument");
  21034. if(argc == 1) {
  21035. PY_CHECK_ARG_TYPE(0, tp_int);
  21036. code = py_toint(argv);
  21037. }
  21038. exit(code);
  21039. return false;
  21040. }
  21041. static bool builtins_input(int argc, py_Ref argv) {
  21042. if(argc > 1) return TypeError("input() takes at most 1 argument");
  21043. const char* prompt = "";
  21044. if(argc == 1) {
  21045. if(!py_checkstr(argv)) return false;
  21046. prompt = py_tostr(argv);
  21047. }
  21048. py_callbacks()->print(prompt);
  21049. c11_sbuf buf;
  21050. c11_sbuf__ctor(&buf);
  21051. while(true) {
  21052. int c = py_callbacks()->getchr();
  21053. if(c == '\n' || c == '\r') break;
  21054. if(c == EOF) break;
  21055. c11_sbuf__write_char(&buf, c);
  21056. }
  21057. c11_sbuf__py_submit(&buf, py_retval());
  21058. return true;
  21059. }
  21060. static bool builtins_repr(int argc, py_Ref argv) {
  21061. PY_CHECK_ARGC(1);
  21062. return py_repr(argv);
  21063. }
  21064. static bool builtins_len(int argc, py_Ref argv) {
  21065. PY_CHECK_ARGC(1);
  21066. return py_len(argv);
  21067. }
  21068. static bool builtins_hex(int argc, py_Ref argv) {
  21069. PY_CHECK_ARGC(1);
  21070. PY_CHECK_ARG_TYPE(0, tp_int);
  21071. py_i64 val = py_toint(argv);
  21072. if(val == 0) {
  21073. py_newstr(py_retval(), "0x0");
  21074. return true;
  21075. }
  21076. c11_sbuf ss;
  21077. c11_sbuf__ctor(&ss);
  21078. if(val < 0) {
  21079. c11_sbuf__write_char(&ss, '-');
  21080. val = -val;
  21081. }
  21082. c11_sbuf__write_cstr(&ss, "0x");
  21083. bool non_zero = true;
  21084. for(int i = 56; i >= 0; i -= 8) {
  21085. unsigned char cpnt = (val >> i) & 0xff;
  21086. c11_sbuf__write_hex(&ss, cpnt, non_zero);
  21087. if(cpnt != 0) non_zero = false;
  21088. }
  21089. c11_sbuf__py_submit(&ss, py_retval());
  21090. return true;
  21091. }
  21092. static bool builtins_bin(int argc, py_Ref argv) {
  21093. PY_CHECK_ARGC(1);
  21094. PY_CHECK_ARG_TYPE(0, tp_int);
  21095. py_i64 val = py_toint(argv);
  21096. if(val == 0) {
  21097. py_newstr(py_retval(), "0b0");
  21098. return true;
  21099. }
  21100. c11_sbuf ss;
  21101. c11_sbuf__ctor(&ss);
  21102. if(val < 0) {
  21103. c11_sbuf__write_char(&ss, '-');
  21104. val = -val;
  21105. }
  21106. c11_sbuf__write_cstr(&ss, "0b");
  21107. bool non_zero = true;
  21108. for(int i = 63; i >= 0; i--) {
  21109. unsigned char bit = (val >> i) & 1;
  21110. if(bit != 0) non_zero = false;
  21111. if(!non_zero) c11_sbuf__write_char(&ss, bit ? '1' : '0');
  21112. }
  21113. c11_sbuf__py_submit(&ss, py_retval());
  21114. return true;
  21115. }
  21116. static bool builtins_iter(int argc, py_Ref argv) {
  21117. PY_CHECK_ARGC(1);
  21118. return py_iter(argv);
  21119. }
  21120. static bool builtins_next(int argc, py_Ref argv) {
  21121. if(argc == 0 || argc > 2) return TypeError("next() takes 1 or 2 arguments");
  21122. int res = py_next(argv);
  21123. if(res == -1) return false;
  21124. if(res) return true;
  21125. if(argc == 1) {
  21126. // StopIteration stored in py_retval()
  21127. return py_raise(py_retval());
  21128. } else {
  21129. py_assign(py_retval(), py_arg(1));
  21130. return true;
  21131. }
  21132. }
  21133. static bool builtins_hash(int argc, py_Ref argv) {
  21134. PY_CHECK_ARGC(1);
  21135. py_i64 val;
  21136. if(!py_hash(argv, &val)) return false;
  21137. py_newint(py_retval(), val);
  21138. return true;
  21139. }
  21140. static bool builtins_abs(int argc, py_Ref argv) {
  21141. PY_CHECK_ARGC(1);
  21142. return pk_callmagic(__abs__, 1, argv);
  21143. }
  21144. static bool builtins_divmod(int argc, py_Ref argv) {
  21145. PY_CHECK_ARGC(2);
  21146. return pk_callmagic(__divmod__, 2, argv);
  21147. }
  21148. static bool builtins_round(int argc, py_Ref argv) {
  21149. py_i64 ndigits;
  21150. if(argc == 1) {
  21151. ndigits = -1;
  21152. } else if(argc == 2) {
  21153. PY_CHECK_ARG_TYPE(1, tp_int);
  21154. ndigits = py_toint(py_arg(1));
  21155. if(ndigits < 0) return ValueError("ndigits should be non-negative");
  21156. } else {
  21157. return TypeError("round() takes 1 or 2 arguments");
  21158. }
  21159. if(argv->type == tp_int) {
  21160. py_assign(py_retval(), py_arg(0));
  21161. return true;
  21162. } else if(argv->type == tp_float) {
  21163. py_f64 x = py_tofloat(py_arg(0));
  21164. py_f64 offset = x >= 0 ? 0.5 : -0.5;
  21165. if(ndigits == -1) {
  21166. py_newint(py_retval(), (py_i64)(x + offset));
  21167. return true;
  21168. }
  21169. // py_f64 factor = dmath_exp10(ndigits);
  21170. py_f64 factor = 1.0;
  21171. for(int i = 0; i < ndigits; i++) factor *= 10.0;
  21172. py_newfloat(py_retval(), (py_i64)(x * factor + offset) / factor);
  21173. return true;
  21174. }
  21175. return pk_callmagic(__round__, argc, argv);
  21176. }
  21177. static bool builtins_print(int argc, py_Ref argv) {
  21178. // print(*args, sep=' ', end='\n', flush=False)
  21179. py_TValue* args = py_tuple_data(argv);
  21180. int length = py_tuple_len(argv);
  21181. PY_CHECK_ARG_TYPE(1, tp_str);
  21182. PY_CHECK_ARG_TYPE(2, tp_str);
  21183. PY_CHECK_ARG_TYPE(3, tp_bool);
  21184. c11_sv sep = py_tosv(py_arg(1));
  21185. c11_sv end = py_tosv(py_arg(2));
  21186. bool flush = py_tobool(py_arg(3));
  21187. c11_sbuf buf;
  21188. c11_sbuf__ctor(&buf);
  21189. for(int i = 0; i < length; i++) {
  21190. if(i > 0) c11_sbuf__write_sv(&buf, sep);
  21191. if(!py_str(&args[i])) {
  21192. c11_sbuf__dtor(&buf);
  21193. return false;
  21194. }
  21195. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  21196. }
  21197. c11_sbuf__write_sv(&buf, end);
  21198. c11_string* res = c11_sbuf__submit(&buf);
  21199. py_callbacks()->print(res->data);
  21200. if(flush) py_callbacks()->flush();
  21201. c11_string__delete(res);
  21202. py_newnone(py_retval());
  21203. return true;
  21204. }
  21205. static bool builtins_isinstance(int argc, py_Ref argv) {
  21206. PY_CHECK_ARGC(2);
  21207. if(py_istuple(py_arg(1))) {
  21208. int length = py_tuple_len(py_arg(1));
  21209. for(int i = 0; i < length; i++) {
  21210. py_Ref item = py_tuple_getitem(py_arg(1), i);
  21211. if(!py_checktype(item, tp_type)) return false;
  21212. if(py_isinstance(py_arg(0), py_totype(item))) {
  21213. py_newbool(py_retval(), true);
  21214. return true;
  21215. }
  21216. }
  21217. py_newbool(py_retval(), false);
  21218. return true;
  21219. }
  21220. if(!py_checktype(py_arg(1), tp_type)) return false;
  21221. py_newbool(py_retval(), py_isinstance(py_arg(0), py_totype(py_arg(1))));
  21222. return true;
  21223. }
  21224. static bool builtins_issubclass(int argc, py_Ref argv) {
  21225. PY_CHECK_ARGC(2);
  21226. if(!py_checktype(py_arg(0), tp_type)) return false;
  21227. if(!py_checktype(py_arg(1), tp_type)) return false;
  21228. py_newbool(py_retval(), py_issubclass(py_totype(py_arg(0)), py_totype(py_arg(1))));
  21229. return true;
  21230. }
  21231. static bool builtins_callable(int argc, py_Ref argv) {
  21232. PY_CHECK_ARGC(1);
  21233. bool res = py_callable(py_arg(0));
  21234. py_newbool(py_retval(), res);
  21235. return true;
  21236. }
  21237. static bool builtins_getattr(int argc, py_Ref argv) {
  21238. PY_CHECK_ARG_TYPE(1, tp_str);
  21239. py_Name name = py_namev(py_tosv(py_arg(1)));
  21240. if(argc == 2) {
  21241. return py_getattr(py_arg(0), name);
  21242. } else if(argc == 3) {
  21243. bool ok = py_getattr(py_arg(0), name);
  21244. if(!ok && py_matchexc(tp_AttributeError)) {
  21245. py_clearexc(NULL);
  21246. py_assign(py_retval(), py_arg(2));
  21247. return true; // default value
  21248. }
  21249. return ok;
  21250. } else {
  21251. return TypeError("getattr() expected 2 or 3 arguments");
  21252. }
  21253. return true;
  21254. }
  21255. static bool builtins_setattr(int argc, py_Ref argv) {
  21256. PY_CHECK_ARGC(3);
  21257. PY_CHECK_ARG_TYPE(1, tp_str);
  21258. py_Name name = py_namev(py_tosv(py_arg(1)));
  21259. py_newnone(py_retval());
  21260. return py_setattr(py_arg(0), name, py_arg(2));
  21261. }
  21262. static bool builtins_hasattr(int argc, py_Ref argv) {
  21263. PY_CHECK_ARGC(2);
  21264. PY_CHECK_ARG_TYPE(1, tp_str);
  21265. py_Name name = py_namev(py_tosv(py_arg(1)));
  21266. bool ok = py_getattr(py_arg(0), name);
  21267. if(ok) {
  21268. py_newbool(py_retval(), true);
  21269. return true;
  21270. }
  21271. if(py_matchexc(tp_AttributeError)) {
  21272. py_clearexc(NULL);
  21273. py_newbool(py_retval(), false);
  21274. return true;
  21275. }
  21276. return false;
  21277. }
  21278. static bool builtins_delattr(int argc, py_Ref argv) {
  21279. PY_CHECK_ARGC(2);
  21280. PY_CHECK_ARG_TYPE(1, tp_str);
  21281. py_Name name = py_namev(py_tosv(py_arg(1)));
  21282. py_newnone(py_retval());
  21283. return py_delattr(py_arg(0), name);
  21284. }
  21285. static bool builtins_chr(int argc, py_Ref argv) {
  21286. PY_CHECK_ARGC(1);
  21287. PY_CHECK_ARG_TYPE(0, tp_int);
  21288. uint32_t val = py_toint(py_arg(0));
  21289. // convert to utf-8
  21290. char utf8[4];
  21291. int len = c11__u32_to_u8(val, utf8);
  21292. if(len == -1) return ValueError("invalid unicode code point: %d", val);
  21293. py_newstrv(py_retval(), (c11_sv){utf8, len});
  21294. return true;
  21295. }
  21296. static bool builtins_ord(int argc, py_Ref argv) {
  21297. PY_CHECK_ARGC(1);
  21298. PY_CHECK_ARG_TYPE(0, tp_str);
  21299. c11_sv sv = py_tosv(py_arg(0));
  21300. if(c11_sv__u8_length(sv) != 1) {
  21301. return TypeError("ord() expected a character, but string of length %d found",
  21302. c11_sv__u8_length(sv));
  21303. }
  21304. int u8bytes = c11__u8_header(sv.data[0], true);
  21305. if(u8bytes == 0) return ValueError("invalid utf-8 char: %c", sv.data[0]);
  21306. int value = c11__u8_value(u8bytes, sv.data);
  21307. py_newint(py_retval(), value);
  21308. return true;
  21309. }
  21310. static bool builtins_id(int argc, py_Ref argv) {
  21311. PY_CHECK_ARGC(1);
  21312. if(argv->is_ptr) {
  21313. py_newint(py_retval(), (intptr_t)argv->_obj);
  21314. } else {
  21315. py_newnone(py_retval());
  21316. }
  21317. return true;
  21318. }
  21319. static bool builtins_globals(int argc, py_Ref argv) {
  21320. PY_CHECK_ARGC(0);
  21321. py_newglobals(py_retval());
  21322. return true;
  21323. }
  21324. static bool builtins_locals(int argc, py_Ref argv) {
  21325. PY_CHECK_ARGC(0);
  21326. py_newlocals(py_retval());
  21327. return true;
  21328. }
  21329. static void pk_push_special_locals() {
  21330. py_Frame* frame = pk_current_vm->top_frame;
  21331. if(!frame) {
  21332. py_pushnil();
  21333. return;
  21334. }
  21335. if(frame->is_locals_special) {
  21336. py_push(frame->locals);
  21337. } else {
  21338. py_StackRef out = py_pushtmp();
  21339. out->type = tp_locals;
  21340. out->is_ptr = false;
  21341. out->extra = 0;
  21342. // this is a weak reference
  21343. // which will expire when the frame is destroyed
  21344. out->_ptr = frame;
  21345. }
  21346. }
  21347. static bool _builtins_execdyn(const char* title, int argc, py_Ref argv, enum py_CompileMode mode) {
  21348. switch(argc) {
  21349. case 1: {
  21350. py_newglobals(py_pushtmp());
  21351. pk_push_special_locals();
  21352. break;
  21353. }
  21354. case 2: {
  21355. // globals
  21356. if(py_isnone(py_arg(1))) {
  21357. py_newglobals(py_pushtmp());
  21358. } else {
  21359. py_push(py_arg(1));
  21360. }
  21361. // locals
  21362. py_pushnil();
  21363. break;
  21364. }
  21365. case 3: {
  21366. // globals
  21367. if(py_isnone(py_arg(1))) {
  21368. py_newglobals(py_pushtmp());
  21369. } else {
  21370. py_push(py_arg(1));
  21371. }
  21372. // locals
  21373. if(py_isnone(py_arg(2))) {
  21374. py_pushnil();
  21375. } else {
  21376. py_push(py_arg(2));
  21377. }
  21378. break;
  21379. }
  21380. default: return TypeError("%s() takes at most 3 arguments", title);
  21381. }
  21382. if(py_isstr(argv)) {
  21383. bool ok = py_compile(py_tostr(argv), "<string>", mode, true);
  21384. if(!ok) return false;
  21385. py_push(py_retval());
  21386. } else if(py_istype(argv, tp_code)) {
  21387. py_push(argv);
  21388. } else {
  21389. return TypeError("%s() expected 'str' or 'code', got '%t'", title, argv->type);
  21390. }
  21391. py_Frame* frame = pk_current_vm->top_frame;
  21392. // [globals, locals, code]
  21393. CodeObject* code = py_touserdata(py_peek(-1));
  21394. if(code->src->is_dynamic) {
  21395. bool ok = pk_execdyn(code, frame ? frame->module : NULL, py_peek(-3), py_peek(-2));
  21396. py_shrink(3);
  21397. return ok;
  21398. } else {
  21399. if(argc != 1) {
  21400. return ValueError(
  21401. "code object is not dynamic, `globals` and `locals` must not be specified");
  21402. }
  21403. bool ok = pk_exec(code, frame ? frame->module : NULL);
  21404. py_shrink(3);
  21405. return ok;
  21406. }
  21407. }
  21408. static bool builtins_exec(int argc, py_Ref argv) {
  21409. bool ok = _builtins_execdyn("exec", argc, argv, EXEC_MODE);
  21410. py_newnone(py_retval());
  21411. return ok;
  21412. }
  21413. static bool builtins_eval(int argc, py_Ref argv) {
  21414. return _builtins_execdyn("eval", argc, argv, EVAL_MODE);
  21415. }
  21416. static bool builtins_compile(int argc, py_Ref argv) {
  21417. PY_CHECK_ARGC(3);
  21418. for(int i = 0; i < 3; i++) {
  21419. if(!py_checktype(py_arg(i), tp_str)) return false;
  21420. }
  21421. const char* source = py_tostr(py_arg(0));
  21422. const char* filename = py_tostr(py_arg(1));
  21423. const char* mode = py_tostr(py_arg(2));
  21424. enum py_CompileMode compile_mode;
  21425. if(strcmp(mode, "exec") == 0) {
  21426. compile_mode = EXEC_MODE;
  21427. } else if(strcmp(mode, "eval") == 0) {
  21428. compile_mode = EVAL_MODE;
  21429. } else if(strcmp(mode, "single") == 0) {
  21430. compile_mode = SINGLE_MODE;
  21431. } else {
  21432. return ValueError("compile() mode must be 'exec', 'eval', or 'single'");
  21433. }
  21434. return py_compile(source, filename, compile_mode, true);
  21435. }
  21436. static bool builtins__import__(int argc, py_Ref argv) {
  21437. PY_CHECK_ARGC(1);
  21438. PY_CHECK_ARG_TYPE(0, tp_str);
  21439. const char* path = py_tostr(py_arg(0));
  21440. if(path[0] == '.') return ValueError("relative import not allowed here");
  21441. int res = py_import(path);
  21442. if(res == -1) return false;
  21443. if(res) return true;
  21444. return ImportError("module '%s' not found", path);
  21445. }
  21446. static bool NoneType__repr__(int argc, py_Ref argv) {
  21447. py_newstr(py_retval(), "None");
  21448. return true;
  21449. }
  21450. static bool ellipsis__repr__(int argc, py_Ref argv) {
  21451. py_newstr(py_retval(), "...");
  21452. return true;
  21453. }
  21454. static bool NotImplementedType__repr__(int argc, py_Ref argv) {
  21455. py_newstr(py_retval(), "NotImplemented");
  21456. return true;
  21457. }
  21458. py_GlobalRef pk_builtins__register() {
  21459. py_GlobalRef builtins = py_newmodule("builtins");
  21460. py_bindfunc(builtins, "exit", builtins_exit);
  21461. py_bindfunc(builtins, "input", builtins_input);
  21462. py_bindfunc(builtins, "repr", builtins_repr);
  21463. py_bindfunc(builtins, "len", builtins_len);
  21464. py_bindfunc(builtins, "hex", builtins_hex);
  21465. py_bindfunc(builtins, "bin", builtins_bin);
  21466. py_bindfunc(builtins, "iter", builtins_iter);
  21467. py_bindfunc(builtins, "next", builtins_next);
  21468. py_bindfunc(builtins, "hash", builtins_hash);
  21469. py_bindfunc(builtins, "abs", builtins_abs);
  21470. py_bindfunc(builtins, "divmod", builtins_divmod);
  21471. py_bindfunc(builtins, "round", builtins_round);
  21472. py_bind(builtins, "print(*args, sep=' ', end='\\n', flush=False)", builtins_print);
  21473. py_bindfunc(builtins, "isinstance", builtins_isinstance);
  21474. py_bindfunc(builtins, "issubclass", builtins_issubclass);
  21475. py_bindfunc(builtins, "callable", builtins_callable);
  21476. py_bindfunc(builtins, "getattr", builtins_getattr);
  21477. py_bindfunc(builtins, "setattr", builtins_setattr);
  21478. py_bindfunc(builtins, "hasattr", builtins_hasattr);
  21479. py_bindfunc(builtins, "delattr", builtins_delattr);
  21480. py_bindfunc(builtins, "chr", builtins_chr);
  21481. py_bindfunc(builtins, "ord", builtins_ord);
  21482. py_bindfunc(builtins, "id", builtins_id);
  21483. py_bindfunc(builtins, "globals", builtins_globals);
  21484. py_bindfunc(builtins, "locals", builtins_locals);
  21485. py_bindfunc(builtins, "exec", builtins_exec);
  21486. py_bindfunc(builtins, "eval", builtins_eval);
  21487. py_bindfunc(builtins, "compile", builtins_compile);
  21488. py_bindfunc(builtins, "__import__", builtins__import__);
  21489. // some patches
  21490. py_bindmagic(tp_NoneType, __repr__, NoneType__repr__);
  21491. py_setdict(py_tpobject(tp_NoneType), __hash__, py_None());
  21492. py_bindmagic(tp_ellipsis, __repr__, ellipsis__repr__);
  21493. py_setdict(py_tpobject(tp_ellipsis), __hash__, py_None());
  21494. py_bindmagic(tp_NotImplementedType, __repr__, NotImplementedType__repr__);
  21495. py_setdict(py_tpobject(tp_NotImplementedType), __hash__, py_None());
  21496. return builtins;
  21497. }
  21498. void function__gc_mark(void* ud, c11_vector* p_stack) {
  21499. Function* func = ud;
  21500. pk__mark_value(&func->globals);
  21501. if(func->closure) {
  21502. NameDict* dict = func->closure;
  21503. for(int i = 0; i < dict->capacity; i++) {
  21504. NameDict_KV* kv = &dict->items[i];
  21505. if(kv->key == NULL) continue;
  21506. pk__mark_value(&kv->value);
  21507. }
  21508. }
  21509. FuncDecl__gc_mark(func->decl, p_stack);
  21510. }
  21511. static bool function__doc__(int argc, py_Ref argv) {
  21512. PY_CHECK_ARGC(1);
  21513. Function* func = py_touserdata(py_arg(0));
  21514. if(func->decl->docstring) {
  21515. py_newstr(py_retval(), func->decl->docstring);
  21516. } else {
  21517. py_newnone(py_retval());
  21518. }
  21519. return true;
  21520. }
  21521. static bool function__name__(int argc, py_Ref argv) {
  21522. PY_CHECK_ARGC(1);
  21523. Function* func = py_touserdata(py_arg(0));
  21524. py_newstr(py_retval(), func->decl->code.name->data);
  21525. return true;
  21526. }
  21527. static bool function__repr__(int argc, py_Ref argv) {
  21528. // <function f at 0x10365b9c0>
  21529. PY_CHECK_ARGC(1);
  21530. Function* func = py_touserdata(py_arg(0));
  21531. c11_sbuf buf;
  21532. c11_sbuf__ctor(&buf);
  21533. c11_sbuf__write_cstr(&buf, "<function ");
  21534. c11_sbuf__write_cstr(&buf, func->decl->code.name->data);
  21535. c11_sbuf__write_cstr(&buf, " at ");
  21536. c11_sbuf__write_ptr(&buf, func);
  21537. c11_sbuf__write_char(&buf, '>');
  21538. c11_sbuf__py_submit(&buf, py_retval());
  21539. return true;
  21540. }
  21541. py_Type pk_function__register() {
  21542. py_Type type =
  21543. pk_newtype("function", tp_object, NULL, (void (*)(void*))Function__dtor, false, true);
  21544. py_bindproperty(type, "__doc__", function__doc__, NULL);
  21545. py_bindproperty(type, "__name__", function__name__, NULL);
  21546. py_bindmagic(type, __repr__, function__repr__);
  21547. return type;
  21548. }
  21549. static bool nativefunc__repr__(int argc, py_Ref argv) {
  21550. PY_CHECK_ARGC(1);
  21551. py_newstr(py_retval(), "<nativefunc object>");
  21552. return true;
  21553. }
  21554. py_Type pk_nativefunc__register() {
  21555. py_Type type = pk_newtype("nativefunc", tp_object, NULL, NULL, false, true);
  21556. py_bindmagic(type, __repr__, nativefunc__repr__);
  21557. return type;
  21558. }
  21559. static bool super__new__(int argc, py_Ref argv) {
  21560. py_Type class_arg = 0;
  21561. py_Frame* frame = pk_current_vm->top_frame;
  21562. py_Ref self_arg = NULL;
  21563. if(argc == 1) {
  21564. // super()
  21565. if(!frame->is_locals_special) {
  21566. py_TValue* callable = frame->p0;
  21567. if(callable->type == tp_boundmethod) callable = py_getslot(frame->p0, 1);
  21568. if(callable->type == tp_function) {
  21569. Function* func = py_touserdata(callable);
  21570. if(func->clazz != NULL) {
  21571. class_arg = ((py_TypeInfo*)PyObject__userdata(func->clazz))->index;
  21572. if(frame->co->nlocals > 0) { self_arg = &frame->locals[0]; }
  21573. }
  21574. }
  21575. }
  21576. if(class_arg == 0 || self_arg == NULL) return RuntimeError("super(): no arguments");
  21577. if(self_arg->type == tp_type) {
  21578. // f(cls, ...)
  21579. class_arg = pk_typeinfo(class_arg)->base;
  21580. if(class_arg == 0) return RuntimeError("super(): base class is invalid");
  21581. py_assign(py_retval(), py_tpobject(class_arg));
  21582. return true;
  21583. }
  21584. } else if(argc == 3) {
  21585. // super(type[T], obj)
  21586. PY_CHECK_ARG_TYPE(1, tp_type);
  21587. class_arg = py_totype(py_arg(1));
  21588. self_arg = py_arg(2);
  21589. if(!py_isinstance(self_arg, class_arg)) {
  21590. return TypeError("super(type, obj): obj must be an instance of type");
  21591. }
  21592. } else {
  21593. return TypeError("super() takes 0 or 2 arguments");
  21594. }
  21595. class_arg = pk_typeinfo(class_arg)->base;
  21596. if(class_arg == 0) return RuntimeError("super(): base class is invalid");
  21597. py_Type* p_class_arg = py_newobject(py_retval(), tp_super, 1, sizeof(py_Type));
  21598. *p_class_arg = class_arg;
  21599. py_setslot(py_retval(), 0, self_arg);
  21600. return true;
  21601. }
  21602. py_Type pk_super__register() {
  21603. py_Type type = pk_newtype("super", tp_object, NULL, NULL, false, true);
  21604. py_bindmagic(type, __new__, super__new__);
  21605. return type;
  21606. }
  21607. // src/modules\colorcvt.c
  21608. // https://bottosson.github.io/posts/gamutclipping/#oklab-to-linear-srgb-conversion
  21609. // clang-format off
  21610. static c11_vec3 linear_srgb_to_oklab(c11_vec3 c)
  21611. {
  21612. double l = 0.4122214708 * c.x + 0.5363325363 * c.y + 0.0514459929 * c.z;
  21613. double m = 0.2119034982 * c.x + 0.6806995451 * c.y + 0.1073969566 * c.z;
  21614. double s = 0.0883024619 * c.x + 0.2817188376 * c.y + 0.6299787005 * c.z;
  21615. double l_ = dmath_cbrt(l);
  21616. double m_ = dmath_cbrt(m);
  21617. double s_ = dmath_cbrt(s);
  21618. return (c11_vec3){{
  21619. 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
  21620. 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
  21621. 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
  21622. }};
  21623. }
  21624. static c11_vec3 oklab_to_linear_srgb(c11_vec3 c)
  21625. {
  21626. double l_ = c.x + 0.3963377774 * c.y + 0.2158037573 * c.z;
  21627. double m_ = c.x - 0.1055613458 * c.y - 0.0638541728 * c.z;
  21628. double s_ = c.x - 0.0894841775 * c.y - 1.2914855480 * c.z;
  21629. double l = l_ * l_ * l_;
  21630. double m = m_ * m_ * m_;
  21631. double s = s_ * s_ * s_;
  21632. return (c11_vec3){{
  21633. +4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s,
  21634. -1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s,
  21635. -0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s,
  21636. }};
  21637. }
  21638. // clang-format on
  21639. static double _gamma_correct_inv(double x) {
  21640. return (x <= 0.04045) ? (x / 12.92) : dmath_pow((x + 0.055) / 1.055, 2.4);
  21641. }
  21642. static double _gamma_correct(double x) {
  21643. return (x <= 0.0031308) ? (12.92 * x) : (1.055 * dmath_pow(x, 1.0 / 2.4) - 0.055);
  21644. }
  21645. static c11_vec3 srgb_to_linear_srgb(c11_vec3 c) {
  21646. c.x = _gamma_correct_inv(c.x);
  21647. c.y = _gamma_correct_inv(c.y);
  21648. c.z = _gamma_correct_inv(c.z);
  21649. return c;
  21650. }
  21651. static c11_vec3 linear_srgb_to_srgb(c11_vec3 c) {
  21652. c.x = _gamma_correct(c.x);
  21653. c.y = _gamma_correct(c.y);
  21654. c.z = _gamma_correct(c.z);
  21655. return c;
  21656. }
  21657. static c11_vec3 _oklab_to_oklch(c11_vec3 c) {
  21658. c11_vec3 res;
  21659. res.x = c.x;
  21660. res.y = dmath_sqrt(c.y * c.y + c.z * c.z);
  21661. res.z = dmath_fmod(dmath_atan2(c.z, c.y), 2 * DMATH_PI);
  21662. res.z = res.z * DMATH_RAD2DEG;
  21663. return res;
  21664. }
  21665. static c11_vec3 _oklch_to_oklab(c11_vec3 c) {
  21666. c11_vec3 res;
  21667. res.x = c.x;
  21668. res.y = c.y * dmath_cos(c.z * DMATH_DEG2RAD);
  21669. res.z = c.y * dmath_sin(c.z * DMATH_DEG2RAD);
  21670. return res;
  21671. }
  21672. static c11_vec3 linear_srgb_to_oklch(c11_vec3 c) {
  21673. return _oklab_to_oklch(linear_srgb_to_oklab(c));
  21674. }
  21675. static bool _is_valid_srgb(c11_vec3 c) {
  21676. return c.x >= 0.0f && c.x <= 1.0f && c.y >= 0.0f && c.y <= 1.0f && c.z >= 0.0f && c.z <= 1.0f;
  21677. }
  21678. static c11_vec3 oklch_to_linear_srgb(c11_vec3 c) {
  21679. c11_vec3 candidate = oklab_to_linear_srgb(_oklch_to_oklab(c));
  21680. if(_is_valid_srgb(candidate)) return candidate;
  21681. // try with chroma = 0
  21682. c11_vec3 clamped = {
  21683. {c.x, 0.0f, c.z}
  21684. };
  21685. // if not even chroma = 0 is displayable
  21686. // fall back to RGB clamping
  21687. candidate = oklab_to_linear_srgb(_oklch_to_oklab(clamped));
  21688. if(!_is_valid_srgb(candidate)) {
  21689. candidate.x = dmath_fmax(0.0, dmath_fmin(1.0, candidate.x));
  21690. candidate.y = dmath_fmax(0.0, dmath_fmin(1.0, candidate.y));
  21691. candidate.z = dmath_fmax(0.0, dmath_fmin(1.0, candidate.z));
  21692. return candidate;
  21693. }
  21694. // By this time we know chroma = 0 is displayable and our current chroma is not.
  21695. // Find the displayable chroma through the bisection method.
  21696. float start = 0.0f;
  21697. float end = c.y;
  21698. float range[2] = {0.0f, 0.4f};
  21699. float resolution = (range[1] - range[0]) / dmath_pow(2, 13);
  21700. float _last_good_c = clamped.y;
  21701. while(end - start > resolution) {
  21702. clamped.y = start + (end - start) * 0.5f;
  21703. candidate = oklab_to_linear_srgb(_oklch_to_oklab(clamped));
  21704. if(_is_valid_srgb(candidate)) {
  21705. _last_good_c = clamped.y;
  21706. start = clamped.y;
  21707. } else {
  21708. end = clamped.y;
  21709. }
  21710. }
  21711. candidate = oklab_to_linear_srgb(_oklch_to_oklab(clamped));
  21712. if(_is_valid_srgb(candidate)) return candidate;
  21713. clamped.y = _last_good_c;
  21714. return oklab_to_linear_srgb(_oklch_to_oklab(clamped));
  21715. }
  21716. // https://github.com/python/cpython/blob/3.13/Lib/colorsys.py
  21717. static c11_vec3 srgb_to_hsv(c11_vec3 c) {
  21718. float r = c.x;
  21719. float g = c.y;
  21720. float b = c.z;
  21721. float maxc = dmath_fmax(r, dmath_fmax(g, b));
  21722. float minc = dmath_fmin(r, dmath_fmin(g, b));
  21723. float v = maxc;
  21724. if(minc == maxc) {
  21725. return (c11_vec3){
  21726. {0.0f, 0.0f, v}
  21727. };
  21728. }
  21729. float s = (maxc - minc) / maxc;
  21730. float rc = (maxc - r) / (maxc - minc);
  21731. float gc = (maxc - g) / (maxc - minc);
  21732. float bc = (maxc - b) / (maxc - minc);
  21733. float h;
  21734. if(r == maxc) {
  21735. h = bc - gc;
  21736. } else if(g == maxc) {
  21737. h = 2.0f + rc - bc;
  21738. } else {
  21739. h = 4.0f + gc - rc;
  21740. }
  21741. h = dmath_fmod(h / 6.0, 1.0);
  21742. return (c11_vec3){
  21743. {h, s, v}
  21744. };
  21745. }
  21746. static c11_vec3 hsv_to_srgb(c11_vec3 c) {
  21747. float h = c.x;
  21748. float s = c.y;
  21749. float v = c.z;
  21750. if(s == 0.0f) {
  21751. return (c11_vec3){
  21752. {v, v, v}
  21753. };
  21754. }
  21755. int i = (int)(h * 6.0f);
  21756. float f = (h * 6.0f) - i;
  21757. float p = v * (1.0f - s);
  21758. float q = v * (1.0f - s * f);
  21759. float t = v * (1.0f - s * (1.0f - f));
  21760. i = i % 6;
  21761. switch(i) {
  21762. // clang-format off
  21763. case 0: return (c11_vec3){{v, t, p}};
  21764. case 1: return (c11_vec3){{q, v, p}};
  21765. case 2: return (c11_vec3){{p, v, t}};
  21766. case 3: return (c11_vec3){{p, q, v}};
  21767. case 4: return (c11_vec3){{t, p, v}};
  21768. case 5: return (c11_vec3){{v, p, q}};
  21769. // clang-format on
  21770. default: c11__unreachable();
  21771. }
  21772. }
  21773. #define DEF_VEC3_WRAPPER(F) \
  21774. static bool colorcvt_##F(int argc, py_Ref argv); \
  21775. static bool colorcvt_##F(int argc, py_Ref argv) { \
  21776. PY_CHECK_ARGC(1); \
  21777. PY_CHECK_ARG_TYPE(0, tp_vec3); \
  21778. c11_vec3 c = py_tovec3(argv); \
  21779. py_newvec3(py_retval(), F(c)); \
  21780. return true; \
  21781. }
  21782. DEF_VEC3_WRAPPER(linear_srgb_to_srgb)
  21783. DEF_VEC3_WRAPPER(srgb_to_linear_srgb)
  21784. DEF_VEC3_WRAPPER(srgb_to_hsv)
  21785. DEF_VEC3_WRAPPER(hsv_to_srgb)
  21786. DEF_VEC3_WRAPPER(oklch_to_linear_srgb)
  21787. DEF_VEC3_WRAPPER(linear_srgb_to_oklch)
  21788. void pk__add_module_colorcvt() {
  21789. py_Ref mod = py_newmodule("colorcvt");
  21790. py_bindfunc(mod, "linear_srgb_to_srgb", colorcvt_linear_srgb_to_srgb);
  21791. py_bindfunc(mod, "srgb_to_linear_srgb", colorcvt_srgb_to_linear_srgb);
  21792. py_bindfunc(mod, "srgb_to_hsv", colorcvt_srgb_to_hsv);
  21793. py_bindfunc(mod, "hsv_to_srgb", colorcvt_hsv_to_srgb);
  21794. py_bindfunc(mod, "oklch_to_linear_srgb", colorcvt_oklch_to_linear_srgb);
  21795. py_bindfunc(mod, "linear_srgb_to_oklch", colorcvt_linear_srgb_to_oklch);
  21796. }
  21797. #undef DEF_VEC3_WRAPPER
  21798. // src/modules\conio.c
  21799. #if PY_SYS_PLATFORM == 0
  21800. #define WIN32_LEAN_AND_MEAN
  21801. #include <windows.h>
  21802. #include <conio.h>
  21803. #undef WIN32_LEAN_AND_MEAN
  21804. #elif PY_SYS_PLATFORM == 3 || PY_SYS_PLATFORM == 5
  21805. #include <stdio.h>
  21806. #include <unistd.h>
  21807. #include <termios.h>
  21808. #include <fcntl.h>
  21809. #include <string.h>
  21810. // 保存原始终端设置
  21811. static struct termios orig_termios;
  21812. static bool orig_termios_set;
  21813. // 还原终端设置
  21814. static void reset_terminal_mode() { tcsetattr(0, TCSANOW, &orig_termios); }
  21815. // 设置终端为非阻塞模式
  21816. static void set_conio_terminal_mode_if_needed() {
  21817. if(orig_termios_set) return;
  21818. struct termios new_termios;
  21819. // 获取当前终端设置
  21820. tcgetattr(0, &orig_termios);
  21821. memcpy(&new_termios, &orig_termios, sizeof(new_termios));
  21822. // 禁用缓冲和回显
  21823. new_termios.c_lflag &= ~(ICANON | ECHO);
  21824. tcsetattr(0, TCSANOW, &new_termios);
  21825. atexit(reset_terminal_mode);
  21826. orig_termios_set = true;
  21827. }
  21828. // 检查是否有按键按下
  21829. int _kbhit() {
  21830. set_conio_terminal_mode_if_needed();
  21831. struct termios term;
  21832. int oldf;
  21833. int ch;
  21834. int old_flags;
  21835. // 获取终端设置
  21836. tcgetattr(0, &term);
  21837. oldf = term.c_lflag;
  21838. term.c_lflag &= ~(ICANON | ECHO);
  21839. tcsetattr(0, TCSANOW, &term);
  21840. // 设置文件描述符为非阻塞
  21841. old_flags = fcntl(STDIN_FILENO, F_GETFL, 0);
  21842. fcntl(STDIN_FILENO, F_SETFL, old_flags | O_NONBLOCK);
  21843. // 检查是否有输入
  21844. ch = getchar();
  21845. // 还原文件描述符设置
  21846. fcntl(STDIN_FILENO, F_SETFL, old_flags);
  21847. // 还原终端设置
  21848. term.c_lflag = oldf;
  21849. tcsetattr(0, TCSANOW, &term);
  21850. if(ch != EOF) {
  21851. ungetc(ch, stdin);
  21852. return 1;
  21853. }
  21854. return 0;
  21855. }
  21856. // 获取一个字符
  21857. int _getch() {
  21858. set_conio_terminal_mode_if_needed();
  21859. int ch;
  21860. struct termios oldt, newt;
  21861. // 获取当前终端设置
  21862. tcgetattr(STDIN_FILENO, &oldt);
  21863. newt = oldt;
  21864. // 禁用缓冲和回显
  21865. newt.c_lflag &= ~(ICANON | ECHO);
  21866. tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  21867. // 读取字符
  21868. ch = getchar();
  21869. // 还原终端设置
  21870. tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  21871. return ch;
  21872. }
  21873. #endif
  21874. #if PK_IS_DESKTOP_PLATFORM && PK_ENABLE_OS
  21875. static bool conio_kbhit(int argc, py_Ref argv) {
  21876. PY_CHECK_ARGC(0);
  21877. int ret = _kbhit();
  21878. py_newint(py_retval(), ret);
  21879. return true;
  21880. }
  21881. static bool conio_getch(int argc, py_Ref argv) {
  21882. PY_CHECK_ARGC(0);
  21883. int ret = _getch();
  21884. py_newint(py_retval(), ret);
  21885. return true;
  21886. }
  21887. void pk__add_module_conio() {
  21888. py_Ref mod = py_newmodule("conio");
  21889. py_bindfunc(mod, "_kbhit", conio_kbhit);
  21890. py_bindfunc(mod, "_getch", conio_getch);
  21891. }
  21892. #else
  21893. void pk__add_module_conio() {}
  21894. #endif
  21895. // src/modules\dis.c
  21896. #include <stdbool.h>
  21897. static bool disassemble(CodeObject* co) {
  21898. c11_vector /*T=int*/ jumpTargets;
  21899. c11_vector__ctor(&jumpTargets, sizeof(int));
  21900. for(int i = 0; i < co->codes.length; i++) {
  21901. Bytecode* bc = c11__at(Bytecode, &co->codes, i);
  21902. if(Bytecode__is_forward_jump(bc)) {
  21903. int target = (int16_t)bc->arg + i;
  21904. c11_vector__push(int, &jumpTargets, target);
  21905. }
  21906. }
  21907. c11_sbuf ss;
  21908. c11_sbuf__ctor(&ss);
  21909. int prev_line = -1;
  21910. for(int i = 0; i < co->codes.length; i++) {
  21911. Bytecode byte = c11__getitem(Bytecode, &co->codes, i);
  21912. BytecodeEx ex = c11__getitem(BytecodeEx, &co->codes_ex, i);
  21913. char line[8] = "";
  21914. if(ex.lineno == prev_line) {
  21915. // do nothing
  21916. } else {
  21917. snprintf(line, sizeof(line), "%d", ex.lineno);
  21918. if(prev_line != -1) c11_sbuf__write_char(&ss, '\n');
  21919. prev_line = ex.lineno;
  21920. }
  21921. char pointer[4] = "";
  21922. c11__foreach(int, &jumpTargets, it) {
  21923. if(*it == i) {
  21924. snprintf(pointer, sizeof(pointer), "->");
  21925. break;
  21926. }
  21927. }
  21928. char buf[32];
  21929. snprintf(buf, sizeof(buf), "%-8s%-3s%-3d ", line, pointer, i);
  21930. c11_sbuf__write_cstr(&ss, buf);
  21931. c11_sbuf__write_cstr(&ss, pk_opname(byte.op));
  21932. c11_sbuf__write_char(&ss, ' ');
  21933. int padding = 24 - strlen(pk_opname(byte.op));
  21934. for(int j = 0; j < padding; j++)
  21935. c11_sbuf__write_char(&ss, ' ');
  21936. do {
  21937. if(Bytecode__is_forward_jump(&byte)) {
  21938. pk_sprintf(&ss, "%d (to %d)", (int16_t)byte.arg, (int16_t)byte.arg + i);
  21939. break;
  21940. }
  21941. c11_sbuf__write_int(&ss, byte.arg);
  21942. switch(byte.op) {
  21943. case OP_LOAD_CONST: {
  21944. py_Ref value = c11__at(py_TValue, &co->consts, byte.arg);
  21945. if(py_repr(value)) {
  21946. pk_sprintf(&ss, " (%v)", py_tosv(py_retval()));
  21947. } else {
  21948. return false;
  21949. }
  21950. break;
  21951. }
  21952. case OP_FORMAT_STRING:
  21953. case OP_IMPORT_PATH: {
  21954. py_Ref path = c11__at(py_TValue, &co->consts, byte.arg);
  21955. pk_sprintf(&ss, " (%q)", py_tosv(path));
  21956. break;
  21957. }
  21958. case OP_LOAD_NAME: case OP_LOAD_NAME_AS_INT:
  21959. case OP_LOAD_GLOBAL:
  21960. case OP_LOAD_NONLOCAL:
  21961. case OP_STORE_GLOBAL:
  21962. case OP_LOAD_ATTR:
  21963. case OP_LOAD_SELF_ATTR:
  21964. case OP_LOAD_METHOD:
  21965. case OP_STORE_ATTR:
  21966. case OP_STORE_SELF_ATTR:
  21967. case OP_DELETE_ATTR:
  21968. case OP_BEGIN_CLASS:
  21969. case OP_DELETE_GLOBAL:
  21970. case OP_STORE_CLASS_ATTR: {
  21971. py_Name name = c11__getitem(py_Name, &co->names, byte.arg);
  21972. pk_sprintf(&ss, " (%n)", name);
  21973. break;
  21974. }
  21975. case OP_LOAD_FAST:
  21976. case OP_STORE_FAST:
  21977. case OP_DELETE_FAST: {
  21978. py_Name name = c11__getitem(py_Name, &co->varnames, byte.arg);
  21979. pk_sprintf(&ss, " (%n)", name);
  21980. break;
  21981. }
  21982. case OP_LOAD_FUNCTION: {
  21983. const FuncDecl* decl = c11__getitem(FuncDecl*, &co->func_decls, byte.arg);
  21984. pk_sprintf(&ss, " (%s)", decl->code.name->data);
  21985. break;
  21986. }
  21987. #define CASE_BINARY_OP(label, op, rop) \
  21988. case label: { \
  21989. pk_sprintf(&ss, " (%s)", pk_op2str(op)); \
  21990. break; \
  21991. }
  21992. CASE_BINARY_OP(OP_BINARY_ADD, __add__, __radd__)
  21993. CASE_BINARY_OP(OP_BINARY_SUB, __sub__, __rsub__)
  21994. CASE_BINARY_OP(OP_BINARY_MUL, __mul__, __rmul__)
  21995. CASE_BINARY_OP(OP_BINARY_TRUEDIV, __truediv__, __rtruediv__)
  21996. CASE_BINARY_OP(OP_BINARY_FLOORDIV, __floordiv__, __rfloordiv__)
  21997. CASE_BINARY_OP(OP_BINARY_MOD, __mod__, __rmod__)
  21998. CASE_BINARY_OP(OP_BINARY_POW, __pow__, __rpow__)
  21999. CASE_BINARY_OP(OP_BINARY_LSHIFT, __lshift__, 0)
  22000. CASE_BINARY_OP(OP_BINARY_RSHIFT, __rshift__, 0)
  22001. CASE_BINARY_OP(OP_BINARY_AND, __and__, 0)
  22002. CASE_BINARY_OP(OP_BINARY_OR, __or__, 0)
  22003. CASE_BINARY_OP(OP_BINARY_XOR, __xor__, 0)
  22004. CASE_BINARY_OP(OP_BINARY_MATMUL, __matmul__, 0)
  22005. CASE_BINARY_OP(OP_COMPARE_LT, __lt__, __gt__)
  22006. CASE_BINARY_OP(OP_COMPARE_LE, __le__, __ge__)
  22007. CASE_BINARY_OP(OP_COMPARE_EQ, __eq__, __eq__)
  22008. CASE_BINARY_OP(OP_COMPARE_NE, __ne__, __ne__)
  22009. CASE_BINARY_OP(OP_COMPARE_GT, __gt__, __lt__)
  22010. CASE_BINARY_OP(OP_COMPARE_GE, __ge__, __le__)
  22011. #undef CASE_BINARY_OP
  22012. }
  22013. } while(0);
  22014. if(i != co->codes.length - 1) c11_sbuf__write_char(&ss, '\n');
  22015. }
  22016. c11_string* output = c11_sbuf__submit(&ss);
  22017. pk_current_vm->callbacks.print(output->data);
  22018. pk_current_vm->callbacks.print("\n");
  22019. c11_string__delete(output);
  22020. c11_vector__dtor(&jumpTargets);
  22021. return true;
  22022. }
  22023. static bool dis_dis(int argc, py_Ref argv) {
  22024. PY_CHECK_ARGC(1);
  22025. CodeObject* code = NULL;
  22026. if(py_istype(argv, tp_function)) {
  22027. Function* ud = py_touserdata(argv);
  22028. code = &ud->decl->code;
  22029. } else if(py_istype(argv, tp_code)) {
  22030. code = py_touserdata(argv);
  22031. } else {
  22032. return TypeError("dis() expected a code object");
  22033. }
  22034. if(!disassemble(code)) return false;
  22035. py_newnone(py_retval());
  22036. return true;
  22037. }
  22038. void pk__add_module_dis() {
  22039. py_Ref mod = py_newmodule("dis");
  22040. py_bindfunc(mod, "dis", dis_dis);
  22041. }
  22042. // src/modules\easing.c
  22043. // https://easings.net/
  22044. const double kPi = DMATH_PI;
  22045. static double easeLinear(double x) { return x; }
  22046. static double easeInSine(double x) { return 1.0 - dmath_cos(x * kPi / 2); }
  22047. static double easeOutSine(double x) { return dmath_sin(x * kPi / 2); }
  22048. static double easeInOutSine(double x) { return -(dmath_cos(kPi * x) - 1) / 2; }
  22049. static double easeInQuad(double x) { return x * x; }
  22050. static double easeOutQuad(double x) { return 1 - dmath_pow(1 - x, 2); }
  22051. static double easeInOutQuad(double x) {
  22052. if(x < 0.5) {
  22053. return 2 * x * x;
  22054. } else {
  22055. return 1 - dmath_pow(-2 * x + 2, 2) / 2;
  22056. }
  22057. }
  22058. static double easeInCubic(double x) { return x * x * x; }
  22059. static double easeOutCubic(double x) { return 1 - dmath_pow(1 - x, 3); }
  22060. static double easeInOutCubic(double x) {
  22061. if(x < 0.5) {
  22062. return 4 * x * x * x;
  22063. } else {
  22064. return 1 - dmath_pow(-2 * x + 2, 3) / 2;
  22065. }
  22066. }
  22067. static double easeInQuart(double x) { return dmath_pow(x, 4); }
  22068. static double easeOutQuart(double x) { return 1 - dmath_pow(1 - x, 4); }
  22069. static double easeInOutQuart(double x) {
  22070. if(x < 0.5) {
  22071. return 8 * dmath_pow(x, 4);
  22072. } else {
  22073. return 1 - dmath_pow(-2 * x + 2, 4) / 2;
  22074. }
  22075. }
  22076. static double easeInQuint(double x) { return dmath_pow(x, 5); }
  22077. static double easeOutQuint(double x) { return 1 - dmath_pow(1 - x, 5); }
  22078. static double easeInOutQuint(double x) {
  22079. if(x < 0.5) {
  22080. return 16 * dmath_pow(x, 5);
  22081. } else {
  22082. return 1 - dmath_pow(-2 * x + 2, 5) / 2;
  22083. }
  22084. }
  22085. static double easeInExpo(double x) { return x == 0 ? 0 : dmath_pow(2, 10 * x - 10); }
  22086. static double easeOutExpo(double x) { return x == 1 ? 1 : 1 - dmath_pow(2, -10 * x); }
  22087. static double easeInOutExpo(double x) {
  22088. if(x == 0) {
  22089. return 0;
  22090. } else if(x == 1) {
  22091. return 1;
  22092. } else if(x < 0.5) {
  22093. return dmath_pow(2, 20 * x - 10) / 2;
  22094. } else {
  22095. return (2 - dmath_pow(2, -20 * x + 10)) / 2;
  22096. }
  22097. }
  22098. static double easeInCirc(double x) { return 1 - dmath_sqrt(1 - dmath_pow(x, 2)); }
  22099. static double easeOutCirc(double x) { return dmath_sqrt(1 - dmath_pow(x - 1, 2)); }
  22100. static double easeInOutCirc(double x) {
  22101. if(x < 0.5) {
  22102. return (1 - dmath_sqrt(1 - dmath_pow(2 * x, 2))) / 2;
  22103. } else {
  22104. return (dmath_sqrt(1 - dmath_pow(-2 * x + 2, 2)) + 1) / 2;
  22105. }
  22106. }
  22107. static double easeInBack(double x) {
  22108. const double c1 = 1.70158;
  22109. const double c3 = c1 + 1;
  22110. return c3 * x * x * x - c1 * x * x;
  22111. }
  22112. static double easeOutBack(double x) {
  22113. const double c1 = 1.70158;
  22114. const double c3 = c1 + 1;
  22115. return 1 + c3 * dmath_pow(x - 1, 3) + c1 * dmath_pow(x - 1, 2);
  22116. }
  22117. static double easeInOutBack(double x) {
  22118. const double c1 = 1.70158;
  22119. const double c2 = c1 * 1.525;
  22120. if(x < 0.5) {
  22121. return (dmath_pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2;
  22122. } else {
  22123. return (dmath_pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2;
  22124. }
  22125. }
  22126. static double easeInElastic(double x) {
  22127. const double c4 = (2 * kPi) / 3;
  22128. if(x == 0) {
  22129. return 0;
  22130. } else if(x == 1) {
  22131. return 1;
  22132. } else {
  22133. return -dmath_pow(2, 10 * x - 10) * dmath_sin((x * 10 - 10.75) * c4);
  22134. }
  22135. }
  22136. static double easeOutElastic(double x) {
  22137. const double c4 = (2 * kPi) / 3;
  22138. if(x == 0) {
  22139. return 0;
  22140. } else if(x == 1) {
  22141. return 1;
  22142. } else {
  22143. return dmath_pow(2, -10 * x) * dmath_sin((x * 10 - 0.75) * c4) + 1;
  22144. }
  22145. }
  22146. static double easeInOutElastic(double x) {
  22147. const double c5 = (2 * kPi) / 4.5;
  22148. if(x == 0) {
  22149. return 0;
  22150. } else if(x == 1) {
  22151. return 1;
  22152. } else if(x < 0.5) {
  22153. return -(dmath_pow(2, 20 * x - 10) * dmath_sin((20 * x - 11.125) * c5)) / 2;
  22154. } else {
  22155. return (dmath_pow(2, -20 * x + 10) * dmath_sin((20 * x - 11.125) * c5)) / 2 + 1;
  22156. }
  22157. }
  22158. static double easeOutBounce(double x) {
  22159. const double n1 = 7.5625;
  22160. const double d1 = 2.75;
  22161. if(x < 1 / d1) {
  22162. return n1 * x * x;
  22163. } else if(x < 2 / d1) {
  22164. x -= 1.5 / d1;
  22165. return n1 * x * x + 0.75;
  22166. } else if(x < 2.5 / d1) {
  22167. x -= 2.25 / d1;
  22168. return n1 * x * x + 0.9375;
  22169. } else {
  22170. x -= 2.625 / d1;
  22171. return n1 * x * x + 0.984375;
  22172. }
  22173. }
  22174. static double easeInBounce(double x) { return 1 - easeOutBounce(1 - x); }
  22175. static double easeInOutBounce(double x) {
  22176. return x < 0.5 ? (1 - easeOutBounce(1 - 2 * x)) / 2 : (1 + easeOutBounce(2 * x - 1)) / 2;
  22177. }
  22178. #define DEF_EASE(name) \
  22179. static bool easing_##name(int argc, py_Ref argv) { \
  22180. PY_CHECK_ARGC(1); \
  22181. py_f64 t; \
  22182. if(!py_castfloat(argv, &t)) return false; \
  22183. py_newfloat(py_retval(), ease##name(t)); \
  22184. return true; \
  22185. }
  22186. DEF_EASE(Linear)
  22187. DEF_EASE(InSine)
  22188. DEF_EASE(OutSine)
  22189. DEF_EASE(InOutSine)
  22190. DEF_EASE(InQuad)
  22191. DEF_EASE(OutQuad)
  22192. DEF_EASE(InOutQuad)
  22193. DEF_EASE(InCubic)
  22194. DEF_EASE(OutCubic)
  22195. DEF_EASE(InOutCubic)
  22196. DEF_EASE(InQuart)
  22197. DEF_EASE(OutQuart)
  22198. DEF_EASE(InOutQuart)
  22199. DEF_EASE(InQuint)
  22200. DEF_EASE(OutQuint)
  22201. DEF_EASE(InOutQuint)
  22202. DEF_EASE(InExpo)
  22203. DEF_EASE(OutExpo)
  22204. DEF_EASE(InOutExpo)
  22205. DEF_EASE(InCirc)
  22206. DEF_EASE(OutCirc)
  22207. DEF_EASE(InOutCirc)
  22208. DEF_EASE(InBack)
  22209. DEF_EASE(OutBack)
  22210. DEF_EASE(InOutBack)
  22211. DEF_EASE(InElastic)
  22212. DEF_EASE(OutElastic)
  22213. DEF_EASE(InOutElastic)
  22214. DEF_EASE(InBounce)
  22215. DEF_EASE(OutBounce)
  22216. DEF_EASE(InOutBounce)
  22217. #undef DEF_EASE
  22218. void pk__add_module_easing() {
  22219. py_GlobalRef mod = py_newmodule("easing");
  22220. py_bindfunc(mod, "Linear", easing_Linear);
  22221. py_bindfunc(mod, "InSine", easing_InSine);
  22222. py_bindfunc(mod, "OutSine", easing_OutSine);
  22223. py_bindfunc(mod, "InOutSine", easing_InOutSine);
  22224. py_bindfunc(mod, "InQuad", easing_InQuad);
  22225. py_bindfunc(mod, "OutQuad", easing_OutQuad);
  22226. py_bindfunc(mod, "InOutQuad", easing_InOutQuad);
  22227. py_bindfunc(mod, "InCubic", easing_InCubic);
  22228. py_bindfunc(mod, "OutCubic", easing_OutCubic);
  22229. py_bindfunc(mod, "InOutCubic", easing_InOutCubic);
  22230. py_bindfunc(mod, "InQuart", easing_InQuart);
  22231. py_bindfunc(mod, "OutQuart", easing_OutQuart);
  22232. py_bindfunc(mod, "InOutQuart", easing_InOutQuart);
  22233. py_bindfunc(mod, "InQuint", easing_InQuint);
  22234. py_bindfunc(mod, "OutQuint", easing_OutQuint);
  22235. py_bindfunc(mod, "InOutQuint", easing_InOutQuint);
  22236. py_bindfunc(mod, "InExpo", easing_InExpo);
  22237. py_bindfunc(mod, "OutExpo", easing_OutExpo);
  22238. py_bindfunc(mod, "InOutExpo", easing_InOutExpo);
  22239. py_bindfunc(mod, "InCirc", easing_InCirc);
  22240. py_bindfunc(mod, "OutCirc", easing_OutCirc);
  22241. py_bindfunc(mod, "InOutCirc", easing_InOutCirc);
  22242. py_bindfunc(mod, "InBack", easing_InBack);
  22243. py_bindfunc(mod, "OutBack", easing_OutBack);
  22244. py_bindfunc(mod, "InOutBack", easing_InOutBack);
  22245. py_bindfunc(mod, "InElastic", easing_InElastic);
  22246. py_bindfunc(mod, "OutElastic", easing_OutElastic);
  22247. py_bindfunc(mod, "InOutElastic", easing_InOutElastic);
  22248. py_bindfunc(mod, "InBounce", easing_InBounce);
  22249. py_bindfunc(mod, "OutBounce", easing_OutBounce);
  22250. py_bindfunc(mod, "InOutBounce", easing_InOutBounce);
  22251. }
  22252. // src/modules\enum.c
  22253. static bool Enum__wrapper_field(py_Name name, py_Ref value, void* ctx) {
  22254. c11_sv name_sv = py_name2sv(name);
  22255. if(name_sv.size == 0 || name_sv.data[0] == '_') return true;
  22256. py_push(ctx);
  22257. py_pushnil();
  22258. py_assign(py_pushtmp(), py_name2ref(name));
  22259. py_push(value);
  22260. bool ok = py_vectorcall(2, 0);
  22261. if(!ok) return false;
  22262. py_assign(value, py_retval());
  22263. return true;
  22264. }
  22265. static void Enum__on_end_subclass(py_TypeInfo* derived_ti) {
  22266. derived_ti->is_final = true;
  22267. py_applydict(&derived_ti->self, Enum__wrapper_field, &derived_ti->self);
  22268. }
  22269. static bool Enum__new__(int argc, py_Ref argv) {
  22270. py_newobject(py_retval(), py_totype(argv), 2, 0);
  22271. return true;
  22272. }
  22273. static bool Enum__init__(int argc, py_Ref argv) {
  22274. PY_CHECK_ARGC(3);
  22275. PY_CHECK_ARG_TYPE(1, tp_str);
  22276. py_setslot(argv, 0, py_arg(1));
  22277. py_setslot(argv, 1, py_arg(2));
  22278. py_newnone(py_retval());
  22279. return true;
  22280. }
  22281. static bool Enum__str__(int argc, py_Ref argv) {
  22282. PY_CHECK_ARGC(1);
  22283. // f'{type(self).__name__}.{self.name}'
  22284. c11_sbuf buf;
  22285. c11_sbuf__ctor(&buf);
  22286. c11_sbuf__write_cstr(&buf, py_tpname(argv->type));
  22287. c11_sbuf__write_char(&buf, '.');
  22288. c11_sbuf__write_cstr(&buf, py_tostr(py_getslot(argv, 0)));
  22289. c11_sbuf__py_submit(&buf, py_retval());
  22290. return true;
  22291. }
  22292. static bool Enum__repr__(int argc, py_Ref argv) {
  22293. PY_CHECK_ARGC(1);
  22294. // f'<{str(self)}: {self.value!r}>'
  22295. if(!py_str(argv)) return false;
  22296. py_push(py_retval()); // str(self)
  22297. if(!py_repr(py_getslot(argv, 1))) return false;
  22298. py_push(py_retval()); // repr(self.value)
  22299. c11_sbuf buf;
  22300. c11_sbuf__ctor(&buf);
  22301. c11_sbuf__write_cstr(&buf, "<");
  22302. c11_sbuf__write_cstr(&buf, py_tostr(py_peek(-2)));
  22303. c11_sbuf__write_cstr(&buf, ": ");
  22304. c11_sbuf__write_cstr(&buf, py_tostr(py_peek(-1)));
  22305. c11_sbuf__write_cstr(&buf, ">");
  22306. c11_sbuf__py_submit(&buf, py_retval());
  22307. py_shrink(2);
  22308. return true;
  22309. }
  22310. static bool Enum__name(int argc, py_Ref argv) {
  22311. py_assign(py_retval(), py_getslot(argv, 0));
  22312. return true;
  22313. }
  22314. static bool Enum__value(int argc, py_Ref argv) {
  22315. py_assign(py_retval(), py_getslot(argv, 1));
  22316. return true;
  22317. }
  22318. void pk__add_module_enum() {
  22319. py_Ref mod = py_newmodule("enum");
  22320. py_Type type = py_newtype("Enum", tp_object, mod, NULL);
  22321. py_bindmagic(type, __new__, Enum__new__);
  22322. py_bindmagic(type, __init__, Enum__init__);
  22323. py_bindmagic(type, __str__, Enum__str__);
  22324. py_bindmagic(type, __repr__, Enum__repr__);
  22325. py_bindproperty(type, "name", Enum__name, NULL);
  22326. py_bindproperty(type, "value", Enum__value, NULL);
  22327. pk_typeinfo(type)->on_end_subclass = Enum__on_end_subclass;
  22328. }
  22329. // src/modules\gc.c
  22330. static bool gc_enable(int argc, py_Ref argv) {
  22331. PY_CHECK_ARGC(0);
  22332. ManagedHeap* heap = &pk_current_vm->heap;
  22333. heap->gc_enabled = true;
  22334. py_newnone(py_retval());
  22335. return true;
  22336. }
  22337. static bool gc_disable(int argc, py_Ref argv) {
  22338. PY_CHECK_ARGC(0);
  22339. ManagedHeap* heap = &pk_current_vm->heap;
  22340. heap->gc_enabled = false;
  22341. py_newnone(py_retval());
  22342. return true;
  22343. }
  22344. static bool gc_isenabled(int argc, py_Ref argv) {
  22345. PY_CHECK_ARGC(0);
  22346. ManagedHeap* heap = &pk_current_vm->heap;
  22347. py_newbool(py_retval(), heap->gc_enabled);
  22348. return true;
  22349. }
  22350. static bool gc_collect(int argc, py_Ref argv) {
  22351. PY_CHECK_ARGC(0);
  22352. ManagedHeap* heap = &pk_current_vm->heap;
  22353. int freed = ManagedHeap__collect(heap);
  22354. py_newint(py_retval(), freed);
  22355. return true;
  22356. }
  22357. static bool gc_collect_hint(int argc, py_Ref argv) {
  22358. PY_CHECK_ARGC(0);
  22359. ManagedHeap* heap = &pk_current_vm->heap;
  22360. int freed = ManagedHeap__collect_hint(heap);
  22361. py_newint(py_retval(), freed);
  22362. return true;
  22363. }
  22364. static bool gc_setup_debug_callback(int argc, py_Ref argv) {
  22365. PY_CHECK_ARGC(1);
  22366. ManagedHeap* heap = &pk_current_vm->heap;
  22367. heap->debug_callback = *argv;
  22368. py_newnone(py_retval());
  22369. return true;
  22370. }
  22371. static bool gc_is_tracked(int argc, py_Ref argv) {
  22372. PY_CHECK_ARGC(1);
  22373. if(!argv->is_ptr) {
  22374. py_newbool(py_retval(), false);
  22375. return true;
  22376. }
  22377. bool res = !(argv->_obj->gc_marked & 0b10);
  22378. py_newbool(py_retval(), res);
  22379. return true;
  22380. }
  22381. static bool gc_track(int argc, py_Ref argv) {
  22382. PY_CHECK_ARGC(1);
  22383. if(!argv->is_ptr) return TypeError("gc.track() only accepts objects");
  22384. argv->_obj->gc_marked &= 0b01;
  22385. py_newnone(py_retval());
  22386. return true;
  22387. }
  22388. static bool gc_untrack(int argc, py_Ref argv) {
  22389. PY_CHECK_ARGC(1);
  22390. if(!argv->is_ptr) return TypeError("gc.untrack() only accepts objects");
  22391. argv->_obj->gc_marked |= 0b10;
  22392. py_newnone(py_retval());
  22393. return true;
  22394. }
  22395. void pk__add_module_gc() {
  22396. py_Ref mod = py_newmodule("gc");
  22397. py_bindfunc(mod, "enable", gc_enable);
  22398. py_bindfunc(mod, "disable", gc_disable);
  22399. py_bindfunc(mod, "isenabled", gc_isenabled);
  22400. py_bindfunc(mod, "collect", gc_collect);
  22401. py_bindfunc(mod, "collect_hint", gc_collect_hint);
  22402. py_bindfunc(mod, "setup_debug_callback", gc_setup_debug_callback);
  22403. py_bindfunc(mod, "is_tracked", gc_is_tracked);
  22404. py_bindfunc(mod, "track", gc_track);
  22405. py_bindfunc(mod, "untrack", gc_untrack);
  22406. }
  22407. // src/modules\importlib.c
  22408. static bool importlib_reload(int argc, py_Ref argv) {
  22409. PY_CHECK_ARGC(1);
  22410. PY_CHECK_ARG_TYPE(0, tp_module);
  22411. return py_importlib_reload(argv);
  22412. }
  22413. void pk__add_module_importlib() {
  22414. py_Ref mod = py_newmodule("importlib");
  22415. py_bindfunc(mod, "reload", importlib_reload);
  22416. }
  22417. // src/modules\inspect.c
  22418. static bool inspect_isgeneratorfunction(int argc, py_Ref argv) {
  22419. PY_CHECK_ARGC(1);
  22420. py_Ref obj = argv;
  22421. if(py_istype(argv, tp_boundmethod)) {
  22422. py_TValue* slots = PyObject__slots(argv->_obj);
  22423. obj = &slots[1]; // callable
  22424. }
  22425. if(py_istype(obj, tp_function)) {
  22426. Function* fn = py_touserdata(obj);
  22427. py_newbool(py_retval(), fn->decl->type == FuncType_GENERATOR);
  22428. } else {
  22429. py_newbool(py_retval(), false);
  22430. }
  22431. return true;
  22432. }
  22433. static bool inspect_is_user_defined_type(int argc, py_Ref argv) {
  22434. PY_CHECK_ARGC(1);
  22435. PY_CHECK_ARG_TYPE(0, tp_type);
  22436. py_TypeInfo* ti = py_touserdata(argv);
  22437. py_newbool(py_retval(), ti->is_python);
  22438. return true;
  22439. }
  22440. // Returns a tuple of (name, kind[, default]) entries.
  22441. static bool inspect__signature_data(int argc, py_Ref argv) {
  22442. PY_CHECK_ARGC(1);
  22443. if(!py_istype(argv, tp_function)) {
  22444. return ValueError("no signature found for '%t' object", argv->type);
  22445. }
  22446. Function* fn = py_touserdata(argv);
  22447. FuncDecl* decl = fn->decl;
  22448. const CodeObject* co = &decl->code;
  22449. bool has_starred_arg = decl->starred_arg != -1;
  22450. bool has_starred_kwarg = decl->starred_kwarg != -1;
  22451. int total = decl->args.length + decl->kwargs.length + (int)has_starred_arg +
  22452. (int)has_starred_kwarg;
  22453. py_TValue* items = py_newtuple(py_retval(), total);
  22454. int j = 0;
  22455. for(int i = 0; i < decl->args.length; i++) {
  22456. int32_t index = c11__getitem(int32_t, &decl->args, i);
  22457. py_Name name = c11__getitem(py_Name, &co->varnames, index);
  22458. py_TValue* entry = py_newtuple(&items[j++], 2);
  22459. py_newstr(&entry[0], py_name2str(name));
  22460. py_newint(&entry[1], 1);
  22461. }
  22462. if(has_starred_arg) {
  22463. py_Name name = c11__getitem(py_Name, &co->varnames, decl->starred_arg);
  22464. py_TValue* entry = py_newtuple(&items[j++], 2);
  22465. py_newstr(&entry[0], py_name2str(name));
  22466. py_newint(&entry[1], 2);
  22467. }
  22468. for(int i = 0; i < decl->kwargs.length; i++) {
  22469. FuncDeclKwArg kv = c11__getitem(FuncDeclKwArg, &decl->kwargs, i);
  22470. py_TValue* entry = py_newtuple(&items[j++], 3);
  22471. py_newstr(&entry[0], py_name2str(kv.key));
  22472. // defaults after *args can only be passed by keyword
  22473. py_newint(&entry[1], has_starred_arg ? 3 : 1);
  22474. entry[2] = kv.value;
  22475. }
  22476. if(has_starred_kwarg) {
  22477. py_Name name = c11__getitem(py_Name, &co->varnames, decl->starred_kwarg);
  22478. py_TValue* entry = py_newtuple(&items[j++], 2);
  22479. py_newstr(&entry[0], py_name2str(name));
  22480. py_newint(&entry[1], 4);
  22481. }
  22482. return true;
  22483. }
  22484. void pk__add_module_inspect() {
  22485. py_Ref mod = py_newmodule("inspect");
  22486. py_bindfunc(mod, "isgeneratorfunction", inspect_isgeneratorfunction);
  22487. py_bindfunc(mod, "is_user_defined_type", inspect_is_user_defined_type);
  22488. py_bindfunc(mod, "_signature_data", inspect__signature_data);
  22489. if(!py_exec(kPythonLibs_inspect, "inspect.py", EXEC_MODE, mod)) {
  22490. py_printexc();
  22491. c11__abort("failed to execute inspect.py");
  22492. }
  22493. }
  22494. // src/modules\json.c
  22495. static bool json_loads(int argc, py_Ref argv) {
  22496. PY_CHECK_ARGC(1);
  22497. PY_CHECK_ARG_TYPE(0, tp_str);
  22498. const char* source = py_tostr(argv);
  22499. return py_json_loads(source);
  22500. }
  22501. static bool json_dumps(int argc, py_Ref argv) {
  22502. PY_CHECK_ARGC(2);
  22503. PY_CHECK_ARG_TYPE(1, tp_int);
  22504. int indent = py_toint(&argv[1]);
  22505. return py_json_dumps(argv, indent);
  22506. }
  22507. void pk__add_module_json() {
  22508. py_Ref mod = py_newmodule("json");
  22509. py_setdict(mod, py_name("null"), py_None());
  22510. py_setdict(mod, py_name("true"), py_True());
  22511. py_setdict(mod, py_name("false"), py_False());
  22512. py_TValue tmp;
  22513. py_newfloat(&tmp, DMATH_NAN);
  22514. py_setdict(mod, py_name("NaN"), &tmp);
  22515. py_newfloat(&tmp, DMATH_INFINITY);
  22516. py_setdict(mod, py_name("Infinity"), &tmp);
  22517. py_bindfunc(mod, "loads", json_loads);
  22518. py_bind(mod, "dumps(obj, indent=0)", json_dumps);
  22519. }
  22520. typedef struct {
  22521. c11_sbuf* buf;
  22522. bool first;
  22523. int indent;
  22524. int depth;
  22525. } json__write_dict_kv_ctx;
  22526. static bool json__write_object(c11_sbuf* buf, py_TValue* obj, int indent, int depth);
  22527. static void json__write_indent(c11_sbuf* buf, int n_spaces) {
  22528. for(int i = 0; i < n_spaces; i++) {
  22529. c11_sbuf__write_char(buf, ' ');
  22530. }
  22531. }
  22532. static bool json__write_array(c11_sbuf* buf, py_TValue* arr, int length, int indent, int depth) {
  22533. c11_sbuf__write_char(buf, '[');
  22534. if(length == 0) {
  22535. c11_sbuf__write_char(buf, ']');
  22536. return true;
  22537. }
  22538. if(indent > 0) c11_sbuf__write_char(buf, '\n');
  22539. int n_spaces = indent * depth;
  22540. const char* sep = indent > 0 ? ",\n" : ", ";
  22541. for(int i = 0; i < length; i++) {
  22542. if(i != 0) c11_sbuf__write_cstr(buf, sep);
  22543. json__write_indent(buf, n_spaces);
  22544. bool ok = json__write_object(buf, arr + i, indent, depth);
  22545. if(!ok) return false;
  22546. }
  22547. if(indent > 0) {
  22548. c11_sbuf__write_char(buf, '\n');
  22549. json__write_indent(buf, n_spaces - indent);
  22550. }
  22551. c11_sbuf__write_char(buf, ']');
  22552. return true;
  22553. }
  22554. static bool json__write_dict_kv(py_Ref k, py_Ref v, void* ctx_) {
  22555. json__write_dict_kv_ctx* ctx = ctx_;
  22556. int n_spaces = ctx->indent * ctx->depth;
  22557. const char* sep = ctx->indent > 0 ? ",\n" : ", ";
  22558. if(!ctx->first) c11_sbuf__write_cstr(ctx->buf, sep);
  22559. ctx->first = false;
  22560. if(!py_isstr(k)) return TypeError("keys must be strings");
  22561. json__write_indent(ctx->buf, n_spaces);
  22562. c11_sbuf__write_quoted(ctx->buf, py_tosv(k), '"');
  22563. c11_sbuf__write_cstr(ctx->buf, ": ");
  22564. return json__write_object(ctx->buf, v, ctx->indent, ctx->depth);
  22565. }
  22566. static bool json__write_namedict_kv(py_Name k, py_Ref v, void* ctx_) {
  22567. json__write_dict_kv_ctx* ctx = ctx_;
  22568. int n_spaces = ctx->indent * ctx->depth;
  22569. const char* sep = ctx->indent > 0 ? ",\n" : ", ";
  22570. if(!ctx->first) c11_sbuf__write_cstr(ctx->buf, sep);
  22571. ctx->first = false;
  22572. json__write_indent(ctx->buf, n_spaces);
  22573. c11_sbuf__write_quoted(ctx->buf, py_name2sv(k), '"');
  22574. c11_sbuf__write_cstr(ctx->buf, ": ");
  22575. return json__write_object(ctx->buf, v, ctx->indent, ctx->depth);
  22576. }
  22577. static bool json__write_object(c11_sbuf* buf, py_TValue* obj, int indent, int depth) {
  22578. switch(obj->type) {
  22579. case tp_NoneType: c11_sbuf__write_cstr(buf, "null"); return true;
  22580. case tp_int: c11_sbuf__write_i64(buf, obj->_i64); return true;
  22581. case tp_float: {
  22582. if(dmath_isnan(obj->_f64)) {
  22583. c11_sbuf__write_cstr(buf, "NaN");
  22584. } else if(dmath_isinf(obj->_f64)) {
  22585. c11_sbuf__write_cstr(buf, obj->_f64 < 0 ? "-Infinity" : "Infinity");
  22586. } else {
  22587. c11_sbuf__write_f64(buf, obj->_f64, -1);
  22588. }
  22589. return true;
  22590. }
  22591. case tp_bool: {
  22592. c11_sbuf__write_cstr(buf, py_tobool(obj) ? "true" : "false");
  22593. return true;
  22594. }
  22595. case tp_str: {
  22596. c11_sbuf__write_quoted(buf, py_tosv(obj), '"');
  22597. return true;
  22598. }
  22599. case tp_list: {
  22600. return json__write_array(buf, py_list_data(obj), py_list_len(obj), indent, depth + 1);
  22601. }
  22602. case tp_tuple: {
  22603. return json__write_array(buf, py_tuple_data(obj), py_tuple_len(obj), indent, depth + 1);
  22604. }
  22605. case tp_dict: {
  22606. c11_sbuf__write_char(buf, '{');
  22607. if(py_dict_len(obj) == 0) {
  22608. c11_sbuf__write_char(buf, '}');
  22609. return true;
  22610. }
  22611. if(indent > 0) c11_sbuf__write_char(buf, '\n');
  22612. json__write_dict_kv_ctx ctx = {.buf = buf,
  22613. .first = true,
  22614. .indent = indent,
  22615. .depth = depth + 1};
  22616. bool ok = py_dict_apply(obj, json__write_dict_kv, &ctx);
  22617. if(!ok) return false;
  22618. if(indent > 0) {
  22619. c11_sbuf__write_char(buf, '\n');
  22620. json__write_indent(buf, indent * depth);
  22621. }
  22622. c11_sbuf__write_char(buf, '}');
  22623. return true;
  22624. }
  22625. case tp_namedict: {
  22626. py_Ref original = py_getslot(obj, 0);
  22627. c11_sbuf__write_char(buf, '{');
  22628. if(PyObject__dict(original->_obj)->length == 0) {
  22629. c11_sbuf__write_char(buf, '}');
  22630. return true;
  22631. }
  22632. if(indent > 0) c11_sbuf__write_char(buf, '\n');
  22633. json__write_dict_kv_ctx ctx = {.buf = buf,
  22634. .first = true,
  22635. .indent = indent,
  22636. .depth = depth + 1};
  22637. bool ok = py_applydict(original, json__write_namedict_kv, &ctx);
  22638. if(!ok) return false;
  22639. if(indent > 0) {
  22640. c11_sbuf__write_char(buf, '\n');
  22641. json__write_indent(buf, indent * depth);
  22642. }
  22643. c11_sbuf__write_char(buf, '}');
  22644. return true;
  22645. }
  22646. default: return TypeError("'%t' object is not JSON serializable", obj->type);
  22647. }
  22648. }
  22649. bool py_json_dumps(py_Ref val, int indent) {
  22650. c11_sbuf buf;
  22651. c11_sbuf__ctor(&buf);
  22652. bool ok = json__write_object(&buf, val, indent, 0);
  22653. if(!ok) {
  22654. c11_sbuf__dtor(&buf);
  22655. return false;
  22656. }
  22657. c11_sbuf__py_submit(&buf, py_retval());
  22658. return true;
  22659. }
  22660. bool py_json_loads(const char* source) {
  22661. py_GlobalRef mod = py_getmodule("json");
  22662. return py_exec(source, "<json>", EVAL_MODE, mod);
  22663. }
  22664. // src/modules\lz4.c
  22665. #ifdef PK_BUILD_MODULE_LZ4
  22666. #include <string.h>
  22667. #include <assert.h>
  22668. #include "lz4/lib/lz4.h"
  22669. static bool lz4_compress(int argc, py_Ref argv) {
  22670. PY_CHECK_ARGC(1);
  22671. PY_CHECK_ARG_TYPE(0, tp_bytes);
  22672. int src_size;
  22673. const void* src = py_tobytes(argv, &src_size);
  22674. uint32_t dst_capacity = LZ4_compressBound(src_size);
  22675. char* p = (char*)py_newbytes(py_retval(), sizeof(uint32_t) + dst_capacity);
  22676. memcpy(p, &src_size, sizeof(uint32_t));
  22677. char* dst = p + sizeof(uint32_t);
  22678. int dst_size = LZ4_compress_default(src, dst, src_size, dst_capacity);
  22679. if(dst_size <= 0) return ValueError("LZ4 compression failed");
  22680. py_bytes_resize(py_retval(), sizeof(uint32_t) + dst_size);
  22681. return true;
  22682. }
  22683. static bool lz4_decompress(int argc, py_Ref argv) {
  22684. PY_CHECK_ARGC(1);
  22685. PY_CHECK_ARG_TYPE(0, tp_bytes);
  22686. int total_size;
  22687. const uint32_t* p = (uint32_t*)py_tobytes(argv, &total_size);
  22688. const char* src = (const char*)(p + 1);
  22689. if(total_size < sizeof(uint32_t)) return ValueError("invalid LZ4 data");
  22690. uint32_t uncompressed_size;
  22691. memcpy(&uncompressed_size, p, sizeof(uint32_t));
  22692. if(uncompressed_size >= INT32_MAX) return ValueError("invalid LZ4 data");
  22693. char* dst = (char*)py_newbytes(py_retval(), uncompressed_size);
  22694. int dst_size = LZ4_decompress_safe(src, dst, total_size - sizeof(uint32_t), uncompressed_size);
  22695. if(dst_size < 0) return ValueError("LZ4 decompression failed");
  22696. c11__rtassert(dst_size == uncompressed_size);
  22697. return true;
  22698. }
  22699. void pk__add_module_lz4() {
  22700. py_Ref mod = py_newmodule("lz4");
  22701. py_bindfunc(mod, "compress", lz4_compress);
  22702. py_bindfunc(mod, "decompress", lz4_decompress);
  22703. }
  22704. #else
  22705. void pk__add_module_lz4() {}
  22706. #endif
  22707. // src/modules\math.c
  22708. #define ONE_ARG_FUNC(name, func) \
  22709. static bool math_##name(int argc, py_Ref argv) { \
  22710. PY_CHECK_ARGC(1); \
  22711. double x; \
  22712. if(!py_castfloat(py_arg(0), &x)) return false; \
  22713. py_newfloat(py_retval(), func(x)); \
  22714. return true; \
  22715. }
  22716. #define ONE_ARG_INT_FUNC(name, func) \
  22717. static bool math_##name(int argc, py_Ref argv) { \
  22718. PY_CHECK_ARGC(1); \
  22719. double x; \
  22720. if(!py_castfloat(py_arg(0), &x)) return false; \
  22721. py_newint(py_retval(), (py_i64)func(x)); \
  22722. return true; \
  22723. }
  22724. #define ONE_ARG_BOOL_FUNC(name, func) \
  22725. static bool math_##name(int argc, py_Ref argv) { \
  22726. PY_CHECK_ARGC(1); \
  22727. double x; \
  22728. if(!py_castfloat(py_arg(0), &x)) return false; \
  22729. py_newbool(py_retval(), func(x)); \
  22730. return true; \
  22731. }
  22732. #define TWO_ARG_FUNC(name, func) \
  22733. static bool math_##name(int argc, py_Ref argv) { \
  22734. PY_CHECK_ARGC(2); \
  22735. double x, y; \
  22736. if(!py_castfloat(py_arg(0), &x)) return false; \
  22737. if(!py_castfloat(py_arg(1), &y)) return false; \
  22738. py_newfloat(py_retval(), func(x, y)); \
  22739. return true; \
  22740. }
  22741. ONE_ARG_INT_FUNC(ceil, dmath_ceil)
  22742. ONE_ARG_INT_FUNC(floor, dmath_floor)
  22743. ONE_ARG_INT_FUNC(trunc, dmath_trunc)
  22744. ONE_ARG_FUNC(fabs, dmath_fabs)
  22745. static bool math_fsum(int argc, py_Ref argv) {
  22746. PY_CHECK_ARGC(1);
  22747. PY_CHECK_ARG_TYPE(0, tp_list);
  22748. py_Ref list = py_arg(0);
  22749. double sum = 0;
  22750. double c = 0;
  22751. for(int i = 0; i < py_list_len(list); i++) {
  22752. py_Ref item = py_list_getitem(list, i);
  22753. double x;
  22754. if(!py_castfloat(item, &x)) return false;
  22755. double y = x - c;
  22756. double t = sum + y;
  22757. c = (t - sum) - y;
  22758. sum = t;
  22759. }
  22760. py_newfloat(py_retval(), sum);
  22761. return true;
  22762. }
  22763. static bool math_gcd(int argc, py_Ref argv) {
  22764. PY_CHECK_ARGC(2);
  22765. PY_CHECK_ARG_TYPE(0, tp_int);
  22766. PY_CHECK_ARG_TYPE(1, tp_int);
  22767. py_i64 a = py_toint(py_arg(0));
  22768. py_i64 b = py_toint(py_arg(1));
  22769. if(a < 0) a = -a;
  22770. if(b < 0) b = -b;
  22771. while(b != 0) {
  22772. py_i64 t = b;
  22773. b = a % b;
  22774. a = t;
  22775. }
  22776. py_newint(py_retval(), a);
  22777. return true;
  22778. }
  22779. ONE_ARG_BOOL_FUNC(isfinite, dmath_isfinite)
  22780. ONE_ARG_BOOL_FUNC(isinf, dmath_isinf)
  22781. ONE_ARG_BOOL_FUNC(isnan, dmath_isnan)
  22782. static bool math_isclose(int argc, py_Ref argv) {
  22783. PY_CHECK_ARGC(2);
  22784. double a, b;
  22785. if(!py_castfloat(py_arg(0), &a)) return false;
  22786. if(!py_castfloat(py_arg(1), &b)) return false;
  22787. py_newbool(py_retval(), dmath_fabs(a - b) < 1e-9);
  22788. return true;
  22789. }
  22790. ONE_ARG_FUNC(exp, dmath_exp)
  22791. static bool math_log(int argc, py_Ref argv) {
  22792. double x;
  22793. if(!py_castfloat(py_arg(0), &x)) return false;
  22794. if(x < 0) {
  22795. py_newfloat(py_retval(), DMATH_NAN);
  22796. return true;
  22797. }
  22798. if(argc == 1) {
  22799. py_newfloat(py_retval(), dmath_log(x));
  22800. } else if(argc == 2) {
  22801. double base;
  22802. if(!py_castfloat(py_arg(1), &base)) return false;
  22803. py_newfloat(py_retval(), dmath_log2(x) / dmath_log2(base));
  22804. } else {
  22805. return TypeError("log() takes 1 or 2 arguments");
  22806. }
  22807. return true;
  22808. }
  22809. ONE_ARG_FUNC(log2, dmath_log2)
  22810. ONE_ARG_FUNC(log10, dmath_log10)
  22811. TWO_ARG_FUNC(pow, dmath_pow)
  22812. ONE_ARG_FUNC(sqrt, dmath_sqrt)
  22813. ONE_ARG_FUNC(acos, dmath_acos)
  22814. ONE_ARG_FUNC(asin, dmath_asin)
  22815. ONE_ARG_FUNC(atan, dmath_atan)
  22816. ONE_ARG_FUNC(cos, dmath_cos)
  22817. ONE_ARG_FUNC(sin, dmath_sin)
  22818. ONE_ARG_FUNC(tan, dmath_tan)
  22819. TWO_ARG_FUNC(atan2, dmath_atan2)
  22820. static bool math_degrees(int argc, py_Ref argv) {
  22821. PY_CHECK_ARGC(1);
  22822. double x;
  22823. if(!py_castfloat(py_arg(0), &x)) return false;
  22824. py_newfloat(py_retval(), x * DMATH_RAD2DEG);
  22825. return true;
  22826. }
  22827. static bool math_radians(int argc, py_Ref argv) {
  22828. PY_CHECK_ARGC(1);
  22829. double x;
  22830. if(!py_castfloat(py_arg(0), &x)) return false;
  22831. py_newfloat(py_retval(), x * DMATH_DEG2RAD);
  22832. return true;
  22833. }
  22834. TWO_ARG_FUNC(copysign, dmath_copysign)
  22835. TWO_ARG_FUNC(fmod, dmath_fmod)
  22836. static bool math_modf(int argc, py_Ref argv) {
  22837. PY_CHECK_ARGC(1);
  22838. double i;
  22839. double f = dmath_modf(py_tofloat(py_arg(0)), &i);
  22840. py_Ref p = py_newtuple(py_retval(), 2);
  22841. py_newfloat(&p[0], f);
  22842. py_newfloat(&p[1], i);
  22843. return true;
  22844. }
  22845. static bool math_factorial(int argc, py_Ref argv) {
  22846. PY_CHECK_ARGC(1);
  22847. PY_CHECK_ARG_TYPE(0, tp_int);
  22848. py_i64 n = py_toint(py_arg(0));
  22849. if(n < 0) return ValueError("factorial() not defined for negative values");
  22850. py_i64 r = 1;
  22851. for(py_i64 i = 2; i <= n; i++)
  22852. r *= i;
  22853. py_newint(py_retval(), r);
  22854. return true;
  22855. }
  22856. void pk__add_module_math() {
  22857. py_Ref mod = py_newmodule("math");
  22858. py_newfloat(py_emplacedict(mod, py_name("pi")), DMATH_PI);
  22859. py_newfloat(py_emplacedict(mod, py_name("e")), DMATH_E);
  22860. py_newfloat(py_emplacedict(mod, py_name("inf")), DMATH_INFINITY);
  22861. py_newfloat(py_emplacedict(mod, py_name("nan")), DMATH_NAN);
  22862. py_bindfunc(mod, "ceil", math_ceil);
  22863. py_bindfunc(mod, "fabs", math_fabs);
  22864. py_bindfunc(mod, "floor", math_floor);
  22865. py_bindfunc(mod, "trunc", math_trunc);
  22866. py_bindfunc(mod, "fsum", math_fsum);
  22867. py_bindfunc(mod, "gcd", math_gcd);
  22868. py_bindfunc(mod, "isfinite", math_isfinite);
  22869. py_bindfunc(mod, "isinf", math_isinf);
  22870. py_bindfunc(mod, "isnan", math_isnan);
  22871. py_bindfunc(mod, "isclose", math_isclose);
  22872. py_bindfunc(mod, "exp", math_exp);
  22873. py_bindfunc(mod, "log", math_log);
  22874. py_bindfunc(mod, "log2", math_log2);
  22875. py_bindfunc(mod, "log10", math_log10);
  22876. py_bindfunc(mod, "pow", math_pow);
  22877. py_bindfunc(mod, "sqrt", math_sqrt);
  22878. py_bindfunc(mod, "acos", math_acos);
  22879. py_bindfunc(mod, "asin", math_asin);
  22880. py_bindfunc(mod, "atan", math_atan);
  22881. py_bindfunc(mod, "cos", math_cos);
  22882. py_bindfunc(mod, "sin", math_sin);
  22883. py_bindfunc(mod, "tan", math_tan);
  22884. py_bindfunc(mod, "atan2", math_atan2);
  22885. py_bindfunc(mod, "degrees", math_degrees);
  22886. py_bindfunc(mod, "radians", math_radians);
  22887. py_bindfunc(mod, "fmod", math_fmod);
  22888. py_bindfunc(mod, "modf", math_modf);
  22889. py_bindfunc(mod, "copysign", math_copysign);
  22890. py_bindfunc(mod, "factorial", math_factorial);
  22891. }
  22892. #undef ONE_ARG_FUNC
  22893. #undef ONE_ARG_BOOL_FUNC
  22894. #undef ONE_ARG_INT_FUNC
  22895. #undef TWO_ARG_FUNC
  22896. // src/modules\os.c
  22897. #if PK_ENABLE_OS
  22898. #include <errno.h>
  22899. #if PY_SYS_PLATFORM == 0
  22900. #include <direct.h>
  22901. #include <io.h>
  22902. int platform_chdir(const char* path) { return _chdir(path); }
  22903. bool platform_getcwd(char* buf, size_t size) { return _getcwd(buf, size) != NULL; }
  22904. bool platform_path_exists(const char* path) { return _access(path, 0) == 0; }
  22905. #elif PY_SYS_PLATFORM == 3 || PY_SYS_PLATFORM == 5
  22906. #include <unistd.h>
  22907. int platform_chdir(const char* path) { return chdir(path); }
  22908. bool platform_getcwd(char* buf, size_t size) { return getcwd(buf, size) != NULL; }
  22909. bool platform_path_exists(const char* path) { return access(path, F_OK) == 0; }
  22910. #else
  22911. int platform_chdir(const char* path) { return -1; }
  22912. bool platform_getcwd(char* buf, size_t size) { return false; }
  22913. bool platform_path_exists(const char* path) { return false; }
  22914. #endif
  22915. static bool os_chdir(int argc, py_Ref argv) {
  22916. PY_CHECK_ARGC(1);
  22917. PY_CHECK_ARG_TYPE(0, tp_str);
  22918. const char* path = py_tostr(py_arg(0));
  22919. int code = platform_chdir(path);
  22920. if(code != 0) {
  22921. const char* msg = strerror(errno);
  22922. return OSError("[Errno %d] %s: '%s'", errno, msg, path);
  22923. }
  22924. py_newnone(py_retval());
  22925. return true;
  22926. }
  22927. static bool os_getcwd(int argc, py_Ref argv) {
  22928. PY_CHECK_ARGC(0);
  22929. char buf[1024];
  22930. if(!platform_getcwd(buf, sizeof(buf))) return OSError("getcwd() failed");
  22931. py_newstr(py_retval(), buf);
  22932. return true;
  22933. }
  22934. static bool os_system(int argc, py_Ref argv) {
  22935. PY_CHECK_ARGC(1);
  22936. PY_CHECK_ARG_TYPE(0, tp_str);
  22937. #if PK_IS_DESKTOP_PLATFORM
  22938. const char* cmd = py_tostr(py_arg(0));
  22939. int code = system(cmd);
  22940. py_newint(py_retval(), code);
  22941. return true;
  22942. #else
  22943. return OSError("system() is not supported on this platform");
  22944. #endif
  22945. }
  22946. static bool os_remove(int argc, py_Ref argv) {
  22947. PY_CHECK_ARGC(1);
  22948. PY_CHECK_ARG_TYPE(0, tp_str);
  22949. const char* path = py_tostr(py_arg(0));
  22950. int code = remove(path);
  22951. if(code != 0) {
  22952. const char* msg = strerror(errno);
  22953. return OSError("[Errno %d] %s: '%s'", errno, msg, path);
  22954. }
  22955. py_newnone(py_retval());
  22956. return true;
  22957. }
  22958. static bool os_path_exists(int argc, py_Ref argv) {
  22959. PY_CHECK_ARGC(1);
  22960. PY_CHECK_ARG_TYPE(0, tp_str);
  22961. const char* path = py_tostr(py_arg(0));
  22962. py_newbool(py_retval(), platform_path_exists(path));
  22963. return true;
  22964. }
  22965. void pk__add_module_os() {
  22966. py_Ref mod = py_newmodule("os");
  22967. py_bindfunc(mod, "chdir", os_chdir);
  22968. py_bindfunc(mod, "getcwd", os_getcwd);
  22969. py_bindfunc(mod, "system", os_system);
  22970. py_bindfunc(mod, "remove", os_remove);
  22971. py_ItemRef path_object = py_emplacedict(mod, py_name("path"));
  22972. py_newobject(path_object, tp_object, -1, 0);
  22973. py_bindfunc(path_object, "exists", os_path_exists);
  22974. py_newdict(py_emplacedict(mod, py_name("environ")));
  22975. }
  22976. static bool io_FileIO__new__(int argc, py_Ref argv) {
  22977. // __new__(cls, file, mode)
  22978. PY_CHECK_ARGC(3);
  22979. PY_CHECK_ARG_TYPE(1, tp_str);
  22980. PY_CHECK_ARG_TYPE(2, tp_str);
  22981. py_Type cls = py_totype(argv);
  22982. io_FileIO* ud = py_newobject(py_retval(), cls, 0, sizeof(io_FileIO));
  22983. ud->path = py_tostr(py_arg(1));
  22984. ud->mode = py_tostr(py_arg(2));
  22985. ud->file = fopen(ud->path, ud->mode);
  22986. if(ud->file == NULL) {
  22987. const char* msg = strerror(errno);
  22988. return OSError("[Errno %d] %s: '%s'", errno, msg, ud->path);
  22989. }
  22990. return true;
  22991. }
  22992. static bool io_FileIO__enter__(int argc, py_Ref argv) {
  22993. py_assign(py_retval(), py_arg(0));
  22994. return true;
  22995. }
  22996. static bool io_FileIO__exit__(int argc, py_Ref argv) {
  22997. io_FileIO* ud = py_touserdata(py_arg(0));
  22998. if(ud->file != NULL) {
  22999. fclose(ud->file);
  23000. ud->file = NULL;
  23001. }
  23002. py_newnone(py_retval());
  23003. return true;
  23004. }
  23005. static bool io_FileIO_read(int argc, py_Ref argv) {
  23006. io_FileIO* ud = py_touserdata(py_arg(0));
  23007. if(ud->file == NULL) return ValueError("I/O operation on closed file");
  23008. bool is_binary = ud->mode[strlen(ud->mode) - 1] == 'b';
  23009. int size;
  23010. if(argc == 1) {
  23011. long current = ftell(ud->file);
  23012. fseek(ud->file, 0, SEEK_END);
  23013. size = ftell(ud->file);
  23014. fseek(ud->file, current, SEEK_SET);
  23015. } else if(argc == 2) {
  23016. PY_CHECK_ARG_TYPE(1, tp_int);
  23017. size = py_toint(py_arg(1));
  23018. if (size < 0) {
  23019. long current = ftell(ud->file);
  23020. fseek(ud->file, 0, SEEK_END);
  23021. size = ftell(ud->file);
  23022. fseek(ud->file, current, SEEK_SET);
  23023. }
  23024. } else {
  23025. return TypeError("read() takes at most 2 arguments (%d given)", argc);
  23026. }
  23027. if(is_binary) {
  23028. void* dst = py_newbytes(py_retval(), size);
  23029. if(size > 0) {
  23030. int actual_size = fread(dst, 1, size, ud->file);
  23031. py_bytes_resize(py_retval(), actual_size);
  23032. }
  23033. } else {
  23034. if(size > 0) {
  23035. void* dst = PK_MALLOC(size);
  23036. int actual_size = fread(dst, 1, size, ud->file);
  23037. py_newstrv(py_retval(), (c11_sv){dst, actual_size});
  23038. PK_FREE(dst);
  23039. } else {
  23040. py_newstr(py_retval(), "");
  23041. }
  23042. }
  23043. return true;
  23044. }
  23045. static bool io_FileIO_tell(int argc, py_Ref argv) {
  23046. io_FileIO* ud = py_touserdata(py_arg(0));
  23047. if(ud->file == NULL) return ValueError("I/O operation on closed file");
  23048. py_newint(py_retval(), ftell(ud->file));
  23049. return true;
  23050. }
  23051. static bool io_FileIO_seek(int argc, py_Ref argv) {
  23052. PY_CHECK_ARGC(3);
  23053. PY_CHECK_ARG_TYPE(1, tp_int);
  23054. PY_CHECK_ARG_TYPE(2, tp_int);
  23055. io_FileIO* ud = py_touserdata(py_arg(0));
  23056. if(ud->file == NULL) return ValueError("I/O operation on closed file");
  23057. long cookie = py_toint(py_arg(1));
  23058. int whence = py_toint(py_arg(2));
  23059. py_newint(py_retval(), fseek(ud->file, cookie, whence));
  23060. return true;
  23061. }
  23062. static bool io_FileIO_close(int argc, py_Ref argv) {
  23063. PY_CHECK_ARGC(1);
  23064. io_FileIO* ud = py_touserdata(py_arg(0));
  23065. if(ud->file != NULL) {
  23066. fclose(ud->file);
  23067. ud->file = NULL;
  23068. }
  23069. py_newnone(py_retval());
  23070. return true;
  23071. }
  23072. static bool io_FileIO_write(int argc, py_Ref argv) {
  23073. PY_CHECK_ARGC(2);
  23074. io_FileIO* ud = py_touserdata(py_arg(0));
  23075. if(ud->file == NULL) return ValueError("I/O operation on closed file");
  23076. size_t written_size;
  23077. if(ud->mode[strlen(ud->mode) - 1] == 'b') {
  23078. PY_CHECK_ARG_TYPE(1, tp_bytes);
  23079. int filesize;
  23080. unsigned char* data = py_tobytes(py_arg(1), &filesize);
  23081. written_size = fwrite(data, 1, filesize, ud->file);
  23082. } else {
  23083. PY_CHECK_ARG_TYPE(1, tp_str);
  23084. c11_sv sv = py_tosv(py_arg(1));
  23085. written_size = fwrite(sv.data, 1, sv.size, ud->file);
  23086. }
  23087. py_newint(py_retval(), written_size);
  23088. return true;
  23089. }
  23090. static bool io_FileIO_flush(int argc, py_Ref argv) {
  23091. PY_CHECK_ARGC(1);
  23092. io_FileIO* ud = py_touserdata(py_arg(0));
  23093. if(ud->file == NULL) return ValueError("I/O operation on closed file");
  23094. fflush(ud->file);
  23095. py_newnone(py_retval());
  23096. return true;
  23097. }
  23098. void pk__add_module_io() {
  23099. py_Ref mod = py_newmodule("io");
  23100. py_Type FileIO = py_newtype("FileIO", tp_object, mod, NULL);
  23101. py_tpsetfinal(FileIO);
  23102. py_bindmagic(FileIO, __new__, io_FileIO__new__);
  23103. py_bindmagic(FileIO, __enter__, io_FileIO__enter__);
  23104. py_bindmagic(FileIO, __exit__, io_FileIO__exit__);
  23105. py_bindmethod(FileIO, "read", io_FileIO_read);
  23106. py_bindmethod(FileIO, "write", io_FileIO_write);
  23107. py_bindmethod(FileIO, "close", io_FileIO_close);
  23108. py_bindmethod(FileIO, "tell", io_FileIO_tell);
  23109. py_bindmethod(FileIO, "seek", io_FileIO_seek);
  23110. py_bindmethod(FileIO, "flush", io_FileIO_flush);
  23111. py_newint(py_emplacedict(mod, py_name("SEEK_SET")), SEEK_SET);
  23112. py_newint(py_emplacedict(mod, py_name("SEEK_CUR")), SEEK_CUR);
  23113. py_newint(py_emplacedict(mod, py_name("SEEK_END")), SEEK_END);
  23114. py_setdict(pk_current_vm->builtins, py_name("open"), py_tpobject(FileIO));
  23115. }
  23116. #else
  23117. void pk__add_module_os() {}
  23118. void pk__add_module_io() {}
  23119. #endif
  23120. static bool sys_setrecursionlimit(int argc, py_Ref argv) {
  23121. PY_CHECK_ARGC(1);
  23122. PY_CHECK_ARG_TYPE(0, tp_int);
  23123. int limit = py_toint(py_arg(0));
  23124. if(limit <= pk_current_vm->recursion_depth) return ValueError("the limit is too low");
  23125. pk_current_vm->max_recursion_depth = limit;
  23126. py_newnone(py_retval());
  23127. return true;
  23128. }
  23129. static bool sys_getrecursionlimit(int argc, py_Ref argv) {
  23130. PY_CHECK_ARGC(0);
  23131. py_newint(py_retval(), pk_current_vm->max_recursion_depth);
  23132. return true;
  23133. }
  23134. void pk__add_module_sys() {
  23135. py_Ref mod = py_newmodule("sys");
  23136. py_newstr(py_emplacedict(mod, py_name("platform")), PY_SYS_PLATFORM_STRING);
  23137. py_newstr(py_emplacedict(mod, py_name("version")), PK_VERSION);
  23138. py_newlist(py_emplacedict(mod, py_name("argv")));
  23139. py_bindfunc(mod, "setrecursionlimit", sys_setrecursionlimit);
  23140. py_bindfunc(mod, "getrecursionlimit", sys_getrecursionlimit);
  23141. }
  23142. // src/modules\pickle.c
  23143. #include <stdint.h>
  23144. typedef enum {
  23145. // clang-format off
  23146. PKL_MEMO_GET,
  23147. PKL_MEMO_SET,
  23148. PKL_NIL, PKL_NONE, PKL_ELLIPSIS,
  23149. PKL_INT_0, PKL_INT_1, PKL_INT_2, PKL_INT_3, PKL_INT_4, PKL_INT_5, PKL_INT_6, PKL_INT_7,
  23150. PKL_INT_8, PKL_INT_9, PKL_INT_10, PKL_INT_11, PKL_INT_12, PKL_INT_13, PKL_INT_14, PKL_INT_15,
  23151. PKL_INT8, PKL_INT16, PKL_INT32, PKL_INT64,
  23152. PKL_FLOAT32, PKL_FLOAT64,
  23153. PKL_TRUE, PKL_FALSE,
  23154. PKL_STRING, PKL_BYTES,
  23155. PKL_BUILD_LIST,
  23156. PKL_BUILD_TUPLE,
  23157. PKL_BUILD_DICT,
  23158. PKL_VEC2, PKL_VEC3,
  23159. PKL_VEC2I, PKL_VEC3I,
  23160. PKL_TYPE,
  23161. PKL_ARRAY2D,
  23162. PKL_IMPORT_PATH,
  23163. PKL_GETATTR,
  23164. PKL_TVALUE,
  23165. PKL_CALL,
  23166. PKL_OBJECT,
  23167. PKL_EOF,
  23168. // clang-format on
  23169. } PickleOp;
  23170. typedef struct {
  23171. bool* used_types;
  23172. int used_types_length;
  23173. c11_smallmap_p2i memo;
  23174. c11_vector /*T=char*/ codes;
  23175. } PickleObject;
  23176. static void PickleObject__ctor(PickleObject* self) {
  23177. self->used_types_length = pk_current_vm->types.length;
  23178. self->used_types = PK_MALLOC(self->used_types_length);
  23179. memset(self->used_types, 0, self->used_types_length);
  23180. c11_smallmap_p2i__ctor(&self->memo);
  23181. c11_vector__ctor(&self->codes, sizeof(char));
  23182. }
  23183. static void PickleObject__dtor(PickleObject* self) {
  23184. PK_FREE(self->used_types);
  23185. c11_smallmap_p2i__dtor(&self->memo);
  23186. c11_vector__dtor(&self->codes);
  23187. }
  23188. static bool PickleObject__py_submit(PickleObject* self, py_OutRef out);
  23189. static void PickleObject__write_bytes(PickleObject* buf, const void* data, int size) {
  23190. c11_vector__extend(&buf->codes, data, size);
  23191. }
  23192. static void c11_sbuf__write_type_path(c11_sbuf* path_buf, py_Type type) {
  23193. py_TypeInfo* ti = pk_typeinfo(type);
  23194. if(py_isnil(ti->module)) {
  23195. c11_sbuf__write_cstr(path_buf, py_name2str(ti->name));
  23196. return;
  23197. }
  23198. py_ModuleInfo* mi = py_touserdata(ti->module);
  23199. c11_sbuf__write_sv(path_buf, c11_string__sv(mi->path));
  23200. c11_sbuf__write_char(path_buf, '.');
  23201. c11_sbuf__write_sv(path_buf, py_name2sv(ti->name));
  23202. }
  23203. static void pkl__emit_op(PickleObject* buf, PickleOp op) {
  23204. c11_vector__push(char, &buf->codes, op);
  23205. }
  23206. static void pkl__emit_int(PickleObject* buf, py_i64 val) {
  23207. if(val >= 0 && val <= 15) {
  23208. pkl__emit_op(buf, PKL_INT_0 + val);
  23209. return;
  23210. }
  23211. if(INT8_MIN <= val && val <= INT8_MAX) {
  23212. pkl__emit_op(buf, PKL_INT8);
  23213. PickleObject__write_bytes(buf, &val, 1);
  23214. } else if(INT16_MIN <= val && val <= INT16_MAX) {
  23215. pkl__emit_op(buf, PKL_INT16);
  23216. PickleObject__write_bytes(buf, &val, 2);
  23217. } else if(INT32_MIN <= val && val <= INT32_MAX) {
  23218. pkl__emit_op(buf, PKL_INT32);
  23219. PickleObject__write_bytes(buf, &val, 4);
  23220. } else {
  23221. pkl__emit_op(buf, PKL_INT64);
  23222. PickleObject__write_bytes(buf, &val, 8);
  23223. }
  23224. }
  23225. static void pkl__emit_cstr(PickleObject* buf, const char* s) {
  23226. PickleObject__write_bytes(buf, s, strlen(s) + 1);
  23227. }
  23228. const static char* pkl__read_cstr(const unsigned char** p) {
  23229. const char* s = (const char*)*p;
  23230. (*p) += strlen(s) + 1;
  23231. return s;
  23232. }
  23233. #define UNALIGNED_READ(p_val, p_buf) \
  23234. do { \
  23235. memcpy((p_val), (p_buf), sizeof(*(p_val))); \
  23236. (p_buf) += sizeof(*(p_val)); \
  23237. } while(0)
  23238. static py_i64 pkl__read_int(const unsigned char** p) {
  23239. PickleOp op = (PickleOp) * *p;
  23240. (*p)++;
  23241. switch(op) {
  23242. // clang-format off
  23243. case PKL_INT_0: return 0; case PKL_INT_1: return 1; case PKL_INT_2: return 2; case PKL_INT_3: return 3;
  23244. case PKL_INT_4: return 4; case PKL_INT_5: return 5; case PKL_INT_6: return 6; case PKL_INT_7: return 7;
  23245. case PKL_INT_8: return 8; case PKL_INT_9: return 9; case PKL_INT_10: return 10; case PKL_INT_11: return 11;
  23246. case PKL_INT_12: return 12; case PKL_INT_13: return 13; case PKL_INT_14: return 14; case PKL_INT_15: return 15;
  23247. // clang-format on
  23248. case PKL_INT8: {
  23249. int8_t val;
  23250. UNALIGNED_READ(&val, *p);
  23251. return val;
  23252. }
  23253. case PKL_INT16: {
  23254. int16_t val;
  23255. UNALIGNED_READ(&val, *p);
  23256. return val;
  23257. }
  23258. case PKL_INT32: {
  23259. int32_t val;
  23260. UNALIGNED_READ(&val, *p);
  23261. return val;
  23262. }
  23263. case PKL_INT64: {
  23264. int64_t val;
  23265. UNALIGNED_READ(&val, *p);
  23266. return val;
  23267. }
  23268. default: c11__abort("pkl__read_int(): invalid op: %d", op);
  23269. }
  23270. }
  23271. static bool pickle_loads(int argc, py_Ref argv) {
  23272. PY_CHECK_ARGC(1);
  23273. PY_CHECK_ARG_TYPE(0, tp_bytes);
  23274. int size;
  23275. const unsigned char* data = py_tobytes(argv, &size);
  23276. return py_pickle_loads(data, size);
  23277. }
  23278. static bool pickle_dumps(int argc, py_Ref argv) {
  23279. PY_CHECK_ARGC(1);
  23280. return py_pickle_dumps(argv);
  23281. }
  23282. void pk__add_module_pickle() {
  23283. py_Ref mod = py_newmodule("pickle");
  23284. py_bindfunc(mod, "loads", pickle_loads);
  23285. py_bindfunc(mod, "dumps", pickle_dumps);
  23286. }
  23287. static bool pkl__write_object(PickleObject* buf, py_TValue* obj);
  23288. static bool pkl__write_array(PickleObject* buf, PickleOp op, py_TValue* arr, int length) {
  23289. for(int i = 0; i < length; i++) {
  23290. bool ok = pkl__write_object(buf, arr + i);
  23291. if(!ok) return false;
  23292. }
  23293. pkl__emit_op(buf, op);
  23294. pkl__emit_int(buf, length);
  23295. return true;
  23296. }
  23297. static bool pkl__write_dict_kv(py_Ref k, py_Ref v, void* ctx) {
  23298. PickleObject* buf = (PickleObject*)ctx;
  23299. if(!pkl__write_object(buf, k)) return false;
  23300. if(!pkl__write_object(buf, v)) return false;
  23301. return true;
  23302. }
  23303. static bool pkl__try_memo(PickleObject* buf, PyObject* memo_key) {
  23304. int index = c11_smallmap_p2i__get(&buf->memo, memo_key, -1);
  23305. if(index != -1) {
  23306. pkl__emit_op(buf, PKL_MEMO_GET);
  23307. pkl__emit_int(buf, index);
  23308. return true;
  23309. }
  23310. return false;
  23311. }
  23312. static void pkl__store_memo(PickleObject* buf, PyObject* memo_key) {
  23313. int index = buf->memo.length;
  23314. c11_smallmap_p2i__set(&buf->memo, memo_key, index);
  23315. pkl__emit_op(buf, PKL_MEMO_SET);
  23316. pkl__emit_int(buf, index);
  23317. }
  23318. static bool _check_function(Function* f) {
  23319. if(!f->module) return ValueError("cannot pickle function (!f->module)");
  23320. if(f->closure) return ValueError("cannot pickle function with closure");
  23321. if(f->decl->nested) return ValueError("cannot pickle nested function");
  23322. c11_string* name = f->decl->code.name;
  23323. if(name->size == 0) return ValueError("cannot pickle function with empty name");
  23324. if(name->data[0] == '<') return ValueError("cannot pickle anonymous function");
  23325. return true;
  23326. }
  23327. static bool pkl__write_object(PickleObject* buf, py_TValue* obj) {
  23328. switch(obj->type) {
  23329. case tp_nil: {
  23330. return ValueError("'nil' object is not picklable");
  23331. }
  23332. case tp_NoneType: {
  23333. pkl__emit_op(buf, PKL_NONE);
  23334. return true;
  23335. }
  23336. case tp_ellipsis: {
  23337. pkl__emit_op(buf, PKL_ELLIPSIS);
  23338. return true;
  23339. }
  23340. case tp_int: {
  23341. py_i64 val = obj->_i64;
  23342. pkl__emit_int(buf, val);
  23343. return true;
  23344. }
  23345. case tp_float: {
  23346. py_f64 val = obj->_f64;
  23347. float val32 = (float)val;
  23348. if(val == val32) {
  23349. pkl__emit_op(buf, PKL_FLOAT32);
  23350. PickleObject__write_bytes(buf, &val32, 4);
  23351. } else {
  23352. pkl__emit_op(buf, PKL_FLOAT64);
  23353. PickleObject__write_bytes(buf, &val, 8);
  23354. }
  23355. return true;
  23356. }
  23357. case tp_bool: {
  23358. bool val = obj->_bool;
  23359. pkl__emit_op(buf, val ? PKL_TRUE : PKL_FALSE);
  23360. return true;
  23361. }
  23362. case tp_str: {
  23363. if(obj->is_ptr && pkl__try_memo(buf, obj->_obj)) return true;
  23364. pkl__emit_op(buf, PKL_STRING);
  23365. c11_sv sv = py_tosv(obj);
  23366. pkl__emit_int(buf, sv.size);
  23367. PickleObject__write_bytes(buf, sv.data, sv.size);
  23368. if(obj->is_ptr) pkl__store_memo(buf, obj->_obj);
  23369. return true;
  23370. }
  23371. case tp_bytes: {
  23372. if(pkl__try_memo(buf, obj->_obj)) return true;
  23373. pkl__emit_op(buf, PKL_BYTES);
  23374. int size;
  23375. unsigned char* data = py_tobytes(obj, &size);
  23376. pkl__emit_int(buf, size);
  23377. PickleObject__write_bytes(buf, data, size);
  23378. pkl__store_memo(buf, obj->_obj);
  23379. return true;
  23380. }
  23381. case tp_list: {
  23382. if(pkl__try_memo(buf, obj->_obj)) return true;
  23383. bool ok = pkl__write_array(buf, PKL_BUILD_LIST, py_list_data(obj), py_list_len(obj));
  23384. if(!ok) return false;
  23385. pkl__store_memo(buf, obj->_obj);
  23386. return true;
  23387. }
  23388. case tp_tuple: {
  23389. if(pkl__try_memo(buf, obj->_obj)) return true;
  23390. bool ok = pkl__write_array(buf, PKL_BUILD_TUPLE, py_tuple_data(obj), py_tuple_len(obj));
  23391. if(!ok) return false;
  23392. pkl__store_memo(buf, obj->_obj);
  23393. return true;
  23394. }
  23395. case tp_dict: {
  23396. if(pkl__try_memo(buf, obj->_obj)) return true;
  23397. bool ok = py_dict_apply(obj, pkl__write_dict_kv, (void*)buf);
  23398. if(!ok) return false;
  23399. pkl__emit_op(buf, PKL_BUILD_DICT);
  23400. pkl__emit_int(buf, py_dict_len(obj));
  23401. pkl__store_memo(buf, obj->_obj);
  23402. return true;
  23403. }
  23404. case tp_vec2: {
  23405. c11_vec2 val = py_tovec2(obj);
  23406. pkl__emit_op(buf, PKL_VEC2);
  23407. PickleObject__write_bytes(buf, &val, sizeof(c11_vec2));
  23408. return true;
  23409. }
  23410. case tp_vec3: {
  23411. c11_vec3 val = py_tovec3(obj);
  23412. pkl__emit_op(buf, PKL_VEC3);
  23413. PickleObject__write_bytes(buf, &val, sizeof(c11_vec3));
  23414. return true;
  23415. }
  23416. case tp_vec2i: {
  23417. c11_vec2i val = py_tovec2i(obj);
  23418. pkl__emit_op(buf, PKL_VEC2I);
  23419. pkl__emit_int(buf, val.x);
  23420. pkl__emit_int(buf, val.y);
  23421. return true;
  23422. }
  23423. case tp_vec3i: {
  23424. c11_vec3i val = py_tovec3i(obj);
  23425. pkl__emit_op(buf, PKL_VEC3I);
  23426. pkl__emit_int(buf, val.x);
  23427. pkl__emit_int(buf, val.y);
  23428. pkl__emit_int(buf, val.z);
  23429. return true;
  23430. }
  23431. case tp_type: {
  23432. pkl__emit_op(buf, PKL_TYPE);
  23433. py_Type type = py_totype(obj);
  23434. buf->used_types[type] = true;
  23435. pkl__emit_int(buf, type);
  23436. return true;
  23437. }
  23438. case tp_module: {
  23439. if(pkl__try_memo(buf, obj->_obj)) return true;
  23440. py_ModuleInfo* mi = py_touserdata(obj);
  23441. pkl__emit_op(buf, PKL_IMPORT_PATH);
  23442. pkl__emit_cstr(buf, mi->path->data);
  23443. pkl__store_memo(buf, obj->_obj);
  23444. return true;
  23445. }
  23446. case tp_function: {
  23447. if(pkl__try_memo(buf, obj->_obj)) return true;
  23448. Function* f = py_touserdata(obj);
  23449. if(!_check_function(f)) return false;
  23450. c11_string* name = f->decl->code.name;
  23451. if(f->clazz) {
  23452. // NOTE: copied from logic of `case tp_type:`
  23453. pkl__emit_op(buf, PKL_TYPE);
  23454. py_TypeInfo* ti = PyObject__userdata(f->clazz);
  23455. py_Type type = ti->index;
  23456. buf->used_types[type] = true;
  23457. pkl__emit_int(buf, type);
  23458. } else {
  23459. if(!pkl__write_object(buf, f->module)) return false;
  23460. }
  23461. pkl__emit_op(buf, PKL_GETATTR);
  23462. pkl__emit_cstr(buf, name->data);
  23463. pkl__store_memo(buf, obj->_obj);
  23464. return true;
  23465. }
  23466. case tp_boundmethod: {
  23467. py_Ref self = py_getslot(obj, 0);
  23468. if(!py_istype(self, tp_type)) {
  23469. return ValueError("tp_boundmethod: !py_istype(self, tp_type)");
  23470. }
  23471. py_Ref func = py_getslot(obj, 1);
  23472. if(!py_istype(func, tp_function)) {
  23473. return ValueError("tp_boundmethod: !py_istype(func, tp_function)");
  23474. }
  23475. Function* f = py_touserdata(func);
  23476. if(!_check_function(f)) return false;
  23477. c11_string* name = f->decl->code.name;
  23478. // NOTE: copied from logic of `case tp_type:`
  23479. pkl__emit_op(buf, PKL_TYPE);
  23480. py_Type type = py_totype(self);
  23481. buf->used_types[type] = true;
  23482. pkl__emit_int(buf, type);
  23483. pkl__emit_op(buf, PKL_GETATTR);
  23484. pkl__emit_cstr(buf, name->data);
  23485. return true;
  23486. }
  23487. case tp_array2d: {
  23488. if(pkl__try_memo(buf, obj->_obj)) return true;
  23489. c11_array2d* arr = py_touserdata(obj);
  23490. for(int i = 0; i < arr->header.numel; i++) {
  23491. if(arr->data[i].is_ptr)
  23492. return TypeError(
  23493. "'array2d' object is not picklable because it contains heap-allocated objects");
  23494. buf->used_types[arr->data[i].type] = true;
  23495. }
  23496. pkl__emit_op(buf, PKL_ARRAY2D);
  23497. pkl__emit_int(buf, arr->header.n_cols);
  23498. pkl__emit_int(buf, arr->header.n_rows);
  23499. PickleObject__write_bytes(buf, arr->data, arr->header.numel * sizeof(py_TValue));
  23500. pkl__store_memo(buf, obj->_obj);
  23501. return true;
  23502. }
  23503. default: {
  23504. if(!obj->is_ptr) {
  23505. pkl__emit_op(buf, PKL_TVALUE);
  23506. PickleObject__write_bytes(buf, obj, sizeof(py_TValue));
  23507. buf->used_types[obj->type] = true;
  23508. return true;
  23509. }
  23510. // try memo for `is_ptr=true` objects
  23511. if(pkl__try_memo(buf, obj->_obj)) return true;
  23512. py_TypeInfo* ti = pk_typeinfo(obj->type);
  23513. py_Ref f_reduce = py_tpfindmagic(obj->type, __reduce__);
  23514. if(f_reduce != NULL) {
  23515. if(!py_call(f_reduce, 1, obj)) return false;
  23516. // expected: (callable, args)
  23517. py_Ref reduced = py_retval();
  23518. if(!py_istuple(reduced)) return TypeError("__reduce__ must return a tuple");
  23519. if(py_tuple_len(reduced) != 2) {
  23520. return TypeError("__reduce__ must return a tuple of length 2");
  23521. }
  23522. if(!pkl__write_object(buf, py_tuple_getitem(reduced, 0))) return false;
  23523. pkl__emit_op(buf, PKL_NIL);
  23524. py_Ref args_tuple = py_tuple_getitem(reduced, 1);
  23525. if(!py_istuple(args_tuple)) return TypeError("__reduce__ args must be a tuple");
  23526. int args_length = py_tuple_len(args_tuple);
  23527. for(int i = 0; i < args_length; i++) {
  23528. if(!pkl__write_object(buf, py_tuple_getitem(args_tuple, i))) return false;
  23529. }
  23530. pkl__emit_op(buf, PKL_CALL);
  23531. pkl__emit_int(buf, args_length);
  23532. // store memo
  23533. pkl__store_memo(buf, obj->_obj);
  23534. return true;
  23535. }
  23536. if(ti->is_python) {
  23537. NameDict* dict = PyObject__dict(obj->_obj);
  23538. for(int i = dict->capacity - 1; i >= 0; i--) {
  23539. NameDict_KV* kv = &dict->items[i];
  23540. if(kv->key == NULL) continue;
  23541. if(!pkl__write_object(buf, &kv->value)) return false;
  23542. }
  23543. pkl__emit_op(buf, PKL_OBJECT);
  23544. pkl__emit_int(buf, obj->type);
  23545. buf->used_types[obj->type] = true;
  23546. pkl__emit_int(buf, dict->length);
  23547. for(int i = 0; i < dict->capacity; i++) {
  23548. NameDict_KV* kv = &dict->items[i];
  23549. if(kv->key == NULL) continue;
  23550. c11_sv field = py_name2sv(kv->key);
  23551. // include '\0'
  23552. PickleObject__write_bytes(buf, field.data, field.size + 1);
  23553. }
  23554. // store memo
  23555. pkl__store_memo(buf, obj->_obj);
  23556. return true;
  23557. }
  23558. return TypeError("'%t' object is not picklable", obj->type);
  23559. }
  23560. }
  23561. c11__unreachable();
  23562. }
  23563. bool py_pickle_dumps(py_Ref val) {
  23564. PickleObject buf;
  23565. PickleObject__ctor(&buf);
  23566. bool ok = pkl__write_object(&buf, val);
  23567. if(!ok) {
  23568. PickleObject__dtor(&buf);
  23569. return false;
  23570. }
  23571. pkl__emit_op(&buf, PKL_EOF);
  23572. return PickleObject__py_submit(&buf, py_retval());
  23573. }
  23574. static py_Type pkl__header_find_type(c11_sv path) {
  23575. int sep_index = c11_sv__rindex(path, '.');
  23576. if(sep_index == -1) return py_gettype(NULL, py_namev(path));
  23577. c11_sv mod_name = c11_sv__slice2(path, 0, sep_index);
  23578. c11_sv name = c11_sv__slice(path, sep_index + 1);
  23579. char buf[PK_MAX_MODULE_PATH_LEN + 1];
  23580. memcpy(buf, mod_name.data, mod_name.size);
  23581. buf[mod_name.size] = '\0';
  23582. return py_gettype(buf, py_namev(name));
  23583. }
  23584. static c11_sv pkl__header_read_sv(const unsigned char** p, char sep) {
  23585. c11_sv text;
  23586. text.data = (const char*)*p;
  23587. const char* p_end = strchr(text.data, sep);
  23588. assert(p_end != NULL);
  23589. text.size = p_end - text.data;
  23590. *p = (const unsigned char*)p_end + 1;
  23591. return text;
  23592. }
  23593. static py_i64 pkl__header_read_int(const unsigned char** p, char sep) {
  23594. c11_sv text = pkl__header_read_sv(p, sep);
  23595. py_i64 out;
  23596. IntParsingResult res = c11__parse_uint(text, &out, 10);
  23597. assert(res == IntParsing_SUCCESS);
  23598. return out;
  23599. }
  23600. bool py_pickle_loads_body(const unsigned char* p, int memo_length, c11_smallmap_d2d* type_mapping);
  23601. bool py_pickle_loads(const unsigned char* data, int size) {
  23602. const unsigned char* p = data;
  23603. // PK
  23604. if(size < 2 || p[0] != 'P' || p[1] != 'K')
  23605. return ValueError("invalid pickle data");
  23606. p += 2;
  23607. c11_smallmap_d2d type_mapping;
  23608. c11_smallmap_d2d__ctor(&type_mapping);
  23609. while(true) {
  23610. if(*p == '\n') {
  23611. p++;
  23612. break;
  23613. }
  23614. py_Type type = pkl__header_read_int(&p, '(');
  23615. c11_sv path = pkl__header_read_sv(&p, ')');
  23616. py_Type new_type = pkl__header_find_type(path);
  23617. if(new_type == 0) {
  23618. c11_smallmap_d2d__dtor(&type_mapping);
  23619. return ImportError("cannot find type '%v'", path);
  23620. }
  23621. if(type != new_type) c11_smallmap_d2d__set(&type_mapping, type, new_type);
  23622. }
  23623. int memo_length = pkl__header_read_int(&p, '\n');
  23624. bool ok = py_pickle_loads_body(p, memo_length, &type_mapping);
  23625. c11_smallmap_d2d__dtor(&type_mapping);
  23626. return ok;
  23627. }
  23628. static py_Type pkl__fix_type(py_Type type, c11_smallmap_d2d* type_mapping) {
  23629. int new_type = c11_smallmap_d2d__get(type_mapping, type, -1);
  23630. if(new_type != -1) return (py_Type)new_type;
  23631. return type;
  23632. }
  23633. bool py_pickle_loads_body(const unsigned char* p, int memo_length, c11_smallmap_d2d* type_mapping) {
  23634. py_StackRef p0 = py_peek(0);
  23635. py_Ref p_memo = py_newtuple(py_pushtmp(), memo_length);
  23636. while(true) {
  23637. PickleOp op = (PickleOp)*p;
  23638. p++;
  23639. switch(op) {
  23640. case PKL_MEMO_GET: {
  23641. int index = pkl__read_int(&p);
  23642. py_Ref val = &p_memo[index];
  23643. assert(!py_isnil(val));
  23644. py_push(val);
  23645. break;
  23646. }
  23647. case PKL_MEMO_SET: {
  23648. int index = pkl__read_int(&p);
  23649. p_memo[index] = *py_peek(-1);
  23650. break;
  23651. }
  23652. case PKL_NIL: {
  23653. py_pushnil();
  23654. break;
  23655. }
  23656. case PKL_NONE: {
  23657. py_pushnone();
  23658. break;
  23659. }
  23660. case PKL_ELLIPSIS: {
  23661. py_newellipsis(py_pushtmp());
  23662. break;
  23663. }
  23664. // clang-format off
  23665. case PKL_INT_0: case PKL_INT_1: case PKL_INT_2: case PKL_INT_3:
  23666. case PKL_INT_4: case PKL_INT_5: case PKL_INT_6: case PKL_INT_7:
  23667. case PKL_INT_8: case PKL_INT_9: case PKL_INT_10: case PKL_INT_11:
  23668. case PKL_INT_12: case PKL_INT_13: case PKL_INT_14: case PKL_INT_15: {
  23669. py_newint(py_pushtmp(), op - PKL_INT_0);
  23670. break;
  23671. }
  23672. // clang-format on
  23673. case PKL_INT8: {
  23674. int8_t val;
  23675. UNALIGNED_READ(&val, p);
  23676. py_newint(py_pushtmp(), val);
  23677. break;
  23678. }
  23679. case PKL_INT16: {
  23680. int16_t val;
  23681. UNALIGNED_READ(&val, p);
  23682. py_newint(py_pushtmp(), val);
  23683. break;
  23684. }
  23685. case PKL_INT32: {
  23686. int32_t val;
  23687. UNALIGNED_READ(&val, p);
  23688. py_newint(py_pushtmp(), val);
  23689. break;
  23690. }
  23691. case PKL_INT64: {
  23692. int64_t val;
  23693. UNALIGNED_READ(&val, p);
  23694. py_newint(py_pushtmp(), val);
  23695. break;
  23696. }
  23697. case PKL_FLOAT32: {
  23698. float val;
  23699. UNALIGNED_READ(&val, p);
  23700. py_newfloat(py_pushtmp(), val);
  23701. break;
  23702. }
  23703. case PKL_FLOAT64: {
  23704. double val;
  23705. UNALIGNED_READ(&val, p);
  23706. py_newfloat(py_pushtmp(), val);
  23707. break;
  23708. }
  23709. case PKL_TRUE: {
  23710. py_newbool(py_pushtmp(), true);
  23711. break;
  23712. }
  23713. case PKL_FALSE: {
  23714. py_newbool(py_pushtmp(), false);
  23715. break;
  23716. }
  23717. case PKL_STRING: {
  23718. int size = pkl__read_int(&p);
  23719. char* dst = py_newstrn(py_pushtmp(), size);
  23720. memcpy(dst, p, size);
  23721. p += size;
  23722. break;
  23723. }
  23724. case PKL_BYTES: {
  23725. int size = pkl__read_int(&p);
  23726. unsigned char* dst = py_newbytes(py_pushtmp(), size);
  23727. memcpy(dst, p, size);
  23728. p += size;
  23729. break;
  23730. }
  23731. case PKL_BUILD_LIST: {
  23732. int length = pkl__read_int(&p);
  23733. py_Ref val = py_retval();
  23734. py_newlistn(val, length);
  23735. for(int i = length - 1; i >= 0; i--) {
  23736. py_StackRef item = py_peek(-1);
  23737. py_list_setitem(val, i, item);
  23738. py_pop();
  23739. }
  23740. py_push(val);
  23741. break;
  23742. }
  23743. case PKL_BUILD_TUPLE: {
  23744. int length = pkl__read_int(&p);
  23745. py_Ref val = py_retval();
  23746. py_Ref p = py_newtuple(val, length);
  23747. for(int i = length - 1; i >= 0; i--) {
  23748. p[i] = *py_peek(-1);
  23749. py_pop();
  23750. }
  23751. py_push(val);
  23752. break;
  23753. }
  23754. case PKL_BUILD_DICT: {
  23755. int length = pkl__read_int(&p);
  23756. py_Ref val = py_pushtmp();
  23757. py_newdict(val);
  23758. py_StackRef begin = py_peek(-1) - 2 * length;
  23759. py_StackRef end = py_peek(-1);
  23760. for(py_StackRef i = begin; i < end; i += 2) {
  23761. py_StackRef k = i;
  23762. py_StackRef v = i + 1;
  23763. bool ok = py_dict_setitem(val, k, v);
  23764. if(!ok) return false;
  23765. }
  23766. py_assign(py_retval(), val);
  23767. py_shrink(2 * length + 1);
  23768. py_push(py_retval());
  23769. break;
  23770. }
  23771. case PKL_VEC2: {
  23772. c11_vec2 val;
  23773. UNALIGNED_READ(&val, p);
  23774. py_newvec2(py_pushtmp(), val);
  23775. break;
  23776. }
  23777. case PKL_VEC3: {
  23778. c11_vec3 val;
  23779. UNALIGNED_READ(&val, p);
  23780. py_newvec3(py_pushtmp(), val);
  23781. break;
  23782. }
  23783. case PKL_VEC2I: {
  23784. c11_vec2i val;
  23785. val.x = pkl__read_int(&p);
  23786. val.y = pkl__read_int(&p);
  23787. py_newvec2i(py_pushtmp(), val);
  23788. break;
  23789. }
  23790. case PKL_VEC3I: {
  23791. c11_vec3i val;
  23792. val.x = pkl__read_int(&p);
  23793. val.y = pkl__read_int(&p);
  23794. val.z = pkl__read_int(&p);
  23795. py_newvec3i(py_pushtmp(), val);
  23796. break;
  23797. }
  23798. case PKL_TYPE: {
  23799. py_Type type = (py_Type)pkl__read_int(&p);
  23800. type = pkl__fix_type(type, type_mapping);
  23801. py_push(py_tpobject(type));
  23802. break;
  23803. }
  23804. case PKL_ARRAY2D: {
  23805. int n_cols = pkl__read_int(&p);
  23806. int n_rows = pkl__read_int(&p);
  23807. c11_array2d* arr = c11_newarray2d(py_pushtmp(), n_cols, n_rows);
  23808. int total_size = arr->header.numel * sizeof(py_TValue);
  23809. memcpy(arr->data, p, total_size);
  23810. for(int i = 0; i < arr->header.numel; i++) {
  23811. arr->data[i].type = pkl__fix_type(arr->data[i].type, type_mapping);
  23812. }
  23813. p += total_size;
  23814. break;
  23815. }
  23816. case PKL_IMPORT_PATH: {
  23817. const char* path = pkl__read_cstr(&p);
  23818. int res = py_import(path);
  23819. if(res == -1) return false;
  23820. if(res == 0) return ImportError("No module named '%s'", path);
  23821. py_push(py_retval());
  23822. break;
  23823. }
  23824. case PKL_GETATTR: {
  23825. const char* name = pkl__read_cstr(&p);
  23826. py_Ref obj = py_peek(-1);
  23827. if(!py_getattr(obj, py_name(name))) return false;
  23828. py_pop();
  23829. py_push(py_retval());
  23830. break;
  23831. }
  23832. case PKL_TVALUE: {
  23833. py_TValue* tmp = py_pushtmp();
  23834. memcpy(tmp, p, sizeof(py_TValue));
  23835. tmp->type = pkl__fix_type(tmp->type, type_mapping);
  23836. p += sizeof(py_TValue);
  23837. break;
  23838. }
  23839. case PKL_CALL: {
  23840. int argc = pkl__read_int(&p);
  23841. if(!py_vectorcall(argc, 0)) return false;
  23842. py_push(py_retval());
  23843. break;
  23844. }
  23845. case PKL_OBJECT: {
  23846. py_Type type = (py_Type)pkl__read_int(&p);
  23847. type = pkl__fix_type(type, type_mapping);
  23848. py_newobject(py_retval(), type, -1, 0);
  23849. NameDict* dict = PyObject__dict(py_retval()->_obj);
  23850. int dict_length = pkl__read_int(&p);
  23851. for(int i = 0; i < dict_length; i++) {
  23852. py_StackRef value = py_peek(-1);
  23853. c11_sv field = {(const char*)p, strlen((const char*)p)};
  23854. NameDict__set(dict, py_namev(field), value);
  23855. py_pop();
  23856. p += field.size + 1;
  23857. }
  23858. py_push(py_retval());
  23859. break;
  23860. }
  23861. case PKL_EOF: {
  23862. // [memo, obj]
  23863. if(py_peek(0) - p0 != 2) return ValueError("invalid pickle data");
  23864. py_assign(py_retval(), py_peek(-1));
  23865. py_shrink(2);
  23866. return true;
  23867. }
  23868. default: c11__unreachable();
  23869. }
  23870. }
  23871. c11__unreachable();
  23872. }
  23873. static bool PickleObject__py_submit(PickleObject* self, py_OutRef out) {
  23874. c11_sbuf cleartext;
  23875. c11_sbuf__ctor(&cleartext);
  23876. c11_sbuf__write_cstr(&cleartext, "PK");
  23877. // line 1: type mapping
  23878. for(py_Type type = 0; type < self->used_types_length; type++) {
  23879. if(self->used_types[type]) {
  23880. c11_sbuf__write_int(&cleartext, type);
  23881. c11_sbuf__write_char(&cleartext, '(');
  23882. c11_sbuf__write_type_path(&cleartext, type);
  23883. c11_sbuf__write_char(&cleartext, ')');
  23884. }
  23885. }
  23886. c11_sbuf__write_char(&cleartext, '\n');
  23887. // line 2: memo length
  23888. c11_sbuf__write_int(&cleartext, self->memo.length);
  23889. c11_sbuf__write_char(&cleartext, '\n');
  23890. // -------------------------------------------------- //
  23891. c11_string* header = c11_sbuf__submit(&cleartext);
  23892. int total_size = header->size + self->codes.length;
  23893. unsigned char* p = py_newbytes(py_retval(), total_size);
  23894. memcpy(p, header->data, header->size);
  23895. memcpy(p + header->size, self->codes.data, self->codes.length);
  23896. c11_string__delete(header);
  23897. PickleObject__dtor(self);
  23898. return true;
  23899. }
  23900. #undef UNALIGNED_READ
  23901. // src/modules\picoterm.c
  23902. #include <stdio.h>
  23903. const char* c11__u32_east_asian_width(int c);
  23904. static int c11__wcwidth(int c) {
  23905. if(c >= 32 && c < 0x7f) return 1;
  23906. if(c < 32) return 0;
  23907. const char* w = c11__u32_east_asian_width(c);
  23908. bool fullwidth = (w[0] == 'F' && w[1] == '\0') || (w[0] == 'W' && w[1] == '\0');
  23909. return fullwidth ? 2 : 1;
  23910. }
  23911. static bool picoterm_enable_full_buffering_mode(int argc, py_Ref argv) {
  23912. PY_CHECK_ARGC(0);
  23913. static char buf[1024 * 32]; // 32KB
  23914. setvbuf(stdout, buf, _IOFBF, sizeof(buf));
  23915. py_newnone(py_retval());
  23916. return true;
  23917. }
  23918. // https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
  23919. typedef struct {
  23920. c11_sv text;
  23921. char suffix;
  23922. } AnsiEscapedToken;
  23923. static bool split_ansi_escaped_string(c11_sv sv, c11_vector* out_tokens);
  23924. static bool picoterm_split_ansi_escaped_string(int argc, py_Ref argv) {
  23925. PY_CHECK_ARGC(1);
  23926. PY_CHECK_ARG_TYPE(0, tp_str);
  23927. c11_sv s = py_tosv(argv);
  23928. c11_vector /*T=AnsiEscapedToken*/ tokens;
  23929. c11_vector__ctor(&tokens, sizeof(AnsiEscapedToken));
  23930. if(!split_ansi_escaped_string(s, &tokens)) {
  23931. c11_vector__dtor(&tokens);
  23932. return ValueError("invalid ANSI escape sequences");
  23933. }
  23934. py_newlistn(py_retval(), tokens.length);
  23935. for(int i = 0; i < tokens.length; i++) {
  23936. AnsiEscapedToken t = c11__getitem(AnsiEscapedToken, &tokens, i);
  23937. py_ItemRef item = py_list_getitem(py_retval(), i);
  23938. py_newstrv(item, t.text);
  23939. }
  23940. c11_vector__dtor(&tokens);
  23941. return true;
  23942. }
  23943. static bool picoterm_wcwidth(int argc, py_Ref argv) {
  23944. PY_CHECK_ARGC(1);
  23945. PY_CHECK_ARG_TYPE(0, tp_int);
  23946. int c = py_toint(py_arg(0));
  23947. py_newint(py_retval(), c11__wcwidth(c));
  23948. return true;
  23949. }
  23950. static bool picoterm_wcswidth(int argc, py_Ref argv) {
  23951. PY_CHECK_ARGC(1);
  23952. PY_CHECK_ARG_TYPE(0, tp_str);
  23953. c11_sv sv = py_tosv(py_arg(0));
  23954. c11_vector /*T=AnsiEscapedToken*/ tokens;
  23955. c11_vector__ctor(&tokens, sizeof(AnsiEscapedToken));
  23956. if(!split_ansi_escaped_string(sv, &tokens)) {
  23957. c11_vector__dtor(&tokens);
  23958. return ValueError("invalid ANSI escape sequences");
  23959. }
  23960. int total_width = 0;
  23961. for(int i = 0; i < tokens.length; i++) {
  23962. AnsiEscapedToken* p_token = c11__at(AnsiEscapedToken, &tokens, i);
  23963. if(p_token->suffix != '\0') continue;
  23964. const char* curr_char = p_token->text.data;
  23965. const char* end_char = p_token->text.data + p_token->text.size;
  23966. while(curr_char < end_char) {
  23967. unsigned char c = *curr_char;
  23968. int u8bytes = c11__u8_header(c, true);
  23969. if(u8bytes == 0) return ValueError("invalid utf-8 header: %d", (int)c);
  23970. int value = c11__u8_value(u8bytes, curr_char);
  23971. total_width += c11__wcwidth(value);
  23972. curr_char += u8bytes;
  23973. }
  23974. }
  23975. c11_vector__dtor(&tokens);
  23976. py_newint(py_retval(), total_width);
  23977. return true;
  23978. }
  23979. static bool picoterm_sscanf(int argc, py_Ref argv) {
  23980. PY_CHECK_ARGC(3);
  23981. PY_CHECK_ARG_TYPE(0, tp_str);
  23982. PY_CHECK_ARG_TYPE(1, tp_str);
  23983. PY_CHECK_ARG_TYPE(2, tp_list);
  23984. const char* input = py_tostr(py_arg(0));
  23985. const char* format = py_tostr(py_arg(1));
  23986. py_Ref output_list = py_arg(2);
  23987. py_list_clear(output_list);
  23988. const char* p1 = input;
  23989. const char* p2 = format;
  23990. while(*p1 != '\0' && *p2 != '\0') {
  23991. if(*p2 == '%') {
  23992. p2++;
  23993. if(*p2 == 'd' || *p2 == 'i') {
  23994. bool negative = false;
  23995. if(*p1 == '-') {
  23996. negative = true;
  23997. p1++;
  23998. }
  23999. const char* start = p1;
  24000. while(*p1 >= '0' && *p1 <= '9')
  24001. p1++;
  24002. c11_sv num_sv = {.data = start, .size = p1 - start};
  24003. if(num_sv.size == 0) break;
  24004. int64_t value = 0;
  24005. IntParsingResult res = c11__parse_uint(num_sv, &value, 10);
  24006. if(res != IntParsing_SUCCESS) break;
  24007. if(negative) value = -value;
  24008. py_ItemRef item = py_list_emplace(output_list);
  24009. py_newint(item, value);
  24010. p2++;
  24011. } else {
  24012. return ValueError("unsupported format specifier: %%%c", *p2);
  24013. }
  24014. } else {
  24015. if(*p1 != *p2) break;
  24016. p1++;
  24017. p2++;
  24018. }
  24019. }
  24020. py_newbool(py_retval(), *p2 == '\0');
  24021. return true;
  24022. }
  24023. void pk__add_module_picoterm() {
  24024. py_Ref mod = py_newmodule("picoterm");
  24025. py_bindfunc(mod, "enable_full_buffering_mode", picoterm_enable_full_buffering_mode);
  24026. py_bindfunc(mod, "split_ansi_escaped_string", picoterm_split_ansi_escaped_string);
  24027. py_bindfunc(mod, "wcwidth", picoterm_wcwidth);
  24028. py_bindfunc(mod, "wcswidth", picoterm_wcswidth);
  24029. py_bindfunc(mod, "sscanf", picoterm_sscanf);
  24030. }
  24031. static bool split_ansi_escaped_string(c11_sv sv, c11_vector* out_tokens) {
  24032. const char* p = sv.data;
  24033. int i = 0;
  24034. while(i < sv.size) {
  24035. if(p[i] == '\x1b') {
  24036. i++; // skip '\x1b'
  24037. if(i >= sv.size || p[i] != '[') {
  24038. return false; // invalid escape sequence
  24039. }
  24040. int esc_start = i - 1;
  24041. i++; // skip '['
  24042. c11_sv content;
  24043. content.data = p + i;
  24044. while(i < sv.size && !((p[i] >= 'A' && p[i] <= 'Z') || (p[i] >= 'a' && p[i] <= 'z'))) {
  24045. i++;
  24046. }
  24047. content.size = p + i - content.data;
  24048. if(i >= sv.size) {
  24049. return false; // invalid escape sequence
  24050. }
  24051. char suffix = p[i];
  24052. i++; // skip suffix
  24053. AnsiEscapedToken token;
  24054. token.text = (c11_sv){p + esc_start, i - esc_start};
  24055. token.suffix = suffix;
  24056. c11_vector__push(AnsiEscapedToken, out_tokens, token);
  24057. } else if(p[i] == '\n') {
  24058. AnsiEscapedToken token;
  24059. token.text = (c11_sv){p + i, 1};
  24060. token.suffix = '\n';
  24061. c11_vector__push(AnsiEscapedToken, out_tokens, token);
  24062. i++;
  24063. } else {
  24064. int text_start = i;
  24065. while(i < sv.size && p[i] != '\x1b' && p[i] != '\n') {
  24066. i++;
  24067. }
  24068. AnsiEscapedToken token;
  24069. token.text = (c11_sv){p + text_start, i - text_start};
  24070. token.suffix = '\0';
  24071. c11_vector__push(AnsiEscapedToken, out_tokens, token);
  24072. }
  24073. }
  24074. return true;
  24075. }
  24076. // src/modules\pkpy.c
  24077. #include <time.h>
  24078. #define DEF_TVALUE_METHODS(T, Field) \
  24079. static bool TValue_##T##__new__(int argc, py_Ref argv) { \
  24080. PY_CHECK_ARGC(2); \
  24081. PY_CHECK_ARG_TYPE(0, tp_type); \
  24082. PY_CHECK_ARG_TYPE(1, tp_##T); \
  24083. *py_retval() = (py_TValue){ \
  24084. .type = py_totype(&argv[0]), \
  24085. .is_ptr = false, \
  24086. .Field = py_to##T(&argv[1]), \
  24087. }; \
  24088. return true; \
  24089. } \
  24090. static bool TValue_##T##_value(int argc, py_Ref argv) { \
  24091. PY_CHECK_ARGC(1); \
  24092. py_new##T(py_retval(), argv->Field); \
  24093. return true; \
  24094. } \
  24095. static bool TValue_##T##__repr__(int argc, py_Ref argv) { \
  24096. PY_CHECK_ARGC(1); \
  24097. py_newstr(py_retval(), "<TValue_" #T " object>"); \
  24098. return true; \
  24099. }
  24100. DEF_TVALUE_METHODS(int, _i64)
  24101. DEF_TVALUE_METHODS(float, _f64)
  24102. DEF_TVALUE_METHODS(vec2, _vec2)
  24103. DEF_TVALUE_METHODS(vec2i, _vec2i)
  24104. static bool pkpy_memory_usage(int argc, py_Ref argv) {
  24105. PY_CHECK_ARGC(0);
  24106. ManagedHeap* heap = &pk_current_vm->heap;
  24107. py_i64 size = MultiPool__total_allocated_bytes(&heap->small_objects);
  24108. size += heap->large_total_size;
  24109. size += sizeof(VM);
  24110. py_newint(py_retval(), size);
  24111. return true;
  24112. }
  24113. static bool pkpy_memory_usage_info(int argc, py_Ref argv) {
  24114. PY_CHECK_ARGC(0);
  24115. ManagedHeap* heap = &pk_current_vm->heap;
  24116. c11_string* small_objects_usage = MultiPool__summary(&heap->small_objects);
  24117. int large_object_count = heap->large_objects.length;
  24118. c11_sbuf buf;
  24119. c11_sbuf__ctor(&buf);
  24120. c11_sbuf__write_cstr(&buf, "== pre-allocated ==\n");
  24121. double vm_size_mb = sizeof(VM) / 1024.0 / 1024.0;
  24122. c11_sbuf__write_cstr(&buf, "VM: ");
  24123. c11_sbuf__write_f64(&buf, vm_size_mb, 2);
  24124. c11_sbuf__write_cstr(&buf, " MB\n");
  24125. c11_sbuf__write_cstr(&buf, "== heap.small_objects ==\n");
  24126. c11_sbuf__write_cstr(&buf, small_objects_usage->data);
  24127. c11_sbuf__write_cstr(&buf, "== heap.large_objects ==\n");
  24128. pk_sprintf(&buf, "len(large_objects)=%d\n", large_object_count);
  24129. double large_total_size_mb = (size_t)(heap->large_total_size / 1024) / 1024.0;
  24130. c11_sbuf__write_cstr(&buf, "Total: ~");
  24131. c11_sbuf__write_f64(&buf, large_total_size_mb, 2);
  24132. c11_sbuf__write_cstr(&buf, " MB\n");
  24133. c11_sbuf__write_cstr(&buf, "== heap.gc ==\n");
  24134. pk_sprintf(&buf, "gc_counter=%d\n", heap->gc_counter);
  24135. pk_sprintf(&buf, "gc_threshold=%d", heap->gc_threshold);
  24136. // c11_sbuf__write_cstr(&buf, "== vm.pool_frame ==\n");
  24137. c11_sbuf__py_submit(&buf, py_retval());
  24138. c11_string__delete(small_objects_usage);
  24139. return true;
  24140. }
  24141. static bool pkpy_currentvm(int argc, py_Ref argv) {
  24142. PY_CHECK_ARGC(0);
  24143. py_newint(py_retval(), py_currentvm());
  24144. return true;
  24145. }
  24146. #if PK_ENABLE_WATCHDOG
  24147. void py_watchdog_begin(py_i64 timeout) {
  24148. WatchdogInfo* info = &pk_current_vm->watchdog_info;
  24149. info->max_reset_time = clock() + (timeout * (CLOCKS_PER_SEC / 1000));
  24150. }
  24151. void py_watchdog_end() {
  24152. WatchdogInfo* info = &pk_current_vm->watchdog_info;
  24153. info->max_reset_time = 0;
  24154. }
  24155. static bool pkpy_watchdog_begin(int argc, py_Ref argv) {
  24156. PY_CHECK_ARGC(1);
  24157. PY_CHECK_ARG_TYPE(0, tp_int);
  24158. py_watchdog_begin(py_toint(argv));
  24159. py_newnone(py_retval());
  24160. return true;
  24161. }
  24162. static bool pkpy_watchdog_end(int argc, py_Ref argv) {
  24163. PY_CHECK_ARGC(0);
  24164. py_watchdog_end();
  24165. py_newnone(py_retval());
  24166. return true;
  24167. }
  24168. #endif
  24169. #if PK_ENABLE_THREADS
  24170. typedef struct c11_ComputeThread c11_ComputeThread;
  24171. typedef struct {
  24172. c11_ComputeThread* self;
  24173. char* eval_src;
  24174. unsigned char* args_data;
  24175. int args_size;
  24176. unsigned char* kwargs_data;
  24177. int kwargs_size;
  24178. } ComputeThreadJobCall;
  24179. typedef struct {
  24180. c11_ComputeThread* self;
  24181. char* source;
  24182. enum py_CompileMode mode;
  24183. } ComputeThreadJobExec;
  24184. static void ComputeThreadJobCall__dtor(void* arg) {
  24185. ComputeThreadJobCall* self = arg;
  24186. PK_FREE(self->eval_src);
  24187. PK_FREE(self->args_data);
  24188. PK_FREE(self->kwargs_data);
  24189. }
  24190. static void ComputeThreadJobExec__dtor(void* arg) {
  24191. ComputeThreadJobExec* self = arg;
  24192. PK_FREE(self->source);
  24193. }
  24194. typedef struct c11_ComputeThread {
  24195. int vm_index;
  24196. atomic_bool is_done;
  24197. unsigned char* last_retval_data;
  24198. int last_retval_size;
  24199. char* last_error;
  24200. c11_thrd_t thread;
  24201. void* job;
  24202. void (*job_dtor)(void*);
  24203. } c11_ComputeThread;
  24204. static void
  24205. c11_ComputeThread__reset_job(c11_ComputeThread* self, void* job, void (*job_dtor)(void*)) {
  24206. if(self->job) {
  24207. self->job_dtor(self->job);
  24208. PK_FREE(self->job);
  24209. }
  24210. self->job = job;
  24211. self->job_dtor = job_dtor;
  24212. }
  24213. static bool _pk_compute_thread_flags[16];
  24214. static void c11_ComputeThread__dtor(c11_ComputeThread* self) {
  24215. if(!atomic_load(&self->is_done)) {
  24216. c11__abort("ComputeThread(%d) is not done yet!! But the object was deleted.",
  24217. self->vm_index);
  24218. }
  24219. if(self->last_retval_data) PK_FREE(self->last_retval_data);
  24220. if(self->last_error) PK_FREE(self->last_error);
  24221. c11_ComputeThread__reset_job(self, NULL, NULL);
  24222. _pk_compute_thread_flags[self->vm_index] = false;
  24223. }
  24224. static void c11_ComputeThread__on_job_begin(c11_ComputeThread* self) {
  24225. if(self->last_retval_data) {
  24226. PK_FREE(self->last_retval_data);
  24227. self->last_retval_data = NULL;
  24228. self->last_retval_size = 0;
  24229. }
  24230. if(self->last_error) {
  24231. PK_FREE(self->last_error);
  24232. self->last_error = NULL;
  24233. }
  24234. py_switchvm(self->vm_index);
  24235. }
  24236. static bool ComputeThread__new__(int argc, py_Ref argv) {
  24237. c11_ComputeThread* self =
  24238. py_newobject(py_retval(), py_totype(argv), 0, sizeof(c11_ComputeThread));
  24239. self->vm_index = 0;
  24240. atomic_store(&self->is_done, true);
  24241. self->last_retval_data = NULL;
  24242. self->last_retval_size = 0;
  24243. self->last_error = NULL;
  24244. self->job = NULL;
  24245. self->job_dtor = NULL;
  24246. return true;
  24247. }
  24248. static bool ComputeThread__init__(int argc, py_Ref argv) {
  24249. PY_CHECK_ARGC(2);
  24250. PY_CHECK_ARG_TYPE(1, tp_int);
  24251. c11_ComputeThread* self = py_touserdata(py_arg(0));
  24252. int index = py_toint(py_arg(1));
  24253. if(index >= 1 && index < 16) {
  24254. if(_pk_compute_thread_flags[index]) {
  24255. return ValueError("vm_index %d is already in use", index);
  24256. }
  24257. _pk_compute_thread_flags[index] = true;
  24258. self->vm_index = index;
  24259. } else {
  24260. return ValueError("vm_index %d is out of range", index);
  24261. }
  24262. py_newnone(py_retval());
  24263. return true;
  24264. }
  24265. static bool ComputeThread_is_done(int argc, py_Ref argv) {
  24266. PY_CHECK_ARGC(1);
  24267. c11_ComputeThread* self = py_touserdata(argv);
  24268. bool value = atomic_load(&self->is_done);
  24269. py_newbool(py_retval(), value);
  24270. return true;
  24271. }
  24272. static bool ComputeThread_wait_for_done(int argc, py_Ref argv) {
  24273. PY_CHECK_ARGC(1);
  24274. c11_ComputeThread* self = py_touserdata(argv);
  24275. while(!atomic_load(&self->is_done)) {
  24276. c11_thrd__yield();
  24277. }
  24278. py_newnone(py_retval());
  24279. return true;
  24280. }
  24281. static bool ComputeThread_last_error(int argc, py_Ref argv) {
  24282. PY_CHECK_ARGC(1);
  24283. c11_ComputeThread* self = py_touserdata(argv);
  24284. if(!atomic_load(&self->is_done)) return OSError("thread is not done yet");
  24285. if(self->last_error) {
  24286. py_newstr(py_retval(), self->last_error);
  24287. } else {
  24288. py_newnone(py_retval());
  24289. }
  24290. return true;
  24291. }
  24292. static bool ComputeThread_last_retval(int argc, py_Ref argv) {
  24293. PY_CHECK_ARGC(1);
  24294. c11_ComputeThread* self = py_touserdata(argv);
  24295. if(!atomic_load(&self->is_done)) return OSError("thread is not done yet");
  24296. if(self->last_retval_data == NULL) return ValueError("no retval available");
  24297. return py_pickle_loads(self->last_retval_data, self->last_retval_size);
  24298. }
  24299. static c11_thrd_retval_t ComputeThreadJob_call(void* arg) {
  24300. ComputeThreadJobCall* job = arg;
  24301. c11_ComputeThread* self = job->self;
  24302. c11_ComputeThread__on_job_begin(self);
  24303. py_StackRef p0 = py_peek(0);
  24304. if(!py_pusheval(job->eval_src, NULL)) goto __ERROR;
  24305. // [callable]
  24306. if(!py_pickle_loads(job->args_data, job->args_size)) goto __ERROR;
  24307. py_push(py_retval());
  24308. // [callable, args]
  24309. if(!py_pickle_loads(job->kwargs_data, job->kwargs_size)) goto __ERROR;
  24310. py_push(py_retval());
  24311. // [callable, args, kwargs]
  24312. if(!py_smarteval("_0(*_1, **_2)", NULL, py_peek(-3), py_peek(-2), py_peek(-1))) goto __ERROR;
  24313. py_shrink(3);
  24314. if(!py_pickle_dumps(py_retval())) goto __ERROR;
  24315. int retval_size;
  24316. unsigned char* retval_data = py_tobytes(py_retval(), &retval_size);
  24317. self->last_retval_data = c11_memdup(retval_data, retval_size);
  24318. self->last_retval_size = retval_size;
  24319. atomic_store(&self->is_done, true);
  24320. return (c11_thrd_retval_t)0;
  24321. __ERROR:
  24322. self->last_error = py_formatexc();
  24323. atomic_store(&self->is_done, true);
  24324. py_clearexc(p0);
  24325. py_newnone(py_retval());
  24326. return (c11_thrd_retval_t)0;
  24327. }
  24328. static c11_thrd_retval_t ComputeThreadJob_exec(void* arg) {
  24329. ComputeThreadJobExec* job = arg;
  24330. c11_ComputeThread* self = job->self;
  24331. c11_ComputeThread__on_job_begin(self);
  24332. py_StackRef p0 = py_peek(0);
  24333. if(!py_exec(job->source, "<job>", job->mode, NULL)) goto __ERROR;
  24334. if(!py_pickle_dumps(py_retval())) goto __ERROR;
  24335. int retval_size;
  24336. unsigned char* retval_data = py_tobytes(py_retval(), &retval_size);
  24337. self->last_retval_data = c11_memdup(retval_data, retval_size);
  24338. self->last_retval_size = retval_size;
  24339. atomic_store(&self->is_done, true);
  24340. return (c11_thrd_retval_t)0;
  24341. __ERROR:
  24342. self->last_error = py_formatexc();
  24343. atomic_store(&self->is_done, true);
  24344. py_clearexc(p0);
  24345. return (c11_thrd_retval_t)0;
  24346. }
  24347. static bool ComputeThread_submit_exec(int argc, py_Ref argv) {
  24348. PY_CHECK_ARGC(2);
  24349. c11_ComputeThread* self = py_touserdata(py_arg(0));
  24350. if(!atomic_load(&self->is_done)) return OSError("thread is not done yet");
  24351. PY_CHECK_ARG_TYPE(1, tp_str);
  24352. const char* source = py_tostr(py_arg(1));
  24353. /**************************/
  24354. ComputeThreadJobExec* job = PK_MALLOC(sizeof(ComputeThreadJobExec));
  24355. job->self = self;
  24356. job->source = c11_strdup(source);
  24357. job->mode = EXEC_MODE;
  24358. c11_ComputeThread__reset_job(self, job, ComputeThreadJobExec__dtor);
  24359. /**************************/
  24360. atomic_store(&self->is_done, false);
  24361. bool ok = c11_thrd__create(&self->thread, ComputeThreadJob_exec, job);
  24362. if(!ok) {
  24363. atomic_store(&self->is_done, true);
  24364. return OSError("thrd_create() failed");
  24365. }
  24366. py_newnone(py_retval());
  24367. return true;
  24368. }
  24369. static bool ComputeThread_submit_eval(int argc, py_Ref argv) {
  24370. PY_CHECK_ARGC(2);
  24371. c11_ComputeThread* self = py_touserdata(py_arg(0));
  24372. if(!atomic_load(&self->is_done)) return OSError("thread is not done yet");
  24373. PY_CHECK_ARG_TYPE(1, tp_str);
  24374. const char* source = py_tostr(py_arg(1));
  24375. /**************************/
  24376. ComputeThreadJobExec* job = PK_MALLOC(sizeof(ComputeThreadJobExec));
  24377. job->self = self;
  24378. job->source = c11_strdup(source);
  24379. job->mode = EVAL_MODE;
  24380. c11_ComputeThread__reset_job(self, job, ComputeThreadJobExec__dtor);
  24381. /**************************/
  24382. atomic_store(&self->is_done, false);
  24383. bool ok = c11_thrd__create(&self->thread, ComputeThreadJob_exec, job);
  24384. if(!ok) {
  24385. atomic_store(&self->is_done, true);
  24386. return OSError("thrd_create() failed");
  24387. }
  24388. py_newnone(py_retval());
  24389. return true;
  24390. }
  24391. static bool ComputeThread_submit_call(int argc, py_Ref argv) {
  24392. PY_CHECK_ARGC(4);
  24393. c11_ComputeThread* self = py_touserdata(py_arg(0));
  24394. if(!atomic_load(&self->is_done)) return OSError("thread is not done yet");
  24395. PY_CHECK_ARG_TYPE(1, tp_str);
  24396. PY_CHECK_ARG_TYPE(2, tp_tuple);
  24397. PY_CHECK_ARG_TYPE(3, tp_dict);
  24398. // eval_src
  24399. const char* eval_src = py_tostr(py_arg(1));
  24400. // *args
  24401. if(!py_pickle_dumps(py_arg(2))) return false;
  24402. int args_size;
  24403. unsigned char* args_data = py_tobytes(py_retval(), &args_size);
  24404. // *kwargs
  24405. if(!py_pickle_dumps(py_arg(3))) return false;
  24406. int kwargs_size;
  24407. unsigned char* kwargs_data = py_tobytes(py_retval(), &kwargs_size);
  24408. /**************************/
  24409. ComputeThreadJobCall* job = PK_MALLOC(sizeof(ComputeThreadJobCall));
  24410. job->self = self;
  24411. job->eval_src = c11_strdup(eval_src);
  24412. job->args_data = c11_memdup(args_data, args_size);
  24413. job->args_size = args_size;
  24414. job->kwargs_data = c11_memdup(kwargs_data, kwargs_size);
  24415. job->kwargs_size = kwargs_size;
  24416. c11_ComputeThread__reset_job(self, job, ComputeThreadJobCall__dtor);
  24417. /**************************/
  24418. atomic_store(&self->is_done, false);
  24419. bool ok = c11_thrd__create(&self->thread, ComputeThreadJob_call, job);
  24420. if(!ok) {
  24421. atomic_store(&self->is_done, true);
  24422. return OSError("thrd_create() failed");
  24423. }
  24424. py_newnone(py_retval());
  24425. return true;
  24426. }
  24427. static bool c11_ComputeThread__exec_blocked(c11_ComputeThread* self,
  24428. const char* source,
  24429. enum py_CompileMode mode) {
  24430. if(!atomic_load(&self->is_done)) return OSError("thread is not done yet");
  24431. atomic_store(&self->is_done, false);
  24432. char* err = NULL;
  24433. int old_vm_index = py_currentvm();
  24434. py_switchvm(self->vm_index);
  24435. py_StackRef p0 = py_peek(0);
  24436. if(!py_exec(source, "<job_blocked>", mode, NULL)) goto __ERROR;
  24437. if(!py_pickle_dumps(py_retval())) goto __ERROR;
  24438. int retval_size;
  24439. unsigned char* retval_data = py_tobytes(py_retval(), &retval_size);
  24440. py_switchvm(old_vm_index);
  24441. bool ok = py_pickle_loads(retval_data, retval_size);
  24442. atomic_store(&self->is_done, true);
  24443. return ok;
  24444. __ERROR:
  24445. err = py_formatexc();
  24446. py_clearexc(p0);
  24447. py_switchvm(old_vm_index);
  24448. atomic_store(&self->is_done, true);
  24449. RuntimeError("c11_ComputeThread__exec_blocked() failed:\n%s", err);
  24450. PK_FREE(err);
  24451. return false;
  24452. }
  24453. static bool ComputeThread_exec(int argc, py_Ref argv) {
  24454. PY_CHECK_ARGC(2);
  24455. c11_ComputeThread* self = py_touserdata(py_arg(0));
  24456. PY_CHECK_ARG_TYPE(1, tp_str);
  24457. const char* source = py_tostr(py_arg(1));
  24458. return c11_ComputeThread__exec_blocked(self, source, EXEC_MODE);
  24459. }
  24460. static bool ComputeThread_eval(int argc, py_Ref argv) {
  24461. PY_CHECK_ARGC(2);
  24462. c11_ComputeThread* self = py_touserdata(py_arg(0));
  24463. PY_CHECK_ARG_TYPE(1, tp_str);
  24464. const char* source = py_tostr(py_arg(1));
  24465. return c11_ComputeThread__exec_blocked(self, source, EVAL_MODE);
  24466. }
  24467. static void pk_ComputeThread__register(py_Ref mod) {
  24468. py_Type type = py_newtype("ComputeThread", tp_object, mod, (py_Dtor)c11_ComputeThread__dtor);
  24469. py_bindmagic(type, __new__, ComputeThread__new__);
  24470. py_bindmagic(type, __init__, ComputeThread__init__);
  24471. py_bindproperty(type, "is_done", ComputeThread_is_done, NULL);
  24472. py_bindmethod(type, "wait_for_done", ComputeThread_wait_for_done);
  24473. py_bindmethod(type, "last_error", ComputeThread_last_error);
  24474. py_bindmethod(type, "last_retval", ComputeThread_last_retval);
  24475. py_bindmethod(type, "submit_exec", ComputeThread_submit_exec);
  24476. py_bindmethod(type, "submit_eval", ComputeThread_submit_eval);
  24477. py_bind(py_tpobject(type),
  24478. "submit_call(self, eval_src, *args, **kwargs)",
  24479. ComputeThread_submit_call);
  24480. py_bindmethod(type, "exec", ComputeThread_exec);
  24481. py_bindmethod(type, "eval", ComputeThread_eval);
  24482. }
  24483. #endif // PK_ENABLE_THREADS
  24484. static void pkpy_configmacros_add(py_Ref dict, const char* key, int val) {
  24485. assert(dict->type == tp_dict);
  24486. py_TValue tmp;
  24487. py_newint(&tmp, val);
  24488. py_dict_setitem_by_str(dict, key, &tmp);
  24489. }
  24490. static bool pkpy_profiler_begin(int argc, py_Ref argv) {
  24491. PY_CHECK_ARGC(0);
  24492. TraceInfo* trace_info = &pk_current_vm->trace_info;
  24493. if(trace_info->func == NULL) py_sys_settrace(LineProfiler_tracefunc, true);
  24494. if(trace_info->func != LineProfiler_tracefunc) {
  24495. return RuntimeError("LineProfiler_tracefunc() should be set as the trace function");
  24496. }
  24497. LineProfiler__begin(&pk_current_vm->line_profiler);
  24498. py_newnone(py_retval());
  24499. return true;
  24500. }
  24501. static bool pkpy_profiler_end(int argc, py_Ref argv) {
  24502. PY_CHECK_ARGC(0);
  24503. LineProfiler__end(&pk_current_vm->line_profiler);
  24504. py_newnone(py_retval());
  24505. return true;
  24506. }
  24507. static bool pkpy_profiler_reset(int argc, py_Ref argv) {
  24508. PY_CHECK_ARGC(0);
  24509. LineProfiler__reset(&pk_current_vm->line_profiler);
  24510. py_newnone(py_retval());
  24511. return true;
  24512. }
  24513. static bool pkpy_profiler_report(int argc, py_Ref argv) {
  24514. PY_CHECK_ARGC(0);
  24515. LineProfiler* lp = &pk_current_vm->line_profiler;
  24516. if(lp->enabled) LineProfiler__end(lp);
  24517. c11_string* report = LineProfiler__get_report(lp);
  24518. bool ok = py_json_loads(report->data);
  24519. c11_string__delete(report);
  24520. return ok;
  24521. }
  24522. void pk__add_module_pkpy() {
  24523. py_Ref mod = py_newmodule("pkpy");
  24524. py_Type ttype;
  24525. py_Ref TValue_dict = py_pushtmp();
  24526. py_newdict(TValue_dict);
  24527. ttype = pk_newtype("TValue_int", tp_object, mod, NULL, false, false);
  24528. py_bindmagic(ttype, __new__, TValue_int__new__);
  24529. py_bindmagic(ttype, __repr__, TValue_int__repr__);
  24530. py_bindproperty(ttype, "value", TValue_int_value, NULL);
  24531. py_dict_setitem(TValue_dict, py_tpobject(tp_int), py_tpobject(ttype));
  24532. ttype = pk_newtype("TValue_float", tp_object, mod, NULL, false, false);
  24533. py_bindmagic(ttype, __new__, TValue_float__new__);
  24534. py_bindmagic(ttype, __repr__, TValue_float__repr__);
  24535. py_bindproperty(ttype, "value", TValue_float_value, NULL);
  24536. py_dict_setitem(TValue_dict, py_tpobject(tp_float), py_tpobject(ttype));
  24537. ttype = pk_newtype("TValue_vec2", tp_object, mod, NULL, false, false);
  24538. py_bindmagic(ttype, __new__, TValue_vec2__new__);
  24539. py_bindmagic(ttype, __repr__, TValue_vec2__repr__);
  24540. py_bindproperty(ttype, "value", TValue_vec2_value, NULL);
  24541. py_dict_setitem(TValue_dict, py_tpobject(tp_vec2), py_tpobject(ttype));
  24542. ttype = pk_newtype("TValue_vec2i", tp_object, mod, NULL, false, false);
  24543. py_bindmagic(ttype, __new__, TValue_vec2i__new__);
  24544. py_bindmagic(ttype, __repr__, TValue_vec2i__repr__);
  24545. py_bindproperty(ttype, "value", TValue_vec2i_value, NULL);
  24546. py_dict_setitem(TValue_dict, py_tpobject(tp_vec2i), py_tpobject(ttype));
  24547. py_setdict(mod, py_name("TValue"), TValue_dict);
  24548. py_pop();
  24549. py_bindfunc(mod, "memory_usage", pkpy_memory_usage);
  24550. py_bindfunc(mod, "memory_usage_info", pkpy_memory_usage_info);
  24551. py_bindfunc(mod, "currentvm", pkpy_currentvm);
  24552. #if PK_ENABLE_WATCHDOG
  24553. py_bindfunc(mod, "watchdog_begin", pkpy_watchdog_begin);
  24554. py_bindfunc(mod, "watchdog_end", pkpy_watchdog_end);
  24555. #endif
  24556. #if PK_ENABLE_THREADS
  24557. pk_ComputeThread__register(mod);
  24558. #endif
  24559. py_bindfunc(mod, "profiler_begin", pkpy_profiler_begin);
  24560. py_bindfunc(mod, "profiler_end", pkpy_profiler_end);
  24561. py_bindfunc(mod, "profiler_reset", pkpy_profiler_reset);
  24562. py_bindfunc(mod, "profiler_report", pkpy_profiler_report);
  24563. py_Ref configmacros = py_emplacedict(mod, py_name("configmacros"));
  24564. py_newdict(configmacros);
  24565. pkpy_configmacros_add(configmacros, "PK_ENABLE_OS", PK_ENABLE_OS);
  24566. pkpy_configmacros_add(configmacros, "PK_ENABLE_THREADS", PK_ENABLE_THREADS);
  24567. pkpy_configmacros_add(configmacros, "PK_ENABLE_DETERMINISM", PK_ENABLE_DETERMINISM);
  24568. pkpy_configmacros_add(configmacros, "PK_ENABLE_WATCHDOG", PK_ENABLE_WATCHDOG);
  24569. pkpy_configmacros_add(configmacros, "PK_GC_MIN_THRESHOLD", PK_GC_MIN_THRESHOLD);
  24570. pkpy_configmacros_add(configmacros, "PK_VM_STACK_SIZE", PK_VM_STACK_SIZE);
  24571. }
  24572. #undef DEF_TVALUE_METHODS
  24573. // src/modules\random.c
  24574. /* https://github.com/clibs/mt19937ar
  24575. Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima
  24576. University and The University of Tokyo. All rights reserved.
  24577. Redistribution and use in source and binary forms, with or without
  24578. modification, are permitted provided that the following conditions are
  24579. met:
  24580. * Redistributions of source code must retain the above copyright
  24581. notice, this list of conditions and the following disclaimer.
  24582. * Redistributions in binary form must reproduce the above
  24583. copyright notice, this list of conditions and the following
  24584. disclaimer in the documentation and/or other materials provided
  24585. with the distribution.
  24586. * Neither the name of the Hiroshima University nor the names of
  24587. its contributors may be used to endorse or promote products
  24588. derived from this software without specific prior written
  24589. permission.
  24590. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24591. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24592. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24593. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24594. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24595. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24596. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24597. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24598. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24599. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24600. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24601. */
  24602. /* Period parameters */
  24603. #define N 624
  24604. #define M 397
  24605. #define MATRIX_A 0x9908b0dfUL /* constant vector a */
  24606. #define UPPER_MASK 0x80000000UL /* most significant w-r bits */
  24607. #define LOWER_MASK 0x7fffffffUL /* least significant r bits */
  24608. typedef struct mt19937 {
  24609. uint32_t mt[N]; /* the array for the state vector */
  24610. int mti; /* mti==N+1 means mt[N] is not initialized */
  24611. } mt19937;
  24612. /* initializes mt[N] with a seed */
  24613. static void mt19937__seed(mt19937* self, uint32_t s) {
  24614. self->mt[0] = s & 0xffffffffUL;
  24615. for(self->mti = 1; self->mti < N; self->mti++) {
  24616. self->mt[self->mti] =
  24617. (1812433253UL * (self->mt[self->mti - 1] ^ (self->mt[self->mti - 1] >> 30)) +
  24618. self->mti);
  24619. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  24620. /* In the previous versions, MSBs of the seed affect */
  24621. /* only MSBs of the array mt[]. */
  24622. /* 2002/01/09 modified by Makoto Matsumoto */
  24623. self->mt[self->mti] &= 0xffffffffUL;
  24624. /* for >32 bit machines */
  24625. }
  24626. }
  24627. static void mt19937__ctor(mt19937* self) { self->mti = N + 1; }
  24628. /* generates a random number on [0,0xffffffff]-interval */
  24629. static uint32_t mt19937__next_uint32(mt19937* self) {
  24630. uint32_t* mt = self->mt;
  24631. uint32_t y;
  24632. static uint32_t mag01[2] = {0x0UL, MATRIX_A};
  24633. /* mag01[x] = x * MATRIX_A for x=0,1 */
  24634. if(self->mti >= N) { /* generate N words at one time */
  24635. int kk;
  24636. if(self->mti == N + 1) { /* if init_genrand() has not been called, */
  24637. int64_t seed = time_ns();
  24638. mt19937__seed(self, (uint32_t)seed);
  24639. // seed(5489UL); /* a default initial seed is used */
  24640. }
  24641. for(kk = 0; kk < N - M; kk++) {
  24642. y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
  24643. mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 0x1UL];
  24644. }
  24645. for(; kk < N - 1; kk++) {
  24646. y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
  24647. mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
  24648. }
  24649. y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
  24650. mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 0x1UL];
  24651. self->mti = 0;
  24652. }
  24653. y = mt[self->mti++];
  24654. /* Tempering */
  24655. y ^= (y >> 11);
  24656. y ^= (y << 7) & 0x9d2c5680UL;
  24657. y ^= (y << 15) & 0xefc60000UL;
  24658. y ^= (y >> 18);
  24659. return y;
  24660. }
  24661. static uint64_t mt19937__next_uint64(mt19937* self) {
  24662. return (uint64_t)mt19937__next_uint32(self) << 32 | mt19937__next_uint32(self);
  24663. }
  24664. static double mt19937__random(mt19937* self) {
  24665. // from cpython
  24666. uint32_t a = mt19937__next_uint32(self) >> 5;
  24667. uint32_t b = mt19937__next_uint32(self) >> 6;
  24668. return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
  24669. }
  24670. static double mt19937__uniform(mt19937* self, double a, double b) {
  24671. if(a > b) { return b + mt19937__random(self) * (a - b); }
  24672. return a + mt19937__random(self) * (b - a);
  24673. }
  24674. /* generates a random number on [a, b]-interval */
  24675. int64_t mt19937__randint(mt19937* self, int64_t a, int64_t b) {
  24676. uint64_t delta = b - a + 1;
  24677. if(delta < 0x80000000UL) {
  24678. return a + mt19937__next_uint32(self) % delta;
  24679. } else {
  24680. return a + mt19937__next_uint64(self) % delta;
  24681. }
  24682. }
  24683. static bool Random__new__(int argc, py_Ref argv) {
  24684. mt19937* ud = py_newobject(py_retval(), py_totype(argv), 0, sizeof(mt19937));
  24685. mt19937__ctor(ud);
  24686. return true;
  24687. }
  24688. static bool Random__init__(int argc, py_Ref argv) {
  24689. if(argc == 1) {
  24690. // do nothing
  24691. } else if(argc == 2) {
  24692. mt19937* ud = py_touserdata(py_arg(0));
  24693. if(!py_isnone(&argv[1])) {
  24694. PY_CHECK_ARG_TYPE(1, tp_int);
  24695. py_i64 seed = py_toint(py_arg(1));
  24696. mt19937__seed(ud, (uint32_t)seed);
  24697. }
  24698. } else {
  24699. return TypeError("Random(): expected 1 or 2 arguments, got %d");
  24700. }
  24701. py_newnone(py_retval());
  24702. return true;
  24703. }
  24704. static bool Random_seed(int argc, py_Ref argv) {
  24705. PY_CHECK_ARGC(2);
  24706. mt19937* ud = py_touserdata(py_arg(0));
  24707. py_i64 seed;
  24708. if(py_isnone(&argv[1])) {
  24709. seed = time_ns();
  24710. } else {
  24711. PY_CHECK_ARG_TYPE(1, tp_int);
  24712. seed = py_toint(py_arg(1));
  24713. }
  24714. mt19937__seed(ud, (uint32_t)seed);
  24715. py_newnone(py_retval());
  24716. return true;
  24717. }
  24718. static bool Random_random(int argc, py_Ref argv) {
  24719. PY_CHECK_ARGC(1);
  24720. mt19937* ud = py_touserdata(py_arg(0));
  24721. py_f64 res = mt19937__random(ud);
  24722. py_newfloat(py_retval(), res);
  24723. return true;
  24724. }
  24725. static bool Random_uniform(int argc, py_Ref argv) {
  24726. PY_CHECK_ARGC(3);
  24727. mt19937* ud = py_touserdata(py_arg(0));
  24728. py_f64 a, b;
  24729. if(!py_castfloat(py_arg(1), &a)) return false;
  24730. if(!py_castfloat(py_arg(2), &b)) return false;
  24731. py_f64 res = mt19937__uniform(ud, a, b);
  24732. py_newfloat(py_retval(), res);
  24733. return true;
  24734. }
  24735. static bool Random_shuffle(int argc, py_Ref argv) {
  24736. PY_CHECK_ARGC(2);
  24737. PY_CHECK_ARG_TYPE(1, tp_list);
  24738. mt19937* ud = py_touserdata(py_arg(0));
  24739. py_Ref L = py_arg(1);
  24740. int length = py_list_len(L);
  24741. for(int i = length - 1; i > 0; i--) {
  24742. int j = mt19937__randint(ud, 0, i);
  24743. py_list_swap(L, i, j);
  24744. }
  24745. py_newnone(py_retval());
  24746. return true;
  24747. }
  24748. static bool Random_randint(int argc, py_Ref argv) {
  24749. PY_CHECK_ARGC(3);
  24750. PY_CHECK_ARG_TYPE(1, tp_int);
  24751. PY_CHECK_ARG_TYPE(2, tp_int);
  24752. mt19937* ud = py_touserdata(py_arg(0));
  24753. py_i64 a = py_toint(py_arg(1));
  24754. py_i64 b = py_toint(py_arg(2));
  24755. if(a > b) return ValueError("randint(a, b): a must be less than or equal to b");
  24756. py_i64 res = mt19937__randint(ud, a, b);
  24757. py_newint(py_retval(), res);
  24758. return true;
  24759. }
  24760. static bool Random_choice(int argc, py_Ref argv) {
  24761. PY_CHECK_ARGC(2);
  24762. mt19937* ud = py_touserdata(py_arg(0));
  24763. if (py_isstr(py_arg(1))) {
  24764. c11_sv sv = py_tosv(py_arg(1));
  24765. int length = c11_sv__u8_length(sv);
  24766. if(length == 0) return IndexError("cannot choose from an empty sequence");
  24767. int index = mt19937__randint(ud, 0, length - 1);
  24768. c11_sv ch = c11_sv__u8_getitem(sv, index);
  24769. py_newstrv(py_retval(), ch);
  24770. } else {
  24771. py_TValue* p;
  24772. int length = pk_arrayview(py_arg(1), &p);
  24773. if(length == -1) return TypeError("choice(): argument must be a list, tuple or str");
  24774. if(length == 0) return IndexError("cannot choose from an empty sequence");
  24775. int index = mt19937__randint(ud, 0, length - 1);
  24776. py_assign(py_retval(), p + index);
  24777. }
  24778. return true;
  24779. }
  24780. static bool Random_choices(int argc, py_Ref argv) {
  24781. mt19937* ud = py_touserdata(py_arg(0));
  24782. py_TValue* p;
  24783. int length = pk_arrayview(py_arg(1), &p);
  24784. if(length == -1) return TypeError("choices(): argument must be a list or tuple");
  24785. if(length == 0) return IndexError("cannot choose from an empty sequence");
  24786. py_Ref weights = py_arg(2);
  24787. if(!py_checktype(py_arg(3), tp_int)) return false;
  24788. py_i64 k = py_toint(py_arg(3));
  24789. py_f64* cum_weights = PK_MALLOC(sizeof(py_f64) * length);
  24790. if(py_isnone(weights)) {
  24791. for(int i = 0; i < length; i++)
  24792. cum_weights[i] = i + 1;
  24793. } else {
  24794. py_TValue* w;
  24795. int wlen = pk_arrayview(weights, &w);
  24796. if(wlen == -1) {
  24797. PK_FREE(cum_weights);
  24798. return TypeError("choices(): weights must be a list or tuple");
  24799. }
  24800. if(wlen != length) {
  24801. PK_FREE(cum_weights);
  24802. return ValueError("len(weights) != len(population)");
  24803. }
  24804. if(!py_castfloat(&w[0], &cum_weights[0])) {
  24805. PK_FREE(cum_weights);
  24806. return false;
  24807. }
  24808. for(int i = 1; i < length; i++) {
  24809. py_f64 tmp;
  24810. if(!py_castfloat(&w[i], &tmp)) {
  24811. PK_FREE(cum_weights);
  24812. return false;
  24813. }
  24814. cum_weights[i] = cum_weights[i - 1] + tmp;
  24815. }
  24816. }
  24817. py_f64 total = cum_weights[length - 1];
  24818. if(total <= 1e-6) {
  24819. PK_FREE(cum_weights);
  24820. return ValueError("total of weights must be greater than 1e-6");
  24821. }
  24822. py_newlistn(py_retval(), k);
  24823. for(int i = 0; i < k; i++) {
  24824. py_f64 key = mt19937__random(ud) * total;
  24825. int index;
  24826. c11__lower_bound(py_f64, cum_weights, length, key, c11__less, &index);
  24827. assert(index != length);
  24828. py_list_setitem(py_retval(), i, p + index);
  24829. }
  24830. PK_FREE(cum_weights);
  24831. return true;
  24832. }
  24833. void pk__add_module_random() {
  24834. py_Ref mod = py_newmodule("random");
  24835. py_Type type = py_newtype("Random", tp_object, mod, NULL);
  24836. py_bindmagic(type, __new__, Random__new__);
  24837. py_bindmagic(type, __init__, Random__init__);
  24838. py_bindmethod(type, "seed", Random_seed);
  24839. py_bindmethod(type, "random", Random_random);
  24840. py_bindmethod(type, "uniform", Random_uniform);
  24841. py_bindmethod(type, "randint", Random_randint);
  24842. py_bindmethod(type, "shuffle", Random_shuffle);
  24843. py_bindmethod(type, "choice", Random_choice);
  24844. py_bind(py_tpobject(type), "choices(self, population, weights=None, k=1)", Random_choices);
  24845. py_Ref inst = py_pushtmp();
  24846. if(!py_tpcall(type, 0, NULL)) goto __ERROR;
  24847. py_assign(inst, py_retval());
  24848. #define ADD_INST_BOUNDMETHOD(name) \
  24849. if(!py_getattr(inst, py_name(name))) goto __ERROR; \
  24850. py_setdict(mod, py_name(name), py_retval());
  24851. ADD_INST_BOUNDMETHOD("seed");
  24852. ADD_INST_BOUNDMETHOD("random");
  24853. ADD_INST_BOUNDMETHOD("uniform");
  24854. ADD_INST_BOUNDMETHOD("randint");
  24855. ADD_INST_BOUNDMETHOD("shuffle");
  24856. ADD_INST_BOUNDMETHOD("choice");
  24857. ADD_INST_BOUNDMETHOD("choices");
  24858. #undef ADD_INST_BOUNDMETHOD
  24859. py_pop(); // pop inst
  24860. return;
  24861. __ERROR:
  24862. py_printexc();
  24863. c11__abort("failed to add module random");
  24864. }
  24865. #undef N
  24866. #undef M
  24867. #undef MATRIX_A
  24868. #undef UPPER_MASK
  24869. #undef LOWER_MASK
  24870. #undef ADD_INST_BOUNDMETHOD
  24871. void py_newRandom(py_OutRef out) {
  24872. py_Type type = py_gettype("random", py_name("Random"));
  24873. assert(type != 0);
  24874. mt19937* ud = py_newobject(out, type, 0, sizeof(mt19937));
  24875. mt19937__ctor(ud);
  24876. }
  24877. void py_Random_seed(py_Ref self, py_i64 seed) {
  24878. mt19937* ud = py_touserdata(self);
  24879. mt19937__seed(ud, (uint32_t)seed);
  24880. }
  24881. py_f64 py_Random_random(py_Ref self) {
  24882. mt19937* ud = py_touserdata(self);
  24883. return mt19937__random(ud);
  24884. }
  24885. py_f64 py_Random_uniform(py_Ref self, py_f64 a, py_f64 b) {
  24886. mt19937* ud = py_touserdata(self);
  24887. return mt19937__uniform(ud, a, b);
  24888. }
  24889. py_i64 py_Random_randint(py_Ref self, py_i64 a, py_i64 b) {
  24890. mt19937* ud = py_touserdata(self);
  24891. if(a > b) { c11__abort("randint(a, b): a must be less than or equal to b"); }
  24892. return mt19937__randint(ud, a, b);
  24893. }
  24894. // src/modules\stdc.c
  24895. #include <string.h>
  24896. #define DEF_BUILTIN_MEMORY_T(Char_, char_, tp_int_, py_newint_, py_toint_, py_i64_) \
  24897. static bool stdc_##Char_##__new__(int argc, py_Ref argv) { \
  24898. char_* ud = py_newobject(py_retval(), tp_stdc_##Char_, 0, sizeof(char_)); \
  24899. if(argc == 2) { \
  24900. PY_CHECK_ARG_TYPE(1, tp_int_); \
  24901. *ud = (char_)py_toint_(&argv[1]); \
  24902. } else if(argc > 2) { \
  24903. return TypeError("expected 1 or 2 arguments, got %d", argc); \
  24904. } \
  24905. return true; \
  24906. } \
  24907. static bool stdc_##Char_##__get_value(int argc, py_Ref argv) { \
  24908. PY_CHECK_ARGC(1); \
  24909. char_* ud = py_touserdata(argv); \
  24910. py_newint_(py_retval(), (py_i64_)(*ud)); \
  24911. return true; \
  24912. } \
  24913. static bool stdc_##Char_##__set_value(int argc, py_Ref argv) { \
  24914. PY_CHECK_ARGC(2); \
  24915. char_* ud = py_touserdata(argv); \
  24916. PY_CHECK_ARG_TYPE(1, tp_int_); \
  24917. *ud = (char_)py_toint_(&argv[1]); \
  24918. py_newnone(py_retval()); \
  24919. return true; \
  24920. } \
  24921. static bool stdc_##Char_##__read_STATIC(int argc, py_Ref argv) { \
  24922. PY_CHECK_ARGC(2); \
  24923. PY_CHECK_ARG_TYPE(0, tp_int); \
  24924. PY_CHECK_ARG_TYPE(1, tp_int); \
  24925. char_* p = (char_*)(intptr_t)py_toint(&argv[0]); \
  24926. int offset = py_toint(&argv[1]); \
  24927. py_newint_(py_retval(), (py_i64_)(p[offset])); \
  24928. return true; \
  24929. } \
  24930. static bool stdc_##Char_##__write_STATIC(int argc, py_Ref argv) { \
  24931. PY_CHECK_ARGC(3); \
  24932. PY_CHECK_ARG_TYPE(0, tp_int); \
  24933. PY_CHECK_ARG_TYPE(1, tp_int); \
  24934. PY_CHECK_ARG_TYPE(2, tp_int_); \
  24935. char_* p = (char_*)(intptr_t)py_toint(&argv[0]); \
  24936. int offset = py_toint(&argv[1]); \
  24937. p[offset] = (char_)py_toint_(&argv[2]); \
  24938. py_newnone(py_retval()); \
  24939. return true; \
  24940. } \
  24941. static bool stdc_##Char_##__array_STATIC(int argc, py_Ref argv) { \
  24942. PY_CHECK_ARGC(1); \
  24943. PY_CHECK_ARG_TYPE(0, tp_int); \
  24944. int length = py_toint(argv); \
  24945. int size = sizeof(char_) * length; \
  24946. py_newobject(py_retval(), tp_stdc_##Char_, 0, size); \
  24947. return true; \
  24948. } \
  24949. static bool stdc_##Char_##__getitem__(int argc, py_Ref argv) { \
  24950. PY_CHECK_ARGC(2); \
  24951. char_* ud = py_touserdata(argv); \
  24952. PY_CHECK_ARG_TYPE(1, tp_int); \
  24953. int index = py_toint(&argv[1]); \
  24954. py_newint_(py_retval(), (py_i64_)(ud[index])); \
  24955. return true; \
  24956. } \
  24957. static bool stdc_##Char_##__setitem__(int argc, py_Ref argv) { \
  24958. PY_CHECK_ARGC(3); \
  24959. char_* ud = py_touserdata(argv); \
  24960. PY_CHECK_ARG_TYPE(1, tp_int); \
  24961. PY_CHECK_ARG_TYPE(2, tp_int_); \
  24962. int index = py_toint(&argv[1]); \
  24963. ud[index] = (char_)py_toint_(&argv[2]); \
  24964. py_newnone(py_retval()); \
  24965. return true; \
  24966. } \
  24967. static void pk__bind_stdc_##Char_(py_Ref mod) { \
  24968. py_Type type = py_newtype(#Char_, tp_stdc_Memory, mod, NULL); \
  24969. py_tpsetfinal(type); \
  24970. assert(type == tp_stdc_##Char_); \
  24971. py_bindmagic(type, __new__, stdc_##Char_##__new__); \
  24972. py_bindmagic(type, __getitem__, stdc_##Char_##__getitem__); \
  24973. py_bindmagic(type, __setitem__, stdc_##Char_##__setitem__); \
  24974. py_bindproperty(type, "value", stdc_##Char_##__get_value, stdc_##Char_##__set_value); \
  24975. py_bindstaticmethod(type, "read", stdc_##Char_##__read_STATIC); \
  24976. py_bindstaticmethod(type, "write", stdc_##Char_##__write_STATIC); \
  24977. py_bindstaticmethod(type, "array", stdc_##Char_##__array_STATIC); \
  24978. py_newint(py_emplacedict(py_tpobject(type), py_name("size")), sizeof(char_)); \
  24979. }
  24980. DEF_BUILTIN_MEMORY_T(Char, char, tp_int, py_newint, py_toint, py_i64)
  24981. DEF_BUILTIN_MEMORY_T(UChar, unsigned char, tp_int, py_newint, py_toint, py_i64)
  24982. DEF_BUILTIN_MEMORY_T(Short, short, tp_int, py_newint, py_toint, py_i64)
  24983. DEF_BUILTIN_MEMORY_T(UShort, unsigned short, tp_int, py_newint, py_toint, py_i64)
  24984. DEF_BUILTIN_MEMORY_T(Int, int, tp_int, py_newint, py_toint, py_i64)
  24985. DEF_BUILTIN_MEMORY_T(UInt, unsigned int, tp_int, py_newint, py_toint, py_i64)
  24986. DEF_BUILTIN_MEMORY_T(Long, long, tp_int, py_newint, py_toint, py_i64)
  24987. DEF_BUILTIN_MEMORY_T(ULong, unsigned long, tp_int, py_newint, py_toint, py_i64)
  24988. DEF_BUILTIN_MEMORY_T(LongLong, long long, tp_int, py_newint, py_toint, py_i64)
  24989. DEF_BUILTIN_MEMORY_T(ULongLong, unsigned long long, tp_int, py_newint, py_toint, py_i64)
  24990. DEF_BUILTIN_MEMORY_T(Float, float, tp_float, py_newfloat, py_tofloat, float)
  24991. DEF_BUILTIN_MEMORY_T(Double, double, tp_float, py_newfloat, py_tofloat, double)
  24992. DEF_BUILTIN_MEMORY_T(Pointer, void*, tp_int, py_newint, py_toint, py_i64)
  24993. DEF_BUILTIN_MEMORY_T(Bool, bool, tp_bool, py_newbool, py_tobool, bool)
  24994. #undef DEF_BUILTIN_MEMORY_T
  24995. static bool stdc_malloc(int argc, py_Ref argv) {
  24996. PY_CHECK_ARGC(1);
  24997. PY_CHECK_ARG_TYPE(0, tp_int);
  24998. py_i64 size = py_toint(&argv[0]);
  24999. void* p = py_malloc(size);
  25000. py_newint(py_retval(), (py_i64)(intptr_t)p);
  25001. return true;
  25002. }
  25003. static bool stdc_free(int argc, py_Ref argv) {
  25004. PY_CHECK_ARGC(1);
  25005. PY_CHECK_ARG_TYPE(0, tp_int);
  25006. void* p = (void*)(intptr_t)py_toint(&argv[0]);
  25007. py_free(p);
  25008. py_newnone(py_retval());
  25009. return true;
  25010. }
  25011. static bool stdc_memcpy(int argc, py_Ref argv) {
  25012. PY_CHECK_ARGC(3);
  25013. PY_CHECK_ARG_TYPE(0, tp_int); // dst
  25014. void* dst = (void*)(intptr_t)py_toint(&argv[0]);
  25015. PY_CHECK_ARG_TYPE(2, tp_int); // n
  25016. py_i64 n = py_toint(&argv[2]);
  25017. void* src;
  25018. if(py_istype(&argv[1], tp_bytes)) {
  25019. int size;
  25020. src = py_tobytes(&argv[1], &size);
  25021. if(size < n) n = size;
  25022. } else {
  25023. PY_CHECK_ARG_TYPE(1, tp_int); // src
  25024. src = (void*)(intptr_t)py_toint(&argv[1]);
  25025. }
  25026. memcpy(dst, src, (size_t)n);
  25027. py_newnone(py_retval());
  25028. return true;
  25029. }
  25030. static bool stdc_memset(int argc, py_Ref argv) {
  25031. PY_CHECK_ARGC(3);
  25032. PY_CHECK_ARG_TYPE(0, tp_int);
  25033. PY_CHECK_ARG_TYPE(1, tp_int);
  25034. PY_CHECK_ARG_TYPE(2, tp_int);
  25035. void* dst = (void*)(intptr_t)py_toint(&argv[0]);
  25036. int value = (int)py_toint(&argv[1]);
  25037. py_i64 n = py_toint(&argv[2]);
  25038. memset(dst, value, (size_t)n);
  25039. py_newnone(py_retval());
  25040. return true;
  25041. }
  25042. static bool stdc_memcmp(int argc, py_Ref argv) {
  25043. PY_CHECK_ARGC(3);
  25044. PY_CHECK_ARG_TYPE(0, tp_int);
  25045. PY_CHECK_ARG_TYPE(1, tp_int);
  25046. PY_CHECK_ARG_TYPE(2, tp_int);
  25047. void* p1 = (void*)(intptr_t)py_toint(&argv[0]);
  25048. void* p2 = (void*)(intptr_t)py_toint(&argv[1]);
  25049. py_i64 n = py_toint(&argv[2]);
  25050. int res = memcmp(p1, p2, (size_t)n);
  25051. py_newint(py_retval(), (py_i64)res);
  25052. return true;
  25053. }
  25054. static bool stdc_addressof(int argc, py_Ref argv) {
  25055. PY_CHECK_ARGC(1);
  25056. if(!py_checkinstance(argv, tp_stdc_Memory)) return false;
  25057. void* ud = py_touserdata(argv);
  25058. py_newint(py_retval(), (py_i64)(intptr_t)ud);
  25059. return true;
  25060. }
  25061. static bool stdc_sizeof(int argc, py_Ref argv) {
  25062. PY_CHECK_ARGC(1);
  25063. PY_CHECK_ARG_TYPE(0, tp_type);
  25064. py_Type type = py_totype(&argv[0]);
  25065. if(!py_issubclass(type, tp_stdc_Memory)) {
  25066. return TypeError("expected a type derived from stdc.Memory");
  25067. }
  25068. py_assign(py_retval(), py_getdict(py_tpobject(type), py_name("size")));
  25069. return true;
  25070. }
  25071. static bool stdc_read_cstr(int argc, py_Ref argv) {
  25072. PY_CHECK_ARGC(1);
  25073. PY_CHECK_ARG_TYPE(0, tp_int);
  25074. char* p = (char*)(intptr_t)py_toint(&argv[0]);
  25075. py_newstr(py_retval(), p);
  25076. return true;
  25077. }
  25078. static bool stdc_write_cstr(int argc, py_Ref argv) {
  25079. PY_CHECK_ARGC(2);
  25080. PY_CHECK_ARG_TYPE(0, tp_int);
  25081. PY_CHECK_ARG_TYPE(1, tp_str);
  25082. char* p = (char*)(intptr_t)py_toint(&argv[0]);
  25083. c11_sv sv = py_tosv(&argv[1]);
  25084. memcpy(p, sv.data, sv.size);
  25085. p[sv.size] = '\0';
  25086. py_newnone(py_retval());
  25087. return true;
  25088. }
  25089. static bool stdc_read_bytes(int argc, py_Ref argv) {
  25090. PY_CHECK_ARGC(2);
  25091. PY_CHECK_ARG_TYPE(0, tp_int);
  25092. PY_CHECK_ARG_TYPE(1, tp_int);
  25093. unsigned char* p = (unsigned char*)(intptr_t)py_toint(&argv[0]);
  25094. int size = py_toint(&argv[1]);
  25095. unsigned char* dst = py_newbytes(py_retval(), size);
  25096. memcpy(dst, p, size);
  25097. return true;
  25098. }
  25099. static bool stdc_write_bytes(int argc, py_Ref argv) {
  25100. PY_CHECK_ARGC(2);
  25101. PY_CHECK_ARG_TYPE(0, tp_int);
  25102. PY_CHECK_ARG_TYPE(1, tp_bytes);
  25103. unsigned char* p = (unsigned char*)(intptr_t)py_toint(&argv[0]);
  25104. int size;
  25105. unsigned char* src = py_tobytes(&argv[1], &size);
  25106. memcpy(p, src, size);
  25107. py_newnone(py_retval());
  25108. return true;
  25109. }
  25110. void pk__add_module_stdc() {
  25111. py_Ref mod = py_newmodule("stdc");
  25112. py_bindfunc(mod, "malloc", stdc_malloc);
  25113. py_bindfunc(mod, "free", stdc_free);
  25114. py_bindfunc(mod, "memcpy", stdc_memcpy);
  25115. py_bindfunc(mod, "memset", stdc_memset);
  25116. py_bindfunc(mod, "memcmp", stdc_memcmp);
  25117. py_bindfunc(mod, "addressof", stdc_addressof);
  25118. py_bindfunc(mod, "sizeof", stdc_sizeof);
  25119. py_bindfunc(mod, "read_cstr", stdc_read_cstr);
  25120. py_bindfunc(mod, "write_cstr", stdc_write_cstr);
  25121. py_bindfunc(mod, "read_bytes", stdc_read_bytes);
  25122. py_bindfunc(mod, "write_bytes", stdc_write_bytes);
  25123. py_Type Memory = py_newtype("Memory", tp_object, mod, NULL);
  25124. assert(Memory == tp_stdc_Memory);
  25125. pk__bind_stdc_Char(mod);
  25126. pk__bind_stdc_UChar(mod);
  25127. pk__bind_stdc_Short(mod);
  25128. pk__bind_stdc_UShort(mod);
  25129. pk__bind_stdc_Int(mod);
  25130. pk__bind_stdc_UInt(mod);
  25131. pk__bind_stdc_Long(mod);
  25132. pk__bind_stdc_ULong(mod);
  25133. pk__bind_stdc_LongLong(mod);
  25134. pk__bind_stdc_ULongLong(mod);
  25135. for(int size = 1; size <= 8; size *= 2) {
  25136. for(py_Type t = tp_stdc_Char; t <= tp_stdc_ULongLong; t += 2) {
  25137. py_Ref size_var = py_getdict(py_tpobject(t), py_name("size"));
  25138. if(py_toint(size_var) == size) {
  25139. char buf[16];
  25140. snprintf(buf, sizeof(buf), "Int%d", size * 8);
  25141. py_setdict(mod, py_name(buf), py_tpobject(t));
  25142. snprintf(buf, sizeof(buf), "UInt%d", size * 8);
  25143. py_setdict(mod, py_name(buf), py_tpobject(t + 1));
  25144. break;
  25145. }
  25146. }
  25147. }
  25148. for(py_Type t = tp_stdc_Char; t <= tp_stdc_ULongLong; t += 2) {
  25149. py_Ref size_var = py_getdict(py_tpobject(t), py_name("size"));
  25150. if(py_toint(size_var) == sizeof(size_t)) {
  25151. py_setdict(mod, py_name("SizeT"), py_tpobject(t + 1));
  25152. break;
  25153. }
  25154. }
  25155. if(sizeof(void*) == 4) {
  25156. py_setdict(mod, py_name("IntPtrT"), py_getdict(mod, py_name("Int32")));
  25157. py_setdict(mod, py_name("UIntPtrT"), py_getdict(mod, py_name("UInt32")));
  25158. } else if(sizeof(void*) == 8) {
  25159. py_setdict(mod, py_name("IntPtrT"), py_getdict(mod, py_name("Int64")));
  25160. py_setdict(mod, py_name("UIntPtrT"), py_getdict(mod, py_name("UInt64")));
  25161. } else {
  25162. c11__abort("unsupported pointer size");
  25163. }
  25164. pk__bind_stdc_Float(mod);
  25165. pk__bind_stdc_Double(mod);
  25166. pk__bind_stdc_Pointer(mod);
  25167. pk__bind_stdc_Bool(mod);
  25168. }
  25169. // src/modules\time.c
  25170. #define _XOPEN_SOURCE 700
  25171. #include <time.h>
  25172. #undef _XOPEN_SOURCE
  25173. #ifdef _WIN32
  25174. #define WIN32_LEAN_AND_MEAN
  25175. #include <windows.h>
  25176. #include <profileapi.h>
  25177. #undef WIN32_LEAN_AND_MEAN
  25178. #endif
  25179. #include <assert.h>
  25180. #define NANOS_PER_SEC 1000000000
  25181. #ifndef __circle__
  25182. int64_t time_ns() {
  25183. struct timespec tms;
  25184. #if !defined(_WIN32) && defined(CLOCK_REALTIME)
  25185. clock_gettime(CLOCK_REALTIME, &tms);
  25186. #else
  25187. /* The C11 way */
  25188. timespec_get(&tms, TIME_UTC);
  25189. #endif
  25190. /* seconds, multiplied with 1 billion */
  25191. int64_t nanos = tms.tv_sec * (int64_t)NANOS_PER_SEC;
  25192. /* Add full nanoseconds */
  25193. nanos += tms.tv_nsec;
  25194. return nanos;
  25195. }
  25196. int64_t time_monotonic_ns() {
  25197. #ifdef _WIN32
  25198. LARGE_INTEGER now;
  25199. QueryPerformanceCounter(&now);
  25200. LONGLONG ticksll = now.QuadPart;
  25201. static LARGE_INTEGER freq;
  25202. if(freq.QuadPart == 0) QueryPerformanceFrequency(&freq);
  25203. /* Convert ticks to nanoseconds */
  25204. return (ticksll * NANOS_PER_SEC) / freq.QuadPart;
  25205. #else
  25206. struct timespec tms;
  25207. #ifdef CLOCK_MONOTONIC
  25208. clock_gettime(CLOCK_MONOTONIC, &tms);
  25209. #else
  25210. /* The C11 way */
  25211. timespec_get(&tms, TIME_UTC);
  25212. #endif
  25213. /* seconds, multiplied with 1 billion */
  25214. int64_t nanos = tms.tv_sec * (int64_t)NANOS_PER_SEC;
  25215. /* Add full nanoseconds */
  25216. nanos += tms.tv_nsec;
  25217. return nanos;
  25218. #endif
  25219. }
  25220. #else
  25221. int64_t time_ns() { return 0; }
  25222. int64_t time_monotonic_ns() { return 0; }
  25223. #endif
  25224. static bool time_time(int argc, py_Ref argv) {
  25225. PY_CHECK_ARGC(0);
  25226. int64_t nanos = time_ns();
  25227. py_newfloat(py_retval(), (double)nanos / NANOS_PER_SEC);
  25228. return true;
  25229. }
  25230. static bool time_time_ns(int argc, py_Ref argv) {
  25231. PY_CHECK_ARGC(0);
  25232. int64_t nanos = time_ns();
  25233. py_newint(py_retval(), nanos);
  25234. return true;
  25235. }
  25236. static bool time_time_monotonic(int argc, py_Ref argv) {
  25237. PY_CHECK_ARGC(0);
  25238. int64_t nanos = time_monotonic_ns();
  25239. py_newfloat(py_retval(), (double)nanos / NANOS_PER_SEC);
  25240. return true;
  25241. }
  25242. static bool time_time_monotonic_ns(int argc, py_Ref argv) {
  25243. PY_CHECK_ARGC(0);
  25244. int64_t nanos = time_monotonic_ns();
  25245. py_newint(py_retval(), nanos);
  25246. return true;
  25247. }
  25248. static bool time_perf_counter(int argc, py_Ref argv) {
  25249. return time_time_monotonic(argc, argv);
  25250. }
  25251. static bool time_process_time(int argc, py_Ref argv) {
  25252. PY_CHECK_ARGC(0);
  25253. py_newfloat(py_retval(), (double)clock() / CLOCKS_PER_SEC);
  25254. return true;
  25255. }
  25256. static bool time_sleep(int argc, py_Ref argv) {
  25257. PY_CHECK_ARGC(1);
  25258. py_f64 secs;
  25259. if(!py_castfloat(argv, &secs)) return false;
  25260. int64_t start = time_monotonic_ns();
  25261. const int64_t end = start + secs * NANOS_PER_SEC;
  25262. while(true) {
  25263. int64_t now = time_monotonic_ns();
  25264. if(now >= end) break;
  25265. #if PK_ENABLE_THREADS
  25266. c11_thrd__yield();
  25267. #endif
  25268. }
  25269. py_newnone(py_retval());
  25270. return true;
  25271. }
  25272. static bool time_localtime(int argc, py_Ref argv) {
  25273. PY_CHECK_ARGC(0);
  25274. py_Type tp_struct_time = py_gettype("time", py_name("struct_time"));
  25275. assert(tp_struct_time);
  25276. struct tm* ud = py_newobject(py_retval(), tp_struct_time, 0, sizeof(struct tm));
  25277. time_t t = time(NULL);
  25278. *ud = *localtime(&t);
  25279. return true;
  25280. }
  25281. #define DEF_STRUCT_TIME__PROPERTY(name, expr) \
  25282. static bool struct_time__##name(int argc, py_Ref argv) { \
  25283. PY_CHECK_ARGC(1); \
  25284. struct tm* tm = py_touserdata(argv); \
  25285. py_newint(py_retval(), expr); \
  25286. return true; \
  25287. }
  25288. DEF_STRUCT_TIME__PROPERTY(tm_year, tm->tm_year + 1900)
  25289. DEF_STRUCT_TIME__PROPERTY(tm_mon, tm->tm_mon + 1)
  25290. DEF_STRUCT_TIME__PROPERTY(tm_mday, tm->tm_mday)
  25291. DEF_STRUCT_TIME__PROPERTY(tm_hour, tm->tm_hour)
  25292. DEF_STRUCT_TIME__PROPERTY(tm_min, tm->tm_min)
  25293. DEF_STRUCT_TIME__PROPERTY(tm_sec, tm->tm_sec)
  25294. DEF_STRUCT_TIME__PROPERTY(tm_wday, (tm->tm_wday + 6) % 7)
  25295. DEF_STRUCT_TIME__PROPERTY(tm_yday, tm->tm_yday + 1)
  25296. DEF_STRUCT_TIME__PROPERTY(tm_isdst, tm->tm_isdst)
  25297. #undef DEF_STRUCT_TIME__PROPERTY
  25298. void pk__add_module_time() {
  25299. py_Ref mod = py_newmodule("time");
  25300. py_Type tp_struct_time = py_newtype("struct_time", tp_object, mod, NULL);
  25301. py_bindproperty(tp_struct_time, "tm_year", struct_time__tm_year, NULL);
  25302. py_bindproperty(tp_struct_time, "tm_mon", struct_time__tm_mon, NULL);
  25303. py_bindproperty(tp_struct_time, "tm_mday", struct_time__tm_mday, NULL);
  25304. py_bindproperty(tp_struct_time, "tm_hour", struct_time__tm_hour, NULL);
  25305. py_bindproperty(tp_struct_time, "tm_min", struct_time__tm_min, NULL);
  25306. py_bindproperty(tp_struct_time, "tm_sec", struct_time__tm_sec, NULL);
  25307. py_bindproperty(tp_struct_time, "tm_wday", struct_time__tm_wday, NULL);
  25308. py_bindproperty(tp_struct_time, "tm_yday", struct_time__tm_yday, NULL);
  25309. py_bindproperty(tp_struct_time, "tm_isdst", struct_time__tm_isdst, NULL);
  25310. py_bindfunc(mod, "time", time_time);
  25311. py_bindfunc(mod, "time_ns", time_time_ns);
  25312. py_bindfunc(mod, "monotonic", time_time_monotonic);
  25313. py_bindfunc(mod, "monotonic_ns", time_time_monotonic_ns);
  25314. py_bindfunc(mod, "perf_counter", time_perf_counter);
  25315. py_bindfunc(mod, "process_time", time_process_time);
  25316. py_bindfunc(mod, "sleep", time_sleep);
  25317. py_bindfunc(mod, "localtime", time_localtime);
  25318. }
  25319. #undef NANOS_PER_SEC
  25320. #undef DEF_STRUCT_TIME__PROPERTY
  25321. // src/modules\traceback.c
  25322. static bool traceback_format_exc(int argc, py_Ref argv) {
  25323. PY_CHECK_ARGC(0);
  25324. VM* vm = pk_current_vm;
  25325. if(vm->top_frame) {
  25326. FrameExcInfo* info = Frame__top_exc_info(vm->top_frame);
  25327. if(info && !py_isnil(&info->exc)) {
  25328. char* res = formatexc_internal(&info->exc);
  25329. py_newstr(py_retval(), res);
  25330. PK_FREE(res);
  25331. return true;
  25332. }
  25333. }
  25334. py_newnone(py_retval());
  25335. return true;
  25336. }
  25337. static bool traceback_print_exc(int argc, py_Ref argv) {
  25338. PY_CHECK_ARGC(0);
  25339. py_printexc();
  25340. py_newnone(py_retval());
  25341. return true;
  25342. }
  25343. void pk__add_module_traceback() {
  25344. py_Ref mod = py_newmodule("traceback");
  25345. py_bindfunc(mod, "format_exc", traceback_format_exc);
  25346. py_bindfunc(mod, "print_exc", traceback_print_exc);
  25347. }
  25348. // src/modules\unicodedata.c
  25349. // clang-format off
  25350. const static c11_u32_range kEastAsianWidthRanges[] = {
  25351. { 32, 126, "Na\0" },
  25352. { 161, 161, "A\0" },
  25353. { 162, 163, "Na\0" },
  25354. { 164, 164, "A\0" },
  25355. { 165, 166, "Na\0" },
  25356. { 167, 168, "A\0" },
  25357. { 170, 170, "A\0" },
  25358. { 172, 172, "Na\0" },
  25359. { 173, 174, "A\0" },
  25360. { 175, 175, "Na\0" },
  25361. { 176, 180, "A\0" },
  25362. { 182, 186, "A\0" },
  25363. { 188, 191, "A\0" },
  25364. { 198, 198, "A\0" },
  25365. { 208, 208, "A\0" },
  25366. { 215, 216, "A\0" },
  25367. { 222, 225, "A\0" },
  25368. { 230, 230, "A\0" },
  25369. { 232, 234, "A\0" },
  25370. { 236, 237, "A\0" },
  25371. { 240, 240, "A\0" },
  25372. { 242, 243, "A\0" },
  25373. { 247, 250, "A\0" },
  25374. { 252, 252, "A\0" },
  25375. { 254, 254, "A\0" },
  25376. { 257, 257, "A\0" },
  25377. { 273, 273, "A\0" },
  25378. { 275, 275, "A\0" },
  25379. { 283, 283, "A\0" },
  25380. { 294, 295, "A\0" },
  25381. { 299, 299, "A\0" },
  25382. { 305, 307, "A\0" },
  25383. { 312, 312, "A\0" },
  25384. { 319, 322, "A\0" },
  25385. { 324, 324, "A\0" },
  25386. { 328, 331, "A\0" },
  25387. { 333, 333, "A\0" },
  25388. { 338, 339, "A\0" },
  25389. { 358, 359, "A\0" },
  25390. { 363, 363, "A\0" },
  25391. { 462, 462, "A\0" },
  25392. { 464, 464, "A\0" },
  25393. { 466, 466, "A\0" },
  25394. { 468, 468, "A\0" },
  25395. { 470, 470, "A\0" },
  25396. { 472, 472, "A\0" },
  25397. { 474, 474, "A\0" },
  25398. { 476, 476, "A\0" },
  25399. { 593, 593, "A\0" },
  25400. { 609, 609, "A\0" },
  25401. { 708, 708, "A\0" },
  25402. { 711, 711, "A\0" },
  25403. { 713, 715, "A\0" },
  25404. { 717, 717, "A\0" },
  25405. { 720, 720, "A\0" },
  25406. { 728, 731, "A\0" },
  25407. { 733, 733, "A\0" },
  25408. { 735, 735, "A\0" },
  25409. { 768, 879, "A\0" },
  25410. { 888, 889, "F\0" },
  25411. { 896, 899, "F\0" },
  25412. { 907, 907, "F\0" },
  25413. { 909, 909, "F\0" },
  25414. { 913, 929, "A\0" },
  25415. { 930, 930, "F\0" },
  25416. { 931, 937, "A\0" },
  25417. { 945, 961, "A\0" },
  25418. { 963, 969, "A\0" },
  25419. { 1025, 1025, "A\0" },
  25420. { 1040, 1103, "A\0" },
  25421. { 1105, 1105, "A\0" },
  25422. { 1328, 1328, "F\0" },
  25423. { 1367, 1368, "F\0" },
  25424. { 1419, 1420, "F\0" },
  25425. { 1424, 1424, "F\0" },
  25426. { 1480, 1487, "F\0" },
  25427. { 1515, 1518, "F\0" },
  25428. { 1525, 1535, "F\0" },
  25429. { 1806, 1806, "F\0" },
  25430. { 1867, 1868, "F\0" },
  25431. { 1970, 1983, "F\0" },
  25432. { 2043, 2044, "F\0" },
  25433. { 2094, 2095, "F\0" },
  25434. { 2111, 2111, "F\0" },
  25435. { 2140, 2141, "F\0" },
  25436. { 2143, 2143, "F\0" },
  25437. { 2155, 2159, "F\0" },
  25438. { 2191, 2191, "F\0" },
  25439. { 2194, 2199, "F\0" },
  25440. { 2436, 2436, "F\0" },
  25441. { 2445, 2446, "F\0" },
  25442. { 2449, 2450, "F\0" },
  25443. { 2473, 2473, "F\0" },
  25444. { 2481, 2481, "F\0" },
  25445. { 2483, 2485, "F\0" },
  25446. { 2490, 2491, "F\0" },
  25447. { 2501, 2502, "F\0" },
  25448. { 2505, 2506, "F\0" },
  25449. { 2511, 2518, "F\0" },
  25450. { 2520, 2523, "F\0" },
  25451. { 2526, 2526, "F\0" },
  25452. { 2532, 2533, "F\0" },
  25453. { 2559, 2560, "F\0" },
  25454. { 2564, 2564, "F\0" },
  25455. { 2571, 2574, "F\0" },
  25456. { 2577, 2578, "F\0" },
  25457. { 2601, 2601, "F\0" },
  25458. { 2609, 2609, "F\0" },
  25459. { 2612, 2612, "F\0" },
  25460. { 2615, 2615, "F\0" },
  25461. { 2618, 2619, "F\0" },
  25462. { 2621, 2621, "F\0" },
  25463. { 2627, 2630, "F\0" },
  25464. { 2633, 2634, "F\0" },
  25465. { 2638, 2640, "F\0" },
  25466. { 2642, 2648, "F\0" },
  25467. { 2653, 2653, "F\0" },
  25468. { 2655, 2661, "F\0" },
  25469. { 2679, 2688, "F\0" },
  25470. { 2692, 2692, "F\0" },
  25471. { 2702, 2702, "F\0" },
  25472. { 2706, 2706, "F\0" },
  25473. { 2729, 2729, "F\0" },
  25474. { 2737, 2737, "F\0" },
  25475. { 2740, 2740, "F\0" },
  25476. { 2746, 2747, "F\0" },
  25477. { 2758, 2758, "F\0" },
  25478. { 2762, 2762, "F\0" },
  25479. { 2766, 2767, "F\0" },
  25480. { 2769, 2783, "F\0" },
  25481. { 2788, 2789, "F\0" },
  25482. { 2802, 2808, "F\0" },
  25483. { 2816, 2816, "F\0" },
  25484. { 2820, 2820, "F\0" },
  25485. { 2829, 2830, "F\0" },
  25486. { 2833, 2834, "F\0" },
  25487. { 2857, 2857, "F\0" },
  25488. { 2865, 2865, "F\0" },
  25489. { 2868, 2868, "F\0" },
  25490. { 2874, 2875, "F\0" },
  25491. { 2885, 2886, "F\0" },
  25492. { 2889, 2890, "F\0" },
  25493. { 2894, 2900, "F\0" },
  25494. { 2904, 2907, "F\0" },
  25495. { 2910, 2910, "F\0" },
  25496. { 2916, 2917, "F\0" },
  25497. { 2936, 2945, "F\0" },
  25498. { 2948, 2948, "F\0" },
  25499. { 2955, 2957, "F\0" },
  25500. { 2961, 2961, "F\0" },
  25501. { 2966, 2968, "F\0" },
  25502. { 2971, 2971, "F\0" },
  25503. { 2973, 2973, "F\0" },
  25504. { 2976, 2978, "F\0" },
  25505. { 2981, 2983, "F\0" },
  25506. { 2987, 2989, "F\0" },
  25507. { 3002, 3005, "F\0" },
  25508. { 3011, 3013, "F\0" },
  25509. { 3017, 3017, "F\0" },
  25510. { 3022, 3023, "F\0" },
  25511. { 3025, 3030, "F\0" },
  25512. { 3032, 3045, "F\0" },
  25513. { 3067, 3071, "F\0" },
  25514. { 3085, 3085, "F\0" },
  25515. { 3089, 3089, "F\0" },
  25516. { 3113, 3113, "F\0" },
  25517. { 3130, 3131, "F\0" },
  25518. { 3141, 3141, "F\0" },
  25519. { 3145, 3145, "F\0" },
  25520. { 3150, 3156, "F\0" },
  25521. { 3159, 3159, "F\0" },
  25522. { 3163, 3164, "F\0" },
  25523. { 3166, 3167, "F\0" },
  25524. { 3172, 3173, "F\0" },
  25525. { 3184, 3190, "F\0" },
  25526. { 3213, 3213, "F\0" },
  25527. { 3217, 3217, "F\0" },
  25528. { 3241, 3241, "F\0" },
  25529. { 3252, 3252, "F\0" },
  25530. { 3258, 3259, "F\0" },
  25531. { 3269, 3269, "F\0" },
  25532. { 3273, 3273, "F\0" },
  25533. { 3278, 3284, "F\0" },
  25534. { 3287, 3292, "F\0" },
  25535. { 3295, 3295, "F\0" },
  25536. { 3300, 3301, "F\0" },
  25537. { 3312, 3312, "F\0" },
  25538. { 3315, 3327, "F\0" },
  25539. { 3341, 3341, "F\0" },
  25540. { 3345, 3345, "F\0" },
  25541. { 3397, 3397, "F\0" },
  25542. { 3401, 3401, "F\0" },
  25543. { 3408, 3411, "F\0" },
  25544. { 3428, 3429, "F\0" },
  25545. { 3456, 3456, "F\0" },
  25546. { 3460, 3460, "F\0" },
  25547. { 3479, 3481, "F\0" },
  25548. { 3506, 3506, "F\0" },
  25549. { 3516, 3516, "F\0" },
  25550. { 3518, 3519, "F\0" },
  25551. { 3527, 3529, "F\0" },
  25552. { 3531, 3534, "F\0" },
  25553. { 3541, 3541, "F\0" },
  25554. { 3543, 3543, "F\0" },
  25555. { 3552, 3557, "F\0" },
  25556. { 3568, 3569, "F\0" },
  25557. { 3573, 3584, "F\0" },
  25558. { 3643, 3646, "F\0" },
  25559. { 3676, 3712, "F\0" },
  25560. { 3715, 3715, "F\0" },
  25561. { 3717, 3717, "F\0" },
  25562. { 3723, 3723, "F\0" },
  25563. { 3748, 3748, "F\0" },
  25564. { 3750, 3750, "F\0" },
  25565. { 3774, 3775, "F\0" },
  25566. { 3781, 3781, "F\0" },
  25567. { 3783, 3783, "F\0" },
  25568. { 3790, 3791, "F\0" },
  25569. { 3802, 3803, "F\0" },
  25570. { 3808, 3839, "F\0" },
  25571. { 3912, 3912, "F\0" },
  25572. { 3949, 3952, "F\0" },
  25573. { 3992, 3992, "F\0" },
  25574. { 4029, 4029, "F\0" },
  25575. { 4045, 4045, "F\0" },
  25576. { 4059, 4095, "F\0" },
  25577. { 4294, 4294, "F\0" },
  25578. { 4296, 4300, "F\0" },
  25579. { 4302, 4303, "F\0" },
  25580. { 4352, 4447, "W\0" },
  25581. { 4681, 4681, "F\0" },
  25582. { 4686, 4687, "F\0" },
  25583. { 4695, 4695, "F\0" },
  25584. { 4697, 4697, "F\0" },
  25585. { 4702, 4703, "F\0" },
  25586. { 4745, 4745, "F\0" },
  25587. { 4750, 4751, "F\0" },
  25588. { 4785, 4785, "F\0" },
  25589. { 4790, 4791, "F\0" },
  25590. { 4799, 4799, "F\0" },
  25591. { 4801, 4801, "F\0" },
  25592. { 4806, 4807, "F\0" },
  25593. { 4823, 4823, "F\0" },
  25594. { 4881, 4881, "F\0" },
  25595. { 4886, 4887, "F\0" },
  25596. { 4955, 4956, "F\0" },
  25597. { 4989, 4991, "F\0" },
  25598. { 5018, 5023, "F\0" },
  25599. { 5110, 5111, "F\0" },
  25600. { 5118, 5119, "F\0" },
  25601. { 5789, 5791, "F\0" },
  25602. { 5881, 5887, "F\0" },
  25603. { 5910, 5918, "F\0" },
  25604. { 5943, 5951, "F\0" },
  25605. { 5972, 5983, "F\0" },
  25606. { 5997, 5997, "F\0" },
  25607. { 6001, 6001, "F\0" },
  25608. { 6004, 6015, "F\0" },
  25609. { 6110, 6111, "F\0" },
  25610. { 6122, 6127, "F\0" },
  25611. { 6138, 6143, "F\0" },
  25612. { 6170, 6175, "F\0" },
  25613. { 6265, 6271, "F\0" },
  25614. { 6315, 6319, "F\0" },
  25615. { 6390, 6399, "F\0" },
  25616. { 6431, 6431, "F\0" },
  25617. { 6444, 6447, "F\0" },
  25618. { 6460, 6463, "F\0" },
  25619. { 6465, 6467, "F\0" },
  25620. { 6510, 6511, "F\0" },
  25621. { 6517, 6527, "F\0" },
  25622. { 6572, 6575, "F\0" },
  25623. { 6602, 6607, "F\0" },
  25624. { 6619, 6621, "F\0" },
  25625. { 6684, 6685, "F\0" },
  25626. { 6751, 6751, "F\0" },
  25627. { 6781, 6782, "F\0" },
  25628. { 6794, 6799, "F\0" },
  25629. { 6810, 6815, "F\0" },
  25630. { 6830, 6831, "F\0" },
  25631. { 6863, 6911, "F\0" },
  25632. { 6989, 6991, "F\0" },
  25633. { 7039, 7039, "F\0" },
  25634. { 7156, 7163, "F\0" },
  25635. { 7224, 7226, "F\0" },
  25636. { 7242, 7244, "F\0" },
  25637. { 7305, 7311, "F\0" },
  25638. { 7355, 7356, "F\0" },
  25639. { 7368, 7375, "F\0" },
  25640. { 7419, 7423, "F\0" },
  25641. { 7958, 7959, "F\0" },
  25642. { 7966, 7967, "F\0" },
  25643. { 8006, 8007, "F\0" },
  25644. { 8014, 8015, "F\0" },
  25645. { 8024, 8024, "F\0" },
  25646. { 8026, 8026, "F\0" },
  25647. { 8028, 8028, "F\0" },
  25648. { 8030, 8030, "F\0" },
  25649. { 8062, 8063, "F\0" },
  25650. { 8117, 8117, "F\0" },
  25651. { 8133, 8133, "F\0" },
  25652. { 8148, 8149, "F\0" },
  25653. { 8156, 8156, "F\0" },
  25654. { 8176, 8177, "F\0" },
  25655. { 8181, 8181, "F\0" },
  25656. { 8191, 8191, "F\0" },
  25657. { 8208, 8208, "A\0" },
  25658. { 8211, 8214, "A\0" },
  25659. { 8216, 8217, "A\0" },
  25660. { 8220, 8221, "A\0" },
  25661. { 8224, 8226, "A\0" },
  25662. { 8228, 8231, "A\0" },
  25663. { 8240, 8240, "A\0" },
  25664. { 8242, 8243, "A\0" },
  25665. { 8245, 8245, "A\0" },
  25666. { 8251, 8251, "A\0" },
  25667. { 8254, 8254, "A\0" },
  25668. { 8293, 8293, "F\0" },
  25669. { 8306, 8307, "F\0" },
  25670. { 8308, 8308, "A\0" },
  25671. { 8319, 8319, "A\0" },
  25672. { 8321, 8324, "A\0" },
  25673. { 8335, 8335, "F\0" },
  25674. { 8349, 8351, "F\0" },
  25675. { 8361, 8361, "H\0" },
  25676. { 8364, 8364, "A\0" },
  25677. { 8385, 8399, "F\0" },
  25678. { 8433, 8447, "F\0" },
  25679. { 8451, 8451, "A\0" },
  25680. { 8453, 8453, "A\0" },
  25681. { 8457, 8457, "A\0" },
  25682. { 8467, 8467, "A\0" },
  25683. { 8470, 8470, "A\0" },
  25684. { 8481, 8482, "A\0" },
  25685. { 8486, 8486, "A\0" },
  25686. { 8491, 8491, "A\0" },
  25687. { 8531, 8532, "A\0" },
  25688. { 8539, 8542, "A\0" },
  25689. { 8544, 8555, "A\0" },
  25690. { 8560, 8569, "A\0" },
  25691. { 8585, 8585, "A\0" },
  25692. { 8588, 8591, "F\0" },
  25693. { 8592, 8601, "A\0" },
  25694. { 8632, 8633, "A\0" },
  25695. { 8658, 8658, "A\0" },
  25696. { 8660, 8660, "A\0" },
  25697. { 8679, 8679, "A\0" },
  25698. { 8704, 8704, "A\0" },
  25699. { 8706, 8707, "A\0" },
  25700. { 8711, 8712, "A\0" },
  25701. { 8715, 8715, "A\0" },
  25702. { 8719, 8719, "A\0" },
  25703. { 8721, 8721, "A\0" },
  25704. { 8725, 8725, "A\0" },
  25705. { 8730, 8730, "A\0" },
  25706. { 8733, 8736, "A\0" },
  25707. { 8739, 8739, "A\0" },
  25708. { 8741, 8741, "A\0" },
  25709. { 8743, 8748, "A\0" },
  25710. { 8750, 8750, "A\0" },
  25711. { 8756, 8759, "A\0" },
  25712. { 8764, 8765, "A\0" },
  25713. { 8776, 8776, "A\0" },
  25714. { 8780, 8780, "A\0" },
  25715. { 8786, 8786, "A\0" },
  25716. { 8800, 8801, "A\0" },
  25717. { 8804, 8807, "A\0" },
  25718. { 8810, 8811, "A\0" },
  25719. { 8814, 8815, "A\0" },
  25720. { 8834, 8835, "A\0" },
  25721. { 8838, 8839, "A\0" },
  25722. { 8853, 8853, "A\0" },
  25723. { 8857, 8857, "A\0" },
  25724. { 8869, 8869, "A\0" },
  25725. { 8895, 8895, "A\0" },
  25726. { 8978, 8978, "A\0" },
  25727. { 8986, 8987, "W\0" },
  25728. { 9001, 9002, "W\0" },
  25729. { 9193, 9196, "W\0" },
  25730. { 9200, 9200, "W\0" },
  25731. { 9203, 9203, "W\0" },
  25732. { 9255, 9279, "F\0" },
  25733. { 9291, 9311, "F\0" },
  25734. { 9312, 9449, "A\0" },
  25735. { 9451, 9547, "A\0" },
  25736. { 9552, 9587, "A\0" },
  25737. { 9600, 9615, "A\0" },
  25738. { 9618, 9621, "A\0" },
  25739. { 9632, 9633, "A\0" },
  25740. { 9635, 9641, "A\0" },
  25741. { 9650, 9651, "A\0" },
  25742. { 9654, 9655, "A\0" },
  25743. { 9660, 9661, "A\0" },
  25744. { 9664, 9665, "A\0" },
  25745. { 9670, 9672, "A\0" },
  25746. { 9675, 9675, "A\0" },
  25747. { 9678, 9681, "A\0" },
  25748. { 9698, 9701, "A\0" },
  25749. { 9711, 9711, "A\0" },
  25750. { 9725, 9726, "W\0" },
  25751. { 9733, 9734, "A\0" },
  25752. { 9737, 9737, "A\0" },
  25753. { 9742, 9743, "A\0" },
  25754. { 9748, 9749, "W\0" },
  25755. { 9756, 9756, "A\0" },
  25756. { 9758, 9758, "A\0" },
  25757. { 9792, 9792, "A\0" },
  25758. { 9794, 9794, "A\0" },
  25759. { 9800, 9811, "W\0" },
  25760. { 9824, 9825, "A\0" },
  25761. { 9827, 9829, "A\0" },
  25762. { 9831, 9834, "A\0" },
  25763. { 9836, 9837, "A\0" },
  25764. { 9839, 9839, "A\0" },
  25765. { 9855, 9855, "W\0" },
  25766. { 9875, 9875, "W\0" },
  25767. { 9886, 9887, "A\0" },
  25768. { 9889, 9889, "W\0" },
  25769. { 9898, 9899, "W\0" },
  25770. { 9917, 9918, "W\0" },
  25771. { 9919, 9919, "A\0" },
  25772. { 9924, 9925, "W\0" },
  25773. { 9926, 9933, "A\0" },
  25774. { 9934, 9934, "W\0" },
  25775. { 9935, 9939, "A\0" },
  25776. { 9940, 9940, "W\0" },
  25777. { 9941, 9953, "A\0" },
  25778. { 9955, 9955, "A\0" },
  25779. { 9960, 9961, "A\0" },
  25780. { 9962, 9962, "W\0" },
  25781. { 9963, 9969, "A\0" },
  25782. { 9970, 9971, "W\0" },
  25783. { 9972, 9972, "A\0" },
  25784. { 9973, 9973, "W\0" },
  25785. { 9974, 9977, "A\0" },
  25786. { 9978, 9978, "W\0" },
  25787. { 9979, 9980, "A\0" },
  25788. { 9981, 9981, "W\0" },
  25789. { 9982, 9983, "A\0" },
  25790. { 9989, 9989, "W\0" },
  25791. { 9994, 9995, "W\0" },
  25792. { 10024, 10024, "W\0" },
  25793. { 10045, 10045, "A\0" },
  25794. { 10060, 10060, "W\0" },
  25795. { 10062, 10062, "W\0" },
  25796. { 10067, 10069, "W\0" },
  25797. { 10071, 10071, "W\0" },
  25798. { 10102, 10111, "A\0" },
  25799. { 10133, 10135, "W\0" },
  25800. { 10160, 10160, "W\0" },
  25801. { 10175, 10175, "W\0" },
  25802. { 10214, 10221, "Na\0" },
  25803. { 10629, 10630, "Na\0" },
  25804. { 11035, 11036, "W\0" },
  25805. { 11088, 11088, "W\0" },
  25806. { 11093, 11093, "W\0" },
  25807. { 11094, 11097, "A\0" },
  25808. { 11124, 11125, "F\0" },
  25809. { 11158, 11158, "F\0" },
  25810. { 11508, 11512, "F\0" },
  25811. { 11558, 11558, "F\0" },
  25812. { 11560, 11564, "F\0" },
  25813. { 11566, 11567, "F\0" },
  25814. { 11624, 11630, "F\0" },
  25815. { 11633, 11646, "F\0" },
  25816. { 11671, 11679, "F\0" },
  25817. { 11687, 11687, "F\0" },
  25818. { 11695, 11695, "F\0" },
  25819. { 11703, 11703, "F\0" },
  25820. { 11711, 11711, "F\0" },
  25821. { 11719, 11719, "F\0" },
  25822. { 11727, 11727, "F\0" },
  25823. { 11735, 11735, "F\0" },
  25824. { 11743, 11743, "F\0" },
  25825. { 11870, 11903, "F\0" },
  25826. { 11904, 11929, "W\0" },
  25827. { 11930, 11930, "F\0" },
  25828. { 11931, 12019, "W\0" },
  25829. { 12020, 12031, "F\0" },
  25830. { 12032, 12245, "W\0" },
  25831. { 12246, 12271, "F\0" },
  25832. { 12272, 12283, "W\0" },
  25833. { 12284, 12288, "F\0" },
  25834. { 12289, 12350, "W\0" },
  25835. { 12352, 12352, "F\0" },
  25836. { 12353, 12438, "W\0" },
  25837. { 12439, 12440, "F\0" },
  25838. { 12441, 12543, "W\0" },
  25839. { 12544, 12548, "F\0" },
  25840. { 12549, 12591, "W\0" },
  25841. { 12592, 12592, "F\0" },
  25842. { 12593, 12686, "W\0" },
  25843. { 12687, 12687, "F\0" },
  25844. { 12688, 12771, "W\0" },
  25845. { 12772, 12783, "F\0" },
  25846. { 12784, 12830, "W\0" },
  25847. { 12831, 12831, "F\0" },
  25848. { 12832, 12871, "W\0" },
  25849. { 12872, 12879, "A\0" },
  25850. { 12880, 19903, "W\0" },
  25851. { 19968, 42124, "W\0" },
  25852. { 42125, 42127, "F\0" },
  25853. { 42128, 42182, "W\0" },
  25854. { 42183, 42191, "F\0" },
  25855. { 42540, 42559, "F\0" },
  25856. { 42744, 42751, "F\0" },
  25857. { 42955, 42959, "F\0" },
  25858. { 42962, 42962, "F\0" },
  25859. { 42964, 42964, "F\0" },
  25860. { 42970, 42993, "F\0" },
  25861. { 43053, 43055, "F\0" },
  25862. { 43066, 43071, "F\0" },
  25863. { 43128, 43135, "F\0" },
  25864. { 43206, 43213, "F\0" },
  25865. { 43226, 43231, "F\0" },
  25866. { 43348, 43358, "F\0" },
  25867. { 43360, 43388, "W\0" },
  25868. { 43389, 43391, "F\0" },
  25869. { 43470, 43470, "F\0" },
  25870. { 43482, 43485, "F\0" },
  25871. { 43519, 43519, "F\0" },
  25872. { 43575, 43583, "F\0" },
  25873. { 43598, 43599, "F\0" },
  25874. { 43610, 43611, "F\0" },
  25875. { 43715, 43738, "F\0" },
  25876. { 43767, 43776, "F\0" },
  25877. { 43783, 43784, "F\0" },
  25878. { 43791, 43792, "F\0" },
  25879. { 43799, 43807, "F\0" },
  25880. { 43815, 43815, "F\0" },
  25881. { 43823, 43823, "F\0" },
  25882. { 43884, 43887, "F\0" },
  25883. { 44014, 44015, "F\0" },
  25884. { 44026, 44031, "F\0" },
  25885. { 44032, 55203, "W\0" },
  25886. { 55204, 55215, "F\0" },
  25887. { 55239, 55242, "F\0" },
  25888. { 55292, 55295, "F\0" },
  25889. { 57344, 63743, "A\0" },
  25890. { 63744, 64109, "W\0" },
  25891. { 64110, 64111, "F\0" },
  25892. { 64112, 64217, "W\0" },
  25893. { 64218, 64255, "F\0" },
  25894. { 64263, 64274, "F\0" },
  25895. { 64280, 64284, "F\0" },
  25896. { 64311, 64311, "F\0" },
  25897. { 64317, 64317, "F\0" },
  25898. { 64319, 64319, "F\0" },
  25899. { 64322, 64322, "F\0" },
  25900. { 64325, 64325, "F\0" },
  25901. { 64451, 64466, "F\0" },
  25902. { 64912, 64913, "F\0" },
  25903. { 64968, 64974, "F\0" },
  25904. { 64976, 65007, "F\0" },
  25905. { 65024, 65039, "A\0" },
  25906. { 65040, 65049, "W\0" },
  25907. { 65050, 65055, "F\0" },
  25908. { 65072, 65106, "W\0" },
  25909. { 65107, 65107, "F\0" },
  25910. { 65108, 65126, "W\0" },
  25911. { 65127, 65127, "F\0" },
  25912. { 65128, 65131, "W\0" },
  25913. { 65132, 65135, "F\0" },
  25914. { 65141, 65141, "F\0" },
  25915. { 65277, 65278, "F\0" },
  25916. { 65280, 65376, "F\0" },
  25917. { 65377, 65470, "H\0" },
  25918. { 65471, 65473, "F\0" },
  25919. { 65474, 65479, "H\0" },
  25920. { 65480, 65481, "F\0" },
  25921. { 65482, 65487, "H\0" },
  25922. { 65488, 65489, "F\0" },
  25923. { 65490, 65495, "H\0" },
  25924. { 65496, 65497, "F\0" },
  25925. { 65498, 65500, "H\0" },
  25926. { 65501, 65511, "F\0" },
  25927. { 65512, 65518, "H\0" },
  25928. { 65519, 65528, "F\0" },
  25929. { 65533, 65533, "A\0" },
  25930. { 65534, 65535, "F\0" },
  25931. { 65548, 65548, "F\0" },
  25932. { 65575, 65575, "F\0" },
  25933. { 65595, 65595, "F\0" },
  25934. { 65598, 65598, "F\0" },
  25935. { 65614, 65615, "F\0" },
  25936. { 65630, 65663, "F\0" },
  25937. { 65787, 65791, "F\0" },
  25938. { 65795, 65798, "F\0" },
  25939. { 65844, 65846, "F\0" },
  25940. { 65935, 65935, "F\0" },
  25941. { 65949, 65951, "F\0" },
  25942. { 65953, 65999, "F\0" },
  25943. { 66046, 66175, "F\0" },
  25944. { 66205, 66207, "F\0" },
  25945. { 66257, 66271, "F\0" },
  25946. { 66300, 66303, "F\0" },
  25947. { 66340, 66348, "F\0" },
  25948. { 66379, 66383, "F\0" },
  25949. { 66427, 66431, "F\0" },
  25950. { 66462, 66462, "F\0" },
  25951. { 66500, 66503, "F\0" },
  25952. { 66518, 66559, "F\0" },
  25953. { 66718, 66719, "F\0" },
  25954. { 66730, 66735, "F\0" },
  25955. { 66772, 66775, "F\0" },
  25956. { 66812, 66815, "F\0" },
  25957. { 66856, 66863, "F\0" },
  25958. { 66916, 66926, "F\0" },
  25959. { 66939, 66939, "F\0" },
  25960. { 66955, 66955, "F\0" },
  25961. { 66963, 66963, "F\0" },
  25962. { 66966, 66966, "F\0" },
  25963. { 66978, 66978, "F\0" },
  25964. { 66994, 66994, "F\0" },
  25965. { 67002, 67002, "F\0" },
  25966. { 67005, 67071, "F\0" },
  25967. { 67383, 67391, "F\0" },
  25968. { 67414, 67423, "F\0" },
  25969. { 67432, 67455, "F\0" },
  25970. { 67462, 67462, "F\0" },
  25971. { 67505, 67505, "F\0" },
  25972. { 67515, 67583, "F\0" },
  25973. { 67590, 67591, "F\0" },
  25974. { 67593, 67593, "F\0" },
  25975. { 67638, 67638, "F\0" },
  25976. { 67641, 67643, "F\0" },
  25977. { 67645, 67646, "F\0" },
  25978. { 67670, 67670, "F\0" },
  25979. { 67743, 67750, "F\0" },
  25980. { 67760, 67807, "F\0" },
  25981. { 67827, 67827, "F\0" },
  25982. { 67830, 67834, "F\0" },
  25983. { 67868, 67870, "F\0" },
  25984. { 67898, 67902, "F\0" },
  25985. { 67904, 67967, "F\0" },
  25986. { 68024, 68027, "F\0" },
  25987. { 68048, 68049, "F\0" },
  25988. { 68100, 68100, "F\0" },
  25989. { 68103, 68107, "F\0" },
  25990. { 68116, 68116, "F\0" },
  25991. { 68120, 68120, "F\0" },
  25992. { 68150, 68151, "F\0" },
  25993. { 68155, 68158, "F\0" },
  25994. { 68169, 68175, "F\0" },
  25995. { 68185, 68191, "F\0" },
  25996. { 68256, 68287, "F\0" },
  25997. { 68327, 68330, "F\0" },
  25998. { 68343, 68351, "F\0" },
  25999. { 68406, 68408, "F\0" },
  26000. { 68438, 68439, "F\0" },
  26001. { 68467, 68471, "F\0" },
  26002. { 68498, 68504, "F\0" },
  26003. { 68509, 68520, "F\0" },
  26004. { 68528, 68607, "F\0" },
  26005. { 68681, 68735, "F\0" },
  26006. { 68787, 68799, "F\0" },
  26007. { 68851, 68857, "F\0" },
  26008. { 68904, 68911, "F\0" },
  26009. { 68922, 69215, "F\0" },
  26010. { 69247, 69247, "F\0" },
  26011. { 69290, 69290, "F\0" },
  26012. { 69294, 69295, "F\0" },
  26013. { 69298, 69375, "F\0" },
  26014. { 69416, 69423, "F\0" },
  26015. { 69466, 69487, "F\0" },
  26016. { 69514, 69551, "F\0" },
  26017. { 69580, 69599, "F\0" },
  26018. { 69623, 69631, "F\0" },
  26019. { 69710, 69713, "F\0" },
  26020. { 69750, 69758, "F\0" },
  26021. { 69827, 69836, "F\0" },
  26022. { 69838, 69839, "F\0" },
  26023. { 69865, 69871, "F\0" },
  26024. { 69882, 69887, "F\0" },
  26025. { 69941, 69941, "F\0" },
  26026. { 69960, 69967, "F\0" },
  26027. { 70007, 70015, "F\0" },
  26028. { 70112, 70112, "F\0" },
  26029. { 70133, 70143, "F\0" },
  26030. { 70162, 70162, "F\0" },
  26031. { 70207, 70271, "F\0" },
  26032. { 70279, 70279, "F\0" },
  26033. { 70281, 70281, "F\0" },
  26034. { 70286, 70286, "F\0" },
  26035. { 70302, 70302, "F\0" },
  26036. { 70314, 70319, "F\0" },
  26037. { 70379, 70383, "F\0" },
  26038. { 70394, 70399, "F\0" },
  26039. { 70404, 70404, "F\0" },
  26040. { 70413, 70414, "F\0" },
  26041. { 70417, 70418, "F\0" },
  26042. { 70441, 70441, "F\0" },
  26043. { 70449, 70449, "F\0" },
  26044. { 70452, 70452, "F\0" },
  26045. { 70458, 70458, "F\0" },
  26046. { 70469, 70470, "F\0" },
  26047. { 70473, 70474, "F\0" },
  26048. { 70478, 70479, "F\0" },
  26049. { 70481, 70486, "F\0" },
  26050. { 70488, 70492, "F\0" },
  26051. { 70500, 70501, "F\0" },
  26052. { 70509, 70511, "F\0" },
  26053. { 70517, 70655, "F\0" },
  26054. { 70748, 70748, "F\0" },
  26055. { 70754, 70783, "F\0" },
  26056. { 70856, 70863, "F\0" },
  26057. { 70874, 71039, "F\0" },
  26058. { 71094, 71095, "F\0" },
  26059. { 71134, 71167, "F\0" },
  26060. { 71237, 71247, "F\0" },
  26061. { 71258, 71263, "F\0" },
  26062. { 71277, 71295, "F\0" },
  26063. { 71354, 71359, "F\0" },
  26064. { 71370, 71423, "F\0" },
  26065. { 71451, 71452, "F\0" },
  26066. { 71468, 71471, "F\0" },
  26067. { 71495, 71679, "F\0" },
  26068. { 71740, 71839, "F\0" },
  26069. { 71923, 71934, "F\0" },
  26070. { 71943, 71944, "F\0" },
  26071. { 71946, 71947, "F\0" },
  26072. { 71956, 71956, "F\0" },
  26073. { 71959, 71959, "F\0" },
  26074. { 71990, 71990, "F\0" },
  26075. { 71993, 71994, "F\0" },
  26076. { 72007, 72015, "F\0" },
  26077. { 72026, 72095, "F\0" },
  26078. { 72104, 72105, "F\0" },
  26079. { 72152, 72153, "F\0" },
  26080. { 72165, 72191, "F\0" },
  26081. { 72264, 72271, "F\0" },
  26082. { 72355, 72367, "F\0" },
  26083. { 72441, 72703, "F\0" },
  26084. { 72713, 72713, "F\0" },
  26085. { 72759, 72759, "F\0" },
  26086. { 72774, 72783, "F\0" },
  26087. { 72813, 72815, "F\0" },
  26088. { 72848, 72849, "F\0" },
  26089. { 72872, 72872, "F\0" },
  26090. { 72887, 72959, "F\0" },
  26091. { 72967, 72967, "F\0" },
  26092. { 72970, 72970, "F\0" },
  26093. { 73015, 73017, "F\0" },
  26094. { 73019, 73019, "F\0" },
  26095. { 73022, 73022, "F\0" },
  26096. { 73032, 73039, "F\0" },
  26097. { 73050, 73055, "F\0" },
  26098. { 73062, 73062, "F\0" },
  26099. { 73065, 73065, "F\0" },
  26100. { 73103, 73103, "F\0" },
  26101. { 73106, 73106, "F\0" },
  26102. { 73113, 73119, "F\0" },
  26103. { 73130, 73439, "F\0" },
  26104. { 73465, 73647, "F\0" },
  26105. { 73649, 73663, "F\0" },
  26106. { 73714, 73726, "F\0" },
  26107. { 74650, 74751, "F\0" },
  26108. { 74863, 74863, "F\0" },
  26109. { 74869, 74879, "F\0" },
  26110. { 75076, 77711, "F\0" },
  26111. { 77811, 77823, "F\0" },
  26112. { 78895, 78895, "F\0" },
  26113. { 78905, 82943, "F\0" },
  26114. { 83527, 92159, "F\0" },
  26115. { 92729, 92735, "F\0" },
  26116. { 92767, 92767, "F\0" },
  26117. { 92778, 92781, "F\0" },
  26118. { 92863, 92863, "F\0" },
  26119. { 92874, 92879, "F\0" },
  26120. { 92910, 92911, "F\0" },
  26121. { 92918, 92927, "F\0" },
  26122. { 92998, 93007, "F\0" },
  26123. { 93018, 93018, "F\0" },
  26124. { 93026, 93026, "F\0" },
  26125. { 93048, 93052, "F\0" },
  26126. { 93072, 93759, "F\0" },
  26127. { 93851, 93951, "F\0" },
  26128. { 94027, 94030, "F\0" },
  26129. { 94088, 94094, "F\0" },
  26130. { 94112, 94175, "F\0" },
  26131. { 94176, 94180, "W\0" },
  26132. { 94181, 94191, "F\0" },
  26133. { 94192, 94193, "W\0" },
  26134. { 94194, 94207, "F\0" },
  26135. { 94208, 100343, "W\0" },
  26136. { 100344, 100351, "F\0" },
  26137. { 100352, 101589, "W\0" },
  26138. { 101590, 101631, "F\0" },
  26139. { 101632, 101640, "W\0" },
  26140. { 101641, 110575, "F\0" },
  26141. { 110576, 110579, "W\0" },
  26142. { 110580, 110580, "F\0" },
  26143. { 110581, 110587, "W\0" },
  26144. { 110588, 110588, "F\0" },
  26145. { 110589, 110590, "W\0" },
  26146. { 110591, 110591, "F\0" },
  26147. { 110592, 110882, "W\0" },
  26148. { 110883, 110927, "F\0" },
  26149. { 110928, 110930, "W\0" },
  26150. { 110931, 110947, "F\0" },
  26151. { 110948, 110951, "W\0" },
  26152. { 110952, 110959, "F\0" },
  26153. { 110960, 111355, "W\0" },
  26154. { 111356, 113663, "F\0" },
  26155. { 113771, 113775, "F\0" },
  26156. { 113789, 113791, "F\0" },
  26157. { 113801, 113807, "F\0" },
  26158. { 113818, 113819, "F\0" },
  26159. { 113828, 118527, "F\0" },
  26160. { 118574, 118575, "F\0" },
  26161. { 118599, 118607, "F\0" },
  26162. { 118724, 118783, "F\0" },
  26163. { 119030, 119039, "F\0" },
  26164. { 119079, 119080, "F\0" },
  26165. { 119275, 119295, "F\0" },
  26166. { 119366, 119519, "F\0" },
  26167. { 119540, 119551, "F\0" },
  26168. { 119639, 119647, "F\0" },
  26169. { 119673, 119807, "F\0" },
  26170. { 119893, 119893, "F\0" },
  26171. { 119965, 119965, "F\0" },
  26172. { 119968, 119969, "F\0" },
  26173. { 119971, 119972, "F\0" },
  26174. { 119975, 119976, "F\0" },
  26175. { 119981, 119981, "F\0" },
  26176. { 119994, 119994, "F\0" },
  26177. { 119996, 119996, "F\0" },
  26178. { 120004, 120004, "F\0" },
  26179. { 120070, 120070, "F\0" },
  26180. { 120075, 120076, "F\0" },
  26181. { 120085, 120085, "F\0" },
  26182. { 120093, 120093, "F\0" },
  26183. { 120122, 120122, "F\0" },
  26184. { 120127, 120127, "F\0" },
  26185. { 120133, 120133, "F\0" },
  26186. { 120135, 120137, "F\0" },
  26187. { 120145, 120145, "F\0" },
  26188. { 120486, 120487, "F\0" },
  26189. { 120780, 120781, "F\0" },
  26190. { 121484, 121498, "F\0" },
  26191. { 121504, 121504, "F\0" },
  26192. { 121520, 122623, "F\0" },
  26193. { 122655, 122879, "F\0" },
  26194. { 122887, 122887, "F\0" },
  26195. { 122905, 122906, "F\0" },
  26196. { 122914, 122914, "F\0" },
  26197. { 122917, 122917, "F\0" },
  26198. { 122923, 123135, "F\0" },
  26199. { 123181, 123183, "F\0" },
  26200. { 123198, 123199, "F\0" },
  26201. { 123210, 123213, "F\0" },
  26202. { 123216, 123535, "F\0" },
  26203. { 123567, 123583, "F\0" },
  26204. { 123642, 123646, "F\0" },
  26205. { 123648, 124895, "F\0" },
  26206. { 124903, 124903, "F\0" },
  26207. { 124908, 124908, "F\0" },
  26208. { 124911, 124911, "F\0" },
  26209. { 124927, 124927, "F\0" },
  26210. { 125125, 125126, "F\0" },
  26211. { 125143, 125183, "F\0" },
  26212. { 125260, 125263, "F\0" },
  26213. { 125274, 125277, "F\0" },
  26214. { 125280, 126064, "F\0" },
  26215. { 126133, 126208, "F\0" },
  26216. { 126270, 126463, "F\0" },
  26217. { 126468, 126468, "F\0" },
  26218. { 126496, 126496, "F\0" },
  26219. { 126499, 126499, "F\0" },
  26220. { 126501, 126502, "F\0" },
  26221. { 126504, 126504, "F\0" },
  26222. { 126515, 126515, "F\0" },
  26223. { 126520, 126520, "F\0" },
  26224. { 126522, 126522, "F\0" },
  26225. { 126524, 126529, "F\0" },
  26226. { 126531, 126534, "F\0" },
  26227. { 126536, 126536, "F\0" },
  26228. { 126538, 126538, "F\0" },
  26229. { 126540, 126540, "F\0" },
  26230. { 126544, 126544, "F\0" },
  26231. { 126547, 126547, "F\0" },
  26232. { 126549, 126550, "F\0" },
  26233. { 126552, 126552, "F\0" },
  26234. { 126554, 126554, "F\0" },
  26235. { 126556, 126556, "F\0" },
  26236. { 126558, 126558, "F\0" },
  26237. { 126560, 126560, "F\0" },
  26238. { 126563, 126563, "F\0" },
  26239. { 126565, 126566, "F\0" },
  26240. { 126571, 126571, "F\0" },
  26241. { 126579, 126579, "F\0" },
  26242. { 126584, 126584, "F\0" },
  26243. { 126589, 126589, "F\0" },
  26244. { 126591, 126591, "F\0" },
  26245. { 126602, 126602, "F\0" },
  26246. { 126620, 126624, "F\0" },
  26247. { 126628, 126628, "F\0" },
  26248. { 126634, 126634, "F\0" },
  26249. { 126652, 126703, "F\0" },
  26250. { 126706, 126975, "F\0" },
  26251. { 126980, 126980, "W\0" },
  26252. { 127020, 127023, "F\0" },
  26253. { 127124, 127135, "F\0" },
  26254. { 127151, 127152, "F\0" },
  26255. { 127168, 127168, "F\0" },
  26256. { 127183, 127183, "W\0" },
  26257. { 127184, 127184, "F\0" },
  26258. { 127222, 127231, "F\0" },
  26259. { 127232, 127242, "A\0" },
  26260. { 127248, 127277, "A\0" },
  26261. { 127280, 127337, "A\0" },
  26262. { 127344, 127373, "A\0" },
  26263. { 127374, 127374, "W\0" },
  26264. { 127375, 127376, "A\0" },
  26265. { 127377, 127386, "W\0" },
  26266. { 127387, 127404, "A\0" },
  26267. { 127406, 127461, "F\0" },
  26268. { 127488, 127490, "W\0" },
  26269. { 127491, 127503, "F\0" },
  26270. { 127504, 127547, "W\0" },
  26271. { 127548, 127551, "F\0" },
  26272. { 127552, 127560, "W\0" },
  26273. { 127561, 127567, "F\0" },
  26274. { 127568, 127569, "W\0" },
  26275. { 127570, 127583, "F\0" },
  26276. { 127584, 127589, "W\0" },
  26277. { 127590, 127743, "F\0" },
  26278. { 127744, 127776, "W\0" },
  26279. { 127789, 127797, "W\0" },
  26280. { 127799, 127868, "W\0" },
  26281. { 127870, 127891, "W\0" },
  26282. { 127904, 127946, "W\0" },
  26283. { 127951, 127955, "W\0" },
  26284. { 127968, 127984, "W\0" },
  26285. { 127988, 127988, "W\0" },
  26286. { 127992, 128062, "W\0" },
  26287. { 128064, 128064, "W\0" },
  26288. { 128066, 128252, "W\0" },
  26289. { 128255, 128317, "W\0" },
  26290. { 128331, 128334, "W\0" },
  26291. { 128336, 128359, "W\0" },
  26292. { 128378, 128378, "W\0" },
  26293. { 128405, 128406, "W\0" },
  26294. { 128420, 128420, "W\0" },
  26295. { 128507, 128591, "W\0" },
  26296. { 128640, 128709, "W\0" },
  26297. { 128716, 128716, "W\0" },
  26298. { 128720, 128722, "W\0" },
  26299. { 128725, 128727, "W\0" },
  26300. { 128728, 128732, "F\0" },
  26301. { 128733, 128735, "W\0" },
  26302. { 128747, 128748, "W\0" },
  26303. { 128749, 128751, "F\0" },
  26304. { 128756, 128764, "W\0" },
  26305. { 128765, 128767, "F\0" },
  26306. { 128884, 128895, "F\0" },
  26307. { 128985, 128991, "F\0" },
  26308. { 128992, 129003, "W\0" },
  26309. { 129004, 129007, "F\0" },
  26310. { 129008, 129008, "W\0" },
  26311. { 129009, 129023, "F\0" },
  26312. { 129036, 129039, "F\0" },
  26313. { 129096, 129103, "F\0" },
  26314. { 129114, 129119, "F\0" },
  26315. { 129160, 129167, "F\0" },
  26316. { 129198, 129199, "F\0" },
  26317. { 129202, 129279, "F\0" },
  26318. { 129292, 129338, "W\0" },
  26319. { 129340, 129349, "W\0" },
  26320. { 129351, 129535, "W\0" },
  26321. { 129620, 129631, "F\0" },
  26322. { 129646, 129647, "F\0" },
  26323. { 129648, 129652, "W\0" },
  26324. { 129653, 129655, "F\0" },
  26325. { 129656, 129660, "W\0" },
  26326. { 129661, 129663, "F\0" },
  26327. { 129664, 129670, "W\0" },
  26328. { 129671, 129679, "F\0" },
  26329. { 129680, 129708, "W\0" },
  26330. { 129709, 129711, "F\0" },
  26331. { 129712, 129722, "W\0" },
  26332. { 129723, 129727, "F\0" },
  26333. { 129728, 129733, "W\0" },
  26334. { 129734, 129743, "F\0" },
  26335. { 129744, 129753, "W\0" },
  26336. { 129754, 129759, "F\0" },
  26337. { 129760, 129767, "W\0" },
  26338. { 129768, 129775, "F\0" },
  26339. { 129776, 129782, "W\0" },
  26340. { 129783, 129791, "F\0" },
  26341. { 129939, 129939, "F\0" },
  26342. { 129995, 130031, "F\0" },
  26343. { 130042, 131071, "F\0" },
  26344. { 131072, 173791, "W\0" },
  26345. { 173792, 173823, "F\0" },
  26346. { 173824, 177976, "W\0" },
  26347. { 177977, 177983, "F\0" },
  26348. { 177984, 178205, "W\0" },
  26349. { 178206, 178207, "F\0" },
  26350. { 178208, 183969, "W\0" },
  26351. { 183970, 183983, "F\0" },
  26352. { 183984, 191456, "W\0" },
  26353. { 191457, 194559, "F\0" },
  26354. { 194560, 195101, "W\0" },
  26355. { 195102, 196607, "F\0" },
  26356. { 196608, 201546, "W\0" },
  26357. { 201547, 917504, "F\0" },
  26358. { 917506, 917535, "F\0" },
  26359. { 917632, 917759, "F\0" },
  26360. { 917760, 917999, "A\0" },
  26361. { 918000, 983039, "F\0" },
  26362. { 983040, 1048573, "A\0" },
  26363. { 1048574, 1048575, "F\0" },
  26364. { 1048576, 1114109, "A\0" },
  26365. { 1114110, 1114111, "F\0" },
  26366. };
  26367. // clang-format on
  26368. const char* c11__u32_east_asian_width(int c) {
  26369. const char* data =
  26370. c11__search_u32_ranges(c,
  26371. kEastAsianWidthRanges,
  26372. sizeof(kEastAsianWidthRanges) / sizeof(c11_u32_range));
  26373. if(data == NULL) return "N";
  26374. return data;
  26375. }
  26376. static bool unicodedata_east_asian_width(int argc, py_Ref argv) {
  26377. PY_CHECK_ARGC(1);
  26378. PY_CHECK_ARG_TYPE(0, tp_str);
  26379. c11_sv sv = py_tosv(py_arg(0));
  26380. if(c11_sv__u8_length(sv) != 1) {
  26381. return TypeError("east_asian_width() expected a character, but string of length %d found",
  26382. c11_sv__u8_length(sv));
  26383. }
  26384. int u8bytes = c11__u8_header(sv.data[0], true);
  26385. if(u8bytes == 0) return ValueError("invalid utf-8 char: %c", sv.data[0]);
  26386. int value = c11__u8_value(u8bytes, sv.data);
  26387. const char* width = c11__u32_east_asian_width(value);
  26388. py_newstr(py_retval(), width);
  26389. return true;
  26390. }
  26391. void pk__add_module_unicodedata() {
  26392. py_Ref mod = py_newmodule("unicodedata");
  26393. py_bindfunc(mod, "east_asian_width", unicodedata_east_asian_width);
  26394. }
  26395. // src/modules\vmath.c
  26396. static bool isclose(float a, float b) { return dmath_fabs(a - b) < 1e-4; }
  26397. py_i64 cpy312__int_floordiv(py_i64 a, py_i64 b);
  26398. py_i64 cpy312__int_mod(py_i64 a, py_i64 b);
  26399. #define DEFINE_VEC_FIELD(name, T, Tc, field) \
  26400. static bool name##__##field(int argc, py_Ref argv) { \
  26401. PY_CHECK_ARGC(1); \
  26402. py_new##T(py_retval(), py_to##name(argv).field); \
  26403. return true; \
  26404. } \
  26405. static bool name##__with_##field(int argc, py_Ref argv) { \
  26406. PY_CHECK_ARGC(2); \
  26407. Tc val; \
  26408. if(!py_cast##T(&argv[1], &val)) return false; \
  26409. c11_##name v = py_to##name(argv); \
  26410. v.field = val; \
  26411. py_new##name(py_retval(), v); \
  26412. return true; \
  26413. }
  26414. #define DEFINE_BOOL_NE(name, f_eq) \
  26415. static bool name##__ne__(int argc, py_Ref argv) { \
  26416. f_eq(argc, argv); \
  26417. py_Ref ret = py_retval(); \
  26418. if(ret->type == tp_NotImplementedType) return true; \
  26419. ret->_bool = !ret->_bool; \
  26420. return true; \
  26421. }
  26422. void py_newvec2(py_OutRef out, c11_vec2 v) {
  26423. out->type = tp_vec2;
  26424. out->is_ptr = false;
  26425. out->_vec2 = v;
  26426. }
  26427. c11_vec2 py_tovec2(py_Ref self) {
  26428. assert(self->type == tp_vec2);
  26429. return self->_vec2;
  26430. }
  26431. void py_newvec2i(py_OutRef out, c11_vec2i v) {
  26432. out->type = tp_vec2i;
  26433. out->is_ptr = false;
  26434. out->_vec2i = v;
  26435. }
  26436. c11_vec2i py_tovec2i(py_Ref self) {
  26437. assert(self->type == tp_vec2i);
  26438. return self->_vec2i;
  26439. }
  26440. void py_newvec3(py_OutRef out, c11_vec3 v) {
  26441. out->type = tp_vec3;
  26442. out->is_ptr = false;
  26443. out->_vec3 = v;
  26444. }
  26445. c11_vec3 py_tovec3(py_Ref self) {
  26446. assert(self->type == tp_vec3);
  26447. return self->_vec3;
  26448. }
  26449. void py_newvec3i(py_OutRef out, c11_vec3i v) {
  26450. out->type = tp_vec3i;
  26451. out->is_ptr = false;
  26452. out->_vec3i = v;
  26453. }
  26454. c11_vec3i py_tovec3i(py_Ref self) {
  26455. assert(self->type == tp_vec3i);
  26456. return self->_vec3i;
  26457. }
  26458. void py_newvec4i(py_OutRef out, c11_vec4i v) {
  26459. out->type = tp_vec4i;
  26460. out->is_ptr = false;
  26461. out->_vec4i = v;
  26462. }
  26463. c11_vec4i py_tovec4i(py_Ref self) {
  26464. assert(self->type == tp_vec4i);
  26465. return self->_vec4i;
  26466. }
  26467. c11_mat3x3* py_newmat3x3(py_OutRef out) {
  26468. return py_newobject(out, tp_mat3x3, 0, sizeof(c11_mat3x3));
  26469. }
  26470. c11_mat3x3* py_tomat3x3(py_Ref self) {
  26471. assert(self->type == tp_mat3x3);
  26472. return py_touserdata(self);
  26473. }
  26474. static py_Ref _const(py_Type type, const char* name) {
  26475. return py_emplacedict(py_tpobject(type), py_name(name));
  26476. }
  26477. #define DEF_VECTOR_ELEMENT_WISE(D, T, name, op) \
  26478. static bool T##name(int argc, py_Ref argv) { \
  26479. PY_CHECK_ARGC(2); \
  26480. if(argv[1].type != tp_##T) { \
  26481. py_newnotimplemented(py_retval()); \
  26482. return true; \
  26483. } \
  26484. c11_##T a = py_to##T(&argv[0]); \
  26485. c11_##T b = py_to##T(&argv[1]); \
  26486. c11_##T res; \
  26487. for(int i = 0; i < D; i++) \
  26488. res.data[i] = a.data[i] op b.data[i]; \
  26489. py_new##T(py_retval(), res); \
  26490. return true; \
  26491. }
  26492. #define DEF_VECTOR_OPS(D) \
  26493. static bool vec##D##__new__(int argc, py_Ref argv) { \
  26494. c11_vec##D res; \
  26495. if(argc == 2) { \
  26496. PY_CHECK_ARG_TYPE(1, tp_vec##D##i); \
  26497. c11_vec##D##i v = py_tovec##D##i(&argv[1]); \
  26498. for(int i = 0; i < D; i++) \
  26499. res.data[i] = v.data[i]; \
  26500. } else { \
  26501. PY_CHECK_ARGC(D + 1); \
  26502. for(int i = 0; i < D; i++) { \
  26503. if(!py_castfloat32(&argv[i + 1], &res.data[i])) return false; \
  26504. } \
  26505. } \
  26506. py_newvec##D(py_retval(), res); \
  26507. return true; \
  26508. } \
  26509. DEF_VECTOR_ELEMENT_WISE(D, vec##D, __add__, +) \
  26510. DEF_VECTOR_ELEMENT_WISE(D, vec##D, __sub__, -) \
  26511. static bool vec##D##__mul__(int argc, py_Ref argv) { \
  26512. PY_CHECK_ARGC(2); \
  26513. c11_vec##D res; \
  26514. switch(argv[1].type) { \
  26515. case tp_vec##D: { \
  26516. c11_vec##D a = py_tovec##D(&argv[0]); \
  26517. c11_vec##D b = py_tovec##D(&argv[1]); \
  26518. for(int i = 0; i < D; i++) \
  26519. res.data[i] = a.data[i] * b.data[i]; \
  26520. py_newvec##D(py_retval(), res); \
  26521. return true; \
  26522. } \
  26523. case tp_int: { \
  26524. c11_vec##D a = py_tovec##D(&argv[0]); \
  26525. py_i64 b = argv[1]._i64; \
  26526. for(int i = 0; i < D; i++) \
  26527. res.data[i] = a.data[i] * b; \
  26528. py_newvec##D(py_retval(), res); \
  26529. return true; \
  26530. } \
  26531. case tp_float: { \
  26532. c11_vec##D a = py_tovec##D(&argv[0]); \
  26533. py_f64 b = argv[1]._f64; \
  26534. for(int i = 0; i < D; i++) \
  26535. res.data[i] = a.data[i] * b; \
  26536. py_newvec##D(py_retval(), res); \
  26537. return true; \
  26538. } \
  26539. default: py_newnotimplemented(py_retval()); return true; \
  26540. } \
  26541. } \
  26542. static bool vec##D##__truediv__(int argc, py_Ref argv) { \
  26543. PY_CHECK_ARGC(2); \
  26544. float divisor; \
  26545. if(!py_castfloat32(&argv[1], &divisor)) { \
  26546. py_clearexc(NULL); \
  26547. py_newnotimplemented(py_retval()); \
  26548. return true; \
  26549. } \
  26550. c11_vec##D res; \
  26551. c11_vec##D a = py_tovec##D(&argv[0]); \
  26552. for(int i = 0; i < D; i++) \
  26553. res.data[i] = a.data[i] / divisor; \
  26554. py_newvec##D(py_retval(), res); \
  26555. return true; \
  26556. } \
  26557. static bool vec##D##__eq__(int argc, py_Ref argv) { \
  26558. PY_CHECK_ARGC(2); \
  26559. if(argv[1].type != tp_vec##D) { \
  26560. py_newnotimplemented(py_retval()); \
  26561. return true; \
  26562. } \
  26563. c11_vec##D lhs = py_tovec##D(&argv[0]); \
  26564. c11_vec##D rhs = py_tovec##D(&argv[1]); \
  26565. bool ok = true; \
  26566. for(int i = 0; i < D; i++) { \
  26567. if(!isclose(lhs.data[i], rhs.data[i])) ok = false; \
  26568. } \
  26569. py_newbool(py_retval(), ok); \
  26570. return true; \
  26571. } \
  26572. DEFINE_BOOL_NE(vec##D, vec##D##__eq__) \
  26573. static bool vec##D##_length(int argc, py_Ref argv) { \
  26574. PY_CHECK_ARGC(1); \
  26575. c11_vec##D v = py_tovec##D(argv); \
  26576. float sum = 0; \
  26577. for(int i = 0; i < D; i++) \
  26578. sum += v.data[i] * v.data[i]; \
  26579. py_newfloat(py_retval(), dmath_sqrt(sum)); \
  26580. return true; \
  26581. } \
  26582. static bool vec##D##_length_squared(int argc, py_Ref argv) { \
  26583. PY_CHECK_ARGC(1); \
  26584. c11_vec##D v = py_tovec##D(argv); \
  26585. float sum = 0; \
  26586. for(int i = 0; i < D; i++) \
  26587. sum += v.data[i] * v.data[i]; \
  26588. py_newfloat(py_retval(), sum); \
  26589. return true; \
  26590. } \
  26591. static bool vec##D##_dot(int argc, py_Ref argv) { \
  26592. PY_CHECK_ARGC(2); \
  26593. PY_CHECK_ARG_TYPE(1, tp_vec##D); \
  26594. c11_vec##D a = py_tovec##D(&argv[0]); \
  26595. c11_vec##D b = py_tovec##D(&argv[1]); \
  26596. float sum = 0; \
  26597. for(int i = 0; i < D; i++) \
  26598. sum += a.data[i] * b.data[i]; \
  26599. py_newfloat(py_retval(), sum); \
  26600. return true; \
  26601. } \
  26602. static bool vec##D##_normalize(int argc, py_Ref argv) { \
  26603. PY_CHECK_ARGC(1); \
  26604. c11_vec##D self = py_tovec##D(argv); \
  26605. float len = 0; \
  26606. for(int i = 0; i < D; i++) \
  26607. len += self.data[i] * self.data[i]; \
  26608. if(isclose(len, 0)) return ZeroDivisionError("cannot normalize zero vector"); \
  26609. len = dmath_sqrt(len); \
  26610. c11_vec##D res; \
  26611. for(int i = 0; i < D; i++) \
  26612. res.data[i] = self.data[i] / len; \
  26613. py_newvec##D(py_retval(), res); \
  26614. return true; \
  26615. }
  26616. DEF_VECTOR_OPS(2)
  26617. DEF_VECTOR_OPS(3)
  26618. #define DEF_VECTOR_INT_OPS(D) \
  26619. static bool vec##D##i__new__(int argc, py_Ref argv) { \
  26620. PY_CHECK_ARGC(D + 1); \
  26621. c11_vec##D##i res; \
  26622. for(int i = 0; i < D; i++) { \
  26623. if(!py_checkint(&argv[i + 1])) return false; \
  26624. res.data[i] = py_toint(&argv[i + 1]); \
  26625. } \
  26626. py_newvec##D##i(py_retval(), res); \
  26627. return true; \
  26628. } \
  26629. DEF_VECTOR_ELEMENT_WISE(D, vec##D##i, __add__, +) \
  26630. DEF_VECTOR_ELEMENT_WISE(D, vec##D##i, __sub__, -) \
  26631. static bool vec##D##i__mul__(int argc, py_Ref argv) { \
  26632. PY_CHECK_ARGC(2); \
  26633. c11_vec##D##i res; \
  26634. switch(argv[1].type) { \
  26635. case tp_vec##D##i: { \
  26636. c11_vec##D##i a = py_tovec##D##i(&argv[0]); \
  26637. c11_vec##D##i b = py_tovec##D##i(&argv[1]); \
  26638. for(int i = 0; i < D; i++) \
  26639. res.data[i] = a.data[i] * b.data[i]; \
  26640. py_newvec##D##i(py_retval(), res); \
  26641. return true; \
  26642. } \
  26643. case tp_int: { \
  26644. c11_vec##D##i a = py_tovec##D##i(&argv[0]); \
  26645. py_i64 b = argv[1]._i64; \
  26646. for(int i = 0; i < D; i++) \
  26647. res.data[i] = a.data[i] * b; \
  26648. py_newvec##D##i(py_retval(), res); \
  26649. return true; \
  26650. } \
  26651. default: py_newnotimplemented(py_retval()); return true; \
  26652. } \
  26653. } \
  26654. static bool vec##D##i__eq__(int argc, py_Ref argv) { \
  26655. PY_CHECK_ARGC(2); \
  26656. if(argv[1].type != tp_vec##D##i) { \
  26657. py_newnotimplemented(py_retval()); \
  26658. return true; \
  26659. } \
  26660. c11_vec##D##i lhs = py_tovec##D##i(&argv[0]); \
  26661. c11_vec##D##i rhs = py_tovec##D##i(&argv[1]); \
  26662. bool ok = true; \
  26663. for(int i = 0; i < D; i++) { \
  26664. if(lhs.data[i] != rhs.data[i]) ok = false; \
  26665. } \
  26666. py_newbool(py_retval(), ok); \
  26667. return true; \
  26668. } \
  26669. DEFINE_BOOL_NE(vec##D##i, vec##D##i__eq__) \
  26670. static bool vec##D##i##_dot(int argc, py_Ref argv) { \
  26671. PY_CHECK_ARGC(2); \
  26672. PY_CHECK_ARG_TYPE(1, tp_vec##D##i); \
  26673. c11_vec##D##i a = py_tovec##D##i(&argv[0]); \
  26674. c11_vec##D##i b = py_tovec##D##i(&argv[1]); \
  26675. py_i64 sum = 0; \
  26676. for(int i = 0; i < D; i++) \
  26677. sum += a.data[i] * b.data[i]; \
  26678. py_newint(py_retval(), sum); \
  26679. return true; \
  26680. } \
  26681. static bool vec##D##i##__floordiv__(int argc, py_Ref argv) { \
  26682. PY_CHECK_ARGC(2); \
  26683. PY_CHECK_ARG_TYPE(1, tp_int); \
  26684. c11_vec##D##i a = py_tovec##D##i(&argv[0]); \
  26685. py_i64 b = py_toint(&argv[1]); \
  26686. for(int i = 0; i < D; i++) \
  26687. a.data[i] = cpy312__int_floordiv(a.data[i], b); \
  26688. py_newvec##D##i(py_retval(), a); \
  26689. return true; \
  26690. } \
  26691. static bool vec##D##i##__mod__(int argc, py_Ref argv) { \
  26692. PY_CHECK_ARGC(2); \
  26693. PY_CHECK_ARG_TYPE(1, tp_int); \
  26694. c11_vec##D##i a = py_tovec##D##i(&argv[0]); \
  26695. py_i64 b = py_toint(&argv[1]); \
  26696. for(int i = 0; i < D; i++) \
  26697. a.data[i] = cpy312__int_mod(a.data[i], b); \
  26698. py_newvec##D##i(py_retval(), a); \
  26699. return true; \
  26700. }
  26701. DEF_VECTOR_INT_OPS(2)
  26702. DEF_VECTOR_INT_OPS(3)
  26703. DEF_VECTOR_INT_OPS(4)
  26704. // vec2i l1_norm, l2_norm, max_norm
  26705. static bool vec2i_l1_norm(int argc, py_Ref argv) {
  26706. PY_CHECK_ARGC(1);
  26707. c11_vec2i v = py_tovec2i(argv);
  26708. int norm = abs(v.x) + abs(v.y);
  26709. py_newint(py_retval(), norm);
  26710. return true;
  26711. }
  26712. static bool vec2i_l2_norm(int argc, py_Ref argv) {
  26713. PY_CHECK_ARGC(1);
  26714. c11_vec2i v = py_tovec2i(argv);
  26715. double norm = dmath_sqrt(v.x * v.x + v.y * v.y);
  26716. py_newfloat(py_retval(), norm);
  26717. return true;
  26718. }
  26719. static bool vec2i_max_norm(int argc, py_Ref argv) {
  26720. PY_CHECK_ARGC(1);
  26721. c11_vec2i v = py_tovec2i(argv);
  26722. int norm = c11__max(abs(v.x), abs(v.y));
  26723. py_newint(py_retval(), norm);
  26724. return true;
  26725. }
  26726. static bool vec2i__hash__(int argc, py_Ref argv) {
  26727. PY_CHECK_ARGC(1);
  26728. c11_vec2i v = py_tovec2i(argv);
  26729. uint64_t x_part = (uint32_t)v.x & 0xFFFFFFFF;
  26730. uint64_t y_part = (uint32_t)v.y & 0xFFFFFFFF;
  26731. uint64_t hash = (x_part << 32) | y_part;
  26732. py_newint(py_retval(), (py_i64)hash);
  26733. return true;
  26734. }
  26735. static bool vec3i__hash__(int argc, py_Ref argv) {
  26736. PY_CHECK_ARGC(1);
  26737. c11_vec3i v = py_tovec3i(argv);
  26738. uint64_t x_part = (uint32_t)v.x & 0xFFFFFF;
  26739. uint64_t y_part = (uint32_t)v.y & 0xFFFFFF;
  26740. uint64_t z_part = (uint32_t)v.z & 0xFFFF;
  26741. uint64_t hash = (x_part << 40) | (y_part << 16) | z_part;
  26742. py_newint(py_retval(), (py_i64)hash);
  26743. return true;
  26744. }
  26745. static bool vec4i__hash__(int argc, py_Ref argv) {
  26746. PY_CHECK_ARGC(1);
  26747. c11_vec4i v = py_tovec4i(argv);
  26748. uint64_t x_part = (uint32_t)v.x & 0xFFFF;
  26749. uint64_t y_part = (uint32_t)v.y & 0xFFFF;
  26750. uint64_t z_part = (uint32_t)v.z & 0xFFFF;
  26751. uint64_t w_part = (uint32_t)v.w & 0xFFFF;
  26752. uint64_t hash = (x_part << 48) | (y_part << 32) | (z_part << 16) | w_part;
  26753. py_newint(py_retval(), (py_i64)hash);
  26754. return true;
  26755. }
  26756. static bool vec2__repr__(int argc, py_Ref argv) {
  26757. PY_CHECK_ARGC(1);
  26758. char buf[64];
  26759. int size = snprintf(buf, 64, "vec2(%.4f, %.4f)", argv[0]._vec2.x, argv[0]._vec2.y);
  26760. py_newstrv(py_retval(), (c11_sv){buf, size});
  26761. return true;
  26762. }
  26763. static bool vec2_rotate(int argc, py_Ref argv) {
  26764. PY_CHECK_ARGC(2);
  26765. py_f64 radians;
  26766. if(!py_castfloat(&argv[1], &radians)) return false;
  26767. double sr, cr;
  26768. dmath_sincos(radians, &sr, &cr);
  26769. c11_vec2 res;
  26770. res.x = argv[0]._vec2.x * cr - argv[0]._vec2.y * sr;
  26771. res.y = argv[0]._vec2.x * sr + argv[0]._vec2.y * cr;
  26772. py_newvec2(py_retval(), res);
  26773. return true;
  26774. }
  26775. static bool vec2_angle_STATIC(int argc, py_Ref argv) {
  26776. PY_CHECK_ARGC(2);
  26777. PY_CHECK_ARG_TYPE(0, tp_vec2);
  26778. PY_CHECK_ARG_TYPE(1, tp_vec2);
  26779. float val = dmath_atan2(argv[1]._vec2.y, argv[1]._vec2.x) -
  26780. dmath_atan2(argv[0]._vec2.y, argv[0]._vec2.x);
  26781. if(val > DMATH_PI) val -= 2 * (float)DMATH_PI;
  26782. if(val < -DMATH_PI) val += 2 * (float)DMATH_PI;
  26783. py_newfloat(py_retval(), val);
  26784. return true;
  26785. }
  26786. static bool vec2_smoothdamp_STATIC(int argc, py_Ref argv) {
  26787. PY_CHECK_ARGC(6);
  26788. PY_CHECK_ARG_TYPE(0, tp_vec2); // current: vec2
  26789. PY_CHECK_ARG_TYPE(1, tp_vec2); // target: vec2
  26790. PY_CHECK_ARG_TYPE(2, tp_vec2); // current_velocity: vec2
  26791. float smoothTime;
  26792. if(!py_castfloat32(&argv[3], &smoothTime)) return false;
  26793. float maxSpeed;
  26794. if(!py_castfloat32(&argv[4], &maxSpeed)) return false;
  26795. float deltaTime;
  26796. if(!py_castfloat32(&argv[5], &deltaTime)) return false;
  26797. c11_vec2 current = argv[0]._vec2;
  26798. c11_vec2 target = argv[1]._vec2;
  26799. c11_vec2 currentVelocity = argv[2]._vec2;
  26800. // https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Math/Vector2.cs#L289
  26801. // Based on Game Programming Gems 4 Chapter 1.10
  26802. smoothTime = c11__max(0.0001F, smoothTime);
  26803. float omega = 2.0F / smoothTime;
  26804. float x = omega * deltaTime;
  26805. float exp = 1.0F / (1.0F + x + 0.48F * x * x + 0.235F * x * x * x);
  26806. float change_x = current.x - target.x;
  26807. float change_y = current.y - target.y;
  26808. c11_vec2 originalTo = target;
  26809. // Clamp maximum speed
  26810. float maxChange = maxSpeed * smoothTime;
  26811. float maxChangeSq = maxChange * maxChange;
  26812. float sqDist = change_x * change_x + change_y * change_y;
  26813. if(sqDist > maxChangeSq) {
  26814. float mag = dmath_sqrt(sqDist);
  26815. change_x = change_x / mag * maxChange;
  26816. change_y = change_y / mag * maxChange;
  26817. }
  26818. target.x = current.x - change_x;
  26819. target.y = current.y - change_y;
  26820. float temp_x = (currentVelocity.x + omega * change_x) * deltaTime;
  26821. float temp_y = (currentVelocity.y + omega * change_y) * deltaTime;
  26822. currentVelocity.x = (currentVelocity.x - omega * temp_x) * exp;
  26823. currentVelocity.y = (currentVelocity.y - omega * temp_y) * exp;
  26824. float output_x = target.x + (change_x + temp_x) * exp;
  26825. float output_y = target.y + (change_y + temp_y) * exp;
  26826. // Prevent overshooting
  26827. float origMinusCurrent_x = originalTo.x - current.x;
  26828. float origMinusCurrent_y = originalTo.y - current.y;
  26829. float outMinusOrig_x = output_x - originalTo.x;
  26830. float outMinusOrig_y = output_y - originalTo.y;
  26831. if(origMinusCurrent_x * outMinusOrig_x + origMinusCurrent_y * outMinusOrig_y > 0) {
  26832. output_x = originalTo.x;
  26833. output_y = originalTo.y;
  26834. currentVelocity.x = (output_x - originalTo.x) / deltaTime;
  26835. currentVelocity.y = (output_y - originalTo.y) / deltaTime;
  26836. }
  26837. py_Ref ret = py_retval();
  26838. py_Ref p = py_newtuple(ret, 2);
  26839. py_newvec2(&p[0],
  26840. (c11_vec2){
  26841. {output_x, output_y}
  26842. });
  26843. py_newvec2(&p[1], currentVelocity);
  26844. return true;
  26845. }
  26846. DEFINE_VEC_FIELD(vec2, float, py_f64, x)
  26847. DEFINE_VEC_FIELD(vec2, float, py_f64, y)
  26848. static bool vec2__with_z(int argc, py_Ref argv) {
  26849. PY_CHECK_ARGC(2);
  26850. float z;
  26851. if(!py_castfloat32(&argv[1], &z)) return false;
  26852. c11_vec3 v = {
  26853. {argv->_vec2.x, argv->_vec2.y, z}
  26854. };
  26855. py_newvec3(py_retval(), v);
  26856. return true;
  26857. }
  26858. /* mat3x3 */
  26859. static bool mat3x3__new__(int argc, py_Ref argv) {
  26860. PY_CHECK_ARGC(10);
  26861. c11_mat3x3* m = py_newmat3x3(py_retval());
  26862. for(int i = 0; i < 9; i++) {
  26863. py_f64 val;
  26864. if(!py_castfloat(&argv[i + 1], &val)) return false;
  26865. m->data[i] = val;
  26866. }
  26867. return true;
  26868. }
  26869. static bool mat3x3__repr__(int argc, py_Ref argv) {
  26870. PY_CHECK_ARGC(1);
  26871. c11_mat3x3* m = py_tomat3x3(argv);
  26872. char buf[256];
  26873. const char* fmt =
  26874. "mat3x3(%.4f, %.4f, %.4f,\n %.4f, %.4f, %.4f,\n "
  26875. " %.4f, %.4f, %.4f)";
  26876. int size = snprintf(buf,
  26877. 256,
  26878. fmt,
  26879. m->data[0],
  26880. m->data[1],
  26881. m->data[2],
  26882. m->data[3],
  26883. m->data[4],
  26884. m->data[5],
  26885. m->data[6],
  26886. m->data[7],
  26887. m->data[8]);
  26888. py_newstrv(py_retval(), (c11_sv){buf, size});
  26889. return true;
  26890. }
  26891. static bool mat3x3__getitem__(int argc, py_Ref argv) {
  26892. PY_CHECK_ARGC(2);
  26893. PY_CHECK_ARG_TYPE(1, tp_tuple);
  26894. c11_mat3x3* ud = py_tomat3x3(argv);
  26895. if(py_tuple_len(&argv[1]) != 2) return IndexError("expected a tuple of length 2");
  26896. py_Ref i = py_tuple_getitem(&argv[1], 0);
  26897. py_Ref j = py_tuple_getitem(&argv[1], 1);
  26898. if(!py_checktype(i, tp_int) || !py_checktype(j, tp_int)) return false;
  26899. if(i->_i64 < 0 || i->_i64 >= 3 || j->_i64 < 0 || j->_i64 >= 3) {
  26900. return IndexError("index out of range");
  26901. }
  26902. py_newfloat(py_retval(), ud->m[i->_i64][j->_i64]);
  26903. return true;
  26904. }
  26905. static bool mat3x3__setitem__(int argc, py_Ref argv) {
  26906. PY_CHECK_ARGC(3);
  26907. PY_CHECK_ARG_TYPE(1, tp_tuple);
  26908. c11_mat3x3* ud = py_tomat3x3(argv);
  26909. if(py_tuple_len(&argv[1]) != 2) return IndexError("expected a tuple of length 2");
  26910. py_Ref i = py_tuple_getitem(&argv[1], 0);
  26911. py_Ref j = py_tuple_getitem(&argv[1], 1);
  26912. if(!py_checktype(i, tp_int) || !py_checktype(j, tp_int)) return false;
  26913. py_f64 val;
  26914. if(!py_castfloat(&argv[2], &val)) return false;
  26915. if(i->_i64 < 0 || i->_i64 >= 3 || j->_i64 < 0 || j->_i64 >= 3) {
  26916. return IndexError("index out of range");
  26917. }
  26918. ud->m[i->_i64][j->_i64] = val;
  26919. py_newnone(py_retval());
  26920. return true;
  26921. }
  26922. static bool mat3x3__eq__(int argc, py_Ref argv) {
  26923. PY_CHECK_ARGC(2);
  26924. if(argv[1].type != tp_mat3x3) {
  26925. py_newnotimplemented(py_retval());
  26926. return true;
  26927. }
  26928. c11_mat3x3* lhs = py_tomat3x3(argv);
  26929. c11_mat3x3* rhs = py_tomat3x3(&argv[1]);
  26930. for(int i = 0; i < 9; i++) {
  26931. if(!isclose(lhs->data[i], rhs->data[i])) {
  26932. py_newbool(py_retval(), false);
  26933. return true;
  26934. }
  26935. }
  26936. py_newbool(py_retval(), true);
  26937. return true;
  26938. }
  26939. DEFINE_BOOL_NE(mat3x3, mat3x3__eq__)
  26940. static void matmul(const c11_mat3x3* lhs, const c11_mat3x3* rhs, c11_mat3x3* restrict out) {
  26941. out->_11 = lhs->_11 * rhs->_11 + lhs->_12 * rhs->_21 + lhs->_13 * rhs->_31;
  26942. out->_12 = lhs->_11 * rhs->_12 + lhs->_12 * rhs->_22 + lhs->_13 * rhs->_32;
  26943. out->_13 = lhs->_11 * rhs->_13 + lhs->_12 * rhs->_23 + lhs->_13 * rhs->_33;
  26944. out->_21 = lhs->_21 * rhs->_11 + lhs->_22 * rhs->_21 + lhs->_23 * rhs->_31;
  26945. out->_22 = lhs->_21 * rhs->_12 + lhs->_22 * rhs->_22 + lhs->_23 * rhs->_32;
  26946. out->_23 = lhs->_21 * rhs->_13 + lhs->_22 * rhs->_23 + lhs->_23 * rhs->_33;
  26947. out->_31 = lhs->_31 * rhs->_11 + lhs->_32 * rhs->_21 + lhs->_33 * rhs->_31;
  26948. out->_32 = lhs->_31 * rhs->_12 + lhs->_32 * rhs->_22 + lhs->_33 * rhs->_32;
  26949. out->_33 = lhs->_31 * rhs->_13 + lhs->_32 * rhs->_23 + lhs->_33 * rhs->_33;
  26950. }
  26951. static float determinant(const c11_mat3x3* m) {
  26952. return m->_11 * (m->_22 * m->_33 - m->_23 * m->_32) -
  26953. m->_12 * (m->_21 * m->_33 - m->_23 * m->_31) +
  26954. m->_13 * (m->_21 * m->_32 - m->_22 * m->_31);
  26955. }
  26956. static bool inverse(const c11_mat3x3* m, c11_mat3x3* restrict out) {
  26957. float det = determinant(m);
  26958. if(isclose(det, 0)) return false;
  26959. float invdet = 1.0f / det;
  26960. out->_11 = (m->_22 * m->_33 - m->_23 * m->_32) * invdet;
  26961. out->_12 = (m->_13 * m->_32 - m->_12 * m->_33) * invdet;
  26962. out->_13 = (m->_12 * m->_23 - m->_13 * m->_22) * invdet;
  26963. out->_21 = (m->_23 * m->_31 - m->_21 * m->_33) * invdet;
  26964. out->_22 = (m->_11 * m->_33 - m->_13 * m->_31) * invdet;
  26965. out->_23 = (m->_13 * m->_21 - m->_11 * m->_23) * invdet;
  26966. out->_31 = (m->_21 * m->_32 - m->_22 * m->_31) * invdet;
  26967. out->_32 = (m->_12 * m->_31 - m->_11 * m->_32) * invdet;
  26968. out->_33 = (m->_11 * m->_22 - m->_12 * m->_21) * invdet;
  26969. return true;
  26970. }
  26971. static void trs(c11_vec2 t, float r, c11_vec2 s, c11_mat3x3* restrict out) {
  26972. double sr, cr;
  26973. dmath_sincos(r, &sr, &cr);
  26974. // clang-format off
  26975. *out = (c11_mat3x3){
  26976. ._11 = s.x * cr, ._12 = -s.y * sr, ._13 = t.x,
  26977. ._21 = s.x * sr, ._22 = s.y * cr, ._23 = t.y,
  26978. ._31 = 0, ._32 = 0, ._33 = 1,
  26979. };
  26980. // clang-format on
  26981. }
  26982. static bool mat3x3__matmul__(int argc, py_Ref argv) {
  26983. PY_CHECK_ARGC(2);
  26984. c11_mat3x3* lhs = py_tomat3x3(argv);
  26985. if(argv[1].type == tp_mat3x3) {
  26986. c11_mat3x3* rhs = py_tomat3x3(&argv[1]);
  26987. c11_mat3x3* out = py_newmat3x3(py_retval());
  26988. matmul(lhs, rhs, out);
  26989. } else if(argv[1].type == tp_vec3) {
  26990. c11_vec3 rhs = py_tovec3(&argv[1]);
  26991. c11_vec3 res;
  26992. res.x = lhs->_11 * rhs.x + lhs->_12 * rhs.y + lhs->_13 * rhs.z;
  26993. res.y = lhs->_21 * rhs.x + lhs->_22 * rhs.y + lhs->_23 * rhs.z;
  26994. res.z = lhs->_31 * rhs.x + lhs->_32 * rhs.y + lhs->_33 * rhs.z;
  26995. py_newvec3(py_retval(), res);
  26996. } else {
  26997. py_newnotimplemented(py_retval());
  26998. }
  26999. return true;
  27000. }
  27001. static bool mat3x3__invert__(int argc, py_Ref argv) {
  27002. PY_CHECK_ARGC(1);
  27003. c11_mat3x3* ud = py_tomat3x3(argv);
  27004. c11_mat3x3* out = py_newmat3x3(py_retval());
  27005. if(inverse(ud, out)) return true;
  27006. return ZeroDivisionError("matrix is not invertible");
  27007. }
  27008. static bool mat3x3_matmul(int argc, py_Ref argv) {
  27009. PY_CHECK_ARGC(3);
  27010. PY_CHECK_ARG_TYPE(0, tp_mat3x3);
  27011. PY_CHECK_ARG_TYPE(1, tp_mat3x3);
  27012. PY_CHECK_ARG_TYPE(2, tp_mat3x3);
  27013. c11_mat3x3* lhs = py_tomat3x3(&argv[0]);
  27014. c11_mat3x3* rhs = py_tomat3x3(&argv[1]);
  27015. c11_mat3x3* out = py_tomat3x3(&argv[2]);
  27016. matmul(lhs, rhs, out);
  27017. py_newnone(py_retval());
  27018. return true;
  27019. }
  27020. static bool mat3x3_determinant(int argc, py_Ref argv) {
  27021. PY_CHECK_ARGC(1);
  27022. c11_mat3x3* ud = py_tomat3x3(argv);
  27023. py_newfloat(py_retval(), determinant(ud));
  27024. return true;
  27025. }
  27026. static bool mat3x3_copy(int argc, py_Ref argv) {
  27027. PY_CHECK_ARGC(1);
  27028. c11_mat3x3* ud = py_tomat3x3(argv);
  27029. c11_mat3x3* out = py_newmat3x3(py_retval());
  27030. *out = *ud;
  27031. return true;
  27032. }
  27033. static bool mat3x3_inverse(int argc, py_Ref argv) {
  27034. PY_CHECK_ARGC(1);
  27035. c11_mat3x3* ud = py_tomat3x3(argv);
  27036. c11_mat3x3* out = py_newmat3x3(py_retval());
  27037. if(inverse(ud, out)) return true;
  27038. return ZeroDivisionError("matrix is not invertible");
  27039. }
  27040. static bool mat3x3_copy_(int argc, py_Ref argv) {
  27041. PY_CHECK_ARGC(2);
  27042. PY_CHECK_ARG_TYPE(1, tp_mat3x3);
  27043. c11_mat3x3* self = py_tomat3x3(argv);
  27044. c11_mat3x3* other = py_tomat3x3(&argv[1]);
  27045. *self = *other;
  27046. py_newnone(py_retval());
  27047. return true;
  27048. }
  27049. static bool mat3x3_inverse_(int argc, py_Ref argv) {
  27050. PY_CHECK_ARGC(1);
  27051. c11_mat3x3* ud = py_tomat3x3(argv);
  27052. c11_mat3x3 res;
  27053. if(inverse(ud, &res)) {
  27054. *ud = res;
  27055. py_newnone(py_retval());
  27056. return true;
  27057. }
  27058. return ZeroDivisionError("matrix is not invertible");
  27059. }
  27060. static bool mat3x3_zeros_STATIC(int argc, py_Ref argv) {
  27061. PY_CHECK_ARGC(0);
  27062. c11_mat3x3* out = py_newmat3x3(py_retval());
  27063. memset(out, 0, sizeof(c11_mat3x3));
  27064. return true;
  27065. }
  27066. static bool mat3x3_identity_STATIC(int argc, py_Ref argv) {
  27067. PY_CHECK_ARGC(0);
  27068. c11_mat3x3* out = py_newmat3x3(py_retval());
  27069. // clang-format off
  27070. *out = (c11_mat3x3){
  27071. ._11 = 1, ._12 = 0, ._13 = 0,
  27072. ._21 = 0, ._22 = 1, ._23 = 0,
  27073. ._31 = 0, ._32 = 0, ._33 = 1,
  27074. };
  27075. // clang-format on
  27076. return true;
  27077. }
  27078. static bool mat3x3_trs_STATIC(int argc, py_Ref argv) {
  27079. PY_CHECK_ARGC(3);
  27080. py_f64 r;
  27081. if(!py_checktype(&argv[0], tp_vec2)) return false;
  27082. if(!py_castfloat(&argv[1], &r)) return false;
  27083. if(!py_checktype(&argv[2], tp_vec2)) return false;
  27084. c11_vec2 t = py_tovec2(&argv[0]);
  27085. c11_vec2 s = py_tovec2(&argv[2]);
  27086. c11_mat3x3* out = py_newmat3x3(py_retval());
  27087. trs(t, r, s, out);
  27088. return true;
  27089. }
  27090. static bool mat3x3_copy_trs_(int argc, py_Ref argv) {
  27091. PY_CHECK_ARGC(4);
  27092. c11_mat3x3* ud = py_tomat3x3(&argv[0]);
  27093. py_f64 r;
  27094. if(!py_checktype(&argv[1], tp_vec2)) return false;
  27095. if(!py_castfloat(&argv[2], &r)) return false;
  27096. if(!py_checktype(&argv[3], tp_vec2)) return false;
  27097. c11_vec2 t = py_tovec2(&argv[1]);
  27098. c11_vec2 s = py_tovec2(&argv[3]);
  27099. trs(t, r, s, ud);
  27100. py_newnone(py_retval());
  27101. return true;
  27102. }
  27103. static bool mat3x3_t(int argc, py_Ref argv) {
  27104. PY_CHECK_ARGC(1);
  27105. c11_mat3x3* ud = py_tomat3x3(argv);
  27106. c11_vec2 res;
  27107. res.x = ud->_13;
  27108. res.y = ud->_23;
  27109. py_newvec2(py_retval(), res);
  27110. return true;
  27111. }
  27112. static bool mat3x3_r(int argc, py_Ref argv) {
  27113. PY_CHECK_ARGC(1);
  27114. c11_mat3x3* ud = py_tomat3x3(argv);
  27115. float r = dmath_atan2(ud->_21, ud->_11);
  27116. py_newfloat(py_retval(), r);
  27117. return true;
  27118. }
  27119. static bool mat3x3_s(int argc, py_Ref argv) {
  27120. PY_CHECK_ARGC(1);
  27121. c11_mat3x3* ud = py_tomat3x3(argv);
  27122. c11_vec2 res;
  27123. res.x = dmath_sqrt(ud->_11 * ud->_11 + ud->_21 * ud->_21);
  27124. res.y = dmath_sqrt(ud->_12 * ud->_12 + ud->_22 * ud->_22);
  27125. py_newvec2(py_retval(), res);
  27126. return true;
  27127. }
  27128. static bool mat3x3_transform_point(int argc, py_Ref argv) {
  27129. PY_CHECK_ARGC(2);
  27130. PY_CHECK_ARG_TYPE(1, tp_vec2);
  27131. c11_mat3x3* ud = py_tomat3x3(&argv[0]);
  27132. c11_vec2 p = py_tovec2(&argv[1]);
  27133. c11_vec2 res;
  27134. res.x = ud->_11 * p.x + ud->_12 * p.y + ud->_13;
  27135. res.y = ud->_21 * p.x + ud->_22 * p.y + ud->_23;
  27136. py_newvec2(py_retval(), res);
  27137. return true;
  27138. }
  27139. static bool mat3x3_transform_vector(int argc, py_Ref argv) {
  27140. PY_CHECK_ARGC(2);
  27141. PY_CHECK_ARG_TYPE(1, tp_vec2);
  27142. c11_mat3x3* ud = py_tomat3x3(&argv[0]);
  27143. c11_vec2 p = py_tovec2(&argv[1]);
  27144. c11_vec2 res;
  27145. res.x = ud->_11 * p.x + ud->_12 * p.y;
  27146. res.y = ud->_21 * p.x + ud->_22 * p.y;
  27147. py_newvec2(py_retval(), res);
  27148. return true;
  27149. }
  27150. /* vec2i */
  27151. DEFINE_VEC_FIELD(vec2i, int, py_i64, x)
  27152. DEFINE_VEC_FIELD(vec2i, int, py_i64, y)
  27153. static bool vec2i__repr__(int argc, py_Ref argv) {
  27154. PY_CHECK_ARGC(1);
  27155. c11_vec2i data = py_tovec2i(argv);
  27156. char buf[64];
  27157. int size = snprintf(buf, 64, "vec2i(%d, %d)", data.x, data.y);
  27158. py_newstrv(py_retval(), (c11_sv){buf, size});
  27159. return true;
  27160. }
  27161. /* vec3i */
  27162. static bool vec3i__repr__(int argc, py_Ref argv) {
  27163. PY_CHECK_ARGC(1);
  27164. c11_vec3i data = py_tovec3i(argv);
  27165. char buf[64];
  27166. int size = snprintf(buf, 64, "vec3i(%d, %d, %d)", data.x, data.y, data.z);
  27167. py_newstrv(py_retval(), (c11_sv){buf, size});
  27168. return true;
  27169. }
  27170. DEFINE_VEC_FIELD(vec3i, int, py_i64, x)
  27171. DEFINE_VEC_FIELD(vec3i, int, py_i64, y)
  27172. DEFINE_VEC_FIELD(vec3i, int, py_i64, z)
  27173. /* vec4i */
  27174. static bool vec4i__repr__(int argc, py_Ref argv) {
  27175. PY_CHECK_ARGC(1);
  27176. c11_vec4i data = py_tovec4i(argv);
  27177. char buf[64];
  27178. int size = snprintf(buf, 64, "vec4i(%d, %d, %d, %d)", data.x, data.y, data.z, data.w);
  27179. py_newstrv(py_retval(), (c11_sv){buf, size});
  27180. return true;
  27181. }
  27182. DEFINE_VEC_FIELD(vec4i, int, py_i64, x)
  27183. DEFINE_VEC_FIELD(vec4i, int, py_i64, y)
  27184. DEFINE_VEC_FIELD(vec4i, int, py_i64, z)
  27185. DEFINE_VEC_FIELD(vec4i, int, py_i64, w)
  27186. /* vec3 */
  27187. static bool vec3__repr__(int argc, py_Ref argv) {
  27188. PY_CHECK_ARGC(1);
  27189. c11_vec3 data = py_tovec3(argv);
  27190. char buf[64];
  27191. int size = snprintf(buf, 64, "vec3(%.4f, %.4f, %.4f)", data.x, data.y, data.z);
  27192. py_newstrv(py_retval(), (c11_sv){buf, size});
  27193. return true;
  27194. }
  27195. DEFINE_VEC_FIELD(vec3, float, py_f64, x)
  27196. DEFINE_VEC_FIELD(vec3, float, py_f64, y)
  27197. DEFINE_VEC_FIELD(vec3, float, py_f64, z)
  27198. static bool vec3__xy(int argc, py_Ref argv) {
  27199. PY_CHECK_ARGC(1);
  27200. c11_vec3 data = py_tovec3(argv);
  27201. c11_vec2 res = {
  27202. {data.x, data.y}
  27203. };
  27204. py_newvec2(py_retval(), res);
  27205. return true;
  27206. }
  27207. static bool vec3__with_xy(int argc, py_Ref argv) {
  27208. PY_CHECK_ARGC(2);
  27209. PY_CHECK_ARG_TYPE(1, tp_vec2);
  27210. c11_vec2 xy = py_tovec2(&argv[1]);
  27211. c11_vec3 res = {
  27212. {xy.x, xy.y, py_tovec3(argv).z}
  27213. };
  27214. py_newvec3(py_retval(), res);
  27215. return true;
  27216. }
  27217. /* Color32 */
  27218. void py_newcolor32(py_OutRef out, c11_color32 color) {
  27219. out->type = tp_color32;
  27220. out->is_ptr = false;
  27221. out->_color32 = color;
  27222. }
  27223. c11_color32 py_tocolor32(py_Ref obj) {
  27224. assert(obj->type == tp_color32);
  27225. return obj->_color32;
  27226. }
  27227. static bool color32__new__(int argc, py_Ref argv) {
  27228. PY_CHECK_ARGC(5);
  27229. c11_color32 color;
  27230. for(int i = 1; i < 5; i++) {
  27231. PY_CHECK_ARG_TYPE(i, tp_int);
  27232. py_i64 val = py_toint(&argv[i]);
  27233. if(val < 0 || val > 255) return ValueError("color32 values must be between 0 and 255");
  27234. color.data[i - 1] = (unsigned char)val;
  27235. }
  27236. py_newcolor32(py_retval(), color);
  27237. return true;
  27238. }
  27239. #define DEFINE_COLOR32_FIELD(name) \
  27240. static bool color32__##name(int argc, py_Ref argv) { \
  27241. PY_CHECK_ARGC(1); \
  27242. c11_color32 color = py_tocolor32(argv); \
  27243. py_newint(py_retval(), color.name); \
  27244. return true; \
  27245. } \
  27246. static bool color32_with_##name(int argc, py_Ref argv) { \
  27247. PY_CHECK_ARGC(2); \
  27248. c11_color32 color = py_tocolor32(argv); \
  27249. PY_CHECK_ARG_TYPE(1, tp_int); \
  27250. py_i64 val = py_toint(&argv[1]); \
  27251. if(val < 0 || val > 255) { \
  27252. return ValueError("color32 values must be between 0 and 255"); \
  27253. } \
  27254. color.name = (unsigned char)val; \
  27255. py_newcolor32(py_retval(), color); \
  27256. return true; \
  27257. }
  27258. DEFINE_COLOR32_FIELD(r)
  27259. DEFINE_COLOR32_FIELD(g)
  27260. DEFINE_COLOR32_FIELD(b)
  27261. DEFINE_COLOR32_FIELD(a)
  27262. #undef DEFINE_COLOR32_FIELD
  27263. static bool color32_from_hex_STATIC(int argc, py_Ref argv) {
  27264. PY_CHECK_ARGC(1);
  27265. PY_CHECK_ARG_TYPE(0, tp_str);
  27266. c11_sv hex = py_tosv(argv);
  27267. c11_color32 color;
  27268. int res;
  27269. if(hex.size == 7) {
  27270. res = sscanf(hex.data, "#%2hhx%2hhx%2hhx", &color.r, &color.g, &color.b);
  27271. if(res != 3) return ValueError("invalid hex color format");
  27272. color.a = 255;
  27273. } else {
  27274. res = sscanf(hex.data, "#%2hhx%2hhx%2hhx%2hhx", &color.r, &color.g, &color.b, &color.a);
  27275. if(res != 4) return ValueError("invalid hex color format");
  27276. }
  27277. py_newcolor32(py_retval(), color);
  27278. return true;
  27279. }
  27280. static bool color32_from_vec3_STATIC(int argc, py_Ref argv) {
  27281. PY_CHECK_ARGC(1);
  27282. PY_CHECK_ARG_TYPE(0, tp_vec3);
  27283. c11_vec3 v = py_tovec3(argv);
  27284. c11_color32 color;
  27285. color.r = (unsigned char)(v.x * 255);
  27286. color.g = (unsigned char)(v.y * 255);
  27287. color.b = (unsigned char)(v.z * 255);
  27288. color.a = 255;
  27289. py_newcolor32(py_retval(), color);
  27290. return true;
  27291. }
  27292. static bool color32_from_vec3i_STATIC(int argc, py_Ref argv) {
  27293. PY_CHECK_ARGC(1);
  27294. PY_CHECK_ARG_TYPE(0, tp_vec3i);
  27295. c11_vec3i v = py_tovec3i(argv);
  27296. c11_color32 color;
  27297. color.r = (unsigned char)v.x;
  27298. color.g = (unsigned char)v.y;
  27299. color.b = (unsigned char)v.z;
  27300. color.a = 255;
  27301. py_newcolor32(py_retval(), color);
  27302. return true;
  27303. }
  27304. static bool color32_to_hex(int argc, py_Ref argv) {
  27305. PY_CHECK_ARGC(1);
  27306. c11_color32 color = py_tocolor32(argv);
  27307. char buf[16];
  27308. int size;
  27309. if(color.a == 255) {
  27310. size = snprintf(buf, sizeof(buf), "#%02x%02x%02x", color.r, color.g, color.b);
  27311. } else {
  27312. size = snprintf(buf, sizeof(buf), "#%02x%02x%02x%02x", color.r, color.g, color.b, color.a);
  27313. }
  27314. py_newstrv(py_retval(), (c11_sv){buf, size});
  27315. return true;
  27316. }
  27317. void c11_color32_premult(c11_color32* color) {
  27318. if(color->a == 255) return;
  27319. float alpha = color->a / 255.0f;
  27320. color->r = (unsigned char)(color->r * alpha);
  27321. color->g = (unsigned char)(color->g * alpha);
  27322. color->b = (unsigned char)(color->b * alpha);
  27323. }
  27324. static bool color32_to_vec3(int argc, py_Ref argv) {
  27325. PY_CHECK_ARGC(1);
  27326. c11_color32 color = py_tocolor32(argv);
  27327. c11_color32_premult(&color);
  27328. c11_vec3 v;
  27329. v.x = (float)color.r / 255;
  27330. v.y = (float)color.g / 255;
  27331. v.z = (float)color.b / 255;
  27332. py_newvec3(py_retval(), v);
  27333. return true;
  27334. }
  27335. static bool color32_to_vec3i(int argc, py_Ref argv) {
  27336. PY_CHECK_ARGC(1);
  27337. c11_color32 color = py_tocolor32(argv);
  27338. c11_color32_premult(&color);
  27339. c11_vec3i v;
  27340. v.x = (int)color.r;
  27341. v.y = (int)color.g;
  27342. v.z = (int)color.b;
  27343. py_newvec3i(py_retval(), v);
  27344. return true;
  27345. }
  27346. static bool color32_to_rgb565(int argc, py_Ref argv) {
  27347. PY_CHECK_ARGC(1);
  27348. c11_color32 color = py_tocolor32(argv);
  27349. c11_color32_premult(&color);
  27350. uint16_t r = (color.r >> 3) & 0x1F;
  27351. uint16_t g = (color.g >> 2) & 0x3F;
  27352. uint16_t b = (color.b >> 3) & 0x1F;
  27353. uint16_t rgb565 = (r << 11) | (g << 5) | b;
  27354. py_newint(py_retval(), rgb565);
  27355. return true;
  27356. }
  27357. static bool color32__eq__(int argc, py_Ref argv) {
  27358. PY_CHECK_ARGC(2);
  27359. if(argv[1].type != tp_color32) {
  27360. py_newnotimplemented(py_retval());
  27361. return true;
  27362. }
  27363. c11_color32 lhs = py_tocolor32(&argv[0]);
  27364. c11_color32 rhs = py_tocolor32(&argv[1]);
  27365. bool eq = memcmp(&lhs, &rhs, sizeof(c11_color32)) == 0;
  27366. py_newbool(py_retval(), eq);
  27367. return true;
  27368. }
  27369. static bool color32__ne__(int argc, py_Ref argv) {
  27370. PY_CHECK_ARGC(2);
  27371. if(argv[1].type != tp_color32) {
  27372. py_newnotimplemented(py_retval());
  27373. return true;
  27374. }
  27375. c11_color32 lhs = py_tocolor32(&argv[0]);
  27376. c11_color32 rhs = py_tocolor32(&argv[1]);
  27377. bool eq = memcmp(&lhs, &rhs, sizeof(c11_color32)) != 0;
  27378. py_newbool(py_retval(), eq);
  27379. return true;
  27380. }
  27381. static bool color32__repr__(int argc, py_Ref argv) {
  27382. PY_CHECK_ARGC(1);
  27383. c11_color32 color = py_tocolor32(argv);
  27384. char buf[64];
  27385. int size = snprintf(buf, 64, "color32(%d, %d, %d, %d)", color.r, color.g, color.b, color.a);
  27386. py_newstrv(py_retval(), (c11_sv){buf, size});
  27387. return true;
  27388. }
  27389. static bool color32__hash__(int argc, py_Ref argv) {
  27390. PY_CHECK_ARGC(1);
  27391. c11_color32 color = py_tocolor32(argv);
  27392. uint32_t* color_int = (uint32_t*)&color;
  27393. py_newint(py_retval(), *color_int);
  27394. return true;
  27395. }
  27396. static bool color32_ansi_fg(int argc, py_Ref argv) {
  27397. PY_CHECK_ARGC(2);
  27398. c11_color32 color = py_tocolor32(argv);
  27399. c11_color32_premult(&color);
  27400. PY_CHECK_ARG_TYPE(1, tp_str);
  27401. c11_sv text = py_tosv(&argv[1]);
  27402. c11_sbuf buf;
  27403. c11_sbuf__ctor(&buf);
  27404. pk_sprintf(&buf, "\x1b[38;2;%d;%d;%dm%v\x1b[0m", color.r, color.g, color.b, text);
  27405. c11_sbuf__py_submit(&buf, py_retval());
  27406. return true;
  27407. }
  27408. static bool color32_ansi_bg(int argc, py_Ref argv) {
  27409. PY_CHECK_ARGC(2);
  27410. c11_color32 color = py_tocolor32(argv);
  27411. c11_color32_premult(&color);
  27412. PY_CHECK_ARG_TYPE(1, tp_str);
  27413. c11_sv text = py_tosv(&argv[1]);
  27414. c11_sbuf buf;
  27415. c11_sbuf__ctor(&buf);
  27416. pk_sprintf(&buf, "\x1b[48;2;%d;%d;%dm%v\x1b[0m", color.r, color.g, color.b, text);
  27417. c11_sbuf__py_submit(&buf, py_retval());
  27418. return true;
  27419. }
  27420. static bool vmath_rgb(int argc, py_Ref argv) {
  27421. PY_CHECK_ARGC(3);
  27422. PY_CHECK_ARG_TYPE(0, tp_int);
  27423. PY_CHECK_ARG_TYPE(1, tp_int);
  27424. PY_CHECK_ARG_TYPE(2, tp_int);
  27425. c11_color32 color;
  27426. color.r = (unsigned char)py_toint(&argv[0]);
  27427. color.g = (unsigned char)py_toint(&argv[1]);
  27428. color.b = (unsigned char)py_toint(&argv[2]);
  27429. color.a = 255;
  27430. py_newcolor32(py_retval(), color);
  27431. return true;
  27432. }
  27433. static bool vmath_rgba(int argc, py_Ref argv) {
  27434. PY_CHECK_ARGC(4);
  27435. PY_CHECK_ARG_TYPE(0, tp_int);
  27436. PY_CHECK_ARG_TYPE(1, tp_int);
  27437. PY_CHECK_ARG_TYPE(2, tp_int);
  27438. PY_CHECK_ARG_TYPE(3, tp_float);
  27439. c11_color32 color;
  27440. color.r = (unsigned char)py_toint(&argv[0]);
  27441. color.g = (unsigned char)py_toint(&argv[1]);
  27442. color.b = (unsigned char)py_toint(&argv[2]);
  27443. color.a = (unsigned char)(py_tofloat(&argv[3]) * 255);
  27444. py_newcolor32(py_retval(), color);
  27445. return true;
  27446. }
  27447. static bool color32_alpha_blend_STATIC(int argc, py_Ref argv) {
  27448. PY_CHECK_ARGC(2);
  27449. if(!py_checktype(&argv[0], tp_color32)) return false;
  27450. if(py_isnone(&argv[1])) {
  27451. py_assign(py_retval(), &argv[0]);
  27452. return true;
  27453. }
  27454. if(!py_checktype(&argv[1], tp_color32)) return false;
  27455. c11_color32 src = py_tocolor32(&argv[0]);
  27456. c11_color32 dst = py_tocolor32(&argv[1]);
  27457. float alpha = src.a / 255.0f;
  27458. c11_color32 res;
  27459. res.r = (unsigned char)(src.r * alpha + dst.r * (1 - alpha));
  27460. res.g = (unsigned char)(src.g * alpha + dst.g * (1 - alpha));
  27461. res.b = (unsigned char)(src.b * alpha + dst.b * (1 - alpha));
  27462. res.a = (unsigned char)(src.a + dst.a * (1 - alpha));
  27463. py_newcolor32(py_retval(), res);
  27464. return true;
  27465. }
  27466. void pk__add_module_vmath() {
  27467. py_Ref mod = py_newmodule("vmath");
  27468. py_Type vec2 = pk_newtype("vec2", tp_object, mod, NULL, false, true);
  27469. py_Type vec3 = pk_newtype("vec3", tp_object, mod, NULL, false, true);
  27470. py_Type vec2i = pk_newtype("vec2i", tp_object, mod, NULL, false, true);
  27471. py_Type vec3i = pk_newtype("vec3i", tp_object, mod, NULL, false, true);
  27472. py_Type vec4i = pk_newtype("vec4i", tp_object, mod, NULL, false, true);
  27473. py_Type mat3x3 = pk_newtype("mat3x3", tp_object, mod, NULL, false, true);
  27474. py_Type color32 = pk_newtype("color32", tp_object, mod, NULL, false, true);
  27475. py_setdict(mod, py_name("vec2"), py_tpobject(vec2));
  27476. py_setdict(mod, py_name("vec3"), py_tpobject(vec3));
  27477. py_setdict(mod, py_name("vec2i"), py_tpobject(vec2i));
  27478. py_setdict(mod, py_name("vec3i"), py_tpobject(vec3i));
  27479. py_setdict(mod, py_name("vec4i"), py_tpobject(vec4i));
  27480. py_setdict(mod, py_name("mat3x3"), py_tpobject(mat3x3));
  27481. py_setdict(mod, py_name("color32"), py_tpobject(color32));
  27482. c11__rtassert(vec2 == tp_vec2);
  27483. c11__rtassert(vec3 == tp_vec3);
  27484. c11__rtassert(vec2i == tp_vec2i);
  27485. c11__rtassert(vec3i == tp_vec3i);
  27486. c11__rtassert(vec4i == tp_vec4i);
  27487. c11__rtassert(mat3x3 == tp_mat3x3);
  27488. c11__rtassert(color32 == tp_color32);
  27489. /* vec2 */
  27490. py_bindmagic(vec2, __new__, vec2__new__);
  27491. py_bindmagic(vec2, __add__, vec2__add__);
  27492. py_bindmagic(vec2, __sub__, vec2__sub__);
  27493. py_bindmagic(vec2, __mul__, vec2__mul__);
  27494. py_bindmagic(vec2, __truediv__, vec2__truediv__);
  27495. py_bindmagic(vec2, __repr__, vec2__repr__);
  27496. py_bindmagic(vec2, __eq__, vec2__eq__);
  27497. py_bindmagic(vec2, __ne__, vec2__ne__);
  27498. py_bindmethod(vec2, "dot", vec2_dot);
  27499. py_bindmethod(vec2, "length", vec2_length);
  27500. py_bindmethod(vec2, "length_squared", vec2_length_squared);
  27501. py_bindmethod(vec2, "normalize", vec2_normalize);
  27502. py_bindmethod(vec2, "rotate", vec2_rotate);
  27503. // clang-format off
  27504. py_newvec2(_const(vec2, "ZERO"), (c11_vec2){{0, 0}});
  27505. py_newvec2(_const(vec2, "ONE"), (c11_vec2){{1, 1}});
  27506. py_newvec2(_const(vec2, "LEFT"), (c11_vec2){{-1, 0}});
  27507. py_newvec2(_const(vec2, "RIGHT"), (c11_vec2){{1, 0}});
  27508. py_newvec2(_const(vec2, "UP"), (c11_vec2){{0, -1}});
  27509. py_newvec2(_const(vec2, "DOWN"), (c11_vec2){{0, 1}});
  27510. // clang-format on
  27511. py_bindstaticmethod(vec2, "angle", vec2_angle_STATIC);
  27512. py_bindstaticmethod(vec2, "smooth_damp", vec2_smoothdamp_STATIC);
  27513. py_bindproperty(vec2, "x", vec2__x, NULL);
  27514. py_bindproperty(vec2, "y", vec2__y, NULL);
  27515. py_bindmethod(vec2, "with_x", vec2__with_x);
  27516. py_bindmethod(vec2, "with_y", vec2__with_y);
  27517. py_bindmethod(vec2, "with_z", vec2__with_z);
  27518. /* mat3x3 */
  27519. py_bindmagic(mat3x3, __new__, mat3x3__new__);
  27520. py_bindmagic(mat3x3, __repr__, mat3x3__repr__);
  27521. py_bindmagic(mat3x3, __getitem__, mat3x3__getitem__);
  27522. py_bindmagic(mat3x3, __setitem__, mat3x3__setitem__);
  27523. py_bindmagic(mat3x3, __matmul__, mat3x3__matmul__);
  27524. py_bindmagic(mat3x3, __invert__, mat3x3__invert__);
  27525. py_bindmagic(mat3x3, __eq__, mat3x3__eq__);
  27526. py_bindmagic(mat3x3, __ne__, mat3x3__ne__);
  27527. py_bindmethod(mat3x3, "matmul", mat3x3_matmul);
  27528. py_bindmethod(mat3x3, "determinant", mat3x3_determinant);
  27529. py_bindmethod(mat3x3, "copy", mat3x3_copy);
  27530. py_bindmethod(mat3x3, "inverse", mat3x3_inverse);
  27531. py_bindmethod(mat3x3, "copy_", mat3x3_copy_);
  27532. py_bindmethod(mat3x3, "inverse_", mat3x3_inverse_);
  27533. py_bindstaticmethod(mat3x3, "zeros", mat3x3_zeros_STATIC);
  27534. py_bindstaticmethod(mat3x3, "identity", mat3x3_identity_STATIC);
  27535. py_bindstaticmethod(mat3x3, "trs", mat3x3_trs_STATIC);
  27536. py_bindmethod(mat3x3, "copy_trs_", mat3x3_copy_trs_);
  27537. py_bindmethod(mat3x3, "t", mat3x3_t);
  27538. py_bindmethod(mat3x3, "r", mat3x3_r);
  27539. py_bindmethod(mat3x3, "s", mat3x3_s);
  27540. py_bindmethod(mat3x3, "transform_point", mat3x3_transform_point);
  27541. py_bindmethod(mat3x3, "transform_vector", mat3x3_transform_vector);
  27542. /* vec2i */
  27543. py_bindmagic(vec2i, __new__, vec2i__new__);
  27544. py_bindmagic(vec2i, __repr__, vec2i__repr__);
  27545. py_bindmagic(vec2i, __add__, vec2i__add__);
  27546. py_bindmagic(vec2i, __sub__, vec2i__sub__);
  27547. py_bindmagic(vec2i, __mul__, vec2i__mul__);
  27548. py_bindmagic(vec2i, __floordiv__, vec2i__floordiv__);
  27549. py_bindmagic(vec2i, __mod__, vec2i__mod__);
  27550. py_bindmagic(vec2i, __eq__, vec2i__eq__);
  27551. py_bindmagic(vec2i, __ne__, vec2i__ne__);
  27552. py_bindmagic(vec2i, __hash__, vec2i__hash__);
  27553. py_bindproperty(vec2i, "x", vec2i__x, NULL);
  27554. py_bindproperty(vec2i, "y", vec2i__y, NULL);
  27555. py_bindmethod(vec2i, "with_x", vec2i__with_x);
  27556. py_bindmethod(vec2i, "with_y", vec2i__with_y);
  27557. py_bindmethod(vec2i, "dot", vec2i_dot);
  27558. py_bindmethod(vec2i, "l1_norm", vec2i_l1_norm);
  27559. py_bindmethod(vec2i, "l2_norm", vec2i_l2_norm);
  27560. py_bindmethod(vec2i, "max_norm", vec2i_max_norm);
  27561. py_bindmethod(vec2i, "length", vec2i_l2_norm);
  27562. // clang-format off
  27563. py_newvec2i(_const(vec2i, "ZERO"), (c11_vec2i){{0, 0}});
  27564. py_newvec2i(_const(vec2i, "ONE"), (c11_vec2i){{1, 1}});
  27565. py_newvec2i(_const(vec2i, "LEFT"), (c11_vec2i){{-1, 0}});
  27566. py_newvec2i(_const(vec2i, "RIGHT"), (c11_vec2i){{1, 0}});
  27567. py_newvec2i(_const(vec2i, "UP"), (c11_vec2i){{0, -1}});
  27568. py_newvec2i(_const(vec2i, "DOWN"), (c11_vec2i){{0, 1}});
  27569. // clang-format on
  27570. /* vec3i */
  27571. py_bindmagic(vec3i, __new__, vec3i__new__);
  27572. py_bindmagic(vec3i, __repr__, vec3i__repr__);
  27573. py_bindmagic(vec3i, __add__, vec3i__add__);
  27574. py_bindmagic(vec3i, __sub__, vec3i__sub__);
  27575. py_bindmagic(vec3i, __mul__, vec3i__mul__);
  27576. py_bindmagic(vec3i, __floordiv__, vec3i__floordiv__);
  27577. py_bindmagic(vec3i, __mod__, vec3i__mod__);
  27578. py_bindmagic(vec3i, __eq__, vec3i__eq__);
  27579. py_bindmagic(vec3i, __ne__, vec3i__ne__);
  27580. py_bindmagic(vec3i, __hash__, vec3i__hash__);
  27581. py_bindproperty(vec3i, "x", vec3i__x, NULL);
  27582. py_bindproperty(vec3i, "y", vec3i__y, NULL);
  27583. py_bindproperty(vec3i, "z", vec3i__z, NULL);
  27584. py_bindmethod(vec3i, "with_x", vec3i__with_x);
  27585. py_bindmethod(vec3i, "with_y", vec3i__with_y);
  27586. py_bindmethod(vec3i, "with_z", vec3i__with_z);
  27587. py_bindmethod(vec3i, "dot", vec3i_dot);
  27588. py_newvec3i(_const(vec3i, "ZERO"),
  27589. (c11_vec3i){
  27590. {0, 0, 0}
  27591. });
  27592. py_newvec3i(_const(vec3i, "ONE"),
  27593. (c11_vec3i){
  27594. {1, 1, 1}
  27595. });
  27596. /* vec4i */
  27597. py_bindmagic(vec4i, __new__, vec4i__new__);
  27598. py_bindmagic(vec4i, __repr__, vec4i__repr__);
  27599. py_bindmagic(vec4i, __add__, vec4i__add__);
  27600. py_bindmagic(vec4i, __sub__, vec4i__sub__);
  27601. py_bindmagic(vec4i, __mul__, vec4i__mul__);
  27602. py_bindmagic(vec4i, __floordiv__, vec4i__floordiv__);
  27603. py_bindmagic(vec4i, __mod__, vec4i__mod__);
  27604. py_bindmagic(vec4i, __eq__, vec4i__eq__);
  27605. py_bindmagic(vec4i, __ne__, vec4i__ne__);
  27606. py_bindmagic(vec4i, __hash__, vec4i__hash__);
  27607. py_bindproperty(vec4i, "x", vec4i__x, NULL);
  27608. py_bindproperty(vec4i, "y", vec4i__y, NULL);
  27609. py_bindproperty(vec4i, "z", vec4i__z, NULL);
  27610. py_bindproperty(vec4i, "w", vec4i__w, NULL);
  27611. py_bindmethod(vec4i, "with_x", vec4i__with_x);
  27612. py_bindmethod(vec4i, "with_y", vec4i__with_y);
  27613. py_bindmethod(vec4i, "with_z", vec4i__with_z);
  27614. py_bindmethod(vec4i, "with_w", vec4i__with_w);
  27615. py_bindmethod(vec4i, "dot", vec4i_dot);
  27616. py_newvec4i(_const(vec4i, "ZERO"),
  27617. (c11_vec4i){
  27618. {0, 0, 0, 0}
  27619. });
  27620. py_newvec4i(_const(vec4i, "ONE"),
  27621. (c11_vec4i){
  27622. {1, 1, 1, 1}
  27623. });
  27624. /* vec3 */
  27625. py_bindmagic(vec3, __new__, vec3__new__);
  27626. py_bindmagic(vec3, __add__, vec3__add__);
  27627. py_bindmagic(vec3, __sub__, vec3__sub__);
  27628. py_bindmagic(vec3, __mul__, vec3__mul__);
  27629. py_bindmagic(vec3, __truediv__, vec3__truediv__);
  27630. py_bindmagic(vec3, __repr__, vec3__repr__);
  27631. py_bindmagic(vec3, __eq__, vec3__eq__);
  27632. py_bindmagic(vec3, __ne__, vec3__ne__);
  27633. py_bindmethod(vec3, "dot", vec3_dot);
  27634. py_bindmethod(vec3, "length", vec3_length);
  27635. py_bindmethod(vec3, "length_squared", vec3_length_squared);
  27636. py_bindmethod(vec3, "normalize", vec3_normalize);
  27637. py_bindproperty(vec3, "x", vec3__x, NULL);
  27638. py_bindproperty(vec3, "y", vec3__y, NULL);
  27639. py_bindproperty(vec3, "z", vec3__z, NULL);
  27640. py_bindproperty(vec3, "xy", vec3__xy, NULL);
  27641. py_bindmethod(vec3, "with_x", vec3__with_x);
  27642. py_bindmethod(vec3, "with_y", vec3__with_y);
  27643. py_bindmethod(vec3, "with_z", vec3__with_z);
  27644. py_bindmethod(vec3, "with_xy", vec3__with_xy);
  27645. py_newvec3(_const(vec3, "ZERO"),
  27646. (c11_vec3){
  27647. {0, 0, 0}
  27648. });
  27649. py_newvec3(_const(vec3, "ONE"),
  27650. (c11_vec3){
  27651. {1, 1, 1}
  27652. });
  27653. /* color32 */
  27654. py_bindmagic(color32, __new__, color32__new__);
  27655. py_bindmagic(color32, __repr__, color32__repr__);
  27656. py_bindmagic(color32, __eq__, color32__eq__);
  27657. py_bindmagic(color32, __ne__, color32__ne__);
  27658. py_bindmagic(color32, __hash__, color32__hash__);
  27659. py_bindproperty(color32, "r", color32__r, NULL);
  27660. py_bindproperty(color32, "g", color32__g, NULL);
  27661. py_bindproperty(color32, "b", color32__b, NULL);
  27662. py_bindproperty(color32, "a", color32__a, NULL);
  27663. py_bindmethod(color32, "with_r", color32_with_r);
  27664. py_bindmethod(color32, "with_g", color32_with_g);
  27665. py_bindmethod(color32, "with_b", color32_with_b);
  27666. py_bindmethod(color32, "with_a", color32_with_a);
  27667. py_bindstaticmethod(color32, "from_hex", color32_from_hex_STATIC);
  27668. py_bindstaticmethod(color32, "from_vec3", color32_from_vec3_STATIC);
  27669. py_bindstaticmethod(color32, "from_vec3i", color32_from_vec3i_STATIC);
  27670. py_bindmethod(color32, "to_hex", color32_to_hex);
  27671. py_bindmethod(color32, "to_vec3", color32_to_vec3);
  27672. py_bindmethod(color32, "to_vec3i", color32_to_vec3i);
  27673. py_bindmethod(color32, "to_rgb565", color32_to_rgb565);
  27674. py_bindmethod(color32, "ansi_fg", color32_ansi_fg);
  27675. py_bindmethod(color32, "ansi_bg", color32_ansi_bg);
  27676. py_bindfunc(mod, "rgb", vmath_rgb);
  27677. py_bindfunc(mod, "rgba", vmath_rgba);
  27678. py_bindstaticmethod(color32, "alpha_blend", color32_alpha_blend_STATIC);
  27679. }
  27680. #undef DEFINE_VEC_FIELD
  27681. #undef DEFINE_BOOL_NE
  27682. #undef DEF_VECTOR_ELEMENT_WISE
  27683. #undef DEF_VECTOR_OPS
  27684. #undef DEF_VECTOR_INT_OPS
  27685. // src/objects\bintree.c
  27686. void BinTree__ctor(BinTree* self, void* key, py_Ref value, const BinTreeConfig* config) {
  27687. self->key = key;
  27688. self->value = *value;
  27689. self->config = config;
  27690. self->left = NULL;
  27691. self->right = NULL;
  27692. }
  27693. void BinTree__dtor(BinTree* self) {
  27694. if(self->config->need_free_key) PK_FREE(self->key);
  27695. if(self->left) {
  27696. BinTree__dtor(self->left);
  27697. PK_FREE(self->left);
  27698. }
  27699. if(self->right) {
  27700. BinTree__dtor(self->right);
  27701. PK_FREE(self->right);
  27702. }
  27703. }
  27704. void BinTree__set(BinTree* self, void* key, py_Ref value) {
  27705. int cmp = self->config->f_cmp(key, self->key);
  27706. if(cmp < 0) {
  27707. if(self->left) {
  27708. BinTree__set(self->left, key, value);
  27709. } else {
  27710. self->left = PK_MALLOC(sizeof(BinTree));
  27711. BinTree__ctor(self->left, key, value, self->config);
  27712. }
  27713. } else if(cmp > 0) {
  27714. if(self->right) {
  27715. BinTree__set(self->right, key, value);
  27716. } else {
  27717. self->right = PK_MALLOC(sizeof(BinTree));
  27718. BinTree__ctor(self->right, key, value, self->config);
  27719. }
  27720. } else {
  27721. self->value = *value;
  27722. }
  27723. }
  27724. py_Ref BinTree__try_get(BinTree* self, void* key) {
  27725. int cmp = self->config->f_cmp(key, self->key);
  27726. if(cmp < 0) {
  27727. if(self->left) {
  27728. return BinTree__try_get(self->left, key);
  27729. } else {
  27730. return NULL;
  27731. }
  27732. } else if(cmp > 0) {
  27733. if(self->right) {
  27734. return BinTree__try_get(self->right, key);
  27735. } else {
  27736. return NULL;
  27737. }
  27738. } else {
  27739. return &self->value;
  27740. }
  27741. }
  27742. bool BinTree__contains(BinTree* self, void* key) { return BinTree__try_get(self, key) != NULL; }
  27743. void BinTree__apply_mark(BinTree* self, c11_vector* p_stack) {
  27744. pk__mark_value(&self->value);
  27745. if(self->left) BinTree__apply_mark(self->left, p_stack);
  27746. if(self->right) BinTree__apply_mark(self->right, p_stack);
  27747. }
  27748. // src/objects\codeobject.c
  27749. #include <stdint.h>
  27750. #include <assert.h>
  27751. void Bytecode__set_signed_arg(Bytecode* self, int arg) {
  27752. self->arg = (int16_t)arg;
  27753. if((int16_t)self->arg != arg) {
  27754. c11__abort("Bytecode__set_signed_arg(): %d is not representable in int16_t", arg);
  27755. }
  27756. }
  27757. bool Bytecode__is_forward_jump(const Bytecode* self) {
  27758. Opcode op = self->op;
  27759. return (op >= OP_JUMP_FORWARD && op <= OP_LOOP_BREAK) ||
  27760. (op == OP_FOR_ITER || op == OP_FOR_ITER_YIELD_VALUE);
  27761. }
  27762. void FuncDecl__dtor(void* p) {
  27763. FuncDecl* self = p;
  27764. CodeObject__dtor(&self->code);
  27765. c11_vector__dtor(&self->args);
  27766. c11_vector__dtor(&self->kwargs);
  27767. c11_smallmap_n2d__dtor(&self->kw_to_index);
  27768. if(self->docstring) py_free(self->docstring);
  27769. }
  27770. FuncDecl_ FuncDecl__rcnew(SourceData_ src, c11_sv name) {
  27771. FuncDecl* self = PK_MALLOC(sizeof(FuncDecl));
  27772. self->rc.count = 1;
  27773. self->rc.dtor = FuncDecl__dtor;
  27774. CodeObject__ctor(&self->code, src, name);
  27775. c11_vector__ctor(&self->args, sizeof(int32_t));
  27776. c11_vector__ctor(&self->kwargs, sizeof(FuncDeclKwArg));
  27777. self->starred_arg = -1;
  27778. self->starred_kwarg = -1;
  27779. self->nested = false;
  27780. self->docstring = NULL;
  27781. self->type = FuncType_UNSET;
  27782. c11_smallmap_n2d__ctor(&self->kw_to_index);
  27783. return self;
  27784. }
  27785. bool FuncDecl__is_duplicated_arg(const FuncDecl* decl, py_Name name) {
  27786. py_Name tmp_name;
  27787. c11__foreach(int, &decl->args, j) {
  27788. tmp_name = c11__getitem(py_Name, &decl->code.varnames, *j);
  27789. if(tmp_name == name) return true;
  27790. }
  27791. c11__foreach(FuncDeclKwArg, &decl->kwargs, kv) {
  27792. tmp_name = c11__getitem(py_Name, &decl->code.varnames, kv->index);
  27793. if(tmp_name == name) return true;
  27794. }
  27795. if(decl->starred_arg != -1) {
  27796. tmp_name = c11__getitem(py_Name, &decl->code.varnames, decl->starred_arg);
  27797. if(tmp_name == name) return true;
  27798. }
  27799. if(decl->starred_kwarg != -1) {
  27800. tmp_name = c11__getitem(py_Name, &decl->code.varnames, decl->starred_kwarg);
  27801. if(tmp_name == name) return true;
  27802. }
  27803. return false;
  27804. }
  27805. void FuncDecl__add_arg(FuncDecl* self, py_Name name) {
  27806. int32_t index = CodeObject__add_varname(&self->code, name);
  27807. c11_vector__push(int32_t, &self->args, index);
  27808. }
  27809. void FuncDecl__add_kwarg(FuncDecl* self, py_Name name, const py_TValue* value) {
  27810. int index = CodeObject__add_varname(&self->code, name);
  27811. c11_smallmap_n2d__set(&self->kw_to_index, name, index);
  27812. FuncDeclKwArg* item = c11_vector__emplace(&self->kwargs);
  27813. item->index = index;
  27814. item->key = name;
  27815. item->value = *value;
  27816. }
  27817. void FuncDecl__add_starred_arg(FuncDecl* self, py_Name name) {
  27818. int index = CodeObject__add_varname(&self->code, name);
  27819. self->starred_arg = index;
  27820. }
  27821. void FuncDecl__add_starred_kwarg(FuncDecl* self, py_Name name) {
  27822. int index = CodeObject__add_varname(&self->code, name);
  27823. self->starred_kwarg = index;
  27824. }
  27825. void CodeObject__ctor(CodeObject* self, SourceData_ src, c11_sv name) {
  27826. self->src = src;
  27827. PK_INCREF(src);
  27828. self->name = c11_string__new2(name.data, name.size);
  27829. c11_vector__ctor(&self->codes, sizeof(Bytecode));
  27830. c11_vector__ctor(&self->codes_ex, sizeof(BytecodeEx));
  27831. c11_vector__ctor(&self->consts, sizeof(py_TValue));
  27832. c11_vector__ctor(&self->varnames, sizeof(py_Name));
  27833. c11_vector__ctor(&self->names, sizeof(py_Name));
  27834. self->nlocals = 0;
  27835. c11_smallmap_n2d__ctor(&self->varnames_inv);
  27836. c11_smallmap_n2d__ctor(&self->names_inv);
  27837. c11_vector__ctor(&self->blocks, sizeof(CodeBlock));
  27838. c11_vector__ctor(&self->func_decls, sizeof(FuncDecl_));
  27839. self->start_line = -1;
  27840. self->end_line = -1;
  27841. CodeBlock root_block = {CodeBlockType_NO_BLOCK, -1, 0, -1, -1};
  27842. c11_vector__push(CodeBlock, &self->blocks, root_block);
  27843. }
  27844. void CodeObject__dtor(CodeObject* self) {
  27845. PK_DECREF(self->src);
  27846. c11_string__delete(self->name);
  27847. c11_vector__dtor(&self->codes);
  27848. c11_vector__dtor(&self->codes_ex);
  27849. c11_vector__dtor(&self->consts);
  27850. c11_vector__dtor(&self->varnames);
  27851. c11_vector__dtor(&self->names);
  27852. c11_smallmap_n2d__dtor(&self->varnames_inv);
  27853. c11_smallmap_n2d__dtor(&self->names_inv);
  27854. c11_vector__dtor(&self->blocks);
  27855. for(int i = 0; i < self->func_decls.length; i++) {
  27856. FuncDecl_ decl = c11__getitem(FuncDecl_, &self->func_decls, i);
  27857. PK_DECREF(decl);
  27858. }
  27859. c11_vector__dtor(&self->func_decls);
  27860. }
  27861. void Function__ctor(Function* self, FuncDecl_ decl, py_GlobalRef module, py_Ref globals) {
  27862. PK_INCREF(decl);
  27863. self->decl = decl;
  27864. self->module = module;
  27865. self->globals = globals != NULL ? *globals : *py_NIL();
  27866. self->closure = NULL;
  27867. self->clazz = NULL;
  27868. self->cfunc = NULL;
  27869. }
  27870. int CodeObject__add_varname(CodeObject* self, py_Name name) {
  27871. int index = c11_smallmap_n2d__get(&self->varnames_inv, name, -1);
  27872. if(index >= 0) return index;
  27873. c11_vector__push(py_Name, &self->varnames, name);
  27874. self->nlocals++;
  27875. index = self->varnames.length - 1;
  27876. c11_smallmap_n2d__set(&self->varnames_inv, name, index);
  27877. return index;
  27878. }
  27879. int CodeObject__add_name(CodeObject* self, py_Name name) {
  27880. int index = c11_smallmap_n2d__get(&self->names_inv, name, -1);
  27881. if(index >= 0) return index;
  27882. c11_vector__push(py_Name, &self->names, name);
  27883. index = self->names.length - 1;
  27884. c11_smallmap_n2d__set(&self->names_inv, name, index);
  27885. return index;
  27886. }
  27887. void Function__dtor(Function* self) {
  27888. // printf("%s() in %s freed!\n", self->decl->code.name->data,
  27889. // self->decl->code.src->filename->data);
  27890. PK_DECREF(self->decl);
  27891. if(self->closure) NameDict__delete(self->closure);
  27892. memset(self, 0, sizeof(Function));
  27893. }
  27894. // src/objects\codeobject_ser.c
  27895. // Magic number for CodeObject serialization: "CO" = 0x434F
  27896. #define CODEOBJECT_MAGIC 0x434F
  27897. #define CODEOBJECT_VER_MAJOR 1
  27898. #define CODEOBJECT_VER_MINOR 1
  27899. #define CODEOBJECT_VER_MINOR_MIN 1
  27900. // Forward declarations
  27901. static void FuncDecl__serialize(c11_serializer* s,
  27902. const FuncDecl* decl,
  27903. const struct SourceData* parent_src);
  27904. static FuncDecl_ FuncDecl__deserialize(c11_deserializer* d, SourceData_ embedded_src);
  27905. static void CodeObject__serialize(c11_serializer* s,
  27906. const CodeObject* co,
  27907. const struct SourceData* parent_src);
  27908. static CodeObject CodeObject__deserialize(c11_deserializer* d, const char* filename, SourceData_ embedded_src);
  27909. // Serialize a py_TValue constant
  27910. static void TValue__serialize(c11_serializer* s, py_Ref val) {
  27911. c11_serializer__write_type(s, val->type);
  27912. // 1. co_consts: int | float | str
  27913. // 2. function defaults: see `read_literal()` in compiler.c
  27914. switch(val->type) {
  27915. case tp_int: c11_serializer__write_i64(s, val->_i64); break;
  27916. case tp_float: c11_serializer__write_f64(s, val->_f64); break;
  27917. case tp_str: {
  27918. c11_sv sv = py_tosv((py_Ref)val);
  27919. c11_serializer__write_i32(s, sv.size);
  27920. c11_serializer__write_bytes(s, sv.data, sv.size);
  27921. break;
  27922. }
  27923. case tp_bool: {
  27924. bool value = py_tobool(val);
  27925. c11_serializer__write_i8(s, value ? 1 : 0);
  27926. break;
  27927. }
  27928. case tp_NoneType: break;
  27929. case tp_ellipsis: break;
  27930. case tp_tuple: {
  27931. int len = py_tuple_len(val);
  27932. c11_serializer__write_i32(s, len);
  27933. for(int i = 0; i < len; i++) {
  27934. py_Ref item = py_tuple_getitem(val, i);
  27935. TValue__serialize(s, item);
  27936. }
  27937. break;
  27938. }
  27939. default: c11__abort("TValue__serialize: invalid type '%s'", py_tpname(val->type));
  27940. }
  27941. }
  27942. // Deserialize a py_TValue constant
  27943. static void TValue__deserialize(c11_deserializer* d, py_OutRef out) {
  27944. py_Type type = c11_deserializer__read_type(d);
  27945. switch(type) {
  27946. case tp_int: {
  27947. py_i64 v = c11_deserializer__read_i64(d);
  27948. py_newint(out, v);
  27949. break;
  27950. }
  27951. case tp_float: {
  27952. py_f64 v = c11_deserializer__read_f64(d);
  27953. py_newfloat(out, v);
  27954. break;
  27955. }
  27956. case tp_str: {
  27957. int size = c11_deserializer__read_i32(d);
  27958. char* dst = py_newstrn(out, size);
  27959. char* src = c11_deserializer__read_bytes(d, size);
  27960. memcpy(dst, src, size);
  27961. break;
  27962. }
  27963. case tp_bool: {
  27964. bool v = c11_deserializer__read_i8(d) != 0;
  27965. py_newbool(out, v);
  27966. break;
  27967. }
  27968. case tp_NoneType: {
  27969. py_newnone(out);
  27970. break;
  27971. }
  27972. case tp_ellipsis: {
  27973. py_newellipsis(out);
  27974. break;
  27975. }
  27976. case tp_tuple: {
  27977. int len = c11_deserializer__read_i32(d);
  27978. py_newtuple(out, len);
  27979. for(int i = 0; i < len; i++) {
  27980. py_ItemRef item = py_tuple_getitem(out, i);
  27981. TValue__deserialize(d, item);
  27982. }
  27983. break;
  27984. }
  27985. default:
  27986. c11__abort("TValue__deserialize: invalid type '%s'", py_tpname(type));
  27987. }
  27988. }
  27989. // Serialize CodeObject
  27990. static void CodeObject__serialize(c11_serializer* s,
  27991. const CodeObject* co,
  27992. const struct SourceData* parent_src) {
  27993. // SourceData
  27994. if(parent_src) {
  27995. c11__rtassert(co->src == parent_src);
  27996. }
  27997. // name
  27998. c11_serializer__write_cstr(s, co->name->data);
  27999. // codes
  28000. _Static_assert(sizeof(Bytecode) == sizeof(uint16_t) * 2, "");
  28001. c11_serializer__write_i32(s, co->codes.length);
  28002. c11_serializer__write_mark(s, '[');
  28003. c11_serializer__write_bytes(s, co->codes.data, co->codes.length * sizeof(Bytecode));
  28004. c11_serializer__write_mark(s, ']');
  28005. // codes_ex
  28006. _Static_assert(sizeof(BytecodeEx) == sizeof(int32_t) * 2, "");
  28007. c11_serializer__write_i32(s, co->codes_ex.length);
  28008. c11_serializer__write_mark(s, '[');
  28009. c11_serializer__write_bytes(s, co->codes_ex.data, co->codes_ex.length * sizeof(BytecodeEx));
  28010. c11_serializer__write_mark(s, ']');
  28011. // consts
  28012. c11_serializer__write_i32(s, co->consts.length);
  28013. c11_serializer__write_mark(s, '[');
  28014. for(int i = 0; i < co->consts.length; i++) {
  28015. py_Ref val = c11__at(py_TValue, &co->consts, i);
  28016. TValue__serialize(s, val);
  28017. }
  28018. c11_serializer__write_mark(s, ']');
  28019. // varnames (as cstr via py_name2str)
  28020. c11_serializer__write_i32(s, co->varnames.length);
  28021. c11_serializer__write_mark(s, '[');
  28022. for(int i = 0; i < co->varnames.length; i++) {
  28023. py_Name name = c11__getitem(py_Name, &co->varnames, i);
  28024. c11_serializer__write_cstr(s, py_name2str(name));
  28025. }
  28026. c11_serializer__write_mark(s, ']');
  28027. // names (as cstr via py_name2str)
  28028. c11_serializer__write_i32(s, co->names.length);
  28029. c11_serializer__write_mark(s, '[');
  28030. for(int i = 0; i < co->names.length; i++) {
  28031. py_Name name = c11__getitem(py_Name, &co->names, i);
  28032. c11_serializer__write_cstr(s, py_name2str(name));
  28033. }
  28034. c11_serializer__write_mark(s, ']');
  28035. // nlocals
  28036. c11_serializer__write_i32(s, co->nlocals);
  28037. // blocks
  28038. _Static_assert(sizeof(CodeBlock) == sizeof(int32_t) * 5, "");
  28039. c11_serializer__write_i32(s, co->blocks.length);
  28040. c11_serializer__write_mark(s, '[');
  28041. c11_serializer__write_bytes(s, co->blocks.data, co->blocks.length * sizeof(CodeBlock));
  28042. c11_serializer__write_mark(s, ']');
  28043. // func_decls
  28044. c11_serializer__write_i32(s, co->func_decls.length);
  28045. c11_serializer__write_mark(s, '[');
  28046. for(int i = 0; i < co->func_decls.length; i++) {
  28047. const FuncDecl* decl = c11__getitem(FuncDecl_, &co->func_decls, i);
  28048. FuncDecl__serialize(s, decl, co->src);
  28049. c11_serializer__write_mark(s, '|');
  28050. }
  28051. c11_serializer__write_mark(s, ']');
  28052. // start_line, end_line
  28053. c11_serializer__write_i32(s, co->start_line);
  28054. c11_serializer__write_i32(s, co->end_line);
  28055. }
  28056. // Deserialize CodeObject (initialize co before calling)
  28057. static CodeObject CodeObject__deserialize(c11_deserializer* d, const char* filename, SourceData_ embedded_src) {
  28058. CodeObject co;
  28059. // SourceData
  28060. SourceData_ src;
  28061. if(embedded_src != NULL) {
  28062. c11__rtassert(filename == NULL);
  28063. src = embedded_src;
  28064. PK_INCREF(src);
  28065. } else {
  28066. c11__rtassert(filename != NULL);
  28067. src = SourceData__rcnew(NULL, filename, EXEC_MODE, false);
  28068. }
  28069. // name
  28070. const char* name = c11_deserializer__read_cstr(d);
  28071. c11_sv name_sv = {name, strlen(name)};
  28072. // Initialize the CodeObject
  28073. CodeObject__ctor(&co, src, name_sv);
  28074. PK_DECREF(src); // CodeObject__ctor increments ref count
  28075. // Clear the default root block that CodeObject__ctor adds
  28076. c11_vector__clear(&co.blocks);
  28077. // codes
  28078. int codes_len = c11_deserializer__read_i32(d);
  28079. c11_deserializer__consume_mark(d, '[');
  28080. c11_vector__extend(&co.codes,
  28081. c11_deserializer__read_bytes(d, codes_len * sizeof(Bytecode)),
  28082. codes_len);
  28083. c11_deserializer__consume_mark(d, ']');
  28084. // codes_ex
  28085. int codes_ex_len = c11_deserializer__read_i32(d);
  28086. c11_deserializer__consume_mark(d, '[');
  28087. c11_vector__extend(&co.codes_ex,
  28088. c11_deserializer__read_bytes(d, codes_ex_len * sizeof(BytecodeEx)),
  28089. codes_ex_len);
  28090. c11_deserializer__consume_mark(d, ']');
  28091. // consts
  28092. int consts_len = c11_deserializer__read_i32(d);
  28093. c11_deserializer__consume_mark(d, '[');
  28094. for(int i = 0; i < consts_len; i++) {
  28095. py_Ref p_val = c11_vector__emplace(&co.consts);
  28096. TValue__deserialize(d, p_val);
  28097. }
  28098. c11_deserializer__consume_mark(d, ']');
  28099. // varnames
  28100. int varnames_len = c11_deserializer__read_i32(d);
  28101. c11_deserializer__consume_mark(d, '[');
  28102. for(int i = 0; i < varnames_len; i++) {
  28103. const char* s = c11_deserializer__read_cstr(d);
  28104. py_Name n = py_name(s);
  28105. c11_vector__push(py_Name, &co.varnames, n);
  28106. c11_smallmap_n2d__set(&co.varnames_inv, n, i);
  28107. }
  28108. c11_deserializer__consume_mark(d, ']');
  28109. // names
  28110. int names_len = c11_deserializer__read_i32(d);
  28111. c11_deserializer__consume_mark(d, '[');
  28112. for(int i = 0; i < names_len; i++) {
  28113. const char* s = c11_deserializer__read_cstr(d);
  28114. py_Name n = py_name(s);
  28115. c11_vector__push(py_Name, &co.names, n);
  28116. c11_smallmap_n2d__set(&co.names_inv, n, i);
  28117. }
  28118. c11_deserializer__consume_mark(d, ']');
  28119. // nlocals
  28120. co.nlocals = c11_deserializer__read_i32(d);
  28121. // blocks
  28122. int blocks_len = c11_deserializer__read_i32(d);
  28123. c11_deserializer__consume_mark(d, '[');
  28124. c11_vector__extend(&co.blocks,
  28125. c11_deserializer__read_bytes(d, blocks_len * sizeof(CodeBlock)),
  28126. blocks_len);
  28127. c11_deserializer__consume_mark(d, ']');
  28128. // func_decls
  28129. int func_decls_len = c11_deserializer__read_i32(d);
  28130. c11_deserializer__consume_mark(d, '[');
  28131. for(int i = 0; i < func_decls_len; i++) {
  28132. FuncDecl_ decl = FuncDecl__deserialize(d, src);
  28133. c11_vector__push(FuncDecl_, &co.func_decls, decl);
  28134. c11_deserializer__consume_mark(d, '|');
  28135. }
  28136. c11_deserializer__consume_mark(d, ']');
  28137. // start_line, end_line
  28138. co.start_line = c11_deserializer__read_i32(d);
  28139. co.end_line = c11_deserializer__read_i32(d);
  28140. return co;
  28141. }
  28142. // Serialize FuncDecl
  28143. static void FuncDecl__serialize(c11_serializer* s,
  28144. const FuncDecl* decl,
  28145. const struct SourceData* parent_src) {
  28146. // CodeObject (embedded)
  28147. c11_serializer__write_mark(s, '{');
  28148. CodeObject__serialize(s, &decl->code, parent_src);
  28149. c11_serializer__write_mark(s, '}');
  28150. // args
  28151. c11_serializer__write_i32(s, decl->args.length);
  28152. c11_serializer__write_mark(s, '[');
  28153. c11_serializer__write_bytes(s, decl->args.data, decl->args.length * sizeof(int32_t));
  28154. c11_serializer__write_mark(s, ']');
  28155. // kwargs
  28156. c11_serializer__write_i32(s, decl->kwargs.length);
  28157. c11_serializer__write_mark(s, '[');
  28158. for(int i = 0; i < decl->kwargs.length; i++) {
  28159. FuncDeclKwArg* kw = c11__at(FuncDeclKwArg, &decl->kwargs, i);
  28160. c11_serializer__write_i32(s, kw->index);
  28161. c11_serializer__write_cstr(s, py_name2str(kw->key));
  28162. TValue__serialize(s, &kw->value);
  28163. }
  28164. c11_serializer__write_mark(s, ']');
  28165. // starred_arg, starred_kwarg
  28166. c11_serializer__write_i32(s, decl->starred_arg);
  28167. c11_serializer__write_i32(s, decl->starred_kwarg);
  28168. // nested
  28169. c11_serializer__write_i8(s, decl->nested ? 1 : 0);
  28170. // docstring
  28171. int has_docstring = decl->docstring != NULL ? 1 : 0;
  28172. c11_serializer__write_i8(s, has_docstring);
  28173. if(has_docstring) c11_serializer__write_cstr(s, decl->docstring);
  28174. // type
  28175. c11_serializer__write_i8(s, (int8_t)decl->type);
  28176. }
  28177. // Deserialize FuncDecl
  28178. static FuncDecl_ FuncDecl__deserialize(c11_deserializer* d, SourceData_ embedded_src) {
  28179. FuncDecl_ self = PK_MALLOC(sizeof(FuncDecl));
  28180. self->rc.count = 1;
  28181. self->rc.dtor = FuncDecl__dtor;
  28182. c11_vector__ctor(&self->args, sizeof(int32_t));
  28183. c11_vector__ctor(&self->kwargs, sizeof(FuncDeclKwArg));
  28184. c11_smallmap_n2d__ctor(&self->kw_to_index);
  28185. // CodeObject (embedded)
  28186. c11_deserializer__consume_mark(d, '{');
  28187. self->code = CodeObject__deserialize(d, NULL, embedded_src);
  28188. c11_deserializer__consume_mark(d, '}');
  28189. // args
  28190. int args_len = c11_deserializer__read_i32(d);
  28191. c11_deserializer__consume_mark(d, '[');
  28192. c11_vector__extend(&self->args,
  28193. c11_deserializer__read_bytes(d, args_len * sizeof(int32_t)),
  28194. args_len);
  28195. c11_deserializer__consume_mark(d, ']');
  28196. // kwargs
  28197. int kwargs_len = c11_deserializer__read_i32(d);
  28198. c11_deserializer__consume_mark(d, '[');
  28199. for(int i = 0; i < kwargs_len; i++) {
  28200. FuncDeclKwArg* kw = c11_vector__emplace(&self->kwargs);
  28201. kw->index = c11_deserializer__read_i32(d);
  28202. const char* key_str = c11_deserializer__read_cstr(d);
  28203. kw->key = py_name(key_str);
  28204. TValue__deserialize(d, &kw->value);
  28205. c11_smallmap_n2d__set(&self->kw_to_index, kw->key, kw->index);
  28206. }
  28207. c11_deserializer__consume_mark(d, ']');
  28208. // starred_arg
  28209. self->starred_arg = c11_deserializer__read_i32(d);
  28210. // starred_kwarg
  28211. self->starred_kwarg = c11_deserializer__read_i32(d);
  28212. // nested
  28213. self->nested = c11_deserializer__read_i8(d) != 0;
  28214. // docstring
  28215. int has_docstring = c11_deserializer__read_i8(d);
  28216. if(has_docstring) {
  28217. const char* docstring = c11_deserializer__read_cstr(d);
  28218. self->docstring = c11_strdup(docstring);
  28219. } else {
  28220. self->docstring = NULL;
  28221. }
  28222. // type
  28223. self->type = (FuncType)c11_deserializer__read_i8(d);
  28224. return self;
  28225. }
  28226. // Public API: Serialize CodeObject to bytes
  28227. void* CodeObject__dumps(const CodeObject* co, int* size) {
  28228. c11_serializer s;
  28229. c11_serializer__ctor(&s, CODEOBJECT_MAGIC, CODEOBJECT_VER_MAJOR, CODEOBJECT_VER_MINOR);
  28230. CodeObject__serialize(&s, co, NULL);
  28231. return c11_serializer__submit(&s, size);
  28232. }
  28233. // Public API: Deserialize CodeObject from bytes
  28234. // Returns error message or NULL on success
  28235. char* CodeObject__loads(const void* data, int size, const char* filename, CodeObject* out) {
  28236. c11_deserializer d;
  28237. c11_deserializer__ctor(&d, data, size);
  28238. if(!c11_deserializer__check_header(&d,
  28239. CODEOBJECT_MAGIC,
  28240. CODEOBJECT_VER_MAJOR,
  28241. CODEOBJECT_VER_MINOR_MIN)) {
  28242. char* error_msg = c11_strdup(d.error_msg);
  28243. c11_deserializer__dtor(&d);
  28244. return error_msg;
  28245. }
  28246. *out = CodeObject__deserialize(&d, filename, NULL);
  28247. c11_deserializer__dtor(&d);
  28248. return NULL;
  28249. }
  28250. #undef CODEOBJECT_MAGIC
  28251. #undef CODEOBJECT_VER_MAJOR
  28252. #undef CODEOBJECT_VER_MINOR
  28253. #undef CODEOBJECT_VER_MINOR_MIN
  28254. // src/objects\container.c
  28255. #define FIXEDHASH_T__SOURCE
  28256. #define K py_Name
  28257. #define V py_TValue
  28258. #define NAME CachedNames
  28259. #if !defined(FIXEDHASH_T__HEADER) && !defined(FIXEDHASH_T__SOURCE)
  28260. #include "pocketpy/common/chunkedvector.h"
  28261. #include "pocketpy/config.h"
  28262. #include <stdint.h>
  28263. #define FIXEDHASH_T__HEADER
  28264. #define FIXEDHASH_T__SOURCE
  28265. /* Input */
  28266. #define K int
  28267. #define V float
  28268. #define NAME c11_fixedhash_d2f
  28269. #endif
  28270. /* Optional Input */
  28271. #ifndef hash
  28272. #define hash(a) ((uint64_t)(a))
  28273. #endif
  28274. #ifndef equal
  28275. #define equal(a, b) ((a) == (b))
  28276. #endif
  28277. /* Temporary macros */
  28278. #define CONCAT(A, B) CONCAT_(A, B)
  28279. #define CONCAT_(A, B) A##B
  28280. #define KV CONCAT(NAME, _KV)
  28281. #define METHOD(name) CONCAT(NAME, CONCAT(__, name))
  28282. #ifdef FIXEDHASH_T__HEADER
  28283. /* Declaration */
  28284. typedef struct {
  28285. uint64_t hash;
  28286. K key;
  28287. V val;
  28288. } KV;
  28289. typedef struct {
  28290. int length;
  28291. uint16_t indices[0x10000];
  28292. c11_chunkedvector /*T=FixedHashEntry*/ entries;
  28293. } NAME;
  28294. void METHOD(ctor)(NAME* self);
  28295. void METHOD(dtor)(NAME* self);
  28296. NAME* METHOD(new)();
  28297. void METHOD(delete)(NAME* self);
  28298. void METHOD(set)(NAME* self, K key, V* value);
  28299. V* METHOD(try_get)(NAME* self, K key);
  28300. bool METHOD(contains)(NAME* self, K key);
  28301. #endif
  28302. #ifdef FIXEDHASH_T__SOURCE
  28303. /* Implementation */
  28304. void METHOD(ctor)(NAME* self) {
  28305. self->length = 0;
  28306. memset(self->indices, 0xFF, sizeof(self->indices));
  28307. c11_chunkedvector__ctor(&self->entries, sizeof(KV), 0);
  28308. }
  28309. void METHOD(dtor)(NAME* self) { c11_chunkedvector__dtor(&self->entries); }
  28310. NAME* METHOD(new)() {
  28311. NAME* self = PK_MALLOC(sizeof(NAME));
  28312. METHOD(ctor)(self);
  28313. return self;
  28314. }
  28315. void METHOD(delete)(NAME* self) {
  28316. METHOD(dtor)(self);
  28317. PK_FREE(self);
  28318. }
  28319. void METHOD(set)(NAME* self, K key, V* value) {
  28320. uint64_t hash_value = hash(key);
  28321. int index = (uint16_t)(hash_value & 0xFFFF);
  28322. while(self->indices[index] != 0xFFFF) {
  28323. KV* entry = c11_chunkedvector__at(&self->entries, self->indices[index]);
  28324. if(equal(entry->key, key)) {
  28325. entry->val = *value;
  28326. return;
  28327. }
  28328. index = ((5 * index) + 1) & 0xFFFF;
  28329. }
  28330. if(self->length >= 65000) abort();
  28331. KV* kv = c11_chunkedvector__emplace(&self->entries);
  28332. kv->hash = hash_value;
  28333. kv->key = key;
  28334. kv->val = *value;
  28335. self->indices[index] = self->entries.length - 1;
  28336. self->length++;
  28337. }
  28338. V* METHOD(try_get)(NAME* self, K key) {
  28339. uint64_t hash_value = hash(key);
  28340. int index = (uint16_t)(hash_value & 0xFFFF);
  28341. while(self->indices[index] != 0xFFFF) {
  28342. KV* entry = c11_chunkedvector__at(&self->entries, self->indices[index]);
  28343. if(equal(entry->key, key)) return &entry->val;
  28344. index = ((5 * index) + 1) & 0xFFFF;
  28345. }
  28346. return NULL;
  28347. }
  28348. bool METHOD(contains)(NAME* self, K key) {
  28349. V* value = METHOD(try_get)(self, key);
  28350. return value != NULL;
  28351. }
  28352. #endif
  28353. /* Undefine all macros */
  28354. #undef KV
  28355. #undef METHOD
  28356. #undef CONCAT
  28357. #undef CONCAT_
  28358. #undef K
  28359. #undef V
  28360. #undef NAME
  28361. #undef less
  28362. #undef partial_less
  28363. #undef equal
  28364. #undef hash
  28365. #undef FIXEDHASH_T__SOURCE
  28366. // src/objects\namedict.c
  28367. #include <stdint.h>
  28368. #include <string.h>
  28369. #include <assert.h>
  28370. // https://jfdube.wordpress.com/2011/10/12/hashing-strings-and-pointers-avoiding-common-pitfalls/
  28371. uintptr_t ThomasWangInt32Hash(void* Ptr) {
  28372. // Here we think only the lower 32 bits are useful
  28373. uint32_t Value = (uint32_t)(uintptr_t)Ptr;
  28374. Value = ~Value + (Value << 15);
  28375. Value = Value ^ (Value >> 12);
  28376. Value = Value + (Value << 2);
  28377. Value = Value ^ (Value >> 4);
  28378. Value = Value * 2057;
  28379. Value = Value ^ (Value >> 16);
  28380. return Value;
  28381. }
  28382. #define HASH_KEY(__k) ThomasWangInt32Hash(__k)
  28383. #define HASH_PROBE_0(__k, ok, i) \
  28384. ok = false; \
  28385. i = HASH_KEY(__k) & self->mask; \
  28386. do { \
  28387. if(self->items[i].key == (__k)) { \
  28388. ok = true; \
  28389. break; \
  28390. } \
  28391. if(self->items[i].key == NULL) break; \
  28392. i = (i + 1) & self->mask; \
  28393. } while(true);
  28394. #define HASH_PROBE_1(__k, ok, i) \
  28395. ok = false; \
  28396. i = HASH_KEY(__k) & self->mask; \
  28397. while(self->items[i].key != NULL) { \
  28398. if(self->items[i].key == (__k)) { \
  28399. ok = true; \
  28400. break; \
  28401. } \
  28402. i = (i + 1) & self->mask; \
  28403. }
  28404. static void NameDict__set_capacity_and_alloc_items(NameDict* self, int val) {
  28405. self->capacity = val;
  28406. self->critical_size = val * self->load_factor;
  28407. self->mask = (uintptr_t)val - 1;
  28408. self->items = PK_MALLOC(self->capacity * sizeof(NameDict_KV));
  28409. memset(self->items, 0, self->capacity * sizeof(NameDict_KV));
  28410. }
  28411. static void NameDict__rehash_2x(NameDict* self) {
  28412. NameDict_KV* old_items = self->items;
  28413. int old_capacity = self->capacity;
  28414. NameDict__set_capacity_and_alloc_items(self, self->capacity * 2);
  28415. for(int i = 0; i < old_capacity; i++) {
  28416. if(old_items[i].key == NULL) continue;
  28417. bool ok;
  28418. uintptr_t j;
  28419. HASH_PROBE_1(old_items[i].key, ok, j);
  28420. c11__rtassert(!ok);
  28421. self->items[j] = old_items[i];
  28422. }
  28423. PK_FREE(old_items);
  28424. }
  28425. NameDict* NameDict__new(float load_factor) {
  28426. NameDict* p = PK_MALLOC(sizeof(NameDict));
  28427. NameDict__ctor(p, load_factor);
  28428. return p;
  28429. }
  28430. void NameDict__delete(NameDict* self) {
  28431. NameDict__dtor(self);
  28432. PK_FREE(self);
  28433. }
  28434. void NameDict__ctor(NameDict* self, float load_factor) {
  28435. assert(load_factor > 0.0f && load_factor < 1.0f);
  28436. self->length = 0;
  28437. self->load_factor = load_factor;
  28438. NameDict__set_capacity_and_alloc_items(self, 4);
  28439. }
  28440. void NameDict__dtor(NameDict* self) { PK_FREE(self->items); }
  28441. py_TValue* NameDict__try_get(NameDict* self, py_Name key) {
  28442. bool ok;
  28443. uintptr_t i;
  28444. HASH_PROBE_0(key, ok, i);
  28445. if(!ok) return NULL;
  28446. return &self->items[i].value;
  28447. }
  28448. bool NameDict__contains(NameDict* self, py_Name key) {
  28449. bool ok;
  28450. uintptr_t i;
  28451. HASH_PROBE_0(key, ok, i);
  28452. return ok;
  28453. }
  28454. void NameDict__set(NameDict* self, py_Name key, py_TValue* val) {
  28455. bool ok;
  28456. uintptr_t i;
  28457. HASH_PROBE_1(key, ok, i);
  28458. if(!ok) {
  28459. self->length++;
  28460. if(self->length > self->critical_size) {
  28461. NameDict__rehash_2x(self);
  28462. HASH_PROBE_1(key, ok, i);
  28463. }
  28464. self->items[i].key = key;
  28465. }
  28466. self->items[i].value = *val;
  28467. }
  28468. bool NameDict__del(NameDict* self, py_Name key) {
  28469. bool ok;
  28470. uintptr_t i;
  28471. HASH_PROBE_0(key, ok, i);
  28472. if(!ok) return false;
  28473. self->items[i].key = NULL;
  28474. self->items[i].value = *py_NIL();
  28475. self->length--;
  28476. /* tidy */
  28477. uintptr_t posToRemove = i;
  28478. uintptr_t posToShift = posToRemove;
  28479. while(true) {
  28480. posToShift = (posToShift + 1) & self->mask;
  28481. if(self->items[posToShift].key == NULL) break;
  28482. uintptr_t hash_z = HASH_KEY(self->items[posToShift].key);
  28483. uintptr_t insertPos = hash_z & self->mask;
  28484. bool cond1 = insertPos <= posToRemove;
  28485. bool cond2 = posToRemove <= posToShift;
  28486. if((cond1 && cond2) ||
  28487. // chain wrapped around capacity
  28488. (posToShift < insertPos && (cond1 || cond2))) {
  28489. NameDict_KV tmp = self->items[posToRemove];
  28490. assert(tmp.key == NULL);
  28491. self->items[posToRemove] = self->items[posToShift];
  28492. self->items[posToShift] = tmp;
  28493. posToRemove = posToShift;
  28494. }
  28495. }
  28496. return true;
  28497. }
  28498. void NameDict__clear(NameDict* self) {
  28499. for(int i = 0; i < self->capacity; i++) {
  28500. self->items[i].key = NULL;
  28501. self->items[i].value = *py_NIL();
  28502. }
  28503. self->length = 0;
  28504. }
  28505. #undef HASH_PROBE_0
  28506. #undef HASH_PROBE_1
  28507. #undef HASH_KEY
  28508. // src/objects\object.c
  28509. #include <assert.h>
  28510. PK_INLINE void* PyObject__userdata(PyObject* self) {
  28511. return self->flex + PK_OBJ_SLOTS_SIZE(self->slots);
  28512. }
  28513. PK_INLINE NameDict* PyObject__dict(PyObject* self) {
  28514. assert(self->slots == -1);
  28515. return (NameDict*)(self->flex);
  28516. }
  28517. PK_INLINE py_TValue* PyObject__slots(PyObject* self) {
  28518. assert(self->slots >= 0);
  28519. return (py_TValue*)(self->flex);
  28520. }
  28521. // src/public\Bindings.c
  28522. void py_bind(py_Ref obj, const char* sig, py_CFunction f) {
  28523. py_Ref tmp = py_pushtmp();
  28524. py_Name name = py_newfunction(tmp, sig, f, NULL, 0);
  28525. py_setdict(obj, name, tmp);
  28526. py_pop();
  28527. }
  28528. void py_bindmethod(py_Type type, const char* name, py_CFunction f) {
  28529. py_TValue tmp;
  28530. py_newnativefunc(&tmp, f);
  28531. py_setdict(py_tpobject(type), py_name(name), &tmp);
  28532. }
  28533. void py_bindstaticmethod(py_Type type, const char* name, py_CFunction f) {
  28534. py_TValue tmp;
  28535. py_newnativefunc(&tmp, f);
  28536. bool ok = py_tpcall(tp_staticmethod, 1, &tmp);
  28537. if(!ok) {
  28538. py_printexc();
  28539. c11__abort("py_bindstaticmethod(): failed to create staticmethod");
  28540. }
  28541. py_setdict(py_tpobject(type), py_name(name), py_retval());
  28542. }
  28543. void py_bindfunc(py_Ref obj, const char* name, py_CFunction f) {
  28544. py_TValue tmp;
  28545. py_newnativefunc(&tmp, f);
  28546. py_setdict(obj, py_name(name), &tmp);
  28547. }
  28548. void py_bindproperty(py_Type type, const char* name, py_CFunction getter, py_CFunction setter) {
  28549. py_TValue tmp;
  28550. py_newobject(&tmp, tp_property, 2, 0);
  28551. py_newnativefunc(py_getslot(&tmp, 0), getter);
  28552. if(setter) {
  28553. py_newnativefunc(py_getslot(&tmp, 1), setter);
  28554. } else {
  28555. py_setslot(&tmp, 1, py_None());
  28556. }
  28557. py_setdict(py_tpobject(type), py_name(name), &tmp);
  28558. }
  28559. void py_bindmagic(py_Type type, py_Name name, py_CFunction f) {
  28560. py_Ref tmp = py_emplacedict(py_tpobject(type), name);
  28561. py_newnativefunc(tmp, f);
  28562. }
  28563. // src/public\CodeExecution.c
  28564. #include <assert.h>
  28565. #include <ctype.h>
  28566. py_Type pk_code__register() {
  28567. py_Type type = pk_newtype("code", tp_object, NULL, (py_Dtor)CodeObject__dtor, false, true);
  28568. return type;
  28569. }
  28570. static bool _py_compile(CodeObject* out,
  28571. const char* source,
  28572. const char* filename,
  28573. enum py_CompileMode mode,
  28574. bool is_dynamic) {
  28575. VM* vm = pk_current_vm;
  28576. SourceData_ src = SourceData__rcnew(source, filename, mode, is_dynamic);
  28577. Error* err = pk_compile(src, out);
  28578. if(err) {
  28579. py_exception(tp_SyntaxError, "%s", err->msg);
  28580. py_BaseException__stpush(NULL, &vm->unhandled_exc, err->src, err->lineno, NULL);
  28581. PK_DECREF(src);
  28582. PK_DECREF(err->src);
  28583. PK_FREE(err);
  28584. return false;
  28585. }
  28586. PK_DECREF(src);
  28587. return true;
  28588. }
  28589. bool pk_exec(CodeObject* co, py_Ref module) {
  28590. VM* vm = pk_current_vm;
  28591. if(!module) module = vm->main;
  28592. assert(module->type == tp_module);
  28593. py_StackRef sp = vm->stack.sp;
  28594. py_Frame* frame = Frame__new(co, sp, module, module, py_NIL(), true);
  28595. VM__push_frame(vm, frame);
  28596. FrameResult res = VM__run_top_frame(vm);
  28597. if(res == RES_ERROR) return false;
  28598. assert(res == RES_RETURN);
  28599. return true;
  28600. }
  28601. bool pk_execdyn(CodeObject* co, py_Ref module, py_Ref globals, py_Ref locals) {
  28602. VM* vm = pk_current_vm;
  28603. if(!module) module = vm->main;
  28604. assert(module->type == tp_module);
  28605. py_StackRef sp = vm->stack.sp;
  28606. assert(globals != NULL && locals != NULL);
  28607. // check globals
  28608. if(globals->type == tp_namedict) {
  28609. globals = py_getslot(globals, 0);
  28610. assert(globals->type == tp_module);
  28611. } else {
  28612. if(!py_istype(globals, tp_dict)) { return TypeError("globals must be a dict object"); }
  28613. }
  28614. // check locals
  28615. switch(locals->type) {
  28616. case tp_locals: break;
  28617. case tp_dict: break;
  28618. case tp_nil: break;
  28619. default: return TypeError("locals must be a dict object");
  28620. }
  28621. py_Frame* frame = Frame__new(co, sp, module, globals, locals, true);
  28622. VM__push_frame(vm, frame);
  28623. FrameResult res = VM__run_top_frame(vm);
  28624. if(res == RES_ERROR) return false;
  28625. assert(res == RES_RETURN);
  28626. return true;
  28627. }
  28628. static bool
  28629. pk_smartexec(const char* source, py_Ref module, enum py_CompileMode mode, va_list args) {
  28630. if(module == NULL) module = pk_current_vm->main;
  28631. pk_mappingproxy__namedict(py_pushtmp(), module); // globals
  28632. py_newdict(py_pushtmp()); // locals
  28633. bool ok = py_compile(source, "<string>", mode, true);
  28634. if(!ok) return false;
  28635. py_push(py_retval());
  28636. // [globals, locals, code]
  28637. CodeObject* co = py_touserdata(py_peek(-1));
  28638. py_StackRef locals = py_peek(-2);
  28639. int max_index = -1;
  28640. c11__foreach(Bytecode, &co->codes, bc) {
  28641. if(bc->op == OP_LOAD_NAME) {
  28642. c11_sv name = py_name2sv(c11__getitem(py_Name, &co->names, bc->arg));
  28643. if(name.data[0] != '_') continue;
  28644. int index;
  28645. if(name.size == 1) {
  28646. index = 0;
  28647. } else if(name.size == 2 && isdigit(name.data[1])) {
  28648. index = name.data[1] - '0';
  28649. } else {
  28650. continue;
  28651. }
  28652. max_index = c11__max(max_index, index);
  28653. }
  28654. }
  28655. if(max_index == -1) return ValueError("no placeholder found in the source");
  28656. for(int i = 0; i <= max_index; i++) {
  28657. py_Ref val = va_arg(args, py_Ref);
  28658. char buf[3];
  28659. buf[0] = '_';
  28660. buf[1] = '0' + i;
  28661. buf[2] = '\0';
  28662. py_dict_setitem_by_str(locals, buf, val);
  28663. if(i == 0) {
  28664. // _ => _0
  28665. py_dict_setitem_by_str(locals, "_", val);
  28666. }
  28667. }
  28668. ok = pk_execdyn(co, module, py_peek(-3), locals);
  28669. if(!ok) return false;
  28670. py_shrink(3);
  28671. return true;
  28672. }
  28673. bool py_compile(const char* source,
  28674. const char* filename,
  28675. enum py_CompileMode mode,
  28676. bool is_dynamic) {
  28677. CodeObject co;
  28678. bool ok = _py_compile(&co, source, filename, mode, is_dynamic);
  28679. if(ok) {
  28680. // compile success
  28681. CodeObject* ud = py_newobject(py_retval(), tp_code, 0, sizeof(CodeObject));
  28682. *ud = co;
  28683. }
  28684. return ok;
  28685. }
  28686. bool py_exec(const char* source, const char* filename, enum py_CompileMode mode, py_Ref module) {
  28687. CodeObject co;
  28688. if(!_py_compile(&co, source, filename, mode, false)) return false;
  28689. bool ok = pk_exec(&co, module);
  28690. CodeObject__dtor(&co);
  28691. return ok;
  28692. }
  28693. bool py_execo(const void* data, int size, const char* filename, py_Ref module) {
  28694. CodeObject co;
  28695. char* err = CodeObject__loads(data, size, filename, &co);
  28696. if(err == NULL) {
  28697. c11__rtassert(co.src->mode == EXEC_MODE);
  28698. c11__rtassert(co.src->is_dynamic == false);
  28699. bool ok = pk_exec(&co, module);
  28700. CodeObject__dtor(&co);
  28701. return ok;
  28702. } else {
  28703. bool ok = RuntimeError("bad code object %s: %s", filename, err);
  28704. PK_FREE(err);
  28705. return ok;
  28706. }
  28707. }
  28708. bool py_eval(const char* source, py_Ref module) {
  28709. return py_exec(source, "<string>", EVAL_MODE, module);
  28710. }
  28711. bool py_smartexec(const char* source, py_Ref module, ...) {
  28712. va_list args;
  28713. va_start(args, module);
  28714. bool ok = pk_smartexec(source, module, EXEC_MODE, args);
  28715. va_end(args);
  28716. return ok;
  28717. }
  28718. bool py_smarteval(const char* source, py_Ref module, ...) {
  28719. va_list args;
  28720. va_start(args, module);
  28721. bool ok = pk_smartexec(source, module, EVAL_MODE, args);
  28722. va_end(args);
  28723. return ok;
  28724. }
  28725. // src/public\DictSlots.c
  28726. PK_INLINE py_Ref py_getreg(int i) { return pk_current_vm->reg + i; }
  28727. PK_INLINE void py_setreg(int i, py_Ref val) { pk_current_vm->reg[i] = *val; }
  28728. PK_INLINE py_Ref py_retval() { return &pk_current_vm->last_retval; }
  28729. PK_INLINE py_Ref py_getdict(py_Ref self, py_Name name) {
  28730. assert(self && self->is_ptr);
  28731. return NameDict__try_get(PyObject__dict(self->_obj), name);
  28732. }
  28733. PK_INLINE void py_setdict(py_Ref self, py_Name name, py_Ref val) {
  28734. assert(self && self->is_ptr);
  28735. NameDict__set(PyObject__dict(self->_obj), name, val);
  28736. }
  28737. bool py_deldict(py_Ref self, py_Name name) {
  28738. assert(self && self->is_ptr);
  28739. return NameDict__del(PyObject__dict(self->_obj), name);
  28740. }
  28741. py_ItemRef py_emplacedict(py_Ref self, py_Name name) {
  28742. py_setdict(self, name, py_NIL());
  28743. return py_getdict(self, name);
  28744. }
  28745. bool py_applydict(py_Ref self, bool (*f)(py_Name, py_Ref, void*), void* ctx) {
  28746. assert(self && self->is_ptr);
  28747. NameDict* dict = PyObject__dict(self->_obj);
  28748. for(int i = 0; i < dict->capacity; i++) {
  28749. NameDict_KV* kv = &dict->items[i];
  28750. if(kv->key == NULL) continue;
  28751. bool ok = f(kv->key, &kv->value, ctx);
  28752. if(!ok) return false;
  28753. }
  28754. return true;
  28755. }
  28756. void py_cleardict(py_Ref self) {
  28757. assert(self && self->is_ptr);
  28758. NameDict* dict = PyObject__dict(self->_obj);
  28759. NameDict__clear(dict);
  28760. }
  28761. py_Ref py_getslot(py_Ref self, int i) {
  28762. assert(self && self->is_ptr);
  28763. assert(i >= 0 && i < self->_obj->slots);
  28764. return PyObject__slots(self->_obj) + i;
  28765. }
  28766. void py_setslot(py_Ref self, int i, py_Ref val) {
  28767. assert(self && self->is_ptr);
  28768. assert(i >= 0 && i < self->_obj->slots);
  28769. PyObject__slots(self->_obj)[i] = *val;
  28770. }
  28771. py_Ref py_getbuiltin(py_Name name) { return py_getdict(pk_current_vm->builtins, name); }
  28772. py_Ref py_getglobal(py_Name name) { return py_getdict(pk_current_vm->main, name); }
  28773. void py_setglobal(py_Name name, py_Ref val) { py_setdict(pk_current_vm->main, name, val); }
  28774. // src/public\FrameOps.c
  28775. const char* py_Frame_sourceloc(py_Frame* self, int* lineno) {
  28776. SourceLocation loc = Frame__source_location(self);
  28777. *lineno = loc.lineno;
  28778. return loc.src->filename->data;
  28779. }
  28780. void py_Frame_newglobals(py_Frame* frame, py_OutRef out) {
  28781. if(!frame) {
  28782. pk_mappingproxy__namedict(out, pk_current_vm->main);
  28783. return;
  28784. }
  28785. if(frame->globals->type == tp_module) {
  28786. pk_mappingproxy__namedict(out, frame->globals);
  28787. } else {
  28788. *out = *frame->globals; // dict
  28789. }
  28790. }
  28791. void py_Frame_newlocals(py_Frame* frame, py_OutRef out) {
  28792. if(!frame) {
  28793. py_newdict(out);
  28794. return;
  28795. }
  28796. if(frame->is_locals_special) {
  28797. switch(frame->locals->type) {
  28798. case tp_locals: frame = frame->locals->_ptr; break;
  28799. case tp_dict: *out = *frame->locals; return;
  28800. case tp_nil: py_newdict(out); return;
  28801. default: c11__unreachable();
  28802. }
  28803. }
  28804. FastLocals__to_dict(frame->locals, frame->co);
  28805. py_assign(out, py_retval());
  28806. }
  28807. py_StackRef py_Frame_function(py_Frame* self) {
  28808. if(self->is_locals_special) return NULL;
  28809. assert(self->p0->type == tp_function);
  28810. return self->p0;
  28811. }
  28812. // src/public\GlobalSetup.c
  28813. PK_THREAD_LOCAL VM* pk_current_vm;
  28814. static bool pk_initialized;
  28815. static bool pk_finalized;
  28816. static VM pk_default_vm;
  28817. static VM* pk_all_vm[16];
  28818. static py_TValue _True, _False, _None, _NIL;
  28819. void py_initialize() {
  28820. c11__rtassert(!pk_finalized);
  28821. if(pk_initialized) {
  28822. // c11__abort("py_initialize() can only be called once!");
  28823. return;
  28824. }
  28825. pk_names_initialize();
  28826. // check endianness
  28827. int x = 1;
  28828. bool is_little_endian = *(char*)&x == 1;
  28829. if(!is_little_endian) c11__abort("is_little_endian != true");
  28830. _Static_assert(sizeof(py_TValue) == 24, "sizeof(py_TValue) != 24");
  28831. _Static_assert(offsetof(py_TValue, extra) == 4, "offsetof(py_TValue, extra) != 4");
  28832. // check sizes
  28833. _Static_assert(sizeof(float) == 4, "");
  28834. _Static_assert(sizeof(double) == 8, "");
  28835. pk_current_vm = pk_all_vm[0] = &pk_default_vm;
  28836. // initialize some convenient references
  28837. py_newbool(&_True, true);
  28838. py_newbool(&_False, false);
  28839. py_newnone(&_None);
  28840. py_newnil(&_NIL);
  28841. VM__ctor(&pk_default_vm);
  28842. pk_initialized = true;
  28843. }
  28844. void py_finalize() {
  28845. if(pk_finalized) c11__abort("py_finalize() can only be called once!");
  28846. pk_finalized = true;
  28847. for(int i = 1; i < 16; i++) {
  28848. VM* vm = pk_all_vm[i];
  28849. if(vm) {
  28850. // temp fix https://github.com/pocketpy/pocketpy/issues/315
  28851. // TODO: refactor VM__ctor and VM__dtor
  28852. pk_current_vm = vm;
  28853. VM__dtor(vm);
  28854. PK_FREE(vm);
  28855. }
  28856. }
  28857. pk_current_vm = &pk_default_vm;
  28858. VM__dtor(&pk_default_vm);
  28859. pk_current_vm = NULL;
  28860. pk_names_finalize();
  28861. }
  28862. int VM__index(VM* self) {
  28863. for(int i = 0; i < 16; i++) {
  28864. if(pk_all_vm[i] == self) return i;
  28865. }
  28866. return -1;
  28867. }
  28868. int py_currentvm() { return VM__index(pk_current_vm); }
  28869. void py_switchvm(int index) {
  28870. if(index < 0 || index >= 16) c11__abort("invalid vm index");
  28871. if(!pk_all_vm[index]) {
  28872. pk_current_vm = pk_all_vm[index] = PK_MALLOC(sizeof(VM));
  28873. memset(pk_current_vm, 0, sizeof(VM));
  28874. VM__ctor(pk_all_vm[index]);
  28875. } else {
  28876. pk_current_vm = pk_all_vm[index];
  28877. }
  28878. }
  28879. void py_resetvm() {
  28880. VM* vm = pk_current_vm;
  28881. VM__dtor(vm);
  28882. memset(vm, 0, sizeof(VM));
  28883. VM__ctor(vm);
  28884. }
  28885. void py_resetallvm() {
  28886. for(int i = 0; i < 16; i++) {
  28887. py_switchvm(i);
  28888. py_resetvm();
  28889. }
  28890. py_switchvm(0);
  28891. }
  28892. void* py_getvmctx() { return pk_current_vm->ctx; }
  28893. void py_setvmctx(void* ctx) { pk_current_vm->ctx = ctx; }
  28894. py_Callbacks* py_callbacks() { return &pk_current_vm->callbacks; }
  28895. py_AppCallbacks* py_appcallbacks() {
  28896. static py_AppCallbacks _callbacks = {0};
  28897. return &_callbacks;
  28898. }
  28899. /////////////////////////////
  28900. void py_sys_setargv(int argc, char** argv) {
  28901. py_GlobalRef sys = py_getmodule("sys");
  28902. py_Ref argv_list = py_getdict(sys, py_name("argv"));
  28903. py_list_clear(argv_list);
  28904. for(int i = 1; i < argc; i++) {
  28905. py_newstr(py_list_emplace(argv_list), argv[i]);
  28906. }
  28907. }
  28908. void py_sys_settrace(py_TraceFunc func, bool reset) {
  28909. TraceInfo* info = &pk_current_vm->trace_info;
  28910. info->func = func;
  28911. if(!reset) return;
  28912. if(info->prev_loc.src) {
  28913. PK_DECREF(info->prev_loc.src);
  28914. info->prev_loc.src = NULL;
  28915. }
  28916. info->prev_loc.lineno = -1;
  28917. }
  28918. int py_gc_collect() {
  28919. ManagedHeap* heap = &pk_current_vm->heap;
  28920. return ManagedHeap__collect(heap);
  28921. }
  28922. /////////////////////////////
  28923. void* py_malloc(size_t size) { return PK_MALLOC(size); }
  28924. void* py_realloc(void* ptr, size_t size) { return PK_REALLOC(ptr, size); }
  28925. void py_free(void* ptr) { PK_FREE(ptr); }
  28926. /////////////////////////////
  28927. py_GlobalRef py_True() { return &_True; }
  28928. py_GlobalRef py_False() { return &_False; }
  28929. py_GlobalRef py_None() { return &_None; }
  28930. py_GlobalRef py_NIL() { return &_NIL; }
  28931. /////////////////////////////
  28932. const char* pk_opname(Opcode op) {
  28933. const static char* OP_NAMES[] = {
  28934. #define OPCODE(name) #name,
  28935. #ifdef OPCODE
  28936. /**************************/
  28937. OPCODE(NO_OP)
  28938. /**************************/
  28939. OPCODE(POP_TOP)
  28940. OPCODE(DUP_TOP)
  28941. OPCODE(DUP_TOP_TWO)
  28942. OPCODE(ROT_TWO)
  28943. OPCODE(ROT_THREE)
  28944. OPCODE(PRINT_EXPR)
  28945. /**************************/
  28946. OPCODE(LOAD_CONST)
  28947. OPCODE(LOAD_NONE)
  28948. OPCODE(LOAD_TRUE)
  28949. OPCODE(LOAD_FALSE)
  28950. /**************************/
  28951. OPCODE(LOAD_SMALL_INT)
  28952. OPCODE(LOAD_NAME_AS_INT)
  28953. /**************************/
  28954. OPCODE(LOAD_ELLIPSIS)
  28955. OPCODE(LOAD_FUNCTION)
  28956. OPCODE(LOAD_NULL)
  28957. /**************************/
  28958. OPCODE(LOAD_FAST)
  28959. OPCODE(LOAD_NAME)
  28960. OPCODE(LOAD_NONLOCAL)
  28961. OPCODE(LOAD_GLOBAL)
  28962. OPCODE(LOAD_ATTR)
  28963. OPCODE(LOAD_SELF_ATTR)
  28964. OPCODE(LOAD_CLASS_GLOBAL)
  28965. OPCODE(LOAD_METHOD)
  28966. OPCODE(LOAD_SUBSCR)
  28967. OPCODE(STORE_FAST)
  28968. OPCODE(STORE_NAME)
  28969. OPCODE(STORE_GLOBAL)
  28970. OPCODE(STORE_ATTR)
  28971. OPCODE(STORE_SELF_ATTR)
  28972. OPCODE(STORE_SUBSCR)
  28973. OPCODE(DELETE_FAST)
  28974. OPCODE(DELETE_NAME)
  28975. OPCODE(DELETE_GLOBAL)
  28976. OPCODE(DELETE_ATTR)
  28977. OPCODE(DELETE_SUBSCR)
  28978. /**************************/
  28979. OPCODE(BUILD_IMAG)
  28980. OPCODE(BUILD_BYTES)
  28981. OPCODE(BUILD_TUPLE)
  28982. OPCODE(BUILD_LIST)
  28983. OPCODE(BUILD_DICT)
  28984. OPCODE(BUILD_SET)
  28985. OPCODE(BUILD_SLICE)
  28986. OPCODE(BUILD_STRING)
  28987. /**************************/
  28988. OPCODE(BINARY_ADD)
  28989. OPCODE(BINARY_SUB)
  28990. OPCODE(BINARY_MUL)
  28991. OPCODE(BINARY_TRUEDIV)
  28992. OPCODE(BINARY_FLOORDIV)
  28993. OPCODE(BINARY_MOD)
  28994. OPCODE(BINARY_POW)
  28995. OPCODE(BINARY_LSHIFT)
  28996. OPCODE(BINARY_RSHIFT)
  28997. OPCODE(BINARY_AND)
  28998. OPCODE(BINARY_OR)
  28999. OPCODE(BINARY_XOR)
  29000. OPCODE(BINARY_MATMUL)
  29001. OPCODE(COMPARE_LT)
  29002. OPCODE(COMPARE_LE)
  29003. OPCODE(COMPARE_EQ)
  29004. OPCODE(COMPARE_NE)
  29005. OPCODE(COMPARE_GT)
  29006. OPCODE(COMPARE_GE)
  29007. OPCODE(IS_OP)
  29008. OPCODE(CONTAINS_OP)
  29009. /**************************/
  29010. OPCODE(JUMP_FORWARD)
  29011. OPCODE(POP_JUMP_IF_NOT_MATCH)
  29012. OPCODE(POP_JUMP_IF_FALSE)
  29013. OPCODE(POP_JUMP_IF_TRUE)
  29014. OPCODE(JUMP_IF_TRUE_OR_POP)
  29015. OPCODE(JUMP_IF_FALSE_OR_POP)
  29016. OPCODE(SHORTCUT_IF_FALSE_OR_POP)
  29017. OPCODE(LOOP_CONTINUE)
  29018. OPCODE(LOOP_BREAK)
  29019. /**************************/
  29020. OPCODE(CALL)
  29021. OPCODE(CALL_VARGS)
  29022. /**************************/
  29023. OPCODE(RETURN_VALUE)
  29024. OPCODE(YIELD_VALUE)
  29025. OPCODE(FOR_ITER_YIELD_VALUE)
  29026. /**************************/
  29027. OPCODE(LIST_APPEND)
  29028. OPCODE(DICT_ADD)
  29029. OPCODE(SET_ADD)
  29030. /**************************/
  29031. OPCODE(UNARY_NEGATIVE)
  29032. OPCODE(UNARY_NOT)
  29033. OPCODE(UNARY_STAR)
  29034. OPCODE(UNARY_INVERT)
  29035. /**************************/
  29036. OPCODE(GET_ITER)
  29037. OPCODE(FOR_ITER)
  29038. /**************************/
  29039. OPCODE(IMPORT_PATH)
  29040. OPCODE(POP_IMPORT_STAR)
  29041. /**************************/
  29042. OPCODE(UNPACK_SEQUENCE)
  29043. OPCODE(UNPACK_EX)
  29044. /**************************/
  29045. OPCODE(BEGIN_CLASS)
  29046. OPCODE(END_CLASS)
  29047. OPCODE(STORE_CLASS_ATTR)
  29048. OPCODE(ADD_CLASS_ANNOTATION)
  29049. /**************************/
  29050. OPCODE(WITH_ENTER)
  29051. OPCODE(WITH_EXIT)
  29052. /**************************/
  29053. OPCODE(BEGIN_TRY)
  29054. OPCODE(END_TRY)
  29055. OPCODE(EXCEPTION_MATCH)
  29056. OPCODE(HANDLE_EXCEPTION)
  29057. OPCODE(RAISE)
  29058. OPCODE(RAISE_ASSERT)
  29059. OPCODE(RE_RAISE)
  29060. OPCODE(PUSH_EXCEPTION)
  29061. /**************************/
  29062. OPCODE(FORMAT_STRING)
  29063. /**************************/
  29064. #endif
  29065. #undef OPCODE
  29066. };
  29067. return OP_NAMES[op];
  29068. }
  29069. // src/public\Inspection.c
  29070. py_StackRef py_inspect_currentfunction() {
  29071. VM* vm = pk_current_vm;
  29072. if(vm->curr_function >= vm->stack.sp) return NULL;
  29073. return vm->curr_function;
  29074. }
  29075. py_GlobalRef py_inspect_currentmodule() {
  29076. py_Frame* frame = pk_current_vm->top_frame;
  29077. if(!frame) return NULL;
  29078. return frame->module;
  29079. }
  29080. py_Frame* py_inspect_currentframe() { return pk_current_vm->top_frame; }
  29081. void py_newglobals(py_OutRef out) {
  29082. py_Frame* frame = pk_current_vm->top_frame;
  29083. py_Frame_newglobals(frame, out);
  29084. }
  29085. void py_newlocals(py_OutRef out) {
  29086. py_Frame* frame = pk_current_vm->top_frame;
  29087. py_Frame_newlocals(frame, out);
  29088. }
  29089. // src/public\ModuleSystem.c
  29090. py_Ref py_getmodule(const char* path) {
  29091. VM* vm = pk_current_vm;
  29092. return BinTree__try_get(&vm->modules, (void*)path);
  29093. }
  29094. static py_Ref pk_newmodule(const char* path, bool is_init) {
  29095. c11_sv pathv = {path, strlen(path)};
  29096. if(pathv.size > PK_MAX_MODULE_PATH_LEN) c11__abort("module path too long: %s", path);
  29097. if(pathv.size == 0) c11__abort("module path cannot be empty");
  29098. py_ModuleInfo* mi = py_newobject(py_retval(), tp_module, -1, sizeof(py_ModuleInfo));
  29099. int last_dot = c11_sv__rindex(pathv, '.');
  29100. if(last_dot == -1 || is_init) {
  29101. mi->package = c11_string__new(path);
  29102. } else {
  29103. // a.b.c -> a.b
  29104. mi->package = c11_string__new2(path, last_dot);
  29105. }
  29106. mi->path = c11_string__new(path);
  29107. path = mi->path->data;
  29108. // we do not allow override in order to avoid memory leak
  29109. // it is because Module objects are not garbage collected
  29110. bool exists = BinTree__contains(&pk_current_vm->modules, (void*)path);
  29111. if(exists) c11__abort("module '%s' already exists", path);
  29112. BinTree__set(&pk_current_vm->modules, (void*)path, py_retval());
  29113. py_GlobalRef retval = py_getmodule(path);
  29114. mi->self = retval;
  29115. // setup __name__
  29116. py_newstrv(py_emplacedict(retval, __name__), c11_string__sv(mi->path));
  29117. // setup __package__
  29118. py_newstrv(py_emplacedict(retval, __package__), c11_string__sv(mi->package));
  29119. return retval;
  29120. }
  29121. py_Ref py_newmodule(const char* path) {
  29122. return pk_newmodule(path, false);
  29123. }
  29124. static void py_ModuleInfo__dtor(py_ModuleInfo* mi) {
  29125. c11_string__delete(mi->package);
  29126. c11_string__delete(mi->path);
  29127. }
  29128. static bool module__repr__(int argc, py_Ref argv) {
  29129. PY_CHECK_ARGC(1);
  29130. py_ModuleInfo* self = py_touserdata(argv);
  29131. c11_sbuf buf;
  29132. c11_sbuf__ctor(&buf);
  29133. pk_sprintf(&buf, "<module '%s'>", self->path->data);
  29134. c11_sbuf__py_submit(&buf, py_retval());
  29135. return true;
  29136. }
  29137. py_Type pk_module__register() {
  29138. py_Type type = pk_newtype("module", tp_object, NULL, (py_Dtor)py_ModuleInfo__dtor, false, true);
  29139. py_bindmagic(type, __repr__, module__repr__);
  29140. return type;
  29141. }
  29142. int load_module_from_dll_desktop_only(const char* path) PY_RAISE PY_RETURN;
  29143. int py_import(const char* path_cstr) {
  29144. VM* vm = pk_current_vm;
  29145. c11_sv path = {path_cstr, strlen(path_cstr)};
  29146. if(path.size == 0) {
  29147. ValueError("empty module name");
  29148. return -1;
  29149. }
  29150. if(path.size > PK_MAX_MODULE_PATH_LEN) {
  29151. ValueError("module name too long: %v", path);
  29152. return -1;
  29153. }
  29154. if(path.data[0] == '.') {
  29155. c11__rtassert(vm->top_frame != NULL && vm->top_frame->module != NULL);
  29156. // try relative import
  29157. int dot_count = 1;
  29158. while(dot_count < path.size && path.data[dot_count] == '.')
  29159. dot_count++;
  29160. py_ModuleInfo* mi = py_touserdata(vm->top_frame->module);
  29161. c11_sv package_sv = c11_string__sv(mi->package);
  29162. if(package_sv.size == 0) {
  29163. ImportError("attempted relative import with no known parent package");
  29164. return -1;
  29165. }
  29166. c11_vector /* T=c11_sv */ cpnts = c11_sv__split(package_sv, '.');
  29167. for(int i = 1; i < dot_count; i++) {
  29168. if(cpnts.length == 0){
  29169. ImportError("attempted relative import beyond top-level package");
  29170. return -1;
  29171. }
  29172. c11_vector__pop(&cpnts);
  29173. }
  29174. if(dot_count < path.size) {
  29175. c11_sv last_cpnt = c11_sv__slice(path, dot_count);
  29176. c11_vector__push(c11_sv, &cpnts, last_cpnt);
  29177. }
  29178. // join cpnts
  29179. c11_sbuf buf;
  29180. c11_sbuf__ctor(&buf);
  29181. for(int i = 0; i < cpnts.length; i++) {
  29182. if(i > 0) c11_sbuf__write_char(&buf, '.');
  29183. c11_sbuf__write_sv(&buf, c11__getitem(c11_sv, &cpnts, i));
  29184. }
  29185. c11_vector__dtor(&cpnts);
  29186. c11_string* new_path = c11_sbuf__submit(&buf);
  29187. int res = py_import(new_path->data);
  29188. c11_string__delete(new_path);
  29189. return res;
  29190. }
  29191. c11__rtassert(path.data[0] != '.' && path.data[path.size - 1] != '.');
  29192. // import parent module (implicit recursion)
  29193. int last_dot_index = c11_sv__rindex(path, '.');
  29194. if(last_dot_index >= 0) {
  29195. c11_sv ppath = c11_sv__slice2(path, 0, last_dot_index);
  29196. py_GlobalRef ext_mod = py_getmodule(ppath.data);
  29197. if(!ext_mod) {
  29198. char buf[PK_MAX_MODULE_PATH_LEN + 1];
  29199. memcpy(buf, ppath.data, ppath.size);
  29200. buf[ppath.size] = '\0';
  29201. int res = py_import(buf);
  29202. if(res != 1) return res;
  29203. py_newnil(py_retval());
  29204. }
  29205. }
  29206. // check existing module
  29207. py_GlobalRef ext_mod = py_getmodule(path.data);
  29208. if(ext_mod) {
  29209. py_assign(py_retval(), ext_mod);
  29210. return 1;
  29211. }
  29212. if(vm->callbacks.lazyimport) {
  29213. py_GlobalRef lazymod = vm->callbacks.lazyimport(path_cstr);
  29214. if(lazymod) {
  29215. c11__rtassert(py_istype(lazymod, tp_module));
  29216. py_assign(py_retval(), lazymod);
  29217. return 1;
  29218. }
  29219. }
  29220. // try import
  29221. c11_string* slashed_path = c11_sv__replace(path, '.', PK_PLATFORM_SEP);
  29222. c11_string* filename = c11_string__new3("%s.py", slashed_path->data);
  29223. bool need_free = true;
  29224. bool is_pyc = false;
  29225. bool is_init = false;
  29226. const char* data = load_kPythonLib(path_cstr);
  29227. int data_size = -1;
  29228. if(data != NULL) {
  29229. need_free = false;
  29230. goto __SUCCESS;
  29231. }
  29232. data = vm->callbacks.importfile(filename->data, &data_size);
  29233. if(data != NULL) goto __SUCCESS;
  29234. c11_string__delete(filename);
  29235. filename = c11_string__new3("%s.pyc", slashed_path->data);
  29236. data = vm->callbacks.importfile(filename->data, &data_size);
  29237. if(data != NULL) {
  29238. is_pyc = true;
  29239. goto __SUCCESS;
  29240. }
  29241. c11_string__delete(filename);
  29242. filename = c11_string__new3("%s%c__init__.py", slashed_path->data, PK_PLATFORM_SEP);
  29243. data = vm->callbacks.importfile(filename->data, &data_size);
  29244. if(data != NULL) {
  29245. is_init = true;
  29246. goto __SUCCESS;
  29247. }
  29248. c11_string__delete(filename);
  29249. filename = c11_string__new3("%s%c__init__.pyc", slashed_path->data, PK_PLATFORM_SEP);
  29250. data = vm->callbacks.importfile(filename->data, &data_size);
  29251. if(data != NULL) {
  29252. is_pyc = true;
  29253. is_init = true;
  29254. goto __SUCCESS;
  29255. }
  29256. c11_string__delete(filename);
  29257. c11_string__delete(slashed_path);
  29258. // not found
  29259. return load_module_from_dll_desktop_only(path_cstr);
  29260. __SUCCESS:
  29261. do {
  29262. } while(0);
  29263. py_GlobalRef mod = pk_newmodule(path_cstr, is_init);
  29264. bool ok;
  29265. if(is_pyc) {
  29266. ok = py_execo(data, data_size, filename->data, mod);
  29267. } else {
  29268. ok = py_exec(data, filename->data, EXEC_MODE, mod);
  29269. }
  29270. py_assign(py_retval(), mod);
  29271. c11_string__delete(filename);
  29272. c11_string__delete(slashed_path);
  29273. if(need_free) PK_FREE((void*)data);
  29274. return ok ? 1 : -1;
  29275. }
  29276. bool py_importlib_reload(py_Ref module) {
  29277. VM* vm = pk_current_vm;
  29278. py_ModuleInfo* mi = py_touserdata(module);
  29279. // We should ensure that the module is its original py_GlobalRef
  29280. module = mi->self;
  29281. c11_sv path = c11_string__sv(mi->path);
  29282. c11_string* slashed_path = c11_sv__replace(path, '.', PK_PLATFORM_SEP);
  29283. c11_string* filename = c11_string__new3("%s.py", slashed_path->data);
  29284. // Here we only consider source modules.
  29285. // Because compiled modules have no source file (it cannot be reloaded)
  29286. char* data = vm->callbacks.importfile(filename->data, NULL);
  29287. if(data == NULL) {
  29288. c11_string__delete(filename);
  29289. filename = c11_string__new3("%s%c__init__.py", slashed_path->data, PK_PLATFORM_SEP);
  29290. data = vm->callbacks.importfile(filename->data, NULL);
  29291. }
  29292. c11_string__delete(slashed_path);
  29293. if(data == NULL) return ImportError("module '%v' not found", path);
  29294. // py_cleardict(module); BUG: removing old classes will cause RELOAD_MODE to fail
  29295. bool ok = py_exec(data, filename->data, RELOAD_MODE, module);
  29296. c11_string__delete(filename);
  29297. PK_FREE(data);
  29298. py_assign(py_retval(), module);
  29299. return ok;
  29300. }
  29301. // src/public\PyDict.c
  29302. typedef struct {
  29303. Dict* dict; // weakref for slot 0
  29304. Dict dict_backup;
  29305. DictEntry* curr;
  29306. DictEntry* end;
  29307. int mode; // 0: keys, 1: values, 2: items
  29308. } DictIterator;
  29309. #define Dict__step(x) ((x) < mask ? (x) + 1 : 0)
  29310. static uint32_t Dict__next_cap(uint32_t cap) {
  29311. switch(cap) {
  29312. case 7: return 17;
  29313. case 17: return 37;
  29314. case 37: return 79;
  29315. case 79: return 163;
  29316. case 163: return 331;
  29317. case 331: return 673;
  29318. case 673: return 1361;
  29319. case 1361: return 2053;
  29320. case 2053: return 3083;
  29321. case 3083: return 4637;
  29322. case 4637: return 6959;
  29323. case 6959: return 10453;
  29324. case 10453: return 15683;
  29325. case 15683: return 23531;
  29326. case 23531: return 35311;
  29327. case 35311: return 52967;
  29328. case 52967: return 79451;
  29329. case 79451: return 119179;
  29330. case 119179: return 178781;
  29331. case 178781: return 268189;
  29332. case 268189: return 402299;
  29333. case 402299: return 603457;
  29334. case 603457: return 905189;
  29335. case 905189: return 1357787;
  29336. case 1357787: return 2036687;
  29337. case 2036687: return 3055043;
  29338. case 3055043: return 4582577;
  29339. case 4582577: return 6873871;
  29340. case 6873871: return 10310819;
  29341. case 10310819: return 15466229;
  29342. case 15466229: return 23199347;
  29343. case 23199347: return 34799021;
  29344. case 34799021: return 52198537;
  29345. case 52198537: return 78297827;
  29346. case 78297827: return 117446801;
  29347. case 117446801: return 176170229;
  29348. case 176170229: return 264255353;
  29349. case 264255353: return 396383041;
  29350. case 396383041: return 594574583;
  29351. case 594574583: return 891861923;
  29352. default: c11__unreachable();
  29353. }
  29354. }
  29355. static uint64_t Dict__hash_2nd(uint64_t key) {
  29356. // https://gist.github.com/badboy/6267743
  29357. key = (~key) + (key << 21); // key = (key << 21) - key - 1
  29358. key = key ^ (key >> 24);
  29359. key = (key + (key << 3)) + (key << 8); // key * 265
  29360. key = key ^ (key >> 14);
  29361. key = (key + (key << 2)) + (key << 4); // key * 21
  29362. key = key ^ (key >> 28);
  29363. key = key + (key << 31);
  29364. return key;
  29365. }
  29366. static void Dict__ctor(Dict* self, uint32_t capacity, int entries_capacity) {
  29367. self->length = 0;
  29368. self->capacity = capacity;
  29369. size_t indices_size;
  29370. if(self->capacity < UINT16_MAX) {
  29371. self->index_is_short = true;
  29372. indices_size = self->capacity * sizeof(uint16_t);
  29373. self->null_index_value = UINT16_MAX;
  29374. } else {
  29375. self->index_is_short = false;
  29376. indices_size = self->capacity * sizeof(uint32_t);
  29377. self->null_index_value = UINT32_MAX;
  29378. }
  29379. self->indices = PK_MALLOC(indices_size);
  29380. memset(self->indices, -1, indices_size);
  29381. c11_vector__ctor(&self->entries, sizeof(DictEntry));
  29382. c11_vector__reserve(&self->entries, entries_capacity);
  29383. }
  29384. static void Dict__dtor(Dict* self) {
  29385. self->length = 0;
  29386. self->capacity = 0;
  29387. PK_FREE(self->indices);
  29388. c11_vector__dtor(&self->entries);
  29389. }
  29390. static uint32_t Dict__get_index(Dict* self, uint32_t index) {
  29391. if(self->index_is_short) {
  29392. uint16_t* indices = self->indices;
  29393. return indices[index];
  29394. } else {
  29395. uint32_t* indices = self->indices;
  29396. return indices[index];
  29397. }
  29398. }
  29399. static void Dict__swap_null_index(Dict* self, uint32_t pre_z, uint32_t z) {
  29400. if(self->index_is_short) {
  29401. uint16_t* indices = self->indices;
  29402. assert(indices[pre_z] == UINT16_MAX);
  29403. indices[pre_z] = indices[z];
  29404. indices[z] = UINT16_MAX;
  29405. } else {
  29406. uint32_t* indices = self->indices;
  29407. assert(indices[pre_z] == UINT32_MAX);
  29408. indices[pre_z] = indices[z];
  29409. indices[z] = UINT32_MAX;
  29410. }
  29411. }
  29412. static void Dict__set_index(Dict* self, uint32_t index, uint32_t value) {
  29413. if(self->index_is_short) {
  29414. uint16_t* indices = self->indices;
  29415. indices[index] = (uint16_t)value;
  29416. } else {
  29417. uint32_t* indices = self->indices;
  29418. indices[index] = value;
  29419. }
  29420. }
  29421. // Dict__probe won't raise exception for string keys
  29422. static bool Dict__probe(Dict* self,
  29423. py_TValue* key,
  29424. uint64_t* p_hash,
  29425. uint32_t* p_idx,
  29426. DictEntry** p_entry) {
  29427. if(py_isstr(key)) {
  29428. *p_hash = c11_sv__hash(py_tosv(key));
  29429. } else {
  29430. py_i64 h_user;
  29431. if(!py_hash(key, &h_user)) return false;
  29432. *p_hash = Dict__hash_2nd((uint64_t)h_user);
  29433. }
  29434. uint32_t mask = self->capacity - 1;
  29435. uint32_t idx = (*p_hash) % self->capacity;
  29436. while(true) {
  29437. uint32_t idx2 = Dict__get_index(self, idx);
  29438. if(idx2 == self->null_index_value) break;
  29439. DictEntry* entry = c11__at(DictEntry, &self->entries, idx2);
  29440. if(entry->hash == (*p_hash)) {
  29441. if(py_isstr(&entry->key) && py_isstr(key)) {
  29442. c11_sv lhs = py_tosv(&entry->key);
  29443. c11_sv rhs = py_tosv(key);
  29444. if(c11__sveq(lhs, rhs)) {
  29445. *p_idx = idx;
  29446. *p_entry = entry;
  29447. return true;
  29448. }
  29449. } else {
  29450. int res = py_equal(&entry->key, key);
  29451. if(res == 1) {
  29452. *p_idx = idx;
  29453. *p_entry = entry;
  29454. return true;
  29455. }
  29456. if(res == -1) return false; // error
  29457. }
  29458. }
  29459. // try next index
  29460. idx = Dict__step(idx);
  29461. }
  29462. // not found
  29463. *p_idx = idx;
  29464. *p_entry = NULL;
  29465. return true;
  29466. }
  29467. static bool Dict__try_get(Dict* self, py_TValue* key, DictEntry** out) {
  29468. uint64_t hash;
  29469. uint32_t idx;
  29470. return Dict__probe(self, key, &hash, &idx, out);
  29471. }
  29472. static void Dict__clear(Dict* self) {
  29473. size_t indices_size = self->index_is_short ? self->capacity * sizeof(uint16_t)
  29474. : self->capacity * sizeof(uint32_t);
  29475. memset(self->indices, -1, indices_size);
  29476. c11_vector__clear(&self->entries);
  29477. self->length = 0;
  29478. }
  29479. static void Dict__rehash_2x(Dict* self) {
  29480. Dict old_dict = *self;
  29481. uint32_t new_capacity = Dict__next_cap(old_dict.capacity);
  29482. uint32_t mask = new_capacity - 1;
  29483. // create a new dict with new capacity
  29484. Dict__ctor(self, new_capacity, old_dict.entries.capacity);
  29485. // move entries from old dict to new dict
  29486. for(int i = 0; i < old_dict.entries.length; i++) {
  29487. DictEntry* old_entry = c11__at(DictEntry, &old_dict.entries, i);
  29488. if(py_isnil(&old_entry->key)) continue; // skip deleted
  29489. uint32_t idx = old_entry->hash % new_capacity;
  29490. while(true) {
  29491. uint32_t idx2 = Dict__get_index(self, idx);
  29492. if(idx2 == self->null_index_value) {
  29493. c11_vector__push(DictEntry, &self->entries, *old_entry);
  29494. Dict__set_index(self, idx, self->entries.length - 1);
  29495. self->length++;
  29496. break;
  29497. }
  29498. // try next index
  29499. idx = Dict__step(idx);
  29500. }
  29501. }
  29502. Dict__dtor(&old_dict);
  29503. }
  29504. static void Dict__compact_entries(Dict* self) {
  29505. uint32_t* mappings = PK_MALLOC(self->entries.length * sizeof(uint32_t));
  29506. int n = 0;
  29507. for(int i = 0; i < self->entries.length; i++) {
  29508. DictEntry* entry = c11__at(DictEntry, &self->entries, i);
  29509. if(py_isnil(&entry->key)) continue;
  29510. mappings[i] = n;
  29511. if(i != n) {
  29512. DictEntry* new_entry = c11__at(DictEntry, &self->entries, n);
  29513. *new_entry = *entry;
  29514. }
  29515. n++;
  29516. }
  29517. self->entries.length = n;
  29518. // update indices
  29519. for(uint32_t idx = 0; idx < self->capacity; idx++) {
  29520. uint32_t idx2 = Dict__get_index(self, idx);
  29521. if(idx2 == self->null_index_value) continue;
  29522. Dict__set_index(self, idx, mappings[idx2]);
  29523. }
  29524. PK_FREE(mappings);
  29525. }
  29526. static bool Dict__set(Dict* self, py_TValue* key, py_TValue* val) {
  29527. uint64_t hash;
  29528. uint32_t idx;
  29529. DictEntry* entry;
  29530. if(!Dict__probe(self, key, &hash, &idx, &entry)) return false;
  29531. if(entry) {
  29532. // update existing entry
  29533. entry->val = *val;
  29534. return true;
  29535. }
  29536. // insert new entry
  29537. DictEntry* new_entry = c11_vector__emplace(&self->entries);
  29538. new_entry->hash = hash;
  29539. new_entry->key = *key;
  29540. new_entry->val = *val;
  29541. Dict__set_index(self, idx, self->entries.length - 1);
  29542. self->length++;
  29543. // check if we need to rehash
  29544. float load_factor = (float)self->length / self->capacity;
  29545. if(load_factor > (self->index_is_short ? 0.3f : 0.4f)) Dict__rehash_2x(self);
  29546. return true;
  29547. }
  29548. /// Delete an entry from the dict.
  29549. /// -1: error, 0: not found, 1: found and deleted
  29550. static int Dict__pop(Dict* self, py_Ref key) {
  29551. // Dict__log_index(self, "before pop");
  29552. uint64_t hash;
  29553. uint32_t idx;
  29554. DictEntry* entry;
  29555. if(!Dict__probe(self, key, &hash, &idx, &entry)) return -1;
  29556. if(!entry) return 0; // not found
  29557. // found the entry, delete and return it
  29558. py_assign(py_retval(), &entry->val);
  29559. Dict__set_index(self, idx, self->null_index_value);
  29560. py_newnil(&entry->key);
  29561. py_newnil(&entry->val);
  29562. self->length--;
  29563. /* tidy */
  29564. // https://github.com/OpenHFT/Chronicle-Map/blob/820573a68471509ffc1b0584454f4a67c0be1b84/src/main/java/net/openhft/chronicle/hash/impl/CompactOffHeapLinearHashTable.java#L156
  29565. uint32_t mask = self->capacity - 1;
  29566. uint32_t posToRemove = idx;
  29567. uint32_t posToShift = posToRemove;
  29568. // int probe_count = 0;
  29569. // int swap_count = 0;
  29570. while(true) {
  29571. posToShift = Dict__step(posToShift);
  29572. uint32_t idx_z = Dict__get_index(self, posToShift);
  29573. if(idx_z == self->null_index_value) break;
  29574. uint64_t hash_z = c11__at(DictEntry, &self->entries, idx_z)->hash;
  29575. uint32_t insertPos = (uint64_t)hash_z % self->capacity;
  29576. // the following condition essentially means circular permutations
  29577. // of three (r = posToRemove, s = posToShift, i = insertPos)
  29578. // positions are accepted:
  29579. // [...i..r...s.] or
  29580. // [...r..s...i.] or
  29581. // [...s..i...r.]
  29582. bool cond1 = insertPos <= posToRemove;
  29583. bool cond2 = posToRemove <= posToShift;
  29584. if((cond1 && cond2) ||
  29585. // chain wrapped around capacity
  29586. (posToShift < insertPos && (cond1 || cond2))) {
  29587. Dict__swap_null_index(self, posToRemove, posToShift);
  29588. posToRemove = posToShift;
  29589. // swap_count++;
  29590. }
  29591. // probe_count++;
  29592. }
  29593. // printf("Dict__pop: probe_count=%d, swap_count=%d\n", probe_count, swap_count);
  29594. // compact entries if necessary
  29595. if(self->entries.length > 16 && (self->length < self->entries.length >> 1)) {
  29596. Dict__compact_entries(self); // compact entries
  29597. }
  29598. // Dict__log_index(self, "after pop");
  29599. return 1;
  29600. }
  29601. static void DictIterator__ctor(DictIterator* self, Dict* dict, int mode) {
  29602. assert(mode >= 0 && mode <= 2);
  29603. self->dict = dict;
  29604. self->dict_backup = *dict; // backup the dict
  29605. self->curr = dict->entries.data;
  29606. self->end = self->curr + dict->entries.length;
  29607. self->mode = mode;
  29608. }
  29609. static DictEntry* DictIterator__next(DictIterator* self) {
  29610. DictEntry* retval;
  29611. do {
  29612. if(self->curr == self->end) return NULL;
  29613. retval = self->curr++;
  29614. } while(py_isnil(&retval->key));
  29615. return retval;
  29616. }
  29617. static bool DictIterator__modified(DictIterator* self) {
  29618. return memcmp(self->dict, &self->dict_backup, sizeof(Dict)) != 0;
  29619. }
  29620. ///////////////////////////////
  29621. static bool dict__new__(int argc, py_Ref argv) {
  29622. py_Type cls = py_totype(argv);
  29623. int slots = cls == tp_dict ? 0 : -1;
  29624. Dict* ud = py_newobject(py_retval(), cls, slots, sizeof(Dict));
  29625. Dict__ctor(ud, 17, 4);
  29626. return true;
  29627. }
  29628. void py_newdict(py_OutRef out) {
  29629. Dict* ud = py_newobject(out, tp_dict, 0, sizeof(Dict));
  29630. Dict__ctor(ud, 17, 4);
  29631. }
  29632. static bool dict__init__(int argc, py_Ref argv) {
  29633. if(argc > 2) return TypeError("dict.__init__() takes at most 2 arguments (%d given)", argc);
  29634. if(argc == 1) {
  29635. py_newnone(py_retval());
  29636. return true;
  29637. }
  29638. assert(argc == 2);
  29639. py_TValue* p;
  29640. int length = pk_arrayview(py_arg(1), &p);
  29641. if(length == -1) { return TypeError("dict.__init__() expects a list or tuple"); }
  29642. Dict* self = py_touserdata(argv);
  29643. for(int i = 0; i < length; i++) {
  29644. py_Ref tuple = &p[i];
  29645. if(!py_istuple(tuple) || py_tuple_len(tuple) != 2) {
  29646. return ValueError("dict.__init__() argument must be a list of tuple-2");
  29647. }
  29648. py_Ref key = py_tuple_getitem(tuple, 0);
  29649. py_Ref val = py_tuple_getitem(tuple, 1);
  29650. if(!Dict__set(self, key, val)) return false;
  29651. }
  29652. py_newnone(py_retval());
  29653. return true;
  29654. }
  29655. static bool dict__getitem__(int argc, py_Ref argv) {
  29656. PY_CHECK_ARGC(2);
  29657. Dict* self = py_touserdata(argv);
  29658. DictEntry* entry;
  29659. if(!Dict__try_get(self, py_arg(1), &entry)) return false;
  29660. if(entry) {
  29661. *py_retval() = entry->val;
  29662. return true;
  29663. }
  29664. // try __missing__
  29665. py_Ref missing = py_tpfindmagic(argv->type, __missing__);
  29666. if(missing) return py_call(missing, argc, argv);
  29667. return KeyError(py_arg(1));
  29668. }
  29669. static bool dict__setitem__(int argc, py_Ref argv) {
  29670. PY_CHECK_ARGC(3);
  29671. Dict* self = py_touserdata(argv);
  29672. bool ok = Dict__set(self, py_arg(1), py_arg(2));
  29673. if(ok) py_newnone(py_retval());
  29674. return ok;
  29675. }
  29676. static bool dict__delitem__(int argc, py_Ref argv) {
  29677. PY_CHECK_ARGC(2);
  29678. Dict* self = py_touserdata(argv);
  29679. int res = Dict__pop(self, py_arg(1));
  29680. if(res == 1) {
  29681. py_newnone(py_retval());
  29682. return true;
  29683. }
  29684. if(res == 0) return KeyError(py_arg(1));
  29685. return false;
  29686. }
  29687. static bool dict__contains__(int argc, py_Ref argv) {
  29688. PY_CHECK_ARGC(2);
  29689. Dict* self = py_touserdata(argv);
  29690. DictEntry* entry;
  29691. if(!Dict__try_get(self, py_arg(1), &entry)) return false;
  29692. py_newbool(py_retval(), entry != NULL);
  29693. return true;
  29694. }
  29695. static bool dict__len__(int argc, py_Ref argv) {
  29696. PY_CHECK_ARGC(1);
  29697. Dict* self = py_touserdata(argv);
  29698. py_newint(py_retval(), self->length);
  29699. return true;
  29700. }
  29701. static bool dict__repr__(int argc, py_Ref argv) {
  29702. PY_CHECK_ARGC(1);
  29703. Dict* self = py_touserdata(argv);
  29704. c11_sbuf buf;
  29705. c11_sbuf__ctor(&buf);
  29706. c11_sbuf__write_char(&buf, '{');
  29707. bool is_first = true;
  29708. for(int i = 0; i < self->entries.length; i++) {
  29709. DictEntry* entry = c11__at(DictEntry, &self->entries, i);
  29710. if(py_isnil(&entry->key)) continue;
  29711. if(!is_first) c11_sbuf__write_cstr(&buf, ", ");
  29712. if(!py_repr(&entry->key)) return false;
  29713. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  29714. c11_sbuf__write_cstr(&buf, ": ");
  29715. if(!py_repr(&entry->val)) return false;
  29716. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  29717. is_first = false;
  29718. }
  29719. c11_sbuf__write_char(&buf, '}');
  29720. c11_sbuf__py_submit(&buf, py_retval());
  29721. return true;
  29722. }
  29723. static bool dict__eq__(int argc, py_Ref argv) {
  29724. PY_CHECK_ARGC(2);
  29725. Dict* self = py_touserdata(py_arg(0));
  29726. if(!py_isdict(py_arg(1))) {
  29727. py_newnotimplemented(py_retval());
  29728. return true;
  29729. }
  29730. Dict* other = py_touserdata(py_arg(1));
  29731. if(self->length != other->length) {
  29732. py_newbool(py_retval(), false);
  29733. return true;
  29734. }
  29735. DictIterator iter;
  29736. DictIterator__ctor(&iter, self, 2);
  29737. // for each self key
  29738. while(1) {
  29739. DictEntry* entry = DictIterator__next(&iter);
  29740. if(!entry) break;
  29741. DictEntry* other_entry;
  29742. if(!Dict__try_get(other, &entry->key, &other_entry)) return false;
  29743. if(!other_entry) {
  29744. py_newbool(py_retval(), false);
  29745. return true;
  29746. }
  29747. if(entry->hash != other_entry->hash) {
  29748. py_newbool(py_retval(), false);
  29749. return true;
  29750. }
  29751. int res = py_equal(&entry->val, &other_entry->val);
  29752. if(res == 0) {
  29753. py_newbool(py_retval(), false);
  29754. return true;
  29755. }
  29756. if(res == -1) return false; // error
  29757. }
  29758. py_newbool(py_retval(), true);
  29759. return true;
  29760. }
  29761. static bool dict__ne__(int argc, py_Ref argv) {
  29762. if(!dict__eq__(argc, argv)) return false;
  29763. if(py_isbool(py_retval())) {
  29764. bool res = py_tobool(py_retval());
  29765. py_newbool(py_retval(), !res);
  29766. }
  29767. return true;
  29768. }
  29769. static bool dict_clear(int argc, py_Ref argv) {
  29770. PY_CHECK_ARGC(1);
  29771. Dict* self = py_touserdata(argv);
  29772. Dict__clear(self);
  29773. py_newnone(py_retval());
  29774. return true;
  29775. }
  29776. static bool dict_copy(int argc, py_Ref argv) {
  29777. PY_CHECK_ARGC(1);
  29778. Dict* self = py_touserdata(argv);
  29779. Dict* new_dict = py_newobject(py_retval(), tp_dict, 0, sizeof(Dict));
  29780. new_dict->length = self->length;
  29781. new_dict->capacity = self->capacity;
  29782. new_dict->null_index_value = self->null_index_value;
  29783. new_dict->index_is_short = self->index_is_short;
  29784. // copy entries
  29785. new_dict->entries = c11_vector__copy(&self->entries);
  29786. // copy indices
  29787. size_t indices_size = self->index_is_short ? self->capacity * sizeof(uint16_t)
  29788. : self->capacity * sizeof(uint32_t);
  29789. new_dict->indices = PK_MALLOC(indices_size);
  29790. memcpy(new_dict->indices, self->indices, indices_size);
  29791. return true;
  29792. }
  29793. static bool dict_update(int argc, py_Ref argv) {
  29794. PY_CHECK_ARGC(2);
  29795. PY_CHECK_ARG_TYPE(1, tp_dict);
  29796. Dict* self = py_touserdata(argv);
  29797. Dict* other = py_touserdata(py_arg(1));
  29798. for(int i = 0; i < other->entries.length; i++) {
  29799. DictEntry* entry = c11__at(DictEntry, &other->entries, i);
  29800. if(py_isnil(&entry->key)) continue;
  29801. if(!Dict__set(self, &entry->key, &entry->val)) return false;
  29802. }
  29803. py_newnone(py_retval());
  29804. return true;
  29805. }
  29806. static bool dict_get(int argc, py_Ref argv) {
  29807. Dict* self = py_touserdata(argv);
  29808. if(argc > 3) return TypeError("get() takes at most 3 arguments (%d given)", argc);
  29809. py_Ref default_val = argc == 3 ? py_arg(2) : py_None();
  29810. DictEntry* entry;
  29811. if(!Dict__try_get(self, py_arg(1), &entry)) return false;
  29812. *py_retval() = entry ? entry->val : *default_val;
  29813. return true;
  29814. }
  29815. static bool dict_pop(int argc, py_Ref argv) {
  29816. Dict* self = py_touserdata(argv);
  29817. if(argc < 2 || argc > 3) return TypeError("pop() takes 1 or 2 arguments (%d given)", argc - 1);
  29818. py_Ref default_val = argc == 3 ? py_arg(2) : py_None();
  29819. int res = Dict__pop(self, py_arg(1));
  29820. if(res == -1) return false;
  29821. if(res == 0) py_assign(py_retval(), default_val);
  29822. return true;
  29823. }
  29824. static bool dict_popitem(int argc, py_Ref argv) {
  29825. PY_CHECK_ARGC(1);
  29826. Dict* self = py_touserdata(argv);
  29827. for(int i = self->entries.length - 1; i >= 0; i--) {
  29828. DictEntry* entry = c11__at(DictEntry, &self->entries, i);
  29829. if(py_isnil(&entry->key)) continue;
  29830. py_Ref p = py_newtuple(py_pushtmp(), 2);
  29831. p[0] = entry->key;
  29832. p[1] = entry->val;
  29833. int res = Dict__pop(self, &p[0]);
  29834. c11__rtassert(res == 1);
  29835. py_assign(py_retval(), py_peek(-1));
  29836. py_pop();
  29837. return true;
  29838. }
  29839. return KeyError(py_None());
  29840. }
  29841. static bool dict_keys(int argc, py_Ref argv) {
  29842. PY_CHECK_ARGC(1);
  29843. Dict* self = py_touserdata(argv);
  29844. DictIterator* ud = py_newobject(py_retval(), tp_dict_iterator, 1, sizeof(DictIterator));
  29845. DictIterator__ctor(ud, self, 0);
  29846. py_setslot(py_retval(), 0, argv); // keep a reference to the dict
  29847. return true;
  29848. }
  29849. static bool dict_values(int argc, py_Ref argv) {
  29850. PY_CHECK_ARGC(1);
  29851. Dict* self = py_touserdata(argv);
  29852. DictIterator* ud = py_newobject(py_retval(), tp_dict_iterator, 1, sizeof(DictIterator));
  29853. DictIterator__ctor(ud, self, 1);
  29854. py_setslot(py_retval(), 0, argv); // keep a reference to the dict
  29855. return true;
  29856. }
  29857. static bool dict_items(int argc, py_Ref argv) {
  29858. PY_CHECK_ARGC(1);
  29859. Dict* self = py_touserdata(argv);
  29860. DictIterator* ud = py_newobject(py_retval(), tp_dict_iterator, 1, sizeof(DictIterator));
  29861. DictIterator__ctor(ud, self, 2);
  29862. py_setslot(py_retval(), 0, argv); // keep a reference to the dict
  29863. return true;
  29864. }
  29865. py_Type pk_dict__register() {
  29866. py_Type type = pk_newtype("dict", tp_object, NULL, (void (*)(void*))Dict__dtor, false, false);
  29867. py_bindmagic(type, __new__, dict__new__);
  29868. py_bindmagic(type, __init__, dict__init__);
  29869. py_bindmagic(type, __getitem__, dict__getitem__);
  29870. py_bindmagic(type, __setitem__, dict__setitem__);
  29871. py_bindmagic(type, __delitem__, dict__delitem__);
  29872. py_bindmagic(type, __contains__, dict__contains__);
  29873. py_bindmagic(type, __len__, dict__len__);
  29874. py_bindmagic(type, __repr__, dict__repr__);
  29875. py_bindmagic(type, __eq__, dict__eq__);
  29876. py_bindmagic(type, __ne__, dict__ne__);
  29877. py_bindmagic(type, __iter__, dict_keys);
  29878. py_bindmethod(type, "clear", dict_clear);
  29879. py_bindmethod(type, "copy", dict_copy);
  29880. py_bindmethod(type, "update", dict_update);
  29881. py_bindmethod(type, "get", dict_get);
  29882. py_bindmethod(type, "pop", dict_pop);
  29883. py_bindmethod(type, "popitem", dict_popitem);
  29884. py_bindmethod(type, "keys", dict_keys);
  29885. py_bindmethod(type, "values", dict_values);
  29886. py_bindmethod(type, "items", dict_items);
  29887. py_setdict(py_tpobject(type), __hash__, py_None());
  29888. return type;
  29889. }
  29890. //////////////////////////
  29891. bool dict_items__next__(int argc, py_Ref argv) {
  29892. PY_CHECK_ARGC(1);
  29893. DictIterator* iter = py_touserdata(py_arg(0));
  29894. if(DictIterator__modified(iter)) return RuntimeError("dictionary modified during iteration");
  29895. DictEntry* entry = (DictIterator__next(iter));
  29896. if(entry) {
  29897. switch(iter->mode) {
  29898. case 0: // keys
  29899. py_assign(py_retval(), &entry->key);
  29900. return true;
  29901. case 1: // values
  29902. py_assign(py_retval(), &entry->val);
  29903. return true;
  29904. case 2: // items
  29905. {
  29906. py_Ref p = py_newtuple(py_retval(), 2);
  29907. p[0] = entry->key;
  29908. p[1] = entry->val;
  29909. return true;
  29910. }
  29911. default: c11__unreachable();
  29912. }
  29913. }
  29914. return StopIteration();
  29915. }
  29916. bool dict_items__len__(int argc, py_Ref argv) {
  29917. PY_CHECK_ARGC(1);
  29918. DictIterator* iter = py_touserdata(py_arg(0));
  29919. py_newint(py_retval(), iter->dict->length);
  29920. return true;
  29921. }
  29922. py_Type pk_dict_items__register() {
  29923. py_Type type = pk_newtype("dict_iterator", tp_object, NULL, NULL, false, true);
  29924. py_bindmagic(type, __iter__, pk_wrapper__self);
  29925. py_bindmagic(type, __next__, dict_items__next__);
  29926. py_bindmagic(type, __len__, dict_items__len__);
  29927. return type;
  29928. }
  29929. //////////////////////////
  29930. int py_dict_getitem(py_Ref self, py_Ref key) {
  29931. assert(py_isdict(self));
  29932. Dict* ud = py_touserdata(self);
  29933. DictEntry* entry;
  29934. if(!Dict__try_get(ud, key, &entry)) return -1;
  29935. if(entry) {
  29936. py_assign(py_retval(), &entry->val);
  29937. return 1;
  29938. }
  29939. return 0;
  29940. }
  29941. bool py_dict_setitem(py_Ref self, py_Ref key, py_Ref val) {
  29942. assert(py_isdict(self));
  29943. Dict* ud = py_touserdata(self);
  29944. return Dict__set(ud, key, val);
  29945. }
  29946. int py_dict_delitem(py_Ref self, py_Ref key) {
  29947. assert(py_isdict(self));
  29948. Dict* ud = py_touserdata(self);
  29949. return Dict__pop(ud, key);
  29950. }
  29951. int py_dict_getitem_by_str(py_Ref self, const char* key) {
  29952. py_Ref tmp = py_pushtmp();
  29953. py_newstr(tmp, key);
  29954. int res = py_dict_getitem(self, tmp);
  29955. py_pop();
  29956. return res;
  29957. }
  29958. bool py_dict_setitem_by_str(py_Ref self, const char* key, py_Ref val) {
  29959. py_Ref tmp = py_pushtmp();
  29960. py_newstr(tmp, key);
  29961. bool res = py_dict_setitem(self, tmp, val);
  29962. py_pop();
  29963. return res;
  29964. }
  29965. int py_dict_delitem_by_str(py_Ref self, const char* key) {
  29966. py_Ref tmp = py_pushtmp();
  29967. py_newstr(tmp, key);
  29968. int res = py_dict_delitem(self, tmp);
  29969. py_pop();
  29970. return res;
  29971. }
  29972. int py_dict_getitem_by_int(py_Ref self, py_i64 key) {
  29973. py_TValue tmp;
  29974. py_newint(&tmp, key);
  29975. return py_dict_getitem(self, &tmp);
  29976. }
  29977. bool py_dict_setitem_by_int(py_Ref self, py_i64 key, py_Ref val) {
  29978. py_TValue tmp;
  29979. py_newint(&tmp, key);
  29980. return py_dict_setitem(self, &tmp, val);
  29981. }
  29982. int py_dict_delitem_by_int(py_Ref self, py_i64 key) {
  29983. py_TValue tmp;
  29984. py_newint(&tmp, key);
  29985. return py_dict_delitem(self, &tmp);
  29986. }
  29987. int py_dict_len(py_Ref self) {
  29988. assert(py_isdict(self));
  29989. Dict* ud = py_touserdata(self);
  29990. return ud->length;
  29991. }
  29992. bool py_dict_apply(py_Ref self, bool (*f)(py_Ref, py_Ref, void*), void* ctx) {
  29993. Dict* ud = py_touserdata(self);
  29994. for(int i = 0; i < ud->entries.length; i++) {
  29995. DictEntry* entry = c11__at(DictEntry, &ud->entries, i);
  29996. if(py_isnil(&entry->key)) continue;
  29997. if(!f(&entry->key, &entry->val, ctx)) return false;
  29998. }
  29999. return true;
  30000. }
  30001. #undef Dict__step
  30002. // src/public\PyException.c
  30003. void py_BaseException__stpush(py_Frame* frame,
  30004. py_Ref self,
  30005. SourceData_ src,
  30006. int lineno,
  30007. const char* func_name) {
  30008. BaseException* ud = py_touserdata(self);
  30009. int max_frame_dumps = py_debugger_status() == 1 ? 31 : 7;
  30010. if(ud->stacktrace.length >= max_frame_dumps) return;
  30011. BaseExceptionFrame* frame_dump = c11_vector__emplace(&ud->stacktrace);
  30012. PK_INCREF(src);
  30013. frame_dump->src = src;
  30014. frame_dump->lineno = lineno;
  30015. frame_dump->name = func_name ? c11_string__new(func_name) : NULL;
  30016. if(py_debugger_status() == 1) {
  30017. if(frame != NULL) {
  30018. py_Frame_newlocals(frame, &frame_dump->locals);
  30019. py_Frame_newglobals(frame, &frame_dump->globals);
  30020. } else {
  30021. py_newdict(&frame_dump->locals);
  30022. py_newdict(&frame_dump->globals);
  30023. }
  30024. }
  30025. }
  30026. static void BaseException__dtor(void* ud) {
  30027. BaseException* self = (BaseException*)ud;
  30028. c11__foreach(BaseExceptionFrame, &self->stacktrace, it) {
  30029. PK_DECREF(it->src);
  30030. if(it->name) c11_string__delete(it->name);
  30031. }
  30032. c11_vector__dtor(&self->stacktrace);
  30033. }
  30034. static bool _py_BaseException__new__(int argc, py_Ref argv) {
  30035. py_Type cls = py_totype(argv);
  30036. BaseException* ud = py_newobject(py_retval(), cls, 0, sizeof(BaseException));
  30037. py_newnil(&ud->args);
  30038. py_newnil(&ud->inner_exc);
  30039. c11_vector__ctor(&ud->stacktrace, sizeof(BaseExceptionFrame));
  30040. return true;
  30041. }
  30042. static bool _py_BaseException__init__(int argc, py_Ref argv) {
  30043. BaseException* ud = py_touserdata(argv);
  30044. py_newnone(py_retval());
  30045. if(argc == 1 + 0) return true;
  30046. if(argc == 1 + 1) {
  30047. py_assign(&ud->args, &argv[1]);
  30048. return true;
  30049. }
  30050. return TypeError("__init__() takes at most 1 arguments but %d were given", argc - 1);
  30051. }
  30052. static bool _py_BaseException__repr__(int argc, py_Ref argv) {
  30053. PY_CHECK_ARGC(1);
  30054. BaseException* ud = py_touserdata(argv);
  30055. c11_sbuf ss;
  30056. c11_sbuf__ctor(&ss);
  30057. pk_sprintf(&ss, "%t(", argv->type);
  30058. py_Ref args = &ud->args;
  30059. if(!py_isnil(args)) {
  30060. if(!py_repr(args)) return false;
  30061. c11_sbuf__write_sv(&ss, py_tosv(py_retval()));
  30062. }
  30063. c11_sbuf__write_char(&ss, ')');
  30064. c11_sbuf__py_submit(&ss, py_retval());
  30065. return true;
  30066. }
  30067. static bool _py_BaseException__str__(int argc, py_Ref argv) {
  30068. PY_CHECK_ARGC(1);
  30069. BaseException* ud = py_touserdata(argv);
  30070. c11_sbuf ss;
  30071. c11_sbuf__ctor(&ss);
  30072. py_Ref args = &ud->args;
  30073. if(!py_isnil(args)) {
  30074. if(argv->type == tp_KeyError) {
  30075. if(!py_repr(args)) return false;
  30076. } else {
  30077. if(!py_str(args)) return false;
  30078. }
  30079. c11_sbuf__write_sv(&ss, py_tosv(py_retval()));
  30080. }
  30081. c11_sbuf__py_submit(&ss, py_retval());
  30082. return true;
  30083. }
  30084. static bool BaseException_args(int argc, py_Ref argv) {
  30085. BaseException* ud = py_touserdata(argv);
  30086. PY_CHECK_ARGC(1);
  30087. py_Ref args = &ud->args;
  30088. if(!py_isnil(args)) {
  30089. py_Ref p = py_newtuple(py_retval(), 1);
  30090. p[0] = *args;
  30091. } else {
  30092. py_newtuple(py_retval(), 0);
  30093. }
  30094. return true;
  30095. }
  30096. static bool StopIteration_value(int argc, py_Ref argv) {
  30097. BaseException* ud = py_touserdata(argv);
  30098. PY_CHECK_ARGC(1);
  30099. py_Ref args = &ud->args;
  30100. if(py_isnil(args)) {
  30101. py_newnone(py_retval());
  30102. } else {
  30103. py_assign(py_retval(), args);
  30104. }
  30105. return true;
  30106. }
  30107. py_Type pk_BaseException__register() {
  30108. py_Type type = pk_newtype("BaseException", tp_object, NULL, BaseException__dtor, false, false);
  30109. py_bindmagic(type, __new__, _py_BaseException__new__);
  30110. py_bindmagic(type, __init__, _py_BaseException__init__);
  30111. py_bindmagic(type, __repr__, _py_BaseException__repr__);
  30112. py_bindmagic(type, __str__, _py_BaseException__str__);
  30113. py_bindproperty(type, "args", BaseException_args, NULL);
  30114. return type;
  30115. }
  30116. py_Type pk_Exception__register() {
  30117. py_Type type = pk_newtype("Exception", tp_BaseException, NULL, NULL, false, false);
  30118. return type;
  30119. }
  30120. py_Type pk_StopIteration__register() {
  30121. py_Type type = pk_newtype("StopIteration", tp_Exception, NULL, NULL, false, false);
  30122. py_bindproperty(type, "value", StopIteration_value, NULL);
  30123. return type;
  30124. }
  30125. static void c11_sbuf__write_exc(c11_sbuf* self, py_Ref exc) {
  30126. c11_sbuf__write_cstr(self, "Traceback (most recent call last):\n");
  30127. BaseException* ud = py_touserdata(exc);
  30128. for(int i = ud->stacktrace.length - 1; i >= 0; i--) {
  30129. BaseExceptionFrame* frame = c11__at(BaseExceptionFrame, &ud->stacktrace, i);
  30130. SourceData__snapshot(frame->src,
  30131. self,
  30132. frame->lineno,
  30133. NULL,
  30134. frame->name ? frame->name->data : NULL);
  30135. c11_sbuf__write_char(self, '\n');
  30136. }
  30137. const char* name = py_tpname(exc->type);
  30138. char* message = safe_stringify_exception(exc);
  30139. c11_sbuf__write_cstr(self, name);
  30140. c11_sbuf__write_cstr(self, ": ");
  30141. c11_sbuf__write_cstr(self, message);
  30142. PK_FREE(message);
  30143. }
  30144. char* safe_stringify_exception(py_Ref exc) {
  30145. VM* vm = pk_current_vm;
  30146. const char* message = "<exception str() failed>";
  30147. py_Ref tmp = py_pushtmp();
  30148. py_Ref old_unhandled_exc = py_pushtmp();
  30149. *tmp = *exc;
  30150. *old_unhandled_exc = vm->unhandled_exc;
  30151. py_newnil(&vm->unhandled_exc);
  30152. py_StackRef p0 = py_peek(0);
  30153. bool ok = py_str(tmp);
  30154. if(ok) {
  30155. if(py_isstr(py_retval())) message = py_tostr(py_retval());
  30156. } else {
  30157. py_clearexc(p0);
  30158. }
  30159. vm->unhandled_exc = *old_unhandled_exc;
  30160. py_shrink(2);
  30161. return c11_strdup(message);
  30162. }
  30163. //////////////////////////////////////////////////
  30164. bool py_checkexc() {
  30165. VM* vm = pk_current_vm;
  30166. return !py_isnil(&vm->unhandled_exc);
  30167. }
  30168. bool py_matchexc(py_Type type) {
  30169. VM* vm = pk_current_vm;
  30170. if(py_isnil(&vm->unhandled_exc)) return false;
  30171. bool ok = py_issubclass(vm->unhandled_exc.type, type);
  30172. if(ok) vm->last_retval = vm->unhandled_exc;
  30173. return ok;
  30174. }
  30175. void py_clearexc(py_StackRef p0) {
  30176. VM* vm = pk_current_vm;
  30177. py_newnil(&vm->unhandled_exc);
  30178. if(p0) {
  30179. c11__rtassert(p0 >= vm->stack.begin && p0 <= vm->stack.sp);
  30180. vm->stack.sp = p0;
  30181. }
  30182. }
  30183. void py_printexc() {
  30184. char* msg = py_formatexc();
  30185. if(!msg) return;
  30186. pk_current_vm->callbacks.print(msg);
  30187. pk_current_vm->callbacks.print("\n");
  30188. PK_FREE(msg);
  30189. }
  30190. char* py_formatexc() {
  30191. VM* vm = pk_current_vm;
  30192. if(py_isnil(&vm->unhandled_exc)) return NULL;
  30193. char* res = formatexc_internal(&vm->unhandled_exc);
  30194. if(py_debugger_status() == 1) py_debugger_exceptionbreakpoint(&vm->unhandled_exc);
  30195. return res;
  30196. }
  30197. char* formatexc_internal(py_Ref exc) {
  30198. c11__rtassert(exc != NULL);
  30199. c11__rtassert(py_issubclass(exc->type, tp_BaseException));
  30200. c11_sbuf ss;
  30201. c11_sbuf__ctor(&ss);
  30202. BaseException* ud = py_touserdata(exc);
  30203. py_Ref inner = &ud->inner_exc;
  30204. if(py_isnil(inner)) {
  30205. c11_sbuf__write_exc(&ss, exc);
  30206. } else {
  30207. c11_sbuf__write_exc(&ss, inner);
  30208. c11_sbuf__write_cstr(
  30209. &ss,
  30210. "\n\nDuring handling of the above exception, another exception occurred:\n\n");
  30211. c11_sbuf__write_exc(&ss, exc);
  30212. }
  30213. c11_string* res = c11_sbuf__submit(&ss);
  30214. char* dup = PK_MALLOC(res->size + 1);
  30215. memcpy(dup, res->data, res->size);
  30216. dup[res->size] = '\0';
  30217. c11_string__delete(res);
  30218. return dup;
  30219. }
  30220. bool py_exception(py_Type type, const char* fmt, ...) {
  30221. #ifndef NDEBUG
  30222. if(py_checkexc()) {
  30223. const char* name = py_tpname(pk_current_vm->unhandled_exc.type);
  30224. c11__abort("py_exception(): `%s` was already set!", name);
  30225. }
  30226. #endif
  30227. c11_sbuf buf;
  30228. c11_sbuf__ctor(&buf);
  30229. va_list args;
  30230. va_start(args, fmt);
  30231. pk_vsprintf(&buf, fmt, args);
  30232. va_end(args);
  30233. py_Ref message = py_pushtmp();
  30234. c11_sbuf__py_submit(&buf, message);
  30235. bool ok = py_tpcall(type, 1, message);
  30236. if(!ok) return false;
  30237. py_pop();
  30238. return py_raise(py_retval());
  30239. }
  30240. bool py_raise(py_Ref exc) {
  30241. assert(py_isinstance(exc, tp_BaseException));
  30242. VM* vm = pk_current_vm;
  30243. if(vm->top_frame) {
  30244. FrameExcInfo* info = Frame__top_exc_info(vm->top_frame);
  30245. if(info && !py_isnil(&info->exc)) {
  30246. BaseException* ud = py_touserdata(exc);
  30247. ud->inner_exc = info->exc;
  30248. }
  30249. }
  30250. assert(py_isnil(&vm->unhandled_exc));
  30251. vm->unhandled_exc = *exc;
  30252. return false;
  30253. }
  30254. bool KeyError(py_Ref key) {
  30255. bool ok = py_tpcall(tp_KeyError, 1, key);
  30256. if(!ok) return false;
  30257. return py_raise(py_retval());
  30258. }
  30259. bool StopIteration() {
  30260. bool ok = py_tpcall(tp_StopIteration, 0, NULL);
  30261. if(!ok) return false;
  30262. return py_raise(py_retval());
  30263. }
  30264. // src/public\PyList.c
  30265. void py_newlist(py_OutRef out) {
  30266. List* ud = py_newobject(out, tp_list, 0, sizeof(List));
  30267. c11_vector__ctor(ud, sizeof(py_TValue));
  30268. }
  30269. void py_newlistn(py_OutRef out, int n) {
  30270. py_newlist(out);
  30271. List* ud = py_touserdata(out);
  30272. c11_vector__reserve(ud, n);
  30273. ud->length = n;
  30274. }
  30275. py_Ref py_list_data(py_Ref self) {
  30276. List* ud = py_touserdata(self);
  30277. return ud->data;
  30278. }
  30279. py_Ref py_list_getitem(py_Ref self, int i) {
  30280. List* ud = py_touserdata(self);
  30281. return c11__at(py_TValue, ud, i);
  30282. }
  30283. void py_list_setitem(py_Ref self, int i, py_Ref val) {
  30284. List* ud = py_touserdata(self);
  30285. c11__setitem(py_TValue, ud, i, *val);
  30286. }
  30287. void py_list_delitem(py_Ref self, int i) {
  30288. List* ud = py_touserdata(self);
  30289. c11_vector__erase(py_TValue, ud, i);
  30290. }
  30291. int py_list_len(py_Ref self) {
  30292. List* ud = py_touserdata(self);
  30293. return ud->length;
  30294. }
  30295. void py_list_swap(py_Ref self, int i, int j) {
  30296. py_TValue* data = py_list_data(self);
  30297. py_TValue tmp = data[i];
  30298. data[i] = data[j];
  30299. data[j] = tmp;
  30300. }
  30301. void py_list_append(py_Ref self, py_Ref val) {
  30302. List* ud = py_touserdata(self);
  30303. c11_vector__push(py_TValue, ud, *val);
  30304. }
  30305. py_ItemRef py_list_emplace(py_Ref self) {
  30306. List* ud = py_touserdata(self);
  30307. c11_vector__emplace(ud);
  30308. return &c11_vector__back(py_TValue, ud);
  30309. }
  30310. void py_list_clear(py_Ref self) {
  30311. List* ud = py_touserdata(self);
  30312. c11_vector__clear(ud);
  30313. }
  30314. void py_list_insert(py_Ref self, int i, py_Ref val) {
  30315. List* ud = py_touserdata(self);
  30316. c11_vector__insert(py_TValue, ud, i, *val);
  30317. }
  30318. ////////////////////////////////
  30319. static bool list__len__(int argc, py_Ref argv) {
  30320. PY_CHECK_ARGC(1);
  30321. py_i64 res = py_list_len(py_arg(0));
  30322. py_newint(py_retval(), res);
  30323. return true;
  30324. }
  30325. static bool list__eq__(int argc, py_Ref argv) {
  30326. return pk_wrapper__arrayequal(tp_list, argc, argv);
  30327. }
  30328. static bool list__ne__(int argc, py_Ref argv) {
  30329. if(!list__eq__(argc, argv)) return false;
  30330. if(py_isbool(py_retval())) {
  30331. bool res = py_tobool(py_retval());
  30332. py_newbool(py_retval(), !res);
  30333. }
  30334. return true;
  30335. }
  30336. static bool list__new__(int argc, py_Ref argv) {
  30337. if(argc == 1) {
  30338. py_newlist(py_retval());
  30339. return true;
  30340. }
  30341. if(argc == 2) {
  30342. py_TValue* p;
  30343. int length = pk_arrayview(py_arg(1), &p);
  30344. if(length != -1) {
  30345. py_newlistn(py_retval(), length);
  30346. for(int i = 0; i < length; i++) {
  30347. py_list_setitem(py_retval(), i, p + i);
  30348. }
  30349. return true;
  30350. }
  30351. if(!py_iter(py_arg(1))) return false;
  30352. py_Ref iter = py_pushtmp();
  30353. py_Ref list = py_pushtmp();
  30354. *iter = *py_retval();
  30355. py_newlist(list);
  30356. while(true) {
  30357. int res = py_next(iter);
  30358. if(res == -1) {
  30359. py_shrink(2);
  30360. return false;
  30361. }
  30362. if(!res) break;
  30363. py_list_append(list, py_retval());
  30364. // LYNX: list() of a long iterator grows inside one call, where no opcode checks the heap limit
  30365. if(py_lynx_out_of_memory) {
  30366. py_shrink(2);
  30367. return RuntimeError("out of memory");
  30368. }
  30369. }
  30370. *py_retval() = *list;
  30371. py_shrink(2);
  30372. return true;
  30373. }
  30374. return TypeError("list() takes at most 1 argument");
  30375. }
  30376. static bool list__getitem__(int argc, py_Ref argv) {
  30377. PY_CHECK_ARGC(2);
  30378. List* self = py_touserdata(py_arg(0));
  30379. py_Ref _1 = py_arg(1);
  30380. if(_1->type == tp_int) {
  30381. int index = py_toint(py_arg(1));
  30382. if(!pk__normalize_index(&index, self->length)) return false;
  30383. *py_retval() = c11__getitem(py_TValue, self, index);
  30384. return true;
  30385. } else if(_1->type == tp_slice) {
  30386. int start, stop, step;
  30387. bool ok = pk__parse_int_slice(_1, self->length, &start, &stop, &step);
  30388. if(!ok) return false;
  30389. py_newlist(py_retval());
  30390. List* list = py_touserdata(py_retval());
  30391. PK_SLICE_LOOP(i, start, stop, step) {
  30392. c11_vector__push(py_TValue, list, c11__getitem(py_TValue, self, i));
  30393. }
  30394. return true;
  30395. } else {
  30396. return TypeError("list indices must be integers");
  30397. }
  30398. }
  30399. static bool list__setitem__(int argc, py_Ref argv) {
  30400. PY_CHECK_ARGC(3);
  30401. PY_CHECK_ARG_TYPE(1, tp_int);
  30402. List* self = py_touserdata(py_arg(0));
  30403. int index = py_toint(py_arg(1));
  30404. if(!pk__normalize_index(&index, self->length)) return false;
  30405. c11__setitem(py_TValue, self, index, *py_arg(2));
  30406. py_newnone(py_retval());
  30407. return true;
  30408. }
  30409. static bool list__delitem__(int argc, py_Ref argv) {
  30410. PY_CHECK_ARGC(2);
  30411. List* self = py_touserdata(py_arg(0));
  30412. if(py_istype(py_arg(1), tp_slice)) {
  30413. int start, stop, step;
  30414. bool ok = pk__parse_int_slice(py_arg(1), self->length, &start, &stop, &step);
  30415. if(!ok) return false;
  30416. if(step != 1) return ValueError("slice step must be 1 for deletion");
  30417. int n = stop - start;
  30418. if(n > 0) {
  30419. py_TValue* p = self->data;
  30420. for(int i = stop; i < self->length; i++) {
  30421. p[start + i - stop] = p[i];
  30422. }
  30423. self->length -= n;
  30424. }
  30425. py_newnone(py_retval());
  30426. return true;
  30427. }
  30428. PY_CHECK_ARG_TYPE(1, tp_int);
  30429. int index = py_toint(py_arg(1));
  30430. if(!pk__normalize_index(&index, self->length)) return false;
  30431. c11_vector__erase(py_TValue, self, index);
  30432. py_newnone(py_retval());
  30433. return true;
  30434. }
  30435. static bool list__add__(int argc, py_Ref argv) {
  30436. PY_CHECK_ARGC(2);
  30437. py_Ref _0 = py_arg(0);
  30438. py_Ref _1 = py_arg(1);
  30439. if(py_istype(_1, tp_list)) {
  30440. List* list_0 = py_touserdata(_0);
  30441. List* list_1 = py_touserdata(_1);
  30442. py_newlist(py_retval());
  30443. List* list = py_touserdata(py_retval());
  30444. c11_vector__extend(list, list_0->data, list_0->length);
  30445. c11_vector__extend(list, list_1->data, list_1->length);
  30446. } else {
  30447. py_newnotimplemented(py_retval());
  30448. }
  30449. return true;
  30450. }
  30451. static bool list__mul__(int argc, py_Ref argv) {
  30452. PY_CHECK_ARGC(2);
  30453. py_Ref _0 = py_arg(0);
  30454. py_Ref _1 = py_arg(1);
  30455. if(py_istype(_1, tp_int)) {
  30456. py_i64 n64 = py_toint(_1);
  30457. List* list_0 = py_touserdata(_0);
  30458. // LYNX: the result's size is known: a repeat past the heap's room stops the script before it allocates
  30459. if(n64 > 0 && list_0->length > 0 &&
  30460. !py_lynx_heap_room(n64 > (py_i64)(0x7fffffff / list_0->length)
  30461. ? (size_t)-1
  30462. : (size_t)n64 * (size_t)list_0->length * sizeof(py_TValue)))
  30463. return RuntimeError("out of memory");
  30464. int n = list_0->length > 0 && n64 > 0 ? (int)n64 : 0;
  30465. py_newlist(py_retval());
  30466. List* list = py_touserdata(py_retval());
  30467. for(int i = 0; i < n; i++) {
  30468. c11_vector__extend(list, list_0->data, list_0->length);
  30469. }
  30470. } else {
  30471. py_newnotimplemented(py_retval());
  30472. }
  30473. return true;
  30474. }
  30475. static bool list__rmul__(int argc, py_Ref argv) { return list__mul__(argc, argv); }
  30476. static bool list_append(int argc, py_Ref argv) {
  30477. PY_CHECK_ARGC(2);
  30478. py_list_append(py_arg(0), py_arg(1));
  30479. py_newnone(py_retval());
  30480. return true;
  30481. }
  30482. static bool list__repr__(int argc, py_Ref argv) {
  30483. List* self = py_touserdata(py_arg(0));
  30484. c11_sbuf buf;
  30485. c11_sbuf__ctor(&buf);
  30486. c11_sbuf__write_char(&buf, '[');
  30487. for(int i = 0; i < self->length; i++) {
  30488. py_TValue* val = c11__at(py_TValue, self, i);
  30489. bool ok = py_repr(val);
  30490. if(!ok) {
  30491. c11_sbuf__dtor(&buf);
  30492. return false;
  30493. }
  30494. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  30495. if(i != self->length - 1) c11_sbuf__write_cstr(&buf, ", ");
  30496. }
  30497. c11_sbuf__write_char(&buf, ']');
  30498. c11_sbuf__py_submit(&buf, py_retval());
  30499. return true;
  30500. }
  30501. static bool list_extend(int argc, py_Ref argv) {
  30502. PY_CHECK_ARGC(2);
  30503. List* self = py_touserdata(py_arg(0));
  30504. py_TValue* p;
  30505. int length = pk_arrayview(py_arg(1), &p);
  30506. if(length >= 0) {
  30507. c11_vector__extend(self, p, length);
  30508. } else {
  30509. // get iterator
  30510. if (!py_iter(py_arg(1))) return false;
  30511. py_StackRef tmp_iter = py_pushtmp();
  30512. py_assign(tmp_iter, py_retval());
  30513. while(true) {
  30514. int res = py_next(tmp_iter);
  30515. if (res == 0) break;
  30516. if (res == -1) return false;
  30517. assert(res == 1);
  30518. c11_vector__push(py_TValue, self, *py_retval());
  30519. }
  30520. py_pop();
  30521. }
  30522. py_newnone(py_retval());
  30523. return true;
  30524. }
  30525. static bool list_count(int argc, py_Ref argv) {
  30526. PY_CHECK_ARGC(2);
  30527. int count = 0;
  30528. for(int i = 0; i < py_list_len(py_arg(0)); i++) {
  30529. int res = py_equal(py_list_getitem(py_arg(0), i), py_arg(1));
  30530. if(res == -1) return false;
  30531. if(res) count++;
  30532. }
  30533. py_newint(py_retval(), count);
  30534. return true;
  30535. }
  30536. static bool list_clear(int argc, py_Ref argv) {
  30537. PY_CHECK_ARGC(1);
  30538. py_list_clear(py_arg(0));
  30539. py_newnone(py_retval());
  30540. return true;
  30541. }
  30542. static bool list_copy(int argc, py_Ref argv) {
  30543. PY_CHECK_ARGC(1);
  30544. py_newlist(py_retval());
  30545. List* self = py_touserdata(py_arg(0));
  30546. List* list = py_touserdata(py_retval());
  30547. c11_vector__extend(list, self->data, self->length);
  30548. return true;
  30549. }
  30550. static bool list_index(int argc, py_Ref argv) {
  30551. if(argc > 3) return TypeError("index() takes at most 3 arguments");
  30552. int start = 0;
  30553. if(argc == 3) {
  30554. PY_CHECK_ARG_TYPE(2, tp_int);
  30555. start = py_toint(py_arg(2));
  30556. if(start < 0) start += py_list_len(py_arg(0));
  30557. if(start < 0) start = 0;
  30558. }
  30559. for(int i = start; i < py_list_len(py_arg(0)); i++) {
  30560. int res = py_equal(py_list_getitem(py_arg(0), i), py_arg(1));
  30561. if(res == -1) return false;
  30562. if(res) {
  30563. py_newint(py_retval(), i);
  30564. return true;
  30565. }
  30566. }
  30567. return ValueError("list.index(x): x not in list");
  30568. }
  30569. static bool list_reverse(int argc, py_Ref argv) {
  30570. PY_CHECK_ARGC(1);
  30571. List* self = py_touserdata(py_arg(0));
  30572. c11__reverse(py_TValue, self);
  30573. py_newnone(py_retval());
  30574. return true;
  30575. }
  30576. static bool list_remove(int argc, py_Ref argv) {
  30577. PY_CHECK_ARGC(2);
  30578. for(int i = 0; i < py_list_len(py_arg(0)); i++) {
  30579. int res = py_equal(py_list_getitem(py_arg(0), i), py_arg(1));
  30580. if(res == -1) return false;
  30581. if(res) {
  30582. py_list_delitem(py_arg(0), i);
  30583. py_newnone(py_retval());
  30584. return true;
  30585. }
  30586. }
  30587. return ValueError("list.remove(x): x not in list");
  30588. }
  30589. static bool list_pop(int argc, py_Ref argv) {
  30590. int index;
  30591. if(argc == 1) {
  30592. index = -1;
  30593. } else if(argc == 2) {
  30594. PY_CHECK_ARG_TYPE(1, tp_int);
  30595. index = py_toint(py_arg(1));
  30596. } else {
  30597. return TypeError("pop() takes at most 2 arguments");
  30598. }
  30599. List* self = py_touserdata(py_arg(0));
  30600. if(self->length == 0) return IndexError("pop from empty list");
  30601. if(!pk__normalize_index(&index, self->length)) return false;
  30602. *py_retval() = c11__getitem(py_TValue, self, index);
  30603. c11_vector__erase(py_TValue, self, index);
  30604. return true;
  30605. }
  30606. static bool list_insert(int argc, py_Ref argv) {
  30607. PY_CHECK_ARGC(3);
  30608. PY_CHECK_ARG_TYPE(1, tp_int);
  30609. List* self = py_touserdata(py_arg(0));
  30610. int index = py_toint(py_arg(1));
  30611. if(index < 0) index += self->length;
  30612. if(index < 0) index = 0;
  30613. if(index > self->length) index = self->length;
  30614. c11_vector__insert(py_TValue, self, index, *py_arg(2));
  30615. py_newnone(py_retval());
  30616. return true;
  30617. }
  30618. static int lt_with_key(const void* a_, const void* b_, void* extra) {
  30619. py_TValue* a = (py_TValue*)a_;
  30620. py_TValue* b = (py_TValue*)b_;
  30621. py_TValue* key = (py_TValue*)extra;
  30622. if(!key) return py_less(a, b);
  30623. VM* vm = pk_current_vm;
  30624. // project a
  30625. py_push(key);
  30626. py_pushnil();
  30627. py_push(a);
  30628. if(!py_vectorcall(1, 0)) return -1;
  30629. py_push(py_retval());
  30630. // project b
  30631. py_push(key);
  30632. py_pushnil();
  30633. py_push(b);
  30634. if(!py_vectorcall(1, 0)) return -1;
  30635. py_push(py_retval());
  30636. // binary op
  30637. bool ok = pk_stack_binaryop(vm, __lt__, __gt__);
  30638. if(!ok) return -1;
  30639. py_shrink(2);
  30640. return py_bool(py_retval());
  30641. }
  30642. // sort(self, key=None, reverse=False)
  30643. static bool list_sort(int argc, py_Ref argv) {
  30644. List* self = py_touserdata(py_arg(0));
  30645. py_Ref key = py_arg(1);
  30646. if(py_isnone(key)) key = NULL;
  30647. bool ok = c11__stable_sort(self->data,
  30648. self->length,
  30649. sizeof(py_TValue),
  30650. lt_with_key,
  30651. key);
  30652. if(!ok) return false;
  30653. PY_CHECK_ARG_TYPE(2, tp_bool);
  30654. bool reverse = py_tobool(py_arg(2));
  30655. if(reverse) c11__reverse(py_TValue, self);
  30656. py_newnone(py_retval());
  30657. return true;
  30658. }
  30659. static bool list__iter__(int argc, py_Ref argv) {
  30660. PY_CHECK_ARGC(1);
  30661. list_iterator* ud = py_newobject(py_retval(), tp_list_iterator, 1, sizeof(list_iterator));
  30662. ud->vec = py_touserdata(argv);
  30663. ud->index = 0;
  30664. py_setslot(py_retval(), 0, argv); // keep a reference to the object
  30665. return true;
  30666. }
  30667. static bool list__contains__(int argc, py_Ref argv) {
  30668. PY_CHECK_ARGC(2);
  30669. return pk_arraycontains(py_arg(0), py_arg(1));
  30670. }
  30671. py_Type pk_list__register() {
  30672. py_Type type =
  30673. pk_newtype("list", tp_object, NULL, (void (*)(void*))c11_vector__dtor, false, true);
  30674. py_bindmagic(type, __len__, list__len__);
  30675. py_bindmagic(type, __eq__, list__eq__);
  30676. py_bindmagic(type, __ne__, list__ne__);
  30677. py_bindmagic(type, __new__, list__new__);
  30678. py_bindmagic(type, __getitem__, list__getitem__);
  30679. py_bindmagic(type, __setitem__, list__setitem__);
  30680. py_bindmagic(type, __delitem__, list__delitem__);
  30681. py_bindmagic(type, __add__, list__add__);
  30682. py_bindmagic(type, __mul__, list__mul__);
  30683. py_bindmagic(type, __rmul__, list__rmul__);
  30684. py_bindmagic(type, __repr__, list__repr__);
  30685. py_bindmagic(type, __iter__, list__iter__);
  30686. py_bindmagic(type, __contains__, list__contains__);
  30687. py_bindmethod(type, "append", list_append);
  30688. py_bindmethod(type, "extend", list_extend);
  30689. py_bindmethod(type, "count", list_count);
  30690. py_bindmethod(type, "clear", list_clear);
  30691. py_bindmethod(type, "copy", list_copy);
  30692. py_bindmethod(type, "index", list_index);
  30693. py_bindmethod(type, "reverse", list_reverse);
  30694. py_bindmethod(type, "remove", list_remove);
  30695. py_bindmethod(type, "pop", list_pop);
  30696. py_bindmethod(type, "insert", list_insert);
  30697. py_bindmethod(type, "sort", list_sort);
  30698. py_bind(py_tpobject(type), "sort(self, key=None, reverse=False)", list_sort);
  30699. py_setdict(py_tpobject(type), __hash__, py_None());
  30700. return type;
  30701. }
  30702. // src/public\PySlice.c
  30703. py_ObjectRef py_newslice(py_OutRef out) {
  30704. VM* vm = pk_current_vm;
  30705. PyObject* obj = ManagedHeap__gcnew(&vm->heap, tp_slice, 3, 0);
  30706. out->type = tp_slice;
  30707. out->is_ptr = true;
  30708. out->_obj = obj;
  30709. return PyObject__slots(obj);
  30710. }
  30711. void py_newsliceint(py_OutRef out, py_i64 start, py_i64 stop, py_i64 step) {
  30712. py_Ref slots = py_newslice(out);
  30713. py_newint(&slots[0], start);
  30714. py_newint(&slots[1], stop);
  30715. py_newint(&slots[2], step);
  30716. }
  30717. static bool slice__new__(int argc, py_Ref argv) {
  30718. PY_CHECK_ARGC(1 + 3);
  30719. py_Ref slice = py_retval();
  30720. py_newslice(slice);
  30721. py_setslot(slice, 0, py_arg(1));
  30722. py_setslot(slice, 1, py_arg(2));
  30723. py_setslot(slice, 2, py_arg(3));
  30724. return true;
  30725. }
  30726. static bool slice__repr__(int argc, py_Ref argv) {
  30727. c11_sbuf buf;
  30728. c11_sbuf__ctor(&buf);
  30729. c11_sbuf__write_cstr(&buf, "slice(");
  30730. for(int i = 0; i < 3; i++) {
  30731. py_TValue* val = py_getslot(argv, i);
  30732. bool ok = py_repr(val);
  30733. if(!ok) {
  30734. c11_sbuf__dtor(&buf);
  30735. return false;
  30736. }
  30737. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  30738. if(i != 2) c11_sbuf__write_cstr(&buf, ", ");
  30739. }
  30740. c11_sbuf__write_char(&buf, ')');
  30741. c11_sbuf__py_submit(&buf, py_retval());
  30742. return true;
  30743. }
  30744. static bool slice_start(int argc, py_Ref argv) {
  30745. py_Ref self = py_arg(0);
  30746. py_TValue* val = py_getslot(self, 0);
  30747. py_assign(py_retval(), val);
  30748. return true;
  30749. }
  30750. static bool slice_stop(int argc, py_Ref argv) {
  30751. py_Ref self = py_arg(0);
  30752. py_TValue* val = py_getslot(self, 1);
  30753. py_assign(py_retval(), val);
  30754. return true;
  30755. }
  30756. static bool slice_step(int argc, py_Ref argv) {
  30757. py_Ref self = py_arg(0);
  30758. py_TValue* val = py_getslot(self, 2);
  30759. py_assign(py_retval(), val);
  30760. return true;
  30761. }
  30762. static bool slice__eq__(int argc, py_Ref argv) {
  30763. py_Ref self = py_arg(0);
  30764. py_Ref other = py_arg(1);
  30765. if(!py_istype(other, tp_slice)) {
  30766. py_newnotimplemented(py_retval());
  30767. return true;
  30768. }
  30769. for(int i = 0; i < 3; i++) {
  30770. py_Ref lhs = py_getslot(self, i);
  30771. py_Ref rhs = py_getslot(other, i);
  30772. int res = py_equal(lhs, rhs);
  30773. if(res == -1) return false;
  30774. if(res == 0) {
  30775. py_newbool(py_retval(), false);
  30776. return true;
  30777. }
  30778. }
  30779. py_newbool(py_retval(), true);
  30780. return true;
  30781. }
  30782. static bool slice__ne__(int argc, py_Ref argv) {
  30783. bool ok = slice__eq__(argc, argv);
  30784. if(!ok) return false;
  30785. py_Ref res = py_retval();
  30786. if(py_isbool(res)) py_newbool(py_retval(), !py_tobool(res));
  30787. return true;
  30788. }
  30789. py_Type pk_slice__register() {
  30790. py_Type type = pk_newtype("slice", tp_object, NULL, NULL, false, true);
  30791. py_bindmagic(type, __new__, slice__new__);
  30792. py_bindmagic(type, __repr__, slice__repr__);
  30793. py_bindmagic(type, __eq__, slice__eq__);
  30794. py_bindmagic(type, __ne__, slice__ne__);
  30795. py_setdict(py_tpobject(type), __hash__, py_None());
  30796. py_bindproperty(type, "start", slice_start, NULL);
  30797. py_bindproperty(type, "stop", slice_stop, NULL);
  30798. py_bindproperty(type, "step", slice_step, NULL);
  30799. return type;
  30800. }
  30801. // src/public\PythonOps.c
  30802. bool py_binaryadd(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __add__, __radd__); }
  30803. bool py_binarysub(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __sub__, __rsub__); }
  30804. bool py_binarymul(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __mul__, __rmul__); }
  30805. bool py_binarytruediv(py_Ref lhs, py_Ref rhs) {
  30806. return py_binaryop(lhs, rhs, __truediv__, __rtruediv__);
  30807. }
  30808. bool py_binaryfloordiv(py_Ref lhs, py_Ref rhs) {
  30809. return py_binaryop(lhs, rhs, __floordiv__, __rfloordiv__);
  30810. }
  30811. bool py_binarymod(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __mod__, __rmod__); }
  30812. bool py_binarypow(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __pow__, __rpow__); }
  30813. bool py_binarylshift(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __lshift__, 0); }
  30814. bool py_binaryrshift(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __rshift__, 0); }
  30815. bool py_binaryand(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __and__, 0); }
  30816. bool py_binaryor(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __or__, 0); }
  30817. bool py_binaryxor(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __xor__, 0); }
  30818. bool py_binarymatmul(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __matmul__, 0); }
  30819. bool py_eq(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __eq__, __eq__); }
  30820. bool py_ne(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __ne__, __ne__); }
  30821. bool py_lt(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __lt__, __gt__); }
  30822. bool py_le(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __le__, __ge__); }
  30823. bool py_gt(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __gt__, __lt__); }
  30824. bool py_ge(py_Ref lhs, py_Ref rhs) { return py_binaryop(lhs, rhs, __ge__, __le__); }
  30825. bool py_isidentical(py_Ref lhs, py_Ref rhs) {
  30826. if(lhs->type != rhs->type) return false;
  30827. switch(lhs->type) {
  30828. case tp_int: return lhs->_i64 == rhs->_i64;
  30829. case tp_float: return lhs->_f64 == rhs->_f64;
  30830. case tp_bool: return lhs->_bool == rhs->_bool;
  30831. case tp_str: {
  30832. if(lhs->is_ptr && rhs->is_ptr) {
  30833. return lhs->_obj == rhs->_obj;
  30834. } else {
  30835. return strcmp(lhs->_chars, rhs->_chars) == 0;
  30836. }
  30837. }
  30838. case tp_nativefunc: return lhs->_cfunc == rhs->_cfunc;
  30839. case tp_NoneType: return true;
  30840. case tp_NotImplementedType: return true;
  30841. case tp_ellipsis: return true;
  30842. // fallback to pointer comparison
  30843. default: return lhs->is_ptr && rhs->is_ptr && lhs->_obj == rhs->_obj;
  30844. }
  30845. }
  30846. int py_bool(py_Ref val) {
  30847. switch(val->type) {
  30848. case tp_bool: return val->_bool;
  30849. case tp_int: return val->_i64 != 0;
  30850. case tp_float: return val->_f64 != 0;
  30851. case tp_NoneType: return 0;
  30852. default: {
  30853. py_Ref tmp = py_tpfindmagic(val->type, __bool__);
  30854. if(tmp) {
  30855. if(!py_call(tmp, 1, val)) return -1;
  30856. if(!py_checkbool(py_retval())) return -1;
  30857. return py_tobool(py_retval());
  30858. } else {
  30859. tmp = py_tpfindmagic(val->type, __len__);
  30860. if(tmp) {
  30861. if(!py_call(tmp, 1, val)) return -1;
  30862. if(!py_checkint(py_retval())) return -1;
  30863. return py_toint(py_retval());
  30864. } else {
  30865. return 1; // True
  30866. }
  30867. }
  30868. }
  30869. }
  30870. }
  30871. int py_equal(py_Ref lhs, py_Ref rhs) {
  30872. if(py_isidentical(lhs, rhs)) return 1;
  30873. if(!py_eq(lhs, rhs)) return -1;
  30874. return py_bool(py_retval());
  30875. }
  30876. int py_less(py_Ref lhs, py_Ref rhs) {
  30877. if(!py_lt(lhs, rhs)) return -1;
  30878. return py_bool(py_retval());
  30879. }
  30880. bool py_callable(py_Ref val) {
  30881. switch(val->type) {
  30882. case tp_nativefunc: return true;
  30883. case tp_function: return true;
  30884. case tp_type: return true;
  30885. case tp_boundmethod: return true;
  30886. case tp_staticmethod: return true;
  30887. case tp_classmethod: return true;
  30888. default: return py_tpfindmagic(val->type, __call__);
  30889. }
  30890. }
  30891. bool py_hash(py_Ref val, int64_t* out) {
  30892. py_TypeInfo* ti = pk_typeinfo(val->type);
  30893. do {
  30894. py_Ref slot_hash = py_getdict(&ti->self, __hash__);
  30895. if(slot_hash && py_isnone(slot_hash)) break;
  30896. py_Ref slot_eq = py_getdict(&ti->self, __eq__);
  30897. if(slot_eq) {
  30898. if(!slot_hash) break;
  30899. if(!py_call(slot_hash, 1, val)) return false;
  30900. if(!py_checkint(py_retval())) return false;
  30901. *out = py_toint(py_retval());
  30902. return true;
  30903. }
  30904. ti = ti->base_ti;
  30905. } while(ti);
  30906. return TypeError("unhashable type: '%t'", val->type);
  30907. }
  30908. bool py_iter(py_Ref val) {
  30909. py_Ref tmp = py_tpfindmagic(val->type, __iter__);
  30910. if(!tmp) return TypeError("'%t' object is not iterable", val->type);
  30911. return py_call(tmp, 1, val);
  30912. }
  30913. int py_next(py_Ref val) {
  30914. VM* vm = pk_current_vm;
  30915. switch(val->type) {
  30916. case tp_generator:
  30917. if(generator__next__(1, val)) return 1;
  30918. break;
  30919. case tp_array2d_like_iterator:
  30920. if(array2d_like_iterator__next__(1, val)) return 1;
  30921. break;
  30922. case tp_list_iterator:
  30923. if(list_iterator__next__(1, val)) return 1;
  30924. break;
  30925. case tp_tuple_iterator:
  30926. if(tuple_iterator__next__(1, val)) return 1;
  30927. break;
  30928. case tp_dict_iterator:
  30929. if(dict_items__next__(1, val)) return 1;
  30930. break;
  30931. case tp_range_iterator:
  30932. if(range_iterator__next__(1, val)) return 1;
  30933. break;
  30934. case tp_str_iterator:
  30935. if(str_iterator__next__(1, val)) return 1;
  30936. break;
  30937. default: {
  30938. py_Ref tmp = py_tpfindmagic(val->type, __next__);
  30939. if(!tmp) {
  30940. TypeError("'%t' object is not an iterator", val->type);
  30941. return -1;
  30942. }
  30943. if(py_call(tmp, 1, val)) return 1;
  30944. break;
  30945. }
  30946. }
  30947. if(vm->unhandled_exc.type == tp_StopIteration) {
  30948. vm->last_retval = vm->unhandled_exc;
  30949. py_clearexc(NULL);
  30950. return 0;
  30951. }
  30952. return -1;
  30953. }
  30954. bool py_str(py_Ref val) {
  30955. if(val->type == tp_str) {
  30956. py_assign(py_retval(), val);
  30957. return true;
  30958. }
  30959. py_Ref tmp = py_tpfindmagic(val->type, __str__);
  30960. if(!tmp) return py_repr(val);
  30961. return py_call(tmp, 1, val);
  30962. }
  30963. bool py_repr(py_Ref val) { return pk_callmagic(__repr__, 1, val); }
  30964. bool py_len(py_Ref val) { return pk_callmagic(__len__, 1, val); }
  30965. bool py_getattr(py_Ref self, py_Name name) {
  30966. // https://docs.python.org/3/howto/descriptor.html#invocation-from-an-instance
  30967. py_TypeInfo* ti = pk_typeinfo(self->type);
  30968. if(ti->getattribute) return ti->getattribute(self, name);
  30969. py_Ref cls_var = pk_tpfindname(ti, name);
  30970. if(cls_var) {
  30971. // handle descriptor
  30972. if(py_istype(cls_var, tp_property)) {
  30973. py_Ref getter = py_getslot(cls_var, 0);
  30974. return py_call(getter, 1, self);
  30975. }
  30976. }
  30977. // handle instance __dict__
  30978. if(self->is_ptr && self->_obj->slots == -1) {
  30979. if(!py_istype(self, tp_type)) {
  30980. py_Ref res = py_getdict(self, name);
  30981. if(res) {
  30982. py_assign(py_retval(), res);
  30983. return true;
  30984. }
  30985. } else {
  30986. // self is a type object
  30987. py_TypeInfo* inner_type = py_touserdata(self);
  30988. py_Ref res = pk_tpfindname(inner_type, name);
  30989. if(res) {
  30990. if(py_istype(res, tp_staticmethod)) {
  30991. res = py_getslot(res, 0);
  30992. } else if(py_istype(res, tp_classmethod)) {
  30993. res = py_getslot(res, 0);
  30994. py_newboundmethod(py_retval(), self, res);
  30995. return true;
  30996. }
  30997. py_assign(py_retval(), res);
  30998. return true;
  30999. }
  31000. }
  31001. }
  31002. if(cls_var) {
  31003. // bound method is non-data descriptor
  31004. switch(cls_var->type) {
  31005. case tp_function: {
  31006. if(name == __new__) goto __STATIC_NEW;
  31007. py_newboundmethod(py_retval(), self, cls_var);
  31008. return true;
  31009. }
  31010. case tp_nativefunc: {
  31011. if(name == __new__) goto __STATIC_NEW;
  31012. py_newboundmethod(py_retval(), self, cls_var);
  31013. return true;
  31014. }
  31015. case tp_staticmethod: {
  31016. py_assign(py_retval(), py_getslot(cls_var, 0));
  31017. return true;
  31018. }
  31019. case tp_classmethod: {
  31020. py_newboundmethod(py_retval(), &ti->self, py_getslot(cls_var, 0));
  31021. return true;
  31022. }
  31023. default: {
  31024. __STATIC_NEW:
  31025. py_assign(py_retval(), cls_var);
  31026. return true;
  31027. }
  31028. }
  31029. }
  31030. py_Ref fallback = pk_tpfindmagic(ti, __getattr__);
  31031. if(fallback) {
  31032. py_push(fallback);
  31033. py_push(self);
  31034. py_assign(py_pushtmp(), py_name2ref(name));
  31035. return py_vectorcall(1, 0);
  31036. }
  31037. if(self->type == tp_module) {
  31038. py_ModuleInfo* mi = py_touserdata(self);
  31039. c11_sbuf buf;
  31040. c11_sbuf__ctor(&buf);
  31041. pk_sprintf(&buf, "%v.%n", c11_string__sv(mi->path), name);
  31042. c11_string* new_path = c11_sbuf__submit(&buf);
  31043. int res = py_import(new_path->data);
  31044. c11_string__delete(new_path);
  31045. if(res == -1) {
  31046. return false;
  31047. } else if(res == 1) {
  31048. return true;
  31049. }
  31050. }
  31051. return AttributeError(self, name);
  31052. }
  31053. bool py_setattr(py_Ref self, py_Name name, py_Ref val) {
  31054. py_TypeInfo* ti = pk_typeinfo(self->type);
  31055. if(ti->setattribute) return ti->setattribute(self, name, val);
  31056. py_Ref cls_var = pk_tpfindname(ti, name);
  31057. if(cls_var) {
  31058. // handle descriptor
  31059. if(py_istype(cls_var, tp_property)) {
  31060. py_Ref setter = py_getslot(cls_var, 1);
  31061. if(!py_isnone(setter)) {
  31062. py_push(setter);
  31063. py_push(self);
  31064. py_push(val);
  31065. return py_vectorcall(1, 0);
  31066. } else {
  31067. return TypeError("readonly attribute: '%n'", name);
  31068. }
  31069. }
  31070. }
  31071. // handle instance __dict__
  31072. if(self->is_ptr && self->_obj->slots == -1) {
  31073. py_setdict(self, name, val);
  31074. return true;
  31075. }
  31076. return TypeError("cannot set attribute");
  31077. }
  31078. bool py_delattr(py_Ref self, py_Name name) {
  31079. py_TypeInfo* ti = pk_typeinfo(self->type);
  31080. if(ti->delattribute) return ti->delattribute(self, name);
  31081. if(self->is_ptr && self->_obj->slots == -1) {
  31082. if(py_deldict(self, name)) return true;
  31083. return AttributeError(self, name);
  31084. }
  31085. return TypeError("cannot delete attribute");
  31086. }
  31087. bool py_getitem(py_Ref self, py_Ref key) {
  31088. py_push(self);
  31089. py_push(key);
  31090. bool ok = pk_callmagic(__getitem__, 2, py_peek(-2));
  31091. py_shrink(2);
  31092. return ok;
  31093. }
  31094. bool py_setitem(py_Ref self, py_Ref key, py_Ref val) {
  31095. py_push(self);
  31096. py_push(key);
  31097. py_push(val);
  31098. bool ok = pk_callmagic(__setitem__, 3, py_peek(-3));
  31099. py_shrink(3);
  31100. return ok;
  31101. }
  31102. bool py_delitem(py_Ref self, py_Ref key) {
  31103. py_push(self);
  31104. py_push(key);
  31105. bool ok = pk_callmagic(__delitem__, 2, py_peek(-2));
  31106. py_shrink(2);
  31107. return ok;
  31108. }
  31109. // src/public\PyTuple.c
  31110. py_ObjectRef py_newtuple(py_OutRef out, int n) {
  31111. VM* vm = pk_current_vm;
  31112. PyObject* obj = ManagedHeap__gcnew(&vm->heap, tp_tuple, n, 0);
  31113. out->type = tp_tuple;
  31114. out->is_ptr = true;
  31115. out->_obj = obj;
  31116. return PyObject__slots(obj);
  31117. }
  31118. py_Ref py_tuple_getitem(py_Ref self, int i) { return py_getslot(self, i); }
  31119. py_Ref py_tuple_data(py_Ref self) { return PyObject__slots(self->_obj); }
  31120. void py_tuple_setitem(py_Ref self, int i, py_Ref val) { py_setslot(self, i, val); }
  31121. int py_tuple_len(py_Ref self) { return self->_obj->slots; }
  31122. //////////////
  31123. static bool tuple__len__(int argc, py_Ref argv) {
  31124. py_newint(py_retval(), py_tuple_len(argv));
  31125. return true;
  31126. }
  31127. static bool tuple__repr__(int argc, py_Ref argv) {
  31128. c11_sbuf buf;
  31129. c11_sbuf__ctor(&buf);
  31130. c11_sbuf__write_char(&buf, '(');
  31131. int length = py_tuple_len(argv);
  31132. for(int i = 0; i < length; i++) {
  31133. py_TValue* val = py_getslot(argv, i);
  31134. bool ok = py_repr(val);
  31135. if(!ok) {
  31136. c11_sbuf__dtor(&buf);
  31137. return false;
  31138. }
  31139. c11_sbuf__write_sv(&buf, py_tosv(py_retval()));
  31140. if(i != length - 1) c11_sbuf__write_cstr(&buf, ", ");
  31141. }
  31142. if(length == 1) c11_sbuf__write_char(&buf, ',');
  31143. c11_sbuf__write_char(&buf, ')');
  31144. c11_sbuf__py_submit(&buf, py_retval());
  31145. return true;
  31146. }
  31147. static bool tuple__new__(int argc, py_Ref argv) {
  31148. if(argc == 1 + 0) {
  31149. py_newtuple(py_retval(), 0);
  31150. return true;
  31151. }
  31152. if(argc == 1 + 1) {
  31153. bool ok = py_tpcall(tp_list, 1, py_arg(1));
  31154. if(!ok) return false;
  31155. py_Ref tmp = py_pushtmp();
  31156. *tmp = *py_retval(); // backup the list
  31157. int length = py_list_len(tmp);
  31158. py_Ref p = py_newtuple(py_retval(), length);
  31159. for(int i = 0; i < py_tuple_len(py_retval()); i++) {
  31160. p[i] = *py_list_getitem(tmp, i);
  31161. }
  31162. py_pop();
  31163. return true;
  31164. }
  31165. return TypeError("tuple() takes at most 1 argument");
  31166. }
  31167. static bool tuple__getitem__(int argc, py_Ref argv) {
  31168. PY_CHECK_ARGC(2);
  31169. int length = py_tuple_len(argv);
  31170. py_Ref _1 = py_arg(1);
  31171. if(_1->type == tp_int) {
  31172. int index = py_toint(py_arg(1));
  31173. if(!pk__normalize_index(&index, length)) return false;
  31174. *py_retval() = *py_getslot(argv, index);
  31175. return true;
  31176. } else if(_1->type == tp_slice) {
  31177. int start, stop, step;
  31178. bool ok = pk__parse_int_slice(_1, length, &start, &stop, &step);
  31179. if(!ok) return false;
  31180. py_Ref tmp = py_pushtmp();
  31181. py_newlist(tmp);
  31182. PK_SLICE_LOOP(i, start, stop, step) py_list_append(tmp, py_getslot(argv, i));
  31183. // convert list to tuple
  31184. py_Ref p = py_newtuple(py_retval(), py_list_len(tmp));
  31185. for(int i = 0; i < py_tuple_len(py_retval()); i++) {
  31186. p[i] = *py_list_getitem(tmp, i);
  31187. }
  31188. py_pop();
  31189. return true;
  31190. } else {
  31191. return TypeError("tuple indices must be integers");
  31192. }
  31193. }
  31194. static bool tuple__eq__(int argc, py_Ref argv) {
  31195. return pk_wrapper__arrayequal(tp_tuple, argc, argv);
  31196. }
  31197. static bool tuple__ne__(int argc, py_Ref argv) {
  31198. if(!tuple__eq__(argc, argv)) return false;
  31199. if(py_isbool(py_retval())) {
  31200. bool res = py_tobool(py_retval());
  31201. py_newbool(py_retval(), !res);
  31202. }
  31203. return true;
  31204. }
  31205. static bool tuple__lt__(int argc, py_Ref argv) {
  31206. PY_CHECK_ARGC(2);
  31207. if(!py_istype(py_arg(1), tp_tuple)) {
  31208. py_newnotimplemented(py_retval());
  31209. return true;
  31210. }
  31211. py_TValue *p0, *p1;
  31212. int lhs_length = py_tuple_len(py_arg(0));
  31213. int rhs_length = py_tuple_len(py_arg(1));
  31214. p0 = py_tuple_data(py_arg(0));
  31215. p1 = py_tuple_data(py_arg(1));
  31216. int length = lhs_length < rhs_length ? lhs_length : rhs_length;
  31217. for(int i = 0; i < length; i++) {
  31218. int res_lt = py_less(p0 + i, p1 + i);
  31219. if(res_lt == -1) return false;
  31220. if(res_lt) {
  31221. py_newbool(py_retval(), true);
  31222. return true;
  31223. } else {
  31224. int res_eq = py_equal(p0 + i, p1 + i);
  31225. if(res_eq == -1) return false;
  31226. if(!res_eq) {
  31227. py_newbool(py_retval(), false);
  31228. return true;
  31229. }
  31230. }
  31231. }
  31232. py_newbool(py_retval(), lhs_length < rhs_length);
  31233. return true;
  31234. }
  31235. static bool tuple__iter__(int argc, py_Ref argv) {
  31236. PY_CHECK_ARGC(1);
  31237. tuple_iterator* ud = py_newobject(py_retval(), tp_tuple_iterator, 1, sizeof(tuple_iterator));
  31238. ud->p = py_tuple_data(argv);
  31239. ud->length = py_tuple_len(argv);
  31240. ud->index = 0;
  31241. py_setslot(py_retval(), 0, argv); // keep a reference to the object
  31242. return true;
  31243. }
  31244. static bool tuple__contains__(int argc, py_Ref argv) {
  31245. PY_CHECK_ARGC(2);
  31246. return pk_arraycontains(py_arg(0), py_arg(1));
  31247. }
  31248. static bool tuple__hash__(int argc, py_Ref argv) {
  31249. PY_CHECK_ARGC(1);
  31250. int length = py_tuple_len(argv);
  31251. py_TValue* data = py_tuple_data(argv);
  31252. uint64_t x = 1000003;
  31253. for(int i = 0; i < length; i++) {
  31254. py_i64 y;
  31255. if(!py_hash(&data[i], &y)) return false;
  31256. // recommended by Github Copilot
  31257. x = x ^ (y + 0x9e3779b9 + (x << 6) + (x >> 2));
  31258. }
  31259. py_newint(py_retval(), x);
  31260. return true;
  31261. }
  31262. py_Type pk_tuple__register() {
  31263. py_Type type = pk_newtype("tuple", tp_object, NULL, NULL, false, true);
  31264. py_bindmagic(type, __len__, tuple__len__);
  31265. py_bindmagic(type, __repr__, tuple__repr__);
  31266. py_bindmagic(type, __new__, tuple__new__);
  31267. py_bindmagic(type, __getitem__, tuple__getitem__);
  31268. py_bindmagic(type, __eq__, tuple__eq__);
  31269. py_bindmagic(type, __ne__, tuple__ne__);
  31270. py_bindmagic(type, __lt__, tuple__lt__);
  31271. py_bindmagic(type, __iter__, tuple__iter__);
  31272. py_bindmagic(type, __contains__, tuple__contains__);
  31273. py_bindmagic(type, __hash__, tuple__hash__);
  31274. return type;
  31275. }
  31276. // src/public\StackOps.c
  31277. PK_INLINE py_Ref py_peek(int i) {
  31278. assert(i <= 0);
  31279. return pk_current_vm->stack.sp + i;
  31280. }
  31281. PK_INLINE void py_push(py_Ref src) {
  31282. VM* vm = pk_current_vm;
  31283. *vm->stack.sp++ = *src;
  31284. }
  31285. PK_INLINE void py_pushnil() {
  31286. VM* vm = pk_current_vm;
  31287. py_newnil(vm->stack.sp++);
  31288. }
  31289. PK_INLINE void py_pushnone() {
  31290. VM* vm = pk_current_vm;
  31291. py_newnone(vm->stack.sp++);
  31292. }
  31293. PK_INLINE void py_pushname(py_Name name) {
  31294. VM* vm = pk_current_vm;
  31295. py_newint(vm->stack.sp++, (uintptr_t)name);
  31296. }
  31297. PK_INLINE void py_pop() {
  31298. VM* vm = pk_current_vm;
  31299. vm->stack.sp--;
  31300. }
  31301. PK_INLINE void py_shrink(int n) {
  31302. VM* vm = pk_current_vm;
  31303. vm->stack.sp -= n;
  31304. }
  31305. PK_INLINE py_Ref py_pushtmp() {
  31306. VM* vm = pk_current_vm;
  31307. return vm->stack.sp++;
  31308. }
  31309. PK_INLINE bool py_pushmethod(py_Name name) {
  31310. bool ok = pk_loadmethod(py_peek(-1), name);
  31311. if(ok) pk_current_vm->stack.sp++;
  31312. return ok;
  31313. }
  31314. bool py_pusheval(const char* expr, py_GlobalRef module) {
  31315. bool ok = py_exec(expr, "<string>", EVAL_MODE, module);
  31316. if(!ok) return false;
  31317. py_push(py_retval());
  31318. return true;
  31319. }
  31320. PK_INLINE bool py_vectorcall(uint16_t argc, uint16_t kwargc) {
  31321. return VM__vectorcall(pk_current_vm, argc, kwargc, false) != RES_ERROR;
  31322. }
  31323. bool py_call(py_Ref f, int argc, py_Ref argv) {
  31324. if(f->type == tp_nativefunc) {
  31325. return py_callcfunc(f->_cfunc, argc, argv);
  31326. } else {
  31327. py_push(f);
  31328. py_pushnil();
  31329. for(int i = 0; i < argc; i++)
  31330. py_push(py_offset(argv, i));
  31331. bool ok = py_vectorcall(argc, 0);
  31332. return ok;
  31333. }
  31334. }
  31335. #ifndef NDEBUG
  31336. bool py_callcfunc(py_CFunction f, int argc, py_Ref argv) {
  31337. if(py_checkexc()) {
  31338. const char* name = py_tpname(pk_current_vm->unhandled_exc.type);
  31339. c11__abort("unhandled exception `%s` was set!", name);
  31340. }
  31341. py_StackRef p0 = py_peek(0);
  31342. // NOTE: sometimes users are using `py_retval()` to pass `argv`
  31343. // It will be reset to `nil` and cause an exception
  31344. py_newnil(py_retval());
  31345. bool ok = f(argc, argv);
  31346. if(!ok) {
  31347. if(!py_checkexc()) { c11__abort("py_CFunction returns `false` but no exception is set!"); }
  31348. return false;
  31349. }
  31350. if(py_peek(0) != p0) {
  31351. c11__abort("py_CFunction corrupts the stack! Did you forget to call `py_pop()`?");
  31352. }
  31353. if(py_isnil(py_retval())) {
  31354. c11__abort(
  31355. "py_CFunction returns nothing! Did you forget to call `py_newnone(py_retval())`?");
  31356. }
  31357. if(py_checkexc()) {
  31358. const char* name = py_tpname(pk_current_vm->unhandled_exc.type);
  31359. c11__abort("py_CFunction returns `true`, but `%s` was set!", name);
  31360. }
  31361. return true;
  31362. }
  31363. #endif
  31364. bool py_tpcall(py_Type type, int argc, py_Ref argv) {
  31365. return py_call(py_tpobject(type), argc, argv);
  31366. }
  31367. bool py_binaryop(py_Ref lhs, py_Ref rhs, py_Name op, py_Name rop) {
  31368. py_push(lhs);
  31369. py_push(rhs);
  31370. bool ok = pk_stack_binaryop(pk_current_vm, op, rop);
  31371. py_shrink(2);
  31372. return ok;
  31373. }
  31374. bool pk_loadmethod(py_StackRef self, py_Name name) {
  31375. // NOTE: `out` and `out_self` may overlap with `self`
  31376. py_Type type;
  31377. if(name == __new__) {
  31378. // __new__ acts like a @staticmethod
  31379. if(self->type == tp_type) {
  31380. // T.__new__(...)
  31381. type = py_totype(self);
  31382. } else if(self->type == tp_super) {
  31383. // super(T, obj).__new__(...)
  31384. type = *(py_Type*)py_touserdata(self);
  31385. } else {
  31386. // invalid usage of `__new__`
  31387. return false;
  31388. }
  31389. py_Ref cls_var = py_tpfindmagic(type, name);
  31390. if(cls_var) {
  31391. self[0] = *cls_var;
  31392. self[1] = *py_NIL();
  31393. return true;
  31394. }
  31395. return false;
  31396. }
  31397. py_TValue self_bak; // to avoid overlapping
  31398. // handle super() proxy
  31399. if(py_istype(self, tp_super)) {
  31400. type = *(py_Type*)py_touserdata(self);
  31401. // BUG: here we modify `self` which refers to the stack directly
  31402. // If `pk_loadmethod` fails, `self` will be corrupted
  31403. self_bak = *py_getslot(self, 0);
  31404. } else {
  31405. type = self->type;
  31406. self_bak = *self;
  31407. }
  31408. py_TypeInfo* ti = pk_typeinfo(type);
  31409. if(ti->getunboundmethod) {
  31410. bool ok = ti->getunboundmethod(self, name);
  31411. if(ok) {
  31412. assert(py_retval()->type == tp_nativefunc || py_retval()->type == tp_function);
  31413. self[0] = *py_retval();
  31414. self[1] = self_bak;
  31415. return true;
  31416. } else {
  31417. return false;
  31418. }
  31419. }
  31420. py_Ref cls_var = pk_tpfindname(ti, name);
  31421. if(cls_var != NULL) {
  31422. switch(cls_var->type) {
  31423. case tp_function:
  31424. case tp_nativefunc: {
  31425. self[0] = *cls_var;
  31426. self[1] = self_bak;
  31427. break;
  31428. }
  31429. case tp_staticmethod:
  31430. self[0] = *py_getslot(cls_var, 0);
  31431. self[1] = *py_NIL();
  31432. break;
  31433. case tp_classmethod:
  31434. self[0] = *py_getslot(cls_var, 0);
  31435. self[1] = ti->self;
  31436. break;
  31437. default: return false;
  31438. }
  31439. return true;
  31440. }
  31441. return false;
  31442. }
  31443. bool pk_callmagic(py_Name name, int argc, py_Ref argv) {
  31444. assert(argc >= 1);
  31445. // assert(py_ismagicname(name));
  31446. py_Ref tmp = py_tpfindmagic(argv->type, name);
  31447. if(!tmp) return AttributeError(argv, name);
  31448. return py_call(tmp, argc, argv);
  31449. }
  31450. // src/public\TypeSystem.c
  31451. py_Type py_newtype(const char* name, py_Type base, const py_GlobalRef module, void (*dtor)(void*)) {
  31452. if(strlen(name) == 0) c11__abort("type name cannot be empty");
  31453. py_Type type = pk_newtype(name, base, module, dtor, false, false);
  31454. if(module) py_setdict(module, py_name(name), py_tpobject(type));
  31455. return type;
  31456. }
  31457. PK_INLINE bool py_istype(py_Ref self, py_Type type) { return self->type == type; }
  31458. PK_INLINE py_Type py_typeof(py_Ref self) { return self->type; }
  31459. bool py_isinstance(py_Ref obj, py_Type type) { return py_issubclass(obj->type, type); }
  31460. bool py_issubclass(py_Type derived, py_Type base) {
  31461. assert(derived != 0 && base != 0);
  31462. py_TypeInfo* derived_ti = pk_typeinfo(derived);
  31463. py_TypeInfo* base_ti = pk_typeinfo(base);
  31464. do {
  31465. if(derived_ti == base_ti) return true;
  31466. derived_ti = derived_ti->base_ti;
  31467. } while(derived_ti);
  31468. return false;
  31469. }
  31470. py_Type py_gettype(const char* module, py_Name name) {
  31471. py_Ref mod;
  31472. if(module != NULL) {
  31473. mod = py_getmodule(module);
  31474. if(!mod) return tp_nil;
  31475. } else {
  31476. mod = pk_current_vm->builtins;
  31477. }
  31478. py_Ref object = py_getdict(mod, name);
  31479. if(object && py_istype(object, tp_type)) return py_totype(object);
  31480. return tp_nil;
  31481. }
  31482. bool py_checktype(py_Ref self, py_Type type) {
  31483. if(self->type == type) return true;
  31484. return TypeError("expected '%t', got '%t'", type, self->type);
  31485. }
  31486. bool py_checkinstance(py_Ref self, py_Type type) {
  31487. if(py_isinstance(self, type)) return true;
  31488. return TypeError("expected '%t' or its subclass, got '%t'", type, self->type);
  31489. }
  31490. PK_DEPRECATED py_Ref py_tpgetmagic(py_Type type, py_Name name) {
  31491. // assert(py_ismagicname(name));
  31492. py_TypeInfo* ti = pk_typeinfo(type);
  31493. py_Ref retval = py_getdict(&ti->self, name);
  31494. return retval != NULL ? retval : py_NIL();
  31495. }
  31496. PK_INLINE py_Ref py_tpfindmagic(py_Type t, py_Name name) {
  31497. // assert(py_ismagicname(name));
  31498. return py_tpfindname(t, name);
  31499. }
  31500. PK_INLINE py_ItemRef py_tpfindname(py_Type type, py_Name name) {
  31501. py_TypeInfo* ti = pk_typeinfo(type);
  31502. return pk_tpfindname(ti, name);
  31503. }
  31504. PK_INLINE py_Type py_tpbase(py_Type t) {
  31505. assert(t);
  31506. py_TypeInfo* ti = pk_typeinfo(t);
  31507. return ti->base;
  31508. }
  31509. py_Ref py_tpobject(py_Type type) {
  31510. assert(type);
  31511. return &pk_typeinfo(type)->self;
  31512. }
  31513. const char* py_tpname(py_Type type) {
  31514. if(!type) return "nil";
  31515. py_Name name = pk_typeinfo(type)->name;
  31516. return py_name2str(name);
  31517. }
  31518. void py_tpsetfinal(py_Type type) {
  31519. assert(type);
  31520. py_TypeInfo* ti = pk_typeinfo(type);
  31521. ti->is_final = true;
  31522. }
  31523. void py_tphookattributes(py_Type type,
  31524. bool (*getattribute)(py_Ref self, py_Name name),
  31525. bool (*setattribute)(py_Ref self, py_Name name, py_Ref val),
  31526. bool (*delattribute)(py_Ref self, py_Name name),
  31527. bool (*getunboundmethod)(py_Ref self, py_Name name)) {
  31528. assert(type);
  31529. py_TypeInfo* ti = pk_typeinfo(type);
  31530. ti->getattribute = getattribute;
  31531. ti->setattribute = setattribute;
  31532. ti->delattribute = delattribute;
  31533. ti->getunboundmethod = getunboundmethod;
  31534. }
  31535. // src/public\ValueCast.c
  31536. py_i64 py_toint(py_Ref self) {
  31537. assert(self->type == tp_int);
  31538. return self->_i64;
  31539. }
  31540. void* py_totrivial(py_Ref self) { return &self->_chars; }
  31541. double py_tofloat(py_Ref self) {
  31542. assert(self->type == tp_float);
  31543. return self->_f64;
  31544. }
  31545. bool py_castfloat(py_Ref self, double* out) {
  31546. switch(self->type) {
  31547. case tp_int: *out = (double)self->_i64; return true;
  31548. case tp_float: *out = self->_f64; return true;
  31549. default: return TypeError("expected 'int' or 'float', got '%t'", self->type);
  31550. }
  31551. }
  31552. bool py_castfloat32(py_Ref self, float* out) {
  31553. switch(self->type) {
  31554. case tp_int: *out = (float)self->_i64; return true;
  31555. case tp_float: *out = (float)self->_f64; return true;
  31556. default: return TypeError("expected 'int' or 'float', got '%t'", self->type);
  31557. }
  31558. }
  31559. bool py_castint(py_Ref self, int64_t* out) {
  31560. if(self->type == tp_int) {
  31561. *out = self->_i64;
  31562. return true;
  31563. }
  31564. return TypeError("expected 'int', got '%t'", self->type);
  31565. }
  31566. bool py_tobool(py_Ref self) {
  31567. assert(self->type == tp_bool);
  31568. return self->_bool;
  31569. }
  31570. py_Type py_totype(py_Ref self) {
  31571. assert(self->type == tp_type);
  31572. py_TypeInfo* ud = py_touserdata(self);
  31573. return ud->index;
  31574. }
  31575. void* py_touserdata(py_Ref self) {
  31576. assert(self && self->is_ptr);
  31577. return PyObject__userdata(self->_obj);
  31578. }
  31579. const char* py_tostr(py_Ref self) { return pk_tostr(self)->data; }
  31580. const char* py_tostrn(py_Ref self, int* size) {
  31581. c11_string* ud = pk_tostr(self);
  31582. *size = ud->size;
  31583. return ud->data;
  31584. }
  31585. c11_sv py_tosv(py_Ref self) {
  31586. c11_string* ud = pk_tostr(self);
  31587. return c11_string__sv(ud);
  31588. }
  31589. unsigned char* py_tobytes(py_Ref self, int* size) {
  31590. assert(self->type == tp_bytes);
  31591. c11_bytes* ud = PyObject__userdata(self->_obj);
  31592. *size = ud->size;
  31593. return ud->data;
  31594. }
  31595. void py_bytes_resize(py_Ref self, int size) {
  31596. assert(self->type == tp_bytes);
  31597. c11_bytes* ud = PyObject__userdata(self->_obj);
  31598. if(size > ud->size) c11__abort("bytes can only be resized down: %d > %d", ud->size, size);
  31599. ud->size = size;
  31600. }
  31601. // src/public\ValueCreation.c
  31602. void py_newint(py_OutRef out, py_i64 val) {
  31603. out->type = tp_int;
  31604. out->is_ptr = false;
  31605. out->_i64 = val;
  31606. }
  31607. void py_newtrivial(py_OutRef out, py_Type type, void* data, int size) {
  31608. out->type = type;
  31609. out->is_ptr = false;
  31610. assert(size <= 16);
  31611. memcpy(&out->_chars, data, size);
  31612. }
  31613. void py_newfloat(py_OutRef out, py_f64 val) {
  31614. out->type = tp_float;
  31615. out->is_ptr = false;
  31616. out->_f64 = val;
  31617. }
  31618. void py_newbool(py_OutRef out, bool val) {
  31619. out->type = tp_bool;
  31620. out->is_ptr = false;
  31621. out->_bool = val;
  31622. }
  31623. void py_newstr(py_OutRef out, const char* data) { py_newstrv(out, (c11_sv){data, strlen(data)}); }
  31624. char* py_newstrn(py_OutRef out, int size) {
  31625. if(size < 16) {
  31626. out->type = tp_str;
  31627. out->is_ptr = false;
  31628. c11_string* ud = (c11_string*)(&out->extra);
  31629. c11_string__ctor3(ud, size);
  31630. return ud->data;
  31631. }
  31632. ManagedHeap* heap = &pk_current_vm->heap;
  31633. int total_size = sizeof(c11_string) + size + 1;
  31634. PyObject* obj = ManagedHeap__gcnew(heap, tp_str, 0, total_size);
  31635. c11_string* ud = PyObject__userdata(obj);
  31636. c11_string__ctor3(ud, size);
  31637. out->type = tp_str;
  31638. out->is_ptr = true;
  31639. out->_obj = obj;
  31640. return ud->data;
  31641. }
  31642. void py_newstrv(py_OutRef out, c11_sv sv) {
  31643. char* data = py_newstrn(out, sv.size);
  31644. memcpy(data, sv.data, sv.size);
  31645. }
  31646. void py_newfstr(py_OutRef out, const char* fmt, ...) {
  31647. c11_sbuf buf;
  31648. c11_sbuf__ctor(&buf);
  31649. va_list args;
  31650. va_start(args, fmt);
  31651. pk_vsprintf(&buf, fmt, args);
  31652. va_end(args);
  31653. c11_sbuf__py_submit(&buf, out);
  31654. }
  31655. unsigned char* py_newbytes(py_OutRef out, int size) {
  31656. ManagedHeap* heap = &pk_current_vm->heap;
  31657. // 4 bytes size + data
  31658. PyObject* obj = ManagedHeap__gcnew(heap, tp_bytes, 0, sizeof(c11_bytes) + size);
  31659. c11_bytes* ud = PyObject__userdata(obj);
  31660. ud->size = size;
  31661. out->type = tp_bytes;
  31662. out->is_ptr = true;
  31663. out->_obj = obj;
  31664. return ud->data;
  31665. }
  31666. void py_newnone(py_OutRef out) {
  31667. out->type = tp_NoneType;
  31668. out->is_ptr = false;
  31669. }
  31670. void py_newnotimplemented(py_OutRef out) {
  31671. out->type = tp_NotImplementedType;
  31672. out->is_ptr = false;
  31673. }
  31674. void py_newellipsis(py_OutRef out) {
  31675. out->type = tp_ellipsis;
  31676. out->is_ptr = false;
  31677. }
  31678. void py_newnil(py_OutRef out) {
  31679. out->type = tp_nil;
  31680. out->is_ptr = false;
  31681. }
  31682. void py_newnativefunc(py_OutRef out, py_CFunction f) {
  31683. out->type = tp_nativefunc;
  31684. out->is_ptr = false;
  31685. out->_cfunc = f;
  31686. }
  31687. py_Name py_newfunction(py_OutRef out,
  31688. const char* sig,
  31689. py_CFunction f,
  31690. const char* docstring,
  31691. int slots) {
  31692. char buffer[256];
  31693. snprintf(buffer, sizeof(buffer), "def %s: pass", sig);
  31694. // fn(a, b, *c, d=1) -> None
  31695. CodeObject code;
  31696. SourceData_ source = SourceData__rcnew(buffer, "<bind>", EXEC_MODE, false);
  31697. Error* err = pk_compile(source, &code);
  31698. if(err || code.func_decls.length != 1) {
  31699. c11__abort("py_newfunction(): invalid signature '%s'", sig);
  31700. }
  31701. FuncDecl_ decl = c11__getitem(FuncDecl_, &code.func_decls, 0);
  31702. if(docstring) decl->docstring = c11_strdup(docstring);
  31703. // construct the function
  31704. Function* ud = py_newobject(out, tp_function, slots, sizeof(Function));
  31705. Function__ctor(ud, decl, NULL, NULL);
  31706. ud->cfunc = f;
  31707. CodeObject__dtor(&code);
  31708. PK_DECREF(source);
  31709. assert(decl->rc.count == 1);
  31710. py_Name decl_name = py_name(ud->decl->code.name->data);
  31711. if(decl_name == __new__ || decl_name == __init__) {
  31712. if(ud->decl->args.length == 0) {
  31713. c11__abort("%s() should have at least one positional argument", py_name2str(decl_name));
  31714. }
  31715. }
  31716. return decl_name;
  31717. }
  31718. void py_newboundmethod(py_OutRef out, py_Ref self, py_Ref func) {
  31719. py_newobject(out, tp_boundmethod, 2, 0);
  31720. py_setslot(out, 0, self);
  31721. py_setslot(out, 1, func);
  31722. }
  31723. void* py_newobject(py_OutRef out, py_Type type, int slots, int udsize) {
  31724. ManagedHeap* heap = &pk_current_vm->heap;
  31725. PyObject* obj = ManagedHeap__gcnew(heap, type, slots, udsize);
  31726. out->type = type;
  31727. out->is_ptr = true;
  31728. out->_obj = obj;
  31729. return PyObject__userdata(obj);
  31730. }