compile.c 253 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168
  1. /*
  2. * This file compiles an abstract syntax tree (AST) into Python bytecode.
  3. *
  4. * The primary entry point is _PyAST_Compile(), which returns a
  5. * PyCodeObject. The compiler makes several passes to build the code
  6. * object:
  7. * 1. Checks for future statements. See future.c
  8. * 2. Builds a symbol table. See symtable.c.
  9. * 3. Generate an instruction sequence. See compiler_mod() in this file.
  10. * 4. Generate a control flow graph and run optimizations on it. See flowgraph.c.
  11. * 5. Assemble the basic blocks into final code. See optimize_and_assemble() in
  12. * this file, and assembler.c.
  13. *
  14. * Note that compiler_mod() suggests module, but the module ast type
  15. * (mod_ty) has cases for expressions and interactive statements.
  16. *
  17. * CAUTION: The VISIT_* macros abort the current function when they
  18. * encounter a problem. So don't invoke them when there is memory
  19. * which needs to be released. Code blocks are OK, as the compiler
  20. * structure takes care of releasing those. Use the arena to manage
  21. * objects.
  22. */
  23. #include <stdbool.h>
  24. #include "Python.h"
  25. #include "pycore_ast.h" // _PyAST_GetDocString()
  26. #define NEED_OPCODE_TABLES
  27. #include "pycore_opcode_utils.h"
  28. #undef NEED_OPCODE_TABLES
  29. #include "pycore_flowgraph.h"
  30. #include "pycore_code.h" // _PyCode_New()
  31. #include "pycore_compile.h"
  32. #include "pycore_intrinsics.h"
  33. #include "pycore_long.h" // _PyLong_GetZero()
  34. #include "pycore_pymem.h" // _PyMem_IsPtrFreed()
  35. #include "pycore_symtable.h" // PySTEntryObject, _PyFuture_FromAST()
  36. #include "opcode_metadata.h" // _PyOpcode_opcode_metadata, _PyOpcode_num_popped/pushed
  37. #define DEFAULT_CODE_SIZE 128
  38. #define DEFAULT_LNOTAB_SIZE 16
  39. #define DEFAULT_CNOTAB_SIZE 32
  40. #define COMP_GENEXP 0
  41. #define COMP_LISTCOMP 1
  42. #define COMP_SETCOMP 2
  43. #define COMP_DICTCOMP 3
  44. /* A soft limit for stack use, to avoid excessive
  45. * memory use for large constants, etc.
  46. *
  47. * The value 30 is plucked out of thin air.
  48. * Code that could use more stack than this is
  49. * rare, so the exact value is unimportant.
  50. */
  51. #define STACK_USE_GUIDELINE 30
  52. #undef SUCCESS
  53. #undef ERROR
  54. #define SUCCESS 0
  55. #define ERROR -1
  56. #define RETURN_IF_ERROR(X) \
  57. if ((X) == -1) { \
  58. return ERROR; \
  59. }
  60. /* If we exceed this limit, it should
  61. * be considered a compiler bug.
  62. * Currently it should be impossible
  63. * to exceed STACK_USE_GUIDELINE * 100,
  64. * as 100 is the maximum parse depth.
  65. * For performance reasons we will
  66. * want to reduce this to a
  67. * few hundred in the future.
  68. *
  69. * NOTE: Whatever MAX_ALLOWED_STACK_USE is
  70. * set to, it should never restrict what Python
  71. * we can write, just how we compile it.
  72. */
  73. #define MAX_ALLOWED_STACK_USE (STACK_USE_GUIDELINE * 100)
  74. #define IS_TOP_LEVEL_AWAIT(C) ( \
  75. ((C)->c_flags.cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
  76. && ((C)->u->u_ste->ste_type == ModuleBlock))
  77. typedef _PyCompilerSrcLocation location;
  78. typedef _PyCfgInstruction cfg_instr;
  79. typedef _PyCfgBasicblock basicblock;
  80. typedef _PyCfgBuilder cfg_builder;
  81. #define LOCATION(LNO, END_LNO, COL, END_COL) \
  82. ((const _PyCompilerSrcLocation){(LNO), (END_LNO), (COL), (END_COL)})
  83. /* Return true if loc1 starts after loc2 ends. */
  84. static inline bool
  85. location_is_after(location loc1, location loc2) {
  86. return (loc1.lineno > loc2.end_lineno) ||
  87. ((loc1.lineno == loc2.end_lineno) &&
  88. (loc1.col_offset > loc2.end_col_offset));
  89. }
  90. #define LOC(x) SRC_LOCATION_FROM_AST(x)
  91. typedef _PyCfgJumpTargetLabel jump_target_label;
  92. static jump_target_label NO_LABEL = {-1};
  93. #define SAME_LABEL(L1, L2) ((L1).id == (L2).id)
  94. #define IS_LABEL(L) (!SAME_LABEL((L), (NO_LABEL)))
  95. #define NEW_JUMP_TARGET_LABEL(C, NAME) \
  96. jump_target_label NAME = instr_sequence_new_label(INSTR_SEQUENCE(C)); \
  97. if (!IS_LABEL(NAME)) { \
  98. return ERROR; \
  99. }
  100. #define USE_LABEL(C, LBL) \
  101. RETURN_IF_ERROR(instr_sequence_use_label(INSTR_SEQUENCE(C), (LBL).id))
  102. /* fblockinfo tracks the current frame block.
  103. A frame block is used to handle loops, try/except, and try/finally.
  104. It's called a frame block to distinguish it from a basic block in the
  105. compiler IR.
  106. */
  107. enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
  108. WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER,
  109. EXCEPTION_GROUP_HANDLER, ASYNC_COMPREHENSION_GENERATOR,
  110. STOP_ITERATION };
  111. struct fblockinfo {
  112. enum fblocktype fb_type;
  113. jump_target_label fb_block;
  114. /* (optional) type-specific exit or cleanup block */
  115. jump_target_label fb_exit;
  116. /* (optional) additional information required for unwinding */
  117. void *fb_datum;
  118. };
  119. enum {
  120. COMPILER_SCOPE_MODULE,
  121. COMPILER_SCOPE_CLASS,
  122. COMPILER_SCOPE_FUNCTION,
  123. COMPILER_SCOPE_ASYNC_FUNCTION,
  124. COMPILER_SCOPE_LAMBDA,
  125. COMPILER_SCOPE_COMPREHENSION,
  126. COMPILER_SCOPE_TYPEPARAMS,
  127. };
  128. int
  129. _PyCompile_InstrSize(int opcode, int oparg)
  130. {
  131. assert(!IS_PSEUDO_OPCODE(opcode));
  132. assert(HAS_ARG(opcode) || oparg == 0);
  133. int extended_args = (0xFFFFFF < oparg) + (0xFFFF < oparg) + (0xFF < oparg);
  134. int caches = _PyOpcode_Caches[opcode];
  135. return extended_args + 1 + caches;
  136. }
  137. typedef _PyCompile_Instruction instruction;
  138. typedef _PyCompile_InstructionSequence instr_sequence;
  139. #define INITIAL_INSTR_SEQUENCE_SIZE 100
  140. #define INITIAL_INSTR_SEQUENCE_LABELS_MAP_SIZE 10
  141. /*
  142. * Resize the array if index is out of range.
  143. *
  144. * idx: the index we want to access
  145. * arr: pointer to the array
  146. * alloc: pointer to the capacity of the array
  147. * default_alloc: initial number of items
  148. * item_size: size of each item
  149. *
  150. */
  151. int
  152. _PyCompile_EnsureArrayLargeEnough(int idx, void **array, int *alloc,
  153. int default_alloc, size_t item_size)
  154. {
  155. void *arr = *array;
  156. if (arr == NULL) {
  157. int new_alloc = default_alloc;
  158. if (idx >= new_alloc) {
  159. new_alloc = idx + default_alloc;
  160. }
  161. arr = PyObject_Calloc(new_alloc, item_size);
  162. if (arr == NULL) {
  163. PyErr_NoMemory();
  164. return ERROR;
  165. }
  166. *alloc = new_alloc;
  167. }
  168. else if (idx >= *alloc) {
  169. size_t oldsize = *alloc * item_size;
  170. int new_alloc = *alloc << 1;
  171. if (idx >= new_alloc) {
  172. new_alloc = idx + default_alloc;
  173. }
  174. size_t newsize = new_alloc * item_size;
  175. if (oldsize > (SIZE_MAX >> 1)) {
  176. PyErr_NoMemory();
  177. return ERROR;
  178. }
  179. assert(newsize > 0);
  180. void *tmp = PyObject_Realloc(arr, newsize);
  181. if (tmp == NULL) {
  182. PyErr_NoMemory();
  183. return ERROR;
  184. }
  185. *alloc = new_alloc;
  186. arr = tmp;
  187. memset((char *)arr + oldsize, 0, newsize - oldsize);
  188. }
  189. *array = arr;
  190. return SUCCESS;
  191. }
  192. static int
  193. instr_sequence_next_inst(instr_sequence *seq) {
  194. assert(seq->s_instrs != NULL || seq->s_used == 0);
  195. RETURN_IF_ERROR(
  196. _PyCompile_EnsureArrayLargeEnough(seq->s_used + 1,
  197. (void**)&seq->s_instrs,
  198. &seq->s_allocated,
  199. INITIAL_INSTR_SEQUENCE_SIZE,
  200. sizeof(instruction)));
  201. assert(seq->s_allocated >= 0);
  202. assert(seq->s_used < seq->s_allocated);
  203. return seq->s_used++;
  204. }
  205. static jump_target_label
  206. instr_sequence_new_label(instr_sequence *seq)
  207. {
  208. jump_target_label lbl = {++seq->s_next_free_label};
  209. return lbl;
  210. }
  211. static int
  212. instr_sequence_use_label(instr_sequence *seq, int lbl) {
  213. int old_size = seq->s_labelmap_size;
  214. RETURN_IF_ERROR(
  215. _PyCompile_EnsureArrayLargeEnough(lbl,
  216. (void**)&seq->s_labelmap,
  217. &seq->s_labelmap_size,
  218. INITIAL_INSTR_SEQUENCE_LABELS_MAP_SIZE,
  219. sizeof(int)));
  220. for(int i = old_size; i < seq->s_labelmap_size; i++) {
  221. seq->s_labelmap[i] = -111; /* something weird, for debugging */
  222. }
  223. seq->s_labelmap[lbl] = seq->s_used; /* label refers to the next instruction */
  224. return SUCCESS;
  225. }
  226. static int
  227. instr_sequence_addop(instr_sequence *seq, int opcode, int oparg, location loc)
  228. {
  229. assert(IS_WITHIN_OPCODE_RANGE(opcode));
  230. assert(HAS_ARG(opcode) || HAS_TARGET(opcode) || oparg == 0);
  231. assert(0 <= oparg && oparg < (1 << 30));
  232. int idx = instr_sequence_next_inst(seq);
  233. RETURN_IF_ERROR(idx);
  234. instruction *ci = &seq->s_instrs[idx];
  235. ci->i_opcode = opcode;
  236. ci->i_oparg = oparg;
  237. ci->i_loc = loc;
  238. return SUCCESS;
  239. }
  240. static int
  241. instr_sequence_insert_instruction(instr_sequence *seq, int pos,
  242. int opcode, int oparg, location loc)
  243. {
  244. assert(pos >= 0 && pos <= seq->s_used);
  245. int last_idx = instr_sequence_next_inst(seq);
  246. RETURN_IF_ERROR(last_idx);
  247. for (int i=last_idx-1; i >= pos; i--) {
  248. seq->s_instrs[i+1] = seq->s_instrs[i];
  249. }
  250. instruction *ci = &seq->s_instrs[pos];
  251. ci->i_opcode = opcode;
  252. ci->i_oparg = oparg;
  253. ci->i_loc = loc;
  254. /* fix the labels map */
  255. for(int lbl=0; lbl < seq->s_labelmap_size; lbl++) {
  256. if (seq->s_labelmap[lbl] >= pos) {
  257. seq->s_labelmap[lbl]++;
  258. }
  259. }
  260. return SUCCESS;
  261. }
  262. static void
  263. instr_sequence_fini(instr_sequence *seq) {
  264. PyObject_Free(seq->s_labelmap);
  265. seq->s_labelmap = NULL;
  266. PyObject_Free(seq->s_instrs);
  267. seq->s_instrs = NULL;
  268. }
  269. static int
  270. instr_sequence_to_cfg(instr_sequence *seq, cfg_builder *g) {
  271. memset(g, 0, sizeof(cfg_builder));
  272. RETURN_IF_ERROR(_PyCfgBuilder_Init(g));
  273. /* There can be more than one label for the same offset. The
  274. * offset2lbl maping selects one of them which we use consistently.
  275. */
  276. int *offset2lbl = PyMem_Malloc(seq->s_used * sizeof(int));
  277. if (offset2lbl == NULL) {
  278. PyErr_NoMemory();
  279. return ERROR;
  280. }
  281. for (int i = 0; i < seq->s_used; i++) {
  282. offset2lbl[i] = -1;
  283. }
  284. for (int lbl=0; lbl < seq->s_labelmap_size; lbl++) {
  285. int offset = seq->s_labelmap[lbl];
  286. if (offset >= 0) {
  287. assert(offset < seq->s_used);
  288. offset2lbl[offset] = lbl;
  289. }
  290. }
  291. for (int i = 0; i < seq->s_used; i++) {
  292. int lbl = offset2lbl[i];
  293. if (lbl >= 0) {
  294. assert (lbl < seq->s_labelmap_size);
  295. jump_target_label lbl_ = {lbl};
  296. if (_PyCfgBuilder_UseLabel(g, lbl_) < 0) {
  297. goto error;
  298. }
  299. }
  300. instruction *instr = &seq->s_instrs[i];
  301. int opcode = instr->i_opcode;
  302. int oparg = instr->i_oparg;
  303. if (HAS_TARGET(opcode)) {
  304. int offset = seq->s_labelmap[oparg];
  305. assert(offset >= 0 && offset < seq->s_used);
  306. int lbl = offset2lbl[offset];
  307. assert(lbl >= 0 && lbl < seq->s_labelmap_size);
  308. oparg = lbl;
  309. }
  310. if (_PyCfgBuilder_Addop(g, opcode, oparg, instr->i_loc) < 0) {
  311. goto error;
  312. }
  313. }
  314. PyMem_Free(offset2lbl);
  315. int nblocks = 0;
  316. for (basicblock *b = g->g_block_list; b != NULL; b = b->b_list) {
  317. nblocks++;
  318. }
  319. if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
  320. PyErr_NoMemory();
  321. return ERROR;
  322. }
  323. return SUCCESS;
  324. error:
  325. PyMem_Free(offset2lbl);
  326. return ERROR;
  327. }
  328. /* The following items change on entry and exit of code blocks.
  329. They must be saved and restored when returning to a block.
  330. */
  331. struct compiler_unit {
  332. PySTEntryObject *u_ste;
  333. int u_scope_type;
  334. PyObject *u_private; /* for private name mangling */
  335. instr_sequence u_instr_sequence; /* codegen output */
  336. int u_nfblocks;
  337. int u_in_inlined_comp;
  338. struct fblockinfo u_fblock[CO_MAXBLOCKS];
  339. _PyCompile_CodeUnitMetadata u_metadata;
  340. };
  341. /* This struct captures the global state of a compilation.
  342. The u pointer points to the current compilation unit, while units
  343. for enclosing blocks are stored in c_stack. The u and c_stack are
  344. managed by compiler_enter_scope() and compiler_exit_scope().
  345. Note that we don't track recursion levels during compilation - the
  346. task of detecting and rejecting excessive levels of nesting is
  347. handled by the symbol analysis pass.
  348. */
  349. struct compiler {
  350. PyObject *c_filename;
  351. struct symtable *c_st;
  352. PyFutureFeatures c_future; /* module's __future__ */
  353. PyCompilerFlags c_flags;
  354. int c_optimize; /* optimization level */
  355. int c_interactive; /* true if in interactive mode */
  356. int c_nestlevel;
  357. PyObject *c_const_cache; /* Python dict holding all constants,
  358. including names tuple */
  359. struct compiler_unit *u; /* compiler state for current block */
  360. PyObject *c_stack; /* Python list holding compiler_unit ptrs */
  361. PyArena *c_arena; /* pointer to memory allocation arena */
  362. };
  363. #define INSTR_SEQUENCE(C) (&((C)->u->u_instr_sequence))
  364. typedef struct {
  365. // A list of strings corresponding to name captures. It is used to track:
  366. // - Repeated name assignments in the same pattern.
  367. // - Different name assignments in alternatives.
  368. // - The order of name assignments in alternatives.
  369. PyObject *stores;
  370. // If 0, any name captures against our subject will raise.
  371. int allow_irrefutable;
  372. // An array of blocks to jump to on failure. Jumping to fail_pop[i] will pop
  373. // i items off of the stack. The end result looks like this (with each block
  374. // falling through to the next):
  375. // fail_pop[4]: POP_TOP
  376. // fail_pop[3]: POP_TOP
  377. // fail_pop[2]: POP_TOP
  378. // fail_pop[1]: POP_TOP
  379. // fail_pop[0]: NOP
  380. jump_target_label *fail_pop;
  381. // The current length of fail_pop.
  382. Py_ssize_t fail_pop_size;
  383. // The number of items on top of the stack that need to *stay* on top of the
  384. // stack. Variable captures go beneath these. All of them will be popped on
  385. // failure.
  386. Py_ssize_t on_top;
  387. } pattern_context;
  388. static int codegen_addop_i(instr_sequence *seq, int opcode, Py_ssize_t oparg, location loc);
  389. static void compiler_free(struct compiler *);
  390. static int compiler_error(struct compiler *, location loc, const char *, ...);
  391. static int compiler_warn(struct compiler *, location loc, const char *, ...);
  392. static int compiler_nameop(struct compiler *, location, identifier, expr_context_ty);
  393. static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
  394. static int compiler_visit_stmt(struct compiler *, stmt_ty);
  395. static int compiler_visit_keyword(struct compiler *, keyword_ty);
  396. static int compiler_visit_expr(struct compiler *, expr_ty);
  397. static int compiler_augassign(struct compiler *, stmt_ty);
  398. static int compiler_annassign(struct compiler *, stmt_ty);
  399. static int compiler_subscript(struct compiler *, expr_ty);
  400. static int compiler_slice(struct compiler *, expr_ty);
  401. static bool are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
  402. static int compiler_with(struct compiler *, stmt_ty, int);
  403. static int compiler_async_with(struct compiler *, stmt_ty, int);
  404. static int compiler_async_for(struct compiler *, stmt_ty);
  405. static int compiler_call_simple_kw_helper(struct compiler *c,
  406. location loc,
  407. asdl_keyword_seq *keywords,
  408. Py_ssize_t nkwelts);
  409. static int compiler_call_helper(struct compiler *c, location loc,
  410. int n, asdl_expr_seq *args,
  411. asdl_keyword_seq *keywords);
  412. static int compiler_try_except(struct compiler *, stmt_ty);
  413. static int compiler_try_star_except(struct compiler *, stmt_ty);
  414. static int compiler_set_qualname(struct compiler *);
  415. static int compiler_sync_comprehension_generator(
  416. struct compiler *c, location loc,
  417. asdl_comprehension_seq *generators, int gen_index,
  418. int depth,
  419. expr_ty elt, expr_ty val, int type,
  420. int iter_on_stack);
  421. static int compiler_async_comprehension_generator(
  422. struct compiler *c, location loc,
  423. asdl_comprehension_seq *generators, int gen_index,
  424. int depth,
  425. expr_ty elt, expr_ty val, int type,
  426. int iter_on_stack);
  427. static int compiler_pattern(struct compiler *, pattern_ty, pattern_context *);
  428. static int compiler_match(struct compiler *, stmt_ty);
  429. static int compiler_pattern_subpattern(struct compiler *,
  430. pattern_ty, pattern_context *);
  431. static PyCodeObject *optimize_and_assemble(struct compiler *, int addNone);
  432. #define CAPSULE_NAME "compile.c compiler unit"
  433. static int
  434. compiler_setup(struct compiler *c, mod_ty mod, PyObject *filename,
  435. PyCompilerFlags *flags, int optimize, PyArena *arena)
  436. {
  437. PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
  438. c->c_const_cache = PyDict_New();
  439. if (!c->c_const_cache) {
  440. return ERROR;
  441. }
  442. c->c_stack = PyList_New(0);
  443. if (!c->c_stack) {
  444. return ERROR;
  445. }
  446. c->c_filename = Py_NewRef(filename);
  447. c->c_arena = arena;
  448. if (!_PyFuture_FromAST(mod, filename, &c->c_future)) {
  449. return ERROR;
  450. }
  451. if (!flags) {
  452. flags = &local_flags;
  453. }
  454. int merged = c->c_future.ff_features | flags->cf_flags;
  455. c->c_future.ff_features = merged;
  456. flags->cf_flags = merged;
  457. c->c_flags = *flags;
  458. c->c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
  459. c->c_nestlevel = 0;
  460. _PyASTOptimizeState state;
  461. state.optimize = c->c_optimize;
  462. state.ff_features = merged;
  463. if (!_PyAST_Optimize(mod, arena, &state)) {
  464. return ERROR;
  465. }
  466. c->c_st = _PySymtable_Build(mod, filename, &c->c_future);
  467. if (c->c_st == NULL) {
  468. if (!PyErr_Occurred()) {
  469. PyErr_SetString(PyExc_SystemError, "no symtable");
  470. }
  471. return ERROR;
  472. }
  473. return SUCCESS;
  474. }
  475. static struct compiler*
  476. new_compiler(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
  477. int optimize, PyArena *arena)
  478. {
  479. struct compiler *c = PyMem_Calloc(1, sizeof(struct compiler));
  480. if (c == NULL) {
  481. return NULL;
  482. }
  483. if (compiler_setup(c, mod, filename, pflags, optimize, arena) < 0) {
  484. compiler_free(c);
  485. return NULL;
  486. }
  487. return c;
  488. }
  489. PyCodeObject *
  490. _PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
  491. int optimize, PyArena *arena)
  492. {
  493. assert(!PyErr_Occurred());
  494. struct compiler *c = new_compiler(mod, filename, pflags, optimize, arena);
  495. if (c == NULL) {
  496. return NULL;
  497. }
  498. PyCodeObject *co = compiler_mod(c, mod);
  499. compiler_free(c);
  500. assert(co || PyErr_Occurred());
  501. return co;
  502. }
  503. static void
  504. compiler_free(struct compiler *c)
  505. {
  506. if (c->c_st)
  507. _PySymtable_Free(c->c_st);
  508. Py_XDECREF(c->c_filename);
  509. Py_XDECREF(c->c_const_cache);
  510. Py_XDECREF(c->c_stack);
  511. PyMem_Free(c);
  512. }
  513. static PyObject *
  514. list2dict(PyObject *list)
  515. {
  516. Py_ssize_t i, n;
  517. PyObject *v, *k;
  518. PyObject *dict = PyDict_New();
  519. if (!dict) return NULL;
  520. n = PyList_Size(list);
  521. for (i = 0; i < n; i++) {
  522. v = PyLong_FromSsize_t(i);
  523. if (!v) {
  524. Py_DECREF(dict);
  525. return NULL;
  526. }
  527. k = PyList_GET_ITEM(list, i);
  528. if (PyDict_SetItem(dict, k, v) < 0) {
  529. Py_DECREF(v);
  530. Py_DECREF(dict);
  531. return NULL;
  532. }
  533. Py_DECREF(v);
  534. }
  535. return dict;
  536. }
  537. /* Return new dict containing names from src that match scope(s).
  538. src is a symbol table dictionary. If the scope of a name matches
  539. either scope_type or flag is set, insert it into the new dict. The
  540. values are integers, starting at offset and increasing by one for
  541. each key.
  542. */
  543. static PyObject *
  544. dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
  545. {
  546. Py_ssize_t i = offset, scope, num_keys, key_i;
  547. PyObject *k, *v, *dest = PyDict_New();
  548. PyObject *sorted_keys;
  549. assert(offset >= 0);
  550. if (dest == NULL)
  551. return NULL;
  552. /* Sort the keys so that we have a deterministic order on the indexes
  553. saved in the returned dictionary. These indexes are used as indexes
  554. into the free and cell var storage. Therefore if they aren't
  555. deterministic, then the generated bytecode is not deterministic.
  556. */
  557. sorted_keys = PyDict_Keys(src);
  558. if (sorted_keys == NULL)
  559. return NULL;
  560. if (PyList_Sort(sorted_keys) != 0) {
  561. Py_DECREF(sorted_keys);
  562. return NULL;
  563. }
  564. num_keys = PyList_GET_SIZE(sorted_keys);
  565. for (key_i = 0; key_i < num_keys; key_i++) {
  566. /* XXX this should probably be a macro in symtable.h */
  567. long vi;
  568. k = PyList_GET_ITEM(sorted_keys, key_i);
  569. v = PyDict_GetItemWithError(src, k);
  570. assert(v && PyLong_Check(v));
  571. vi = PyLong_AS_LONG(v);
  572. scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
  573. if (scope == scope_type || vi & flag) {
  574. PyObject *item = PyLong_FromSsize_t(i);
  575. if (item == NULL) {
  576. Py_DECREF(sorted_keys);
  577. Py_DECREF(dest);
  578. return NULL;
  579. }
  580. i++;
  581. if (PyDict_SetItem(dest, k, item) < 0) {
  582. Py_DECREF(sorted_keys);
  583. Py_DECREF(item);
  584. Py_DECREF(dest);
  585. return NULL;
  586. }
  587. Py_DECREF(item);
  588. }
  589. }
  590. Py_DECREF(sorted_keys);
  591. return dest;
  592. }
  593. static void
  594. compiler_unit_free(struct compiler_unit *u)
  595. {
  596. instr_sequence_fini(&u->u_instr_sequence);
  597. Py_CLEAR(u->u_ste);
  598. Py_CLEAR(u->u_metadata.u_name);
  599. Py_CLEAR(u->u_metadata.u_qualname);
  600. Py_CLEAR(u->u_metadata.u_consts);
  601. Py_CLEAR(u->u_metadata.u_names);
  602. Py_CLEAR(u->u_metadata.u_varnames);
  603. Py_CLEAR(u->u_metadata.u_freevars);
  604. Py_CLEAR(u->u_metadata.u_cellvars);
  605. Py_CLEAR(u->u_metadata.u_fasthidden);
  606. Py_CLEAR(u->u_private);
  607. PyObject_Free(u);
  608. }
  609. static int
  610. compiler_set_qualname(struct compiler *c)
  611. {
  612. Py_ssize_t stack_size;
  613. struct compiler_unit *u = c->u;
  614. PyObject *name, *base;
  615. base = NULL;
  616. stack_size = PyList_GET_SIZE(c->c_stack);
  617. assert(stack_size >= 1);
  618. if (stack_size > 1) {
  619. int scope, force_global = 0;
  620. struct compiler_unit *parent;
  621. PyObject *mangled, *capsule;
  622. capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
  623. parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
  624. assert(parent);
  625. if (parent->u_scope_type == COMPILER_SCOPE_TYPEPARAMS) {
  626. /* The parent is a type parameter scope, so we need to
  627. look at the grandparent. */
  628. if (stack_size == 2) {
  629. // If we're immediately within the module, we can skip
  630. // the rest and just set the qualname to be the same as name.
  631. u->u_metadata.u_qualname = Py_NewRef(u->u_metadata.u_name);
  632. return SUCCESS;
  633. }
  634. capsule = PyList_GET_ITEM(c->c_stack, stack_size - 2);
  635. parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
  636. assert(parent);
  637. }
  638. if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
  639. || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
  640. || u->u_scope_type == COMPILER_SCOPE_CLASS) {
  641. assert(u->u_metadata.u_name);
  642. mangled = _Py_Mangle(parent->u_private, u->u_metadata.u_name);
  643. if (!mangled) {
  644. return ERROR;
  645. }
  646. scope = _PyST_GetScope(parent->u_ste, mangled);
  647. Py_DECREF(mangled);
  648. assert(scope != GLOBAL_IMPLICIT);
  649. if (scope == GLOBAL_EXPLICIT)
  650. force_global = 1;
  651. }
  652. if (!force_global) {
  653. if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
  654. || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
  655. || parent->u_scope_type == COMPILER_SCOPE_LAMBDA)
  656. {
  657. _Py_DECLARE_STR(dot_locals, ".<locals>");
  658. base = PyUnicode_Concat(parent->u_metadata.u_qualname,
  659. &_Py_STR(dot_locals));
  660. if (base == NULL) {
  661. return ERROR;
  662. }
  663. }
  664. else {
  665. base = Py_NewRef(parent->u_metadata.u_qualname);
  666. }
  667. }
  668. }
  669. if (base != NULL) {
  670. _Py_DECLARE_STR(dot, ".");
  671. name = PyUnicode_Concat(base, &_Py_STR(dot));
  672. Py_DECREF(base);
  673. if (name == NULL) {
  674. return ERROR;
  675. }
  676. PyUnicode_Append(&name, u->u_metadata.u_name);
  677. if (name == NULL) {
  678. return ERROR;
  679. }
  680. }
  681. else {
  682. name = Py_NewRef(u->u_metadata.u_name);
  683. }
  684. u->u_metadata.u_qualname = name;
  685. return SUCCESS;
  686. }
  687. /* Return the stack effect of opcode with argument oparg.
  688. Some opcodes have different stack effect when jump to the target and
  689. when not jump. The 'jump' parameter specifies the case:
  690. * 0 -- when not jump
  691. * 1 -- when jump
  692. * -1 -- maximal
  693. */
  694. static int
  695. stack_effect(int opcode, int oparg, int jump)
  696. {
  697. if (0 <= opcode && opcode <= MAX_REAL_OPCODE) {
  698. if (_PyOpcode_Deopt[opcode] != opcode) {
  699. // Specialized instructions are not supported.
  700. return PY_INVALID_STACK_EFFECT;
  701. }
  702. int popped, pushed;
  703. if (jump > 0) {
  704. popped = _PyOpcode_num_popped(opcode, oparg, true);
  705. pushed = _PyOpcode_num_pushed(opcode, oparg, true);
  706. }
  707. else {
  708. popped = _PyOpcode_num_popped(opcode, oparg, false);
  709. pushed = _PyOpcode_num_pushed(opcode, oparg, false);
  710. }
  711. if (popped < 0 || pushed < 0) {
  712. return PY_INVALID_STACK_EFFECT;
  713. }
  714. if (jump >= 0) {
  715. return pushed - popped;
  716. }
  717. if (jump < 0) {
  718. // Compute max(pushed - popped, alt_pushed - alt_popped)
  719. int alt_popped = _PyOpcode_num_popped(opcode, oparg, true);
  720. int alt_pushed = _PyOpcode_num_pushed(opcode, oparg, true);
  721. if (alt_popped < 0 || alt_pushed < 0) {
  722. return PY_INVALID_STACK_EFFECT;
  723. }
  724. int diff = pushed - popped;
  725. int alt_diff = alt_pushed - alt_popped;
  726. if (alt_diff > diff) {
  727. return alt_diff;
  728. }
  729. return diff;
  730. }
  731. }
  732. // Pseudo ops
  733. switch (opcode) {
  734. case POP_BLOCK:
  735. case JUMP:
  736. case JUMP_NO_INTERRUPT:
  737. return 0;
  738. /* Exception handling pseudo-instructions */
  739. case SETUP_FINALLY:
  740. /* 0 in the normal flow.
  741. * Restore the stack position and push 1 value before jumping to
  742. * the handler if an exception be raised. */
  743. return jump ? 1 : 0;
  744. case SETUP_CLEANUP:
  745. /* As SETUP_FINALLY, but pushes lasti as well */
  746. return jump ? 2 : 0;
  747. case SETUP_WITH:
  748. /* 0 in the normal flow.
  749. * Restore the stack position to the position before the result
  750. * of __(a)enter__ and push 2 values before jumping to the handler
  751. * if an exception be raised. */
  752. return jump ? 1 : 0;
  753. case STORE_FAST_MAYBE_NULL:
  754. return -1;
  755. case LOAD_METHOD:
  756. return 1;
  757. case LOAD_SUPER_METHOD:
  758. case LOAD_ZERO_SUPER_METHOD:
  759. case LOAD_ZERO_SUPER_ATTR:
  760. return -1;
  761. default:
  762. return PY_INVALID_STACK_EFFECT;
  763. }
  764. return PY_INVALID_STACK_EFFECT; /* not reachable */
  765. }
  766. int
  767. PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
  768. {
  769. return stack_effect(opcode, oparg, jump);
  770. }
  771. int
  772. PyCompile_OpcodeStackEffect(int opcode, int oparg)
  773. {
  774. return stack_effect(opcode, oparg, -1);
  775. }
  776. static int
  777. codegen_addop_noarg(instr_sequence *seq, int opcode, location loc)
  778. {
  779. assert(!HAS_ARG(opcode));
  780. assert(!IS_ASSEMBLER_OPCODE(opcode));
  781. return instr_sequence_addop(seq, opcode, 0, loc);
  782. }
  783. static Py_ssize_t
  784. dict_add_o(PyObject *dict, PyObject *o)
  785. {
  786. PyObject *v;
  787. Py_ssize_t arg;
  788. v = PyDict_GetItemWithError(dict, o);
  789. if (!v) {
  790. if (PyErr_Occurred()) {
  791. return ERROR;
  792. }
  793. arg = PyDict_GET_SIZE(dict);
  794. v = PyLong_FromSsize_t(arg);
  795. if (!v) {
  796. return ERROR;
  797. }
  798. if (PyDict_SetItem(dict, o, v) < 0) {
  799. Py_DECREF(v);
  800. return ERROR;
  801. }
  802. Py_DECREF(v);
  803. }
  804. else
  805. arg = PyLong_AsLong(v);
  806. return arg;
  807. }
  808. // Merge const *o* recursively and return constant key object.
  809. static PyObject*
  810. merge_consts_recursive(PyObject *const_cache, PyObject *o)
  811. {
  812. assert(PyDict_CheckExact(const_cache));
  813. // None and Ellipsis are singleton, and key is the singleton.
  814. // No need to merge object and key.
  815. if (o == Py_None || o == Py_Ellipsis) {
  816. return Py_NewRef(o);
  817. }
  818. PyObject *key = _PyCode_ConstantKey(o);
  819. if (key == NULL) {
  820. return NULL;
  821. }
  822. // t is borrowed reference
  823. PyObject *t = PyDict_SetDefault(const_cache, key, key);
  824. if (t != key) {
  825. // o is registered in const_cache. Just use it.
  826. Py_XINCREF(t);
  827. Py_DECREF(key);
  828. return t;
  829. }
  830. // We registered o in const_cache.
  831. // When o is a tuple or frozenset, we want to merge its
  832. // items too.
  833. if (PyTuple_CheckExact(o)) {
  834. Py_ssize_t len = PyTuple_GET_SIZE(o);
  835. for (Py_ssize_t i = 0; i < len; i++) {
  836. PyObject *item = PyTuple_GET_ITEM(o, i);
  837. PyObject *u = merge_consts_recursive(const_cache, item);
  838. if (u == NULL) {
  839. Py_DECREF(key);
  840. return NULL;
  841. }
  842. // See _PyCode_ConstantKey()
  843. PyObject *v; // borrowed
  844. if (PyTuple_CheckExact(u)) {
  845. v = PyTuple_GET_ITEM(u, 1);
  846. }
  847. else {
  848. v = u;
  849. }
  850. if (v != item) {
  851. PyTuple_SET_ITEM(o, i, Py_NewRef(v));
  852. Py_DECREF(item);
  853. }
  854. Py_DECREF(u);
  855. }
  856. }
  857. else if (PyFrozenSet_CheckExact(o)) {
  858. // *key* is tuple. And its first item is frozenset of
  859. // constant keys.
  860. // See _PyCode_ConstantKey() for detail.
  861. assert(PyTuple_CheckExact(key));
  862. assert(PyTuple_GET_SIZE(key) == 2);
  863. Py_ssize_t len = PySet_GET_SIZE(o);
  864. if (len == 0) { // empty frozenset should not be re-created.
  865. return key;
  866. }
  867. PyObject *tuple = PyTuple_New(len);
  868. if (tuple == NULL) {
  869. Py_DECREF(key);
  870. return NULL;
  871. }
  872. Py_ssize_t i = 0, pos = 0;
  873. PyObject *item;
  874. Py_hash_t hash;
  875. while (_PySet_NextEntry(o, &pos, &item, &hash)) {
  876. PyObject *k = merge_consts_recursive(const_cache, item);
  877. if (k == NULL) {
  878. Py_DECREF(tuple);
  879. Py_DECREF(key);
  880. return NULL;
  881. }
  882. PyObject *u;
  883. if (PyTuple_CheckExact(k)) {
  884. u = Py_NewRef(PyTuple_GET_ITEM(k, 1));
  885. Py_DECREF(k);
  886. }
  887. else {
  888. u = k;
  889. }
  890. PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
  891. i++;
  892. }
  893. // Instead of rewriting o, we create new frozenset and embed in the
  894. // key tuple. Caller should get merged frozenset from the key tuple.
  895. PyObject *new = PyFrozenSet_New(tuple);
  896. Py_DECREF(tuple);
  897. if (new == NULL) {
  898. Py_DECREF(key);
  899. return NULL;
  900. }
  901. assert(PyTuple_GET_ITEM(key, 1) == o);
  902. Py_DECREF(o);
  903. PyTuple_SET_ITEM(key, 1, new);
  904. }
  905. return key;
  906. }
  907. static Py_ssize_t
  908. compiler_add_const(PyObject *const_cache, struct compiler_unit *u, PyObject *o)
  909. {
  910. assert(PyDict_CheckExact(const_cache));
  911. PyObject *key = merge_consts_recursive(const_cache, o);
  912. if (key == NULL) {
  913. return ERROR;
  914. }
  915. Py_ssize_t arg = dict_add_o(u->u_metadata.u_consts, key);
  916. Py_DECREF(key);
  917. return arg;
  918. }
  919. static int
  920. compiler_addop_load_const(PyObject *const_cache, struct compiler_unit *u, location loc, PyObject *o)
  921. {
  922. Py_ssize_t arg = compiler_add_const(const_cache, u, o);
  923. if (arg < 0) {
  924. return ERROR;
  925. }
  926. return codegen_addop_i(&u->u_instr_sequence, LOAD_CONST, arg, loc);
  927. }
  928. static int
  929. compiler_addop_o(struct compiler_unit *u, location loc,
  930. int opcode, PyObject *dict, PyObject *o)
  931. {
  932. Py_ssize_t arg = dict_add_o(dict, o);
  933. if (arg < 0) {
  934. return ERROR;
  935. }
  936. return codegen_addop_i(&u->u_instr_sequence, opcode, arg, loc);
  937. }
  938. static int
  939. compiler_addop_name(struct compiler_unit *u, location loc,
  940. int opcode, PyObject *dict, PyObject *o)
  941. {
  942. PyObject *mangled = _Py_MaybeMangle(u->u_private, u->u_ste, o);
  943. if (!mangled) {
  944. return ERROR;
  945. }
  946. Py_ssize_t arg = dict_add_o(dict, mangled);
  947. Py_DECREF(mangled);
  948. if (arg < 0) {
  949. return ERROR;
  950. }
  951. if (opcode == LOAD_ATTR) {
  952. arg <<= 1;
  953. }
  954. if (opcode == LOAD_METHOD) {
  955. opcode = LOAD_ATTR;
  956. arg <<= 1;
  957. arg |= 1;
  958. }
  959. if (opcode == LOAD_SUPER_ATTR) {
  960. arg <<= 2;
  961. arg |= 2;
  962. }
  963. if (opcode == LOAD_SUPER_METHOD) {
  964. opcode = LOAD_SUPER_ATTR;
  965. arg <<= 2;
  966. arg |= 3;
  967. }
  968. if (opcode == LOAD_ZERO_SUPER_ATTR) {
  969. opcode = LOAD_SUPER_ATTR;
  970. arg <<= 2;
  971. }
  972. if (opcode == LOAD_ZERO_SUPER_METHOD) {
  973. opcode = LOAD_SUPER_ATTR;
  974. arg <<= 2;
  975. arg |= 1;
  976. }
  977. return codegen_addop_i(&u->u_instr_sequence, opcode, arg, loc);
  978. }
  979. /* Add an opcode with an integer argument */
  980. static int
  981. codegen_addop_i(instr_sequence *seq, int opcode, Py_ssize_t oparg, location loc)
  982. {
  983. /* oparg value is unsigned, but a signed C int is usually used to store
  984. it in the C code (like Python/ceval.c).
  985. Limit to 32-bit signed C int (rather than INT_MAX) for portability.
  986. The argument of a concrete bytecode instruction is limited to 8-bit.
  987. EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
  988. int oparg_ = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
  989. assert(!IS_ASSEMBLER_OPCODE(opcode));
  990. return instr_sequence_addop(seq, opcode, oparg_, loc);
  991. }
  992. static int
  993. codegen_addop_j(instr_sequence *seq, location loc,
  994. int opcode, jump_target_label target)
  995. {
  996. assert(IS_LABEL(target));
  997. assert(IS_JUMP_OPCODE(opcode) || IS_BLOCK_PUSH_OPCODE(opcode));
  998. assert(!IS_ASSEMBLER_OPCODE(opcode));
  999. return instr_sequence_addop(seq, opcode, target.id, loc);
  1000. }
  1001. #define RETURN_IF_ERROR_IN_SCOPE(C, CALL) { \
  1002. if ((CALL) < 0) { \
  1003. compiler_exit_scope((C)); \
  1004. return ERROR; \
  1005. } \
  1006. }
  1007. #define ADDOP(C, LOC, OP) \
  1008. RETURN_IF_ERROR(codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC)))
  1009. #define ADDOP_IN_SCOPE(C, LOC, OP) RETURN_IF_ERROR_IN_SCOPE((C), codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC)))
  1010. #define ADDOP_LOAD_CONST(C, LOC, O) \
  1011. RETURN_IF_ERROR(compiler_addop_load_const((C)->c_const_cache, (C)->u, (LOC), (O)))
  1012. /* Same as ADDOP_LOAD_CONST, but steals a reference. */
  1013. #define ADDOP_LOAD_CONST_NEW(C, LOC, O) { \
  1014. PyObject *__new_const = (O); \
  1015. if (__new_const == NULL) { \
  1016. return ERROR; \
  1017. } \
  1018. if (compiler_addop_load_const((C)->c_const_cache, (C)->u, (LOC), __new_const) < 0) { \
  1019. Py_DECREF(__new_const); \
  1020. return ERROR; \
  1021. } \
  1022. Py_DECREF(__new_const); \
  1023. }
  1024. #define ADDOP_N(C, LOC, OP, O, TYPE) { \
  1025. assert(!HAS_CONST(OP)); /* use ADDOP_LOAD_CONST_NEW */ \
  1026. if (compiler_addop_o((C)->u, (LOC), (OP), (C)->u->u_metadata.u_ ## TYPE, (O)) < 0) { \
  1027. Py_DECREF((O)); \
  1028. return ERROR; \
  1029. } \
  1030. Py_DECREF((O)); \
  1031. }
  1032. #define ADDOP_NAME(C, LOC, OP, O, TYPE) \
  1033. RETURN_IF_ERROR(compiler_addop_name((C)->u, (LOC), (OP), (C)->u->u_metadata.u_ ## TYPE, (O)))
  1034. #define ADDOP_I(C, LOC, OP, O) \
  1035. RETURN_IF_ERROR(codegen_addop_i(INSTR_SEQUENCE(C), (OP), (O), (LOC)))
  1036. #define ADDOP_JUMP(C, LOC, OP, O) \
  1037. RETURN_IF_ERROR(codegen_addop_j(INSTR_SEQUENCE(C), (LOC), (OP), (O)))
  1038. #define ADDOP_COMPARE(C, LOC, CMP) \
  1039. RETURN_IF_ERROR(compiler_addcompare((C), (LOC), (cmpop_ty)(CMP)))
  1040. #define ADDOP_BINARY(C, LOC, BINOP) \
  1041. RETURN_IF_ERROR(addop_binary((C), (LOC), (BINOP), false))
  1042. #define ADDOP_INPLACE(C, LOC, BINOP) \
  1043. RETURN_IF_ERROR(addop_binary((C), (LOC), (BINOP), true))
  1044. #define ADD_YIELD_FROM(C, LOC, await) \
  1045. RETURN_IF_ERROR(compiler_add_yield_from((C), (LOC), (await)))
  1046. #define POP_EXCEPT_AND_RERAISE(C, LOC) \
  1047. RETURN_IF_ERROR(compiler_pop_except_and_reraise((C), (LOC)))
  1048. #define ADDOP_YIELD(C, LOC) \
  1049. RETURN_IF_ERROR(addop_yield((C), (LOC)))
  1050. /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
  1051. the ASDL name to synthesize the name of the C type and the visit function.
  1052. */
  1053. #define VISIT(C, TYPE, V) \
  1054. RETURN_IF_ERROR(compiler_visit_ ## TYPE((C), (V)));
  1055. #define VISIT_IN_SCOPE(C, TYPE, V) \
  1056. RETURN_IF_ERROR_IN_SCOPE((C), compiler_visit_ ## TYPE((C), (V)))
  1057. #define VISIT_SEQ(C, TYPE, SEQ) { \
  1058. int _i; \
  1059. asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
  1060. for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
  1061. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
  1062. RETURN_IF_ERROR(compiler_visit_ ## TYPE((C), elt)); \
  1063. } \
  1064. }
  1065. #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
  1066. int _i; \
  1067. asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
  1068. for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
  1069. TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
  1070. if (compiler_visit_ ## TYPE((C), elt) < 0) { \
  1071. compiler_exit_scope(C); \
  1072. return ERROR; \
  1073. } \
  1074. } \
  1075. }
  1076. static int
  1077. compiler_enter_scope(struct compiler *c, identifier name,
  1078. int scope_type, void *key, int lineno)
  1079. {
  1080. location loc = LOCATION(lineno, lineno, 0, 0);
  1081. struct compiler_unit *u;
  1082. u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
  1083. struct compiler_unit));
  1084. if (!u) {
  1085. PyErr_NoMemory();
  1086. return ERROR;
  1087. }
  1088. u->u_scope_type = scope_type;
  1089. u->u_metadata.u_argcount = 0;
  1090. u->u_metadata.u_posonlyargcount = 0;
  1091. u->u_metadata.u_kwonlyargcount = 0;
  1092. u->u_ste = PySymtable_Lookup(c->c_st, key);
  1093. if (!u->u_ste) {
  1094. compiler_unit_free(u);
  1095. return ERROR;
  1096. }
  1097. u->u_metadata.u_name = Py_NewRef(name);
  1098. u->u_metadata.u_varnames = list2dict(u->u_ste->ste_varnames);
  1099. if (!u->u_metadata.u_varnames) {
  1100. compiler_unit_free(u);
  1101. return ERROR;
  1102. }
  1103. u->u_metadata.u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, DEF_COMP_CELL, 0);
  1104. if (!u->u_metadata.u_cellvars) {
  1105. compiler_unit_free(u);
  1106. return ERROR;
  1107. }
  1108. if (u->u_ste->ste_needs_class_closure) {
  1109. /* Cook up an implicit __class__ cell. */
  1110. Py_ssize_t res;
  1111. assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
  1112. res = dict_add_o(u->u_metadata.u_cellvars, &_Py_ID(__class__));
  1113. if (res < 0) {
  1114. compiler_unit_free(u);
  1115. return ERROR;
  1116. }
  1117. }
  1118. if (u->u_ste->ste_needs_classdict) {
  1119. /* Cook up an implicit __classdict__ cell. */
  1120. Py_ssize_t res;
  1121. assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
  1122. res = dict_add_o(u->u_metadata.u_cellvars, &_Py_ID(__classdict__));
  1123. if (res < 0) {
  1124. compiler_unit_free(u);
  1125. return ERROR;
  1126. }
  1127. }
  1128. u->u_metadata.u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
  1129. PyDict_GET_SIZE(u->u_metadata.u_cellvars));
  1130. if (!u->u_metadata.u_freevars) {
  1131. compiler_unit_free(u);
  1132. return ERROR;
  1133. }
  1134. u->u_metadata.u_fasthidden = PyDict_New();
  1135. if (!u->u_metadata.u_fasthidden) {
  1136. compiler_unit_free(u);
  1137. return ERROR;
  1138. }
  1139. u->u_nfblocks = 0;
  1140. u->u_in_inlined_comp = 0;
  1141. u->u_metadata.u_firstlineno = lineno;
  1142. u->u_metadata.u_consts = PyDict_New();
  1143. if (!u->u_metadata.u_consts) {
  1144. compiler_unit_free(u);
  1145. return ERROR;
  1146. }
  1147. u->u_metadata.u_names = PyDict_New();
  1148. if (!u->u_metadata.u_names) {
  1149. compiler_unit_free(u);
  1150. return ERROR;
  1151. }
  1152. u->u_private = NULL;
  1153. /* Push the old compiler_unit on the stack. */
  1154. if (c->u) {
  1155. PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
  1156. if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
  1157. Py_XDECREF(capsule);
  1158. compiler_unit_free(u);
  1159. return ERROR;
  1160. }
  1161. Py_DECREF(capsule);
  1162. u->u_private = Py_XNewRef(c->u->u_private);
  1163. }
  1164. c->u = u;
  1165. c->c_nestlevel++;
  1166. if (u->u_scope_type == COMPILER_SCOPE_MODULE) {
  1167. loc.lineno = 0;
  1168. }
  1169. else {
  1170. RETURN_IF_ERROR(compiler_set_qualname(c));
  1171. }
  1172. ADDOP_I(c, loc, RESUME, 0);
  1173. if (u->u_scope_type == COMPILER_SCOPE_MODULE) {
  1174. loc.lineno = -1;
  1175. }
  1176. return SUCCESS;
  1177. }
  1178. static void
  1179. compiler_exit_scope(struct compiler *c)
  1180. {
  1181. // Don't call PySequence_DelItem() with an exception raised
  1182. PyObject *exc = PyErr_GetRaisedException();
  1183. c->c_nestlevel--;
  1184. compiler_unit_free(c->u);
  1185. /* Restore c->u to the parent unit. */
  1186. Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
  1187. if (n >= 0) {
  1188. PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
  1189. c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
  1190. assert(c->u);
  1191. /* we are deleting from a list so this really shouldn't fail */
  1192. if (PySequence_DelItem(c->c_stack, n) < 0) {
  1193. _PyErr_WriteUnraisableMsg("on removing the last compiler "
  1194. "stack item", NULL);
  1195. }
  1196. }
  1197. else {
  1198. c->u = NULL;
  1199. }
  1200. PyErr_SetRaisedException(exc);
  1201. }
  1202. /* Search if variable annotations are present statically in a block. */
  1203. static bool
  1204. find_ann(asdl_stmt_seq *stmts)
  1205. {
  1206. int i, j, res = 0;
  1207. stmt_ty st;
  1208. for (i = 0; i < asdl_seq_LEN(stmts); i++) {
  1209. st = (stmt_ty)asdl_seq_GET(stmts, i);
  1210. switch (st->kind) {
  1211. case AnnAssign_kind:
  1212. return true;
  1213. case For_kind:
  1214. res = find_ann(st->v.For.body) ||
  1215. find_ann(st->v.For.orelse);
  1216. break;
  1217. case AsyncFor_kind:
  1218. res = find_ann(st->v.AsyncFor.body) ||
  1219. find_ann(st->v.AsyncFor.orelse);
  1220. break;
  1221. case While_kind:
  1222. res = find_ann(st->v.While.body) ||
  1223. find_ann(st->v.While.orelse);
  1224. break;
  1225. case If_kind:
  1226. res = find_ann(st->v.If.body) ||
  1227. find_ann(st->v.If.orelse);
  1228. break;
  1229. case With_kind:
  1230. res = find_ann(st->v.With.body);
  1231. break;
  1232. case AsyncWith_kind:
  1233. res = find_ann(st->v.AsyncWith.body);
  1234. break;
  1235. case Try_kind:
  1236. for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
  1237. excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
  1238. st->v.Try.handlers, j);
  1239. if (find_ann(handler->v.ExceptHandler.body)) {
  1240. return true;
  1241. }
  1242. }
  1243. res = find_ann(st->v.Try.body) ||
  1244. find_ann(st->v.Try.finalbody) ||
  1245. find_ann(st->v.Try.orelse);
  1246. break;
  1247. case TryStar_kind:
  1248. for (j = 0; j < asdl_seq_LEN(st->v.TryStar.handlers); j++) {
  1249. excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
  1250. st->v.TryStar.handlers, j);
  1251. if (find_ann(handler->v.ExceptHandler.body)) {
  1252. return true;
  1253. }
  1254. }
  1255. res = find_ann(st->v.TryStar.body) ||
  1256. find_ann(st->v.TryStar.finalbody) ||
  1257. find_ann(st->v.TryStar.orelse);
  1258. break;
  1259. case Match_kind:
  1260. for (j = 0; j < asdl_seq_LEN(st->v.Match.cases); j++) {
  1261. match_case_ty match_case = (match_case_ty)asdl_seq_GET(
  1262. st->v.Match.cases, j);
  1263. if (find_ann(match_case->body)) {
  1264. return true;
  1265. }
  1266. }
  1267. break;
  1268. default:
  1269. res = false;
  1270. break;
  1271. }
  1272. if (res) {
  1273. break;
  1274. }
  1275. }
  1276. return res;
  1277. }
  1278. /*
  1279. * Frame block handling functions
  1280. */
  1281. static int
  1282. compiler_push_fblock(struct compiler *c, location loc,
  1283. enum fblocktype t, jump_target_label block_label,
  1284. jump_target_label exit, void *datum)
  1285. {
  1286. struct fblockinfo *f;
  1287. if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
  1288. return compiler_error(c, loc, "too many statically nested blocks");
  1289. }
  1290. f = &c->u->u_fblock[c->u->u_nfblocks++];
  1291. f->fb_type = t;
  1292. f->fb_block = block_label;
  1293. f->fb_exit = exit;
  1294. f->fb_datum = datum;
  1295. return SUCCESS;
  1296. }
  1297. static void
  1298. compiler_pop_fblock(struct compiler *c, enum fblocktype t, jump_target_label block_label)
  1299. {
  1300. struct compiler_unit *u = c->u;
  1301. assert(u->u_nfblocks > 0);
  1302. u->u_nfblocks--;
  1303. assert(u->u_fblock[u->u_nfblocks].fb_type == t);
  1304. assert(SAME_LABEL(u->u_fblock[u->u_nfblocks].fb_block, block_label));
  1305. }
  1306. static int
  1307. compiler_call_exit_with_nones(struct compiler *c, location loc)
  1308. {
  1309. ADDOP_LOAD_CONST(c, loc, Py_None);
  1310. ADDOP_LOAD_CONST(c, loc, Py_None);
  1311. ADDOP_LOAD_CONST(c, loc, Py_None);
  1312. ADDOP_I(c, loc, CALL, 2);
  1313. return SUCCESS;
  1314. }
  1315. static int
  1316. compiler_add_yield_from(struct compiler *c, location loc, int await)
  1317. {
  1318. NEW_JUMP_TARGET_LABEL(c, send);
  1319. NEW_JUMP_TARGET_LABEL(c, fail);
  1320. NEW_JUMP_TARGET_LABEL(c, exit);
  1321. USE_LABEL(c, send);
  1322. ADDOP_JUMP(c, loc, SEND, exit);
  1323. // Set up a virtual try/except to handle when StopIteration is raised during
  1324. // a close or throw call. The only way YIELD_VALUE raises if they do!
  1325. ADDOP_JUMP(c, loc, SETUP_FINALLY, fail);
  1326. ADDOP_I(c, loc, YIELD_VALUE, 0);
  1327. ADDOP(c, NO_LOCATION, POP_BLOCK);
  1328. ADDOP_I(c, loc, RESUME, await ? 3 : 2);
  1329. ADDOP_JUMP(c, loc, JUMP_NO_INTERRUPT, send);
  1330. USE_LABEL(c, fail);
  1331. ADDOP(c, loc, CLEANUP_THROW);
  1332. USE_LABEL(c, exit);
  1333. ADDOP(c, loc, END_SEND);
  1334. return SUCCESS;
  1335. }
  1336. static int
  1337. compiler_pop_except_and_reraise(struct compiler *c, location loc)
  1338. {
  1339. /* Stack contents
  1340. * [exc_info, lasti, exc] COPY 3
  1341. * [exc_info, lasti, exc, exc_info] POP_EXCEPT
  1342. * [exc_info, lasti, exc] RERAISE 1
  1343. * (exception_unwind clears the stack)
  1344. */
  1345. ADDOP_I(c, loc, COPY, 3);
  1346. ADDOP(c, loc, POP_EXCEPT);
  1347. ADDOP_I(c, loc, RERAISE, 1);
  1348. return SUCCESS;
  1349. }
  1350. /* Unwind a frame block. If preserve_tos is true, the TOS before
  1351. * popping the blocks will be restored afterwards, unless another
  1352. * return, break or continue is found. In which case, the TOS will
  1353. * be popped.
  1354. */
  1355. static int
  1356. compiler_unwind_fblock(struct compiler *c, location *ploc,
  1357. struct fblockinfo *info, int preserve_tos)
  1358. {
  1359. switch (info->fb_type) {
  1360. case WHILE_LOOP:
  1361. case EXCEPTION_HANDLER:
  1362. case EXCEPTION_GROUP_HANDLER:
  1363. case ASYNC_COMPREHENSION_GENERATOR:
  1364. case STOP_ITERATION:
  1365. return SUCCESS;
  1366. case FOR_LOOP:
  1367. /* Pop the iterator */
  1368. if (preserve_tos) {
  1369. ADDOP_I(c, *ploc, SWAP, 2);
  1370. }
  1371. ADDOP(c, *ploc, POP_TOP);
  1372. return SUCCESS;
  1373. case TRY_EXCEPT:
  1374. ADDOP(c, *ploc, POP_BLOCK);
  1375. return SUCCESS;
  1376. case FINALLY_TRY:
  1377. /* This POP_BLOCK gets the line number of the unwinding statement */
  1378. ADDOP(c, *ploc, POP_BLOCK);
  1379. if (preserve_tos) {
  1380. RETURN_IF_ERROR(
  1381. compiler_push_fblock(c, *ploc, POP_VALUE, NO_LABEL, NO_LABEL, NULL));
  1382. }
  1383. /* Emit the finally block */
  1384. VISIT_SEQ(c, stmt, info->fb_datum);
  1385. if (preserve_tos) {
  1386. compiler_pop_fblock(c, POP_VALUE, NO_LABEL);
  1387. }
  1388. /* The finally block should appear to execute after the
  1389. * statement causing the unwinding, so make the unwinding
  1390. * instruction artificial */
  1391. *ploc = NO_LOCATION;
  1392. return SUCCESS;
  1393. case FINALLY_END:
  1394. if (preserve_tos) {
  1395. ADDOP_I(c, *ploc, SWAP, 2);
  1396. }
  1397. ADDOP(c, *ploc, POP_TOP); /* exc_value */
  1398. if (preserve_tos) {
  1399. ADDOP_I(c, *ploc, SWAP, 2);
  1400. }
  1401. ADDOP(c, *ploc, POP_BLOCK);
  1402. ADDOP(c, *ploc, POP_EXCEPT);
  1403. return SUCCESS;
  1404. case WITH:
  1405. case ASYNC_WITH:
  1406. *ploc = LOC((stmt_ty)info->fb_datum);
  1407. ADDOP(c, *ploc, POP_BLOCK);
  1408. if (preserve_tos) {
  1409. ADDOP_I(c, *ploc, SWAP, 2);
  1410. }
  1411. RETURN_IF_ERROR(compiler_call_exit_with_nones(c, *ploc));
  1412. if (info->fb_type == ASYNC_WITH) {
  1413. ADDOP_I(c, *ploc, GET_AWAITABLE, 2);
  1414. ADDOP_LOAD_CONST(c, *ploc, Py_None);
  1415. ADD_YIELD_FROM(c, *ploc, 1);
  1416. }
  1417. ADDOP(c, *ploc, POP_TOP);
  1418. /* The exit block should appear to execute after the
  1419. * statement causing the unwinding, so make the unwinding
  1420. * instruction artificial */
  1421. *ploc = NO_LOCATION;
  1422. return SUCCESS;
  1423. case HANDLER_CLEANUP: {
  1424. if (info->fb_datum) {
  1425. ADDOP(c, *ploc, POP_BLOCK);
  1426. }
  1427. if (preserve_tos) {
  1428. ADDOP_I(c, *ploc, SWAP, 2);
  1429. }
  1430. ADDOP(c, *ploc, POP_BLOCK);
  1431. ADDOP(c, *ploc, POP_EXCEPT);
  1432. if (info->fb_datum) {
  1433. ADDOP_LOAD_CONST(c, *ploc, Py_None);
  1434. RETURN_IF_ERROR(compiler_nameop(c, *ploc, info->fb_datum, Store));
  1435. RETURN_IF_ERROR(compiler_nameop(c, *ploc, info->fb_datum, Del));
  1436. }
  1437. return SUCCESS;
  1438. }
  1439. case POP_VALUE: {
  1440. if (preserve_tos) {
  1441. ADDOP_I(c, *ploc, SWAP, 2);
  1442. }
  1443. ADDOP(c, *ploc, POP_TOP);
  1444. return SUCCESS;
  1445. }
  1446. }
  1447. Py_UNREACHABLE();
  1448. }
  1449. /** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
  1450. static int
  1451. compiler_unwind_fblock_stack(struct compiler *c, location *ploc,
  1452. int preserve_tos, struct fblockinfo **loop)
  1453. {
  1454. if (c->u->u_nfblocks == 0) {
  1455. return SUCCESS;
  1456. }
  1457. struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
  1458. if (top->fb_type == EXCEPTION_GROUP_HANDLER) {
  1459. return compiler_error(
  1460. c, *ploc, "'break', 'continue' and 'return' cannot appear in an except* block");
  1461. }
  1462. if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
  1463. *loop = top;
  1464. return SUCCESS;
  1465. }
  1466. struct fblockinfo copy = *top;
  1467. c->u->u_nfblocks--;
  1468. RETURN_IF_ERROR(compiler_unwind_fblock(c, ploc, &copy, preserve_tos));
  1469. RETURN_IF_ERROR(compiler_unwind_fblock_stack(c, ploc, preserve_tos, loop));
  1470. c->u->u_fblock[c->u->u_nfblocks] = copy;
  1471. c->u->u_nfblocks++;
  1472. return SUCCESS;
  1473. }
  1474. /* Compile a sequence of statements, checking for a docstring
  1475. and for annotations. */
  1476. static int
  1477. compiler_body(struct compiler *c, location loc, asdl_stmt_seq *stmts)
  1478. {
  1479. int i = 0;
  1480. stmt_ty st;
  1481. PyObject *docstring;
  1482. /* Set current line number to the line number of first statement.
  1483. This way line number for SETUP_ANNOTATIONS will always
  1484. coincide with the line number of first "real" statement in module.
  1485. If body is empty, then lineno will be set later in optimize_and_assemble. */
  1486. if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
  1487. st = (stmt_ty)asdl_seq_GET(stmts, 0);
  1488. loc = LOC(st);
  1489. }
  1490. /* Every annotated class and module should have __annotations__. */
  1491. if (find_ann(stmts)) {
  1492. ADDOP(c, loc, SETUP_ANNOTATIONS);
  1493. }
  1494. if (!asdl_seq_LEN(stmts)) {
  1495. return SUCCESS;
  1496. }
  1497. /* if not -OO mode, set docstring */
  1498. if (c->c_optimize < 2) {
  1499. docstring = _PyAST_GetDocString(stmts);
  1500. if (docstring) {
  1501. i = 1;
  1502. st = (stmt_ty)asdl_seq_GET(stmts, 0);
  1503. assert(st->kind == Expr_kind);
  1504. VISIT(c, expr, st->v.Expr.value);
  1505. RETURN_IF_ERROR(compiler_nameop(c, NO_LOCATION, &_Py_ID(__doc__), Store));
  1506. }
  1507. }
  1508. for (; i < asdl_seq_LEN(stmts); i++) {
  1509. VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
  1510. }
  1511. return SUCCESS;
  1512. }
  1513. static int
  1514. compiler_codegen(struct compiler *c, mod_ty mod)
  1515. {
  1516. _Py_DECLARE_STR(anon_module, "<module>");
  1517. RETURN_IF_ERROR(
  1518. compiler_enter_scope(c, &_Py_STR(anon_module), COMPILER_SCOPE_MODULE,
  1519. mod, 1));
  1520. location loc = LOCATION(1, 1, 0, 0);
  1521. switch (mod->kind) {
  1522. case Module_kind:
  1523. if (compiler_body(c, loc, mod->v.Module.body) < 0) {
  1524. compiler_exit_scope(c);
  1525. return ERROR;
  1526. }
  1527. break;
  1528. case Interactive_kind:
  1529. if (find_ann(mod->v.Interactive.body)) {
  1530. ADDOP(c, loc, SETUP_ANNOTATIONS);
  1531. }
  1532. c->c_interactive = 1;
  1533. VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
  1534. break;
  1535. case Expression_kind:
  1536. VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
  1537. break;
  1538. default:
  1539. PyErr_Format(PyExc_SystemError,
  1540. "module kind %d should not be possible",
  1541. mod->kind);
  1542. return ERROR;
  1543. }
  1544. return SUCCESS;
  1545. }
  1546. static PyCodeObject *
  1547. compiler_mod(struct compiler *c, mod_ty mod)
  1548. {
  1549. int addNone = mod->kind != Expression_kind;
  1550. if (compiler_codegen(c, mod) < 0) {
  1551. return NULL;
  1552. }
  1553. PyCodeObject *co = optimize_and_assemble(c, addNone);
  1554. compiler_exit_scope(c);
  1555. return co;
  1556. }
  1557. /* The test for LOCAL must come before the test for FREE in order to
  1558. handle classes where name is both local and free. The local var is
  1559. a method and the free var is a free var referenced within a method.
  1560. */
  1561. static int
  1562. get_ref_type(struct compiler *c, PyObject *name)
  1563. {
  1564. int scope;
  1565. if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
  1566. (_PyUnicode_EqualToASCIIString(name, "__class__") ||
  1567. _PyUnicode_EqualToASCIIString(name, "__classdict__"))) {
  1568. return CELL;
  1569. }
  1570. scope = _PyST_GetScope(c->u->u_ste, name);
  1571. if (scope == 0) {
  1572. PyErr_Format(PyExc_SystemError,
  1573. "_PyST_GetScope(name=%R) failed: "
  1574. "unknown scope in unit %S (%R); "
  1575. "symbols: %R; locals: %R; globals: %R",
  1576. name,
  1577. c->u->u_metadata.u_name, c->u->u_ste->ste_id,
  1578. c->u->u_ste->ste_symbols, c->u->u_metadata.u_varnames, c->u->u_metadata.u_names);
  1579. return ERROR;
  1580. }
  1581. return scope;
  1582. }
  1583. static int
  1584. compiler_lookup_arg(PyObject *dict, PyObject *name)
  1585. {
  1586. PyObject *v = PyDict_GetItemWithError(dict, name);
  1587. if (v == NULL) {
  1588. return ERROR;
  1589. }
  1590. return PyLong_AS_LONG(v);
  1591. }
  1592. static int
  1593. compiler_make_closure(struct compiler *c, location loc,
  1594. PyCodeObject *co, Py_ssize_t flags)
  1595. {
  1596. if (co->co_nfreevars) {
  1597. int i = PyCode_GetFirstFree(co);
  1598. for (; i < co->co_nlocalsplus; ++i) {
  1599. /* Bypass com_addop_varname because it will generate
  1600. LOAD_DEREF but LOAD_CLOSURE is needed.
  1601. */
  1602. PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
  1603. /* Special case: If a class contains a method with a
  1604. free variable that has the same name as a method,
  1605. the name will be considered free *and* local in the
  1606. class. It should be handled by the closure, as
  1607. well as by the normal name lookup logic.
  1608. */
  1609. int reftype = get_ref_type(c, name);
  1610. if (reftype == -1) {
  1611. return ERROR;
  1612. }
  1613. int arg;
  1614. if (reftype == CELL) {
  1615. arg = compiler_lookup_arg(c->u->u_metadata.u_cellvars, name);
  1616. }
  1617. else {
  1618. arg = compiler_lookup_arg(c->u->u_metadata.u_freevars, name);
  1619. }
  1620. if (arg == -1) {
  1621. PyObject *freevars = _PyCode_GetFreevars(co);
  1622. if (freevars == NULL) {
  1623. PyErr_Clear();
  1624. }
  1625. PyErr_Format(PyExc_SystemError,
  1626. "compiler_lookup_arg(name=%R) with reftype=%d failed in %S; "
  1627. "freevars of code %S: %R",
  1628. name,
  1629. reftype,
  1630. c->u->u_metadata.u_name,
  1631. co->co_name,
  1632. freevars);
  1633. Py_DECREF(freevars);
  1634. return ERROR;
  1635. }
  1636. ADDOP_I(c, loc, LOAD_CLOSURE, arg);
  1637. }
  1638. flags |= 0x08;
  1639. ADDOP_I(c, loc, BUILD_TUPLE, co->co_nfreevars);
  1640. }
  1641. ADDOP_LOAD_CONST(c, loc, (PyObject*)co);
  1642. ADDOP_I(c, loc, MAKE_FUNCTION, flags);
  1643. return SUCCESS;
  1644. }
  1645. static int
  1646. compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
  1647. {
  1648. if (!decos) {
  1649. return SUCCESS;
  1650. }
  1651. for (Py_ssize_t i = 0; i < asdl_seq_LEN(decos); i++) {
  1652. VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
  1653. }
  1654. return SUCCESS;
  1655. }
  1656. static int
  1657. compiler_apply_decorators(struct compiler *c, asdl_expr_seq* decos)
  1658. {
  1659. if (!decos) {
  1660. return SUCCESS;
  1661. }
  1662. for (Py_ssize_t i = asdl_seq_LEN(decos) - 1; i > -1; i--) {
  1663. location loc = LOC((expr_ty)asdl_seq_GET(decos, i));
  1664. ADDOP_I(c, loc, CALL, 0);
  1665. }
  1666. return SUCCESS;
  1667. }
  1668. static int
  1669. compiler_visit_kwonlydefaults(struct compiler *c, location loc,
  1670. asdl_arg_seq *kwonlyargs, asdl_expr_seq *kw_defaults)
  1671. {
  1672. /* Push a dict of keyword-only default values.
  1673. Return -1 on error, 0 if no dict pushed, 1 if a dict is pushed.
  1674. */
  1675. int i;
  1676. PyObject *keys = NULL;
  1677. for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
  1678. arg_ty arg = asdl_seq_GET(kwonlyargs, i);
  1679. expr_ty default_ = asdl_seq_GET(kw_defaults, i);
  1680. if (default_) {
  1681. PyObject *mangled = _Py_MaybeMangle(c->u->u_private, c->u->u_ste, arg->arg);
  1682. if (!mangled) {
  1683. goto error;
  1684. }
  1685. if (keys == NULL) {
  1686. keys = PyList_New(1);
  1687. if (keys == NULL) {
  1688. Py_DECREF(mangled);
  1689. return ERROR;
  1690. }
  1691. PyList_SET_ITEM(keys, 0, mangled);
  1692. }
  1693. else {
  1694. int res = PyList_Append(keys, mangled);
  1695. Py_DECREF(mangled);
  1696. if (res == -1) {
  1697. goto error;
  1698. }
  1699. }
  1700. if (compiler_visit_expr(c, default_) < 0) {
  1701. goto error;
  1702. }
  1703. }
  1704. }
  1705. if (keys != NULL) {
  1706. Py_ssize_t default_count = PyList_GET_SIZE(keys);
  1707. PyObject *keys_tuple = PyList_AsTuple(keys);
  1708. Py_DECREF(keys);
  1709. ADDOP_LOAD_CONST_NEW(c, loc, keys_tuple);
  1710. ADDOP_I(c, loc, BUILD_CONST_KEY_MAP, default_count);
  1711. assert(default_count > 0);
  1712. return 1;
  1713. }
  1714. else {
  1715. return 0;
  1716. }
  1717. error:
  1718. Py_XDECREF(keys);
  1719. return ERROR;
  1720. }
  1721. static int
  1722. compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
  1723. {
  1724. location loc = LOC(annotation);
  1725. ADDOP_LOAD_CONST_NEW(c, loc, _PyAST_ExprAsUnicode(annotation));
  1726. return SUCCESS;
  1727. }
  1728. static int
  1729. compiler_visit_argannotation(struct compiler *c, identifier id,
  1730. expr_ty annotation, Py_ssize_t *annotations_len, location loc)
  1731. {
  1732. if (!annotation) {
  1733. return SUCCESS;
  1734. }
  1735. PyObject *mangled = _Py_MaybeMangle(c->u->u_private, c->u->u_ste, id);
  1736. if (!mangled) {
  1737. return ERROR;
  1738. }
  1739. ADDOP_LOAD_CONST(c, loc, mangled);
  1740. Py_DECREF(mangled);
  1741. if (c->c_future.ff_features & CO_FUTURE_ANNOTATIONS) {
  1742. VISIT(c, annexpr, annotation);
  1743. }
  1744. else {
  1745. if (annotation->kind == Starred_kind) {
  1746. // *args: *Ts (where Ts is a TypeVarTuple).
  1747. // Do [annotation_value] = [*Ts].
  1748. // (Note that in theory we could end up here even for an argument
  1749. // other than *args, but in practice the grammar doesn't allow it.)
  1750. VISIT(c, expr, annotation->v.Starred.value);
  1751. ADDOP_I(c, loc, UNPACK_SEQUENCE, (Py_ssize_t) 1);
  1752. }
  1753. else {
  1754. VISIT(c, expr, annotation);
  1755. }
  1756. }
  1757. *annotations_len += 2;
  1758. return SUCCESS;
  1759. }
  1760. static int
  1761. compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
  1762. Py_ssize_t *annotations_len, location loc)
  1763. {
  1764. int i;
  1765. for (i = 0; i < asdl_seq_LEN(args); i++) {
  1766. arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
  1767. RETURN_IF_ERROR(
  1768. compiler_visit_argannotation(
  1769. c,
  1770. arg->arg,
  1771. arg->annotation,
  1772. annotations_len,
  1773. loc));
  1774. }
  1775. return SUCCESS;
  1776. }
  1777. static int
  1778. compiler_visit_annotations(struct compiler *c, location loc,
  1779. arguments_ty args, expr_ty returns)
  1780. {
  1781. /* Push arg annotation names and values.
  1782. The expressions are evaluated out-of-order wrt the source code.
  1783. Return -1 on error, 0 if no annotations pushed, 1 if a annotations is pushed.
  1784. */
  1785. Py_ssize_t annotations_len = 0;
  1786. RETURN_IF_ERROR(
  1787. compiler_visit_argannotations(c, args->args, &annotations_len, loc));
  1788. RETURN_IF_ERROR(
  1789. compiler_visit_argannotations(c, args->posonlyargs, &annotations_len, loc));
  1790. if (args->vararg && args->vararg->annotation) {
  1791. RETURN_IF_ERROR(
  1792. compiler_visit_argannotation(c, args->vararg->arg,
  1793. args->vararg->annotation, &annotations_len, loc));
  1794. }
  1795. RETURN_IF_ERROR(
  1796. compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len, loc));
  1797. if (args->kwarg && args->kwarg->annotation) {
  1798. RETURN_IF_ERROR(
  1799. compiler_visit_argannotation(c, args->kwarg->arg,
  1800. args->kwarg->annotation, &annotations_len, loc));
  1801. }
  1802. RETURN_IF_ERROR(
  1803. compiler_visit_argannotation(c, &_Py_ID(return), returns, &annotations_len, loc));
  1804. if (annotations_len) {
  1805. ADDOP_I(c, loc, BUILD_TUPLE, annotations_len);
  1806. return 1;
  1807. }
  1808. return 0;
  1809. }
  1810. static int
  1811. compiler_visit_defaults(struct compiler *c, arguments_ty args,
  1812. location loc)
  1813. {
  1814. VISIT_SEQ(c, expr, args->defaults);
  1815. ADDOP_I(c, loc, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
  1816. return SUCCESS;
  1817. }
  1818. static Py_ssize_t
  1819. compiler_default_arguments(struct compiler *c, location loc,
  1820. arguments_ty args)
  1821. {
  1822. Py_ssize_t funcflags = 0;
  1823. if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
  1824. RETURN_IF_ERROR(compiler_visit_defaults(c, args, loc));
  1825. funcflags |= 0x01;
  1826. }
  1827. if (args->kwonlyargs) {
  1828. int res = compiler_visit_kwonlydefaults(c, loc,
  1829. args->kwonlyargs,
  1830. args->kw_defaults);
  1831. RETURN_IF_ERROR(res);
  1832. if (res > 0) {
  1833. funcflags |= 0x02;
  1834. }
  1835. }
  1836. return funcflags;
  1837. }
  1838. static bool
  1839. forbidden_name(struct compiler *c, location loc, identifier name,
  1840. expr_context_ty ctx)
  1841. {
  1842. if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
  1843. compiler_error(c, loc, "cannot assign to __debug__");
  1844. return true;
  1845. }
  1846. if (ctx == Del && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
  1847. compiler_error(c, loc, "cannot delete __debug__");
  1848. return true;
  1849. }
  1850. return false;
  1851. }
  1852. static int
  1853. compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
  1854. {
  1855. if (arg != NULL) {
  1856. if (forbidden_name(c, LOC(arg), arg->arg, Store)) {
  1857. return ERROR;
  1858. }
  1859. }
  1860. return SUCCESS;
  1861. }
  1862. static int
  1863. compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
  1864. {
  1865. if (args != NULL) {
  1866. for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
  1867. RETURN_IF_ERROR(
  1868. compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)));
  1869. }
  1870. }
  1871. return SUCCESS;
  1872. }
  1873. static int
  1874. compiler_check_debug_args(struct compiler *c, arguments_ty args)
  1875. {
  1876. RETURN_IF_ERROR(compiler_check_debug_args_seq(c, args->posonlyargs));
  1877. RETURN_IF_ERROR(compiler_check_debug_args_seq(c, args->args));
  1878. RETURN_IF_ERROR(compiler_check_debug_one_arg(c, args->vararg));
  1879. RETURN_IF_ERROR(compiler_check_debug_args_seq(c, args->kwonlyargs));
  1880. RETURN_IF_ERROR(compiler_check_debug_one_arg(c, args->kwarg));
  1881. return SUCCESS;
  1882. }
  1883. static int
  1884. wrap_in_stopiteration_handler(struct compiler *c)
  1885. {
  1886. NEW_JUMP_TARGET_LABEL(c, handler);
  1887. /* Insert SETUP_CLEANUP at start */
  1888. RETURN_IF_ERROR(
  1889. instr_sequence_insert_instruction(
  1890. INSTR_SEQUENCE(c), 0,
  1891. SETUP_CLEANUP, handler.id, NO_LOCATION));
  1892. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  1893. ADDOP(c, NO_LOCATION, RETURN_VALUE);
  1894. USE_LABEL(c, handler);
  1895. ADDOP_I(c, NO_LOCATION, CALL_INTRINSIC_1, INTRINSIC_STOPITERATION_ERROR);
  1896. ADDOP_I(c, NO_LOCATION, RERAISE, 1);
  1897. return SUCCESS;
  1898. }
  1899. static int
  1900. compiler_type_params(struct compiler *c, asdl_type_param_seq *type_params)
  1901. {
  1902. if (!type_params) {
  1903. return SUCCESS;
  1904. }
  1905. Py_ssize_t n = asdl_seq_LEN(type_params);
  1906. for (Py_ssize_t i = 0; i < n; i++) {
  1907. type_param_ty typeparam = asdl_seq_GET(type_params, i);
  1908. location loc = LOC(typeparam);
  1909. switch(typeparam->kind) {
  1910. case TypeVar_kind:
  1911. ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVar.name);
  1912. if (typeparam->v.TypeVar.bound) {
  1913. expr_ty bound = typeparam->v.TypeVar.bound;
  1914. if (compiler_enter_scope(c, typeparam->v.TypeVar.name, COMPILER_SCOPE_TYPEPARAMS,
  1915. (void *)typeparam, bound->lineno) == -1) {
  1916. return ERROR;
  1917. }
  1918. VISIT_IN_SCOPE(c, expr, bound);
  1919. ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
  1920. PyCodeObject *co = optimize_and_assemble(c, 1);
  1921. compiler_exit_scope(c);
  1922. if (co == NULL) {
  1923. return ERROR;
  1924. }
  1925. if (compiler_make_closure(c, loc, co, 0) < 0) {
  1926. Py_DECREF(co);
  1927. return ERROR;
  1928. }
  1929. Py_DECREF(co);
  1930. int intrinsic = bound->kind == Tuple_kind
  1931. ? INTRINSIC_TYPEVAR_WITH_CONSTRAINTS
  1932. : INTRINSIC_TYPEVAR_WITH_BOUND;
  1933. ADDOP_I(c, loc, CALL_INTRINSIC_2, intrinsic);
  1934. }
  1935. else {
  1936. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVAR);
  1937. }
  1938. ADDOP_I(c, loc, COPY, 1);
  1939. RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.TypeVar.name, Store));
  1940. break;
  1941. case TypeVarTuple_kind:
  1942. ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVarTuple.name);
  1943. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVARTUPLE);
  1944. ADDOP_I(c, loc, COPY, 1);
  1945. RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.TypeVarTuple.name, Store));
  1946. break;
  1947. case ParamSpec_kind:
  1948. ADDOP_LOAD_CONST(c, loc, typeparam->v.ParamSpec.name);
  1949. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_PARAMSPEC);
  1950. ADDOP_I(c, loc, COPY, 1);
  1951. RETURN_IF_ERROR(compiler_nameop(c, loc, typeparam->v.ParamSpec.name, Store));
  1952. break;
  1953. }
  1954. }
  1955. ADDOP_I(c, LOC(asdl_seq_GET(type_params, 0)), BUILD_TUPLE, n);
  1956. return SUCCESS;
  1957. }
  1958. static int
  1959. compiler_function_body(struct compiler *c, stmt_ty s, int is_async, Py_ssize_t funcflags,
  1960. int firstlineno)
  1961. {
  1962. PyObject *docstring = NULL;
  1963. arguments_ty args;
  1964. identifier name;
  1965. asdl_stmt_seq *body;
  1966. int scope_type;
  1967. if (is_async) {
  1968. assert(s->kind == AsyncFunctionDef_kind);
  1969. args = s->v.AsyncFunctionDef.args;
  1970. name = s->v.AsyncFunctionDef.name;
  1971. body = s->v.AsyncFunctionDef.body;
  1972. scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
  1973. } else {
  1974. assert(s->kind == FunctionDef_kind);
  1975. args = s->v.FunctionDef.args;
  1976. name = s->v.FunctionDef.name;
  1977. body = s->v.FunctionDef.body;
  1978. scope_type = COMPILER_SCOPE_FUNCTION;
  1979. }
  1980. RETURN_IF_ERROR(
  1981. compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno));
  1982. /* if not -OO mode, add docstring */
  1983. if (c->c_optimize < 2) {
  1984. docstring = _PyAST_GetDocString(body);
  1985. }
  1986. if (compiler_add_const(c->c_const_cache, c->u, docstring ? docstring : Py_None) < 0) {
  1987. compiler_exit_scope(c);
  1988. return ERROR;
  1989. }
  1990. c->u->u_metadata.u_argcount = asdl_seq_LEN(args->args);
  1991. c->u->u_metadata.u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
  1992. c->u->u_metadata.u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
  1993. NEW_JUMP_TARGET_LABEL(c, start);
  1994. USE_LABEL(c, start);
  1995. bool add_stopiteration_handler = c->u->u_ste->ste_coroutine || c->u->u_ste->ste_generator;
  1996. if (add_stopiteration_handler) {
  1997. /* wrap_in_stopiteration_handler will push a block, so we need to account for that */
  1998. RETURN_IF_ERROR(
  1999. compiler_push_fblock(c, NO_LOCATION, STOP_ITERATION,
  2000. start, NO_LABEL, NULL));
  2001. }
  2002. for (Py_ssize_t i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
  2003. VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
  2004. }
  2005. if (add_stopiteration_handler) {
  2006. if (wrap_in_stopiteration_handler(c) < 0) {
  2007. compiler_exit_scope(c);
  2008. return ERROR;
  2009. }
  2010. compiler_pop_fblock(c, STOP_ITERATION, start);
  2011. }
  2012. PyCodeObject *co = optimize_and_assemble(c, 1);
  2013. compiler_exit_scope(c);
  2014. if (co == NULL) {
  2015. Py_XDECREF(co);
  2016. return ERROR;
  2017. }
  2018. location loc = LOC(s);
  2019. if (compiler_make_closure(c, loc, co, funcflags) < 0) {
  2020. Py_DECREF(co);
  2021. return ERROR;
  2022. }
  2023. Py_DECREF(co);
  2024. return SUCCESS;
  2025. }
  2026. static int
  2027. compiler_function(struct compiler *c, stmt_ty s, int is_async)
  2028. {
  2029. arguments_ty args;
  2030. expr_ty returns;
  2031. identifier name;
  2032. asdl_expr_seq *decos;
  2033. asdl_type_param_seq *type_params;
  2034. Py_ssize_t funcflags;
  2035. int annotations;
  2036. int firstlineno;
  2037. if (is_async) {
  2038. assert(s->kind == AsyncFunctionDef_kind);
  2039. args = s->v.AsyncFunctionDef.args;
  2040. returns = s->v.AsyncFunctionDef.returns;
  2041. decos = s->v.AsyncFunctionDef.decorator_list;
  2042. name = s->v.AsyncFunctionDef.name;
  2043. type_params = s->v.AsyncFunctionDef.type_params;
  2044. } else {
  2045. assert(s->kind == FunctionDef_kind);
  2046. args = s->v.FunctionDef.args;
  2047. returns = s->v.FunctionDef.returns;
  2048. decos = s->v.FunctionDef.decorator_list;
  2049. name = s->v.FunctionDef.name;
  2050. type_params = s->v.FunctionDef.type_params;
  2051. }
  2052. RETURN_IF_ERROR(compiler_check_debug_args(c, args));
  2053. RETURN_IF_ERROR(compiler_decorators(c, decos));
  2054. firstlineno = s->lineno;
  2055. if (asdl_seq_LEN(decos)) {
  2056. firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
  2057. }
  2058. location loc = LOC(s);
  2059. int is_generic = asdl_seq_LEN(type_params) > 0;
  2060. if (is_generic) {
  2061. // Used by the CALL to the type parameters function.
  2062. ADDOP(c, loc, PUSH_NULL);
  2063. }
  2064. funcflags = compiler_default_arguments(c, loc, args);
  2065. if (funcflags == -1) {
  2066. return ERROR;
  2067. }
  2068. int num_typeparam_args = 0;
  2069. if (is_generic) {
  2070. if (funcflags & 0x01) {
  2071. num_typeparam_args += 1;
  2072. }
  2073. if (funcflags & 0x02) {
  2074. num_typeparam_args += 1;
  2075. }
  2076. if (num_typeparam_args == 2) {
  2077. ADDOP_I(c, loc, SWAP, 2);
  2078. }
  2079. PyObject *type_params_name = PyUnicode_FromFormat("<generic parameters of %U>", name);
  2080. if (!type_params_name) {
  2081. return ERROR;
  2082. }
  2083. if (compiler_enter_scope(c, type_params_name, COMPILER_SCOPE_TYPEPARAMS,
  2084. (void *)type_params, firstlineno) == -1) {
  2085. Py_DECREF(type_params_name);
  2086. return ERROR;
  2087. }
  2088. Py_DECREF(type_params_name);
  2089. RETURN_IF_ERROR_IN_SCOPE(c, compiler_type_params(c, type_params));
  2090. if ((funcflags & 0x01) || (funcflags & 0x02)) {
  2091. RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i(INSTR_SEQUENCE(c), LOAD_FAST, 0, loc));
  2092. }
  2093. if ((funcflags & 0x01) && (funcflags & 0x02)) {
  2094. RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i(INSTR_SEQUENCE(c), LOAD_FAST, 1, loc));
  2095. }
  2096. }
  2097. annotations = compiler_visit_annotations(c, loc, args, returns);
  2098. if (annotations < 0) {
  2099. if (is_generic) {
  2100. compiler_exit_scope(c);
  2101. }
  2102. return ERROR;
  2103. }
  2104. if (annotations > 0) {
  2105. funcflags |= 0x04;
  2106. }
  2107. if (compiler_function_body(c, s, is_async, funcflags, firstlineno) < 0) {
  2108. if (is_generic) {
  2109. compiler_exit_scope(c);
  2110. }
  2111. return ERROR;
  2112. }
  2113. if (is_generic) {
  2114. RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i(
  2115. INSTR_SEQUENCE(c), SWAP, 2, loc));
  2116. RETURN_IF_ERROR_IN_SCOPE(c, codegen_addop_i(
  2117. INSTR_SEQUENCE(c), CALL_INTRINSIC_2, INTRINSIC_SET_FUNCTION_TYPE_PARAMS, loc));
  2118. c->u->u_metadata.u_argcount = num_typeparam_args;
  2119. PyCodeObject *co = optimize_and_assemble(c, 0);
  2120. compiler_exit_scope(c);
  2121. if (co == NULL) {
  2122. return ERROR;
  2123. }
  2124. if (compiler_make_closure(c, loc, co, 0) < 0) {
  2125. Py_DECREF(co);
  2126. return ERROR;
  2127. }
  2128. Py_DECREF(co);
  2129. if (num_typeparam_args > 0) {
  2130. ADDOP_I(c, loc, SWAP, num_typeparam_args + 1);
  2131. }
  2132. ADDOP_I(c, loc, CALL, num_typeparam_args);
  2133. }
  2134. RETURN_IF_ERROR(compiler_apply_decorators(c, decos));
  2135. return compiler_nameop(c, loc, name, Store);
  2136. }
  2137. static int
  2138. compiler_set_type_params_in_class(struct compiler *c, location loc)
  2139. {
  2140. _Py_DECLARE_STR(type_params, ".type_params");
  2141. RETURN_IF_ERROR(compiler_nameop(c, loc, &_Py_STR(type_params), Load));
  2142. RETURN_IF_ERROR(compiler_nameop(c, loc, &_Py_ID(__type_params__), Store));
  2143. return 1;
  2144. }
  2145. static int
  2146. compiler_class_body(struct compiler *c, stmt_ty s, int firstlineno)
  2147. {
  2148. /* ultimately generate code for:
  2149. <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
  2150. where:
  2151. <func> is a zero arg function/closure created from the class body.
  2152. It mutates its locals to build the class namespace.
  2153. <name> is the class name
  2154. <bases> is the positional arguments and *varargs argument
  2155. <keywords> is the keyword arguments and **kwds argument
  2156. This borrows from compiler_call.
  2157. */
  2158. /* 1. compile the class body into a code object */
  2159. RETURN_IF_ERROR(
  2160. compiler_enter_scope(c, s->v.ClassDef.name,
  2161. COMPILER_SCOPE_CLASS, (void *)s, firstlineno));
  2162. location loc = LOCATION(firstlineno, firstlineno, 0, 0);
  2163. /* use the class name for name mangling */
  2164. Py_XSETREF(c->u->u_private, Py_NewRef(s->v.ClassDef.name));
  2165. /* load (global) __name__ ... */
  2166. if (compiler_nameop(c, loc, &_Py_ID(__name__), Load) < 0) {
  2167. compiler_exit_scope(c);
  2168. return ERROR;
  2169. }
  2170. /* ... and store it as __module__ */
  2171. if (compiler_nameop(c, loc, &_Py_ID(__module__), Store) < 0) {
  2172. compiler_exit_scope(c);
  2173. return ERROR;
  2174. }
  2175. assert(c->u->u_metadata.u_qualname);
  2176. ADDOP_LOAD_CONST(c, loc, c->u->u_metadata.u_qualname);
  2177. if (compiler_nameop(c, loc, &_Py_ID(__qualname__), Store) < 0) {
  2178. compiler_exit_scope(c);
  2179. return ERROR;
  2180. }
  2181. asdl_type_param_seq *type_params = s->v.ClassDef.type_params;
  2182. if (asdl_seq_LEN(type_params) > 0) {
  2183. if (!compiler_set_type_params_in_class(c, loc)) {
  2184. compiler_exit_scope(c);
  2185. return ERROR;
  2186. }
  2187. }
  2188. if (c->u->u_ste->ste_needs_classdict) {
  2189. ADDOP(c, loc, LOAD_LOCALS);
  2190. // We can't use compiler_nameop here because we need to generate a
  2191. // STORE_DEREF in a class namespace, and compiler_nameop() won't do
  2192. // that by default.
  2193. PyObject *cellvars = c->u->u_metadata.u_cellvars;
  2194. if (compiler_addop_o(c->u, loc, STORE_DEREF, cellvars,
  2195. &_Py_ID(__classdict__)) < 0) {
  2196. compiler_exit_scope(c);
  2197. return ERROR;
  2198. }
  2199. }
  2200. /* compile the body proper */
  2201. if (compiler_body(c, loc, s->v.ClassDef.body) < 0) {
  2202. compiler_exit_scope(c);
  2203. return ERROR;
  2204. }
  2205. /* The following code is artificial */
  2206. /* Set __classdictcell__ if necessary */
  2207. if (c->u->u_ste->ste_needs_classdict) {
  2208. /* Store __classdictcell__ into class namespace */
  2209. int i = compiler_lookup_arg(c->u->u_metadata.u_cellvars, &_Py_ID(__classdict__));
  2210. if (i < 0) {
  2211. compiler_exit_scope(c);
  2212. return ERROR;
  2213. }
  2214. ADDOP_I(c, NO_LOCATION, LOAD_CLOSURE, i);
  2215. if (compiler_nameop(c, NO_LOCATION, &_Py_ID(__classdictcell__), Store) < 0) {
  2216. compiler_exit_scope(c);
  2217. return ERROR;
  2218. }
  2219. }
  2220. /* Return __classcell__ if it is referenced, otherwise return None */
  2221. if (c->u->u_ste->ste_needs_class_closure) {
  2222. /* Store __classcell__ into class namespace & return it */
  2223. int i = compiler_lookup_arg(c->u->u_metadata.u_cellvars, &_Py_ID(__class__));
  2224. if (i < 0) {
  2225. compiler_exit_scope(c);
  2226. return ERROR;
  2227. }
  2228. ADDOP_I(c, NO_LOCATION, LOAD_CLOSURE, i);
  2229. ADDOP_I(c, NO_LOCATION, COPY, 1);
  2230. if (compiler_nameop(c, NO_LOCATION, &_Py_ID(__classcell__), Store) < 0) {
  2231. compiler_exit_scope(c);
  2232. return ERROR;
  2233. }
  2234. }
  2235. else {
  2236. /* No methods referenced __class__, so just return None */
  2237. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  2238. }
  2239. ADDOP_IN_SCOPE(c, NO_LOCATION, RETURN_VALUE);
  2240. /* create the code object */
  2241. PyCodeObject *co = optimize_and_assemble(c, 1);
  2242. /* leave the new scope */
  2243. compiler_exit_scope(c);
  2244. if (co == NULL) {
  2245. return ERROR;
  2246. }
  2247. /* 2. load the 'build_class' function */
  2248. // these instructions should be attributed to the class line,
  2249. // not a decorator line
  2250. loc = LOC(s);
  2251. ADDOP(c, loc, PUSH_NULL);
  2252. ADDOP(c, loc, LOAD_BUILD_CLASS);
  2253. /* 3. load a function (or closure) made from the code object */
  2254. if (compiler_make_closure(c, loc, co, 0) < 0) {
  2255. Py_DECREF(co);
  2256. return ERROR;
  2257. }
  2258. Py_DECREF(co);
  2259. /* 4. load class name */
  2260. ADDOP_LOAD_CONST(c, loc, s->v.ClassDef.name);
  2261. return SUCCESS;
  2262. }
  2263. static int
  2264. compiler_class(struct compiler *c, stmt_ty s)
  2265. {
  2266. asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
  2267. RETURN_IF_ERROR(compiler_decorators(c, decos));
  2268. int firstlineno = s->lineno;
  2269. if (asdl_seq_LEN(decos)) {
  2270. firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
  2271. }
  2272. location loc = LOC(s);
  2273. asdl_type_param_seq *type_params = s->v.ClassDef.type_params;
  2274. int is_generic = asdl_seq_LEN(type_params) > 0;
  2275. if (is_generic) {
  2276. ADDOP(c, loc, PUSH_NULL);
  2277. PyObject *type_params_name = PyUnicode_FromFormat("<generic parameters of %U>",
  2278. s->v.ClassDef.name);
  2279. if (!type_params_name) {
  2280. return ERROR;
  2281. }
  2282. if (compiler_enter_scope(c, type_params_name, COMPILER_SCOPE_TYPEPARAMS,
  2283. (void *)type_params, firstlineno) == -1) {
  2284. Py_DECREF(type_params_name);
  2285. return ERROR;
  2286. }
  2287. Py_DECREF(type_params_name);
  2288. Py_XSETREF(c->u->u_private, Py_NewRef(s->v.ClassDef.name));
  2289. RETURN_IF_ERROR_IN_SCOPE(c, compiler_type_params(c, type_params));
  2290. _Py_DECLARE_STR(type_params, ".type_params");
  2291. RETURN_IF_ERROR_IN_SCOPE(c, compiler_nameop(c, loc, &_Py_STR(type_params), Store));
  2292. }
  2293. if (compiler_class_body(c, s, firstlineno) < 0) {
  2294. if (is_generic) {
  2295. compiler_exit_scope(c);
  2296. }
  2297. return ERROR;
  2298. }
  2299. /* generate the rest of the code for the call */
  2300. if (is_generic) {
  2301. _Py_DECLARE_STR(type_params, ".type_params");
  2302. _Py_DECLARE_STR(generic_base, ".generic_base");
  2303. RETURN_IF_ERROR_IN_SCOPE(c, compiler_nameop(c, loc, &_Py_STR(type_params), Load));
  2304. RETURN_IF_ERROR_IN_SCOPE(
  2305. c, codegen_addop_i(INSTR_SEQUENCE(c), CALL_INTRINSIC_1, INTRINSIC_SUBSCRIPT_GENERIC, loc)
  2306. )
  2307. RETURN_IF_ERROR_IN_SCOPE(c, compiler_nameop(c, loc, &_Py_STR(generic_base), Store));
  2308. Py_ssize_t original_len = asdl_seq_LEN(s->v.ClassDef.bases);
  2309. asdl_expr_seq *bases = _Py_asdl_expr_seq_new(
  2310. original_len + 1, c->c_arena);
  2311. if (bases == NULL) {
  2312. compiler_exit_scope(c);
  2313. return ERROR;
  2314. }
  2315. for (Py_ssize_t i = 0; i < original_len; i++) {
  2316. asdl_seq_SET(bases, i, asdl_seq_GET(s->v.ClassDef.bases, i));
  2317. }
  2318. expr_ty name_node = _PyAST_Name(
  2319. &_Py_STR(generic_base), Load,
  2320. loc.lineno, loc.col_offset, loc.end_lineno, loc.end_col_offset, c->c_arena
  2321. );
  2322. if (name_node == NULL) {
  2323. compiler_exit_scope(c);
  2324. return ERROR;
  2325. }
  2326. asdl_seq_SET(bases, original_len, name_node);
  2327. RETURN_IF_ERROR_IN_SCOPE(c, compiler_call_helper(c, loc, 2,
  2328. bases,
  2329. s->v.ClassDef.keywords));
  2330. PyCodeObject *co = optimize_and_assemble(c, 0);
  2331. compiler_exit_scope(c);
  2332. if (co == NULL) {
  2333. return ERROR;
  2334. }
  2335. if (compiler_make_closure(c, loc, co, 0) < 0) {
  2336. Py_DECREF(co);
  2337. return ERROR;
  2338. }
  2339. Py_DECREF(co);
  2340. ADDOP_I(c, loc, CALL, 0);
  2341. } else {
  2342. RETURN_IF_ERROR(compiler_call_helper(c, loc, 2,
  2343. s->v.ClassDef.bases,
  2344. s->v.ClassDef.keywords));
  2345. }
  2346. /* 6. apply decorators */
  2347. RETURN_IF_ERROR(compiler_apply_decorators(c, decos));
  2348. /* 7. store into <name> */
  2349. RETURN_IF_ERROR(compiler_nameop(c, loc, s->v.ClassDef.name, Store));
  2350. return SUCCESS;
  2351. }
  2352. static int
  2353. compiler_typealias_body(struct compiler *c, stmt_ty s)
  2354. {
  2355. location loc = LOC(s);
  2356. PyObject *name = s->v.TypeAlias.name->v.Name.id;
  2357. RETURN_IF_ERROR(
  2358. compiler_enter_scope(c, name, COMPILER_SCOPE_FUNCTION, s, loc.lineno));
  2359. /* Make None the first constant, so the evaluate function can't have a
  2360. docstring. */
  2361. RETURN_IF_ERROR(compiler_add_const(c->c_const_cache, c->u, Py_None));
  2362. VISIT_IN_SCOPE(c, expr, s->v.TypeAlias.value);
  2363. ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
  2364. PyCodeObject *co = optimize_and_assemble(c, 0);
  2365. compiler_exit_scope(c);
  2366. if (co == NULL) {
  2367. return ERROR;
  2368. }
  2369. if (compiler_make_closure(c, loc, co, 0) < 0) {
  2370. Py_DECREF(co);
  2371. return ERROR;
  2372. }
  2373. Py_DECREF(co);
  2374. ADDOP_I(c, loc, BUILD_TUPLE, 3);
  2375. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEALIAS);
  2376. return SUCCESS;
  2377. }
  2378. static int
  2379. compiler_typealias(struct compiler *c, stmt_ty s)
  2380. {
  2381. location loc = LOC(s);
  2382. asdl_type_param_seq *type_params = s->v.TypeAlias.type_params;
  2383. int is_generic = asdl_seq_LEN(type_params) > 0;
  2384. PyObject *name = s->v.TypeAlias.name->v.Name.id;
  2385. if (is_generic) {
  2386. ADDOP(c, loc, PUSH_NULL);
  2387. PyObject *type_params_name = PyUnicode_FromFormat("<generic parameters of %U>",
  2388. name);
  2389. if (!type_params_name) {
  2390. return ERROR;
  2391. }
  2392. if (compiler_enter_scope(c, type_params_name, COMPILER_SCOPE_TYPEPARAMS,
  2393. (void *)type_params, loc.lineno) == -1) {
  2394. Py_DECREF(type_params_name);
  2395. return ERROR;
  2396. }
  2397. Py_DECREF(type_params_name);
  2398. RETURN_IF_ERROR_IN_SCOPE(
  2399. c, compiler_addop_load_const(c->c_const_cache, c->u, loc, name)
  2400. );
  2401. RETURN_IF_ERROR_IN_SCOPE(c, compiler_type_params(c, type_params));
  2402. }
  2403. else {
  2404. ADDOP_LOAD_CONST(c, loc, name);
  2405. ADDOP_LOAD_CONST(c, loc, Py_None);
  2406. }
  2407. if (compiler_typealias_body(c, s) < 0) {
  2408. if (is_generic) {
  2409. compiler_exit_scope(c);
  2410. }
  2411. return ERROR;
  2412. }
  2413. if (is_generic) {
  2414. PyCodeObject *co = optimize_and_assemble(c, 0);
  2415. compiler_exit_scope(c);
  2416. if (co == NULL) {
  2417. return ERROR;
  2418. }
  2419. if (compiler_make_closure(c, loc, co, 0) < 0) {
  2420. Py_DECREF(co);
  2421. return ERROR;
  2422. }
  2423. Py_DECREF(co);
  2424. ADDOP_I(c, loc, CALL, 0);
  2425. }
  2426. RETURN_IF_ERROR(compiler_nameop(c, loc, name, Store));
  2427. return SUCCESS;
  2428. }
  2429. /* Return false if the expression is a constant value except named singletons.
  2430. Return true otherwise. */
  2431. static bool
  2432. check_is_arg(expr_ty e)
  2433. {
  2434. if (e->kind != Constant_kind) {
  2435. return true;
  2436. }
  2437. PyObject *value = e->v.Constant.value;
  2438. return (value == Py_None
  2439. || value == Py_False
  2440. || value == Py_True
  2441. || value == Py_Ellipsis);
  2442. }
  2443. static PyTypeObject * infer_type(expr_ty e);
  2444. /* Check operands of identity checks ("is" and "is not").
  2445. Emit a warning if any operand is a constant except named singletons.
  2446. */
  2447. static int
  2448. check_compare(struct compiler *c, expr_ty e)
  2449. {
  2450. Py_ssize_t i, n;
  2451. bool left = check_is_arg(e->v.Compare.left);
  2452. expr_ty left_expr = e->v.Compare.left;
  2453. n = asdl_seq_LEN(e->v.Compare.ops);
  2454. for (i = 0; i < n; i++) {
  2455. cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
  2456. expr_ty right_expr = (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i);
  2457. bool right = check_is_arg(right_expr);
  2458. if (op == Is || op == IsNot) {
  2459. if (!right || !left) {
  2460. const char *msg = (op == Is)
  2461. ? "\"is\" with '%.200s' literal. Did you mean \"==\"?"
  2462. : "\"is not\" with '%.200s' literal. Did you mean \"!=\"?";
  2463. expr_ty literal = !left ? left_expr : right_expr;
  2464. return compiler_warn(
  2465. c, LOC(e), msg, infer_type(literal)->tp_name
  2466. );
  2467. }
  2468. }
  2469. left = right;
  2470. left_expr = right_expr;
  2471. }
  2472. return SUCCESS;
  2473. }
  2474. static const int compare_masks[] = {
  2475. [Py_LT] = COMPARISON_LESS_THAN,
  2476. [Py_LE] = COMPARISON_LESS_THAN | COMPARISON_EQUALS,
  2477. [Py_EQ] = COMPARISON_EQUALS,
  2478. [Py_NE] = COMPARISON_NOT_EQUALS,
  2479. [Py_GT] = COMPARISON_GREATER_THAN,
  2480. [Py_GE] = COMPARISON_GREATER_THAN | COMPARISON_EQUALS,
  2481. };
  2482. static int compiler_addcompare(struct compiler *c, location loc,
  2483. cmpop_ty op)
  2484. {
  2485. int cmp;
  2486. switch (op) {
  2487. case Eq:
  2488. cmp = Py_EQ;
  2489. break;
  2490. case NotEq:
  2491. cmp = Py_NE;
  2492. break;
  2493. case Lt:
  2494. cmp = Py_LT;
  2495. break;
  2496. case LtE:
  2497. cmp = Py_LE;
  2498. break;
  2499. case Gt:
  2500. cmp = Py_GT;
  2501. break;
  2502. case GtE:
  2503. cmp = Py_GE;
  2504. break;
  2505. case Is:
  2506. ADDOP_I(c, loc, IS_OP, 0);
  2507. return SUCCESS;
  2508. case IsNot:
  2509. ADDOP_I(c, loc, IS_OP, 1);
  2510. return SUCCESS;
  2511. case In:
  2512. ADDOP_I(c, loc, CONTAINS_OP, 0);
  2513. return SUCCESS;
  2514. case NotIn:
  2515. ADDOP_I(c, loc, CONTAINS_OP, 1);
  2516. return SUCCESS;
  2517. default:
  2518. Py_UNREACHABLE();
  2519. }
  2520. /* cmp goes in top bits of the oparg, while the low bits are used by quickened
  2521. * versions of this opcode to store the comparison mask. */
  2522. ADDOP_I(c, loc, COMPARE_OP, (cmp << 4) | compare_masks[cmp]);
  2523. return SUCCESS;
  2524. }
  2525. static int
  2526. compiler_jump_if(struct compiler *c, location loc,
  2527. expr_ty e, jump_target_label next, int cond)
  2528. {
  2529. switch (e->kind) {
  2530. case UnaryOp_kind:
  2531. if (e->v.UnaryOp.op == Not) {
  2532. return compiler_jump_if(c, loc, e->v.UnaryOp.operand, next, !cond);
  2533. }
  2534. /* fallback to general implementation */
  2535. break;
  2536. case BoolOp_kind: {
  2537. asdl_expr_seq *s = e->v.BoolOp.values;
  2538. Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
  2539. assert(n >= 0);
  2540. int cond2 = e->v.BoolOp.op == Or;
  2541. jump_target_label next2 = next;
  2542. if (!cond2 != !cond) {
  2543. NEW_JUMP_TARGET_LABEL(c, new_next2);
  2544. next2 = new_next2;
  2545. }
  2546. for (i = 0; i < n; ++i) {
  2547. RETURN_IF_ERROR(
  2548. compiler_jump_if(c, loc, (expr_ty)asdl_seq_GET(s, i), next2, cond2));
  2549. }
  2550. RETURN_IF_ERROR(
  2551. compiler_jump_if(c, loc, (expr_ty)asdl_seq_GET(s, n), next, cond));
  2552. if (!SAME_LABEL(next2, next)) {
  2553. USE_LABEL(c, next2);
  2554. }
  2555. return SUCCESS;
  2556. }
  2557. case IfExp_kind: {
  2558. NEW_JUMP_TARGET_LABEL(c, end);
  2559. NEW_JUMP_TARGET_LABEL(c, next2);
  2560. RETURN_IF_ERROR(
  2561. compiler_jump_if(c, loc, e->v.IfExp.test, next2, 0));
  2562. RETURN_IF_ERROR(
  2563. compiler_jump_if(c, loc, e->v.IfExp.body, next, cond));
  2564. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  2565. USE_LABEL(c, next2);
  2566. RETURN_IF_ERROR(
  2567. compiler_jump_if(c, loc, e->v.IfExp.orelse, next, cond));
  2568. USE_LABEL(c, end);
  2569. return SUCCESS;
  2570. }
  2571. case Compare_kind: {
  2572. Py_ssize_t n = asdl_seq_LEN(e->v.Compare.ops) - 1;
  2573. if (n > 0) {
  2574. RETURN_IF_ERROR(check_compare(c, e));
  2575. NEW_JUMP_TARGET_LABEL(c, cleanup);
  2576. VISIT(c, expr, e->v.Compare.left);
  2577. for (Py_ssize_t i = 0; i < n; i++) {
  2578. VISIT(c, expr,
  2579. (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
  2580. ADDOP_I(c, LOC(e), SWAP, 2);
  2581. ADDOP_I(c, LOC(e), COPY, 2);
  2582. ADDOP_COMPARE(c, LOC(e), asdl_seq_GET(e->v.Compare.ops, i));
  2583. ADDOP_JUMP(c, LOC(e), POP_JUMP_IF_FALSE, cleanup);
  2584. }
  2585. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
  2586. ADDOP_COMPARE(c, LOC(e), asdl_seq_GET(e->v.Compare.ops, n));
  2587. ADDOP_JUMP(c, LOC(e), cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
  2588. NEW_JUMP_TARGET_LABEL(c, end);
  2589. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  2590. USE_LABEL(c, cleanup);
  2591. ADDOP(c, LOC(e), POP_TOP);
  2592. if (!cond) {
  2593. ADDOP_JUMP(c, NO_LOCATION, JUMP, next);
  2594. }
  2595. USE_LABEL(c, end);
  2596. return SUCCESS;
  2597. }
  2598. /* fallback to general implementation */
  2599. break;
  2600. }
  2601. default:
  2602. /* fallback to general implementation */
  2603. break;
  2604. }
  2605. /* general implementation */
  2606. VISIT(c, expr, e);
  2607. ADDOP_JUMP(c, LOC(e), cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
  2608. return SUCCESS;
  2609. }
  2610. static int
  2611. compiler_ifexp(struct compiler *c, expr_ty e)
  2612. {
  2613. assert(e->kind == IfExp_kind);
  2614. NEW_JUMP_TARGET_LABEL(c, end);
  2615. NEW_JUMP_TARGET_LABEL(c, next);
  2616. RETURN_IF_ERROR(
  2617. compiler_jump_if(c, LOC(e), e->v.IfExp.test, next, 0));
  2618. VISIT(c, expr, e->v.IfExp.body);
  2619. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  2620. USE_LABEL(c, next);
  2621. VISIT(c, expr, e->v.IfExp.orelse);
  2622. USE_LABEL(c, end);
  2623. return SUCCESS;
  2624. }
  2625. static int
  2626. compiler_lambda(struct compiler *c, expr_ty e)
  2627. {
  2628. PyCodeObject *co;
  2629. Py_ssize_t funcflags;
  2630. arguments_ty args = e->v.Lambda.args;
  2631. assert(e->kind == Lambda_kind);
  2632. RETURN_IF_ERROR(compiler_check_debug_args(c, args));
  2633. location loc = LOC(e);
  2634. funcflags = compiler_default_arguments(c, loc, args);
  2635. if (funcflags == -1) {
  2636. return ERROR;
  2637. }
  2638. _Py_DECLARE_STR(anon_lambda, "<lambda>");
  2639. RETURN_IF_ERROR(
  2640. compiler_enter_scope(c, &_Py_STR(anon_lambda), COMPILER_SCOPE_LAMBDA,
  2641. (void *)e, e->lineno));
  2642. /* Make None the first constant, so the lambda can't have a
  2643. docstring. */
  2644. RETURN_IF_ERROR(compiler_add_const(c->c_const_cache, c->u, Py_None));
  2645. c->u->u_metadata.u_argcount = asdl_seq_LEN(args->args);
  2646. c->u->u_metadata.u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
  2647. c->u->u_metadata.u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
  2648. VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
  2649. if (c->u->u_ste->ste_generator) {
  2650. co = optimize_and_assemble(c, 0);
  2651. }
  2652. else {
  2653. location loc = LOC(e->v.Lambda.body);
  2654. ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
  2655. co = optimize_and_assemble(c, 1);
  2656. }
  2657. compiler_exit_scope(c);
  2658. if (co == NULL) {
  2659. return ERROR;
  2660. }
  2661. if (compiler_make_closure(c, loc, co, funcflags) < 0) {
  2662. Py_DECREF(co);
  2663. return ERROR;
  2664. }
  2665. Py_DECREF(co);
  2666. return SUCCESS;
  2667. }
  2668. static int
  2669. compiler_if(struct compiler *c, stmt_ty s)
  2670. {
  2671. jump_target_label next;
  2672. assert(s->kind == If_kind);
  2673. NEW_JUMP_TARGET_LABEL(c, end);
  2674. if (asdl_seq_LEN(s->v.If.orelse)) {
  2675. NEW_JUMP_TARGET_LABEL(c, orelse);
  2676. next = orelse;
  2677. }
  2678. else {
  2679. next = end;
  2680. }
  2681. RETURN_IF_ERROR(
  2682. compiler_jump_if(c, LOC(s), s->v.If.test, next, 0));
  2683. VISIT_SEQ(c, stmt, s->v.If.body);
  2684. if (asdl_seq_LEN(s->v.If.orelse)) {
  2685. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  2686. USE_LABEL(c, next);
  2687. VISIT_SEQ(c, stmt, s->v.If.orelse);
  2688. }
  2689. USE_LABEL(c, end);
  2690. return SUCCESS;
  2691. }
  2692. static int
  2693. compiler_for(struct compiler *c, stmt_ty s)
  2694. {
  2695. location loc = LOC(s);
  2696. NEW_JUMP_TARGET_LABEL(c, start);
  2697. NEW_JUMP_TARGET_LABEL(c, body);
  2698. NEW_JUMP_TARGET_LABEL(c, cleanup);
  2699. NEW_JUMP_TARGET_LABEL(c, end);
  2700. RETURN_IF_ERROR(compiler_push_fblock(c, loc, FOR_LOOP, start, end, NULL));
  2701. VISIT(c, expr, s->v.For.iter);
  2702. loc = LOC(s->v.For.iter);
  2703. ADDOP(c, loc, GET_ITER);
  2704. USE_LABEL(c, start);
  2705. ADDOP_JUMP(c, loc, FOR_ITER, cleanup);
  2706. /* Add NOP to ensure correct line tracing of multiline for statements.
  2707. * It will be removed later if redundant.
  2708. */
  2709. ADDOP(c, LOC(s->v.For.target), NOP);
  2710. USE_LABEL(c, body);
  2711. VISIT(c, expr, s->v.For.target);
  2712. VISIT_SEQ(c, stmt, s->v.For.body);
  2713. /* Mark jump as artificial */
  2714. ADDOP_JUMP(c, NO_LOCATION, JUMP, start);
  2715. USE_LABEL(c, cleanup);
  2716. ADDOP(c, NO_LOCATION, END_FOR);
  2717. compiler_pop_fblock(c, FOR_LOOP, start);
  2718. VISIT_SEQ(c, stmt, s->v.For.orelse);
  2719. USE_LABEL(c, end);
  2720. return SUCCESS;
  2721. }
  2722. static int
  2723. compiler_async_for(struct compiler *c, stmt_ty s)
  2724. {
  2725. location loc = LOC(s);
  2726. if (IS_TOP_LEVEL_AWAIT(c)){
  2727. c->u->u_ste->ste_coroutine = 1;
  2728. } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
  2729. return compiler_error(c, loc, "'async for' outside async function");
  2730. }
  2731. NEW_JUMP_TARGET_LABEL(c, start);
  2732. NEW_JUMP_TARGET_LABEL(c, except);
  2733. NEW_JUMP_TARGET_LABEL(c, end);
  2734. VISIT(c, expr, s->v.AsyncFor.iter);
  2735. ADDOP(c, loc, GET_AITER);
  2736. USE_LABEL(c, start);
  2737. RETURN_IF_ERROR(compiler_push_fblock(c, loc, FOR_LOOP, start, end, NULL));
  2738. /* SETUP_FINALLY to guard the __anext__ call */
  2739. ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
  2740. ADDOP(c, loc, GET_ANEXT);
  2741. ADDOP_LOAD_CONST(c, loc, Py_None);
  2742. ADD_YIELD_FROM(c, loc, 1);
  2743. ADDOP(c, loc, POP_BLOCK); /* for SETUP_FINALLY */
  2744. /* Success block for __anext__ */
  2745. VISIT(c, expr, s->v.AsyncFor.target);
  2746. VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
  2747. /* Mark jump as artificial */
  2748. ADDOP_JUMP(c, NO_LOCATION, JUMP, start);
  2749. compiler_pop_fblock(c, FOR_LOOP, start);
  2750. /* Except block for __anext__ */
  2751. USE_LABEL(c, except);
  2752. /* Use same line number as the iterator,
  2753. * as the END_ASYNC_FOR succeeds the `for`, not the body. */
  2754. loc = LOC(s->v.AsyncFor.iter);
  2755. ADDOP(c, loc, END_ASYNC_FOR);
  2756. /* `else` block */
  2757. VISIT_SEQ(c, stmt, s->v.For.orelse);
  2758. USE_LABEL(c, end);
  2759. return SUCCESS;
  2760. }
  2761. static int
  2762. compiler_while(struct compiler *c, stmt_ty s)
  2763. {
  2764. NEW_JUMP_TARGET_LABEL(c, loop);
  2765. NEW_JUMP_TARGET_LABEL(c, body);
  2766. NEW_JUMP_TARGET_LABEL(c, end);
  2767. NEW_JUMP_TARGET_LABEL(c, anchor);
  2768. USE_LABEL(c, loop);
  2769. RETURN_IF_ERROR(compiler_push_fblock(c, LOC(s), WHILE_LOOP, loop, end, NULL));
  2770. RETURN_IF_ERROR(compiler_jump_if(c, LOC(s), s->v.While.test, anchor, 0));
  2771. USE_LABEL(c, body);
  2772. VISIT_SEQ(c, stmt, s->v.While.body);
  2773. RETURN_IF_ERROR(compiler_jump_if(c, LOC(s), s->v.While.test, body, 1));
  2774. compiler_pop_fblock(c, WHILE_LOOP, loop);
  2775. USE_LABEL(c, anchor);
  2776. if (s->v.While.orelse) {
  2777. VISIT_SEQ(c, stmt, s->v.While.orelse);
  2778. }
  2779. USE_LABEL(c, end);
  2780. return SUCCESS;
  2781. }
  2782. static int
  2783. compiler_return(struct compiler *c, stmt_ty s)
  2784. {
  2785. location loc = LOC(s);
  2786. int preserve_tos = ((s->v.Return.value != NULL) &&
  2787. (s->v.Return.value->kind != Constant_kind));
  2788. if (!_PyST_IsFunctionLike(c->u->u_ste)) {
  2789. return compiler_error(c, loc, "'return' outside function");
  2790. }
  2791. if (s->v.Return.value != NULL &&
  2792. c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
  2793. {
  2794. return compiler_error(c, loc, "'return' with value in async generator");
  2795. }
  2796. if (preserve_tos) {
  2797. VISIT(c, expr, s->v.Return.value);
  2798. } else {
  2799. /* Emit instruction with line number for return value */
  2800. if (s->v.Return.value != NULL) {
  2801. loc = LOC(s->v.Return.value);
  2802. ADDOP(c, loc, NOP);
  2803. }
  2804. }
  2805. if (s->v.Return.value == NULL || s->v.Return.value->lineno != s->lineno) {
  2806. loc = LOC(s);
  2807. ADDOP(c, loc, NOP);
  2808. }
  2809. RETURN_IF_ERROR(compiler_unwind_fblock_stack(c, &loc, preserve_tos, NULL));
  2810. if (s->v.Return.value == NULL) {
  2811. ADDOP_LOAD_CONST(c, loc, Py_None);
  2812. }
  2813. else if (!preserve_tos) {
  2814. ADDOP_LOAD_CONST(c, loc, s->v.Return.value->v.Constant.value);
  2815. }
  2816. ADDOP(c, loc, RETURN_VALUE);
  2817. return SUCCESS;
  2818. }
  2819. static int
  2820. compiler_break(struct compiler *c, location loc)
  2821. {
  2822. struct fblockinfo *loop = NULL;
  2823. location origin_loc = loc;
  2824. /* Emit instruction with line number */
  2825. ADDOP(c, loc, NOP);
  2826. RETURN_IF_ERROR(compiler_unwind_fblock_stack(c, &loc, 0, &loop));
  2827. if (loop == NULL) {
  2828. return compiler_error(c, origin_loc, "'break' outside loop");
  2829. }
  2830. RETURN_IF_ERROR(compiler_unwind_fblock(c, &loc, loop, 0));
  2831. ADDOP_JUMP(c, loc, JUMP, loop->fb_exit);
  2832. return SUCCESS;
  2833. }
  2834. static int
  2835. compiler_continue(struct compiler *c, location loc)
  2836. {
  2837. struct fblockinfo *loop = NULL;
  2838. location origin_loc = loc;
  2839. /* Emit instruction with line number */
  2840. ADDOP(c, loc, NOP);
  2841. RETURN_IF_ERROR(compiler_unwind_fblock_stack(c, &loc, 0, &loop));
  2842. if (loop == NULL) {
  2843. return compiler_error(c, origin_loc, "'continue' not properly in loop");
  2844. }
  2845. ADDOP_JUMP(c, loc, JUMP, loop->fb_block);
  2846. return SUCCESS;
  2847. }
  2848. /* Code generated for "try: <body> finally: <finalbody>" is as follows:
  2849. SETUP_FINALLY L
  2850. <code for body>
  2851. POP_BLOCK
  2852. <code for finalbody>
  2853. JUMP E
  2854. L:
  2855. <code for finalbody>
  2856. E:
  2857. The special instructions use the block stack. Each block
  2858. stack entry contains the instruction that created it (here
  2859. SETUP_FINALLY), the level of the value stack at the time the
  2860. block stack entry was created, and a label (here L).
  2861. SETUP_FINALLY:
  2862. Pushes the current value stack level and the label
  2863. onto the block stack.
  2864. POP_BLOCK:
  2865. Pops en entry from the block stack.
  2866. The block stack is unwound when an exception is raised:
  2867. when a SETUP_FINALLY entry is found, the raised and the caught
  2868. exceptions are pushed onto the value stack (and the exception
  2869. condition is cleared), and the interpreter jumps to the label
  2870. gotten from the block stack.
  2871. */
  2872. static int
  2873. compiler_try_finally(struct compiler *c, stmt_ty s)
  2874. {
  2875. location loc = LOC(s);
  2876. NEW_JUMP_TARGET_LABEL(c, body);
  2877. NEW_JUMP_TARGET_LABEL(c, end);
  2878. NEW_JUMP_TARGET_LABEL(c, exit);
  2879. NEW_JUMP_TARGET_LABEL(c, cleanup);
  2880. /* `try` block */
  2881. ADDOP_JUMP(c, loc, SETUP_FINALLY, end);
  2882. USE_LABEL(c, body);
  2883. RETURN_IF_ERROR(
  2884. compiler_push_fblock(c, loc, FINALLY_TRY, body, end,
  2885. s->v.Try.finalbody));
  2886. if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
  2887. RETURN_IF_ERROR(compiler_try_except(c, s));
  2888. }
  2889. else {
  2890. VISIT_SEQ(c, stmt, s->v.Try.body);
  2891. }
  2892. ADDOP(c, NO_LOCATION, POP_BLOCK);
  2893. compiler_pop_fblock(c, FINALLY_TRY, body);
  2894. VISIT_SEQ(c, stmt, s->v.Try.finalbody);
  2895. ADDOP_JUMP(c, NO_LOCATION, JUMP, exit);
  2896. /* `finally` block */
  2897. USE_LABEL(c, end);
  2898. loc = NO_LOCATION;
  2899. ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
  2900. ADDOP(c, loc, PUSH_EXC_INFO);
  2901. RETURN_IF_ERROR(
  2902. compiler_push_fblock(c, loc, FINALLY_END, end, NO_LABEL, NULL));
  2903. VISIT_SEQ(c, stmt, s->v.Try.finalbody);
  2904. compiler_pop_fblock(c, FINALLY_END, end);
  2905. loc = NO_LOCATION;
  2906. ADDOP_I(c, loc, RERAISE, 0);
  2907. USE_LABEL(c, cleanup);
  2908. POP_EXCEPT_AND_RERAISE(c, loc);
  2909. USE_LABEL(c, exit);
  2910. return SUCCESS;
  2911. }
  2912. static int
  2913. compiler_try_star_finally(struct compiler *c, stmt_ty s)
  2914. {
  2915. location loc = LOC(s);
  2916. NEW_JUMP_TARGET_LABEL(c, body);
  2917. NEW_JUMP_TARGET_LABEL(c, end);
  2918. NEW_JUMP_TARGET_LABEL(c, exit);
  2919. NEW_JUMP_TARGET_LABEL(c, cleanup);
  2920. /* `try` block */
  2921. ADDOP_JUMP(c, loc, SETUP_FINALLY, end);
  2922. USE_LABEL(c, body);
  2923. RETURN_IF_ERROR(
  2924. compiler_push_fblock(c, loc, FINALLY_TRY, body, end,
  2925. s->v.TryStar.finalbody));
  2926. if (s->v.TryStar.handlers && asdl_seq_LEN(s->v.TryStar.handlers)) {
  2927. RETURN_IF_ERROR(compiler_try_star_except(c, s));
  2928. }
  2929. else {
  2930. VISIT_SEQ(c, stmt, s->v.TryStar.body);
  2931. }
  2932. ADDOP(c, NO_LOCATION, POP_BLOCK);
  2933. compiler_pop_fblock(c, FINALLY_TRY, body);
  2934. VISIT_SEQ(c, stmt, s->v.TryStar.finalbody);
  2935. ADDOP_JUMP(c, NO_LOCATION, JUMP, exit);
  2936. /* `finally` block */
  2937. USE_LABEL(c, end);
  2938. loc = NO_LOCATION;
  2939. ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
  2940. ADDOP(c, loc, PUSH_EXC_INFO);
  2941. RETURN_IF_ERROR(
  2942. compiler_push_fblock(c, loc, FINALLY_END, end, NO_LABEL, NULL));
  2943. VISIT_SEQ(c, stmt, s->v.TryStar.finalbody);
  2944. compiler_pop_fblock(c, FINALLY_END, end);
  2945. loc = NO_LOCATION;
  2946. ADDOP_I(c, loc, RERAISE, 0);
  2947. USE_LABEL(c, cleanup);
  2948. POP_EXCEPT_AND_RERAISE(c, loc);
  2949. USE_LABEL(c, exit);
  2950. return SUCCESS;
  2951. }
  2952. /*
  2953. Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
  2954. (The contents of the value stack is shown in [], with the top
  2955. at the right; 'tb' is trace-back info, 'val' the exception's
  2956. associated value, and 'exc' the exception.)
  2957. Value stack Label Instruction Argument
  2958. [] SETUP_FINALLY L1
  2959. [] <code for S>
  2960. [] POP_BLOCK
  2961. [] JUMP L0
  2962. [exc] L1: <evaluate E1> )
  2963. [exc, E1] CHECK_EXC_MATCH )
  2964. [exc, bool] POP_JUMP_IF_FALSE L2 ) only if E1
  2965. [exc] <assign to V1> (or POP if no V1)
  2966. [] <code for S1>
  2967. JUMP L0
  2968. [exc] L2: <evaluate E2>
  2969. .............................etc.......................
  2970. [exc] Ln+1: RERAISE # re-raise exception
  2971. [] L0: <next statement>
  2972. Of course, parts are not generated if Vi or Ei is not present.
  2973. */
  2974. static int
  2975. compiler_try_except(struct compiler *c, stmt_ty s)
  2976. {
  2977. location loc = LOC(s);
  2978. Py_ssize_t i, n;
  2979. NEW_JUMP_TARGET_LABEL(c, body);
  2980. NEW_JUMP_TARGET_LABEL(c, except);
  2981. NEW_JUMP_TARGET_LABEL(c, end);
  2982. NEW_JUMP_TARGET_LABEL(c, cleanup);
  2983. ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
  2984. USE_LABEL(c, body);
  2985. RETURN_IF_ERROR(
  2986. compiler_push_fblock(c, loc, TRY_EXCEPT, body, NO_LABEL, NULL));
  2987. VISIT_SEQ(c, stmt, s->v.Try.body);
  2988. compiler_pop_fblock(c, TRY_EXCEPT, body);
  2989. ADDOP(c, NO_LOCATION, POP_BLOCK);
  2990. if (s->v.Try.orelse && asdl_seq_LEN(s->v.Try.orelse)) {
  2991. VISIT_SEQ(c, stmt, s->v.Try.orelse);
  2992. }
  2993. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  2994. n = asdl_seq_LEN(s->v.Try.handlers);
  2995. USE_LABEL(c, except);
  2996. ADDOP_JUMP(c, NO_LOCATION, SETUP_CLEANUP, cleanup);
  2997. ADDOP(c, NO_LOCATION, PUSH_EXC_INFO);
  2998. /* Runtime will push a block here, so we need to account for that */
  2999. RETURN_IF_ERROR(
  3000. compiler_push_fblock(c, loc, EXCEPTION_HANDLER, NO_LABEL, NO_LABEL, NULL));
  3001. for (i = 0; i < n; i++) {
  3002. excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
  3003. s->v.Try.handlers, i);
  3004. location loc = LOC(handler);
  3005. if (!handler->v.ExceptHandler.type && i < n-1) {
  3006. return compiler_error(c, loc, "default 'except:' must be last");
  3007. }
  3008. NEW_JUMP_TARGET_LABEL(c, next_except);
  3009. except = next_except;
  3010. if (handler->v.ExceptHandler.type) {
  3011. VISIT(c, expr, handler->v.ExceptHandler.type);
  3012. ADDOP(c, loc, CHECK_EXC_MATCH);
  3013. ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, except);
  3014. }
  3015. if (handler->v.ExceptHandler.name) {
  3016. NEW_JUMP_TARGET_LABEL(c, cleanup_end);
  3017. NEW_JUMP_TARGET_LABEL(c, cleanup_body);
  3018. RETURN_IF_ERROR(
  3019. compiler_nameop(c, loc, handler->v.ExceptHandler.name, Store));
  3020. /*
  3021. try:
  3022. # body
  3023. except type as name:
  3024. try:
  3025. # body
  3026. finally:
  3027. name = None # in case body contains "del name"
  3028. del name
  3029. */
  3030. /* second try: */
  3031. ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup_end);
  3032. USE_LABEL(c, cleanup_body);
  3033. RETURN_IF_ERROR(
  3034. compiler_push_fblock(c, loc, HANDLER_CLEANUP, cleanup_body,
  3035. NO_LABEL, handler->v.ExceptHandler.name));
  3036. /* second # body */
  3037. VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
  3038. compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
  3039. /* name = None; del name; # Mark as artificial */
  3040. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3041. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3042. ADDOP(c, NO_LOCATION, POP_EXCEPT);
  3043. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  3044. RETURN_IF_ERROR(
  3045. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
  3046. RETURN_IF_ERROR(
  3047. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
  3048. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  3049. /* except: */
  3050. USE_LABEL(c, cleanup_end);
  3051. /* name = None; del name; # artificial */
  3052. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  3053. RETURN_IF_ERROR(
  3054. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
  3055. RETURN_IF_ERROR(
  3056. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
  3057. ADDOP_I(c, NO_LOCATION, RERAISE, 1);
  3058. }
  3059. else {
  3060. NEW_JUMP_TARGET_LABEL(c, cleanup_body);
  3061. ADDOP(c, loc, POP_TOP); /* exc_value */
  3062. USE_LABEL(c, cleanup_body);
  3063. RETURN_IF_ERROR(
  3064. compiler_push_fblock(c, loc, HANDLER_CLEANUP, cleanup_body,
  3065. NO_LABEL, NULL));
  3066. VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
  3067. compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
  3068. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3069. ADDOP(c, NO_LOCATION, POP_EXCEPT);
  3070. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  3071. }
  3072. USE_LABEL(c, except);
  3073. }
  3074. /* artificial */
  3075. compiler_pop_fblock(c, EXCEPTION_HANDLER, NO_LABEL);
  3076. ADDOP_I(c, NO_LOCATION, RERAISE, 0);
  3077. USE_LABEL(c, cleanup);
  3078. POP_EXCEPT_AND_RERAISE(c, NO_LOCATION);
  3079. USE_LABEL(c, end);
  3080. return SUCCESS;
  3081. }
  3082. /*
  3083. Code generated for "try: S except* E1 as V1: S1 except* E2 as V2: S2 ...":
  3084. (The contents of the value stack is shown in [], with the top
  3085. at the right; 'tb' is trace-back info, 'val' the exception instance,
  3086. and 'typ' the exception's type.)
  3087. Value stack Label Instruction Argument
  3088. [] SETUP_FINALLY L1
  3089. [] <code for S>
  3090. [] POP_BLOCK
  3091. [] JUMP L0
  3092. [exc] L1: BUILD_LIST ) list for raised/reraised excs ("result")
  3093. [orig, res] COPY 2 ) make a copy of the original EG
  3094. [orig, res, exc] <evaluate E1>
  3095. [orig, res, exc, E1] CHECK_EG_MATCH
  3096. [orig, res, rest/exc, match?] COPY 1
  3097. [orig, res, rest/exc, match?, match?] POP_JUMP_IF_NONE C1
  3098. [orig, res, rest, match] <assign to V1> (or POP if no V1)
  3099. [orig, res, rest] SETUP_FINALLY R1
  3100. [orig, res, rest] <code for S1>
  3101. [orig, res, rest] JUMP L2
  3102. [orig, res, rest, i, v] R1: LIST_APPEND 3 ) exc raised in except* body - add to res
  3103. [orig, res, rest, i] POP
  3104. [orig, res, rest] JUMP LE2
  3105. [orig, res, rest] L2: NOP ) for lineno
  3106. [orig, res, rest] JUMP LE2
  3107. [orig, res, rest/exc, None] C1: POP
  3108. [orig, res, rest] LE2: <evaluate E2>
  3109. .............................etc.......................
  3110. [orig, res, rest] Ln+1: LIST_APPEND 1 ) add unhandled exc to res (could be None)
  3111. [orig, res] CALL_INTRINSIC_2 PREP_RERAISE_STAR
  3112. [exc] COPY 1
  3113. [exc, exc] POP_JUMP_IF_NOT_NONE RER
  3114. [exc] POP_TOP
  3115. [] JUMP L0
  3116. [exc] RER: SWAP 2
  3117. [exc, prev_exc_info] POP_EXCEPT
  3118. [exc] RERAISE 0
  3119. [] L0: <next statement>
  3120. */
  3121. static int
  3122. compiler_try_star_except(struct compiler *c, stmt_ty s)
  3123. {
  3124. location loc = LOC(s);
  3125. NEW_JUMP_TARGET_LABEL(c, body);
  3126. NEW_JUMP_TARGET_LABEL(c, except);
  3127. NEW_JUMP_TARGET_LABEL(c, orelse);
  3128. NEW_JUMP_TARGET_LABEL(c, end);
  3129. NEW_JUMP_TARGET_LABEL(c, cleanup);
  3130. NEW_JUMP_TARGET_LABEL(c, reraise_star);
  3131. ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
  3132. USE_LABEL(c, body);
  3133. RETURN_IF_ERROR(
  3134. compiler_push_fblock(c, loc, TRY_EXCEPT, body, NO_LABEL, NULL));
  3135. VISIT_SEQ(c, stmt, s->v.TryStar.body);
  3136. compiler_pop_fblock(c, TRY_EXCEPT, body);
  3137. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3138. ADDOP_JUMP(c, NO_LOCATION, JUMP, orelse);
  3139. Py_ssize_t n = asdl_seq_LEN(s->v.TryStar.handlers);
  3140. USE_LABEL(c, except);
  3141. ADDOP_JUMP(c, NO_LOCATION, SETUP_CLEANUP, cleanup);
  3142. ADDOP(c, NO_LOCATION, PUSH_EXC_INFO);
  3143. /* Runtime will push a block here, so we need to account for that */
  3144. RETURN_IF_ERROR(
  3145. compiler_push_fblock(c, loc, EXCEPTION_GROUP_HANDLER,
  3146. NO_LABEL, NO_LABEL, "except handler"));
  3147. for (Py_ssize_t i = 0; i < n; i++) {
  3148. excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
  3149. s->v.TryStar.handlers, i);
  3150. location loc = LOC(handler);
  3151. NEW_JUMP_TARGET_LABEL(c, next_except);
  3152. except = next_except;
  3153. NEW_JUMP_TARGET_LABEL(c, except_with_error);
  3154. NEW_JUMP_TARGET_LABEL(c, no_match);
  3155. if (i == 0) {
  3156. /* create empty list for exceptions raised/reraise in the except* blocks */
  3157. /*
  3158. [orig] BUILD_LIST
  3159. */
  3160. /* Create a copy of the original EG */
  3161. /*
  3162. [orig, []] COPY 2
  3163. [orig, [], exc]
  3164. */
  3165. ADDOP_I(c, loc, BUILD_LIST, 0);
  3166. ADDOP_I(c, loc, COPY, 2);
  3167. }
  3168. if (handler->v.ExceptHandler.type) {
  3169. VISIT(c, expr, handler->v.ExceptHandler.type);
  3170. ADDOP(c, loc, CHECK_EG_MATCH);
  3171. ADDOP_I(c, loc, COPY, 1);
  3172. ADDOP_JUMP(c, loc, POP_JUMP_IF_NONE, no_match);
  3173. }
  3174. NEW_JUMP_TARGET_LABEL(c, cleanup_end);
  3175. NEW_JUMP_TARGET_LABEL(c, cleanup_body);
  3176. if (handler->v.ExceptHandler.name) {
  3177. RETURN_IF_ERROR(
  3178. compiler_nameop(c, loc, handler->v.ExceptHandler.name, Store));
  3179. }
  3180. else {
  3181. ADDOP(c, loc, POP_TOP); // match
  3182. }
  3183. /*
  3184. try:
  3185. # body
  3186. except type as name:
  3187. try:
  3188. # body
  3189. finally:
  3190. name = None # in case body contains "del name"
  3191. del name
  3192. */
  3193. /* second try: */
  3194. ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup_end);
  3195. USE_LABEL(c, cleanup_body);
  3196. RETURN_IF_ERROR(
  3197. compiler_push_fblock(c, loc, HANDLER_CLEANUP, cleanup_body,
  3198. NO_LABEL, handler->v.ExceptHandler.name));
  3199. /* second # body */
  3200. VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
  3201. compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
  3202. /* name = None; del name; # artificial */
  3203. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3204. if (handler->v.ExceptHandler.name) {
  3205. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  3206. RETURN_IF_ERROR(
  3207. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
  3208. RETURN_IF_ERROR(
  3209. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
  3210. }
  3211. ADDOP_JUMP(c, NO_LOCATION, JUMP, except);
  3212. /* except: */
  3213. USE_LABEL(c, cleanup_end);
  3214. /* name = None; del name; # artificial */
  3215. if (handler->v.ExceptHandler.name) {
  3216. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  3217. RETURN_IF_ERROR(
  3218. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
  3219. RETURN_IF_ERROR(
  3220. compiler_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
  3221. }
  3222. /* add exception raised to the res list */
  3223. ADDOP_I(c, NO_LOCATION, LIST_APPEND, 3); // exc
  3224. ADDOP(c, NO_LOCATION, POP_TOP); // lasti
  3225. ADDOP_JUMP(c, NO_LOCATION, JUMP, except_with_error);
  3226. USE_LABEL(c, except);
  3227. ADDOP(c, NO_LOCATION, NOP); // to hold a propagated location info
  3228. ADDOP_JUMP(c, NO_LOCATION, JUMP, except_with_error);
  3229. USE_LABEL(c, no_match);
  3230. ADDOP(c, loc, POP_TOP); // match (None)
  3231. USE_LABEL(c, except_with_error);
  3232. if (i == n - 1) {
  3233. /* Add exc to the list (if not None it's the unhandled part of the EG) */
  3234. ADDOP_I(c, NO_LOCATION, LIST_APPEND, 1);
  3235. ADDOP_JUMP(c, NO_LOCATION, JUMP, reraise_star);
  3236. }
  3237. }
  3238. /* artificial */
  3239. compiler_pop_fblock(c, EXCEPTION_GROUP_HANDLER, NO_LABEL);
  3240. NEW_JUMP_TARGET_LABEL(c, reraise);
  3241. USE_LABEL(c, reraise_star);
  3242. ADDOP_I(c, NO_LOCATION, CALL_INTRINSIC_2, INTRINSIC_PREP_RERAISE_STAR);
  3243. ADDOP_I(c, NO_LOCATION, COPY, 1);
  3244. ADDOP_JUMP(c, NO_LOCATION, POP_JUMP_IF_NOT_NONE, reraise);
  3245. /* Nothing to reraise */
  3246. ADDOP(c, NO_LOCATION, POP_TOP);
  3247. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3248. ADDOP(c, NO_LOCATION, POP_EXCEPT);
  3249. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  3250. USE_LABEL(c, reraise);
  3251. ADDOP(c, NO_LOCATION, POP_BLOCK);
  3252. ADDOP_I(c, NO_LOCATION, SWAP, 2);
  3253. ADDOP(c, NO_LOCATION, POP_EXCEPT);
  3254. ADDOP_I(c, NO_LOCATION, RERAISE, 0);
  3255. USE_LABEL(c, cleanup);
  3256. POP_EXCEPT_AND_RERAISE(c, NO_LOCATION);
  3257. USE_LABEL(c, orelse);
  3258. VISIT_SEQ(c, stmt, s->v.TryStar.orelse);
  3259. USE_LABEL(c, end);
  3260. return SUCCESS;
  3261. }
  3262. static int
  3263. compiler_try(struct compiler *c, stmt_ty s) {
  3264. if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
  3265. return compiler_try_finally(c, s);
  3266. else
  3267. return compiler_try_except(c, s);
  3268. }
  3269. static int
  3270. compiler_try_star(struct compiler *c, stmt_ty s)
  3271. {
  3272. if (s->v.TryStar.finalbody && asdl_seq_LEN(s->v.TryStar.finalbody)) {
  3273. return compiler_try_star_finally(c, s);
  3274. }
  3275. else {
  3276. return compiler_try_star_except(c, s);
  3277. }
  3278. }
  3279. static int
  3280. compiler_import_as(struct compiler *c, location loc,
  3281. identifier name, identifier asname)
  3282. {
  3283. /* The IMPORT_NAME opcode was already generated. This function
  3284. merely needs to bind the result to a name.
  3285. If there is a dot in name, we need to split it and emit a
  3286. IMPORT_FROM for each name.
  3287. */
  3288. Py_ssize_t len = PyUnicode_GET_LENGTH(name);
  3289. Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
  3290. if (dot == -2) {
  3291. return ERROR;
  3292. }
  3293. if (dot != -1) {
  3294. /* Consume the base module name to get the first attribute */
  3295. while (1) {
  3296. Py_ssize_t pos = dot + 1;
  3297. PyObject *attr;
  3298. dot = PyUnicode_FindChar(name, '.', pos, len, 1);
  3299. if (dot == -2) {
  3300. return ERROR;
  3301. }
  3302. attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
  3303. if (!attr) {
  3304. return ERROR;
  3305. }
  3306. ADDOP_N(c, loc, IMPORT_FROM, attr, names);
  3307. if (dot == -1) {
  3308. break;
  3309. }
  3310. ADDOP_I(c, loc, SWAP, 2);
  3311. ADDOP(c, loc, POP_TOP);
  3312. }
  3313. RETURN_IF_ERROR(compiler_nameop(c, loc, asname, Store));
  3314. ADDOP(c, loc, POP_TOP);
  3315. return SUCCESS;
  3316. }
  3317. return compiler_nameop(c, loc, asname, Store);
  3318. }
  3319. static int
  3320. compiler_import(struct compiler *c, stmt_ty s)
  3321. {
  3322. location loc = LOC(s);
  3323. /* The Import node stores a module name like a.b.c as a single
  3324. string. This is convenient for all cases except
  3325. import a.b.c as d
  3326. where we need to parse that string to extract the individual
  3327. module names.
  3328. XXX Perhaps change the representation to make this case simpler?
  3329. */
  3330. Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
  3331. PyObject *zero = _PyLong_GetZero(); // borrowed reference
  3332. for (i = 0; i < n; i++) {
  3333. alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
  3334. int r;
  3335. ADDOP_LOAD_CONST(c, loc, zero);
  3336. ADDOP_LOAD_CONST(c, loc, Py_None);
  3337. ADDOP_NAME(c, loc, IMPORT_NAME, alias->name, names);
  3338. if (alias->asname) {
  3339. r = compiler_import_as(c, loc, alias->name, alias->asname);
  3340. RETURN_IF_ERROR(r);
  3341. }
  3342. else {
  3343. identifier tmp = alias->name;
  3344. Py_ssize_t dot = PyUnicode_FindChar(
  3345. alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
  3346. if (dot != -1) {
  3347. tmp = PyUnicode_Substring(alias->name, 0, dot);
  3348. if (tmp == NULL) {
  3349. return ERROR;
  3350. }
  3351. }
  3352. r = compiler_nameop(c, loc, tmp, Store);
  3353. if (dot != -1) {
  3354. Py_DECREF(tmp);
  3355. }
  3356. RETURN_IF_ERROR(r);
  3357. }
  3358. }
  3359. return SUCCESS;
  3360. }
  3361. static int
  3362. compiler_from_import(struct compiler *c, stmt_ty s)
  3363. {
  3364. Py_ssize_t n = asdl_seq_LEN(s->v.ImportFrom.names);
  3365. ADDOP_LOAD_CONST_NEW(c, LOC(s), PyLong_FromLong(s->v.ImportFrom.level));
  3366. PyObject *names = PyTuple_New(n);
  3367. if (!names) {
  3368. return ERROR;
  3369. }
  3370. /* build up the names */
  3371. for (Py_ssize_t i = 0; i < n; i++) {
  3372. alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
  3373. PyTuple_SET_ITEM(names, i, Py_NewRef(alias->name));
  3374. }
  3375. if (location_is_after(LOC(s), c->c_future.ff_location) &&
  3376. s->v.ImportFrom.module &&
  3377. _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__"))
  3378. {
  3379. Py_DECREF(names);
  3380. return compiler_error(c, LOC(s), "from __future__ imports must occur "
  3381. "at the beginning of the file");
  3382. }
  3383. ADDOP_LOAD_CONST_NEW(c, LOC(s), names);
  3384. if (s->v.ImportFrom.module) {
  3385. ADDOP_NAME(c, LOC(s), IMPORT_NAME, s->v.ImportFrom.module, names);
  3386. }
  3387. else {
  3388. _Py_DECLARE_STR(empty, "");
  3389. ADDOP_NAME(c, LOC(s), IMPORT_NAME, &_Py_STR(empty), names);
  3390. }
  3391. for (Py_ssize_t i = 0; i < n; i++) {
  3392. alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
  3393. identifier store_name;
  3394. if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
  3395. assert(n == 1);
  3396. ADDOP_I(c, LOC(s), CALL_INTRINSIC_1, INTRINSIC_IMPORT_STAR);
  3397. ADDOP(c, NO_LOCATION, POP_TOP);
  3398. return SUCCESS;
  3399. }
  3400. ADDOP_NAME(c, LOC(s), IMPORT_FROM, alias->name, names);
  3401. store_name = alias->name;
  3402. if (alias->asname) {
  3403. store_name = alias->asname;
  3404. }
  3405. RETURN_IF_ERROR(compiler_nameop(c, LOC(s), store_name, Store));
  3406. }
  3407. /* remove imported module */
  3408. ADDOP(c, LOC(s), POP_TOP);
  3409. return SUCCESS;
  3410. }
  3411. static int
  3412. compiler_assert(struct compiler *c, stmt_ty s)
  3413. {
  3414. /* Always emit a warning if the test is a non-zero length tuple */
  3415. if ((s->v.Assert.test->kind == Tuple_kind &&
  3416. asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) ||
  3417. (s->v.Assert.test->kind == Constant_kind &&
  3418. PyTuple_Check(s->v.Assert.test->v.Constant.value) &&
  3419. PyTuple_Size(s->v.Assert.test->v.Constant.value) > 0))
  3420. {
  3421. RETURN_IF_ERROR(
  3422. compiler_warn(c, LOC(s), "assertion is always true, "
  3423. "perhaps remove parentheses?"));
  3424. }
  3425. if (c->c_optimize) {
  3426. return SUCCESS;
  3427. }
  3428. NEW_JUMP_TARGET_LABEL(c, end);
  3429. RETURN_IF_ERROR(compiler_jump_if(c, LOC(s), s->v.Assert.test, end, 1));
  3430. ADDOP(c, LOC(s), LOAD_ASSERTION_ERROR);
  3431. if (s->v.Assert.msg) {
  3432. VISIT(c, expr, s->v.Assert.msg);
  3433. ADDOP_I(c, LOC(s), CALL, 0);
  3434. }
  3435. ADDOP_I(c, LOC(s->v.Assert.test), RAISE_VARARGS, 1);
  3436. USE_LABEL(c, end);
  3437. return SUCCESS;
  3438. }
  3439. static int
  3440. compiler_stmt_expr(struct compiler *c, location loc, expr_ty value)
  3441. {
  3442. if (c->c_interactive && c->c_nestlevel <= 1) {
  3443. VISIT(c, expr, value);
  3444. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_PRINT);
  3445. ADDOP(c, NO_LOCATION, POP_TOP);
  3446. return SUCCESS;
  3447. }
  3448. if (value->kind == Constant_kind) {
  3449. /* ignore constant statement */
  3450. ADDOP(c, loc, NOP);
  3451. return SUCCESS;
  3452. }
  3453. VISIT(c, expr, value);
  3454. ADDOP(c, NO_LOCATION, POP_TOP); /* artificial */
  3455. return SUCCESS;
  3456. }
  3457. static int
  3458. compiler_visit_stmt(struct compiler *c, stmt_ty s)
  3459. {
  3460. switch (s->kind) {
  3461. case FunctionDef_kind:
  3462. return compiler_function(c, s, 0);
  3463. case ClassDef_kind:
  3464. return compiler_class(c, s);
  3465. case TypeAlias_kind:
  3466. return compiler_typealias(c, s);
  3467. case Return_kind:
  3468. return compiler_return(c, s);
  3469. case Delete_kind:
  3470. VISIT_SEQ(c, expr, s->v.Delete.targets)
  3471. break;
  3472. case Assign_kind:
  3473. {
  3474. Py_ssize_t n = asdl_seq_LEN(s->v.Assign.targets);
  3475. VISIT(c, expr, s->v.Assign.value);
  3476. for (Py_ssize_t i = 0; i < n; i++) {
  3477. if (i < n - 1) {
  3478. ADDOP_I(c, LOC(s), COPY, 1);
  3479. }
  3480. VISIT(c, expr,
  3481. (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
  3482. }
  3483. break;
  3484. }
  3485. case AugAssign_kind:
  3486. return compiler_augassign(c, s);
  3487. case AnnAssign_kind:
  3488. return compiler_annassign(c, s);
  3489. case For_kind:
  3490. return compiler_for(c, s);
  3491. case While_kind:
  3492. return compiler_while(c, s);
  3493. case If_kind:
  3494. return compiler_if(c, s);
  3495. case Match_kind:
  3496. return compiler_match(c, s);
  3497. case Raise_kind:
  3498. {
  3499. Py_ssize_t n = 0;
  3500. if (s->v.Raise.exc) {
  3501. VISIT(c, expr, s->v.Raise.exc);
  3502. n++;
  3503. if (s->v.Raise.cause) {
  3504. VISIT(c, expr, s->v.Raise.cause);
  3505. n++;
  3506. }
  3507. }
  3508. ADDOP_I(c, LOC(s), RAISE_VARARGS, (int)n);
  3509. break;
  3510. }
  3511. case Try_kind:
  3512. return compiler_try(c, s);
  3513. case TryStar_kind:
  3514. return compiler_try_star(c, s);
  3515. case Assert_kind:
  3516. return compiler_assert(c, s);
  3517. case Import_kind:
  3518. return compiler_import(c, s);
  3519. case ImportFrom_kind:
  3520. return compiler_from_import(c, s);
  3521. case Global_kind:
  3522. case Nonlocal_kind:
  3523. break;
  3524. case Expr_kind:
  3525. {
  3526. return compiler_stmt_expr(c, LOC(s), s->v.Expr.value);
  3527. }
  3528. case Pass_kind:
  3529. {
  3530. ADDOP(c, LOC(s), NOP);
  3531. break;
  3532. }
  3533. case Break_kind:
  3534. {
  3535. return compiler_break(c, LOC(s));
  3536. }
  3537. case Continue_kind:
  3538. {
  3539. return compiler_continue(c, LOC(s));
  3540. }
  3541. case With_kind:
  3542. return compiler_with(c, s, 0);
  3543. case AsyncFunctionDef_kind:
  3544. return compiler_function(c, s, 1);
  3545. case AsyncWith_kind:
  3546. return compiler_async_with(c, s, 0);
  3547. case AsyncFor_kind:
  3548. return compiler_async_for(c, s);
  3549. }
  3550. return SUCCESS;
  3551. }
  3552. static int
  3553. unaryop(unaryop_ty op)
  3554. {
  3555. switch (op) {
  3556. case Invert:
  3557. return UNARY_INVERT;
  3558. case Not:
  3559. return UNARY_NOT;
  3560. case USub:
  3561. return UNARY_NEGATIVE;
  3562. default:
  3563. PyErr_Format(PyExc_SystemError,
  3564. "unary op %d should not be possible", op);
  3565. return 0;
  3566. }
  3567. }
  3568. static int
  3569. addop_binary(struct compiler *c, location loc, operator_ty binop,
  3570. bool inplace)
  3571. {
  3572. int oparg;
  3573. switch (binop) {
  3574. case Add:
  3575. oparg = inplace ? NB_INPLACE_ADD : NB_ADD;
  3576. break;
  3577. case Sub:
  3578. oparg = inplace ? NB_INPLACE_SUBTRACT : NB_SUBTRACT;
  3579. break;
  3580. case Mult:
  3581. oparg = inplace ? NB_INPLACE_MULTIPLY : NB_MULTIPLY;
  3582. break;
  3583. case MatMult:
  3584. oparg = inplace ? NB_INPLACE_MATRIX_MULTIPLY : NB_MATRIX_MULTIPLY;
  3585. break;
  3586. case Div:
  3587. oparg = inplace ? NB_INPLACE_TRUE_DIVIDE : NB_TRUE_DIVIDE;
  3588. break;
  3589. case Mod:
  3590. oparg = inplace ? NB_INPLACE_REMAINDER : NB_REMAINDER;
  3591. break;
  3592. case Pow:
  3593. oparg = inplace ? NB_INPLACE_POWER : NB_POWER;
  3594. break;
  3595. case LShift:
  3596. oparg = inplace ? NB_INPLACE_LSHIFT : NB_LSHIFT;
  3597. break;
  3598. case RShift:
  3599. oparg = inplace ? NB_INPLACE_RSHIFT : NB_RSHIFT;
  3600. break;
  3601. case BitOr:
  3602. oparg = inplace ? NB_INPLACE_OR : NB_OR;
  3603. break;
  3604. case BitXor:
  3605. oparg = inplace ? NB_INPLACE_XOR : NB_XOR;
  3606. break;
  3607. case BitAnd:
  3608. oparg = inplace ? NB_INPLACE_AND : NB_AND;
  3609. break;
  3610. case FloorDiv:
  3611. oparg = inplace ? NB_INPLACE_FLOOR_DIVIDE : NB_FLOOR_DIVIDE;
  3612. break;
  3613. default:
  3614. PyErr_Format(PyExc_SystemError, "%s op %d should not be possible",
  3615. inplace ? "inplace" : "binary", binop);
  3616. return ERROR;
  3617. }
  3618. ADDOP_I(c, loc, BINARY_OP, oparg);
  3619. return SUCCESS;
  3620. }
  3621. static int
  3622. addop_yield(struct compiler *c, location loc) {
  3623. if (c->u->u_ste->ste_generator && c->u->u_ste->ste_coroutine) {
  3624. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_ASYNC_GEN_WRAP);
  3625. }
  3626. ADDOP_I(c, loc, YIELD_VALUE, 0);
  3627. ADDOP_I(c, loc, RESUME, 1);
  3628. return SUCCESS;
  3629. }
  3630. static int
  3631. compiler_nameop(struct compiler *c, location loc,
  3632. identifier name, expr_context_ty ctx)
  3633. {
  3634. int op, scope;
  3635. Py_ssize_t arg;
  3636. enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
  3637. PyObject *dict = c->u->u_metadata.u_names;
  3638. PyObject *mangled;
  3639. assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
  3640. !_PyUnicode_EqualToASCIIString(name, "True") &&
  3641. !_PyUnicode_EqualToASCIIString(name, "False"));
  3642. if (forbidden_name(c, loc, name, ctx)) {
  3643. return ERROR;
  3644. }
  3645. mangled = _Py_MaybeMangle(c->u->u_private, c->u->u_ste, name);
  3646. if (!mangled) {
  3647. return ERROR;
  3648. }
  3649. op = 0;
  3650. optype = OP_NAME;
  3651. scope = _PyST_GetScope(c->u->u_ste, mangled);
  3652. switch (scope) {
  3653. case FREE:
  3654. dict = c->u->u_metadata.u_freevars;
  3655. optype = OP_DEREF;
  3656. break;
  3657. case CELL:
  3658. dict = c->u->u_metadata.u_cellvars;
  3659. optype = OP_DEREF;
  3660. break;
  3661. case LOCAL:
  3662. if (_PyST_IsFunctionLike(c->u->u_ste) ||
  3663. (PyDict_GetItem(c->u->u_metadata.u_fasthidden, mangled) == Py_True))
  3664. optype = OP_FAST;
  3665. break;
  3666. case GLOBAL_IMPLICIT:
  3667. if (_PyST_IsFunctionLike(c->u->u_ste))
  3668. optype = OP_GLOBAL;
  3669. break;
  3670. case GLOBAL_EXPLICIT:
  3671. optype = OP_GLOBAL;
  3672. break;
  3673. default:
  3674. /* scope can be 0 */
  3675. break;
  3676. }
  3677. /* XXX Leave assert here, but handle __doc__ and the like better */
  3678. assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
  3679. switch (optype) {
  3680. case OP_DEREF:
  3681. switch (ctx) {
  3682. case Load:
  3683. if (c->u->u_ste->ste_type == ClassBlock && !c->u->u_in_inlined_comp) {
  3684. op = LOAD_FROM_DICT_OR_DEREF;
  3685. // First load the locals
  3686. if (codegen_addop_noarg(INSTR_SEQUENCE(c), LOAD_LOCALS, loc) < 0) {
  3687. return ERROR;
  3688. }
  3689. }
  3690. else if (c->u->u_ste->ste_can_see_class_scope) {
  3691. op = LOAD_FROM_DICT_OR_DEREF;
  3692. // First load the classdict
  3693. if (compiler_addop_o(c->u, loc, LOAD_DEREF,
  3694. c->u->u_metadata.u_freevars, &_Py_ID(__classdict__)) < 0) {
  3695. return ERROR;
  3696. }
  3697. }
  3698. else {
  3699. op = LOAD_DEREF;
  3700. }
  3701. break;
  3702. case Store: op = STORE_DEREF; break;
  3703. case Del: op = DELETE_DEREF; break;
  3704. }
  3705. break;
  3706. case OP_FAST:
  3707. switch (ctx) {
  3708. case Load: op = LOAD_FAST; break;
  3709. case Store: op = STORE_FAST; break;
  3710. case Del: op = DELETE_FAST; break;
  3711. }
  3712. ADDOP_N(c, loc, op, mangled, varnames);
  3713. return SUCCESS;
  3714. case OP_GLOBAL:
  3715. switch (ctx) {
  3716. case Load:
  3717. if (c->u->u_ste->ste_can_see_class_scope && scope == GLOBAL_IMPLICIT) {
  3718. op = LOAD_FROM_DICT_OR_GLOBALS;
  3719. // First load the classdict
  3720. if (compiler_addop_o(c->u, loc, LOAD_DEREF,
  3721. c->u->u_metadata.u_freevars, &_Py_ID(__classdict__)) < 0) {
  3722. return ERROR;
  3723. }
  3724. } else {
  3725. op = LOAD_GLOBAL;
  3726. }
  3727. break;
  3728. case Store: op = STORE_GLOBAL; break;
  3729. case Del: op = DELETE_GLOBAL; break;
  3730. }
  3731. break;
  3732. case OP_NAME:
  3733. switch (ctx) {
  3734. case Load:
  3735. op = (c->u->u_ste->ste_type == ClassBlock
  3736. && c->u->u_in_inlined_comp)
  3737. ? LOAD_GLOBAL
  3738. : LOAD_NAME;
  3739. break;
  3740. case Store: op = STORE_NAME; break;
  3741. case Del: op = DELETE_NAME; break;
  3742. }
  3743. break;
  3744. }
  3745. assert(op);
  3746. arg = dict_add_o(dict, mangled);
  3747. Py_DECREF(mangled);
  3748. if (arg < 0) {
  3749. return ERROR;
  3750. }
  3751. if (op == LOAD_GLOBAL) {
  3752. arg <<= 1;
  3753. }
  3754. return codegen_addop_i(INSTR_SEQUENCE(c), op, arg, loc);
  3755. }
  3756. static int
  3757. compiler_boolop(struct compiler *c, expr_ty e)
  3758. {
  3759. int jumpi;
  3760. Py_ssize_t i, n;
  3761. asdl_expr_seq *s;
  3762. location loc = LOC(e);
  3763. assert(e->kind == BoolOp_kind);
  3764. if (e->v.BoolOp.op == And)
  3765. jumpi = POP_JUMP_IF_FALSE;
  3766. else
  3767. jumpi = POP_JUMP_IF_TRUE;
  3768. NEW_JUMP_TARGET_LABEL(c, end);
  3769. s = e->v.BoolOp.values;
  3770. n = asdl_seq_LEN(s) - 1;
  3771. assert(n >= 0);
  3772. for (i = 0; i < n; ++i) {
  3773. VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
  3774. ADDOP_I(c, loc, COPY, 1);
  3775. ADDOP_JUMP(c, loc, jumpi, end);
  3776. ADDOP(c, loc, POP_TOP);
  3777. }
  3778. VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
  3779. USE_LABEL(c, end);
  3780. return SUCCESS;
  3781. }
  3782. static int
  3783. starunpack_helper(struct compiler *c, location loc,
  3784. asdl_expr_seq *elts, int pushed,
  3785. int build, int add, int extend, int tuple)
  3786. {
  3787. Py_ssize_t n = asdl_seq_LEN(elts);
  3788. if (n > 2 && are_all_items_const(elts, 0, n)) {
  3789. PyObject *folded = PyTuple_New(n);
  3790. if (folded == NULL) {
  3791. return ERROR;
  3792. }
  3793. PyObject *val;
  3794. for (Py_ssize_t i = 0; i < n; i++) {
  3795. val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
  3796. PyTuple_SET_ITEM(folded, i, Py_NewRef(val));
  3797. }
  3798. if (tuple && !pushed) {
  3799. ADDOP_LOAD_CONST_NEW(c, loc, folded);
  3800. } else {
  3801. if (add == SET_ADD) {
  3802. Py_SETREF(folded, PyFrozenSet_New(folded));
  3803. if (folded == NULL) {
  3804. return ERROR;
  3805. }
  3806. }
  3807. ADDOP_I(c, loc, build, pushed);
  3808. ADDOP_LOAD_CONST_NEW(c, loc, folded);
  3809. ADDOP_I(c, loc, extend, 1);
  3810. if (tuple) {
  3811. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_LIST_TO_TUPLE);
  3812. }
  3813. }
  3814. return SUCCESS;
  3815. }
  3816. int big = n+pushed > STACK_USE_GUIDELINE;
  3817. int seen_star = 0;
  3818. for (Py_ssize_t i = 0; i < n; i++) {
  3819. expr_ty elt = asdl_seq_GET(elts, i);
  3820. if (elt->kind == Starred_kind) {
  3821. seen_star = 1;
  3822. break;
  3823. }
  3824. }
  3825. if (!seen_star && !big) {
  3826. for (Py_ssize_t i = 0; i < n; i++) {
  3827. expr_ty elt = asdl_seq_GET(elts, i);
  3828. VISIT(c, expr, elt);
  3829. }
  3830. if (tuple) {
  3831. ADDOP_I(c, loc, BUILD_TUPLE, n+pushed);
  3832. } else {
  3833. ADDOP_I(c, loc, build, n+pushed);
  3834. }
  3835. return SUCCESS;
  3836. }
  3837. int sequence_built = 0;
  3838. if (big) {
  3839. ADDOP_I(c, loc, build, pushed);
  3840. sequence_built = 1;
  3841. }
  3842. for (Py_ssize_t i = 0; i < n; i++) {
  3843. expr_ty elt = asdl_seq_GET(elts, i);
  3844. if (elt->kind == Starred_kind) {
  3845. if (sequence_built == 0) {
  3846. ADDOP_I(c, loc, build, i+pushed);
  3847. sequence_built = 1;
  3848. }
  3849. VISIT(c, expr, elt->v.Starred.value);
  3850. ADDOP_I(c, loc, extend, 1);
  3851. }
  3852. else {
  3853. VISIT(c, expr, elt);
  3854. if (sequence_built) {
  3855. ADDOP_I(c, loc, add, 1);
  3856. }
  3857. }
  3858. }
  3859. assert(sequence_built);
  3860. if (tuple) {
  3861. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_LIST_TO_TUPLE);
  3862. }
  3863. return SUCCESS;
  3864. }
  3865. static int
  3866. unpack_helper(struct compiler *c, location loc, asdl_expr_seq *elts)
  3867. {
  3868. Py_ssize_t n = asdl_seq_LEN(elts);
  3869. int seen_star = 0;
  3870. for (Py_ssize_t i = 0; i < n; i++) {
  3871. expr_ty elt = asdl_seq_GET(elts, i);
  3872. if (elt->kind == Starred_kind && !seen_star) {
  3873. if ((i >= (1 << 8)) ||
  3874. (n-i-1 >= (INT_MAX >> 8))) {
  3875. return compiler_error(c, loc,
  3876. "too many expressions in "
  3877. "star-unpacking assignment");
  3878. }
  3879. ADDOP_I(c, loc, UNPACK_EX, (i + ((n-i-1) << 8)));
  3880. seen_star = 1;
  3881. }
  3882. else if (elt->kind == Starred_kind) {
  3883. return compiler_error(c, loc,
  3884. "multiple starred expressions in assignment");
  3885. }
  3886. }
  3887. if (!seen_star) {
  3888. ADDOP_I(c, loc, UNPACK_SEQUENCE, n);
  3889. }
  3890. return SUCCESS;
  3891. }
  3892. static int
  3893. assignment_helper(struct compiler *c, location loc, asdl_expr_seq *elts)
  3894. {
  3895. Py_ssize_t n = asdl_seq_LEN(elts);
  3896. RETURN_IF_ERROR(unpack_helper(c, loc, elts));
  3897. for (Py_ssize_t i = 0; i < n; i++) {
  3898. expr_ty elt = asdl_seq_GET(elts, i);
  3899. VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
  3900. }
  3901. return SUCCESS;
  3902. }
  3903. static int
  3904. compiler_list(struct compiler *c, expr_ty e)
  3905. {
  3906. location loc = LOC(e);
  3907. asdl_expr_seq *elts = e->v.List.elts;
  3908. if (e->v.List.ctx == Store) {
  3909. return assignment_helper(c, loc, elts);
  3910. }
  3911. else if (e->v.List.ctx == Load) {
  3912. return starunpack_helper(c, loc, elts, 0,
  3913. BUILD_LIST, LIST_APPEND, LIST_EXTEND, 0);
  3914. }
  3915. else {
  3916. VISIT_SEQ(c, expr, elts);
  3917. }
  3918. return SUCCESS;
  3919. }
  3920. static int
  3921. compiler_tuple(struct compiler *c, expr_ty e)
  3922. {
  3923. location loc = LOC(e);
  3924. asdl_expr_seq *elts = e->v.Tuple.elts;
  3925. if (e->v.Tuple.ctx == Store) {
  3926. return assignment_helper(c, loc, elts);
  3927. }
  3928. else if (e->v.Tuple.ctx == Load) {
  3929. return starunpack_helper(c, loc, elts, 0,
  3930. BUILD_LIST, LIST_APPEND, LIST_EXTEND, 1);
  3931. }
  3932. else {
  3933. VISIT_SEQ(c, expr, elts);
  3934. }
  3935. return SUCCESS;
  3936. }
  3937. static int
  3938. compiler_set(struct compiler *c, expr_ty e)
  3939. {
  3940. location loc = LOC(e);
  3941. return starunpack_helper(c, loc, e->v.Set.elts, 0,
  3942. BUILD_SET, SET_ADD, SET_UPDATE, 0);
  3943. }
  3944. static bool
  3945. are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
  3946. {
  3947. for (Py_ssize_t i = begin; i < end; i++) {
  3948. expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
  3949. if (key == NULL || key->kind != Constant_kind) {
  3950. return false;
  3951. }
  3952. }
  3953. return true;
  3954. }
  3955. static int
  3956. compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
  3957. {
  3958. Py_ssize_t i, n = end - begin;
  3959. PyObject *keys, *key;
  3960. int big = n*2 > STACK_USE_GUIDELINE;
  3961. location loc = LOC(e);
  3962. if (n > 1 && !big && are_all_items_const(e->v.Dict.keys, begin, end)) {
  3963. for (i = begin; i < end; i++) {
  3964. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
  3965. }
  3966. keys = PyTuple_New(n);
  3967. if (keys == NULL) {
  3968. return SUCCESS;
  3969. }
  3970. for (i = begin; i < end; i++) {
  3971. key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
  3972. PyTuple_SET_ITEM(keys, i - begin, Py_NewRef(key));
  3973. }
  3974. ADDOP_LOAD_CONST_NEW(c, loc, keys);
  3975. ADDOP_I(c, loc, BUILD_CONST_KEY_MAP, n);
  3976. return SUCCESS;
  3977. }
  3978. if (big) {
  3979. ADDOP_I(c, loc, BUILD_MAP, 0);
  3980. }
  3981. for (i = begin; i < end; i++) {
  3982. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
  3983. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
  3984. if (big) {
  3985. ADDOP_I(c, loc, MAP_ADD, 1);
  3986. }
  3987. }
  3988. if (!big) {
  3989. ADDOP_I(c, loc, BUILD_MAP, n);
  3990. }
  3991. return SUCCESS;
  3992. }
  3993. static int
  3994. compiler_dict(struct compiler *c, expr_ty e)
  3995. {
  3996. location loc = LOC(e);
  3997. Py_ssize_t i, n, elements;
  3998. int have_dict;
  3999. int is_unpacking = 0;
  4000. n = asdl_seq_LEN(e->v.Dict.values);
  4001. have_dict = 0;
  4002. elements = 0;
  4003. for (i = 0; i < n; i++) {
  4004. is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
  4005. if (is_unpacking) {
  4006. if (elements) {
  4007. RETURN_IF_ERROR(compiler_subdict(c, e, i - elements, i));
  4008. if (have_dict) {
  4009. ADDOP_I(c, loc, DICT_UPDATE, 1);
  4010. }
  4011. have_dict = 1;
  4012. elements = 0;
  4013. }
  4014. if (have_dict == 0) {
  4015. ADDOP_I(c, loc, BUILD_MAP, 0);
  4016. have_dict = 1;
  4017. }
  4018. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
  4019. ADDOP_I(c, loc, DICT_UPDATE, 1);
  4020. }
  4021. else {
  4022. if (elements*2 > STACK_USE_GUIDELINE) {
  4023. RETURN_IF_ERROR(compiler_subdict(c, e, i - elements, i + 1));
  4024. if (have_dict) {
  4025. ADDOP_I(c, loc, DICT_UPDATE, 1);
  4026. }
  4027. have_dict = 1;
  4028. elements = 0;
  4029. }
  4030. else {
  4031. elements++;
  4032. }
  4033. }
  4034. }
  4035. if (elements) {
  4036. RETURN_IF_ERROR(compiler_subdict(c, e, n - elements, n));
  4037. if (have_dict) {
  4038. ADDOP_I(c, loc, DICT_UPDATE, 1);
  4039. }
  4040. have_dict = 1;
  4041. }
  4042. if (!have_dict) {
  4043. ADDOP_I(c, loc, BUILD_MAP, 0);
  4044. }
  4045. return SUCCESS;
  4046. }
  4047. static int
  4048. compiler_compare(struct compiler *c, expr_ty e)
  4049. {
  4050. location loc = LOC(e);
  4051. Py_ssize_t i, n;
  4052. RETURN_IF_ERROR(check_compare(c, e));
  4053. VISIT(c, expr, e->v.Compare.left);
  4054. assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
  4055. n = asdl_seq_LEN(e->v.Compare.ops) - 1;
  4056. if (n == 0) {
  4057. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
  4058. ADDOP_COMPARE(c, loc, asdl_seq_GET(e->v.Compare.ops, 0));
  4059. }
  4060. else {
  4061. NEW_JUMP_TARGET_LABEL(c, cleanup);
  4062. for (i = 0; i < n; i++) {
  4063. VISIT(c, expr,
  4064. (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
  4065. ADDOP_I(c, loc, SWAP, 2);
  4066. ADDOP_I(c, loc, COPY, 2);
  4067. ADDOP_COMPARE(c, loc, asdl_seq_GET(e->v.Compare.ops, i));
  4068. ADDOP_I(c, loc, COPY, 1);
  4069. ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, cleanup);
  4070. ADDOP(c, loc, POP_TOP);
  4071. }
  4072. VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
  4073. ADDOP_COMPARE(c, loc, asdl_seq_GET(e->v.Compare.ops, n));
  4074. NEW_JUMP_TARGET_LABEL(c, end);
  4075. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  4076. USE_LABEL(c, cleanup);
  4077. ADDOP_I(c, loc, SWAP, 2);
  4078. ADDOP(c, loc, POP_TOP);
  4079. USE_LABEL(c, end);
  4080. }
  4081. return SUCCESS;
  4082. }
  4083. static PyTypeObject *
  4084. infer_type(expr_ty e)
  4085. {
  4086. switch (e->kind) {
  4087. case Tuple_kind:
  4088. return &PyTuple_Type;
  4089. case List_kind:
  4090. case ListComp_kind:
  4091. return &PyList_Type;
  4092. case Dict_kind:
  4093. case DictComp_kind:
  4094. return &PyDict_Type;
  4095. case Set_kind:
  4096. case SetComp_kind:
  4097. return &PySet_Type;
  4098. case GeneratorExp_kind:
  4099. return &PyGen_Type;
  4100. case Lambda_kind:
  4101. return &PyFunction_Type;
  4102. case JoinedStr_kind:
  4103. case FormattedValue_kind:
  4104. return &PyUnicode_Type;
  4105. case Constant_kind:
  4106. return Py_TYPE(e->v.Constant.value);
  4107. default:
  4108. return NULL;
  4109. }
  4110. }
  4111. static int
  4112. check_caller(struct compiler *c, expr_ty e)
  4113. {
  4114. switch (e->kind) {
  4115. case Constant_kind:
  4116. case Tuple_kind:
  4117. case List_kind:
  4118. case ListComp_kind:
  4119. case Dict_kind:
  4120. case DictComp_kind:
  4121. case Set_kind:
  4122. case SetComp_kind:
  4123. case GeneratorExp_kind:
  4124. case JoinedStr_kind:
  4125. case FormattedValue_kind: {
  4126. location loc = LOC(e);
  4127. return compiler_warn(c, loc, "'%.200s' object is not callable; "
  4128. "perhaps you missed a comma?",
  4129. infer_type(e)->tp_name);
  4130. }
  4131. default:
  4132. return SUCCESS;
  4133. }
  4134. }
  4135. static int
  4136. check_subscripter(struct compiler *c, expr_ty e)
  4137. {
  4138. PyObject *v;
  4139. switch (e->kind) {
  4140. case Constant_kind:
  4141. v = e->v.Constant.value;
  4142. if (!(v == Py_None || v == Py_Ellipsis ||
  4143. PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
  4144. PyAnySet_Check(v)))
  4145. {
  4146. return SUCCESS;
  4147. }
  4148. /* fall through */
  4149. case Set_kind:
  4150. case SetComp_kind:
  4151. case GeneratorExp_kind:
  4152. case Lambda_kind: {
  4153. location loc = LOC(e);
  4154. return compiler_warn(c, loc, "'%.200s' object is not subscriptable; "
  4155. "perhaps you missed a comma?",
  4156. infer_type(e)->tp_name);
  4157. }
  4158. default:
  4159. return SUCCESS;
  4160. }
  4161. }
  4162. static int
  4163. check_index(struct compiler *c, expr_ty e, expr_ty s)
  4164. {
  4165. PyObject *v;
  4166. PyTypeObject *index_type = infer_type(s);
  4167. if (index_type == NULL
  4168. || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
  4169. || index_type == &PySlice_Type) {
  4170. return SUCCESS;
  4171. }
  4172. switch (e->kind) {
  4173. case Constant_kind:
  4174. v = e->v.Constant.value;
  4175. if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
  4176. return SUCCESS;
  4177. }
  4178. /* fall through */
  4179. case Tuple_kind:
  4180. case List_kind:
  4181. case ListComp_kind:
  4182. case JoinedStr_kind:
  4183. case FormattedValue_kind: {
  4184. location loc = LOC(e);
  4185. return compiler_warn(c, loc, "%.200s indices must be integers "
  4186. "or slices, not %.200s; "
  4187. "perhaps you missed a comma?",
  4188. infer_type(e)->tp_name,
  4189. index_type->tp_name);
  4190. }
  4191. default:
  4192. return SUCCESS;
  4193. }
  4194. }
  4195. static int
  4196. is_import_originated(struct compiler *c, expr_ty e)
  4197. {
  4198. /* Check whether the global scope has an import named
  4199. e, if it is a Name object. For not traversing all the
  4200. scope stack every time this function is called, it will
  4201. only check the global scope to determine whether something
  4202. is imported or not. */
  4203. if (e->kind != Name_kind) {
  4204. return 0;
  4205. }
  4206. long flags = _PyST_GetSymbol(c->c_st->st_top, e->v.Name.id);
  4207. return flags & DEF_IMPORT;
  4208. }
  4209. static int
  4210. can_optimize_super_call(struct compiler *c, expr_ty attr)
  4211. {
  4212. expr_ty e = attr->v.Attribute.value;
  4213. if (e->kind != Call_kind ||
  4214. e->v.Call.func->kind != Name_kind ||
  4215. !_PyUnicode_EqualToASCIIString(e->v.Call.func->v.Name.id, "super") ||
  4216. _PyUnicode_EqualToASCIIString(attr->v.Attribute.attr, "__class__") ||
  4217. asdl_seq_LEN(e->v.Call.keywords) != 0) {
  4218. return 0;
  4219. }
  4220. Py_ssize_t num_args = asdl_seq_LEN(e->v.Call.args);
  4221. PyObject *super_name = e->v.Call.func->v.Name.id;
  4222. // detect statically-visible shadowing of 'super' name
  4223. int scope = _PyST_GetScope(c->u->u_ste, super_name);
  4224. if (scope != GLOBAL_IMPLICIT) {
  4225. return 0;
  4226. }
  4227. scope = _PyST_GetScope(c->c_st->st_top, super_name);
  4228. if (scope != 0) {
  4229. return 0;
  4230. }
  4231. if (num_args == 2) {
  4232. for (Py_ssize_t i = 0; i < num_args; i++) {
  4233. expr_ty elt = asdl_seq_GET(e->v.Call.args, i);
  4234. if (elt->kind == Starred_kind) {
  4235. return 0;
  4236. }
  4237. }
  4238. // exactly two non-starred args; we can just load
  4239. // the provided args
  4240. return 1;
  4241. }
  4242. if (num_args != 0) {
  4243. return 0;
  4244. }
  4245. // we need the following for zero-arg super():
  4246. // enclosing function should have at least one argument
  4247. if (c->u->u_metadata.u_argcount == 0 &&
  4248. c->u->u_metadata.u_posonlyargcount == 0) {
  4249. return 0;
  4250. }
  4251. // __class__ cell should be available
  4252. if (get_ref_type(c, &_Py_ID(__class__)) == FREE) {
  4253. return 1;
  4254. }
  4255. return 0;
  4256. }
  4257. static int
  4258. load_args_for_super(struct compiler *c, expr_ty e) {
  4259. location loc = LOC(e);
  4260. // load super() global
  4261. PyObject *super_name = e->v.Call.func->v.Name.id;
  4262. RETURN_IF_ERROR(compiler_nameop(c, LOC(e->v.Call.func), super_name, Load));
  4263. if (asdl_seq_LEN(e->v.Call.args) == 2) {
  4264. VISIT(c, expr, asdl_seq_GET(e->v.Call.args, 0));
  4265. VISIT(c, expr, asdl_seq_GET(e->v.Call.args, 1));
  4266. return SUCCESS;
  4267. }
  4268. // load __class__ cell
  4269. PyObject *name = &_Py_ID(__class__);
  4270. assert(get_ref_type(c, name) == FREE);
  4271. RETURN_IF_ERROR(compiler_nameop(c, loc, name, Load));
  4272. // load self (first argument)
  4273. Py_ssize_t i = 0;
  4274. PyObject *key, *value;
  4275. if (!PyDict_Next(c->u->u_metadata.u_varnames, &i, &key, &value)) {
  4276. return ERROR;
  4277. }
  4278. RETURN_IF_ERROR(compiler_nameop(c, loc, key, Load));
  4279. return SUCCESS;
  4280. }
  4281. // If an attribute access spans multiple lines, update the current start
  4282. // location to point to the attribute name.
  4283. static location
  4284. update_start_location_to_match_attr(struct compiler *c, location loc,
  4285. expr_ty attr)
  4286. {
  4287. assert(attr->kind == Attribute_kind);
  4288. if (loc.lineno != attr->end_lineno) {
  4289. loc.lineno = attr->end_lineno;
  4290. int len = (int)PyUnicode_GET_LENGTH(attr->v.Attribute.attr);
  4291. if (len <= attr->end_col_offset) {
  4292. loc.col_offset = attr->end_col_offset - len;
  4293. }
  4294. else {
  4295. // GH-94694: Somebody's compiling weird ASTs. Just drop the columns:
  4296. loc.col_offset = -1;
  4297. loc.end_col_offset = -1;
  4298. }
  4299. // Make sure the end position still follows the start position, even for
  4300. // weird ASTs:
  4301. loc.end_lineno = Py_MAX(loc.lineno, loc.end_lineno);
  4302. if (loc.lineno == loc.end_lineno) {
  4303. loc.end_col_offset = Py_MAX(loc.col_offset, loc.end_col_offset);
  4304. }
  4305. }
  4306. return loc;
  4307. }
  4308. // Return 1 if the method call was optimized, 0 if not, and -1 on error.
  4309. static int
  4310. maybe_optimize_method_call(struct compiler *c, expr_ty e)
  4311. {
  4312. Py_ssize_t argsl, i, kwdsl;
  4313. expr_ty meth = e->v.Call.func;
  4314. asdl_expr_seq *args = e->v.Call.args;
  4315. asdl_keyword_seq *kwds = e->v.Call.keywords;
  4316. /* Check that the call node is an attribute access */
  4317. if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load) {
  4318. return 0;
  4319. }
  4320. /* Check that the base object is not something that is imported */
  4321. if (is_import_originated(c, meth->v.Attribute.value)) {
  4322. return 0;
  4323. }
  4324. /* Check that there aren't too many arguments */
  4325. argsl = asdl_seq_LEN(args);
  4326. kwdsl = asdl_seq_LEN(kwds);
  4327. if (argsl + kwdsl + (kwdsl != 0) >= STACK_USE_GUIDELINE) {
  4328. return 0;
  4329. }
  4330. /* Check that there are no *varargs types of arguments. */
  4331. for (i = 0; i < argsl; i++) {
  4332. expr_ty elt = asdl_seq_GET(args, i);
  4333. if (elt->kind == Starred_kind) {
  4334. return 0;
  4335. }
  4336. }
  4337. for (i = 0; i < kwdsl; i++) {
  4338. keyword_ty kw = asdl_seq_GET(kwds, i);
  4339. if (kw->arg == NULL) {
  4340. return 0;
  4341. }
  4342. }
  4343. /* Alright, we can optimize the code. */
  4344. location loc = LOC(meth);
  4345. if (can_optimize_super_call(c, meth)) {
  4346. RETURN_IF_ERROR(load_args_for_super(c, meth->v.Attribute.value));
  4347. int opcode = asdl_seq_LEN(meth->v.Attribute.value->v.Call.args) ?
  4348. LOAD_SUPER_METHOD : LOAD_ZERO_SUPER_METHOD;
  4349. ADDOP_NAME(c, loc, opcode, meth->v.Attribute.attr, names);
  4350. loc = update_start_location_to_match_attr(c, loc, meth);
  4351. ADDOP(c, loc, NOP);
  4352. } else {
  4353. VISIT(c, expr, meth->v.Attribute.value);
  4354. loc = update_start_location_to_match_attr(c, loc, meth);
  4355. ADDOP_NAME(c, loc, LOAD_METHOD, meth->v.Attribute.attr, names);
  4356. }
  4357. VISIT_SEQ(c, expr, e->v.Call.args);
  4358. if (kwdsl) {
  4359. VISIT_SEQ(c, keyword, kwds);
  4360. RETURN_IF_ERROR(
  4361. compiler_call_simple_kw_helper(c, loc, kwds, kwdsl));
  4362. }
  4363. loc = update_start_location_to_match_attr(c, LOC(e), meth);
  4364. ADDOP_I(c, loc, CALL, argsl + kwdsl);
  4365. return 1;
  4366. }
  4367. static int
  4368. validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
  4369. {
  4370. Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
  4371. for (Py_ssize_t i = 0; i < nkeywords; i++) {
  4372. keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
  4373. if (key->arg == NULL) {
  4374. continue;
  4375. }
  4376. location loc = LOC(key);
  4377. if (forbidden_name(c, loc, key->arg, Store)) {
  4378. return ERROR;
  4379. }
  4380. for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
  4381. keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
  4382. if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
  4383. compiler_error(c, LOC(other), "keyword argument repeated: %U", key->arg);
  4384. return ERROR;
  4385. }
  4386. }
  4387. }
  4388. return SUCCESS;
  4389. }
  4390. static int
  4391. compiler_call(struct compiler *c, expr_ty e)
  4392. {
  4393. RETURN_IF_ERROR(validate_keywords(c, e->v.Call.keywords));
  4394. int ret = maybe_optimize_method_call(c, e);
  4395. if (ret < 0) {
  4396. return ERROR;
  4397. }
  4398. if (ret == 1) {
  4399. return SUCCESS;
  4400. }
  4401. RETURN_IF_ERROR(check_caller(c, e->v.Call.func));
  4402. location loc = LOC(e->v.Call.func);
  4403. ADDOP(c, loc, PUSH_NULL);
  4404. VISIT(c, expr, e->v.Call.func);
  4405. loc = LOC(e);
  4406. return compiler_call_helper(c, loc, 0,
  4407. e->v.Call.args,
  4408. e->v.Call.keywords);
  4409. }
  4410. static int
  4411. compiler_joined_str(struct compiler *c, expr_ty e)
  4412. {
  4413. location loc = LOC(e);
  4414. Py_ssize_t value_count = asdl_seq_LEN(e->v.JoinedStr.values);
  4415. if (value_count > STACK_USE_GUIDELINE) {
  4416. _Py_DECLARE_STR(empty, "");
  4417. ADDOP_LOAD_CONST_NEW(c, loc, Py_NewRef(&_Py_STR(empty)));
  4418. ADDOP_NAME(c, loc, LOAD_METHOD, &_Py_ID(join), names);
  4419. ADDOP_I(c, loc, BUILD_LIST, 0);
  4420. for (Py_ssize_t i = 0; i < asdl_seq_LEN(e->v.JoinedStr.values); i++) {
  4421. VISIT(c, expr, asdl_seq_GET(e->v.JoinedStr.values, i));
  4422. ADDOP_I(c, loc, LIST_APPEND, 1);
  4423. }
  4424. ADDOP_I(c, loc, CALL, 1);
  4425. }
  4426. else {
  4427. VISIT_SEQ(c, expr, e->v.JoinedStr.values);
  4428. if (asdl_seq_LEN(e->v.JoinedStr.values) != 1) {
  4429. ADDOP_I(c, loc, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
  4430. }
  4431. }
  4432. return SUCCESS;
  4433. }
  4434. /* Used to implement f-strings. Format a single value. */
  4435. static int
  4436. compiler_formatted_value(struct compiler *c, expr_ty e)
  4437. {
  4438. /* Our oparg encodes 2 pieces of information: the conversion
  4439. character, and whether or not a format_spec was provided.
  4440. Convert the conversion char to 3 bits:
  4441. : 000 0x0 FVC_NONE The default if nothing specified.
  4442. !s : 001 0x1 FVC_STR
  4443. !r : 010 0x2 FVC_REPR
  4444. !a : 011 0x3 FVC_ASCII
  4445. next bit is whether or not we have a format spec:
  4446. yes : 100 0x4
  4447. no : 000 0x0
  4448. */
  4449. int conversion = e->v.FormattedValue.conversion;
  4450. int oparg;
  4451. /* The expression to be formatted. */
  4452. VISIT(c, expr, e->v.FormattedValue.value);
  4453. switch (conversion) {
  4454. case 's': oparg = FVC_STR; break;
  4455. case 'r': oparg = FVC_REPR; break;
  4456. case 'a': oparg = FVC_ASCII; break;
  4457. case -1: oparg = FVC_NONE; break;
  4458. default:
  4459. PyErr_Format(PyExc_SystemError,
  4460. "Unrecognized conversion character %d", conversion);
  4461. return ERROR;
  4462. }
  4463. if (e->v.FormattedValue.format_spec) {
  4464. /* Evaluate the format spec, and update our opcode arg. */
  4465. VISIT(c, expr, e->v.FormattedValue.format_spec);
  4466. oparg |= FVS_HAVE_SPEC;
  4467. }
  4468. /* And push our opcode and oparg */
  4469. location loc = LOC(e);
  4470. ADDOP_I(c, loc, FORMAT_VALUE, oparg);
  4471. return SUCCESS;
  4472. }
  4473. static int
  4474. compiler_subkwargs(struct compiler *c, location loc,
  4475. asdl_keyword_seq *keywords,
  4476. Py_ssize_t begin, Py_ssize_t end)
  4477. {
  4478. Py_ssize_t i, n = end - begin;
  4479. keyword_ty kw;
  4480. PyObject *keys, *key;
  4481. assert(n > 0);
  4482. int big = n*2 > STACK_USE_GUIDELINE;
  4483. if (n > 1 && !big) {
  4484. for (i = begin; i < end; i++) {
  4485. kw = asdl_seq_GET(keywords, i);
  4486. VISIT(c, expr, kw->value);
  4487. }
  4488. keys = PyTuple_New(n);
  4489. if (keys == NULL) {
  4490. return ERROR;
  4491. }
  4492. for (i = begin; i < end; i++) {
  4493. key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
  4494. PyTuple_SET_ITEM(keys, i - begin, Py_NewRef(key));
  4495. }
  4496. ADDOP_LOAD_CONST_NEW(c, loc, keys);
  4497. ADDOP_I(c, loc, BUILD_CONST_KEY_MAP, n);
  4498. return SUCCESS;
  4499. }
  4500. if (big) {
  4501. ADDOP_I(c, NO_LOCATION, BUILD_MAP, 0);
  4502. }
  4503. for (i = begin; i < end; i++) {
  4504. kw = asdl_seq_GET(keywords, i);
  4505. ADDOP_LOAD_CONST(c, loc, kw->arg);
  4506. VISIT(c, expr, kw->value);
  4507. if (big) {
  4508. ADDOP_I(c, NO_LOCATION, MAP_ADD, 1);
  4509. }
  4510. }
  4511. if (!big) {
  4512. ADDOP_I(c, loc, BUILD_MAP, n);
  4513. }
  4514. return SUCCESS;
  4515. }
  4516. /* Used by compiler_call_helper and maybe_optimize_method_call to emit
  4517. * KW_NAMES before CALL.
  4518. */
  4519. static int
  4520. compiler_call_simple_kw_helper(struct compiler *c, location loc,
  4521. asdl_keyword_seq *keywords, Py_ssize_t nkwelts)
  4522. {
  4523. PyObject *names;
  4524. names = PyTuple_New(nkwelts);
  4525. if (names == NULL) {
  4526. return ERROR;
  4527. }
  4528. for (int i = 0; i < nkwelts; i++) {
  4529. keyword_ty kw = asdl_seq_GET(keywords, i);
  4530. PyTuple_SET_ITEM(names, i, Py_NewRef(kw->arg));
  4531. }
  4532. Py_ssize_t arg = compiler_add_const(c->c_const_cache, c->u, names);
  4533. if (arg < 0) {
  4534. return ERROR;
  4535. }
  4536. Py_DECREF(names);
  4537. ADDOP_I(c, loc, KW_NAMES, arg);
  4538. return SUCCESS;
  4539. }
  4540. /* shared code between compiler_call and compiler_class */
  4541. static int
  4542. compiler_call_helper(struct compiler *c, location loc,
  4543. int n, /* Args already pushed */
  4544. asdl_expr_seq *args,
  4545. asdl_keyword_seq *keywords)
  4546. {
  4547. Py_ssize_t i, nseen, nelts, nkwelts;
  4548. RETURN_IF_ERROR(validate_keywords(c, keywords));
  4549. nelts = asdl_seq_LEN(args);
  4550. nkwelts = asdl_seq_LEN(keywords);
  4551. if (nelts + nkwelts*2 > STACK_USE_GUIDELINE) {
  4552. goto ex_call;
  4553. }
  4554. for (i = 0; i < nelts; i++) {
  4555. expr_ty elt = asdl_seq_GET(args, i);
  4556. if (elt->kind == Starred_kind) {
  4557. goto ex_call;
  4558. }
  4559. }
  4560. for (i = 0; i < nkwelts; i++) {
  4561. keyword_ty kw = asdl_seq_GET(keywords, i);
  4562. if (kw->arg == NULL) {
  4563. goto ex_call;
  4564. }
  4565. }
  4566. /* No * or ** args, so can use faster calling sequence */
  4567. for (i = 0; i < nelts; i++) {
  4568. expr_ty elt = asdl_seq_GET(args, i);
  4569. assert(elt->kind != Starred_kind);
  4570. VISIT(c, expr, elt);
  4571. }
  4572. if (nkwelts) {
  4573. VISIT_SEQ(c, keyword, keywords);
  4574. RETURN_IF_ERROR(
  4575. compiler_call_simple_kw_helper(c, loc, keywords, nkwelts));
  4576. }
  4577. ADDOP_I(c, loc, CALL, n + nelts + nkwelts);
  4578. return SUCCESS;
  4579. ex_call:
  4580. /* Do positional arguments. */
  4581. if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
  4582. VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
  4583. }
  4584. else {
  4585. RETURN_IF_ERROR(starunpack_helper(c, loc, args, n, BUILD_LIST,
  4586. LIST_APPEND, LIST_EXTEND, 1));
  4587. }
  4588. /* Then keyword arguments */
  4589. if (nkwelts) {
  4590. /* Has a new dict been pushed */
  4591. int have_dict = 0;
  4592. nseen = 0; /* the number of keyword arguments on the stack following */
  4593. for (i = 0; i < nkwelts; i++) {
  4594. keyword_ty kw = asdl_seq_GET(keywords, i);
  4595. if (kw->arg == NULL) {
  4596. /* A keyword argument unpacking. */
  4597. if (nseen) {
  4598. RETURN_IF_ERROR(compiler_subkwargs(c, loc, keywords, i - nseen, i));
  4599. if (have_dict) {
  4600. ADDOP_I(c, loc, DICT_MERGE, 1);
  4601. }
  4602. have_dict = 1;
  4603. nseen = 0;
  4604. }
  4605. if (!have_dict) {
  4606. ADDOP_I(c, loc, BUILD_MAP, 0);
  4607. have_dict = 1;
  4608. }
  4609. VISIT(c, expr, kw->value);
  4610. ADDOP_I(c, loc, DICT_MERGE, 1);
  4611. }
  4612. else {
  4613. nseen++;
  4614. }
  4615. }
  4616. if (nseen) {
  4617. /* Pack up any trailing keyword arguments. */
  4618. RETURN_IF_ERROR(compiler_subkwargs(c, loc, keywords, nkwelts - nseen, nkwelts));
  4619. if (have_dict) {
  4620. ADDOP_I(c, loc, DICT_MERGE, 1);
  4621. }
  4622. have_dict = 1;
  4623. }
  4624. assert(have_dict);
  4625. }
  4626. ADDOP_I(c, loc, CALL_FUNCTION_EX, nkwelts > 0);
  4627. return SUCCESS;
  4628. }
  4629. /* List and set comprehensions and generator expressions work by creating a
  4630. nested function to perform the actual iteration. This means that the
  4631. iteration variables don't leak into the current scope.
  4632. The defined function is called immediately following its definition, with the
  4633. result of that call being the result of the expression.
  4634. The LC/SC version returns the populated container, while the GE version is
  4635. flagged in symtable.c as a generator, so it returns the generator object
  4636. when the function is called.
  4637. Possible cleanups:
  4638. - iterate over the generator sequence instead of using recursion
  4639. */
  4640. static int
  4641. compiler_comprehension_generator(struct compiler *c, location loc,
  4642. asdl_comprehension_seq *generators, int gen_index,
  4643. int depth,
  4644. expr_ty elt, expr_ty val, int type,
  4645. int iter_on_stack)
  4646. {
  4647. comprehension_ty gen;
  4648. gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
  4649. if (gen->is_async) {
  4650. return compiler_async_comprehension_generator(
  4651. c, loc, generators, gen_index, depth, elt, val, type,
  4652. iter_on_stack);
  4653. } else {
  4654. return compiler_sync_comprehension_generator(
  4655. c, loc, generators, gen_index, depth, elt, val, type,
  4656. iter_on_stack);
  4657. }
  4658. }
  4659. static int
  4660. compiler_sync_comprehension_generator(struct compiler *c, location loc,
  4661. asdl_comprehension_seq *generators,
  4662. int gen_index, int depth,
  4663. expr_ty elt, expr_ty val, int type,
  4664. int iter_on_stack)
  4665. {
  4666. /* generate code for the iterator, then each of the ifs,
  4667. and then write to the element */
  4668. NEW_JUMP_TARGET_LABEL(c, start);
  4669. NEW_JUMP_TARGET_LABEL(c, if_cleanup);
  4670. NEW_JUMP_TARGET_LABEL(c, anchor);
  4671. comprehension_ty gen = (comprehension_ty)asdl_seq_GET(generators,
  4672. gen_index);
  4673. if (!iter_on_stack) {
  4674. if (gen_index == 0) {
  4675. /* Receive outermost iter as an implicit argument */
  4676. c->u->u_metadata.u_argcount = 1;
  4677. ADDOP_I(c, loc, LOAD_FAST, 0);
  4678. }
  4679. else {
  4680. /* Sub-iter - calculate on the fly */
  4681. /* Fast path for the temporary variable assignment idiom:
  4682. for y in [f(x)]
  4683. */
  4684. asdl_expr_seq *elts;
  4685. switch (gen->iter->kind) {
  4686. case List_kind:
  4687. elts = gen->iter->v.List.elts;
  4688. break;
  4689. case Tuple_kind:
  4690. elts = gen->iter->v.Tuple.elts;
  4691. break;
  4692. default:
  4693. elts = NULL;
  4694. }
  4695. if (asdl_seq_LEN(elts) == 1) {
  4696. expr_ty elt = asdl_seq_GET(elts, 0);
  4697. if (elt->kind != Starred_kind) {
  4698. VISIT(c, expr, elt);
  4699. start = NO_LABEL;
  4700. }
  4701. }
  4702. if (IS_LABEL(start)) {
  4703. VISIT(c, expr, gen->iter);
  4704. ADDOP(c, loc, GET_ITER);
  4705. }
  4706. }
  4707. }
  4708. if (IS_LABEL(start)) {
  4709. depth++;
  4710. USE_LABEL(c, start);
  4711. ADDOP_JUMP(c, loc, FOR_ITER, anchor);
  4712. }
  4713. VISIT(c, expr, gen->target);
  4714. /* XXX this needs to be cleaned up...a lot! */
  4715. Py_ssize_t n = asdl_seq_LEN(gen->ifs);
  4716. for (Py_ssize_t i = 0; i < n; i++) {
  4717. expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
  4718. RETURN_IF_ERROR(compiler_jump_if(c, loc, e, if_cleanup, 0));
  4719. }
  4720. if (++gen_index < asdl_seq_LEN(generators)) {
  4721. RETURN_IF_ERROR(
  4722. compiler_comprehension_generator(c, loc,
  4723. generators, gen_index, depth,
  4724. elt, val, type, 0));
  4725. }
  4726. location elt_loc = LOC(elt);
  4727. /* only append after the last for generator */
  4728. if (gen_index >= asdl_seq_LEN(generators)) {
  4729. /* comprehension specific code */
  4730. switch (type) {
  4731. case COMP_GENEXP:
  4732. VISIT(c, expr, elt);
  4733. ADDOP_YIELD(c, elt_loc);
  4734. ADDOP(c, elt_loc, POP_TOP);
  4735. break;
  4736. case COMP_LISTCOMP:
  4737. VISIT(c, expr, elt);
  4738. ADDOP_I(c, elt_loc, LIST_APPEND, depth + 1);
  4739. break;
  4740. case COMP_SETCOMP:
  4741. VISIT(c, expr, elt);
  4742. ADDOP_I(c, elt_loc, SET_ADD, depth + 1);
  4743. break;
  4744. case COMP_DICTCOMP:
  4745. /* With '{k: v}', k is evaluated before v, so we do
  4746. the same. */
  4747. VISIT(c, expr, elt);
  4748. VISIT(c, expr, val);
  4749. elt_loc = LOCATION(elt->lineno,
  4750. val->end_lineno,
  4751. elt->col_offset,
  4752. val->end_col_offset);
  4753. ADDOP_I(c, elt_loc, MAP_ADD, depth + 1);
  4754. break;
  4755. default:
  4756. return ERROR;
  4757. }
  4758. }
  4759. USE_LABEL(c, if_cleanup);
  4760. if (IS_LABEL(start)) {
  4761. ADDOP_JUMP(c, elt_loc, JUMP, start);
  4762. USE_LABEL(c, anchor);
  4763. ADDOP(c, NO_LOCATION, END_FOR);
  4764. }
  4765. return SUCCESS;
  4766. }
  4767. static int
  4768. compiler_async_comprehension_generator(struct compiler *c, location loc,
  4769. asdl_comprehension_seq *generators,
  4770. int gen_index, int depth,
  4771. expr_ty elt, expr_ty val, int type,
  4772. int iter_on_stack)
  4773. {
  4774. NEW_JUMP_TARGET_LABEL(c, start);
  4775. NEW_JUMP_TARGET_LABEL(c, except);
  4776. NEW_JUMP_TARGET_LABEL(c, if_cleanup);
  4777. comprehension_ty gen = (comprehension_ty)asdl_seq_GET(generators,
  4778. gen_index);
  4779. if (!iter_on_stack) {
  4780. if (gen_index == 0) {
  4781. /* Receive outermost iter as an implicit argument */
  4782. c->u->u_metadata.u_argcount = 1;
  4783. ADDOP_I(c, loc, LOAD_FAST, 0);
  4784. }
  4785. else {
  4786. /* Sub-iter - calculate on the fly */
  4787. VISIT(c, expr, gen->iter);
  4788. ADDOP(c, loc, GET_AITER);
  4789. }
  4790. }
  4791. USE_LABEL(c, start);
  4792. /* Runtime will push a block here, so we need to account for that */
  4793. RETURN_IF_ERROR(
  4794. compiler_push_fblock(c, loc, ASYNC_COMPREHENSION_GENERATOR,
  4795. start, NO_LABEL, NULL));
  4796. ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
  4797. ADDOP(c, loc, GET_ANEXT);
  4798. ADDOP_LOAD_CONST(c, loc, Py_None);
  4799. ADD_YIELD_FROM(c, loc, 1);
  4800. ADDOP(c, loc, POP_BLOCK);
  4801. VISIT(c, expr, gen->target);
  4802. Py_ssize_t n = asdl_seq_LEN(gen->ifs);
  4803. for (Py_ssize_t i = 0; i < n; i++) {
  4804. expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
  4805. RETURN_IF_ERROR(compiler_jump_if(c, loc, e, if_cleanup, 0));
  4806. }
  4807. depth++;
  4808. if (++gen_index < asdl_seq_LEN(generators)) {
  4809. RETURN_IF_ERROR(
  4810. compiler_comprehension_generator(c, loc,
  4811. generators, gen_index, depth,
  4812. elt, val, type, 0));
  4813. }
  4814. location elt_loc = LOC(elt);
  4815. /* only append after the last for generator */
  4816. if (gen_index >= asdl_seq_LEN(generators)) {
  4817. /* comprehension specific code */
  4818. switch (type) {
  4819. case COMP_GENEXP:
  4820. VISIT(c, expr, elt);
  4821. ADDOP_YIELD(c, elt_loc);
  4822. ADDOP(c, elt_loc, POP_TOP);
  4823. break;
  4824. case COMP_LISTCOMP:
  4825. VISIT(c, expr, elt);
  4826. ADDOP_I(c, elt_loc, LIST_APPEND, depth + 1);
  4827. break;
  4828. case COMP_SETCOMP:
  4829. VISIT(c, expr, elt);
  4830. ADDOP_I(c, elt_loc, SET_ADD, depth + 1);
  4831. break;
  4832. case COMP_DICTCOMP:
  4833. /* With '{k: v}', k is evaluated before v, so we do
  4834. the same. */
  4835. VISIT(c, expr, elt);
  4836. VISIT(c, expr, val);
  4837. elt_loc = LOCATION(elt->lineno,
  4838. val->end_lineno,
  4839. elt->col_offset,
  4840. val->end_col_offset);
  4841. ADDOP_I(c, elt_loc, MAP_ADD, depth + 1);
  4842. break;
  4843. default:
  4844. return ERROR;
  4845. }
  4846. }
  4847. USE_LABEL(c, if_cleanup);
  4848. ADDOP_JUMP(c, elt_loc, JUMP, start);
  4849. compiler_pop_fblock(c, ASYNC_COMPREHENSION_GENERATOR, start);
  4850. USE_LABEL(c, except);
  4851. ADDOP(c, loc, END_ASYNC_FOR);
  4852. return SUCCESS;
  4853. }
  4854. typedef struct {
  4855. PyObject *pushed_locals;
  4856. PyObject *temp_symbols;
  4857. PyObject *fast_hidden;
  4858. jump_target_label cleanup;
  4859. jump_target_label end;
  4860. } inlined_comprehension_state;
  4861. static int
  4862. push_inlined_comprehension_state(struct compiler *c, location loc,
  4863. PySTEntryObject *entry,
  4864. inlined_comprehension_state *state)
  4865. {
  4866. int in_class_block = (c->u->u_ste->ste_type == ClassBlock) && !c->u->u_in_inlined_comp;
  4867. c->u->u_in_inlined_comp++;
  4868. // iterate over names bound in the comprehension and ensure we isolate
  4869. // them from the outer scope as needed
  4870. PyObject *k, *v;
  4871. Py_ssize_t pos = 0;
  4872. while (PyDict_Next(entry->ste_symbols, &pos, &k, &v)) {
  4873. assert(PyLong_Check(v));
  4874. long symbol = PyLong_AS_LONG(v);
  4875. long scope = (symbol >> SCOPE_OFFSET) & SCOPE_MASK;
  4876. PyObject *outv = PyDict_GetItemWithError(c->u->u_ste->ste_symbols, k);
  4877. if (outv == NULL) {
  4878. if (PyErr_Occurred()) {
  4879. return ERROR;
  4880. }
  4881. outv = _PyLong_GetZero();
  4882. }
  4883. assert(PyLong_CheckExact(outv));
  4884. long outsc = (PyLong_AS_LONG(outv) >> SCOPE_OFFSET) & SCOPE_MASK;
  4885. // If a name has different scope inside than outside the comprehension,
  4886. // we need to temporarily handle it with the right scope while
  4887. // compiling the comprehension. If it's free in the comprehension
  4888. // scope, no special handling; it should be handled the same as the
  4889. // enclosing scope. (If it's free in outer scope and cell in inner
  4890. // scope, we can't treat it as both cell and free in the same function,
  4891. // but treating it as free throughout is fine; it's *_DEREF
  4892. // either way.)
  4893. if ((scope != outsc && scope != FREE && !(scope == CELL && outsc == FREE))
  4894. || in_class_block) {
  4895. if (state->temp_symbols == NULL) {
  4896. state->temp_symbols = PyDict_New();
  4897. if (state->temp_symbols == NULL) {
  4898. return ERROR;
  4899. }
  4900. }
  4901. // update the symbol to the in-comprehension version and save
  4902. // the outer version; we'll restore it after running the
  4903. // comprehension
  4904. Py_INCREF(outv);
  4905. if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v) < 0) {
  4906. Py_DECREF(outv);
  4907. return ERROR;
  4908. }
  4909. if (PyDict_SetItem(state->temp_symbols, k, outv) < 0) {
  4910. Py_DECREF(outv);
  4911. return ERROR;
  4912. }
  4913. Py_DECREF(outv);
  4914. }
  4915. // locals handling for names bound in comprehension (DEF_LOCAL |
  4916. // DEF_NONLOCAL occurs in assignment expression to nonlocal)
  4917. if ((symbol & DEF_LOCAL && !(symbol & DEF_NONLOCAL)) || in_class_block) {
  4918. if (!_PyST_IsFunctionLike(c->u->u_ste)) {
  4919. // non-function scope: override this name to use fast locals
  4920. PyObject *orig = PyDict_GetItem(c->u->u_metadata.u_fasthidden, k);
  4921. if (orig != Py_True) {
  4922. if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_True) < 0) {
  4923. return ERROR;
  4924. }
  4925. if (state->fast_hidden == NULL) {
  4926. state->fast_hidden = PySet_New(NULL);
  4927. if (state->fast_hidden == NULL) {
  4928. return ERROR;
  4929. }
  4930. }
  4931. if (PySet_Add(state->fast_hidden, k) < 0) {
  4932. return ERROR;
  4933. }
  4934. }
  4935. }
  4936. // local names bound in comprehension must be isolated from
  4937. // outer scope; push existing value (which may be NULL if
  4938. // not defined) on stack
  4939. if (state->pushed_locals == NULL) {
  4940. state->pushed_locals = PyList_New(0);
  4941. if (state->pushed_locals == NULL) {
  4942. return ERROR;
  4943. }
  4944. }
  4945. // in the case of a cell, this will actually push the cell
  4946. // itself to the stack, then we'll create a new one for the
  4947. // comprehension and restore the original one after
  4948. ADDOP_NAME(c, loc, LOAD_FAST_AND_CLEAR, k, varnames);
  4949. if (scope == CELL) {
  4950. if (outsc == FREE) {
  4951. ADDOP_NAME(c, loc, MAKE_CELL, k, freevars);
  4952. } else {
  4953. ADDOP_NAME(c, loc, MAKE_CELL, k, cellvars);
  4954. }
  4955. }
  4956. if (PyList_Append(state->pushed_locals, k) < 0) {
  4957. return ERROR;
  4958. }
  4959. }
  4960. }
  4961. if (state->pushed_locals) {
  4962. // Outermost iterable expression was already evaluated and is on the
  4963. // stack, we need to swap it back to TOS. This also rotates the order of
  4964. // `pushed_locals` on the stack, but this will be reversed when we swap
  4965. // out the comprehension result in pop_inlined_comprehension_state
  4966. ADDOP_I(c, loc, SWAP, PyList_GET_SIZE(state->pushed_locals) + 1);
  4967. // Add our own cleanup handler to restore comprehension locals in case
  4968. // of exception, so they have the correct values inside an exception
  4969. // handler or finally block.
  4970. NEW_JUMP_TARGET_LABEL(c, cleanup);
  4971. state->cleanup = cleanup;
  4972. NEW_JUMP_TARGET_LABEL(c, end);
  4973. state->end = end;
  4974. // no need to push an fblock for this "virtual" try/finally; there can't
  4975. // be return/continue/break inside a comprehension
  4976. ADDOP_JUMP(c, loc, SETUP_FINALLY, cleanup);
  4977. }
  4978. return SUCCESS;
  4979. }
  4980. static int
  4981. restore_inlined_comprehension_locals(struct compiler *c, location loc,
  4982. inlined_comprehension_state state)
  4983. {
  4984. PyObject *k;
  4985. // pop names we pushed to stack earlier
  4986. Py_ssize_t npops = PyList_GET_SIZE(state.pushed_locals);
  4987. // Preserve the comprehension result (or exception) as TOS. This
  4988. // reverses the SWAP we did in push_inlined_comprehension_state to get
  4989. // the outermost iterable to TOS, so we can still just iterate
  4990. // pushed_locals in simple reverse order
  4991. ADDOP_I(c, loc, SWAP, npops + 1);
  4992. for (Py_ssize_t i = npops - 1; i >= 0; --i) {
  4993. k = PyList_GetItem(state.pushed_locals, i);
  4994. if (k == NULL) {
  4995. return ERROR;
  4996. }
  4997. ADDOP_NAME(c, loc, STORE_FAST_MAYBE_NULL, k, varnames);
  4998. }
  4999. return SUCCESS;
  5000. }
  5001. static int
  5002. pop_inlined_comprehension_state(struct compiler *c, location loc,
  5003. inlined_comprehension_state state)
  5004. {
  5005. c->u->u_in_inlined_comp--;
  5006. PyObject *k, *v;
  5007. Py_ssize_t pos = 0;
  5008. if (state.temp_symbols) {
  5009. while (PyDict_Next(state.temp_symbols, &pos, &k, &v)) {
  5010. if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v)) {
  5011. return ERROR;
  5012. }
  5013. }
  5014. Py_CLEAR(state.temp_symbols);
  5015. }
  5016. if (state.pushed_locals) {
  5017. ADDOP(c, NO_LOCATION, POP_BLOCK);
  5018. ADDOP_JUMP(c, NO_LOCATION, JUMP, state.end);
  5019. // cleanup from an exception inside the comprehension
  5020. USE_LABEL(c, state.cleanup);
  5021. // discard incomplete comprehension result (beneath exc on stack)
  5022. ADDOP_I(c, NO_LOCATION, SWAP, 2);
  5023. ADDOP(c, NO_LOCATION, POP_TOP);
  5024. if (restore_inlined_comprehension_locals(c, loc, state) < 0) {
  5025. return ERROR;
  5026. }
  5027. ADDOP_I(c, NO_LOCATION, RERAISE, 0);
  5028. USE_LABEL(c, state.end);
  5029. if (restore_inlined_comprehension_locals(c, loc, state) < 0) {
  5030. return ERROR;
  5031. }
  5032. Py_CLEAR(state.pushed_locals);
  5033. }
  5034. if (state.fast_hidden) {
  5035. while (PySet_Size(state.fast_hidden) > 0) {
  5036. PyObject *k = PySet_Pop(state.fast_hidden);
  5037. if (k == NULL) {
  5038. return ERROR;
  5039. }
  5040. // we set to False instead of clearing, so we can track which names
  5041. // were temporarily fast-locals and should use CO_FAST_HIDDEN
  5042. if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_False)) {
  5043. Py_DECREF(k);
  5044. return ERROR;
  5045. }
  5046. Py_DECREF(k);
  5047. }
  5048. Py_CLEAR(state.fast_hidden);
  5049. }
  5050. return SUCCESS;
  5051. }
  5052. static inline int
  5053. compiler_comprehension_iter(struct compiler *c, location loc,
  5054. comprehension_ty comp)
  5055. {
  5056. VISIT(c, expr, comp->iter);
  5057. if (comp->is_async) {
  5058. ADDOP(c, loc, GET_AITER);
  5059. }
  5060. else {
  5061. ADDOP(c, loc, GET_ITER);
  5062. }
  5063. return SUCCESS;
  5064. }
  5065. static int
  5066. compiler_comprehension(struct compiler *c, expr_ty e, int type,
  5067. identifier name, asdl_comprehension_seq *generators, expr_ty elt,
  5068. expr_ty val)
  5069. {
  5070. PyCodeObject *co = NULL;
  5071. inlined_comprehension_state inline_state = {NULL, NULL, NULL, NO_LABEL, NO_LABEL};
  5072. comprehension_ty outermost;
  5073. int scope_type = c->u->u_scope_type;
  5074. int is_top_level_await = IS_TOP_LEVEL_AWAIT(c);
  5075. PySTEntryObject *entry = PySymtable_Lookup(c->c_st, (void *)e);
  5076. if (entry == NULL) {
  5077. goto error;
  5078. }
  5079. int is_inlined = entry->ste_comp_inlined;
  5080. int is_async_generator = entry->ste_coroutine;
  5081. location loc = LOC(e);
  5082. outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
  5083. if (is_inlined) {
  5084. if (compiler_comprehension_iter(c, loc, outermost)) {
  5085. goto error;
  5086. }
  5087. if (push_inlined_comprehension_state(c, loc, entry, &inline_state)) {
  5088. goto error;
  5089. }
  5090. }
  5091. else {
  5092. if (compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
  5093. (void *)e, e->lineno) < 0)
  5094. {
  5095. goto error;
  5096. }
  5097. }
  5098. Py_CLEAR(entry);
  5099. if (is_async_generator && type != COMP_GENEXP &&
  5100. scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
  5101. scope_type != COMPILER_SCOPE_COMPREHENSION &&
  5102. !is_top_level_await)
  5103. {
  5104. compiler_error(c, loc, "asynchronous comprehension outside of "
  5105. "an asynchronous function");
  5106. goto error_in_scope;
  5107. }
  5108. if (type != COMP_GENEXP) {
  5109. int op;
  5110. switch (type) {
  5111. case COMP_LISTCOMP:
  5112. op = BUILD_LIST;
  5113. break;
  5114. case COMP_SETCOMP:
  5115. op = BUILD_SET;
  5116. break;
  5117. case COMP_DICTCOMP:
  5118. op = BUILD_MAP;
  5119. break;
  5120. default:
  5121. PyErr_Format(PyExc_SystemError,
  5122. "unknown comprehension type %d", type);
  5123. goto error_in_scope;
  5124. }
  5125. ADDOP_I(c, loc, op, 0);
  5126. if (is_inlined) {
  5127. ADDOP_I(c, loc, SWAP, 2);
  5128. }
  5129. }
  5130. if (compiler_comprehension_generator(c, loc, generators, 0, 0,
  5131. elt, val, type, is_inlined) < 0) {
  5132. goto error_in_scope;
  5133. }
  5134. if (is_inlined) {
  5135. if (pop_inlined_comprehension_state(c, loc, inline_state)) {
  5136. goto error;
  5137. }
  5138. return SUCCESS;
  5139. }
  5140. if (type != COMP_GENEXP) {
  5141. ADDOP(c, LOC(e), RETURN_VALUE);
  5142. }
  5143. if (type == COMP_GENEXP) {
  5144. if (wrap_in_stopiteration_handler(c) < 0) {
  5145. goto error_in_scope;
  5146. }
  5147. }
  5148. co = optimize_and_assemble(c, 1);
  5149. compiler_exit_scope(c);
  5150. if (is_top_level_await && is_async_generator){
  5151. c->u->u_ste->ste_coroutine = 1;
  5152. }
  5153. if (co == NULL) {
  5154. goto error;
  5155. }
  5156. loc = LOC(e);
  5157. if (compiler_make_closure(c, loc, co, 0) < 0) {
  5158. goto error;
  5159. }
  5160. Py_CLEAR(co);
  5161. if (compiler_comprehension_iter(c, loc, outermost)) {
  5162. goto error;
  5163. }
  5164. ADDOP_I(c, loc, CALL, 0);
  5165. if (is_async_generator && type != COMP_GENEXP) {
  5166. ADDOP_I(c, loc, GET_AWAITABLE, 0);
  5167. ADDOP_LOAD_CONST(c, loc, Py_None);
  5168. ADD_YIELD_FROM(c, loc, 1);
  5169. }
  5170. return SUCCESS;
  5171. error_in_scope:
  5172. if (!is_inlined) {
  5173. compiler_exit_scope(c);
  5174. }
  5175. error:
  5176. Py_XDECREF(co);
  5177. Py_XDECREF(entry);
  5178. Py_XDECREF(inline_state.pushed_locals);
  5179. Py_XDECREF(inline_state.temp_symbols);
  5180. Py_XDECREF(inline_state.fast_hidden);
  5181. return ERROR;
  5182. }
  5183. static int
  5184. compiler_genexp(struct compiler *c, expr_ty e)
  5185. {
  5186. assert(e->kind == GeneratorExp_kind);
  5187. _Py_DECLARE_STR(anon_genexpr, "<genexpr>");
  5188. return compiler_comprehension(c, e, COMP_GENEXP, &_Py_STR(anon_genexpr),
  5189. e->v.GeneratorExp.generators,
  5190. e->v.GeneratorExp.elt, NULL);
  5191. }
  5192. static int
  5193. compiler_listcomp(struct compiler *c, expr_ty e)
  5194. {
  5195. assert(e->kind == ListComp_kind);
  5196. _Py_DECLARE_STR(anon_listcomp, "<listcomp>");
  5197. return compiler_comprehension(c, e, COMP_LISTCOMP, &_Py_STR(anon_listcomp),
  5198. e->v.ListComp.generators,
  5199. e->v.ListComp.elt, NULL);
  5200. }
  5201. static int
  5202. compiler_setcomp(struct compiler *c, expr_ty e)
  5203. {
  5204. assert(e->kind == SetComp_kind);
  5205. _Py_DECLARE_STR(anon_setcomp, "<setcomp>");
  5206. return compiler_comprehension(c, e, COMP_SETCOMP, &_Py_STR(anon_setcomp),
  5207. e->v.SetComp.generators,
  5208. e->v.SetComp.elt, NULL);
  5209. }
  5210. static int
  5211. compiler_dictcomp(struct compiler *c, expr_ty e)
  5212. {
  5213. assert(e->kind == DictComp_kind);
  5214. _Py_DECLARE_STR(anon_dictcomp, "<dictcomp>");
  5215. return compiler_comprehension(c, e, COMP_DICTCOMP, &_Py_STR(anon_dictcomp),
  5216. e->v.DictComp.generators,
  5217. e->v.DictComp.key, e->v.DictComp.value);
  5218. }
  5219. static int
  5220. compiler_visit_keyword(struct compiler *c, keyword_ty k)
  5221. {
  5222. VISIT(c, expr, k->value);
  5223. return SUCCESS;
  5224. }
  5225. static int
  5226. compiler_with_except_finish(struct compiler *c, jump_target_label cleanup) {
  5227. NEW_JUMP_TARGET_LABEL(c, suppress);
  5228. ADDOP_JUMP(c, NO_LOCATION, POP_JUMP_IF_TRUE, suppress);
  5229. ADDOP_I(c, NO_LOCATION, RERAISE, 2);
  5230. USE_LABEL(c, suppress);
  5231. ADDOP(c, NO_LOCATION, POP_TOP); /* exc_value */
  5232. ADDOP(c, NO_LOCATION, POP_BLOCK);
  5233. ADDOP(c, NO_LOCATION, POP_EXCEPT);
  5234. ADDOP(c, NO_LOCATION, POP_TOP);
  5235. ADDOP(c, NO_LOCATION, POP_TOP);
  5236. NEW_JUMP_TARGET_LABEL(c, exit);
  5237. ADDOP_JUMP(c, NO_LOCATION, JUMP, exit);
  5238. USE_LABEL(c, cleanup);
  5239. POP_EXCEPT_AND_RERAISE(c, NO_LOCATION);
  5240. USE_LABEL(c, exit);
  5241. return SUCCESS;
  5242. }
  5243. /*
  5244. Implements the async with statement.
  5245. The semantics outlined in that PEP are as follows:
  5246. async with EXPR as VAR:
  5247. BLOCK
  5248. It is implemented roughly as:
  5249. context = EXPR
  5250. exit = context.__aexit__ # not calling it
  5251. value = await context.__aenter__()
  5252. try:
  5253. VAR = value # if VAR present in the syntax
  5254. BLOCK
  5255. finally:
  5256. if an exception was raised:
  5257. exc = copy of (exception, instance, traceback)
  5258. else:
  5259. exc = (None, None, None)
  5260. if not (await exit(*exc)):
  5261. raise
  5262. */
  5263. static int
  5264. compiler_async_with(struct compiler *c, stmt_ty s, int pos)
  5265. {
  5266. location loc = LOC(s);
  5267. withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
  5268. assert(s->kind == AsyncWith_kind);
  5269. if (IS_TOP_LEVEL_AWAIT(c)){
  5270. c->u->u_ste->ste_coroutine = 1;
  5271. } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
  5272. return compiler_error(c, loc, "'async with' outside async function");
  5273. }
  5274. NEW_JUMP_TARGET_LABEL(c, block);
  5275. NEW_JUMP_TARGET_LABEL(c, final);
  5276. NEW_JUMP_TARGET_LABEL(c, exit);
  5277. NEW_JUMP_TARGET_LABEL(c, cleanup);
  5278. /* Evaluate EXPR */
  5279. VISIT(c, expr, item->context_expr);
  5280. ADDOP(c, loc, BEFORE_ASYNC_WITH);
  5281. ADDOP_I(c, loc, GET_AWAITABLE, 1);
  5282. ADDOP_LOAD_CONST(c, loc, Py_None);
  5283. ADD_YIELD_FROM(c, loc, 1);
  5284. ADDOP_JUMP(c, loc, SETUP_WITH, final);
  5285. /* SETUP_WITH pushes a finally block. */
  5286. USE_LABEL(c, block);
  5287. RETURN_IF_ERROR(compiler_push_fblock(c, loc, ASYNC_WITH, block, final, s));
  5288. if (item->optional_vars) {
  5289. VISIT(c, expr, item->optional_vars);
  5290. }
  5291. else {
  5292. /* Discard result from context.__aenter__() */
  5293. ADDOP(c, loc, POP_TOP);
  5294. }
  5295. pos++;
  5296. if (pos == asdl_seq_LEN(s->v.AsyncWith.items)) {
  5297. /* BLOCK code */
  5298. VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
  5299. }
  5300. else {
  5301. RETURN_IF_ERROR(compiler_async_with(c, s, pos));
  5302. }
  5303. compiler_pop_fblock(c, ASYNC_WITH, block);
  5304. ADDOP(c, loc, POP_BLOCK);
  5305. /* End of body; start the cleanup */
  5306. /* For successful outcome:
  5307. * call __exit__(None, None, None)
  5308. */
  5309. RETURN_IF_ERROR(compiler_call_exit_with_nones(c, loc));
  5310. ADDOP_I(c, loc, GET_AWAITABLE, 2);
  5311. ADDOP_LOAD_CONST(c, loc, Py_None);
  5312. ADD_YIELD_FROM(c, loc, 1);
  5313. ADDOP(c, loc, POP_TOP);
  5314. ADDOP_JUMP(c, loc, JUMP, exit);
  5315. /* For exceptional outcome: */
  5316. USE_LABEL(c, final);
  5317. ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
  5318. ADDOP(c, loc, PUSH_EXC_INFO);
  5319. ADDOP(c, loc, WITH_EXCEPT_START);
  5320. ADDOP_I(c, loc, GET_AWAITABLE, 2);
  5321. ADDOP_LOAD_CONST(c, loc, Py_None);
  5322. ADD_YIELD_FROM(c, loc, 1);
  5323. RETURN_IF_ERROR(compiler_with_except_finish(c, cleanup));
  5324. USE_LABEL(c, exit);
  5325. return SUCCESS;
  5326. }
  5327. /*
  5328. Implements the with statement from PEP 343.
  5329. with EXPR as VAR:
  5330. BLOCK
  5331. is implemented as:
  5332. <code for EXPR>
  5333. SETUP_WITH E
  5334. <code to store to VAR> or POP_TOP
  5335. <code for BLOCK>
  5336. LOAD_CONST (None, None, None)
  5337. CALL_FUNCTION_EX 0
  5338. JUMP EXIT
  5339. E: WITH_EXCEPT_START (calls EXPR.__exit__)
  5340. POP_JUMP_IF_TRUE T:
  5341. RERAISE
  5342. T: POP_TOP (remove exception from stack)
  5343. POP_EXCEPT
  5344. POP_TOP
  5345. EXIT:
  5346. */
  5347. static int
  5348. compiler_with(struct compiler *c, stmt_ty s, int pos)
  5349. {
  5350. withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
  5351. assert(s->kind == With_kind);
  5352. NEW_JUMP_TARGET_LABEL(c, block);
  5353. NEW_JUMP_TARGET_LABEL(c, final);
  5354. NEW_JUMP_TARGET_LABEL(c, exit);
  5355. NEW_JUMP_TARGET_LABEL(c, cleanup);
  5356. /* Evaluate EXPR */
  5357. VISIT(c, expr, item->context_expr);
  5358. /* Will push bound __exit__ */
  5359. location loc = LOC(s);
  5360. ADDOP(c, loc, BEFORE_WITH);
  5361. ADDOP_JUMP(c, loc, SETUP_WITH, final);
  5362. /* SETUP_WITH pushes a finally block. */
  5363. USE_LABEL(c, block);
  5364. RETURN_IF_ERROR(compiler_push_fblock(c, loc, WITH, block, final, s));
  5365. if (item->optional_vars) {
  5366. VISIT(c, expr, item->optional_vars);
  5367. }
  5368. else {
  5369. /* Discard result from context.__enter__() */
  5370. ADDOP(c, loc, POP_TOP);
  5371. }
  5372. pos++;
  5373. if (pos == asdl_seq_LEN(s->v.With.items)) {
  5374. /* BLOCK code */
  5375. VISIT_SEQ(c, stmt, s->v.With.body)
  5376. }
  5377. else {
  5378. RETURN_IF_ERROR(compiler_with(c, s, pos));
  5379. }
  5380. ADDOP(c, NO_LOCATION, POP_BLOCK);
  5381. compiler_pop_fblock(c, WITH, block);
  5382. /* End of body; start the cleanup. */
  5383. /* For successful outcome:
  5384. * call __exit__(None, None, None)
  5385. */
  5386. loc = LOC(s);
  5387. RETURN_IF_ERROR(compiler_call_exit_with_nones(c, loc));
  5388. ADDOP(c, loc, POP_TOP);
  5389. ADDOP_JUMP(c, loc, JUMP, exit);
  5390. /* For exceptional outcome: */
  5391. USE_LABEL(c, final);
  5392. ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
  5393. ADDOP(c, loc, PUSH_EXC_INFO);
  5394. ADDOP(c, loc, WITH_EXCEPT_START);
  5395. RETURN_IF_ERROR(compiler_with_except_finish(c, cleanup));
  5396. USE_LABEL(c, exit);
  5397. return SUCCESS;
  5398. }
  5399. static int
  5400. compiler_visit_expr1(struct compiler *c, expr_ty e)
  5401. {
  5402. location loc = LOC(e);
  5403. switch (e->kind) {
  5404. case NamedExpr_kind:
  5405. VISIT(c, expr, e->v.NamedExpr.value);
  5406. ADDOP_I(c, loc, COPY, 1);
  5407. VISIT(c, expr, e->v.NamedExpr.target);
  5408. break;
  5409. case BoolOp_kind:
  5410. return compiler_boolop(c, e);
  5411. case BinOp_kind:
  5412. VISIT(c, expr, e->v.BinOp.left);
  5413. VISIT(c, expr, e->v.BinOp.right);
  5414. ADDOP_BINARY(c, loc, e->v.BinOp.op);
  5415. break;
  5416. case UnaryOp_kind:
  5417. VISIT(c, expr, e->v.UnaryOp.operand);
  5418. if (e->v.UnaryOp.op == UAdd) {
  5419. ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_UNARY_POSITIVE);
  5420. }
  5421. else {
  5422. ADDOP(c, loc, unaryop(e->v.UnaryOp.op));
  5423. }
  5424. break;
  5425. case Lambda_kind:
  5426. return compiler_lambda(c, e);
  5427. case IfExp_kind:
  5428. return compiler_ifexp(c, e);
  5429. case Dict_kind:
  5430. return compiler_dict(c, e);
  5431. case Set_kind:
  5432. return compiler_set(c, e);
  5433. case GeneratorExp_kind:
  5434. return compiler_genexp(c, e);
  5435. case ListComp_kind:
  5436. return compiler_listcomp(c, e);
  5437. case SetComp_kind:
  5438. return compiler_setcomp(c, e);
  5439. case DictComp_kind:
  5440. return compiler_dictcomp(c, e);
  5441. case Yield_kind:
  5442. if (!_PyST_IsFunctionLike(c->u->u_ste)) {
  5443. return compiler_error(c, loc, "'yield' outside function");
  5444. }
  5445. if (e->v.Yield.value) {
  5446. VISIT(c, expr, e->v.Yield.value);
  5447. }
  5448. else {
  5449. ADDOP_LOAD_CONST(c, loc, Py_None);
  5450. }
  5451. ADDOP_YIELD(c, loc);
  5452. break;
  5453. case YieldFrom_kind:
  5454. if (!_PyST_IsFunctionLike(c->u->u_ste)) {
  5455. return compiler_error(c, loc, "'yield from' outside function");
  5456. }
  5457. if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION) {
  5458. return compiler_error(c, loc, "'yield from' inside async function");
  5459. }
  5460. VISIT(c, expr, e->v.YieldFrom.value);
  5461. ADDOP(c, loc, GET_YIELD_FROM_ITER);
  5462. ADDOP_LOAD_CONST(c, loc, Py_None);
  5463. ADD_YIELD_FROM(c, loc, 0);
  5464. break;
  5465. case Await_kind:
  5466. if (!IS_TOP_LEVEL_AWAIT(c)){
  5467. if (!_PyST_IsFunctionLike(c->u->u_ste)) {
  5468. return compiler_error(c, loc, "'await' outside function");
  5469. }
  5470. if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
  5471. c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION) {
  5472. return compiler_error(c, loc, "'await' outside async function");
  5473. }
  5474. }
  5475. VISIT(c, expr, e->v.Await.value);
  5476. ADDOP_I(c, loc, GET_AWAITABLE, 0);
  5477. ADDOP_LOAD_CONST(c, loc, Py_None);
  5478. ADD_YIELD_FROM(c, loc, 1);
  5479. break;
  5480. case Compare_kind:
  5481. return compiler_compare(c, e);
  5482. case Call_kind:
  5483. return compiler_call(c, e);
  5484. case Constant_kind:
  5485. ADDOP_LOAD_CONST(c, loc, e->v.Constant.value);
  5486. break;
  5487. case JoinedStr_kind:
  5488. return compiler_joined_str(c, e);
  5489. case FormattedValue_kind:
  5490. return compiler_formatted_value(c, e);
  5491. /* The following exprs can be assignment targets. */
  5492. case Attribute_kind:
  5493. if (e->v.Attribute.ctx == Load && can_optimize_super_call(c, e)) {
  5494. RETURN_IF_ERROR(load_args_for_super(c, e->v.Attribute.value));
  5495. int opcode = asdl_seq_LEN(e->v.Attribute.value->v.Call.args) ?
  5496. LOAD_SUPER_ATTR : LOAD_ZERO_SUPER_ATTR;
  5497. ADDOP_NAME(c, loc, opcode, e->v.Attribute.attr, names);
  5498. loc = update_start_location_to_match_attr(c, loc, e);
  5499. ADDOP(c, loc, NOP);
  5500. return SUCCESS;
  5501. }
  5502. VISIT(c, expr, e->v.Attribute.value);
  5503. loc = LOC(e);
  5504. loc = update_start_location_to_match_attr(c, loc, e);
  5505. switch (e->v.Attribute.ctx) {
  5506. case Load:
  5507. ADDOP_NAME(c, loc, LOAD_ATTR, e->v.Attribute.attr, names);
  5508. break;
  5509. case Store:
  5510. if (forbidden_name(c, loc, e->v.Attribute.attr, e->v.Attribute.ctx)) {
  5511. return ERROR;
  5512. }
  5513. ADDOP_NAME(c, loc, STORE_ATTR, e->v.Attribute.attr, names);
  5514. break;
  5515. case Del:
  5516. ADDOP_NAME(c, loc, DELETE_ATTR, e->v.Attribute.attr, names);
  5517. break;
  5518. }
  5519. break;
  5520. case Subscript_kind:
  5521. return compiler_subscript(c, e);
  5522. case Starred_kind:
  5523. switch (e->v.Starred.ctx) {
  5524. case Store:
  5525. /* In all legitimate cases, the Starred node was already replaced
  5526. * by compiler_list/compiler_tuple. XXX: is that okay? */
  5527. return compiler_error(c, loc,
  5528. "starred assignment target must be in a list or tuple");
  5529. default:
  5530. return compiler_error(c, loc,
  5531. "can't use starred expression here");
  5532. }
  5533. break;
  5534. case Slice_kind:
  5535. {
  5536. int n = compiler_slice(c, e);
  5537. RETURN_IF_ERROR(n);
  5538. ADDOP_I(c, loc, BUILD_SLICE, n);
  5539. break;
  5540. }
  5541. case Name_kind:
  5542. return compiler_nameop(c, loc, e->v.Name.id, e->v.Name.ctx);
  5543. /* child nodes of List and Tuple will have expr_context set */
  5544. case List_kind:
  5545. return compiler_list(c, e);
  5546. case Tuple_kind:
  5547. return compiler_tuple(c, e);
  5548. }
  5549. return SUCCESS;
  5550. }
  5551. static int
  5552. compiler_visit_expr(struct compiler *c, expr_ty e)
  5553. {
  5554. int res = compiler_visit_expr1(c, e);
  5555. return res;
  5556. }
  5557. static bool
  5558. is_two_element_slice(expr_ty s)
  5559. {
  5560. return s->kind == Slice_kind &&
  5561. s->v.Slice.step == NULL;
  5562. }
  5563. static int
  5564. compiler_augassign(struct compiler *c, stmt_ty s)
  5565. {
  5566. assert(s->kind == AugAssign_kind);
  5567. expr_ty e = s->v.AugAssign.target;
  5568. location loc = LOC(e);
  5569. switch (e->kind) {
  5570. case Attribute_kind:
  5571. VISIT(c, expr, e->v.Attribute.value);
  5572. ADDOP_I(c, loc, COPY, 1);
  5573. loc = update_start_location_to_match_attr(c, loc, e);
  5574. ADDOP_NAME(c, loc, LOAD_ATTR, e->v.Attribute.attr, names);
  5575. break;
  5576. case Subscript_kind:
  5577. VISIT(c, expr, e->v.Subscript.value);
  5578. if (is_two_element_slice(e->v.Subscript.slice)) {
  5579. RETURN_IF_ERROR(compiler_slice(c, e->v.Subscript.slice));
  5580. ADDOP_I(c, loc, COPY, 3);
  5581. ADDOP_I(c, loc, COPY, 3);
  5582. ADDOP_I(c, loc, COPY, 3);
  5583. ADDOP(c, loc, BINARY_SLICE);
  5584. }
  5585. else {
  5586. VISIT(c, expr, e->v.Subscript.slice);
  5587. ADDOP_I(c, loc, COPY, 2);
  5588. ADDOP_I(c, loc, COPY, 2);
  5589. ADDOP(c, loc, BINARY_SUBSCR);
  5590. }
  5591. break;
  5592. case Name_kind:
  5593. RETURN_IF_ERROR(compiler_nameop(c, loc, e->v.Name.id, Load));
  5594. break;
  5595. default:
  5596. PyErr_Format(PyExc_SystemError,
  5597. "invalid node type (%d) for augmented assignment",
  5598. e->kind);
  5599. return ERROR;
  5600. }
  5601. loc = LOC(s);
  5602. VISIT(c, expr, s->v.AugAssign.value);
  5603. ADDOP_INPLACE(c, loc, s->v.AugAssign.op);
  5604. loc = LOC(e);
  5605. switch (e->kind) {
  5606. case Attribute_kind:
  5607. loc = update_start_location_to_match_attr(c, loc, e);
  5608. ADDOP_I(c, loc, SWAP, 2);
  5609. ADDOP_NAME(c, loc, STORE_ATTR, e->v.Attribute.attr, names);
  5610. break;
  5611. case Subscript_kind:
  5612. if (is_two_element_slice(e->v.Subscript.slice)) {
  5613. ADDOP_I(c, loc, SWAP, 4);
  5614. ADDOP_I(c, loc, SWAP, 3);
  5615. ADDOP_I(c, loc, SWAP, 2);
  5616. ADDOP(c, loc, STORE_SLICE);
  5617. }
  5618. else {
  5619. ADDOP_I(c, loc, SWAP, 3);
  5620. ADDOP_I(c, loc, SWAP, 2);
  5621. ADDOP(c, loc, STORE_SUBSCR);
  5622. }
  5623. break;
  5624. case Name_kind:
  5625. return compiler_nameop(c, loc, e->v.Name.id, Store);
  5626. default:
  5627. Py_UNREACHABLE();
  5628. }
  5629. return SUCCESS;
  5630. }
  5631. static int
  5632. check_ann_expr(struct compiler *c, expr_ty e)
  5633. {
  5634. VISIT(c, expr, e);
  5635. ADDOP(c, LOC(e), POP_TOP);
  5636. return SUCCESS;
  5637. }
  5638. static int
  5639. check_annotation(struct compiler *c, stmt_ty s)
  5640. {
  5641. /* Annotations of complex targets does not produce anything
  5642. under annotations future */
  5643. if (c->c_future.ff_features & CO_FUTURE_ANNOTATIONS) {
  5644. return SUCCESS;
  5645. }
  5646. /* Annotations are only evaluated in a module or class. */
  5647. if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
  5648. c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
  5649. return check_ann_expr(c, s->v.AnnAssign.annotation);
  5650. }
  5651. return SUCCESS;
  5652. }
  5653. static int
  5654. check_ann_subscr(struct compiler *c, expr_ty e)
  5655. {
  5656. /* We check that everything in a subscript is defined at runtime. */
  5657. switch (e->kind) {
  5658. case Slice_kind:
  5659. if (e->v.Slice.lower && check_ann_expr(c, e->v.Slice.lower) < 0) {
  5660. return ERROR;
  5661. }
  5662. if (e->v.Slice.upper && check_ann_expr(c, e->v.Slice.upper) < 0) {
  5663. return ERROR;
  5664. }
  5665. if (e->v.Slice.step && check_ann_expr(c, e->v.Slice.step) < 0) {
  5666. return ERROR;
  5667. }
  5668. return SUCCESS;
  5669. case Tuple_kind: {
  5670. /* extended slice */
  5671. asdl_expr_seq *elts = e->v.Tuple.elts;
  5672. Py_ssize_t i, n = asdl_seq_LEN(elts);
  5673. for (i = 0; i < n; i++) {
  5674. RETURN_IF_ERROR(check_ann_subscr(c, asdl_seq_GET(elts, i)));
  5675. }
  5676. return SUCCESS;
  5677. }
  5678. default:
  5679. return check_ann_expr(c, e);
  5680. }
  5681. }
  5682. static int
  5683. compiler_annassign(struct compiler *c, stmt_ty s)
  5684. {
  5685. location loc = LOC(s);
  5686. expr_ty targ = s->v.AnnAssign.target;
  5687. PyObject* mangled;
  5688. assert(s->kind == AnnAssign_kind);
  5689. /* We perform the actual assignment first. */
  5690. if (s->v.AnnAssign.value) {
  5691. VISIT(c, expr, s->v.AnnAssign.value);
  5692. VISIT(c, expr, targ);
  5693. }
  5694. switch (targ->kind) {
  5695. case Name_kind:
  5696. if (forbidden_name(c, loc, targ->v.Name.id, Store)) {
  5697. return ERROR;
  5698. }
  5699. /* If we have a simple name in a module or class, store annotation. */
  5700. if (s->v.AnnAssign.simple &&
  5701. (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
  5702. c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
  5703. if (c->c_future.ff_features & CO_FUTURE_ANNOTATIONS) {
  5704. VISIT(c, annexpr, s->v.AnnAssign.annotation)
  5705. }
  5706. else {
  5707. VISIT(c, expr, s->v.AnnAssign.annotation);
  5708. }
  5709. ADDOP_NAME(c, loc, LOAD_NAME, &_Py_ID(__annotations__), names);
  5710. mangled = _Py_MaybeMangle(c->u->u_private, c->u->u_ste, targ->v.Name.id);
  5711. ADDOP_LOAD_CONST_NEW(c, loc, mangled);
  5712. ADDOP(c, loc, STORE_SUBSCR);
  5713. }
  5714. break;
  5715. case Attribute_kind:
  5716. if (forbidden_name(c, loc, targ->v.Attribute.attr, Store)) {
  5717. return ERROR;
  5718. }
  5719. if (!s->v.AnnAssign.value &&
  5720. check_ann_expr(c, targ->v.Attribute.value) < 0) {
  5721. return ERROR;
  5722. }
  5723. break;
  5724. case Subscript_kind:
  5725. if (!s->v.AnnAssign.value &&
  5726. (check_ann_expr(c, targ->v.Subscript.value) < 0 ||
  5727. check_ann_subscr(c, targ->v.Subscript.slice) < 0)) {
  5728. return ERROR;
  5729. }
  5730. break;
  5731. default:
  5732. PyErr_Format(PyExc_SystemError,
  5733. "invalid node type (%d) for annotated assignment",
  5734. targ->kind);
  5735. return ERROR;
  5736. }
  5737. /* Annotation is evaluated last. */
  5738. if (!s->v.AnnAssign.simple && check_annotation(c, s) < 0) {
  5739. return ERROR;
  5740. }
  5741. return SUCCESS;
  5742. }
  5743. /* Raises a SyntaxError and returns 0.
  5744. If something goes wrong, a different exception may be raised.
  5745. */
  5746. static int
  5747. compiler_error(struct compiler *c, location loc,
  5748. const char *format, ...)
  5749. {
  5750. va_list vargs;
  5751. va_start(vargs, format);
  5752. PyObject *msg = PyUnicode_FromFormatV(format, vargs);
  5753. va_end(vargs);
  5754. if (msg == NULL) {
  5755. return ERROR;
  5756. }
  5757. PyObject *loc_obj = PyErr_ProgramTextObject(c->c_filename, loc.lineno);
  5758. if (loc_obj == NULL) {
  5759. loc_obj = Py_NewRef(Py_None);
  5760. }
  5761. PyObject *args = Py_BuildValue("O(OiiOii)", msg, c->c_filename,
  5762. loc.lineno, loc.col_offset + 1, loc_obj,
  5763. loc.end_lineno, loc.end_col_offset + 1);
  5764. Py_DECREF(msg);
  5765. if (args == NULL) {
  5766. goto exit;
  5767. }
  5768. PyErr_SetObject(PyExc_SyntaxError, args);
  5769. exit:
  5770. Py_DECREF(loc_obj);
  5771. Py_XDECREF(args);
  5772. return ERROR;
  5773. }
  5774. /* Emits a SyntaxWarning and returns 1 on success.
  5775. If a SyntaxWarning raised as error, replaces it with a SyntaxError
  5776. and returns 0.
  5777. */
  5778. static int
  5779. compiler_warn(struct compiler *c, location loc,
  5780. const char *format, ...)
  5781. {
  5782. va_list vargs;
  5783. va_start(vargs, format);
  5784. PyObject *msg = PyUnicode_FromFormatV(format, vargs);
  5785. va_end(vargs);
  5786. if (msg == NULL) {
  5787. return ERROR;
  5788. }
  5789. if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
  5790. loc.lineno, NULL, NULL) < 0)
  5791. {
  5792. if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
  5793. /* Replace the SyntaxWarning exception with a SyntaxError
  5794. to get a more accurate error report */
  5795. PyErr_Clear();
  5796. assert(PyUnicode_AsUTF8(msg) != NULL);
  5797. compiler_error(c, loc, PyUnicode_AsUTF8(msg));
  5798. }
  5799. Py_DECREF(msg);
  5800. return ERROR;
  5801. }
  5802. Py_DECREF(msg);
  5803. return SUCCESS;
  5804. }
  5805. static int
  5806. compiler_subscript(struct compiler *c, expr_ty e)
  5807. {
  5808. location loc = LOC(e);
  5809. expr_context_ty ctx = e->v.Subscript.ctx;
  5810. int op = 0;
  5811. if (ctx == Load) {
  5812. RETURN_IF_ERROR(check_subscripter(c, e->v.Subscript.value));
  5813. RETURN_IF_ERROR(check_index(c, e->v.Subscript.value, e->v.Subscript.slice));
  5814. }
  5815. VISIT(c, expr, e->v.Subscript.value);
  5816. if (is_two_element_slice(e->v.Subscript.slice) && ctx != Del) {
  5817. RETURN_IF_ERROR(compiler_slice(c, e->v.Subscript.slice));
  5818. if (ctx == Load) {
  5819. ADDOP(c, loc, BINARY_SLICE);
  5820. }
  5821. else {
  5822. assert(ctx == Store);
  5823. ADDOP(c, loc, STORE_SLICE);
  5824. }
  5825. }
  5826. else {
  5827. VISIT(c, expr, e->v.Subscript.slice);
  5828. switch (ctx) {
  5829. case Load: op = BINARY_SUBSCR; break;
  5830. case Store: op = STORE_SUBSCR; break;
  5831. case Del: op = DELETE_SUBSCR; break;
  5832. }
  5833. assert(op);
  5834. ADDOP(c, loc, op);
  5835. }
  5836. return SUCCESS;
  5837. }
  5838. /* Returns the number of the values emitted,
  5839. * thus are needed to build the slice, or -1 if there is an error. */
  5840. static int
  5841. compiler_slice(struct compiler *c, expr_ty s)
  5842. {
  5843. int n = 2;
  5844. assert(s->kind == Slice_kind);
  5845. /* only handles the cases where BUILD_SLICE is emitted */
  5846. if (s->v.Slice.lower) {
  5847. VISIT(c, expr, s->v.Slice.lower);
  5848. }
  5849. else {
  5850. ADDOP_LOAD_CONST(c, LOC(s), Py_None);
  5851. }
  5852. if (s->v.Slice.upper) {
  5853. VISIT(c, expr, s->v.Slice.upper);
  5854. }
  5855. else {
  5856. ADDOP_LOAD_CONST(c, LOC(s), Py_None);
  5857. }
  5858. if (s->v.Slice.step) {
  5859. n++;
  5860. VISIT(c, expr, s->v.Slice.step);
  5861. }
  5862. return n;
  5863. }
  5864. // PEP 634: Structural Pattern Matching
  5865. // To keep things simple, all compiler_pattern_* and pattern_helper_* routines
  5866. // follow the convention of consuming TOS (the subject for the given pattern)
  5867. // and calling jump_to_fail_pop on failure (no match).
  5868. // When calling into these routines, it's important that pc->on_top be kept
  5869. // updated to reflect the current number of items that we are using on the top
  5870. // of the stack: they will be popped on failure, and any name captures will be
  5871. // stored *underneath* them on success. This lets us defer all names stores
  5872. // until the *entire* pattern matches.
  5873. #define WILDCARD_CHECK(N) \
  5874. ((N)->kind == MatchAs_kind && !(N)->v.MatchAs.name)
  5875. #define WILDCARD_STAR_CHECK(N) \
  5876. ((N)->kind == MatchStar_kind && !(N)->v.MatchStar.name)
  5877. // Limit permitted subexpressions, even if the parser & AST validator let them through
  5878. #define MATCH_VALUE_EXPR(N) \
  5879. ((N)->kind == Constant_kind || (N)->kind == Attribute_kind)
  5880. // Allocate or resize pc->fail_pop to allow for n items to be popped on failure.
  5881. static int
  5882. ensure_fail_pop(struct compiler *c, pattern_context *pc, Py_ssize_t n)
  5883. {
  5884. Py_ssize_t size = n + 1;
  5885. if (size <= pc->fail_pop_size) {
  5886. return SUCCESS;
  5887. }
  5888. Py_ssize_t needed = sizeof(jump_target_label) * size;
  5889. jump_target_label *resized = PyObject_Realloc(pc->fail_pop, needed);
  5890. if (resized == NULL) {
  5891. PyErr_NoMemory();
  5892. return ERROR;
  5893. }
  5894. pc->fail_pop = resized;
  5895. while (pc->fail_pop_size < size) {
  5896. NEW_JUMP_TARGET_LABEL(c, new_block);
  5897. pc->fail_pop[pc->fail_pop_size++] = new_block;
  5898. }
  5899. return SUCCESS;
  5900. }
  5901. // Use op to jump to the correct fail_pop block.
  5902. static int
  5903. jump_to_fail_pop(struct compiler *c, location loc,
  5904. pattern_context *pc, int op)
  5905. {
  5906. // Pop any items on the top of the stack, plus any objects we were going to
  5907. // capture on success:
  5908. Py_ssize_t pops = pc->on_top + PyList_GET_SIZE(pc->stores);
  5909. RETURN_IF_ERROR(ensure_fail_pop(c, pc, pops));
  5910. ADDOP_JUMP(c, loc, op, pc->fail_pop[pops]);
  5911. return SUCCESS;
  5912. }
  5913. // Build all of the fail_pop blocks and reset fail_pop.
  5914. static int
  5915. emit_and_reset_fail_pop(struct compiler *c, location loc,
  5916. pattern_context *pc)
  5917. {
  5918. if (!pc->fail_pop_size) {
  5919. assert(pc->fail_pop == NULL);
  5920. return SUCCESS;
  5921. }
  5922. while (--pc->fail_pop_size) {
  5923. USE_LABEL(c, pc->fail_pop[pc->fail_pop_size]);
  5924. if (codegen_addop_noarg(INSTR_SEQUENCE(c), POP_TOP, loc) < 0) {
  5925. pc->fail_pop_size = 0;
  5926. PyObject_Free(pc->fail_pop);
  5927. pc->fail_pop = NULL;
  5928. return ERROR;
  5929. }
  5930. }
  5931. USE_LABEL(c, pc->fail_pop[0]);
  5932. PyObject_Free(pc->fail_pop);
  5933. pc->fail_pop = NULL;
  5934. return SUCCESS;
  5935. }
  5936. static int
  5937. compiler_error_duplicate_store(struct compiler *c, location loc, identifier n)
  5938. {
  5939. return compiler_error(c, loc,
  5940. "multiple assignments to name %R in pattern", n);
  5941. }
  5942. // Duplicate the effect of 3.10's ROT_* instructions using SWAPs.
  5943. static int
  5944. pattern_helper_rotate(struct compiler *c, location loc, Py_ssize_t count)
  5945. {
  5946. while (1 < count) {
  5947. ADDOP_I(c, loc, SWAP, count--);
  5948. }
  5949. return SUCCESS;
  5950. }
  5951. static int
  5952. pattern_helper_store_name(struct compiler *c, location loc,
  5953. identifier n, pattern_context *pc)
  5954. {
  5955. if (n == NULL) {
  5956. ADDOP(c, loc, POP_TOP);
  5957. return SUCCESS;
  5958. }
  5959. if (forbidden_name(c, loc, n, Store)) {
  5960. return ERROR;
  5961. }
  5962. // Can't assign to the same name twice:
  5963. int duplicate = PySequence_Contains(pc->stores, n);
  5964. RETURN_IF_ERROR(duplicate);
  5965. if (duplicate) {
  5966. return compiler_error_duplicate_store(c, loc, n);
  5967. }
  5968. // Rotate this object underneath any items we need to preserve:
  5969. Py_ssize_t rotations = pc->on_top + PyList_GET_SIZE(pc->stores) + 1;
  5970. RETURN_IF_ERROR(pattern_helper_rotate(c, loc, rotations));
  5971. RETURN_IF_ERROR(PyList_Append(pc->stores, n));
  5972. return SUCCESS;
  5973. }
  5974. static int
  5975. pattern_unpack_helper(struct compiler *c, location loc,
  5976. asdl_pattern_seq *elts)
  5977. {
  5978. Py_ssize_t n = asdl_seq_LEN(elts);
  5979. int seen_star = 0;
  5980. for (Py_ssize_t i = 0; i < n; i++) {
  5981. pattern_ty elt = asdl_seq_GET(elts, i);
  5982. if (elt->kind == MatchStar_kind && !seen_star) {
  5983. if ((i >= (1 << 8)) ||
  5984. (n-i-1 >= (INT_MAX >> 8))) {
  5985. return compiler_error(c, loc,
  5986. "too many expressions in "
  5987. "star-unpacking sequence pattern");
  5988. }
  5989. ADDOP_I(c, loc, UNPACK_EX, (i + ((n-i-1) << 8)));
  5990. seen_star = 1;
  5991. }
  5992. else if (elt->kind == MatchStar_kind) {
  5993. return compiler_error(c, loc,
  5994. "multiple starred expressions in sequence pattern");
  5995. }
  5996. }
  5997. if (!seen_star) {
  5998. ADDOP_I(c, loc, UNPACK_SEQUENCE, n);
  5999. }
  6000. return SUCCESS;
  6001. }
  6002. static int
  6003. pattern_helper_sequence_unpack(struct compiler *c, location loc,
  6004. asdl_pattern_seq *patterns, Py_ssize_t star,
  6005. pattern_context *pc)
  6006. {
  6007. RETURN_IF_ERROR(pattern_unpack_helper(c, loc, patterns));
  6008. Py_ssize_t size = asdl_seq_LEN(patterns);
  6009. // We've now got a bunch of new subjects on the stack. They need to remain
  6010. // there after each subpattern match:
  6011. pc->on_top += size;
  6012. for (Py_ssize_t i = 0; i < size; i++) {
  6013. // One less item to keep track of each time we loop through:
  6014. pc->on_top--;
  6015. pattern_ty pattern = asdl_seq_GET(patterns, i);
  6016. RETURN_IF_ERROR(compiler_pattern_subpattern(c, pattern, pc));
  6017. }
  6018. return SUCCESS;
  6019. }
  6020. // Like pattern_helper_sequence_unpack, but uses BINARY_SUBSCR instead of
  6021. // UNPACK_SEQUENCE / UNPACK_EX. This is more efficient for patterns with a
  6022. // starred wildcard like [first, *_] / [first, *_, last] / [*_, last] / etc.
  6023. static int
  6024. pattern_helper_sequence_subscr(struct compiler *c, location loc,
  6025. asdl_pattern_seq *patterns, Py_ssize_t star,
  6026. pattern_context *pc)
  6027. {
  6028. // We need to keep the subject around for extracting elements:
  6029. pc->on_top++;
  6030. Py_ssize_t size = asdl_seq_LEN(patterns);
  6031. for (Py_ssize_t i = 0; i < size; i++) {
  6032. pattern_ty pattern = asdl_seq_GET(patterns, i);
  6033. if (WILDCARD_CHECK(pattern)) {
  6034. continue;
  6035. }
  6036. if (i == star) {
  6037. assert(WILDCARD_STAR_CHECK(pattern));
  6038. continue;
  6039. }
  6040. ADDOP_I(c, loc, COPY, 1);
  6041. if (i < star) {
  6042. ADDOP_LOAD_CONST_NEW(c, loc, PyLong_FromSsize_t(i));
  6043. }
  6044. else {
  6045. // The subject may not support negative indexing! Compute a
  6046. // nonnegative index:
  6047. ADDOP(c, loc, GET_LEN);
  6048. ADDOP_LOAD_CONST_NEW(c, loc, PyLong_FromSsize_t(size - i));
  6049. ADDOP_BINARY(c, loc, Sub);
  6050. }
  6051. ADDOP(c, loc, BINARY_SUBSCR);
  6052. RETURN_IF_ERROR(compiler_pattern_subpattern(c, pattern, pc));
  6053. }
  6054. // Pop the subject, we're done with it:
  6055. pc->on_top--;
  6056. ADDOP(c, loc, POP_TOP);
  6057. return SUCCESS;
  6058. }
  6059. // Like compiler_pattern, but turn off checks for irrefutability.
  6060. static int
  6061. compiler_pattern_subpattern(struct compiler *c,
  6062. pattern_ty p, pattern_context *pc)
  6063. {
  6064. int allow_irrefutable = pc->allow_irrefutable;
  6065. pc->allow_irrefutable = 1;
  6066. RETURN_IF_ERROR(compiler_pattern(c, p, pc));
  6067. pc->allow_irrefutable = allow_irrefutable;
  6068. return SUCCESS;
  6069. }
  6070. static int
  6071. compiler_pattern_as(struct compiler *c, pattern_ty p, pattern_context *pc)
  6072. {
  6073. assert(p->kind == MatchAs_kind);
  6074. if (p->v.MatchAs.pattern == NULL) {
  6075. // An irrefutable match:
  6076. if (!pc->allow_irrefutable) {
  6077. if (p->v.MatchAs.name) {
  6078. const char *e = "name capture %R makes remaining patterns unreachable";
  6079. return compiler_error(c, LOC(p), e, p->v.MatchAs.name);
  6080. }
  6081. const char *e = "wildcard makes remaining patterns unreachable";
  6082. return compiler_error(c, LOC(p), e);
  6083. }
  6084. return pattern_helper_store_name(c, LOC(p), p->v.MatchAs.name, pc);
  6085. }
  6086. // Need to make a copy for (possibly) storing later:
  6087. pc->on_top++;
  6088. ADDOP_I(c, LOC(p), COPY, 1);
  6089. RETURN_IF_ERROR(compiler_pattern(c, p->v.MatchAs.pattern, pc));
  6090. // Success! Store it:
  6091. pc->on_top--;
  6092. RETURN_IF_ERROR(pattern_helper_store_name(c, LOC(p), p->v.MatchAs.name, pc));
  6093. return SUCCESS;
  6094. }
  6095. static int
  6096. compiler_pattern_star(struct compiler *c, pattern_ty p, pattern_context *pc)
  6097. {
  6098. assert(p->kind == MatchStar_kind);
  6099. RETURN_IF_ERROR(
  6100. pattern_helper_store_name(c, LOC(p), p->v.MatchStar.name, pc));
  6101. return SUCCESS;
  6102. }
  6103. static int
  6104. validate_kwd_attrs(struct compiler *c, asdl_identifier_seq *attrs, asdl_pattern_seq* patterns)
  6105. {
  6106. // Any errors will point to the pattern rather than the arg name as the
  6107. // parser is only supplying identifiers rather than Name or keyword nodes
  6108. Py_ssize_t nattrs = asdl_seq_LEN(attrs);
  6109. for (Py_ssize_t i = 0; i < nattrs; i++) {
  6110. identifier attr = ((identifier)asdl_seq_GET(attrs, i));
  6111. location loc = LOC((pattern_ty) asdl_seq_GET(patterns, i));
  6112. if (forbidden_name(c, loc, attr, Store)) {
  6113. return ERROR;
  6114. }
  6115. for (Py_ssize_t j = i + 1; j < nattrs; j++) {
  6116. identifier other = ((identifier)asdl_seq_GET(attrs, j));
  6117. if (!PyUnicode_Compare(attr, other)) {
  6118. location loc = LOC((pattern_ty) asdl_seq_GET(patterns, j));
  6119. compiler_error(c, loc, "attribute name repeated in class pattern: %U", attr);
  6120. return ERROR;
  6121. }
  6122. }
  6123. }
  6124. return SUCCESS;
  6125. }
  6126. static int
  6127. compiler_pattern_class(struct compiler *c, pattern_ty p, pattern_context *pc)
  6128. {
  6129. assert(p->kind == MatchClass_kind);
  6130. asdl_pattern_seq *patterns = p->v.MatchClass.patterns;
  6131. asdl_identifier_seq *kwd_attrs = p->v.MatchClass.kwd_attrs;
  6132. asdl_pattern_seq *kwd_patterns = p->v.MatchClass.kwd_patterns;
  6133. Py_ssize_t nargs = asdl_seq_LEN(patterns);
  6134. Py_ssize_t nattrs = asdl_seq_LEN(kwd_attrs);
  6135. Py_ssize_t nkwd_patterns = asdl_seq_LEN(kwd_patterns);
  6136. if (nattrs != nkwd_patterns) {
  6137. // AST validator shouldn't let this happen, but if it does,
  6138. // just fail, don't crash out of the interpreter
  6139. const char * e = "kwd_attrs (%d) / kwd_patterns (%d) length mismatch in class pattern";
  6140. return compiler_error(c, LOC(p), e, nattrs, nkwd_patterns);
  6141. }
  6142. if (INT_MAX < nargs || INT_MAX < nargs + nattrs - 1) {
  6143. const char *e = "too many sub-patterns in class pattern %R";
  6144. return compiler_error(c, LOC(p), e, p->v.MatchClass.cls);
  6145. }
  6146. if (nattrs) {
  6147. RETURN_IF_ERROR(validate_kwd_attrs(c, kwd_attrs, kwd_patterns));
  6148. }
  6149. VISIT(c, expr, p->v.MatchClass.cls);
  6150. PyObject *attr_names = PyTuple_New(nattrs);
  6151. if (attr_names == NULL) {
  6152. return ERROR;
  6153. }
  6154. Py_ssize_t i;
  6155. for (i = 0; i < nattrs; i++) {
  6156. PyObject *name = asdl_seq_GET(kwd_attrs, i);
  6157. PyTuple_SET_ITEM(attr_names, i, Py_NewRef(name));
  6158. }
  6159. ADDOP_LOAD_CONST_NEW(c, LOC(p), attr_names);
  6160. ADDOP_I(c, LOC(p), MATCH_CLASS, nargs);
  6161. ADDOP_I(c, LOC(p), COPY, 1);
  6162. ADDOP_LOAD_CONST(c, LOC(p), Py_None);
  6163. ADDOP_I(c, LOC(p), IS_OP, 1);
  6164. // TOS is now a tuple of (nargs + nattrs) attributes (or None):
  6165. pc->on_top++;
  6166. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6167. ADDOP_I(c, LOC(p), UNPACK_SEQUENCE, nargs + nattrs);
  6168. pc->on_top += nargs + nattrs - 1;
  6169. for (i = 0; i < nargs + nattrs; i++) {
  6170. pc->on_top--;
  6171. pattern_ty pattern;
  6172. if (i < nargs) {
  6173. // Positional:
  6174. pattern = asdl_seq_GET(patterns, i);
  6175. }
  6176. else {
  6177. // Keyword:
  6178. pattern = asdl_seq_GET(kwd_patterns, i - nargs);
  6179. }
  6180. if (WILDCARD_CHECK(pattern)) {
  6181. ADDOP(c, LOC(p), POP_TOP);
  6182. continue;
  6183. }
  6184. RETURN_IF_ERROR(compiler_pattern_subpattern(c, pattern, pc));
  6185. }
  6186. // Success! Pop the tuple of attributes:
  6187. return SUCCESS;
  6188. }
  6189. static int
  6190. compiler_pattern_mapping(struct compiler *c, pattern_ty p,
  6191. pattern_context *pc)
  6192. {
  6193. assert(p->kind == MatchMapping_kind);
  6194. asdl_expr_seq *keys = p->v.MatchMapping.keys;
  6195. asdl_pattern_seq *patterns = p->v.MatchMapping.patterns;
  6196. Py_ssize_t size = asdl_seq_LEN(keys);
  6197. Py_ssize_t npatterns = asdl_seq_LEN(patterns);
  6198. if (size != npatterns) {
  6199. // AST validator shouldn't let this happen, but if it does,
  6200. // just fail, don't crash out of the interpreter
  6201. const char * e = "keys (%d) / patterns (%d) length mismatch in mapping pattern";
  6202. return compiler_error(c, LOC(p), e, size, npatterns);
  6203. }
  6204. // We have a double-star target if "rest" is set
  6205. PyObject *star_target = p->v.MatchMapping.rest;
  6206. // We need to keep the subject on top during the mapping and length checks:
  6207. pc->on_top++;
  6208. ADDOP(c, LOC(p), MATCH_MAPPING);
  6209. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6210. if (!size && !star_target) {
  6211. // If the pattern is just "{}", we're done! Pop the subject:
  6212. pc->on_top--;
  6213. ADDOP(c, LOC(p), POP_TOP);
  6214. return SUCCESS;
  6215. }
  6216. if (size) {
  6217. // If the pattern has any keys in it, perform a length check:
  6218. ADDOP(c, LOC(p), GET_LEN);
  6219. ADDOP_LOAD_CONST_NEW(c, LOC(p), PyLong_FromSsize_t(size));
  6220. ADDOP_COMPARE(c, LOC(p), GtE);
  6221. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6222. }
  6223. if (INT_MAX < size - 1) {
  6224. return compiler_error(c, LOC(p), "too many sub-patterns in mapping pattern");
  6225. }
  6226. // Collect all of the keys into a tuple for MATCH_KEYS and
  6227. // **rest. They can either be dotted names or literals:
  6228. // Maintaining a set of Constant_kind kind keys allows us to raise a
  6229. // SyntaxError in the case of duplicates.
  6230. PyObject *seen = PySet_New(NULL);
  6231. if (seen == NULL) {
  6232. return ERROR;
  6233. }
  6234. // NOTE: goto error on failure in the loop below to avoid leaking `seen`
  6235. for (Py_ssize_t i = 0; i < size; i++) {
  6236. expr_ty key = asdl_seq_GET(keys, i);
  6237. if (key == NULL) {
  6238. const char *e = "can't use NULL keys in MatchMapping "
  6239. "(set 'rest' parameter instead)";
  6240. location loc = LOC((pattern_ty) asdl_seq_GET(patterns, i));
  6241. compiler_error(c, loc, e);
  6242. goto error;
  6243. }
  6244. if (key->kind == Constant_kind) {
  6245. int in_seen = PySet_Contains(seen, key->v.Constant.value);
  6246. if (in_seen < 0) {
  6247. goto error;
  6248. }
  6249. if (in_seen) {
  6250. const char *e = "mapping pattern checks duplicate key (%R)";
  6251. compiler_error(c, LOC(p), e, key->v.Constant.value);
  6252. goto error;
  6253. }
  6254. if (PySet_Add(seen, key->v.Constant.value)) {
  6255. goto error;
  6256. }
  6257. }
  6258. else if (key->kind != Attribute_kind) {
  6259. const char *e = "mapping pattern keys may only match literals and attribute lookups";
  6260. compiler_error(c, LOC(p), e);
  6261. goto error;
  6262. }
  6263. if (compiler_visit_expr(c, key) < 0) {
  6264. goto error;
  6265. }
  6266. }
  6267. // all keys have been checked; there are no duplicates
  6268. Py_DECREF(seen);
  6269. ADDOP_I(c, LOC(p), BUILD_TUPLE, size);
  6270. ADDOP(c, LOC(p), MATCH_KEYS);
  6271. // There's now a tuple of keys and a tuple of values on top of the subject:
  6272. pc->on_top += 2;
  6273. ADDOP_I(c, LOC(p), COPY, 1);
  6274. ADDOP_LOAD_CONST(c, LOC(p), Py_None);
  6275. ADDOP_I(c, LOC(p), IS_OP, 1);
  6276. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6277. // So far so good. Use that tuple of values on the stack to match
  6278. // sub-patterns against:
  6279. ADDOP_I(c, LOC(p), UNPACK_SEQUENCE, size);
  6280. pc->on_top += size - 1;
  6281. for (Py_ssize_t i = 0; i < size; i++) {
  6282. pc->on_top--;
  6283. pattern_ty pattern = asdl_seq_GET(patterns, i);
  6284. RETURN_IF_ERROR(compiler_pattern_subpattern(c, pattern, pc));
  6285. }
  6286. // If we get this far, it's a match! Whatever happens next should consume
  6287. // the tuple of keys and the subject:
  6288. pc->on_top -= 2;
  6289. if (star_target) {
  6290. // If we have a starred name, bind a dict of remaining items to it (this may
  6291. // seem a bit inefficient, but keys is rarely big enough to actually impact
  6292. // runtime):
  6293. // rest = dict(TOS1)
  6294. // for key in TOS:
  6295. // del rest[key]
  6296. ADDOP_I(c, LOC(p), BUILD_MAP, 0); // [subject, keys, empty]
  6297. ADDOP_I(c, LOC(p), SWAP, 3); // [empty, keys, subject]
  6298. ADDOP_I(c, LOC(p), DICT_UPDATE, 2); // [copy, keys]
  6299. ADDOP_I(c, LOC(p), UNPACK_SEQUENCE, size); // [copy, keys...]
  6300. while (size) {
  6301. ADDOP_I(c, LOC(p), COPY, 1 + size--); // [copy, keys..., copy]
  6302. ADDOP_I(c, LOC(p), SWAP, 2); // [copy, keys..., copy, key]
  6303. ADDOP(c, LOC(p), DELETE_SUBSCR); // [copy, keys...]
  6304. }
  6305. RETURN_IF_ERROR(pattern_helper_store_name(c, LOC(p), star_target, pc));
  6306. }
  6307. else {
  6308. ADDOP(c, LOC(p), POP_TOP); // Tuple of keys.
  6309. ADDOP(c, LOC(p), POP_TOP); // Subject.
  6310. }
  6311. return SUCCESS;
  6312. error:
  6313. Py_DECREF(seen);
  6314. return ERROR;
  6315. }
  6316. static int
  6317. compiler_pattern_or(struct compiler *c, pattern_ty p, pattern_context *pc)
  6318. {
  6319. assert(p->kind == MatchOr_kind);
  6320. NEW_JUMP_TARGET_LABEL(c, end);
  6321. Py_ssize_t size = asdl_seq_LEN(p->v.MatchOr.patterns);
  6322. assert(size > 1);
  6323. // We're going to be messing with pc. Keep the original info handy:
  6324. pattern_context old_pc = *pc;
  6325. Py_INCREF(pc->stores);
  6326. // control is the list of names bound by the first alternative. It is used
  6327. // for checking different name bindings in alternatives, and for correcting
  6328. // the order in which extracted elements are placed on the stack.
  6329. PyObject *control = NULL;
  6330. // NOTE: We can't use returning macros anymore! goto error on error.
  6331. for (Py_ssize_t i = 0; i < size; i++) {
  6332. pattern_ty alt = asdl_seq_GET(p->v.MatchOr.patterns, i);
  6333. PyObject *pc_stores = PyList_New(0);
  6334. if (pc_stores == NULL) {
  6335. goto error;
  6336. }
  6337. Py_SETREF(pc->stores, pc_stores);
  6338. // An irrefutable sub-pattern must be last, if it is allowed at all:
  6339. pc->allow_irrefutable = (i == size - 1) && old_pc.allow_irrefutable;
  6340. pc->fail_pop = NULL;
  6341. pc->fail_pop_size = 0;
  6342. pc->on_top = 0;
  6343. if (codegen_addop_i(INSTR_SEQUENCE(c), COPY, 1, LOC(alt)) < 0 ||
  6344. compiler_pattern(c, alt, pc) < 0) {
  6345. goto error;
  6346. }
  6347. // Success!
  6348. Py_ssize_t nstores = PyList_GET_SIZE(pc->stores);
  6349. if (!i) {
  6350. // This is the first alternative, so save its stores as a "control"
  6351. // for the others (they can't bind a different set of names, and
  6352. // might need to be reordered):
  6353. assert(control == NULL);
  6354. control = Py_NewRef(pc->stores);
  6355. }
  6356. else if (nstores != PyList_GET_SIZE(control)) {
  6357. goto diff;
  6358. }
  6359. else if (nstores) {
  6360. // There were captures. Check to see if we differ from control:
  6361. Py_ssize_t icontrol = nstores;
  6362. while (icontrol--) {
  6363. PyObject *name = PyList_GET_ITEM(control, icontrol);
  6364. Py_ssize_t istores = PySequence_Index(pc->stores, name);
  6365. if (istores < 0) {
  6366. PyErr_Clear();
  6367. goto diff;
  6368. }
  6369. if (icontrol != istores) {
  6370. // Reorder the names on the stack to match the order of the
  6371. // names in control. There's probably a better way of doing
  6372. // this; the current solution is potentially very
  6373. // inefficient when each alternative subpattern binds lots
  6374. // of names in different orders. It's fine for reasonable
  6375. // cases, though, and the peephole optimizer will ensure
  6376. // that the final code is as efficient as possible.
  6377. assert(istores < icontrol);
  6378. Py_ssize_t rotations = istores + 1;
  6379. // Perform the same rotation on pc->stores:
  6380. PyObject *rotated = PyList_GetSlice(pc->stores, 0,
  6381. rotations);
  6382. if (rotated == NULL ||
  6383. PyList_SetSlice(pc->stores, 0, rotations, NULL) ||
  6384. PyList_SetSlice(pc->stores, icontrol - istores,
  6385. icontrol - istores, rotated))
  6386. {
  6387. Py_XDECREF(rotated);
  6388. goto error;
  6389. }
  6390. Py_DECREF(rotated);
  6391. // That just did:
  6392. // rotated = pc_stores[:rotations]
  6393. // del pc_stores[:rotations]
  6394. // pc_stores[icontrol-istores:icontrol-istores] = rotated
  6395. // Do the same thing to the stack, using several
  6396. // rotations:
  6397. while (rotations--) {
  6398. if (pattern_helper_rotate(c, LOC(alt), icontrol + 1) < 0) {
  6399. goto error;
  6400. }
  6401. }
  6402. }
  6403. }
  6404. }
  6405. assert(control);
  6406. if (codegen_addop_j(INSTR_SEQUENCE(c), LOC(alt), JUMP, end) < 0 ||
  6407. emit_and_reset_fail_pop(c, LOC(alt), pc) < 0)
  6408. {
  6409. goto error;
  6410. }
  6411. }
  6412. Py_DECREF(pc->stores);
  6413. *pc = old_pc;
  6414. Py_INCREF(pc->stores);
  6415. // Need to NULL this for the PyObject_Free call in the error block.
  6416. old_pc.fail_pop = NULL;
  6417. // No match. Pop the remaining copy of the subject and fail:
  6418. if (codegen_addop_noarg(INSTR_SEQUENCE(c), POP_TOP, LOC(p)) < 0 ||
  6419. jump_to_fail_pop(c, LOC(p), pc, JUMP) < 0) {
  6420. goto error;
  6421. }
  6422. USE_LABEL(c, end);
  6423. Py_ssize_t nstores = PyList_GET_SIZE(control);
  6424. // There's a bunch of stuff on the stack between where the new stores
  6425. // are and where they need to be:
  6426. // - The other stores.
  6427. // - A copy of the subject.
  6428. // - Anything else that may be on top of the stack.
  6429. // - Any previous stores we've already stashed away on the stack.
  6430. Py_ssize_t nrots = nstores + 1 + pc->on_top + PyList_GET_SIZE(pc->stores);
  6431. for (Py_ssize_t i = 0; i < nstores; i++) {
  6432. // Rotate this capture to its proper place on the stack:
  6433. if (pattern_helper_rotate(c, LOC(p), nrots) < 0) {
  6434. goto error;
  6435. }
  6436. // Update the list of previous stores with this new name, checking for
  6437. // duplicates:
  6438. PyObject *name = PyList_GET_ITEM(control, i);
  6439. int dupe = PySequence_Contains(pc->stores, name);
  6440. if (dupe < 0) {
  6441. goto error;
  6442. }
  6443. if (dupe) {
  6444. compiler_error_duplicate_store(c, LOC(p), name);
  6445. goto error;
  6446. }
  6447. if (PyList_Append(pc->stores, name)) {
  6448. goto error;
  6449. }
  6450. }
  6451. Py_DECREF(old_pc.stores);
  6452. Py_DECREF(control);
  6453. // NOTE: Returning macros are safe again.
  6454. // Pop the copy of the subject:
  6455. ADDOP(c, LOC(p), POP_TOP);
  6456. return SUCCESS;
  6457. diff:
  6458. compiler_error(c, LOC(p), "alternative patterns bind different names");
  6459. error:
  6460. PyObject_Free(old_pc.fail_pop);
  6461. Py_DECREF(old_pc.stores);
  6462. Py_XDECREF(control);
  6463. return ERROR;
  6464. }
  6465. static int
  6466. compiler_pattern_sequence(struct compiler *c, pattern_ty p,
  6467. pattern_context *pc)
  6468. {
  6469. assert(p->kind == MatchSequence_kind);
  6470. asdl_pattern_seq *patterns = p->v.MatchSequence.patterns;
  6471. Py_ssize_t size = asdl_seq_LEN(patterns);
  6472. Py_ssize_t star = -1;
  6473. int only_wildcard = 1;
  6474. int star_wildcard = 0;
  6475. // Find a starred name, if it exists. There may be at most one:
  6476. for (Py_ssize_t i = 0; i < size; i++) {
  6477. pattern_ty pattern = asdl_seq_GET(patterns, i);
  6478. if (pattern->kind == MatchStar_kind) {
  6479. if (star >= 0) {
  6480. const char *e = "multiple starred names in sequence pattern";
  6481. return compiler_error(c, LOC(p), e);
  6482. }
  6483. star_wildcard = WILDCARD_STAR_CHECK(pattern);
  6484. only_wildcard &= star_wildcard;
  6485. star = i;
  6486. continue;
  6487. }
  6488. only_wildcard &= WILDCARD_CHECK(pattern);
  6489. }
  6490. // We need to keep the subject on top during the sequence and length checks:
  6491. pc->on_top++;
  6492. ADDOP(c, LOC(p), MATCH_SEQUENCE);
  6493. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6494. if (star < 0) {
  6495. // No star: len(subject) == size
  6496. ADDOP(c, LOC(p), GET_LEN);
  6497. ADDOP_LOAD_CONST_NEW(c, LOC(p), PyLong_FromSsize_t(size));
  6498. ADDOP_COMPARE(c, LOC(p), Eq);
  6499. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6500. }
  6501. else if (size > 1) {
  6502. // Star: len(subject) >= size - 1
  6503. ADDOP(c, LOC(p), GET_LEN);
  6504. ADDOP_LOAD_CONST_NEW(c, LOC(p), PyLong_FromSsize_t(size - 1));
  6505. ADDOP_COMPARE(c, LOC(p), GtE);
  6506. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6507. }
  6508. // Whatever comes next should consume the subject:
  6509. pc->on_top--;
  6510. if (only_wildcard) {
  6511. // Patterns like: [] / [_] / [_, _] / [*_] / [_, *_] / [_, _, *_] / etc.
  6512. ADDOP(c, LOC(p), POP_TOP);
  6513. }
  6514. else if (star_wildcard) {
  6515. RETURN_IF_ERROR(pattern_helper_sequence_subscr(c, LOC(p), patterns, star, pc));
  6516. }
  6517. else {
  6518. RETURN_IF_ERROR(pattern_helper_sequence_unpack(c, LOC(p), patterns, star, pc));
  6519. }
  6520. return SUCCESS;
  6521. }
  6522. static int
  6523. compiler_pattern_value(struct compiler *c, pattern_ty p, pattern_context *pc)
  6524. {
  6525. assert(p->kind == MatchValue_kind);
  6526. expr_ty value = p->v.MatchValue.value;
  6527. if (!MATCH_VALUE_EXPR(value)) {
  6528. const char *e = "patterns may only match literals and attribute lookups";
  6529. return compiler_error(c, LOC(p), e);
  6530. }
  6531. VISIT(c, expr, value);
  6532. ADDOP_COMPARE(c, LOC(p), Eq);
  6533. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6534. return SUCCESS;
  6535. }
  6536. static int
  6537. compiler_pattern_singleton(struct compiler *c, pattern_ty p, pattern_context *pc)
  6538. {
  6539. assert(p->kind == MatchSingleton_kind);
  6540. ADDOP_LOAD_CONST(c, LOC(p), p->v.MatchSingleton.value);
  6541. ADDOP_COMPARE(c, LOC(p), Is);
  6542. RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
  6543. return SUCCESS;
  6544. }
  6545. static int
  6546. compiler_pattern(struct compiler *c, pattern_ty p, pattern_context *pc)
  6547. {
  6548. switch (p->kind) {
  6549. case MatchValue_kind:
  6550. return compiler_pattern_value(c, p, pc);
  6551. case MatchSingleton_kind:
  6552. return compiler_pattern_singleton(c, p, pc);
  6553. case MatchSequence_kind:
  6554. return compiler_pattern_sequence(c, p, pc);
  6555. case MatchMapping_kind:
  6556. return compiler_pattern_mapping(c, p, pc);
  6557. case MatchClass_kind:
  6558. return compiler_pattern_class(c, p, pc);
  6559. case MatchStar_kind:
  6560. return compiler_pattern_star(c, p, pc);
  6561. case MatchAs_kind:
  6562. return compiler_pattern_as(c, p, pc);
  6563. case MatchOr_kind:
  6564. return compiler_pattern_or(c, p, pc);
  6565. }
  6566. // AST validator shouldn't let this happen, but if it does,
  6567. // just fail, don't crash out of the interpreter
  6568. const char *e = "invalid match pattern node in AST (kind=%d)";
  6569. return compiler_error(c, LOC(p), e, p->kind);
  6570. }
  6571. static int
  6572. compiler_match_inner(struct compiler *c, stmt_ty s, pattern_context *pc)
  6573. {
  6574. VISIT(c, expr, s->v.Match.subject);
  6575. NEW_JUMP_TARGET_LABEL(c, end);
  6576. Py_ssize_t cases = asdl_seq_LEN(s->v.Match.cases);
  6577. assert(cases > 0);
  6578. match_case_ty m = asdl_seq_GET(s->v.Match.cases, cases - 1);
  6579. int has_default = WILDCARD_CHECK(m->pattern) && 1 < cases;
  6580. for (Py_ssize_t i = 0; i < cases - has_default; i++) {
  6581. m = asdl_seq_GET(s->v.Match.cases, i);
  6582. // Only copy the subject if we're *not* on the last case:
  6583. if (i != cases - has_default - 1) {
  6584. ADDOP_I(c, LOC(m->pattern), COPY, 1);
  6585. }
  6586. pc->stores = PyList_New(0);
  6587. if (pc->stores == NULL) {
  6588. return ERROR;
  6589. }
  6590. // Irrefutable cases must be either guarded, last, or both:
  6591. pc->allow_irrefutable = m->guard != NULL || i == cases - 1;
  6592. pc->fail_pop = NULL;
  6593. pc->fail_pop_size = 0;
  6594. pc->on_top = 0;
  6595. // NOTE: Can't use returning macros here (they'll leak pc->stores)!
  6596. if (compiler_pattern(c, m->pattern, pc) < 0) {
  6597. Py_DECREF(pc->stores);
  6598. return ERROR;
  6599. }
  6600. assert(!pc->on_top);
  6601. // It's a match! Store all of the captured names (they're on the stack).
  6602. Py_ssize_t nstores = PyList_GET_SIZE(pc->stores);
  6603. for (Py_ssize_t n = 0; n < nstores; n++) {
  6604. PyObject *name = PyList_GET_ITEM(pc->stores, n);
  6605. if (compiler_nameop(c, LOC(m->pattern), name, Store) < 0) {
  6606. Py_DECREF(pc->stores);
  6607. return ERROR;
  6608. }
  6609. }
  6610. Py_DECREF(pc->stores);
  6611. // NOTE: Returning macros are safe again.
  6612. if (m->guard) {
  6613. RETURN_IF_ERROR(ensure_fail_pop(c, pc, 0));
  6614. RETURN_IF_ERROR(compiler_jump_if(c, LOC(m->pattern), m->guard, pc->fail_pop[0], 0));
  6615. }
  6616. // Success! Pop the subject off, we're done with it:
  6617. if (i != cases - has_default - 1) {
  6618. ADDOP(c, LOC(m->pattern), POP_TOP);
  6619. }
  6620. VISIT_SEQ(c, stmt, m->body);
  6621. ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
  6622. // If the pattern fails to match, we want the line number of the
  6623. // cleanup to be associated with the failed pattern, not the last line
  6624. // of the body
  6625. RETURN_IF_ERROR(emit_and_reset_fail_pop(c, LOC(m->pattern), pc));
  6626. }
  6627. if (has_default) {
  6628. // A trailing "case _" is common, and lets us save a bit of redundant
  6629. // pushing and popping in the loop above:
  6630. m = asdl_seq_GET(s->v.Match.cases, cases - 1);
  6631. if (cases == 1) {
  6632. // No matches. Done with the subject:
  6633. ADDOP(c, LOC(m->pattern), POP_TOP);
  6634. }
  6635. else {
  6636. // Show line coverage for default case (it doesn't create bytecode)
  6637. ADDOP(c, LOC(m->pattern), NOP);
  6638. }
  6639. if (m->guard) {
  6640. RETURN_IF_ERROR(compiler_jump_if(c, LOC(m->pattern), m->guard, end, 0));
  6641. }
  6642. VISIT_SEQ(c, stmt, m->body);
  6643. }
  6644. USE_LABEL(c, end);
  6645. return SUCCESS;
  6646. }
  6647. static int
  6648. compiler_match(struct compiler *c, stmt_ty s)
  6649. {
  6650. pattern_context pc;
  6651. pc.fail_pop = NULL;
  6652. int result = compiler_match_inner(c, s, &pc);
  6653. PyObject_Free(pc.fail_pop);
  6654. return result;
  6655. }
  6656. #undef WILDCARD_CHECK
  6657. #undef WILDCARD_STAR_CHECK
  6658. static PyObject *
  6659. consts_dict_keys_inorder(PyObject *dict)
  6660. {
  6661. PyObject *consts, *k, *v;
  6662. Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
  6663. consts = PyList_New(size); /* PyCode_Optimize() requires a list */
  6664. if (consts == NULL)
  6665. return NULL;
  6666. while (PyDict_Next(dict, &pos, &k, &v)) {
  6667. i = PyLong_AS_LONG(v);
  6668. /* The keys of the dictionary can be tuples wrapping a constant.
  6669. * (see dict_add_o and _PyCode_ConstantKey). In that case
  6670. * the object we want is always second. */
  6671. if (PyTuple_CheckExact(k)) {
  6672. k = PyTuple_GET_ITEM(k, 1);
  6673. }
  6674. assert(i < size);
  6675. assert(i >= 0);
  6676. PyList_SET_ITEM(consts, i, Py_NewRef(k));
  6677. }
  6678. return consts;
  6679. }
  6680. static int
  6681. compute_code_flags(struct compiler *c)
  6682. {
  6683. PySTEntryObject *ste = c->u->u_ste;
  6684. int flags = 0;
  6685. if (_PyST_IsFunctionLike(c->u->u_ste)) {
  6686. flags |= CO_NEWLOCALS | CO_OPTIMIZED;
  6687. if (ste->ste_nested)
  6688. flags |= CO_NESTED;
  6689. if (ste->ste_generator && !ste->ste_coroutine)
  6690. flags |= CO_GENERATOR;
  6691. if (!ste->ste_generator && ste->ste_coroutine)
  6692. flags |= CO_COROUTINE;
  6693. if (ste->ste_generator && ste->ste_coroutine)
  6694. flags |= CO_ASYNC_GENERATOR;
  6695. if (ste->ste_varargs)
  6696. flags |= CO_VARARGS;
  6697. if (ste->ste_varkeywords)
  6698. flags |= CO_VARKEYWORDS;
  6699. }
  6700. /* (Only) inherit compilerflags in PyCF_MASK */
  6701. flags |= (c->c_flags.cf_flags & PyCF_MASK);
  6702. if ((IS_TOP_LEVEL_AWAIT(c)) &&
  6703. ste->ste_coroutine &&
  6704. !ste->ste_generator) {
  6705. flags |= CO_COROUTINE;
  6706. }
  6707. return flags;
  6708. }
  6709. // Merge *obj* with constant cache.
  6710. // Unlike merge_consts_recursive(), this function doesn't work recursively.
  6711. int
  6712. _PyCompile_ConstCacheMergeOne(PyObject *const_cache, PyObject **obj)
  6713. {
  6714. assert(PyDict_CheckExact(const_cache));
  6715. PyObject *key = _PyCode_ConstantKey(*obj);
  6716. if (key == NULL) {
  6717. return ERROR;
  6718. }
  6719. // t is borrowed reference
  6720. PyObject *t = PyDict_SetDefault(const_cache, key, key);
  6721. Py_DECREF(key);
  6722. if (t == NULL) {
  6723. return ERROR;
  6724. }
  6725. if (t == key) { // obj is new constant.
  6726. return SUCCESS;
  6727. }
  6728. if (PyTuple_CheckExact(t)) {
  6729. // t is still borrowed reference
  6730. t = PyTuple_GET_ITEM(t, 1);
  6731. }
  6732. Py_SETREF(*obj, Py_NewRef(t));
  6733. return SUCCESS;
  6734. }
  6735. static int *
  6736. build_cellfixedoffsets(_PyCompile_CodeUnitMetadata *umd)
  6737. {
  6738. int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
  6739. int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
  6740. int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
  6741. int noffsets = ncellvars + nfreevars;
  6742. int *fixed = PyMem_New(int, noffsets);
  6743. if (fixed == NULL) {
  6744. PyErr_NoMemory();
  6745. return NULL;
  6746. }
  6747. for (int i = 0; i < noffsets; i++) {
  6748. fixed[i] = nlocals + i;
  6749. }
  6750. PyObject *varname, *cellindex;
  6751. Py_ssize_t pos = 0;
  6752. while (PyDict_Next(umd->u_cellvars, &pos, &varname, &cellindex)) {
  6753. PyObject *varindex = PyDict_GetItem(umd->u_varnames, varname);
  6754. if (varindex != NULL) {
  6755. assert(PyLong_AS_LONG(cellindex) < INT_MAX);
  6756. assert(PyLong_AS_LONG(varindex) < INT_MAX);
  6757. int oldindex = (int)PyLong_AS_LONG(cellindex);
  6758. int argoffset = (int)PyLong_AS_LONG(varindex);
  6759. fixed[oldindex] = argoffset;
  6760. }
  6761. }
  6762. return fixed;
  6763. }
  6764. static int
  6765. insert_prefix_instructions(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock,
  6766. int *fixed, int nfreevars, int code_flags)
  6767. {
  6768. assert(umd->u_firstlineno > 0);
  6769. /* Add the generator prefix instructions. */
  6770. if (code_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
  6771. cfg_instr make_gen = {
  6772. .i_opcode = RETURN_GENERATOR,
  6773. .i_oparg = 0,
  6774. .i_loc = LOCATION(umd->u_firstlineno, umd->u_firstlineno, -1, -1),
  6775. .i_target = NULL,
  6776. };
  6777. RETURN_IF_ERROR(_PyBasicblock_InsertInstruction(entryblock, 0, &make_gen));
  6778. cfg_instr pop_top = {
  6779. .i_opcode = POP_TOP,
  6780. .i_oparg = 0,
  6781. .i_loc = NO_LOCATION,
  6782. .i_target = NULL,
  6783. };
  6784. RETURN_IF_ERROR(_PyBasicblock_InsertInstruction(entryblock, 1, &pop_top));
  6785. }
  6786. /* Set up cells for any variable that escapes, to be put in a closure. */
  6787. const int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
  6788. if (ncellvars) {
  6789. // umd->u_cellvars has the cells out of order so we sort them
  6790. // before adding the MAKE_CELL instructions. Note that we
  6791. // adjust for arg cells, which come first.
  6792. const int nvars = ncellvars + (int)PyDict_GET_SIZE(umd->u_varnames);
  6793. int *sorted = PyMem_RawCalloc(nvars, sizeof(int));
  6794. if (sorted == NULL) {
  6795. PyErr_NoMemory();
  6796. return ERROR;
  6797. }
  6798. for (int i = 0; i < ncellvars; i++) {
  6799. sorted[fixed[i]] = i + 1;
  6800. }
  6801. for (int i = 0, ncellsused = 0; ncellsused < ncellvars; i++) {
  6802. int oldindex = sorted[i] - 1;
  6803. if (oldindex == -1) {
  6804. continue;
  6805. }
  6806. cfg_instr make_cell = {
  6807. .i_opcode = MAKE_CELL,
  6808. // This will get fixed in offset_derefs().
  6809. .i_oparg = oldindex,
  6810. .i_loc = NO_LOCATION,
  6811. .i_target = NULL,
  6812. };
  6813. if (_PyBasicblock_InsertInstruction(entryblock, ncellsused, &make_cell) < 0) {
  6814. PyMem_RawFree(sorted);
  6815. return ERROR;
  6816. }
  6817. ncellsused += 1;
  6818. }
  6819. PyMem_RawFree(sorted);
  6820. }
  6821. if (nfreevars) {
  6822. cfg_instr copy_frees = {
  6823. .i_opcode = COPY_FREE_VARS,
  6824. .i_oparg = nfreevars,
  6825. .i_loc = NO_LOCATION,
  6826. .i_target = NULL,
  6827. };
  6828. RETURN_IF_ERROR(_PyBasicblock_InsertInstruction(entryblock, 0, &copy_frees));
  6829. }
  6830. return SUCCESS;
  6831. }
  6832. static int
  6833. fix_cell_offsets(_PyCompile_CodeUnitMetadata *umd, basicblock *entryblock, int *fixedmap)
  6834. {
  6835. int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
  6836. int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
  6837. int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
  6838. int noffsets = ncellvars + nfreevars;
  6839. // First deal with duplicates (arg cells).
  6840. int numdropped = 0;
  6841. for (int i = 0; i < noffsets ; i++) {
  6842. if (fixedmap[i] == i + nlocals) {
  6843. fixedmap[i] -= numdropped;
  6844. }
  6845. else {
  6846. // It was a duplicate (cell/arg).
  6847. numdropped += 1;
  6848. }
  6849. }
  6850. // Then update offsets, either relative to locals or by cell2arg.
  6851. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  6852. for (int i = 0; i < b->b_iused; i++) {
  6853. cfg_instr *inst = &b->b_instr[i];
  6854. // This is called before extended args are generated.
  6855. assert(inst->i_opcode != EXTENDED_ARG);
  6856. int oldoffset = inst->i_oparg;
  6857. switch(inst->i_opcode) {
  6858. case MAKE_CELL:
  6859. case LOAD_CLOSURE:
  6860. case LOAD_DEREF:
  6861. case STORE_DEREF:
  6862. case DELETE_DEREF:
  6863. case LOAD_FROM_DICT_OR_DEREF:
  6864. assert(oldoffset >= 0);
  6865. assert(oldoffset < noffsets);
  6866. assert(fixedmap[oldoffset] >= 0);
  6867. inst->i_oparg = fixedmap[oldoffset];
  6868. }
  6869. }
  6870. }
  6871. return numdropped;
  6872. }
  6873. static int
  6874. prepare_localsplus(_PyCompile_CodeUnitMetadata *umd, cfg_builder *g, int code_flags)
  6875. {
  6876. assert(PyDict_GET_SIZE(umd->u_varnames) < INT_MAX);
  6877. assert(PyDict_GET_SIZE(umd->u_cellvars) < INT_MAX);
  6878. assert(PyDict_GET_SIZE(umd->u_freevars) < INT_MAX);
  6879. int nlocals = (int)PyDict_GET_SIZE(umd->u_varnames);
  6880. int ncellvars = (int)PyDict_GET_SIZE(umd->u_cellvars);
  6881. int nfreevars = (int)PyDict_GET_SIZE(umd->u_freevars);
  6882. assert(INT_MAX - nlocals - ncellvars > 0);
  6883. assert(INT_MAX - nlocals - ncellvars - nfreevars > 0);
  6884. int nlocalsplus = nlocals + ncellvars + nfreevars;
  6885. int* cellfixedoffsets = build_cellfixedoffsets(umd);
  6886. if (cellfixedoffsets == NULL) {
  6887. return ERROR;
  6888. }
  6889. // This must be called before fix_cell_offsets().
  6890. if (insert_prefix_instructions(umd, g->g_entryblock, cellfixedoffsets, nfreevars, code_flags)) {
  6891. PyMem_Free(cellfixedoffsets);
  6892. return ERROR;
  6893. }
  6894. int numdropped = fix_cell_offsets(umd, g->g_entryblock, cellfixedoffsets);
  6895. PyMem_Free(cellfixedoffsets); // At this point we're done with it.
  6896. cellfixedoffsets = NULL;
  6897. if (numdropped < 0) {
  6898. return ERROR;
  6899. }
  6900. nlocalsplus -= numdropped;
  6901. return nlocalsplus;
  6902. }
  6903. static int
  6904. add_return_at_end(struct compiler *c, int addNone)
  6905. {
  6906. /* Make sure every instruction stream that falls off the end returns None.
  6907. * This also ensures that no jump target offsets are out of bounds.
  6908. */
  6909. if (addNone) {
  6910. ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
  6911. }
  6912. ADDOP(c, NO_LOCATION, RETURN_VALUE);
  6913. return SUCCESS;
  6914. }
  6915. static int cfg_to_instr_sequence(cfg_builder *g, instr_sequence *seq);
  6916. static PyCodeObject *
  6917. optimize_and_assemble_code_unit(struct compiler_unit *u, PyObject *const_cache,
  6918. int code_flags, PyObject *filename)
  6919. {
  6920. instr_sequence optimized_instrs;
  6921. memset(&optimized_instrs, 0, sizeof(instr_sequence));
  6922. PyCodeObject *co = NULL;
  6923. PyObject *consts = consts_dict_keys_inorder(u->u_metadata.u_consts);
  6924. if (consts == NULL) {
  6925. return NULL;
  6926. }
  6927. cfg_builder g;
  6928. if (instr_sequence_to_cfg(&u->u_instr_sequence, &g) < 0) {
  6929. goto error;
  6930. }
  6931. int nparams = (int)PyList_GET_SIZE(u->u_ste->ste_varnames);
  6932. int nlocals = (int)PyDict_GET_SIZE(u->u_metadata.u_varnames);
  6933. assert(u->u_metadata.u_firstlineno);
  6934. if (_PyCfg_OptimizeCodeUnit(&g, consts, const_cache, code_flags, nlocals,
  6935. nparams, u->u_metadata.u_firstlineno) < 0) {
  6936. goto error;
  6937. }
  6938. /** Assembly **/
  6939. int nlocalsplus = prepare_localsplus(&u->u_metadata, &g, code_flags);
  6940. if (nlocalsplus < 0) {
  6941. goto error;
  6942. }
  6943. int maxdepth = _PyCfg_Stackdepth(g.g_entryblock, code_flags);
  6944. if (maxdepth < 0) {
  6945. goto error;
  6946. }
  6947. _PyCfg_ConvertPseudoOps(g.g_entryblock);
  6948. /* Order of basic blocks must have been determined by now */
  6949. if (_PyCfg_ResolveJumps(&g) < 0) {
  6950. goto error;
  6951. }
  6952. /* Can't modify the bytecode after computing jump offsets. */
  6953. if (cfg_to_instr_sequence(&g, &optimized_instrs) < 0) {
  6954. goto error;
  6955. }
  6956. co = _PyAssemble_MakeCodeObject(&u->u_metadata, const_cache, consts,
  6957. maxdepth, &optimized_instrs, nlocalsplus,
  6958. code_flags, filename);
  6959. error:
  6960. Py_XDECREF(consts);
  6961. instr_sequence_fini(&optimized_instrs);
  6962. _PyCfgBuilder_Fini(&g);
  6963. return co;
  6964. }
  6965. static PyCodeObject *
  6966. optimize_and_assemble(struct compiler *c, int addNone)
  6967. {
  6968. struct compiler_unit *u = c->u;
  6969. PyObject *const_cache = c->c_const_cache;
  6970. PyObject *filename = c->c_filename;
  6971. int code_flags = compute_code_flags(c);
  6972. if (code_flags < 0) {
  6973. return NULL;
  6974. }
  6975. if (add_return_at_end(c, addNone) < 0) {
  6976. return NULL;
  6977. }
  6978. return optimize_and_assemble_code_unit(u, const_cache, code_flags, filename);
  6979. }
  6980. static int
  6981. cfg_to_instr_sequence(cfg_builder *g, instr_sequence *seq)
  6982. {
  6983. int lbl = 0;
  6984. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  6985. b->b_label = (jump_target_label){lbl};
  6986. lbl += b->b_iused;
  6987. }
  6988. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  6989. RETURN_IF_ERROR(instr_sequence_use_label(seq, b->b_label.id));
  6990. for (int i = 0; i < b->b_iused; i++) {
  6991. cfg_instr *instr = &b->b_instr[i];
  6992. RETURN_IF_ERROR(
  6993. instr_sequence_addop(seq, instr->i_opcode, instr->i_oparg, instr->i_loc));
  6994. _PyCompile_ExceptHandlerInfo *hi = &seq->s_instrs[seq->s_used-1].i_except_handler_info;
  6995. if (instr->i_except != NULL) {
  6996. hi->h_offset = instr->i_except->b_offset;
  6997. hi->h_startdepth = instr->i_except->b_startdepth;
  6998. hi->h_preserve_lasti = instr->i_except->b_preserve_lasti;
  6999. }
  7000. else {
  7001. hi->h_offset = -1;
  7002. }
  7003. }
  7004. }
  7005. return SUCCESS;
  7006. }
  7007. /* Access to compiler optimizations for unit tests.
  7008. *
  7009. * _PyCompile_CodeGen takes and AST, applies code-gen and
  7010. * returns the unoptimized CFG as an instruction list.
  7011. *
  7012. * _PyCompile_OptimizeCfg takes an instruction list, constructs
  7013. * a CFG, optimizes it and converts back to an instruction list.
  7014. *
  7015. * An instruction list is a PyList where each item is either
  7016. * a tuple describing a single instruction:
  7017. * (opcode, oparg, lineno, end_lineno, col, end_col), or
  7018. * a jump target label marking the beginning of a basic block.
  7019. */
  7020. static int
  7021. instructions_to_instr_sequence(PyObject *instructions, instr_sequence *seq)
  7022. {
  7023. assert(PyList_Check(instructions));
  7024. Py_ssize_t num_insts = PyList_GET_SIZE(instructions);
  7025. bool *is_target = PyMem_Calloc(num_insts, sizeof(bool));
  7026. if (is_target == NULL) {
  7027. return ERROR;
  7028. }
  7029. for (Py_ssize_t i = 0; i < num_insts; i++) {
  7030. PyObject *item = PyList_GET_ITEM(instructions, i);
  7031. if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 6) {
  7032. PyErr_SetString(PyExc_ValueError, "expected a 6-tuple");
  7033. goto error;
  7034. }
  7035. int opcode = PyLong_AsLong(PyTuple_GET_ITEM(item, 0));
  7036. if (PyErr_Occurred()) {
  7037. goto error;
  7038. }
  7039. if (HAS_TARGET(opcode)) {
  7040. int oparg = PyLong_AsLong(PyTuple_GET_ITEM(item, 1));
  7041. if (PyErr_Occurred()) {
  7042. goto error;
  7043. }
  7044. if (oparg < 0 || oparg >= num_insts) {
  7045. PyErr_SetString(PyExc_ValueError, "label out of range");
  7046. goto error;
  7047. }
  7048. is_target[oparg] = true;
  7049. }
  7050. }
  7051. for (int i = 0; i < num_insts; i++) {
  7052. if (is_target[i]) {
  7053. if (instr_sequence_use_label(seq, i) < 0) {
  7054. goto error;
  7055. }
  7056. }
  7057. PyObject *item = PyList_GET_ITEM(instructions, i);
  7058. if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 6) {
  7059. PyErr_SetString(PyExc_ValueError, "expected a 6-tuple");
  7060. goto error;
  7061. }
  7062. int opcode = PyLong_AsLong(PyTuple_GET_ITEM(item, 0));
  7063. if (PyErr_Occurred()) {
  7064. goto error;
  7065. }
  7066. int oparg;
  7067. if (HAS_ARG(opcode)) {
  7068. oparg = PyLong_AsLong(PyTuple_GET_ITEM(item, 1));
  7069. if (PyErr_Occurred()) {
  7070. goto error;
  7071. }
  7072. }
  7073. else {
  7074. oparg = 0;
  7075. }
  7076. location loc;
  7077. loc.lineno = PyLong_AsLong(PyTuple_GET_ITEM(item, 2));
  7078. if (PyErr_Occurred()) {
  7079. goto error;
  7080. }
  7081. loc.end_lineno = PyLong_AsLong(PyTuple_GET_ITEM(item, 3));
  7082. if (PyErr_Occurred()) {
  7083. goto error;
  7084. }
  7085. loc.col_offset = PyLong_AsLong(PyTuple_GET_ITEM(item, 4));
  7086. if (PyErr_Occurred()) {
  7087. goto error;
  7088. }
  7089. loc.end_col_offset = PyLong_AsLong(PyTuple_GET_ITEM(item, 5));
  7090. if (PyErr_Occurred()) {
  7091. goto error;
  7092. }
  7093. if (instr_sequence_addop(seq, opcode, oparg, loc) < 0) {
  7094. goto error;
  7095. }
  7096. }
  7097. PyMem_Free(is_target);
  7098. return SUCCESS;
  7099. error:
  7100. PyMem_Free(is_target);
  7101. return ERROR;
  7102. }
  7103. static int
  7104. instructions_to_cfg(PyObject *instructions, cfg_builder *g)
  7105. {
  7106. instr_sequence seq;
  7107. memset(&seq, 0, sizeof(instr_sequence));
  7108. if (instructions_to_instr_sequence(instructions, &seq) < 0) {
  7109. goto error;
  7110. }
  7111. if (instr_sequence_to_cfg(&seq, g) < 0) {
  7112. goto error;
  7113. }
  7114. instr_sequence_fini(&seq);
  7115. return SUCCESS;
  7116. error:
  7117. instr_sequence_fini(&seq);
  7118. return ERROR;
  7119. }
  7120. static PyObject *
  7121. instr_sequence_to_instructions(instr_sequence *seq)
  7122. {
  7123. PyObject *instructions = PyList_New(0);
  7124. if (instructions == NULL) {
  7125. return NULL;
  7126. }
  7127. for (int i = 0; i < seq->s_used; i++) {
  7128. instruction *instr = &seq->s_instrs[i];
  7129. location loc = instr->i_loc;
  7130. int arg = HAS_TARGET(instr->i_opcode) ?
  7131. seq->s_labelmap[instr->i_oparg] : instr->i_oparg;
  7132. PyObject *inst_tuple = Py_BuildValue(
  7133. "(iiiiii)", instr->i_opcode, arg,
  7134. loc.lineno, loc.end_lineno,
  7135. loc.col_offset, loc.end_col_offset);
  7136. if (inst_tuple == NULL) {
  7137. goto error;
  7138. }
  7139. int res = PyList_Append(instructions, inst_tuple);
  7140. Py_DECREF(inst_tuple);
  7141. if (res != 0) {
  7142. goto error;
  7143. }
  7144. }
  7145. return instructions;
  7146. error:
  7147. Py_XDECREF(instructions);
  7148. return NULL;
  7149. }
  7150. static PyObject *
  7151. cfg_to_instructions(cfg_builder *g)
  7152. {
  7153. PyObject *instructions = PyList_New(0);
  7154. if (instructions == NULL) {
  7155. return NULL;
  7156. }
  7157. int lbl = 0;
  7158. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  7159. b->b_label = (jump_target_label){lbl};
  7160. lbl += b->b_iused;
  7161. }
  7162. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  7163. for (int i = 0; i < b->b_iused; i++) {
  7164. cfg_instr *instr = &b->b_instr[i];
  7165. location loc = instr->i_loc;
  7166. int arg = HAS_TARGET(instr->i_opcode) ?
  7167. instr->i_target->b_label.id : instr->i_oparg;
  7168. PyObject *inst_tuple = Py_BuildValue(
  7169. "(iiiiii)", instr->i_opcode, arg,
  7170. loc.lineno, loc.end_lineno,
  7171. loc.col_offset, loc.end_col_offset);
  7172. if (inst_tuple == NULL) {
  7173. goto error;
  7174. }
  7175. if (PyList_Append(instructions, inst_tuple) != 0) {
  7176. Py_DECREF(inst_tuple);
  7177. goto error;
  7178. }
  7179. Py_DECREF(inst_tuple);
  7180. }
  7181. }
  7182. return instructions;
  7183. error:
  7184. Py_DECREF(instructions);
  7185. return NULL;
  7186. }
  7187. PyObject *
  7188. _PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
  7189. int optimize, int compile_mode)
  7190. {
  7191. PyObject *res = NULL;
  7192. PyObject *metadata = NULL;
  7193. if (!PyAST_Check(ast)) {
  7194. PyErr_SetString(PyExc_TypeError, "expected an AST");
  7195. return NULL;
  7196. }
  7197. PyArena *arena = _PyArena_New();
  7198. if (arena == NULL) {
  7199. return NULL;
  7200. }
  7201. mod_ty mod = PyAST_obj2mod(ast, arena, compile_mode);
  7202. if (mod == NULL || !_PyAST_Validate(mod)) {
  7203. _PyArena_Free(arena);
  7204. return NULL;
  7205. }
  7206. struct compiler *c = new_compiler(mod, filename, pflags, optimize, arena);
  7207. if (c == NULL) {
  7208. _PyArena_Free(arena);
  7209. return NULL;
  7210. }
  7211. if (compiler_codegen(c, mod) < 0) {
  7212. goto finally;
  7213. }
  7214. _PyCompile_CodeUnitMetadata *umd = &c->u->u_metadata;
  7215. metadata = PyDict_New();
  7216. if (metadata == NULL) {
  7217. goto finally;
  7218. }
  7219. #define SET_MATADATA_ITEM(key, value) \
  7220. if (value != NULL) { \
  7221. if (PyDict_SetItemString(metadata, key, value) < 0) goto finally; \
  7222. }
  7223. SET_MATADATA_ITEM("name", umd->u_name);
  7224. SET_MATADATA_ITEM("qualname", umd->u_qualname);
  7225. SET_MATADATA_ITEM("consts", umd->u_consts);
  7226. SET_MATADATA_ITEM("names", umd->u_names);
  7227. SET_MATADATA_ITEM("varnames", umd->u_varnames);
  7228. SET_MATADATA_ITEM("cellvars", umd->u_cellvars);
  7229. SET_MATADATA_ITEM("freevars", umd->u_freevars);
  7230. #undef SET_MATADATA_ITEM
  7231. #define SET_MATADATA_INT(key, value) do { \
  7232. PyObject *v = PyLong_FromLong((long)value); \
  7233. if (v == NULL) goto finally; \
  7234. int res = PyDict_SetItemString(metadata, key, v); \
  7235. Py_XDECREF(v); \
  7236. if (res < 0) goto finally; \
  7237. } while (0);
  7238. SET_MATADATA_INT("argcount", umd->u_argcount);
  7239. SET_MATADATA_INT("posonlyargcount", umd->u_posonlyargcount);
  7240. SET_MATADATA_INT("kwonlyargcount", umd->u_kwonlyargcount);
  7241. #undef SET_MATADATA_INT
  7242. int addNone = mod->kind != Expression_kind;
  7243. if (add_return_at_end(c, addNone) < 0) {
  7244. goto finally;
  7245. }
  7246. PyObject *insts = instr_sequence_to_instructions(INSTR_SEQUENCE(c));
  7247. if (insts == NULL) {
  7248. goto finally;
  7249. }
  7250. res = PyTuple_Pack(2, insts, metadata);
  7251. Py_DECREF(insts);
  7252. finally:
  7253. Py_XDECREF(metadata);
  7254. compiler_exit_scope(c);
  7255. compiler_free(c);
  7256. _PyArena_Free(arena);
  7257. return res;
  7258. }
  7259. PyObject *
  7260. _PyCompile_OptimizeCfg(PyObject *instructions, PyObject *consts, int nlocals)
  7261. {
  7262. PyObject *res = NULL;
  7263. PyObject *const_cache = PyDict_New();
  7264. if (const_cache == NULL) {
  7265. return NULL;
  7266. }
  7267. cfg_builder g;
  7268. if (instructions_to_cfg(instructions, &g) < 0) {
  7269. goto error;
  7270. }
  7271. int code_flags = 0, nparams = 0, firstlineno = 1;
  7272. if (_PyCfg_OptimizeCodeUnit(&g, consts, const_cache, code_flags, nlocals,
  7273. nparams, firstlineno) < 0) {
  7274. goto error;
  7275. }
  7276. res = cfg_to_instructions(&g);
  7277. error:
  7278. Py_DECREF(const_cache);
  7279. _PyCfgBuilder_Fini(&g);
  7280. return res;
  7281. }
  7282. int _PyCfg_JumpLabelsToTargets(basicblock *entryblock);
  7283. PyCodeObject *
  7284. _PyCompile_Assemble(_PyCompile_CodeUnitMetadata *umd, PyObject *filename,
  7285. PyObject *instructions)
  7286. {
  7287. PyCodeObject *co = NULL;
  7288. instr_sequence optimized_instrs;
  7289. memset(&optimized_instrs, 0, sizeof(instr_sequence));
  7290. PyObject *const_cache = PyDict_New();
  7291. if (const_cache == NULL) {
  7292. return NULL;
  7293. }
  7294. cfg_builder g;
  7295. if (instructions_to_cfg(instructions, &g) < 0) {
  7296. goto error;
  7297. }
  7298. if (_PyCfg_JumpLabelsToTargets(g.g_entryblock) < 0) {
  7299. goto error;
  7300. }
  7301. int code_flags = 0;
  7302. int nlocalsplus = prepare_localsplus(umd, &g, code_flags);
  7303. if (nlocalsplus < 0) {
  7304. goto error;
  7305. }
  7306. int maxdepth = _PyCfg_Stackdepth(g.g_entryblock, code_flags);
  7307. if (maxdepth < 0) {
  7308. goto error;
  7309. }
  7310. _PyCfg_ConvertPseudoOps(g.g_entryblock);
  7311. /* Order of basic blocks must have been determined by now */
  7312. if (_PyCfg_ResolveJumps(&g) < 0) {
  7313. goto error;
  7314. }
  7315. /* Can't modify the bytecode after computing jump offsets. */
  7316. if (cfg_to_instr_sequence(&g, &optimized_instrs) < 0) {
  7317. goto error;
  7318. }
  7319. PyObject *consts = consts_dict_keys_inorder(umd->u_consts);
  7320. if (consts == NULL) {
  7321. goto error;
  7322. }
  7323. co = _PyAssemble_MakeCodeObject(umd, const_cache,
  7324. consts, maxdepth, &optimized_instrs,
  7325. nlocalsplus, code_flags, filename);
  7326. Py_DECREF(consts);
  7327. error:
  7328. Py_DECREF(const_cache);
  7329. _PyCfgBuilder_Fini(&g);
  7330. instr_sequence_fini(&optimized_instrs);
  7331. return co;
  7332. }
  7333. /* Retained for API compatibility.
  7334. * Optimization is now done in _PyCfg_OptimizeCodeUnit */
  7335. PyObject *
  7336. PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
  7337. PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
  7338. {
  7339. return Py_NewRef(code);
  7340. }