Nodes.py 375 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323
  1. #
  2. # Parse tree nodes
  3. #
  4. from __future__ import absolute_import
  5. import cython
  6. cython.declare(sys=object, os=object, copy=object,
  7. Builtin=object, error=object, warning=object, Naming=object, PyrexTypes=object,
  8. py_object_type=object, ModuleScope=object, LocalScope=object, ClosureScope=object,
  9. StructOrUnionScope=object, PyClassScope=object,
  10. CppClassScope=object, UtilityCode=object, EncodedString=object,
  11. error_type=object, _py_int_types=object)
  12. import sys, os, copy
  13. from itertools import chain
  14. from . import Builtin
  15. from .Errors import error, warning, InternalError, CompileError
  16. from . import Naming
  17. from . import PyrexTypes
  18. from . import TypeSlots
  19. from .PyrexTypes import py_object_type, error_type
  20. from .Symtab import (ModuleScope, LocalScope, ClosureScope,
  21. StructOrUnionScope, PyClassScope, CppClassScope, TemplateScope)
  22. from .Code import UtilityCode
  23. from .StringEncoding import EncodedString
  24. from . import Future
  25. from . import Options
  26. from . import DebugFlags
  27. from .Pythran import has_np_pythran, pythran_type, is_pythran_buffer
  28. from ..Utils import add_metaclass
  29. if sys.version_info[0] >= 3:
  30. _py_int_types = int
  31. else:
  32. _py_int_types = (int, long)
  33. def relative_position(pos):
  34. return (pos[0].get_filenametable_entry(), pos[1])
  35. def embed_position(pos, docstring):
  36. if not Options.embed_pos_in_docstring:
  37. return docstring
  38. pos_line = u'File: %s (starting at line %s)' % relative_position(pos)
  39. if docstring is None:
  40. # unicode string
  41. return EncodedString(pos_line)
  42. # make sure we can encode the filename in the docstring encoding
  43. # otherwise make the docstring a unicode string
  44. encoding = docstring.encoding
  45. if encoding is not None:
  46. try:
  47. pos_line.encode(encoding)
  48. except UnicodeEncodeError:
  49. encoding = None
  50. if not docstring:
  51. # reuse the string encoding of the original docstring
  52. doc = EncodedString(pos_line)
  53. else:
  54. doc = EncodedString(pos_line + u'\n' + docstring)
  55. doc.encoding = encoding
  56. return doc
  57. def analyse_type_annotation(annotation, env, assigned_value=None):
  58. base_type = None
  59. is_ambiguous = False
  60. explicit_pytype = explicit_ctype = False
  61. if annotation.is_dict_literal:
  62. warning(annotation.pos,
  63. "Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly.")
  64. for name, value in annotation.key_value_pairs:
  65. if not name.is_string_literal:
  66. continue
  67. if name.value in ('type', b'type'):
  68. explicit_pytype = True
  69. if not explicit_ctype:
  70. annotation = value
  71. elif name.value in ('ctype', b'ctype'):
  72. explicit_ctype = True
  73. annotation = value
  74. if explicit_pytype and explicit_ctype:
  75. warning(annotation.pos, "Duplicate type declarations found in signature annotation")
  76. arg_type = annotation.analyse_as_type(env)
  77. if annotation.is_name and not annotation.cython_attribute and annotation.name in ('int', 'long', 'float'):
  78. # Map builtin numeric Python types to C types in safe cases.
  79. if assigned_value is not None and arg_type is not None and not arg_type.is_pyobject:
  80. assigned_type = assigned_value.infer_type(env)
  81. if assigned_type and assigned_type.is_pyobject:
  82. # C type seems unsafe, e.g. due to 'None' default value => ignore annotation type
  83. is_ambiguous = True
  84. arg_type = None
  85. # ignore 'int' and require 'cython.int' to avoid unsafe integer declarations
  86. if arg_type in (PyrexTypes.c_long_type, PyrexTypes.c_int_type, PyrexTypes.c_float_type):
  87. arg_type = PyrexTypes.c_double_type if annotation.name == 'float' else py_object_type
  88. elif arg_type is not None and annotation.is_string_literal:
  89. warning(annotation.pos,
  90. "Strings should no longer be used for type declarations. Use 'cython.int' etc. directly.")
  91. if arg_type is not None:
  92. if explicit_pytype and not explicit_ctype and not arg_type.is_pyobject:
  93. warning(annotation.pos,
  94. "Python type declaration in signature annotation does not refer to a Python type")
  95. base_type = CAnalysedBaseTypeNode(
  96. annotation.pos, type=arg_type, is_arg=True)
  97. elif is_ambiguous:
  98. warning(annotation.pos, "Ambiguous types in annotation, ignoring")
  99. else:
  100. warning(annotation.pos, "Unknown type declaration in annotation, ignoring")
  101. return base_type, arg_type
  102. def write_func_call(func, codewriter_class):
  103. def f(*args, **kwds):
  104. if len(args) > 1 and isinstance(args[1], codewriter_class):
  105. # here we annotate the code with this function call
  106. # but only if new code is generated
  107. node, code = args[:2]
  108. marker = ' /* %s -> %s.%s %s */' % (
  109. ' ' * code.call_level,
  110. node.__class__.__name__,
  111. func.__name__,
  112. node.pos[1:])
  113. pristine = code.buffer.stream.tell()
  114. code.putln(marker)
  115. start = code.buffer.stream.tell()
  116. code.call_level += 4
  117. res = func(*args, **kwds)
  118. code.call_level -= 4
  119. if start == code.buffer.stream.tell():
  120. # no code written => undo writing marker
  121. code.buffer.stream.truncate(pristine)
  122. else:
  123. marker = marker.replace('->', '<-', 1)
  124. code.putln(marker)
  125. return res
  126. else:
  127. return func(*args, **kwds)
  128. return f
  129. class VerboseCodeWriter(type):
  130. # Set this as a metaclass to trace function calls in code.
  131. # This slows down code generation and makes much larger files.
  132. def __new__(cls, name, bases, attrs):
  133. from types import FunctionType
  134. from .Code import CCodeWriter
  135. attrs = dict(attrs)
  136. for mname, m in attrs.items():
  137. if isinstance(m, FunctionType):
  138. attrs[mname] = write_func_call(m, CCodeWriter)
  139. return super(VerboseCodeWriter, cls).__new__(cls, name, bases, attrs)
  140. class CheckAnalysers(type):
  141. """Metaclass to check that type analysis functions return a node.
  142. """
  143. methods = set(['analyse_types',
  144. 'analyse_expressions',
  145. 'analyse_target_types'])
  146. def __new__(cls, name, bases, attrs):
  147. from types import FunctionType
  148. def check(name, func):
  149. def call(*args, **kwargs):
  150. retval = func(*args, **kwargs)
  151. if retval is None:
  152. print('%s %s %s' % (name, args, kwargs))
  153. return retval
  154. return call
  155. attrs = dict(attrs)
  156. for mname, m in attrs.items():
  157. if isinstance(m, FunctionType) and mname in cls.methods:
  158. attrs[mname] = check(mname, m)
  159. return super(CheckAnalysers, cls).__new__(cls, name, bases, attrs)
  160. def _with_metaclass(cls):
  161. if DebugFlags.debug_trace_code_generation:
  162. return add_metaclass(VerboseCodeWriter)(cls)
  163. #return add_metaclass(CheckAnalysers)(cls)
  164. return cls
  165. @_with_metaclass
  166. class Node(object):
  167. # pos (string, int, int) Source file position
  168. # is_name boolean Is a NameNode
  169. # is_literal boolean Is a ConstNode
  170. is_name = 0
  171. is_none = 0
  172. is_nonecheck = 0
  173. is_literal = 0
  174. is_terminator = 0
  175. is_wrapper = False # is a DefNode wrapper for a C function
  176. temps = None
  177. # All descendants should set child_attrs to a list of the attributes
  178. # containing nodes considered "children" in the tree. Each such attribute
  179. # can either contain a single node or a list of nodes. See Visitor.py.
  180. child_attrs = None
  181. cf_state = None
  182. # This may be an additional (or 'actual') type that will be checked when
  183. # this node is coerced to another type. This could be useful to set when
  184. # the actual type to which it can coerce is known, but you want to leave
  185. # the type a py_object_type
  186. coercion_type = None
  187. def __init__(self, pos, **kw):
  188. self.pos = pos
  189. self.__dict__.update(kw)
  190. gil_message = "Operation"
  191. nogil_check = None
  192. def gil_error(self, env=None):
  193. error(self.pos, "%s not allowed without gil" % self.gil_message)
  194. cpp_message = "Operation"
  195. def cpp_check(self, env):
  196. if not env.is_cpp():
  197. self.cpp_error()
  198. def cpp_error(self):
  199. error(self.pos, "%s only allowed in c++" % self.cpp_message)
  200. def clone_node(self):
  201. """Clone the node. This is defined as a shallow copy, except for member lists
  202. amongst the child attributes (from get_child_accessors) which are also
  203. copied. Lists containing child nodes are thus seen as a way for the node
  204. to hold multiple children directly; the list is not treated as a separate
  205. level in the tree."""
  206. result = copy.copy(self)
  207. for attrname in result.child_attrs:
  208. value = getattr(result, attrname)
  209. if isinstance(value, list):
  210. setattr(result, attrname, [x for x in value])
  211. return result
  212. #
  213. # There are 3 phases of parse tree processing, applied in order to
  214. # all the statements in a given scope-block:
  215. #
  216. # (0) analyse_declarations
  217. # Make symbol table entries for all declarations at the current
  218. # level, both explicit (def, cdef, etc.) and implicit (assignment
  219. # to an otherwise undeclared name).
  220. #
  221. # (1) analyse_expressions
  222. # Determine the result types of expressions and fill in the
  223. # 'type' attribute of each ExprNode. Insert coercion nodes into the
  224. # tree where needed to convert to and from Python objects.
  225. # Allocate temporary locals for intermediate results. Fill
  226. # in the 'result_code' attribute of each ExprNode with a C code
  227. # fragment.
  228. #
  229. # (2) generate_code
  230. # Emit C code for all declarations, statements and expressions.
  231. # Recursively applies the 3 processing phases to the bodies of
  232. # functions.
  233. #
  234. def analyse_declarations(self, env):
  235. pass
  236. def analyse_expressions(self, env):
  237. raise InternalError("analyse_expressions not implemented for %s" % \
  238. self.__class__.__name__)
  239. def generate_code(self, code):
  240. raise InternalError("generate_code not implemented for %s" % \
  241. self.__class__.__name__)
  242. def annotate(self, code):
  243. # mro does the wrong thing
  244. if isinstance(self, BlockNode):
  245. self.body.annotate(code)
  246. def end_pos(self):
  247. try:
  248. return self._end_pos
  249. except AttributeError:
  250. pos = self.pos
  251. if not self.child_attrs:
  252. self._end_pos = pos
  253. return pos
  254. for attr in self.child_attrs:
  255. child = getattr(self, attr)
  256. # Sometimes lists, sometimes nodes
  257. if child is None:
  258. pass
  259. elif isinstance(child, list):
  260. for c in child:
  261. pos = max(pos, c.end_pos())
  262. else:
  263. pos = max(pos, child.end_pos())
  264. self._end_pos = pos
  265. return pos
  266. def dump(self, level=0, filter_out=("pos",), cutoff=100, encountered=None):
  267. """Debug helper method that returns a recursive string representation of this node.
  268. """
  269. if cutoff == 0:
  270. return "<...nesting level cutoff...>"
  271. if encountered is None:
  272. encountered = set()
  273. if id(self) in encountered:
  274. return "<%s (0x%x) -- already output>" % (self.__class__.__name__, id(self))
  275. encountered.add(id(self))
  276. def dump_child(x, level):
  277. if isinstance(x, Node):
  278. return x.dump(level, filter_out, cutoff-1, encountered)
  279. elif isinstance(x, list):
  280. return "[%s]" % ", ".join([dump_child(item, level) for item in x])
  281. else:
  282. return repr(x)
  283. attrs = [(key, value) for key, value in self.__dict__.items() if key not in filter_out]
  284. if len(attrs) == 0:
  285. return "<%s (0x%x)>" % (self.__class__.__name__, id(self))
  286. else:
  287. indent = " " * level
  288. res = "<%s (0x%x)\n" % (self.__class__.__name__, id(self))
  289. for key, value in attrs:
  290. res += "%s %s: %s\n" % (indent, key, dump_child(value, level + 1))
  291. res += "%s>" % indent
  292. return res
  293. def dump_pos(self, mark_column=False, marker='(#)'):
  294. """Debug helper method that returns the source code context of this node as a string.
  295. """
  296. if not self.pos:
  297. return u''
  298. source_desc, line, col = self.pos
  299. contents = source_desc.get_lines(encoding='ASCII', error_handling='ignore')
  300. # line numbers start at 1
  301. lines = contents[max(0, line-3):line]
  302. current = lines[-1]
  303. if mark_column:
  304. current = current[:col] + marker + current[col:]
  305. lines[-1] = current.rstrip() + u' # <<<<<<<<<<<<<<\n'
  306. lines += contents[line:line+2]
  307. return u'"%s":%d:%d\n%s\n' % (
  308. source_desc.get_escaped_description(), line, col, u''.join(lines))
  309. class CompilerDirectivesNode(Node):
  310. """
  311. Sets compiler directives for the children nodes
  312. """
  313. # directives {string:value} A dictionary holding the right value for
  314. # *all* possible directives.
  315. # body Node
  316. child_attrs = ["body"]
  317. def analyse_declarations(self, env):
  318. old = env.directives
  319. env.directives = self.directives
  320. self.body.analyse_declarations(env)
  321. env.directives = old
  322. def analyse_expressions(self, env):
  323. old = env.directives
  324. env.directives = self.directives
  325. self.body = self.body.analyse_expressions(env)
  326. env.directives = old
  327. return self
  328. def generate_function_definitions(self, env, code):
  329. env_old = env.directives
  330. code_old = code.globalstate.directives
  331. code.globalstate.directives = self.directives
  332. self.body.generate_function_definitions(env, code)
  333. env.directives = env_old
  334. code.globalstate.directives = code_old
  335. def generate_execution_code(self, code):
  336. old = code.globalstate.directives
  337. code.globalstate.directives = self.directives
  338. self.body.generate_execution_code(code)
  339. code.globalstate.directives = old
  340. def annotate(self, code):
  341. old = code.globalstate.directives
  342. code.globalstate.directives = self.directives
  343. self.body.annotate(code)
  344. code.globalstate.directives = old
  345. class BlockNode(object):
  346. # Mixin class for nodes representing a declaration block.
  347. def generate_cached_builtins_decls(self, env, code):
  348. entries = env.global_scope().undeclared_cached_builtins
  349. for entry in entries:
  350. code.globalstate.add_cached_builtin_decl(entry)
  351. del entries[:]
  352. def generate_lambda_definitions(self, env, code):
  353. for node in env.lambda_defs:
  354. node.generate_function_definitions(env, code)
  355. class StatListNode(Node):
  356. # stats a list of StatNode
  357. child_attrs = ["stats"]
  358. @staticmethod
  359. def create_analysed(pos, env, *args, **kw):
  360. node = StatListNode(pos, *args, **kw)
  361. return node # No node-specific analysis needed
  362. def analyse_declarations(self, env):
  363. #print "StatListNode.analyse_declarations" ###
  364. for stat in self.stats:
  365. stat.analyse_declarations(env)
  366. def analyse_expressions(self, env):
  367. #print "StatListNode.analyse_expressions" ###
  368. self.stats = [stat.analyse_expressions(env)
  369. for stat in self.stats]
  370. return self
  371. def generate_function_definitions(self, env, code):
  372. #print "StatListNode.generate_function_definitions" ###
  373. for stat in self.stats:
  374. stat.generate_function_definitions(env, code)
  375. def generate_execution_code(self, code):
  376. #print "StatListNode.generate_execution_code" ###
  377. for stat in self.stats:
  378. code.mark_pos(stat.pos)
  379. stat.generate_execution_code(code)
  380. def annotate(self, code):
  381. for stat in self.stats:
  382. stat.annotate(code)
  383. class StatNode(Node):
  384. #
  385. # Code generation for statements is split into the following subphases:
  386. #
  387. # (1) generate_function_definitions
  388. # Emit C code for the definitions of any structs,
  389. # unions, enums and functions defined in the current
  390. # scope-block.
  391. #
  392. # (2) generate_execution_code
  393. # Emit C code for executable statements.
  394. #
  395. def generate_function_definitions(self, env, code):
  396. pass
  397. def generate_execution_code(self, code):
  398. raise InternalError("generate_execution_code not implemented for %s" % \
  399. self.__class__.__name__)
  400. class CDefExternNode(StatNode):
  401. # include_file string or None
  402. # verbatim_include string or None
  403. # body StatListNode
  404. child_attrs = ["body"]
  405. def analyse_declarations(self, env):
  406. old_cinclude_flag = env.in_cinclude
  407. env.in_cinclude = 1
  408. self.body.analyse_declarations(env)
  409. env.in_cinclude = old_cinclude_flag
  410. if self.include_file or self.verbatim_include:
  411. # Determine whether include should be late
  412. stats = self.body.stats
  413. if not env.directives['preliminary_late_includes_cy28']:
  414. late = False
  415. elif not stats:
  416. # Special case: empty 'cdef extern' blocks are early
  417. late = False
  418. else:
  419. late = all(isinstance(node, CVarDefNode) for node in stats)
  420. env.add_include_file(self.include_file, self.verbatim_include, late)
  421. def analyse_expressions(self, env):
  422. return self
  423. def generate_execution_code(self, code):
  424. pass
  425. def annotate(self, code):
  426. self.body.annotate(code)
  427. class CDeclaratorNode(Node):
  428. # Part of a C declaration.
  429. #
  430. # Processing during analyse_declarations phase:
  431. #
  432. # analyse
  433. # Returns (name, type) pair where name is the
  434. # CNameDeclaratorNode of the name being declared
  435. # and type is the type it is being declared as.
  436. #
  437. # calling_convention string Calling convention of CFuncDeclaratorNode
  438. # for which this is a base
  439. child_attrs = []
  440. calling_convention = ""
  441. def analyse_templates(self):
  442. # Only C++ functions have templates.
  443. return None
  444. class CNameDeclaratorNode(CDeclaratorNode):
  445. # name string The Cython name being declared
  446. # cname string or None C name, if specified
  447. # default ExprNode or None the value assigned on declaration
  448. child_attrs = ['default']
  449. default = None
  450. def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
  451. if nonempty and self.name == '':
  452. # May have mistaken the name for the type.
  453. if base_type.is_ptr or base_type.is_array or base_type.is_buffer:
  454. error(self.pos, "Missing argument name")
  455. elif base_type.is_void:
  456. error(self.pos, "Use spam() rather than spam(void) to declare a function with no arguments.")
  457. else:
  458. self.name = base_type.declaration_code("", for_display=1, pyrex=1)
  459. base_type = py_object_type
  460. if base_type.is_fused and env.fused_to_specific:
  461. base_type = base_type.specialize(env.fused_to_specific)
  462. self.type = base_type
  463. return self, base_type
  464. class CPtrDeclaratorNode(CDeclaratorNode):
  465. # base CDeclaratorNode
  466. child_attrs = ["base"]
  467. def analyse_templates(self):
  468. return self.base.analyse_templates()
  469. def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
  470. if base_type.is_pyobject:
  471. error(self.pos, "Pointer base type cannot be a Python object")
  472. ptr_type = PyrexTypes.c_ptr_type(base_type)
  473. return self.base.analyse(ptr_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd)
  474. class CReferenceDeclaratorNode(CDeclaratorNode):
  475. # base CDeclaratorNode
  476. child_attrs = ["base"]
  477. def analyse_templates(self):
  478. return self.base.analyse_templates()
  479. def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
  480. if base_type.is_pyobject:
  481. error(self.pos, "Reference base type cannot be a Python object")
  482. ref_type = PyrexTypes.c_ref_type(base_type)
  483. return self.base.analyse(ref_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd)
  484. class CArrayDeclaratorNode(CDeclaratorNode):
  485. # base CDeclaratorNode
  486. # dimension ExprNode
  487. child_attrs = ["base", "dimension"]
  488. def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
  489. if (base_type.is_cpp_class and base_type.is_template_type()) or base_type.is_cfunction:
  490. from .ExprNodes import TupleNode
  491. if isinstance(self.dimension, TupleNode):
  492. args = self.dimension.args
  493. else:
  494. args = self.dimension,
  495. values = [v.analyse_as_type(env) for v in args]
  496. if None in values:
  497. ix = values.index(None)
  498. error(args[ix].pos, "Template parameter not a type")
  499. base_type = error_type
  500. else:
  501. base_type = base_type.specialize_here(self.pos, values)
  502. return self.base.analyse(base_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd)
  503. if self.dimension:
  504. self.dimension = self.dimension.analyse_const_expression(env)
  505. if not self.dimension.type.is_int:
  506. error(self.dimension.pos, "Array dimension not integer")
  507. size = self.dimension.get_constant_c_result_code()
  508. if size is not None:
  509. try:
  510. size = int(size)
  511. except ValueError:
  512. # runtime constant?
  513. pass
  514. else:
  515. size = None
  516. if not base_type.is_complete():
  517. error(self.pos, "Array element type '%s' is incomplete" % base_type)
  518. if base_type.is_pyobject:
  519. error(self.pos, "Array element cannot be a Python object")
  520. if base_type.is_cfunction:
  521. error(self.pos, "Array element cannot be a function")
  522. array_type = PyrexTypes.c_array_type(base_type, size)
  523. return self.base.analyse(array_type, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd)
  524. class CFuncDeclaratorNode(CDeclaratorNode):
  525. # base CDeclaratorNode
  526. # args [CArgDeclNode]
  527. # templates [TemplatePlaceholderType]
  528. # has_varargs boolean
  529. # exception_value ConstNode
  530. # exception_check boolean True if PyErr_Occurred check needed
  531. # nogil boolean Can be called without gil
  532. # with_gil boolean Acquire gil around function body
  533. # is_const_method boolean Whether this is a const method
  534. child_attrs = ["base", "args", "exception_value"]
  535. overridable = 0
  536. optional_arg_count = 0
  537. is_const_method = 0
  538. templates = None
  539. def analyse_templates(self):
  540. if isinstance(self.base, CArrayDeclaratorNode):
  541. from .ExprNodes import TupleNode, NameNode
  542. template_node = self.base.dimension
  543. if isinstance(template_node, TupleNode):
  544. template_nodes = template_node.args
  545. elif isinstance(template_node, NameNode):
  546. template_nodes = [template_node]
  547. else:
  548. error(template_node.pos, "Template arguments must be a list of names")
  549. return None
  550. self.templates = []
  551. for template in template_nodes:
  552. if isinstance(template, NameNode):
  553. self.templates.append(PyrexTypes.TemplatePlaceholderType(template.name))
  554. else:
  555. error(template.pos, "Template arguments must be a list of names")
  556. self.base = self.base.base
  557. return self.templates
  558. else:
  559. return None
  560. def analyse(self, return_type, env, nonempty=0, directive_locals=None, visibility=None, in_pxd=False):
  561. if directive_locals is None:
  562. directive_locals = {}
  563. if nonempty:
  564. nonempty -= 1
  565. func_type_args = []
  566. for i, arg_node in enumerate(self.args):
  567. name_declarator, type = arg_node.analyse(
  568. env, nonempty=nonempty,
  569. is_self_arg=(i == 0 and env.is_c_class_scope and 'staticmethod' not in env.directives))
  570. name = name_declarator.name
  571. if name in directive_locals:
  572. type_node = directive_locals[name]
  573. other_type = type_node.analyse_as_type(env)
  574. if other_type is None:
  575. error(type_node.pos, "Not a type")
  576. elif (type is not PyrexTypes.py_object_type
  577. and not type.same_as(other_type)):
  578. error(self.base.pos, "Signature does not agree with previous declaration")
  579. error(type_node.pos, "Previous declaration here")
  580. else:
  581. type = other_type
  582. if name_declarator.cname:
  583. error(self.pos, "Function argument cannot have C name specification")
  584. if i == 0 and env.is_c_class_scope and type.is_unspecified:
  585. # fix the type of self
  586. type = env.parent_type
  587. # Turn *[] argument into **
  588. if type.is_array:
  589. type = PyrexTypes.c_ptr_type(type.base_type)
  590. # Catch attempted C-style func(void) decl
  591. if type.is_void:
  592. error(arg_node.pos, "Use spam() rather than spam(void) to declare a function with no arguments.")
  593. func_type_args.append(
  594. PyrexTypes.CFuncTypeArg(name, type, arg_node.pos))
  595. if arg_node.default:
  596. self.optional_arg_count += 1
  597. elif self.optional_arg_count:
  598. error(self.pos, "Non-default argument follows default argument")
  599. exc_val = None
  600. exc_check = 0
  601. if self.exception_check == '+':
  602. env.add_include_file('ios') # for std::ios_base::failure
  603. env.add_include_file('new') # for std::bad_alloc
  604. env.add_include_file('stdexcept')
  605. env.add_include_file('typeinfo') # for std::bad_cast
  606. if (return_type.is_pyobject
  607. and (self.exception_value or self.exception_check)
  608. and self.exception_check != '+'):
  609. error(self.pos, "Exception clause not allowed for function returning Python object")
  610. else:
  611. if self.exception_value is None and self.exception_check and self.exception_check != '+':
  612. # Use an explicit exception return value to speed up exception checks.
  613. # Even if it is not declared, we can use the default exception value of the return type,
  614. # unless the function is some kind of external function that we do not control.
  615. if return_type.exception_value is not None and (visibility != 'extern' and not in_pxd):
  616. # Extension types are more difficult because the signature must match the base type signature.
  617. if not env.is_c_class_scope:
  618. from .ExprNodes import ConstNode
  619. self.exception_value = ConstNode(
  620. self.pos, value=return_type.exception_value, type=return_type)
  621. if self.exception_value:
  622. self.exception_value = self.exception_value.analyse_const_expression(env)
  623. if self.exception_check == '+':
  624. exc_val_type = self.exception_value.type
  625. if (not exc_val_type.is_error
  626. and not exc_val_type.is_pyobject
  627. and not (exc_val_type.is_cfunction
  628. and not exc_val_type.return_type.is_pyobject
  629. and not exc_val_type.args)):
  630. error(self.exception_value.pos,
  631. "Exception value must be a Python exception or cdef function with no arguments.")
  632. exc_val = self.exception_value
  633. else:
  634. self.exception_value = self.exception_value.coerce_to(
  635. return_type, env).analyse_const_expression(env)
  636. exc_val = self.exception_value.get_constant_c_result_code()
  637. if exc_val is None:
  638. raise InternalError(
  639. "get_constant_c_result_code not implemented for %s" %
  640. self.exception_value.__class__.__name__)
  641. if not return_type.assignable_from(self.exception_value.type):
  642. error(self.exception_value.pos,
  643. "Exception value incompatible with function return type")
  644. exc_check = self.exception_check
  645. if return_type.is_cfunction:
  646. error(self.pos, "Function cannot return a function")
  647. func_type = PyrexTypes.CFuncType(
  648. return_type, func_type_args, self.has_varargs,
  649. optional_arg_count=self.optional_arg_count,
  650. exception_value=exc_val, exception_check=exc_check,
  651. calling_convention=self.base.calling_convention,
  652. nogil=self.nogil, with_gil=self.with_gil, is_overridable=self.overridable,
  653. is_const_method=self.is_const_method,
  654. templates=self.templates)
  655. if self.optional_arg_count:
  656. if func_type.is_fused:
  657. # This is a bit of a hack... When we need to create specialized CFuncTypes
  658. # on the fly because the cdef is defined in a pxd, we need to declare the specialized optional arg
  659. # struct
  660. def declare_opt_arg_struct(func_type, fused_cname):
  661. self.declare_optional_arg_struct(func_type, env, fused_cname)
  662. func_type.declare_opt_arg_struct = declare_opt_arg_struct
  663. else:
  664. self.declare_optional_arg_struct(func_type, env)
  665. callspec = env.directives['callspec']
  666. if callspec:
  667. current = func_type.calling_convention
  668. if current and current != callspec:
  669. error(self.pos, "cannot have both '%s' and '%s' "
  670. "calling conventions" % (current, callspec))
  671. func_type.calling_convention = callspec
  672. return self.base.analyse(func_type, env, visibility=visibility, in_pxd=in_pxd)
  673. def declare_optional_arg_struct(self, func_type, env, fused_cname=None):
  674. """
  675. Declares the optional argument struct (the struct used to hold the
  676. values for optional arguments). For fused cdef functions, this is
  677. deferred as analyse_declarations is called only once (on the fused
  678. cdef function).
  679. """
  680. scope = StructOrUnionScope()
  681. arg_count_member = '%sn' % Naming.pyrex_prefix
  682. scope.declare_var(arg_count_member, PyrexTypes.c_int_type, self.pos)
  683. for arg in func_type.args[len(func_type.args) - self.optional_arg_count:]:
  684. scope.declare_var(arg.name, arg.type, arg.pos, allow_pyobject=True, allow_memoryview=True)
  685. struct_cname = env.mangle(Naming.opt_arg_prefix, self.base.name)
  686. if fused_cname is not None:
  687. struct_cname = PyrexTypes.get_fused_cname(fused_cname, struct_cname)
  688. op_args_struct = env.global_scope().declare_struct_or_union(
  689. name=struct_cname,
  690. kind='struct',
  691. scope=scope,
  692. typedef_flag=0,
  693. pos=self.pos,
  694. cname=struct_cname)
  695. op_args_struct.defined_in_pxd = 1
  696. op_args_struct.used = 1
  697. func_type.op_arg_struct = PyrexTypes.c_ptr_type(op_args_struct.type)
  698. class CConstDeclaratorNode(CDeclaratorNode):
  699. # base CDeclaratorNode
  700. child_attrs = ["base"]
  701. def analyse(self, base_type, env, nonempty=0, visibility=None, in_pxd=False):
  702. if base_type.is_pyobject:
  703. error(self.pos,
  704. "Const base type cannot be a Python object")
  705. const = PyrexTypes.c_const_type(base_type)
  706. return self.base.analyse(const, env, nonempty=nonempty, visibility=visibility, in_pxd=in_pxd)
  707. class CArgDeclNode(Node):
  708. # Item in a function declaration argument list.
  709. #
  710. # base_type CBaseTypeNode
  711. # declarator CDeclaratorNode
  712. # not_none boolean Tagged with 'not None'
  713. # or_none boolean Tagged with 'or None'
  714. # accept_none boolean Resolved boolean for not_none/or_none
  715. # default ExprNode or None
  716. # default_value PyObjectConst constant for default value
  717. # annotation ExprNode or None Py3 function arg annotation
  718. # is_self_arg boolean Is the "self" arg of an extension type method
  719. # is_type_arg boolean Is the "class" arg of an extension type classmethod
  720. # is_kw_only boolean Is a keyword-only argument
  721. # is_dynamic boolean Non-literal arg stored inside CyFunction
  722. child_attrs = ["base_type", "declarator", "default", "annotation"]
  723. is_self_arg = 0
  724. is_type_arg = 0
  725. is_generic = 1
  726. kw_only = 0
  727. not_none = 0
  728. or_none = 0
  729. type = None
  730. name_declarator = None
  731. default_value = None
  732. annotation = None
  733. is_dynamic = 0
  734. def analyse(self, env, nonempty=0, is_self_arg=False):
  735. if is_self_arg:
  736. self.base_type.is_self_arg = self.is_self_arg = True
  737. if self.type is None:
  738. # The parser may misinterpret names as types. We fix that here.
  739. if isinstance(self.declarator, CNameDeclaratorNode) and self.declarator.name == '':
  740. if nonempty:
  741. if self.base_type.is_basic_c_type:
  742. # char, short, long called "int"
  743. type = self.base_type.analyse(env, could_be_name=True)
  744. arg_name = type.empty_declaration_code()
  745. else:
  746. arg_name = self.base_type.name
  747. self.declarator.name = EncodedString(arg_name)
  748. self.base_type.name = None
  749. self.base_type.is_basic_c_type = False
  750. could_be_name = True
  751. else:
  752. could_be_name = False
  753. self.base_type.is_arg = True
  754. base_type = self.base_type.analyse(env, could_be_name=could_be_name)
  755. if hasattr(self.base_type, 'arg_name') and self.base_type.arg_name:
  756. self.declarator.name = self.base_type.arg_name
  757. # The parser is unable to resolve the ambiguity of [] as part of the
  758. # type (e.g. in buffers) or empty declarator (as with arrays).
  759. # This is only arises for empty multi-dimensional arrays.
  760. if (base_type.is_array
  761. and isinstance(self.base_type, TemplatedTypeNode)
  762. and isinstance(self.declarator, CArrayDeclaratorNode)):
  763. declarator = self.declarator
  764. while isinstance(declarator.base, CArrayDeclaratorNode):
  765. declarator = declarator.base
  766. declarator.base = self.base_type.array_declarator
  767. base_type = base_type.base_type
  768. # inject type declaration from annotations
  769. # this is called without 'env' by AdjustDefByDirectives transform before declaration analysis
  770. if self.annotation and env and env.directives['annotation_typing'] and self.base_type.name is None:
  771. arg_type = self.inject_type_from_annotations(env)
  772. if arg_type is not None:
  773. base_type = arg_type
  774. return self.declarator.analyse(base_type, env, nonempty=nonempty)
  775. else:
  776. return self.name_declarator, self.type
  777. def inject_type_from_annotations(self, env):
  778. annotation = self.annotation
  779. if not annotation:
  780. return None
  781. base_type, arg_type = analyse_type_annotation(annotation, env, assigned_value=self.default)
  782. if base_type is not None:
  783. self.base_type = base_type
  784. return arg_type
  785. def calculate_default_value_code(self, code):
  786. if self.default_value is None:
  787. if self.default:
  788. if self.default.is_literal:
  789. # will not output any code, just assign the result_code
  790. self.default.generate_evaluation_code(code)
  791. return self.type.cast_code(self.default.result())
  792. self.default_value = code.get_argument_default_const(self.type)
  793. return self.default_value
  794. def annotate(self, code):
  795. if self.default:
  796. self.default.annotate(code)
  797. def generate_assignment_code(self, code, target=None, overloaded_assignment=False):
  798. default = self.default
  799. if default is None or default.is_literal:
  800. return
  801. if target is None:
  802. target = self.calculate_default_value_code(code)
  803. default.generate_evaluation_code(code)
  804. default.make_owned_reference(code)
  805. result = default.result() if overloaded_assignment else default.result_as(self.type)
  806. code.putln("%s = %s;" % (target, result))
  807. if self.type.is_pyobject:
  808. code.put_giveref(default.result())
  809. default.generate_post_assignment_code(code)
  810. default.free_temps(code)
  811. class CBaseTypeNode(Node):
  812. # Abstract base class for C base type nodes.
  813. #
  814. # Processing during analyse_declarations phase:
  815. #
  816. # analyse
  817. # Returns the type.
  818. def analyse_as_type(self, env):
  819. return self.analyse(env)
  820. class CAnalysedBaseTypeNode(Node):
  821. # type type
  822. child_attrs = []
  823. def analyse(self, env, could_be_name=False):
  824. return self.type
  825. class CSimpleBaseTypeNode(CBaseTypeNode):
  826. # name string
  827. # module_path [string] Qualifying name components
  828. # is_basic_c_type boolean
  829. # signed boolean
  830. # longness integer
  831. # complex boolean
  832. # is_self_arg boolean Is self argument of C method
  833. # ##is_type_arg boolean Is type argument of class method
  834. child_attrs = []
  835. arg_name = None # in case the argument name was interpreted as a type
  836. module_path = []
  837. is_basic_c_type = False
  838. complex = False
  839. def analyse(self, env, could_be_name=False):
  840. # Return type descriptor.
  841. #print "CSimpleBaseTypeNode.analyse: is_self_arg =", self.is_self_arg ###
  842. type = None
  843. if self.is_basic_c_type:
  844. type = PyrexTypes.simple_c_type(self.signed, self.longness, self.name)
  845. if not type:
  846. error(self.pos, "Unrecognised type modifier combination")
  847. elif self.name == "object" and not self.module_path:
  848. type = py_object_type
  849. elif self.name is None:
  850. if self.is_self_arg and env.is_c_class_scope:
  851. #print "CSimpleBaseTypeNode.analyse: defaulting to parent type" ###
  852. type = env.parent_type
  853. ## elif self.is_type_arg and env.is_c_class_scope:
  854. ## type = Builtin.type_type
  855. else:
  856. type = py_object_type
  857. else:
  858. if self.module_path:
  859. # Maybe it's a nested C++ class.
  860. scope = env
  861. for item in self.module_path:
  862. entry = scope.lookup(item)
  863. if entry is not None and entry.is_cpp_class:
  864. scope = entry.type.scope
  865. else:
  866. scope = None
  867. break
  868. if scope is None:
  869. # Maybe it's a cimport.
  870. scope = env.find_imported_module(self.module_path, self.pos)
  871. if scope:
  872. scope.fused_to_specific = env.fused_to_specific
  873. else:
  874. scope = env
  875. if scope:
  876. if scope.is_c_class_scope:
  877. scope = scope.global_scope()
  878. type = scope.lookup_type(self.name)
  879. if type is not None:
  880. pass
  881. elif could_be_name:
  882. if self.is_self_arg and env.is_c_class_scope:
  883. type = env.parent_type
  884. ## elif self.is_type_arg and env.is_c_class_scope:
  885. ## type = Builtin.type_type
  886. else:
  887. type = py_object_type
  888. self.arg_name = EncodedString(self.name)
  889. else:
  890. if self.templates:
  891. if not self.name in self.templates:
  892. error(self.pos, "'%s' is not a type identifier" % self.name)
  893. type = PyrexTypes.TemplatePlaceholderType(self.name)
  894. else:
  895. error(self.pos, "'%s' is not a type identifier" % self.name)
  896. if self.complex:
  897. if not type.is_numeric or type.is_complex:
  898. error(self.pos, "can only complexify c numeric types")
  899. type = PyrexTypes.CComplexType(type)
  900. type.create_declaration_utility_code(env)
  901. elif type is Builtin.complex_type:
  902. # Special case: optimise builtin complex type into C's
  903. # double complex. The parser cannot do this (as for the
  904. # normal scalar types) as the user may have redeclared the
  905. # 'complex' type. Testing for the exact type here works.
  906. type = PyrexTypes.c_double_complex_type
  907. type.create_declaration_utility_code(env)
  908. self.complex = True
  909. if type:
  910. return type
  911. else:
  912. return PyrexTypes.error_type
  913. class MemoryViewSliceTypeNode(CBaseTypeNode):
  914. name = 'memoryview'
  915. child_attrs = ['base_type_node', 'axes']
  916. def analyse(self, env, could_be_name=False):
  917. base_type = self.base_type_node.analyse(env)
  918. if base_type.is_error: return base_type
  919. from . import MemoryView
  920. try:
  921. axes_specs = MemoryView.get_axes_specs(env, self.axes)
  922. except CompileError as e:
  923. error(e.position, e.message_only)
  924. self.type = PyrexTypes.ErrorType()
  925. return self.type
  926. if not MemoryView.validate_axes(self.pos, axes_specs):
  927. self.type = error_type
  928. else:
  929. self.type = PyrexTypes.MemoryViewSliceType(base_type, axes_specs)
  930. self.type.validate_memslice_dtype(self.pos)
  931. self.use_memview_utilities(env)
  932. return self.type
  933. def use_memview_utilities(self, env):
  934. from . import MemoryView
  935. env.use_utility_code(MemoryView.view_utility_code)
  936. class CNestedBaseTypeNode(CBaseTypeNode):
  937. # For C++ classes that live inside other C++ classes.
  938. # name string
  939. # base_type CBaseTypeNode
  940. child_attrs = ['base_type']
  941. def analyse(self, env, could_be_name=None):
  942. base_type = self.base_type.analyse(env)
  943. if base_type is PyrexTypes.error_type:
  944. return PyrexTypes.error_type
  945. if not base_type.is_cpp_class:
  946. error(self.pos, "'%s' is not a valid type scope" % base_type)
  947. return PyrexTypes.error_type
  948. type_entry = base_type.scope.lookup_here(self.name)
  949. if not type_entry or not type_entry.is_type:
  950. error(self.pos, "'%s.%s' is not a type identifier" % (base_type, self.name))
  951. return PyrexTypes.error_type
  952. return type_entry.type
  953. class TemplatedTypeNode(CBaseTypeNode):
  954. # After parsing:
  955. # positional_args [ExprNode] List of positional arguments
  956. # keyword_args DictNode Keyword arguments
  957. # base_type_node CBaseTypeNode
  958. # After analysis:
  959. # type PyrexTypes.BufferType or PyrexTypes.CppClassType ...containing the right options
  960. child_attrs = ["base_type_node", "positional_args",
  961. "keyword_args", "dtype_node"]
  962. dtype_node = None
  963. name = None
  964. def analyse(self, env, could_be_name=False, base_type=None):
  965. if base_type is None:
  966. base_type = self.base_type_node.analyse(env)
  967. if base_type.is_error: return base_type
  968. if base_type.is_cpp_class and base_type.is_template_type():
  969. # Templated class
  970. if self.keyword_args and self.keyword_args.key_value_pairs:
  971. error(self.pos, "c++ templates cannot take keyword arguments")
  972. self.type = PyrexTypes.error_type
  973. else:
  974. template_types = []
  975. for template_node in self.positional_args:
  976. type = template_node.analyse_as_type(env)
  977. if type is None:
  978. error(template_node.pos, "unknown type in template argument")
  979. type = error_type
  980. template_types.append(type)
  981. self.type = base_type.specialize_here(self.pos, template_types)
  982. elif base_type.is_pyobject:
  983. # Buffer
  984. from . import Buffer
  985. options = Buffer.analyse_buffer_options(
  986. self.pos,
  987. env,
  988. self.positional_args,
  989. self.keyword_args,
  990. base_type.buffer_defaults)
  991. if sys.version_info[0] < 3:
  992. # Py 2.x enforces byte strings as keyword arguments ...
  993. options = dict([(name.encode('ASCII'), value)
  994. for name, value in options.items()])
  995. self.type = PyrexTypes.BufferType(base_type, **options)
  996. if has_np_pythran(env) and is_pythran_buffer(self.type):
  997. self.type = PyrexTypes.PythranExpr(pythran_type(self.type), self.type)
  998. else:
  999. # Array
  1000. empty_declarator = CNameDeclaratorNode(self.pos, name="", cname=None)
  1001. if len(self.positional_args) > 1 or self.keyword_args.key_value_pairs:
  1002. error(self.pos, "invalid array declaration")
  1003. self.type = PyrexTypes.error_type
  1004. else:
  1005. # It would be nice to merge this class with CArrayDeclaratorNode,
  1006. # but arrays are part of the declaration, not the type...
  1007. if not self.positional_args:
  1008. dimension = None
  1009. else:
  1010. dimension = self.positional_args[0]
  1011. self.array_declarator = CArrayDeclaratorNode(
  1012. self.pos,
  1013. base=empty_declarator,
  1014. dimension=dimension)
  1015. self.type = self.array_declarator.analyse(base_type, env)[1]
  1016. if self.type.is_fused and env.fused_to_specific:
  1017. self.type = self.type.specialize(env.fused_to_specific)
  1018. return self.type
  1019. class CComplexBaseTypeNode(CBaseTypeNode):
  1020. # base_type CBaseTypeNode
  1021. # declarator CDeclaratorNode
  1022. child_attrs = ["base_type", "declarator"]
  1023. def analyse(self, env, could_be_name=False):
  1024. base = self.base_type.analyse(env, could_be_name)
  1025. _, type = self.declarator.analyse(base, env)
  1026. return type
  1027. class CTupleBaseTypeNode(CBaseTypeNode):
  1028. # components [CBaseTypeNode]
  1029. child_attrs = ["components"]
  1030. def analyse(self, env, could_be_name=False):
  1031. component_types = []
  1032. for c in self.components:
  1033. type = c.analyse(env)
  1034. if type.is_pyobject:
  1035. error(c.pos, "Tuple types can't (yet) contain Python objects.")
  1036. return error_type
  1037. component_types.append(type)
  1038. entry = env.declare_tuple_type(self.pos, component_types)
  1039. entry.used = True
  1040. return entry.type
  1041. class FusedTypeNode(CBaseTypeNode):
  1042. """
  1043. Represents a fused type in a ctypedef statement:
  1044. ctypedef cython.fused_type(int, long, long long) integral
  1045. name str name of this fused type
  1046. types [CSimpleBaseTypeNode] is the list of types to be fused
  1047. """
  1048. child_attrs = []
  1049. def analyse_declarations(self, env):
  1050. type = self.analyse(env)
  1051. entry = env.declare_typedef(self.name, type, self.pos)
  1052. # Omit the typedef declaration that self.declarator would produce
  1053. entry.in_cinclude = True
  1054. def analyse(self, env, could_be_name=False):
  1055. types = []
  1056. for type_node in self.types:
  1057. type = type_node.analyse_as_type(env)
  1058. if not type:
  1059. error(type_node.pos, "Not a type")
  1060. continue
  1061. if type in types:
  1062. error(type_node.pos, "Type specified multiple times")
  1063. else:
  1064. types.append(type)
  1065. # if len(self.types) == 1:
  1066. # return types[0]
  1067. return PyrexTypes.FusedType(types, name=self.name)
  1068. class CConstTypeNode(CBaseTypeNode):
  1069. # base_type CBaseTypeNode
  1070. child_attrs = ["base_type"]
  1071. def analyse(self, env, could_be_name=False):
  1072. base = self.base_type.analyse(env, could_be_name)
  1073. if base.is_pyobject:
  1074. error(self.pos,
  1075. "Const base type cannot be a Python object")
  1076. return PyrexTypes.c_const_type(base)
  1077. class CVarDefNode(StatNode):
  1078. # C variable definition or forward/extern function declaration.
  1079. #
  1080. # visibility 'private' or 'public' or 'extern'
  1081. # base_type CBaseTypeNode
  1082. # declarators [CDeclaratorNode]
  1083. # in_pxd boolean
  1084. # api boolean
  1085. # overridable boolean whether it is a cpdef
  1086. # modifiers ['inline']
  1087. # decorators [cython.locals(...)] or None
  1088. # directive_locals { string : NameNode } locals defined by cython.locals(...)
  1089. child_attrs = ["base_type", "declarators"]
  1090. decorators = None
  1091. directive_locals = None
  1092. def analyse_declarations(self, env, dest_scope=None):
  1093. if self.directive_locals is None:
  1094. self.directive_locals = {}
  1095. if not dest_scope:
  1096. dest_scope = env
  1097. self.dest_scope = dest_scope
  1098. if self.declarators:
  1099. templates = self.declarators[0].analyse_templates()
  1100. else:
  1101. templates = None
  1102. if templates is not None:
  1103. if self.visibility != 'extern':
  1104. error(self.pos, "Only extern functions allowed")
  1105. if len(self.declarators) > 1:
  1106. error(self.declarators[1].pos, "Can't multiply declare template types")
  1107. env = TemplateScope('func_template', env)
  1108. env.directives = env.outer_scope.directives
  1109. for template_param in templates:
  1110. env.declare_type(template_param.name, template_param, self.pos)
  1111. base_type = self.base_type.analyse(env)
  1112. if base_type.is_fused and not self.in_pxd and (env.is_c_class_scope or
  1113. env.is_module_scope):
  1114. error(self.pos, "Fused types not allowed here")
  1115. return error_type
  1116. self.entry = None
  1117. visibility = self.visibility
  1118. for declarator in self.declarators:
  1119. if (len(self.declarators) > 1
  1120. and not isinstance(declarator, CNameDeclaratorNode)
  1121. and env.directives['warn.multiple_declarators']):
  1122. warning(
  1123. declarator.pos,
  1124. "Non-trivial type declarators in shared declaration (e.g. mix of pointers and values). "
  1125. "Each pointer declaration should be on its own line.", 1)
  1126. create_extern_wrapper = (self.overridable
  1127. and self.visibility == 'extern'
  1128. and env.is_module_scope)
  1129. if create_extern_wrapper:
  1130. declarator.overridable = False
  1131. if isinstance(declarator, CFuncDeclaratorNode):
  1132. name_declarator, type = declarator.analyse(
  1133. base_type, env, directive_locals=self.directive_locals, visibility=visibility, in_pxd=self.in_pxd)
  1134. else:
  1135. name_declarator, type = declarator.analyse(
  1136. base_type, env, visibility=visibility, in_pxd=self.in_pxd)
  1137. if not type.is_complete():
  1138. if not (self.visibility == 'extern' and type.is_array or type.is_memoryviewslice):
  1139. error(declarator.pos, "Variable type '%s' is incomplete" % type)
  1140. if self.visibility == 'extern' and type.is_pyobject:
  1141. error(declarator.pos, "Python object cannot be declared extern")
  1142. name = name_declarator.name
  1143. cname = name_declarator.cname
  1144. if name == '':
  1145. error(declarator.pos, "Missing name in declaration.")
  1146. return
  1147. if type.is_reference and self.visibility != 'extern':
  1148. error(declarator.pos, "C++ references cannot be declared; use a pointer instead")
  1149. if type.is_cfunction:
  1150. if 'staticmethod' in env.directives:
  1151. type.is_static_method = True
  1152. self.entry = dest_scope.declare_cfunction(
  1153. name, type, declarator.pos,
  1154. cname=cname, visibility=self.visibility, in_pxd=self.in_pxd,
  1155. api=self.api, modifiers=self.modifiers, overridable=self.overridable)
  1156. if self.entry is not None:
  1157. self.entry.directive_locals = copy.copy(self.directive_locals)
  1158. if create_extern_wrapper:
  1159. self.entry.type.create_to_py_utility_code(env)
  1160. self.entry.create_wrapper = True
  1161. else:
  1162. if self.directive_locals:
  1163. error(self.pos, "Decorators can only be followed by functions")
  1164. self.entry = dest_scope.declare_var(
  1165. name, type, declarator.pos,
  1166. cname=cname, visibility=visibility, in_pxd=self.in_pxd,
  1167. api=self.api, is_cdef=1)
  1168. if Options.docstrings:
  1169. self.entry.doc = embed_position(self.pos, self.doc)
  1170. class CStructOrUnionDefNode(StatNode):
  1171. # name string
  1172. # cname string or None
  1173. # kind "struct" or "union"
  1174. # typedef_flag boolean
  1175. # visibility "public" or "private"
  1176. # api boolean
  1177. # in_pxd boolean
  1178. # attributes [CVarDefNode] or None
  1179. # entry Entry
  1180. # packed boolean
  1181. child_attrs = ["attributes"]
  1182. def declare(self, env, scope=None):
  1183. self.entry = env.declare_struct_or_union(
  1184. self.name, self.kind, scope, self.typedef_flag, self.pos,
  1185. self.cname, visibility=self.visibility, api=self.api,
  1186. packed=self.packed)
  1187. def analyse_declarations(self, env):
  1188. scope = None
  1189. if self.attributes is not None:
  1190. scope = StructOrUnionScope(self.name)
  1191. self.declare(env, scope)
  1192. if self.attributes is not None:
  1193. if self.in_pxd and not env.in_cinclude:
  1194. self.entry.defined_in_pxd = 1
  1195. for attr in self.attributes:
  1196. attr.analyse_declarations(env, scope)
  1197. if self.visibility != 'extern':
  1198. for attr in scope.var_entries:
  1199. type = attr.type
  1200. while type.is_array:
  1201. type = type.base_type
  1202. if type == self.entry.type:
  1203. error(attr.pos, "Struct cannot contain itself as a member.")
  1204. def analyse_expressions(self, env):
  1205. return self
  1206. def generate_execution_code(self, code):
  1207. pass
  1208. class CppClassNode(CStructOrUnionDefNode, BlockNode):
  1209. # name string
  1210. # cname string or None
  1211. # visibility "extern"
  1212. # in_pxd boolean
  1213. # attributes [CVarDefNode] or None
  1214. # entry Entry
  1215. # base_classes [CBaseTypeNode]
  1216. # templates [(string, bool)] or None
  1217. # decorators [DecoratorNode] or None
  1218. decorators = None
  1219. def declare(self, env):
  1220. if self.templates is None:
  1221. template_types = None
  1222. else:
  1223. template_types = [PyrexTypes.TemplatePlaceholderType(template_name, not required)
  1224. for template_name, required in self.templates]
  1225. num_optional_templates = sum(not required for _, required in self.templates)
  1226. if num_optional_templates and not all(required for _, required in self.templates[:-num_optional_templates]):
  1227. error(self.pos, "Required template parameters must precede optional template parameters.")
  1228. self.entry = env.declare_cpp_class(
  1229. self.name, None, self.pos, self.cname,
  1230. base_classes=[], visibility=self.visibility, templates=template_types)
  1231. def analyse_declarations(self, env):
  1232. if self.templates is None:
  1233. template_types = template_names = None
  1234. else:
  1235. template_names = [template_name for template_name, _ in self.templates]
  1236. template_types = [PyrexTypes.TemplatePlaceholderType(template_name, not required)
  1237. for template_name, required in self.templates]
  1238. scope = None
  1239. if self.attributes is not None:
  1240. scope = CppClassScope(self.name, env, templates=template_names)
  1241. def base_ok(base_class):
  1242. if base_class.is_cpp_class or base_class.is_struct:
  1243. return True
  1244. else:
  1245. error(self.pos, "Base class '%s' not a struct or class." % base_class)
  1246. base_class_types = filter(base_ok, [b.analyse(scope or env) for b in self.base_classes])
  1247. self.entry = env.declare_cpp_class(
  1248. self.name, scope, self.pos,
  1249. self.cname, base_class_types, visibility=self.visibility, templates=template_types)
  1250. if self.entry is None:
  1251. return
  1252. self.entry.is_cpp_class = 1
  1253. if scope is not None:
  1254. scope.type = self.entry.type
  1255. defined_funcs = []
  1256. def func_attributes(attributes):
  1257. for attr in attributes:
  1258. if isinstance(attr, CFuncDefNode):
  1259. yield attr
  1260. elif isinstance(attr, CompilerDirectivesNode):
  1261. for sub_attr in func_attributes(attr.body.stats):
  1262. yield sub_attr
  1263. if self.attributes is not None:
  1264. if self.in_pxd and not env.in_cinclude:
  1265. self.entry.defined_in_pxd = 1
  1266. for attr in self.attributes:
  1267. declare = getattr(attr, 'declare', None)
  1268. if declare:
  1269. attr.declare(scope)
  1270. attr.analyse_declarations(scope)
  1271. for func in func_attributes(self.attributes):
  1272. defined_funcs.append(func)
  1273. if self.templates is not None:
  1274. func.template_declaration = "template <typename %s>" % ", typename ".join(template_names)
  1275. self.body = StatListNode(self.pos, stats=defined_funcs)
  1276. self.scope = scope
  1277. def analyse_expressions(self, env):
  1278. self.body = self.body.analyse_expressions(self.entry.type.scope)
  1279. return self
  1280. def generate_function_definitions(self, env, code):
  1281. self.body.generate_function_definitions(self.entry.type.scope, code)
  1282. def generate_execution_code(self, code):
  1283. self.body.generate_execution_code(code)
  1284. def annotate(self, code):
  1285. self.body.annotate(code)
  1286. class CEnumDefNode(StatNode):
  1287. # name string or None
  1288. # cname string or None
  1289. # items [CEnumDefItemNode]
  1290. # typedef_flag boolean
  1291. # visibility "public" or "private" or "extern"
  1292. # api boolean
  1293. # in_pxd boolean
  1294. # create_wrapper boolean
  1295. # entry Entry
  1296. child_attrs = ["items"]
  1297. def declare(self, env):
  1298. self.entry = env.declare_enum(
  1299. self.name, self.pos,
  1300. cname=self.cname, typedef_flag=self.typedef_flag,
  1301. visibility=self.visibility, api=self.api,
  1302. create_wrapper=self.create_wrapper)
  1303. def analyse_declarations(self, env):
  1304. if self.items is not None:
  1305. if self.in_pxd and not env.in_cinclude:
  1306. self.entry.defined_in_pxd = 1
  1307. for item in self.items:
  1308. item.analyse_declarations(env, self.entry)
  1309. def analyse_expressions(self, env):
  1310. return self
  1311. def generate_execution_code(self, code):
  1312. if self.visibility == 'public' or self.api:
  1313. code.mark_pos(self.pos)
  1314. temp = code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=True)
  1315. for item in self.entry.enum_values:
  1316. code.putln("%s = PyInt_FromLong(%s); %s" % (
  1317. temp,
  1318. item.cname,
  1319. code.error_goto_if_null(temp, item.pos)))
  1320. code.put_gotref(temp)
  1321. code.putln('if (PyDict_SetItemString(%s, "%s", %s) < 0) %s' % (
  1322. Naming.moddict_cname,
  1323. item.name,
  1324. temp,
  1325. code.error_goto(item.pos)))
  1326. code.put_decref_clear(temp, PyrexTypes.py_object_type)
  1327. code.funcstate.release_temp(temp)
  1328. class CEnumDefItemNode(StatNode):
  1329. # name string
  1330. # cname string or None
  1331. # value ExprNode or None
  1332. child_attrs = ["value"]
  1333. def analyse_declarations(self, env, enum_entry):
  1334. if self.value:
  1335. self.value = self.value.analyse_const_expression(env)
  1336. if not self.value.type.is_int:
  1337. self.value = self.value.coerce_to(PyrexTypes.c_int_type, env)
  1338. self.value = self.value.analyse_const_expression(env)
  1339. entry = env.declare_const(
  1340. self.name, enum_entry.type,
  1341. self.value, self.pos, cname=self.cname,
  1342. visibility=enum_entry.visibility, api=enum_entry.api,
  1343. create_wrapper=enum_entry.create_wrapper and enum_entry.name is None)
  1344. enum_entry.enum_values.append(entry)
  1345. if enum_entry.name:
  1346. enum_entry.type.values.append(entry.name)
  1347. class CTypeDefNode(StatNode):
  1348. # base_type CBaseTypeNode
  1349. # declarator CDeclaratorNode
  1350. # visibility "public" or "private"
  1351. # api boolean
  1352. # in_pxd boolean
  1353. child_attrs = ["base_type", "declarator"]
  1354. def analyse_declarations(self, env):
  1355. base = self.base_type.analyse(env)
  1356. name_declarator, type = self.declarator.analyse(
  1357. base, env, visibility=self.visibility, in_pxd=self.in_pxd)
  1358. name = name_declarator.name
  1359. cname = name_declarator.cname
  1360. entry = env.declare_typedef(
  1361. name, type, self.pos,
  1362. cname=cname, visibility=self.visibility, api=self.api)
  1363. if type.is_fused:
  1364. entry.in_cinclude = True
  1365. if self.in_pxd and not env.in_cinclude:
  1366. entry.defined_in_pxd = 1
  1367. def analyse_expressions(self, env):
  1368. return self
  1369. def generate_execution_code(self, code):
  1370. pass
  1371. class FuncDefNode(StatNode, BlockNode):
  1372. # Base class for function definition nodes.
  1373. #
  1374. # return_type PyrexType
  1375. # #filename string C name of filename string const
  1376. # entry Symtab.Entry
  1377. # needs_closure boolean Whether or not this function has inner functions/classes/yield
  1378. # needs_outer_scope boolean Whether or not this function requires outer scope
  1379. # pymethdef_required boolean Force Python method struct generation
  1380. # directive_locals { string : ExprNode } locals defined by cython.locals(...)
  1381. # directive_returns [ExprNode] type defined by cython.returns(...)
  1382. # star_arg PyArgDeclNode or None * argument
  1383. # starstar_arg PyArgDeclNode or None ** argument
  1384. #
  1385. # is_async_def boolean is a Coroutine function
  1386. #
  1387. # has_fused_arguments boolean
  1388. # Whether this cdef function has fused parameters. This is needed
  1389. # by AnalyseDeclarationsTransform, so it can replace CFuncDefNodes
  1390. # with fused argument types with a FusedCFuncDefNode
  1391. py_func = None
  1392. needs_closure = False
  1393. needs_outer_scope = False
  1394. pymethdef_required = False
  1395. is_generator = False
  1396. is_generator_body = False
  1397. is_async_def = False
  1398. modifiers = []
  1399. has_fused_arguments = False
  1400. star_arg = None
  1401. starstar_arg = None
  1402. is_cyfunction = False
  1403. code_object = None
  1404. def analyse_default_values(self, env):
  1405. default_seen = 0
  1406. for arg in self.args:
  1407. if arg.default:
  1408. default_seen = 1
  1409. if arg.is_generic:
  1410. arg.default = arg.default.analyse_types(env)
  1411. arg.default = arg.default.coerce_to(arg.type, env)
  1412. else:
  1413. error(arg.pos, "This argument cannot have a default value")
  1414. arg.default = None
  1415. elif arg.kw_only:
  1416. default_seen = 1
  1417. elif default_seen:
  1418. error(arg.pos, "Non-default argument following default argument")
  1419. def analyse_annotation(self, env, annotation):
  1420. # Annotations can not only contain valid Python expressions but arbitrary type references.
  1421. if annotation is None:
  1422. return None
  1423. if not env.directives['annotation_typing'] or annotation.analyse_as_type(env) is None:
  1424. annotation = annotation.analyse_types(env)
  1425. return annotation
  1426. def analyse_annotations(self, env):
  1427. for arg in self.args:
  1428. if arg.annotation:
  1429. arg.annotation = self.analyse_annotation(env, arg.annotation)
  1430. def align_argument_type(self, env, arg):
  1431. # @cython.locals()
  1432. directive_locals = self.directive_locals
  1433. orig_type = arg.type
  1434. if arg.name in directive_locals:
  1435. type_node = directive_locals[arg.name]
  1436. other_type = type_node.analyse_as_type(env)
  1437. elif isinstance(arg, CArgDeclNode) and arg.annotation and env.directives['annotation_typing']:
  1438. type_node = arg.annotation
  1439. other_type = arg.inject_type_from_annotations(env)
  1440. if other_type is None:
  1441. return arg
  1442. else:
  1443. return arg
  1444. if other_type is None:
  1445. error(type_node.pos, "Not a type")
  1446. elif orig_type is not py_object_type and not orig_type.same_as(other_type):
  1447. error(arg.base_type.pos, "Signature does not agree with previous declaration")
  1448. error(type_node.pos, "Previous declaration here")
  1449. else:
  1450. arg.type = other_type
  1451. return arg
  1452. def need_gil_acquisition(self, lenv):
  1453. return 0
  1454. def create_local_scope(self, env):
  1455. genv = env
  1456. while genv.is_py_class_scope or genv.is_c_class_scope:
  1457. genv = genv.outer_scope
  1458. if self.needs_closure:
  1459. lenv = ClosureScope(name=self.entry.name,
  1460. outer_scope=genv,
  1461. parent_scope=env,
  1462. scope_name=self.entry.cname)
  1463. else:
  1464. lenv = LocalScope(name=self.entry.name,
  1465. outer_scope=genv,
  1466. parent_scope=env)
  1467. lenv.return_type = self.return_type
  1468. type = self.entry.type
  1469. if type.is_cfunction:
  1470. lenv.nogil = type.nogil and not type.with_gil
  1471. self.local_scope = lenv
  1472. lenv.directives = env.directives
  1473. return lenv
  1474. def generate_function_body(self, env, code):
  1475. self.body.generate_execution_code(code)
  1476. def generate_function_definitions(self, env, code):
  1477. from . import Buffer
  1478. if self.return_type.is_memoryviewslice:
  1479. from . import MemoryView
  1480. lenv = self.local_scope
  1481. if lenv.is_closure_scope and not lenv.is_passthrough:
  1482. outer_scope_cname = "%s->%s" % (Naming.cur_scope_cname,
  1483. Naming.outer_scope_cname)
  1484. else:
  1485. outer_scope_cname = Naming.outer_scope_cname
  1486. lenv.mangle_closure_cnames(outer_scope_cname)
  1487. # Generate closure function definitions
  1488. self.body.generate_function_definitions(lenv, code)
  1489. # generate lambda function definitions
  1490. self.generate_lambda_definitions(lenv, code)
  1491. is_getbuffer_slot = (self.entry.name == "__getbuffer__" and
  1492. self.entry.scope.is_c_class_scope)
  1493. is_releasebuffer_slot = (self.entry.name == "__releasebuffer__" and
  1494. self.entry.scope.is_c_class_scope)
  1495. is_buffer_slot = is_getbuffer_slot or is_releasebuffer_slot
  1496. if is_buffer_slot:
  1497. if 'cython_unused' not in self.modifiers:
  1498. self.modifiers = self.modifiers + ['cython_unused']
  1499. preprocessor_guard = self.get_preprocessor_guard()
  1500. profile = code.globalstate.directives['profile']
  1501. linetrace = code.globalstate.directives['linetrace']
  1502. if profile or linetrace:
  1503. code.globalstate.use_utility_code(
  1504. UtilityCode.load_cached("Profile", "Profile.c"))
  1505. # Generate C code for header and body of function
  1506. code.enter_cfunc_scope(lenv)
  1507. code.return_from_error_cleanup_label = code.new_label()
  1508. code.funcstate.gil_owned = not lenv.nogil
  1509. # ----- Top-level constants used by this function
  1510. code.mark_pos(self.pos)
  1511. self.generate_cached_builtins_decls(lenv, code)
  1512. # ----- Function header
  1513. code.putln("")
  1514. if preprocessor_guard:
  1515. code.putln(preprocessor_guard)
  1516. with_pymethdef = (self.needs_assignment_synthesis(env, code) or
  1517. self.pymethdef_required)
  1518. if self.py_func:
  1519. self.py_func.generate_function_header(
  1520. code, with_pymethdef=with_pymethdef, proto_only=True)
  1521. self.generate_function_header(code, with_pymethdef=with_pymethdef)
  1522. # ----- Local variable declarations
  1523. # Find function scope
  1524. cenv = env
  1525. while cenv.is_py_class_scope or cenv.is_c_class_scope:
  1526. cenv = cenv.outer_scope
  1527. if self.needs_closure:
  1528. code.put(lenv.scope_class.type.declaration_code(Naming.cur_scope_cname))
  1529. code.putln(";")
  1530. elif self.needs_outer_scope:
  1531. if lenv.is_passthrough:
  1532. code.put(lenv.scope_class.type.declaration_code(Naming.cur_scope_cname))
  1533. code.putln(";")
  1534. code.put(cenv.scope_class.type.declaration_code(Naming.outer_scope_cname))
  1535. code.putln(";")
  1536. self.generate_argument_declarations(lenv, code)
  1537. for entry in lenv.var_entries:
  1538. if not (entry.in_closure or entry.is_arg):
  1539. code.put_var_declaration(entry)
  1540. # Initialize the return variable __pyx_r
  1541. init = ""
  1542. if not self.return_type.is_void:
  1543. if self.return_type.is_pyobject:
  1544. init = " = NULL"
  1545. elif self.return_type.is_memoryviewslice:
  1546. init = ' = ' + MemoryView.memslice_entry_init
  1547. code.putln("%s%s;" % (
  1548. self.return_type.declaration_code(Naming.retval_cname),
  1549. init))
  1550. tempvardecl_code = code.insertion_point()
  1551. self.generate_keyword_list(code)
  1552. # ----- GIL acquisition
  1553. acquire_gil = self.acquire_gil
  1554. # See if we need to acquire the GIL for variable declarations, or for
  1555. # refnanny only
  1556. # Closures are not currently possible for cdef nogil functions,
  1557. # but check them anyway
  1558. have_object_args = self.needs_closure or self.needs_outer_scope
  1559. for arg in lenv.arg_entries:
  1560. if arg.type.is_pyobject:
  1561. have_object_args = True
  1562. break
  1563. used_buffer_entries = [entry for entry in lenv.buffer_entries if entry.used]
  1564. acquire_gil_for_var_decls_only = (
  1565. lenv.nogil and lenv.has_with_gil_block and
  1566. (have_object_args or used_buffer_entries))
  1567. acquire_gil_for_refnanny_only = (
  1568. lenv.nogil and lenv.has_with_gil_block and not
  1569. acquire_gil_for_var_decls_only)
  1570. use_refnanny = not lenv.nogil or lenv.has_with_gil_block
  1571. if acquire_gil or acquire_gil_for_var_decls_only:
  1572. code.put_ensure_gil()
  1573. code.funcstate.gil_owned = True
  1574. elif lenv.nogil and lenv.has_with_gil_block:
  1575. code.declare_gilstate()
  1576. if profile or linetrace:
  1577. if not self.is_generator:
  1578. # generators are traced when iterated, not at creation
  1579. tempvardecl_code.put_trace_declarations()
  1580. code_object = self.code_object.calculate_result_code(code) if self.code_object else None
  1581. code.put_trace_frame_init(code_object)
  1582. # ----- Special check for getbuffer
  1583. if is_getbuffer_slot:
  1584. self.getbuffer_check(code)
  1585. # ----- set up refnanny
  1586. if use_refnanny:
  1587. tempvardecl_code.put_declare_refcount_context()
  1588. code.put_setup_refcount_context(
  1589. self.entry.name, acquire_gil=acquire_gil_for_refnanny_only)
  1590. # ----- Automatic lead-ins for certain special functions
  1591. if is_getbuffer_slot:
  1592. self.getbuffer_init(code)
  1593. # ----- Create closure scope object
  1594. if self.needs_closure:
  1595. tp_slot = TypeSlots.ConstructorSlot("tp_new", '__new__')
  1596. slot_func_cname = TypeSlots.get_slot_function(lenv.scope_class.type.scope, tp_slot)
  1597. if not slot_func_cname:
  1598. slot_func_cname = '%s->tp_new' % lenv.scope_class.type.typeptr_cname
  1599. code.putln("%s = (%s)%s(%s, %s, NULL);" % (
  1600. Naming.cur_scope_cname,
  1601. lenv.scope_class.type.empty_declaration_code(),
  1602. slot_func_cname,
  1603. lenv.scope_class.type.typeptr_cname,
  1604. Naming.empty_tuple))
  1605. code.putln("if (unlikely(!%s)) {" % Naming.cur_scope_cname)
  1606. # Scope unconditionally DECREFed on return.
  1607. code.putln("%s = %s;" % (
  1608. Naming.cur_scope_cname,
  1609. lenv.scope_class.type.cast_code("Py_None")))
  1610. code.put_incref("Py_None", py_object_type)
  1611. code.putln(code.error_goto(self.pos))
  1612. code.putln("} else {")
  1613. code.put_gotref(Naming.cur_scope_cname)
  1614. code.putln("}")
  1615. # Note that it is unsafe to decref the scope at this point.
  1616. if self.needs_outer_scope:
  1617. if self.is_cyfunction:
  1618. code.putln("%s = (%s) __Pyx_CyFunction_GetClosure(%s);" % (
  1619. outer_scope_cname,
  1620. cenv.scope_class.type.empty_declaration_code(),
  1621. Naming.self_cname))
  1622. else:
  1623. code.putln("%s = (%s) %s;" % (
  1624. outer_scope_cname,
  1625. cenv.scope_class.type.empty_declaration_code(),
  1626. Naming.self_cname))
  1627. if lenv.is_passthrough:
  1628. code.putln("%s = %s;" % (Naming.cur_scope_cname, outer_scope_cname))
  1629. elif self.needs_closure:
  1630. # inner closures own a reference to their outer parent
  1631. code.put_incref(outer_scope_cname, cenv.scope_class.type)
  1632. code.put_giveref(outer_scope_cname)
  1633. # ----- Trace function call
  1634. if profile or linetrace:
  1635. # this looks a bit late, but if we don't get here due to a
  1636. # fatal error before hand, it's not really worth tracing
  1637. if not self.is_generator:
  1638. # generators are traced when iterated, not at creation
  1639. if self.is_wrapper:
  1640. trace_name = self.entry.name + " (wrapper)"
  1641. else:
  1642. trace_name = self.entry.name
  1643. code.put_trace_call(
  1644. trace_name, self.pos, nogil=not code.funcstate.gil_owned)
  1645. code.funcstate.can_trace = True
  1646. # ----- Fetch arguments
  1647. self.generate_argument_parsing_code(env, code)
  1648. # If an argument is assigned to in the body, we must
  1649. # incref it to properly keep track of refcounts.
  1650. is_cdef = isinstance(self, CFuncDefNode)
  1651. for entry in lenv.arg_entries:
  1652. if entry.type.is_pyobject:
  1653. if (acquire_gil or len(entry.cf_assignments) > 1) and not entry.in_closure:
  1654. code.put_var_incref(entry)
  1655. # Note: defaults are always incref-ed. For def functions, we
  1656. # we acquire arguments from object conversion, so we have
  1657. # new references. If we are a cdef function, we need to
  1658. # incref our arguments
  1659. elif is_cdef and entry.type.is_memoryviewslice and len(entry.cf_assignments) > 1:
  1660. code.put_incref_memoryviewslice(entry.cname, have_gil=code.funcstate.gil_owned)
  1661. for entry in lenv.var_entries:
  1662. if entry.is_arg and len(entry.cf_assignments) > 1 and not entry.in_closure:
  1663. if entry.xdecref_cleanup:
  1664. code.put_var_xincref(entry)
  1665. else:
  1666. code.put_var_incref(entry)
  1667. # ----- Initialise local buffer auxiliary variables
  1668. for entry in lenv.var_entries + lenv.arg_entries:
  1669. if entry.type.is_buffer and entry.buffer_aux.buflocal_nd_var.used:
  1670. Buffer.put_init_vars(entry, code)
  1671. # ----- Check and convert arguments
  1672. self.generate_argument_type_tests(code)
  1673. # ----- Acquire buffer arguments
  1674. for entry in lenv.arg_entries:
  1675. if entry.type.is_buffer:
  1676. Buffer.put_acquire_arg_buffer(entry, code, self.pos)
  1677. if acquire_gil_for_var_decls_only:
  1678. code.put_release_ensured_gil()
  1679. code.funcstate.gil_owned = False
  1680. # -------------------------
  1681. # ----- Function body -----
  1682. # -------------------------
  1683. self.generate_function_body(env, code)
  1684. code.mark_pos(self.pos, trace=False)
  1685. code.putln("")
  1686. code.putln("/* function exit code */")
  1687. # ----- Default return value
  1688. if not self.body.is_terminator:
  1689. if self.return_type.is_pyobject:
  1690. #if self.return_type.is_extension_type:
  1691. # lhs = "(PyObject *)%s" % Naming.retval_cname
  1692. #else:
  1693. lhs = Naming.retval_cname
  1694. code.put_init_to_py_none(lhs, self.return_type)
  1695. else:
  1696. val = self.return_type.default_value
  1697. if val:
  1698. code.putln("%s = %s;" % (Naming.retval_cname, val))
  1699. elif not self.return_type.is_void:
  1700. code.putln("__Pyx_pretend_to_initialize(&%s);" % Naming.retval_cname)
  1701. # ----- Error cleanup
  1702. if code.error_label in code.labels_used:
  1703. if not self.body.is_terminator:
  1704. code.put_goto(code.return_label)
  1705. code.put_label(code.error_label)
  1706. for cname, type in code.funcstate.all_managed_temps():
  1707. code.put_xdecref(cname, type, have_gil=not lenv.nogil)
  1708. # Clean up buffers -- this calls a Python function
  1709. # so need to save and restore error state
  1710. buffers_present = len(used_buffer_entries) > 0
  1711. #memslice_entries = [e for e in lenv.entries.values() if e.type.is_memoryviewslice]
  1712. if buffers_present:
  1713. code.globalstate.use_utility_code(restore_exception_utility_code)
  1714. code.putln("{ PyObject *__pyx_type, *__pyx_value, *__pyx_tb;")
  1715. code.putln("__Pyx_PyThreadState_declare")
  1716. code.putln("__Pyx_PyThreadState_assign")
  1717. code.putln("__Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb);")
  1718. for entry in used_buffer_entries:
  1719. Buffer.put_release_buffer_code(code, entry)
  1720. #code.putln("%s = 0;" % entry.cname)
  1721. code.putln("__Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);}")
  1722. if self.return_type.is_memoryviewslice:
  1723. MemoryView.put_init_entry(Naming.retval_cname, code)
  1724. err_val = Naming.retval_cname
  1725. else:
  1726. err_val = self.error_value()
  1727. exc_check = self.caller_will_check_exceptions()
  1728. if err_val is not None or exc_check:
  1729. # TODO: Fix exception tracing (though currently unused by cProfile).
  1730. # code.globalstate.use_utility_code(get_exception_tuple_utility_code)
  1731. # code.put_trace_exception()
  1732. if lenv.nogil and not lenv.has_with_gil_block:
  1733. code.putln("{")
  1734. code.put_ensure_gil()
  1735. code.put_add_traceback(self.entry.qualified_name)
  1736. if lenv.nogil and not lenv.has_with_gil_block:
  1737. code.put_release_ensured_gil()
  1738. code.putln("}")
  1739. else:
  1740. warning(self.entry.pos,
  1741. "Unraisable exception in function '%s'." %
  1742. self.entry.qualified_name, 0)
  1743. code.put_unraisable(self.entry.qualified_name, lenv.nogil)
  1744. default_retval = self.return_type.default_value
  1745. if err_val is None and default_retval:
  1746. err_val = default_retval
  1747. if err_val is not None:
  1748. code.putln("%s = %s;" % (Naming.retval_cname, err_val))
  1749. elif not self.return_type.is_void:
  1750. code.putln("__Pyx_pretend_to_initialize(&%s);" % Naming.retval_cname)
  1751. if is_getbuffer_slot:
  1752. self.getbuffer_error_cleanup(code)
  1753. # If we are using the non-error cleanup section we should
  1754. # jump past it if we have an error. The if-test below determine
  1755. # whether this section is used.
  1756. if buffers_present or is_getbuffer_slot or self.return_type.is_memoryviewslice:
  1757. code.put_goto(code.return_from_error_cleanup_label)
  1758. # ----- Non-error return cleanup
  1759. code.put_label(code.return_label)
  1760. for entry in used_buffer_entries:
  1761. Buffer.put_release_buffer_code(code, entry)
  1762. if is_getbuffer_slot:
  1763. self.getbuffer_normal_cleanup(code)
  1764. if self.return_type.is_memoryviewslice:
  1765. # See if our return value is uninitialized on non-error return
  1766. # from . import MemoryView
  1767. # MemoryView.err_if_nogil_initialized_check(self.pos, env)
  1768. cond = code.unlikely(self.return_type.error_condition(Naming.retval_cname))
  1769. code.putln(
  1770. 'if (%s) {' % cond)
  1771. if env.nogil:
  1772. code.put_ensure_gil()
  1773. code.putln(
  1774. 'PyErr_SetString(PyExc_TypeError, "Memoryview return value is not initialized");')
  1775. if env.nogil:
  1776. code.put_release_ensured_gil()
  1777. code.putln(
  1778. '}')
  1779. # ----- Return cleanup for both error and no-error return
  1780. code.put_label(code.return_from_error_cleanup_label)
  1781. for entry in lenv.var_entries:
  1782. if not entry.used or entry.in_closure:
  1783. continue
  1784. if entry.type.is_memoryviewslice:
  1785. code.put_xdecref_memoryviewslice(entry.cname, have_gil=not lenv.nogil)
  1786. elif entry.type.is_pyobject:
  1787. if not entry.is_arg or len(entry.cf_assignments) > 1:
  1788. if entry.xdecref_cleanup:
  1789. code.put_var_xdecref(entry)
  1790. else:
  1791. code.put_var_decref(entry)
  1792. # Decref any increfed args
  1793. for entry in lenv.arg_entries:
  1794. if entry.type.is_pyobject:
  1795. if (acquire_gil or len(entry.cf_assignments) > 1) and not entry.in_closure:
  1796. code.put_var_decref(entry)
  1797. elif (entry.type.is_memoryviewslice and
  1798. (not is_cdef or len(entry.cf_assignments) > 1)):
  1799. # decref slices of def functions and acquired slices from cdef
  1800. # functions, but not borrowed slices from cdef functions.
  1801. code.put_xdecref_memoryviewslice(entry.cname,
  1802. have_gil=not lenv.nogil)
  1803. if self.needs_closure:
  1804. code.put_decref(Naming.cur_scope_cname, lenv.scope_class.type)
  1805. # ----- Return
  1806. # This code is duplicated in ModuleNode.generate_module_init_func
  1807. if not lenv.nogil:
  1808. default_retval = self.return_type.default_value
  1809. err_val = self.error_value()
  1810. if err_val is None and default_retval:
  1811. err_val = default_retval # FIXME: why is err_val not used?
  1812. if self.return_type.is_pyobject:
  1813. code.put_xgiveref(self.return_type.as_pyobject(Naming.retval_cname))
  1814. if self.entry.is_special and self.entry.name == "__hash__":
  1815. # Returning -1 for __hash__ is supposed to signal an error
  1816. # We do as Python instances and coerce -1 into -2.
  1817. code.putln("if (unlikely(%s == -1) && !PyErr_Occurred()) %s = -2;" % (
  1818. Naming.retval_cname, Naming.retval_cname))
  1819. if profile or linetrace:
  1820. code.funcstate.can_trace = False
  1821. if not self.is_generator:
  1822. # generators are traced when iterated, not at creation
  1823. if self.return_type.is_pyobject:
  1824. code.put_trace_return(
  1825. Naming.retval_cname, nogil=not code.funcstate.gil_owned)
  1826. else:
  1827. code.put_trace_return(
  1828. "Py_None", nogil=not code.funcstate.gil_owned)
  1829. if not lenv.nogil:
  1830. # GIL holding function
  1831. code.put_finish_refcount_context()
  1832. if acquire_gil or (lenv.nogil and lenv.has_with_gil_block):
  1833. # release the GIL (note that with-gil blocks acquire it on exit in their EnsureGILNode)
  1834. code.put_release_ensured_gil()
  1835. code.funcstate.gil_owned = False
  1836. if not self.return_type.is_void:
  1837. code.putln("return %s;" % Naming.retval_cname)
  1838. code.putln("}")
  1839. if preprocessor_guard:
  1840. code.putln("#endif /*!(%s)*/" % preprocessor_guard)
  1841. # ----- Go back and insert temp variable declarations
  1842. tempvardecl_code.put_temp_declarations(code.funcstate)
  1843. # ----- Python version
  1844. code.exit_cfunc_scope()
  1845. if self.py_func:
  1846. self.py_func.generate_function_definitions(env, code)
  1847. self.generate_wrapper_functions(code)
  1848. def declare_argument(self, env, arg):
  1849. if arg.type.is_void:
  1850. error(arg.pos, "Invalid use of 'void'")
  1851. elif not arg.type.is_complete() and not (arg.type.is_array or arg.type.is_memoryviewslice):
  1852. error(arg.pos, "Argument type '%s' is incomplete" % arg.type)
  1853. entry = env.declare_arg(arg.name, arg.type, arg.pos)
  1854. if arg.annotation:
  1855. entry.annotation = arg.annotation
  1856. return entry
  1857. def generate_arg_type_test(self, arg, code):
  1858. # Generate type test for one argument.
  1859. if arg.type.typeobj_is_available():
  1860. code.globalstate.use_utility_code(
  1861. UtilityCode.load_cached("ArgTypeTest", "FunctionArguments.c"))
  1862. typeptr_cname = arg.type.typeptr_cname
  1863. arg_code = "((PyObject *)%s)" % arg.entry.cname
  1864. code.putln(
  1865. 'if (unlikely(!__Pyx_ArgTypeTest(%s, %s, %d, "%s", %s))) %s' % (
  1866. arg_code,
  1867. typeptr_cname,
  1868. arg.accept_none,
  1869. arg.name,
  1870. arg.type.is_builtin_type and arg.type.require_exact,
  1871. code.error_goto(arg.pos)))
  1872. else:
  1873. error(arg.pos, "Cannot test type of extern C class without type object name specification")
  1874. def generate_arg_none_check(self, arg, code):
  1875. # Generate None check for one argument.
  1876. if arg.type.is_memoryviewslice:
  1877. cname = "%s.memview" % arg.entry.cname
  1878. else:
  1879. cname = arg.entry.cname
  1880. code.putln('if (unlikely(((PyObject *)%s) == Py_None)) {' % cname)
  1881. code.putln('''PyErr_Format(PyExc_TypeError, "Argument '%%.%ds' must not be None", "%s"); %s''' % (
  1882. max(200, len(arg.name)), arg.name,
  1883. code.error_goto(arg.pos)))
  1884. code.putln('}')
  1885. def generate_wrapper_functions(self, code):
  1886. pass
  1887. def generate_execution_code(self, code):
  1888. code.mark_pos(self.pos)
  1889. # Evaluate and store argument default values
  1890. for arg in self.args:
  1891. if not arg.is_dynamic:
  1892. arg.generate_assignment_code(code)
  1893. #
  1894. # Special code for the __getbuffer__ function
  1895. #
  1896. def _get_py_buffer_info(self):
  1897. py_buffer = self.local_scope.arg_entries[1]
  1898. try:
  1899. # Check builtin definition of struct Py_buffer
  1900. obj_type = py_buffer.type.base_type.scope.entries['obj'].type
  1901. except (AttributeError, KeyError):
  1902. # User code redeclared struct Py_buffer
  1903. obj_type = None
  1904. return py_buffer, obj_type
  1905. # Old Python 3 used to support write-locks on buffer-like objects by
  1906. # calling PyObject_GetBuffer() with a view==NULL parameter. This obscure
  1907. # feature is obsolete, it was almost never used (only one instance in
  1908. # `Modules/posixmodule.c` in Python 3.1) and it is now officially removed
  1909. # (see bpo-14203). We add an extra check here to prevent legacy code from
  1910. # from trying to use the feature and prevent segmentation faults.
  1911. def getbuffer_check(self, code):
  1912. py_buffer, _ = self._get_py_buffer_info()
  1913. view = py_buffer.cname
  1914. code.putln("if (%s == NULL) {" % view)
  1915. code.putln("PyErr_SetString(PyExc_BufferError, "
  1916. "\"PyObject_GetBuffer: view==NULL argument is obsolete\");")
  1917. code.putln("return -1;")
  1918. code.putln("}")
  1919. def getbuffer_init(self, code):
  1920. py_buffer, obj_type = self._get_py_buffer_info()
  1921. view = py_buffer.cname
  1922. if obj_type and obj_type.is_pyobject:
  1923. code.put_init_to_py_none("%s->obj" % view, obj_type)
  1924. code.put_giveref("%s->obj" % view) # Do not refnanny object within structs
  1925. else:
  1926. code.putln("%s->obj = NULL;" % view)
  1927. def getbuffer_error_cleanup(self, code):
  1928. py_buffer, obj_type = self._get_py_buffer_info()
  1929. view = py_buffer.cname
  1930. if obj_type and obj_type.is_pyobject:
  1931. code.putln("if (%s->obj != NULL) {" % view)
  1932. code.put_gotref("%s->obj" % view)
  1933. code.put_decref_clear("%s->obj" % view, obj_type)
  1934. code.putln("}")
  1935. else:
  1936. code.putln("Py_CLEAR(%s->obj);" % view)
  1937. def getbuffer_normal_cleanup(self, code):
  1938. py_buffer, obj_type = self._get_py_buffer_info()
  1939. view = py_buffer.cname
  1940. if obj_type and obj_type.is_pyobject:
  1941. code.putln("if (%s->obj == Py_None) {" % view)
  1942. code.put_gotref("%s->obj" % view)
  1943. code.put_decref_clear("%s->obj" % view, obj_type)
  1944. code.putln("}")
  1945. def get_preprocessor_guard(self):
  1946. if not self.entry.is_special:
  1947. return None
  1948. name = self.entry.name
  1949. slot = TypeSlots.method_name_to_slot.get(name)
  1950. if not slot:
  1951. return None
  1952. if name == '__long__' and not self.entry.scope.lookup_here('__int__'):
  1953. return None
  1954. if name in ("__getbuffer__", "__releasebuffer__") and self.entry.scope.is_c_class_scope:
  1955. return None
  1956. return slot.preprocessor_guard_code()
  1957. class CFuncDefNode(FuncDefNode):
  1958. # C function definition.
  1959. #
  1960. # modifiers ['inline']
  1961. # visibility 'private' or 'public' or 'extern'
  1962. # base_type CBaseTypeNode
  1963. # declarator CDeclaratorNode
  1964. # cfunc_declarator the CFuncDeclarator of this function
  1965. # (this is also available through declarator or a
  1966. # base thereof)
  1967. # body StatListNode
  1968. # api boolean
  1969. # decorators [DecoratorNode] list of decorators
  1970. #
  1971. # with_gil boolean Acquire GIL around body
  1972. # type CFuncType
  1973. # py_func wrapper for calling from Python
  1974. # overridable whether or not this is a cpdef function
  1975. # inline_in_pxd whether this is an inline function in a pxd file
  1976. # template_declaration String or None Used for c++ class methods
  1977. # is_const_method whether this is a const method
  1978. # is_static_method whether this is a static method
  1979. # is_c_class_method whether this is a cclass method
  1980. child_attrs = ["base_type", "declarator", "body", "py_func_stat"]
  1981. inline_in_pxd = False
  1982. decorators = None
  1983. directive_locals = None
  1984. directive_returns = None
  1985. override = None
  1986. template_declaration = None
  1987. is_const_method = False
  1988. py_func_stat = None
  1989. def unqualified_name(self):
  1990. return self.entry.name
  1991. @property
  1992. def code_object(self):
  1993. # share the CodeObject with the cpdef wrapper (if available)
  1994. return self.py_func.code_object if self.py_func else None
  1995. def analyse_declarations(self, env):
  1996. self.is_c_class_method = env.is_c_class_scope
  1997. if self.directive_locals is None:
  1998. self.directive_locals = {}
  1999. self.directive_locals.update(env.directives['locals'])
  2000. if self.directive_returns is not None:
  2001. base_type = self.directive_returns.analyse_as_type(env)
  2002. if base_type is None:
  2003. error(self.directive_returns.pos, "Not a type")
  2004. base_type = PyrexTypes.error_type
  2005. else:
  2006. base_type = self.base_type.analyse(env)
  2007. self.is_static_method = 'staticmethod' in env.directives and not env.lookup_here('staticmethod')
  2008. # The 2 here is because we need both function and argument names.
  2009. if isinstance(self.declarator, CFuncDeclaratorNode):
  2010. name_declarator, type = self.declarator.analyse(
  2011. base_type, env, nonempty=2 * (self.body is not None),
  2012. directive_locals=self.directive_locals, visibility=self.visibility)
  2013. else:
  2014. name_declarator, type = self.declarator.analyse(
  2015. base_type, env, nonempty=2 * (self.body is not None), visibility=self.visibility)
  2016. if not type.is_cfunction:
  2017. error(self.pos, "Suite attached to non-function declaration")
  2018. # Remember the actual type according to the function header
  2019. # written here, because the type in the symbol table entry
  2020. # may be different if we're overriding a C method inherited
  2021. # from the base type of an extension type.
  2022. self.type = type
  2023. type.is_overridable = self.overridable
  2024. declarator = self.declarator
  2025. while not hasattr(declarator, 'args'):
  2026. declarator = declarator.base
  2027. self.cfunc_declarator = declarator
  2028. self.args = declarator.args
  2029. opt_arg_count = self.cfunc_declarator.optional_arg_count
  2030. if (self.visibility == 'public' or self.api) and opt_arg_count:
  2031. error(self.cfunc_declarator.pos,
  2032. "Function with optional arguments may not be declared public or api")
  2033. if type.exception_check == '+' and self.visibility != 'extern':
  2034. warning(self.cfunc_declarator.pos,
  2035. "Only extern functions can throw C++ exceptions.")
  2036. for formal_arg, type_arg in zip(self.args, type.args):
  2037. self.align_argument_type(env, type_arg)
  2038. formal_arg.type = type_arg.type
  2039. formal_arg.name = type_arg.name
  2040. formal_arg.cname = type_arg.cname
  2041. self._validate_type_visibility(type_arg.type, type_arg.pos, env)
  2042. if type_arg.type.is_fused:
  2043. self.has_fused_arguments = True
  2044. if type_arg.type.is_buffer and 'inline' in self.modifiers:
  2045. warning(formal_arg.pos, "Buffer unpacking not optimized away.", 1)
  2046. if type_arg.type.is_buffer or type_arg.type.is_pythran_expr:
  2047. if self.type.nogil:
  2048. error(formal_arg.pos,
  2049. "Buffer may not be acquired without the GIL. Consider using memoryview slices instead.")
  2050. elif 'inline' in self.modifiers:
  2051. warning(formal_arg.pos, "Buffer unpacking not optimized away.", 1)
  2052. self._validate_type_visibility(type.return_type, self.pos, env)
  2053. name = name_declarator.name
  2054. cname = name_declarator.cname
  2055. type.is_const_method = self.is_const_method
  2056. type.is_static_method = self.is_static_method
  2057. self.entry = env.declare_cfunction(
  2058. name, type, self.pos,
  2059. cname=cname, visibility=self.visibility, api=self.api,
  2060. defining=self.body is not None, modifiers=self.modifiers,
  2061. overridable=self.overridable)
  2062. self.entry.inline_func_in_pxd = self.inline_in_pxd
  2063. self.return_type = type.return_type
  2064. if self.return_type.is_array and self.visibility != 'extern':
  2065. error(self.pos, "Function cannot return an array")
  2066. if self.return_type.is_cpp_class:
  2067. self.return_type.check_nullary_constructor(self.pos, "used as a return value")
  2068. if self.overridable and not env.is_module_scope and not self.is_static_method:
  2069. if len(self.args) < 1 or not self.args[0].type.is_pyobject:
  2070. # An error will be produced in the cdef function
  2071. self.overridable = False
  2072. self.declare_cpdef_wrapper(env)
  2073. self.create_local_scope(env)
  2074. def declare_cpdef_wrapper(self, env):
  2075. if self.overridable:
  2076. if self.is_static_method:
  2077. # TODO(robertwb): Finish this up, perhaps via more function refactoring.
  2078. error(self.pos, "static cpdef methods not yet supported")
  2079. name = self.entry.name
  2080. py_func_body = self.call_self_node(is_module_scope=env.is_module_scope)
  2081. if self.is_static_method:
  2082. from .ExprNodes import NameNode
  2083. decorators = [DecoratorNode(self.pos, decorator=NameNode(self.pos, name='staticmethod'))]
  2084. decorators[0].decorator.analyse_types(env)
  2085. else:
  2086. decorators = []
  2087. self.py_func = DefNode(pos=self.pos,
  2088. name=self.entry.name,
  2089. args=self.args,
  2090. star_arg=None,
  2091. starstar_arg=None,
  2092. doc=self.doc,
  2093. body=py_func_body,
  2094. decorators=decorators,
  2095. is_wrapper=1)
  2096. self.py_func.is_module_scope = env.is_module_scope
  2097. self.py_func.analyse_declarations(env)
  2098. self.py_func.entry.is_overridable = True
  2099. self.py_func_stat = StatListNode(self.pos, stats=[self.py_func])
  2100. self.py_func.type = PyrexTypes.py_object_type
  2101. self.entry.as_variable = self.py_func.entry
  2102. self.entry.used = self.entry.as_variable.used = True
  2103. # Reset scope entry the above cfunction
  2104. env.entries[name] = self.entry
  2105. if (not self.entry.is_final_cmethod and
  2106. (not env.is_module_scope or Options.lookup_module_cpdef)):
  2107. self.override = OverrideCheckNode(self.pos, py_func=self.py_func)
  2108. self.body = StatListNode(self.pos, stats=[self.override, self.body])
  2109. def _validate_type_visibility(self, type, pos, env):
  2110. """
  2111. Ensure that types used in cdef functions are public or api, or
  2112. defined in a C header.
  2113. """
  2114. public_or_api = (self.visibility == 'public' or self.api)
  2115. entry = getattr(type, 'entry', None)
  2116. if public_or_api and entry and env.is_module_scope:
  2117. if not (entry.visibility in ('public', 'extern') or
  2118. entry.api or entry.in_cinclude):
  2119. error(pos, "Function declared public or api may not have private types")
  2120. def call_self_node(self, omit_optional_args=0, is_module_scope=0):
  2121. from . import ExprNodes
  2122. args = self.type.args
  2123. if omit_optional_args:
  2124. args = args[:len(args) - self.type.optional_arg_count]
  2125. arg_names = [arg.name for arg in args]
  2126. if is_module_scope:
  2127. cfunc = ExprNodes.NameNode(self.pos, name=self.entry.name)
  2128. call_arg_names = arg_names
  2129. skip_dispatch = Options.lookup_module_cpdef
  2130. elif self.type.is_static_method:
  2131. class_entry = self.entry.scope.parent_type.entry
  2132. class_node = ExprNodes.NameNode(self.pos, name=class_entry.name)
  2133. class_node.entry = class_entry
  2134. cfunc = ExprNodes.AttributeNode(self.pos, obj=class_node, attribute=self.entry.name)
  2135. # Calling static c(p)def methods on an instance disallowed.
  2136. # TODO(robertwb): Support by passing self to check for override?
  2137. skip_dispatch = True
  2138. else:
  2139. type_entry = self.type.args[0].type.entry
  2140. type_arg = ExprNodes.NameNode(self.pos, name=type_entry.name)
  2141. type_arg.entry = type_entry
  2142. cfunc = ExprNodes.AttributeNode(self.pos, obj=type_arg, attribute=self.entry.name)
  2143. skip_dispatch = not is_module_scope or Options.lookup_module_cpdef
  2144. c_call = ExprNodes.SimpleCallNode(
  2145. self.pos,
  2146. function=cfunc,
  2147. args=[ExprNodes.NameNode(self.pos, name=n) for n in arg_names],
  2148. wrapper_call=skip_dispatch)
  2149. return ReturnStatNode(pos=self.pos, return_type=PyrexTypes.py_object_type, value=c_call)
  2150. def declare_arguments(self, env):
  2151. for arg in self.type.args:
  2152. if not arg.name:
  2153. error(arg.pos, "Missing argument name")
  2154. self.declare_argument(env, arg)
  2155. def need_gil_acquisition(self, lenv):
  2156. return self.type.with_gil
  2157. def nogil_check(self, env):
  2158. type = self.type
  2159. with_gil = type.with_gil
  2160. if type.nogil and not with_gil:
  2161. if type.return_type.is_pyobject:
  2162. error(self.pos,
  2163. "Function with Python return type cannot be declared nogil")
  2164. for entry in self.local_scope.var_entries:
  2165. if entry.type.is_pyobject and not entry.in_with_gil_block:
  2166. error(self.pos, "Function declared nogil has Python locals or temporaries")
  2167. def analyse_expressions(self, env):
  2168. self.local_scope.directives = env.directives
  2169. if self.py_func_stat is not None:
  2170. # this will also analyse the default values and the function name assignment
  2171. self.py_func_stat = self.py_func_stat.analyse_expressions(env)
  2172. elif self.py_func is not None:
  2173. # this will also analyse the default values
  2174. self.py_func = self.py_func.analyse_expressions(env)
  2175. else:
  2176. self.analyse_default_values(env)
  2177. self.analyse_annotations(env)
  2178. self.acquire_gil = self.need_gil_acquisition(self.local_scope)
  2179. return self
  2180. def needs_assignment_synthesis(self, env, code=None):
  2181. return False
  2182. def generate_function_header(self, code, with_pymethdef, with_opt_args=1, with_dispatch=1, cname=None):
  2183. scope = self.local_scope
  2184. arg_decls = []
  2185. type = self.type
  2186. for arg in type.args[:len(type.args)-type.optional_arg_count]:
  2187. arg_decl = arg.declaration_code()
  2188. entry = scope.lookup(arg.name)
  2189. if not entry.cf_used:
  2190. arg_decl = 'CYTHON_UNUSED %s' % arg_decl
  2191. arg_decls.append(arg_decl)
  2192. if with_dispatch and self.overridable:
  2193. dispatch_arg = PyrexTypes.c_int_type.declaration_code(
  2194. Naming.skip_dispatch_cname)
  2195. if self.override:
  2196. arg_decls.append(dispatch_arg)
  2197. else:
  2198. arg_decls.append('CYTHON_UNUSED %s' % dispatch_arg)
  2199. if type.optional_arg_count and with_opt_args:
  2200. arg_decls.append(type.op_arg_struct.declaration_code(Naming.optional_args_cname))
  2201. if type.has_varargs:
  2202. arg_decls.append("...")
  2203. if not arg_decls:
  2204. arg_decls = ["void"]
  2205. if cname is None:
  2206. cname = self.entry.func_cname
  2207. entity = type.function_header_code(cname, ', '.join(arg_decls))
  2208. if self.entry.visibility == 'private' and '::' not in cname:
  2209. storage_class = "static "
  2210. else:
  2211. storage_class = ""
  2212. dll_linkage = None
  2213. modifiers = code.build_function_modifiers(self.entry.func_modifiers)
  2214. header = self.return_type.declaration_code(entity, dll_linkage=dll_linkage)
  2215. #print (storage_class, modifiers, header)
  2216. needs_proto = self.is_c_class_method
  2217. if self.template_declaration:
  2218. if needs_proto:
  2219. code.globalstate.parts['module_declarations'].putln(self.template_declaration)
  2220. code.putln(self.template_declaration)
  2221. if needs_proto:
  2222. code.globalstate.parts['module_declarations'].putln(
  2223. "%s%s%s; /* proto*/" % (storage_class, modifiers, header))
  2224. code.putln("%s%s%s {" % (storage_class, modifiers, header))
  2225. def generate_argument_declarations(self, env, code):
  2226. scope = self.local_scope
  2227. for arg in self.args:
  2228. if arg.default:
  2229. entry = scope.lookup(arg.name)
  2230. if self.override or entry.cf_used:
  2231. result = arg.calculate_default_value_code(code)
  2232. code.putln('%s = %s;' % (
  2233. arg.type.declaration_code(arg.cname), result))
  2234. def generate_keyword_list(self, code):
  2235. pass
  2236. def generate_argument_parsing_code(self, env, code):
  2237. i = 0
  2238. used = 0
  2239. scope = self.local_scope
  2240. if self.type.optional_arg_count:
  2241. code.putln('if (%s) {' % Naming.optional_args_cname)
  2242. for arg in self.args:
  2243. if arg.default:
  2244. entry = scope.lookup(arg.name)
  2245. if self.override or entry.cf_used:
  2246. code.putln('if (%s->%sn > %s) {' %
  2247. (Naming.optional_args_cname,
  2248. Naming.pyrex_prefix, i))
  2249. declarator = arg.declarator
  2250. while not hasattr(declarator, 'name'):
  2251. declarator = declarator.base
  2252. code.putln('%s = %s->%s;' %
  2253. (arg.cname, Naming.optional_args_cname,
  2254. self.type.opt_arg_cname(declarator.name)))
  2255. used += 1
  2256. i += 1
  2257. for _ in range(used):
  2258. code.putln('}')
  2259. code.putln('}')
  2260. # Move arguments into closure if required
  2261. def put_into_closure(entry):
  2262. if entry.in_closure and not arg.default:
  2263. code.putln('%s = %s;' % (entry.cname, entry.original_cname))
  2264. code.put_var_incref(entry)
  2265. code.put_var_giveref(entry)
  2266. for arg in self.args:
  2267. put_into_closure(scope.lookup_here(arg.name))
  2268. def generate_argument_conversion_code(self, code):
  2269. pass
  2270. def generate_argument_type_tests(self, code):
  2271. # Generate type tests for args whose type in a parent
  2272. # class is a supertype of the declared type.
  2273. for arg in self.type.args:
  2274. if arg.needs_type_test:
  2275. self.generate_arg_type_test(arg, code)
  2276. elif arg.type.is_pyobject and not arg.accept_none:
  2277. self.generate_arg_none_check(arg, code)
  2278. def generate_execution_code(self, code):
  2279. super(CFuncDefNode, self).generate_execution_code(code)
  2280. if self.py_func_stat:
  2281. self.py_func_stat.generate_execution_code(code)
  2282. def error_value(self):
  2283. if self.return_type.is_pyobject:
  2284. return "0"
  2285. else:
  2286. #return None
  2287. return self.entry.type.exception_value
  2288. def caller_will_check_exceptions(self):
  2289. return self.entry.type.exception_check
  2290. def generate_wrapper_functions(self, code):
  2291. # If the C signature of a function has changed, we need to generate
  2292. # wrappers to put in the slots here.
  2293. k = 0
  2294. entry = self.entry
  2295. func_type = entry.type
  2296. while entry.prev_entry is not None:
  2297. k += 1
  2298. entry = entry.prev_entry
  2299. entry.func_cname = "%s%swrap_%s" % (self.entry.func_cname, Naming.pyrex_prefix, k)
  2300. code.putln()
  2301. self.generate_function_header(
  2302. code, 0,
  2303. with_dispatch=entry.type.is_overridable,
  2304. with_opt_args=entry.type.optional_arg_count,
  2305. cname=entry.func_cname)
  2306. if not self.return_type.is_void:
  2307. code.put('return ')
  2308. args = self.type.args
  2309. arglist = [arg.cname for arg in args[:len(args)-self.type.optional_arg_count]]
  2310. if entry.type.is_overridable:
  2311. arglist.append(Naming.skip_dispatch_cname)
  2312. elif func_type.is_overridable:
  2313. arglist.append('0')
  2314. if entry.type.optional_arg_count:
  2315. arglist.append(Naming.optional_args_cname)
  2316. elif func_type.optional_arg_count:
  2317. arglist.append('NULL')
  2318. code.putln('%s(%s);' % (self.entry.func_cname, ', '.join(arglist)))
  2319. code.putln('}')
  2320. class PyArgDeclNode(Node):
  2321. # Argument which must be a Python object (used
  2322. # for * and ** arguments).
  2323. #
  2324. # name string
  2325. # entry Symtab.Entry
  2326. # annotation ExprNode or None Py3 argument annotation
  2327. child_attrs = []
  2328. is_self_arg = False
  2329. is_type_arg = False
  2330. def generate_function_definitions(self, env, code):
  2331. self.entry.generate_function_definitions(env, code)
  2332. class DecoratorNode(Node):
  2333. # A decorator
  2334. #
  2335. # decorator NameNode or CallNode or AttributeNode
  2336. child_attrs = ['decorator']
  2337. class DefNode(FuncDefNode):
  2338. # A Python function definition.
  2339. #
  2340. # name string the Python name of the function
  2341. # lambda_name string the internal name of a lambda 'function'
  2342. # decorators [DecoratorNode] list of decorators
  2343. # args [CArgDeclNode] formal arguments
  2344. # doc EncodedString or None
  2345. # body StatListNode
  2346. # return_type_annotation
  2347. # ExprNode or None the Py3 return type annotation
  2348. #
  2349. # The following subnode is constructed internally
  2350. # when the def statement is inside a Python class definition.
  2351. #
  2352. # fused_py_func DefNode The original fused cpdef DefNode
  2353. # (in case this is a specialization)
  2354. # specialized_cpdefs [DefNode] list of specialized cpdef DefNodes
  2355. # py_cfunc_node PyCFunctionNode/InnerFunctionNode The PyCFunction to create and assign
  2356. #
  2357. # decorator_indirection IndirectionNode Used to remove __Pyx_Method_ClassMethod for fused functions
  2358. child_attrs = ["args", "star_arg", "starstar_arg", "body", "decorators", "return_type_annotation"]
  2359. is_staticmethod = False
  2360. is_classmethod = False
  2361. lambda_name = None
  2362. reqd_kw_flags_cname = "0"
  2363. is_wrapper = 0
  2364. no_assignment_synthesis = 0
  2365. decorators = None
  2366. return_type_annotation = None
  2367. entry = None
  2368. acquire_gil = 0
  2369. self_in_stararg = 0
  2370. py_cfunc_node = None
  2371. requires_classobj = False
  2372. defaults_struct = None # Dynamic kwrds structure name
  2373. doc = None
  2374. fused_py_func = False
  2375. specialized_cpdefs = None
  2376. py_wrapper = None
  2377. py_wrapper_required = True
  2378. func_cname = None
  2379. defaults_getter = None
  2380. def __init__(self, pos, **kwds):
  2381. FuncDefNode.__init__(self, pos, **kwds)
  2382. k = rk = r = 0
  2383. for arg in self.args:
  2384. if arg.kw_only:
  2385. k += 1
  2386. if not arg.default:
  2387. rk += 1
  2388. if not arg.default:
  2389. r += 1
  2390. self.num_kwonly_args = k
  2391. self.num_required_kw_args = rk
  2392. self.num_required_args = r
  2393. def as_cfunction(self, cfunc=None, scope=None, overridable=True, returns=None, except_val=None, modifiers=None):
  2394. if self.star_arg:
  2395. error(self.star_arg.pos, "cdef function cannot have star argument")
  2396. if self.starstar_arg:
  2397. error(self.starstar_arg.pos, "cdef function cannot have starstar argument")
  2398. exception_value, exception_check = except_val or (None, False)
  2399. if cfunc is None:
  2400. cfunc_args = []
  2401. for formal_arg in self.args:
  2402. name_declarator, type = formal_arg.analyse(scope, nonempty=1)
  2403. cfunc_args.append(PyrexTypes.CFuncTypeArg(name=name_declarator.name,
  2404. cname=None,
  2405. annotation=formal_arg.annotation,
  2406. type=py_object_type,
  2407. pos=formal_arg.pos))
  2408. cfunc_type = PyrexTypes.CFuncType(return_type=py_object_type,
  2409. args=cfunc_args,
  2410. has_varargs=False,
  2411. exception_value=None,
  2412. exception_check=exception_check,
  2413. nogil=False,
  2414. with_gil=False,
  2415. is_overridable=overridable)
  2416. cfunc = CVarDefNode(self.pos, type=cfunc_type)
  2417. else:
  2418. if scope is None:
  2419. scope = cfunc.scope
  2420. cfunc_type = cfunc.type
  2421. if len(self.args) != len(cfunc_type.args) or cfunc_type.has_varargs:
  2422. error(self.pos, "wrong number of arguments")
  2423. error(cfunc.pos, "previous declaration here")
  2424. for i, (formal_arg, type_arg) in enumerate(zip(self.args, cfunc_type.args)):
  2425. name_declarator, type = formal_arg.analyse(scope, nonempty=1,
  2426. is_self_arg=(i == 0 and scope.is_c_class_scope))
  2427. if type is None or type is PyrexTypes.py_object_type:
  2428. formal_arg.type = type_arg.type
  2429. formal_arg.name_declarator = name_declarator
  2430. if exception_value is None and cfunc_type.exception_value is not None:
  2431. from .ExprNodes import ConstNode
  2432. exception_value = ConstNode(
  2433. self.pos, value=cfunc_type.exception_value, type=cfunc_type.return_type)
  2434. declarator = CFuncDeclaratorNode(self.pos,
  2435. base=CNameDeclaratorNode(self.pos, name=self.name, cname=None),
  2436. args=self.args,
  2437. has_varargs=False,
  2438. exception_check=cfunc_type.exception_check,
  2439. exception_value=exception_value,
  2440. with_gil=cfunc_type.with_gil,
  2441. nogil=cfunc_type.nogil)
  2442. return CFuncDefNode(self.pos,
  2443. modifiers=modifiers or [],
  2444. base_type=CAnalysedBaseTypeNode(self.pos, type=cfunc_type.return_type),
  2445. declarator=declarator,
  2446. body=self.body,
  2447. doc=self.doc,
  2448. overridable=cfunc_type.is_overridable,
  2449. type=cfunc_type,
  2450. with_gil=cfunc_type.with_gil,
  2451. nogil=cfunc_type.nogil,
  2452. visibility='private',
  2453. api=False,
  2454. directive_locals=getattr(cfunc, 'directive_locals', {}),
  2455. directive_returns=returns)
  2456. def is_cdef_func_compatible(self):
  2457. """Determines if the function's signature is compatible with a
  2458. cdef function. This can be used before calling
  2459. .as_cfunction() to see if that will be successful.
  2460. """
  2461. if self.needs_closure:
  2462. return False
  2463. if self.star_arg or self.starstar_arg:
  2464. return False
  2465. return True
  2466. def analyse_declarations(self, env):
  2467. if self.decorators:
  2468. for decorator in self.decorators:
  2469. func = decorator.decorator
  2470. if func.is_name:
  2471. self.is_classmethod |= func.name == 'classmethod'
  2472. self.is_staticmethod |= func.name == 'staticmethod'
  2473. if self.is_classmethod and env.lookup_here('classmethod'):
  2474. # classmethod() was overridden - not much we can do here ...
  2475. self.is_classmethod = False
  2476. if self.is_staticmethod and env.lookup_here('staticmethod'):
  2477. # staticmethod() was overridden - not much we can do here ...
  2478. self.is_staticmethod = False
  2479. if self.name == '__new__' and env.is_py_class_scope:
  2480. self.is_staticmethod = 1
  2481. self.analyse_argument_types(env)
  2482. if self.name == '<lambda>':
  2483. self.declare_lambda_function(env)
  2484. else:
  2485. self.declare_pyfunction(env)
  2486. self.analyse_signature(env)
  2487. self.return_type = self.entry.signature.return_type()
  2488. # if a signature annotation provides a more specific return object type, use it
  2489. if self.return_type is py_object_type and self.return_type_annotation:
  2490. if env.directives['annotation_typing'] and not self.entry.is_special:
  2491. _, return_type = analyse_type_annotation(self.return_type_annotation, env)
  2492. if return_type and return_type.is_pyobject:
  2493. self.return_type = return_type
  2494. self.create_local_scope(env)
  2495. self.py_wrapper = DefNodeWrapper(
  2496. self.pos,
  2497. target=self,
  2498. name=self.entry.name,
  2499. args=self.args,
  2500. star_arg=self.star_arg,
  2501. starstar_arg=self.starstar_arg,
  2502. return_type=self.return_type)
  2503. self.py_wrapper.analyse_declarations(env)
  2504. def analyse_argument_types(self, env):
  2505. self.directive_locals = env.directives['locals']
  2506. allow_none_for_extension_args = env.directives['allow_none_for_extension_args']
  2507. f2s = env.fused_to_specific
  2508. env.fused_to_specific = None
  2509. for arg in self.args:
  2510. if hasattr(arg, 'name'):
  2511. name_declarator = None
  2512. else:
  2513. base_type = arg.base_type.analyse(env)
  2514. # If we hare in pythran mode and we got a buffer supported by
  2515. # Pythran, we change this node to a fused type
  2516. if has_np_pythran(env) and base_type.is_pythran_expr:
  2517. base_type = PyrexTypes.FusedType([
  2518. base_type,
  2519. #PyrexTypes.PythranExpr(pythran_type(self.type, "numpy_texpr")),
  2520. base_type.org_buffer])
  2521. name_declarator, type = \
  2522. arg.declarator.analyse(base_type, env)
  2523. arg.name = name_declarator.name
  2524. arg.type = type
  2525. if type.is_fused:
  2526. self.has_fused_arguments = True
  2527. self.align_argument_type(env, arg)
  2528. if name_declarator and name_declarator.cname:
  2529. error(self.pos, "Python function argument cannot have C name specification")
  2530. arg.type = arg.type.as_argument_type()
  2531. arg.hdr_type = None
  2532. arg.needs_conversion = 0
  2533. arg.needs_type_test = 0
  2534. arg.is_generic = 1
  2535. if arg.type.is_pyobject or arg.type.is_buffer or arg.type.is_memoryviewslice:
  2536. if arg.or_none:
  2537. arg.accept_none = True
  2538. elif arg.not_none:
  2539. arg.accept_none = False
  2540. elif (arg.type.is_extension_type or arg.type.is_builtin_type
  2541. or arg.type.is_buffer or arg.type.is_memoryviewslice):
  2542. if arg.default and arg.default.constant_result is None:
  2543. # special case: def func(MyType obj = None)
  2544. arg.accept_none = True
  2545. else:
  2546. # default depends on compiler directive
  2547. arg.accept_none = allow_none_for_extension_args
  2548. else:
  2549. # probably just a plain 'object'
  2550. arg.accept_none = True
  2551. else:
  2552. arg.accept_none = True # won't be used, but must be there
  2553. if arg.not_none:
  2554. error(arg.pos, "Only Python type arguments can have 'not None'")
  2555. if arg.or_none:
  2556. error(arg.pos, "Only Python type arguments can have 'or None'")
  2557. env.fused_to_specific = f2s
  2558. if has_np_pythran(env):
  2559. self.np_args_idx = [i for i,a in enumerate(self.args) if a.type.is_numpy_buffer]
  2560. else:
  2561. self.np_args_idx = []
  2562. def analyse_signature(self, env):
  2563. if self.entry.is_special:
  2564. if self.decorators:
  2565. error(self.pos, "special functions of cdef classes cannot have decorators")
  2566. self.entry.trivial_signature = len(self.args) == 1 and not (self.star_arg or self.starstar_arg)
  2567. elif not env.directives['always_allow_keywords'] and not (self.star_arg or self.starstar_arg):
  2568. # Use the simpler calling signature for zero- and one-argument functions.
  2569. if self.entry.signature is TypeSlots.pyfunction_signature:
  2570. if len(self.args) == 0:
  2571. self.entry.signature = TypeSlots.pyfunction_noargs
  2572. elif len(self.args) == 1:
  2573. if self.args[0].default is None and not self.args[0].kw_only:
  2574. self.entry.signature = TypeSlots.pyfunction_onearg
  2575. elif self.entry.signature is TypeSlots.pymethod_signature:
  2576. if len(self.args) == 1:
  2577. self.entry.signature = TypeSlots.unaryfunc
  2578. elif len(self.args) == 2:
  2579. if self.args[1].default is None and not self.args[1].kw_only:
  2580. self.entry.signature = TypeSlots.ibinaryfunc
  2581. sig = self.entry.signature
  2582. nfixed = sig.num_fixed_args()
  2583. if (sig is TypeSlots.pymethod_signature and nfixed == 1
  2584. and len(self.args) == 0 and self.star_arg):
  2585. # this is the only case where a diverging number of
  2586. # arguments is not an error - when we have no explicit
  2587. # 'self' parameter as in method(*args)
  2588. sig = self.entry.signature = TypeSlots.pyfunction_signature # self is not 'really' used
  2589. self.self_in_stararg = 1
  2590. nfixed = 0
  2591. if self.is_staticmethod and env.is_c_class_scope:
  2592. nfixed = 0
  2593. self.self_in_stararg = True # FIXME: why for staticmethods?
  2594. self.entry.signature = sig = copy.copy(sig)
  2595. sig.fixed_arg_format = "*"
  2596. sig.is_staticmethod = True
  2597. sig.has_generic_args = True
  2598. if ((self.is_classmethod or self.is_staticmethod) and
  2599. self.has_fused_arguments and env.is_c_class_scope):
  2600. del self.decorator_indirection.stats[:]
  2601. for i in range(min(nfixed, len(self.args))):
  2602. arg = self.args[i]
  2603. arg.is_generic = 0
  2604. if sig.is_self_arg(i) and not self.is_staticmethod:
  2605. if self.is_classmethod:
  2606. arg.is_type_arg = 1
  2607. arg.hdr_type = arg.type = Builtin.type_type
  2608. else:
  2609. arg.is_self_arg = 1
  2610. arg.hdr_type = arg.type = env.parent_type
  2611. arg.needs_conversion = 0
  2612. else:
  2613. arg.hdr_type = sig.fixed_arg_type(i)
  2614. if not arg.type.same_as(arg.hdr_type):
  2615. if arg.hdr_type.is_pyobject and arg.type.is_pyobject:
  2616. arg.needs_type_test = 1
  2617. else:
  2618. arg.needs_conversion = 1
  2619. if arg.needs_conversion:
  2620. arg.hdr_cname = Naming.arg_prefix + arg.name
  2621. else:
  2622. arg.hdr_cname = Naming.var_prefix + arg.name
  2623. if nfixed > len(self.args):
  2624. self.bad_signature()
  2625. return
  2626. elif nfixed < len(self.args):
  2627. if not sig.has_generic_args:
  2628. self.bad_signature()
  2629. for arg in self.args:
  2630. if arg.is_generic and (arg.type.is_extension_type or arg.type.is_builtin_type):
  2631. arg.needs_type_test = 1
  2632. def bad_signature(self):
  2633. sig = self.entry.signature
  2634. expected_str = "%d" % sig.num_fixed_args()
  2635. if sig.has_generic_args:
  2636. expected_str += " or more"
  2637. name = self.name
  2638. if name.startswith("__") and name.endswith("__"):
  2639. desc = "Special method"
  2640. else:
  2641. desc = "Method"
  2642. error(self.pos, "%s %s has wrong number of arguments (%d declared, %s expected)" % (
  2643. desc, self.name, len(self.args), expected_str))
  2644. def declare_pyfunction(self, env):
  2645. #print "DefNode.declare_pyfunction:", self.name, "in", env ###
  2646. name = self.name
  2647. entry = env.lookup_here(name)
  2648. if entry:
  2649. if entry.is_final_cmethod and not env.parent_type.is_final_type:
  2650. error(self.pos, "Only final types can have final Python (def/cpdef) methods")
  2651. if entry.type.is_cfunction and not entry.is_builtin_cmethod and not self.is_wrapper:
  2652. warning(self.pos, "Overriding cdef method with def method.", 5)
  2653. entry = env.declare_pyfunction(name, self.pos, allow_redefine=not self.is_wrapper)
  2654. self.entry = entry
  2655. prefix = env.next_id(env.scope_prefix)
  2656. self.entry.pyfunc_cname = Naming.pyfunc_prefix + prefix + name
  2657. if Options.docstrings:
  2658. entry.doc = embed_position(self.pos, self.doc)
  2659. entry.doc_cname = Naming.funcdoc_prefix + prefix + name
  2660. if entry.is_special:
  2661. if entry.name in TypeSlots.invisible or not entry.doc or (
  2662. entry.name in '__getattr__' and env.directives['fast_getattr']):
  2663. entry.wrapperbase_cname = None
  2664. else:
  2665. entry.wrapperbase_cname = Naming.wrapperbase_prefix + prefix + name
  2666. else:
  2667. entry.doc = None
  2668. def declare_lambda_function(self, env):
  2669. entry = env.declare_lambda_function(self.lambda_name, self.pos)
  2670. entry.doc = None
  2671. self.entry = entry
  2672. self.entry.pyfunc_cname = entry.cname
  2673. def declare_arguments(self, env):
  2674. for arg in self.args:
  2675. if not arg.name:
  2676. error(arg.pos, "Missing argument name")
  2677. if arg.needs_conversion:
  2678. arg.entry = env.declare_var(arg.name, arg.type, arg.pos)
  2679. if arg.type.is_pyobject:
  2680. arg.entry.init = "0"
  2681. else:
  2682. arg.entry = self.declare_argument(env, arg)
  2683. arg.entry.is_arg = 1
  2684. arg.entry.used = 1
  2685. arg.entry.is_self_arg = arg.is_self_arg
  2686. self.declare_python_arg(env, self.star_arg)
  2687. self.declare_python_arg(env, self.starstar_arg)
  2688. def declare_python_arg(self, env, arg):
  2689. if arg:
  2690. if env.directives['infer_types'] != False:
  2691. type = PyrexTypes.unspecified_type
  2692. else:
  2693. type = py_object_type
  2694. entry = env.declare_var(arg.name, type, arg.pos)
  2695. entry.is_arg = 1
  2696. entry.used = 1
  2697. entry.init = "0"
  2698. entry.xdecref_cleanup = 1
  2699. arg.entry = entry
  2700. def analyse_expressions(self, env):
  2701. self.local_scope.directives = env.directives
  2702. self.analyse_default_values(env)
  2703. self.analyse_annotations(env)
  2704. if self.return_type_annotation:
  2705. self.return_type_annotation = self.analyse_annotation(env, self.return_type_annotation)
  2706. if not self.needs_assignment_synthesis(env) and self.decorators:
  2707. for decorator in self.decorators[::-1]:
  2708. decorator.decorator = decorator.decorator.analyse_expressions(env)
  2709. self.py_wrapper.prepare_argument_coercion(env)
  2710. return self
  2711. def needs_assignment_synthesis(self, env, code=None):
  2712. if self.is_staticmethod:
  2713. return True
  2714. if self.specialized_cpdefs or self.entry.is_fused_specialized:
  2715. return False
  2716. if self.no_assignment_synthesis:
  2717. return False
  2718. if self.entry.is_special:
  2719. return False
  2720. if self.entry.is_anonymous:
  2721. return True
  2722. if env.is_module_scope or env.is_c_class_scope:
  2723. if code is None:
  2724. return self.local_scope.directives['binding']
  2725. else:
  2726. return code.globalstate.directives['binding']
  2727. return env.is_py_class_scope or env.is_closure_scope
  2728. def error_value(self):
  2729. return self.entry.signature.error_value
  2730. def caller_will_check_exceptions(self):
  2731. return self.entry.signature.exception_check
  2732. def generate_function_definitions(self, env, code):
  2733. if self.defaults_getter:
  2734. # defaults getter must never live in class scopes, it's always a module function
  2735. self.defaults_getter.generate_function_definitions(env.global_scope(), code)
  2736. # Before closure cnames are mangled
  2737. if self.py_wrapper_required:
  2738. # func_cname might be modified by @cname
  2739. self.py_wrapper.func_cname = self.entry.func_cname
  2740. self.py_wrapper.generate_function_definitions(env, code)
  2741. FuncDefNode.generate_function_definitions(self, env, code)
  2742. def generate_function_header(self, code, with_pymethdef, proto_only=0):
  2743. if proto_only:
  2744. if self.py_wrapper_required:
  2745. self.py_wrapper.generate_function_header(
  2746. code, with_pymethdef, True)
  2747. return
  2748. arg_code_list = []
  2749. if self.entry.signature.has_dummy_arg:
  2750. self_arg = 'PyObject *%s' % Naming.self_cname
  2751. if not self.needs_outer_scope:
  2752. self_arg = 'CYTHON_UNUSED ' + self_arg
  2753. arg_code_list.append(self_arg)
  2754. def arg_decl_code(arg):
  2755. entry = arg.entry
  2756. if entry.in_closure:
  2757. cname = entry.original_cname
  2758. else:
  2759. cname = entry.cname
  2760. decl = entry.type.declaration_code(cname)
  2761. if not entry.cf_used:
  2762. decl = 'CYTHON_UNUSED ' + decl
  2763. return decl
  2764. for arg in self.args:
  2765. arg_code_list.append(arg_decl_code(arg))
  2766. if self.star_arg:
  2767. arg_code_list.append(arg_decl_code(self.star_arg))
  2768. if self.starstar_arg:
  2769. arg_code_list.append(arg_decl_code(self.starstar_arg))
  2770. if arg_code_list:
  2771. arg_code = ', '.join(arg_code_list)
  2772. else:
  2773. arg_code = 'void' # No arguments
  2774. dc = self.return_type.declaration_code(self.entry.pyfunc_cname)
  2775. decls_code = code.globalstate['decls']
  2776. preprocessor_guard = self.get_preprocessor_guard()
  2777. if preprocessor_guard:
  2778. decls_code.putln(preprocessor_guard)
  2779. decls_code.putln(
  2780. "static %s(%s); /* proto */" % (dc, arg_code))
  2781. if preprocessor_guard:
  2782. decls_code.putln("#endif")
  2783. code.putln("static %s(%s) {" % (dc, arg_code))
  2784. def generate_argument_declarations(self, env, code):
  2785. pass
  2786. def generate_keyword_list(self, code):
  2787. pass
  2788. def generate_argument_parsing_code(self, env, code):
  2789. # Move arguments into closure if required
  2790. def put_into_closure(entry):
  2791. if entry.in_closure:
  2792. code.putln('%s = %s;' % (entry.cname, entry.original_cname))
  2793. code.put_var_incref(entry)
  2794. code.put_var_giveref(entry)
  2795. for arg in self.args:
  2796. put_into_closure(arg.entry)
  2797. for arg in self.star_arg, self.starstar_arg:
  2798. if arg:
  2799. put_into_closure(arg.entry)
  2800. def generate_argument_type_tests(self, code):
  2801. pass
  2802. class DefNodeWrapper(FuncDefNode):
  2803. # DefNode python wrapper code generator
  2804. defnode = None
  2805. target = None # Target DefNode
  2806. def __init__(self, *args, **kwargs):
  2807. FuncDefNode.__init__(self, *args, **kwargs)
  2808. self.num_kwonly_args = self.target.num_kwonly_args
  2809. self.num_required_kw_args = self.target.num_required_kw_args
  2810. self.num_required_args = self.target.num_required_args
  2811. self.self_in_stararg = self.target.self_in_stararg
  2812. self.signature = None
  2813. def analyse_declarations(self, env):
  2814. target_entry = self.target.entry
  2815. name = self.name
  2816. prefix = env.next_id(env.scope_prefix)
  2817. target_entry.func_cname = Naming.pywrap_prefix + prefix + name
  2818. target_entry.pymethdef_cname = Naming.pymethdef_prefix + prefix + name
  2819. self.signature = target_entry.signature
  2820. self.np_args_idx = self.target.np_args_idx
  2821. def prepare_argument_coercion(self, env):
  2822. # This is only really required for Cython utility code at this time,
  2823. # everything else can be done during code generation. But we expand
  2824. # all utility code here, simply because we cannot easily distinguish
  2825. # different code types.
  2826. for arg in self.args:
  2827. if not arg.type.is_pyobject:
  2828. if not arg.type.create_from_py_utility_code(env):
  2829. pass # will fail later
  2830. elif arg.hdr_type and not arg.hdr_type.is_pyobject:
  2831. if not arg.hdr_type.create_to_py_utility_code(env):
  2832. pass # will fail later
  2833. if self.starstar_arg and not self.starstar_arg.entry.cf_used:
  2834. # we will set the kwargs argument to NULL instead of a new dict
  2835. # and must therefore correct the control flow state
  2836. entry = self.starstar_arg.entry
  2837. entry.xdecref_cleanup = 1
  2838. for ass in entry.cf_assignments:
  2839. if not ass.is_arg and ass.lhs.is_name:
  2840. ass.lhs.cf_maybe_null = True
  2841. def signature_has_nongeneric_args(self):
  2842. argcount = len(self.args)
  2843. if argcount == 0 or (
  2844. argcount == 1 and (self.args[0].is_self_arg or
  2845. self.args[0].is_type_arg)):
  2846. return 0
  2847. return 1
  2848. def signature_has_generic_args(self):
  2849. return self.signature.has_generic_args
  2850. def generate_function_body(self, code):
  2851. args = []
  2852. if self.signature.has_dummy_arg:
  2853. args.append(Naming.self_cname)
  2854. for arg in self.args:
  2855. if arg.hdr_type and not (arg.type.is_memoryviewslice or
  2856. arg.type.is_struct or
  2857. arg.type.is_complex):
  2858. args.append(arg.type.cast_code(arg.entry.cname))
  2859. else:
  2860. args.append(arg.entry.cname)
  2861. if self.star_arg:
  2862. args.append(self.star_arg.entry.cname)
  2863. if self.starstar_arg:
  2864. args.append(self.starstar_arg.entry.cname)
  2865. args = ', '.join(args)
  2866. if not self.return_type.is_void:
  2867. code.put('%s = ' % Naming.retval_cname)
  2868. code.putln('%s(%s);' % (
  2869. self.target.entry.pyfunc_cname, args))
  2870. def generate_function_definitions(self, env, code):
  2871. lenv = self.target.local_scope
  2872. # Generate C code for header and body of function
  2873. code.mark_pos(self.pos)
  2874. code.putln("")
  2875. code.putln("/* Python wrapper */")
  2876. preprocessor_guard = self.target.get_preprocessor_guard()
  2877. if preprocessor_guard:
  2878. code.putln(preprocessor_guard)
  2879. code.enter_cfunc_scope(lenv)
  2880. code.return_from_error_cleanup_label = code.new_label()
  2881. with_pymethdef = (self.target.needs_assignment_synthesis(env, code) or
  2882. self.target.pymethdef_required)
  2883. self.generate_function_header(code, with_pymethdef)
  2884. self.generate_argument_declarations(lenv, code)
  2885. tempvardecl_code = code.insertion_point()
  2886. if self.return_type.is_pyobject:
  2887. retval_init = ' = 0'
  2888. else:
  2889. retval_init = ''
  2890. if not self.return_type.is_void:
  2891. code.putln('%s%s;' % (
  2892. self.return_type.declaration_code(Naming.retval_cname),
  2893. retval_init))
  2894. code.put_declare_refcount_context()
  2895. code.put_setup_refcount_context('%s (wrapper)' % self.name)
  2896. self.generate_argument_parsing_code(lenv, code)
  2897. self.generate_argument_type_tests(code)
  2898. self.generate_function_body(code)
  2899. # ----- Go back and insert temp variable declarations
  2900. tempvardecl_code.put_temp_declarations(code.funcstate)
  2901. code.mark_pos(self.pos)
  2902. code.putln("")
  2903. code.putln("/* function exit code */")
  2904. # ----- Error cleanup
  2905. if code.error_label in code.labels_used:
  2906. code.put_goto(code.return_label)
  2907. code.put_label(code.error_label)
  2908. for cname, type in code.funcstate.all_managed_temps():
  2909. code.put_xdecref(cname, type)
  2910. err_val = self.error_value()
  2911. if err_val is not None:
  2912. code.putln("%s = %s;" % (Naming.retval_cname, err_val))
  2913. # ----- Non-error return cleanup
  2914. code.put_label(code.return_label)
  2915. for entry in lenv.var_entries:
  2916. if entry.is_arg and entry.type.is_pyobject:
  2917. code.put_var_decref(entry)
  2918. code.put_finish_refcount_context()
  2919. if not self.return_type.is_void:
  2920. code.putln("return %s;" % Naming.retval_cname)
  2921. code.putln('}')
  2922. code.exit_cfunc_scope()
  2923. if preprocessor_guard:
  2924. code.putln("#endif /*!(%s)*/" % preprocessor_guard)
  2925. def generate_function_header(self, code, with_pymethdef, proto_only=0):
  2926. arg_code_list = []
  2927. sig = self.signature
  2928. if sig.has_dummy_arg or self.self_in_stararg:
  2929. arg_code = "PyObject *%s" % Naming.self_cname
  2930. if not sig.has_dummy_arg:
  2931. arg_code = 'CYTHON_UNUSED ' + arg_code
  2932. arg_code_list.append(arg_code)
  2933. for arg in self.args:
  2934. if not arg.is_generic:
  2935. if arg.is_self_arg or arg.is_type_arg:
  2936. arg_code_list.append("PyObject *%s" % arg.hdr_cname)
  2937. else:
  2938. arg_code_list.append(
  2939. arg.hdr_type.declaration_code(arg.hdr_cname))
  2940. entry = self.target.entry
  2941. if not entry.is_special and sig.method_flags() == [TypeSlots.method_noargs]:
  2942. arg_code_list.append("CYTHON_UNUSED PyObject *unused")
  2943. if entry.scope.is_c_class_scope and entry.name == "__ipow__":
  2944. arg_code_list.append("CYTHON_UNUSED PyObject *unused")
  2945. if sig.has_generic_args:
  2946. arg_code_list.append(
  2947. "PyObject *%s, PyObject *%s" % (
  2948. Naming.args_cname, Naming.kwds_cname))
  2949. arg_code = ", ".join(arg_code_list)
  2950. # Prevent warning: unused function '__pyx_pw_5numpy_7ndarray_1__getbuffer__'
  2951. mf = ""
  2952. if (entry.name in ("__getbuffer__", "__releasebuffer__")
  2953. and entry.scope.is_c_class_scope):
  2954. mf = "CYTHON_UNUSED "
  2955. with_pymethdef = False
  2956. dc = self.return_type.declaration_code(entry.func_cname)
  2957. header = "static %s%s(%s)" % (mf, dc, arg_code)
  2958. code.putln("%s; /*proto*/" % header)
  2959. if proto_only:
  2960. if self.target.fused_py_func:
  2961. # If we are the specialized version of the cpdef, we still
  2962. # want the prototype for the "fused cpdef", in case we're
  2963. # checking to see if our method was overridden in Python
  2964. self.target.fused_py_func.generate_function_header(
  2965. code, with_pymethdef, proto_only=True)
  2966. return
  2967. if (Options.docstrings and entry.doc and
  2968. not self.target.fused_py_func and
  2969. not entry.scope.is_property_scope and
  2970. (not entry.is_special or entry.wrapperbase_cname)):
  2971. # h_code = code.globalstate['h_code']
  2972. docstr = entry.doc
  2973. if docstr.is_unicode:
  2974. docstr = docstr.as_utf8_string()
  2975. code.putln(
  2976. 'static char %s[] = %s;' % (
  2977. entry.doc_cname,
  2978. docstr.as_c_string_literal()))
  2979. if entry.is_special:
  2980. code.putln('#if CYTHON_COMPILING_IN_CPYTHON')
  2981. code.putln(
  2982. "struct wrapperbase %s;" % entry.wrapperbase_cname)
  2983. code.putln('#endif')
  2984. if with_pymethdef or self.target.fused_py_func:
  2985. code.put(
  2986. "static PyMethodDef %s = " % entry.pymethdef_cname)
  2987. code.put_pymethoddef(self.target.entry, ";", allow_skip=False)
  2988. code.putln("%s {" % header)
  2989. def generate_argument_declarations(self, env, code):
  2990. for arg in self.args:
  2991. if arg.is_generic:
  2992. if arg.needs_conversion:
  2993. code.putln("PyObject *%s = 0;" % arg.hdr_cname)
  2994. else:
  2995. code.put_var_declaration(arg.entry)
  2996. for entry in env.var_entries:
  2997. if entry.is_arg:
  2998. code.put_var_declaration(entry)
  2999. def generate_argument_parsing_code(self, env, code):
  3000. # Generate fast equivalent of PyArg_ParseTuple call for
  3001. # generic arguments, if any, including args/kwargs
  3002. old_error_label = code.new_error_label()
  3003. our_error_label = code.error_label
  3004. end_label = code.new_label("argument_unpacking_done")
  3005. has_kwonly_args = self.num_kwonly_args > 0
  3006. has_star_or_kw_args = self.star_arg is not None \
  3007. or self.starstar_arg is not None or has_kwonly_args
  3008. for arg in self.args:
  3009. if not arg.type.is_pyobject:
  3010. if not arg.type.create_from_py_utility_code(env):
  3011. pass # will fail later
  3012. if not self.signature_has_generic_args():
  3013. if has_star_or_kw_args:
  3014. error(self.pos, "This method cannot have * or keyword arguments")
  3015. self.generate_argument_conversion_code(code)
  3016. elif not self.signature_has_nongeneric_args():
  3017. # func(*args) or func(**kw) or func(*args, **kw)
  3018. self.generate_stararg_copy_code(code)
  3019. else:
  3020. self.generate_tuple_and_keyword_parsing_code(self.args, end_label, code)
  3021. code.error_label = old_error_label
  3022. if code.label_used(our_error_label):
  3023. if not code.label_used(end_label):
  3024. code.put_goto(end_label)
  3025. code.put_label(our_error_label)
  3026. if has_star_or_kw_args:
  3027. self.generate_arg_decref(self.star_arg, code)
  3028. if self.starstar_arg:
  3029. if self.starstar_arg.entry.xdecref_cleanup:
  3030. code.put_var_xdecref_clear(self.starstar_arg.entry)
  3031. else:
  3032. code.put_var_decref_clear(self.starstar_arg.entry)
  3033. code.put_add_traceback(self.target.entry.qualified_name)
  3034. code.put_finish_refcount_context()
  3035. code.putln("return %s;" % self.error_value())
  3036. if code.label_used(end_label):
  3037. code.put_label(end_label)
  3038. def generate_arg_xdecref(self, arg, code):
  3039. if arg:
  3040. code.put_var_xdecref_clear(arg.entry)
  3041. def generate_arg_decref(self, arg, code):
  3042. if arg:
  3043. code.put_var_decref_clear(arg.entry)
  3044. def generate_stararg_copy_code(self, code):
  3045. if not self.star_arg:
  3046. code.globalstate.use_utility_code(
  3047. UtilityCode.load_cached("RaiseArgTupleInvalid", "FunctionArguments.c"))
  3048. code.putln("if (unlikely(PyTuple_GET_SIZE(%s) > 0)) {" %
  3049. Naming.args_cname)
  3050. code.put('__Pyx_RaiseArgtupleInvalid("%s", 1, 0, 0, PyTuple_GET_SIZE(%s)); return %s;' % (
  3051. self.name, Naming.args_cname, self.error_value()))
  3052. code.putln("}")
  3053. if self.starstar_arg:
  3054. if self.star_arg or not self.starstar_arg.entry.cf_used:
  3055. kwarg_check = "unlikely(%s)" % Naming.kwds_cname
  3056. else:
  3057. kwarg_check = "%s" % Naming.kwds_cname
  3058. else:
  3059. kwarg_check = "unlikely(%s) && unlikely(PyDict_Size(%s) > 0)" % (
  3060. Naming.kwds_cname, Naming.kwds_cname)
  3061. code.globalstate.use_utility_code(
  3062. UtilityCode.load_cached("KeywordStringCheck", "FunctionArguments.c"))
  3063. code.putln(
  3064. "if (%s && unlikely(!__Pyx_CheckKeywordStrings(%s, \"%s\", %d))) return %s;" % (
  3065. kwarg_check, Naming.kwds_cname, self.name,
  3066. bool(self.starstar_arg), self.error_value()))
  3067. if self.starstar_arg and self.starstar_arg.entry.cf_used:
  3068. if all(ref.node.allow_null for ref in self.starstar_arg.entry.cf_references):
  3069. code.putln("if (%s) {" % kwarg_check)
  3070. code.putln("%s = PyDict_Copy(%s); if (unlikely(!%s)) return %s;" % (
  3071. self.starstar_arg.entry.cname,
  3072. Naming.kwds_cname,
  3073. self.starstar_arg.entry.cname,
  3074. self.error_value()))
  3075. code.put_gotref(self.starstar_arg.entry.cname)
  3076. code.putln("} else {")
  3077. code.putln("%s = NULL;" % (self.starstar_arg.entry.cname,))
  3078. code.putln("}")
  3079. self.starstar_arg.entry.xdecref_cleanup = 1
  3080. else:
  3081. code.put("%s = (%s) ? PyDict_Copy(%s) : PyDict_New(); " % (
  3082. self.starstar_arg.entry.cname,
  3083. Naming.kwds_cname,
  3084. Naming.kwds_cname))
  3085. code.putln("if (unlikely(!%s)) return %s;" % (
  3086. self.starstar_arg.entry.cname, self.error_value()))
  3087. self.starstar_arg.entry.xdecref_cleanup = 0
  3088. code.put_gotref(self.starstar_arg.entry.cname)
  3089. if self.self_in_stararg and not self.target.is_staticmethod:
  3090. # need to create a new tuple with 'self' inserted as first item
  3091. code.put("%s = PyTuple_New(PyTuple_GET_SIZE(%s)+1); if (unlikely(!%s)) " % (
  3092. self.star_arg.entry.cname,
  3093. Naming.args_cname,
  3094. self.star_arg.entry.cname))
  3095. if self.starstar_arg and self.starstar_arg.entry.cf_used:
  3096. code.putln("{")
  3097. code.put_xdecref_clear(self.starstar_arg.entry.cname, py_object_type)
  3098. code.putln("return %s;" % self.error_value())
  3099. code.putln("}")
  3100. else:
  3101. code.putln("return %s;" % self.error_value())
  3102. code.put_gotref(self.star_arg.entry.cname)
  3103. code.put_incref(Naming.self_cname, py_object_type)
  3104. code.put_giveref(Naming.self_cname)
  3105. code.putln("PyTuple_SET_ITEM(%s, 0, %s);" % (
  3106. self.star_arg.entry.cname, Naming.self_cname))
  3107. temp = code.funcstate.allocate_temp(PyrexTypes.c_py_ssize_t_type, manage_ref=False)
  3108. code.putln("for (%s=0; %s < PyTuple_GET_SIZE(%s); %s++) {" % (
  3109. temp, temp, Naming.args_cname, temp))
  3110. code.putln("PyObject* item = PyTuple_GET_ITEM(%s, %s);" % (
  3111. Naming.args_cname, temp))
  3112. code.put_incref("item", py_object_type)
  3113. code.put_giveref("item")
  3114. code.putln("PyTuple_SET_ITEM(%s, %s+1, item);" % (
  3115. self.star_arg.entry.cname, temp))
  3116. code.putln("}")
  3117. code.funcstate.release_temp(temp)
  3118. self.star_arg.entry.xdecref_cleanup = 0
  3119. elif self.star_arg:
  3120. code.put_incref(Naming.args_cname, py_object_type)
  3121. code.putln("%s = %s;" % (
  3122. self.star_arg.entry.cname,
  3123. Naming.args_cname))
  3124. self.star_arg.entry.xdecref_cleanup = 0
  3125. def generate_tuple_and_keyword_parsing_code(self, args, success_label, code):
  3126. argtuple_error_label = code.new_label("argtuple_error")
  3127. positional_args = []
  3128. required_kw_only_args = []
  3129. optional_kw_only_args = []
  3130. for arg in args:
  3131. if arg.is_generic:
  3132. if arg.default:
  3133. if not arg.is_self_arg and not arg.is_type_arg:
  3134. if arg.kw_only:
  3135. optional_kw_only_args.append(arg)
  3136. else:
  3137. positional_args.append(arg)
  3138. elif arg.kw_only:
  3139. required_kw_only_args.append(arg)
  3140. elif not arg.is_self_arg and not arg.is_type_arg:
  3141. positional_args.append(arg)
  3142. # sort required kw-only args before optional ones to avoid special
  3143. # cases in the unpacking code
  3144. kw_only_args = required_kw_only_args + optional_kw_only_args
  3145. min_positional_args = self.num_required_args - self.num_required_kw_args
  3146. if len(args) > 0 and (args[0].is_self_arg or args[0].is_type_arg):
  3147. min_positional_args -= 1
  3148. max_positional_args = len(positional_args)
  3149. has_fixed_positional_count = not self.star_arg and \
  3150. min_positional_args == max_positional_args
  3151. has_kw_only_args = bool(kw_only_args)
  3152. if self.starstar_arg or self.star_arg:
  3153. self.generate_stararg_init_code(max_positional_args, code)
  3154. code.putln('{')
  3155. all_args = tuple(positional_args) + tuple(kw_only_args)
  3156. code.putln("static PyObject **%s[] = {%s,0};" % (
  3157. Naming.pykwdlist_cname,
  3158. ','.join(['&%s' % code.intern_identifier(arg.name)
  3159. for arg in all_args])))
  3160. # Before being converted and assigned to the target variables,
  3161. # borrowed references to all unpacked argument values are
  3162. # collected into a local PyObject* array called "values",
  3163. # regardless if they were taken from default arguments,
  3164. # positional arguments or keyword arguments. Note that
  3165. # C-typed default arguments are handled at conversion time,
  3166. # so their array value is NULL in the end if no argument
  3167. # was passed for them.
  3168. self.generate_argument_values_setup_code(all_args, code)
  3169. # --- optimised code when we receive keyword arguments
  3170. code.putln("if (%s(%s)) {" % (
  3171. (self.num_required_kw_args > 0) and "likely" or "unlikely",
  3172. Naming.kwds_cname))
  3173. self.generate_keyword_unpacking_code(
  3174. min_positional_args, max_positional_args,
  3175. has_fixed_positional_count, has_kw_only_args,
  3176. all_args, argtuple_error_label, code)
  3177. # --- optimised code when we do not receive any keyword arguments
  3178. if (self.num_required_kw_args and min_positional_args > 0) or min_positional_args == max_positional_args:
  3179. # Python raises arg tuple related errors first, so we must
  3180. # check the length here
  3181. if min_positional_args == max_positional_args and not self.star_arg:
  3182. compare = '!='
  3183. else:
  3184. compare = '<'
  3185. code.putln('} else if (PyTuple_GET_SIZE(%s) %s %d) {' % (
  3186. Naming.args_cname, compare, min_positional_args))
  3187. code.put_goto(argtuple_error_label)
  3188. if self.num_required_kw_args:
  3189. # pure error case: keywords required but not passed
  3190. if max_positional_args > min_positional_args and not self.star_arg:
  3191. code.putln('} else if (PyTuple_GET_SIZE(%s) > %d) {' % (
  3192. Naming.args_cname, max_positional_args))
  3193. code.put_goto(argtuple_error_label)
  3194. code.putln('} else {')
  3195. for i, arg in enumerate(kw_only_args):
  3196. if not arg.default:
  3197. pystring_cname = code.intern_identifier(arg.name)
  3198. # required keyword-only argument missing
  3199. code.globalstate.use_utility_code(
  3200. UtilityCode.load_cached("RaiseKeywordRequired", "FunctionArguments.c"))
  3201. code.put('__Pyx_RaiseKeywordRequired("%s", %s); ' % (
  3202. self.name,
  3203. pystring_cname))
  3204. code.putln(code.error_goto(self.pos))
  3205. break
  3206. else:
  3207. # optimised tuple unpacking code
  3208. code.putln('} else {')
  3209. if min_positional_args == max_positional_args:
  3210. # parse the exact number of positional arguments from
  3211. # the args tuple
  3212. for i, arg in enumerate(positional_args):
  3213. code.putln("values[%d] = PyTuple_GET_ITEM(%s, %d);" % (i, Naming.args_cname, i))
  3214. else:
  3215. # parse the positional arguments from the variable length
  3216. # args tuple and reject illegal argument tuple sizes
  3217. code.putln('switch (PyTuple_GET_SIZE(%s)) {' % Naming.args_cname)
  3218. if self.star_arg:
  3219. code.putln('default:')
  3220. reversed_args = list(enumerate(positional_args))[::-1]
  3221. for i, arg in reversed_args:
  3222. if i >= min_positional_args-1:
  3223. if i != reversed_args[0][0]:
  3224. code.putln('CYTHON_FALLTHROUGH;')
  3225. code.put('case %2d: ' % (i+1))
  3226. code.putln("values[%d] = PyTuple_GET_ITEM(%s, %d);" % (i, Naming.args_cname, i))
  3227. if min_positional_args == 0:
  3228. code.putln('CYTHON_FALLTHROUGH;')
  3229. code.put('case 0: ')
  3230. code.putln('break;')
  3231. if self.star_arg:
  3232. if min_positional_args:
  3233. for i in range(min_positional_args-1, -1, -1):
  3234. code.putln('case %2d:' % i)
  3235. code.put_goto(argtuple_error_label)
  3236. else:
  3237. code.put('default: ')
  3238. code.put_goto(argtuple_error_label)
  3239. code.putln('}')
  3240. code.putln('}') # end of the conditional unpacking blocks
  3241. # Convert arg values to their final type and assign them.
  3242. # Also inject non-Python default arguments, which do cannot
  3243. # live in the values[] array.
  3244. for i, arg in enumerate(all_args):
  3245. self.generate_arg_assignment(arg, "values[%d]" % i, code)
  3246. code.putln('}') # end of the whole argument unpacking block
  3247. if code.label_used(argtuple_error_label):
  3248. code.put_goto(success_label)
  3249. code.put_label(argtuple_error_label)
  3250. code.globalstate.use_utility_code(
  3251. UtilityCode.load_cached("RaiseArgTupleInvalid", "FunctionArguments.c"))
  3252. code.put('__Pyx_RaiseArgtupleInvalid("%s", %d, %d, %d, PyTuple_GET_SIZE(%s)); ' % (
  3253. self.name, has_fixed_positional_count,
  3254. min_positional_args, max_positional_args,
  3255. Naming.args_cname))
  3256. code.putln(code.error_goto(self.pos))
  3257. def generate_arg_assignment(self, arg, item, code):
  3258. if arg.type.is_pyobject:
  3259. # Python default arguments were already stored in 'item' at the very beginning
  3260. if arg.is_generic:
  3261. item = PyrexTypes.typecast(arg.type, PyrexTypes.py_object_type, item)
  3262. entry = arg.entry
  3263. code.putln("%s = %s;" % (entry.cname, item))
  3264. else:
  3265. if arg.type.from_py_function:
  3266. if arg.default:
  3267. # C-typed default arguments must be handled here
  3268. code.putln('if (%s) {' % item)
  3269. code.putln(arg.type.from_py_call_code(
  3270. item, arg.entry.cname, arg.pos, code))
  3271. if arg.default:
  3272. code.putln('} else {')
  3273. code.putln("%s = %s;" % (
  3274. arg.entry.cname,
  3275. arg.calculate_default_value_code(code)))
  3276. if arg.type.is_memoryviewslice:
  3277. code.put_incref_memoryviewslice(arg.entry.cname,
  3278. have_gil=True)
  3279. code.putln('}')
  3280. else:
  3281. error(arg.pos, "Cannot convert Python object argument to type '%s'" % arg.type)
  3282. def generate_stararg_init_code(self, max_positional_args, code):
  3283. if self.starstar_arg:
  3284. self.starstar_arg.entry.xdecref_cleanup = 0
  3285. code.putln('%s = PyDict_New(); if (unlikely(!%s)) return %s;' % (
  3286. self.starstar_arg.entry.cname,
  3287. self.starstar_arg.entry.cname,
  3288. self.error_value()))
  3289. code.put_gotref(self.starstar_arg.entry.cname)
  3290. if self.star_arg:
  3291. self.star_arg.entry.xdecref_cleanup = 0
  3292. code.putln('if (PyTuple_GET_SIZE(%s) > %d) {' % (
  3293. Naming.args_cname,
  3294. max_positional_args))
  3295. code.putln('%s = PyTuple_GetSlice(%s, %d, PyTuple_GET_SIZE(%s));' % (
  3296. self.star_arg.entry.cname, Naming.args_cname,
  3297. max_positional_args, Naming.args_cname))
  3298. code.putln("if (unlikely(!%s)) {" % self.star_arg.entry.cname)
  3299. if self.starstar_arg:
  3300. code.put_decref_clear(self.starstar_arg.entry.cname, py_object_type)
  3301. code.put_finish_refcount_context()
  3302. code.putln('return %s;' % self.error_value())
  3303. code.putln('}')
  3304. code.put_gotref(self.star_arg.entry.cname)
  3305. code.putln('} else {')
  3306. code.put("%s = %s; " % (self.star_arg.entry.cname, Naming.empty_tuple))
  3307. code.put_incref(Naming.empty_tuple, py_object_type)
  3308. code.putln('}')
  3309. def generate_argument_values_setup_code(self, args, code):
  3310. max_args = len(args)
  3311. # the 'values' array collects borrowed references to arguments
  3312. # before doing any type coercion etc.
  3313. code.putln("PyObject* values[%d] = {%s};" % (
  3314. max_args, ','.join('0'*max_args)))
  3315. if self.target.defaults_struct:
  3316. code.putln('%s *%s = __Pyx_CyFunction_Defaults(%s, %s);' % (
  3317. self.target.defaults_struct, Naming.dynamic_args_cname,
  3318. self.target.defaults_struct, Naming.self_cname))
  3319. # assign borrowed Python default values to the values array,
  3320. # so that they can be overwritten by received arguments below
  3321. for i, arg in enumerate(args):
  3322. if arg.default and arg.type.is_pyobject:
  3323. default_value = arg.calculate_default_value_code(code)
  3324. code.putln('values[%d] = %s;' % (i, arg.type.as_pyobject(default_value)))
  3325. def generate_keyword_unpacking_code(self, min_positional_args, max_positional_args,
  3326. has_fixed_positional_count, has_kw_only_args,
  3327. all_args, argtuple_error_label, code):
  3328. code.putln('Py_ssize_t kw_args;')
  3329. code.putln('const Py_ssize_t pos_args = PyTuple_GET_SIZE(%s);' % Naming.args_cname)
  3330. # copy the values from the args tuple and check that it's not too long
  3331. code.putln('switch (pos_args) {')
  3332. if self.star_arg:
  3333. code.putln('default:')
  3334. for i in range(max_positional_args-1, -1, -1):
  3335. code.put('case %2d: ' % (i+1))
  3336. code.putln("values[%d] = PyTuple_GET_ITEM(%s, %d);" % (
  3337. i, Naming.args_cname, i))
  3338. code.putln('CYTHON_FALLTHROUGH;')
  3339. code.putln('case 0: break;')
  3340. if not self.star_arg:
  3341. code.put('default: ') # more arguments than allowed
  3342. code.put_goto(argtuple_error_label)
  3343. code.putln('}')
  3344. # The code above is very often (but not always) the same as
  3345. # the optimised non-kwargs tuple unpacking code, so we keep
  3346. # the code block above at the very top, before the following
  3347. # 'external' PyDict_Size() call, to make it easy for the C
  3348. # compiler to merge the two separate tuple unpacking
  3349. # implementations into one when they turn out to be identical.
  3350. # If we received kwargs, fill up the positional/required
  3351. # arguments with values from the kw dict
  3352. code.putln('kw_args = PyDict_Size(%s);' % Naming.kwds_cname)
  3353. if self.num_required_args or max_positional_args > 0:
  3354. last_required_arg = -1
  3355. for i, arg in enumerate(all_args):
  3356. if not arg.default:
  3357. last_required_arg = i
  3358. if last_required_arg < max_positional_args:
  3359. last_required_arg = max_positional_args-1
  3360. if max_positional_args > 0:
  3361. code.putln('switch (pos_args) {')
  3362. for i, arg in enumerate(all_args[:last_required_arg+1]):
  3363. if max_positional_args > 0 and i <= max_positional_args:
  3364. if i != 0:
  3365. code.putln('CYTHON_FALLTHROUGH;')
  3366. if self.star_arg and i == max_positional_args:
  3367. code.putln('default:')
  3368. else:
  3369. code.putln('case %2d:' % i)
  3370. pystring_cname = code.intern_identifier(arg.name)
  3371. if arg.default:
  3372. if arg.kw_only:
  3373. # optional kw-only args are handled separately below
  3374. continue
  3375. code.putln('if (kw_args > 0) {')
  3376. # don't overwrite default argument
  3377. code.putln('PyObject* value = __Pyx_PyDict_GetItemStr(%s, %s);' % (
  3378. Naming.kwds_cname, pystring_cname))
  3379. code.putln('if (value) { values[%d] = value; kw_args--; }' % i)
  3380. code.putln('}')
  3381. else:
  3382. code.putln('if (likely((values[%d] = __Pyx_PyDict_GetItemStr(%s, %s)) != 0)) kw_args--;' % (
  3383. i, Naming.kwds_cname, pystring_cname))
  3384. if i < min_positional_args:
  3385. if i == 0:
  3386. # special case: we know arg 0 is missing
  3387. code.put('else ')
  3388. code.put_goto(argtuple_error_label)
  3389. else:
  3390. # print the correct number of values (args or
  3391. # kwargs) that were passed into positional
  3392. # arguments up to this point
  3393. code.putln('else {')
  3394. code.globalstate.use_utility_code(
  3395. UtilityCode.load_cached("RaiseArgTupleInvalid", "FunctionArguments.c"))
  3396. code.put('__Pyx_RaiseArgtupleInvalid("%s", %d, %d, %d, %d); ' % (
  3397. self.name, has_fixed_positional_count,
  3398. min_positional_args, max_positional_args, i))
  3399. code.putln(code.error_goto(self.pos))
  3400. code.putln('}')
  3401. elif arg.kw_only:
  3402. code.putln('else {')
  3403. code.globalstate.use_utility_code(
  3404. UtilityCode.load_cached("RaiseKeywordRequired", "FunctionArguments.c"))
  3405. code.put('__Pyx_RaiseKeywordRequired("%s", %s); ' % (
  3406. self.name, pystring_cname))
  3407. code.putln(code.error_goto(self.pos))
  3408. code.putln('}')
  3409. if max_positional_args > 0:
  3410. code.putln('}')
  3411. if has_kw_only_args:
  3412. # unpack optional keyword-only arguments separately because
  3413. # checking for interned strings in a dict is faster than iterating
  3414. self.generate_optional_kwonly_args_unpacking_code(all_args, code)
  3415. code.putln('if (unlikely(kw_args > 0)) {')
  3416. # non-positional/-required kw args left in dict: default args,
  3417. # kw-only args, **kwargs or error
  3418. #
  3419. # This is sort of a catch-all: except for checking required
  3420. # arguments, this will always do the right thing for unpacking
  3421. # keyword arguments, so that we can concentrate on optimising
  3422. # common cases above.
  3423. if max_positional_args == 0:
  3424. pos_arg_count = "0"
  3425. elif self.star_arg:
  3426. code.putln("const Py_ssize_t used_pos_args = (pos_args < %d) ? pos_args : %d;" % (
  3427. max_positional_args, max_positional_args))
  3428. pos_arg_count = "used_pos_args"
  3429. else:
  3430. pos_arg_count = "pos_args"
  3431. code.globalstate.use_utility_code(
  3432. UtilityCode.load_cached("ParseKeywords", "FunctionArguments.c"))
  3433. code.putln('if (unlikely(__Pyx_ParseOptionalKeywords(%s, %s, %s, values, %s, "%s") < 0)) %s' % (
  3434. Naming.kwds_cname,
  3435. Naming.pykwdlist_cname,
  3436. self.starstar_arg and self.starstar_arg.entry.cname or '0',
  3437. pos_arg_count,
  3438. self.name,
  3439. code.error_goto(self.pos)))
  3440. code.putln('}')
  3441. def generate_optional_kwonly_args_unpacking_code(self, all_args, code):
  3442. optional_args = []
  3443. first_optional_arg = -1
  3444. for i, arg in enumerate(all_args):
  3445. if not arg.kw_only or not arg.default:
  3446. continue
  3447. if not optional_args:
  3448. first_optional_arg = i
  3449. optional_args.append(arg.name)
  3450. if optional_args:
  3451. if len(optional_args) > 1:
  3452. # if we receive more than the named kwargs, we either have **kwargs
  3453. # (in which case we must iterate anyway) or it's an error (which we
  3454. # also handle during iteration) => skip this part if there are more
  3455. code.putln('if (kw_args > 0 && %s(kw_args <= %d)) {' % (
  3456. not self.starstar_arg and 'likely' or '',
  3457. len(optional_args)))
  3458. code.putln('Py_ssize_t index;')
  3459. # not unrolling the loop here reduces the C code overhead
  3460. code.putln('for (index = %d; index < %d && kw_args > 0; index++) {' % (
  3461. first_optional_arg, first_optional_arg + len(optional_args)))
  3462. else:
  3463. code.putln('if (kw_args == 1) {')
  3464. code.putln('const Py_ssize_t index = %d;' % first_optional_arg)
  3465. code.putln('PyObject* value = __Pyx_PyDict_GetItemStr(%s, *%s[index]);' % (
  3466. Naming.kwds_cname, Naming.pykwdlist_cname))
  3467. code.putln('if (value) { values[index] = value; kw_args--; }')
  3468. if len(optional_args) > 1:
  3469. code.putln('}')
  3470. code.putln('}')
  3471. def generate_argument_conversion_code(self, code):
  3472. # Generate code to convert arguments from signature type to
  3473. # declared type, if needed. Also copies signature arguments
  3474. # into closure fields.
  3475. for arg in self.args:
  3476. if arg.needs_conversion:
  3477. self.generate_arg_conversion(arg, code)
  3478. def generate_arg_conversion(self, arg, code):
  3479. # Generate conversion code for one argument.
  3480. old_type = arg.hdr_type
  3481. new_type = arg.type
  3482. if old_type.is_pyobject:
  3483. if arg.default:
  3484. code.putln("if (%s) {" % arg.hdr_cname)
  3485. else:
  3486. code.putln("assert(%s); {" % arg.hdr_cname)
  3487. self.generate_arg_conversion_from_pyobject(arg, code)
  3488. code.putln("}")
  3489. elif new_type.is_pyobject:
  3490. self.generate_arg_conversion_to_pyobject(arg, code)
  3491. else:
  3492. if new_type.assignable_from(old_type):
  3493. code.putln("%s = %s;" % (arg.entry.cname, arg.hdr_cname))
  3494. else:
  3495. error(arg.pos, "Cannot convert 1 argument from '%s' to '%s'" % (old_type, new_type))
  3496. def generate_arg_conversion_from_pyobject(self, arg, code):
  3497. new_type = arg.type
  3498. # copied from CoerceFromPyTypeNode
  3499. if new_type.from_py_function:
  3500. code.putln(new_type.from_py_call_code(
  3501. arg.hdr_cname,
  3502. arg.entry.cname,
  3503. arg.pos,
  3504. code,
  3505. ))
  3506. else:
  3507. error(arg.pos, "Cannot convert Python object argument to type '%s'" % new_type)
  3508. def generate_arg_conversion_to_pyobject(self, arg, code):
  3509. old_type = arg.hdr_type
  3510. func = old_type.to_py_function
  3511. if func:
  3512. code.putln("%s = %s(%s); %s" % (
  3513. arg.entry.cname,
  3514. func,
  3515. arg.hdr_cname,
  3516. code.error_goto_if_null(arg.entry.cname, arg.pos)))
  3517. code.put_var_gotref(arg.entry)
  3518. else:
  3519. error(arg.pos, "Cannot convert argument of type '%s' to Python object" % old_type)
  3520. def generate_argument_type_tests(self, code):
  3521. # Generate type tests for args whose signature
  3522. # type is PyObject * and whose declared type is
  3523. # a subtype thereof.
  3524. for arg in self.args:
  3525. if arg.needs_type_test:
  3526. self.generate_arg_type_test(arg, code)
  3527. elif not arg.accept_none and (arg.type.is_pyobject or
  3528. arg.type.is_buffer or
  3529. arg.type.is_memoryviewslice):
  3530. self.generate_arg_none_check(arg, code)
  3531. def error_value(self):
  3532. return self.signature.error_value
  3533. class GeneratorDefNode(DefNode):
  3534. # Generator function node that creates a new generator instance when called.
  3535. #
  3536. # gbody GeneratorBodyDefNode the function implementing the generator
  3537. #
  3538. is_generator = True
  3539. is_coroutine = False
  3540. is_iterable_coroutine = False
  3541. is_asyncgen = False
  3542. gen_type_name = 'Generator'
  3543. needs_closure = True
  3544. child_attrs = DefNode.child_attrs + ["gbody"]
  3545. def __init__(self, pos, **kwargs):
  3546. # XXX: don't actually needs a body
  3547. kwargs['body'] = StatListNode(pos, stats=[], is_terminator=True)
  3548. super(GeneratorDefNode, self).__init__(pos, **kwargs)
  3549. def analyse_declarations(self, env):
  3550. super(GeneratorDefNode, self).analyse_declarations(env)
  3551. self.gbody.local_scope = self.local_scope
  3552. self.gbody.analyse_declarations(env)
  3553. def generate_function_body(self, env, code):
  3554. body_cname = self.gbody.entry.func_cname
  3555. name = code.intern_identifier(self.name)
  3556. qualname = code.intern_identifier(self.qualname)
  3557. module_name = code.intern_identifier(self.module_name)
  3558. code.putln('{')
  3559. code.putln('__pyx_CoroutineObject *gen = __Pyx_%s_New('
  3560. '(__pyx_coroutine_body_t) %s, %s, (PyObject *) %s, %s, %s, %s); %s' % (
  3561. self.gen_type_name,
  3562. body_cname, self.code_object.calculate_result_code(code) if self.code_object else 'NULL',
  3563. Naming.cur_scope_cname, name, qualname, module_name,
  3564. code.error_goto_if_null('gen', self.pos)))
  3565. code.put_decref(Naming.cur_scope_cname, py_object_type)
  3566. if self.requires_classobj:
  3567. classobj_cname = 'gen->classobj'
  3568. code.putln('%s = __Pyx_CyFunction_GetClassObj(%s);' % (
  3569. classobj_cname, Naming.self_cname))
  3570. code.put_incref(classobj_cname, py_object_type)
  3571. code.put_giveref(classobj_cname)
  3572. code.put_finish_refcount_context()
  3573. code.putln('return (PyObject *) gen;')
  3574. code.putln('}')
  3575. def generate_function_definitions(self, env, code):
  3576. env.use_utility_code(UtilityCode.load_cached(self.gen_type_name, "Coroutine.c"))
  3577. self.gbody.generate_function_header(code, proto=True)
  3578. super(GeneratorDefNode, self).generate_function_definitions(env, code)
  3579. self.gbody.generate_function_definitions(env, code)
  3580. class AsyncDefNode(GeneratorDefNode):
  3581. gen_type_name = 'Coroutine'
  3582. is_coroutine = True
  3583. class IterableAsyncDefNode(AsyncDefNode):
  3584. gen_type_name = 'IterableCoroutine'
  3585. is_iterable_coroutine = True
  3586. class AsyncGenNode(AsyncDefNode):
  3587. gen_type_name = 'AsyncGen'
  3588. is_asyncgen = True
  3589. class GeneratorBodyDefNode(DefNode):
  3590. # Main code body of a generator implemented as a DefNode.
  3591. #
  3592. is_generator_body = True
  3593. is_inlined = False
  3594. is_async_gen_body = False
  3595. inlined_comprehension_type = None # container type for inlined comprehensions
  3596. def __init__(self, pos=None, name=None, body=None, is_async_gen_body=False):
  3597. super(GeneratorBodyDefNode, self).__init__(
  3598. pos=pos, body=body, name=name, is_async_gen_body=is_async_gen_body,
  3599. doc=None, args=[], star_arg=None, starstar_arg=None)
  3600. def declare_generator_body(self, env):
  3601. prefix = env.next_id(env.scope_prefix)
  3602. name = env.next_id('generator')
  3603. cname = Naming.genbody_prefix + prefix + name
  3604. entry = env.declare_var(None, py_object_type, self.pos,
  3605. cname=cname, visibility='private')
  3606. entry.func_cname = cname
  3607. entry.qualified_name = EncodedString(self.name)
  3608. self.entry = entry
  3609. def analyse_declarations(self, env):
  3610. self.analyse_argument_types(env)
  3611. self.declare_generator_body(env)
  3612. def generate_function_header(self, code, proto=False):
  3613. header = "static PyObject *%s(__pyx_CoroutineObject *%s, CYTHON_UNUSED PyThreadState *%s, PyObject *%s)" % (
  3614. self.entry.func_cname,
  3615. Naming.generator_cname,
  3616. Naming.local_tstate_cname,
  3617. Naming.sent_value_cname)
  3618. if proto:
  3619. code.putln('%s; /* proto */' % header)
  3620. else:
  3621. code.putln('%s /* generator body */\n{' % header)
  3622. def generate_function_definitions(self, env, code):
  3623. lenv = self.local_scope
  3624. # Generate closure function definitions
  3625. self.body.generate_function_definitions(lenv, code)
  3626. # Generate C code for header and body of function
  3627. code.enter_cfunc_scope(lenv)
  3628. code.return_from_error_cleanup_label = code.new_label()
  3629. # ----- Top-level constants used by this function
  3630. code.mark_pos(self.pos)
  3631. self.generate_cached_builtins_decls(lenv, code)
  3632. # ----- Function header
  3633. code.putln("")
  3634. self.generate_function_header(code)
  3635. closure_init_code = code.insertion_point()
  3636. # ----- Local variables
  3637. code.putln("PyObject *%s = NULL;" % Naming.retval_cname)
  3638. tempvardecl_code = code.insertion_point()
  3639. code.put_declare_refcount_context()
  3640. code.put_setup_refcount_context(self.entry.name or self.entry.qualified_name)
  3641. profile = code.globalstate.directives['profile']
  3642. linetrace = code.globalstate.directives['linetrace']
  3643. if profile or linetrace:
  3644. tempvardecl_code.put_trace_declarations()
  3645. code.funcstate.can_trace = True
  3646. code_object = self.code_object.calculate_result_code(code) if self.code_object else None
  3647. code.put_trace_frame_init(code_object)
  3648. # ----- Resume switch point.
  3649. code.funcstate.init_closure_temps(lenv.scope_class.type.scope)
  3650. resume_code = code.insertion_point()
  3651. first_run_label = code.new_label('first_run')
  3652. code.use_label(first_run_label)
  3653. code.put_label(first_run_label)
  3654. code.putln('%s' %
  3655. (code.error_goto_if_null(Naming.sent_value_cname, self.pos)))
  3656. # ----- prepare target container for inlined comprehension
  3657. if self.is_inlined and self.inlined_comprehension_type is not None:
  3658. target_type = self.inlined_comprehension_type
  3659. if target_type is Builtin.list_type:
  3660. comp_init = 'PyList_New(0)'
  3661. elif target_type is Builtin.set_type:
  3662. comp_init = 'PySet_New(NULL)'
  3663. elif target_type is Builtin.dict_type:
  3664. comp_init = 'PyDict_New()'
  3665. else:
  3666. raise InternalError(
  3667. "invalid type of inlined comprehension: %s" % target_type)
  3668. code.putln("%s = %s; %s" % (
  3669. Naming.retval_cname, comp_init,
  3670. code.error_goto_if_null(Naming.retval_cname, self.pos)))
  3671. code.put_gotref(Naming.retval_cname)
  3672. # ----- Function body
  3673. self.generate_function_body(env, code)
  3674. # ----- Closure initialization
  3675. if lenv.scope_class.type.scope.var_entries:
  3676. closure_init_code.putln('%s = %s;' % (
  3677. lenv.scope_class.type.declaration_code(Naming.cur_scope_cname),
  3678. lenv.scope_class.type.cast_code('%s->closure' %
  3679. Naming.generator_cname)))
  3680. # FIXME: this silences a potential "unused" warning => try to avoid unused closures in more cases
  3681. code.putln("CYTHON_MAYBE_UNUSED_VAR(%s);" % Naming.cur_scope_cname)
  3682. if profile or linetrace:
  3683. code.funcstate.can_trace = False
  3684. code.mark_pos(self.pos)
  3685. code.putln("")
  3686. code.putln("/* function exit code */")
  3687. # on normal generator termination, we do not take the exception propagation
  3688. # path: no traceback info is required and not creating it is much faster
  3689. if not self.is_inlined and not self.body.is_terminator:
  3690. if self.is_async_gen_body:
  3691. code.globalstate.use_utility_code(
  3692. UtilityCode.load_cached("StopAsyncIteration", "Coroutine.c"))
  3693. code.putln('PyErr_SetNone(%s);' % (
  3694. '__Pyx_PyExc_StopAsyncIteration' if self.is_async_gen_body else 'PyExc_StopIteration'))
  3695. # ----- Error cleanup
  3696. if code.label_used(code.error_label):
  3697. if not self.body.is_terminator:
  3698. code.put_goto(code.return_label)
  3699. code.put_label(code.error_label)
  3700. if self.is_inlined and self.inlined_comprehension_type is not None:
  3701. code.put_xdecref_clear(Naming.retval_cname, py_object_type)
  3702. if Future.generator_stop in env.global_scope().context.future_directives:
  3703. # PEP 479: turn accidental StopIteration exceptions into a RuntimeError
  3704. code.globalstate.use_utility_code(UtilityCode.load_cached("pep479", "Coroutine.c"))
  3705. code.putln("__Pyx_Generator_Replace_StopIteration(%d);" % bool(self.is_async_gen_body))
  3706. for cname, type in code.funcstate.all_managed_temps():
  3707. code.put_xdecref(cname, type)
  3708. code.put_add_traceback(self.entry.qualified_name)
  3709. # ----- Non-error return cleanup
  3710. code.put_label(code.return_label)
  3711. if self.is_inlined:
  3712. code.put_xgiveref(Naming.retval_cname)
  3713. else:
  3714. code.put_xdecref_clear(Naming.retval_cname, py_object_type)
  3715. code.putln("__Pyx_Coroutine_ResetAndClearException(%s);" % Naming.generator_cname)
  3716. code.putln('%s->resume_label = -1;' % Naming.generator_cname)
  3717. # clean up as early as possible to help breaking any reference cycles
  3718. code.putln('__Pyx_Coroutine_clear((PyObject*)%s);' % Naming.generator_cname)
  3719. if profile or linetrace:
  3720. code.put_trace_return(Naming.retval_cname,
  3721. nogil=not code.funcstate.gil_owned)
  3722. code.put_finish_refcount_context()
  3723. code.putln("return %s;" % Naming.retval_cname)
  3724. code.putln("}")
  3725. # ----- Go back and insert temp variable declarations
  3726. tempvardecl_code.put_temp_declarations(code.funcstate)
  3727. # ----- Generator resume code
  3728. if profile or linetrace:
  3729. resume_code.put_trace_call(self.entry.qualified_name, self.pos,
  3730. nogil=not code.funcstate.gil_owned)
  3731. resume_code.putln("switch (%s->resume_label) {" % (
  3732. Naming.generator_cname))
  3733. resume_code.putln("case 0: goto %s;" % first_run_label)
  3734. for i, label in code.yield_labels:
  3735. resume_code.putln("case %d: goto %s;" % (i, label))
  3736. resume_code.putln("default: /* CPython raises the right error here */")
  3737. if profile or linetrace:
  3738. resume_code.put_trace_return("Py_None",
  3739. nogil=not code.funcstate.gil_owned)
  3740. resume_code.put_finish_refcount_context()
  3741. resume_code.putln("return NULL;")
  3742. resume_code.putln("}")
  3743. code.exit_cfunc_scope()
  3744. class OverrideCheckNode(StatNode):
  3745. # A Node for dispatching to the def method if it
  3746. # is overridden.
  3747. #
  3748. # py_func
  3749. #
  3750. # args
  3751. # func_temp
  3752. # body
  3753. child_attrs = ['body']
  3754. body = None
  3755. def analyse_expressions(self, env):
  3756. self.args = env.arg_entries
  3757. if self.py_func.is_module_scope:
  3758. first_arg = 0
  3759. else:
  3760. first_arg = 1
  3761. from . import ExprNodes
  3762. self.func_node = ExprNodes.RawCNameExprNode(self.pos, py_object_type)
  3763. call_node = ExprNodes.SimpleCallNode(
  3764. self.pos, function=self.func_node,
  3765. args=[ExprNodes.NameNode(self.pos, name=arg.name)
  3766. for arg in self.args[first_arg:]])
  3767. if env.return_type.is_void or env.return_type.is_returncode:
  3768. self.body = StatListNode(self.pos, stats=[
  3769. ExprStatNode(self.pos, expr=call_node),
  3770. ReturnStatNode(self.pos, value=None)])
  3771. else:
  3772. self.body = ReturnStatNode(self.pos, value=call_node)
  3773. self.body = self.body.analyse_expressions(env)
  3774. return self
  3775. def generate_execution_code(self, code):
  3776. interned_attr_cname = code.intern_identifier(self.py_func.entry.name)
  3777. # Check to see if we are an extension type
  3778. if self.py_func.is_module_scope:
  3779. self_arg = "((PyObject *)%s)" % Naming.module_cname
  3780. else:
  3781. self_arg = "((PyObject *)%s)" % self.args[0].cname
  3782. code.putln("/* Check if called by wrapper */")
  3783. code.putln("if (unlikely(%s)) ;" % Naming.skip_dispatch_cname)
  3784. code.putln("/* Check if overridden in Python */")
  3785. if self.py_func.is_module_scope:
  3786. code.putln("else {")
  3787. else:
  3788. code.putln("else if (unlikely(Py_TYPE(%s)->tp_dictoffset != 0)) {" % self_arg)
  3789. func_node_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  3790. self.func_node.set_cname(func_node_temp)
  3791. # need to get attribute manually--scope would return cdef method
  3792. code.globalstate.use_utility_code(
  3793. UtilityCode.load_cached("PyObjectGetAttrStr", "ObjectHandling.c"))
  3794. err = code.error_goto_if_null(func_node_temp, self.pos)
  3795. code.putln("%s = __Pyx_PyObject_GetAttrStr(%s, %s); %s" % (
  3796. func_node_temp, self_arg, interned_attr_cname, err))
  3797. code.put_gotref(func_node_temp)
  3798. is_builtin_function_or_method = "PyCFunction_Check(%s)" % func_node_temp
  3799. is_overridden = "(PyCFunction_GET_FUNCTION(%s) != (PyCFunction)%s)" % (
  3800. func_node_temp, self.py_func.entry.func_cname)
  3801. code.putln("if (!%s || %s) {" % (is_builtin_function_or_method, is_overridden))
  3802. self.body.generate_execution_code(code)
  3803. code.putln("}")
  3804. code.put_decref_clear(func_node_temp, PyrexTypes.py_object_type)
  3805. code.funcstate.release_temp(func_node_temp)
  3806. code.putln("}")
  3807. class ClassDefNode(StatNode, BlockNode):
  3808. pass
  3809. class PyClassDefNode(ClassDefNode):
  3810. # A Python class definition.
  3811. #
  3812. # name EncodedString Name of the class
  3813. # doc string or None
  3814. # body StatNode Attribute definition code
  3815. # entry Symtab.Entry
  3816. # scope PyClassScope
  3817. # decorators [DecoratorNode] list of decorators or None
  3818. #
  3819. # The following subnodes are constructed internally:
  3820. #
  3821. # dict DictNode Class dictionary or Py3 namespace
  3822. # classobj ClassNode Class object
  3823. # target NameNode Variable to assign class object to
  3824. child_attrs = ["body", "dict", "metaclass", "mkw", "bases", "class_result",
  3825. "target", "class_cell", "decorators"]
  3826. decorators = None
  3827. class_result = None
  3828. is_py3_style_class = False # Python3 style class (kwargs)
  3829. metaclass = None
  3830. mkw = None
  3831. def __init__(self, pos, name, bases, doc, body, decorators=None,
  3832. keyword_args=None, force_py3_semantics=False):
  3833. StatNode.__init__(self, pos)
  3834. self.name = name
  3835. self.doc = doc
  3836. self.body = body
  3837. self.decorators = decorators
  3838. self.bases = bases
  3839. from . import ExprNodes
  3840. if self.doc and Options.docstrings:
  3841. doc = embed_position(self.pos, self.doc)
  3842. doc_node = ExprNodes.StringNode(pos, value=doc)
  3843. else:
  3844. doc_node = None
  3845. allow_py2_metaclass = not force_py3_semantics
  3846. if keyword_args:
  3847. allow_py2_metaclass = False
  3848. self.is_py3_style_class = True
  3849. if keyword_args.is_dict_literal:
  3850. if keyword_args.key_value_pairs:
  3851. for i, item in list(enumerate(keyword_args.key_value_pairs))[::-1]:
  3852. if item.key.value == 'metaclass':
  3853. if self.metaclass is not None:
  3854. error(item.pos, "keyword argument 'metaclass' passed multiple times")
  3855. # special case: we already know the metaclass,
  3856. # so we don't need to do the "build kwargs,
  3857. # find metaclass" dance at runtime
  3858. self.metaclass = item.value
  3859. del keyword_args.key_value_pairs[i]
  3860. self.mkw = keyword_args
  3861. else:
  3862. assert self.metaclass is not None
  3863. else:
  3864. # MergedDictNode
  3865. self.mkw = ExprNodes.ProxyNode(keyword_args)
  3866. if force_py3_semantics or self.bases or self.mkw or self.metaclass:
  3867. if self.metaclass is None:
  3868. if keyword_args and not keyword_args.is_dict_literal:
  3869. # **kwargs may contain 'metaclass' arg
  3870. mkdict = self.mkw
  3871. else:
  3872. mkdict = None
  3873. if (not mkdict and
  3874. self.bases.is_sequence_constructor and
  3875. not self.bases.args):
  3876. pass # no base classes => no inherited metaclass
  3877. else:
  3878. self.metaclass = ExprNodes.PyClassMetaclassNode(
  3879. pos, mkw=mkdict, bases=self.bases)
  3880. needs_metaclass_calculation = False
  3881. else:
  3882. needs_metaclass_calculation = True
  3883. self.dict = ExprNodes.PyClassNamespaceNode(
  3884. pos, name=name, doc=doc_node,
  3885. metaclass=self.metaclass, bases=self.bases, mkw=self.mkw)
  3886. self.classobj = ExprNodes.Py3ClassNode(
  3887. pos, name=name,
  3888. bases=self.bases, dict=self.dict, doc=doc_node,
  3889. metaclass=self.metaclass, mkw=self.mkw,
  3890. calculate_metaclass=needs_metaclass_calculation,
  3891. allow_py2_metaclass=allow_py2_metaclass)
  3892. else:
  3893. # no bases, no metaclass => old style class creation
  3894. self.dict = ExprNodes.DictNode(pos, key_value_pairs=[])
  3895. self.classobj = ExprNodes.ClassNode(
  3896. pos, name=name,
  3897. bases=bases, dict=self.dict, doc=doc_node)
  3898. self.target = ExprNodes.NameNode(pos, name=name)
  3899. self.class_cell = ExprNodes.ClassCellInjectorNode(self.pos)
  3900. def as_cclass(self):
  3901. """
  3902. Return this node as if it were declared as an extension class
  3903. """
  3904. if self.is_py3_style_class:
  3905. error(self.classobj.pos, "Python3 style class could not be represented as C class")
  3906. return
  3907. from . import ExprNodes
  3908. return CClassDefNode(self.pos,
  3909. visibility='private',
  3910. module_name=None,
  3911. class_name=self.name,
  3912. bases=self.classobj.bases or ExprNodes.TupleNode(self.pos, args=[]),
  3913. decorators=self.decorators,
  3914. body=self.body,
  3915. in_pxd=False,
  3916. doc=self.doc)
  3917. def create_scope(self, env):
  3918. genv = env
  3919. while genv.is_py_class_scope or genv.is_c_class_scope:
  3920. genv = genv.outer_scope
  3921. cenv = self.scope = PyClassScope(name=self.name, outer_scope=genv)
  3922. return cenv
  3923. def analyse_declarations(self, env):
  3924. class_result = self.classobj
  3925. if self.decorators:
  3926. from .ExprNodes import SimpleCallNode
  3927. for decorator in self.decorators[::-1]:
  3928. class_result = SimpleCallNode(
  3929. decorator.pos,
  3930. function=decorator.decorator,
  3931. args=[class_result])
  3932. self.decorators = None
  3933. self.class_result = class_result
  3934. self.class_result.analyse_declarations(env)
  3935. self.target.analyse_target_declaration(env)
  3936. cenv = self.create_scope(env)
  3937. cenv.directives = env.directives
  3938. cenv.class_obj_cname = self.target.entry.cname
  3939. self.body.analyse_declarations(cenv)
  3940. def analyse_expressions(self, env):
  3941. if self.bases:
  3942. self.bases = self.bases.analyse_expressions(env)
  3943. if self.metaclass:
  3944. self.metaclass = self.metaclass.analyse_expressions(env)
  3945. if self.mkw:
  3946. self.mkw = self.mkw.analyse_expressions(env)
  3947. self.dict = self.dict.analyse_expressions(env)
  3948. self.class_result = self.class_result.analyse_expressions(env)
  3949. cenv = self.scope
  3950. self.body = self.body.analyse_expressions(cenv)
  3951. self.target.analyse_target_expression(env, self.classobj)
  3952. self.class_cell = self.class_cell.analyse_expressions(cenv)
  3953. return self
  3954. def generate_function_definitions(self, env, code):
  3955. self.generate_lambda_definitions(self.scope, code)
  3956. self.body.generate_function_definitions(self.scope, code)
  3957. def generate_execution_code(self, code):
  3958. code.mark_pos(self.pos)
  3959. code.pyclass_stack.append(self)
  3960. cenv = self.scope
  3961. if self.bases:
  3962. self.bases.generate_evaluation_code(code)
  3963. if self.mkw:
  3964. self.mkw.generate_evaluation_code(code)
  3965. if self.metaclass:
  3966. self.metaclass.generate_evaluation_code(code)
  3967. self.dict.generate_evaluation_code(code)
  3968. cenv.namespace_cname = cenv.class_obj_cname = self.dict.result()
  3969. self.class_cell.generate_evaluation_code(code)
  3970. self.body.generate_execution_code(code)
  3971. self.class_result.generate_evaluation_code(code)
  3972. self.class_cell.generate_injection_code(
  3973. code, self.class_result.result())
  3974. self.class_cell.generate_disposal_code(code)
  3975. cenv.namespace_cname = cenv.class_obj_cname = self.classobj.result()
  3976. self.target.generate_assignment_code(self.class_result, code)
  3977. self.dict.generate_disposal_code(code)
  3978. self.dict.free_temps(code)
  3979. if self.metaclass:
  3980. self.metaclass.generate_disposal_code(code)
  3981. self.metaclass.free_temps(code)
  3982. if self.mkw:
  3983. self.mkw.generate_disposal_code(code)
  3984. self.mkw.free_temps(code)
  3985. if self.bases:
  3986. self.bases.generate_disposal_code(code)
  3987. self.bases.free_temps(code)
  3988. code.pyclass_stack.pop()
  3989. class CClassDefNode(ClassDefNode):
  3990. # An extension type definition.
  3991. #
  3992. # visibility 'private' or 'public' or 'extern'
  3993. # typedef_flag boolean
  3994. # api boolean
  3995. # module_name string or None For import of extern type objects
  3996. # class_name string Unqualified name of class
  3997. # as_name string or None Name to declare as in this scope
  3998. # bases TupleNode Base class(es)
  3999. # objstruct_name string or None Specified C name of object struct
  4000. # typeobj_name string or None Specified C name of type object
  4001. # in_pxd boolean Is in a .pxd file
  4002. # decorators [DecoratorNode] list of decorators or None
  4003. # doc string or None
  4004. # body StatNode or None
  4005. # entry Symtab.Entry
  4006. # base_type PyExtensionType or None
  4007. # buffer_defaults_node DictNode or None Declares defaults for a buffer
  4008. # buffer_defaults_pos
  4009. child_attrs = ["body"]
  4010. buffer_defaults_node = None
  4011. buffer_defaults_pos = None
  4012. typedef_flag = False
  4013. api = False
  4014. objstruct_name = None
  4015. typeobj_name = None
  4016. decorators = None
  4017. shadow = False
  4018. def buffer_defaults(self, env):
  4019. if not hasattr(self, '_buffer_defaults'):
  4020. from . import Buffer
  4021. if self.buffer_defaults_node:
  4022. self._buffer_defaults = Buffer.analyse_buffer_options(
  4023. self.buffer_defaults_pos,
  4024. env, [], self.buffer_defaults_node,
  4025. need_complete=False)
  4026. else:
  4027. self._buffer_defaults = None
  4028. return self._buffer_defaults
  4029. def declare(self, env):
  4030. if self.module_name and self.visibility != 'extern':
  4031. module_path = self.module_name.split(".")
  4032. home_scope = env.find_imported_module(module_path, self.pos)
  4033. if not home_scope:
  4034. return None
  4035. else:
  4036. home_scope = env
  4037. self.entry = home_scope.declare_c_class(
  4038. name=self.class_name,
  4039. pos=self.pos,
  4040. defining=0,
  4041. implementing=0,
  4042. module_name=self.module_name,
  4043. base_type=None,
  4044. objstruct_cname=self.objstruct_name,
  4045. typeobj_cname=self.typeobj_name,
  4046. visibility=self.visibility,
  4047. typedef_flag=self.typedef_flag,
  4048. api=self.api,
  4049. buffer_defaults=self.buffer_defaults(env),
  4050. shadow=self.shadow)
  4051. def analyse_declarations(self, env):
  4052. #print "CClassDefNode.analyse_declarations:", self.class_name
  4053. #print "...visibility =", self.visibility
  4054. #print "...module_name =", self.module_name
  4055. if env.in_cinclude and not self.objstruct_name:
  4056. error(self.pos, "Object struct name specification required for C class defined in 'extern from' block")
  4057. if self.decorators:
  4058. error(self.pos, "Decorators not allowed on cdef classes (used on type '%s')" % self.class_name)
  4059. self.base_type = None
  4060. # Now that module imports are cached, we need to
  4061. # import the modules for extern classes.
  4062. if self.module_name:
  4063. self.module = None
  4064. for module in env.cimported_modules:
  4065. if module.name == self.module_name:
  4066. self.module = module
  4067. if self.module is None:
  4068. self.module = ModuleScope(self.module_name, None, env.context)
  4069. self.module.has_extern_class = 1
  4070. env.add_imported_module(self.module)
  4071. if self.bases.args:
  4072. base = self.bases.args[0]
  4073. base_type = base.analyse_as_type(env)
  4074. if base_type in (PyrexTypes.c_int_type, PyrexTypes.c_long_type, PyrexTypes.c_float_type):
  4075. # Use the Python rather than C variant of these types.
  4076. base_type = env.lookup(base_type.sign_and_name()).type
  4077. if base_type is None:
  4078. error(base.pos, "First base of '%s' is not an extension type" % self.class_name)
  4079. elif base_type == PyrexTypes.py_object_type:
  4080. base_class_scope = None
  4081. elif not base_type.is_extension_type and \
  4082. not (base_type.is_builtin_type and base_type.objstruct_cname):
  4083. error(base.pos, "'%s' is not an extension type" % base_type)
  4084. elif not base_type.is_complete():
  4085. error(base.pos, "Base class '%s' of type '%s' is incomplete" % (
  4086. base_type.name, self.class_name))
  4087. elif base_type.scope and base_type.scope.directives and \
  4088. base_type.is_final_type:
  4089. error(base.pos, "Base class '%s' of type '%s' is final" % (
  4090. base_type, self.class_name))
  4091. elif base_type.is_builtin_type and \
  4092. base_type.name in ('tuple', 'str', 'bytes'):
  4093. error(base.pos, "inheritance from PyVarObject types like '%s' is not currently supported"
  4094. % base_type.name)
  4095. else:
  4096. self.base_type = base_type
  4097. if env.directives.get('freelist', 0) > 0 and base_type != PyrexTypes.py_object_type:
  4098. warning(self.pos, "freelists cannot be used on subtypes, only the base class can manage them", 1)
  4099. has_body = self.body is not None
  4100. if has_body and self.base_type and not self.base_type.scope:
  4101. # To properly initialize inherited attributes, the base type must
  4102. # be analysed before this type.
  4103. self.base_type.defered_declarations.append(lambda : self.analyse_declarations(env))
  4104. return
  4105. if self.module_name and self.visibility != 'extern':
  4106. module_path = self.module_name.split(".")
  4107. home_scope = env.find_imported_module(module_path, self.pos)
  4108. if not home_scope:
  4109. return
  4110. else:
  4111. home_scope = env
  4112. if self.visibility == 'extern':
  4113. if (self.module_name == '__builtin__' and
  4114. self.class_name in Builtin.builtin_types and
  4115. env.qualified_name[:8] != 'cpython.'): # allow overloaded names for cimporting from cpython
  4116. warning(self.pos, "%s already a builtin Cython type" % self.class_name, 1)
  4117. self.entry = home_scope.declare_c_class(
  4118. name=self.class_name,
  4119. pos=self.pos,
  4120. defining=has_body and self.in_pxd,
  4121. implementing=has_body and not self.in_pxd,
  4122. module_name=self.module_name,
  4123. base_type=self.base_type,
  4124. objstruct_cname=self.objstruct_name,
  4125. typeobj_cname=self.typeobj_name,
  4126. visibility=self.visibility,
  4127. typedef_flag=self.typedef_flag,
  4128. api=self.api,
  4129. buffer_defaults=self.buffer_defaults(env),
  4130. shadow=self.shadow)
  4131. if self.shadow:
  4132. home_scope.lookup(self.class_name).as_variable = self.entry
  4133. if home_scope is not env and self.visibility == 'extern':
  4134. env.add_imported_entry(self.class_name, self.entry, self.pos)
  4135. self.scope = scope = self.entry.type.scope
  4136. if scope is not None:
  4137. scope.directives = env.directives
  4138. if self.doc and Options.docstrings:
  4139. scope.doc = embed_position(self.pos, self.doc)
  4140. if has_body:
  4141. self.body.analyse_declarations(scope)
  4142. dict_entry = self.scope.lookup_here("__dict__")
  4143. if dict_entry and dict_entry.is_variable and (not scope.defined and not scope.implemented):
  4144. dict_entry.getter_cname = self.scope.mangle_internal("__dict__getter")
  4145. self.scope.declare_property("__dict__", dict_entry.doc, dict_entry.pos)
  4146. if self.in_pxd:
  4147. scope.defined = 1
  4148. else:
  4149. scope.implemented = 1
  4150. if len(self.bases.args) > 1:
  4151. if not has_body or self.in_pxd:
  4152. error(self.bases.args[1].pos, "Only declare first base in declaration.")
  4153. # At runtime, we check that the other bases are heap types
  4154. # and that a __dict__ is added if required.
  4155. for other_base in self.bases.args[1:]:
  4156. if other_base.analyse_as_type(env):
  4157. error(other_base.pos, "Only one extension type base class allowed.")
  4158. self.entry.type.early_init = 0
  4159. from . import ExprNodes
  4160. self.type_init_args = ExprNodes.TupleNode(
  4161. self.pos,
  4162. args=[ExprNodes.IdentifierStringNode(self.pos, value=self.class_name),
  4163. self.bases,
  4164. ExprNodes.DictNode(self.pos, key_value_pairs=[])])
  4165. elif self.base_type:
  4166. self.entry.type.early_init = self.base_type.is_external or self.base_type.early_init
  4167. self.type_init_args = None
  4168. else:
  4169. self.entry.type.early_init = 1
  4170. self.type_init_args = None
  4171. env.allocate_vtable_names(self.entry)
  4172. for thunk in self.entry.type.defered_declarations:
  4173. thunk()
  4174. def analyse_expressions(self, env):
  4175. if self.body:
  4176. scope = self.entry.type.scope
  4177. self.body = self.body.analyse_expressions(scope)
  4178. if self.type_init_args:
  4179. self.type_init_args.analyse_expressions(env)
  4180. return self
  4181. def generate_function_definitions(self, env, code):
  4182. if self.body:
  4183. self.generate_lambda_definitions(self.scope, code)
  4184. self.body.generate_function_definitions(self.scope, code)
  4185. def generate_execution_code(self, code):
  4186. # This is needed to generate evaluation code for
  4187. # default values of method arguments.
  4188. code.mark_pos(self.pos)
  4189. if self.body:
  4190. self.body.generate_execution_code(code)
  4191. if not self.entry.type.early_init:
  4192. if self.type_init_args:
  4193. self.type_init_args.generate_evaluation_code(code)
  4194. bases = "PyTuple_GET_ITEM(%s, 1)" % self.type_init_args.result()
  4195. first_base = "((PyTypeObject*)PyTuple_GET_ITEM(%s, 0))" % bases
  4196. # Let Python do the base types compatibility checking.
  4197. trial_type = code.funcstate.allocate_temp(PyrexTypes.py_object_type, True)
  4198. code.putln("%s = PyType_Type.tp_new(&PyType_Type, %s, NULL);" % (
  4199. trial_type, self.type_init_args.result()))
  4200. code.putln(code.error_goto_if_null(trial_type, self.pos))
  4201. code.put_gotref(trial_type)
  4202. code.putln("if (((PyTypeObject*) %s)->tp_base != %s) {" % (
  4203. trial_type, first_base))
  4204. code.putln("PyErr_Format(PyExc_TypeError, \"best base '%s' must be equal to first base '%s'\",")
  4205. code.putln(" ((PyTypeObject*) %s)->tp_base->tp_name, %s->tp_name);" % (
  4206. trial_type, first_base))
  4207. code.putln(code.error_goto(self.pos))
  4208. code.putln("}")
  4209. code.funcstate.release_temp(trial_type)
  4210. code.put_incref(bases, PyrexTypes.py_object_type)
  4211. code.put_giveref(bases)
  4212. code.putln("%s.tp_bases = %s;" % (self.entry.type.typeobj_cname, bases))
  4213. code.put_decref_clear(trial_type, PyrexTypes.py_object_type)
  4214. self.type_init_args.generate_disposal_code(code)
  4215. self.type_init_args.free_temps(code)
  4216. self.generate_type_ready_code(self.entry, code, True)
  4217. # Also called from ModuleNode for early init types.
  4218. @staticmethod
  4219. def generate_type_ready_code(entry, code, heap_type_bases=False):
  4220. # Generate a call to PyType_Ready for an extension
  4221. # type defined in this module.
  4222. type = entry.type
  4223. typeobj_cname = type.typeobj_cname
  4224. scope = type.scope
  4225. if not scope: # could be None if there was an error
  4226. return
  4227. if entry.visibility != 'extern':
  4228. for slot in TypeSlots.slot_table:
  4229. slot.generate_dynamic_init_code(scope, code)
  4230. if heap_type_bases:
  4231. code.globalstate.use_utility_code(
  4232. UtilityCode.load_cached('PyType_Ready', 'ExtensionTypes.c'))
  4233. readyfunc = "__Pyx_PyType_Ready"
  4234. else:
  4235. readyfunc = "PyType_Ready"
  4236. code.putln(
  4237. "if (%s(&%s) < 0) %s" % (
  4238. readyfunc,
  4239. typeobj_cname,
  4240. code.error_goto(entry.pos)))
  4241. # Don't inherit tp_print from builtin types, restoring the
  4242. # behavior of using tp_repr or tp_str instead.
  4243. code.putln("%s.tp_print = 0;" % typeobj_cname)
  4244. # Use specialised attribute lookup for types with generic lookup but no instance dict.
  4245. getattr_slot_func = TypeSlots.get_slot_code_by_name(scope, 'tp_getattro')
  4246. dictoffset_slot_func = TypeSlots.get_slot_code_by_name(scope, 'tp_dictoffset')
  4247. if getattr_slot_func == '0' and dictoffset_slot_func == '0':
  4248. if type.is_final_type:
  4249. py_cfunc = "__Pyx_PyObject_GenericGetAttrNoDict" # grepable
  4250. utility_func = "PyObject_GenericGetAttrNoDict"
  4251. else:
  4252. py_cfunc = "__Pyx_PyObject_GenericGetAttr"
  4253. utility_func = "PyObject_GenericGetAttr"
  4254. code.globalstate.use_utility_code(UtilityCode.load_cached(utility_func, "ObjectHandling.c"))
  4255. code.putln("if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) &&"
  4256. " likely(!%s.tp_dictoffset && %s.tp_getattro == PyObject_GenericGetAttr)) {" % (
  4257. typeobj_cname, typeobj_cname))
  4258. code.putln("%s.tp_getattro = %s;" % (
  4259. typeobj_cname, py_cfunc))
  4260. code.putln("}")
  4261. # Fix special method docstrings. This is a bit of a hack, but
  4262. # unless we let PyType_Ready create the slot wrappers we have
  4263. # a significant performance hit. (See trac #561.)
  4264. for func in entry.type.scope.pyfunc_entries:
  4265. is_buffer = func.name in ('__getbuffer__', '__releasebuffer__')
  4266. if (func.is_special and Options.docstrings and
  4267. func.wrapperbase_cname and not is_buffer):
  4268. slot = TypeSlots.method_name_to_slot.get(func.name)
  4269. preprocessor_guard = slot.preprocessor_guard_code() if slot else None
  4270. if preprocessor_guard:
  4271. code.putln(preprocessor_guard)
  4272. code.putln('#if CYTHON_COMPILING_IN_CPYTHON')
  4273. code.putln("{")
  4274. code.putln(
  4275. 'PyObject *wrapper = PyObject_GetAttrString((PyObject *)&%s, "%s"); %s' % (
  4276. typeobj_cname,
  4277. func.name,
  4278. code.error_goto_if_null('wrapper', entry.pos)))
  4279. code.putln(
  4280. "if (Py_TYPE(wrapper) == &PyWrapperDescr_Type) {")
  4281. code.putln(
  4282. "%s = *((PyWrapperDescrObject *)wrapper)->d_base;" % (
  4283. func.wrapperbase_cname))
  4284. code.putln(
  4285. "%s.doc = %s;" % (func.wrapperbase_cname, func.doc_cname))
  4286. code.putln(
  4287. "((PyWrapperDescrObject *)wrapper)->d_base = &%s;" % (
  4288. func.wrapperbase_cname))
  4289. code.putln("}")
  4290. code.putln("}")
  4291. code.putln('#endif')
  4292. if preprocessor_guard:
  4293. code.putln('#endif')
  4294. if type.vtable_cname:
  4295. code.globalstate.use_utility_code(
  4296. UtilityCode.load_cached('SetVTable', 'ImportExport.c'))
  4297. code.putln(
  4298. "if (__Pyx_SetVtable(%s.tp_dict, %s) < 0) %s" % (
  4299. typeobj_cname,
  4300. type.vtabptr_cname,
  4301. code.error_goto(entry.pos)))
  4302. if heap_type_bases:
  4303. code.globalstate.use_utility_code(
  4304. UtilityCode.load_cached('MergeVTables', 'ImportExport.c'))
  4305. code.putln("if (__Pyx_MergeVtables(&%s) < 0) %s" % (
  4306. typeobj_cname,
  4307. code.error_goto(entry.pos)))
  4308. if not type.scope.is_internal and not type.scope.directives['internal']:
  4309. # scope.is_internal is set for types defined by
  4310. # Cython (such as closures), the 'internal'
  4311. # directive is set by users
  4312. code.putln(
  4313. 'if (PyObject_SetAttrString(%s, "%s", (PyObject *)&%s) < 0) %s' % (
  4314. Naming.module_cname,
  4315. scope.class_name,
  4316. typeobj_cname,
  4317. code.error_goto(entry.pos)))
  4318. weakref_entry = scope.lookup_here("__weakref__") if not scope.is_closure_class_scope else None
  4319. if weakref_entry:
  4320. if weakref_entry.type is py_object_type:
  4321. tp_weaklistoffset = "%s.tp_weaklistoffset" % typeobj_cname
  4322. if type.typedef_flag:
  4323. objstruct = type.objstruct_cname
  4324. else:
  4325. objstruct = "struct %s" % type.objstruct_cname
  4326. code.putln("if (%s == 0) %s = offsetof(%s, %s);" % (
  4327. tp_weaklistoffset,
  4328. tp_weaklistoffset,
  4329. objstruct,
  4330. weakref_entry.cname))
  4331. else:
  4332. error(weakref_entry.pos, "__weakref__ slot must be of type 'object'")
  4333. if scope.lookup_here("__reduce_cython__") if not scope.is_closure_class_scope else None:
  4334. # Unfortunately, we cannot reliably detect whether a
  4335. # superclass defined __reduce__ at compile time, so we must
  4336. # do so at runtime.
  4337. code.globalstate.use_utility_code(
  4338. UtilityCode.load_cached('SetupReduce', 'ExtensionTypes.c'))
  4339. code.putln('if (__Pyx_setup_reduce((PyObject*)&%s) < 0) %s' % (
  4340. typeobj_cname,
  4341. code.error_goto(entry.pos)))
  4342. # Generate code to initialise the typeptr of an extension
  4343. # type defined in this module to point to its type object.
  4344. if type.typeobj_cname:
  4345. code.putln(
  4346. "%s = &%s;" % (
  4347. type.typeptr_cname, type.typeobj_cname))
  4348. def annotate(self, code):
  4349. if self.type_init_args:
  4350. self.type_init_args.annotate(code)
  4351. if self.body:
  4352. self.body.annotate(code)
  4353. class PropertyNode(StatNode):
  4354. # Definition of a property in an extension type.
  4355. #
  4356. # name string
  4357. # doc EncodedString or None Doc string
  4358. # entry Symtab.Entry
  4359. # body StatListNode
  4360. child_attrs = ["body"]
  4361. def analyse_declarations(self, env):
  4362. self.entry = env.declare_property(self.name, self.doc, self.pos)
  4363. self.entry.scope.directives = env.directives
  4364. self.body.analyse_declarations(self.entry.scope)
  4365. def analyse_expressions(self, env):
  4366. self.body = self.body.analyse_expressions(env)
  4367. return self
  4368. def generate_function_definitions(self, env, code):
  4369. self.body.generate_function_definitions(env, code)
  4370. def generate_execution_code(self, code):
  4371. pass
  4372. def annotate(self, code):
  4373. self.body.annotate(code)
  4374. class GlobalNode(StatNode):
  4375. # Global variable declaration.
  4376. #
  4377. # names [string]
  4378. child_attrs = []
  4379. def analyse_declarations(self, env):
  4380. for name in self.names:
  4381. env.declare_global(name, self.pos)
  4382. def analyse_expressions(self, env):
  4383. return self
  4384. def generate_execution_code(self, code):
  4385. pass
  4386. class NonlocalNode(StatNode):
  4387. # Nonlocal variable declaration via the 'nonlocal' keyword.
  4388. #
  4389. # names [string]
  4390. child_attrs = []
  4391. def analyse_declarations(self, env):
  4392. for name in self.names:
  4393. env.declare_nonlocal(name, self.pos)
  4394. def analyse_expressions(self, env):
  4395. return self
  4396. def generate_execution_code(self, code):
  4397. pass
  4398. class ExprStatNode(StatNode):
  4399. # Expression used as a statement.
  4400. #
  4401. # expr ExprNode
  4402. child_attrs = ["expr"]
  4403. def analyse_declarations(self, env):
  4404. from . import ExprNodes
  4405. expr = self.expr
  4406. if isinstance(expr, ExprNodes.GeneralCallNode):
  4407. func = expr.function.as_cython_attribute()
  4408. if func == u'declare':
  4409. args, kwds = expr.explicit_args_kwds()
  4410. if len(args):
  4411. error(expr.pos, "Variable names must be specified.")
  4412. for var, type_node in kwds.key_value_pairs:
  4413. type = type_node.analyse_as_type(env)
  4414. if type is None:
  4415. error(type_node.pos, "Unknown type")
  4416. else:
  4417. env.declare_var(var.value, type, var.pos, is_cdef=True)
  4418. self.__class__ = PassStatNode
  4419. elif getattr(expr, 'annotation', None) is not None:
  4420. if expr.is_name:
  4421. # non-code variable annotation, e.g. "name: type"
  4422. expr.declare_from_annotation(env)
  4423. self.__class__ = PassStatNode
  4424. elif expr.is_attribute or expr.is_subscript:
  4425. # unused expression with annotation, e.g. "a[0]: type" or "a.xyz : type"
  4426. self.__class__ = PassStatNode
  4427. def analyse_expressions(self, env):
  4428. self.expr.result_is_used = False # hint that .result() may safely be left empty
  4429. self.expr = self.expr.analyse_expressions(env)
  4430. # Repeat in case of node replacement.
  4431. self.expr.result_is_used = False # hint that .result() may safely be left empty
  4432. return self
  4433. def nogil_check(self, env):
  4434. if self.expr.type.is_pyobject and self.expr.is_temp:
  4435. self.gil_error()
  4436. gil_message = "Discarding owned Python object"
  4437. def generate_execution_code(self, code):
  4438. code.mark_pos(self.pos)
  4439. self.expr.result_is_used = False # hint that .result() may safely be left empty
  4440. self.expr.generate_evaluation_code(code)
  4441. if not self.expr.is_temp and self.expr.result():
  4442. result = self.expr.result()
  4443. if not self.expr.type.is_void:
  4444. result = "(void)(%s)" % result
  4445. code.putln("%s;" % result)
  4446. self.expr.generate_disposal_code(code)
  4447. self.expr.free_temps(code)
  4448. def generate_function_definitions(self, env, code):
  4449. self.expr.generate_function_definitions(env, code)
  4450. def annotate(self, code):
  4451. self.expr.annotate(code)
  4452. class AssignmentNode(StatNode):
  4453. # Abstract base class for assignment nodes.
  4454. #
  4455. # The analyse_expressions and generate_execution_code
  4456. # phases of assignments are split into two sub-phases
  4457. # each, to enable all the right hand sides of a
  4458. # parallel assignment to be evaluated before assigning
  4459. # to any of the left hand sides.
  4460. def analyse_expressions(self, env):
  4461. node = self.analyse_types(env)
  4462. if isinstance(node, AssignmentNode) and not isinstance(node, ParallelAssignmentNode):
  4463. if node.rhs.type.is_ptr and node.rhs.is_ephemeral():
  4464. error(self.pos, "Storing unsafe C derivative of temporary Python reference")
  4465. return node
  4466. # def analyse_expressions(self, env):
  4467. # self.analyse_expressions_1(env)
  4468. # self.analyse_expressions_2(env)
  4469. def generate_execution_code(self, code):
  4470. code.mark_pos(self.pos)
  4471. self.generate_rhs_evaluation_code(code)
  4472. self.generate_assignment_code(code)
  4473. class SingleAssignmentNode(AssignmentNode):
  4474. # The simplest case:
  4475. #
  4476. # a = b
  4477. #
  4478. # lhs ExprNode Left hand side
  4479. # rhs ExprNode Right hand side
  4480. # first bool Is this guaranteed the first assignment to lhs?
  4481. # is_overloaded_assignment bool Is this assignment done via an overloaded operator=
  4482. # exception_check
  4483. # exception_value
  4484. child_attrs = ["lhs", "rhs"]
  4485. first = False
  4486. is_overloaded_assignment = False
  4487. declaration_only = False
  4488. def analyse_declarations(self, env):
  4489. from . import ExprNodes
  4490. # handle declarations of the form x = cython.foo()
  4491. if isinstance(self.rhs, ExprNodes.CallNode):
  4492. func_name = self.rhs.function.as_cython_attribute()
  4493. if func_name:
  4494. args, kwds = self.rhs.explicit_args_kwds()
  4495. if func_name in ['declare', 'typedef']:
  4496. if len(args) > 2:
  4497. error(args[2].pos, "Invalid positional argument.")
  4498. return
  4499. if kwds is not None:
  4500. kwdict = kwds.compile_time_value(None)
  4501. if func_name == 'typedef' or 'visibility' not in kwdict:
  4502. error(kwds.pos, "Invalid keyword argument.")
  4503. return
  4504. visibility = kwdict['visibility']
  4505. else:
  4506. visibility = 'private'
  4507. type = args[0].analyse_as_type(env)
  4508. if type is None:
  4509. error(args[0].pos, "Unknown type")
  4510. return
  4511. lhs = self.lhs
  4512. if func_name == 'declare':
  4513. if isinstance(lhs, ExprNodes.NameNode):
  4514. vars = [(lhs.name, lhs.pos)]
  4515. elif isinstance(lhs, ExprNodes.TupleNode):
  4516. vars = [(var.name, var.pos) for var in lhs.args]
  4517. else:
  4518. error(lhs.pos, "Invalid declaration")
  4519. return
  4520. for var, pos in vars:
  4521. env.declare_var(var, type, pos, is_cdef=True, visibility=visibility)
  4522. if len(args) == 2:
  4523. # we have a value
  4524. self.rhs = args[1]
  4525. else:
  4526. self.declaration_only = True
  4527. else:
  4528. self.declaration_only = True
  4529. if not isinstance(lhs, ExprNodes.NameNode):
  4530. error(lhs.pos, "Invalid declaration.")
  4531. env.declare_typedef(lhs.name, type, self.pos, visibility='private')
  4532. elif func_name in ['struct', 'union']:
  4533. self.declaration_only = True
  4534. if len(args) > 0 or kwds is None:
  4535. error(self.rhs.pos, "Struct or union members must be given by name.")
  4536. return
  4537. members = []
  4538. for member, type_node in kwds.key_value_pairs:
  4539. type = type_node.analyse_as_type(env)
  4540. if type is None:
  4541. error(type_node.pos, "Unknown type")
  4542. else:
  4543. members.append((member.value, type, member.pos))
  4544. if len(members) < len(kwds.key_value_pairs):
  4545. return
  4546. if not isinstance(self.lhs, ExprNodes.NameNode):
  4547. error(self.lhs.pos, "Invalid declaration.")
  4548. name = self.lhs.name
  4549. scope = StructOrUnionScope(name)
  4550. env.declare_struct_or_union(name, func_name, scope, False, self.rhs.pos)
  4551. for member, type, pos in members:
  4552. scope.declare_var(member, type, pos)
  4553. elif func_name == 'fused_type':
  4554. # dtype = cython.fused_type(...)
  4555. self.declaration_only = True
  4556. if kwds:
  4557. error(self.rhs.function.pos,
  4558. "fused_type does not take keyword arguments")
  4559. fusednode = FusedTypeNode(self.rhs.pos,
  4560. name=self.lhs.name, types=args)
  4561. fusednode.analyse_declarations(env)
  4562. if self.declaration_only:
  4563. return
  4564. else:
  4565. self.lhs.analyse_target_declaration(env)
  4566. def analyse_types(self, env, use_temp=0):
  4567. from . import ExprNodes
  4568. self.rhs = self.rhs.analyse_types(env)
  4569. unrolled_assignment = self.unroll_rhs(env)
  4570. if unrolled_assignment:
  4571. return unrolled_assignment
  4572. self.lhs = self.lhs.analyse_target_types(env)
  4573. self.lhs.gil_assignment_check(env)
  4574. unrolled_assignment = self.unroll_lhs(env)
  4575. if unrolled_assignment:
  4576. return unrolled_assignment
  4577. if isinstance(self.lhs, ExprNodes.MemoryViewIndexNode):
  4578. self.lhs.analyse_broadcast_operation(self.rhs)
  4579. self.lhs = self.lhs.analyse_as_memview_scalar_assignment(self.rhs)
  4580. elif self.lhs.type.is_array:
  4581. if not isinstance(self.lhs, ExprNodes.SliceIndexNode):
  4582. # cannot assign to C array, only to its full slice
  4583. self.lhs = ExprNodes.SliceIndexNode(self.lhs.pos, base=self.lhs, start=None, stop=None)
  4584. self.lhs = self.lhs.analyse_target_types(env)
  4585. if self.lhs.type.is_cpp_class:
  4586. op = env.lookup_operator_for_types(self.pos, '=', [self.lhs.type, self.rhs.type])
  4587. if op:
  4588. rhs = self.rhs
  4589. self.is_overloaded_assignment = True
  4590. self.exception_check = op.type.exception_check
  4591. self.exception_value = op.type.exception_value
  4592. if self.exception_check == '+' and self.exception_value is None:
  4593. env.use_utility_code(UtilityCode.load_cached("CppExceptionConversion", "CppSupport.cpp"))
  4594. else:
  4595. rhs = self.rhs.coerce_to(self.lhs.type, env)
  4596. else:
  4597. rhs = self.rhs.coerce_to(self.lhs.type, env)
  4598. if use_temp or rhs.is_attribute or (
  4599. not rhs.is_name and not rhs.is_literal and
  4600. rhs.type.is_pyobject):
  4601. # things like (cdef) attribute access are not safe (traverses pointers)
  4602. rhs = rhs.coerce_to_temp(env)
  4603. elif rhs.type.is_pyobject:
  4604. rhs = rhs.coerce_to_simple(env)
  4605. self.rhs = rhs
  4606. return self
  4607. def unroll(self, node, target_size, env):
  4608. from . import ExprNodes, UtilNodes
  4609. base = node
  4610. start_node = stop_node = step_node = check_node = None
  4611. if node.type.is_ctuple:
  4612. slice_size = node.type.size
  4613. elif node.type.is_ptr or node.type.is_array:
  4614. while isinstance(node, ExprNodes.SliceIndexNode) and not (node.start or node.stop):
  4615. base = node = node.base
  4616. if isinstance(node, ExprNodes.SliceIndexNode):
  4617. base = node.base
  4618. start_node = node.start
  4619. if start_node:
  4620. start_node = start_node.coerce_to(PyrexTypes.c_py_ssize_t_type, env)
  4621. stop_node = node.stop
  4622. if stop_node:
  4623. stop_node = stop_node.coerce_to(PyrexTypes.c_py_ssize_t_type, env)
  4624. else:
  4625. if node.type.is_array and node.type.size:
  4626. stop_node = ExprNodes.IntNode(
  4627. self.pos, value=str(node.type.size),
  4628. constant_result=(node.type.size if isinstance(node.type.size, _py_int_types)
  4629. else ExprNodes.constant_value_not_set))
  4630. else:
  4631. error(self.pos, "C array iteration requires known end index")
  4632. return
  4633. step_node = None #node.step
  4634. if step_node:
  4635. step_node = step_node.coerce_to(PyrexTypes.c_py_ssize_t_type, env)
  4636. # TODO: Factor out SliceIndexNode.generate_slice_guard_code() for use here.
  4637. def get_const(node, none_value):
  4638. if node is None:
  4639. return none_value
  4640. elif node.has_constant_result():
  4641. return node.constant_result
  4642. else:
  4643. raise ValueError("Not a constant.")
  4644. try:
  4645. slice_size = (get_const(stop_node, None) - get_const(start_node, 0)) / get_const(step_node, 1)
  4646. except ValueError:
  4647. error(self.pos, "C array assignment currently requires known endpoints")
  4648. return
  4649. elif node.type.is_array:
  4650. slice_size = node.type.size
  4651. if not isinstance(slice_size, _py_int_types):
  4652. return # might still work when coercing to Python
  4653. else:
  4654. return
  4655. else:
  4656. return
  4657. if slice_size != target_size:
  4658. error(self.pos, "Assignment to/from slice of wrong length, expected %s, got %s" % (
  4659. slice_size, target_size))
  4660. return
  4661. items = []
  4662. base = UtilNodes.LetRefNode(base)
  4663. refs = [base]
  4664. if start_node and not start_node.is_literal:
  4665. start_node = UtilNodes.LetRefNode(start_node)
  4666. refs.append(start_node)
  4667. if stop_node and not stop_node.is_literal:
  4668. stop_node = UtilNodes.LetRefNode(stop_node)
  4669. refs.append(stop_node)
  4670. if step_node and not step_node.is_literal:
  4671. step_node = UtilNodes.LetRefNode(step_node)
  4672. refs.append(step_node)
  4673. for ix in range(target_size):
  4674. ix_node = ExprNodes.IntNode(self.pos, value=str(ix), constant_result=ix, type=PyrexTypes.c_py_ssize_t_type)
  4675. if step_node is not None:
  4676. if step_node.has_constant_result():
  4677. step_value = ix_node.constant_result * step_node.constant_result
  4678. ix_node = ExprNodes.IntNode(self.pos, value=str(step_value), constant_result=step_value)
  4679. else:
  4680. ix_node = ExprNodes.MulNode(self.pos, operator='*', operand1=step_node, operand2=ix_node)
  4681. if start_node is not None:
  4682. if start_node.has_constant_result() and ix_node.has_constant_result():
  4683. index_value = ix_node.constant_result + start_node.constant_result
  4684. ix_node = ExprNodes.IntNode(self.pos, value=str(index_value), constant_result=index_value)
  4685. else:
  4686. ix_node = ExprNodes.AddNode(
  4687. self.pos, operator='+', operand1=start_node, operand2=ix_node)
  4688. items.append(ExprNodes.IndexNode(self.pos, base=base, index=ix_node.analyse_types(env)))
  4689. return check_node, refs, items
  4690. def unroll_assignments(self, refs, check_node, lhs_list, rhs_list, env):
  4691. from . import UtilNodes
  4692. assignments = []
  4693. for lhs, rhs in zip(lhs_list, rhs_list):
  4694. assignments.append(SingleAssignmentNode(self.pos, lhs=lhs, rhs=rhs, first=self.first))
  4695. node = ParallelAssignmentNode(pos=self.pos, stats=assignments).analyse_expressions(env)
  4696. if check_node:
  4697. node = StatListNode(pos=self.pos, stats=[check_node, node])
  4698. for ref in refs[::-1]:
  4699. node = UtilNodes.LetNode(ref, node)
  4700. return node
  4701. def unroll_rhs(self, env):
  4702. from . import ExprNodes
  4703. if not isinstance(self.lhs, ExprNodes.TupleNode):
  4704. return
  4705. if any(arg.is_starred for arg in self.lhs.args):
  4706. return
  4707. unrolled = self.unroll(self.rhs, len(self.lhs.args), env)
  4708. if not unrolled:
  4709. return
  4710. check_node, refs, rhs = unrolled
  4711. return self.unroll_assignments(refs, check_node, self.lhs.args, rhs, env)
  4712. def unroll_lhs(self, env):
  4713. if self.lhs.type.is_ctuple:
  4714. # Handled directly.
  4715. return
  4716. from . import ExprNodes
  4717. if not isinstance(self.rhs, ExprNodes.TupleNode):
  4718. return
  4719. unrolled = self.unroll(self.lhs, len(self.rhs.args), env)
  4720. if not unrolled:
  4721. return
  4722. check_node, refs, lhs = unrolled
  4723. return self.unroll_assignments(refs, check_node, lhs, self.rhs.args, env)
  4724. def generate_rhs_evaluation_code(self, code):
  4725. self.rhs.generate_evaluation_code(code)
  4726. def generate_assignment_code(self, code, overloaded_assignment=False):
  4727. if self.is_overloaded_assignment:
  4728. self.lhs.generate_assignment_code(
  4729. self.rhs,
  4730. code,
  4731. overloaded_assignment=self.is_overloaded_assignment,
  4732. exception_check=self.exception_check,
  4733. exception_value=self.exception_value)
  4734. else:
  4735. self.lhs.generate_assignment_code(self.rhs, code)
  4736. def generate_function_definitions(self, env, code):
  4737. self.rhs.generate_function_definitions(env, code)
  4738. def annotate(self, code):
  4739. self.lhs.annotate(code)
  4740. self.rhs.annotate(code)
  4741. class CascadedAssignmentNode(AssignmentNode):
  4742. # An assignment with multiple left hand sides:
  4743. #
  4744. # a = b = c
  4745. #
  4746. # lhs_list [ExprNode] Left hand sides
  4747. # rhs ExprNode Right hand sides
  4748. #
  4749. # Used internally:
  4750. #
  4751. # coerced_values [ExprNode] RHS coerced to all distinct LHS types
  4752. # cloned_values [ExprNode] cloned RHS value for each LHS
  4753. # assignment_overloads [Bool] If each assignment uses a C++ operator=
  4754. child_attrs = ["lhs_list", "rhs", "coerced_values", "cloned_values"]
  4755. cloned_values = None
  4756. coerced_values = None
  4757. assignment_overloads = None
  4758. def analyse_declarations(self, env):
  4759. for lhs in self.lhs_list:
  4760. lhs.analyse_target_declaration(env)
  4761. def analyse_types(self, env, use_temp=0):
  4762. from .ExprNodes import CloneNode, ProxyNode
  4763. # collect distinct types used on the LHS
  4764. lhs_types = set()
  4765. for i, lhs in enumerate(self.lhs_list):
  4766. lhs = self.lhs_list[i] = lhs.analyse_target_types(env)
  4767. lhs.gil_assignment_check(env)
  4768. lhs_types.add(lhs.type)
  4769. rhs = self.rhs.analyse_types(env)
  4770. # common special case: only one type needed on the LHS => coerce only once
  4771. if len(lhs_types) == 1:
  4772. # Avoid coercion for overloaded assignment operators.
  4773. if next(iter(lhs_types)).is_cpp_class:
  4774. op = env.lookup_operator('=', [lhs, self.rhs])
  4775. if not op:
  4776. rhs = rhs.coerce_to(lhs_types.pop(), env)
  4777. else:
  4778. rhs = rhs.coerce_to(lhs_types.pop(), env)
  4779. if not rhs.is_name and not rhs.is_literal and (
  4780. use_temp or rhs.is_attribute or rhs.type.is_pyobject):
  4781. rhs = rhs.coerce_to_temp(env)
  4782. else:
  4783. rhs = rhs.coerce_to_simple(env)
  4784. self.rhs = ProxyNode(rhs) if rhs.is_temp else rhs
  4785. # clone RHS and coerce it to all distinct LHS types
  4786. self.coerced_values = []
  4787. coerced_values = {}
  4788. self.assignment_overloads = []
  4789. for lhs in self.lhs_list:
  4790. overloaded = lhs.type.is_cpp_class and env.lookup_operator('=', [lhs, self.rhs])
  4791. self.assignment_overloads.append(overloaded)
  4792. if lhs.type not in coerced_values and lhs.type != rhs.type:
  4793. rhs = CloneNode(self.rhs)
  4794. if not overloaded:
  4795. rhs = rhs.coerce_to(lhs.type, env)
  4796. self.coerced_values.append(rhs)
  4797. coerced_values[lhs.type] = rhs
  4798. # clone coerced values for all LHS assignments
  4799. self.cloned_values = []
  4800. for lhs in self.lhs_list:
  4801. rhs = coerced_values.get(lhs.type, self.rhs)
  4802. self.cloned_values.append(CloneNode(rhs))
  4803. return self
  4804. def generate_rhs_evaluation_code(self, code):
  4805. self.rhs.generate_evaluation_code(code)
  4806. def generate_assignment_code(self, code, overloaded_assignment=False):
  4807. # prepare all coercions
  4808. for rhs in self.coerced_values:
  4809. rhs.generate_evaluation_code(code)
  4810. # assign clones to LHS
  4811. for lhs, rhs, overload in zip(self.lhs_list, self.cloned_values, self.assignment_overloads):
  4812. rhs.generate_evaluation_code(code)
  4813. lhs.generate_assignment_code(rhs, code, overloaded_assignment=overload)
  4814. # dispose of coerced values and original RHS
  4815. for rhs_value in self.coerced_values:
  4816. rhs_value.generate_disposal_code(code)
  4817. rhs_value.free_temps(code)
  4818. self.rhs.generate_disposal_code(code)
  4819. self.rhs.free_temps(code)
  4820. def generate_function_definitions(self, env, code):
  4821. self.rhs.generate_function_definitions(env, code)
  4822. def annotate(self, code):
  4823. for rhs in self.coerced_values:
  4824. rhs.annotate(code)
  4825. for lhs, rhs in zip(self.lhs_list, self.cloned_values):
  4826. lhs.annotate(code)
  4827. rhs.annotate(code)
  4828. self.rhs.annotate(code)
  4829. class ParallelAssignmentNode(AssignmentNode):
  4830. # A combined packing/unpacking assignment:
  4831. #
  4832. # a, b, c = d, e, f
  4833. #
  4834. # This has been rearranged by the parser into
  4835. #
  4836. # a = d ; b = e ; c = f
  4837. #
  4838. # but we must evaluate all the right hand sides
  4839. # before assigning to any of the left hand sides.
  4840. #
  4841. # stats [AssignmentNode] The constituent assignments
  4842. child_attrs = ["stats"]
  4843. def analyse_declarations(self, env):
  4844. for stat in self.stats:
  4845. stat.analyse_declarations(env)
  4846. def analyse_expressions(self, env):
  4847. self.stats = [stat.analyse_types(env, use_temp=1)
  4848. for stat in self.stats]
  4849. return self
  4850. # def analyse_expressions(self, env):
  4851. # for stat in self.stats:
  4852. # stat.analyse_expressions_1(env, use_temp=1)
  4853. # for stat in self.stats:
  4854. # stat.analyse_expressions_2(env)
  4855. def generate_execution_code(self, code):
  4856. code.mark_pos(self.pos)
  4857. for stat in self.stats:
  4858. stat.generate_rhs_evaluation_code(code)
  4859. for stat in self.stats:
  4860. stat.generate_assignment_code(code)
  4861. def generate_function_definitions(self, env, code):
  4862. for stat in self.stats:
  4863. stat.generate_function_definitions(env, code)
  4864. def annotate(self, code):
  4865. for stat in self.stats:
  4866. stat.annotate(code)
  4867. class InPlaceAssignmentNode(AssignmentNode):
  4868. # An in place arithmetic operand:
  4869. #
  4870. # a += b
  4871. # a -= b
  4872. # ...
  4873. #
  4874. # lhs ExprNode Left hand side
  4875. # rhs ExprNode Right hand side
  4876. # operator char one of "+-*/%^&|"
  4877. #
  4878. # This code is a bit tricky because in order to obey Python
  4879. # semantics the sub-expressions (e.g. indices) of the lhs must
  4880. # not be evaluated twice. So we must re-use the values calculated
  4881. # in evaluation phase for the assignment phase as well.
  4882. # Fortunately, the type of the lhs node is fairly constrained
  4883. # (it must be a NameNode, AttributeNode, or IndexNode).
  4884. child_attrs = ["lhs", "rhs"]
  4885. def analyse_declarations(self, env):
  4886. self.lhs.analyse_target_declaration(env)
  4887. def analyse_types(self, env):
  4888. self.rhs = self.rhs.analyse_types(env)
  4889. self.lhs = self.lhs.analyse_target_types(env)
  4890. # When assigning to a fully indexed buffer or memoryview, coerce the rhs
  4891. if self.lhs.is_memview_index or self.lhs.is_buffer_access:
  4892. self.rhs = self.rhs.coerce_to(self.lhs.type, env)
  4893. elif self.lhs.type.is_string and self.operator in '+-':
  4894. # use pointer arithmetic for char* LHS instead of string concat
  4895. self.rhs = self.rhs.coerce_to(PyrexTypes.c_py_ssize_t_type, env)
  4896. return self
  4897. def generate_execution_code(self, code):
  4898. code.mark_pos(self.pos)
  4899. lhs, rhs = self.lhs, self.rhs
  4900. rhs.generate_evaluation_code(code)
  4901. lhs.generate_subexpr_evaluation_code(code)
  4902. c_op = self.operator
  4903. if c_op == "//":
  4904. c_op = "/"
  4905. elif c_op == "**":
  4906. error(self.pos, "No C inplace power operator")
  4907. if lhs.is_buffer_access or lhs.is_memview_index:
  4908. if lhs.type.is_pyobject:
  4909. error(self.pos, "In-place operators not allowed on object buffers in this release.")
  4910. if c_op in ('/', '%') and lhs.type.is_int and not code.globalstate.directives['cdivision']:
  4911. error(self.pos, "In-place non-c divide operators not allowed on int buffers.")
  4912. lhs.generate_buffer_setitem_code(rhs, code, c_op)
  4913. elif lhs.is_memview_slice:
  4914. error(self.pos, "Inplace operators not supported on memoryview slices")
  4915. else:
  4916. # C++
  4917. # TODO: make sure overload is declared
  4918. code.putln("%s %s= %s;" % (lhs.result(), c_op, rhs.result()))
  4919. lhs.generate_subexpr_disposal_code(code)
  4920. lhs.free_subexpr_temps(code)
  4921. rhs.generate_disposal_code(code)
  4922. rhs.free_temps(code)
  4923. def annotate(self, code):
  4924. self.lhs.annotate(code)
  4925. self.rhs.annotate(code)
  4926. def create_binop_node(self):
  4927. from . import ExprNodes
  4928. return ExprNodes.binop_node(self.pos, self.operator, self.lhs, self.rhs)
  4929. class PrintStatNode(StatNode):
  4930. # print statement
  4931. #
  4932. # arg_tuple TupleNode
  4933. # stream ExprNode or None (stdout)
  4934. # append_newline boolean
  4935. child_attrs = ["arg_tuple", "stream"]
  4936. def analyse_expressions(self, env):
  4937. if self.stream:
  4938. stream = self.stream.analyse_expressions(env)
  4939. self.stream = stream.coerce_to_pyobject(env)
  4940. arg_tuple = self.arg_tuple.analyse_expressions(env)
  4941. self.arg_tuple = arg_tuple.coerce_to_pyobject(env)
  4942. env.use_utility_code(printing_utility_code)
  4943. if len(self.arg_tuple.args) == 1 and self.append_newline:
  4944. env.use_utility_code(printing_one_utility_code)
  4945. return self
  4946. nogil_check = Node.gil_error
  4947. gil_message = "Python print statement"
  4948. def generate_execution_code(self, code):
  4949. code.mark_pos(self.pos)
  4950. if self.stream:
  4951. self.stream.generate_evaluation_code(code)
  4952. stream_result = self.stream.py_result()
  4953. else:
  4954. stream_result = '0'
  4955. if len(self.arg_tuple.args) == 1 and self.append_newline:
  4956. arg = self.arg_tuple.args[0]
  4957. arg.generate_evaluation_code(code)
  4958. code.putln(
  4959. "if (__Pyx_PrintOne(%s, %s) < 0) %s" % (
  4960. stream_result,
  4961. arg.py_result(),
  4962. code.error_goto(self.pos)))
  4963. arg.generate_disposal_code(code)
  4964. arg.free_temps(code)
  4965. else:
  4966. self.arg_tuple.generate_evaluation_code(code)
  4967. code.putln(
  4968. "if (__Pyx_Print(%s, %s, %d) < 0) %s" % (
  4969. stream_result,
  4970. self.arg_tuple.py_result(),
  4971. self.append_newline,
  4972. code.error_goto(self.pos)))
  4973. self.arg_tuple.generate_disposal_code(code)
  4974. self.arg_tuple.free_temps(code)
  4975. if self.stream:
  4976. self.stream.generate_disposal_code(code)
  4977. self.stream.free_temps(code)
  4978. def generate_function_definitions(self, env, code):
  4979. if self.stream:
  4980. self.stream.generate_function_definitions(env, code)
  4981. self.arg_tuple.generate_function_definitions(env, code)
  4982. def annotate(self, code):
  4983. if self.stream:
  4984. self.stream.annotate(code)
  4985. self.arg_tuple.annotate(code)
  4986. class ExecStatNode(StatNode):
  4987. # exec statement
  4988. #
  4989. # args [ExprNode]
  4990. child_attrs = ["args"]
  4991. def analyse_expressions(self, env):
  4992. for i, arg in enumerate(self.args):
  4993. arg = arg.analyse_expressions(env)
  4994. arg = arg.coerce_to_pyobject(env)
  4995. self.args[i] = arg
  4996. env.use_utility_code(Builtin.pyexec_utility_code)
  4997. return self
  4998. nogil_check = Node.gil_error
  4999. gil_message = "Python exec statement"
  5000. def generate_execution_code(self, code):
  5001. code.mark_pos(self.pos)
  5002. args = []
  5003. for arg in self.args:
  5004. arg.generate_evaluation_code(code)
  5005. args.append(arg.py_result())
  5006. args = tuple(args + ['0', '0'][:3-len(args)])
  5007. temp_result = code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=True)
  5008. code.putln("%s = __Pyx_PyExec3(%s, %s, %s);" % ((temp_result,) + args))
  5009. for arg in self.args:
  5010. arg.generate_disposal_code(code)
  5011. arg.free_temps(code)
  5012. code.putln(
  5013. code.error_goto_if_null(temp_result, self.pos))
  5014. code.put_gotref(temp_result)
  5015. code.put_decref_clear(temp_result, py_object_type)
  5016. code.funcstate.release_temp(temp_result)
  5017. def annotate(self, code):
  5018. for arg in self.args:
  5019. arg.annotate(code)
  5020. class DelStatNode(StatNode):
  5021. # del statement
  5022. #
  5023. # args [ExprNode]
  5024. child_attrs = ["args"]
  5025. ignore_nonexisting = False
  5026. def analyse_declarations(self, env):
  5027. for arg in self.args:
  5028. arg.analyse_target_declaration(env)
  5029. def analyse_expressions(self, env):
  5030. for i, arg in enumerate(self.args):
  5031. arg = self.args[i] = arg.analyse_target_expression(env, None)
  5032. if arg.type.is_pyobject or (arg.is_name and arg.type.is_memoryviewslice):
  5033. if arg.is_name and arg.entry.is_cglobal:
  5034. error(arg.pos, "Deletion of global C variable")
  5035. elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
  5036. self.cpp_check(env)
  5037. elif arg.type.is_cpp_class:
  5038. error(arg.pos, "Deletion of non-heap C++ object")
  5039. elif arg.is_subscript and arg.base.type is Builtin.bytearray_type:
  5040. pass # del ba[i]
  5041. else:
  5042. error(arg.pos, "Deletion of non-Python, non-C++ object")
  5043. #arg.release_target_temp(env)
  5044. return self
  5045. def nogil_check(self, env):
  5046. for arg in self.args:
  5047. if arg.type.is_pyobject:
  5048. self.gil_error()
  5049. gil_message = "Deleting Python object"
  5050. def generate_execution_code(self, code):
  5051. code.mark_pos(self.pos)
  5052. for arg in self.args:
  5053. if (arg.type.is_pyobject or
  5054. arg.type.is_memoryviewslice or
  5055. arg.is_subscript and arg.base.type is Builtin.bytearray_type):
  5056. arg.generate_deletion_code(
  5057. code, ignore_nonexisting=self.ignore_nonexisting)
  5058. elif arg.type.is_ptr and arg.type.base_type.is_cpp_class:
  5059. arg.generate_evaluation_code(code)
  5060. code.putln("delete %s;" % arg.result())
  5061. arg.generate_disposal_code(code)
  5062. # else error reported earlier
  5063. def annotate(self, code):
  5064. for arg in self.args:
  5065. arg.annotate(code)
  5066. class PassStatNode(StatNode):
  5067. # pass statement
  5068. child_attrs = []
  5069. def analyse_expressions(self, env):
  5070. return self
  5071. def generate_execution_code(self, code):
  5072. pass
  5073. class IndirectionNode(StatListNode):
  5074. """
  5075. This adds an indirection so that the node can be shared and a subtree can
  5076. be removed at any time by clearing self.stats.
  5077. """
  5078. def __init__(self, stats):
  5079. super(IndirectionNode, self).__init__(stats[0].pos, stats=stats)
  5080. class BreakStatNode(StatNode):
  5081. child_attrs = []
  5082. is_terminator = True
  5083. def analyse_expressions(self, env):
  5084. return self
  5085. def generate_execution_code(self, code):
  5086. code.mark_pos(self.pos)
  5087. if not code.break_label:
  5088. error(self.pos, "break statement not inside loop")
  5089. else:
  5090. code.put_goto(code.break_label)
  5091. class ContinueStatNode(StatNode):
  5092. child_attrs = []
  5093. is_terminator = True
  5094. def analyse_expressions(self, env):
  5095. return self
  5096. def generate_execution_code(self, code):
  5097. if not code.continue_label:
  5098. error(self.pos, "continue statement not inside loop")
  5099. return
  5100. code.mark_pos(self.pos)
  5101. code.put_goto(code.continue_label)
  5102. class ReturnStatNode(StatNode):
  5103. # return statement
  5104. #
  5105. # value ExprNode or None
  5106. # return_type PyrexType
  5107. # in_generator return inside of generator => raise StopIteration
  5108. # in_async_gen return inside of async generator
  5109. child_attrs = ["value"]
  5110. is_terminator = True
  5111. in_generator = False
  5112. in_async_gen = False
  5113. # Whether we are in a parallel section
  5114. in_parallel = False
  5115. def analyse_expressions(self, env):
  5116. return_type = env.return_type
  5117. self.return_type = return_type
  5118. if not return_type:
  5119. error(self.pos, "Return not inside a function body")
  5120. return self
  5121. if self.value:
  5122. if self.in_async_gen:
  5123. error(self.pos, "Return with value in async generator")
  5124. self.value = self.value.analyse_types(env)
  5125. if return_type.is_void or return_type.is_returncode:
  5126. error(self.value.pos, "Return with value in void function")
  5127. else:
  5128. self.value = self.value.coerce_to(env.return_type, env)
  5129. else:
  5130. if (not return_type.is_void
  5131. and not return_type.is_pyobject
  5132. and not return_type.is_returncode):
  5133. error(self.pos, "Return value required")
  5134. return self
  5135. def nogil_check(self, env):
  5136. if self.return_type.is_pyobject:
  5137. self.gil_error()
  5138. gil_message = "Returning Python object"
  5139. def generate_execution_code(self, code):
  5140. code.mark_pos(self.pos)
  5141. if not self.return_type:
  5142. # error reported earlier
  5143. return
  5144. value = self.value
  5145. if self.return_type.is_pyobject:
  5146. code.put_xdecref(Naming.retval_cname, self.return_type)
  5147. if value and value.is_none:
  5148. # Use specialised default handling for "return None".
  5149. value = None
  5150. if value:
  5151. value.generate_evaluation_code(code)
  5152. if self.return_type.is_memoryviewslice:
  5153. from . import MemoryView
  5154. MemoryView.put_acquire_memoryviewslice(
  5155. lhs_cname=Naming.retval_cname,
  5156. lhs_type=self.return_type,
  5157. lhs_pos=value.pos,
  5158. rhs=value,
  5159. code=code,
  5160. have_gil=self.in_nogil_context)
  5161. elif self.in_generator:
  5162. # return value == raise StopIteration(value), but uncatchable
  5163. code.globalstate.use_utility_code(
  5164. UtilityCode.load_cached("ReturnWithStopIteration", "Coroutine.c"))
  5165. code.putln("%s = NULL; __Pyx_ReturnWithStopIteration(%s);" % (
  5166. Naming.retval_cname,
  5167. value.py_result()))
  5168. value.generate_disposal_code(code)
  5169. else:
  5170. value.make_owned_reference(code)
  5171. code.putln("%s = %s;" % (
  5172. Naming.retval_cname,
  5173. value.result_as(self.return_type)))
  5174. value.generate_post_assignment_code(code)
  5175. value.free_temps(code)
  5176. else:
  5177. if self.return_type.is_pyobject:
  5178. if self.in_generator:
  5179. if self.in_async_gen:
  5180. code.globalstate.use_utility_code(
  5181. UtilityCode.load_cached("StopAsyncIteration", "Coroutine.c"))
  5182. code.put("PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration); ")
  5183. code.putln("%s = NULL;" % Naming.retval_cname)
  5184. else:
  5185. code.put_init_to_py_none(Naming.retval_cname, self.return_type)
  5186. elif self.return_type.is_returncode:
  5187. self.put_return(code, self.return_type.default_value)
  5188. for cname, type in code.funcstate.temps_holding_reference():
  5189. code.put_decref_clear(cname, type)
  5190. code.put_goto(code.return_label)
  5191. def put_return(self, code, value):
  5192. if self.in_parallel:
  5193. code.putln_openmp("#pragma omp critical(__pyx_returning)")
  5194. code.putln("%s = %s;" % (Naming.retval_cname, value))
  5195. def generate_function_definitions(self, env, code):
  5196. if self.value is not None:
  5197. self.value.generate_function_definitions(env, code)
  5198. def annotate(self, code):
  5199. if self.value:
  5200. self.value.annotate(code)
  5201. class RaiseStatNode(StatNode):
  5202. # raise statement
  5203. #
  5204. # exc_type ExprNode or None
  5205. # exc_value ExprNode or None
  5206. # exc_tb ExprNode or None
  5207. # cause ExprNode or None
  5208. child_attrs = ["exc_type", "exc_value", "exc_tb", "cause"]
  5209. is_terminator = True
  5210. def analyse_expressions(self, env):
  5211. if self.exc_type:
  5212. exc_type = self.exc_type.analyse_types(env)
  5213. self.exc_type = exc_type.coerce_to_pyobject(env)
  5214. if self.exc_value:
  5215. exc_value = self.exc_value.analyse_types(env)
  5216. self.exc_value = exc_value.coerce_to_pyobject(env)
  5217. if self.exc_tb:
  5218. exc_tb = self.exc_tb.analyse_types(env)
  5219. self.exc_tb = exc_tb.coerce_to_pyobject(env)
  5220. if self.cause:
  5221. cause = self.cause.analyse_types(env)
  5222. self.cause = cause.coerce_to_pyobject(env)
  5223. # special cases for builtin exceptions
  5224. self.builtin_exc_name = None
  5225. if self.exc_type and not self.exc_value and not self.exc_tb:
  5226. exc = self.exc_type
  5227. from . import ExprNodes
  5228. if (isinstance(exc, ExprNodes.SimpleCallNode) and
  5229. not (exc.args or (exc.arg_tuple is not None and exc.arg_tuple.args))):
  5230. exc = exc.function # extract the exception type
  5231. if exc.is_name and exc.entry.is_builtin:
  5232. self.builtin_exc_name = exc.name
  5233. if self.builtin_exc_name == 'MemoryError':
  5234. self.exc_type = None # has a separate implementation
  5235. return self
  5236. nogil_check = Node.gil_error
  5237. gil_message = "Raising exception"
  5238. def generate_execution_code(self, code):
  5239. code.mark_pos(self.pos)
  5240. if self.builtin_exc_name == 'MemoryError':
  5241. code.putln('PyErr_NoMemory(); %s' % code.error_goto(self.pos))
  5242. return
  5243. if self.exc_type:
  5244. self.exc_type.generate_evaluation_code(code)
  5245. type_code = self.exc_type.py_result()
  5246. if self.exc_type.is_name:
  5247. code.globalstate.use_entry_utility_code(self.exc_type.entry)
  5248. else:
  5249. type_code = "0"
  5250. if self.exc_value:
  5251. self.exc_value.generate_evaluation_code(code)
  5252. value_code = self.exc_value.py_result()
  5253. else:
  5254. value_code = "0"
  5255. if self.exc_tb:
  5256. self.exc_tb.generate_evaluation_code(code)
  5257. tb_code = self.exc_tb.py_result()
  5258. else:
  5259. tb_code = "0"
  5260. if self.cause:
  5261. self.cause.generate_evaluation_code(code)
  5262. cause_code = self.cause.py_result()
  5263. else:
  5264. cause_code = "0"
  5265. code.globalstate.use_utility_code(raise_utility_code)
  5266. code.putln(
  5267. "__Pyx_Raise(%s, %s, %s, %s);" % (
  5268. type_code,
  5269. value_code,
  5270. tb_code,
  5271. cause_code))
  5272. for obj in (self.exc_type, self.exc_value, self.exc_tb, self.cause):
  5273. if obj:
  5274. obj.generate_disposal_code(code)
  5275. obj.free_temps(code)
  5276. code.putln(
  5277. code.error_goto(self.pos))
  5278. def generate_function_definitions(self, env, code):
  5279. if self.exc_type is not None:
  5280. self.exc_type.generate_function_definitions(env, code)
  5281. if self.exc_value is not None:
  5282. self.exc_value.generate_function_definitions(env, code)
  5283. if self.exc_tb is not None:
  5284. self.exc_tb.generate_function_definitions(env, code)
  5285. if self.cause is not None:
  5286. self.cause.generate_function_definitions(env, code)
  5287. def annotate(self, code):
  5288. if self.exc_type:
  5289. self.exc_type.annotate(code)
  5290. if self.exc_value:
  5291. self.exc_value.annotate(code)
  5292. if self.exc_tb:
  5293. self.exc_tb.annotate(code)
  5294. if self.cause:
  5295. self.cause.annotate(code)
  5296. class ReraiseStatNode(StatNode):
  5297. child_attrs = []
  5298. is_terminator = True
  5299. def analyse_expressions(self, env):
  5300. return self
  5301. nogil_check = Node.gil_error
  5302. gil_message = "Raising exception"
  5303. def generate_execution_code(self, code):
  5304. code.mark_pos(self.pos)
  5305. vars = code.funcstate.exc_vars
  5306. if vars:
  5307. code.globalstate.use_utility_code(restore_exception_utility_code)
  5308. code.put_giveref(vars[0])
  5309. code.put_giveref(vars[1])
  5310. # fresh exceptions may not have a traceback yet (-> finally!)
  5311. code.put_xgiveref(vars[2])
  5312. code.putln("__Pyx_ErrRestoreWithState(%s, %s, %s);" % tuple(vars))
  5313. for varname in vars:
  5314. code.put("%s = 0; " % varname)
  5315. code.putln()
  5316. code.putln(code.error_goto(self.pos))
  5317. else:
  5318. code.globalstate.use_utility_code(
  5319. UtilityCode.load_cached("ReRaiseException", "Exceptions.c"))
  5320. code.putln("__Pyx_ReraiseException(); %s" % code.error_goto(self.pos))
  5321. class AssertStatNode(StatNode):
  5322. # assert statement
  5323. #
  5324. # cond ExprNode
  5325. # value ExprNode or None
  5326. child_attrs = ["cond", "value"]
  5327. def analyse_expressions(self, env):
  5328. self.cond = self.cond.analyse_boolean_expression(env)
  5329. if self.value:
  5330. value = self.value.analyse_types(env)
  5331. if value.type is Builtin.tuple_type or not value.type.is_builtin_type:
  5332. # prevent tuple values from being interpreted as argument value tuples
  5333. from .ExprNodes import TupleNode
  5334. value = TupleNode(value.pos, args=[value], slow=True)
  5335. self.value = value.analyse_types(env, skip_children=True).coerce_to_pyobject(env)
  5336. else:
  5337. self.value = value.coerce_to_pyobject(env)
  5338. return self
  5339. nogil_check = Node.gil_error
  5340. gil_message = "Raising exception"
  5341. def generate_execution_code(self, code):
  5342. code.putln("#ifndef CYTHON_WITHOUT_ASSERTIONS")
  5343. code.putln("if (unlikely(!Py_OptimizeFlag)) {")
  5344. code.mark_pos(self.pos)
  5345. self.cond.generate_evaluation_code(code)
  5346. code.putln(
  5347. "if (unlikely(!%s)) {" % self.cond.result())
  5348. if self.value:
  5349. self.value.generate_evaluation_code(code)
  5350. code.putln(
  5351. "PyErr_SetObject(PyExc_AssertionError, %s);" % self.value.py_result())
  5352. self.value.generate_disposal_code(code)
  5353. self.value.free_temps(code)
  5354. else:
  5355. code.putln(
  5356. "PyErr_SetNone(PyExc_AssertionError);")
  5357. code.putln(
  5358. code.error_goto(self.pos))
  5359. code.putln(
  5360. "}")
  5361. self.cond.generate_disposal_code(code)
  5362. self.cond.free_temps(code)
  5363. code.putln(
  5364. "}")
  5365. code.putln("#endif")
  5366. def generate_function_definitions(self, env, code):
  5367. self.cond.generate_function_definitions(env, code)
  5368. if self.value is not None:
  5369. self.value.generate_function_definitions(env, code)
  5370. def annotate(self, code):
  5371. self.cond.annotate(code)
  5372. if self.value:
  5373. self.value.annotate(code)
  5374. class IfStatNode(StatNode):
  5375. # if statement
  5376. #
  5377. # if_clauses [IfClauseNode]
  5378. # else_clause StatNode or None
  5379. child_attrs = ["if_clauses", "else_clause"]
  5380. def analyse_declarations(self, env):
  5381. for if_clause in self.if_clauses:
  5382. if_clause.analyse_declarations(env)
  5383. if self.else_clause:
  5384. self.else_clause.analyse_declarations(env)
  5385. def analyse_expressions(self, env):
  5386. self.if_clauses = [if_clause.analyse_expressions(env) for if_clause in self.if_clauses]
  5387. if self.else_clause:
  5388. self.else_clause = self.else_clause.analyse_expressions(env)
  5389. return self
  5390. def generate_execution_code(self, code):
  5391. code.mark_pos(self.pos)
  5392. end_label = code.new_label()
  5393. last = len(self.if_clauses)
  5394. if self.else_clause:
  5395. # If the 'else' clause is 'unlikely', then set the preceding 'if' clause to 'likely' to reflect that.
  5396. self._set_branch_hint(self.if_clauses[-1], self.else_clause, inverse=True)
  5397. else:
  5398. last -= 1 # avoid redundant goto at end of last if-clause
  5399. for i, if_clause in enumerate(self.if_clauses):
  5400. self._set_branch_hint(if_clause, if_clause.body)
  5401. if_clause.generate_execution_code(code, end_label, is_last=i == last)
  5402. if self.else_clause:
  5403. code.mark_pos(self.else_clause.pos)
  5404. code.putln("/*else*/ {")
  5405. self.else_clause.generate_execution_code(code)
  5406. code.putln("}")
  5407. code.put_label(end_label)
  5408. def _set_branch_hint(self, clause, statements_node, inverse=False):
  5409. if not statements_node.is_terminator:
  5410. return
  5411. if not isinstance(statements_node, StatListNode) or not statements_node.stats:
  5412. return
  5413. # Anything that unconditionally raises exceptions should be considered unlikely.
  5414. if isinstance(statements_node.stats[-1], (RaiseStatNode, ReraiseStatNode)):
  5415. if len(statements_node.stats) > 1:
  5416. # Allow simple statements before the 'raise', but no conditions, loops, etc.
  5417. non_branch_nodes = (ExprStatNode, AssignmentNode, DelStatNode, GlobalNode, NonlocalNode)
  5418. for node in statements_node.stats[:-1]:
  5419. if not isinstance(node, non_branch_nodes):
  5420. return
  5421. clause.branch_hint = 'likely' if inverse else 'unlikely'
  5422. def generate_function_definitions(self, env, code):
  5423. for clause in self.if_clauses:
  5424. clause.generate_function_definitions(env, code)
  5425. if self.else_clause is not None:
  5426. self.else_clause.generate_function_definitions(env, code)
  5427. def annotate(self, code):
  5428. for if_clause in self.if_clauses:
  5429. if_clause.annotate(code)
  5430. if self.else_clause:
  5431. self.else_clause.annotate(code)
  5432. class IfClauseNode(Node):
  5433. # if or elif clause in an if statement
  5434. #
  5435. # condition ExprNode
  5436. # body StatNode
  5437. child_attrs = ["condition", "body"]
  5438. branch_hint = None
  5439. def analyse_declarations(self, env):
  5440. self.body.analyse_declarations(env)
  5441. def analyse_expressions(self, env):
  5442. self.condition = self.condition.analyse_temp_boolean_expression(env)
  5443. self.body = self.body.analyse_expressions(env)
  5444. return self
  5445. def generate_execution_code(self, code, end_label, is_last):
  5446. self.condition.generate_evaluation_code(code)
  5447. code.mark_pos(self.pos)
  5448. condition = self.condition.result()
  5449. if self.branch_hint:
  5450. condition = '%s(%s)' % (self.branch_hint, condition)
  5451. code.putln("if (%s) {" % condition)
  5452. self.condition.generate_disposal_code(code)
  5453. self.condition.free_temps(code)
  5454. self.body.generate_execution_code(code)
  5455. code.mark_pos(self.pos, trace=False)
  5456. if not (is_last or self.body.is_terminator):
  5457. code.put_goto(end_label)
  5458. code.putln("}")
  5459. def generate_function_definitions(self, env, code):
  5460. self.condition.generate_function_definitions(env, code)
  5461. self.body.generate_function_definitions(env, code)
  5462. def annotate(self, code):
  5463. self.condition.annotate(code)
  5464. self.body.annotate(code)
  5465. class SwitchCaseNode(StatNode):
  5466. # Generated in the optimization of an if-elif-else node
  5467. #
  5468. # conditions [ExprNode]
  5469. # body StatNode
  5470. child_attrs = ['conditions', 'body']
  5471. def generate_execution_code(self, code):
  5472. for cond in self.conditions:
  5473. code.mark_pos(cond.pos)
  5474. cond.generate_evaluation_code(code)
  5475. code.putln("case %s:" % cond.result())
  5476. self.body.generate_execution_code(code)
  5477. code.mark_pos(self.pos, trace=False)
  5478. code.putln("break;")
  5479. def generate_function_definitions(self, env, code):
  5480. for cond in self.conditions:
  5481. cond.generate_function_definitions(env, code)
  5482. self.body.generate_function_definitions(env, code)
  5483. def annotate(self, code):
  5484. for cond in self.conditions:
  5485. cond.annotate(code)
  5486. self.body.annotate(code)
  5487. class SwitchStatNode(StatNode):
  5488. # Generated in the optimization of an if-elif-else node
  5489. #
  5490. # test ExprNode
  5491. # cases [SwitchCaseNode]
  5492. # else_clause StatNode or None
  5493. child_attrs = ['test', 'cases', 'else_clause']
  5494. def generate_execution_code(self, code):
  5495. self.test.generate_evaluation_code(code)
  5496. code.mark_pos(self.pos)
  5497. code.putln("switch (%s) {" % self.test.result())
  5498. for case in self.cases:
  5499. case.generate_execution_code(code)
  5500. if self.else_clause is not None:
  5501. code.putln("default:")
  5502. self.else_clause.generate_execution_code(code)
  5503. code.putln("break;")
  5504. else:
  5505. # Always generate a default clause to prevent C compiler warnings
  5506. # about unmatched enum values (it was not the user who decided to
  5507. # generate the switch statement, so shouldn't be bothered).
  5508. code.putln("default: break;")
  5509. code.putln("}")
  5510. def generate_function_definitions(self, env, code):
  5511. self.test.generate_function_definitions(env, code)
  5512. for case in self.cases:
  5513. case.generate_function_definitions(env, code)
  5514. if self.else_clause is not None:
  5515. self.else_clause.generate_function_definitions(env, code)
  5516. def annotate(self, code):
  5517. self.test.annotate(code)
  5518. for case in self.cases:
  5519. case.annotate(code)
  5520. if self.else_clause is not None:
  5521. self.else_clause.annotate(code)
  5522. class LoopNode(object):
  5523. pass
  5524. class WhileStatNode(LoopNode, StatNode):
  5525. # while statement
  5526. #
  5527. # condition ExprNode
  5528. # body StatNode
  5529. # else_clause StatNode
  5530. child_attrs = ["condition", "body", "else_clause"]
  5531. def analyse_declarations(self, env):
  5532. self.body.analyse_declarations(env)
  5533. if self.else_clause:
  5534. self.else_clause.analyse_declarations(env)
  5535. def analyse_expressions(self, env):
  5536. if self.condition:
  5537. self.condition = self.condition.analyse_temp_boolean_expression(env)
  5538. self.body = self.body.analyse_expressions(env)
  5539. if self.else_clause:
  5540. self.else_clause = self.else_clause.analyse_expressions(env)
  5541. return self
  5542. def generate_execution_code(self, code):
  5543. code.mark_pos(self.pos)
  5544. old_loop_labels = code.new_loop_labels()
  5545. code.putln(
  5546. "while (1) {")
  5547. if self.condition:
  5548. self.condition.generate_evaluation_code(code)
  5549. self.condition.generate_disposal_code(code)
  5550. code.putln(
  5551. "if (!%s) break;" % self.condition.result())
  5552. self.condition.free_temps(code)
  5553. self.body.generate_execution_code(code)
  5554. code.put_label(code.continue_label)
  5555. code.putln("}")
  5556. break_label = code.break_label
  5557. code.set_loop_labels(old_loop_labels)
  5558. if self.else_clause:
  5559. code.mark_pos(self.else_clause.pos)
  5560. code.putln("/*else*/ {")
  5561. self.else_clause.generate_execution_code(code)
  5562. code.putln("}")
  5563. code.put_label(break_label)
  5564. def generate_function_definitions(self, env, code):
  5565. if self.condition:
  5566. self.condition.generate_function_definitions(env, code)
  5567. self.body.generate_function_definitions(env, code)
  5568. if self.else_clause is not None:
  5569. self.else_clause.generate_function_definitions(env, code)
  5570. def annotate(self, code):
  5571. if self.condition:
  5572. self.condition.annotate(code)
  5573. self.body.annotate(code)
  5574. if self.else_clause:
  5575. self.else_clause.annotate(code)
  5576. class DictIterationNextNode(Node):
  5577. # Helper node for calling PyDict_Next() inside of a WhileStatNode
  5578. # and checking the dictionary size for changes. Created in
  5579. # Optimize.py.
  5580. child_attrs = ['dict_obj', 'expected_size', 'pos_index_var',
  5581. 'coerced_key_var', 'coerced_value_var', 'coerced_tuple_var',
  5582. 'key_target', 'value_target', 'tuple_target', 'is_dict_flag']
  5583. coerced_key_var = key_ref = None
  5584. coerced_value_var = value_ref = None
  5585. coerced_tuple_var = tuple_ref = None
  5586. def __init__(self, dict_obj, expected_size, pos_index_var,
  5587. key_target, value_target, tuple_target, is_dict_flag):
  5588. Node.__init__(
  5589. self, dict_obj.pos,
  5590. dict_obj=dict_obj,
  5591. expected_size=expected_size,
  5592. pos_index_var=pos_index_var,
  5593. key_target=key_target,
  5594. value_target=value_target,
  5595. tuple_target=tuple_target,
  5596. is_dict_flag=is_dict_flag,
  5597. is_temp=True,
  5598. type=PyrexTypes.c_bint_type)
  5599. def analyse_expressions(self, env):
  5600. from . import ExprNodes
  5601. self.dict_obj = self.dict_obj.analyse_types(env)
  5602. self.expected_size = self.expected_size.analyse_types(env)
  5603. if self.pos_index_var:
  5604. self.pos_index_var = self.pos_index_var.analyse_types(env)
  5605. if self.key_target:
  5606. self.key_target = self.key_target.analyse_target_types(env)
  5607. self.key_ref = ExprNodes.TempNode(self.key_target.pos, PyrexTypes.py_object_type)
  5608. self.coerced_key_var = self.key_ref.coerce_to(self.key_target.type, env)
  5609. if self.value_target:
  5610. self.value_target = self.value_target.analyse_target_types(env)
  5611. self.value_ref = ExprNodes.TempNode(self.value_target.pos, type=PyrexTypes.py_object_type)
  5612. self.coerced_value_var = self.value_ref.coerce_to(self.value_target.type, env)
  5613. if self.tuple_target:
  5614. self.tuple_target = self.tuple_target.analyse_target_types(env)
  5615. self.tuple_ref = ExprNodes.TempNode(self.tuple_target.pos, PyrexTypes.py_object_type)
  5616. self.coerced_tuple_var = self.tuple_ref.coerce_to(self.tuple_target.type, env)
  5617. self.is_dict_flag = self.is_dict_flag.analyse_types(env)
  5618. return self
  5619. def generate_function_definitions(self, env, code):
  5620. self.dict_obj.generate_function_definitions(env, code)
  5621. def generate_execution_code(self, code):
  5622. code.globalstate.use_utility_code(UtilityCode.load_cached("dict_iter", "Optimize.c"))
  5623. self.dict_obj.generate_evaluation_code(code)
  5624. assignments = []
  5625. temp_addresses = []
  5626. for var, result, target in [(self.key_ref, self.coerced_key_var, self.key_target),
  5627. (self.value_ref, self.coerced_value_var, self.value_target),
  5628. (self.tuple_ref, self.coerced_tuple_var, self.tuple_target)]:
  5629. if target is None:
  5630. addr = 'NULL'
  5631. else:
  5632. assignments.append((var, result, target))
  5633. var.allocate(code)
  5634. addr = '&%s' % var.result()
  5635. temp_addresses.append(addr)
  5636. result_temp = code.funcstate.allocate_temp(PyrexTypes.c_int_type, False)
  5637. code.putln("%s = __Pyx_dict_iter_next(%s, %s, &%s, %s, %s, %s, %s);" % (
  5638. result_temp,
  5639. self.dict_obj.py_result(),
  5640. self.expected_size.result(),
  5641. self.pos_index_var.result(),
  5642. temp_addresses[0],
  5643. temp_addresses[1],
  5644. temp_addresses[2],
  5645. self.is_dict_flag.result()
  5646. ))
  5647. code.putln("if (unlikely(%s == 0)) break;" % result_temp)
  5648. code.putln(code.error_goto_if("%s == -1" % result_temp, self.pos))
  5649. code.funcstate.release_temp(result_temp)
  5650. # evaluate all coercions before the assignments
  5651. for var, result, target in assignments:
  5652. code.put_gotref(var.result())
  5653. for var, result, target in assignments:
  5654. result.generate_evaluation_code(code)
  5655. for var, result, target in assignments:
  5656. target.generate_assignment_code(result, code)
  5657. var.release(code)
  5658. class SetIterationNextNode(Node):
  5659. # Helper node for calling _PySet_NextEntry() inside of a WhileStatNode
  5660. # and checking the set size for changes. Created in Optimize.py.
  5661. child_attrs = ['set_obj', 'expected_size', 'pos_index_var',
  5662. 'coerced_value_var', 'value_target', 'is_set_flag']
  5663. coerced_value_var = value_ref = None
  5664. def __init__(self, set_obj, expected_size, pos_index_var, value_target, is_set_flag):
  5665. Node.__init__(
  5666. self, set_obj.pos,
  5667. set_obj=set_obj,
  5668. expected_size=expected_size,
  5669. pos_index_var=pos_index_var,
  5670. value_target=value_target,
  5671. is_set_flag=is_set_flag,
  5672. is_temp=True,
  5673. type=PyrexTypes.c_bint_type)
  5674. def analyse_expressions(self, env):
  5675. from . import ExprNodes
  5676. self.set_obj = self.set_obj.analyse_types(env)
  5677. self.expected_size = self.expected_size.analyse_types(env)
  5678. self.pos_index_var = self.pos_index_var.analyse_types(env)
  5679. self.value_target = self.value_target.analyse_target_types(env)
  5680. self.value_ref = ExprNodes.TempNode(self.value_target.pos, type=PyrexTypes.py_object_type)
  5681. self.coerced_value_var = self.value_ref.coerce_to(self.value_target.type, env)
  5682. self.is_set_flag = self.is_set_flag.analyse_types(env)
  5683. return self
  5684. def generate_function_definitions(self, env, code):
  5685. self.set_obj.generate_function_definitions(env, code)
  5686. def generate_execution_code(self, code):
  5687. code.globalstate.use_utility_code(UtilityCode.load_cached("set_iter", "Optimize.c"))
  5688. self.set_obj.generate_evaluation_code(code)
  5689. value_ref = self.value_ref
  5690. value_ref.allocate(code)
  5691. result_temp = code.funcstate.allocate_temp(PyrexTypes.c_int_type, False)
  5692. code.putln("%s = __Pyx_set_iter_next(%s, %s, &%s, &%s, %s);" % (
  5693. result_temp,
  5694. self.set_obj.py_result(),
  5695. self.expected_size.result(),
  5696. self.pos_index_var.result(),
  5697. value_ref.result(),
  5698. self.is_set_flag.result()
  5699. ))
  5700. code.putln("if (unlikely(%s == 0)) break;" % result_temp)
  5701. code.putln(code.error_goto_if("%s == -1" % result_temp, self.pos))
  5702. code.funcstate.release_temp(result_temp)
  5703. # evaluate all coercions before the assignments
  5704. code.put_gotref(value_ref.result())
  5705. self.coerced_value_var.generate_evaluation_code(code)
  5706. self.value_target.generate_assignment_code(self.coerced_value_var, code)
  5707. value_ref.release(code)
  5708. def ForStatNode(pos, **kw):
  5709. if 'iterator' in kw:
  5710. if kw['iterator'].is_async:
  5711. return AsyncForStatNode(pos, **kw)
  5712. else:
  5713. return ForInStatNode(pos, **kw)
  5714. else:
  5715. return ForFromStatNode(pos, **kw)
  5716. class _ForInStatNode(LoopNode, StatNode):
  5717. # Base class of 'for-in' statements.
  5718. #
  5719. # target ExprNode
  5720. # iterator IteratorNode | AIterAwaitExprNode(AsyncIteratorNode)
  5721. # body StatNode
  5722. # else_clause StatNode
  5723. # item NextNode | AwaitExprNode(AsyncNextNode)
  5724. # is_async boolean true for 'async for' statements
  5725. child_attrs = ["target", "item", "iterator", "body", "else_clause"]
  5726. item = None
  5727. is_async = False
  5728. def _create_item_node(self):
  5729. raise NotImplementedError("must be implemented by subclasses")
  5730. def analyse_declarations(self, env):
  5731. self.target.analyse_target_declaration(env)
  5732. self.body.analyse_declarations(env)
  5733. if self.else_clause:
  5734. self.else_clause.analyse_declarations(env)
  5735. self._create_item_node()
  5736. def analyse_expressions(self, env):
  5737. self.target = self.target.analyse_target_types(env)
  5738. self.iterator = self.iterator.analyse_expressions(env)
  5739. self._create_item_node() # must rewrap self.item after analysis
  5740. self.item = self.item.analyse_expressions(env)
  5741. if (not self.is_async and
  5742. (self.iterator.type.is_ptr or self.iterator.type.is_array) and
  5743. self.target.type.assignable_from(self.iterator.type)):
  5744. # C array slice optimization.
  5745. pass
  5746. else:
  5747. self.item = self.item.coerce_to(self.target.type, env)
  5748. self.body = self.body.analyse_expressions(env)
  5749. if self.else_clause:
  5750. self.else_clause = self.else_clause.analyse_expressions(env)
  5751. return self
  5752. def generate_execution_code(self, code):
  5753. code.mark_pos(self.pos)
  5754. old_loop_labels = code.new_loop_labels()
  5755. self.iterator.generate_evaluation_code(code)
  5756. code.putln("for (;;) {")
  5757. self.item.generate_evaluation_code(code)
  5758. self.target.generate_assignment_code(self.item, code)
  5759. self.body.generate_execution_code(code)
  5760. code.mark_pos(self.pos)
  5761. code.put_label(code.continue_label)
  5762. code.putln("}")
  5763. break_label = code.break_label
  5764. code.set_loop_labels(old_loop_labels)
  5765. if self.else_clause:
  5766. # in nested loops, the 'else' block can contain a
  5767. # 'continue' statement for the outer loop, but we may need
  5768. # to generate cleanup code before taking that path, so we
  5769. # intercept it here
  5770. orig_continue_label = code.continue_label
  5771. code.continue_label = code.new_label('outer_continue')
  5772. code.putln("/*else*/ {")
  5773. self.else_clause.generate_execution_code(code)
  5774. code.putln("}")
  5775. if code.label_used(code.continue_label):
  5776. code.put_goto(break_label)
  5777. code.mark_pos(self.pos)
  5778. code.put_label(code.continue_label)
  5779. self.iterator.generate_disposal_code(code)
  5780. code.put_goto(orig_continue_label)
  5781. code.set_loop_labels(old_loop_labels)
  5782. code.mark_pos(self.pos)
  5783. if code.label_used(break_label):
  5784. code.put_label(break_label)
  5785. self.iterator.generate_disposal_code(code)
  5786. self.iterator.free_temps(code)
  5787. def generate_function_definitions(self, env, code):
  5788. self.target.generate_function_definitions(env, code)
  5789. self.iterator.generate_function_definitions(env, code)
  5790. self.body.generate_function_definitions(env, code)
  5791. if self.else_clause is not None:
  5792. self.else_clause.generate_function_definitions(env, code)
  5793. def annotate(self, code):
  5794. self.target.annotate(code)
  5795. self.iterator.annotate(code)
  5796. self.body.annotate(code)
  5797. if self.else_clause:
  5798. self.else_clause.annotate(code)
  5799. self.item.annotate(code)
  5800. class ForInStatNode(_ForInStatNode):
  5801. # 'for' statement
  5802. is_async = False
  5803. def _create_item_node(self):
  5804. from .ExprNodes import NextNode
  5805. self.item = NextNode(self.iterator)
  5806. class AsyncForStatNode(_ForInStatNode):
  5807. # 'async for' statement
  5808. #
  5809. # iterator AIterAwaitExprNode(AsyncIteratorNode)
  5810. # item AwaitIterNextExprNode(AsyncIteratorNode)
  5811. is_async = True
  5812. def __init__(self, pos, **kw):
  5813. assert 'item' not in kw
  5814. from . import ExprNodes
  5815. # AwaitExprNodes must appear before running MarkClosureVisitor
  5816. kw['item'] = ExprNodes.AwaitIterNextExprNode(kw['iterator'].pos, arg=None)
  5817. _ForInStatNode.__init__(self, pos, **kw)
  5818. def _create_item_node(self):
  5819. from . import ExprNodes
  5820. self.item.arg = ExprNodes.AsyncNextNode(self.iterator)
  5821. class ForFromStatNode(LoopNode, StatNode):
  5822. # for name from expr rel name rel expr
  5823. #
  5824. # target NameNode
  5825. # bound1 ExprNode
  5826. # relation1 string
  5827. # relation2 string
  5828. # bound2 ExprNode
  5829. # step ExprNode or None
  5830. # body StatNode
  5831. # else_clause StatNode or None
  5832. #
  5833. # Used internally:
  5834. #
  5835. # from_range bool
  5836. # is_py_target bool
  5837. # loopvar_node ExprNode (usually a NameNode or temp node)
  5838. # py_loopvar_node PyTempNode or None
  5839. child_attrs = ["target", "bound1", "bound2", "step", "body", "else_clause"]
  5840. is_py_target = False
  5841. loopvar_node = None
  5842. py_loopvar_node = None
  5843. from_range = False
  5844. gil_message = "For-loop using object bounds or target"
  5845. def nogil_check(self, env):
  5846. for x in (self.target, self.bound1, self.bound2):
  5847. if x.type.is_pyobject:
  5848. self.gil_error()
  5849. def analyse_declarations(self, env):
  5850. self.target.analyse_target_declaration(env)
  5851. self.body.analyse_declarations(env)
  5852. if self.else_clause:
  5853. self.else_clause.analyse_declarations(env)
  5854. def analyse_expressions(self, env):
  5855. from . import ExprNodes
  5856. self.target = self.target.analyse_target_types(env)
  5857. self.bound1 = self.bound1.analyse_types(env)
  5858. self.bound2 = self.bound2.analyse_types(env)
  5859. if self.step is not None:
  5860. if isinstance(self.step, ExprNodes.UnaryMinusNode):
  5861. warning(self.step.pos, "Probable infinite loop in for-from-by statement. "
  5862. "Consider switching the directions of the relations.", 2)
  5863. self.step = self.step.analyse_types(env)
  5864. self.set_up_loop(env)
  5865. target_type = self.target.type
  5866. if not (target_type.is_pyobject or target_type.is_numeric):
  5867. error(self.target.pos, "for-from loop variable must be c numeric type or Python object")
  5868. self.body = self.body.analyse_expressions(env)
  5869. if self.else_clause:
  5870. self.else_clause = self.else_clause.analyse_expressions(env)
  5871. return self
  5872. def set_up_loop(self, env):
  5873. from . import ExprNodes
  5874. target_type = self.target.type
  5875. if target_type.is_numeric:
  5876. loop_type = target_type
  5877. else:
  5878. if target_type.is_enum:
  5879. warning(self.target.pos,
  5880. "Integer loops over enum values are fragile. Please cast to a safe integer type instead.")
  5881. loop_type = PyrexTypes.c_long_type if target_type.is_pyobject else PyrexTypes.c_int_type
  5882. if not self.bound1.type.is_pyobject:
  5883. loop_type = PyrexTypes.widest_numeric_type(loop_type, self.bound1.type)
  5884. if not self.bound2.type.is_pyobject:
  5885. loop_type = PyrexTypes.widest_numeric_type(loop_type, self.bound2.type)
  5886. if self.step is not None and not self.step.type.is_pyobject:
  5887. loop_type = PyrexTypes.widest_numeric_type(loop_type, self.step.type)
  5888. self.bound1 = self.bound1.coerce_to(loop_type, env)
  5889. self.bound2 = self.bound2.coerce_to(loop_type, env)
  5890. if not self.bound2.is_literal:
  5891. self.bound2 = self.bound2.coerce_to_temp(env)
  5892. if self.step is not None:
  5893. self.step = self.step.coerce_to(loop_type, env)
  5894. if not self.step.is_literal:
  5895. self.step = self.step.coerce_to_temp(env)
  5896. if target_type.is_numeric or target_type.is_enum:
  5897. self.is_py_target = False
  5898. if isinstance(self.target, ExprNodes.BufferIndexNode):
  5899. raise error(self.pos, "Buffer or memoryview slicing/indexing not allowed as for-loop target.")
  5900. self.loopvar_node = self.target
  5901. self.py_loopvar_node = None
  5902. else:
  5903. self.is_py_target = True
  5904. c_loopvar_node = ExprNodes.TempNode(self.pos, loop_type, env)
  5905. self.loopvar_node = c_loopvar_node
  5906. self.py_loopvar_node = ExprNodes.CloneNode(c_loopvar_node).coerce_to_pyobject(env)
  5907. def generate_execution_code(self, code):
  5908. code.mark_pos(self.pos)
  5909. old_loop_labels = code.new_loop_labels()
  5910. from_range = self.from_range
  5911. self.bound1.generate_evaluation_code(code)
  5912. self.bound2.generate_evaluation_code(code)
  5913. offset, incop = self.relation_table[self.relation1]
  5914. if self.step is not None:
  5915. self.step.generate_evaluation_code(code)
  5916. step = self.step.result()
  5917. incop = "%s=%s" % (incop[0], step) # e.g. '++' => '+= STEP'
  5918. else:
  5919. step = '1'
  5920. from . import ExprNodes
  5921. if isinstance(self.loopvar_node, ExprNodes.TempNode):
  5922. self.loopvar_node.allocate(code)
  5923. if isinstance(self.py_loopvar_node, ExprNodes.TempNode):
  5924. self.py_loopvar_node.allocate(code)
  5925. loopvar_type = PyrexTypes.c_long_type if self.target.type.is_enum else self.target.type
  5926. if from_range and not self.is_py_target:
  5927. loopvar_name = code.funcstate.allocate_temp(loopvar_type, False)
  5928. else:
  5929. loopvar_name = self.loopvar_node.result()
  5930. if loopvar_type.is_int and not loopvar_type.signed and self.relation2[0] == '>':
  5931. # Handle the case where the endpoint of an unsigned int iteration
  5932. # is within step of 0.
  5933. code.putln("for (%s = %s%s + %s; %s %s %s + %s; ) { %s%s;" % (
  5934. loopvar_name,
  5935. self.bound1.result(), offset, step,
  5936. loopvar_name, self.relation2, self.bound2.result(), step,
  5937. loopvar_name, incop))
  5938. else:
  5939. code.putln("for (%s = %s%s; %s %s %s; %s%s) {" % (
  5940. loopvar_name,
  5941. self.bound1.result(), offset,
  5942. loopvar_name, self.relation2, self.bound2.result(),
  5943. loopvar_name, incop))
  5944. coerced_loopvar_node = self.py_loopvar_node
  5945. if coerced_loopvar_node is None and from_range:
  5946. coerced_loopvar_node = ExprNodes.RawCNameExprNode(self.target.pos, loopvar_type, loopvar_name)
  5947. if coerced_loopvar_node is not None:
  5948. coerced_loopvar_node.generate_evaluation_code(code)
  5949. self.target.generate_assignment_code(coerced_loopvar_node, code)
  5950. self.body.generate_execution_code(code)
  5951. code.put_label(code.continue_label)
  5952. if not from_range and self.py_loopvar_node:
  5953. # This mess is to make for..from loops with python targets behave
  5954. # exactly like those with C targets with regards to re-assignment
  5955. # of the loop variable.
  5956. if self.target.entry.is_pyglobal:
  5957. # We know target is a NameNode, this is the only ugly case.
  5958. target_node = ExprNodes.PyTempNode(self.target.pos, None)
  5959. target_node.allocate(code)
  5960. interned_cname = code.intern_identifier(self.target.entry.name)
  5961. if self.target.entry.scope.is_module_scope:
  5962. code.globalstate.use_utility_code(
  5963. UtilityCode.load_cached("GetModuleGlobalName", "ObjectHandling.c"))
  5964. lookup_func = '__Pyx_GetModuleGlobalName(%s)'
  5965. else:
  5966. code.globalstate.use_utility_code(
  5967. UtilityCode.load_cached("GetNameInClass", "ObjectHandling.c"))
  5968. lookup_func = '__Pyx_GetNameInClass(%s, %%s)' % (
  5969. self.target.entry.scope.namespace_cname)
  5970. code.putln("%s = %s; %s" % (
  5971. target_node.result(),
  5972. lookup_func % interned_cname,
  5973. code.error_goto_if_null(target_node.result(), self.target.pos)))
  5974. code.put_gotref(target_node.result())
  5975. else:
  5976. target_node = self.target
  5977. from_py_node = ExprNodes.CoerceFromPyTypeNode(
  5978. self.loopvar_node.type, target_node, self.target.entry.scope)
  5979. from_py_node.temp_code = loopvar_name
  5980. from_py_node.generate_result_code(code)
  5981. if self.target.entry.is_pyglobal:
  5982. code.put_decref(target_node.result(), target_node.type)
  5983. target_node.release(code)
  5984. code.putln("}")
  5985. if not from_range and self.py_loopvar_node:
  5986. # This is potentially wasteful, but we don't want the semantics to
  5987. # depend on whether or not the loop is a python type.
  5988. self.py_loopvar_node.generate_evaluation_code(code)
  5989. self.target.generate_assignment_code(self.py_loopvar_node, code)
  5990. if from_range and not self.is_py_target:
  5991. code.funcstate.release_temp(loopvar_name)
  5992. break_label = code.break_label
  5993. code.set_loop_labels(old_loop_labels)
  5994. if self.else_clause:
  5995. code.putln("/*else*/ {")
  5996. self.else_clause.generate_execution_code(code)
  5997. code.putln("}")
  5998. code.put_label(break_label)
  5999. self.bound1.generate_disposal_code(code)
  6000. self.bound1.free_temps(code)
  6001. self.bound2.generate_disposal_code(code)
  6002. self.bound2.free_temps(code)
  6003. if isinstance(self.loopvar_node, ExprNodes.TempNode):
  6004. self.loopvar_node.release(code)
  6005. if isinstance(self.py_loopvar_node, ExprNodes.TempNode):
  6006. self.py_loopvar_node.release(code)
  6007. if self.step is not None:
  6008. self.step.generate_disposal_code(code)
  6009. self.step.free_temps(code)
  6010. relation_table = {
  6011. # {relop : (initial offset, increment op)}
  6012. '<=': ("", "++"),
  6013. '<' : ("+1", "++"),
  6014. '>=': ("", "--"),
  6015. '>' : ("-1", "--"),
  6016. }
  6017. def generate_function_definitions(self, env, code):
  6018. self.target.generate_function_definitions(env, code)
  6019. self.bound1.generate_function_definitions(env, code)
  6020. self.bound2.generate_function_definitions(env, code)
  6021. if self.step is not None:
  6022. self.step.generate_function_definitions(env, code)
  6023. self.body.generate_function_definitions(env, code)
  6024. if self.else_clause is not None:
  6025. self.else_clause.generate_function_definitions(env, code)
  6026. def annotate(self, code):
  6027. self.target.annotate(code)
  6028. self.bound1.annotate(code)
  6029. self.bound2.annotate(code)
  6030. if self.step:
  6031. self.step.annotate(code)
  6032. self.body.annotate(code)
  6033. if self.else_clause:
  6034. self.else_clause.annotate(code)
  6035. class WithStatNode(StatNode):
  6036. """
  6037. Represents a Python with statement.
  6038. Implemented by the WithTransform as follows:
  6039. MGR = EXPR
  6040. EXIT = MGR.__exit__
  6041. VALUE = MGR.__enter__()
  6042. EXC = True
  6043. try:
  6044. try:
  6045. TARGET = VALUE # optional
  6046. BODY
  6047. except:
  6048. EXC = False
  6049. if not EXIT(*EXCINFO):
  6050. raise
  6051. finally:
  6052. if EXC:
  6053. EXIT(None, None, None)
  6054. MGR = EXIT = VALUE = None
  6055. """
  6056. # manager The with statement manager object
  6057. # target ExprNode the target lhs of the __enter__() call
  6058. # body StatNode
  6059. # enter_call ExprNode the call to the __enter__() method
  6060. # exit_var String the cname of the __exit__() method reference
  6061. child_attrs = ["manager", "enter_call", "target", "body"]
  6062. enter_call = None
  6063. target_temp = None
  6064. def analyse_declarations(self, env):
  6065. self.manager.analyse_declarations(env)
  6066. self.enter_call.analyse_declarations(env)
  6067. self.body.analyse_declarations(env)
  6068. def analyse_expressions(self, env):
  6069. self.manager = self.manager.analyse_types(env)
  6070. self.enter_call = self.enter_call.analyse_types(env)
  6071. if self.target:
  6072. # set up target_temp before descending into body (which uses it)
  6073. from .ExprNodes import TempNode
  6074. self.target_temp = TempNode(self.enter_call.pos, self.enter_call.type)
  6075. self.body = self.body.analyse_expressions(env)
  6076. return self
  6077. def generate_function_definitions(self, env, code):
  6078. self.manager.generate_function_definitions(env, code)
  6079. self.enter_call.generate_function_definitions(env, code)
  6080. self.body.generate_function_definitions(env, code)
  6081. def generate_execution_code(self, code):
  6082. code.mark_pos(self.pos)
  6083. code.putln("/*with:*/ {")
  6084. self.manager.generate_evaluation_code(code)
  6085. self.exit_var = code.funcstate.allocate_temp(py_object_type, manage_ref=False)
  6086. code.globalstate.use_utility_code(
  6087. UtilityCode.load_cached("PyObjectLookupSpecial", "ObjectHandling.c"))
  6088. code.putln("%s = __Pyx_PyObject_LookupSpecial(%s, %s); %s" % (
  6089. self.exit_var,
  6090. self.manager.py_result(),
  6091. code.intern_identifier(EncodedString('__aexit__' if self.is_async else '__exit__')),
  6092. code.error_goto_if_null(self.exit_var, self.pos),
  6093. ))
  6094. code.put_gotref(self.exit_var)
  6095. # need to free exit_var in the face of exceptions during setup
  6096. old_error_label = code.new_error_label()
  6097. intermediate_error_label = code.error_label
  6098. self.enter_call.generate_evaluation_code(code)
  6099. if self.target:
  6100. # The temp result will be cleaned up by the WithTargetAssignmentStatNode
  6101. # after assigning its result to the target of the 'with' statement.
  6102. self.target_temp.allocate(code)
  6103. self.enter_call.make_owned_reference(code)
  6104. code.putln("%s = %s;" % (self.target_temp.result(), self.enter_call.result()))
  6105. self.enter_call.generate_post_assignment_code(code)
  6106. else:
  6107. self.enter_call.generate_disposal_code(code)
  6108. self.enter_call.free_temps(code)
  6109. self.manager.generate_disposal_code(code)
  6110. self.manager.free_temps(code)
  6111. code.error_label = old_error_label
  6112. self.body.generate_execution_code(code)
  6113. if code.label_used(intermediate_error_label):
  6114. step_over_label = code.new_label()
  6115. code.put_goto(step_over_label)
  6116. code.put_label(intermediate_error_label)
  6117. code.put_decref_clear(self.exit_var, py_object_type)
  6118. code.put_goto(old_error_label)
  6119. code.put_label(step_over_label)
  6120. code.funcstate.release_temp(self.exit_var)
  6121. code.putln('}')
  6122. class WithTargetAssignmentStatNode(AssignmentNode):
  6123. # The target assignment of the 'with' statement value (return
  6124. # value of the __enter__() call).
  6125. #
  6126. # This is a special cased assignment that properly cleans up the RHS.
  6127. #
  6128. # lhs ExprNode the assignment target
  6129. # rhs ExprNode a (coerced) TempNode for the rhs (from WithStatNode)
  6130. # with_node WithStatNode the surrounding with-statement
  6131. child_attrs = ["rhs", "lhs"]
  6132. with_node = None
  6133. rhs = None
  6134. def analyse_declarations(self, env):
  6135. self.lhs.analyse_target_declaration(env)
  6136. def analyse_expressions(self, env):
  6137. self.lhs = self.lhs.analyse_target_types(env)
  6138. self.lhs.gil_assignment_check(env)
  6139. self.rhs = self.with_node.target_temp.coerce_to(self.lhs.type, env)
  6140. return self
  6141. def generate_execution_code(self, code):
  6142. self.rhs.generate_evaluation_code(code)
  6143. self.lhs.generate_assignment_code(self.rhs, code)
  6144. self.with_node.target_temp.release(code)
  6145. def annotate(self, code):
  6146. self.lhs.annotate(code)
  6147. self.rhs.annotate(code)
  6148. class TryExceptStatNode(StatNode):
  6149. # try .. except statement
  6150. #
  6151. # body StatNode
  6152. # except_clauses [ExceptClauseNode]
  6153. # else_clause StatNode or None
  6154. child_attrs = ["body", "except_clauses", "else_clause"]
  6155. in_generator = False
  6156. def analyse_declarations(self, env):
  6157. self.body.analyse_declarations(env)
  6158. for except_clause in self.except_clauses:
  6159. except_clause.analyse_declarations(env)
  6160. if self.else_clause:
  6161. self.else_clause.analyse_declarations(env)
  6162. def analyse_expressions(self, env):
  6163. self.body = self.body.analyse_expressions(env)
  6164. default_clause_seen = 0
  6165. for i, except_clause in enumerate(self.except_clauses):
  6166. except_clause = self.except_clauses[i] = except_clause.analyse_expressions(env)
  6167. if default_clause_seen:
  6168. error(except_clause.pos, "default 'except:' must be last")
  6169. if not except_clause.pattern:
  6170. default_clause_seen = 1
  6171. self.has_default_clause = default_clause_seen
  6172. if self.else_clause:
  6173. self.else_clause = self.else_clause.analyse_expressions(env)
  6174. return self
  6175. nogil_check = Node.gil_error
  6176. gil_message = "Try-except statement"
  6177. def generate_execution_code(self, code):
  6178. old_return_label = code.return_label
  6179. old_break_label = code.break_label
  6180. old_continue_label = code.continue_label
  6181. old_error_label = code.new_error_label()
  6182. our_error_label = code.error_label
  6183. except_end_label = code.new_label('exception_handled')
  6184. except_error_label = code.new_label('except_error')
  6185. except_return_label = code.new_label('except_return')
  6186. try_return_label = code.new_label('try_return')
  6187. try_break_label = code.new_label('try_break') if old_break_label else None
  6188. try_continue_label = code.new_label('try_continue') if old_continue_label else None
  6189. try_end_label = code.new_label('try_end')
  6190. exc_save_vars = [code.funcstate.allocate_temp(py_object_type, False)
  6191. for _ in range(3)]
  6192. code.mark_pos(self.pos)
  6193. code.putln("{")
  6194. save_exc = code.insertion_point()
  6195. code.putln(
  6196. "/*try:*/ {")
  6197. code.return_label = try_return_label
  6198. code.break_label = try_break_label
  6199. code.continue_label = try_continue_label
  6200. self.body.generate_execution_code(code)
  6201. code.mark_pos(self.pos, trace=False)
  6202. code.putln(
  6203. "}")
  6204. temps_to_clean_up = code.funcstate.all_free_managed_temps()
  6205. can_raise = code.label_used(our_error_label)
  6206. if can_raise:
  6207. # inject code before the try block to save away the exception state
  6208. code.globalstate.use_utility_code(reset_exception_utility_code)
  6209. if not self.in_generator:
  6210. save_exc.putln("__Pyx_PyThreadState_declare")
  6211. save_exc.putln("__Pyx_PyThreadState_assign")
  6212. save_exc.putln("__Pyx_ExceptionSave(%s);" % (
  6213. ', '.join(['&%s' % var for var in exc_save_vars])))
  6214. for var in exc_save_vars:
  6215. save_exc.put_xgotref(var)
  6216. def restore_saved_exception():
  6217. for name in exc_save_vars:
  6218. code.put_xgiveref(name)
  6219. code.putln("__Pyx_ExceptionReset(%s);" %
  6220. ', '.join(exc_save_vars))
  6221. else:
  6222. # try block cannot raise exceptions, but we had to allocate the temps above,
  6223. # so just keep the C compiler from complaining about them being unused
  6224. mark_vars_used = ["(void)%s;" % var for var in exc_save_vars]
  6225. save_exc.putln("%s /* mark used */" % ' '.join(mark_vars_used))
  6226. def restore_saved_exception():
  6227. pass
  6228. code.error_label = except_error_label
  6229. code.return_label = except_return_label
  6230. normal_case_terminates = self.body.is_terminator
  6231. if self.else_clause:
  6232. code.mark_pos(self.else_clause.pos)
  6233. code.putln(
  6234. "/*else:*/ {")
  6235. self.else_clause.generate_execution_code(code)
  6236. code.putln(
  6237. "}")
  6238. if not normal_case_terminates:
  6239. normal_case_terminates = self.else_clause.is_terminator
  6240. if can_raise:
  6241. if not normal_case_terminates:
  6242. for var in exc_save_vars:
  6243. code.put_xdecref_clear(var, py_object_type)
  6244. code.put_goto(try_end_label)
  6245. code.put_label(our_error_label)
  6246. for temp_name, temp_type in temps_to_clean_up:
  6247. code.put_xdecref_clear(temp_name, temp_type)
  6248. outer_except = code.funcstate.current_except
  6249. # Currently points to self, but the ExceptClauseNode would also be ok. Change if needed.
  6250. code.funcstate.current_except = self
  6251. for except_clause in self.except_clauses:
  6252. except_clause.generate_handling_code(code, except_end_label)
  6253. code.funcstate.current_except = outer_except
  6254. if not self.has_default_clause:
  6255. code.put_goto(except_error_label)
  6256. for exit_label, old_label in [(except_error_label, old_error_label),
  6257. (try_break_label, old_break_label),
  6258. (try_continue_label, old_continue_label),
  6259. (try_return_label, old_return_label),
  6260. (except_return_label, old_return_label)]:
  6261. if code.label_used(exit_label):
  6262. if not normal_case_terminates and not code.label_used(try_end_label):
  6263. code.put_goto(try_end_label)
  6264. code.put_label(exit_label)
  6265. code.mark_pos(self.pos, trace=False)
  6266. if can_raise:
  6267. restore_saved_exception()
  6268. code.put_goto(old_label)
  6269. if code.label_used(except_end_label):
  6270. if not normal_case_terminates and not code.label_used(try_end_label):
  6271. code.put_goto(try_end_label)
  6272. code.put_label(except_end_label)
  6273. if can_raise:
  6274. restore_saved_exception()
  6275. if code.label_used(try_end_label):
  6276. code.put_label(try_end_label)
  6277. code.putln("}")
  6278. for cname in exc_save_vars:
  6279. code.funcstate.release_temp(cname)
  6280. code.return_label = old_return_label
  6281. code.break_label = old_break_label
  6282. code.continue_label = old_continue_label
  6283. code.error_label = old_error_label
  6284. def generate_function_definitions(self, env, code):
  6285. self.body.generate_function_definitions(env, code)
  6286. for except_clause in self.except_clauses:
  6287. except_clause.generate_function_definitions(env, code)
  6288. if self.else_clause is not None:
  6289. self.else_clause.generate_function_definitions(env, code)
  6290. def annotate(self, code):
  6291. self.body.annotate(code)
  6292. for except_node in self.except_clauses:
  6293. except_node.annotate(code)
  6294. if self.else_clause:
  6295. self.else_clause.annotate(code)
  6296. class ExceptClauseNode(Node):
  6297. # Part of try ... except statement.
  6298. #
  6299. # pattern [ExprNode]
  6300. # target ExprNode or None
  6301. # body StatNode
  6302. # excinfo_target TupleNode(3*ResultRefNode) or None optional target for exception info (not owned here!)
  6303. # match_flag string result of exception match
  6304. # exc_value ExcValueNode used internally
  6305. # function_name string qualified name of enclosing function
  6306. # exc_vars (string * 3) local exception variables
  6307. # is_except_as bool Py3-style "except ... as xyz"
  6308. # excinfo_target is never set by the parser, but can be set by a transform
  6309. # in order to extract more extensive information about the exception as a
  6310. # sys.exc_info()-style tuple into a target variable
  6311. child_attrs = ["pattern", "target", "body", "exc_value"]
  6312. exc_value = None
  6313. excinfo_target = None
  6314. is_except_as = False
  6315. def analyse_declarations(self, env):
  6316. if self.target:
  6317. self.target.analyse_target_declaration(env)
  6318. self.body.analyse_declarations(env)
  6319. def analyse_expressions(self, env):
  6320. self.function_name = env.qualified_name
  6321. if self.pattern:
  6322. # normalise/unpack self.pattern into a list
  6323. for i, pattern in enumerate(self.pattern):
  6324. pattern = pattern.analyse_expressions(env)
  6325. self.pattern[i] = pattern.coerce_to_pyobject(env)
  6326. if self.target:
  6327. from . import ExprNodes
  6328. self.exc_value = ExprNodes.ExcValueNode(self.pos)
  6329. self.target = self.target.analyse_target_expression(env, self.exc_value)
  6330. self.body = self.body.analyse_expressions(env)
  6331. return self
  6332. def generate_handling_code(self, code, end_label):
  6333. code.mark_pos(self.pos)
  6334. if self.pattern:
  6335. has_non_literals = not all(
  6336. pattern.is_literal or pattern.is_simple() and not pattern.is_temp
  6337. for pattern in self.pattern)
  6338. if has_non_literals:
  6339. # For non-trivial exception check expressions, hide the live exception from C-API calls.
  6340. exc_vars = [code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  6341. for _ in range(3)]
  6342. code.globalstate.use_utility_code(UtilityCode.load_cached("PyErrFetchRestore", "Exceptions.c"))
  6343. code.putln("__Pyx_ErrFetch(&%s, &%s, &%s);" % tuple(exc_vars))
  6344. code.globalstate.use_utility_code(UtilityCode.load_cached("FastTypeChecks", "ModuleSetupCode.c"))
  6345. exc_test_func = "__Pyx_PyErr_GivenExceptionMatches(%s, %%s)" % exc_vars[0]
  6346. else:
  6347. exc_vars = ()
  6348. code.globalstate.use_utility_code(UtilityCode.load_cached("PyErrExceptionMatches", "Exceptions.c"))
  6349. exc_test_func = "__Pyx_PyErr_ExceptionMatches(%s)"
  6350. exc_tests = []
  6351. for pattern in self.pattern:
  6352. pattern.generate_evaluation_code(code)
  6353. exc_tests.append(exc_test_func % pattern.py_result())
  6354. match_flag = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
  6355. code.putln("%s = %s;" % (match_flag, ' || '.join(exc_tests)))
  6356. for pattern in self.pattern:
  6357. pattern.generate_disposal_code(code)
  6358. pattern.free_temps(code)
  6359. if has_non_literals:
  6360. code.putln("__Pyx_ErrRestore(%s, %s, %s);" % tuple(exc_vars))
  6361. code.putln(' '.join(["%s = 0;" % var for var in exc_vars]))
  6362. for temp in exc_vars:
  6363. code.funcstate.release_temp(temp)
  6364. code.putln(
  6365. "if (%s) {" %
  6366. match_flag)
  6367. code.funcstate.release_temp(match_flag)
  6368. else:
  6369. code.putln("/*except:*/ {")
  6370. if (not getattr(self.body, 'stats', True)
  6371. and self.excinfo_target is None
  6372. and self.target is None):
  6373. # most simple case: no exception variable, empty body (pass)
  6374. # => reset the exception state, done
  6375. code.globalstate.use_utility_code(UtilityCode.load_cached("PyErrFetchRestore", "Exceptions.c"))
  6376. code.putln("__Pyx_ErrRestore(0,0,0);")
  6377. code.put_goto(end_label)
  6378. code.putln("}")
  6379. return
  6380. exc_vars = [code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  6381. for _ in range(3)]
  6382. code.put_add_traceback(self.function_name)
  6383. # We always have to fetch the exception value even if
  6384. # there is no target, because this also normalises the
  6385. # exception and stores it in the thread state.
  6386. code.globalstate.use_utility_code(get_exception_utility_code)
  6387. exc_args = "&%s, &%s, &%s" % tuple(exc_vars)
  6388. code.putln("if (__Pyx_GetException(%s) < 0) %s" % (
  6389. exc_args, code.error_goto(self.pos)))
  6390. for var in exc_vars:
  6391. code.put_gotref(var)
  6392. if self.target:
  6393. self.exc_value.set_var(exc_vars[1])
  6394. self.exc_value.generate_evaluation_code(code)
  6395. self.target.generate_assignment_code(self.exc_value, code)
  6396. if self.excinfo_target is not None:
  6397. for tempvar, node in zip(exc_vars, self.excinfo_target.args):
  6398. node.set_var(tempvar)
  6399. old_break_label, old_continue_label = code.break_label, code.continue_label
  6400. code.break_label = code.new_label('except_break')
  6401. code.continue_label = code.new_label('except_continue')
  6402. old_exc_vars = code.funcstate.exc_vars
  6403. code.funcstate.exc_vars = exc_vars
  6404. self.body.generate_execution_code(code)
  6405. code.funcstate.exc_vars = old_exc_vars
  6406. if not self.body.is_terminator:
  6407. for var in exc_vars:
  6408. code.put_decref_clear(var, py_object_type)
  6409. code.put_goto(end_label)
  6410. for new_label, old_label in [(code.break_label, old_break_label),
  6411. (code.continue_label, old_continue_label)]:
  6412. if code.label_used(new_label):
  6413. code.put_label(new_label)
  6414. for var in exc_vars:
  6415. code.put_decref_clear(var, py_object_type)
  6416. code.put_goto(old_label)
  6417. code.break_label = old_break_label
  6418. code.continue_label = old_continue_label
  6419. for temp in exc_vars:
  6420. code.funcstate.release_temp(temp)
  6421. code.putln(
  6422. "}")
  6423. def generate_function_definitions(self, env, code):
  6424. if self.target is not None:
  6425. self.target.generate_function_definitions(env, code)
  6426. self.body.generate_function_definitions(env, code)
  6427. def annotate(self, code):
  6428. if self.pattern:
  6429. for pattern in self.pattern:
  6430. pattern.annotate(code)
  6431. if self.target:
  6432. self.target.annotate(code)
  6433. self.body.annotate(code)
  6434. class TryFinallyStatNode(StatNode):
  6435. # try ... finally statement
  6436. #
  6437. # body StatNode
  6438. # finally_clause StatNode
  6439. # finally_except_clause deep-copy of finally_clause for exception case
  6440. # in_generator inside of generator => must store away current exception also in return case
  6441. #
  6442. # Each of the continue, break, return and error gotos runs
  6443. # into its own deep-copy of the finally block code.
  6444. # In addition, if we're doing an error, we save the
  6445. # exception on entry to the finally block and restore
  6446. # it on exit.
  6447. child_attrs = ["body", "finally_clause", "finally_except_clause"]
  6448. preserve_exception = 1
  6449. # handle exception case, in addition to return/break/continue
  6450. handle_error_case = True
  6451. func_return_type = None
  6452. finally_except_clause = None
  6453. is_try_finally_in_nogil = False
  6454. in_generator = False
  6455. @staticmethod
  6456. def create_analysed(pos, env, body, finally_clause):
  6457. node = TryFinallyStatNode(pos, body=body, finally_clause=finally_clause)
  6458. return node
  6459. def analyse_declarations(self, env):
  6460. self.body.analyse_declarations(env)
  6461. self.finally_except_clause = copy.deepcopy(self.finally_clause)
  6462. self.finally_except_clause.analyse_declarations(env)
  6463. self.finally_clause.analyse_declarations(env)
  6464. def analyse_expressions(self, env):
  6465. self.body = self.body.analyse_expressions(env)
  6466. self.finally_clause = self.finally_clause.analyse_expressions(env)
  6467. self.finally_except_clause = self.finally_except_clause.analyse_expressions(env)
  6468. if env.return_type and not env.return_type.is_void:
  6469. self.func_return_type = env.return_type
  6470. return self
  6471. nogil_check = Node.gil_error
  6472. gil_message = "Try-finally statement"
  6473. def generate_execution_code(self, code):
  6474. code.mark_pos(self.pos)
  6475. old_error_label = code.error_label
  6476. old_labels = code.all_new_labels()
  6477. new_labels = code.get_all_labels()
  6478. new_error_label = code.error_label
  6479. if not self.handle_error_case:
  6480. code.error_label = old_error_label
  6481. catch_label = code.new_label()
  6482. code.putln("/*try:*/ {")
  6483. was_in_try_finally = code.funcstate.in_try_finally
  6484. code.funcstate.in_try_finally = 1
  6485. self.body.generate_execution_code(code)
  6486. code.funcstate.in_try_finally = was_in_try_finally
  6487. code.putln("}")
  6488. code.set_all_labels(old_labels)
  6489. temps_to_clean_up = code.funcstate.all_free_managed_temps()
  6490. code.mark_pos(self.finally_clause.pos)
  6491. code.putln("/*finally:*/ {")
  6492. def fresh_finally_clause(_next=[self.finally_clause]):
  6493. # generate the original subtree once and always keep a fresh copy
  6494. node = _next[0]
  6495. node_copy = copy.deepcopy(node)
  6496. if node is self.finally_clause:
  6497. _next[0] = node_copy
  6498. else:
  6499. node = node_copy
  6500. return node
  6501. preserve_error = self.preserve_exception and code.label_used(new_error_label)
  6502. needs_success_cleanup = not self.finally_clause.is_terminator
  6503. if not self.body.is_terminator:
  6504. code.putln('/*normal exit:*/{')
  6505. fresh_finally_clause().generate_execution_code(code)
  6506. if not self.finally_clause.is_terminator:
  6507. code.put_goto(catch_label)
  6508. code.putln('}')
  6509. if preserve_error:
  6510. code.put_label(new_error_label)
  6511. code.putln('/*exception exit:*/{')
  6512. if not self.in_generator:
  6513. code.putln("__Pyx_PyThreadState_declare")
  6514. if self.is_try_finally_in_nogil:
  6515. code.declare_gilstate()
  6516. if needs_success_cleanup:
  6517. exc_lineno_cnames = tuple([
  6518. code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
  6519. for _ in range(2)])
  6520. exc_filename_cname = code.funcstate.allocate_temp(
  6521. PyrexTypes.CPtrType(PyrexTypes.c_const_type(PyrexTypes.c_char_type)),
  6522. manage_ref=False)
  6523. else:
  6524. exc_lineno_cnames = exc_filename_cname = None
  6525. exc_vars = tuple([
  6526. code.funcstate.allocate_temp(py_object_type, manage_ref=False)
  6527. for _ in range(6)])
  6528. self.put_error_catcher(
  6529. code, temps_to_clean_up, exc_vars, exc_lineno_cnames, exc_filename_cname)
  6530. finally_old_labels = code.all_new_labels()
  6531. code.putln('{')
  6532. old_exc_vars = code.funcstate.exc_vars
  6533. code.funcstate.exc_vars = exc_vars[:3]
  6534. self.finally_except_clause.generate_execution_code(code)
  6535. code.funcstate.exc_vars = old_exc_vars
  6536. code.putln('}')
  6537. if needs_success_cleanup:
  6538. self.put_error_uncatcher(code, exc_vars, exc_lineno_cnames, exc_filename_cname)
  6539. if exc_lineno_cnames:
  6540. for cname in exc_lineno_cnames:
  6541. code.funcstate.release_temp(cname)
  6542. if exc_filename_cname:
  6543. code.funcstate.release_temp(exc_filename_cname)
  6544. code.put_goto(old_error_label)
  6545. for new_label, old_label in zip(code.get_all_labels(), finally_old_labels):
  6546. if not code.label_used(new_label):
  6547. continue
  6548. code.put_label(new_label)
  6549. self.put_error_cleaner(code, exc_vars)
  6550. code.put_goto(old_label)
  6551. for cname in exc_vars:
  6552. code.funcstate.release_temp(cname)
  6553. code.putln('}')
  6554. code.set_all_labels(old_labels)
  6555. return_label = code.return_label
  6556. exc_vars = ()
  6557. for i, (new_label, old_label) in enumerate(zip(new_labels, old_labels)):
  6558. if not code.label_used(new_label):
  6559. continue
  6560. if new_label == new_error_label and preserve_error:
  6561. continue # handled above
  6562. code.putln('%s: {' % new_label)
  6563. ret_temp = None
  6564. if old_label == return_label:
  6565. # return actually raises an (uncatchable) exception in generators that we must preserve
  6566. if self.in_generator:
  6567. exc_vars = tuple([
  6568. code.funcstate.allocate_temp(py_object_type, manage_ref=False)
  6569. for _ in range(6)])
  6570. self.put_error_catcher(code, [], exc_vars)
  6571. if not self.finally_clause.is_terminator:
  6572. # store away return value for later reuse
  6573. if (self.func_return_type and
  6574. not self.is_try_finally_in_nogil and
  6575. not isinstance(self.finally_clause, GILExitNode)):
  6576. ret_temp = code.funcstate.allocate_temp(
  6577. self.func_return_type, manage_ref=False)
  6578. code.putln("%s = %s;" % (ret_temp, Naming.retval_cname))
  6579. if self.func_return_type.is_pyobject:
  6580. code.putln("%s = 0;" % Naming.retval_cname)
  6581. fresh_finally_clause().generate_execution_code(code)
  6582. if old_label == return_label:
  6583. if ret_temp:
  6584. code.putln("%s = %s;" % (Naming.retval_cname, ret_temp))
  6585. if self.func_return_type.is_pyobject:
  6586. code.putln("%s = 0;" % ret_temp)
  6587. code.funcstate.release_temp(ret_temp)
  6588. ret_temp = None
  6589. if self.in_generator:
  6590. self.put_error_uncatcher(code, exc_vars)
  6591. if not self.finally_clause.is_terminator:
  6592. code.put_goto(old_label)
  6593. code.putln('}')
  6594. # End finally
  6595. code.put_label(catch_label)
  6596. code.putln(
  6597. "}")
  6598. def generate_function_definitions(self, env, code):
  6599. self.body.generate_function_definitions(env, code)
  6600. self.finally_clause.generate_function_definitions(env, code)
  6601. def put_error_catcher(self, code, temps_to_clean_up, exc_vars,
  6602. exc_lineno_cnames=None, exc_filename_cname=None):
  6603. code.globalstate.use_utility_code(restore_exception_utility_code)
  6604. code.globalstate.use_utility_code(get_exception_utility_code)
  6605. code.globalstate.use_utility_code(swap_exception_utility_code)
  6606. if self.is_try_finally_in_nogil:
  6607. code.put_ensure_gil(declare_gilstate=False)
  6608. code.putln("__Pyx_PyThreadState_assign")
  6609. code.putln(' '.join(["%s = 0;" % var for var in exc_vars]))
  6610. for temp_name, type in temps_to_clean_up:
  6611. code.put_xdecref_clear(temp_name, type)
  6612. # not using preprocessor here to avoid warnings about
  6613. # unused utility functions and/or temps
  6614. code.putln("if (PY_MAJOR_VERSION >= 3)"
  6615. " __Pyx_ExceptionSwap(&%s, &%s, &%s);" % exc_vars[3:])
  6616. code.putln("if ((PY_MAJOR_VERSION < 3) ||"
  6617. # if __Pyx_GetException() fails in Py3,
  6618. # store the newly raised exception instead
  6619. " unlikely(__Pyx_GetException(&%s, &%s, &%s) < 0)) "
  6620. "__Pyx_ErrFetch(&%s, &%s, &%s);" % (exc_vars[:3] * 2))
  6621. for var in exc_vars:
  6622. code.put_xgotref(var)
  6623. if exc_lineno_cnames:
  6624. code.putln("%s = %s; %s = %s; %s = %s;" % (
  6625. exc_lineno_cnames[0], Naming.lineno_cname,
  6626. exc_lineno_cnames[1], Naming.clineno_cname,
  6627. exc_filename_cname, Naming.filename_cname))
  6628. if self.is_try_finally_in_nogil:
  6629. code.put_release_ensured_gil()
  6630. def put_error_uncatcher(self, code, exc_vars, exc_lineno_cnames=None, exc_filename_cname=None):
  6631. code.globalstate.use_utility_code(restore_exception_utility_code)
  6632. code.globalstate.use_utility_code(reset_exception_utility_code)
  6633. if self.is_try_finally_in_nogil:
  6634. code.put_ensure_gil(declare_gilstate=False)
  6635. # not using preprocessor here to avoid warnings about
  6636. # unused utility functions and/or temps
  6637. code.putln("if (PY_MAJOR_VERSION >= 3) {")
  6638. for var in exc_vars[3:]:
  6639. code.put_xgiveref(var)
  6640. code.putln("__Pyx_ExceptionReset(%s, %s, %s);" % exc_vars[3:])
  6641. code.putln("}")
  6642. for var in exc_vars[:3]:
  6643. code.put_xgiveref(var)
  6644. code.putln("__Pyx_ErrRestore(%s, %s, %s);" % exc_vars[:3])
  6645. if self.is_try_finally_in_nogil:
  6646. code.put_release_ensured_gil()
  6647. code.putln(' '.join(["%s = 0;" % var for var in exc_vars]))
  6648. if exc_lineno_cnames:
  6649. code.putln("%s = %s; %s = %s; %s = %s;" % (
  6650. Naming.lineno_cname, exc_lineno_cnames[0],
  6651. Naming.clineno_cname, exc_lineno_cnames[1],
  6652. Naming.filename_cname, exc_filename_cname))
  6653. def put_error_cleaner(self, code, exc_vars):
  6654. code.globalstate.use_utility_code(reset_exception_utility_code)
  6655. if self.is_try_finally_in_nogil:
  6656. code.put_ensure_gil(declare_gilstate=False)
  6657. # not using preprocessor here to avoid warnings about
  6658. # unused utility functions and/or temps
  6659. code.putln("if (PY_MAJOR_VERSION >= 3) {")
  6660. for var in exc_vars[3:]:
  6661. code.put_xgiveref(var)
  6662. code.putln("__Pyx_ExceptionReset(%s, %s, %s);" % exc_vars[3:])
  6663. code.putln("}")
  6664. for var in exc_vars[:3]:
  6665. code.put_xdecref_clear(var, py_object_type)
  6666. if self.is_try_finally_in_nogil:
  6667. code.put_release_ensured_gil()
  6668. code.putln(' '.join(["%s = 0;"]*3) % exc_vars[3:])
  6669. def annotate(self, code):
  6670. self.body.annotate(code)
  6671. self.finally_clause.annotate(code)
  6672. class NogilTryFinallyStatNode(TryFinallyStatNode):
  6673. """
  6674. A try/finally statement that may be used in nogil code sections.
  6675. """
  6676. preserve_exception = False
  6677. nogil_check = None
  6678. class GILStatNode(NogilTryFinallyStatNode):
  6679. # 'with gil' or 'with nogil' statement
  6680. #
  6681. # state string 'gil' or 'nogil'
  6682. state_temp = None
  6683. def __init__(self, pos, state, body):
  6684. self.state = state
  6685. self.create_state_temp_if_needed(pos, state, body)
  6686. TryFinallyStatNode.__init__(
  6687. self, pos,
  6688. body=body,
  6689. finally_clause=GILExitNode(
  6690. pos, state=state, state_temp=self.state_temp))
  6691. def create_state_temp_if_needed(self, pos, state, body):
  6692. from .ParseTreeTransforms import YieldNodeCollector
  6693. collector = YieldNodeCollector()
  6694. collector.visitchildren(body)
  6695. if not collector.yields:
  6696. return
  6697. if state == 'gil':
  6698. temp_type = PyrexTypes.c_gilstate_type
  6699. else:
  6700. temp_type = PyrexTypes.c_threadstate_ptr_type
  6701. from . import ExprNodes
  6702. self.state_temp = ExprNodes.TempNode(pos, temp_type)
  6703. def analyse_declarations(self, env):
  6704. env._in_with_gil_block = (self.state == 'gil')
  6705. if self.state == 'gil':
  6706. env.has_with_gil_block = True
  6707. return super(GILStatNode, self).analyse_declarations(env)
  6708. def analyse_expressions(self, env):
  6709. env.use_utility_code(
  6710. UtilityCode.load_cached("ForceInitThreads", "ModuleSetupCode.c"))
  6711. was_nogil = env.nogil
  6712. env.nogil = self.state == 'nogil'
  6713. node = TryFinallyStatNode.analyse_expressions(self, env)
  6714. env.nogil = was_nogil
  6715. return node
  6716. def generate_execution_code(self, code):
  6717. code.mark_pos(self.pos)
  6718. code.begin_block()
  6719. if self.state_temp:
  6720. self.state_temp.allocate(code)
  6721. variable = self.state_temp.result()
  6722. else:
  6723. variable = None
  6724. old_gil_config = code.funcstate.gil_owned
  6725. if self.state == 'gil':
  6726. code.put_ensure_gil(variable=variable)
  6727. code.funcstate.gil_owned = True
  6728. else:
  6729. code.put_release_gil(variable=variable)
  6730. code.funcstate.gil_owned = False
  6731. TryFinallyStatNode.generate_execution_code(self, code)
  6732. if self.state_temp:
  6733. self.state_temp.release(code)
  6734. code.funcstate.gil_owned = old_gil_config
  6735. code.end_block()
  6736. class GILExitNode(StatNode):
  6737. """
  6738. Used as the 'finally' block in a GILStatNode
  6739. state string 'gil' or 'nogil'
  6740. """
  6741. child_attrs = []
  6742. state_temp = None
  6743. def analyse_expressions(self, env):
  6744. return self
  6745. def generate_execution_code(self, code):
  6746. if self.state_temp:
  6747. variable = self.state_temp.result()
  6748. else:
  6749. variable = None
  6750. if self.state == 'gil':
  6751. code.put_release_ensured_gil(variable)
  6752. else:
  6753. code.put_acquire_gil(variable)
  6754. class EnsureGILNode(GILExitNode):
  6755. """
  6756. Ensure the GIL in nogil functions for cleanup before returning.
  6757. """
  6758. def generate_execution_code(self, code):
  6759. code.put_ensure_gil(declare_gilstate=False)
  6760. def cython_view_utility_code():
  6761. from . import MemoryView
  6762. return MemoryView.view_utility_code
  6763. utility_code_for_cimports = {
  6764. # utility code (or inlining c) in a pxd (or pyx) file.
  6765. # TODO: Consider a generic user-level mechanism for importing
  6766. 'cpython.array' : lambda : UtilityCode.load_cached("ArrayAPI", "arrayarray.h"),
  6767. 'cpython.array.array' : lambda : UtilityCode.load_cached("ArrayAPI", "arrayarray.h"),
  6768. 'cython.view' : cython_view_utility_code,
  6769. }
  6770. utility_code_for_imports = {
  6771. # utility code used when special modules are imported.
  6772. # TODO: Consider a generic user-level mechanism for importing
  6773. 'asyncio': ("__Pyx_patch_asyncio", "PatchAsyncIO", "Coroutine.c"),
  6774. 'inspect': ("__Pyx_patch_inspect", "PatchInspect", "Coroutine.c"),
  6775. }
  6776. class CImportStatNode(StatNode):
  6777. # cimport statement
  6778. #
  6779. # module_name string Qualified name of module being imported
  6780. # as_name string or None Name specified in "as" clause, if any
  6781. # is_absolute bool True for absolute imports, False otherwise
  6782. child_attrs = []
  6783. is_absolute = False
  6784. def analyse_declarations(self, env):
  6785. if not env.is_module_scope:
  6786. error(self.pos, "cimport only allowed at module level")
  6787. return
  6788. module_scope = env.find_module(
  6789. self.module_name, self.pos, relative_level=0 if self.is_absolute else -1)
  6790. if "." in self.module_name:
  6791. names = [EncodedString(name) for name in self.module_name.split(".")]
  6792. top_name = names[0]
  6793. top_module_scope = env.context.find_submodule(top_name)
  6794. module_scope = top_module_scope
  6795. for name in names[1:]:
  6796. submodule_scope = module_scope.find_submodule(name)
  6797. module_scope.declare_module(name, submodule_scope, self.pos)
  6798. module_scope = submodule_scope
  6799. if self.as_name:
  6800. env.declare_module(self.as_name, module_scope, self.pos)
  6801. else:
  6802. env.add_imported_module(module_scope)
  6803. env.declare_module(top_name, top_module_scope, self.pos)
  6804. else:
  6805. name = self.as_name or self.module_name
  6806. env.declare_module(name, module_scope, self.pos)
  6807. if self.module_name in utility_code_for_cimports:
  6808. env.use_utility_code(utility_code_for_cimports[self.module_name]())
  6809. def analyse_expressions(self, env):
  6810. return self
  6811. def generate_execution_code(self, code):
  6812. pass
  6813. class FromCImportStatNode(StatNode):
  6814. # from ... cimport statement
  6815. #
  6816. # module_name string Qualified name of module
  6817. # relative_level int or None Relative import: number of dots before module_name
  6818. # imported_names [(pos, name, as_name, kind)] Names to be imported
  6819. child_attrs = []
  6820. module_name = None
  6821. relative_level = None
  6822. imported_names = None
  6823. def analyse_declarations(self, env):
  6824. if not env.is_module_scope:
  6825. error(self.pos, "cimport only allowed at module level")
  6826. return
  6827. if self.relative_level and self.relative_level > env.qualified_name.count('.'):
  6828. error(self.pos, "relative cimport beyond main package is not allowed")
  6829. return
  6830. module_scope = env.find_module(self.module_name, self.pos, relative_level=self.relative_level)
  6831. module_name = module_scope.qualified_name
  6832. env.add_imported_module(module_scope)
  6833. for pos, name, as_name, kind in self.imported_names:
  6834. if name == "*":
  6835. for local_name, entry in list(module_scope.entries.items()):
  6836. env.add_imported_entry(local_name, entry, pos)
  6837. else:
  6838. entry = module_scope.lookup(name)
  6839. if entry:
  6840. if kind and not self.declaration_matches(entry, kind):
  6841. entry.redeclared(pos)
  6842. entry.used = 1
  6843. else:
  6844. if kind == 'struct' or kind == 'union':
  6845. entry = module_scope.declare_struct_or_union(
  6846. name, kind=kind, scope=None, typedef_flag=0, pos=pos)
  6847. elif kind == 'class':
  6848. entry = module_scope.declare_c_class(name, pos=pos, module_name=module_name)
  6849. else:
  6850. submodule_scope = env.context.find_module(
  6851. name, relative_to=module_scope, pos=self.pos, absolute_fallback=False)
  6852. if submodule_scope.parent_module is module_scope:
  6853. env.declare_module(as_name or name, submodule_scope, self.pos)
  6854. else:
  6855. error(pos, "Name '%s' not declared in module '%s'" % (name, module_name))
  6856. if entry:
  6857. local_name = as_name or name
  6858. env.add_imported_entry(local_name, entry, pos)
  6859. if module_name.startswith('cpython') or module_name.startswith('cython'): # enough for now
  6860. if module_name in utility_code_for_cimports:
  6861. env.use_utility_code(utility_code_for_cimports[module_name]())
  6862. for _, name, _, _ in self.imported_names:
  6863. fqname = '%s.%s' % (module_name, name)
  6864. if fqname in utility_code_for_cimports:
  6865. env.use_utility_code(utility_code_for_cimports[fqname]())
  6866. def declaration_matches(self, entry, kind):
  6867. if not entry.is_type:
  6868. return 0
  6869. type = entry.type
  6870. if kind == 'class':
  6871. if not type.is_extension_type:
  6872. return 0
  6873. else:
  6874. if not type.is_struct_or_union:
  6875. return 0
  6876. if kind != type.kind:
  6877. return 0
  6878. return 1
  6879. def analyse_expressions(self, env):
  6880. return self
  6881. def generate_execution_code(self, code):
  6882. pass
  6883. class FromImportStatNode(StatNode):
  6884. # from ... import statement
  6885. #
  6886. # module ImportNode
  6887. # items [(string, NameNode)]
  6888. # interned_items [(string, NameNode, ExprNode)]
  6889. # item PyTempNode used internally
  6890. # import_star boolean used internally
  6891. child_attrs = ["module"]
  6892. import_star = 0
  6893. def analyse_declarations(self, env):
  6894. for name, target in self.items:
  6895. if name == "*":
  6896. if not env.is_module_scope:
  6897. error(self.pos, "import * only allowed at module level")
  6898. return
  6899. env.has_import_star = 1
  6900. self.import_star = 1
  6901. else:
  6902. target.analyse_target_declaration(env)
  6903. def analyse_expressions(self, env):
  6904. from . import ExprNodes
  6905. self.module = self.module.analyse_expressions(env)
  6906. self.item = ExprNodes.RawCNameExprNode(self.pos, py_object_type)
  6907. self.interned_items = []
  6908. for name, target in self.items:
  6909. if name == '*':
  6910. for _, entry in env.entries.items():
  6911. if not entry.is_type and entry.type.is_extension_type:
  6912. env.use_utility_code(UtilityCode.load_cached("ExtTypeTest", "ObjectHandling.c"))
  6913. break
  6914. else:
  6915. entry = env.lookup(target.name)
  6916. # check whether or not entry is already cimported
  6917. if (entry.is_type and entry.type.name == name
  6918. and hasattr(entry.type, 'module_name')):
  6919. if entry.type.module_name == self.module.module_name.value:
  6920. # cimported with absolute name
  6921. continue
  6922. try:
  6923. # cimported with relative name
  6924. module = env.find_module(self.module.module_name.value, pos=self.pos,
  6925. relative_level=self.module.level)
  6926. if entry.type.module_name == module.qualified_name:
  6927. continue
  6928. except AttributeError:
  6929. pass
  6930. target = target.analyse_target_expression(env, None) # FIXME?
  6931. if target.type is py_object_type:
  6932. coerced_item = None
  6933. else:
  6934. coerced_item = self.item.coerce_to(target.type, env)
  6935. self.interned_items.append((name, target, coerced_item))
  6936. return self
  6937. def generate_execution_code(self, code):
  6938. code.mark_pos(self.pos)
  6939. self.module.generate_evaluation_code(code)
  6940. if self.import_star:
  6941. code.putln(
  6942. 'if (%s(%s) < 0) %s;' % (
  6943. Naming.import_star,
  6944. self.module.py_result(),
  6945. code.error_goto(self.pos)))
  6946. item_temp = code.funcstate.allocate_temp(py_object_type, manage_ref=True)
  6947. self.item.set_cname(item_temp)
  6948. if self.interned_items:
  6949. code.globalstate.use_utility_code(
  6950. UtilityCode.load_cached("ImportFrom", "ImportExport.c"))
  6951. for name, target, coerced_item in self.interned_items:
  6952. code.putln(
  6953. '%s = __Pyx_ImportFrom(%s, %s); %s' % (
  6954. item_temp,
  6955. self.module.py_result(),
  6956. code.intern_identifier(name),
  6957. code.error_goto_if_null(item_temp, self.pos)))
  6958. code.put_gotref(item_temp)
  6959. if coerced_item is None:
  6960. target.generate_assignment_code(self.item, code)
  6961. else:
  6962. coerced_item.allocate_temp_result(code)
  6963. coerced_item.generate_result_code(code)
  6964. target.generate_assignment_code(coerced_item, code)
  6965. code.put_decref_clear(item_temp, py_object_type)
  6966. code.funcstate.release_temp(item_temp)
  6967. self.module.generate_disposal_code(code)
  6968. self.module.free_temps(code)
  6969. class ParallelNode(Node):
  6970. """
  6971. Base class for cython.parallel constructs.
  6972. """
  6973. nogil_check = None
  6974. class ParallelStatNode(StatNode, ParallelNode):
  6975. """
  6976. Base class for 'with cython.parallel.parallel():' and 'for i in prange():'.
  6977. assignments { Entry(var) : (var.pos, inplace_operator_or_None) }
  6978. assignments to variables in this parallel section
  6979. parent parent ParallelStatNode or None
  6980. is_parallel indicates whether this node is OpenMP parallel
  6981. (true for #pragma omp parallel for and
  6982. #pragma omp parallel)
  6983. is_parallel is true for:
  6984. #pragma omp parallel
  6985. #pragma omp parallel for
  6986. sections, but NOT for
  6987. #pragma omp for
  6988. We need this to determine the sharing attributes.
  6989. privatization_insertion_point a code insertion point used to make temps
  6990. private (esp. the "nsteps" temp)
  6991. args tuple the arguments passed to the parallel construct
  6992. kwargs DictNode the keyword arguments passed to the parallel
  6993. construct (replaced by its compile time value)
  6994. """
  6995. child_attrs = ['body', 'num_threads']
  6996. body = None
  6997. is_prange = False
  6998. is_nested_prange = False
  6999. error_label_used = False
  7000. num_threads = None
  7001. chunksize = None
  7002. parallel_exc = (
  7003. Naming.parallel_exc_type,
  7004. Naming.parallel_exc_value,
  7005. Naming.parallel_exc_tb,
  7006. )
  7007. parallel_pos_info = (
  7008. Naming.parallel_filename,
  7009. Naming.parallel_lineno,
  7010. Naming.parallel_clineno,
  7011. )
  7012. pos_info = (
  7013. Naming.filename_cname,
  7014. Naming.lineno_cname,
  7015. Naming.clineno_cname,
  7016. )
  7017. critical_section_counter = 0
  7018. def __init__(self, pos, **kwargs):
  7019. super(ParallelStatNode, self).__init__(pos, **kwargs)
  7020. # All assignments in this scope
  7021. self.assignments = kwargs.get('assignments') or {}
  7022. # All seen closure cnames and their temporary cnames
  7023. self.seen_closure_vars = set()
  7024. # Dict of variables that should be declared (first|last|)private or
  7025. # reduction { Entry: (op, lastprivate) }.
  7026. # If op is not None, it's a reduction.
  7027. self.privates = {}
  7028. # [NameNode]
  7029. self.assigned_nodes = []
  7030. def analyse_declarations(self, env):
  7031. self.body.analyse_declarations(env)
  7032. self.num_threads = None
  7033. if self.kwargs:
  7034. # Try to find num_threads and chunksize keyword arguments
  7035. pairs = []
  7036. seen = set()
  7037. for dictitem in self.kwargs.key_value_pairs:
  7038. if dictitem.key.value in seen:
  7039. error(self.pos, "Duplicate keyword argument found: %s" % dictitem.key.value)
  7040. seen.add(dictitem.key.value)
  7041. if dictitem.key.value == 'num_threads':
  7042. if not dictitem.value.is_none:
  7043. self.num_threads = dictitem.value
  7044. elif self.is_prange and dictitem.key.value == 'chunksize':
  7045. if not dictitem.value.is_none:
  7046. self.chunksize = dictitem.value
  7047. else:
  7048. pairs.append(dictitem)
  7049. self.kwargs.key_value_pairs = pairs
  7050. try:
  7051. self.kwargs = self.kwargs.compile_time_value(env)
  7052. except Exception as e:
  7053. error(self.kwargs.pos, "Only compile-time values may be "
  7054. "supplied as keyword arguments")
  7055. else:
  7056. self.kwargs = {}
  7057. for kw, val in self.kwargs.items():
  7058. if kw not in self.valid_keyword_arguments:
  7059. error(self.pos, "Invalid keyword argument: %s" % kw)
  7060. else:
  7061. setattr(self, kw, val)
  7062. def analyse_expressions(self, env):
  7063. if self.num_threads:
  7064. self.num_threads = self.num_threads.analyse_expressions(env)
  7065. if self.chunksize:
  7066. self.chunksize = self.chunksize.analyse_expressions(env)
  7067. self.body = self.body.analyse_expressions(env)
  7068. self.analyse_sharing_attributes(env)
  7069. if self.num_threads is not None:
  7070. if self.parent and self.parent.num_threads is not None and not self.parent.is_prange:
  7071. error(self.pos, "num_threads already declared in outer section")
  7072. elif self.parent and not self.parent.is_prange:
  7073. error(self.pos, "num_threads must be declared in the parent parallel section")
  7074. elif (self.num_threads.type.is_int and
  7075. self.num_threads.is_literal and
  7076. self.num_threads.compile_time_value(env) <= 0):
  7077. error(self.pos, "argument to num_threads must be greater than 0")
  7078. if not self.num_threads.is_simple() or self.num_threads.type.is_pyobject:
  7079. self.num_threads = self.num_threads.coerce_to(
  7080. PyrexTypes.c_int_type, env).coerce_to_temp(env)
  7081. return self
  7082. def analyse_sharing_attributes(self, env):
  7083. """
  7084. Analyse the privates for this block and set them in self.privates.
  7085. This should be called in a post-order fashion during the
  7086. analyse_expressions phase
  7087. """
  7088. for entry, (pos, op) in self.assignments.items():
  7089. if self.is_prange and not self.is_parallel:
  7090. # closely nested prange in a with parallel block, disallow
  7091. # assigning to privates in the with parallel block (we
  7092. # consider it too implicit and magicky for users)
  7093. if entry in self.parent.assignments:
  7094. error(pos, "Cannot assign to private of outer parallel block")
  7095. continue
  7096. if not self.is_prange and op:
  7097. # Again possible, but considered to magicky
  7098. error(pos, "Reductions not allowed for parallel blocks")
  7099. continue
  7100. # By default all variables should have the same values as if
  7101. # executed sequentially
  7102. lastprivate = True
  7103. self.propagate_var_privatization(entry, pos, op, lastprivate)
  7104. def propagate_var_privatization(self, entry, pos, op, lastprivate):
  7105. """
  7106. Propagate the sharing attributes of a variable. If the privatization is
  7107. determined by a parent scope, done propagate further.
  7108. If we are a prange, we propagate our sharing attributes outwards to
  7109. other pranges. If we are a prange in parallel block and the parallel
  7110. block does not determine the variable private, we propagate to the
  7111. parent of the parent. Recursion stops at parallel blocks, as they have
  7112. no concept of lastprivate or reduction.
  7113. So the following cases propagate:
  7114. sum is a reduction for all loops:
  7115. for i in prange(n):
  7116. for j in prange(n):
  7117. for k in prange(n):
  7118. sum += i * j * k
  7119. sum is a reduction for both loops, local_var is private to the
  7120. parallel with block:
  7121. for i in prange(n):
  7122. with parallel:
  7123. local_var = ... # private to the parallel
  7124. for j in prange(n):
  7125. sum += i * j
  7126. Nested with parallel blocks are disallowed, because they wouldn't
  7127. allow you to propagate lastprivates or reductions:
  7128. #pragma omp parallel for lastprivate(i)
  7129. for i in prange(n):
  7130. sum = 0
  7131. #pragma omp parallel private(j, sum)
  7132. with parallel:
  7133. #pragma omp parallel
  7134. with parallel:
  7135. #pragma omp for lastprivate(j) reduction(+:sum)
  7136. for j in prange(n):
  7137. sum += i
  7138. # sum and j are well-defined here
  7139. # sum and j are undefined here
  7140. # sum and j are undefined here
  7141. """
  7142. self.privates[entry] = (op, lastprivate)
  7143. if entry.type.is_memoryviewslice:
  7144. error(pos, "Memoryview slices can only be shared in parallel sections")
  7145. return
  7146. if self.is_prange:
  7147. if not self.is_parallel and entry not in self.parent.assignments:
  7148. # Parent is a parallel with block
  7149. parent = self.parent.parent
  7150. else:
  7151. parent = self.parent
  7152. # We don't need to propagate privates, only reductions and
  7153. # lastprivates
  7154. if parent and (op or lastprivate):
  7155. parent.propagate_var_privatization(entry, pos, op, lastprivate)
  7156. def _allocate_closure_temp(self, code, entry):
  7157. """
  7158. Helper function that allocate a temporary for a closure variable that
  7159. is assigned to.
  7160. """
  7161. if self.parent:
  7162. return self.parent._allocate_closure_temp(code, entry)
  7163. if entry.cname in self.seen_closure_vars:
  7164. return entry.cname
  7165. cname = code.funcstate.allocate_temp(entry.type, True)
  7166. # Add both the actual cname and the temp cname, as the actual cname
  7167. # will be replaced with the temp cname on the entry
  7168. self.seen_closure_vars.add(entry.cname)
  7169. self.seen_closure_vars.add(cname)
  7170. self.modified_entries.append((entry, entry.cname))
  7171. code.putln("%s = %s;" % (cname, entry.cname))
  7172. entry.cname = cname
  7173. def initialize_privates_to_nan(self, code, exclude=None):
  7174. first = True
  7175. for entry, (op, lastprivate) in sorted(self.privates.items()):
  7176. if not op and (not exclude or entry != exclude):
  7177. invalid_value = entry.type.invalid_value()
  7178. if invalid_value:
  7179. if first:
  7180. code.putln("/* Initialize private variables to "
  7181. "invalid values */")
  7182. first = False
  7183. code.putln("%s = %s;" % (entry.cname,
  7184. entry.type.cast_code(invalid_value)))
  7185. def evaluate_before_block(self, code, expr):
  7186. c = self.begin_of_parallel_control_block_point_after_decls
  7187. # we need to set the owner to ourselves temporarily, as
  7188. # allocate_temp may generate a comment in the middle of our pragma
  7189. # otherwise when DebugFlags.debug_temp_code_comments is in effect
  7190. owner = c.funcstate.owner
  7191. c.funcstate.owner = c
  7192. expr.generate_evaluation_code(c)
  7193. c.funcstate.owner = owner
  7194. return expr.result()
  7195. def put_num_threads(self, code):
  7196. """
  7197. Write self.num_threads if set as the num_threads OpenMP directive
  7198. """
  7199. if self.num_threads is not None:
  7200. code.put(" num_threads(%s)" % self.evaluate_before_block(code, self.num_threads))
  7201. def declare_closure_privates(self, code):
  7202. """
  7203. If a variable is in a scope object, we need to allocate a temp and
  7204. assign the value from the temp to the variable in the scope object
  7205. after the parallel section. This kind of copying should be done only
  7206. in the outermost parallel section.
  7207. """
  7208. self.modified_entries = []
  7209. for entry in sorted(self.assignments):
  7210. if entry.from_closure or entry.in_closure:
  7211. self._allocate_closure_temp(code, entry)
  7212. def release_closure_privates(self, code):
  7213. """
  7214. Release any temps used for variables in scope objects. As this is the
  7215. outermost parallel block, we don't need to delete the cnames from
  7216. self.seen_closure_vars.
  7217. """
  7218. for entry, original_cname in self.modified_entries:
  7219. code.putln("%s = %s;" % (original_cname, entry.cname))
  7220. code.funcstate.release_temp(entry.cname)
  7221. entry.cname = original_cname
  7222. def privatize_temps(self, code, exclude_temps=()):
  7223. """
  7224. Make any used temporaries private. Before the relevant code block
  7225. code.start_collecting_temps() should have been called.
  7226. """
  7227. if self.is_parallel:
  7228. c = self.privatization_insertion_point
  7229. self.temps = temps = code.funcstate.stop_collecting_temps()
  7230. privates, firstprivates = [], []
  7231. for temp, type in sorted(temps):
  7232. if type.is_pyobject or type.is_memoryviewslice:
  7233. firstprivates.append(temp)
  7234. else:
  7235. privates.append(temp)
  7236. if privates:
  7237. c.put(" private(%s)" % ", ".join(privates))
  7238. if firstprivates:
  7239. c.put(" firstprivate(%s)" % ", ".join(firstprivates))
  7240. if self.breaking_label_used:
  7241. shared_vars = [Naming.parallel_why]
  7242. if self.error_label_used:
  7243. shared_vars.extend(self.parallel_exc)
  7244. c.put(" private(%s, %s, %s)" % self.pos_info)
  7245. c.put(" shared(%s)" % ', '.join(shared_vars))
  7246. def cleanup_temps(self, code):
  7247. # Now clean up any memoryview slice and object temporaries
  7248. if self.is_parallel and not self.is_nested_prange:
  7249. code.putln("/* Clean up any temporaries */")
  7250. for temp, type in sorted(self.temps):
  7251. if type.is_memoryviewslice:
  7252. code.put_xdecref_memoryviewslice(temp, have_gil=False)
  7253. elif type.is_pyobject:
  7254. code.put_xdecref(temp, type)
  7255. code.putln("%s = NULL;" % temp)
  7256. def setup_parallel_control_flow_block(self, code):
  7257. """
  7258. Sets up a block that surrounds the parallel block to determine
  7259. how the parallel section was exited. Any kind of return is
  7260. trapped (break, continue, return, exceptions). This is the idea:
  7261. {
  7262. int why = 0;
  7263. #pragma omp parallel
  7264. {
  7265. return # -> goto new_return_label;
  7266. goto end_parallel;
  7267. new_return_label:
  7268. why = 3;
  7269. goto end_parallel;
  7270. end_parallel:;
  7271. #pragma omp flush(why) # we need to flush for every iteration
  7272. }
  7273. if (why == 3)
  7274. goto old_return_label;
  7275. }
  7276. """
  7277. self.old_loop_labels = code.new_loop_labels()
  7278. self.old_error_label = code.new_error_label()
  7279. self.old_return_label = code.return_label
  7280. code.return_label = code.new_label(name="return")
  7281. code.begin_block() # parallel control flow block
  7282. self.begin_of_parallel_control_block_point = code.insertion_point()
  7283. self.begin_of_parallel_control_block_point_after_decls = code.insertion_point()
  7284. self.undef_builtin_expect_apple_gcc_bug(code)
  7285. def begin_parallel_block(self, code):
  7286. """
  7287. Each OpenMP thread in a parallel section that contains a with gil block
  7288. must have the thread-state initialized. The call to
  7289. PyGILState_Release() then deallocates our threadstate. If we wouldn't
  7290. do this, each with gil block would allocate and deallocate one, thereby
  7291. losing exception information before it can be saved before leaving the
  7292. parallel section.
  7293. """
  7294. self.begin_of_parallel_block = code.insertion_point()
  7295. def end_parallel_block(self, code):
  7296. """
  7297. To ensure all OpenMP threads have thread states, we ensure the GIL
  7298. in each thread (which creates a thread state if it doesn't exist),
  7299. after which we release the GIL.
  7300. On exit, reacquire the GIL and release the thread state.
  7301. If compiled without OpenMP support (at the C level), then we still have
  7302. to acquire the GIL to decref any object temporaries.
  7303. """
  7304. if self.error_label_used:
  7305. begin_code = self.begin_of_parallel_block
  7306. end_code = code
  7307. begin_code.putln("#ifdef _OPENMP")
  7308. begin_code.put_ensure_gil(declare_gilstate=True)
  7309. begin_code.putln("Py_BEGIN_ALLOW_THREADS")
  7310. begin_code.putln("#endif /* _OPENMP */")
  7311. end_code.putln("#ifdef _OPENMP")
  7312. end_code.putln("Py_END_ALLOW_THREADS")
  7313. end_code.putln("#else")
  7314. end_code.put_safe("{\n")
  7315. end_code.put_ensure_gil()
  7316. end_code.putln("#endif /* _OPENMP */")
  7317. self.cleanup_temps(end_code)
  7318. end_code.put_release_ensured_gil()
  7319. end_code.putln("#ifndef _OPENMP")
  7320. end_code.put_safe("}\n")
  7321. end_code.putln("#endif /* _OPENMP */")
  7322. def trap_parallel_exit(self, code, should_flush=False):
  7323. """
  7324. Trap any kind of return inside a parallel construct. 'should_flush'
  7325. indicates whether the variable should be flushed, which is needed by
  7326. prange to skip the loop. It also indicates whether we need to register
  7327. a continue (we need this for parallel blocks, but not for prange
  7328. loops, as it is a direct jump there).
  7329. It uses the same mechanism as try/finally:
  7330. 1 continue
  7331. 2 break
  7332. 3 return
  7333. 4 error
  7334. """
  7335. save_lastprivates_label = code.new_label()
  7336. dont_return_label = code.new_label()
  7337. self.any_label_used = False
  7338. self.breaking_label_used = False
  7339. self.error_label_used = False
  7340. self.parallel_private_temps = []
  7341. all_labels = code.get_all_labels()
  7342. # Figure this out before starting to generate any code
  7343. for label in all_labels:
  7344. if code.label_used(label):
  7345. self.breaking_label_used = (self.breaking_label_used or
  7346. label != code.continue_label)
  7347. self.any_label_used = True
  7348. if self.any_label_used:
  7349. code.put_goto(dont_return_label)
  7350. for i, label in enumerate(all_labels):
  7351. if not code.label_used(label):
  7352. continue
  7353. is_continue_label = label == code.continue_label
  7354. code.put_label(label)
  7355. if not (should_flush and is_continue_label):
  7356. if label == code.error_label:
  7357. self.error_label_used = True
  7358. self.fetch_parallel_exception(code)
  7359. code.putln("%s = %d;" % (Naming.parallel_why, i + 1))
  7360. if (self.breaking_label_used and self.is_prange and not
  7361. is_continue_label):
  7362. code.put_goto(save_lastprivates_label)
  7363. else:
  7364. code.put_goto(dont_return_label)
  7365. if self.any_label_used:
  7366. if self.is_prange and self.breaking_label_used:
  7367. # Don't rely on lastprivate, save our lastprivates
  7368. code.put_label(save_lastprivates_label)
  7369. self.save_parallel_vars(code)
  7370. code.put_label(dont_return_label)
  7371. if should_flush and self.breaking_label_used:
  7372. code.putln_openmp("#pragma omp flush(%s)" % Naming.parallel_why)
  7373. def save_parallel_vars(self, code):
  7374. """
  7375. The following shenanigans are instated when we break, return or
  7376. propagate errors from a prange. In this case we cannot rely on
  7377. lastprivate() to do its job, as no iterations may have executed yet
  7378. in the last thread, leaving the values undefined. It is most likely
  7379. that the breaking thread has well-defined values of the lastprivate
  7380. variables, so we keep those values.
  7381. """
  7382. section_name = "__pyx_parallel_lastprivates%d" % self.critical_section_counter
  7383. code.putln_openmp("#pragma omp critical(%s)" % section_name)
  7384. ParallelStatNode.critical_section_counter += 1
  7385. code.begin_block() # begin critical section
  7386. c = self.begin_of_parallel_control_block_point
  7387. temp_count = 0
  7388. for entry, (op, lastprivate) in sorted(self.privates.items()):
  7389. if not lastprivate or entry.type.is_pyobject:
  7390. continue
  7391. type_decl = entry.type.empty_declaration_code()
  7392. temp_cname = "__pyx_parallel_temp%d" % temp_count
  7393. private_cname = entry.cname
  7394. temp_count += 1
  7395. invalid_value = entry.type.invalid_value()
  7396. if invalid_value:
  7397. init = ' = ' + entry.type.cast_code(invalid_value)
  7398. else:
  7399. init = ''
  7400. # Declare the parallel private in the outer block
  7401. c.putln("%s %s%s;" % (type_decl, temp_cname, init))
  7402. # Initialize before escaping
  7403. code.putln("%s = %s;" % (temp_cname, private_cname))
  7404. self.parallel_private_temps.append((temp_cname, private_cname))
  7405. code.end_block() # end critical section
  7406. def fetch_parallel_exception(self, code):
  7407. """
  7408. As each OpenMP thread may raise an exception, we need to fetch that
  7409. exception from the threadstate and save it for after the parallel
  7410. section where it can be re-raised in the master thread.
  7411. Although it would seem that __pyx_filename, __pyx_lineno and
  7412. __pyx_clineno are only assigned to under exception conditions (i.e.,
  7413. when we have the GIL), and thus should be allowed to be shared without
  7414. any race condition, they are in fact subject to the same race
  7415. conditions that they were previously when they were global variables
  7416. and functions were allowed to release the GIL:
  7417. thread A thread B
  7418. acquire
  7419. set lineno
  7420. release
  7421. acquire
  7422. set lineno
  7423. release
  7424. acquire
  7425. fetch exception
  7426. release
  7427. skip the fetch
  7428. deallocate threadstate deallocate threadstate
  7429. """
  7430. code.begin_block()
  7431. code.put_ensure_gil(declare_gilstate=True)
  7432. code.putln_openmp("#pragma omp flush(%s)" % Naming.parallel_exc_type)
  7433. code.putln(
  7434. "if (!%s) {" % Naming.parallel_exc_type)
  7435. code.putln("__Pyx_ErrFetchWithState(&%s, &%s, &%s);" % self.parallel_exc)
  7436. pos_info = chain(*zip(self.parallel_pos_info, self.pos_info))
  7437. code.funcstate.uses_error_indicator = True
  7438. code.putln("%s = %s; %s = %s; %s = %s;" % tuple(pos_info))
  7439. code.put_gotref(Naming.parallel_exc_type)
  7440. code.putln(
  7441. "}")
  7442. code.put_release_ensured_gil()
  7443. code.end_block()
  7444. def restore_parallel_exception(self, code):
  7445. "Re-raise a parallel exception"
  7446. code.begin_block()
  7447. code.put_ensure_gil(declare_gilstate=True)
  7448. code.put_giveref(Naming.parallel_exc_type)
  7449. code.putln("__Pyx_ErrRestoreWithState(%s, %s, %s);" % self.parallel_exc)
  7450. pos_info = chain(*zip(self.pos_info, self.parallel_pos_info))
  7451. code.putln("%s = %s; %s = %s; %s = %s;" % tuple(pos_info))
  7452. code.put_release_ensured_gil()
  7453. code.end_block()
  7454. def restore_labels(self, code):
  7455. """
  7456. Restore all old labels. Call this before the 'else' clause to for
  7457. loops and always before ending the parallel control flow block.
  7458. """
  7459. code.set_all_labels(self.old_loop_labels + (self.old_return_label,
  7460. self.old_error_label))
  7461. def end_parallel_control_flow_block(
  7462. self, code, break_=False, continue_=False, return_=False):
  7463. """
  7464. This ends the parallel control flow block and based on how the parallel
  7465. section was exited, takes the corresponding action. The break_ and
  7466. continue_ parameters indicate whether these should be propagated
  7467. outwards:
  7468. for i in prange(...):
  7469. with cython.parallel.parallel():
  7470. continue
  7471. Here break should be trapped in the parallel block, and propagated to
  7472. the for loop.
  7473. """
  7474. c = self.begin_of_parallel_control_block_point
  7475. # Firstly, always prefer errors over returning, continue or break
  7476. if self.error_label_used:
  7477. c.putln("const char *%s = NULL; int %s = 0, %s = 0;" % self.parallel_pos_info)
  7478. c.putln("PyObject *%s = NULL, *%s = NULL, *%s = NULL;" % self.parallel_exc)
  7479. code.putln(
  7480. "if (%s) {" % Naming.parallel_exc_type)
  7481. code.putln("/* This may have been overridden by a continue, "
  7482. "break or return in another thread. Prefer the error. */")
  7483. code.putln("%s = 4;" % Naming.parallel_why)
  7484. code.putln(
  7485. "}")
  7486. if continue_:
  7487. any_label_used = self.any_label_used
  7488. else:
  7489. any_label_used = self.breaking_label_used
  7490. if any_label_used:
  7491. # __pyx_parallel_why is used, declare and initialize
  7492. c.putln("int %s;" % Naming.parallel_why)
  7493. c.putln("%s = 0;" % Naming.parallel_why)
  7494. code.putln(
  7495. "if (%s) {" % Naming.parallel_why)
  7496. for temp_cname, private_cname in self.parallel_private_temps:
  7497. code.putln("%s = %s;" % (private_cname, temp_cname))
  7498. code.putln("switch (%s) {" % Naming.parallel_why)
  7499. if continue_:
  7500. code.put(" case 1: ")
  7501. code.put_goto(code.continue_label)
  7502. if break_:
  7503. code.put(" case 2: ")
  7504. code.put_goto(code.break_label)
  7505. if return_:
  7506. code.put(" case 3: ")
  7507. code.put_goto(code.return_label)
  7508. if self.error_label_used:
  7509. code.globalstate.use_utility_code(restore_exception_utility_code)
  7510. code.putln(" case 4:")
  7511. self.restore_parallel_exception(code)
  7512. code.put_goto(code.error_label)
  7513. code.putln("}") # end switch
  7514. code.putln(
  7515. "}") # end if
  7516. code.end_block() # end parallel control flow block
  7517. self.redef_builtin_expect_apple_gcc_bug(code)
  7518. # FIXME: improve with version number for OS X Lion
  7519. buggy_platform_macro_condition = "(defined(__APPLE__) || defined(__OSX__))"
  7520. have_expect_condition = "(defined(__GNUC__) && " \
  7521. "(__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))"
  7522. redef_condition = "(%s && %s)" % (buggy_platform_macro_condition, have_expect_condition)
  7523. def undef_builtin_expect_apple_gcc_bug(self, code):
  7524. """
  7525. A bug on OS X Lion disallows __builtin_expect macros. This code avoids them
  7526. """
  7527. if not self.parent:
  7528. code.undef_builtin_expect(self.redef_condition)
  7529. def redef_builtin_expect_apple_gcc_bug(self, code):
  7530. if not self.parent:
  7531. code.redef_builtin_expect(self.redef_condition)
  7532. class ParallelWithBlockNode(ParallelStatNode):
  7533. """
  7534. This node represents a 'with cython.parallel.parallel():' block
  7535. """
  7536. valid_keyword_arguments = ['num_threads']
  7537. num_threads = None
  7538. def analyse_declarations(self, env):
  7539. super(ParallelWithBlockNode, self).analyse_declarations(env)
  7540. if self.args:
  7541. error(self.pos, "cython.parallel.parallel() does not take "
  7542. "positional arguments")
  7543. def generate_execution_code(self, code):
  7544. self.declare_closure_privates(code)
  7545. self.setup_parallel_control_flow_block(code)
  7546. code.putln("#ifdef _OPENMP")
  7547. code.put("#pragma omp parallel ")
  7548. if self.privates:
  7549. privates = [e.cname for e in self.privates
  7550. if not e.type.is_pyobject]
  7551. code.put('private(%s)' % ', '.join(sorted(privates)))
  7552. self.privatization_insertion_point = code.insertion_point()
  7553. self.put_num_threads(code)
  7554. code.putln("")
  7555. code.putln("#endif /* _OPENMP */")
  7556. code.begin_block() # parallel block
  7557. self.begin_parallel_block(code)
  7558. self.initialize_privates_to_nan(code)
  7559. code.funcstate.start_collecting_temps()
  7560. self.body.generate_execution_code(code)
  7561. self.trap_parallel_exit(code)
  7562. self.privatize_temps(code)
  7563. self.end_parallel_block(code)
  7564. code.end_block() # end parallel block
  7565. continue_ = code.label_used(code.continue_label)
  7566. break_ = code.label_used(code.break_label)
  7567. return_ = code.label_used(code.return_label)
  7568. self.restore_labels(code)
  7569. self.end_parallel_control_flow_block(code, break_=break_,
  7570. continue_=continue_,
  7571. return_=return_)
  7572. self.release_closure_privates(code)
  7573. class ParallelRangeNode(ParallelStatNode):
  7574. """
  7575. This node represents a 'for i in cython.parallel.prange():' construct.
  7576. target NameNode the target iteration variable
  7577. else_clause Node or None the else clause of this loop
  7578. """
  7579. child_attrs = ['body', 'target', 'else_clause', 'args', 'num_threads',
  7580. 'chunksize']
  7581. body = target = else_clause = args = None
  7582. start = stop = step = None
  7583. is_prange = True
  7584. nogil = None
  7585. schedule = None
  7586. valid_keyword_arguments = ['schedule', 'nogil', 'num_threads', 'chunksize']
  7587. def __init__(self, pos, **kwds):
  7588. super(ParallelRangeNode, self).__init__(pos, **kwds)
  7589. # Pretend to be a ForInStatNode for control flow analysis
  7590. self.iterator = PassStatNode(pos)
  7591. def analyse_declarations(self, env):
  7592. super(ParallelRangeNode, self).analyse_declarations(env)
  7593. self.target.analyse_target_declaration(env)
  7594. if self.else_clause is not None:
  7595. self.else_clause.analyse_declarations(env)
  7596. if not self.args or len(self.args) > 3:
  7597. error(self.pos, "Invalid number of positional arguments to prange")
  7598. return
  7599. if len(self.args) == 1:
  7600. self.stop, = self.args
  7601. elif len(self.args) == 2:
  7602. self.start, self.stop = self.args
  7603. else:
  7604. self.start, self.stop, self.step = self.args
  7605. if hasattr(self.schedule, 'decode'):
  7606. self.schedule = self.schedule.decode('ascii')
  7607. if self.schedule not in (None, 'static', 'dynamic', 'guided', 'runtime'):
  7608. error(self.pos, "Invalid schedule argument to prange: %s" % (self.schedule,))
  7609. def analyse_expressions(self, env):
  7610. was_nogil = env.nogil
  7611. if self.nogil:
  7612. env.nogil = True
  7613. if self.target is None:
  7614. error(self.pos, "prange() can only be used as part of a for loop")
  7615. return self
  7616. self.target = self.target.analyse_target_types(env)
  7617. if not self.target.type.is_numeric:
  7618. # Not a valid type, assume one for now anyway
  7619. if not self.target.type.is_pyobject:
  7620. # nogil_check will catch the is_pyobject case
  7621. error(self.target.pos,
  7622. "Must be of numeric type, not %s" % self.target.type)
  7623. self.index_type = PyrexTypes.c_py_ssize_t_type
  7624. else:
  7625. self.index_type = self.target.type
  7626. if not self.index_type.signed:
  7627. warning(self.target.pos,
  7628. "Unsigned index type not allowed before OpenMP 3.0",
  7629. level=2)
  7630. # Setup start, stop and step, allocating temps if needed
  7631. self.names = 'start', 'stop', 'step'
  7632. start_stop_step = self.start, self.stop, self.step
  7633. for node, name in zip(start_stop_step, self.names):
  7634. if node is not None:
  7635. node.analyse_types(env)
  7636. if not node.type.is_numeric:
  7637. error(node.pos, "%s argument must be numeric" % name)
  7638. continue
  7639. if not node.is_literal:
  7640. node = node.coerce_to_temp(env)
  7641. setattr(self, name, node)
  7642. # As we range from 0 to nsteps, computing the index along the
  7643. # way, we need a fitting type for 'i' and 'nsteps'
  7644. self.index_type = PyrexTypes.widest_numeric_type(
  7645. self.index_type, node.type)
  7646. if self.else_clause is not None:
  7647. self.else_clause = self.else_clause.analyse_expressions(env)
  7648. # Although not actually an assignment in this scope, it should be
  7649. # treated as such to ensure it is unpacked if a closure temp, and to
  7650. # ensure lastprivate behaviour and propagation. If the target index is
  7651. # not a NameNode, it won't have an entry, and an error was issued by
  7652. # ParallelRangeTransform
  7653. if hasattr(self.target, 'entry'):
  7654. self.assignments[self.target.entry] = self.target.pos, None
  7655. node = super(ParallelRangeNode, self).analyse_expressions(env)
  7656. if node.chunksize:
  7657. if not node.schedule:
  7658. error(node.chunksize.pos,
  7659. "Must provide schedule with chunksize")
  7660. elif node.schedule == 'runtime':
  7661. error(node.chunksize.pos,
  7662. "Chunksize not valid for the schedule runtime")
  7663. elif (node.chunksize.type.is_int and
  7664. node.chunksize.is_literal and
  7665. node.chunksize.compile_time_value(env) <= 0):
  7666. error(node.chunksize.pos, "Chunksize must not be negative")
  7667. node.chunksize = node.chunksize.coerce_to(
  7668. PyrexTypes.c_int_type, env).coerce_to_temp(env)
  7669. if node.nogil:
  7670. env.nogil = was_nogil
  7671. node.is_nested_prange = node.parent and node.parent.is_prange
  7672. if node.is_nested_prange:
  7673. parent = node
  7674. while parent.parent and parent.parent.is_prange:
  7675. parent = parent.parent
  7676. parent.assignments.update(node.assignments)
  7677. parent.privates.update(node.privates)
  7678. parent.assigned_nodes.extend(node.assigned_nodes)
  7679. return node
  7680. def nogil_check(self, env):
  7681. names = 'start', 'stop', 'step', 'target'
  7682. nodes = self.start, self.stop, self.step, self.target
  7683. for name, node in zip(names, nodes):
  7684. if node is not None and node.type.is_pyobject:
  7685. error(node.pos, "%s may not be a Python object "
  7686. "as we don't have the GIL" % name)
  7687. def generate_execution_code(self, code):
  7688. """
  7689. Generate code in the following steps
  7690. 1) copy any closure variables determined thread-private
  7691. into temporaries
  7692. 2) allocate temps for start, stop and step
  7693. 3) generate a loop that calculates the total number of steps,
  7694. which then computes the target iteration variable for every step:
  7695. for i in prange(start, stop, step):
  7696. ...
  7697. becomes
  7698. nsteps = (stop - start) / step;
  7699. i = start;
  7700. #pragma omp parallel for lastprivate(i)
  7701. for (temp = 0; temp < nsteps; temp++) {
  7702. i = start + step * temp;
  7703. ...
  7704. }
  7705. Note that accumulation of 'i' would have a data dependency
  7706. between iterations.
  7707. Also, you can't do this
  7708. for (i = start; i < stop; i += step)
  7709. ...
  7710. as the '<' operator should become '>' for descending loops.
  7711. 'for i from x < i < y:' does not suffer from this problem
  7712. as the relational operator is known at compile time!
  7713. 4) release our temps and write back any private closure variables
  7714. """
  7715. self.declare_closure_privates(code)
  7716. # This can only be a NameNode
  7717. target_index_cname = self.target.entry.cname
  7718. # This will be used as the dict to format our code strings, holding
  7719. # the start, stop , step, temps and target cnames
  7720. fmt_dict = {
  7721. 'target': target_index_cname,
  7722. 'target_type': self.target.type.empty_declaration_code()
  7723. }
  7724. # Setup start, stop and step, allocating temps if needed
  7725. start_stop_step = self.start, self.stop, self.step
  7726. defaults = '0', '0', '1'
  7727. for node, name, default in zip(start_stop_step, self.names, defaults):
  7728. if node is None:
  7729. result = default
  7730. elif node.is_literal:
  7731. result = node.get_constant_c_result_code()
  7732. else:
  7733. node.generate_evaluation_code(code)
  7734. result = node.result()
  7735. fmt_dict[name] = result
  7736. fmt_dict['i'] = code.funcstate.allocate_temp(self.index_type, False)
  7737. fmt_dict['nsteps'] = code.funcstate.allocate_temp(self.index_type, False)
  7738. # TODO: check if the step is 0 and if so, raise an exception in a
  7739. # 'with gil' block. For now, just abort
  7740. code.putln("if (%(step)s == 0) abort();" % fmt_dict)
  7741. self.setup_parallel_control_flow_block(code) # parallel control flow block
  7742. self.control_flow_var_code_point = code.insertion_point()
  7743. # Note: nsteps is private in an outer scope if present
  7744. code.putln("%(nsteps)s = (%(stop)s - %(start)s + %(step)s - %(step)s/abs(%(step)s)) / %(step)s;" % fmt_dict)
  7745. # The target iteration variable might not be initialized, do it only if
  7746. # we are executing at least 1 iteration, otherwise we should leave the
  7747. # target unaffected. The target iteration variable is firstprivate to
  7748. # shut up compiler warnings caused by lastprivate, as the compiler
  7749. # erroneously believes that nsteps may be <= 0, leaving the private
  7750. # target index uninitialized
  7751. code.putln("if (%(nsteps)s > 0)" % fmt_dict)
  7752. code.begin_block() # if block
  7753. self.generate_loop(code, fmt_dict)
  7754. code.end_block() # end if block
  7755. self.restore_labels(code)
  7756. if self.else_clause:
  7757. if self.breaking_label_used:
  7758. code.put("if (%s < 2)" % Naming.parallel_why)
  7759. code.begin_block() # else block
  7760. code.putln("/* else */")
  7761. self.else_clause.generate_execution_code(code)
  7762. code.end_block() # end else block
  7763. # ------ cleanup ------
  7764. self.end_parallel_control_flow_block(code) # end parallel control flow block
  7765. # And finally, release our privates and write back any closure
  7766. # variables
  7767. for temp in start_stop_step + (self.chunksize, self.num_threads):
  7768. if temp is not None:
  7769. temp.generate_disposal_code(code)
  7770. temp.free_temps(code)
  7771. code.funcstate.release_temp(fmt_dict['i'])
  7772. code.funcstate.release_temp(fmt_dict['nsteps'])
  7773. self.release_closure_privates(code)
  7774. def generate_loop(self, code, fmt_dict):
  7775. if self.is_nested_prange:
  7776. code.putln("#if 0")
  7777. else:
  7778. code.putln("#ifdef _OPENMP")
  7779. if not self.is_parallel:
  7780. code.put("#pragma omp for")
  7781. self.privatization_insertion_point = code.insertion_point()
  7782. reduction_codepoint = self.parent.privatization_insertion_point
  7783. else:
  7784. code.put("#pragma omp parallel")
  7785. self.privatization_insertion_point = code.insertion_point()
  7786. reduction_codepoint = self.privatization_insertion_point
  7787. code.putln("")
  7788. code.putln("#endif /* _OPENMP */")
  7789. code.begin_block() # pragma omp parallel begin block
  7790. # Initialize the GIL if needed for this thread
  7791. self.begin_parallel_block(code)
  7792. if self.is_nested_prange:
  7793. code.putln("#if 0")
  7794. else:
  7795. code.putln("#ifdef _OPENMP")
  7796. code.put("#pragma omp for")
  7797. for entry, (op, lastprivate) in sorted(self.privates.items()):
  7798. # Don't declare the index variable as a reduction
  7799. if op and op in "+*-&^|" and entry != self.target.entry:
  7800. if entry.type.is_pyobject:
  7801. error(self.pos, "Python objects cannot be reductions")
  7802. else:
  7803. #code.put(" reduction(%s:%s)" % (op, entry.cname))
  7804. # This is the only way reductions + nesting works in gcc4.5
  7805. reduction_codepoint.put(
  7806. " reduction(%s:%s)" % (op, entry.cname))
  7807. else:
  7808. if entry == self.target.entry:
  7809. code.put(" firstprivate(%s)" % entry.cname)
  7810. code.put(" lastprivate(%s)" % entry.cname)
  7811. continue
  7812. if not entry.type.is_pyobject:
  7813. if lastprivate:
  7814. private = 'lastprivate'
  7815. else:
  7816. private = 'private'
  7817. code.put(" %s(%s)" % (private, entry.cname))
  7818. if self.schedule:
  7819. if self.chunksize:
  7820. chunksize = ", %s" % self.evaluate_before_block(code, self.chunksize)
  7821. else:
  7822. chunksize = ""
  7823. code.put(" schedule(%s%s)" % (self.schedule, chunksize))
  7824. self.put_num_threads(reduction_codepoint)
  7825. code.putln("")
  7826. code.putln("#endif /* _OPENMP */")
  7827. code.put("for (%(i)s = 0; %(i)s < %(nsteps)s; %(i)s++)" % fmt_dict)
  7828. code.begin_block() # for loop block
  7829. guard_around_body_codepoint = code.insertion_point()
  7830. # Start if guard block around the body. This may be unnecessary, but
  7831. # at least it doesn't spoil indentation
  7832. code.begin_block()
  7833. code.putln("%(target)s = (%(target_type)s)(%(start)s + %(step)s * %(i)s);" % fmt_dict)
  7834. self.initialize_privates_to_nan(code, exclude=self.target.entry)
  7835. if self.is_parallel:
  7836. code.funcstate.start_collecting_temps()
  7837. self.body.generate_execution_code(code)
  7838. self.trap_parallel_exit(code, should_flush=True)
  7839. self.privatize_temps(code)
  7840. if self.breaking_label_used:
  7841. # Put a guard around the loop body in case return, break or
  7842. # exceptions might be used
  7843. guard_around_body_codepoint.putln("if (%s < 2)" % Naming.parallel_why)
  7844. code.end_block() # end guard around loop body
  7845. code.end_block() # end for loop block
  7846. if self.is_parallel:
  7847. # Release the GIL and deallocate the thread state
  7848. self.end_parallel_block(code)
  7849. code.end_block() # pragma omp parallel end block
  7850. class CnameDecoratorNode(StatNode):
  7851. """
  7852. This node is for the cname decorator in CythonUtilityCode:
  7853. @cname('the_cname')
  7854. cdef func(...):
  7855. ...
  7856. In case of a cdef class the cname specifies the objstruct_cname.
  7857. node the node to which the cname decorator is applied
  7858. cname the cname the node should get
  7859. """
  7860. child_attrs = ['node']
  7861. def analyse_declarations(self, env):
  7862. self.node.analyse_declarations(env)
  7863. node = self.node
  7864. if isinstance(node, CompilerDirectivesNode):
  7865. node = node.body.stats[0]
  7866. self.is_function = isinstance(node, FuncDefNode)
  7867. is_struct_or_enum = isinstance(node, (CStructOrUnionDefNode, CEnumDefNode))
  7868. e = node.entry
  7869. if self.is_function:
  7870. e.cname = self.cname
  7871. e.func_cname = self.cname
  7872. e.used = True
  7873. if e.pyfunc_cname and '.' in e.pyfunc_cname:
  7874. e.pyfunc_cname = self.mangle(e.pyfunc_cname)
  7875. elif is_struct_or_enum:
  7876. e.cname = e.type.cname = self.cname
  7877. else:
  7878. scope = node.scope
  7879. e.cname = self.cname
  7880. e.type.objstruct_cname = self.cname + '_obj'
  7881. e.type.typeobj_cname = Naming.typeobj_prefix + self.cname
  7882. e.type.typeptr_cname = self.cname + '_type'
  7883. e.type.scope.namespace_cname = e.type.typeptr_cname
  7884. e.as_variable.cname = e.type.typeptr_cname
  7885. scope.scope_prefix = self.cname + "_"
  7886. for name, entry in scope.entries.items():
  7887. if entry.func_cname:
  7888. entry.func_cname = self.mangle(entry.cname)
  7889. if entry.pyfunc_cname:
  7890. entry.pyfunc_cname = self.mangle(entry.pyfunc_cname)
  7891. def mangle(self, cname):
  7892. if '.' in cname:
  7893. # remove __pyx_base from func_cname
  7894. cname = cname.split('.')[-1]
  7895. return '%s_%s' % (self.cname, cname)
  7896. def analyse_expressions(self, env):
  7897. self.node = self.node.analyse_expressions(env)
  7898. return self
  7899. def generate_function_definitions(self, env, code):
  7900. "Ensure a prototype for every @cname method in the right place"
  7901. if self.is_function and env.is_c_class_scope:
  7902. # method in cdef class, generate a prototype in the header
  7903. h_code = code.globalstate['utility_code_proto']
  7904. if isinstance(self.node, DefNode):
  7905. self.node.generate_function_header(
  7906. h_code, with_pymethdef=False, proto_only=True)
  7907. else:
  7908. from . import ModuleNode
  7909. entry = self.node.entry
  7910. cname = entry.cname
  7911. entry.cname = entry.func_cname
  7912. ModuleNode.generate_cfunction_declaration(
  7913. entry,
  7914. env.global_scope(),
  7915. h_code,
  7916. definition=True)
  7917. entry.cname = cname
  7918. self.node.generate_function_definitions(env, code)
  7919. def generate_execution_code(self, code):
  7920. self.node.generate_execution_code(code)
  7921. #------------------------------------------------------------------------------------
  7922. #
  7923. # Runtime support code
  7924. #
  7925. #------------------------------------------------------------------------------------
  7926. if Options.gcc_branch_hints:
  7927. branch_prediction_macros = """
  7928. /* Test for GCC > 2.95 */
  7929. #if defined(__GNUC__) \
  7930. && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95)))
  7931. #define likely(x) __builtin_expect(!!(x), 1)
  7932. #define unlikely(x) __builtin_expect(!!(x), 0)
  7933. #else /* !__GNUC__ or GCC < 2.95 */
  7934. #define likely(x) (x)
  7935. #define unlikely(x) (x)
  7936. #endif /* __GNUC__ */
  7937. """
  7938. else:
  7939. branch_prediction_macros = """
  7940. #define likely(x) (x)
  7941. #define unlikely(x) (x)
  7942. """
  7943. #------------------------------------------------------------------------------------
  7944. printing_utility_code = UtilityCode.load_cached("Print", "Printing.c")
  7945. printing_one_utility_code = UtilityCode.load_cached("PrintOne", "Printing.c")
  7946. #------------------------------------------------------------------------------------
  7947. # Exception raising code
  7948. #
  7949. # Exceptions are raised by __Pyx_Raise() and stored as plain
  7950. # type/value/tb in PyThreadState->curexc_*. When being caught by an
  7951. # 'except' statement, curexc_* is moved over to exc_* by
  7952. # __Pyx_GetException()
  7953. restore_exception_utility_code = UtilityCode.load_cached("PyErrFetchRestore", "Exceptions.c")
  7954. raise_utility_code = UtilityCode.load_cached("RaiseException", "Exceptions.c")
  7955. get_exception_utility_code = UtilityCode.load_cached("GetException", "Exceptions.c")
  7956. swap_exception_utility_code = UtilityCode.load_cached("SwapException", "Exceptions.c")
  7957. reset_exception_utility_code = UtilityCode.load_cached("SaveResetException", "Exceptions.c")
  7958. traceback_utility_code = UtilityCode.load_cached("AddTraceback", "Exceptions.c")
  7959. #------------------------------------------------------------------------------------
  7960. get_exception_tuple_utility_code = UtilityCode(
  7961. proto="""
  7962. static PyObject *__Pyx_GetExceptionTuple(PyThreadState *__pyx_tstate); /*proto*/
  7963. """,
  7964. # I doubt that calling __Pyx_GetException() here is correct as it moves
  7965. # the exception from tstate->curexc_* to tstate->exc_*, which prevents
  7966. # exception handlers later on from receiving it.
  7967. # NOTE: "__pyx_tstate" may be used by __Pyx_GetException() macro
  7968. impl = """
  7969. static PyObject *__Pyx_GetExceptionTuple(CYTHON_UNUSED PyThreadState *__pyx_tstate) {
  7970. PyObject *type = NULL, *value = NULL, *tb = NULL;
  7971. if (__Pyx_GetException(&type, &value, &tb) == 0) {
  7972. PyObject* exc_info = PyTuple_New(3);
  7973. if (exc_info) {
  7974. Py_INCREF(type);
  7975. Py_INCREF(value);
  7976. Py_INCREF(tb);
  7977. PyTuple_SET_ITEM(exc_info, 0, type);
  7978. PyTuple_SET_ITEM(exc_info, 1, value);
  7979. PyTuple_SET_ITEM(exc_info, 2, tb);
  7980. return exc_info;
  7981. }
  7982. }
  7983. return NULL;
  7984. }
  7985. """,
  7986. requires=[get_exception_utility_code])