Deparse.pm 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295
  1. # B::Deparse.pm
  2. # Copyright (c) 1998-2000, 2002, 2003, 2004, 2005, 2006 Stephen McCamant.
  3. # All rights reserved.
  4. # This module is free software; you can redistribute and/or modify
  5. # it under the same terms as Perl itself.
  6. # This is based on the module of the same name by Malcolm Beattie,
  7. # but essentially none of his code remains.
  8. package B::Deparse;
  9. use Carp;
  10. use B qw(class main_root main_start main_cv svref_2object opnumber perlstring
  11. OPf_WANT OPf_WANT_VOID OPf_WANT_SCALAR OPf_WANT_LIST
  12. OPf_KIDS OPf_REF OPf_STACKED OPf_SPECIAL OPf_MOD OPf_PARENS
  13. OPpLVAL_INTRO OPpOUR_INTRO OPpENTERSUB_AMPER OPpSLICE OPpCONST_BARE
  14. OPpTRANS_SQUASH OPpTRANS_DELETE OPpTRANS_COMPLEMENT OPpTARGET_MY
  15. OPpEXISTS_SUB OPpSORT_NUMERIC OPpSORT_INTEGER OPpREPEAT_DOLIST
  16. OPpSORT_REVERSE OPpMULTIDEREF_EXISTS OPpMULTIDEREF_DELETE
  17. SVf_IOK SVf_NOK SVf_ROK SVf_POK SVpad_OUR SVf_FAKE SVs_RMG SVs_SMG
  18. SVs_PADTMP SVpad_TYPED
  19. CVf_METHOD CVf_LVALUE
  20. PMf_KEEP PMf_GLOBAL PMf_CONTINUE PMf_EVAL PMf_ONCE
  21. PMf_MULTILINE PMf_SINGLELINE PMf_FOLD PMf_EXTENDED PMf_EXTENDED_MORE
  22. PADNAMEt_OUTER
  23. MDEREF_reload
  24. MDEREF_AV_pop_rv2av_aelem
  25. MDEREF_AV_gvsv_vivify_rv2av_aelem
  26. MDEREF_AV_padsv_vivify_rv2av_aelem
  27. MDEREF_AV_vivify_rv2av_aelem
  28. MDEREF_AV_padav_aelem
  29. MDEREF_AV_gvav_aelem
  30. MDEREF_HV_pop_rv2hv_helem
  31. MDEREF_HV_gvsv_vivify_rv2hv_helem
  32. MDEREF_HV_padsv_vivify_rv2hv_helem
  33. MDEREF_HV_vivify_rv2hv_helem
  34. MDEREF_HV_padhv_helem
  35. MDEREF_HV_gvhv_helem
  36. MDEREF_ACTION_MASK
  37. MDEREF_INDEX_none
  38. MDEREF_INDEX_const
  39. MDEREF_INDEX_padsv
  40. MDEREF_INDEX_gvsv
  41. MDEREF_INDEX_MASK
  42. MDEREF_FLAG_last
  43. MDEREF_MASK
  44. MDEREF_SHIFT
  45. );
  46. $VERSION = '1.35';
  47. use strict;
  48. use vars qw/$AUTOLOAD/;
  49. use warnings ();
  50. require feature;
  51. BEGIN {
  52. # List version-specific constants here.
  53. # Easiest way to keep this code portable between version looks to
  54. # be to fake up a dummy constant that will never actually be true.
  55. foreach (qw(OPpSORT_INPLACE OPpSORT_DESCEND OPpITER_REVERSED OPpCONST_NOVER
  56. OPpPAD_STATE PMf_SKIPWHITE RXf_SKIPWHITE
  57. RXf_PMf_CHARSET RXf_PMf_KEEPCOPY CVf_ANONCONST
  58. CVf_LOCKED OPpREVERSE_INPLACE OPpSUBSTR_REPL_FIRST
  59. PMf_NONDESTRUCT OPpCONST_ARYBASE OPpEVAL_BYTES
  60. OPpLVREF_TYPE OPpLVREF_SV OPpLVREF_AV OPpLVREF_HV
  61. OPpLVREF_CV OPpLVREF_ELEM SVpad_STATE)) {
  62. eval { import B $_ };
  63. no strict 'refs';
  64. *{$_} = sub () {0} unless *{$_}{CODE};
  65. }
  66. }
  67. # Changes between 0.50 and 0.51:
  68. # - fixed nulled leave with live enter in sort { }
  69. # - fixed reference constants (\"str")
  70. # - handle empty programs gracefully
  71. # - handle infinite loops (for (;;) {}, while (1) {})
  72. # - differentiate between 'for my $x ...' and 'my $x; for $x ...'
  73. # - various minor cleanups
  74. # - moved globals into an object
  75. # - added '-u', like B::C
  76. # - package declarations using cop_stash
  77. # - subs, formats and code sorted by cop_seq
  78. # Changes between 0.51 and 0.52:
  79. # - added pp_threadsv (special variables under USE_5005THREADS)
  80. # - added documentation
  81. # Changes between 0.52 and 0.53:
  82. # - many changes adding precedence contexts and associativity
  83. # - added '-p' and '-s' output style options
  84. # - various other minor fixes
  85. # Changes between 0.53 and 0.54:
  86. # - added support for new 'for (1..100)' optimization,
  87. # thanks to Gisle Aas
  88. # Changes between 0.54 and 0.55:
  89. # - added support for new qr// construct
  90. # - added support for new pp_regcreset OP
  91. # Changes between 0.55 and 0.56:
  92. # - tested on base/*.t, cmd/*.t, comp/*.t, io/*.t
  93. # - fixed $# on non-lexicals broken in last big rewrite
  94. # - added temporary fix for change in opcode of OP_STRINGIFY
  95. # - fixed problem in 0.54's for() patch in 'for (@ary)'
  96. # - fixed precedence in conditional of ?:
  97. # - tweaked list paren elimination in 'my($x) = @_'
  98. # - made continue-block detection trickier wrt. null ops
  99. # - fixed various prototype problems in pp_entersub
  100. # - added support for sub prototypes that never get GVs
  101. # - added unquoting for special filehandle first arg in truncate
  102. # - print doubled rv2gv (a bug) as '*{*GV}' instead of illegal '**GV'
  103. # - added semicolons at the ends of blocks
  104. # - added -l '#line' declaration option -- fixes cmd/subval.t 27,28
  105. # Changes between 0.56 and 0.561:
  106. # - fixed multiply-declared my var in pp_truncate (thanks to Sarathy)
  107. # - used new B.pm symbolic constants (done by Nick Ing-Simmons)
  108. # Changes between 0.561 and 0.57:
  109. # - stylistic changes to symbolic constant stuff
  110. # - handled scope in s///e replacement code
  111. # - added unquote option for expanding "" into concats, etc.
  112. # - split method and proto parts of pp_entersub into separate functions
  113. # - various minor cleanups
  114. # Changes after 0.57:
  115. # - added parens in \&foo (patch by Albert Dvornik)
  116. # Changes between 0.57 and 0.58:
  117. # - fixed '0' statements that weren't being printed
  118. # - added methods for use from other programs
  119. # (based on patches from James Duncan and Hugo van der Sanden)
  120. # - added -si and -sT to control indenting (also based on a patch from Hugo)
  121. # - added -sv to print something else instead of '???'
  122. # - preliminary version of utf8 tr/// handling
  123. # Changes after 0.58:
  124. # - uses of $op->ppaddr changed to new $op->name (done by Sarathy)
  125. # - added support for Hugo's new OP_SETSTATE (like nextstate)
  126. # Changes between 0.58 and 0.59
  127. # - added support for Chip's OP_METHOD_NAMED
  128. # - added support for Ilya's OPpTARGET_MY optimization
  129. # - elided arrows before '()' subscripts when possible
  130. # Changes between 0.59 and 0.60
  131. # - support for method attributes was added
  132. # - some warnings fixed
  133. # - separate recognition of constant subs
  134. # - rewrote continue block handling, now recognizing for loops
  135. # - added more control of expanding control structures
  136. # Changes between 0.60 and 0.61 (mostly by Robin Houston)
  137. # - many bug-fixes
  138. # - support for pragmas and 'use'
  139. # - support for the little-used $[ variable
  140. # - support for __DATA__ sections
  141. # - UTF8 support
  142. # - BEGIN, CHECK, INIT and END blocks
  143. # - scoping of subroutine declarations fixed
  144. # - compile-time output from the input program can be suppressed, so that the
  145. # output is just the deparsed code. (a change to O.pm in fact)
  146. # - our() declarations
  147. # - *all* the known bugs are now listed in the BUGS section
  148. # - comprehensive test mechanism (TEST -deparse)
  149. # Changes between 0.62 and 0.63 (mostly by Rafael Garcia-Suarez)
  150. # - bug-fixes
  151. # - new switch -P
  152. # - support for command-line switches (-l, -0, etc.)
  153. # Changes between 0.63 and 0.64
  154. # - support for //, CHECK blocks, and assertions
  155. # - improved handling of foreach loops and lexicals
  156. # - option to use Data::Dumper for constants
  157. # - more bug fixes
  158. # - discovered lots more bugs not yet fixed
  159. #
  160. # ...
  161. #
  162. # Changes between 0.72 and 0.73
  163. # - support new switch constructs
  164. # Todo:
  165. # (See also BUGS section at the end of this file)
  166. #
  167. # - finish tr/// changes
  168. # - add option for even more parens (generalize \&foo change)
  169. # - left/right context
  170. # - copy comments (look at real text with $^P?)
  171. # - avoid semis in one-statement blocks
  172. # - associativity of &&=, ||=, ?:
  173. # - ',' => '=>' (auto-unquote?)
  174. # - break long lines ("\r" as discretionary break?)
  175. # - configurable syntax highlighting: ANSI color, HTML, TeX, etc.
  176. # - more style options: brace style, hex vs. octal, quotes, ...
  177. # - print big ints as hex/octal instead of decimal (heuristic?)
  178. # - handle 'my $x if 0'?
  179. # - version using op_next instead of op_first/sibling?
  180. # - avoid string copies (pass arrays, one big join?)
  181. # - here-docs?
  182. # Current test.deparse failures
  183. # comp/hints 6 - location of BEGIN blocks wrt. block openings
  184. # run/switchI 1 - missing -I switches entirely
  185. # perl -Ifoo -e 'print @INC'
  186. # op/caller 2 - warning mask propagates backwards before warnings::register
  187. # 'use warnings; BEGIN {${^WARNING_BITS} eq "U"x12;} use warnings::register'
  188. # op/getpid 2 - can't assign to shared my() declaration (threads only)
  189. # 'my $x : shared = 5'
  190. # op/override 7 - parens on overridden require change v-string interpretation
  191. # 'BEGIN{*CORE::GLOBAL::require=sub {}} require v5.6'
  192. # c.f. 'BEGIN { *f = sub {0} }; f 2'
  193. # op/pat 774 - losing Unicode-ness of Latin1-only strings
  194. # 'use charnames ":short"; $x="\N{latin:a with acute}"'
  195. # op/recurse 12 - missing parens on recursive call makes it look like method
  196. # 'sub f { f($x) }'
  197. # op/subst 90 - inconsistent handling of utf8 under "use utf8"
  198. # op/taint 29 - "use re 'taint'" deparsed in the wrong place wrt. block open
  199. # op/tiehandle compile - "use strict" deparsed in the wrong place
  200. # uni/tr_ several
  201. # ext/B/t/xref 11 - line numbers when we add newlines to one-line subs
  202. # ext/Data/Dumper/t/dumper compile
  203. # ext/DB_file/several
  204. # ext/Encode/several
  205. # ext/Ernno/Errno warnings
  206. # ext/IO/lib/IO/t/io_sel 23
  207. # ext/PerlIO/t/encoding compile
  208. # ext/POSIX/t/posix 6
  209. # ext/Socket/Socket 8
  210. # ext/Storable/t/croak compile
  211. # lib/Attribute/Handlers/t/multi compile
  212. # lib/bignum/ several
  213. # lib/charnames 35
  214. # lib/constant 32
  215. # lib/English 40
  216. # lib/ExtUtils/t/bytes 4
  217. # lib/File/DosGlob compile
  218. # lib/Filter/Simple/t/data 1
  219. # lib/Math/BigInt/t/constant 1
  220. # lib/Net/t/config Deparse-warning
  221. # lib/overload compile
  222. # lib/Switch/ several
  223. # lib/Symbol 4
  224. # lib/Test/Simple several
  225. # lib/Term/Complete
  226. # lib/Tie/File/t/29_downcopy 5
  227. # lib/vars 22
  228. # Object fields:
  229. #
  230. # in_coderef2text:
  231. # True when deparsing via $deparse->coderef2text; false when deparsing the
  232. # main program.
  233. #
  234. # avoid_local:
  235. # (local($a), local($b)) and local($a, $b) have the same internal
  236. # representation but the short form looks better. We notice we can
  237. # use a large-scale local when checking the list, but need to prevent
  238. # individual locals too. This hash holds the addresses of OPs that
  239. # have already had their local-ness accounted for. The same thing
  240. # is done with my().
  241. #
  242. # curcv:
  243. # CV for current sub (or main program) being deparsed
  244. #
  245. # curcvlex:
  246. # Cached hash of lexical variables for curcv: keys are
  247. # names prefixed with "m" or "o" (representing my/our), and
  248. # each value is an array with two elements indicating the cop_seq
  249. # of scopes in which a var of that name is valid and a third ele-
  250. # ment referencing the pad name.
  251. #
  252. # curcop:
  253. # COP for statement being deparsed
  254. #
  255. # curstash:
  256. # name of the current package for deparsed code
  257. #
  258. # subs_todo:
  259. # array of [cop_seq, CV, is_format?, name] for subs and formats we still
  260. # want to deparse. The fourth element is a pad name thingy for lexical
  261. # subs or a string for special blocks. For other subs, it is undef. For
  262. # lexical subs, CV may be undef, indicating a stub declaration.
  263. #
  264. # protos_todo:
  265. # as above, but [name, prototype] for subs that never got a GV
  266. #
  267. # subs_done, forms_done:
  268. # keys are addresses of GVs for subs and formats we've already
  269. # deparsed (or at least put into subs_todo)
  270. #
  271. # subs_declared
  272. # keys are names of subs for which we've printed declarations.
  273. # That means we can omit parentheses from the arguments. It also means we
  274. # need to put CORE:: on core functions of the same name.
  275. #
  276. # in_subst_repl
  277. # True when deparsing the replacement part of a substitution.
  278. #
  279. # in_refgen
  280. # True when deparsing the argument to \.
  281. #
  282. # parens: -p
  283. # linenums: -l
  284. # unquote: -q
  285. # cuddle: ' ' or '\n', depending on -sC
  286. # indent_size: -si
  287. # use_tabs: -sT
  288. # ex_const: -sv
  289. # A little explanation of how precedence contexts and associativity
  290. # work:
  291. #
  292. # deparse() calls each per-op subroutine with an argument $cx (short
  293. # for context, but not the same as the cx* in the perl core), which is
  294. # a number describing the op's parents in terms of precedence, whether
  295. # they're inside an expression or at statement level, etc. (see
  296. # chart below). When ops with children call deparse on them, they pass
  297. # along their precedence. Fractional values are used to implement
  298. # associativity ('($x + $y) + $z' => '$x + $y + $y') and related
  299. # parentheses hacks. The major disadvantage of this scheme is that
  300. # it doesn't know about right sides and left sides, so say if you
  301. # assign a listop to a variable, it can't tell it's allowed to leave
  302. # the parens off the listop.
  303. # Precedences:
  304. # 26 [TODO] inside interpolation context ("")
  305. # 25 left terms and list operators (leftward)
  306. # 24 left ->
  307. # 23 nonassoc ++ --
  308. # 22 right **
  309. # 21 right ! ~ \ and unary + and -
  310. # 20 left =~ !~
  311. # 19 left * / % x
  312. # 18 left + - .
  313. # 17 left << >>
  314. # 16 nonassoc named unary operators
  315. # 15 nonassoc < > <= >= lt gt le ge
  316. # 14 nonassoc == != <=> eq ne cmp
  317. # 13 left &
  318. # 12 left | ^
  319. # 11 left &&
  320. # 10 left ||
  321. # 9 nonassoc .. ...
  322. # 8 right ?:
  323. # 7 right = += -= *= etc.
  324. # 6 left , =>
  325. # 5 nonassoc list operators (rightward)
  326. # 4 right not
  327. # 3 left and
  328. # 2 left or xor
  329. # 1 statement modifiers
  330. # 0.5 statements, but still print scopes as do { ... }
  331. # 0 statement level
  332. # -1 format body
  333. # Nonprinting characters with special meaning:
  334. # \cS - steal parens (see maybe_parens_unop)
  335. # \n - newline and indent
  336. # \t - increase indent
  337. # \b - decrease indent ('outdent')
  338. # \f - flush left (no indent)
  339. # \cK - kill following semicolon, if any
  340. # Semicolon handling:
  341. # - Individual statements are not deparsed with trailing semicolons.
  342. # (If necessary, \cK is tacked on to the end.)
  343. # - Whatever code joins statements together or emits them (lineseq,
  344. # scopeop, deparse_root) is responsible for adding semicolons where
  345. # necessary.
  346. # - use statements are deparsed with trailing semicolons because they are
  347. # immediately concatenated with the following statement.
  348. # - indent() removes semicolons wherever it sees \cK.
  349. BEGIN { for (qw[ const stringify rv2sv list glob pushmark null aelem
  350. nextstate dbstate rv2av rv2hv helem custom ]) {
  351. eval "sub OP_\U$_ () { " . opnumber($_) . "}"
  352. }}
  353. # _pessimise_walk(): recursively walk the optree of a sub,
  354. # possibly undoing optimisations along the way.
  355. sub _pessimise_walk {
  356. my ($self, $startop) = @_;
  357. return unless $$startop;
  358. my ($op, $prevop);
  359. for ($op = $startop; $$op; $prevop = $op, $op = $op->sibling) {
  360. my $ppname = $op->name;
  361. # pessimisations start here
  362. if ($ppname eq "padrange") {
  363. # remove PADRANGE:
  364. # the original optimisation either (1) changed this:
  365. # pushmark -> (various pad and list and null ops) -> the_rest
  366. # or (2), for the = @_ case, changed this:
  367. # pushmark -> gv[_] -> rv2av -> (pad stuff) -> the_rest
  368. # into this:
  369. # padrange ----------------------------------------> the_rest
  370. # so we just need to convert the padrange back into a
  371. # pushmark, and in case (1), set its op_next to op_sibling,
  372. # which is the head of the original chain of optimised-away
  373. # pad ops, or for (2), set it to sibling->first, which is
  374. # the original gv[_].
  375. $B::overlay->{$$op} = {
  376. type => OP_PUSHMARK,
  377. name => 'pushmark',
  378. private => ($op->private & OPpLVAL_INTRO),
  379. };
  380. }
  381. # pessimisations end here
  382. if (class($op) eq 'PMOP'
  383. && ref($op->pmreplroot)
  384. && ${$op->pmreplroot}
  385. && $op->pmreplroot->isa( 'B::OP' ))
  386. {
  387. $self-> _pessimise_walk($op->pmreplroot);
  388. }
  389. if ($op->flags & OPf_KIDS) {
  390. $self-> _pessimise_walk($op->first);
  391. }
  392. }
  393. }
  394. # _pessimise_walk_exe(): recursively walk the op_next chain of a sub,
  395. # possibly undoing optimisations along the way.
  396. sub _pessimise_walk_exe {
  397. my ($self, $startop, $visited) = @_;
  398. return unless $$startop;
  399. return if $visited->{$$startop};
  400. my ($op, $prevop);
  401. for ($op = $startop; $$op; $prevop = $op, $op = $op->next) {
  402. last if $visited->{$$op};
  403. $visited->{$$op} = 1;
  404. my $ppname = $op->name;
  405. if ($ppname =~
  406. /^((and|d?or)(assign)?|(map|grep)while|range|cond_expr|once)$/
  407. # entertry is also a logop, but its op_other invariably points
  408. # into the same chain as the main execution path, so we skip it
  409. ) {
  410. $self->_pessimise_walk_exe($op->other, $visited);
  411. }
  412. elsif ($ppname eq "subst") {
  413. $self->_pessimise_walk_exe($op->pmreplstart, $visited);
  414. }
  415. elsif ($ppname =~ /^(enter(loop|iter))$/) {
  416. # redoop and nextop will already be covered by the main block
  417. # of the loop
  418. $self->_pessimise_walk_exe($op->lastop, $visited);
  419. }
  420. # pessimisations start here
  421. }
  422. }
  423. # Go through an optree and "remove" some optimisations by using an
  424. # overlay to selectively modify or un-null some ops. Deparsing in the
  425. # absence of those optimisations is then easier.
  426. #
  427. # Note that older optimisations are not removed, as Deparse was already
  428. # written to recognise them before the pessimise/overlay system was added.
  429. sub pessimise {
  430. my ($self, $root, $start) = @_;
  431. # walk tree in root-to-branch order
  432. $self->_pessimise_walk($root);
  433. my %visited;
  434. # walk tree in execution order
  435. $self->_pessimise_walk_exe($start, \%visited);
  436. }
  437. sub null {
  438. my $op = shift;
  439. return class($op) eq "NULL";
  440. }
  441. sub todo {
  442. my $self = shift;
  443. my($cv, $is_form, $name) = @_;
  444. my $cvfile = $cv->FILE//'';
  445. return unless ($cvfile eq $0 || exists $self->{files}{$cvfile});
  446. my $seq;
  447. if ($cv->OUTSIDE_SEQ) {
  448. $seq = $cv->OUTSIDE_SEQ;
  449. } elsif (!null($cv->START) and is_state($cv->START)) {
  450. $seq = $cv->START->cop_seq;
  451. } else {
  452. $seq = 0;
  453. }
  454. push @{$self->{'subs_todo'}}, [$seq, $cv, $is_form, $name];
  455. }
  456. sub next_todo {
  457. my $self = shift;
  458. my $ent = shift @{$self->{'subs_todo'}};
  459. my $cv = $ent->[1];
  460. if (ref $ent->[3]) { # lexical sub
  461. my @text;
  462. # At this point, we may not yet have deparsed the hints that allow
  463. # lexical subroutines to be recognized. So adjust the current
  464. # hints and deparse them.
  465. # When lex subs cease being experimental, we should be able to
  466. # remove this code.
  467. {
  468. local $^H = $self->{'hints'};
  469. local %^H = %{ $self->{'hinthash'} || {} };
  470. local ${^WARNING_BITS} = $self->{'warnings'};
  471. feature->import("lexical_subs");
  472. warnings->unimport("experimental::lexical_subs");
  473. # Here we depend on the fact that individual features
  474. # will always set the feature bundle to ‘custom’
  475. # (== $feature::hint_mask). If we had another specific bundle
  476. # enabled previously, normalise it.
  477. if (($self->{'hints'} & $feature::hint_mask)
  478. != $feature::hint_mask)
  479. {
  480. if ($self->{'hinthash'}) {
  481. delete $self->{'hinthash'}{$_}
  482. for grep /^feature_/, keys %{$self->{'hinthash'}};
  483. }
  484. else { $self->{'hinthash'} = {} }
  485. $self->{'hinthash'}
  486. = _features_from_bundle(@$self{'hints','hinthash'});
  487. }
  488. push @text, $self->declare_hinthash($self->{'hinthash'}, \%^H,
  489. $self->{indent_size}, $^H);
  490. push @text, $self->declare_warnings($self->{'warnings'},
  491. ${^WARNING_BITS})
  492. unless ($self->{'warnings'} // 'u')
  493. eq (${^WARNING_BITS } // 'u');
  494. $self->{'warnings'} = ${^WARNING_BITS};
  495. $self->{'hints'} = $^H;
  496. $self->{'hinthash'} = {%^H};
  497. }
  498. # Now emit the sub itself.
  499. my $padname = $ent->[3];
  500. my $flags = $padname->FLAGS;
  501. push @text,
  502. !$cv || $ent->[0] <= $padname->COP_SEQ_RANGE_LOW
  503. ? $self->keyword($flags & SVpad_OUR
  504. ? "our"
  505. : $flags & SVpad_STATE
  506. ? "state"
  507. : "my") . " "
  508. : "";
  509. # XXX We would do $self->keyword("sub"), but ‘my CORE::sub’
  510. # doesn’t work and ‘my sub’ ignores a &sub in scope. I.e.,
  511. # we have a core bug here.
  512. push @text, "sub " . substr $padname->PVX, 1;
  513. if ($cv) {
  514. # my sub foo { }
  515. push @text, " " . $self->deparse_sub($cv);
  516. $text[-1] =~ s/ ;$/;/;
  517. }
  518. else {
  519. # my sub foo;
  520. push @text, ";\n";
  521. }
  522. return join "", @text;
  523. }
  524. my $gv = $cv->GV;
  525. my $name = $ent->[3] // $self->gv_name($gv);
  526. if ($ent->[2]) {
  527. return $self->keyword("format") . " $name =\n"
  528. . $self->deparse_format($ent->[1]). "\n";
  529. } else {
  530. my $use_dec;
  531. if ($name eq "BEGIN") {
  532. $use_dec = $self->begin_is_use($cv);
  533. if (defined ($use_dec) and $self->{'expand'} < 5) {
  534. return () if 0 == length($use_dec);
  535. $use_dec =~ s/^(use|no)\b/$self->keyword($1)/e;
  536. }
  537. }
  538. my $l = '';
  539. if ($self->{'linenums'}) {
  540. my $line = $gv->LINE;
  541. my $file = $gv->FILE;
  542. $l = "\n\f#line $line \"$file\"\n";
  543. }
  544. my $p = '';
  545. my $stash;
  546. if (class($cv->STASH) ne "SPECIAL") {
  547. $stash = $cv->STASH->NAME;
  548. if ($stash ne $self->{'curstash'}) {
  549. $p = $self->keyword("package") . " $stash;\n";
  550. $name = "$self->{'curstash'}::$name" unless $name =~ /::/;
  551. $self->{'curstash'} = $stash;
  552. }
  553. }
  554. if ($use_dec) {
  555. return "$p$l$use_dec";
  556. }
  557. if ( $name !~ /::/ and $self->lex_in_scope("&$name")
  558. || $self->lex_in_scope("&$name", 1) )
  559. {
  560. $name = "$self->{'curstash'}::$name";
  561. } elsif (defined $stash) {
  562. $name =~ s/^\Q$stash\E::(?!\z|.*::)//;
  563. }
  564. my $ret = "${p}${l}" . $self->keyword("sub") . " $name "
  565. . $self->deparse_sub($cv);
  566. $self->{'subs_declared'}{$name} = 1;
  567. return $ret;
  568. }
  569. }
  570. # Return a "use" declaration for this BEGIN block, if appropriate
  571. sub begin_is_use {
  572. my ($self, $cv) = @_;
  573. my $root = $cv->ROOT;
  574. local @$self{qw'curcv curcvlex'} = ($cv);
  575. local $B::overlay = {};
  576. $self->pessimise($root, $cv->START);
  577. #require B::Debug;
  578. #B::walkoptree($cv->ROOT, "debug");
  579. my $lineseq = $root->first;
  580. return if $lineseq->name ne "lineseq";
  581. my $req_op = $lineseq->first->sibling;
  582. return if $req_op->name ne "require";
  583. my $module;
  584. if ($req_op->first->private & OPpCONST_BARE) {
  585. # Actually it should always be a bareword
  586. $module = $self->const_sv($req_op->first)->PV;
  587. $module =~ s[/][::]g;
  588. $module =~ s/.pm$//;
  589. }
  590. else {
  591. $module = $self->const($self->const_sv($req_op->first), 6);
  592. }
  593. my $version;
  594. my $version_op = $req_op->sibling;
  595. return if class($version_op) eq "NULL";
  596. if ($version_op->name eq "lineseq") {
  597. # We have a version parameter; skip nextstate & pushmark
  598. my $constop = $version_op->first->next->next;
  599. return unless $self->const_sv($constop)->PV eq $module;
  600. $constop = $constop->sibling;
  601. $version = $self->const_sv($constop);
  602. if (class($version) eq "IV") {
  603. $version = $version->int_value;
  604. } elsif (class($version) eq "NV") {
  605. $version = $version->NV;
  606. } elsif (class($version) ne "PVMG") {
  607. # Includes PVIV and PVNV
  608. $version = $version->PV;
  609. } else {
  610. # version specified as a v-string
  611. $version = 'v'.join '.', map ord, split //, $version->PV;
  612. }
  613. $constop = $constop->sibling;
  614. return if $constop->name ne "method_named";
  615. return if $self->meth_sv($constop)->PV ne "VERSION";
  616. }
  617. $lineseq = $version_op->sibling;
  618. return if $lineseq->name ne "lineseq";
  619. my $entersub = $lineseq->first->sibling;
  620. if ($entersub->name eq "stub") {
  621. return "use $module $version ();\n" if defined $version;
  622. return "use $module ();\n";
  623. }
  624. return if $entersub->name ne "entersub";
  625. # See if there are import arguments
  626. my $args = '';
  627. my $svop = $entersub->first->sibling; # Skip over pushmark
  628. return unless $self->const_sv($svop)->PV eq $module;
  629. # Pull out the arguments
  630. for ($svop=$svop->sibling; index($svop->name, "method_") != 0;
  631. $svop = $svop->sibling) {
  632. $args .= ", " if length($args);
  633. $args .= $self->deparse($svop, 6);
  634. }
  635. my $use = 'use';
  636. my $method_named = $svop;
  637. return if $method_named->name ne "method_named";
  638. my $method_name = $self->meth_sv($method_named)->PV;
  639. if ($method_name eq "unimport") {
  640. $use = 'no';
  641. }
  642. # Certain pragmas are dealt with using hint bits,
  643. # so we ignore them here
  644. if ($module eq 'strict' || $module eq 'integer'
  645. || $module eq 'bytes' || $module eq 'warnings'
  646. || $module eq 'feature') {
  647. return "";
  648. }
  649. if (defined $version && length $args) {
  650. return "$use $module $version ($args);\n";
  651. } elsif (defined $version) {
  652. return "$use $module $version;\n";
  653. } elsif (length $args) {
  654. return "$use $module ($args);\n";
  655. } else {
  656. return "$use $module;\n";
  657. }
  658. }
  659. sub stash_subs {
  660. my ($self, $pack, $seen) = @_;
  661. my (@ret, $stash);
  662. if (!defined $pack) {
  663. $pack = '';
  664. $stash = \%::;
  665. }
  666. else {
  667. $pack =~ s/(::)?$/::/;
  668. no strict 'refs';
  669. $stash = \%{"main::$pack"};
  670. }
  671. return
  672. if ($seen ||= {})->{
  673. $INC{"overload.pm"} ? overload::StrVal($stash) : $stash
  674. }++;
  675. my %stash = svref_2object($stash)->ARRAY;
  676. while (my ($key, $val) = each %stash) {
  677. my $flags = $val->FLAGS;
  678. if ($flags & SVf_ROK) {
  679. # A reference. Dump this if it is a reference to a CV. If it
  680. # is a constant acting as a proxy for a full subroutine, then
  681. # we may or may not have to dump it. If some form of perl-
  682. # space visible code must have created it, be it a use
  683. # statement, or some direct symbol-table manipulation code that
  684. # we will deparse, then we don’t want to dump it. If it is the
  685. # result of a declaration like sub f () { 42 } then we *do*
  686. # want to dump it. The only way to distinguish these seems
  687. # to be the SVs_PADTMP flag on the constant, which is admit-
  688. # tedly a hack.
  689. my $class = class(my $referent = $val->RV);
  690. if ($class eq "CV") {
  691. $self->todo($referent, 0);
  692. } elsif (
  693. $class !~ /^(AV|HV|CV|FM|IO|SPECIAL)\z/
  694. # A more robust way to write that would be this, but B does
  695. # not provide the SVt_ constants:
  696. # ($referent->FLAGS & B::SVTYPEMASK) < B::SVt_PVAV
  697. and $referent->FLAGS & SVs_PADTMP
  698. ) {
  699. push @{$self->{'protos_todo'}}, [$pack . $key, $val];
  700. }
  701. } elsif ($flags & (SVf_POK|SVf_IOK)) {
  702. # Just a prototype. As an ugly but fairly effective way
  703. # to find out if it belongs here is to see if the AUTOLOAD
  704. # (if any) for the stash was defined in one of our files.
  705. my $A = $stash{"AUTOLOAD"};
  706. if (defined ($A) && class($A) eq "GV" && defined($A->CV)
  707. && class($A->CV) eq "CV") {
  708. my $AF = $A->FILE;
  709. next unless $AF eq $0 || exists $self->{'files'}{$AF};
  710. }
  711. push @{$self->{'protos_todo'}},
  712. [$pack . $key, $flags & SVf_POK ? $val->PV: undef];
  713. } elsif (class($val) eq "GV") {
  714. if (class(my $cv = $val->CV) ne "SPECIAL") {
  715. next if $self->{'subs_done'}{$$val}++;
  716. next if $$val != ${$cv->GV}; # Ignore imposters
  717. $self->todo($cv, 0);
  718. }
  719. if (class(my $cv = $val->FORM) ne "SPECIAL") {
  720. next if $self->{'forms_done'}{$$val}++;
  721. next if $$val != ${$cv->GV}; # Ignore imposters
  722. $self->todo($cv, 1);
  723. }
  724. if (class($val->HV) ne "SPECIAL" && $key =~ /::$/) {
  725. $self->stash_subs($pack . $key, $seen);
  726. }
  727. }
  728. }
  729. }
  730. sub print_protos {
  731. my $self = shift;
  732. my $ar;
  733. my @ret;
  734. foreach $ar (@{$self->{'protos_todo'}}) {
  735. my $body = defined $ar->[1]
  736. ? ref $ar->[1]
  737. ? " () {\n " . $self->const($ar->[1]->RV,0) . ";\n}"
  738. : " (". $ar->[1] . ");"
  739. : ";";
  740. push @ret, "sub " . $ar->[0] . "$body\n";
  741. }
  742. delete $self->{'protos_todo'};
  743. return @ret;
  744. }
  745. sub style_opts {
  746. my $self = shift;
  747. my $opts = shift;
  748. my $opt;
  749. while (length($opt = substr($opts, 0, 1))) {
  750. if ($opt eq "C") {
  751. $self->{'cuddle'} = " ";
  752. $opts = substr($opts, 1);
  753. } elsif ($opt eq "i") {
  754. $opts =~ s/^i(\d+)//;
  755. $self->{'indent_size'} = $1;
  756. } elsif ($opt eq "T") {
  757. $self->{'use_tabs'} = 1;
  758. $opts = substr($opts, 1);
  759. } elsif ($opt eq "v") {
  760. $opts =~ s/^v([^.]*)(.|$)//;
  761. $self->{'ex_const'} = $1;
  762. }
  763. }
  764. }
  765. sub new {
  766. my $class = shift;
  767. my $self = bless {}, $class;
  768. $self->{'cuddle'} = "\n";
  769. $self->{'curcop'} = undef;
  770. $self->{'curstash'} = "main";
  771. $self->{'ex_const'} = "'???'";
  772. $self->{'expand'} = 0;
  773. $self->{'files'} = {};
  774. $self->{'indent_size'} = 4;
  775. $self->{'linenums'} = 0;
  776. $self->{'parens'} = 0;
  777. $self->{'subs_todo'} = [];
  778. $self->{'unquote'} = 0;
  779. $self->{'use_dumper'} = 0;
  780. $self->{'use_tabs'} = 0;
  781. $self->{'ambient_arybase'} = 0;
  782. $self->{'ambient_warnings'} = undef; # Assume no lexical warnings
  783. $self->{'ambient_hints'} = 0;
  784. $self->{'ambient_hinthash'} = undef;
  785. $self->init();
  786. while (my $arg = shift @_) {
  787. if ($arg eq "-d") {
  788. $self->{'use_dumper'} = 1;
  789. require Data::Dumper;
  790. } elsif ($arg =~ /^-f(.*)/) {
  791. $self->{'files'}{$1} = 1;
  792. } elsif ($arg eq "-l") {
  793. $self->{'linenums'} = 1;
  794. } elsif ($arg eq "-p") {
  795. $self->{'parens'} = 1;
  796. } elsif ($arg eq "-P") {
  797. $self->{'noproto'} = 1;
  798. } elsif ($arg eq "-q") {
  799. $self->{'unquote'} = 1;
  800. } elsif (substr($arg, 0, 2) eq "-s") {
  801. $self->style_opts(substr $arg, 2);
  802. } elsif ($arg =~ /^-x(\d)$/) {
  803. $self->{'expand'} = $1;
  804. }
  805. }
  806. return $self;
  807. }
  808. {
  809. # Mask out the bits that L<warnings::register> uses
  810. my $WARN_MASK;
  811. BEGIN {
  812. $WARN_MASK = $warnings::Bits{all} | $warnings::DeadBits{all};
  813. }
  814. sub WARN_MASK () {
  815. return $WARN_MASK;
  816. }
  817. }
  818. # Initialise the contextual information, either from
  819. # defaults provided with the ambient_pragmas method,
  820. # or from perl's own defaults otherwise.
  821. sub init {
  822. my $self = shift;
  823. $self->{'arybase'} = $self->{'ambient_arybase'};
  824. $self->{'warnings'} = defined ($self->{'ambient_warnings'})
  825. ? $self->{'ambient_warnings'} & WARN_MASK
  826. : undef;
  827. $self->{'hints'} = $self->{'ambient_hints'};
  828. $self->{'hints'} &= 0xFF if $] < 5.009;
  829. $self->{'hinthash'} = $self->{'ambient_hinthash'};
  830. # also a convenient place to clear out subs_declared
  831. delete $self->{'subs_declared'};
  832. }
  833. sub compile {
  834. my(@args) = @_;
  835. return sub {
  836. my $self = B::Deparse->new(@args);
  837. # First deparse command-line args
  838. if (defined $^I) { # deparse -i
  839. print q(BEGIN { $^I = ).perlstring($^I).qq(; }\n);
  840. }
  841. if ($^W) { # deparse -w
  842. print qq(BEGIN { \$^W = $^W; }\n);
  843. }
  844. if ($/ ne "\n" or defined $O::savebackslash) { # deparse -l and -0
  845. my $fs = perlstring($/) || 'undef';
  846. my $bs = perlstring($O::savebackslash) || 'undef';
  847. print qq(BEGIN { \$/ = $fs; \$\\ = $bs; }\n);
  848. }
  849. my @BEGINs = B::begin_av->isa("B::AV") ? B::begin_av->ARRAY : ();
  850. my @UNITCHECKs = B::unitcheck_av->isa("B::AV")
  851. ? B::unitcheck_av->ARRAY
  852. : ();
  853. my @CHECKs = B::check_av->isa("B::AV") ? B::check_av->ARRAY : ();
  854. my @INITs = B::init_av->isa("B::AV") ? B::init_av->ARRAY : ();
  855. my @ENDs = B::end_av->isa("B::AV") ? B::end_av->ARRAY : ();
  856. my @names = qw(BEGIN UNITCHECK CHECK INIT END);
  857. my @blocks = \(@BEGINs, @UNITCHECKs, @CHECKs, @INITs, @ENDs);
  858. while (@names) {
  859. my ($name, $blocks) = (shift @names, shift @blocks);
  860. for my $block (@$blocks) {
  861. $self->todo($block, 0, $name);
  862. }
  863. }
  864. $self->stash_subs();
  865. local($SIG{"__DIE__"}) =
  866. sub {
  867. if ($self->{'curcop'}) {
  868. my $cop = $self->{'curcop'};
  869. my($line, $file) = ($cop->line, $cop->file);
  870. print STDERR "While deparsing $file near line $line,\n";
  871. }
  872. };
  873. $self->{'curcv'} = main_cv;
  874. $self->{'curcvlex'} = undef;
  875. print $self->print_protos;
  876. @{$self->{'subs_todo'}} =
  877. sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}};
  878. my $root = main_root;
  879. local $B::overlay = {};
  880. unless (null $root) {
  881. $self->pad_subs($self->{'curcv'});
  882. # Check for a stub-followed-by-ex-cop, resulting from a program
  883. # consisting solely of sub declarations. For backward-compati-
  884. # bility (and sane output) we don’t want to emit the stub.
  885. # leave
  886. # enter
  887. # stub
  888. # ex-nextstate (or ex-dbstate)
  889. my $kid;
  890. if ( $root->name eq 'leave'
  891. and ($kid = $root->first)->name eq 'enter'
  892. and !null($kid = $kid->sibling) and $kid->name eq 'stub'
  893. and !null($kid = $kid->sibling) and $kid->name eq 'null'
  894. and class($kid) eq 'COP' and null $kid->sibling )
  895. {
  896. # ignore
  897. } else {
  898. $self->pessimise($root, main_start);
  899. print $self->indent($self->deparse_root($root)), "\n";
  900. }
  901. }
  902. my @text;
  903. while (scalar(@{$self->{'subs_todo'}})) {
  904. push @text, $self->next_todo;
  905. }
  906. print $self->indent(join("", @text)), "\n" if @text;
  907. # Print __DATA__ section, if necessary
  908. no strict 'refs';
  909. my $laststash = defined $self->{'curcop'}
  910. ? $self->{'curcop'}->stash->NAME : $self->{'curstash'};
  911. if (defined *{$laststash."::DATA"}{IO}) {
  912. print $self->keyword("package") . " $laststash;\n"
  913. unless $laststash eq $self->{'curstash'};
  914. print $self->keyword("__DATA__") . "\n";
  915. print readline(*{$laststash."::DATA"});
  916. }
  917. }
  918. }
  919. sub coderef2text {
  920. my $self = shift;
  921. my $sub = shift;
  922. croak "Usage: ->coderef2text(CODEREF)" unless UNIVERSAL::isa($sub, "CODE");
  923. $self->init();
  924. local $self->{in_coderef2text} = 1;
  925. return $self->indent($self->deparse_sub(svref_2object($sub)));
  926. }
  927. my %strict_bits = do {
  928. local $^H;
  929. map +($_ => strict::bits($_)), qw/refs subs vars/
  930. };
  931. sub ambient_pragmas {
  932. my $self = shift;
  933. my ($arybase, $hint_bits, $warning_bits, $hinthash) = (0, 0);
  934. while (@_ > 1) {
  935. my $name = shift();
  936. my $val = shift();
  937. if ($name eq 'strict') {
  938. require strict;
  939. if ($val eq 'none') {
  940. $hint_bits &= $strict_bits{$_} for qw/refs subs vars/;
  941. next();
  942. }
  943. my @names;
  944. if ($val eq "all") {
  945. @names = qw/refs subs vars/;
  946. }
  947. elsif (ref $val) {
  948. @names = @$val;
  949. }
  950. else {
  951. @names = split' ', $val;
  952. }
  953. $hint_bits |= $strict_bits{$_} for @names;
  954. }
  955. elsif ($name eq '$[') {
  956. if (OPpCONST_ARYBASE) {
  957. $arybase = $val;
  958. } else {
  959. croak "\$[ can't be non-zero on this perl" unless $val == 0;
  960. }
  961. }
  962. elsif ($name eq 'integer'
  963. || $name eq 'bytes'
  964. || $name eq 'utf8') {
  965. require "$name.pm";
  966. if ($val) {
  967. $hint_bits |= ${$::{"${name}::"}{"hint_bits"}};
  968. }
  969. else {
  970. $hint_bits &= ~${$::{"${name}::"}{"hint_bits"}};
  971. }
  972. }
  973. elsif ($name eq 're') {
  974. require re;
  975. if ($val eq 'none') {
  976. $hint_bits &= ~re::bits(qw/taint eval/);
  977. next();
  978. }
  979. my @names;
  980. if ($val eq 'all') {
  981. @names = qw/taint eval/;
  982. }
  983. elsif (ref $val) {
  984. @names = @$val;
  985. }
  986. else {
  987. @names = split' ',$val;
  988. }
  989. $hint_bits |= re::bits(@names);
  990. }
  991. elsif ($name eq 'warnings') {
  992. if ($val eq 'none') {
  993. $warning_bits = $warnings::NONE;
  994. next();
  995. }
  996. my @names;
  997. if (ref $val) {
  998. @names = @$val;
  999. }
  1000. else {
  1001. @names = split/\s+/, $val;
  1002. }
  1003. $warning_bits = $warnings::NONE if !defined ($warning_bits);
  1004. $warning_bits |= warnings::bits(@names);
  1005. }
  1006. elsif ($name eq 'warning_bits') {
  1007. $warning_bits = $val;
  1008. }
  1009. elsif ($name eq 'hint_bits') {
  1010. $hint_bits = $val;
  1011. }
  1012. elsif ($name eq '%^H') {
  1013. $hinthash = $val;
  1014. }
  1015. else {
  1016. croak "Unknown pragma type: $name";
  1017. }
  1018. }
  1019. if (@_) {
  1020. croak "The ambient_pragmas method expects an even number of args";
  1021. }
  1022. $self->{'ambient_arybase'} = $arybase;
  1023. $self->{'ambient_warnings'} = $warning_bits;
  1024. $self->{'ambient_hints'} = $hint_bits;
  1025. $self->{'ambient_hinthash'} = $hinthash;
  1026. }
  1027. # This method is the inner loop, so try to keep it simple
  1028. sub deparse {
  1029. my $self = shift;
  1030. my($op, $cx) = @_;
  1031. Carp::confess("Null op in deparse") if !defined($op)
  1032. || class($op) eq "NULL";
  1033. my $meth = "pp_" . $op->name;
  1034. return $self->$meth($op, $cx);
  1035. }
  1036. sub indent {
  1037. my $self = shift;
  1038. my $txt = shift;
  1039. # \cK also swallows a preceding line break when followed by a
  1040. # semicolon.
  1041. $txt =~ s/\n\cK;//g;
  1042. my @lines = split(/\n/, $txt);
  1043. my $leader = "";
  1044. my $level = 0;
  1045. my $line;
  1046. for $line (@lines) {
  1047. my $cmd = substr($line, 0, 1);
  1048. if ($cmd eq "\t" or $cmd eq "\b") {
  1049. $level += ($cmd eq "\t" ? 1 : -1) * $self->{'indent_size'};
  1050. if ($self->{'use_tabs'}) {
  1051. $leader = "\t" x ($level / 8) . " " x ($level % 8);
  1052. } else {
  1053. $leader = " " x $level;
  1054. }
  1055. $line = substr($line, 1);
  1056. }
  1057. if (index($line, "\f") > 0) {
  1058. $line =~ s/\f/\n/;
  1059. }
  1060. if (substr($line, 0, 1) eq "\f") {
  1061. $line = substr($line, 1); # no indent
  1062. } else {
  1063. $line = $leader . $line;
  1064. }
  1065. $line =~ s/\cK;?//g;
  1066. }
  1067. return join("\n", @lines);
  1068. }
  1069. sub pad_subs {
  1070. my ($self, $cv) = @_;
  1071. my $padlist = $cv->PADLIST;
  1072. my @names = $padlist->ARRAYelt(0)->ARRAY;
  1073. my @values = $padlist->ARRAYelt(1)->ARRAY;
  1074. my @todo;
  1075. PADENTRY:
  1076. for my $ix (0.. $#names) { for $_ ($names[$ix]) {
  1077. next if class($_) eq "SPECIAL";
  1078. my $name = $_->PVX;
  1079. if (defined $name && $name =~ /^&./) {
  1080. my $low = $_->COP_SEQ_RANGE_LOW;
  1081. my $flags = $_->FLAGS;
  1082. my $outer = $flags & PADNAMEt_OUTER;
  1083. if ($flags & SVpad_OUR) {
  1084. push @todo, [$low, undef, 0, $_]
  1085. # [seq, no cv, not format, padname]
  1086. unless $outer;
  1087. next;
  1088. }
  1089. my $protocv = $flags & SVpad_STATE
  1090. ? $values[$ix]
  1091. : $_->PROTOCV;
  1092. if (class ($protocv) ne 'CV') {
  1093. my $flags = $flags;
  1094. my $cv = $cv;
  1095. my $name = $_;
  1096. while ($flags & PADNAMEt_OUTER && class ($protocv) ne 'CV')
  1097. {
  1098. $cv = $cv->OUTSIDE;
  1099. next PADENTRY if class($cv) eq 'SPECIAL'; # XXX freed?
  1100. my $padlist = $cv->PADLIST;
  1101. my $ix = $name->PARENT_PAD_INDEX;
  1102. $name = $padlist->NAMES->ARRAYelt($ix);
  1103. $flags = $name->FLAGS;
  1104. $protocv = $flags & SVpad_STATE
  1105. ? $padlist->ARRAYelt(1)->ARRAYelt($ix)
  1106. : $name->PROTOCV;
  1107. }
  1108. }
  1109. my $defined_in_this_sub = ${$protocv->OUTSIDE} == $$cv || do {
  1110. my $other = $protocv->PADLIST;
  1111. $$other && $other->outid == $padlist->id;
  1112. };
  1113. if ($flags & PADNAMEt_OUTER) {
  1114. next unless $defined_in_this_sub;
  1115. push @todo, [$protocv->OUTSIDE_SEQ, $protocv, 0, $_];
  1116. next;
  1117. }
  1118. my $outseq = $protocv->OUTSIDE_SEQ;
  1119. if ($outseq <= $low) {
  1120. # defined before its name is visible, so it’s gotta be
  1121. # declared and defined at once: my sub foo { ... }
  1122. push @todo, [$low, $protocv, 0, $_];
  1123. }
  1124. else {
  1125. # declared and defined separately: my sub f; sub f { ... }
  1126. push @todo, [$low, undef, 0, $_];
  1127. push @todo, [$outseq, $protocv, 0, $_]
  1128. if $defined_in_this_sub;
  1129. }
  1130. }
  1131. }}
  1132. @{$self->{'subs_todo'}} =
  1133. sort {$a->[0] <=> $b->[0]} @{$self->{'subs_todo'}}, @todo
  1134. }
  1135. sub deparse_sub {
  1136. my $self = shift;
  1137. my $cv = shift;
  1138. my $proto = "";
  1139. Carp::confess("NULL in deparse_sub") if !defined($cv) || $cv->isa("B::NULL");
  1140. Carp::confess("SPECIAL in deparse_sub") if $cv->isa("B::SPECIAL");
  1141. local $self->{'curcop'} = $self->{'curcop'};
  1142. if ($cv->FLAGS & SVf_POK) {
  1143. $proto = "(". $cv->PV . ") ";
  1144. }
  1145. if ($cv->CvFLAGS & (CVf_METHOD|CVf_LOCKED|CVf_LVALUE|CVf_ANONCONST)) {
  1146. $proto .= ": ";
  1147. $proto .= "lvalue " if $cv->CvFLAGS & CVf_LVALUE;
  1148. $proto .= "locked " if $cv->CvFLAGS & CVf_LOCKED;
  1149. $proto .= "method " if $cv->CvFLAGS & CVf_METHOD;
  1150. $proto .= "const " if $cv->CvFLAGS & CVf_ANONCONST;
  1151. }
  1152. local($self->{'curcv'}) = $cv;
  1153. local($self->{'curcvlex'});
  1154. local(@$self{qw'curstash warnings hints hinthash'})
  1155. = @$self{qw'curstash warnings hints hinthash'};
  1156. my $body;
  1157. my $root = $cv->ROOT;
  1158. local $B::overlay = {};
  1159. if (not null $root) {
  1160. $self->pad_subs($cv);
  1161. $self->pessimise($root, $cv->START);
  1162. my $lineseq = $root->first;
  1163. if ($lineseq->name eq "lineseq") {
  1164. my @ops;
  1165. for(my$o=$lineseq->first; $$o; $o=$o->sibling) {
  1166. push @ops, $o;
  1167. }
  1168. $body = $self->lineseq(undef, 0, @ops).";";
  1169. my $scope_en = $self->find_scope_en($lineseq);
  1170. if (defined $scope_en) {
  1171. my $subs = join"", $self->seq_subs($scope_en);
  1172. $body .= ";\n$subs" if length($subs);
  1173. }
  1174. }
  1175. else {
  1176. $body = $self->deparse($root->first, 0);
  1177. }
  1178. }
  1179. else {
  1180. my $sv = $cv->const_sv;
  1181. if ($$sv) {
  1182. # uh-oh. inlinable sub... format it differently
  1183. return $proto . "{ " . $self->const($sv, 0) . " }\n";
  1184. } else { # XSUB? (or just a declaration)
  1185. return "$proto;\n";
  1186. }
  1187. }
  1188. return $proto ."{\n\t$body\n\b}" ."\n";
  1189. }
  1190. sub deparse_format {
  1191. my $self = shift;
  1192. my $form = shift;
  1193. my @text;
  1194. local($self->{'curcv'}) = $form;
  1195. local($self->{'curcvlex'});
  1196. local($self->{'in_format'}) = 1;
  1197. local(@$self{qw'curstash warnings hints hinthash'})
  1198. = @$self{qw'curstash warnings hints hinthash'};
  1199. my $op = $form->ROOT;
  1200. local $B::overlay = {};
  1201. $self->pessimise($op, $form->START);
  1202. my $kid;
  1203. return "\f." if $op->first->name eq 'stub'
  1204. || $op->first->name eq 'nextstate';
  1205. $op = $op->first->first; # skip leavewrite, lineseq
  1206. while (not null $op) {
  1207. $op = $op->sibling; # skip nextstate
  1208. my @exprs;
  1209. $kid = $op->first->sibling; # skip pushmark
  1210. push @text, "\f".$self->const_sv($kid)->PV;
  1211. $kid = $kid->sibling;
  1212. for (; not null $kid; $kid = $kid->sibling) {
  1213. push @exprs, $self->deparse($kid, -1);
  1214. $exprs[-1] =~ s/;\z//;
  1215. }
  1216. push @text, "\f".join(", ", @exprs)."\n" if @exprs;
  1217. $op = $op->sibling;
  1218. }
  1219. return join("", @text) . "\f.";
  1220. }
  1221. sub is_scope {
  1222. my $op = shift;
  1223. return $op->name eq "leave" || $op->name eq "scope"
  1224. || $op->name eq "lineseq"
  1225. || ($op->name eq "null" && class($op) eq "UNOP"
  1226. && (is_scope($op->first) || $op->first->name eq "enter"));
  1227. }
  1228. sub is_state {
  1229. my $name = $_[0]->name;
  1230. return $name eq "nextstate" || $name eq "dbstate" || $name eq "setstate";
  1231. }
  1232. sub is_miniwhile { # check for one-line loop ('foo() while $y--')
  1233. my $op = shift;
  1234. return (!null($op) and null($op->sibling)
  1235. and $op->name eq "null" and class($op) eq "UNOP"
  1236. and (($op->first->name =~ /^(and|or)$/
  1237. and $op->first->first->sibling->name eq "lineseq")
  1238. or ($op->first->name eq "lineseq"
  1239. and not null $op->first->first->sibling
  1240. and $op->first->first->sibling->name eq "unstack")
  1241. ));
  1242. }
  1243. # Check if the op and its sibling are the initialization and the rest of a
  1244. # for (..;..;..) { ... } loop
  1245. sub is_for_loop {
  1246. my $op = shift;
  1247. # This OP might be almost anything, though it won't be a
  1248. # nextstate. (It's the initialization, so in the canonical case it
  1249. # will be an sassign.) The sibling is (old style) a lineseq whose
  1250. # first child is a nextstate and whose second is a leaveloop, or
  1251. # (new style) an unstack whose sibling is a leaveloop.
  1252. my $lseq = $op->sibling;
  1253. return 0 unless !is_state($op) and !null($lseq);
  1254. if ($lseq->name eq "lineseq") {
  1255. if ($lseq->first && !null($lseq->first) && is_state($lseq->first)
  1256. && (my $sib = $lseq->first->sibling)) {
  1257. return (!null($sib) && $sib->name eq "leaveloop");
  1258. }
  1259. } elsif ($lseq->name eq "unstack" && ($lseq->flags & OPf_SPECIAL)) {
  1260. my $sib = $lseq->sibling;
  1261. return $sib && !null($sib) && $sib->name eq "leaveloop";
  1262. }
  1263. return 0;
  1264. }
  1265. sub is_scalar {
  1266. my $op = shift;
  1267. return ($op->name eq "rv2sv" or
  1268. $op->name eq "padsv" or
  1269. $op->name eq "gv" or # only in array/hash constructs
  1270. $op->flags & OPf_KIDS && !null($op->first)
  1271. && $op->first->name eq "gvsv");
  1272. }
  1273. sub maybe_parens {
  1274. my $self = shift;
  1275. my($text, $cx, $prec) = @_;
  1276. if ($prec < $cx # unary ops nest just fine
  1277. or $prec == $cx and $cx != 4 and $cx != 16 and $cx != 21
  1278. or $self->{'parens'})
  1279. {
  1280. $text = "($text)";
  1281. # In a unop, let parent reuse our parens; see maybe_parens_unop
  1282. $text = "\cS" . $text if $cx == 16;
  1283. return $text;
  1284. } else {
  1285. return $text;
  1286. }
  1287. }
  1288. # same as above, but get around the 'if it looks like a function' rule
  1289. sub maybe_parens_unop {
  1290. my $self = shift;
  1291. my($name, $kid, $cx) = @_;
  1292. if ($cx > 16 or $self->{'parens'}) {
  1293. $kid = $self->deparse($kid, 1);
  1294. if ($name eq "umask" && $kid =~ /^\d+$/) {
  1295. $kid = sprintf("%#o", $kid);
  1296. }
  1297. return $self->keyword($name) . "($kid)";
  1298. } else {
  1299. $kid = $self->deparse($kid, 16);
  1300. if ($name eq "umask" && $kid =~ /^\d+$/) {
  1301. $kid = sprintf("%#o", $kid);
  1302. }
  1303. $name = $self->keyword($name);
  1304. if (substr($kid, 0, 1) eq "\cS") {
  1305. # use kid's parens
  1306. return $name . substr($kid, 1);
  1307. } elsif (substr($kid, 0, 1) eq "(") {
  1308. # avoid looks-like-a-function trap with extra parens
  1309. # ('+' can lead to ambiguities)
  1310. return "$name(" . $kid . ")";
  1311. } else {
  1312. return "$name $kid";
  1313. }
  1314. }
  1315. }
  1316. sub maybe_parens_func {
  1317. my $self = shift;
  1318. my($func, $text, $cx, $prec) = @_;
  1319. if ($prec <= $cx or substr($text, 0, 1) eq "(" or $self->{'parens'}) {
  1320. return "$func($text)";
  1321. } else {
  1322. return "$func $text";
  1323. }
  1324. }
  1325. sub find_our_type {
  1326. my ($self, $name) = @_;
  1327. $self->populate_curcvlex() if !defined $self->{'curcvlex'};
  1328. my $seq = $self->{'curcop'} ? $self->{'curcop'}->cop_seq : 0;
  1329. for my $a (@{$self->{'curcvlex'}{"o$name"}}) {
  1330. my ($st, undef, $padname) = @$a;
  1331. if ($st >= $seq && $padname->FLAGS & SVpad_TYPED) {
  1332. return $padname->SvSTASH->NAME;
  1333. }
  1334. }
  1335. return '';
  1336. }
  1337. sub maybe_local {
  1338. my $self = shift;
  1339. my($op, $cx, $text) = @_;
  1340. my $name = $op->name;
  1341. my $our_intro = ($name =~ /^(?:(?:gv|rv2)[ash]v|split|refassign
  1342. |lv(?:av)?ref)$/x)
  1343. ? OPpOUR_INTRO
  1344. : 0;
  1345. my $lval_intro = $name eq 'split' ? 0 : OPpLVAL_INTRO;
  1346. # The @a in \(@a) isn't in ref context, but only when the
  1347. # parens are there.
  1348. my $need_parens = $self->{'in_refgen'} && $name =~ /[ah]v\z/
  1349. && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
  1350. if ((my $priv = $op->private) & ($lval_intro|$our_intro)) {
  1351. my @our_local;
  1352. push @our_local, "local" if $priv & $lval_intro;
  1353. push @our_local, "our" if $priv & $our_intro;
  1354. my $our_local = join " ", map $self->keyword($_), @our_local;
  1355. if( $our_local[-1] eq 'our' ) {
  1356. if ( $text !~ /^\W(\w+::)*\w+\z/
  1357. and !utf8::decode($text) || $text !~ /^\W(\w+::)*\w+\z/
  1358. ) {
  1359. die "Unexpected our($text)\n";
  1360. }
  1361. $text =~ s/(\w+::)+//;
  1362. if (my $type = $self->find_our_type($text)) {
  1363. $our_local .= ' ' . $type;
  1364. }
  1365. }
  1366. return $need_parens ? "($text)" : $text
  1367. if $self->{'avoid_local'}{$$op};
  1368. if ($need_parens) {
  1369. return "$our_local($text)";
  1370. } elsif (want_scalar($op)) {
  1371. return "$our_local $text";
  1372. } else {
  1373. return $self->maybe_parens_func("$our_local", $text, $cx, 16);
  1374. }
  1375. } else {
  1376. return $need_parens ? "($text)" : $text;
  1377. }
  1378. }
  1379. sub maybe_targmy {
  1380. my $self = shift;
  1381. my($op, $cx, $func, @args) = @_;
  1382. if ($op->private & OPpTARGET_MY) {
  1383. my $var = $self->padname($op->targ);
  1384. my $val = $func->($self, $op, 7, @args);
  1385. return $self->maybe_parens("$var = $val", $cx, 7);
  1386. } else {
  1387. return $func->($self, $op, $cx, @args);
  1388. }
  1389. }
  1390. sub padname_sv {
  1391. my $self = shift;
  1392. my $targ = shift;
  1393. return $self->{'curcv'}->PADLIST->ARRAYelt(0)->ARRAYelt($targ);
  1394. }
  1395. sub maybe_my {
  1396. my $self = shift;
  1397. my($op, $cx, $text, $padname, $forbid_parens) = @_;
  1398. # The @a in \(@a) isn't in ref context, but only when the
  1399. # parens are there.
  1400. my $need_parens = !$forbid_parens && $self->{'in_refgen'}
  1401. && $op->name =~ /[ah]v\z/
  1402. && ($op->flags & (OPf_PARENS|OPf_REF)) == OPf_PARENS;
  1403. # The @a in \my @a must not have parens.
  1404. if (!$need_parens && $self->{'in_refgen'}) {
  1405. $forbid_parens = 1;
  1406. }
  1407. if ($op->private & OPpLVAL_INTRO and not $self->{'avoid_local'}{$$op}) {
  1408. # Check $padname->FLAGS for statehood, rather than $op->private,
  1409. # because enteriter ops do not carry the flag.
  1410. my $my =
  1411. $self->keyword($padname->FLAGS & SVpad_STATE ? "state" : "my");
  1412. if ($padname->FLAGS & SVpad_TYPED) {
  1413. $my .= ' ' . $padname->SvSTASH->NAME;
  1414. }
  1415. if ($need_parens) {
  1416. return "$my($text)";
  1417. } elsif ($forbid_parens || want_scalar($op)) {
  1418. return "$my $text";
  1419. } else {
  1420. return $self->maybe_parens_func($my, $text, $cx, 16);
  1421. }
  1422. } else {
  1423. return $need_parens ? "($text)" : $text;
  1424. }
  1425. }
  1426. # The following OPs don't have functions:
  1427. # pp_padany -- does not exist after parsing
  1428. sub AUTOLOAD {
  1429. if ($AUTOLOAD =~ s/^.*::pp_//) {
  1430. warn "unexpected OP_".
  1431. ($_[1]->type == OP_CUSTOM ? "CUSTOM ($AUTOLOAD)" : uc $AUTOLOAD);
  1432. return "XXX";
  1433. } else {
  1434. die "Undefined subroutine $AUTOLOAD called";
  1435. }
  1436. }
  1437. sub DESTROY {} # Do not AUTOLOAD
  1438. # $root should be the op which represents the root of whatever
  1439. # we're sequencing here. If it's undefined, then we don't append
  1440. # any subroutine declarations to the deparsed ops, otherwise we
  1441. # append appropriate declarations.
  1442. sub lineseq {
  1443. my($self, $root, $cx, @ops) = @_;
  1444. my($expr, @exprs);
  1445. my $out_cop = $self->{'curcop'};
  1446. my $out_seq = defined($out_cop) ? $out_cop->cop_seq : undef;
  1447. my $limit_seq;
  1448. if (defined $root) {
  1449. $limit_seq = $out_seq;
  1450. my $nseq;
  1451. $nseq = $self->find_scope_st($root->sibling) if ${$root->sibling};
  1452. $limit_seq = $nseq if !defined($limit_seq)
  1453. or defined($nseq) && $nseq < $limit_seq;
  1454. }
  1455. $limit_seq = $self->{'limit_seq'}
  1456. if defined($self->{'limit_seq'})
  1457. && (!defined($limit_seq) || $self->{'limit_seq'} < $limit_seq);
  1458. local $self->{'limit_seq'} = $limit_seq;
  1459. $self->walk_lineseq($root, \@ops,
  1460. sub { push @exprs, $_[0]} );
  1461. my $sep = $cx ? '; ' : ";\n";
  1462. my $body = join($sep, grep {length} @exprs);
  1463. my $subs = "";
  1464. if (defined $root && defined $limit_seq && !$self->{'in_format'}) {
  1465. $subs = join "\n", $self->seq_subs($limit_seq);
  1466. }
  1467. return join($sep, grep {length} $body, $subs);
  1468. }
  1469. sub scopeop {
  1470. my($real_block, $self, $op, $cx) = @_;
  1471. my $kid;
  1472. my @kids;
  1473. local(@$self{qw'curstash warnings hints hinthash'})
  1474. = @$self{qw'curstash warnings hints hinthash'} if $real_block;
  1475. if ($real_block) {
  1476. $kid = $op->first->sibling; # skip enter
  1477. if (is_miniwhile($kid)) {
  1478. my $top = $kid->first;
  1479. my $name = $top->name;
  1480. if ($name eq "and") {
  1481. $name = $self->keyword("while");
  1482. } elsif ($name eq "or") {
  1483. $name = $self->keyword("until");
  1484. } else { # no conditional -> while 1 or until 0
  1485. return $self->deparse($top->first, 1) . " "
  1486. . $self->keyword("while") . " 1";
  1487. }
  1488. my $cond = $top->first;
  1489. my $body = $cond->sibling->first; # skip lineseq
  1490. $cond = $self->deparse($cond, 1);
  1491. $body = $self->deparse($body, 1);
  1492. return "$body $name $cond";
  1493. }
  1494. } else {
  1495. $kid = $op->first;
  1496. }
  1497. for (; !null($kid); $kid = $kid->sibling) {
  1498. push @kids, $kid;
  1499. }
  1500. if ($cx > 0) { # inside an expression, (a do {} while for lineseq)
  1501. my $body = $self->lineseq($op, 0, @kids);
  1502. return is_lexical_subs(@kids)
  1503. ? $body
  1504. : ($self->lex_in_scope("&do") ? "CORE::do" : "do")
  1505. . " {\n\t$body\n\b}";
  1506. } else {
  1507. my $lineseq = $self->lineseq($op, $cx, @kids);
  1508. return (length ($lineseq) ? "$lineseq;" : "");
  1509. }
  1510. }
  1511. sub pp_scope { scopeop(0, @_); }
  1512. sub pp_lineseq { scopeop(0, @_); }
  1513. sub pp_leave { scopeop(1, @_); }
  1514. # This is a special case of scopeop and lineseq, for the case of the
  1515. # main_root. The difference is that we print the output statements as
  1516. # soon as we get them, for the sake of impatient users.
  1517. sub deparse_root {
  1518. my $self = shift;
  1519. my($op) = @_;
  1520. local(@$self{qw'curstash warnings hints hinthash'})
  1521. = @$self{qw'curstash warnings hints hinthash'};
  1522. my @kids;
  1523. return if null $op->first; # Can happen, e.g., for Bytecode without -k
  1524. for (my $kid = $op->first->sibling; !null($kid); $kid = $kid->sibling) {
  1525. push @kids, $kid;
  1526. }
  1527. $self->walk_lineseq($op, \@kids,
  1528. sub { return unless length $_[0];
  1529. print $self->indent($_[0].';');
  1530. print "\n"
  1531. unless $_[1] == $#kids;
  1532. });
  1533. }
  1534. sub walk_lineseq {
  1535. my ($self, $op, $kids, $callback) = @_;
  1536. my @kids = @$kids;
  1537. for (my $i = 0; $i < @kids; $i++) {
  1538. my $expr = "";
  1539. if (is_state $kids[$i]) {
  1540. $expr = $self->deparse($kids[$i++], 0);
  1541. if ($i > $#kids) {
  1542. $callback->($expr, $i);
  1543. last;
  1544. }
  1545. }
  1546. if (is_for_loop($kids[$i])) {
  1547. $callback->($expr . $self->for_loop($kids[$i], 0),
  1548. $i += $kids[$i]->sibling->name eq "unstack" ? 2 : 1);
  1549. next;
  1550. }
  1551. my $expr2 = $self->deparse($kids[$i], (@kids != 1)/2);
  1552. $expr2 =~ s/^sub :(?!:)/+sub :/; # statement label otherwise
  1553. $expr .= $expr2;
  1554. $callback->($expr, $i);
  1555. }
  1556. }
  1557. # The BEGIN {} is used here because otherwise this code isn't executed
  1558. # when you run B::Deparse on itself.
  1559. my %globalnames;
  1560. BEGIN { map($globalnames{$_}++, "SIG", "STDIN", "STDOUT", "STDERR", "INC",
  1561. "ENV", "ARGV", "ARGVOUT", "_"); }
  1562. sub gv_name {
  1563. my $self = shift;
  1564. my $gv = shift;
  1565. my $raw = shift;
  1566. #Carp::confess() unless ref($gv) eq "B::GV";
  1567. my $cv = $gv->FLAGS & SVf_ROK ? $gv->RV : 0;
  1568. my $stash = ($cv || $gv)->STASH->NAME;
  1569. my $name = $raw
  1570. ? $cv ? $cv->NAME_HEK || $cv->GV->NAME : $gv->NAME
  1571. : $cv
  1572. ? B::safename($cv->NAME_HEK || $cv->GV->NAME)
  1573. : $gv->SAFENAME;
  1574. if ($stash eq 'main' && $name =~ /^::/) {
  1575. $stash = '::';
  1576. }
  1577. elsif (($stash eq 'main'
  1578. && ($globalnames{$name} || $name =~ /^[^A-Za-z_:]/))
  1579. or ($stash eq $self->{'curstash'} && !$globalnames{$name}
  1580. && ($stash eq 'main' || $name !~ /::/))
  1581. )
  1582. {
  1583. $stash = "";
  1584. } else {
  1585. $stash = $stash . "::";
  1586. }
  1587. if (!$raw and $name =~ /^(\^..|{)/) {
  1588. $name = "{$name}"; # ${^WARNING_BITS}, etc and ${
  1589. }
  1590. return $stash . $name;
  1591. }
  1592. # Return the name to use for a stash variable.
  1593. # If a lexical with the same name is in scope, or
  1594. # if strictures are enabled, it may need to be
  1595. # fully-qualified.
  1596. sub stash_variable {
  1597. my ($self, $prefix, $name, $cx) = @_;
  1598. return "$prefix$name" if $name =~ /::/;
  1599. unless ($prefix eq '$' || $prefix eq '@' || $prefix eq '&' || #'
  1600. $prefix eq '%' || $prefix eq '$#') {
  1601. return "$prefix$name";
  1602. }
  1603. if ($name =~ /^[^[:alpha:]_+-]$/) {
  1604. if (defined $cx && $cx == 26) {
  1605. if ($prefix eq '@') {
  1606. return "$prefix\{$name}";
  1607. }
  1608. elsif ($name eq '#') { return '${#}' } # "${#}a" vs "$#a"
  1609. }
  1610. if ($prefix eq '$#') {
  1611. return "\$#{$name}";
  1612. }
  1613. }
  1614. return $prefix . $self->maybe_qualify($prefix, $name);
  1615. }
  1616. my %unctrl = # portable to EBCDIC
  1617. (
  1618. "\c@" => '@', # unused
  1619. "\cA" => 'A',
  1620. "\cB" => 'B',
  1621. "\cC" => 'C',
  1622. "\cD" => 'D',
  1623. "\cE" => 'E',
  1624. "\cF" => 'F',
  1625. "\cG" => 'G',
  1626. "\cH" => 'H',
  1627. "\cI" => 'I',
  1628. "\cJ" => 'J',
  1629. "\cK" => 'K',
  1630. "\cL" => 'L',
  1631. "\cM" => 'M',
  1632. "\cN" => 'N',
  1633. "\cO" => 'O',
  1634. "\cP" => 'P',
  1635. "\cQ" => 'Q',
  1636. "\cR" => 'R',
  1637. "\cS" => 'S',
  1638. "\cT" => 'T',
  1639. "\cU" => 'U',
  1640. "\cV" => 'V',
  1641. "\cW" => 'W',
  1642. "\cX" => 'X',
  1643. "\cY" => 'Y',
  1644. "\cZ" => 'Z',
  1645. "\c[" => '[', # unused
  1646. "\c\\" => '\\', # unused
  1647. "\c]" => ']', # unused
  1648. "\c_" => '_', # unused
  1649. );
  1650. # Return just the name, without the prefix. It may be returned as a quoted
  1651. # string. The second return value is a boolean indicating that.
  1652. sub stash_variable_name {
  1653. my($self, $prefix, $gv) = @_;
  1654. my $name = $self->gv_name($gv, 1);
  1655. $name = $self->maybe_qualify($prefix,$name);
  1656. if ($name =~ /^(?:\S|(?!\d)[\ca-\cz]?(?:\w|::)*|\d+)\z/) {
  1657. $name =~ s/^([\ca-\cz])/'^' . $unctrl{$1}/e;
  1658. $name =~ /^(\^..|{)/ and $name = "{$name}";
  1659. return $name, 0; # not quoted
  1660. }
  1661. else {
  1662. single_delim("q", "'", $name, $self), 1;
  1663. }
  1664. }
  1665. sub maybe_qualify {
  1666. my ($self,$prefix,$name) = @_;
  1667. my $v = ($prefix eq '$#' ? '@' : $prefix) . $name;
  1668. return $name if !$prefix || $name =~ /::/;
  1669. return $self->{'curstash'}.'::'. $name
  1670. if
  1671. $name =~ /^(?!\d)\w/ # alphabetic
  1672. && $v !~ /^\$[ab]\z/ # not $a or $b
  1673. && !$globalnames{$name} # not a global name
  1674. && $self->{hints} & $strict_bits{vars} # strict vars
  1675. && !$self->lex_in_scope($v,1) # no "our"
  1676. or $self->lex_in_scope($v); # conflicts with "my" variable
  1677. return $name;
  1678. }
  1679. sub lex_in_scope {
  1680. my ($self, $name, $our) = @_;
  1681. substr $name, 0, 0, = $our ? 'o' : 'm'; # our/my
  1682. $self->populate_curcvlex() if !defined $self->{'curcvlex'};
  1683. return 0 if !defined($self->{'curcop'});
  1684. my $seq = $self->{'curcop'}->cop_seq;
  1685. return 0 if !exists $self->{'curcvlex'}{$name};
  1686. for my $a (@{$self->{'curcvlex'}{$name}}) {
  1687. my ($st, $en) = @$a;
  1688. return 1 if $seq > $st && $seq <= $en;
  1689. }
  1690. return 0;
  1691. }
  1692. sub populate_curcvlex {
  1693. my $self = shift;
  1694. for (my $cv = $self->{'curcv'}; class($cv) eq "CV"; $cv = $cv->OUTSIDE) {
  1695. my $padlist = $cv->PADLIST;
  1696. # an undef CV still in lexical chain
  1697. next if class($padlist) eq "SPECIAL";
  1698. my @padlist = $padlist->ARRAY;
  1699. my @ns = $padlist[0]->ARRAY;
  1700. for (my $i=0; $i<@ns; ++$i) {
  1701. next if class($ns[$i]) eq "SPECIAL";
  1702. if (class($ns[$i]) eq "PV") {
  1703. # Probably that pesky lexical @_
  1704. next;
  1705. }
  1706. my $name = $ns[$i]->PVX;
  1707. next unless defined $name;
  1708. my ($seq_st, $seq_en) =
  1709. ($ns[$i]->FLAGS & SVf_FAKE)
  1710. ? (0, 999999)
  1711. : ($ns[$i]->COP_SEQ_RANGE_LOW, $ns[$i]->COP_SEQ_RANGE_HIGH);
  1712. push @{$self->{'curcvlex'}{
  1713. ($ns[$i]->FLAGS & SVpad_OUR ? 'o' : 'm') . $name
  1714. }}, [$seq_st, $seq_en, $ns[$i]];
  1715. }
  1716. }
  1717. }
  1718. sub find_scope_st { ((find_scope(@_))[0]); }
  1719. sub find_scope_en { ((find_scope(@_))[1]); }
  1720. # Recurses down the tree, looking for pad variable introductions and COPs
  1721. sub find_scope {
  1722. my ($self, $op, $scope_st, $scope_en) = @_;
  1723. carp("Undefined op in find_scope") if !defined $op;
  1724. return ($scope_st, $scope_en) unless $op->flags & OPf_KIDS;
  1725. my @queue = ($op);
  1726. while(my $op = shift @queue ) {
  1727. for (my $o=$op->first; $$o; $o=$o->sibling) {
  1728. if ($o->name =~ /^pad.v$/ && $o->private & OPpLVAL_INTRO) {
  1729. my $s = int($self->padname_sv($o->targ)->COP_SEQ_RANGE_LOW);
  1730. my $e = $self->padname_sv($o->targ)->COP_SEQ_RANGE_HIGH;
  1731. $scope_st = $s if !defined($scope_st) || $s < $scope_st;
  1732. $scope_en = $e if !defined($scope_en) || $e > $scope_en;
  1733. return ($scope_st, $scope_en);
  1734. }
  1735. elsif (is_state($o)) {
  1736. my $c = $o->cop_seq;
  1737. $scope_st = $c if !defined($scope_st) || $c < $scope_st;
  1738. $scope_en = $c if !defined($scope_en) || $c > $scope_en;
  1739. return ($scope_st, $scope_en);
  1740. }
  1741. elsif ($o->flags & OPf_KIDS) {
  1742. unshift (@queue, $o);
  1743. }
  1744. }
  1745. }
  1746. return ($scope_st, $scope_en);
  1747. }
  1748. # Returns a list of subs which should be inserted before the COP
  1749. sub cop_subs {
  1750. my ($self, $op, $out_seq) = @_;
  1751. my $seq = $op->cop_seq;
  1752. if ($] < 5.021006) {
  1753. # If we have nephews, then our sequence number indicates
  1754. # the cop_seq of the end of some sort of scope.
  1755. if (class($op->sibling) ne "NULL" && $op->sibling->flags & OPf_KIDS
  1756. and my $nseq = $self->find_scope_st($op->sibling) ) {
  1757. $seq = $nseq;
  1758. }
  1759. }
  1760. $seq = $out_seq if defined($out_seq) && $out_seq < $seq;
  1761. return $self->seq_subs($seq);
  1762. }
  1763. sub seq_subs {
  1764. my ($self, $seq) = @_;
  1765. my @text;
  1766. #push @text, "# ($seq)\n";
  1767. return "" if !defined $seq;
  1768. my @pending;
  1769. while (scalar(@{$self->{'subs_todo'}})
  1770. and $seq > $self->{'subs_todo'}[0][0]) {
  1771. my $cv = $self->{'subs_todo'}[0][1];
  1772. # Skip the OUTSIDE check for lexical subs. We may be deparsing a
  1773. # cloned anon sub with lexical subs declared in it, in which case
  1774. # the OUTSIDE pointer points to the anon protosub.
  1775. my $lexical = ref $self->{'subs_todo'}[0][3];
  1776. my $outside = !$lexical && $cv && $cv->OUTSIDE;
  1777. if (!$lexical and $cv
  1778. and ${$cv->OUTSIDE || \0} != ${$self->{'curcv'}})
  1779. {
  1780. push @pending, shift @{$self->{'subs_todo'}};
  1781. next;
  1782. }
  1783. push @text, $self->next_todo;
  1784. }
  1785. unshift @{$self->{'subs_todo'}}, @pending;
  1786. return @text;
  1787. }
  1788. sub _features_from_bundle {
  1789. my ($hints, $hh) = @_;
  1790. foreach (@{$feature::feature_bundle{@feature::hint_bundles[$hints >> $feature::hint_shift]}}) {
  1791. $hh->{$feature::feature{$_}} = 1;
  1792. }
  1793. return $hh;
  1794. }
  1795. # Notice how subs and formats are inserted between statements here;
  1796. # also $[ assignments and pragmas.
  1797. sub pp_nextstate {
  1798. my $self = shift;
  1799. my($op, $cx) = @_;
  1800. $self->{'curcop'} = $op;
  1801. my @text;
  1802. push @text, $self->cop_subs($op);
  1803. if (@text) {
  1804. # Special marker to swallow up the semicolon
  1805. push @text, "\cK";
  1806. }
  1807. my $stash = $op->stashpv;
  1808. if ($stash ne $self->{'curstash'}) {
  1809. push @text, $self->keyword("package") . " $stash;\n";
  1810. $self->{'curstash'} = $stash;
  1811. }
  1812. if (OPpCONST_ARYBASE && $self->{'arybase'} != $op->arybase) {
  1813. push @text, '$[ = '. $op->arybase .";\n";
  1814. $self->{'arybase'} = $op->arybase;
  1815. }
  1816. my $warnings = $op->warnings;
  1817. my $warning_bits;
  1818. if ($warnings->isa("B::SPECIAL") && $$warnings == 4) {
  1819. $warning_bits = $warnings::Bits{"all"} & WARN_MASK;
  1820. }
  1821. elsif ($warnings->isa("B::SPECIAL") && $$warnings == 5) {
  1822. $warning_bits = $warnings::NONE;
  1823. }
  1824. elsif ($warnings->isa("B::SPECIAL")) {
  1825. $warning_bits = undef;
  1826. }
  1827. else {
  1828. $warning_bits = $warnings->PV & WARN_MASK;
  1829. }
  1830. if (defined ($warning_bits) and
  1831. !defined($self->{warnings}) || $self->{'warnings'} ne $warning_bits) {
  1832. push @text,
  1833. $self->declare_warnings($self->{'warnings'}, $warning_bits);
  1834. $self->{'warnings'} = $warning_bits;
  1835. }
  1836. my $hints = $] < 5.008009 ? $op->private : $op->hints;
  1837. my $old_hints = $self->{'hints'};
  1838. if ($self->{'hints'} != $hints) {
  1839. push @text, $self->declare_hints($self->{'hints'}, $hints);
  1840. $self->{'hints'} = $hints;
  1841. }
  1842. my $newhh;
  1843. if ($] > 5.009) {
  1844. $newhh = $op->hints_hash->HASH;
  1845. }
  1846. if ($] >= 5.015006) {
  1847. # feature bundle hints
  1848. my $from = $old_hints & $feature::hint_mask;
  1849. my $to = $ hints & $feature::hint_mask;
  1850. if ($from != $to) {
  1851. if ($to == $feature::hint_mask) {
  1852. if ($self->{'hinthash'}) {
  1853. delete $self->{'hinthash'}{$_}
  1854. for grep /^feature_/, keys %{$self->{'hinthash'}};
  1855. }
  1856. else { $self->{'hinthash'} = {} }
  1857. $self->{'hinthash'}
  1858. = _features_from_bundle($from, $self->{'hinthash'});
  1859. }
  1860. else {
  1861. my $bundle =
  1862. $feature::hint_bundles[$to >> $feature::hint_shift];
  1863. $bundle =~ s/(\d[13579])\z/$1+1/e; # 5.11 => 5.12
  1864. push @text,
  1865. $self->keyword("no") . " feature ':all';\n",
  1866. $self->keyword("use") . " feature ':$bundle';\n";
  1867. }
  1868. }
  1869. }
  1870. if ($] > 5.009) {
  1871. push @text, $self->declare_hinthash(
  1872. $self->{'hinthash'}, $newhh,
  1873. $self->{indent_size}, $self->{hints},
  1874. );
  1875. $self->{'hinthash'} = $newhh;
  1876. }
  1877. # This should go after of any branches that add statements, to
  1878. # increase the chances that it refers to the same line it did in
  1879. # the original program.
  1880. if ($self->{'linenums'} && $cx != .5) { # $cx == .5 means in a format
  1881. push @text, "\f#line " . $op->line .
  1882. ' "' . $op->file, qq'"\n';
  1883. }
  1884. push @text, $op->label . ": " if $op->label;
  1885. return join("", @text);
  1886. }
  1887. sub declare_warnings {
  1888. my ($self, $from, $to) = @_;
  1889. if (($to & WARN_MASK) eq (warnings::bits("all") & WARN_MASK)) {
  1890. return $self->keyword("use") . " warnings;\n";
  1891. }
  1892. elsif (($to & WARN_MASK) eq ("\0"x length($to) & WARN_MASK)) {
  1893. return $self->keyword("no") . " warnings;\n";
  1894. }
  1895. return "BEGIN {\${^WARNING_BITS} = \""
  1896. . join("", map { sprintf("\\x%02x", ord $_) } split "", $to)
  1897. . "\"}\n\cK";
  1898. }
  1899. sub declare_hints {
  1900. my ($self, $from, $to) = @_;
  1901. my $use = $to & ~$from;
  1902. my $no = $from & ~$to;
  1903. my $decls = "";
  1904. for my $pragma (hint_pragmas($use)) {
  1905. $decls .= $self->keyword("use") . " $pragma;\n";
  1906. }
  1907. for my $pragma (hint_pragmas($no)) {
  1908. $decls .= $self->keyword("no") . " $pragma;\n";
  1909. }
  1910. return $decls;
  1911. }
  1912. # Internal implementation hints that the core sets automatically, so don't need
  1913. # (or want) to be passed back to the user
  1914. my %ignored_hints = (
  1915. 'open<' => 1,
  1916. 'open>' => 1,
  1917. ':' => 1,
  1918. 'strict/refs' => 1,
  1919. 'strict/subs' => 1,
  1920. 'strict/vars' => 1,
  1921. );
  1922. my %rev_feature;
  1923. sub declare_hinthash {
  1924. my ($self, $from, $to, $indent, $hints) = @_;
  1925. my $doing_features =
  1926. ($hints & $feature::hint_mask) == $feature::hint_mask;
  1927. my @decls;
  1928. my @features;
  1929. my @unfeatures; # bugs?
  1930. for my $key (sort keys %$to) {
  1931. next if $ignored_hints{$key};
  1932. my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
  1933. next if $is_feature and not $doing_features;
  1934. if (!exists $from->{$key} or $from->{$key} ne $to->{$key}) {
  1935. push(@features, $key), next if $is_feature;
  1936. push @decls,
  1937. qq(\$^H{) . single_delim("q", "'", $key, $self) . qq(} = )
  1938. . (
  1939. defined $to->{$key}
  1940. ? single_delim("q", "'", $to->{$key}, $self)
  1941. : 'undef'
  1942. )
  1943. . qq(;);
  1944. }
  1945. }
  1946. for my $key (sort keys %$from) {
  1947. next if $ignored_hints{$key};
  1948. my $is_feature = $key =~ /^feature_/ && $^V ge 5.15.6;
  1949. next if $is_feature and not $doing_features;
  1950. if (!exists $to->{$key}) {
  1951. push(@unfeatures, $key), next if $is_feature;
  1952. push @decls, qq(delete \$^H{'$key'};);
  1953. }
  1954. }
  1955. my @ret;
  1956. if (@features || @unfeatures) {
  1957. if (!%rev_feature) { %rev_feature = reverse %feature::feature }
  1958. }
  1959. if (@features) {
  1960. push @ret, $self->keyword("use") . " feature "
  1961. . join(", ", map "'$rev_feature{$_}'", @features) . ";\n";
  1962. }
  1963. if (@unfeatures) {
  1964. push @ret, $self->keyword("no") . " feature "
  1965. . join(", ", map "'$rev_feature{$_}'", @unfeatures)
  1966. . ";\n";
  1967. }
  1968. @decls and
  1969. push @ret,
  1970. join("\n" . (" " x $indent), "BEGIN {", @decls) . "\n}\n\cK";
  1971. return @ret;
  1972. }
  1973. sub hint_pragmas {
  1974. my ($bits) = @_;
  1975. my (@pragmas, @strict);
  1976. push @pragmas, "integer" if $bits & 0x1;
  1977. for (sort keys %strict_bits) {
  1978. push @strict, "'$_'" if $bits & $strict_bits{$_};
  1979. }
  1980. if (@strict == keys %strict_bits) {
  1981. push @pragmas, "strict";
  1982. }
  1983. elsif (@strict) {
  1984. push @pragmas, "strict " . join ', ', @strict;
  1985. }
  1986. push @pragmas, "bytes" if $bits & 0x8;
  1987. return @pragmas;
  1988. }
  1989. sub pp_dbstate { pp_nextstate(@_) }
  1990. sub pp_setstate { pp_nextstate(@_) }
  1991. sub pp_unstack { return "" } # see also leaveloop
  1992. my %feature_keywords = (
  1993. # keyword => 'feature',
  1994. state => 'state',
  1995. say => 'say',
  1996. given => 'switch',
  1997. when => 'switch',
  1998. default => 'switch',
  1999. break => 'switch',
  2000. evalbytes=>'evalbytes',
  2001. __SUB__ => '__SUB__',
  2002. fc => 'fc',
  2003. );
  2004. # keywords that are strong and also have a prototype
  2005. #
  2006. my %strong_proto_keywords = map { $_ => 1 } qw(
  2007. pos
  2008. prototype
  2009. scalar
  2010. study
  2011. undef
  2012. );
  2013. sub feature_enabled {
  2014. my($self,$name) = @_;
  2015. my $hh;
  2016. my $hints = $self->{hints} & $feature::hint_mask;
  2017. if ($hints && $hints != $feature::hint_mask) {
  2018. $hh = _features_from_bundle($hints);
  2019. }
  2020. elsif ($hints) { $hh = $self->{'hinthash'} }
  2021. return $hh && $hh->{"feature_$feature_keywords{$name}"}
  2022. }
  2023. sub keyword {
  2024. my $self = shift;
  2025. my $name = shift;
  2026. return $name if $name =~ /^CORE::/; # just in case
  2027. if (exists $feature_keywords{$name}) {
  2028. return "CORE::$name" if not $self->feature_enabled($name);
  2029. }
  2030. # This sub may be called for a program that has no nextstate ops. In
  2031. # that case we may have a lexical sub named no/use/sub in scope but
  2032. # but $self->lex_in_scope will return false because it depends on the
  2033. # current nextstate op. So we need this alternate method if there is
  2034. # no current cop.
  2035. if (!$self->{'curcop'}) {
  2036. $self->populate_curcvlex() if !defined $self->{'curcvlex'};
  2037. return "CORE::$name" if exists $self->{'curcvlex'}{"m&$name"}
  2038. || exists $self->{'curcvlex'}{"o&$name"};
  2039. } elsif ($self->lex_in_scope("&$name")
  2040. || $self->lex_in_scope("&$name", 1)) {
  2041. return "CORE::$name";
  2042. }
  2043. if ($strong_proto_keywords{$name}
  2044. || ($name !~ /^(?:chom?p|do|exec|glob|s(?:elect|ystem))\z/
  2045. && !defined eval{prototype "CORE::$name"})
  2046. ) { return $name }
  2047. if (
  2048. exists $self->{subs_declared}{$name}
  2049. or
  2050. exists &{"$self->{curstash}::$name"}
  2051. ) {
  2052. return "CORE::$name"
  2053. }
  2054. return $name;
  2055. }
  2056. sub baseop {
  2057. my $self = shift;
  2058. my($op, $cx, $name) = @_;
  2059. return $self->keyword($name);
  2060. }
  2061. sub pp_stub { "()" }
  2062. sub pp_wantarray { baseop(@_, "wantarray") }
  2063. sub pp_fork { baseop(@_, "fork") }
  2064. sub pp_wait { maybe_targmy(@_, \&baseop, "wait") }
  2065. sub pp_getppid { maybe_targmy(@_, \&baseop, "getppid") }
  2066. sub pp_time { maybe_targmy(@_, \&baseop, "time") }
  2067. sub pp_tms { baseop(@_, "times") }
  2068. sub pp_ghostent { baseop(@_, "gethostent") }
  2069. sub pp_gnetent { baseop(@_, "getnetent") }
  2070. sub pp_gprotoent { baseop(@_, "getprotoent") }
  2071. sub pp_gservent { baseop(@_, "getservent") }
  2072. sub pp_ehostent { baseop(@_, "endhostent") }
  2073. sub pp_enetent { baseop(@_, "endnetent") }
  2074. sub pp_eprotoent { baseop(@_, "endprotoent") }
  2075. sub pp_eservent { baseop(@_, "endservent") }
  2076. sub pp_gpwent { baseop(@_, "getpwent") }
  2077. sub pp_spwent { baseop(@_, "setpwent") }
  2078. sub pp_epwent { baseop(@_, "endpwent") }
  2079. sub pp_ggrent { baseop(@_, "getgrent") }
  2080. sub pp_sgrent { baseop(@_, "setgrent") }
  2081. sub pp_egrent { baseop(@_, "endgrent") }
  2082. sub pp_getlogin { baseop(@_, "getlogin") }
  2083. sub POSTFIX () { 1 }
  2084. # I couldn't think of a good short name, but this is the category of
  2085. # symbolic unary operators with interesting precedence
  2086. sub pfixop {
  2087. my $self = shift;
  2088. my($op, $cx, $name, $prec, $flags) = (@_, 0);
  2089. my $kid = $op->first;
  2090. $kid = $self->deparse($kid, $prec);
  2091. return $self->maybe_parens(($flags & POSTFIX)
  2092. ? "$kid$name"
  2093. # avoid confusion with filetests
  2094. : $name eq '-'
  2095. && $kid =~ /^[a-zA-Z](?!\w)/
  2096. ? "$name($kid)"
  2097. : "$name$kid",
  2098. $cx, $prec);
  2099. }
  2100. sub pp_preinc { pfixop(@_, "++", 23) }
  2101. sub pp_predec { pfixop(@_, "--", 23) }
  2102. sub pp_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
  2103. sub pp_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
  2104. sub pp_i_preinc { pfixop(@_, "++", 23) }
  2105. sub pp_i_predec { pfixop(@_, "--", 23) }
  2106. sub pp_i_postinc { maybe_targmy(@_, \&pfixop, "++", 23, POSTFIX) }
  2107. sub pp_i_postdec { maybe_targmy(@_, \&pfixop, "--", 23, POSTFIX) }
  2108. sub pp_complement { maybe_targmy(@_, \&pfixop, "~", 21) }
  2109. *pp_ncomplement = *pp_complement;
  2110. sub pp_scomplement { maybe_targmy(@_, \&pfixop, "~.", 21) }
  2111. sub pp_negate { maybe_targmy(@_, \&real_negate) }
  2112. sub real_negate {
  2113. my $self = shift;
  2114. my($op, $cx) = @_;
  2115. if ($op->first->name =~ /^(i_)?negate$/) {
  2116. # avoid --$x
  2117. $self->pfixop($op, $cx, "-", 21.5);
  2118. } else {
  2119. $self->pfixop($op, $cx, "-", 21);
  2120. }
  2121. }
  2122. sub pp_i_negate { pp_negate(@_) }
  2123. sub pp_not {
  2124. my $self = shift;
  2125. my($op, $cx) = @_;
  2126. if ($cx <= 4) {
  2127. $self->listop($op, $cx, "not", $op->first);
  2128. } else {
  2129. $self->pfixop($op, $cx, "!", 21);
  2130. }
  2131. }
  2132. sub unop {
  2133. my $self = shift;
  2134. my($op, $cx, $name, $nollafr) = @_;
  2135. my $kid;
  2136. if ($op->flags & OPf_KIDS) {
  2137. $kid = $op->first;
  2138. if (not $name) {
  2139. # this deals with 'boolkeys' right now
  2140. return $self->deparse($kid,$cx);
  2141. }
  2142. my $builtinname = $name;
  2143. $builtinname =~ /^CORE::/ or $builtinname = "CORE::$name";
  2144. if (defined prototype($builtinname)
  2145. && $builtinname ne 'CORE::readline'
  2146. && prototype($builtinname) =~ /^;?\*/
  2147. && $kid->name eq "rv2gv") {
  2148. $kid = $kid->first;
  2149. }
  2150. if ($nollafr) {
  2151. if (($kid = $self->deparse($kid, 16)) !~ s/^\cS//) {
  2152. # require foo() is a syntax error.
  2153. $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
  2154. }
  2155. return $self->maybe_parens(
  2156. $self->keyword($name) . " $kid", $cx, 16
  2157. );
  2158. }
  2159. return $self->maybe_parens_unop($name, $kid, $cx);
  2160. } else {
  2161. return $self->maybe_parens(
  2162. $self->keyword($name) . ($op->flags & OPf_SPECIAL ? "()" : ""),
  2163. $cx, 16,
  2164. );
  2165. }
  2166. }
  2167. sub pp_chop { maybe_targmy(@_, \&unop, "chop") }
  2168. sub pp_chomp { maybe_targmy(@_, \&unop, "chomp") }
  2169. sub pp_schop { maybe_targmy(@_, \&unop, "chop") }
  2170. sub pp_schomp { maybe_targmy(@_, \&unop, "chomp") }
  2171. sub pp_defined { unop(@_, "defined") }
  2172. sub pp_undef { unop(@_, "undef") }
  2173. sub pp_study { unop(@_, "study") }
  2174. sub pp_ref { unop(@_, "ref") }
  2175. sub pp_pos { maybe_local(@_, unop(@_, "pos")) }
  2176. sub pp_sin { maybe_targmy(@_, \&unop, "sin") }
  2177. sub pp_cos { maybe_targmy(@_, \&unop, "cos") }
  2178. sub pp_rand { maybe_targmy(@_, \&unop, "rand") }
  2179. sub pp_srand { unop(@_, "srand") }
  2180. sub pp_exp { maybe_targmy(@_, \&unop, "exp") }
  2181. sub pp_log { maybe_targmy(@_, \&unop, "log") }
  2182. sub pp_sqrt { maybe_targmy(@_, \&unop, "sqrt") }
  2183. sub pp_int { maybe_targmy(@_, \&unop, "int") }
  2184. sub pp_hex { maybe_targmy(@_, \&unop, "hex") }
  2185. sub pp_oct { maybe_targmy(@_, \&unop, "oct") }
  2186. sub pp_abs { maybe_targmy(@_, \&unop, "abs") }
  2187. sub pp_length { maybe_targmy(@_, \&unop, "length") }
  2188. sub pp_ord { maybe_targmy(@_, \&unop, "ord") }
  2189. sub pp_chr { maybe_targmy(@_, \&unop, "chr") }
  2190. sub pp_each { unop(@_, "each") }
  2191. sub pp_values { unop(@_, "values") }
  2192. sub pp_keys { unop(@_, "keys") }
  2193. { no strict 'refs'; *{"pp_r$_"} = *{"pp_$_"} for qw< keys each values >; }
  2194. sub pp_boolkeys {
  2195. # no name because its an optimisation op that has no keyword
  2196. unop(@_,"");
  2197. }
  2198. sub pp_aeach { unop(@_, "each") }
  2199. sub pp_avalues { unop(@_, "values") }
  2200. sub pp_akeys { unop(@_, "keys") }
  2201. sub pp_pop { unop(@_, "pop") }
  2202. sub pp_shift { unop(@_, "shift") }
  2203. sub pp_caller { unop(@_, "caller") }
  2204. sub pp_reset { unop(@_, "reset") }
  2205. sub pp_exit { unop(@_, "exit") }
  2206. sub pp_prototype { unop(@_, "prototype") }
  2207. sub pp_close { unop(@_, "close") }
  2208. sub pp_fileno { unop(@_, "fileno") }
  2209. sub pp_umask { unop(@_, "umask") }
  2210. sub pp_untie { unop(@_, "untie") }
  2211. sub pp_tied { unop(@_, "tied") }
  2212. sub pp_dbmclose { unop(@_, "dbmclose") }
  2213. sub pp_getc { unop(@_, "getc") }
  2214. sub pp_eof { unop(@_, "eof") }
  2215. sub pp_tell { unop(@_, "tell") }
  2216. sub pp_getsockname { unop(@_, "getsockname") }
  2217. sub pp_getpeername { unop(@_, "getpeername") }
  2218. sub pp_chdir {
  2219. my ($self, $op, $cx) = @_;
  2220. if (($op->flags & (OPf_SPECIAL|OPf_KIDS)) == (OPf_SPECIAL|OPf_KIDS)) {
  2221. my $kw = $self->keyword("chdir");
  2222. my $kid = $self->const_sv($op->first)->PV;
  2223. my $code = $kw
  2224. . ($cx >= 16 || $self->{'parens'} ? "($kid)" : " $kid");
  2225. maybe_targmy(@_, sub { $_[3] }, $code);
  2226. } else {
  2227. maybe_targmy(@_, \&unop, "chdir")
  2228. }
  2229. }
  2230. sub pp_chroot { maybe_targmy(@_, \&unop, "chroot") }
  2231. sub pp_readlink { unop(@_, "readlink") }
  2232. sub pp_rmdir { maybe_targmy(@_, \&unop, "rmdir") }
  2233. sub pp_readdir { unop(@_, "readdir") }
  2234. sub pp_telldir { unop(@_, "telldir") }
  2235. sub pp_rewinddir { unop(@_, "rewinddir") }
  2236. sub pp_closedir { unop(@_, "closedir") }
  2237. sub pp_getpgrp { maybe_targmy(@_, \&unop, "getpgrp") }
  2238. sub pp_localtime { unop(@_, "localtime") }
  2239. sub pp_gmtime { unop(@_, "gmtime") }
  2240. sub pp_alarm { unop(@_, "alarm") }
  2241. sub pp_sleep { maybe_targmy(@_, \&unop, "sleep") }
  2242. sub pp_dofile {
  2243. my $code = unop(@_, "do", 1); # llafr does not apply
  2244. if ($code =~ s/^((?:CORE::)?do) \{/$1({/) { $code .= ')' }
  2245. $code;
  2246. }
  2247. sub pp_entereval {
  2248. unop(
  2249. @_,
  2250. $_[1]->private & OPpEVAL_BYTES ? 'evalbytes' : "eval"
  2251. )
  2252. }
  2253. sub pp_ghbyname { unop(@_, "gethostbyname") }
  2254. sub pp_gnbyname { unop(@_, "getnetbyname") }
  2255. sub pp_gpbyname { unop(@_, "getprotobyname") }
  2256. sub pp_shostent { unop(@_, "sethostent") }
  2257. sub pp_snetent { unop(@_, "setnetent") }
  2258. sub pp_sprotoent { unop(@_, "setprotoent") }
  2259. sub pp_sservent { unop(@_, "setservent") }
  2260. sub pp_gpwnam { unop(@_, "getpwnam") }
  2261. sub pp_gpwuid { unop(@_, "getpwuid") }
  2262. sub pp_ggrnam { unop(@_, "getgrnam") }
  2263. sub pp_ggrgid { unop(@_, "getgrgid") }
  2264. sub pp_lock { unop(@_, "lock") }
  2265. sub pp_continue { unop(@_, "continue"); }
  2266. sub pp_break { unop(@_, "break"); }
  2267. sub givwhen {
  2268. my $self = shift;
  2269. my($op, $cx, $givwhen) = @_;
  2270. my $enterop = $op->first;
  2271. my ($head, $block);
  2272. if ($enterop->flags & OPf_SPECIAL) {
  2273. $head = $self->keyword("default");
  2274. $block = $self->deparse($enterop->first, 0);
  2275. }
  2276. else {
  2277. my $cond = $enterop->first;
  2278. my $cond_str = $self->deparse($cond, 1);
  2279. $head = "$givwhen ($cond_str)";
  2280. $block = $self->deparse($cond->sibling, 0);
  2281. }
  2282. return "$head {\n".
  2283. "\t$block\n".
  2284. "\b}\cK";
  2285. }
  2286. sub pp_leavegiven { givwhen(@_, $_[0]->keyword("given")); }
  2287. sub pp_leavewhen { givwhen(@_, $_[0]->keyword("when")); }
  2288. sub pp_exists {
  2289. my $self = shift;
  2290. my($op, $cx) = @_;
  2291. my $arg;
  2292. my $name = $self->keyword("exists");
  2293. if ($op->private & OPpEXISTS_SUB) {
  2294. # Checking for the existence of a subroutine
  2295. return $self->maybe_parens_func($name,
  2296. $self->pp_rv2cv($op->first, 16), $cx, 16);
  2297. }
  2298. if ($op->flags & OPf_SPECIAL) {
  2299. # Array element, not hash element
  2300. return $self->maybe_parens_func($name,
  2301. $self->pp_aelem($op->first, 16), $cx, 16);
  2302. }
  2303. return $self->maybe_parens_func($name, $self->pp_helem($op->first, 16),
  2304. $cx, 16);
  2305. }
  2306. sub pp_delete {
  2307. my $self = shift;
  2308. my($op, $cx) = @_;
  2309. my $arg;
  2310. my $name = $self->keyword("delete");
  2311. if ($op->private & OPpSLICE) {
  2312. if ($op->flags & OPf_SPECIAL) {
  2313. # Deleting from an array, not a hash
  2314. return $self->maybe_parens_func($name,
  2315. $self->pp_aslice($op->first, 16),
  2316. $cx, 16);
  2317. }
  2318. return $self->maybe_parens_func($name,
  2319. $self->pp_hslice($op->first, 16),
  2320. $cx, 16);
  2321. } else {
  2322. if ($op->flags & OPf_SPECIAL) {
  2323. # Deleting from an array, not a hash
  2324. return $self->maybe_parens_func($name,
  2325. $self->pp_aelem($op->first, 16),
  2326. $cx, 16);
  2327. }
  2328. return $self->maybe_parens_func($name,
  2329. $self->pp_helem($op->first, 16),
  2330. $cx, 16);
  2331. }
  2332. }
  2333. sub pp_require {
  2334. my $self = shift;
  2335. my($op, $cx) = @_;
  2336. my $opname = $op->flags & OPf_SPECIAL ? 'CORE::require' : 'require';
  2337. my $kid = $op->first;
  2338. if ($kid->name eq 'const') {
  2339. my $priv = $kid->private;
  2340. my $sv = $self->const_sv($kid);
  2341. my $arg;
  2342. if ($priv & OPpCONST_BARE) {
  2343. $arg = $sv->PV;
  2344. $arg =~ s[/][::]g;
  2345. $arg =~ s/\.pm//g;
  2346. } elsif ($priv & OPpCONST_NOVER) {
  2347. $opname = $self->keyword('no');
  2348. $arg = $self->const($sv, 16);
  2349. } elsif ((my $tmp = $self->const($sv, 16)) =~ /^v/) {
  2350. $arg = $tmp;
  2351. }
  2352. if ($arg) {
  2353. return $self->maybe_parens("$opname $arg", $cx, 16);
  2354. }
  2355. }
  2356. $self->unop(
  2357. $op, $cx,
  2358. $opname,
  2359. 1, # llafr does not apply
  2360. );
  2361. }
  2362. sub pp_scalar {
  2363. my $self = shift;
  2364. my($op, $cx) = @_;
  2365. my $kid = $op->first;
  2366. if (not null $kid->sibling) {
  2367. # XXX Was a here-doc
  2368. return $self->dquote($op);
  2369. }
  2370. $self->unop(@_, "scalar");
  2371. }
  2372. sub padval {
  2373. my $self = shift;
  2374. my $targ = shift;
  2375. return $self->{'curcv'}->PADLIST->ARRAYelt(1)->ARRAYelt($targ);
  2376. }
  2377. sub anon_hash_or_list {
  2378. my $self = shift;
  2379. my($op, $cx) = @_;
  2380. my($pre, $post) = @{{"anonlist" => ["[","]"],
  2381. "anonhash" => ["{","}"]}->{$op->name}};
  2382. my($expr, @exprs);
  2383. $op = $op->first->sibling; # skip pushmark
  2384. for (; !null($op); $op = $op->sibling) {
  2385. $expr = $self->deparse($op, 6);
  2386. push @exprs, $expr;
  2387. }
  2388. if ($pre eq "{" and $cx < 1) {
  2389. # Disambiguate that it's not a block
  2390. $pre = "+{";
  2391. }
  2392. return $pre . join(", ", @exprs) . $post;
  2393. }
  2394. sub pp_anonlist {
  2395. my $self = shift;
  2396. my ($op, $cx) = @_;
  2397. if ($op->flags & OPf_SPECIAL) {
  2398. return $self->anon_hash_or_list($op, $cx);
  2399. }
  2400. warn "Unexpected op pp_" . $op->name() . " without OPf_SPECIAL";
  2401. return 'XXX';
  2402. }
  2403. *pp_anonhash = \&pp_anonlist;
  2404. sub pp_refgen {
  2405. my $self = shift;
  2406. my($op, $cx) = @_;
  2407. my $kid = $op->first;
  2408. if ($kid->name eq "null") {
  2409. my $anoncode = $kid = $kid->first;
  2410. if ($anoncode->name eq "anonconst") {
  2411. $anoncode = $anoncode->first->first->sibling;
  2412. }
  2413. if ($anoncode->name eq "anoncode"
  2414. or !null($anoncode = $kid->sibling) and
  2415. $anoncode->name eq "anoncode") {
  2416. return $self->e_anoncode({ code => $self->padval($anoncode->targ) });
  2417. } elsif ($kid->name eq "pushmark") {
  2418. my $sib_name = $kid->sibling->name;
  2419. if ($sib_name eq 'entersub') {
  2420. my $text = $self->deparse($kid->sibling, 1);
  2421. # Always show parens for \(&func()), but only with -p otherwise
  2422. $text = "($text)" if $self->{'parens'}
  2423. or $kid->sibling->private & OPpENTERSUB_AMPER;
  2424. return "\\$text";
  2425. }
  2426. }
  2427. }
  2428. local $self->{'in_refgen'} = 1;
  2429. $self->pfixop($op, $cx, "\\", 20);
  2430. }
  2431. sub e_anoncode {
  2432. my ($self, $info) = @_;
  2433. my $text = $self->deparse_sub($info->{code});
  2434. return $self->keyword("sub") . " $text";
  2435. }
  2436. sub pp_srefgen { pp_refgen(@_) }
  2437. sub pp_readline {
  2438. my $self = shift;
  2439. my($op, $cx) = @_;
  2440. my $kid = $op->first;
  2441. if (is_scalar($kid)) {
  2442. my $kid_deparsed = $self->deparse($kid, 1);
  2443. return '<<>>' if $op->flags & OPf_SPECIAL and $kid_deparsed eq 'ARGV';
  2444. return "<$kid_deparsed>";
  2445. }
  2446. return $self->unop($op, $cx, "readline");
  2447. }
  2448. sub pp_rcatline {
  2449. my $self = shift;
  2450. my($op) = @_;
  2451. return "<" . $self->gv_name($self->gv_or_padgv($op)) . ">";
  2452. }
  2453. # Unary operators that can occur as pseudo-listops inside double quotes
  2454. sub dq_unop {
  2455. my $self = shift;
  2456. my($op, $cx, $name, $prec, $flags) = (@_, 0, 0);
  2457. my $kid;
  2458. if ($op->flags & OPf_KIDS) {
  2459. $kid = $op->first;
  2460. # If there's more than one kid, the first is an ex-pushmark.
  2461. $kid = $kid->sibling if not null $kid->sibling;
  2462. return $self->maybe_parens_unop($name, $kid, $cx);
  2463. } else {
  2464. return $name . ($op->flags & OPf_SPECIAL ? "()" : "");
  2465. }
  2466. }
  2467. sub pp_ucfirst { dq_unop(@_, "ucfirst") }
  2468. sub pp_lcfirst { dq_unop(@_, "lcfirst") }
  2469. sub pp_uc { dq_unop(@_, "uc") }
  2470. sub pp_lc { dq_unop(@_, "lc") }
  2471. sub pp_quotemeta { maybe_targmy(@_, \&dq_unop, "quotemeta") }
  2472. sub pp_fc { dq_unop(@_, "fc") }
  2473. sub loopex {
  2474. my $self = shift;
  2475. my ($op, $cx, $name) = @_;
  2476. if (class($op) eq "PVOP") {
  2477. $name .= " " . $op->pv;
  2478. } elsif (class($op) eq "OP") {
  2479. # no-op
  2480. } elsif (class($op) eq "UNOP") {
  2481. (my $kid = $self->deparse($op->first, 7)) =~ s/^\cS//;
  2482. # last foo() is a syntax error.
  2483. $kid =~ /^(?!\d)\w/ and $kid = "($kid)";
  2484. $name .= " $kid";
  2485. }
  2486. return $self->maybe_parens($name, $cx, 7);
  2487. }
  2488. sub pp_last { loopex(@_, "last") }
  2489. sub pp_next { loopex(@_, "next") }
  2490. sub pp_redo { loopex(@_, "redo") }
  2491. sub pp_goto { loopex(@_, "goto") }
  2492. sub pp_dump { loopex(@_, "CORE::dump") }
  2493. sub ftst {
  2494. my $self = shift;
  2495. my($op, $cx, $name) = @_;
  2496. if (class($op) eq "UNOP") {
  2497. # Genuine '-X' filetests are exempt from the LLAFR, but not
  2498. # l?stat()
  2499. if ($name =~ /^-/) {
  2500. (my $kid = $self->deparse($op->first, 16)) =~ s/^\cS//;
  2501. return $self->maybe_parens("$name $kid", $cx, 16);
  2502. }
  2503. return $self->maybe_parens_unop($name, $op->first, $cx);
  2504. } elsif (class($op) =~ /^(SV|PAD)OP$/) {
  2505. return $self->maybe_parens_func($name, $self->pp_gv($op, 1), $cx, 16);
  2506. } else { # I don't think baseop filetests ever survive ck_ftst, but...
  2507. return $name;
  2508. }
  2509. }
  2510. sub pp_lstat { ftst(@_, "lstat") }
  2511. sub pp_stat { ftst(@_, "stat") }
  2512. sub pp_ftrread { ftst(@_, "-R") }
  2513. sub pp_ftrwrite { ftst(@_, "-W") }
  2514. sub pp_ftrexec { ftst(@_, "-X") }
  2515. sub pp_fteread { ftst(@_, "-r") }
  2516. sub pp_ftewrite { ftst(@_, "-w") }
  2517. sub pp_fteexec { ftst(@_, "-x") }
  2518. sub pp_ftis { ftst(@_, "-e") }
  2519. sub pp_fteowned { ftst(@_, "-O") }
  2520. sub pp_ftrowned { ftst(@_, "-o") }
  2521. sub pp_ftzero { ftst(@_, "-z") }
  2522. sub pp_ftsize { ftst(@_, "-s") }
  2523. sub pp_ftmtime { ftst(@_, "-M") }
  2524. sub pp_ftatime { ftst(@_, "-A") }
  2525. sub pp_ftctime { ftst(@_, "-C") }
  2526. sub pp_ftsock { ftst(@_, "-S") }
  2527. sub pp_ftchr { ftst(@_, "-c") }
  2528. sub pp_ftblk { ftst(@_, "-b") }
  2529. sub pp_ftfile { ftst(@_, "-f") }
  2530. sub pp_ftdir { ftst(@_, "-d") }
  2531. sub pp_ftpipe { ftst(@_, "-p") }
  2532. sub pp_ftlink { ftst(@_, "-l") }
  2533. sub pp_ftsuid { ftst(@_, "-u") }
  2534. sub pp_ftsgid { ftst(@_, "-g") }
  2535. sub pp_ftsvtx { ftst(@_, "-k") }
  2536. sub pp_fttty { ftst(@_, "-t") }
  2537. sub pp_fttext { ftst(@_, "-T") }
  2538. sub pp_ftbinary { ftst(@_, "-B") }
  2539. sub SWAP_CHILDREN () { 1 }
  2540. sub ASSIGN () { 2 } # has OP= variant
  2541. sub LIST_CONTEXT () { 4 } # Assignment is in list context
  2542. my(%left, %right);
  2543. sub assoc_class {
  2544. my $op = shift;
  2545. my $name = $op->name;
  2546. if ($name eq "concat" and $op->first->name eq "concat") {
  2547. # avoid spurious '=' -- see comment in pp_concat
  2548. return "concat";
  2549. }
  2550. if ($name eq "null" and class($op) eq "UNOP"
  2551. and $op->first->name =~ /^(and|x?or)$/
  2552. and null $op->first->sibling)
  2553. {
  2554. # Like all conditional constructs, OP_ANDs and OP_ORs are topped
  2555. # with a null that's used as the common end point of the two
  2556. # flows of control. For precedence purposes, ignore it.
  2557. # (COND_EXPRs have these too, but we don't bother with
  2558. # their associativity).
  2559. return assoc_class($op->first);
  2560. }
  2561. return $name . ($op->flags & OPf_STACKED ? "=" : "");
  2562. }
  2563. # Left associative operators, like '+', for which
  2564. # $a + $b + $c is equivalent to ($a + $b) + $c
  2565. BEGIN {
  2566. %left = ('multiply' => 19, 'i_multiply' => 19,
  2567. 'divide' => 19, 'i_divide' => 19,
  2568. 'modulo' => 19, 'i_modulo' => 19,
  2569. 'repeat' => 19,
  2570. 'add' => 18, 'i_add' => 18,
  2571. 'subtract' => 18, 'i_subtract' => 18,
  2572. 'concat' => 18,
  2573. 'left_shift' => 17, 'right_shift' => 17,
  2574. 'bit_and' => 13, 'nbit_and' => 13, 'sbit_and' => 13,
  2575. 'bit_or' => 12, 'bit_xor' => 12,
  2576. 'sbit_or' => 12, 'sbit_xor' => 12,
  2577. 'nbit_or' => 12, 'nbit_xor' => 12,
  2578. 'and' => 3,
  2579. 'or' => 2, 'xor' => 2,
  2580. );
  2581. }
  2582. sub deparse_binop_left {
  2583. my $self = shift;
  2584. my($op, $left, $prec) = @_;
  2585. if ($left{assoc_class($op)} && $left{assoc_class($left)}
  2586. and $left{assoc_class($op)} == $left{assoc_class($left)})
  2587. {
  2588. return $self->deparse($left, $prec - .00001);
  2589. } else {
  2590. return $self->deparse($left, $prec);
  2591. }
  2592. }
  2593. # Right associative operators, like '=', for which
  2594. # $a = $b = $c is equivalent to $a = ($b = $c)
  2595. BEGIN {
  2596. %right = ('pow' => 22,
  2597. 'sassign=' => 7, 'aassign=' => 7,
  2598. 'multiply=' => 7, 'i_multiply=' => 7,
  2599. 'divide=' => 7, 'i_divide=' => 7,
  2600. 'modulo=' => 7, 'i_modulo=' => 7,
  2601. 'repeat=' => 7, 'refassign' => 7, 'refassign=' => 7,
  2602. 'add=' => 7, 'i_add=' => 7,
  2603. 'subtract=' => 7, 'i_subtract=' => 7,
  2604. 'concat=' => 7,
  2605. 'left_shift=' => 7, 'right_shift=' => 7,
  2606. 'bit_and=' => 7, 'sbit_and=' => 7, 'nbit_and=' => 7,
  2607. 'nbit_or=' => 7, 'nbit_xor=' => 7,
  2608. 'sbit_or=' => 7, 'sbit_xor=' => 7,
  2609. 'andassign' => 7,
  2610. 'orassign' => 7,
  2611. );
  2612. }
  2613. sub deparse_binop_right {
  2614. my $self = shift;
  2615. my($op, $right, $prec) = @_;
  2616. if ($right{assoc_class($op)} && $right{assoc_class($right)}
  2617. and $right{assoc_class($op)} == $right{assoc_class($right)})
  2618. {
  2619. return $self->deparse($right, $prec - .00001);
  2620. } else {
  2621. return $self->deparse($right, $prec);
  2622. }
  2623. }
  2624. sub binop {
  2625. my $self = shift;
  2626. my ($op, $cx, $opname, $prec, $flags) = (@_, 0);
  2627. my $left = $op->first;
  2628. my $right = $op->last;
  2629. my $eq = "";
  2630. if ($op->flags & OPf_STACKED && $flags & ASSIGN) {
  2631. $eq = "=";
  2632. $prec = 7;
  2633. }
  2634. if ($flags & SWAP_CHILDREN) {
  2635. ($left, $right) = ($right, $left);
  2636. }
  2637. my $leftop = $left;
  2638. $left = $self->deparse_binop_left($op, $left, $prec);
  2639. $left = "($left)" if $flags & LIST_CONTEXT
  2640. and $left !~ /^(my|our|local|)[\@\(]/
  2641. || do {
  2642. # Parenthesize if the left argument is a
  2643. # lone repeat op.
  2644. my $left = $leftop->first->sibling;
  2645. $left->name eq 'repeat'
  2646. && null($left->sibling);
  2647. };
  2648. $right = $self->deparse_binop_right($op, $right, $prec);
  2649. return $self->maybe_parens("$left $opname$eq $right", $cx, $prec);
  2650. }
  2651. sub pp_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
  2652. sub pp_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
  2653. sub pp_subtract { maybe_targmy(@_, \&binop, "-",18, ASSIGN) }
  2654. sub pp_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
  2655. sub pp_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
  2656. sub pp_i_add { maybe_targmy(@_, \&binop, "+", 18, ASSIGN) }
  2657. sub pp_i_multiply { maybe_targmy(@_, \&binop, "*", 19, ASSIGN) }
  2658. sub pp_i_subtract { maybe_targmy(@_, \&binop, "-", 18, ASSIGN) }
  2659. sub pp_i_divide { maybe_targmy(@_, \&binop, "/", 19, ASSIGN) }
  2660. sub pp_i_modulo { maybe_targmy(@_, \&binop, "%", 19, ASSIGN) }
  2661. sub pp_pow { maybe_targmy(@_, \&binop, "**", 22, ASSIGN) }
  2662. sub pp_left_shift { maybe_targmy(@_, \&binop, "<<", 17, ASSIGN) }
  2663. sub pp_right_shift { maybe_targmy(@_, \&binop, ">>", 17, ASSIGN) }
  2664. sub pp_bit_and { maybe_targmy(@_, \&binop, "&", 13, ASSIGN) }
  2665. sub pp_bit_or { maybe_targmy(@_, \&binop, "|", 12, ASSIGN) }
  2666. sub pp_bit_xor { maybe_targmy(@_, \&binop, "^", 12, ASSIGN) }
  2667. *pp_nbit_and = *pp_bit_and;
  2668. *pp_nbit_or = *pp_bit_or;
  2669. *pp_nbit_xor = *pp_bit_xor;
  2670. sub pp_sbit_and { maybe_targmy(@_, \&binop, "&.", 13, ASSIGN) }
  2671. sub pp_sbit_or { maybe_targmy(@_, \&binop, "|.", 12, ASSIGN) }
  2672. sub pp_sbit_xor { maybe_targmy(@_, \&binop, "^.", 12, ASSIGN) }
  2673. sub pp_eq { binop(@_, "==", 14) }
  2674. sub pp_ne { binop(@_, "!=", 14) }
  2675. sub pp_lt { binop(@_, "<", 15) }
  2676. sub pp_gt { binop(@_, ">", 15) }
  2677. sub pp_ge { binop(@_, ">=", 15) }
  2678. sub pp_le { binop(@_, "<=", 15) }
  2679. sub pp_ncmp { binop(@_, "<=>", 14) }
  2680. sub pp_i_eq { binop(@_, "==", 14) }
  2681. sub pp_i_ne { binop(@_, "!=", 14) }
  2682. sub pp_i_lt { binop(@_, "<", 15) }
  2683. sub pp_i_gt { binop(@_, ">", 15) }
  2684. sub pp_i_ge { binop(@_, ">=", 15) }
  2685. sub pp_i_le { binop(@_, "<=", 15) }
  2686. sub pp_i_ncmp { maybe_targmy(@_, \&binop, "<=>", 14) }
  2687. sub pp_seq { binop(@_, "eq", 14) }
  2688. sub pp_sne { binop(@_, "ne", 14) }
  2689. sub pp_slt { binop(@_, "lt", 15) }
  2690. sub pp_sgt { binop(@_, "gt", 15) }
  2691. sub pp_sge { binop(@_, "ge", 15) }
  2692. sub pp_sle { binop(@_, "le", 15) }
  2693. sub pp_scmp { maybe_targmy(@_, \&binop, "cmp", 14) }
  2694. sub pp_sassign { binop(@_, "=", 7, SWAP_CHILDREN) }
  2695. sub pp_aassign { binop(@_, "=", 7, SWAP_CHILDREN | LIST_CONTEXT) }
  2696. sub pp_smartmatch {
  2697. my ($self, $op, $cx) = @_;
  2698. if ($op->flags & OPf_SPECIAL) {
  2699. return $self->deparse($op->last, $cx);
  2700. }
  2701. else {
  2702. binop(@_, "~~", 14);
  2703. }
  2704. }
  2705. # '.' is special because concats-of-concats are optimized to save copying
  2706. # by making all but the first concat stacked. The effect is as if the
  2707. # programmer had written '($a . $b) .= $c', except legal.
  2708. sub pp_concat { maybe_targmy(@_, \&real_concat) }
  2709. sub real_concat {
  2710. my $self = shift;
  2711. my($op, $cx) = @_;
  2712. my $left = $op->first;
  2713. my $right = $op->last;
  2714. my $eq = "";
  2715. my $prec = 18;
  2716. if ($op->flags & OPf_STACKED and $op->first->name ne "concat") {
  2717. $eq = "=";
  2718. $prec = 7;
  2719. }
  2720. $left = $self->deparse_binop_left($op, $left, $prec);
  2721. $right = $self->deparse_binop_right($op, $right, $prec);
  2722. return $self->maybe_parens("$left .$eq $right", $cx, $prec);
  2723. }
  2724. sub pp_repeat { maybe_targmy(@_, \&repeat) }
  2725. # 'x' is weird when the left arg is a list
  2726. sub repeat {
  2727. my $self = shift;
  2728. my($op, $cx) = @_;
  2729. my $left = $op->first;
  2730. my $right = $op->last;
  2731. my $eq = "";
  2732. my $prec = 19;
  2733. if ($op->flags & OPf_STACKED) {
  2734. $eq = "=";
  2735. $prec = 7;
  2736. }
  2737. if (null($right)) { # list repeat; count is inside left-side ex-list
  2738. # in 5.21.5 and earlier
  2739. my $kid = $left->first->sibling; # skip pushmark
  2740. my @exprs;
  2741. for (; !null($kid->sibling); $kid = $kid->sibling) {
  2742. push @exprs, $self->deparse($kid, 6);
  2743. }
  2744. $right = $kid;
  2745. $left = "(" . join(", ", @exprs). ")";
  2746. } else {
  2747. my $dolist = $op->private & OPpREPEAT_DOLIST;
  2748. $left = $self->deparse_binop_left($op, $left, $dolist ? 1 : $prec);
  2749. if ($dolist) {
  2750. $left = "($left)";
  2751. }
  2752. }
  2753. $right = $self->deparse_binop_right($op, $right, $prec);
  2754. return $self->maybe_parens("$left x$eq $right", $cx, $prec);
  2755. }
  2756. sub range {
  2757. my $self = shift;
  2758. my ($op, $cx, $type) = @_;
  2759. my $left = $op->first;
  2760. my $right = $left->sibling;
  2761. $left = $self->deparse($left, 9);
  2762. $right = $self->deparse($right, 9);
  2763. return $self->maybe_parens("$left $type $right", $cx, 9);
  2764. }
  2765. sub pp_flop {
  2766. my $self = shift;
  2767. my($op, $cx) = @_;
  2768. my $flip = $op->first;
  2769. my $type = ($flip->flags & OPf_SPECIAL) ? "..." : "..";
  2770. return $self->range($flip->first, $cx, $type);
  2771. }
  2772. # one-line while/until is handled in pp_leave
  2773. sub logop {
  2774. my $self = shift;
  2775. my ($op, $cx, $lowop, $lowprec, $highop, $highprec, $blockname) = @_;
  2776. my $left = $op->first;
  2777. my $right = $op->first->sibling;
  2778. $blockname &&= $self->keyword($blockname);
  2779. if ($cx < 1 and is_scope($right) and $blockname
  2780. and $self->{'expand'} < 7)
  2781. { # if ($a) {$b}
  2782. $left = $self->deparse($left, 1);
  2783. $right = $self->deparse($right, 0);
  2784. return "$blockname ($left) {\n\t$right\n\b}\cK";
  2785. } elsif ($cx < 1 and $blockname and not $self->{'parens'}
  2786. and $self->{'expand'} < 7) { # $b if $a
  2787. $right = $self->deparse($right, 1);
  2788. $left = $self->deparse($left, 1);
  2789. return "$right $blockname $left";
  2790. } elsif ($cx > $lowprec and $highop) { # $a && $b
  2791. $left = $self->deparse_binop_left($op, $left, $highprec);
  2792. $right = $self->deparse_binop_right($op, $right, $highprec);
  2793. return $self->maybe_parens("$left $highop $right", $cx, $highprec);
  2794. } else { # $a and $b
  2795. $left = $self->deparse_binop_left($op, $left, $lowprec);
  2796. $right = $self->deparse_binop_right($op, $right, $lowprec);
  2797. return $self->maybe_parens("$left $lowop $right", $cx, $lowprec);
  2798. }
  2799. }
  2800. sub pp_and { logop(@_, "and", 3, "&&", 11, "if") }
  2801. sub pp_or { logop(@_, "or", 2, "||", 10, "unless") }
  2802. sub pp_dor { logop(@_, "//", 10) }
  2803. # xor is syntactically a logop, but it's really a binop (contrary to
  2804. # old versions of opcode.pl). Syntax is what matters here.
  2805. sub pp_xor { logop(@_, "xor", 2, "", 0, "") }
  2806. sub logassignop {
  2807. my $self = shift;
  2808. my ($op, $cx, $opname) = @_;
  2809. my $left = $op->first;
  2810. my $right = $op->first->sibling->first; # skip sassign
  2811. $left = $self->deparse($left, 7);
  2812. $right = $self->deparse($right, 7);
  2813. return $self->maybe_parens("$left $opname $right", $cx, 7);
  2814. }
  2815. sub pp_andassign { logassignop(@_, "&&=") }
  2816. sub pp_orassign { logassignop(@_, "||=") }
  2817. sub pp_dorassign { logassignop(@_, "//=") }
  2818. sub rv2gv_or_string {
  2819. my($self,$op) = @_;
  2820. if ($op->name eq "gv") { # could be open("open") or open("###")
  2821. my($name,$quoted) =
  2822. $self->stash_variable_name("", $self->gv_or_padgv($op));
  2823. $quoted ? $name : "*$name";
  2824. }
  2825. else {
  2826. $self->deparse($op, 6);
  2827. }
  2828. }
  2829. sub listop {
  2830. my $self = shift;
  2831. my($op, $cx, $name, $kid, $nollafr) = @_;
  2832. my(@exprs);
  2833. my $parens = ($cx >= 5) || $self->{'parens'};
  2834. $kid ||= $op->first->sibling;
  2835. # If there are no arguments, add final parentheses (or parenthesize the
  2836. # whole thing if the llafr does not apply) to account for cases like
  2837. # (return)+1 or setpgrp()+1. When the llafr does not apply, we use a
  2838. # precedence of 6 (< comma), as "return, 1" does not need parentheses.
  2839. if (null $kid) {
  2840. return $nollafr
  2841. ? $self->maybe_parens($self->keyword($name), $cx, 7)
  2842. : $self->keyword($name) . '()' x (7 < $cx);
  2843. }
  2844. my $first;
  2845. my $fullname = $self->keyword($name);
  2846. my $proto = prototype("CORE::$name");
  2847. if (
  2848. ( (defined $proto && $proto =~ /^;?\*/)
  2849. || $name eq 'select' # select(F) doesn't have a proto
  2850. )
  2851. && $kid->name eq "rv2gv"
  2852. && !($kid->private & OPpLVAL_INTRO)
  2853. ) {
  2854. $first = $self->rv2gv_or_string($kid->first);
  2855. }
  2856. else {
  2857. $first = $self->deparse($kid, 6);
  2858. }
  2859. if ($name eq "chmod" && $first =~ /^\d+$/) {
  2860. $first = sprintf("%#o", $first);
  2861. }
  2862. $first = "+$first"
  2863. if not $parens and not $nollafr and substr($first, 0, 1) eq "(";
  2864. push @exprs, $first;
  2865. $kid = $kid->sibling;
  2866. if (defined $proto && $proto =~ /^\*\*/ && $kid->name eq "rv2gv"
  2867. && !($kid->private & OPpLVAL_INTRO)) {
  2868. push @exprs, $first = $self->rv2gv_or_string($kid->first);
  2869. $kid = $kid->sibling;
  2870. }
  2871. for (; !null($kid); $kid = $kid->sibling) {
  2872. push @exprs, $self->deparse($kid, 6);
  2873. }
  2874. if ($name eq "reverse" && ($op->private & OPpREVERSE_INPLACE)) {
  2875. return "$exprs[0] = $fullname"
  2876. . ($parens ? "($exprs[0])" : " $exprs[0]");
  2877. }
  2878. if ($parens && $nollafr) {
  2879. return "($fullname " . join(", ", @exprs) . ")";
  2880. } elsif ($parens) {
  2881. return "$fullname(" . join(", ", @exprs) . ")";
  2882. } else {
  2883. return "$fullname " . join(", ", @exprs);
  2884. }
  2885. }
  2886. sub pp_bless { listop(@_, "bless") }
  2887. sub pp_atan2 { maybe_targmy(@_, \&listop, "atan2") }
  2888. sub pp_substr {
  2889. my ($self,$op,$cx) = @_;
  2890. if ($op->private & OPpSUBSTR_REPL_FIRST) {
  2891. return
  2892. listop($self, $op, 7, "substr", $op->first->sibling->sibling)
  2893. . " = "
  2894. . $self->deparse($op->first->sibling, 7);
  2895. }
  2896. maybe_local(@_, listop(@_, "substr"))
  2897. }
  2898. sub pp_vec { maybe_targmy(@_, \&maybe_local, listop(@_, "vec")) }
  2899. sub pp_index { maybe_targmy(@_, \&listop, "index") }
  2900. sub pp_rindex { maybe_targmy(@_, \&listop, "rindex") }
  2901. sub pp_sprintf { maybe_targmy(@_, \&listop, "sprintf") }
  2902. sub pp_formline { listop(@_, "formline") } # see also deparse_format
  2903. sub pp_crypt { maybe_targmy(@_, \&listop, "crypt") }
  2904. sub pp_unpack { listop(@_, "unpack") }
  2905. sub pp_pack { listop(@_, "pack") }
  2906. sub pp_join { maybe_targmy(@_, \&listop, "join") }
  2907. sub pp_splice { listop(@_, "splice") }
  2908. sub pp_push { maybe_targmy(@_, \&listop, "push") }
  2909. sub pp_unshift { maybe_targmy(@_, \&listop, "unshift") }
  2910. sub pp_reverse { listop(@_, "reverse") }
  2911. sub pp_warn { listop(@_, "warn") }
  2912. sub pp_die { listop(@_, "die") }
  2913. sub pp_return { listop(@_, "return", undef, 1) } # llafr does not apply
  2914. sub pp_open { listop(@_, "open") }
  2915. sub pp_pipe_op { listop(@_, "pipe") }
  2916. sub pp_tie { listop(@_, "tie") }
  2917. sub pp_binmode { listop(@_, "binmode") }
  2918. sub pp_dbmopen { listop(@_, "dbmopen") }
  2919. sub pp_sselect { listop(@_, "select") }
  2920. sub pp_select { listop(@_, "select") }
  2921. sub pp_read { listop(@_, "read") }
  2922. sub pp_sysopen { listop(@_, "sysopen") }
  2923. sub pp_sysseek { listop(@_, "sysseek") }
  2924. sub pp_sysread { listop(@_, "sysread") }
  2925. sub pp_syswrite { listop(@_, "syswrite") }
  2926. sub pp_send { listop(@_, "send") }
  2927. sub pp_recv { listop(@_, "recv") }
  2928. sub pp_seek { listop(@_, "seek") }
  2929. sub pp_fcntl { listop(@_, "fcntl") }
  2930. sub pp_ioctl { listop(@_, "ioctl") }
  2931. sub pp_flock { maybe_targmy(@_, \&listop, "flock") }
  2932. sub pp_socket { listop(@_, "socket") }
  2933. sub pp_sockpair { listop(@_, "socketpair") }
  2934. sub pp_bind { listop(@_, "bind") }
  2935. sub pp_connect { listop(@_, "connect") }
  2936. sub pp_listen { listop(@_, "listen") }
  2937. sub pp_accept { listop(@_, "accept") }
  2938. sub pp_shutdown { listop(@_, "shutdown") }
  2939. sub pp_gsockopt { listop(@_, "getsockopt") }
  2940. sub pp_ssockopt { listop(@_, "setsockopt") }
  2941. sub pp_chown { maybe_targmy(@_, \&listop, "chown") }
  2942. sub pp_unlink { maybe_targmy(@_, \&listop, "unlink") }
  2943. sub pp_chmod { maybe_targmy(@_, \&listop, "chmod") }
  2944. sub pp_utime { maybe_targmy(@_, \&listop, "utime") }
  2945. sub pp_rename { maybe_targmy(@_, \&listop, "rename") }
  2946. sub pp_link { maybe_targmy(@_, \&listop, "link") }
  2947. sub pp_symlink { maybe_targmy(@_, \&listop, "symlink") }
  2948. sub pp_mkdir { maybe_targmy(@_, \&listop, "mkdir") }
  2949. sub pp_open_dir { listop(@_, "opendir") }
  2950. sub pp_seekdir { listop(@_, "seekdir") }
  2951. sub pp_waitpid { maybe_targmy(@_, \&listop, "waitpid") }
  2952. sub pp_system { maybe_targmy(@_, \&indirop, "system") }
  2953. sub pp_exec { maybe_targmy(@_, \&indirop, "exec") }
  2954. sub pp_kill { maybe_targmy(@_, \&listop, "kill") }
  2955. sub pp_setpgrp { maybe_targmy(@_, \&listop, "setpgrp") }
  2956. sub pp_getpriority { maybe_targmy(@_, \&listop, "getpriority") }
  2957. sub pp_setpriority { maybe_targmy(@_, \&listop, "setpriority") }
  2958. sub pp_shmget { listop(@_, "shmget") }
  2959. sub pp_shmctl { listop(@_, "shmctl") }
  2960. sub pp_shmread { listop(@_, "shmread") }
  2961. sub pp_shmwrite { listop(@_, "shmwrite") }
  2962. sub pp_msgget { listop(@_, "msgget") }
  2963. sub pp_msgctl { listop(@_, "msgctl") }
  2964. sub pp_msgsnd { listop(@_, "msgsnd") }
  2965. sub pp_msgrcv { listop(@_, "msgrcv") }
  2966. sub pp_semget { listop(@_, "semget") }
  2967. sub pp_semctl { listop(@_, "semctl") }
  2968. sub pp_semop { listop(@_, "semop") }
  2969. sub pp_ghbyaddr { listop(@_, "gethostbyaddr") }
  2970. sub pp_gnbyaddr { listop(@_, "getnetbyaddr") }
  2971. sub pp_gpbynumber { listop(@_, "getprotobynumber") }
  2972. sub pp_gsbyname { listop(@_, "getservbyname") }
  2973. sub pp_gsbyport { listop(@_, "getservbyport") }
  2974. sub pp_syscall { listop(@_, "syscall") }
  2975. sub pp_glob {
  2976. my $self = shift;
  2977. my($op, $cx) = @_;
  2978. my $kid = $op->first->sibling; # skip pushmark
  2979. my $keyword =
  2980. $op->flags & OPf_SPECIAL ? 'glob' : $self->keyword('glob');
  2981. my $text;
  2982. if ($keyword =~ /^CORE::/
  2983. or $kid->name ne 'const'
  2984. or ($text = $self->dq($kid))
  2985. =~ /^\$?(\w|::|\`)+$/ # could look like a readline
  2986. or $text =~ /[<>]/) {
  2987. $text = $self->deparse($kid);
  2988. return $cx >= 5 || $self->{'parens'}
  2989. ? "$keyword($text)"
  2990. : "$keyword $text";
  2991. } else {
  2992. return '<' . $text . '>';
  2993. }
  2994. }
  2995. # Truncate is special because OPf_SPECIAL makes a bareword first arg
  2996. # be a filehandle. This could probably be better fixed in the core
  2997. # by moving the GV lookup into ck_truc.
  2998. sub pp_truncate {
  2999. my $self = shift;
  3000. my($op, $cx) = @_;
  3001. my(@exprs);
  3002. my $parens = ($cx >= 5) || $self->{'parens'};
  3003. my $kid = $op->first->sibling;
  3004. my $fh;
  3005. if ($op->flags & OPf_SPECIAL) {
  3006. # $kid is an OP_CONST
  3007. $fh = $self->const_sv($kid)->PV;
  3008. } else {
  3009. $fh = $self->deparse($kid, 6);
  3010. $fh = "+$fh" if not $parens and substr($fh, 0, 1) eq "(";
  3011. }
  3012. my $len = $self->deparse($kid->sibling, 6);
  3013. my $name = $self->keyword('truncate');
  3014. if ($parens) {
  3015. return "$name($fh, $len)";
  3016. } else {
  3017. return "$name $fh, $len";
  3018. }
  3019. }
  3020. sub indirop {
  3021. my $self = shift;
  3022. my($op, $cx, $name) = @_;
  3023. my($expr, @exprs);
  3024. my $firstkid = my $kid = $op->first->sibling;
  3025. my $indir = "";
  3026. if ($op->flags & OPf_STACKED) {
  3027. $indir = $kid;
  3028. $indir = $indir->first; # skip rv2gv
  3029. if (is_scope($indir)) {
  3030. $indir = "{" . $self->deparse($indir, 0) . "}";
  3031. $indir = "{;}" if $indir eq "{}";
  3032. } elsif ($indir->name eq "const" && $indir->private & OPpCONST_BARE) {
  3033. $indir = $self->const_sv($indir)->PV;
  3034. } else {
  3035. $indir = $self->deparse($indir, 24);
  3036. }
  3037. $indir = $indir . " ";
  3038. $kid = $kid->sibling;
  3039. }
  3040. if ($name eq "sort" && $op->private & (OPpSORT_NUMERIC | OPpSORT_INTEGER)) {
  3041. $indir = ($op->private & OPpSORT_DESCEND) ? '{$b <=> $a} '
  3042. : '{$a <=> $b} ';
  3043. }
  3044. elsif ($name eq "sort" && $op->private & OPpSORT_DESCEND) {
  3045. $indir = '{$b cmp $a} ';
  3046. }
  3047. for (; !null($kid); $kid = $kid->sibling) {
  3048. $expr = $self->deparse($kid, !$indir && $kid == $firstkid && $name eq "sort" && $firstkid->name eq "entersub" ? 16 : 6);
  3049. push @exprs, $expr;
  3050. }
  3051. my $name2;
  3052. if ($name eq "sort" && $op->private & OPpSORT_REVERSE) {
  3053. $name2 = $self->keyword('reverse') . ' ' . $self->keyword('sort');
  3054. }
  3055. else { $name2 = $self->keyword($name) }
  3056. if ($name eq "sort" && ($op->private & OPpSORT_INPLACE)) {
  3057. return "$exprs[0] = $name2 $indir $exprs[0]";
  3058. }
  3059. my $args = $indir . join(", ", @exprs);
  3060. if ($indir ne "" && $name eq "sort") {
  3061. # We don't want to say "sort(f 1, 2, 3)", since perl -w will
  3062. # give bareword warnings in that case. Therefore if context
  3063. # requires, we'll put parens around the outside "(sort f 1, 2,
  3064. # 3)". Unfortunately, we'll currently think the parens are
  3065. # necessary more often that they really are, because we don't
  3066. # distinguish which side of an assignment we're on.
  3067. if ($cx >= 5) {
  3068. return "($name2 $args)";
  3069. } else {
  3070. return "$name2 $args";
  3071. }
  3072. } elsif (
  3073. !$indir && $name eq "sort"
  3074. && !null($op->first->sibling)
  3075. && $op->first->sibling->name eq 'entersub'
  3076. ) {
  3077. # We cannot say sort foo(bar), as foo will be interpreted as a
  3078. # comparison routine. We have to say sort(...) in that case.
  3079. return "$name2($args)";
  3080. } else {
  3081. return length $args
  3082. ? $self->maybe_parens_func($name2, $args, $cx, 5)
  3083. : $name2 . '()' x (7 < $cx);
  3084. }
  3085. }
  3086. sub pp_prtf { indirop(@_, "printf") }
  3087. sub pp_print { indirop(@_, "print") }
  3088. sub pp_say { indirop(@_, "say") }
  3089. sub pp_sort { indirop(@_, "sort") }
  3090. sub mapop {
  3091. my $self = shift;
  3092. my($op, $cx, $name) = @_;
  3093. my($expr, @exprs);
  3094. my $kid = $op->first; # this is the (map|grep)start
  3095. $kid = $kid->first->sibling; # skip a pushmark
  3096. my $code = $kid->first; # skip a null
  3097. if (is_scope $code) {
  3098. $code = "{" . $self->deparse($code, 0) . "} ";
  3099. } else {
  3100. $code = $self->deparse($code, 24);
  3101. $code .= ", " if !null($kid->sibling);
  3102. }
  3103. $kid = $kid->sibling;
  3104. for (; !null($kid); $kid = $kid->sibling) {
  3105. $expr = $self->deparse($kid, 6);
  3106. push @exprs, $expr if defined $expr;
  3107. }
  3108. return $self->maybe_parens_func($self->keyword($name),
  3109. $code . join(", ", @exprs), $cx, 5);
  3110. }
  3111. sub pp_mapwhile { mapop(@_, "map") }
  3112. sub pp_grepwhile { mapop(@_, "grep") }
  3113. sub pp_mapstart { baseop(@_, "map") }
  3114. sub pp_grepstart { baseop(@_, "grep") }
  3115. my %uses_intro;
  3116. BEGIN {
  3117. @uses_intro{
  3118. eval { require B::Op_private }
  3119. ? @{$B::Op_private::ops_using{OPpLVAL_INTRO}}
  3120. : qw(gvsv rv2sv rv2hv rv2gv rv2av aelem helem aslice
  3121. hslice delete padsv padav padhv enteriter entersub padrange
  3122. pushmark cond_expr refassign list)
  3123. } = ();
  3124. delete @uses_intro{qw( lvref lvrefslice lvavref entersub )};
  3125. }
  3126. sub pp_list {
  3127. my $self = shift;
  3128. my($op, $cx) = @_;
  3129. my($expr, @exprs);
  3130. my $kid = $op->first->sibling; # skip pushmark
  3131. return '' if class($kid) eq 'NULL';
  3132. my $lop;
  3133. my $local = "either"; # could be local(...), my(...), state(...) or our(...)
  3134. my $type;
  3135. for ($lop = $kid; !null($lop); $lop = $lop->sibling) {
  3136. my $lopname = $lop->name;
  3137. my $loppriv = $lop->private;
  3138. my $newtype;
  3139. if ($lopname =~ /^pad[ash]v$/ && $loppriv & OPpLVAL_INTRO) {
  3140. if ($loppriv & OPpPAD_STATE) { # state()
  3141. ($local = "", last) if $local !~ /^(?:either|state)$/;
  3142. $local = "state";
  3143. } else { # my()
  3144. ($local = "", last) if $local !~ /^(?:either|my)$/;
  3145. $local = "my";
  3146. }
  3147. my $padname = $self->padname_sv($lop->targ);
  3148. if ($padname->FLAGS & SVpad_TYPED) {
  3149. $newtype = $padname->SvSTASH->NAME;
  3150. }
  3151. } elsif ($lopname =~ /^(?:gv|rv2)([ash])v$/
  3152. && $loppriv & OPpOUR_INTRO
  3153. or $lopname eq "null" && class($lop) eq 'UNOP'
  3154. && $lop->first->name eq "gvsv"
  3155. && $lop->first->private & OPpOUR_INTRO) { # our()
  3156. my $newlocal = "local " x !!($loppriv & OPpLVAL_INTRO) . "our";
  3157. ($local = "", last)
  3158. if $local ne 'either' && $local ne $newlocal;
  3159. $local = $newlocal;
  3160. my $funny = !$1 || $1 eq 's' ? '$' : $1 eq 'a' ? '@' : '%';
  3161. if (my $t = $self->find_our_type(
  3162. $funny . $self->gv_or_padgv($lop->first)->NAME
  3163. )) {
  3164. $newtype = $t;
  3165. }
  3166. } elsif ($lopname ne 'undef'
  3167. and !($loppriv & OPpLVAL_INTRO)
  3168. || !exists $uses_intro{$lopname eq 'null'
  3169. ? substr B::ppname($lop->targ), 3
  3170. : $lopname})
  3171. {
  3172. $local = ""; # or not
  3173. last;
  3174. } elsif ($lopname ne "undef")
  3175. {
  3176. # local()
  3177. ($local = "", last) if $local !~ /^(?:either|local)$/;
  3178. $local = "local";
  3179. }
  3180. if (defined $type && defined $newtype && $newtype ne $type) {
  3181. $local = '';
  3182. last;
  3183. }
  3184. $type = $newtype;
  3185. }
  3186. $local = "" if $local eq "either"; # no point if it's all undefs
  3187. $local &&= join ' ', map $self->keyword($_), split / /, $local;
  3188. $local .= " $type " if $local && length $type;
  3189. return $self->deparse($kid, $cx) if null $kid->sibling and not $local;
  3190. for (; !null($kid); $kid = $kid->sibling) {
  3191. if ($local) {
  3192. if (class($kid) eq "UNOP" and $kid->first->name eq "gvsv") {
  3193. $lop = $kid->first;
  3194. } else {
  3195. $lop = $kid;
  3196. }
  3197. $self->{'avoid_local'}{$$lop}++;
  3198. $expr = $self->deparse($kid, 6);
  3199. delete $self->{'avoid_local'}{$$lop};
  3200. } else {
  3201. $expr = $self->deparse($kid, 6);
  3202. }
  3203. push @exprs, $expr;
  3204. }
  3205. if ($local) {
  3206. return "$local(" . join(", ", @exprs) . ")";
  3207. } else {
  3208. return $self->maybe_parens( join(", ", @exprs), $cx, 6);
  3209. }
  3210. }
  3211. sub is_ifelse_cont {
  3212. my $op = shift;
  3213. return ($op->name eq "null" and class($op) eq "UNOP"
  3214. and $op->first->name =~ /^(and|cond_expr)$/
  3215. and is_scope($op->first->first->sibling));
  3216. }
  3217. sub pp_cond_expr {
  3218. my $self = shift;
  3219. my($op, $cx) = @_;
  3220. my $cond = $op->first;
  3221. my $true = $cond->sibling;
  3222. my $false = $true->sibling;
  3223. my $cuddle = $self->{'cuddle'};
  3224. unless ($cx < 1 and (is_scope($true) and $true->name ne "null") and
  3225. (is_scope($false) || is_ifelse_cont($false))
  3226. and $self->{'expand'} < 7) {
  3227. $cond = $self->deparse($cond, 8);
  3228. $true = $self->deparse($true, 6);
  3229. $false = $self->deparse($false, 8);
  3230. return $self->maybe_parens("$cond ? $true : $false", $cx, 8);
  3231. }
  3232. $cond = $self->deparse($cond, 1);
  3233. $true = $self->deparse($true, 0);
  3234. my $head = $self->keyword("if") . " ($cond) {\n\t$true\n\b}";
  3235. my @elsifs;
  3236. my $elsif;
  3237. while (!null($false) and is_ifelse_cont($false)) {
  3238. my $newop = $false->first;
  3239. my $newcond = $newop->first;
  3240. my $newtrue = $newcond->sibling;
  3241. $false = $newtrue->sibling; # last in chain is OP_AND => no else
  3242. if ($newcond->name eq "lineseq")
  3243. {
  3244. # lineseq to ensure correct line numbers in elsif()
  3245. # Bug #37302 fixed by change #33710.
  3246. $newcond = $newcond->first->sibling;
  3247. }
  3248. $newcond = $self->deparse($newcond, 1);
  3249. $newtrue = $self->deparse($newtrue, 0);
  3250. $elsif ||= $self->keyword("elsif");
  3251. push @elsifs, "$elsif ($newcond) {\n\t$newtrue\n\b}";
  3252. }
  3253. if (!null($false)) {
  3254. $false = $cuddle . $self->keyword("else") . " {\n\t" .
  3255. $self->deparse($false, 0) . "\n\b}\cK";
  3256. } else {
  3257. $false = "\cK";
  3258. }
  3259. return $head . join($cuddle, "", @elsifs) . $false;
  3260. }
  3261. sub pp_once {
  3262. my ($self, $op, $cx) = @_;
  3263. my $cond = $op->first;
  3264. my $true = $cond->sibling;
  3265. my $ret = $self->deparse($true, $cx);
  3266. $ret =~ s/^(\(?)\$/$1 . $self->keyword("state") . ' $'/e;
  3267. $ret;
  3268. }
  3269. sub loop_common {
  3270. my $self = shift;
  3271. my($op, $cx, $init) = @_;
  3272. my $enter = $op->first;
  3273. my $kid = $enter->sibling;
  3274. local(@$self{qw'curstash warnings hints hinthash'})
  3275. = @$self{qw'curstash warnings hints hinthash'};
  3276. my $head = "";
  3277. my $bare = 0;
  3278. my $body;
  3279. my $cond = undef;
  3280. my $name;
  3281. if ($kid->name eq "lineseq") { # bare or infinite loop
  3282. if ($kid->last->name eq "unstack") { # infinite
  3283. $head = "while (1) "; # Can't use for(;;) if there's a continue
  3284. $cond = "";
  3285. } else {
  3286. $bare = 1;
  3287. }
  3288. $body = $kid;
  3289. } elsif ($enter->name eq "enteriter") { # foreach
  3290. my $ary = $enter->first->sibling; # first was pushmark
  3291. my $var = $ary->sibling;
  3292. if ($ary->name eq 'null' and $enter->private & OPpITER_REVERSED) {
  3293. # "reverse" was optimised away
  3294. $ary = listop($self, $ary->first->sibling, 1, 'reverse');
  3295. } elsif ($enter->flags & OPf_STACKED
  3296. and not null $ary->first->sibling->sibling)
  3297. {
  3298. $ary = $self->deparse($ary->first->sibling, 9) . " .. " .
  3299. $self->deparse($ary->first->sibling->sibling, 9);
  3300. } else {
  3301. $ary = $self->deparse($ary, 1);
  3302. }
  3303. if (null $var) {
  3304. $var = $self->pp_padsv($enter, 1, 1);
  3305. } elsif ($var->name eq "rv2gv") {
  3306. $var = $self->pp_rv2sv($var, 1);
  3307. if ($enter->private & OPpOUR_INTRO) {
  3308. # our declarations don't have package names
  3309. $var =~ s/^(.).*::/$1/;
  3310. $var = "our $var";
  3311. }
  3312. } elsif ($var->name eq "gv") {
  3313. $var = "\$" . $self->deparse($var, 1);
  3314. } else {
  3315. $var = $self->deparse($var, 1);
  3316. }
  3317. $body = $kid->first->first->sibling; # skip OP_AND and OP_ITER
  3318. if (!is_state $body->first and $body->first->name !~ /^(?:stub|leave|scope)$/) {
  3319. confess unless $var eq '$_';
  3320. $body = $body->first;
  3321. return $self->deparse($body, 2) . " "
  3322. . $self->keyword("foreach") . " ($ary)";
  3323. }
  3324. $head = "foreach $var ($ary) ";
  3325. } elsif ($kid->name eq "null") { # while/until
  3326. $kid = $kid->first;
  3327. $name = {"and" => "while", "or" => "until"}->{$kid->name};
  3328. $cond = $kid->first;
  3329. $body = $kid->first->sibling;
  3330. } elsif ($kid->name eq "stub") { # bare and empty
  3331. return "{;}"; # {} could be a hashref
  3332. }
  3333. # If there isn't a continue block, then the next pointer for the loop
  3334. # will point to the unstack, which is kid's last child, except
  3335. # in a bare loop, when it will point to the leaveloop. When neither of
  3336. # these conditions hold, then the second-to-last child is the continue
  3337. # block (or the last in a bare loop).
  3338. my $cont_start = $enter->nextop;
  3339. my $cont;
  3340. my $precond;
  3341. my $postcond;
  3342. if ($$cont_start != $$op && ${$cont_start} != ${$body->last}) {
  3343. if ($bare) {
  3344. $cont = $body->last;
  3345. } else {
  3346. $cont = $body->first;
  3347. while (!null($cont->sibling->sibling)) {
  3348. $cont = $cont->sibling;
  3349. }
  3350. }
  3351. my $state = $body->first;
  3352. my $cuddle = $self->{'cuddle'};
  3353. my @states;
  3354. for (; $$state != $$cont; $state = $state->sibling) {
  3355. push @states, $state;
  3356. }
  3357. $body = $self->lineseq(undef, 0, @states);
  3358. if (defined $cond and not is_scope $cont and $self->{'expand'} < 3) {
  3359. $precond = "for ($init; ";
  3360. $postcond = "; " . $self->deparse($cont, 1) .") ";
  3361. $cont = "\cK";
  3362. } else {
  3363. $cont = $cuddle . "continue {\n\t" .
  3364. $self->deparse($cont, 0) . "\n\b}\cK";
  3365. }
  3366. } else {
  3367. return "" if !defined $body;
  3368. if (length $init) {
  3369. $precond = "for ($init; ";
  3370. $postcond = ";) ";
  3371. }
  3372. $cont = "\cK";
  3373. $body = $self->deparse($body, 0);
  3374. }
  3375. if ($precond) { # for(;;)
  3376. $cond &&= $name eq 'until'
  3377. ? listop($self, undef, 1, "not", $cond->first)
  3378. : $self->deparse($cond, 1);
  3379. $head = "$precond$cond$postcond";
  3380. }
  3381. if ($name && !$head) {
  3382. ref $cond and $cond = $self->deparse($cond, 1);
  3383. $head = "$name ($cond) ";
  3384. }
  3385. $head =~ s/^(for(?:each)?|while|until)/$self->keyword($1)/e;
  3386. $body =~ s/;?$/;\n/;
  3387. return $head . "{\n\t" . $body . "\b}" . $cont;
  3388. }
  3389. sub pp_leaveloop { shift->loop_common(@_, "") }
  3390. sub for_loop {
  3391. my $self = shift;
  3392. my($op, $cx) = @_;
  3393. my $init = $self->deparse($op, 1);
  3394. my $s = $op->sibling;
  3395. my $ll = $s->name eq "unstack" ? $s->sibling : $s->first->sibling;
  3396. return $self->loop_common($ll, $cx, $init);
  3397. }
  3398. sub pp_leavetry {
  3399. my $self = shift;
  3400. return "eval {\n\t" . $self->pp_leave(@_) . "\n\b}";
  3401. }
  3402. sub _op_is_or_was {
  3403. my ($op, $expect_type) = @_;
  3404. my $type = $op->type;
  3405. return($type == $expect_type
  3406. || ($type == OP_NULL && $op->targ == $expect_type));
  3407. }
  3408. sub pp_null {
  3409. my($self, $op, $cx) = @_;
  3410. if (class($op) eq "OP") {
  3411. # old value is lost
  3412. return $self->{'ex_const'} if $op->targ == OP_CONST;
  3413. } elsif (class ($op) eq "COP") {
  3414. return &pp_nextstate;
  3415. } elsif ($op->first->name eq 'pushmark'
  3416. or $op->first->name eq 'null'
  3417. && $op->first->targ == OP_PUSHMARK
  3418. && _op_is_or_was($op, OP_LIST)) {
  3419. return $self->pp_list($op, $cx);
  3420. } elsif ($op->first->name eq "enter") {
  3421. return $self->pp_leave($op, $cx);
  3422. } elsif ($op->first->name eq "leave") {
  3423. return $self->pp_leave($op->first, $cx);
  3424. } elsif ($op->first->name eq "scope") {
  3425. return $self->pp_scope($op->first, $cx);
  3426. } elsif ($op->targ == OP_STRINGIFY) {
  3427. return $self->dquote($op, $cx);
  3428. } elsif ($op->targ == OP_GLOB) {
  3429. return $self->pp_glob(
  3430. $op->first # entersub
  3431. ->first # ex-list
  3432. ->first # pushmark
  3433. ->sibling, # glob
  3434. $cx
  3435. );
  3436. } elsif (!null($op->first->sibling) and
  3437. $op->first->sibling->name eq "readline" and
  3438. $op->first->sibling->flags & OPf_STACKED) {
  3439. return $self->maybe_parens($self->deparse($op->first, 7) . " = "
  3440. . $self->deparse($op->first->sibling, 7),
  3441. $cx, 7);
  3442. } elsif (!null($op->first->sibling) and
  3443. $op->first->sibling->name =~ /^transr?\z/ and
  3444. $op->first->sibling->flags & OPf_STACKED) {
  3445. return $self->maybe_parens($self->deparse($op->first, 20) . " =~ "
  3446. . $self->deparse($op->first->sibling, 20),
  3447. $cx, 20);
  3448. } elsif ($op->flags & OPf_SPECIAL && $cx < 1 && !$op->targ) {
  3449. return ($self->lex_in_scope("&do") ? "CORE::do" : "do")
  3450. . " {\n\t". $self->deparse($op->first, $cx) ."\n\b};";
  3451. } elsif (!null($op->first->sibling) and
  3452. $op->first->sibling->name eq "null" and
  3453. class($op->first->sibling) eq "UNOP" and
  3454. $op->first->sibling->first->flags & OPf_STACKED and
  3455. $op->first->sibling->first->name eq "rcatline") {
  3456. return $self->maybe_parens($self->deparse($op->first, 18) . " .= "
  3457. . $self->deparse($op->first->sibling, 18),
  3458. $cx, 18);
  3459. } else {
  3460. return $self->deparse($op->first, $cx);
  3461. }
  3462. }
  3463. sub padname {
  3464. my $self = shift;
  3465. my $targ = shift;
  3466. return $self->padname_sv($targ)->PVX;
  3467. }
  3468. sub padany {
  3469. my $self = shift;
  3470. my $op = shift;
  3471. return substr($self->padname($op->targ), 1); # skip $/@/%
  3472. }
  3473. sub pp_padsv {
  3474. my $self = shift;
  3475. my($op, $cx, $forbid_parens) = @_;
  3476. my $targ = $op->targ;
  3477. return $self->maybe_my($op, $cx, $self->padname($targ),
  3478. $self->padname_sv($targ),
  3479. $forbid_parens);
  3480. }
  3481. sub pp_padav { pp_padsv(@_) }
  3482. sub pp_padhv { pp_padsv(@_) }
  3483. sub gv_or_padgv {
  3484. my $self = shift;
  3485. my $op = shift;
  3486. if (class($op) eq "PADOP") {
  3487. return $self->padval($op->padix);
  3488. } else { # class($op) eq "SVOP"
  3489. return $op->gv;
  3490. }
  3491. }
  3492. sub pp_gvsv {
  3493. my $self = shift;
  3494. my($op, $cx) = @_;
  3495. my $gv = $self->gv_or_padgv($op);
  3496. return $self->maybe_local($op, $cx, $self->stash_variable("\$",
  3497. $self->gv_name($gv), $cx));
  3498. }
  3499. sub pp_gv {
  3500. my $self = shift;
  3501. my($op, $cx) = @_;
  3502. my $gv = $self->gv_or_padgv($op);
  3503. return $self->gv_name($gv);
  3504. }
  3505. sub pp_aelemfast_lex {
  3506. my $self = shift;
  3507. my($op, $cx) = @_;
  3508. my $name = $self->padname($op->targ);
  3509. $name =~ s/^@/\$/;
  3510. my $i = $op->private;
  3511. $i -= 256 if $i > 127;
  3512. return $name . "[" . ($i + $self->{'arybase'}) . "]";
  3513. }
  3514. sub pp_aelemfast {
  3515. my $self = shift;
  3516. my($op, $cx) = @_;
  3517. # optimised PADAV, pre 5.15
  3518. return $self->pp_aelemfast_lex(@_) if ($op->flags & OPf_SPECIAL);
  3519. my $gv = $self->gv_or_padgv($op);
  3520. my($name,$quoted) = $self->stash_variable_name('@',$gv);
  3521. $name = $quoted ? "$name->" : '$' . $name;
  3522. my $i = $op->private;
  3523. $i -= 256 if $i > 127;
  3524. return $name . "[" . ($i + $self->{'arybase'}) . "]";
  3525. }
  3526. sub rv2x {
  3527. my $self = shift;
  3528. my($op, $cx, $type) = @_;
  3529. if (class($op) eq 'NULL' || !$op->can("first")) {
  3530. carp("Unexpected op in pp_rv2x");
  3531. return 'XXX';
  3532. }
  3533. my $kid = $op->first;
  3534. if ($kid->name eq "gv") {
  3535. return $self->stash_variable($type, $self->deparse($kid, 0), $cx);
  3536. } elsif (is_scalar $kid) {
  3537. my $str = $self->deparse($kid, 0);
  3538. if ($str =~ /^\$([^\w\d])\z/) {
  3539. # "$$+" isn't a legal way to write the scalar dereference
  3540. # of $+, since the lexer can't tell you aren't trying to
  3541. # do something like "$$ + 1" to get one more than your
  3542. # PID. Either "${$+}" or "$${+}" are workable
  3543. # disambiguations, but if the programmer did the former,
  3544. # they'd be in the "else" clause below rather than here.
  3545. # It's not clear if this should somehow be unified with
  3546. # the code in dq and re_dq that also adds lexer
  3547. # disambiguation braces.
  3548. $str = '$' . "{$1}"; #'
  3549. }
  3550. return $type . $str;
  3551. } else {
  3552. return $type . "{" . $self->deparse($kid, 0) . "}";
  3553. }
  3554. }
  3555. sub pp_rv2sv { maybe_local(@_, rv2x(@_, "\$")) }
  3556. sub pp_rv2hv { maybe_local(@_, rv2x(@_, "%")) }
  3557. sub pp_rv2gv { maybe_local(@_, rv2x(@_, "*")) }
  3558. # skip rv2av
  3559. sub pp_av2arylen {
  3560. my $self = shift;
  3561. my($op, $cx) = @_;
  3562. if ($op->first->name eq "padav") {
  3563. return $self->maybe_local($op, $cx, '$#' . $self->padany($op->first));
  3564. } else {
  3565. return $self->maybe_local($op, $cx,
  3566. $self->rv2x($op->first, $cx, '$#'));
  3567. }
  3568. }
  3569. # skip down to the old, ex-rv2cv
  3570. sub pp_rv2cv {
  3571. my ($self, $op, $cx) = @_;
  3572. if (!null($op->first) && $op->first->name eq 'null' &&
  3573. $op->first->targ == OP_LIST)
  3574. {
  3575. return $self->rv2x($op->first->first->sibling, $cx, "&")
  3576. }
  3577. else {
  3578. return $self->rv2x($op, $cx, "")
  3579. }
  3580. }
  3581. sub list_const {
  3582. my $self = shift;
  3583. my($cx, @list) = @_;
  3584. my @a = map $self->const($_, 6), @list;
  3585. if (@a == 0) {
  3586. return "()";
  3587. } elsif (@a == 1) {
  3588. return $a[0];
  3589. } elsif ( @a > 2 and !grep(!/^-?\d+$/, @a)) {
  3590. # collapse (-1,0,1,2) into (-1..2)
  3591. my ($s, $e) = @a[0,-1];
  3592. my $i = $s;
  3593. return $self->maybe_parens("$s..$e", $cx, 9)
  3594. unless grep $i++ != $_, @a;
  3595. }
  3596. return $self->maybe_parens(join(", ", @a), $cx, 6);
  3597. }
  3598. sub pp_rv2av {
  3599. my $self = shift;
  3600. my($op, $cx) = @_;
  3601. my $kid = $op->first;
  3602. if ($kid->name eq "const") { # constant list
  3603. my $av = $self->const_sv($kid);
  3604. return $self->list_const($cx, $av->ARRAY);
  3605. } else {
  3606. return $self->maybe_local($op, $cx, $self->rv2x($op, $cx, "\@"));
  3607. }
  3608. }
  3609. sub is_subscriptable {
  3610. my $op = shift;
  3611. if ($op->name =~ /^([ahg]elem|multideref$)/) {
  3612. return 1;
  3613. } elsif ($op->name eq "entersub") {
  3614. my $kid = $op->first;
  3615. return 0 unless null $kid->sibling;
  3616. $kid = $kid->first;
  3617. $kid = $kid->sibling until null $kid->sibling;
  3618. return 0 if is_scope($kid);
  3619. $kid = $kid->first;
  3620. return 0 if $kid->name eq "gv" || $kid->name eq "padcv";
  3621. return 0 if is_scalar($kid);
  3622. return is_subscriptable($kid);
  3623. } else {
  3624. return 0;
  3625. }
  3626. }
  3627. sub elem_or_slice_array_name
  3628. {
  3629. my $self = shift;
  3630. my ($array, $left, $padname, $allow_arrow) = @_;
  3631. if ($array->name eq $padname) {
  3632. return $self->padany($array);
  3633. } elsif (is_scope($array)) { # ${expr}[0]
  3634. return "{" . $self->deparse($array, 0) . "}";
  3635. } elsif ($array->name eq "gv") {
  3636. ($array, my $quoted) =
  3637. $self->stash_variable_name(
  3638. $left eq '[' ? '@' : '%', $self->gv_or_padgv($array)
  3639. );
  3640. if (!$allow_arrow && $quoted) {
  3641. # This cannot happen.
  3642. die "Invalid variable name $array for slice";
  3643. }
  3644. return $quoted ? "$array->" : $array;
  3645. } elsif (!$allow_arrow || is_scalar $array) { # $x[0], $$x[0], ...
  3646. return $self->deparse($array, 24);
  3647. } else {
  3648. return undef;
  3649. }
  3650. }
  3651. sub elem_or_slice_single_index
  3652. {
  3653. my $self = shift;
  3654. my ($idx) = @_;
  3655. $idx = $self->deparse($idx, 1);
  3656. # Outer parens in an array index will confuse perl
  3657. # if we're interpolating in a regular expression, i.e.
  3658. # /$x$foo[(-1)]/ is *not* the same as /$x$foo[-1]/
  3659. #
  3660. # If $self->{parens}, then an initial '(' will
  3661. # definitely be paired with a final ')'. If
  3662. # !$self->{parens}, the misleading parens won't
  3663. # have been added in the first place.
  3664. #
  3665. # [You might think that we could get "(...)...(...)"
  3666. # where the initial and final parens do not match
  3667. # each other. But we can't, because the above would
  3668. # only happen if there's an infix binop between the
  3669. # two pairs of parens, and *that* means that the whole
  3670. # expression would be parenthesized as well.]
  3671. #
  3672. $idx =~ s/^\((.*)\)$/$1/ if $self->{'parens'};
  3673. # Hash-element braces will autoquote a bareword inside themselves.
  3674. # We need to make sure that C<$hash{warn()}> doesn't come out as
  3675. # C<$hash{warn}>, which has a quite different meaning. Currently
  3676. # B::Deparse will always quote strings, even if the string was a
  3677. # bareword in the original (i.e. the OPpCONST_BARE flag is ignored
  3678. # for constant strings.) So we can cheat slightly here - if we see
  3679. # a bareword, we know that it is supposed to be a function call.
  3680. #
  3681. $idx =~ s/^([A-Za-z_]\w*)$/$1()/;
  3682. return $idx;
  3683. }
  3684. sub elem {
  3685. my $self = shift;
  3686. my ($op, $cx, $left, $right, $padname) = @_;
  3687. my($array, $idx) = ($op->first, $op->first->sibling);
  3688. $idx = $self->elem_or_slice_single_index($idx);
  3689. unless ($array->name eq $padname) { # Maybe this has been fixed
  3690. $array = $array->first; # skip rv2av (or ex-rv2av in _53+)
  3691. }
  3692. if (my $array_name=$self->elem_or_slice_array_name
  3693. ($array, $left, $padname, 1)) {
  3694. return ($array_name =~ /->\z/
  3695. ? $array_name
  3696. : $array_name eq '#' ? '${#}' : "\$" . $array_name)
  3697. . $left . $idx . $right;
  3698. } else {
  3699. # $x[20][3]{hi} or expr->[20]
  3700. my $arrow = is_subscriptable($array) ? "" : "->";
  3701. return $self->deparse($array, 24) . $arrow . $left . $idx . $right;
  3702. }
  3703. }
  3704. # a simplified version of elem_or_slice_array_name()
  3705. # for the use of pp_multideref
  3706. sub multideref_var_name {
  3707. my $self = shift;
  3708. my ($gv, $is_hash) = @_;
  3709. my ($name, $quoted) =
  3710. $self->stash_variable_name( $is_hash ? '%' : '@', $gv);
  3711. return $quoted ? "$name->"
  3712. : $name eq '#'
  3713. ? '${#}' # avoid ${#}[1] => $#[1]
  3714. : '$' . $name;
  3715. }
  3716. sub pp_multideref {
  3717. my $self = shift;
  3718. my($op, $cx) = @_;
  3719. my $text = "";
  3720. if ($op->private & OPpMULTIDEREF_EXISTS) {
  3721. $text = $self->keyword("exists"). " ";
  3722. }
  3723. elsif ($op->private & OPpMULTIDEREF_DELETE) {
  3724. $text = $self->keyword("delete"). " ";
  3725. }
  3726. elsif ($op->private & OPpLVAL_INTRO) {
  3727. $text = $self->keyword("local"). " ";
  3728. }
  3729. if ($op->first && ($op->first->flags & OPf_KIDS)) {
  3730. # arbitrary initial expression, e.g. f(1,2,3)->[...]
  3731. $text .= $self->deparse($op->first, 24);
  3732. }
  3733. my @items = $op->aux_list($self->{curcv});
  3734. my $actions = shift @items;
  3735. my $is_hash;
  3736. my $derefs = 0;
  3737. while (1) {
  3738. if (($actions & MDEREF_ACTION_MASK) == MDEREF_reload) {
  3739. $actions = shift @items;
  3740. next;
  3741. }
  3742. $is_hash = (
  3743. ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_pop_rv2hv_helem
  3744. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvsv_vivify_rv2hv_helem
  3745. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padsv_vivify_rv2hv_helem
  3746. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_vivify_rv2hv_helem
  3747. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padhv_helem
  3748. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvhv_helem
  3749. );
  3750. if ( ($actions & MDEREF_ACTION_MASK) == MDEREF_AV_padav_aelem
  3751. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_padhv_helem)
  3752. {
  3753. $derefs = 1;
  3754. $text .= '$' . substr($self->padname(shift @items), 1);
  3755. }
  3756. elsif ( ($actions & MDEREF_ACTION_MASK) == MDEREF_AV_gvav_aelem
  3757. || ($actions & MDEREF_ACTION_MASK) == MDEREF_HV_gvhv_helem)
  3758. {
  3759. $derefs = 1;
  3760. $text .= $self->multideref_var_name(shift @items, $is_hash);
  3761. }
  3762. else {
  3763. if ( ($actions & MDEREF_ACTION_MASK) ==
  3764. MDEREF_AV_padsv_vivify_rv2av_aelem
  3765. || ($actions & MDEREF_ACTION_MASK) ==
  3766. MDEREF_HV_padsv_vivify_rv2hv_helem)
  3767. {
  3768. $text .= $self->padname(shift @items);
  3769. }
  3770. elsif ( ($actions & MDEREF_ACTION_MASK) ==
  3771. MDEREF_AV_gvsv_vivify_rv2av_aelem
  3772. || ($actions & MDEREF_ACTION_MASK) ==
  3773. MDEREF_HV_gvsv_vivify_rv2hv_helem)
  3774. {
  3775. $text .= $self->multideref_var_name(shift @items, $is_hash);
  3776. }
  3777. elsif ( ($actions & MDEREF_ACTION_MASK) ==
  3778. MDEREF_AV_pop_rv2av_aelem
  3779. || ($actions & MDEREF_ACTION_MASK) ==
  3780. MDEREF_HV_pop_rv2hv_helem)
  3781. {
  3782. if ( ($op->flags & OPf_KIDS)
  3783. && ( _op_is_or_was($op->first, OP_RV2AV)
  3784. || _op_is_or_was($op->first, OP_RV2HV))
  3785. && ($op->first->flags & OPf_KIDS)
  3786. && ( _op_is_or_was($op->first->first, OP_AELEM)
  3787. || _op_is_or_was($op->first->first, OP_HELEM))
  3788. )
  3789. {
  3790. $derefs++;
  3791. }
  3792. }
  3793. $text .= '->' if !$derefs++;
  3794. }
  3795. if (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_none) {
  3796. last;
  3797. }
  3798. $text .= $is_hash ? '{' : '[';
  3799. if (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_const) {
  3800. my $key = shift @items;
  3801. if ($is_hash) {
  3802. $text .= $self->const($key, $cx);
  3803. }
  3804. else {
  3805. $text .= $key;
  3806. }
  3807. }
  3808. elsif (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_padsv) {
  3809. $text .= $self->padname(shift @items);
  3810. }
  3811. elsif (($actions & MDEREF_INDEX_MASK) == MDEREF_INDEX_gvsv) {
  3812. $text .= '$' . ($self->stash_variable_name('$', shift @items))[0];
  3813. }
  3814. $text .= $is_hash ? '}' : ']';
  3815. if ($actions & MDEREF_FLAG_last) {
  3816. last;
  3817. }
  3818. $actions >>= MDEREF_SHIFT;
  3819. }
  3820. return $text;
  3821. }
  3822. sub pp_aelem { maybe_local(@_, elem(@_, "[", "]", "padav")) }
  3823. sub pp_helem { maybe_local(@_, elem(@_, "{", "}", "padhv")) }
  3824. sub pp_gelem {
  3825. my $self = shift;
  3826. my($op, $cx) = @_;
  3827. my($glob, $part) = ($op->first, $op->last);
  3828. $glob = $glob->first; # skip rv2gv
  3829. $glob = $glob->first if $glob->name eq "rv2gv"; # this one's a bug
  3830. my $scope = is_scope($glob);
  3831. $glob = $self->deparse($glob, 0);
  3832. $part = $self->deparse($part, 1);
  3833. return "*" . ($scope ? "{$glob}" : $glob) . "{$part}";
  3834. }
  3835. sub slice {
  3836. my $self = shift;
  3837. my ($op, $cx, $left, $right, $regname, $padname) = @_;
  3838. my $last;
  3839. my(@elems, $kid, $array, $list);
  3840. if (class($op) eq "LISTOP") {
  3841. $last = $op->last;
  3842. } else { # ex-hslice inside delete()
  3843. for ($kid = $op->first; !null $kid->sibling; $kid = $kid->sibling) {}
  3844. $last = $kid;
  3845. }
  3846. $array = $last;
  3847. $array = $array->first
  3848. if $array->name eq $regname or $array->name eq "null";
  3849. $array = $self->elem_or_slice_array_name($array,$left,$padname,0);
  3850. $kid = $op->first->sibling; # skip pushmark
  3851. if ($kid->name eq "list") {
  3852. $kid = $kid->first->sibling; # skip list, pushmark
  3853. for (; !null $kid; $kid = $kid->sibling) {
  3854. push @elems, $self->deparse($kid, 6);
  3855. }
  3856. $list = join(", ", @elems);
  3857. } else {
  3858. $list = $self->elem_or_slice_single_index($kid);
  3859. }
  3860. my $lead = '@';
  3861. $lead = '%' if $op->name =~ /^kv/i;
  3862. return $lead . $array . $left . $list . $right;
  3863. }
  3864. sub pp_aslice { maybe_local(@_, slice(@_, "[", "]", "rv2av", "padav")) }
  3865. sub pp_kvaslice { slice(@_, "[", "]", "rv2av", "padav") }
  3866. sub pp_hslice { maybe_local(@_, slice(@_, "{", "}", "rv2hv", "padhv")) }
  3867. sub pp_kvhslice { slice(@_, "{", "}", "rv2hv", "padhv") }
  3868. sub pp_lslice {
  3869. my $self = shift;
  3870. my($op, $cx) = @_;
  3871. my $idx = $op->first;
  3872. my $list = $op->last;
  3873. my(@elems, $kid);
  3874. $list = $self->deparse($list, 1);
  3875. $idx = $self->deparse($idx, 1);
  3876. return "($list)" . "[$idx]";
  3877. }
  3878. sub want_scalar {
  3879. my $op = shift;
  3880. return ($op->flags & OPf_WANT) == OPf_WANT_SCALAR;
  3881. }
  3882. sub want_list {
  3883. my $op = shift;
  3884. return ($op->flags & OPf_WANT) == OPf_WANT_LIST;
  3885. }
  3886. sub _method {
  3887. my $self = shift;
  3888. my($op, $cx) = @_;
  3889. my $kid = $op->first->sibling; # skip pushmark
  3890. my($meth, $obj, @exprs);
  3891. if ($kid->name eq "list" and want_list $kid) {
  3892. # When an indirect object isn't a bareword but the args are in
  3893. # parens, the parens aren't part of the method syntax (the LLAFR
  3894. # doesn't apply), but they make a list with OPf_PARENS set that
  3895. # doesn't get flattened by the append_elem that adds the method,
  3896. # making a (object, arg1, arg2, ...) list where the object
  3897. # usually is. This can be distinguished from
  3898. # '($obj, $arg1, $arg2)->meth()' (which is legal if $arg2 is an
  3899. # object) because in the later the list is in scalar context
  3900. # as the left side of -> always is, while in the former
  3901. # the list is in list context as method arguments always are.
  3902. # (Good thing there aren't method prototypes!)
  3903. $meth = $kid->sibling;
  3904. $kid = $kid->first->sibling; # skip pushmark
  3905. $obj = $kid;
  3906. $kid = $kid->sibling;
  3907. for (; not null $kid; $kid = $kid->sibling) {
  3908. push @exprs, $kid;
  3909. }
  3910. } else {
  3911. $obj = $kid;
  3912. $kid = $kid->sibling;
  3913. for (; !null ($kid->sibling) && $kid->name!~/^method(?:_named)?\z/;
  3914. $kid = $kid->sibling) {
  3915. push @exprs, $kid
  3916. }
  3917. $meth = $kid;
  3918. }
  3919. if ($meth->name eq "method_named") {
  3920. $meth = $self->meth_sv($meth)->PV;
  3921. } elsif ($meth->name eq "method_super") {
  3922. $meth = "SUPER::".$self->meth_sv($meth)->PV;
  3923. } elsif ($meth->name eq "method_redir") {
  3924. $meth = $self->meth_rclass_sv($meth)->PV.'::'.$self->meth_sv($meth)->PV;
  3925. } elsif ($meth->name eq "method_redir_super") {
  3926. $meth = $self->meth_rclass_sv($meth)->PV.'::SUPER::'.
  3927. $self->meth_sv($meth)->PV;
  3928. } else {
  3929. $meth = $meth->first;
  3930. if ($meth->name eq "const") {
  3931. # As of 5.005_58, this case is probably obsoleted by the
  3932. # method_named case above
  3933. $meth = $self->const_sv($meth)->PV; # needs to be bare
  3934. }
  3935. }
  3936. return { method => $meth, variable_method => ref($meth),
  3937. object => $obj, args => \@exprs },
  3938. $cx;
  3939. }
  3940. # compat function only
  3941. sub method {
  3942. my $self = shift;
  3943. my $info = $self->_method(@_);
  3944. return $self->e_method( $self->_method(@_) );
  3945. }
  3946. sub e_method {
  3947. my ($self, $info, $cx) = @_;
  3948. my $obj = $self->deparse($info->{object}, 24);
  3949. my $meth = $info->{method};
  3950. $meth = $self->deparse($meth, 1) if $info->{variable_method};
  3951. my $args = join(", ", map { $self->deparse($_, 6) } @{$info->{args}} );
  3952. if ($info->{object}->name eq 'scope' && want_list $info->{object}) {
  3953. # method { $object }
  3954. # This must be deparsed this way to preserve list context
  3955. # of $object.
  3956. my $need_paren = $cx >= 6;
  3957. return '(' x $need_paren
  3958. . $meth . substr($obj,2) # chop off the "do"
  3959. . " $args"
  3960. . ')' x $need_paren;
  3961. }
  3962. my $kid = $obj . "->" . $meth;
  3963. if (length $args) {
  3964. return $kid . "(" . $args . ")"; # parens mandatory
  3965. } else {
  3966. return $kid;
  3967. }
  3968. }
  3969. # returns "&" if the prototype doesn't match the args,
  3970. # or ("", $args_after_prototype_demunging) if it does.
  3971. sub check_proto {
  3972. my $self = shift;
  3973. return "&" if $self->{'noproto'};
  3974. my($proto, @args) = @_;
  3975. my($arg, $real);
  3976. my $doneok = 0;
  3977. my @reals;
  3978. # An unbackslashed @ or % gobbles up the rest of the args
  3979. 1 while $proto =~ s/(?<!\\)([@%])[^\]]+$/$1/;
  3980. $proto =~ s/^\s*//;
  3981. while ($proto) {
  3982. $proto =~ s/^(\\?[\$\@&%*_]|\\\[[\$\@&%*]+\]|;|)\s*//;
  3983. my $chr = $1;
  3984. if ($chr eq "") {
  3985. return "&" if @args;
  3986. } elsif ($chr eq ";") {
  3987. $doneok = 1;
  3988. } elsif ($chr eq "@" or $chr eq "%") {
  3989. push @reals, map($self->deparse($_, 6), @args);
  3990. @args = ();
  3991. } else {
  3992. $arg = shift @args;
  3993. last unless $arg;
  3994. if ($chr eq "\$" || $chr eq "_") {
  3995. if (want_scalar $arg) {
  3996. push @reals, $self->deparse($arg, 6);
  3997. } else {
  3998. return "&";
  3999. }
  4000. } elsif ($chr eq "&") {
  4001. if ($arg->name =~ /^(s?refgen|undef)$/) {
  4002. push @reals, $self->deparse($arg, 6);
  4003. } else {
  4004. return "&";
  4005. }
  4006. } elsif ($chr eq "*") {
  4007. if ($arg->name =~ /^s?refgen$/
  4008. and $arg->first->first->name eq "rv2gv")
  4009. {
  4010. $real = $arg->first->first; # skip refgen, null
  4011. if ($real->first->name eq "gv") {
  4012. push @reals, $self->deparse($real, 6);
  4013. } else {
  4014. push @reals, $self->deparse($real->first, 6);
  4015. }
  4016. } else {
  4017. return "&";
  4018. }
  4019. } elsif (substr($chr, 0, 1) eq "\\") {
  4020. $chr =~ tr/\\[]//d;
  4021. if ($arg->name =~ /^s?refgen$/ and
  4022. !null($real = $arg->first) and
  4023. ($chr =~ /\$/ && is_scalar($real->first)
  4024. or ($chr =~ /@/
  4025. && class($real->first->sibling) ne 'NULL'
  4026. && $real->first->sibling->name
  4027. =~ /^(rv2|pad)av$/)
  4028. or ($chr =~ /%/
  4029. && class($real->first->sibling) ne 'NULL'
  4030. && $real->first->sibling->name
  4031. =~ /^(rv2|pad)hv$/)
  4032. #or ($chr =~ /&/ # This doesn't work
  4033. # && $real->first->name eq "rv2cv")
  4034. or ($chr =~ /\*/
  4035. && $real->first->name eq "rv2gv")))
  4036. {
  4037. push @reals, $self->deparse($real, 6);
  4038. } else {
  4039. return "&";
  4040. }
  4041. }
  4042. }
  4043. }
  4044. return "&" if $proto and !$doneok; # too few args and no ';'
  4045. return "&" if @args; # too many args
  4046. return ("", join ", ", @reals);
  4047. }
  4048. sub retscalar {
  4049. my $name = $_[0]->name;
  4050. # XXX There has to be a better way of doing this scalar-op check.
  4051. # Currently PL_opargs is not exposed.
  4052. if ($name eq 'null') {
  4053. $name = substr B::ppname($_[0]->targ), 3
  4054. }
  4055. $name =~ /^(?:scalar|pushmark|wantarray|const|gvsv|gv|padsv|rv2gv
  4056. |rv2sv|av2arylen|anoncode|prototype|srefgen|ref|bless
  4057. |regcmaybe|regcreset|regcomp|qr|subst|substcont|trans
  4058. |transr|sassign|chop|schop|chomp|schomp|defined|undef
  4059. |study|pos|preinc|i_preinc|predec|i_predec|postinc
  4060. |i_postinc|postdec|i_postdec|pow|multiply|i_multiply
  4061. |divide|i_divide|modulo|i_modulo|add|i_add|subtract
  4062. |i_subtract|concat|stringify|left_shift|right_shift|lt
  4063. |i_lt|gt|i_gt|le|i_le|ge|i_ge|eq|i_eq|ne|i_ne|ncmp|i_ncmp
  4064. |slt|sgt|sle|sge|seq|sne|scmp|[sn]?bit_(?:and|x?or)|negate
  4065. |i_negate|not|[sn]?complement|smartmatch|atan2|sin|cos
  4066. |rand|srand|exp|log|sqrt|int|hex|oct|abs|length|substr
  4067. |vec|index|rindex|sprintf|formline|ord|chr|crypt|ucfirst
  4068. |lcfirst|uc|lc|quotemeta|aelemfast|aelem|exists|helem
  4069. |pack|join|anonlist|anonhash|push|pop|shift|unshift|xor
  4070. |andassign|orassign|dorassign|warn|die|reset|nextstate
  4071. |dbstate|unstack|last|next|redo|dump|goto|exit|open|close
  4072. |pipe_op|fileno|umask|binmode|tie|untie|tied|dbmopen
  4073. |dbmclose|select|getc|read|enterwrite|prtf|print|say
  4074. |sysopen|sysseek|sysread|syswrite|eof|tell|seek|truncate
  4075. |fcntl|ioctl|flock|send|recv|socket|sockpair|bind|connect
  4076. |listen|accept|shutdown|gsockopt|ssockopt|getsockname
  4077. |getpeername|ftrread|ftrwrite|ftrexec|fteread|ftewrite
  4078. |fteexec|ftis|ftsize|ftmtime|ftatime|ftctime|ftrowned
  4079. |fteowned|ftzero|ftsock|ftchr|ftblk|ftfile|ftdir|ftpipe
  4080. |ftsuid|ftsgid|ftsvtx|ftlink|fttty|fttext|ftbinary|chdir
  4081. |chown|chroot|unlink|chmod|utime|rename|link|symlink
  4082. |readlink|mkdir|rmdir|open_dir|telldir|seekdir|rewinddir
  4083. |closedir|fork|wait|waitpid|system|exec|kill|getppid
  4084. |getpgrp|setpgrp|getpriority|setpriority|time|alarm|sleep
  4085. |shmget|shmctl|shmread|shmwrite|msgget|msgctl|msgsnd
  4086. |msgrcv|semop|semget|semctl|hintseval|shostent|snetent
  4087. |sprotoent|sservent|ehostent|enetent|eprotoent|eservent
  4088. |spwent|epwent|sgrent|egrent|getlogin|syscall|lock|runcv
  4089. |fc)\z/x
  4090. }
  4091. sub pp_entersub {
  4092. my $self = shift;
  4093. my($op, $cx) = @_;
  4094. return $self->e_method($self->_method($op, $cx))
  4095. unless null $op->first->sibling;
  4096. my $prefix = "";
  4097. my $amper = "";
  4098. my($kid, @exprs);
  4099. if ($op->flags & OPf_SPECIAL && !($op->flags & OPf_MOD)) {
  4100. $prefix = "do ";
  4101. } elsif ($op->private & OPpENTERSUB_AMPER) {
  4102. $amper = "&";
  4103. }
  4104. $kid = $op->first;
  4105. $kid = $kid->first->sibling; # skip ex-list, pushmark
  4106. for (; not null $kid->sibling; $kid = $kid->sibling) {
  4107. push @exprs, $kid;
  4108. }
  4109. my $simple = 0;
  4110. my $proto = undef;
  4111. my $lexical;
  4112. if (is_scope($kid)) {
  4113. $amper = "&";
  4114. $kid = "{" . $self->deparse($kid, 0) . "}";
  4115. } elsif ($kid->first->name eq "gv") {
  4116. my $gv = $self->gv_or_padgv($kid->first);
  4117. my $cv;
  4118. if (class($gv) eq 'GV' && class($cv = $gv->CV) ne "SPECIAL"
  4119. || $gv->FLAGS & SVf_ROK && class($cv = $gv->RV) eq 'CV') {
  4120. $proto = $cv->PV if $cv->FLAGS & SVf_POK;
  4121. }
  4122. $simple = 1; # only calls of named functions can be prototyped
  4123. $kid = $self->deparse($kid, 24);
  4124. my $fq;
  4125. # Fully qualify any sub name that conflicts with a lexical.
  4126. if ($self->lex_in_scope("&$kid")
  4127. || $self->lex_in_scope("&$kid", 1))
  4128. {
  4129. $fq++;
  4130. } elsif (!$amper) {
  4131. if ($kid eq 'main::') {
  4132. $kid = '::';
  4133. }
  4134. else {
  4135. if ($kid !~ /::/ && $kid ne 'x') {
  4136. # Fully qualify any sub name that is also a keyword. While
  4137. # we could check the import flag, we cannot guarantee that
  4138. # the code deparsed so far would set that flag, so we qual-
  4139. # ify the names regardless of importation.
  4140. if (exists $feature_keywords{$kid}) {
  4141. $fq++ if $self->feature_enabled($kid);
  4142. } elsif (do { local $@; local $SIG{__DIE__};
  4143. eval { () = prototype "CORE::$kid"; 1 } }) {
  4144. $fq++
  4145. }
  4146. }
  4147. if ($kid !~ /^(?:\w|::)(?:[\w\d]|::(?!\z))*\z/) {
  4148. $kid = single_delim("q", "'", $kid, $self) . '->';
  4149. }
  4150. }
  4151. }
  4152. $fq and substr $kid, 0, 0, = $self->{'curstash'}.'::';
  4153. } elsif (is_scalar ($kid->first) && $kid->first->name ne 'rv2cv') {
  4154. $amper = "&";
  4155. $kid = $self->deparse($kid, 24);
  4156. } else {
  4157. $prefix = "";
  4158. my $grandkid = $kid->first;
  4159. my $arrow = ($lexical = $grandkid->name eq "padcv")
  4160. || is_subscriptable($grandkid)
  4161. ? ""
  4162. : "->";
  4163. $kid = $self->deparse($kid, 24) . $arrow;
  4164. if ($lexical) {
  4165. my $padlist = $self->{'curcv'}->PADLIST;
  4166. my $padoff = $grandkid->targ;
  4167. my $padname = $padlist->ARRAYelt(0)->ARRAYelt($padoff);
  4168. my $protocv = $padname->FLAGS & SVpad_STATE
  4169. ? $padlist->ARRAYelt(1)->ARRAYelt($padoff)
  4170. : $padname->PROTOCV;
  4171. if ($protocv->FLAGS & SVf_POK) {
  4172. $proto = $protocv->PV
  4173. }
  4174. $simple = 1;
  4175. }
  4176. }
  4177. # Doesn't matter how many prototypes there are, if
  4178. # they haven't happened yet!
  4179. my $declared = $lexical || exists $self->{'subs_declared'}{$kid};
  4180. if (not $declared and $self->{'in_coderef2text'}) {
  4181. no strict 'refs';
  4182. no warnings 'uninitialized';
  4183. $declared =
  4184. (
  4185. defined &{ ${$self->{'curstash'}."::"}{$kid} }
  4186. && !exists
  4187. $self->{'subs_deparsed'}{$self->{'curstash'}."::".$kid}
  4188. && defined prototype $self->{'curstash'}."::".$kid
  4189. );
  4190. }
  4191. if (!$declared && defined($proto)) {
  4192. # Avoid "too early to check prototype" warning
  4193. ($amper, $proto) = ('&');
  4194. }
  4195. my $args;
  4196. my $listargs = 1;
  4197. if ($declared and defined $proto and not $amper) {
  4198. ($amper, $args) = $self->check_proto($proto, @exprs);
  4199. $listargs = $amper;
  4200. }
  4201. if ($listargs) {
  4202. $args = join(", ", map(
  4203. ($_->flags & OPf_WANT) == OPf_WANT_SCALAR
  4204. && !retscalar($_)
  4205. ? $self->maybe_parens_unop('scalar', $_, 6)
  4206. : $self->deparse($_, 6),
  4207. @exprs
  4208. ));
  4209. }
  4210. if ($prefix or $amper) {
  4211. if ($kid eq '&') { $kid = "{$kid}" } # &{&} cannot be written as &&
  4212. if ($op->flags & OPf_STACKED) {
  4213. return $prefix . $amper . $kid . "(" . $args . ")";
  4214. } else {
  4215. return $prefix . $amper. $kid;
  4216. }
  4217. } else {
  4218. # It's a syntax error to call CORE::GLOBAL::foo with a prefix,
  4219. # so it must have been translated from a keyword call. Translate
  4220. # it back.
  4221. $kid =~ s/^CORE::GLOBAL:://;
  4222. my $dproto = defined($proto) ? $proto : "undefined";
  4223. my $scalar_proto = $dproto =~ /^;*(?:[\$*_+]|\\.|\\\[[^]]\])\z/;
  4224. if (!$declared) {
  4225. return "$kid(" . $args . ")";
  4226. } elsif ($dproto =~ /^\s*\z/) {
  4227. return $kid;
  4228. } elsif ($scalar_proto and is_scalar($exprs[0])) {
  4229. # is_scalar is an excessively conservative test here:
  4230. # really, we should be comparing to the precedence of the
  4231. # top operator of $exprs[0] (ala unop()), but that would
  4232. # take some major code restructuring to do right.
  4233. return $self->maybe_parens_func($kid, $args, $cx, 16);
  4234. } elsif (not $scalar_proto and defined($proto) || $simple) { #'
  4235. return $self->maybe_parens_func($kid, $args, $cx, 5);
  4236. } else {
  4237. return "$kid(" . $args . ")";
  4238. }
  4239. }
  4240. }
  4241. sub pp_enterwrite { unop(@_, "write") }
  4242. # escape things that cause interpolation in double quotes,
  4243. # but not character escapes
  4244. sub uninterp {
  4245. my($str) = @_;
  4246. $str =~ s/(^|\G|[^\\])((?:\\\\)*)([\$\@]|\\[uUlLQE])/$1$2\\$3/g;
  4247. return $str;
  4248. }
  4249. {
  4250. my $bal;
  4251. BEGIN {
  4252. use re "eval";
  4253. # Matches any string which is balanced with respect to {braces}
  4254. $bal = qr(
  4255. (?:
  4256. [^\\{}]
  4257. | \\\\
  4258. | \\[{}]
  4259. | \{(??{$bal})\}
  4260. )*
  4261. )x;
  4262. }
  4263. # the same, but treat $|, $), $( and $ at the end of the string differently
  4264. # and leave comments unmangled for the sake of /x and (?x).
  4265. sub re_uninterp {
  4266. my($str) = @_;
  4267. $str =~ s/
  4268. ( ^|\G # $1
  4269. | [^\\]
  4270. )
  4271. ( # $2
  4272. (?:\\\\)*
  4273. )
  4274. ( # $3
  4275. ( \(\?\??\{$bal\}\) # $4 (skip over (?{}) and (??{}) blocks)
  4276. | \#[^\n]* # (skip over comments)
  4277. )
  4278. | [\$\@]
  4279. (?!\||\)|\(|$|\s)
  4280. | \\[uUlLQE]
  4281. )
  4282. /defined($4) && length($4) ? "$1$2$4" : "$1$2\\$3"/xeg;
  4283. return $str;
  4284. }
  4285. }
  4286. # character escapes, but not delimiters that might need to be escaped
  4287. sub escape_str { # ASCII, UTF8
  4288. my($str) = @_;
  4289. $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
  4290. $str =~ s/\a/\\a/g;
  4291. # $str =~ s/\cH/\\b/g; # \b means something different in a regex; and \cH
  4292. # isn't a backspace in EBCDIC
  4293. $str =~ s/\t/\\t/g;
  4294. $str =~ s/\n/\\n/g;
  4295. $str =~ s/\e/\\e/g;
  4296. $str =~ s/\f/\\f/g;
  4297. $str =~ s/\r/\\r/g;
  4298. $str =~ s/([\cA-\cZ])/'\\c' . $unctrl{$1}/ge;
  4299. $str =~ s/([[:^print:]])/sprintf("\\%03o", ord($1))/age;
  4300. return $str;
  4301. }
  4302. # For regexes. Leave whitespace unmangled in case of /x or (?x).
  4303. sub escape_re {
  4304. my($str) = @_;
  4305. $str =~ s/(.)/ord($1) > 255 ? sprintf("\\x{%x}", ord($1)) : $1/eg;
  4306. $str =~ s/([[:^print:]])/
  4307. ($1 =~ y! \t\n!!) ? $1 : sprintf("\\%03o", ord($1))/age;
  4308. $str =~ s/\n/\n\f/g;
  4309. return $str;
  4310. }
  4311. # Don't do this for regexen
  4312. sub unback {
  4313. my($str) = @_;
  4314. $str =~ s/\\/\\\\/g;
  4315. return $str;
  4316. }
  4317. # Remove backslashes which precede literal control characters,
  4318. # to avoid creating ambiguity when we escape the latter.
  4319. sub re_unback {
  4320. my($str) = @_;
  4321. # the insane complexity here is due to the behaviour of "\c\"
  4322. $str =~ s/(^|[^\\]|\\c\\)(?<!\\c)\\(\\\\)*(?=[[:^print:]])/$1$2/g;
  4323. return $str;
  4324. }
  4325. sub balanced_delim {
  4326. my($str) = @_;
  4327. my @str = split //, $str;
  4328. my($ar, $open, $close, $fail, $c, $cnt, $last_bs);
  4329. for $ar (['[',']'], ['(',')'], ['<','>'], ['{','}']) {
  4330. ($open, $close) = @$ar;
  4331. $fail = 0; $cnt = 0; $last_bs = 0;
  4332. for $c (@str) {
  4333. if ($c eq $open) {
  4334. $fail = 1 if $last_bs;
  4335. $cnt++;
  4336. } elsif ($c eq $close) {
  4337. $fail = 1 if $last_bs;
  4338. $cnt--;
  4339. if ($cnt < 0) {
  4340. # qq()() isn't ")("
  4341. $fail = 1;
  4342. last;
  4343. }
  4344. }
  4345. $last_bs = $c eq '\\';
  4346. }
  4347. $fail = 1 if $cnt != 0;
  4348. return ($open, "$open$str$close") if not $fail;
  4349. }
  4350. return ("", $str);
  4351. }
  4352. sub single_delim {
  4353. my($q, $default, $str, $self) = @_;
  4354. return "$default$str$default" if $default and index($str, $default) == -1;
  4355. my $coreq = $self->keyword($q); # maybe CORE::q
  4356. if ($q ne 'qr') {
  4357. (my $succeed, $str) = balanced_delim($str);
  4358. return "$coreq$str" if $succeed;
  4359. }
  4360. for my $delim ('/', '"', '#') {
  4361. return "$coreq$delim" . $str . $delim if index($str, $delim) == -1;
  4362. }
  4363. if ($default) {
  4364. $str =~ s/$default/\\$default/g;
  4365. return "$default$str$default";
  4366. } else {
  4367. $str =~ s[/][\\/]g;
  4368. return "$coreq/$str/";
  4369. }
  4370. }
  4371. my $max_prec;
  4372. BEGIN { $max_prec = int(0.999 + 8*length(pack("F", 42))*log(2)/log(10)); }
  4373. # Split a floating point number into an integer mantissa and a binary
  4374. # exponent. Assumes you've already made sure the number isn't zero or
  4375. # some weird infinity or NaN.
  4376. sub split_float {
  4377. my($f) = @_;
  4378. my $exponent = 0;
  4379. if ($f == int($f)) {
  4380. while ($f % 2 == 0) {
  4381. $f /= 2;
  4382. $exponent++;
  4383. }
  4384. } else {
  4385. while ($f != int($f)) {
  4386. $f *= 2;
  4387. $exponent--;
  4388. }
  4389. }
  4390. my $mantissa = sprintf("%.0f", $f);
  4391. return ($mantissa, $exponent);
  4392. }
  4393. sub const {
  4394. my $self = shift;
  4395. my($sv, $cx) = @_;
  4396. if ($self->{'use_dumper'}) {
  4397. return $self->const_dumper($sv, $cx);
  4398. }
  4399. if (class($sv) eq "SPECIAL") {
  4400. # sv_undef, sv_yes, sv_no
  4401. return $$sv == 3 ? $self->maybe_parens("!1", $cx, 21)
  4402. : ('undef', '1')[$$sv-1];
  4403. }
  4404. if (class($sv) eq "NULL") {
  4405. return 'undef';
  4406. }
  4407. # convert a version object into the "v1.2.3" string in its V magic
  4408. if ($sv->FLAGS & SVs_RMG) {
  4409. for (my $mg = $sv->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
  4410. return $mg->PTR if $mg->TYPE eq 'V';
  4411. }
  4412. }
  4413. if ($sv->FLAGS & SVf_IOK) {
  4414. my $str = $sv->int_value;
  4415. $str = $self->maybe_parens($str, $cx, 21) if $str < 0;
  4416. return $str;
  4417. } elsif ($sv->FLAGS & SVf_NOK) {
  4418. my $nv = $sv->NV;
  4419. if ($nv == 0) {
  4420. if (pack("F", $nv) eq pack("F", 0)) {
  4421. # positive zero
  4422. return "0";
  4423. } else {
  4424. # negative zero
  4425. return $self->maybe_parens("-.0", $cx, 21);
  4426. }
  4427. } elsif (1/$nv == 0) {
  4428. if ($nv > 0) {
  4429. # positive infinity
  4430. return $self->maybe_parens("9**9**9", $cx, 22);
  4431. } else {
  4432. # negative infinity
  4433. return $self->maybe_parens("-9**9**9", $cx, 21);
  4434. }
  4435. } elsif ($nv != $nv) {
  4436. # NaN
  4437. if (pack("F", $nv) eq pack("F", sin(9**9**9))) {
  4438. # the normal kind
  4439. return "sin(9**9**9)";
  4440. } elsif (pack("F", $nv) eq pack("F", -sin(9**9**9))) {
  4441. # the inverted kind
  4442. return $self->maybe_parens("-sin(9**9**9)", $cx, 21);
  4443. } else {
  4444. # some other kind
  4445. my $hex = unpack("h*", pack("F", $nv));
  4446. return qq'unpack("F", pack("h*", "$hex"))';
  4447. }
  4448. }
  4449. # first, try the default stringification
  4450. my $str = "$nv";
  4451. if ($str != $nv) {
  4452. # failing that, try using more precision
  4453. $str = sprintf("%.${max_prec}g", $nv);
  4454. # if (pack("F", $str) ne pack("F", $nv)) {
  4455. if ($str != $nv) {
  4456. # not representable in decimal with whatever sprintf()
  4457. # and atof() Perl is using here.
  4458. my($mant, $exp) = split_float($nv);
  4459. return $self->maybe_parens("$mant * 2**$exp", $cx, 19);
  4460. }
  4461. }
  4462. $str = $self->maybe_parens($str, $cx, 21) if $nv < 0;
  4463. return $str;
  4464. } elsif ($sv->FLAGS & SVf_ROK && $sv->can("RV")) {
  4465. my $ref = $sv->RV;
  4466. my $class = class($ref);
  4467. if ($class eq "AV") {
  4468. return "[" . $self->list_const(2, $ref->ARRAY) . "]";
  4469. } elsif ($class eq "HV") {
  4470. my %hash = $ref->ARRAY;
  4471. my @elts;
  4472. for my $k (sort keys %hash) {
  4473. push @elts, "$k => " . $self->const($hash{$k}, 6);
  4474. }
  4475. return "{" . join(", ", @elts) . "}";
  4476. } elsif ($class eq "CV") {
  4477. BEGIN {
  4478. if ($] > 5.0150051) {
  4479. require overloading;
  4480. unimport overloading;
  4481. }
  4482. }
  4483. if ($] > 5.0150051 && $self->{curcv} &&
  4484. $self->{curcv}->object_2svref == $ref->object_2svref) {
  4485. return $self->keyword("__SUB__");
  4486. }
  4487. return "sub " . $self->deparse_sub($ref);
  4488. }
  4489. if ($class ne 'SPECIAL' and $ref->FLAGS & SVs_SMG) {
  4490. for (my $mg = $ref->MAGIC; $mg; $mg = $mg->MOREMAGIC) {
  4491. if ($mg->TYPE eq 'r') {
  4492. my $re = re_uninterp(escape_re(re_unback($mg->precomp)));
  4493. return single_delim("qr", "", $re, $self);
  4494. }
  4495. }
  4496. }
  4497. my $const = $self->const($ref, 20);
  4498. if ($self->{in_subst_repl} && $const =~ /^[0-9]/) {
  4499. $const = "($const)";
  4500. }
  4501. return $self->maybe_parens("\\$const", $cx, 20);
  4502. } elsif ($sv->FLAGS & SVf_POK) {
  4503. my $str = $sv->PV;
  4504. if ($str =~ /[[:^print:]]/a) {
  4505. return single_delim("qq", '"',
  4506. uninterp(escape_str unback $str), $self);
  4507. } else {
  4508. return single_delim("q", "'", unback($str), $self);
  4509. }
  4510. } else {
  4511. return "undef";
  4512. }
  4513. }
  4514. sub const_dumper {
  4515. my $self = shift;
  4516. my($sv, $cx) = @_;
  4517. my $ref = $sv->object_2svref();
  4518. my $dumper = Data::Dumper->new([$$ref], ['$v']);
  4519. $dumper->Purity(1)->Terse(1)->Deparse(1)->Indent(0)->Useqq(1)->Sortkeys(1);
  4520. my $str = $dumper->Dump();
  4521. if ($str =~ /^\$v/) {
  4522. return '${my ' . $str . ' \$v}';
  4523. } else {
  4524. return $str;
  4525. }
  4526. }
  4527. sub const_sv {
  4528. my $self = shift;
  4529. my $op = shift;
  4530. my $sv = $op->sv;
  4531. # the constant could be in the pad (under useithreads)
  4532. $sv = $self->padval($op->targ) unless $$sv;
  4533. return $sv;
  4534. }
  4535. sub meth_sv {
  4536. my $self = shift;
  4537. my $op = shift;
  4538. my $sv = $op->meth_sv;
  4539. # the constant could be in the pad (under useithreads)
  4540. $sv = $self->padval($op->targ) unless $$sv;
  4541. return $sv;
  4542. }
  4543. sub meth_rclass_sv {
  4544. my $self = shift;
  4545. my $op = shift;
  4546. my $sv = $op->rclass;
  4547. # the constant could be in the pad (under useithreads)
  4548. $sv = $self->padval($sv) unless ref $sv;
  4549. return $sv;
  4550. }
  4551. sub pp_const {
  4552. my $self = shift;
  4553. my($op, $cx) = @_;
  4554. if ($op->private & OPpCONST_ARYBASE) {
  4555. return '$[';
  4556. }
  4557. # if ($op->private & OPpCONST_BARE) { # trouble with '=>' autoquoting
  4558. # return $self->const_sv($op)->PV;
  4559. # }
  4560. my $sv = $self->const_sv($op);
  4561. return $self->const($sv, $cx);
  4562. }
  4563. sub dq {
  4564. my $self = shift;
  4565. my $op = shift;
  4566. my $type = $op->name;
  4567. if ($type eq "const") {
  4568. return '$[' if $op->private & OPpCONST_ARYBASE;
  4569. return uninterp(escape_str(unback($self->const_sv($op)->as_string)));
  4570. } elsif ($type eq "concat") {
  4571. my $first = $self->dq($op->first);
  4572. my $last = $self->dq($op->last);
  4573. # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]", "$foo\::bar"
  4574. ($last =~ /^[A-Z\\\^\[\]_?]/ &&
  4575. $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
  4576. || ($last =~ /^[:'{\[\w_]/ && #'
  4577. $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
  4578. return $first . $last;
  4579. } elsif ($type eq "uc") {
  4580. return '\U' . $self->dq($op->first->sibling) . '\E';
  4581. } elsif ($type eq "lc") {
  4582. return '\L' . $self->dq($op->first->sibling) . '\E';
  4583. } elsif ($type eq "ucfirst") {
  4584. return '\u' . $self->dq($op->first->sibling);
  4585. } elsif ($type eq "lcfirst") {
  4586. return '\l' . $self->dq($op->first->sibling);
  4587. } elsif ($type eq "quotemeta") {
  4588. return '\Q' . $self->dq($op->first->sibling) . '\E';
  4589. } elsif ($type eq "fc") {
  4590. return '\F' . $self->dq($op->first->sibling) . '\E';
  4591. } elsif ($type eq "join") {
  4592. return $self->deparse($op->last, 26); # was join($", @ary)
  4593. } else {
  4594. return $self->deparse($op, 26);
  4595. }
  4596. }
  4597. sub pp_backtick {
  4598. my $self = shift;
  4599. my($op, $cx) = @_;
  4600. # skip pushmark if it exists (readpipe() vs ``)
  4601. my $child = $op->first->sibling->isa('B::NULL')
  4602. ? $op->first : $op->first->sibling;
  4603. if ($self->pure_string($child)) {
  4604. return single_delim("qx", '`', $self->dq($child, 1), $self);
  4605. }
  4606. unop($self, @_, "readpipe");
  4607. }
  4608. sub dquote {
  4609. my $self = shift;
  4610. my($op, $cx) = @_;
  4611. my $kid = $op->first->sibling; # skip ex-stringify, pushmark
  4612. return $self->deparse($kid, $cx) if $self->{'unquote'};
  4613. $self->maybe_targmy($kid, $cx,
  4614. sub {single_delim("qq", '"', $self->dq($_[1]),
  4615. $self)});
  4616. }
  4617. # OP_STRINGIFY is a listop, but it only ever has one arg
  4618. sub pp_stringify {
  4619. my ($self, $op, $cx) = @_;
  4620. my $kid = $op->first->sibling;
  4621. while ($kid->name eq 'null' && !null($kid->first)) {
  4622. $kid = $kid->first;
  4623. }
  4624. if ($kid->name =~ /^(?:const|padsv|rv2sv|av2arylen|gvsv|multideref
  4625. |aelemfast(?:_lex)?|[ah]elem|join|concat)\z/x) {
  4626. maybe_targmy(@_, \&dquote);
  4627. }
  4628. else {
  4629. # Actually an optimised join.
  4630. my $result = listop(@_,"join");
  4631. $result =~ s/join([( ])/join$1$self->{'ex_const'}, /;
  4632. $result;
  4633. }
  4634. }
  4635. # tr/// and s/// (and tr[][], tr[]//, tr###, etc)
  4636. # note that tr(from)/to/ is OK, but not tr/from/(to)
  4637. sub double_delim {
  4638. my($from, $to) = @_;
  4639. my($succeed, $delim);
  4640. if ($from !~ m[/] and $to !~ m[/]) {
  4641. return "/$from/$to/";
  4642. } elsif (($succeed, $from) = balanced_delim($from) and $succeed) {
  4643. if (($succeed, $to) = balanced_delim($to) and $succeed) {
  4644. return "$from$to";
  4645. } else {
  4646. for $delim ('/', '"', '#') { # note no "'" -- s''' is special
  4647. return "$from$delim$to$delim" if index($to, $delim) == -1;
  4648. }
  4649. $to =~ s[/][\\/]g;
  4650. return "$from/$to/";
  4651. }
  4652. } else {
  4653. for $delim ('/', '"', '#') { # note no '
  4654. return "$delim$from$delim$to$delim"
  4655. if index($to . $from, $delim) == -1;
  4656. }
  4657. $from =~ s[/][\\/]g;
  4658. $to =~ s[/][\\/]g;
  4659. return "/$from/$to/";
  4660. }
  4661. }
  4662. # Only used by tr///, so backslashes hyphens
  4663. sub pchr { # ASCII
  4664. my($n) = @_;
  4665. if ($n == ord '\\') {
  4666. return '\\\\';
  4667. } elsif ($n == ord "-") {
  4668. return "\\-";
  4669. } elsif (utf8::native_to_unicode($n) >= utf8::native_to_unicode(ord(' '))
  4670. and utf8::native_to_unicode($n) <= utf8::native_to_unicode(ord('~')))
  4671. {
  4672. # I'm presuming a regex is not ok here, otherwise we could have used
  4673. # /[[:print:]]/a to get here
  4674. return chr($n);
  4675. } elsif ($n == ord "\a") {
  4676. return '\\a';
  4677. } elsif ($n == ord "\b") {
  4678. return '\\b';
  4679. } elsif ($n == ord "\t") {
  4680. return '\\t';
  4681. } elsif ($n == ord "\n") {
  4682. return '\\n';
  4683. } elsif ($n == ord "\e") {
  4684. return '\\e';
  4685. } elsif ($n == ord "\f") {
  4686. return '\\f';
  4687. } elsif ($n == ord "\r") {
  4688. return '\\r';
  4689. } elsif ($n >= ord("\cA") and $n <= ord("\cZ")) {
  4690. return '\\c' . unctrl{chr $n};
  4691. } else {
  4692. # return '\x' . sprintf("%02x", $n);
  4693. return '\\' . sprintf("%03o", $n);
  4694. }
  4695. }
  4696. sub collapse {
  4697. my(@chars) = @_;
  4698. my($str, $c, $tr) = ("");
  4699. for ($c = 0; $c < @chars; $c++) {
  4700. $tr = $chars[$c];
  4701. $str .= pchr($tr);
  4702. if ($c <= $#chars - 2 and $chars[$c + 1] == $tr + 1 and
  4703. $chars[$c + 2] == $tr + 2)
  4704. {
  4705. for (; $c <= $#chars-1 and $chars[$c + 1] == $chars[$c] + 1; $c++)
  4706. {}
  4707. $str .= "-";
  4708. $str .= pchr($chars[$c]);
  4709. }
  4710. }
  4711. return $str;
  4712. }
  4713. sub tr_decode_byte {
  4714. my($table, $flags) = @_;
  4715. my(@table) = unpack("s*", $table);
  4716. splice @table, 0x100, 1; # Number of subsequent elements
  4717. my($c, $tr, @from, @to, @delfrom, $delhyphen);
  4718. if ($table[ord "-"] != -1 and
  4719. $table[ord("-") - 1] == -1 || $table[ord("-") + 1] == -1)
  4720. {
  4721. $tr = $table[ord "-"];
  4722. $table[ord "-"] = -1;
  4723. if ($tr >= 0) {
  4724. @from = ord("-");
  4725. @to = $tr;
  4726. } else { # -2 ==> delete
  4727. $delhyphen = 1;
  4728. }
  4729. }
  4730. for ($c = 0; $c < @table; $c++) {
  4731. $tr = $table[$c];
  4732. if ($tr >= 0) {
  4733. push @from, $c; push @to, $tr;
  4734. } elsif ($tr == -2) {
  4735. push @delfrom, $c;
  4736. }
  4737. }
  4738. @from = (@from, @delfrom);
  4739. if ($flags & OPpTRANS_COMPLEMENT) {
  4740. my @newfrom = ();
  4741. my %from;
  4742. @from{@from} = (1) x @from;
  4743. for ($c = 0; $c < 256; $c++) {
  4744. push @newfrom, $c unless $from{$c};
  4745. }
  4746. @from = @newfrom;
  4747. }
  4748. unless ($flags & OPpTRANS_DELETE || !@to) {
  4749. pop @to while $#to and $to[$#to] == $to[$#to -1];
  4750. }
  4751. my($from, $to);
  4752. $from = collapse(@from);
  4753. $to = collapse(@to);
  4754. $from .= "-" if $delhyphen;
  4755. return ($from, $to);
  4756. }
  4757. sub tr_chr {
  4758. my $x = shift;
  4759. if ($x == ord "-") {
  4760. return "\\-";
  4761. } elsif ($x == ord "\\") {
  4762. return "\\\\";
  4763. } else {
  4764. return chr $x;
  4765. }
  4766. }
  4767. # XXX This doesn't yet handle all cases correctly either
  4768. sub tr_decode_utf8 {
  4769. my($swash_hv, $flags) = @_;
  4770. my %swash = $swash_hv->ARRAY;
  4771. my $final = undef;
  4772. $final = $swash{'FINAL'}->IV if exists $swash{'FINAL'};
  4773. my $none = $swash{"NONE"}->IV;
  4774. my $extra = $none + 1;
  4775. my(@from, @delfrom, @to);
  4776. my $line;
  4777. foreach $line (split /\n/, $swash{'LIST'}->PV) {
  4778. my($min, $max, $result) = split(/\t/, $line);
  4779. $min = hex $min;
  4780. if (length $max) {
  4781. $max = hex $max;
  4782. } else {
  4783. $max = $min;
  4784. }
  4785. $result = hex $result;
  4786. if ($result == $extra) {
  4787. push @delfrom, [$min, $max];
  4788. } else {
  4789. push @from, [$min, $max];
  4790. push @to, [$result, $result + $max - $min];
  4791. }
  4792. }
  4793. for my $i (0 .. $#from) {
  4794. if ($from[$i][0] == ord '-') {
  4795. unshift @from, splice(@from, $i, 1);
  4796. unshift @to, splice(@to, $i, 1);
  4797. last;
  4798. } elsif ($from[$i][1] == ord '-') {
  4799. $from[$i][1]--;
  4800. $to[$i][1]--;
  4801. unshift @from, ord '-';
  4802. unshift @to, ord '-';
  4803. last;
  4804. }
  4805. }
  4806. for my $i (0 .. $#delfrom) {
  4807. if ($delfrom[$i][0] == ord '-') {
  4808. push @delfrom, splice(@delfrom, $i, 1);
  4809. last;
  4810. } elsif ($delfrom[$i][1] == ord '-') {
  4811. $delfrom[$i][1]--;
  4812. push @delfrom, ord '-';
  4813. last;
  4814. }
  4815. }
  4816. if (defined $final and $to[$#to][1] != $final) {
  4817. push @to, [$final, $final];
  4818. }
  4819. push @from, @delfrom;
  4820. if ($flags & OPpTRANS_COMPLEMENT) {
  4821. my @newfrom;
  4822. my $next = 0;
  4823. for my $i (0 .. $#from) {
  4824. push @newfrom, [$next, $from[$i][0] - 1];
  4825. $next = $from[$i][1] + 1;
  4826. }
  4827. @from = ();
  4828. for my $range (@newfrom) {
  4829. if ($range->[0] <= $range->[1]) {
  4830. push @from, $range;
  4831. }
  4832. }
  4833. }
  4834. my($from, $to, $diff);
  4835. for my $chunk (@from) {
  4836. $diff = $chunk->[1] - $chunk->[0];
  4837. if ($diff > 1) {
  4838. $from .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
  4839. } elsif ($diff == 1) {
  4840. $from .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
  4841. } else {
  4842. $from .= tr_chr($chunk->[0]);
  4843. }
  4844. }
  4845. for my $chunk (@to) {
  4846. $diff = $chunk->[1] - $chunk->[0];
  4847. if ($diff > 1) {
  4848. $to .= tr_chr($chunk->[0]) . "-" . tr_chr($chunk->[1]);
  4849. } elsif ($diff == 1) {
  4850. $to .= tr_chr($chunk->[0]) . tr_chr($chunk->[1]);
  4851. } else {
  4852. $to .= tr_chr($chunk->[0]);
  4853. }
  4854. }
  4855. #$final = sprintf("%04x", $final) if defined $final;
  4856. #$none = sprintf("%04x", $none) if defined $none;
  4857. #$extra = sprintf("%04x", $extra) if defined $extra;
  4858. #print STDERR "final: $final\n none: $none\nextra: $extra\n";
  4859. #print STDERR $swash{'LIST'}->PV;
  4860. return (escape_str($from), escape_str($to));
  4861. }
  4862. sub pp_trans {
  4863. my $self = shift;
  4864. my($op, $cx, $morflags) = @_;
  4865. my($from, $to);
  4866. my $class = class($op);
  4867. my $priv_flags = $op->private;
  4868. if ($class eq "PVOP") {
  4869. ($from, $to) = tr_decode_byte($op->pv, $priv_flags);
  4870. } elsif ($class eq "PADOP") {
  4871. ($from, $to)
  4872. = tr_decode_utf8($self->padval($op->padix)->RV, $priv_flags);
  4873. } else { # class($op) eq "SVOP"
  4874. ($from, $to) = tr_decode_utf8($op->sv->RV, $priv_flags);
  4875. }
  4876. my $flags = "";
  4877. $flags .= "c" if $priv_flags & OPpTRANS_COMPLEMENT;
  4878. $flags .= "d" if $priv_flags & OPpTRANS_DELETE;
  4879. $to = "" if $from eq $to and $flags eq "";
  4880. $flags .= "s" if $priv_flags & OPpTRANS_SQUASH;
  4881. $flags .= $morflags if defined $morflags;
  4882. my $ret = $self->keyword("tr") . double_delim($from, $to) . $flags;
  4883. if (my $targ = $op->targ) {
  4884. return $self->maybe_parens($self->padname($targ) . " =~ $ret",
  4885. $cx, 20);
  4886. }
  4887. return $ret;
  4888. }
  4889. sub pp_transr { push @_, 'r'; goto &pp_trans }
  4890. sub re_dq_disambiguate {
  4891. my ($first, $last) = @_;
  4892. # Disambiguate "${foo}bar", "${foo}{bar}", "${foo}[1]"
  4893. ($last =~ /^[A-Z\\\^\[\]_?]/ &&
  4894. $first =~ s/([\$@])\^$/${1}{^}/) # "${^}W" etc
  4895. || ($last =~ /^[{\[\w_]/ &&
  4896. $first =~ s/([\$@])([A-Za-z_]\w*)$/${1}{$2}/);
  4897. return $first . $last;
  4898. }
  4899. # Like dq(), but different
  4900. sub re_dq {
  4901. my $self = shift;
  4902. my ($op) = @_;
  4903. my $type = $op->name;
  4904. if ($type eq "const") {
  4905. return '$[' if $op->private & OPpCONST_ARYBASE;
  4906. my $unbacked = re_unback($self->const_sv($op)->as_string);
  4907. return re_uninterp(escape_re($unbacked));
  4908. } elsif ($type eq "concat") {
  4909. my $first = $self->re_dq($op->first);
  4910. my $last = $self->re_dq($op->last);
  4911. return re_dq_disambiguate($first, $last);
  4912. } elsif ($type eq "uc") {
  4913. return '\U' . $self->re_dq($op->first->sibling) . '\E';
  4914. } elsif ($type eq "lc") {
  4915. return '\L' . $self->re_dq($op->first->sibling) . '\E';
  4916. } elsif ($type eq "ucfirst") {
  4917. return '\u' . $self->re_dq($op->first->sibling);
  4918. } elsif ($type eq "lcfirst") {
  4919. return '\l' . $self->re_dq($op->first->sibling);
  4920. } elsif ($type eq "quotemeta") {
  4921. return '\Q' . $self->re_dq($op->first->sibling) . '\E';
  4922. } elsif ($type eq "fc") {
  4923. return '\F' . $self->re_dq($op->first->sibling) . '\E';
  4924. } elsif ($type eq "join") {
  4925. return $self->deparse($op->last, 26); # was join($", @ary)
  4926. } else {
  4927. my $ret = $self->deparse($op, 26);
  4928. $ret =~ s/^\$([(|)])\z/\${$1}/ # $( $| $) need braces
  4929. or $ret =~ s/^\@([-+])\z/\@{$1}/; # @- @+ need braces
  4930. return $ret;
  4931. }
  4932. }
  4933. sub pure_string {
  4934. my ($self, $op) = @_;
  4935. return 0 if null $op;
  4936. my $type = $op->name;
  4937. if ($type eq 'const' || $type eq 'av2arylen') {
  4938. return 1;
  4939. }
  4940. elsif ($type =~ /^(?:[ul]c(first)?|fc)$/ || $type eq 'quotemeta') {
  4941. return $self->pure_string($op->first->sibling);
  4942. }
  4943. elsif ($type eq 'join') {
  4944. my $join_op = $op->first->sibling; # Skip pushmark
  4945. return 0 unless $join_op->name eq 'null' && $join_op->targ == OP_RV2SV;
  4946. my $gvop = $join_op->first;
  4947. return 0 unless $gvop->name eq 'gvsv';
  4948. return 0 unless '"' eq $self->gv_name($self->gv_or_padgv($gvop));
  4949. return 0 unless ${$join_op->sibling} eq ${$op->last};
  4950. return 0 unless $op->last->name =~ /^(?:[ah]slice|(?:rv2|pad)av)$/;
  4951. }
  4952. elsif ($type eq 'concat') {
  4953. return $self->pure_string($op->first)
  4954. && $self->pure_string($op->last);
  4955. }
  4956. elsif (is_scalar($op) || $type =~ /^[ah]elem$/) {
  4957. return 1;
  4958. }
  4959. elsif ($type eq "null" and $op->can('first') and not null $op->first) {
  4960. my $first = $op->first;
  4961. return 1 if $first->name eq "multideref";
  4962. return 1 if $first->name eq "aelemfast_lex";
  4963. if ( $first->name eq "null"
  4964. and $first->can('first')
  4965. and not null $first->first
  4966. and $first->first->name eq "aelemfast"
  4967. )
  4968. {
  4969. return 1;
  4970. }
  4971. }
  4972. return 0;
  4973. }
  4974. sub code_list {
  4975. my ($self,$op,$cv) = @_;
  4976. # localise stuff relating to the current sub
  4977. $cv and
  4978. local($self->{'curcv'}) = $cv,
  4979. local($self->{'curcvlex'}),
  4980. local(@$self{qw'curstash warnings hints hinthash curcop'})
  4981. = @$self{qw'curstash warnings hints hinthash curcop'};
  4982. my $re;
  4983. for ($op = $op->first->sibling; !null($op); $op = $op->sibling) {
  4984. if ($op->name eq 'null' and $op->flags & OPf_SPECIAL) {
  4985. my $scope = $op->first;
  4986. # 0 context (last arg to scopeop) means statement context, so
  4987. # the contents of the block will not be wrapped in do{...}.
  4988. my $block = scopeop($scope->first->name eq "enter", $self,
  4989. $scope, 0);
  4990. # next op is the source code of the block
  4991. $op = $op->sibling;
  4992. $re .= ($self->const_sv($op)->PV =~ m|^(\(\?\??\{)|)[0];
  4993. my $multiline = $block =~ /\n/;
  4994. $re .= $multiline ? "\n\t" : ' ';
  4995. $re .= $block;
  4996. $re .= $multiline ? "\n\b})" : " })";
  4997. } else {
  4998. $re = re_dq_disambiguate($re, $self->re_dq($op));
  4999. }
  5000. }
  5001. $re;
  5002. }
  5003. sub regcomp {
  5004. my $self = shift;
  5005. my($op, $cx) = @_;
  5006. my $kid = $op->first;
  5007. $kid = $kid->first if $kid->name eq "regcmaybe";
  5008. $kid = $kid->first if $kid->name eq "regcreset";
  5009. my $kname = $kid->name;
  5010. if ($kname eq "null" and !null($kid->first)
  5011. and $kid->first->name eq 'pushmark')
  5012. {
  5013. my $str = '';
  5014. $kid = $kid->first->sibling;
  5015. while (!null($kid)) {
  5016. my $first = $str;
  5017. my $last = $self->re_dq($kid);
  5018. $str = re_dq_disambiguate($first, $last);
  5019. $kid = $kid->sibling;
  5020. }
  5021. return $str, 1;
  5022. }
  5023. return ($self->re_dq($kid), 1)
  5024. if $kname =~ /^(?:rv2|pad)av/ or $self->pure_string($kid);
  5025. return ($self->deparse($kid, $cx), 0);
  5026. }
  5027. sub pp_regcomp {
  5028. my ($self, $op, $cx) = @_;
  5029. return (($self->regcomp($op, $cx, 0))[0]);
  5030. }
  5031. sub re_flags {
  5032. my ($self, $op) = @_;
  5033. my $flags = '';
  5034. my $pmflags = $op->pmflags;
  5035. if (!$pmflags) {
  5036. my $re = $op->pmregexp;
  5037. if ($$re) {
  5038. $pmflags = $re->compflags;
  5039. }
  5040. }
  5041. $flags .= "g" if $pmflags & PMf_GLOBAL;
  5042. $flags .= "i" if $pmflags & PMf_FOLD;
  5043. $flags .= "m" if $pmflags & PMf_MULTILINE;
  5044. $flags .= "o" if $pmflags & PMf_KEEP;
  5045. $flags .= "s" if $pmflags & PMf_SINGLELINE;
  5046. $flags .= "x" if $pmflags & PMf_EXTENDED;
  5047. $flags .= "x" if $pmflags & PMf_EXTENDED_MORE;
  5048. $flags .= "p" if $pmflags & RXf_PMf_KEEPCOPY;
  5049. if (my $charset = $pmflags & RXf_PMf_CHARSET) {
  5050. # Hardcoding this is fragile, but B does not yet export the
  5051. # constants we need.
  5052. $flags .= qw(d l u a aa)[$charset >> 7]
  5053. }
  5054. # The /d flag is indicated by 0; only show it if necessary.
  5055. elsif ($self->{hinthash} and
  5056. $self->{hinthash}{reflags_charset}
  5057. || $self->{hinthash}{feature_unicode}
  5058. or $self->{hints} & $feature::hint_mask
  5059. && ($self->{hints} & $feature::hint_mask)
  5060. != $feature::hint_mask
  5061. && do {
  5062. $self->{hints} & $feature::hint_uni8bit;
  5063. }
  5064. ) {
  5065. $flags .= 'd';
  5066. }
  5067. $flags;
  5068. }
  5069. # osmic acid -- see osmium tetroxide
  5070. my %matchwords;
  5071. map($matchwords{join "", sort split //, $_} = $_, 'cig', 'cog', 'cos', 'cogs',
  5072. 'cox', 'go', 'is', 'ism', 'iso', 'mig', 'mix', 'osmic', 'ox', 'sic',
  5073. 'sig', 'six', 'smog', 'so', 'soc', 'sog', 'xi', 'soup', 'soupmix');
  5074. # When deparsing a regular expression with code blocks, we have to look in
  5075. # various places to find the blocks.
  5076. #
  5077. # For qr/(?{...})/ without interpolation, the CV is under $qr->qr_anoncv
  5078. # and the code list (list of blocks and constants, maybe vars) is under
  5079. # $cv->ROOT->first->code_list:
  5080. # ./perl -Ilib -MB -e 'use O "Concise", B::svref_2object(sub {qr/(?{die})/})->ROOT->first->first->sibling->pmregexp->qr_anoncv->object_2svref'
  5081. #
  5082. # For qr/$a(?{...})/ with interpolation, the code list is more accessible,
  5083. # under $pmop->code_list, but the $cv is something you have to dig for in
  5084. # the regcomp op’s kids:
  5085. # ./perl -Ilib -mO=Concise -e 'qr/$a(?{die})/'
  5086. #
  5087. # For m// and split //, things are much simpler. There is no CV. The code
  5088. # list is under $pmop->code_list.
  5089. sub matchop {
  5090. my $self = shift;
  5091. my($op, $cx, $name, $delim) = @_;
  5092. my $kid = $op->first;
  5093. my ($binop, $var, $re) = ("", "", "");
  5094. if ($op->flags & OPf_STACKED) {
  5095. $binop = 1;
  5096. $var = $self->deparse($kid, 20);
  5097. $kid = $kid->sibling;
  5098. }
  5099. # not $name; $name will be 'm' for both match and split
  5100. elsif ($op->name eq 'match' and my $targ = $op->targ) {
  5101. $binop = 1;
  5102. $var = $self->padname($targ);
  5103. }
  5104. my $quote = 1;
  5105. my $pmflags = $op->pmflags;
  5106. my $rhs_bound_to_defsv;
  5107. my ($cv, $bregexp);
  5108. my $have_kid = !null $kid;
  5109. # Check for code blocks first
  5110. if (not null my $code_list = $op->code_list) {
  5111. $re = $self->code_list($code_list,
  5112. $op->name eq 'qr'
  5113. ? $self->padval(
  5114. $kid->first # ex-list
  5115. ->first # pushmark
  5116. ->sibling # entersub
  5117. ->first # ex-list
  5118. ->first # pushmark
  5119. ->sibling # srefgen
  5120. ->first # ex-list
  5121. ->first # anoncode
  5122. ->targ
  5123. )
  5124. : undef);
  5125. } elsif (${$bregexp = $op->pmregexp} && ${$cv = $bregexp->qr_anoncv}) {
  5126. my $patop = $cv->ROOT # leavesub
  5127. ->first # qr
  5128. ->code_list;# list
  5129. $re = $self->code_list($patop, $cv);
  5130. } elsif (!$have_kid) {
  5131. $re = re_uninterp(escape_re(re_unback($op->precomp)));
  5132. } elsif ($kid->name ne 'regcomp') {
  5133. carp("found ".$kid->name." where regcomp expected");
  5134. } else {
  5135. ($re, $quote) = $self->regcomp($kid, 21);
  5136. }
  5137. if ($have_kid and $kid->name eq 'regcomp') {
  5138. my $matchop = $kid->first;
  5139. if ($matchop->name eq 'regcreset') {
  5140. $matchop = $matchop->first;
  5141. }
  5142. if ($matchop->name =~ /^(?:match|transr?|subst)\z/
  5143. && $matchop->flags & OPf_SPECIAL) {
  5144. $rhs_bound_to_defsv = 1;
  5145. }
  5146. }
  5147. my $flags = "";
  5148. $flags .= "c" if $pmflags & PMf_CONTINUE;
  5149. $flags .= $self->re_flags($op);
  5150. $flags = join '', sort split //, $flags;
  5151. $flags = $matchwords{$flags} if $matchwords{$flags};
  5152. if ($pmflags & PMf_ONCE) { # only one kind of delimiter works here
  5153. $re =~ s/\?/\\?/g;
  5154. $re = $self->keyword("m") . "?$re?"; # explicit 'm' is required
  5155. } elsif ($quote) {
  5156. $re = single_delim($name, $delim, $re, $self);
  5157. }
  5158. $re = $re . $flags if $quote;
  5159. if ($binop) {
  5160. return
  5161. $self->maybe_parens(
  5162. $rhs_bound_to_defsv
  5163. ? "$var =~ (\$_ =~ $re)"
  5164. : "$var =~ $re",
  5165. $cx, 20
  5166. );
  5167. } else {
  5168. return $re;
  5169. }
  5170. }
  5171. sub pp_match { matchop(@_, "m", "/") }
  5172. sub pp_pushre { matchop(@_, "m", "/") }
  5173. sub pp_qr { matchop(@_, "qr", "") }
  5174. sub pp_runcv { unop(@_, "__SUB__"); }
  5175. sub pp_split {
  5176. maybe_targmy(@_, \&split);
  5177. }
  5178. sub split {
  5179. my $self = shift;
  5180. my($op, $cx) = @_;
  5181. my($kid, @exprs, $ary, $expr);
  5182. $kid = $op->first;
  5183. # For our kid (an OP_PUSHRE), pmreplroot is never actually the
  5184. # root of a replacement; it's either empty, or abused to point to
  5185. # the GV for an array we split into (an optimization to save
  5186. # assignment overhead). Depending on whether we're using ithreads,
  5187. # this OP* holds either a GV* or a PADOFFSET. Luckily, B.xs
  5188. # figures out for us which it is.
  5189. my $replroot = $kid->pmreplroot;
  5190. my $gv = 0;
  5191. my $stacked = $op->flags & OPf_STACKED;
  5192. if (ref($replroot) eq "B::GV") {
  5193. $gv = $replroot;
  5194. } elsif (!ref($replroot) and $replroot > 0) {
  5195. $gv = $self->padval($replroot);
  5196. } elsif ($kid->targ) {
  5197. $ary = $self->padname($kid->targ)
  5198. } elsif ($stacked) {
  5199. $ary = $self->deparse($op->last, 7);
  5200. }
  5201. $ary = $self->maybe_local(@_,
  5202. $self->stash_variable('@',
  5203. $self->gv_name($gv),
  5204. $cx))
  5205. if $gv;
  5206. # Skip the last kid when OPf_STACKED is set, since it is the array
  5207. # on the left.
  5208. for (; !null($stacked ? $kid->sibling : $kid); $kid = $kid->sibling) {
  5209. push @exprs, $self->deparse($kid, 6);
  5210. }
  5211. # handle special case of split(), and split(' ') that compiles to /\s+/
  5212. # Under 5.10, the reflags may be undef if the split regexp isn't a constant
  5213. # Under 5.17.5-5.17.9, the special flag is on split itself.
  5214. $kid = $op->first;
  5215. if ( $op->flags & OPf_SPECIAL
  5216. or (
  5217. $kid->flags & OPf_SPECIAL
  5218. and ( $] < 5.009 ? $kid->pmflags & PMf_SKIPWHITE()
  5219. : ($kid->reflags || 0) & RXf_SKIPWHITE()
  5220. )
  5221. )
  5222. ) {
  5223. $exprs[0] = "' '";
  5224. }
  5225. $expr = "split(" . join(", ", @exprs) . ")";
  5226. if ($ary) {
  5227. return $self->maybe_parens("$ary = $expr", $cx, 7);
  5228. } else {
  5229. return $expr;
  5230. }
  5231. }
  5232. # oxime -- any of various compounds obtained chiefly by the action of
  5233. # hydroxylamine on aldehydes and ketones and characterized by the
  5234. # bivalent grouping C=NOH [Webster's Tenth]
  5235. my %substwords;
  5236. map($substwords{join "", sort split //, $_} = $_, 'ego', 'egoism', 'em',
  5237. 'es', 'ex', 'exes', 'gee', 'go', 'goes', 'ie', 'ism', 'iso', 'me',
  5238. 'meese', 'meso', 'mig', 'mix', 'os', 'ox', 'oxime', 'see', 'seem',
  5239. 'seg', 'sex', 'sig', 'six', 'smog', 'sog', 'some', 'xi', 'rogue',
  5240. 'sir', 'rise', 'smore', 'more', 'seer', 'rome', 'gore', 'grim', 'grime',
  5241. 'or', 'rose', 'rosie');
  5242. sub pp_subst {
  5243. my $self = shift;
  5244. my($op, $cx) = @_;
  5245. my $kid = $op->first;
  5246. my($binop, $var, $re, $repl) = ("", "", "", "");
  5247. if ($op->flags & OPf_STACKED) {
  5248. $binop = 1;
  5249. $var = $self->deparse($kid, 20);
  5250. $kid = $kid->sibling;
  5251. }
  5252. elsif (my $targ = $op->targ) {
  5253. $binop = 1;
  5254. $var = $self->padname($targ);
  5255. }
  5256. my $flags = "";
  5257. my $pmflags = $op->pmflags;
  5258. if (null($op->pmreplroot)) {
  5259. $repl = $kid;
  5260. $kid = $kid->sibling;
  5261. } else {
  5262. $repl = $op->pmreplroot->first; # skip substcont
  5263. }
  5264. while ($repl->name eq "entereval") {
  5265. $repl = $repl->first;
  5266. $flags .= "e";
  5267. }
  5268. {
  5269. local $self->{in_subst_repl} = 1;
  5270. if ($pmflags & PMf_EVAL) {
  5271. $repl = $self->deparse($repl->first, 0);
  5272. } else {
  5273. $repl = $self->dq($repl);
  5274. }
  5275. }
  5276. if (not null my $code_list = $op->code_list) {
  5277. $re = $self->code_list($code_list);
  5278. } elsif (null $kid) {
  5279. $re = re_uninterp(escape_re(re_unback($op->precomp)));
  5280. } else {
  5281. ($re) = $self->regcomp($kid, 1);
  5282. }
  5283. $flags .= "r" if $pmflags & PMf_NONDESTRUCT;
  5284. $flags .= "e" if $pmflags & PMf_EVAL;
  5285. $flags .= $self->re_flags($op);
  5286. $flags = join '', sort split //, $flags;
  5287. $flags = $substwords{$flags} if $substwords{$flags};
  5288. my $core_s = $self->keyword("s"); # maybe CORE::s
  5289. if ($binop) {
  5290. return $self->maybe_parens("$var =~ $core_s"
  5291. . double_delim($re, $repl) . $flags,
  5292. $cx, 20);
  5293. } else {
  5294. return "$core_s". double_delim($re, $repl) . $flags;
  5295. }
  5296. }
  5297. sub is_lexical_subs {
  5298. my (@ops) = shift;
  5299. for my $op (@ops) {
  5300. return 0 if $op->name !~ /\A(?:introcv|clonecv)\z/;
  5301. }
  5302. return 1;
  5303. }
  5304. # Pretend these two ops do not exist. The perl parser adds them to the
  5305. # beginning of any block containing my-sub declarations, whereas we handle
  5306. # the subs in pad_subs and next_todo.
  5307. *pp_clonecv = *pp_introcv;
  5308. sub pp_introcv {
  5309. my $self = shift;
  5310. my($op, $cx) = @_;
  5311. # For now, deparsing doesn't worry about the distinction between introcv
  5312. # and clonecv, so pretend this op doesn't exist:
  5313. return '';
  5314. }
  5315. sub pp_padcv {
  5316. my $self = shift;
  5317. my($op, $cx) = @_;
  5318. return $self->padany($op);
  5319. }
  5320. my %lvref_funnies = (
  5321. OPpLVREF_SV, => '$',
  5322. OPpLVREF_AV, => '@',
  5323. OPpLVREF_HV, => '%',
  5324. OPpLVREF_CV, => '&',
  5325. );
  5326. sub pp_refassign {
  5327. my ($self, $op, $cx) = @_;
  5328. my $left;
  5329. if ($op->private & OPpLVREF_ELEM) {
  5330. $left = $op->first->sibling;
  5331. $left = maybe_local(@_, elem($self, $left, undef,
  5332. $left->targ == OP_AELEM
  5333. ? qw([ ] padav)
  5334. : qw({ } padhv)));
  5335. } elsif ($op->flags & OPf_STACKED) {
  5336. $left = maybe_local(@_,
  5337. $lvref_funnies{$op->private & OPpLVREF_TYPE}
  5338. . $self->deparse($op->first->sibling));
  5339. } else {
  5340. $left = &pp_padsv;
  5341. }
  5342. my $right = $self->deparse_binop_right($op, $op->first, 7);
  5343. return $self->maybe_parens("\\$left = $right", $cx, 7);
  5344. }
  5345. sub pp_lvref {
  5346. my ($self, $op, $cx) = @_;
  5347. my $code;
  5348. if ($op->private & OPpLVREF_ELEM) {
  5349. $code = $op->first->name =~ /av\z/ ? &pp_aelem : &pp_helem;
  5350. } elsif ($op->flags & OPf_STACKED) {
  5351. $code = maybe_local(@_,
  5352. $lvref_funnies{$op->private & OPpLVREF_TYPE}
  5353. . $self->deparse($op->first));
  5354. } else {
  5355. $code = &pp_padsv;
  5356. }
  5357. "\\$code";
  5358. }
  5359. sub pp_lvrefslice {
  5360. my ($self, $op, $cx) = @_;
  5361. '\\' . ($op->last->name =~ /av\z/ ? &pp_aslice : &pp_hslice);
  5362. }
  5363. sub pp_lvavref {
  5364. my ($self, $op, $cx) = @_;
  5365. '\\(' . ($op->flags & OPf_STACKED
  5366. ? maybe_local(@_, rv2x(@_, "\@"))
  5367. : &pp_padsv) . ')'
  5368. }
  5369. 1;
  5370. __END__
  5371. =head1 NAME
  5372. B::Deparse - Perl compiler backend to produce perl code
  5373. =head1 SYNOPSIS
  5374. B<perl> B<-MO=Deparse>[B<,-d>][B<,-f>I<FILE>][B<,-p>][B<,-q>][B<,-l>]
  5375. [B<,-s>I<LETTERS>][B<,-x>I<LEVEL>] I<prog.pl>
  5376. =head1 DESCRIPTION
  5377. B::Deparse is a backend module for the Perl compiler that generates
  5378. perl source code, based on the internal compiled structure that perl
  5379. itself creates after parsing a program. The output of B::Deparse won't
  5380. be exactly the same as the original source, since perl doesn't keep
  5381. track of comments or whitespace, and there isn't a one-to-one
  5382. correspondence between perl's syntactical constructions and their
  5383. compiled form, but it will often be close. When you use the B<-p>
  5384. option, the output also includes parentheses even when they are not
  5385. required by precedence, which can make it easy to see if perl is
  5386. parsing your expressions the way you intended.
  5387. While B::Deparse goes to some lengths to try to figure out what your
  5388. original program was doing, some parts of the language can still trip
  5389. it up; it still fails even on some parts of Perl's own test suite. If
  5390. you encounter a failure other than the most common ones described in
  5391. the BUGS section below, you can help contribute to B::Deparse's
  5392. ongoing development by submitting a bug report with a small
  5393. example.
  5394. =head1 OPTIONS
  5395. As with all compiler backend options, these must follow directly after
  5396. the '-MO=Deparse', separated by a comma but not any white space.
  5397. =over 4
  5398. =item B<-d>
  5399. Output data values (when they appear as constants) using Data::Dumper.
  5400. Without this option, B::Deparse will use some simple routines of its
  5401. own for the same purpose. Currently, Data::Dumper is better for some
  5402. kinds of data (such as complex structures with sharing and
  5403. self-reference) while the built-in routines are better for others
  5404. (such as odd floating-point values).
  5405. =item B<-f>I<FILE>
  5406. Normally, B::Deparse deparses the main code of a program, and all the subs
  5407. defined in the same file. To include subs defined in
  5408. other files, pass the B<-f> option with the filename.
  5409. You can pass the B<-f> option several times, to
  5410. include more than one secondary file. (Most of the time you don't want to
  5411. use it at all.) You can also use this option to include subs which are
  5412. defined in the scope of a B<#line> directive with two parameters.
  5413. =item B<-l>
  5414. Add '#line' declarations to the output based on the line and file
  5415. locations of the original code.
  5416. =item B<-p>
  5417. Print extra parentheses. Without this option, B::Deparse includes
  5418. parentheses in its output only when they are needed, based on the
  5419. structure of your program. With B<-p>, it uses parentheses (almost)
  5420. whenever they would be legal. This can be useful if you are used to
  5421. LISP, or if you want to see how perl parses your input. If you say
  5422. if ($var & 0x7f == 65) {print "Gimme an A!"}
  5423. print ($which ? $a : $b), "\n";
  5424. $name = $ENV{USER} or "Bob";
  5425. C<B::Deparse,-p> will print
  5426. if (($var & 0)) {
  5427. print('Gimme an A!')
  5428. };
  5429. (print(($which ? $a : $b)), '???');
  5430. (($name = $ENV{'USER'}) or '???')
  5431. which probably isn't what you intended (the C<'???'> is a sign that
  5432. perl optimized away a constant value).
  5433. =item B<-P>
  5434. Disable prototype checking. With this option, all function calls are
  5435. deparsed as if no prototype was defined for them. In other words,
  5436. perl -MO=Deparse,-P -e 'sub foo (\@) { 1 } foo @x'
  5437. will print
  5438. sub foo (\@) {
  5439. 1;
  5440. }
  5441. &foo(\@x);
  5442. making clear how the parameters are actually passed to C<foo>.
  5443. =item B<-q>
  5444. Expand double-quoted strings into the corresponding combinations of
  5445. concatenation, uc, ucfirst, lc, lcfirst, quotemeta, and join. For
  5446. instance, print
  5447. print "Hello, $world, @ladies, \u$gentlemen\E, \u\L$me!";
  5448. as
  5449. print 'Hello, ' . $world . ', ' . join($", @ladies) . ', '
  5450. . ucfirst($gentlemen) . ', ' . ucfirst(lc $me . '!');
  5451. Note that the expanded form represents the way perl handles such
  5452. constructions internally -- this option actually turns off the reverse
  5453. translation that B::Deparse usually does. On the other hand, note that
  5454. C<$x = "$y"> is not the same as C<$x = $y>: the former makes the value
  5455. of $y into a string before doing the assignment.
  5456. =item B<-s>I<LETTERS>
  5457. Tweak the style of B::Deparse's output. The letters should follow
  5458. directly after the 's', with no space or punctuation. The following
  5459. options are available:
  5460. =over 4
  5461. =item B<C>
  5462. Cuddle C<elsif>, C<else>, and C<continue> blocks. For example, print
  5463. if (...) {
  5464. ...
  5465. } else {
  5466. ...
  5467. }
  5468. instead of
  5469. if (...) {
  5470. ...
  5471. }
  5472. else {
  5473. ...
  5474. }
  5475. The default is not to cuddle.
  5476. =item B<i>I<NUMBER>
  5477. Indent lines by multiples of I<NUMBER> columns. The default is 4 columns.
  5478. =item B<T>
  5479. Use tabs for each 8 columns of indent. The default is to use only spaces.
  5480. For instance, if the style options are B<-si4T>, a line that's indented
  5481. 3 times will be preceded by one tab and four spaces; if the options were
  5482. B<-si8T>, the same line would be preceded by three tabs.
  5483. =item B<v>I<STRING>B<.>
  5484. Print I<STRING> for the value of a constant that can't be determined
  5485. because it was optimized away (mnemonic: this happens when a constant
  5486. is used in B<v>oid context). The end of the string is marked by a period.
  5487. The string should be a valid perl expression, generally a constant.
  5488. Note that unless it's a number, it probably needs to be quoted, and on
  5489. a command line quotes need to be protected from the shell. Some
  5490. conventional values include 0, 1, 42, '', 'foo', and
  5491. 'Useless use of constant omitted' (which may need to be
  5492. B<-sv"'Useless use of constant omitted'.">
  5493. or something similar depending on your shell). The default is '???'.
  5494. If you're using B::Deparse on a module or other file that's require'd,
  5495. you shouldn't use a value that evaluates to false, since the customary
  5496. true constant at the end of a module will be in void context when the
  5497. file is compiled as a main program.
  5498. =back
  5499. =item B<-x>I<LEVEL>
  5500. Expand conventional syntax constructions into equivalent ones that expose
  5501. their internal operation. I<LEVEL> should be a digit, with higher values
  5502. meaning more expansion. As with B<-q>, this actually involves turning off
  5503. special cases in B::Deparse's normal operations.
  5504. If I<LEVEL> is at least 3, C<for> loops will be translated into equivalent
  5505. while loops with continue blocks; for instance
  5506. for ($i = 0; $i < 10; ++$i) {
  5507. print $i;
  5508. }
  5509. turns into
  5510. $i = 0;
  5511. while ($i < 10) {
  5512. print $i;
  5513. } continue {
  5514. ++$i
  5515. }
  5516. Note that in a few cases this translation can't be perfectly carried back
  5517. into the source code -- if the loop's initializer declares a my variable,
  5518. for instance, it won't have the correct scope outside of the loop.
  5519. If I<LEVEL> is at least 5, C<use> declarations will be translated into
  5520. C<BEGIN> blocks containing calls to C<require> and C<import>; for
  5521. instance,
  5522. use strict 'refs';
  5523. turns into
  5524. sub BEGIN {
  5525. require strict;
  5526. do {
  5527. 'strict'->import('refs')
  5528. };
  5529. }
  5530. If I<LEVEL> is at least 7, C<if> statements will be translated into
  5531. equivalent expressions using C<&&>, C<?:> and C<do {}>; for instance
  5532. print 'hi' if $nice;
  5533. if ($nice) {
  5534. print 'hi';
  5535. }
  5536. if ($nice) {
  5537. print 'hi';
  5538. } else {
  5539. print 'bye';
  5540. }
  5541. turns into
  5542. $nice and print 'hi';
  5543. $nice and do { print 'hi' };
  5544. $nice ? do { print 'hi' } : do { print 'bye' };
  5545. Long sequences of elsifs will turn into nested ternary operators, which
  5546. B::Deparse doesn't know how to indent nicely.
  5547. =back
  5548. =head1 USING B::Deparse AS A MODULE
  5549. =head2 Synopsis
  5550. use B::Deparse;
  5551. $deparse = B::Deparse->new("-p", "-sC");
  5552. $body = $deparse->coderef2text(\&func);
  5553. eval "sub func $body"; # the inverse operation
  5554. =head2 Description
  5555. B::Deparse can also be used on a sub-by-sub basis from other perl
  5556. programs.
  5557. =head2 new
  5558. $deparse = B::Deparse->new(OPTIONS)
  5559. Create an object to store the state of a deparsing operation and any
  5560. options. The options are the same as those that can be given on the
  5561. command line (see L</OPTIONS>); options that are separated by commas
  5562. after B<-MO=Deparse> should be given as separate strings.
  5563. =head2 ambient_pragmas
  5564. $deparse->ambient_pragmas(strict => 'all', '$[' => $[);
  5565. The compilation of a subroutine can be affected by a few compiler
  5566. directives, B<pragmas>. These are:
  5567. =over 4
  5568. =item *
  5569. use strict;
  5570. =item *
  5571. use warnings;
  5572. =item *
  5573. Assigning to the special variable $[
  5574. =item *
  5575. use integer;
  5576. =item *
  5577. use bytes;
  5578. =item *
  5579. use utf8;
  5580. =item *
  5581. use re;
  5582. =back
  5583. Ordinarily, if you use B::Deparse on a subroutine which has
  5584. been compiled in the presence of one or more of these pragmas,
  5585. the output will include statements to turn on the appropriate
  5586. directives. So if you then compile the code returned by coderef2text,
  5587. it will behave the same way as the subroutine which you deparsed.
  5588. However, you may know that you intend to use the results in a
  5589. particular context, where some pragmas are already in scope. In
  5590. this case, you use the B<ambient_pragmas> method to describe the
  5591. assumptions you wish to make.
  5592. Not all of the options currently have any useful effect. See
  5593. L</BUGS> for more details.
  5594. The parameters it accepts are:
  5595. =over 4
  5596. =item strict
  5597. Takes a string, possibly containing several values separated
  5598. by whitespace. The special values "all" and "none" mean what you'd
  5599. expect.
  5600. $deparse->ambient_pragmas(strict => 'subs refs');
  5601. =item $[
  5602. Takes a number, the value of the array base $[.
  5603. Cannot be non-zero on Perl 5.15.3 or later.
  5604. =item bytes
  5605. =item utf8
  5606. =item integer
  5607. If the value is true, then the appropriate pragma is assumed to
  5608. be in the ambient scope, otherwise not.
  5609. =item re
  5610. Takes a string, possibly containing a whitespace-separated list of
  5611. values. The values "all" and "none" are special. It's also permissible
  5612. to pass an array reference here.
  5613. $deparser->ambient_pragmas(re => 'eval');
  5614. =item warnings
  5615. Takes a string, possibly containing a whitespace-separated list of
  5616. values. The values "all" and "none" are special, again. It's also
  5617. permissible to pass an array reference here.
  5618. $deparser->ambient_pragmas(warnings => [qw[void io]]);
  5619. If one of the values is the string "FATAL", then all the warnings
  5620. in that list will be considered fatal, just as with the B<warnings>
  5621. pragma itself. Should you need to specify that some warnings are
  5622. fatal, and others are merely enabled, you can pass the B<warnings>
  5623. parameter twice:
  5624. $deparser->ambient_pragmas(
  5625. warnings => 'all',
  5626. warnings => [FATAL => qw/void io/],
  5627. );
  5628. See L<warnings> for more information about lexical warnings.
  5629. =item hint_bits
  5630. =item warning_bits
  5631. These two parameters are used to specify the ambient pragmas in
  5632. the format used by the special variables $^H and ${^WARNING_BITS}.
  5633. They exist principally so that you can write code like:
  5634. { my ($hint_bits, $warning_bits);
  5635. BEGIN {($hint_bits, $warning_bits) = ($^H, ${^WARNING_BITS})}
  5636. $deparser->ambient_pragmas (
  5637. hint_bits => $hint_bits,
  5638. warning_bits => $warning_bits,
  5639. '$[' => 0 + $[
  5640. ); }
  5641. which specifies that the ambient pragmas are exactly those which
  5642. are in scope at the point of calling.
  5643. =item %^H
  5644. This parameter is used to specify the ambient pragmas which are
  5645. stored in the special hash %^H.
  5646. =back
  5647. =head2 coderef2text
  5648. $body = $deparse->coderef2text(\&func)
  5649. $body = $deparse->coderef2text(sub ($$) { ... })
  5650. Return source code for the body of a subroutine (a block, optionally
  5651. preceded by a prototype in parens), given a reference to the
  5652. sub. Because a subroutine can have no names, or more than one name,
  5653. this method doesn't return a complete subroutine definition -- if you
  5654. want to eval the result, you should prepend "sub subname ", or "sub "
  5655. for an anonymous function constructor. Unless the sub was defined in
  5656. the main:: package, the code will include a package declaration.
  5657. =head1 BUGS
  5658. =over 4
  5659. =item *
  5660. In Perl 5.20 and earlier, the only pragmas to
  5661. be completely supported are: C<use warnings>,
  5662. C<use strict>, C<use bytes>, C<use integer>
  5663. and C<use feature>. (C<$[>, which
  5664. behaves like a pragma, is also supported.)
  5665. Excepting those listed above, we're currently unable to guarantee that
  5666. B::Deparse will produce a pragma at the correct point in the program.
  5667. (Specifically, pragmas at the beginning of a block often appear right
  5668. before the start of the block instead.)
  5669. Since the effects of pragmas are often lexically scoped, this can mean
  5670. that the pragma holds sway over a different portion of the program
  5671. than in the input file.
  5672. =item *
  5673. In fact, the above is a specific instance of a more general problem:
  5674. we can't guarantee to produce BEGIN blocks or C<use> declarations in
  5675. exactly the right place. So if you use a module which affects compilation
  5676. (such as by over-riding keywords, overloading constants or whatever)
  5677. then the output code might not work as intended.
  5678. This is the most serious problem in Perl 5.20 and earlier. Fixing this
  5679. required internal changes in Perl 5.22.
  5680. =item *
  5681. Some constants don't print correctly either with or without B<-d>.
  5682. For instance, neither B::Deparse nor Data::Dumper know how to print
  5683. dual-valued scalars correctly, as in:
  5684. use constant E2BIG => ($!=7); $y = E2BIG; print $y, 0+$y;
  5685. use constant H => { "#" => 1 }; H->{"#"};
  5686. =item *
  5687. An input file that uses source filtering probably won't be deparsed into
  5688. runnable code, because it will still include the B<use> declaration
  5689. for the source filtering module, even though the code that is
  5690. produced is already ordinary Perl which shouldn't be filtered again.
  5691. =item *
  5692. Optimized-away statements are rendered as
  5693. '???'. This includes statements that
  5694. have a compile-time side-effect, such as the obscure
  5695. my $x if 0;
  5696. which is not, consequently, deparsed correctly.
  5697. foreach my $i (@_) { 0 }
  5698. =>
  5699. foreach my $i (@_) { '???' }
  5700. =item *
  5701. Lexical (my) variables declared in scopes external to a subroutine
  5702. appear in code2ref output text as package variables. This is a tricky
  5703. problem, as perl has no native facility for referring to a lexical variable
  5704. defined within a different scope, although L<PadWalker> is a good start.
  5705. See also L<Data::Dump::Streamer>, which combines B::Deparse and
  5706. L<PadWalker> to serialize closures properly.
  5707. =item *
  5708. There are probably many more bugs on non-ASCII platforms (EBCDIC).
  5709. =item *
  5710. Prior to Perl 5.22, lexical C<my> subroutines were not deparsed properly.
  5711. They were emitted as pure declarations, sometimes in the wrong place.
  5712. Lexical C<state> subroutines were not deparsed at all.
  5713. =back
  5714. =head1 AUTHOR
  5715. Stephen McCamant <smcc@CSUA.Berkeley.EDU>, based on an earlier version
  5716. by Malcolm Beattie <mbeattie@sable.ox.ac.uk>, with contributions from
  5717. Gisle Aas, James Duncan, Albert Dvornik, Robin Houston, Dave Mitchell,
  5718. Hugo van der Sanden, Gurusamy Sarathy, Nick Ing-Simmons, and Rafael
  5719. Garcia-Suarez.
  5720. =cut