ItaniumDemangle.h 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===--- ItaniumDemangle.h -----------*- mode:c++;eval:(read-only-mode) -*-===//
  7. // Do not edit! See README.txt.
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Generic itanium demangler library.
  15. // There are two copies of this file in the source tree. The one under
  16. // libcxxabi is the original and the one under llvm is the copy. Use
  17. // cp-to-llvm.sh to update the copy. See README.txt for more details.
  18. //
  19. //===----------------------------------------------------------------------===//
  20. #ifndef DEMANGLE_ITANIUMDEMANGLE_H
  21. #define DEMANGLE_ITANIUMDEMANGLE_H
  22. #include "DemangleConfig.h"
  23. #include "StringView.h"
  24. #include "Utility.h"
  25. #include <algorithm>
  26. #include <cassert>
  27. #include <cctype>
  28. #include <cstdio>
  29. #include <cstdlib>
  30. #include <cstring>
  31. #include <limits>
  32. #include <new>
  33. #include <type_traits>
  34. #include <utility>
  35. DEMANGLE_NAMESPACE_BEGIN
  36. template <class T, size_t N> class PODSmallVector {
  37. static_assert(std::is_trivial<T>::value,
  38. "T is required to be a trivial type");
  39. T *First = nullptr;
  40. T *Last = nullptr;
  41. T *Cap = nullptr;
  42. T Inline[N] = {};
  43. bool isInline() const { return First == Inline; }
  44. void clearInline() {
  45. First = Inline;
  46. Last = Inline;
  47. Cap = Inline + N;
  48. }
  49. void reserve(size_t NewCap) {
  50. size_t S = size();
  51. if (isInline()) {
  52. auto *Tmp = static_cast<T *>(std::malloc(NewCap * sizeof(T)));
  53. if (Tmp == nullptr)
  54. std::terminate();
  55. std::copy(First, Last, Tmp);
  56. First = Tmp;
  57. } else {
  58. First = static_cast<T *>(std::realloc(First, NewCap * sizeof(T)));
  59. if (First == nullptr)
  60. std::terminate();
  61. }
  62. Last = First + S;
  63. Cap = First + NewCap;
  64. }
  65. public:
  66. PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
  67. PODSmallVector(const PODSmallVector &) = delete;
  68. PODSmallVector &operator=(const PODSmallVector &) = delete;
  69. PODSmallVector(PODSmallVector &&Other) : PODSmallVector() {
  70. if (Other.isInline()) {
  71. std::copy(Other.begin(), Other.end(), First);
  72. Last = First + Other.size();
  73. Other.clear();
  74. return;
  75. }
  76. First = Other.First;
  77. Last = Other.Last;
  78. Cap = Other.Cap;
  79. Other.clearInline();
  80. }
  81. PODSmallVector &operator=(PODSmallVector &&Other) {
  82. if (Other.isInline()) {
  83. if (!isInline()) {
  84. std::free(First);
  85. clearInline();
  86. }
  87. std::copy(Other.begin(), Other.end(), First);
  88. Last = First + Other.size();
  89. Other.clear();
  90. return *this;
  91. }
  92. if (isInline()) {
  93. First = Other.First;
  94. Last = Other.Last;
  95. Cap = Other.Cap;
  96. Other.clearInline();
  97. return *this;
  98. }
  99. std::swap(First, Other.First);
  100. std::swap(Last, Other.Last);
  101. std::swap(Cap, Other.Cap);
  102. Other.clear();
  103. return *this;
  104. }
  105. // NOLINTNEXTLINE(readability-identifier-naming)
  106. void push_back(const T &Elem) {
  107. if (Last == Cap)
  108. reserve(size() * 2);
  109. *Last++ = Elem;
  110. }
  111. // NOLINTNEXTLINE(readability-identifier-naming)
  112. void pop_back() {
  113. assert(Last != First && "Popping empty vector!");
  114. --Last;
  115. }
  116. void dropBack(size_t Index) {
  117. assert(Index <= size() && "dropBack() can't expand!");
  118. Last = First + Index;
  119. }
  120. T *begin() { return First; }
  121. T *end() { return Last; }
  122. bool empty() const { return First == Last; }
  123. size_t size() const { return static_cast<size_t>(Last - First); }
  124. T &back() {
  125. assert(Last != First && "Calling back() on empty vector!");
  126. return *(Last - 1);
  127. }
  128. T &operator[](size_t Index) {
  129. assert(Index < size() && "Invalid access!");
  130. return *(begin() + Index);
  131. }
  132. void clear() { Last = First; }
  133. ~PODSmallVector() {
  134. if (!isInline())
  135. std::free(First);
  136. }
  137. };
  138. // Base class of all AST nodes. The AST is built by the parser, then is
  139. // traversed by the printLeft/Right functions to produce a demangled string.
  140. class Node {
  141. public:
  142. enum Kind : unsigned char {
  143. #define NODE(NodeKind) K##NodeKind,
  144. #include "ItaniumNodes.def"
  145. };
  146. /// Three-way bool to track a cached value. Unknown is possible if this node
  147. /// has an unexpanded parameter pack below it that may affect this cache.
  148. enum class Cache : unsigned char { Yes, No, Unknown, };
  149. /// Operator precedence for expression nodes. Used to determine required
  150. /// parens in expression emission.
  151. enum class Prec {
  152. Primary,
  153. Postfix,
  154. Unary,
  155. Cast,
  156. PtrMem,
  157. Multiplicative,
  158. Additive,
  159. Shift,
  160. Spaceship,
  161. Relational,
  162. Equality,
  163. And,
  164. Xor,
  165. Ior,
  166. AndIf,
  167. OrIf,
  168. Conditional,
  169. Assign,
  170. Comma,
  171. Default,
  172. };
  173. private:
  174. Kind K;
  175. Prec Precedence : 6;
  176. // FIXME: Make these protected.
  177. public:
  178. /// Tracks if this node has a component on its right side, in which case we
  179. /// need to call printRight.
  180. Cache RHSComponentCache : 2;
  181. /// Track if this node is a (possibly qualified) array type. This can affect
  182. /// how we format the output string.
  183. Cache ArrayCache : 2;
  184. /// Track if this node is a (possibly qualified) function type. This can
  185. /// affect how we format the output string.
  186. Cache FunctionCache : 2;
  187. public:
  188. Node(Kind K_, Prec Precedence_ = Prec::Primary,
  189. Cache RHSComponentCache_ = Cache::No, Cache ArrayCache_ = Cache::No,
  190. Cache FunctionCache_ = Cache::No)
  191. : K(K_), Precedence(Precedence_), RHSComponentCache(RHSComponentCache_),
  192. ArrayCache(ArrayCache_), FunctionCache(FunctionCache_) {}
  193. Node(Kind K_, Cache RHSComponentCache_, Cache ArrayCache_ = Cache::No,
  194. Cache FunctionCache_ = Cache::No)
  195. : Node(K_, Prec::Primary, RHSComponentCache_, ArrayCache_,
  196. FunctionCache_) {}
  197. /// Visit the most-derived object corresponding to this object.
  198. template<typename Fn> void visit(Fn F) const;
  199. // The following function is provided by all derived classes:
  200. //
  201. // Call F with arguments that, when passed to the constructor of this node,
  202. // would construct an equivalent node.
  203. //template<typename Fn> void match(Fn F) const;
  204. bool hasRHSComponent(OutputBuffer &OB) const {
  205. if (RHSComponentCache != Cache::Unknown)
  206. return RHSComponentCache == Cache::Yes;
  207. return hasRHSComponentSlow(OB);
  208. }
  209. bool hasArray(OutputBuffer &OB) const {
  210. if (ArrayCache != Cache::Unknown)
  211. return ArrayCache == Cache::Yes;
  212. return hasArraySlow(OB);
  213. }
  214. bool hasFunction(OutputBuffer &OB) const {
  215. if (FunctionCache != Cache::Unknown)
  216. return FunctionCache == Cache::Yes;
  217. return hasFunctionSlow(OB);
  218. }
  219. Kind getKind() const { return K; }
  220. Prec getPrecedence() const { return Precedence; }
  221. virtual bool hasRHSComponentSlow(OutputBuffer &) const { return false; }
  222. virtual bool hasArraySlow(OutputBuffer &) const { return false; }
  223. virtual bool hasFunctionSlow(OutputBuffer &) const { return false; }
  224. // Dig through "glue" nodes like ParameterPack and ForwardTemplateReference to
  225. // get at a node that actually represents some concrete syntax.
  226. virtual const Node *getSyntaxNode(OutputBuffer &) const { return this; }
  227. // Print this node as an expression operand, surrounding it in parentheses if
  228. // its precedence is [Strictly] weaker than P.
  229. void printAsOperand(OutputBuffer &OB, Prec P = Prec::Default,
  230. bool StrictlyWorse = false) const {
  231. bool Paren =
  232. unsigned(getPrecedence()) >= unsigned(P) + unsigned(StrictlyWorse);
  233. if (Paren)
  234. OB.printOpen();
  235. print(OB);
  236. if (Paren)
  237. OB.printClose();
  238. }
  239. void print(OutputBuffer &OB) const {
  240. printLeft(OB);
  241. if (RHSComponentCache != Cache::No)
  242. printRight(OB);
  243. }
  244. // Print the "left" side of this Node into OutputBuffer.
  245. virtual void printLeft(OutputBuffer &) const = 0;
  246. // Print the "right". This distinction is necessary to represent C++ types
  247. // that appear on the RHS of their subtype, such as arrays or functions.
  248. // Since most types don't have such a component, provide a default
  249. // implementation.
  250. virtual void printRight(OutputBuffer &) const {}
  251. virtual StringView getBaseName() const { return StringView(); }
  252. // Silence compiler warnings, this dtor will never be called.
  253. virtual ~Node() = default;
  254. #ifndef NDEBUG
  255. DEMANGLE_DUMP_METHOD void dump() const;
  256. #endif
  257. };
  258. class IASTProcessor {
  259. public:
  260. virtual void Process(const Node*) = 0;
  261. };
  262. void demangleAST(const char *MangledName, IASTProcessor *Processor);
  263. class NodeArray {
  264. Node **Elements;
  265. size_t NumElements;
  266. public:
  267. NodeArray() : Elements(nullptr), NumElements(0) {}
  268. NodeArray(Node **Elements_, size_t NumElements_)
  269. : Elements(Elements_), NumElements(NumElements_) {}
  270. bool empty() const { return NumElements == 0; }
  271. size_t size() const { return NumElements; }
  272. Node **begin() const { return Elements; }
  273. Node **end() const { return Elements + NumElements; }
  274. Node *operator[](size_t Idx) const { return Elements[Idx]; }
  275. void printWithComma(OutputBuffer &OB) const {
  276. bool FirstElement = true;
  277. for (size_t Idx = 0; Idx != NumElements; ++Idx) {
  278. size_t BeforeComma = OB.getCurrentPosition();
  279. if (!FirstElement)
  280. OB += ", ";
  281. size_t AfterComma = OB.getCurrentPosition();
  282. Elements[Idx]->printAsOperand(OB, Node::Prec::Comma);
  283. // Elements[Idx] is an empty parameter pack expansion, we should erase the
  284. // comma we just printed.
  285. if (AfterComma == OB.getCurrentPosition()) {
  286. OB.setCurrentPosition(BeforeComma);
  287. continue;
  288. }
  289. FirstElement = false;
  290. }
  291. }
  292. };
  293. struct NodeArrayNode : Node {
  294. NodeArray Array;
  295. NodeArrayNode(NodeArray Array_) : Node(KNodeArrayNode), Array(Array_) {}
  296. template<typename Fn> void match(Fn F) const { F(Array); }
  297. void printLeft(OutputBuffer &OB) const override { Array.printWithComma(OB); }
  298. };
  299. class DotSuffix final : public Node {
  300. const Node *Prefix;
  301. const StringView Suffix;
  302. public:
  303. DotSuffix(const Node *Prefix_, StringView Suffix_)
  304. : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
  305. template<typename Fn> void match(Fn F) const { F(Prefix, Suffix); }
  306. void printLeft(OutputBuffer &OB) const override {
  307. Prefix->print(OB);
  308. OB += " (";
  309. OB += Suffix;
  310. OB += ")";
  311. }
  312. };
  313. class VendorExtQualType final : public Node {
  314. const Node *Ty;
  315. StringView Ext;
  316. const Node *TA;
  317. public:
  318. VendorExtQualType(const Node *Ty_, StringView Ext_, const Node *TA_)
  319. : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_), TA(TA_) {}
  320. const Node *getTy() const { return Ty; }
  321. StringView getExt() const { return Ext; }
  322. const Node *getTA() const { return TA; }
  323. template <typename Fn> void match(Fn F) const { F(Ty, Ext, TA); }
  324. void printLeft(OutputBuffer &OB) const override {
  325. Ty->print(OB);
  326. OB += " ";
  327. OB += Ext;
  328. if (TA != nullptr)
  329. TA->print(OB);
  330. }
  331. };
  332. enum FunctionRefQual : unsigned char {
  333. FrefQualNone,
  334. FrefQualLValue,
  335. FrefQualRValue,
  336. };
  337. enum Qualifiers {
  338. QualNone = 0,
  339. QualConst = 0x1,
  340. QualVolatile = 0x2,
  341. QualRestrict = 0x4,
  342. };
  343. inline Qualifiers operator|=(Qualifiers &Q1, Qualifiers Q2) {
  344. return Q1 = static_cast<Qualifiers>(Q1 | Q2);
  345. }
  346. class QualType final : public Node {
  347. protected:
  348. const Qualifiers Quals;
  349. const Node *Child;
  350. void printQuals(OutputBuffer &OB) const {
  351. if (Quals & QualConst)
  352. OB += " const";
  353. if (Quals & QualVolatile)
  354. OB += " volatile";
  355. if (Quals & QualRestrict)
  356. OB += " restrict";
  357. }
  358. public:
  359. QualType(const Node *Child_, Qualifiers Quals_)
  360. : Node(KQualType, Child_->RHSComponentCache,
  361. Child_->ArrayCache, Child_->FunctionCache),
  362. Quals(Quals_), Child(Child_) {}
  363. Qualifiers getQuals() const { return Quals; }
  364. const Node *getChild() const { return Child; }
  365. template<typename Fn> void match(Fn F) const { F(Child, Quals); }
  366. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  367. return Child->hasRHSComponent(OB);
  368. }
  369. bool hasArraySlow(OutputBuffer &OB) const override {
  370. return Child->hasArray(OB);
  371. }
  372. bool hasFunctionSlow(OutputBuffer &OB) const override {
  373. return Child->hasFunction(OB);
  374. }
  375. void printLeft(OutputBuffer &OB) const override {
  376. Child->printLeft(OB);
  377. printQuals(OB);
  378. }
  379. void printRight(OutputBuffer &OB) const override { Child->printRight(OB); }
  380. };
  381. class ConversionOperatorType final : public Node {
  382. const Node *Ty;
  383. public:
  384. ConversionOperatorType(const Node *Ty_)
  385. : Node(KConversionOperatorType), Ty(Ty_) {}
  386. template<typename Fn> void match(Fn F) const { F(Ty); }
  387. void printLeft(OutputBuffer &OB) const override {
  388. OB += "operator ";
  389. Ty->print(OB);
  390. }
  391. };
  392. class PostfixQualifiedType final : public Node {
  393. const Node *Ty;
  394. const StringView Postfix;
  395. public:
  396. PostfixQualifiedType(const Node *Ty_, StringView Postfix_)
  397. : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {}
  398. template<typename Fn> void match(Fn F) const { F(Ty, Postfix); }
  399. void printLeft(OutputBuffer &OB) const override {
  400. Ty->printLeft(OB);
  401. OB += Postfix;
  402. }
  403. };
  404. class NameType final : public Node {
  405. const StringView Name;
  406. public:
  407. NameType(StringView Name_) : Node(KNameType), Name(Name_) {}
  408. template<typename Fn> void match(Fn F) const { F(Name); }
  409. StringView getName() const { return Name; }
  410. StringView getBaseName() const override { return Name; }
  411. void printLeft(OutputBuffer &OB) const override { OB += Name; }
  412. };
  413. class BitIntType final : public Node {
  414. const Node *Size;
  415. bool Signed;
  416. public:
  417. BitIntType(const Node *Size_, bool Signed_)
  418. : Node(KBitIntType), Size(Size_), Signed(Signed_) {}
  419. template <typename Fn> void match(Fn F) const { F(Size, Signed); }
  420. void printLeft(OutputBuffer &OB) const override {
  421. if (!Signed)
  422. OB += "unsigned ";
  423. OB += "_BitInt";
  424. OB.printOpen();
  425. Size->printAsOperand(OB);
  426. OB.printClose();
  427. }
  428. };
  429. class ElaboratedTypeSpefType : public Node {
  430. StringView Kind;
  431. Node *Child;
  432. public:
  433. ElaboratedTypeSpefType(StringView Kind_, Node *Child_)
  434. : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {}
  435. template<typename Fn> void match(Fn F) const { F(Kind, Child); }
  436. void printLeft(OutputBuffer &OB) const override {
  437. OB += Kind;
  438. OB += ' ';
  439. Child->print(OB);
  440. }
  441. };
  442. struct AbiTagAttr : Node {
  443. Node *Base;
  444. StringView Tag;
  445. AbiTagAttr(Node* Base_, StringView Tag_)
  446. : Node(KAbiTagAttr, Base_->RHSComponentCache,
  447. Base_->ArrayCache, Base_->FunctionCache),
  448. Base(Base_), Tag(Tag_) {}
  449. template<typename Fn> void match(Fn F) const { F(Base, Tag); }
  450. void printLeft(OutputBuffer &OB) const override {
  451. Base->printLeft(OB);
  452. OB += "[abi:";
  453. OB += Tag;
  454. OB += "]";
  455. }
  456. };
  457. class EnableIfAttr : public Node {
  458. NodeArray Conditions;
  459. public:
  460. EnableIfAttr(NodeArray Conditions_)
  461. : Node(KEnableIfAttr), Conditions(Conditions_) {}
  462. template<typename Fn> void match(Fn F) const { F(Conditions); }
  463. void printLeft(OutputBuffer &OB) const override {
  464. OB += " [enable_if:";
  465. Conditions.printWithComma(OB);
  466. OB += ']';
  467. }
  468. };
  469. class ObjCProtoName : public Node {
  470. const Node *Ty;
  471. StringView Protocol;
  472. friend class PointerType;
  473. public:
  474. ObjCProtoName(const Node *Ty_, StringView Protocol_)
  475. : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
  476. template<typename Fn> void match(Fn F) const { F(Ty, Protocol); }
  477. bool isObjCObject() const {
  478. return Ty->getKind() == KNameType &&
  479. static_cast<const NameType *>(Ty)->getName() == "objc_object";
  480. }
  481. void printLeft(OutputBuffer &OB) const override {
  482. Ty->print(OB);
  483. OB += "<";
  484. OB += Protocol;
  485. OB += ">";
  486. }
  487. };
  488. class PointerType final : public Node {
  489. const Node *Pointee;
  490. public:
  491. PointerType(const Node *Pointee_)
  492. : Node(KPointerType, Pointee_->RHSComponentCache),
  493. Pointee(Pointee_) {}
  494. const Node *getPointee() const { return Pointee; }
  495. template<typename Fn> void match(Fn F) const { F(Pointee); }
  496. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  497. return Pointee->hasRHSComponent(OB);
  498. }
  499. void printLeft(OutputBuffer &OB) const override {
  500. // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
  501. if (Pointee->getKind() != KObjCProtoName ||
  502. !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
  503. Pointee->printLeft(OB);
  504. if (Pointee->hasArray(OB))
  505. OB += " ";
  506. if (Pointee->hasArray(OB) || Pointee->hasFunction(OB))
  507. OB += "(";
  508. OB += "*";
  509. } else {
  510. const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
  511. OB += "id<";
  512. OB += objcProto->Protocol;
  513. OB += ">";
  514. }
  515. }
  516. void printRight(OutputBuffer &OB) const override {
  517. if (Pointee->getKind() != KObjCProtoName ||
  518. !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
  519. if (Pointee->hasArray(OB) || Pointee->hasFunction(OB))
  520. OB += ")";
  521. Pointee->printRight(OB);
  522. }
  523. }
  524. };
  525. enum class ReferenceKind {
  526. LValue,
  527. RValue,
  528. };
  529. // Represents either a LValue or an RValue reference type.
  530. class ReferenceType : public Node {
  531. const Node *Pointee;
  532. ReferenceKind RK;
  533. mutable bool Printing = false;
  534. // Dig through any refs to refs, collapsing the ReferenceTypes as we go. The
  535. // rule here is rvalue ref to rvalue ref collapses to a rvalue ref, and any
  536. // other combination collapses to a lvalue ref.
  537. //
  538. // A combination of a TemplateForwardReference and a back-ref Substitution
  539. // from an ill-formed string may have created a cycle; use cycle detection to
  540. // avoid looping forever.
  541. std::pair<ReferenceKind, const Node *> collapse(OutputBuffer &OB) const {
  542. auto SoFar = std::make_pair(RK, Pointee);
  543. // Track the chain of nodes for the Floyd's 'tortoise and hare'
  544. // cycle-detection algorithm, since getSyntaxNode(S) is impure
  545. PODSmallVector<const Node *, 8> Prev;
  546. for (;;) {
  547. const Node *SN = SoFar.second->getSyntaxNode(OB);
  548. if (SN->getKind() != KReferenceType)
  549. break;
  550. auto *RT = static_cast<const ReferenceType *>(SN);
  551. SoFar.second = RT->Pointee;
  552. SoFar.first = std::min(SoFar.first, RT->RK);
  553. // The middle of Prev is the 'slow' pointer moving at half speed
  554. Prev.push_back(SoFar.second);
  555. if (Prev.size() > 1 && SoFar.second == Prev[(Prev.size() - 1) / 2]) {
  556. // Cycle detected
  557. SoFar.second = nullptr;
  558. break;
  559. }
  560. }
  561. return SoFar;
  562. }
  563. public:
  564. ReferenceType(const Node *Pointee_, ReferenceKind RK_)
  565. : Node(KReferenceType, Pointee_->RHSComponentCache),
  566. Pointee(Pointee_), RK(RK_) {}
  567. template<typename Fn> void match(Fn F) const { F(Pointee, RK); }
  568. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  569. return Pointee->hasRHSComponent(OB);
  570. }
  571. void printLeft(OutputBuffer &OB) const override {
  572. if (Printing)
  573. return;
  574. ScopedOverride<bool> SavePrinting(Printing, true);
  575. std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
  576. if (!Collapsed.second)
  577. return;
  578. Collapsed.second->printLeft(OB);
  579. if (Collapsed.second->hasArray(OB))
  580. OB += " ";
  581. if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
  582. OB += "(";
  583. OB += (Collapsed.first == ReferenceKind::LValue ? "&" : "&&");
  584. }
  585. void printRight(OutputBuffer &OB) const override {
  586. if (Printing)
  587. return;
  588. ScopedOverride<bool> SavePrinting(Printing, true);
  589. std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
  590. if (!Collapsed.second)
  591. return;
  592. if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
  593. OB += ")";
  594. Collapsed.second->printRight(OB);
  595. }
  596. };
  597. class PointerToMemberType final : public Node {
  598. const Node *ClassType;
  599. const Node *MemberType;
  600. public:
  601. PointerToMemberType(const Node *ClassType_, const Node *MemberType_)
  602. : Node(KPointerToMemberType, MemberType_->RHSComponentCache),
  603. ClassType(ClassType_), MemberType(MemberType_) {}
  604. template<typename Fn> void match(Fn F) const { F(ClassType, MemberType); }
  605. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  606. return MemberType->hasRHSComponent(OB);
  607. }
  608. void printLeft(OutputBuffer &OB) const override {
  609. MemberType->printLeft(OB);
  610. if (MemberType->hasArray(OB) || MemberType->hasFunction(OB))
  611. OB += "(";
  612. else
  613. OB += " ";
  614. ClassType->print(OB);
  615. OB += "::*";
  616. }
  617. void printRight(OutputBuffer &OB) const override {
  618. if (MemberType->hasArray(OB) || MemberType->hasFunction(OB))
  619. OB += ")";
  620. MemberType->printRight(OB);
  621. }
  622. };
  623. class ArrayType final : public Node {
  624. const Node *Base;
  625. Node *Dimension;
  626. public:
  627. ArrayType(const Node *Base_, Node *Dimension_)
  628. : Node(KArrayType,
  629. /*RHSComponentCache=*/Cache::Yes,
  630. /*ArrayCache=*/Cache::Yes),
  631. Base(Base_), Dimension(Dimension_) {}
  632. template<typename Fn> void match(Fn F) const { F(Base, Dimension); }
  633. bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
  634. bool hasArraySlow(OutputBuffer &) const override { return true; }
  635. void printLeft(OutputBuffer &OB) const override { Base->printLeft(OB); }
  636. void printRight(OutputBuffer &OB) const override {
  637. if (OB.back() != ']')
  638. OB += " ";
  639. OB += "[";
  640. if (Dimension)
  641. Dimension->print(OB);
  642. OB += "]";
  643. Base->printRight(OB);
  644. }
  645. };
  646. class FunctionType final : public Node {
  647. const Node *Ret;
  648. NodeArray Params;
  649. Qualifiers CVQuals;
  650. FunctionRefQual RefQual;
  651. const Node *ExceptionSpec;
  652. public:
  653. FunctionType(const Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
  654. FunctionRefQual RefQual_, const Node *ExceptionSpec_)
  655. : Node(KFunctionType,
  656. /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
  657. /*FunctionCache=*/Cache::Yes),
  658. Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
  659. ExceptionSpec(ExceptionSpec_) {}
  660. template<typename Fn> void match(Fn F) const {
  661. F(Ret, Params, CVQuals, RefQual, ExceptionSpec);
  662. }
  663. bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
  664. bool hasFunctionSlow(OutputBuffer &) const override { return true; }
  665. // Handle C++'s ... quirky decl grammar by using the left & right
  666. // distinction. Consider:
  667. // int (*f(float))(char) {}
  668. // f is a function that takes a float and returns a pointer to a function
  669. // that takes a char and returns an int. If we're trying to print f, start
  670. // by printing out the return types's left, then print our parameters, then
  671. // finally print right of the return type.
  672. void printLeft(OutputBuffer &OB) const override {
  673. Ret->printLeft(OB);
  674. OB += " ";
  675. }
  676. void printRight(OutputBuffer &OB) const override {
  677. OB.printOpen();
  678. Params.printWithComma(OB);
  679. OB.printClose();
  680. Ret->printRight(OB);
  681. if (CVQuals & QualConst)
  682. OB += " const";
  683. if (CVQuals & QualVolatile)
  684. OB += " volatile";
  685. if (CVQuals & QualRestrict)
  686. OB += " restrict";
  687. if (RefQual == FrefQualLValue)
  688. OB += " &";
  689. else if (RefQual == FrefQualRValue)
  690. OB += " &&";
  691. if (ExceptionSpec != nullptr) {
  692. OB += ' ';
  693. ExceptionSpec->print(OB);
  694. }
  695. }
  696. };
  697. class NoexceptSpec : public Node {
  698. const Node *E;
  699. public:
  700. NoexceptSpec(const Node *E_) : Node(KNoexceptSpec), E(E_) {}
  701. template<typename Fn> void match(Fn F) const { F(E); }
  702. void printLeft(OutputBuffer &OB) const override {
  703. OB += "noexcept";
  704. OB.printOpen();
  705. E->printAsOperand(OB);
  706. OB.printClose();
  707. }
  708. };
  709. class DynamicExceptionSpec : public Node {
  710. NodeArray Types;
  711. public:
  712. DynamicExceptionSpec(NodeArray Types_)
  713. : Node(KDynamicExceptionSpec), Types(Types_) {}
  714. template<typename Fn> void match(Fn F) const { F(Types); }
  715. void printLeft(OutputBuffer &OB) const override {
  716. OB += "throw";
  717. OB.printOpen();
  718. Types.printWithComma(OB);
  719. OB.printClose();
  720. }
  721. };
  722. class FunctionEncoding final : public Node {
  723. const Node *Ret;
  724. const Node *Name;
  725. NodeArray Params;
  726. const Node *Attrs;
  727. Qualifiers CVQuals;
  728. FunctionRefQual RefQual;
  729. public:
  730. FunctionEncoding(const Node *Ret_, const Node *Name_, NodeArray Params_,
  731. const Node *Attrs_, Qualifiers CVQuals_,
  732. FunctionRefQual RefQual_)
  733. : Node(KFunctionEncoding,
  734. /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
  735. /*FunctionCache=*/Cache::Yes),
  736. Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_),
  737. CVQuals(CVQuals_), RefQual(RefQual_) {}
  738. template<typename Fn> void match(Fn F) const {
  739. F(Ret, Name, Params, Attrs, CVQuals, RefQual);
  740. }
  741. Qualifiers getCVQuals() const { return CVQuals; }
  742. FunctionRefQual getRefQual() const { return RefQual; }
  743. NodeArray getParams() const { return Params; }
  744. const Node *getReturnType() const { return Ret; }
  745. bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
  746. bool hasFunctionSlow(OutputBuffer &) const override { return true; }
  747. const Node *getName() const { return Name; }
  748. void printLeft(OutputBuffer &OB) const override {
  749. if (Ret) {
  750. Ret->printLeft(OB);
  751. if (!Ret->hasRHSComponent(OB))
  752. OB += " ";
  753. }
  754. Name->print(OB);
  755. }
  756. void printRight(OutputBuffer &OB) const override {
  757. OB.printOpen();
  758. Params.printWithComma(OB);
  759. OB.printClose();
  760. if (Ret)
  761. Ret->printRight(OB);
  762. if (CVQuals & QualConst)
  763. OB += " const";
  764. if (CVQuals & QualVolatile)
  765. OB += " volatile";
  766. if (CVQuals & QualRestrict)
  767. OB += " restrict";
  768. if (RefQual == FrefQualLValue)
  769. OB += " &";
  770. else if (RefQual == FrefQualRValue)
  771. OB += " &&";
  772. if (Attrs != nullptr)
  773. Attrs->print(OB);
  774. }
  775. };
  776. class LiteralOperator : public Node {
  777. const Node *OpName;
  778. public:
  779. LiteralOperator(const Node *OpName_)
  780. : Node(KLiteralOperator), OpName(OpName_) {}
  781. template<typename Fn> void match(Fn F) const { F(OpName); }
  782. void printLeft(OutputBuffer &OB) const override {
  783. OB += "operator\"\" ";
  784. OpName->print(OB);
  785. }
  786. };
  787. class SpecialName final : public Node {
  788. const StringView Special;
  789. const Node *Child;
  790. public:
  791. SpecialName(StringView Special_, const Node *Child_)
  792. : Node(KSpecialName), Special(Special_), Child(Child_) {}
  793. template<typename Fn> void match(Fn F) const { F(Special, Child); }
  794. void printLeft(OutputBuffer &OB) const override {
  795. OB += Special;
  796. Child->print(OB);
  797. }
  798. };
  799. class CtorVtableSpecialName final : public Node {
  800. const Node *FirstType;
  801. const Node *SecondType;
  802. public:
  803. CtorVtableSpecialName(const Node *FirstType_, const Node *SecondType_)
  804. : Node(KCtorVtableSpecialName),
  805. FirstType(FirstType_), SecondType(SecondType_) {}
  806. template<typename Fn> void match(Fn F) const { F(FirstType, SecondType); }
  807. void printLeft(OutputBuffer &OB) const override {
  808. OB += "construction vtable for ";
  809. FirstType->print(OB);
  810. OB += "-in-";
  811. SecondType->print(OB);
  812. }
  813. };
  814. struct NestedName : Node {
  815. Node *Qual;
  816. Node *Name;
  817. NestedName(Node *Qual_, Node *Name_)
  818. : Node(KNestedName), Qual(Qual_), Name(Name_) {}
  819. template<typename Fn> void match(Fn F) const { F(Qual, Name); }
  820. StringView getBaseName() const override { return Name->getBaseName(); }
  821. void printLeft(OutputBuffer &OB) const override {
  822. Qual->print(OB);
  823. OB += "::";
  824. Name->print(OB);
  825. }
  826. };
  827. struct ModuleName : Node {
  828. ModuleName *Parent;
  829. Node *Name;
  830. bool IsPartition;
  831. ModuleName(ModuleName *Parent_, Node *Name_, bool IsPartition_ = false)
  832. : Node(KModuleName), Parent(Parent_), Name(Name_),
  833. IsPartition(IsPartition_) {}
  834. template <typename Fn> void match(Fn F) const {
  835. F(Parent, Name, IsPartition);
  836. }
  837. void printLeft(OutputBuffer &OB) const override {
  838. if (Parent)
  839. Parent->print(OB);
  840. if (Parent || IsPartition)
  841. OB += IsPartition ? ':' : '.';
  842. Name->print(OB);
  843. }
  844. };
  845. struct ModuleEntity : Node {
  846. ModuleName *Module;
  847. Node *Name;
  848. ModuleEntity(ModuleName *Module_, Node *Name_)
  849. : Node(KModuleEntity), Module(Module_), Name(Name_) {}
  850. template <typename Fn> void match(Fn F) const { F(Module, Name); }
  851. StringView getBaseName() const override { return Name->getBaseName(); }
  852. void printLeft(OutputBuffer &OB) const override {
  853. Name->print(OB);
  854. OB += '@';
  855. Module->print(OB);
  856. }
  857. };
  858. struct LocalName : Node {
  859. Node *Encoding;
  860. Node *Entity;
  861. LocalName(Node *Encoding_, Node *Entity_)
  862. : Node(KLocalName), Encoding(Encoding_), Entity(Entity_) {}
  863. template<typename Fn> void match(Fn F) const { F(Encoding, Entity); }
  864. void printLeft(OutputBuffer &OB) const override {
  865. Encoding->print(OB);
  866. OB += "::";
  867. Entity->print(OB);
  868. }
  869. };
  870. class QualifiedName final : public Node {
  871. // qualifier::name
  872. const Node *Qualifier;
  873. const Node *Name;
  874. public:
  875. QualifiedName(const Node *Qualifier_, const Node *Name_)
  876. : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {}
  877. template<typename Fn> void match(Fn F) const { F(Qualifier, Name); }
  878. StringView getBaseName() const override { return Name->getBaseName(); }
  879. void printLeft(OutputBuffer &OB) const override {
  880. Qualifier->print(OB);
  881. OB += "::";
  882. Name->print(OB);
  883. }
  884. };
  885. class VectorType final : public Node {
  886. const Node *BaseType;
  887. const Node *Dimension;
  888. public:
  889. VectorType(const Node *BaseType_, const Node *Dimension_)
  890. : Node(KVectorType), BaseType(BaseType_), Dimension(Dimension_) {}
  891. const Node *getBaseType() const { return BaseType; }
  892. const Node *getDimension() const { return Dimension; }
  893. template<typename Fn> void match(Fn F) const { F(BaseType, Dimension); }
  894. void printLeft(OutputBuffer &OB) const override {
  895. BaseType->print(OB);
  896. OB += " vector[";
  897. if (Dimension)
  898. Dimension->print(OB);
  899. OB += "]";
  900. }
  901. };
  902. class PixelVectorType final : public Node {
  903. const Node *Dimension;
  904. public:
  905. PixelVectorType(const Node *Dimension_)
  906. : Node(KPixelVectorType), Dimension(Dimension_) {}
  907. template<typename Fn> void match(Fn F) const { F(Dimension); }
  908. void printLeft(OutputBuffer &OB) const override {
  909. // FIXME: This should demangle as "vector pixel".
  910. OB += "pixel vector[";
  911. Dimension->print(OB);
  912. OB += "]";
  913. }
  914. };
  915. class BinaryFPType final : public Node {
  916. const Node *Dimension;
  917. public:
  918. BinaryFPType(const Node *Dimension_)
  919. : Node(KBinaryFPType), Dimension(Dimension_) {}
  920. template<typename Fn> void match(Fn F) const { F(Dimension); }
  921. void printLeft(OutputBuffer &OB) const override {
  922. OB += "_Float";
  923. Dimension->print(OB);
  924. }
  925. };
  926. enum class TemplateParamKind { Type, NonType, Template };
  927. /// An invented name for a template parameter for which we don't have a
  928. /// corresponding template argument.
  929. ///
  930. /// This node is created when parsing the <lambda-sig> for a lambda with
  931. /// explicit template arguments, which might be referenced in the parameter
  932. /// types appearing later in the <lambda-sig>.
  933. class SyntheticTemplateParamName final : public Node {
  934. TemplateParamKind Kind;
  935. unsigned Index;
  936. public:
  937. SyntheticTemplateParamName(TemplateParamKind Kind_, unsigned Index_)
  938. : Node(KSyntheticTemplateParamName), Kind(Kind_), Index(Index_) {}
  939. template<typename Fn> void match(Fn F) const { F(Kind, Index); }
  940. void printLeft(OutputBuffer &OB) const override {
  941. switch (Kind) {
  942. case TemplateParamKind::Type:
  943. OB += "$T";
  944. break;
  945. case TemplateParamKind::NonType:
  946. OB += "$N";
  947. break;
  948. case TemplateParamKind::Template:
  949. OB += "$TT";
  950. break;
  951. }
  952. if (Index > 0)
  953. OB << Index - 1;
  954. }
  955. };
  956. /// A template type parameter declaration, 'typename T'.
  957. class TypeTemplateParamDecl final : public Node {
  958. Node *Name;
  959. public:
  960. TypeTemplateParamDecl(Node *Name_)
  961. : Node(KTypeTemplateParamDecl, Cache::Yes), Name(Name_) {}
  962. template<typename Fn> void match(Fn F) const { F(Name); }
  963. void printLeft(OutputBuffer &OB) const override { OB += "typename "; }
  964. void printRight(OutputBuffer &OB) const override { Name->print(OB); }
  965. };
  966. /// A non-type template parameter declaration, 'int N'.
  967. class NonTypeTemplateParamDecl final : public Node {
  968. Node *Name;
  969. Node *Type;
  970. public:
  971. NonTypeTemplateParamDecl(Node *Name_, Node *Type_)
  972. : Node(KNonTypeTemplateParamDecl, Cache::Yes), Name(Name_), Type(Type_) {}
  973. template<typename Fn> void match(Fn F) const { F(Name, Type); }
  974. void printLeft(OutputBuffer &OB) const override {
  975. Type->printLeft(OB);
  976. if (!Type->hasRHSComponent(OB))
  977. OB += " ";
  978. }
  979. void printRight(OutputBuffer &OB) const override {
  980. Name->print(OB);
  981. Type->printRight(OB);
  982. }
  983. };
  984. /// A template template parameter declaration,
  985. /// 'template<typename T> typename N'.
  986. class TemplateTemplateParamDecl final : public Node {
  987. Node *Name;
  988. NodeArray Params;
  989. public:
  990. TemplateTemplateParamDecl(Node *Name_, NodeArray Params_)
  991. : Node(KTemplateTemplateParamDecl, Cache::Yes), Name(Name_),
  992. Params(Params_) {}
  993. template<typename Fn> void match(Fn F) const { F(Name, Params); }
  994. void printLeft(OutputBuffer &OB) const override {
  995. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  996. OB += "template<";
  997. Params.printWithComma(OB);
  998. OB += "> typename ";
  999. }
  1000. void printRight(OutputBuffer &OB) const override { Name->print(OB); }
  1001. };
  1002. /// A template parameter pack declaration, 'typename ...T'.
  1003. class TemplateParamPackDecl final : public Node {
  1004. Node *Param;
  1005. public:
  1006. TemplateParamPackDecl(Node *Param_)
  1007. : Node(KTemplateParamPackDecl, Cache::Yes), Param(Param_) {}
  1008. template<typename Fn> void match(Fn F) const { F(Param); }
  1009. void printLeft(OutputBuffer &OB) const override {
  1010. Param->printLeft(OB);
  1011. OB += "...";
  1012. }
  1013. void printRight(OutputBuffer &OB) const override { Param->printRight(OB); }
  1014. };
  1015. /// An unexpanded parameter pack (either in the expression or type context). If
  1016. /// this AST is correct, this node will have a ParameterPackExpansion node above
  1017. /// it.
  1018. ///
  1019. /// This node is created when some <template-args> are found that apply to an
  1020. /// <encoding>, and is stored in the TemplateParams table. In order for this to
  1021. /// appear in the final AST, it has to referenced via a <template-param> (ie,
  1022. /// T_).
  1023. class ParameterPack final : public Node {
  1024. NodeArray Data;
  1025. // Setup OutputBuffer for a pack expansion, unless we're already expanding
  1026. // one.
  1027. void initializePackExpansion(OutputBuffer &OB) const {
  1028. if (OB.CurrentPackMax == std::numeric_limits<unsigned>::max()) {
  1029. OB.CurrentPackMax = static_cast<unsigned>(Data.size());
  1030. OB.CurrentPackIndex = 0;
  1031. }
  1032. }
  1033. public:
  1034. ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) {
  1035. ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
  1036. if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
  1037. return P->ArrayCache == Cache::No;
  1038. }))
  1039. ArrayCache = Cache::No;
  1040. if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
  1041. return P->FunctionCache == Cache::No;
  1042. }))
  1043. FunctionCache = Cache::No;
  1044. if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
  1045. return P->RHSComponentCache == Cache::No;
  1046. }))
  1047. RHSComponentCache = Cache::No;
  1048. }
  1049. template<typename Fn> void match(Fn F) const { F(Data); }
  1050. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  1051. initializePackExpansion(OB);
  1052. size_t Idx = OB.CurrentPackIndex;
  1053. return Idx < Data.size() && Data[Idx]->hasRHSComponent(OB);
  1054. }
  1055. bool hasArraySlow(OutputBuffer &OB) const override {
  1056. initializePackExpansion(OB);
  1057. size_t Idx = OB.CurrentPackIndex;
  1058. return Idx < Data.size() && Data[Idx]->hasArray(OB);
  1059. }
  1060. bool hasFunctionSlow(OutputBuffer &OB) const override {
  1061. initializePackExpansion(OB);
  1062. size_t Idx = OB.CurrentPackIndex;
  1063. return Idx < Data.size() && Data[Idx]->hasFunction(OB);
  1064. }
  1065. const Node *getSyntaxNode(OutputBuffer &OB) const override {
  1066. initializePackExpansion(OB);
  1067. size_t Idx = OB.CurrentPackIndex;
  1068. return Idx < Data.size() ? Data[Idx]->getSyntaxNode(OB) : this;
  1069. }
  1070. void printLeft(OutputBuffer &OB) const override {
  1071. initializePackExpansion(OB);
  1072. size_t Idx = OB.CurrentPackIndex;
  1073. if (Idx < Data.size())
  1074. Data[Idx]->printLeft(OB);
  1075. }
  1076. void printRight(OutputBuffer &OB) const override {
  1077. initializePackExpansion(OB);
  1078. size_t Idx = OB.CurrentPackIndex;
  1079. if (Idx < Data.size())
  1080. Data[Idx]->printRight(OB);
  1081. }
  1082. };
  1083. /// A variadic template argument. This node represents an occurrence of
  1084. /// J<something>E in some <template-args>. It isn't itself unexpanded, unless
  1085. /// one of it's Elements is. The parser inserts a ParameterPack into the
  1086. /// TemplateParams table if the <template-args> this pack belongs to apply to an
  1087. /// <encoding>.
  1088. class TemplateArgumentPack final : public Node {
  1089. NodeArray Elements;
  1090. public:
  1091. TemplateArgumentPack(NodeArray Elements_)
  1092. : Node(KTemplateArgumentPack), Elements(Elements_) {}
  1093. template<typename Fn> void match(Fn F) const { F(Elements); }
  1094. NodeArray getElements() const { return Elements; }
  1095. void printLeft(OutputBuffer &OB) const override {
  1096. Elements.printWithComma(OB);
  1097. }
  1098. };
  1099. /// A pack expansion. Below this node, there are some unexpanded ParameterPacks
  1100. /// which each have Child->ParameterPackSize elements.
  1101. class ParameterPackExpansion final : public Node {
  1102. const Node *Child;
  1103. public:
  1104. ParameterPackExpansion(const Node *Child_)
  1105. : Node(KParameterPackExpansion), Child(Child_) {}
  1106. template<typename Fn> void match(Fn F) const { F(Child); }
  1107. const Node *getChild() const { return Child; }
  1108. void printLeft(OutputBuffer &OB) const override {
  1109. constexpr unsigned Max = std::numeric_limits<unsigned>::max();
  1110. ScopedOverride<unsigned> SavePackIdx(OB.CurrentPackIndex, Max);
  1111. ScopedOverride<unsigned> SavePackMax(OB.CurrentPackMax, Max);
  1112. size_t StreamPos = OB.getCurrentPosition();
  1113. // Print the first element in the pack. If Child contains a ParameterPack,
  1114. // it will set up S.CurrentPackMax and print the first element.
  1115. Child->print(OB);
  1116. // No ParameterPack was found in Child. This can occur if we've found a pack
  1117. // expansion on a <function-param>.
  1118. if (OB.CurrentPackMax == Max) {
  1119. OB += "...";
  1120. return;
  1121. }
  1122. // We found a ParameterPack, but it has no elements. Erase whatever we may
  1123. // of printed.
  1124. if (OB.CurrentPackMax == 0) {
  1125. OB.setCurrentPosition(StreamPos);
  1126. return;
  1127. }
  1128. // Else, iterate through the rest of the elements in the pack.
  1129. for (unsigned I = 1, E = OB.CurrentPackMax; I < E; ++I) {
  1130. OB += ", ";
  1131. OB.CurrentPackIndex = I;
  1132. Child->print(OB);
  1133. }
  1134. }
  1135. };
  1136. class TemplateArgs final : public Node {
  1137. NodeArray Params;
  1138. public:
  1139. TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {}
  1140. template<typename Fn> void match(Fn F) const { F(Params); }
  1141. NodeArray getParams() { return Params; }
  1142. void printLeft(OutputBuffer &OB) const override {
  1143. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  1144. OB += "<";
  1145. Params.printWithComma(OB);
  1146. OB += ">";
  1147. }
  1148. };
  1149. /// A forward-reference to a template argument that was not known at the point
  1150. /// where the template parameter name was parsed in a mangling.
  1151. ///
  1152. /// This is created when demangling the name of a specialization of a
  1153. /// conversion function template:
  1154. ///
  1155. /// \code
  1156. /// struct A {
  1157. /// template<typename T> operator T*();
  1158. /// };
  1159. /// \endcode
  1160. ///
  1161. /// When demangling a specialization of the conversion function template, we
  1162. /// encounter the name of the template (including the \c T) before we reach
  1163. /// the template argument list, so we cannot substitute the parameter name
  1164. /// for the corresponding argument while parsing. Instead, we create a
  1165. /// \c ForwardTemplateReference node that is resolved after we parse the
  1166. /// template arguments.
  1167. struct ForwardTemplateReference : Node {
  1168. size_t Index;
  1169. Node *Ref = nullptr;
  1170. // If we're currently printing this node. It is possible (though invalid) for
  1171. // a forward template reference to refer to itself via a substitution. This
  1172. // creates a cyclic AST, which will stack overflow printing. To fix this, bail
  1173. // out if more than one print* function is active.
  1174. mutable bool Printing = false;
  1175. ForwardTemplateReference(size_t Index_)
  1176. : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown,
  1177. Cache::Unknown),
  1178. Index(Index_) {}
  1179. // We don't provide a matcher for these, because the value of the node is
  1180. // not determined by its construction parameters, and it generally needs
  1181. // special handling.
  1182. template<typename Fn> void match(Fn F) const = delete;
  1183. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  1184. if (Printing)
  1185. return false;
  1186. ScopedOverride<bool> SavePrinting(Printing, true);
  1187. return Ref->hasRHSComponent(OB);
  1188. }
  1189. bool hasArraySlow(OutputBuffer &OB) const override {
  1190. if (Printing)
  1191. return false;
  1192. ScopedOverride<bool> SavePrinting(Printing, true);
  1193. return Ref->hasArray(OB);
  1194. }
  1195. bool hasFunctionSlow(OutputBuffer &OB) const override {
  1196. if (Printing)
  1197. return false;
  1198. ScopedOverride<bool> SavePrinting(Printing, true);
  1199. return Ref->hasFunction(OB);
  1200. }
  1201. const Node *getSyntaxNode(OutputBuffer &OB) const override {
  1202. if (Printing)
  1203. return this;
  1204. ScopedOverride<bool> SavePrinting(Printing, true);
  1205. return Ref->getSyntaxNode(OB);
  1206. }
  1207. void printLeft(OutputBuffer &OB) const override {
  1208. if (Printing)
  1209. return;
  1210. ScopedOverride<bool> SavePrinting(Printing, true);
  1211. Ref->printLeft(OB);
  1212. }
  1213. void printRight(OutputBuffer &OB) const override {
  1214. if (Printing)
  1215. return;
  1216. ScopedOverride<bool> SavePrinting(Printing, true);
  1217. Ref->printRight(OB);
  1218. }
  1219. };
  1220. struct NameWithTemplateArgs : Node {
  1221. // name<template_args>
  1222. Node *Name;
  1223. Node *TemplateArgs;
  1224. NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
  1225. : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {}
  1226. template<typename Fn> void match(Fn F) const { F(Name, TemplateArgs); }
  1227. StringView getBaseName() const override { return Name->getBaseName(); }
  1228. void printLeft(OutputBuffer &OB) const override {
  1229. Name->print(OB);
  1230. TemplateArgs->print(OB);
  1231. }
  1232. };
  1233. class GlobalQualifiedName final : public Node {
  1234. Node *Child;
  1235. public:
  1236. GlobalQualifiedName(Node* Child_)
  1237. : Node(KGlobalQualifiedName), Child(Child_) {}
  1238. template<typename Fn> void match(Fn F) const { F(Child); }
  1239. StringView getBaseName() const override { return Child->getBaseName(); }
  1240. void printLeft(OutputBuffer &OB) const override {
  1241. OB += "::";
  1242. Child->print(OB);
  1243. }
  1244. };
  1245. enum class SpecialSubKind {
  1246. allocator,
  1247. basic_string,
  1248. string,
  1249. istream,
  1250. ostream,
  1251. iostream,
  1252. };
  1253. class SpecialSubstitution;
  1254. class ExpandedSpecialSubstitution : public Node {
  1255. protected:
  1256. SpecialSubKind SSK;
  1257. ExpandedSpecialSubstitution(SpecialSubKind SSK_, Kind K_)
  1258. : Node(K_), SSK(SSK_) {}
  1259. public:
  1260. ExpandedSpecialSubstitution(SpecialSubKind SSK_)
  1261. : ExpandedSpecialSubstitution(SSK_, KExpandedSpecialSubstitution) {}
  1262. inline ExpandedSpecialSubstitution(SpecialSubstitution const *);
  1263. template<typename Fn> void match(Fn F) const { F(SSK); }
  1264. protected:
  1265. bool isInstantiation() const {
  1266. return unsigned(SSK) >= unsigned(SpecialSubKind::string);
  1267. }
  1268. StringView getBaseName() const override {
  1269. switch (SSK) {
  1270. case SpecialSubKind::allocator:
  1271. return StringView("allocator");
  1272. case SpecialSubKind::basic_string:
  1273. return StringView("basic_string");
  1274. case SpecialSubKind::string:
  1275. return StringView("basic_string");
  1276. case SpecialSubKind::istream:
  1277. return StringView("basic_istream");
  1278. case SpecialSubKind::ostream:
  1279. return StringView("basic_ostream");
  1280. case SpecialSubKind::iostream:
  1281. return StringView("basic_iostream");
  1282. }
  1283. DEMANGLE_UNREACHABLE;
  1284. }
  1285. private:
  1286. void printLeft(OutputBuffer &OB) const override {
  1287. OB << "std::" << getBaseName();
  1288. if (isInstantiation()) {
  1289. OB << "<char, std::char_traits<char>";
  1290. if (SSK == SpecialSubKind::string)
  1291. OB << ", std::allocator<char>";
  1292. OB << ">";
  1293. }
  1294. }
  1295. };
  1296. class SpecialSubstitution final : public ExpandedSpecialSubstitution {
  1297. public:
  1298. SpecialSubstitution(SpecialSubKind SSK_)
  1299. : ExpandedSpecialSubstitution(SSK_, KSpecialSubstitution) {}
  1300. template<typename Fn> void match(Fn F) const { F(SSK); }
  1301. StringView getBaseName() const override {
  1302. auto SV = ExpandedSpecialSubstitution::getBaseName ();
  1303. if (isInstantiation()) {
  1304. // The instantiations are typedefs that drop the "basic_" prefix.
  1305. assert(SV.startsWith("basic_"));
  1306. SV = SV.dropFront(sizeof("basic_") - 1);
  1307. }
  1308. return SV;
  1309. }
  1310. void printLeft(OutputBuffer &OB) const override {
  1311. OB << "std::" << getBaseName();
  1312. }
  1313. };
  1314. inline ExpandedSpecialSubstitution::ExpandedSpecialSubstitution(
  1315. SpecialSubstitution const *SS)
  1316. : ExpandedSpecialSubstitution(SS->SSK) {}
  1317. class CtorDtorName final : public Node {
  1318. const Node *Basename;
  1319. const bool IsDtor;
  1320. const int Variant;
  1321. public:
  1322. CtorDtorName(const Node *Basename_, bool IsDtor_, int Variant_)
  1323. : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_),
  1324. Variant(Variant_) {}
  1325. template<typename Fn> void match(Fn F) const { F(Basename, IsDtor, Variant); }
  1326. void printLeft(OutputBuffer &OB) const override {
  1327. if (IsDtor)
  1328. OB += "~";
  1329. OB += Basename->getBaseName();
  1330. }
  1331. };
  1332. class DtorName : public Node {
  1333. const Node *Base;
  1334. public:
  1335. DtorName(const Node *Base_) : Node(KDtorName), Base(Base_) {}
  1336. template<typename Fn> void match(Fn F) const { F(Base); }
  1337. void printLeft(OutputBuffer &OB) const override {
  1338. OB += "~";
  1339. Base->printLeft(OB);
  1340. }
  1341. };
  1342. class UnnamedTypeName : public Node {
  1343. const StringView Count;
  1344. public:
  1345. UnnamedTypeName(StringView Count_) : Node(KUnnamedTypeName), Count(Count_) {}
  1346. template<typename Fn> void match(Fn F) const { F(Count); }
  1347. void printLeft(OutputBuffer &OB) const override {
  1348. OB += "'unnamed";
  1349. OB += Count;
  1350. OB += "\'";
  1351. }
  1352. };
  1353. class ClosureTypeName : public Node {
  1354. NodeArray TemplateParams;
  1355. NodeArray Params;
  1356. StringView Count;
  1357. public:
  1358. ClosureTypeName(NodeArray TemplateParams_, NodeArray Params_,
  1359. StringView Count_)
  1360. : Node(KClosureTypeName), TemplateParams(TemplateParams_),
  1361. Params(Params_), Count(Count_) {}
  1362. template<typename Fn> void match(Fn F) const {
  1363. F(TemplateParams, Params, Count);
  1364. }
  1365. void printDeclarator(OutputBuffer &OB) const {
  1366. if (!TemplateParams.empty()) {
  1367. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  1368. OB += "<";
  1369. TemplateParams.printWithComma(OB);
  1370. OB += ">";
  1371. }
  1372. OB.printOpen();
  1373. Params.printWithComma(OB);
  1374. OB.printClose();
  1375. }
  1376. void printLeft(OutputBuffer &OB) const override {
  1377. OB += "\'lambda";
  1378. OB += Count;
  1379. OB += "\'";
  1380. printDeclarator(OB);
  1381. }
  1382. };
  1383. class StructuredBindingName : public Node {
  1384. NodeArray Bindings;
  1385. public:
  1386. StructuredBindingName(NodeArray Bindings_)
  1387. : Node(KStructuredBindingName), Bindings(Bindings_) {}
  1388. template<typename Fn> void match(Fn F) const { F(Bindings); }
  1389. void printLeft(OutputBuffer &OB) const override {
  1390. OB.printOpen('[');
  1391. Bindings.printWithComma(OB);
  1392. OB.printClose(']');
  1393. }
  1394. };
  1395. // -- Expression Nodes --
  1396. class BinaryExpr : public Node {
  1397. const Node *LHS;
  1398. const StringView InfixOperator;
  1399. const Node *RHS;
  1400. public:
  1401. BinaryExpr(const Node *LHS_, StringView InfixOperator_, const Node *RHS_,
  1402. Prec Prec_)
  1403. : Node(KBinaryExpr, Prec_), LHS(LHS_), InfixOperator(InfixOperator_),
  1404. RHS(RHS_) {}
  1405. template <typename Fn> void match(Fn F) const {
  1406. F(LHS, InfixOperator, RHS, getPrecedence());
  1407. }
  1408. void printLeft(OutputBuffer &OB) const override {
  1409. bool ParenAll = OB.isGtInsideTemplateArgs() &&
  1410. (InfixOperator == ">" || InfixOperator == ">>");
  1411. if (ParenAll)
  1412. OB.printOpen();
  1413. // Assignment is right associative, with special LHS precedence.
  1414. bool IsAssign = getPrecedence() == Prec::Assign;
  1415. LHS->printAsOperand(OB, IsAssign ? Prec::OrIf : getPrecedence(), !IsAssign);
  1416. // No space before comma operator
  1417. if (!(InfixOperator == ","))
  1418. OB += " ";
  1419. OB += InfixOperator;
  1420. OB += " ";
  1421. RHS->printAsOperand(OB, getPrecedence(), IsAssign);
  1422. if (ParenAll)
  1423. OB.printClose();
  1424. }
  1425. };
  1426. class ArraySubscriptExpr : public Node {
  1427. const Node *Op1;
  1428. const Node *Op2;
  1429. public:
  1430. ArraySubscriptExpr(const Node *Op1_, const Node *Op2_, Prec Prec_)
  1431. : Node(KArraySubscriptExpr, Prec_), Op1(Op1_), Op2(Op2_) {}
  1432. template <typename Fn> void match(Fn F) const {
  1433. F(Op1, Op2, getPrecedence());
  1434. }
  1435. void printLeft(OutputBuffer &OB) const override {
  1436. Op1->printAsOperand(OB, getPrecedence());
  1437. OB.printOpen('[');
  1438. Op2->printAsOperand(OB);
  1439. OB.printClose(']');
  1440. }
  1441. };
  1442. class PostfixExpr : public Node {
  1443. const Node *Child;
  1444. const StringView Operator;
  1445. public:
  1446. PostfixExpr(const Node *Child_, StringView Operator_, Prec Prec_)
  1447. : Node(KPostfixExpr, Prec_), Child(Child_), Operator(Operator_) {}
  1448. template <typename Fn> void match(Fn F) const {
  1449. F(Child, Operator, getPrecedence());
  1450. }
  1451. void printLeft(OutputBuffer &OB) const override {
  1452. Child->printAsOperand(OB, getPrecedence(), true);
  1453. OB += Operator;
  1454. }
  1455. };
  1456. class ConditionalExpr : public Node {
  1457. const Node *Cond;
  1458. const Node *Then;
  1459. const Node *Else;
  1460. public:
  1461. ConditionalExpr(const Node *Cond_, const Node *Then_, const Node *Else_,
  1462. Prec Prec_)
  1463. : Node(KConditionalExpr, Prec_), Cond(Cond_), Then(Then_), Else(Else_) {}
  1464. template <typename Fn> void match(Fn F) const {
  1465. F(Cond, Then, Else, getPrecedence());
  1466. }
  1467. void printLeft(OutputBuffer &OB) const override {
  1468. Cond->printAsOperand(OB, getPrecedence());
  1469. OB += " ? ";
  1470. Then->printAsOperand(OB);
  1471. OB += " : ";
  1472. Else->printAsOperand(OB, Prec::Assign, true);
  1473. }
  1474. };
  1475. class MemberExpr : public Node {
  1476. const Node *LHS;
  1477. const StringView Kind;
  1478. const Node *RHS;
  1479. public:
  1480. MemberExpr(const Node *LHS_, StringView Kind_, const Node *RHS_, Prec Prec_)
  1481. : Node(KMemberExpr, Prec_), LHS(LHS_), Kind(Kind_), RHS(RHS_) {}
  1482. template <typename Fn> void match(Fn F) const {
  1483. F(LHS, Kind, RHS, getPrecedence());
  1484. }
  1485. void printLeft(OutputBuffer &OB) const override {
  1486. LHS->printAsOperand(OB, getPrecedence(), true);
  1487. OB += Kind;
  1488. RHS->printAsOperand(OB, getPrecedence(), false);
  1489. }
  1490. };
  1491. class SubobjectExpr : public Node {
  1492. const Node *Type;
  1493. const Node *SubExpr;
  1494. StringView Offset;
  1495. NodeArray UnionSelectors;
  1496. bool OnePastTheEnd;
  1497. public:
  1498. SubobjectExpr(const Node *Type_, const Node *SubExpr_, StringView Offset_,
  1499. NodeArray UnionSelectors_, bool OnePastTheEnd_)
  1500. : Node(KSubobjectExpr), Type(Type_), SubExpr(SubExpr_), Offset(Offset_),
  1501. UnionSelectors(UnionSelectors_), OnePastTheEnd(OnePastTheEnd_) {}
  1502. template<typename Fn> void match(Fn F) const {
  1503. F(Type, SubExpr, Offset, UnionSelectors, OnePastTheEnd);
  1504. }
  1505. void printLeft(OutputBuffer &OB) const override {
  1506. SubExpr->print(OB);
  1507. OB += ".<";
  1508. Type->print(OB);
  1509. OB += " at offset ";
  1510. if (Offset.empty()) {
  1511. OB += "0";
  1512. } else if (Offset[0] == 'n') {
  1513. OB += "-";
  1514. OB += Offset.dropFront();
  1515. } else {
  1516. OB += Offset;
  1517. }
  1518. OB += ">";
  1519. }
  1520. };
  1521. class EnclosingExpr : public Node {
  1522. const StringView Prefix;
  1523. const Node *Infix;
  1524. const StringView Postfix;
  1525. public:
  1526. EnclosingExpr(StringView Prefix_, const Node *Infix_,
  1527. Prec Prec_ = Prec::Primary)
  1528. : Node(KEnclosingExpr, Prec_), Prefix(Prefix_), Infix(Infix_) {}
  1529. template <typename Fn> void match(Fn F) const {
  1530. F(Prefix, Infix, getPrecedence());
  1531. }
  1532. void printLeft(OutputBuffer &OB) const override {
  1533. OB += Prefix;
  1534. OB.printOpen();
  1535. Infix->print(OB);
  1536. OB.printClose();
  1537. OB += Postfix;
  1538. }
  1539. };
  1540. class CastExpr : public Node {
  1541. // cast_kind<to>(from)
  1542. const StringView CastKind;
  1543. const Node *To;
  1544. const Node *From;
  1545. public:
  1546. CastExpr(StringView CastKind_, const Node *To_, const Node *From_, Prec Prec_)
  1547. : Node(KCastExpr, Prec_), CastKind(CastKind_), To(To_), From(From_) {}
  1548. template <typename Fn> void match(Fn F) const {
  1549. F(CastKind, To, From, getPrecedence());
  1550. }
  1551. void printLeft(OutputBuffer &OB) const override {
  1552. OB += CastKind;
  1553. {
  1554. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  1555. OB += "<";
  1556. To->printLeft(OB);
  1557. OB += ">";
  1558. }
  1559. OB.printOpen();
  1560. From->printAsOperand(OB);
  1561. OB.printClose();
  1562. }
  1563. };
  1564. class SizeofParamPackExpr : public Node {
  1565. const Node *Pack;
  1566. public:
  1567. SizeofParamPackExpr(const Node *Pack_)
  1568. : Node(KSizeofParamPackExpr), Pack(Pack_) {}
  1569. template<typename Fn> void match(Fn F) const { F(Pack); }
  1570. void printLeft(OutputBuffer &OB) const override {
  1571. OB += "sizeof...";
  1572. OB.printOpen();
  1573. ParameterPackExpansion PPE(Pack);
  1574. PPE.printLeft(OB);
  1575. OB.printClose();
  1576. }
  1577. };
  1578. class CallExpr : public Node {
  1579. const Node *Callee;
  1580. NodeArray Args;
  1581. public:
  1582. CallExpr(const Node *Callee_, NodeArray Args_, Prec Prec_)
  1583. : Node(KCallExpr, Prec_), Callee(Callee_), Args(Args_) {}
  1584. template <typename Fn> void match(Fn F) const {
  1585. F(Callee, Args, getPrecedence());
  1586. }
  1587. void printLeft(OutputBuffer &OB) const override {
  1588. Callee->print(OB);
  1589. OB.printOpen();
  1590. Args.printWithComma(OB);
  1591. OB.printClose();
  1592. }
  1593. };
  1594. class NewExpr : public Node {
  1595. // new (expr_list) type(init_list)
  1596. NodeArray ExprList;
  1597. Node *Type;
  1598. NodeArray InitList;
  1599. bool IsGlobal; // ::operator new ?
  1600. bool IsArray; // new[] ?
  1601. public:
  1602. NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
  1603. bool IsArray_, Prec Prec_)
  1604. : Node(KNewExpr, Prec_), ExprList(ExprList_), Type(Type_),
  1605. InitList(InitList_), IsGlobal(IsGlobal_), IsArray(IsArray_) {}
  1606. template<typename Fn> void match(Fn F) const {
  1607. F(ExprList, Type, InitList, IsGlobal, IsArray, getPrecedence());
  1608. }
  1609. void printLeft(OutputBuffer &OB) const override {
  1610. if (IsGlobal)
  1611. OB += "::";
  1612. OB += "new";
  1613. if (IsArray)
  1614. OB += "[]";
  1615. if (!ExprList.empty()) {
  1616. OB.printOpen();
  1617. ExprList.printWithComma(OB);
  1618. OB.printClose();
  1619. }
  1620. OB += " ";
  1621. Type->print(OB);
  1622. if (!InitList.empty()) {
  1623. OB.printOpen();
  1624. InitList.printWithComma(OB);
  1625. OB.printClose();
  1626. }
  1627. }
  1628. };
  1629. class DeleteExpr : public Node {
  1630. Node *Op;
  1631. bool IsGlobal;
  1632. bool IsArray;
  1633. public:
  1634. DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_, Prec Prec_)
  1635. : Node(KDeleteExpr, Prec_), Op(Op_), IsGlobal(IsGlobal_),
  1636. IsArray(IsArray_) {}
  1637. template <typename Fn> void match(Fn F) const {
  1638. F(Op, IsGlobal, IsArray, getPrecedence());
  1639. }
  1640. void printLeft(OutputBuffer &OB) const override {
  1641. if (IsGlobal)
  1642. OB += "::";
  1643. OB += "delete";
  1644. if (IsArray)
  1645. OB += "[]";
  1646. OB += ' ';
  1647. Op->print(OB);
  1648. }
  1649. };
  1650. class PrefixExpr : public Node {
  1651. StringView Prefix;
  1652. Node *Child;
  1653. public:
  1654. PrefixExpr(StringView Prefix_, Node *Child_, Prec Prec_)
  1655. : Node(KPrefixExpr, Prec_), Prefix(Prefix_), Child(Child_) {}
  1656. template <typename Fn> void match(Fn F) const {
  1657. F(Prefix, Child, getPrecedence());
  1658. }
  1659. void printLeft(OutputBuffer &OB) const override {
  1660. OB += Prefix;
  1661. Child->printAsOperand(OB, getPrecedence());
  1662. }
  1663. };
  1664. class FunctionParam : public Node {
  1665. StringView Number;
  1666. public:
  1667. FunctionParam(StringView Number_) : Node(KFunctionParam), Number(Number_) {}
  1668. template<typename Fn> void match(Fn F) const { F(Number); }
  1669. void printLeft(OutputBuffer &OB) const override {
  1670. OB += "fp";
  1671. OB += Number;
  1672. }
  1673. };
  1674. class ConversionExpr : public Node {
  1675. const Node *Type;
  1676. NodeArray Expressions;
  1677. public:
  1678. ConversionExpr(const Node *Type_, NodeArray Expressions_, Prec Prec_)
  1679. : Node(KConversionExpr, Prec_), Type(Type_), Expressions(Expressions_) {}
  1680. template <typename Fn> void match(Fn F) const {
  1681. F(Type, Expressions, getPrecedence());
  1682. }
  1683. void printLeft(OutputBuffer &OB) const override {
  1684. OB.printOpen();
  1685. Type->print(OB);
  1686. OB.printClose();
  1687. OB.printOpen();
  1688. Expressions.printWithComma(OB);
  1689. OB.printClose();
  1690. }
  1691. };
  1692. class PointerToMemberConversionExpr : public Node {
  1693. const Node *Type;
  1694. const Node *SubExpr;
  1695. StringView Offset;
  1696. public:
  1697. PointerToMemberConversionExpr(const Node *Type_, const Node *SubExpr_,
  1698. StringView Offset_, Prec Prec_)
  1699. : Node(KPointerToMemberConversionExpr, Prec_), Type(Type_),
  1700. SubExpr(SubExpr_), Offset(Offset_) {}
  1701. template <typename Fn> void match(Fn F) const {
  1702. F(Type, SubExpr, Offset, getPrecedence());
  1703. }
  1704. void printLeft(OutputBuffer &OB) const override {
  1705. OB.printOpen();
  1706. Type->print(OB);
  1707. OB.printClose();
  1708. OB.printOpen();
  1709. SubExpr->print(OB);
  1710. OB.printClose();
  1711. }
  1712. };
  1713. class InitListExpr : public Node {
  1714. const Node *Ty;
  1715. NodeArray Inits;
  1716. public:
  1717. InitListExpr(const Node *Ty_, NodeArray Inits_)
  1718. : Node(KInitListExpr), Ty(Ty_), Inits(Inits_) {}
  1719. template<typename Fn> void match(Fn F) const { F(Ty, Inits); }
  1720. void printLeft(OutputBuffer &OB) const override {
  1721. if (Ty)
  1722. Ty->print(OB);
  1723. OB += '{';
  1724. Inits.printWithComma(OB);
  1725. OB += '}';
  1726. }
  1727. };
  1728. class BracedExpr : public Node {
  1729. const Node *Elem;
  1730. const Node *Init;
  1731. bool IsArray;
  1732. public:
  1733. BracedExpr(const Node *Elem_, const Node *Init_, bool IsArray_)
  1734. : Node(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
  1735. template<typename Fn> void match(Fn F) const { F(Elem, Init, IsArray); }
  1736. void printLeft(OutputBuffer &OB) const override {
  1737. if (IsArray) {
  1738. OB += '[';
  1739. Elem->print(OB);
  1740. OB += ']';
  1741. } else {
  1742. OB += '.';
  1743. Elem->print(OB);
  1744. }
  1745. if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
  1746. OB += " = ";
  1747. Init->print(OB);
  1748. }
  1749. };
  1750. class BracedRangeExpr : public Node {
  1751. const Node *First;
  1752. const Node *Last;
  1753. const Node *Init;
  1754. public:
  1755. BracedRangeExpr(const Node *First_, const Node *Last_, const Node *Init_)
  1756. : Node(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
  1757. template<typename Fn> void match(Fn F) const { F(First, Last, Init); }
  1758. void printLeft(OutputBuffer &OB) const override {
  1759. OB += '[';
  1760. First->print(OB);
  1761. OB += " ... ";
  1762. Last->print(OB);
  1763. OB += ']';
  1764. if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
  1765. OB += " = ";
  1766. Init->print(OB);
  1767. }
  1768. };
  1769. class FoldExpr : public Node {
  1770. const Node *Pack, *Init;
  1771. StringView OperatorName;
  1772. bool IsLeftFold;
  1773. public:
  1774. FoldExpr(bool IsLeftFold_, StringView OperatorName_, const Node *Pack_,
  1775. const Node *Init_)
  1776. : Node(KFoldExpr), Pack(Pack_), Init(Init_), OperatorName(OperatorName_),
  1777. IsLeftFold(IsLeftFold_) {}
  1778. template<typename Fn> void match(Fn F) const {
  1779. F(IsLeftFold, OperatorName, Pack, Init);
  1780. }
  1781. void printLeft(OutputBuffer &OB) const override {
  1782. auto PrintPack = [&] {
  1783. OB.printOpen();
  1784. ParameterPackExpansion(Pack).print(OB);
  1785. OB.printClose();
  1786. };
  1787. OB.printOpen();
  1788. // Either '[init op ]... op pack' or 'pack op ...[ op init]'
  1789. // Refactored to '[(init|pack) op ]...[ op (pack|init)]'
  1790. // Fold expr operands are cast-expressions
  1791. if (!IsLeftFold || Init != nullptr) {
  1792. // '(init|pack) op '
  1793. if (IsLeftFold)
  1794. Init->printAsOperand(OB, Prec::Cast, true);
  1795. else
  1796. PrintPack();
  1797. OB << " " << OperatorName << " ";
  1798. }
  1799. OB << "...";
  1800. if (IsLeftFold || Init != nullptr) {
  1801. // ' op (init|pack)'
  1802. OB << " " << OperatorName << " ";
  1803. if (IsLeftFold)
  1804. PrintPack();
  1805. else
  1806. Init->printAsOperand(OB, Prec::Cast, true);
  1807. }
  1808. OB.printClose();
  1809. }
  1810. };
  1811. class ThrowExpr : public Node {
  1812. const Node *Op;
  1813. public:
  1814. ThrowExpr(const Node *Op_) : Node(KThrowExpr), Op(Op_) {}
  1815. template<typename Fn> void match(Fn F) const { F(Op); }
  1816. void printLeft(OutputBuffer &OB) const override {
  1817. OB += "throw ";
  1818. Op->print(OB);
  1819. }
  1820. };
  1821. class BoolExpr : public Node {
  1822. bool Value;
  1823. public:
  1824. BoolExpr(bool Value_) : Node(KBoolExpr), Value(Value_) {}
  1825. template<typename Fn> void match(Fn F) const { F(Value); }
  1826. void printLeft(OutputBuffer &OB) const override {
  1827. OB += Value ? StringView("true") : StringView("false");
  1828. }
  1829. };
  1830. class StringLiteral : public Node {
  1831. const Node *Type;
  1832. public:
  1833. StringLiteral(const Node *Type_) : Node(KStringLiteral), Type(Type_) {}
  1834. template<typename Fn> void match(Fn F) const { F(Type); }
  1835. void printLeft(OutputBuffer &OB) const override {
  1836. OB += "\"<";
  1837. Type->print(OB);
  1838. OB += ">\"";
  1839. }
  1840. };
  1841. class LambdaExpr : public Node {
  1842. const Node *Type;
  1843. public:
  1844. LambdaExpr(const Node *Type_) : Node(KLambdaExpr), Type(Type_) {}
  1845. template<typename Fn> void match(Fn F) const { F(Type); }
  1846. void printLeft(OutputBuffer &OB) const override {
  1847. OB += "[]";
  1848. if (Type->getKind() == KClosureTypeName)
  1849. static_cast<const ClosureTypeName *>(Type)->printDeclarator(OB);
  1850. OB += "{...}";
  1851. }
  1852. };
  1853. class EnumLiteral : public Node {
  1854. // ty(integer)
  1855. const Node *Ty;
  1856. StringView Integer;
  1857. public:
  1858. EnumLiteral(const Node *Ty_, StringView Integer_)
  1859. : Node(KEnumLiteral), Ty(Ty_), Integer(Integer_) {}
  1860. template<typename Fn> void match(Fn F) const { F(Ty, Integer); }
  1861. void printLeft(OutputBuffer &OB) const override {
  1862. OB.printOpen();
  1863. Ty->print(OB);
  1864. OB.printClose();
  1865. if (Integer[0] == 'n')
  1866. OB << "-" << Integer.dropFront(1);
  1867. else
  1868. OB << Integer;
  1869. }
  1870. };
  1871. class IntegerLiteral : public Node {
  1872. StringView Type;
  1873. StringView Value;
  1874. public:
  1875. IntegerLiteral(StringView Type_, StringView Value_)
  1876. : Node(KIntegerLiteral), Type(Type_), Value(Value_) {}
  1877. template<typename Fn> void match(Fn F) const { F(Type, Value); }
  1878. void printLeft(OutputBuffer &OB) const override {
  1879. if (Type.size() > 3) {
  1880. OB.printOpen();
  1881. OB += Type;
  1882. OB.printClose();
  1883. }
  1884. if (Value[0] == 'n') {
  1885. OB += '-';
  1886. OB += Value.dropFront(1);
  1887. } else
  1888. OB += Value;
  1889. if (Type.size() <= 3)
  1890. OB += Type;
  1891. }
  1892. };
  1893. template <class Float> struct FloatData;
  1894. namespace float_literal_impl {
  1895. constexpr Node::Kind getFloatLiteralKind(float *) {
  1896. return Node::KFloatLiteral;
  1897. }
  1898. constexpr Node::Kind getFloatLiteralKind(double *) {
  1899. return Node::KDoubleLiteral;
  1900. }
  1901. constexpr Node::Kind getFloatLiteralKind(long double *) {
  1902. return Node::KLongDoubleLiteral;
  1903. }
  1904. }
  1905. template <class Float> class FloatLiteralImpl : public Node {
  1906. const StringView Contents;
  1907. static constexpr Kind KindForClass =
  1908. float_literal_impl::getFloatLiteralKind((Float *)nullptr);
  1909. public:
  1910. FloatLiteralImpl(StringView Contents_)
  1911. : Node(KindForClass), Contents(Contents_) {}
  1912. template<typename Fn> void match(Fn F) const { F(Contents); }
  1913. void printLeft(OutputBuffer &OB) const override {
  1914. const char *first = Contents.begin();
  1915. const char *last = Contents.end() + 1;
  1916. const size_t N = FloatData<Float>::mangled_size;
  1917. if (static_cast<std::size_t>(last - first) > N) {
  1918. last = first + N;
  1919. union {
  1920. Float value;
  1921. char buf[sizeof(Float)];
  1922. };
  1923. const char *t = first;
  1924. char *e = buf;
  1925. for (; t != last; ++t, ++e) {
  1926. unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
  1927. : static_cast<unsigned>(*t - 'a' + 10);
  1928. ++t;
  1929. unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
  1930. : static_cast<unsigned>(*t - 'a' + 10);
  1931. *e = static_cast<char>((d1 << 4) + d0);
  1932. }
  1933. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1934. std::reverse(buf, e);
  1935. #endif
  1936. char num[FloatData<Float>::max_demangled_size] = {0};
  1937. int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
  1938. OB += StringView(num, num + n);
  1939. }
  1940. }
  1941. };
  1942. using FloatLiteral = FloatLiteralImpl<float>;
  1943. using DoubleLiteral = FloatLiteralImpl<double>;
  1944. using LongDoubleLiteral = FloatLiteralImpl<long double>;
  1945. /// Visit the node. Calls \c F(P), where \c P is the node cast to the
  1946. /// appropriate derived class.
  1947. template<typename Fn>
  1948. void Node::visit(Fn F) const {
  1949. switch (K) {
  1950. #define NODE(X) \
  1951. case K##X: \
  1952. return F(static_cast<const X *>(this));
  1953. #include "ItaniumNodes.def"
  1954. }
  1955. assert(0 && "unknown mangling node kind");
  1956. }
  1957. /// Determine the kind of a node from its type.
  1958. template<typename NodeT> struct NodeKind;
  1959. #define NODE(X) \
  1960. template <> struct NodeKind<X> { \
  1961. static constexpr Node::Kind Kind = Node::K##X; \
  1962. static constexpr const char *name() { return #X; } \
  1963. };
  1964. #include "ItaniumNodes.def"
  1965. template <typename Derived, typename Alloc> struct AbstractManglingParser {
  1966. const char *First;
  1967. const char *Last;
  1968. // Name stack, this is used by the parser to hold temporary names that were
  1969. // parsed. The parser collapses multiple names into new nodes to construct
  1970. // the AST. Once the parser is finished, names.size() == 1.
  1971. PODSmallVector<Node *, 32> Names;
  1972. // Substitution table. Itanium supports name substitutions as a means of
  1973. // compression. The string "S42_" refers to the 44nd entry (base-36) in this
  1974. // table.
  1975. PODSmallVector<Node *, 32> Subs;
  1976. using TemplateParamList = PODSmallVector<Node *, 8>;
  1977. class ScopedTemplateParamList {
  1978. AbstractManglingParser *Parser;
  1979. size_t OldNumTemplateParamLists;
  1980. TemplateParamList Params;
  1981. public:
  1982. ScopedTemplateParamList(AbstractManglingParser *TheParser)
  1983. : Parser(TheParser),
  1984. OldNumTemplateParamLists(TheParser->TemplateParams.size()) {
  1985. Parser->TemplateParams.push_back(&Params);
  1986. }
  1987. ~ScopedTemplateParamList() {
  1988. assert(Parser->TemplateParams.size() >= OldNumTemplateParamLists);
  1989. Parser->TemplateParams.dropBack(OldNumTemplateParamLists);
  1990. }
  1991. };
  1992. // Template parameter table. Like the above, but referenced like "T42_".
  1993. // This has a smaller size compared to Subs and Names because it can be
  1994. // stored on the stack.
  1995. TemplateParamList OuterTemplateParams;
  1996. // Lists of template parameters indexed by template parameter depth,
  1997. // referenced like "TL2_4_". If nonempty, element 0 is always
  1998. // OuterTemplateParams; inner elements are always template parameter lists of
  1999. // lambda expressions. For a generic lambda with no explicit template
  2000. // parameter list, the corresponding parameter list pointer will be null.
  2001. PODSmallVector<TemplateParamList *, 4> TemplateParams;
  2002. // Set of unresolved forward <template-param> references. These can occur in a
  2003. // conversion operator's type, and are resolved in the enclosing <encoding>.
  2004. PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
  2005. bool TryToParseTemplateArgs = true;
  2006. bool PermitForwardTemplateReferences = false;
  2007. size_t ParsingLambdaParamsAtLevel = (size_t)-1;
  2008. unsigned NumSyntheticTemplateParameters[3] = {};
  2009. Alloc ASTAllocator;
  2010. AbstractManglingParser(const char *First_, const char *Last_)
  2011. : First(First_), Last(Last_) {}
  2012. Derived &getDerived() { return static_cast<Derived &>(*this); }
  2013. void reset(const char *First_, const char *Last_) {
  2014. First = First_;
  2015. Last = Last_;
  2016. Names.clear();
  2017. Subs.clear();
  2018. TemplateParams.clear();
  2019. ParsingLambdaParamsAtLevel = (size_t)-1;
  2020. TryToParseTemplateArgs = true;
  2021. PermitForwardTemplateReferences = false;
  2022. for (int I = 0; I != 3; ++I)
  2023. NumSyntheticTemplateParameters[I] = 0;
  2024. ASTAllocator.reset();
  2025. }
  2026. template <class T, class... Args> Node *make(Args &&... args) {
  2027. return ASTAllocator.template makeNode<T>(std::forward<Args>(args)...);
  2028. }
  2029. template <class It> NodeArray makeNodeArray(It begin, It end) {
  2030. size_t sz = static_cast<size_t>(end - begin);
  2031. void *mem = ASTAllocator.allocateNodeArray(sz);
  2032. Node **data = new (mem) Node *[sz];
  2033. std::copy(begin, end, data);
  2034. return NodeArray(data, sz);
  2035. }
  2036. NodeArray popTrailingNodeArray(size_t FromPosition) {
  2037. assert(FromPosition <= Names.size());
  2038. NodeArray res =
  2039. makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
  2040. Names.dropBack(FromPosition);
  2041. return res;
  2042. }
  2043. bool consumeIf(StringView S) {
  2044. if (StringView(First, Last).startsWith(S)) {
  2045. First += S.size();
  2046. return true;
  2047. }
  2048. return false;
  2049. }
  2050. bool consumeIf(char C) {
  2051. if (First != Last && *First == C) {
  2052. ++First;
  2053. return true;
  2054. }
  2055. return false;
  2056. }
  2057. char consume() { return First != Last ? *First++ : '\0'; }
  2058. char look(unsigned Lookahead = 0) const {
  2059. if (static_cast<size_t>(Last - First) <= Lookahead)
  2060. return '\0';
  2061. return First[Lookahead];
  2062. }
  2063. size_t numLeft() const { return static_cast<size_t>(Last - First); }
  2064. StringView parseNumber(bool AllowNegative = false);
  2065. Qualifiers parseCVQualifiers();
  2066. bool parsePositiveInteger(size_t *Out);
  2067. StringView parseBareSourceName();
  2068. bool parseSeqId(size_t *Out);
  2069. Node *parseSubstitution();
  2070. Node *parseTemplateParam();
  2071. Node *parseTemplateParamDecl();
  2072. Node *parseTemplateArgs(bool TagTemplates = false);
  2073. Node *parseTemplateArg();
  2074. /// Parse the <expr> production.
  2075. Node *parseExpr();
  2076. Node *parsePrefixExpr(StringView Kind, Node::Prec Prec);
  2077. Node *parseBinaryExpr(StringView Kind, Node::Prec Prec);
  2078. Node *parseIntegerLiteral(StringView Lit);
  2079. Node *parseExprPrimary();
  2080. template <class Float> Node *parseFloatingLiteral();
  2081. Node *parseFunctionParam();
  2082. Node *parseConversionExpr();
  2083. Node *parseBracedExpr();
  2084. Node *parseFoldExpr();
  2085. Node *parsePointerToMemberConversionExpr(Node::Prec Prec);
  2086. Node *parseSubobjectExpr();
  2087. /// Parse the <type> production.
  2088. Node *parseType();
  2089. Node *parseFunctionType();
  2090. Node *parseVectorType();
  2091. Node *parseDecltype();
  2092. Node *parseArrayType();
  2093. Node *parsePointerToMemberType();
  2094. Node *parseClassEnumType();
  2095. Node *parseQualifiedType();
  2096. Node *parseEncoding();
  2097. bool parseCallOffset();
  2098. Node *parseSpecialName();
  2099. /// Holds some extra information about a <name> that is being parsed. This
  2100. /// information is only pertinent if the <name> refers to an <encoding>.
  2101. struct NameState {
  2102. bool CtorDtorConversion = false;
  2103. bool EndsWithTemplateArgs = false;
  2104. Qualifiers CVQualifiers = QualNone;
  2105. FunctionRefQual ReferenceQualifier = FrefQualNone;
  2106. size_t ForwardTemplateRefsBegin;
  2107. NameState(AbstractManglingParser *Enclosing)
  2108. : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
  2109. };
  2110. bool resolveForwardTemplateRefs(NameState &State) {
  2111. size_t I = State.ForwardTemplateRefsBegin;
  2112. size_t E = ForwardTemplateRefs.size();
  2113. for (; I < E; ++I) {
  2114. size_t Idx = ForwardTemplateRefs[I]->Index;
  2115. if (TemplateParams.empty() || !TemplateParams[0] ||
  2116. Idx >= TemplateParams[0]->size())
  2117. return true;
  2118. ForwardTemplateRefs[I]->Ref = (*TemplateParams[0])[Idx];
  2119. }
  2120. ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
  2121. return false;
  2122. }
  2123. /// Parse the <name> production>
  2124. Node *parseName(NameState *State = nullptr);
  2125. Node *parseLocalName(NameState *State);
  2126. Node *parseOperatorName(NameState *State);
  2127. bool parseModuleNameOpt(ModuleName *&Module);
  2128. Node *parseUnqualifiedName(NameState *State, Node *Scope, ModuleName *Module);
  2129. Node *parseUnnamedTypeName(NameState *State);
  2130. Node *parseSourceName(NameState *State);
  2131. Node *parseUnscopedName(NameState *State, bool *isSubstName);
  2132. Node *parseNestedName(NameState *State);
  2133. Node *parseCtorDtorName(Node *&SoFar, NameState *State);
  2134. Node *parseAbiTags(Node *N);
  2135. struct OperatorInfo {
  2136. enum OIKind : unsigned char {
  2137. Prefix, // Prefix unary: @ expr
  2138. Postfix, // Postfix unary: expr @
  2139. Binary, // Binary: lhs @ rhs
  2140. Array, // Array index: lhs [ rhs ]
  2141. Member, // Member access: lhs @ rhs
  2142. New, // New
  2143. Del, // Delete
  2144. Call, // Function call: expr (expr*)
  2145. CCast, // C cast: (type)expr
  2146. Conditional, // Conditional: expr ? expr : expr
  2147. NameOnly, // Overload only, not allowed in expression.
  2148. // Below do not have operator names
  2149. NamedCast, // Named cast, @<type>(expr)
  2150. OfIdOp, // alignof, sizeof, typeid
  2151. Unnameable = NamedCast,
  2152. };
  2153. char Enc[2]; // Encoding
  2154. OIKind Kind; // Kind of operator
  2155. bool Flag : 1; // Entry-specific flag
  2156. Node::Prec Prec : 7; // Precedence
  2157. const char *Name; // Spelling
  2158. public:
  2159. constexpr OperatorInfo(const char (&E)[3], OIKind K, bool F, Node::Prec P,
  2160. const char *N)
  2161. : Enc{E[0], E[1]}, Kind{K}, Flag{F}, Prec{P}, Name{N} {}
  2162. public:
  2163. bool operator<(const OperatorInfo &Other) const {
  2164. return *this < Other.Enc;
  2165. }
  2166. bool operator<(const char *Peek) const {
  2167. return Enc[0] < Peek[0] || (Enc[0] == Peek[0] && Enc[1] < Peek[1]);
  2168. }
  2169. bool operator==(const char *Peek) const {
  2170. return Enc[0] == Peek[0] && Enc[1] == Peek[1];
  2171. }
  2172. bool operator!=(const char *Peek) const { return !this->operator==(Peek); }
  2173. public:
  2174. StringView getSymbol() const {
  2175. StringView Res = Name;
  2176. if (Kind < Unnameable) {
  2177. assert(Res.startsWith("operator") &&
  2178. "operator name does not start with 'operator'");
  2179. Res = Res.dropFront(sizeof("operator") - 1);
  2180. Res.consumeFront(' ');
  2181. }
  2182. return Res;
  2183. }
  2184. StringView getName() const { return Name; }
  2185. OIKind getKind() const { return Kind; }
  2186. bool getFlag() const { return Flag; }
  2187. Node::Prec getPrecedence() const { return Prec; }
  2188. };
  2189. static const OperatorInfo Ops[];
  2190. static const size_t NumOps;
  2191. const OperatorInfo *parseOperatorEncoding();
  2192. /// Parse the <unresolved-name> production.
  2193. Node *parseUnresolvedName(bool Global);
  2194. Node *parseSimpleId();
  2195. Node *parseBaseUnresolvedName();
  2196. Node *parseUnresolvedType();
  2197. Node *parseDestructorName();
  2198. /// Top-level entry point into the parser.
  2199. Node *parse();
  2200. };
  2201. const char* parse_discriminator(const char* first, const char* last);
  2202. // <name> ::= <nested-name> // N
  2203. // ::= <local-name> # See Scope Encoding below // Z
  2204. // ::= <unscoped-template-name> <template-args>
  2205. // ::= <unscoped-name>
  2206. //
  2207. // <unscoped-template-name> ::= <unscoped-name>
  2208. // ::= <substitution>
  2209. template <typename Derived, typename Alloc>
  2210. Node *AbstractManglingParser<Derived, Alloc>::parseName(NameState *State) {
  2211. if (look() == 'N')
  2212. return getDerived().parseNestedName(State);
  2213. if (look() == 'Z')
  2214. return getDerived().parseLocalName(State);
  2215. Node *Result = nullptr;
  2216. bool IsSubst = false;
  2217. Result = getDerived().parseUnscopedName(State, &IsSubst);
  2218. if (!Result)
  2219. return nullptr;
  2220. if (look() == 'I') {
  2221. // ::= <unscoped-template-name> <template-args>
  2222. if (!IsSubst)
  2223. // An unscoped-template-name is substitutable.
  2224. Subs.push_back(Result);
  2225. Node *TA = getDerived().parseTemplateArgs(State != nullptr);
  2226. if (TA == nullptr)
  2227. return nullptr;
  2228. if (State)
  2229. State->EndsWithTemplateArgs = true;
  2230. Result = make<NameWithTemplateArgs>(Result, TA);
  2231. } else if (IsSubst) {
  2232. // The substitution case must be followed by <template-args>.
  2233. return nullptr;
  2234. }
  2235. return Result;
  2236. }
  2237. // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
  2238. // := Z <function encoding> E s [<discriminator>]
  2239. // := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
  2240. template <typename Derived, typename Alloc>
  2241. Node *AbstractManglingParser<Derived, Alloc>::parseLocalName(NameState *State) {
  2242. if (!consumeIf('Z'))
  2243. return nullptr;
  2244. Node *Encoding = getDerived().parseEncoding();
  2245. if (Encoding == nullptr || !consumeIf('E'))
  2246. return nullptr;
  2247. if (consumeIf('s')) {
  2248. First = parse_discriminator(First, Last);
  2249. auto *StringLitName = make<NameType>("string literal");
  2250. if (!StringLitName)
  2251. return nullptr;
  2252. return make<LocalName>(Encoding, StringLitName);
  2253. }
  2254. if (consumeIf('d')) {
  2255. parseNumber(true);
  2256. if (!consumeIf('_'))
  2257. return nullptr;
  2258. Node *N = getDerived().parseName(State);
  2259. if (N == nullptr)
  2260. return nullptr;
  2261. return make<LocalName>(Encoding, N);
  2262. }
  2263. Node *Entity = getDerived().parseName(State);
  2264. if (Entity == nullptr)
  2265. return nullptr;
  2266. First = parse_discriminator(First, Last);
  2267. return make<LocalName>(Encoding, Entity);
  2268. }
  2269. // <unscoped-name> ::= <unqualified-name>
  2270. // ::= St <unqualified-name> # ::std::
  2271. // [*] extension
  2272. template <typename Derived, typename Alloc>
  2273. Node *
  2274. AbstractManglingParser<Derived, Alloc>::parseUnscopedName(NameState *State,
  2275. bool *IsSubst) {
  2276. Node *Std = nullptr;
  2277. if (consumeIf("St")) {
  2278. Std = make<NameType>("std");
  2279. if (Std == nullptr)
  2280. return nullptr;
  2281. }
  2282. Node *Res = nullptr;
  2283. ModuleName *Module = nullptr;
  2284. if (look() == 'S') {
  2285. Node *S = getDerived().parseSubstitution();
  2286. if (!S)
  2287. return nullptr;
  2288. if (S->getKind() == Node::KModuleName)
  2289. Module = static_cast<ModuleName *>(S);
  2290. else if (IsSubst && Std == nullptr) {
  2291. Res = S;
  2292. *IsSubst = true;
  2293. } else {
  2294. return nullptr;
  2295. }
  2296. }
  2297. if (Res == nullptr || Std != nullptr) {
  2298. Res = getDerived().parseUnqualifiedName(State, Std, Module);
  2299. }
  2300. return Res;
  2301. }
  2302. // <unqualified-name> ::= [<module-name>] L? <operator-name> [<abi-tags>]
  2303. // ::= [<module-name>] <ctor-dtor-name> [<abi-tags>]
  2304. // ::= [<module-name>] L? <source-name> [<abi-tags>]
  2305. // ::= [<module-name>] L? <unnamed-type-name> [<abi-tags>]
  2306. // # structured binding declaration
  2307. // ::= [<module-name>] L? DC <source-name>+ E
  2308. template <typename Derived, typename Alloc>
  2309. Node *AbstractManglingParser<Derived, Alloc>::parseUnqualifiedName(
  2310. NameState *State, Node *Scope, ModuleName *Module) {
  2311. if (getDerived().parseModuleNameOpt(Module))
  2312. return nullptr;
  2313. consumeIf('L');
  2314. Node *Result;
  2315. if (look() >= '1' && look() <= '9') {
  2316. Result = getDerived().parseSourceName(State);
  2317. } else if (look() == 'U') {
  2318. Result = getDerived().parseUnnamedTypeName(State);
  2319. } else if (consumeIf("DC")) {
  2320. // Structured binding
  2321. size_t BindingsBegin = Names.size();
  2322. do {
  2323. Node *Binding = getDerived().parseSourceName(State);
  2324. if (Binding == nullptr)
  2325. return nullptr;
  2326. Names.push_back(Binding);
  2327. } while (!consumeIf('E'));
  2328. Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
  2329. } else if (look() == 'C' || look() == 'D') {
  2330. // A <ctor-dtor-name>.
  2331. if (Scope == nullptr || Module != nullptr)
  2332. return nullptr;
  2333. Result = getDerived().parseCtorDtorName(Scope, State);
  2334. } else {
  2335. Result = getDerived().parseOperatorName(State);
  2336. }
  2337. if (Result != nullptr && Module != nullptr)
  2338. Result = make<ModuleEntity>(Module, Result);
  2339. if (Result != nullptr)
  2340. Result = getDerived().parseAbiTags(Result);
  2341. if (Result != nullptr && Scope != nullptr)
  2342. Result = make<NestedName>(Scope, Result);
  2343. return Result;
  2344. }
  2345. // <module-name> ::= <module-subname>
  2346. // ::= <module-name> <module-subname>
  2347. // ::= <substitution> # passed in by caller
  2348. // <module-subname> ::= W <source-name>
  2349. // ::= W P <source-name>
  2350. template <typename Derived, typename Alloc>
  2351. bool AbstractManglingParser<Derived, Alloc>::parseModuleNameOpt(
  2352. ModuleName *&Module) {
  2353. while (consumeIf('W')) {
  2354. bool IsPartition = consumeIf('P');
  2355. Node *Sub = getDerived().parseSourceName(nullptr);
  2356. if (!Sub)
  2357. return true;
  2358. Module =
  2359. static_cast<ModuleName *>(make<ModuleName>(Module, Sub, IsPartition));
  2360. Subs.push_back(Module);
  2361. }
  2362. return false;
  2363. }
  2364. // <unnamed-type-name> ::= Ut [<nonnegative number>] _
  2365. // ::= <closure-type-name>
  2366. //
  2367. // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
  2368. //
  2369. // <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
  2370. template <typename Derived, typename Alloc>
  2371. Node *
  2372. AbstractManglingParser<Derived, Alloc>::parseUnnamedTypeName(NameState *State) {
  2373. // <template-params> refer to the innermost <template-args>. Clear out any
  2374. // outer args that we may have inserted into TemplateParams.
  2375. if (State != nullptr)
  2376. TemplateParams.clear();
  2377. if (consumeIf("Ut")) {
  2378. StringView Count = parseNumber();
  2379. if (!consumeIf('_'))
  2380. return nullptr;
  2381. return make<UnnamedTypeName>(Count);
  2382. }
  2383. if (consumeIf("Ul")) {
  2384. ScopedOverride<size_t> SwapParams(ParsingLambdaParamsAtLevel,
  2385. TemplateParams.size());
  2386. ScopedTemplateParamList LambdaTemplateParams(this);
  2387. size_t ParamsBegin = Names.size();
  2388. while (look() == 'T' &&
  2389. StringView("yptn").find(look(1)) != StringView::npos) {
  2390. Node *T = parseTemplateParamDecl();
  2391. if (!T)
  2392. return nullptr;
  2393. Names.push_back(T);
  2394. }
  2395. NodeArray TempParams = popTrailingNodeArray(ParamsBegin);
  2396. // FIXME: If TempParams is empty and none of the function parameters
  2397. // includes 'auto', we should remove LambdaTemplateParams from the
  2398. // TemplateParams list. Unfortunately, we don't find out whether there are
  2399. // any 'auto' parameters until too late in an example such as:
  2400. //
  2401. // template<typename T> void f(
  2402. // decltype([](decltype([]<typename T>(T v) {}),
  2403. // auto) {})) {}
  2404. // template<typename T> void f(
  2405. // decltype([](decltype([]<typename T>(T w) {}),
  2406. // int) {})) {}
  2407. //
  2408. // Here, the type of v is at level 2 but the type of w is at level 1. We
  2409. // don't find this out until we encounter the type of the next parameter.
  2410. //
  2411. // However, compilers can't actually cope with the former example in
  2412. // practice, and it's likely to be made ill-formed in future, so we don't
  2413. // need to support it here.
  2414. //
  2415. // If we encounter an 'auto' in the function parameter types, we will
  2416. // recreate a template parameter scope for it, but any intervening lambdas
  2417. // will be parsed in the 'wrong' template parameter depth.
  2418. if (TempParams.empty())
  2419. TemplateParams.pop_back();
  2420. if (!consumeIf("vE")) {
  2421. do {
  2422. Node *P = getDerived().parseType();
  2423. if (P == nullptr)
  2424. return nullptr;
  2425. Names.push_back(P);
  2426. } while (!consumeIf('E'));
  2427. }
  2428. NodeArray Params = popTrailingNodeArray(ParamsBegin);
  2429. StringView Count = parseNumber();
  2430. if (!consumeIf('_'))
  2431. return nullptr;
  2432. return make<ClosureTypeName>(TempParams, Params, Count);
  2433. }
  2434. if (consumeIf("Ub")) {
  2435. (void)parseNumber();
  2436. if (!consumeIf('_'))
  2437. return nullptr;
  2438. return make<NameType>("'block-literal'");
  2439. }
  2440. return nullptr;
  2441. }
  2442. // <source-name> ::= <positive length number> <identifier>
  2443. template <typename Derived, typename Alloc>
  2444. Node *AbstractManglingParser<Derived, Alloc>::parseSourceName(NameState *) {
  2445. size_t Length = 0;
  2446. if (parsePositiveInteger(&Length))
  2447. return nullptr;
  2448. if (numLeft() < Length || Length == 0)
  2449. return nullptr;
  2450. StringView Name(First, First + Length);
  2451. First += Length;
  2452. if (Name.startsWith("_GLOBAL__N"))
  2453. return make<NameType>("(anonymous namespace)");
  2454. return make<NameType>(Name);
  2455. }
  2456. // Operator encodings
  2457. template <typename Derived, typename Alloc>
  2458. const typename AbstractManglingParser<
  2459. Derived, Alloc>::OperatorInfo AbstractManglingParser<Derived,
  2460. Alloc>::Ops[] = {
  2461. // Keep ordered by encoding
  2462. {"aN", OperatorInfo::Binary, false, Node::Prec::Assign, "operator&="},
  2463. {"aS", OperatorInfo::Binary, false, Node::Prec::Assign, "operator="},
  2464. {"aa", OperatorInfo::Binary, false, Node::Prec::AndIf, "operator&&"},
  2465. {"ad", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator&"},
  2466. {"an", OperatorInfo::Binary, false, Node::Prec::And, "operator&"},
  2467. {"at", OperatorInfo::OfIdOp, /*Type*/ true, Node::Prec::Unary, "alignof "},
  2468. {"aw", OperatorInfo::NameOnly, false, Node::Prec::Primary,
  2469. "operator co_await"},
  2470. {"az", OperatorInfo::OfIdOp, /*Type*/ false, Node::Prec::Unary, "alignof "},
  2471. {"cc", OperatorInfo::NamedCast, false, Node::Prec::Postfix, "const_cast"},
  2472. {"cl", OperatorInfo::Call, false, Node::Prec::Postfix, "operator()"},
  2473. {"cm", OperatorInfo::Binary, false, Node::Prec::Comma, "operator,"},
  2474. {"co", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator~"},
  2475. {"cv", OperatorInfo::CCast, false, Node::Prec::Cast, "operator"}, // C Cast
  2476. {"dV", OperatorInfo::Binary, false, Node::Prec::Assign, "operator/="},
  2477. {"da", OperatorInfo::Del, /*Ary*/ true, Node::Prec::Unary,
  2478. "operator delete[]"},
  2479. {"dc", OperatorInfo::NamedCast, false, Node::Prec::Postfix, "dynamic_cast"},
  2480. {"de", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator*"},
  2481. {"dl", OperatorInfo::Del, /*Ary*/ false, Node::Prec::Unary,
  2482. "operator delete"},
  2483. {"ds", OperatorInfo::Member, /*Named*/ false, Node::Prec::PtrMem,
  2484. "operator.*"},
  2485. {"dt", OperatorInfo::Member, /*Named*/ false, Node::Prec::Postfix,
  2486. "operator."},
  2487. {"dv", OperatorInfo::Binary, false, Node::Prec::Assign, "operator/"},
  2488. {"eO", OperatorInfo::Binary, false, Node::Prec::Assign, "operator^="},
  2489. {"eo", OperatorInfo::Binary, false, Node::Prec::Xor, "operator^"},
  2490. {"eq", OperatorInfo::Binary, false, Node::Prec::Equality, "operator=="},
  2491. {"ge", OperatorInfo::Binary, false, Node::Prec::Relational, "operator>="},
  2492. {"gt", OperatorInfo::Binary, false, Node::Prec::Relational, "operator>"},
  2493. {"ix", OperatorInfo::Array, false, Node::Prec::Postfix, "operator[]"},
  2494. {"lS", OperatorInfo::Binary, false, Node::Prec::Assign, "operator<<="},
  2495. {"le", OperatorInfo::Binary, false, Node::Prec::Relational, "operator<="},
  2496. {"ls", OperatorInfo::Binary, false, Node::Prec::Shift, "operator<<"},
  2497. {"lt", OperatorInfo::Binary, false, Node::Prec::Relational, "operator<"},
  2498. {"mI", OperatorInfo::Binary, false, Node::Prec::Assign, "operator-="},
  2499. {"mL", OperatorInfo::Binary, false, Node::Prec::Assign, "operator*="},
  2500. {"mi", OperatorInfo::Binary, false, Node::Prec::Additive, "operator-"},
  2501. {"ml", OperatorInfo::Binary, false, Node::Prec::Multiplicative,
  2502. "operator*"},
  2503. {"mm", OperatorInfo::Postfix, false, Node::Prec::Postfix, "operator--"},
  2504. {"na", OperatorInfo::New, /*Ary*/ true, Node::Prec::Unary,
  2505. "operator new[]"},
  2506. {"ne", OperatorInfo::Binary, false, Node::Prec::Equality, "operator!="},
  2507. {"ng", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator-"},
  2508. {"nt", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator!"},
  2509. {"nw", OperatorInfo::New, /*Ary*/ false, Node::Prec::Unary, "operator new"},
  2510. {"oR", OperatorInfo::Binary, false, Node::Prec::Assign, "operator|="},
  2511. {"oo", OperatorInfo::Binary, false, Node::Prec::OrIf, "operator||"},
  2512. {"or", OperatorInfo::Binary, false, Node::Prec::Ior, "operator|"},
  2513. {"pL", OperatorInfo::Binary, false, Node::Prec::Assign, "operator+="},
  2514. {"pl", OperatorInfo::Binary, false, Node::Prec::Additive, "operator+"},
  2515. {"pm", OperatorInfo::Member, /*Named*/ false, Node::Prec::PtrMem,
  2516. "operator->*"},
  2517. {"pp", OperatorInfo::Postfix, false, Node::Prec::Postfix, "operator++"},
  2518. {"ps", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator+"},
  2519. {"pt", OperatorInfo::Member, /*Named*/ true, Node::Prec::Postfix,
  2520. "operator->"},
  2521. {"qu", OperatorInfo::Conditional, false, Node::Prec::Conditional,
  2522. "operator?"},
  2523. {"rM", OperatorInfo::Binary, false, Node::Prec::Assign, "operator%="},
  2524. {"rS", OperatorInfo::Binary, false, Node::Prec::Assign, "operator>>="},
  2525. {"rc", OperatorInfo::NamedCast, false, Node::Prec::Postfix,
  2526. "reinterpret_cast"},
  2527. {"rm", OperatorInfo::Binary, false, Node::Prec::Multiplicative,
  2528. "operator%"},
  2529. {"rs", OperatorInfo::Binary, false, Node::Prec::Shift, "operator>>"},
  2530. {"sc", OperatorInfo::NamedCast, false, Node::Prec::Postfix, "static_cast"},
  2531. {"ss", OperatorInfo::Binary, false, Node::Prec::Spaceship, "operator<=>"},
  2532. {"st", OperatorInfo::OfIdOp, /*Type*/ true, Node::Prec::Unary, "sizeof "},
  2533. {"sz", OperatorInfo::OfIdOp, /*Type*/ false, Node::Prec::Unary, "sizeof "},
  2534. {"te", OperatorInfo::OfIdOp, /*Type*/ false, Node::Prec::Postfix,
  2535. "typeid "},
  2536. {"ti", OperatorInfo::OfIdOp, /*Type*/ true, Node::Prec::Postfix, "typeid "},
  2537. };
  2538. template <typename Derived, typename Alloc>
  2539. const size_t AbstractManglingParser<Derived, Alloc>::NumOps = sizeof(Ops) /
  2540. sizeof(Ops[0]);
  2541. // If the next 2 chars are an operator encoding, consume them and return their
  2542. // OperatorInfo. Otherwise return nullptr.
  2543. template <typename Derived, typename Alloc>
  2544. const typename AbstractManglingParser<Derived, Alloc>::OperatorInfo *
  2545. AbstractManglingParser<Derived, Alloc>::parseOperatorEncoding() {
  2546. if (numLeft() < 2)
  2547. return nullptr;
  2548. // We can't use lower_bound as that can link to symbols in the C++ library,
  2549. // and this must remain independant of that.
  2550. size_t lower = 0u, upper = NumOps - 1; // Inclusive bounds.
  2551. while (upper != lower) {
  2552. size_t middle = (upper + lower) / 2;
  2553. if (Ops[middle] < First)
  2554. lower = middle + 1;
  2555. else
  2556. upper = middle;
  2557. }
  2558. if (Ops[lower] != First)
  2559. return nullptr;
  2560. First += 2;
  2561. return &Ops[lower];
  2562. }
  2563. // <operator-name> ::= See parseOperatorEncoding()
  2564. // ::= li <source-name> # operator ""
  2565. // ::= v <digit> <source-name> # vendor extended operator
  2566. template <typename Derived, typename Alloc>
  2567. Node *
  2568. AbstractManglingParser<Derived, Alloc>::parseOperatorName(NameState *State) {
  2569. if (const auto *Op = parseOperatorEncoding()) {
  2570. if (Op->getKind() == OperatorInfo::CCast) {
  2571. // ::= cv <type> # (cast)
  2572. ScopedOverride<bool> SaveTemplate(TryToParseTemplateArgs, false);
  2573. // If we're parsing an encoding, State != nullptr and the conversion
  2574. // operators' <type> could have a <template-param> that refers to some
  2575. // <template-arg>s further ahead in the mangled name.
  2576. ScopedOverride<bool> SavePermit(PermitForwardTemplateReferences,
  2577. PermitForwardTemplateReferences ||
  2578. State != nullptr);
  2579. Node *Ty = getDerived().parseType();
  2580. if (Ty == nullptr)
  2581. return nullptr;
  2582. if (State) State->CtorDtorConversion = true;
  2583. return make<ConversionOperatorType>(Ty);
  2584. }
  2585. if (Op->getKind() >= OperatorInfo::Unnameable)
  2586. /* Not a nameable operator. */
  2587. return nullptr;
  2588. if (Op->getKind() == OperatorInfo::Member && !Op->getFlag())
  2589. /* Not a nameable MemberExpr */
  2590. return nullptr;
  2591. return make<NameType>(Op->getName());
  2592. }
  2593. if (consumeIf("li")) {
  2594. // ::= li <source-name> # operator ""
  2595. Node *SN = getDerived().parseSourceName(State);
  2596. if (SN == nullptr)
  2597. return nullptr;
  2598. return make<LiteralOperator>(SN);
  2599. }
  2600. if (consumeIf('v')) {
  2601. // ::= v <digit> <source-name> # vendor extended operator
  2602. if (look() >= '0' && look() <= '9') {
  2603. First++;
  2604. Node *SN = getDerived().parseSourceName(State);
  2605. if (SN == nullptr)
  2606. return nullptr;
  2607. return make<ConversionOperatorType>(SN);
  2608. }
  2609. return nullptr;
  2610. }
  2611. return nullptr;
  2612. }
  2613. // <ctor-dtor-name> ::= C1 # complete object constructor
  2614. // ::= C2 # base object constructor
  2615. // ::= C3 # complete object allocating constructor
  2616. // extension ::= C4 # gcc old-style "[unified]" constructor
  2617. // extension ::= C5 # the COMDAT used for ctors
  2618. // ::= D0 # deleting destructor
  2619. // ::= D1 # complete object destructor
  2620. // ::= D2 # base object destructor
  2621. // extension ::= D4 # gcc old-style "[unified]" destructor
  2622. // extension ::= D5 # the COMDAT used for dtors
  2623. template <typename Derived, typename Alloc>
  2624. Node *
  2625. AbstractManglingParser<Derived, Alloc>::parseCtorDtorName(Node *&SoFar,
  2626. NameState *State) {
  2627. if (SoFar->getKind() == Node::KSpecialSubstitution) {
  2628. // Expand the special substitution.
  2629. SoFar = make<ExpandedSpecialSubstitution>(
  2630. static_cast<SpecialSubstitution *>(SoFar));
  2631. if (!SoFar)
  2632. return nullptr;
  2633. }
  2634. if (consumeIf('C')) {
  2635. bool IsInherited = consumeIf('I');
  2636. if (look() != '1' && look() != '2' && look() != '3' && look() != '4' &&
  2637. look() != '5')
  2638. return nullptr;
  2639. int Variant = look() - '0';
  2640. ++First;
  2641. if (State) State->CtorDtorConversion = true;
  2642. if (IsInherited) {
  2643. if (getDerived().parseName(State) == nullptr)
  2644. return nullptr;
  2645. }
  2646. return make<CtorDtorName>(SoFar, /*IsDtor=*/false, Variant);
  2647. }
  2648. if (look() == 'D' && (look(1) == '0' || look(1) == '1' || look(1) == '2' ||
  2649. look(1) == '4' || look(1) == '5')) {
  2650. int Variant = look(1) - '0';
  2651. First += 2;
  2652. if (State) State->CtorDtorConversion = true;
  2653. return make<CtorDtorName>(SoFar, /*IsDtor=*/true, Variant);
  2654. }
  2655. return nullptr;
  2656. }
  2657. // <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix>
  2658. // <unqualified-name> E
  2659. // ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix>
  2660. // <template-args> E
  2661. //
  2662. // <prefix> ::= <prefix> <unqualified-name>
  2663. // ::= <template-prefix> <template-args>
  2664. // ::= <template-param>
  2665. // ::= <decltype>
  2666. // ::= # empty
  2667. // ::= <substitution>
  2668. // ::= <prefix> <data-member-prefix>
  2669. // [*] extension
  2670. //
  2671. // <data-member-prefix> := <member source-name> [<template-args>] M
  2672. //
  2673. // <template-prefix> ::= <prefix> <template unqualified-name>
  2674. // ::= <template-param>
  2675. // ::= <substitution>
  2676. template <typename Derived, typename Alloc>
  2677. Node *
  2678. AbstractManglingParser<Derived, Alloc>::parseNestedName(NameState *State) {
  2679. if (!consumeIf('N'))
  2680. return nullptr;
  2681. Qualifiers CVTmp = parseCVQualifiers();
  2682. if (State) State->CVQualifiers = CVTmp;
  2683. if (consumeIf('O')) {
  2684. if (State) State->ReferenceQualifier = FrefQualRValue;
  2685. } else if (consumeIf('R')) {
  2686. if (State) State->ReferenceQualifier = FrefQualLValue;
  2687. } else {
  2688. if (State) State->ReferenceQualifier = FrefQualNone;
  2689. }
  2690. Node *SoFar = nullptr;
  2691. while (!consumeIf('E')) {
  2692. if (State)
  2693. // Only set end-with-template on the case that does that.
  2694. State->EndsWithTemplateArgs = false;
  2695. if (look() == 'T') {
  2696. // ::= <template-param>
  2697. if (SoFar != nullptr)
  2698. return nullptr; // Cannot have a prefix.
  2699. SoFar = getDerived().parseTemplateParam();
  2700. } else if (look() == 'I') {
  2701. // ::= <template-prefix> <template-args>
  2702. if (SoFar == nullptr)
  2703. return nullptr; // Must have a prefix.
  2704. Node *TA = getDerived().parseTemplateArgs(State != nullptr);
  2705. if (TA == nullptr)
  2706. return nullptr;
  2707. if (SoFar->getKind() == Node::KNameWithTemplateArgs)
  2708. // Semantically <template-args> <template-args> cannot be generated by a
  2709. // C++ entity. There will always be [something like] a name between
  2710. // them.
  2711. return nullptr;
  2712. if (State)
  2713. State->EndsWithTemplateArgs = true;
  2714. SoFar = make<NameWithTemplateArgs>(SoFar, TA);
  2715. } else if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
  2716. // ::= <decltype>
  2717. if (SoFar != nullptr)
  2718. return nullptr; // Cannot have a prefix.
  2719. SoFar = getDerived().parseDecltype();
  2720. } else {
  2721. ModuleName *Module = nullptr;
  2722. if (look() == 'S') {
  2723. // ::= <substitution>
  2724. Node *S = nullptr;
  2725. if (look(1) == 't') {
  2726. First += 2;
  2727. S = make<NameType>("std");
  2728. } else {
  2729. S = getDerived().parseSubstitution();
  2730. }
  2731. if (!S)
  2732. return nullptr;
  2733. if (S->getKind() == Node::KModuleName) {
  2734. Module = static_cast<ModuleName *>(S);
  2735. } else if (SoFar != nullptr) {
  2736. return nullptr; // Cannot have a prefix.
  2737. } else {
  2738. SoFar = S;
  2739. continue; // Do not push a new substitution.
  2740. }
  2741. }
  2742. // ::= [<prefix>] <unqualified-name>
  2743. SoFar = getDerived().parseUnqualifiedName(State, SoFar, Module);
  2744. }
  2745. if (SoFar == nullptr)
  2746. return nullptr;
  2747. Subs.push_back(SoFar);
  2748. // No longer used.
  2749. // <data-member-prefix> := <member source-name> [<template-args>] M
  2750. consumeIf('M');
  2751. }
  2752. if (SoFar == nullptr || Subs.empty())
  2753. return nullptr;
  2754. Subs.pop_back();
  2755. return SoFar;
  2756. }
  2757. // <simple-id> ::= <source-name> [ <template-args> ]
  2758. template <typename Derived, typename Alloc>
  2759. Node *AbstractManglingParser<Derived, Alloc>::parseSimpleId() {
  2760. Node *SN = getDerived().parseSourceName(/*NameState=*/nullptr);
  2761. if (SN == nullptr)
  2762. return nullptr;
  2763. if (look() == 'I') {
  2764. Node *TA = getDerived().parseTemplateArgs();
  2765. if (TA == nullptr)
  2766. return nullptr;
  2767. return make<NameWithTemplateArgs>(SN, TA);
  2768. }
  2769. return SN;
  2770. }
  2771. // <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
  2772. // ::= <simple-id> # e.g., ~A<2*N>
  2773. template <typename Derived, typename Alloc>
  2774. Node *AbstractManglingParser<Derived, Alloc>::parseDestructorName() {
  2775. Node *Result;
  2776. if (std::isdigit(look()))
  2777. Result = getDerived().parseSimpleId();
  2778. else
  2779. Result = getDerived().parseUnresolvedType();
  2780. if (Result == nullptr)
  2781. return nullptr;
  2782. return make<DtorName>(Result);
  2783. }
  2784. // <unresolved-type> ::= <template-param>
  2785. // ::= <decltype>
  2786. // ::= <substitution>
  2787. template <typename Derived, typename Alloc>
  2788. Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedType() {
  2789. if (look() == 'T') {
  2790. Node *TP = getDerived().parseTemplateParam();
  2791. if (TP == nullptr)
  2792. return nullptr;
  2793. Subs.push_back(TP);
  2794. return TP;
  2795. }
  2796. if (look() == 'D') {
  2797. Node *DT = getDerived().parseDecltype();
  2798. if (DT == nullptr)
  2799. return nullptr;
  2800. Subs.push_back(DT);
  2801. return DT;
  2802. }
  2803. return getDerived().parseSubstitution();
  2804. }
  2805. // <base-unresolved-name> ::= <simple-id> # unresolved name
  2806. // extension ::= <operator-name> # unresolved operator-function-id
  2807. // extension ::= <operator-name> <template-args> # unresolved operator template-id
  2808. // ::= on <operator-name> # unresolved operator-function-id
  2809. // ::= on <operator-name> <template-args> # unresolved operator template-id
  2810. // ::= dn <destructor-name> # destructor or pseudo-destructor;
  2811. // # e.g. ~X or ~X<N-1>
  2812. template <typename Derived, typename Alloc>
  2813. Node *AbstractManglingParser<Derived, Alloc>::parseBaseUnresolvedName() {
  2814. if (std::isdigit(look()))
  2815. return getDerived().parseSimpleId();
  2816. if (consumeIf("dn"))
  2817. return getDerived().parseDestructorName();
  2818. consumeIf("on");
  2819. Node *Oper = getDerived().parseOperatorName(/*NameState=*/nullptr);
  2820. if (Oper == nullptr)
  2821. return nullptr;
  2822. if (look() == 'I') {
  2823. Node *TA = getDerived().parseTemplateArgs();
  2824. if (TA == nullptr)
  2825. return nullptr;
  2826. return make<NameWithTemplateArgs>(Oper, TA);
  2827. }
  2828. return Oper;
  2829. }
  2830. // <unresolved-name>
  2831. // extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
  2832. // ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
  2833. // ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
  2834. // # A::x, N::y, A<T>::z; "gs" means leading "::"
  2835. // [gs] has been parsed by caller.
  2836. // ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
  2837. // extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
  2838. // # T::N::x /decltype(p)::N::x
  2839. // (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
  2840. //
  2841. // <unresolved-qualifier-level> ::= <simple-id>
  2842. template <typename Derived, typename Alloc>
  2843. Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedName(bool Global) {
  2844. Node *SoFar = nullptr;
  2845. // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
  2846. // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
  2847. if (consumeIf("srN")) {
  2848. SoFar = getDerived().parseUnresolvedType();
  2849. if (SoFar == nullptr)
  2850. return nullptr;
  2851. if (look() == 'I') {
  2852. Node *TA = getDerived().parseTemplateArgs();
  2853. if (TA == nullptr)
  2854. return nullptr;
  2855. SoFar = make<NameWithTemplateArgs>(SoFar, TA);
  2856. if (!SoFar)
  2857. return nullptr;
  2858. }
  2859. while (!consumeIf('E')) {
  2860. Node *Qual = getDerived().parseSimpleId();
  2861. if (Qual == nullptr)
  2862. return nullptr;
  2863. SoFar = make<QualifiedName>(SoFar, Qual);
  2864. if (!SoFar)
  2865. return nullptr;
  2866. }
  2867. Node *Base = getDerived().parseBaseUnresolvedName();
  2868. if (Base == nullptr)
  2869. return nullptr;
  2870. return make<QualifiedName>(SoFar, Base);
  2871. }
  2872. // [gs] <base-unresolved-name> # x or (with "gs") ::x
  2873. if (!consumeIf("sr")) {
  2874. SoFar = getDerived().parseBaseUnresolvedName();
  2875. if (SoFar == nullptr)
  2876. return nullptr;
  2877. if (Global)
  2878. SoFar = make<GlobalQualifiedName>(SoFar);
  2879. return SoFar;
  2880. }
  2881. // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
  2882. if (std::isdigit(look())) {
  2883. do {
  2884. Node *Qual = getDerived().parseSimpleId();
  2885. if (Qual == nullptr)
  2886. return nullptr;
  2887. if (SoFar)
  2888. SoFar = make<QualifiedName>(SoFar, Qual);
  2889. else if (Global)
  2890. SoFar = make<GlobalQualifiedName>(Qual);
  2891. else
  2892. SoFar = Qual;
  2893. if (!SoFar)
  2894. return nullptr;
  2895. } while (!consumeIf('E'));
  2896. }
  2897. // sr <unresolved-type> <base-unresolved-name>
  2898. // sr <unresolved-type> <template-args> <base-unresolved-name>
  2899. else {
  2900. SoFar = getDerived().parseUnresolvedType();
  2901. if (SoFar == nullptr)
  2902. return nullptr;
  2903. if (look() == 'I') {
  2904. Node *TA = getDerived().parseTemplateArgs();
  2905. if (TA == nullptr)
  2906. return nullptr;
  2907. SoFar = make<NameWithTemplateArgs>(SoFar, TA);
  2908. if (!SoFar)
  2909. return nullptr;
  2910. }
  2911. }
  2912. assert(SoFar != nullptr);
  2913. Node *Base = getDerived().parseBaseUnresolvedName();
  2914. if (Base == nullptr)
  2915. return nullptr;
  2916. return make<QualifiedName>(SoFar, Base);
  2917. }
  2918. // <abi-tags> ::= <abi-tag> [<abi-tags>]
  2919. // <abi-tag> ::= B <source-name>
  2920. template <typename Derived, typename Alloc>
  2921. Node *AbstractManglingParser<Derived, Alloc>::parseAbiTags(Node *N) {
  2922. while (consumeIf('B')) {
  2923. StringView SN = parseBareSourceName();
  2924. if (SN.empty())
  2925. return nullptr;
  2926. N = make<AbiTagAttr>(N, SN);
  2927. if (!N)
  2928. return nullptr;
  2929. }
  2930. return N;
  2931. }
  2932. // <number> ::= [n] <non-negative decimal integer>
  2933. template <typename Alloc, typename Derived>
  2934. StringView
  2935. AbstractManglingParser<Alloc, Derived>::parseNumber(bool AllowNegative) {
  2936. const char *Tmp = First;
  2937. if (AllowNegative)
  2938. consumeIf('n');
  2939. if (numLeft() == 0 || !std::isdigit(*First))
  2940. return StringView();
  2941. while (numLeft() != 0 && std::isdigit(*First))
  2942. ++First;
  2943. return StringView(Tmp, First);
  2944. }
  2945. // <positive length number> ::= [0-9]*
  2946. template <typename Alloc, typename Derived>
  2947. bool AbstractManglingParser<Alloc, Derived>::parsePositiveInteger(size_t *Out) {
  2948. *Out = 0;
  2949. if (look() < '0' || look() > '9')
  2950. return true;
  2951. while (look() >= '0' && look() <= '9') {
  2952. *Out *= 10;
  2953. *Out += static_cast<size_t>(consume() - '0');
  2954. }
  2955. return false;
  2956. }
  2957. template <typename Alloc, typename Derived>
  2958. StringView AbstractManglingParser<Alloc, Derived>::parseBareSourceName() {
  2959. size_t Int = 0;
  2960. if (parsePositiveInteger(&Int) || numLeft() < Int)
  2961. return StringView();
  2962. StringView R(First, First + Int);
  2963. First += Int;
  2964. return R;
  2965. }
  2966. // <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
  2967. //
  2968. // <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
  2969. // ::= DO <expression> E # computed (instantiation-dependent) noexcept
  2970. // ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
  2971. //
  2972. // <ref-qualifier> ::= R # & ref-qualifier
  2973. // <ref-qualifier> ::= O # && ref-qualifier
  2974. template <typename Derived, typename Alloc>
  2975. Node *AbstractManglingParser<Derived, Alloc>::parseFunctionType() {
  2976. Qualifiers CVQuals = parseCVQualifiers();
  2977. Node *ExceptionSpec = nullptr;
  2978. if (consumeIf("Do")) {
  2979. ExceptionSpec = make<NameType>("noexcept");
  2980. if (!ExceptionSpec)
  2981. return nullptr;
  2982. } else if (consumeIf("DO")) {
  2983. Node *E = getDerived().parseExpr();
  2984. if (E == nullptr || !consumeIf('E'))
  2985. return nullptr;
  2986. ExceptionSpec = make<NoexceptSpec>(E);
  2987. if (!ExceptionSpec)
  2988. return nullptr;
  2989. } else if (consumeIf("Dw")) {
  2990. size_t SpecsBegin = Names.size();
  2991. while (!consumeIf('E')) {
  2992. Node *T = getDerived().parseType();
  2993. if (T == nullptr)
  2994. return nullptr;
  2995. Names.push_back(T);
  2996. }
  2997. ExceptionSpec =
  2998. make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
  2999. if (!ExceptionSpec)
  3000. return nullptr;
  3001. }
  3002. consumeIf("Dx"); // transaction safe
  3003. if (!consumeIf('F'))
  3004. return nullptr;
  3005. consumeIf('Y'); // extern "C"
  3006. Node *ReturnType = getDerived().parseType();
  3007. if (ReturnType == nullptr)
  3008. return nullptr;
  3009. FunctionRefQual ReferenceQualifier = FrefQualNone;
  3010. size_t ParamsBegin = Names.size();
  3011. while (true) {
  3012. if (consumeIf('E'))
  3013. break;
  3014. if (consumeIf('v'))
  3015. continue;
  3016. if (consumeIf("RE")) {
  3017. ReferenceQualifier = FrefQualLValue;
  3018. break;
  3019. }
  3020. if (consumeIf("OE")) {
  3021. ReferenceQualifier = FrefQualRValue;
  3022. break;
  3023. }
  3024. Node *T = getDerived().parseType();
  3025. if (T == nullptr)
  3026. return nullptr;
  3027. Names.push_back(T);
  3028. }
  3029. NodeArray Params = popTrailingNodeArray(ParamsBegin);
  3030. return make<FunctionType>(ReturnType, Params, CVQuals,
  3031. ReferenceQualifier, ExceptionSpec);
  3032. }
  3033. // extension:
  3034. // <vector-type> ::= Dv <positive dimension number> _ <extended element type>
  3035. // ::= Dv [<dimension expression>] _ <element type>
  3036. // <extended element type> ::= <element type>
  3037. // ::= p # AltiVec vector pixel
  3038. template <typename Derived, typename Alloc>
  3039. Node *AbstractManglingParser<Derived, Alloc>::parseVectorType() {
  3040. if (!consumeIf("Dv"))
  3041. return nullptr;
  3042. if (look() >= '1' && look() <= '9') {
  3043. Node *DimensionNumber = make<NameType>(parseNumber());
  3044. if (!DimensionNumber)
  3045. return nullptr;
  3046. if (!consumeIf('_'))
  3047. return nullptr;
  3048. if (consumeIf('p'))
  3049. return make<PixelVectorType>(DimensionNumber);
  3050. Node *ElemType = getDerived().parseType();
  3051. if (ElemType == nullptr)
  3052. return nullptr;
  3053. return make<VectorType>(ElemType, DimensionNumber);
  3054. }
  3055. if (!consumeIf('_')) {
  3056. Node *DimExpr = getDerived().parseExpr();
  3057. if (!DimExpr)
  3058. return nullptr;
  3059. if (!consumeIf('_'))
  3060. return nullptr;
  3061. Node *ElemType = getDerived().parseType();
  3062. if (!ElemType)
  3063. return nullptr;
  3064. return make<VectorType>(ElemType, DimExpr);
  3065. }
  3066. Node *ElemType = getDerived().parseType();
  3067. if (!ElemType)
  3068. return nullptr;
  3069. return make<VectorType>(ElemType, /*Dimension=*/nullptr);
  3070. }
  3071. // <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
  3072. // ::= DT <expression> E # decltype of an expression (C++0x)
  3073. template <typename Derived, typename Alloc>
  3074. Node *AbstractManglingParser<Derived, Alloc>::parseDecltype() {
  3075. if (!consumeIf('D'))
  3076. return nullptr;
  3077. if (!consumeIf('t') && !consumeIf('T'))
  3078. return nullptr;
  3079. Node *E = getDerived().parseExpr();
  3080. if (E == nullptr)
  3081. return nullptr;
  3082. if (!consumeIf('E'))
  3083. return nullptr;
  3084. return make<EnclosingExpr>("decltype", E);
  3085. }
  3086. // <array-type> ::= A <positive dimension number> _ <element type>
  3087. // ::= A [<dimension expression>] _ <element type>
  3088. template <typename Derived, typename Alloc>
  3089. Node *AbstractManglingParser<Derived, Alloc>::parseArrayType() {
  3090. if (!consumeIf('A'))
  3091. return nullptr;
  3092. Node *Dimension = nullptr;
  3093. if (std::isdigit(look())) {
  3094. Dimension = make<NameType>(parseNumber());
  3095. if (!Dimension)
  3096. return nullptr;
  3097. if (!consumeIf('_'))
  3098. return nullptr;
  3099. } else if (!consumeIf('_')) {
  3100. Node *DimExpr = getDerived().parseExpr();
  3101. if (DimExpr == nullptr)
  3102. return nullptr;
  3103. if (!consumeIf('_'))
  3104. return nullptr;
  3105. Dimension = DimExpr;
  3106. }
  3107. Node *Ty = getDerived().parseType();
  3108. if (Ty == nullptr)
  3109. return nullptr;
  3110. return make<ArrayType>(Ty, Dimension);
  3111. }
  3112. // <pointer-to-member-type> ::= M <class type> <member type>
  3113. template <typename Derived, typename Alloc>
  3114. Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberType() {
  3115. if (!consumeIf('M'))
  3116. return nullptr;
  3117. Node *ClassType = getDerived().parseType();
  3118. if (ClassType == nullptr)
  3119. return nullptr;
  3120. Node *MemberType = getDerived().parseType();
  3121. if (MemberType == nullptr)
  3122. return nullptr;
  3123. return make<PointerToMemberType>(ClassType, MemberType);
  3124. }
  3125. // <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
  3126. // ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
  3127. // ::= Tu <name> # dependent elaborated type specifier using 'union'
  3128. // ::= Te <name> # dependent elaborated type specifier using 'enum'
  3129. template <typename Derived, typename Alloc>
  3130. Node *AbstractManglingParser<Derived, Alloc>::parseClassEnumType() {
  3131. StringView ElabSpef;
  3132. if (consumeIf("Ts"))
  3133. ElabSpef = "struct";
  3134. else if (consumeIf("Tu"))
  3135. ElabSpef = "union";
  3136. else if (consumeIf("Te"))
  3137. ElabSpef = "enum";
  3138. Node *Name = getDerived().parseName();
  3139. if (Name == nullptr)
  3140. return nullptr;
  3141. if (!ElabSpef.empty())
  3142. return make<ElaboratedTypeSpefType>(ElabSpef, Name);
  3143. return Name;
  3144. }
  3145. // <qualified-type> ::= <qualifiers> <type>
  3146. // <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
  3147. // <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
  3148. template <typename Derived, typename Alloc>
  3149. Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
  3150. if (consumeIf('U')) {
  3151. StringView Qual = parseBareSourceName();
  3152. if (Qual.empty())
  3153. return nullptr;
  3154. // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
  3155. if (Qual.startsWith("objcproto")) {
  3156. StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
  3157. StringView Proto;
  3158. {
  3159. ScopedOverride<const char *> SaveFirst(First, ProtoSourceName.begin()),
  3160. SaveLast(Last, ProtoSourceName.end());
  3161. Proto = parseBareSourceName();
  3162. }
  3163. if (Proto.empty())
  3164. return nullptr;
  3165. Node *Child = getDerived().parseQualifiedType();
  3166. if (Child == nullptr)
  3167. return nullptr;
  3168. return make<ObjCProtoName>(Child, Proto);
  3169. }
  3170. Node *TA = nullptr;
  3171. if (look() == 'I') {
  3172. TA = getDerived().parseTemplateArgs();
  3173. if (TA == nullptr)
  3174. return nullptr;
  3175. }
  3176. Node *Child = getDerived().parseQualifiedType();
  3177. if (Child == nullptr)
  3178. return nullptr;
  3179. return make<VendorExtQualType>(Child, Qual, TA);
  3180. }
  3181. Qualifiers Quals = parseCVQualifiers();
  3182. Node *Ty = getDerived().parseType();
  3183. if (Ty == nullptr)
  3184. return nullptr;
  3185. if (Quals != QualNone)
  3186. Ty = make<QualType>(Ty, Quals);
  3187. return Ty;
  3188. }
  3189. // <type> ::= <builtin-type>
  3190. // ::= <qualified-type>
  3191. // ::= <function-type>
  3192. // ::= <class-enum-type>
  3193. // ::= <array-type>
  3194. // ::= <pointer-to-member-type>
  3195. // ::= <template-param>
  3196. // ::= <template-template-param> <template-args>
  3197. // ::= <decltype>
  3198. // ::= P <type> # pointer
  3199. // ::= R <type> # l-value reference
  3200. // ::= O <type> # r-value reference (C++11)
  3201. // ::= C <type> # complex pair (C99)
  3202. // ::= G <type> # imaginary (C99)
  3203. // ::= <substitution> # See Compression below
  3204. // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
  3205. // extension ::= <vector-type> # <vector-type> starts with Dv
  3206. //
  3207. // <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
  3208. // <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
  3209. template <typename Derived, typename Alloc>
  3210. Node *AbstractManglingParser<Derived, Alloc>::parseType() {
  3211. Node *Result = nullptr;
  3212. switch (look()) {
  3213. // ::= <qualified-type>
  3214. case 'r':
  3215. case 'V':
  3216. case 'K': {
  3217. unsigned AfterQuals = 0;
  3218. if (look(AfterQuals) == 'r') ++AfterQuals;
  3219. if (look(AfterQuals) == 'V') ++AfterQuals;
  3220. if (look(AfterQuals) == 'K') ++AfterQuals;
  3221. if (look(AfterQuals) == 'F' ||
  3222. (look(AfterQuals) == 'D' &&
  3223. (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
  3224. look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
  3225. Result = getDerived().parseFunctionType();
  3226. break;
  3227. }
  3228. DEMANGLE_FALLTHROUGH;
  3229. }
  3230. case 'U': {
  3231. Result = getDerived().parseQualifiedType();
  3232. break;
  3233. }
  3234. // <builtin-type> ::= v # void
  3235. case 'v':
  3236. ++First;
  3237. return make<NameType>("void");
  3238. // ::= w # wchar_t
  3239. case 'w':
  3240. ++First;
  3241. return make<NameType>("wchar_t");
  3242. // ::= b # bool
  3243. case 'b':
  3244. ++First;
  3245. return make<NameType>("bool");
  3246. // ::= c # char
  3247. case 'c':
  3248. ++First;
  3249. return make<NameType>("char");
  3250. // ::= a # signed char
  3251. case 'a':
  3252. ++First;
  3253. return make<NameType>("signed char");
  3254. // ::= h # unsigned char
  3255. case 'h':
  3256. ++First;
  3257. return make<NameType>("unsigned char");
  3258. // ::= s # short
  3259. case 's':
  3260. ++First;
  3261. return make<NameType>("short");
  3262. // ::= t # unsigned short
  3263. case 't':
  3264. ++First;
  3265. return make<NameType>("unsigned short");
  3266. // ::= i # int
  3267. case 'i':
  3268. ++First;
  3269. return make<NameType>("int");
  3270. // ::= j # unsigned int
  3271. case 'j':
  3272. ++First;
  3273. return make<NameType>("unsigned int");
  3274. // ::= l # long
  3275. case 'l':
  3276. ++First;
  3277. return make<NameType>("long");
  3278. // ::= m # unsigned long
  3279. case 'm':
  3280. ++First;
  3281. return make<NameType>("unsigned long");
  3282. // ::= x # long long, __int64
  3283. case 'x':
  3284. ++First;
  3285. return make<NameType>("long long");
  3286. // ::= y # unsigned long long, __int64
  3287. case 'y':
  3288. ++First;
  3289. return make<NameType>("unsigned long long");
  3290. // ::= n # __int128
  3291. case 'n':
  3292. ++First;
  3293. return make<NameType>("__int128");
  3294. // ::= o # unsigned __int128
  3295. case 'o':
  3296. ++First;
  3297. return make<NameType>("unsigned __int128");
  3298. // ::= f # float
  3299. case 'f':
  3300. ++First;
  3301. return make<NameType>("float");
  3302. // ::= d # double
  3303. case 'd':
  3304. ++First;
  3305. return make<NameType>("double");
  3306. // ::= e # long double, __float80
  3307. case 'e':
  3308. ++First;
  3309. return make<NameType>("long double");
  3310. // ::= g # __float128
  3311. case 'g':
  3312. ++First;
  3313. return make<NameType>("__float128");
  3314. // ::= z # ellipsis
  3315. case 'z':
  3316. ++First;
  3317. return make<NameType>("...");
  3318. // <builtin-type> ::= u <source-name> # vendor extended type
  3319. case 'u': {
  3320. ++First;
  3321. StringView Res = parseBareSourceName();
  3322. if (Res.empty())
  3323. return nullptr;
  3324. // Typically, <builtin-type>s are not considered substitution candidates,
  3325. // but the exception to that exception is vendor extended types (Itanium C++
  3326. // ABI 5.9.1).
  3327. Result = make<NameType>(Res);
  3328. break;
  3329. }
  3330. case 'D':
  3331. switch (look(1)) {
  3332. // ::= Dd # IEEE 754r decimal floating point (64 bits)
  3333. case 'd':
  3334. First += 2;
  3335. return make<NameType>("decimal64");
  3336. // ::= De # IEEE 754r decimal floating point (128 bits)
  3337. case 'e':
  3338. First += 2;
  3339. return make<NameType>("decimal128");
  3340. // ::= Df # IEEE 754r decimal floating point (32 bits)
  3341. case 'f':
  3342. First += 2;
  3343. return make<NameType>("decimal32");
  3344. // ::= Dh # IEEE 754r half-precision floating point (16 bits)
  3345. case 'h':
  3346. First += 2;
  3347. return make<NameType>("half");
  3348. // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point (N bits)
  3349. case 'F': {
  3350. First += 2;
  3351. Node *DimensionNumber = make<NameType>(parseNumber());
  3352. if (!DimensionNumber)
  3353. return nullptr;
  3354. if (!consumeIf('_'))
  3355. return nullptr;
  3356. return make<BinaryFPType>(DimensionNumber);
  3357. }
  3358. // ::= DB <number> _ # C23 signed _BitInt(N)
  3359. // ::= DB <instantiation-dependent expression> _ # C23 signed _BitInt(N)
  3360. // ::= DU <number> _ # C23 unsigned _BitInt(N)
  3361. // ::= DU <instantiation-dependent expression> _ # C23 unsigned _BitInt(N)
  3362. case 'B':
  3363. case 'U': {
  3364. bool Signed = look(1) == 'B';
  3365. First += 2;
  3366. Node *Size = std::isdigit(look()) ? make<NameType>(parseNumber())
  3367. : getDerived().parseExpr();
  3368. if (!Size)
  3369. return nullptr;
  3370. if (!consumeIf('_'))
  3371. return nullptr;
  3372. return make<BitIntType>(Size, Signed);
  3373. }
  3374. // ::= Di # char32_t
  3375. case 'i':
  3376. First += 2;
  3377. return make<NameType>("char32_t");
  3378. // ::= Ds # char16_t
  3379. case 's':
  3380. First += 2;
  3381. return make<NameType>("char16_t");
  3382. // ::= Du # char8_t (C++2a, not yet in the Itanium spec)
  3383. case 'u':
  3384. First += 2;
  3385. return make<NameType>("char8_t");
  3386. // ::= Da # auto (in dependent new-expressions)
  3387. case 'a':
  3388. First += 2;
  3389. return make<NameType>("auto");
  3390. // ::= Dc # decltype(auto)
  3391. case 'c':
  3392. First += 2;
  3393. return make<NameType>("decltype(auto)");
  3394. // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
  3395. case 'n':
  3396. First += 2;
  3397. return make<NameType>("std::nullptr_t");
  3398. // ::= <decltype>
  3399. case 't':
  3400. case 'T': {
  3401. Result = getDerived().parseDecltype();
  3402. break;
  3403. }
  3404. // extension ::= <vector-type> # <vector-type> starts with Dv
  3405. case 'v': {
  3406. Result = getDerived().parseVectorType();
  3407. break;
  3408. }
  3409. // ::= Dp <type> # pack expansion (C++0x)
  3410. case 'p': {
  3411. First += 2;
  3412. Node *Child = getDerived().parseType();
  3413. if (!Child)
  3414. return nullptr;
  3415. Result = make<ParameterPackExpansion>(Child);
  3416. break;
  3417. }
  3418. // Exception specifier on a function type.
  3419. case 'o':
  3420. case 'O':
  3421. case 'w':
  3422. // Transaction safe function type.
  3423. case 'x':
  3424. Result = getDerived().parseFunctionType();
  3425. break;
  3426. }
  3427. break;
  3428. // ::= <function-type>
  3429. case 'F': {
  3430. Result = getDerived().parseFunctionType();
  3431. break;
  3432. }
  3433. // ::= <array-type>
  3434. case 'A': {
  3435. Result = getDerived().parseArrayType();
  3436. break;
  3437. }
  3438. // ::= <pointer-to-member-type>
  3439. case 'M': {
  3440. Result = getDerived().parsePointerToMemberType();
  3441. break;
  3442. }
  3443. // ::= <template-param>
  3444. case 'T': {
  3445. // This could be an elaborate type specifier on a <class-enum-type>.
  3446. if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
  3447. Result = getDerived().parseClassEnumType();
  3448. break;
  3449. }
  3450. Result = getDerived().parseTemplateParam();
  3451. if (Result == nullptr)
  3452. return nullptr;
  3453. // Result could be either of:
  3454. // <type> ::= <template-param>
  3455. // <type> ::= <template-template-param> <template-args>
  3456. //
  3457. // <template-template-param> ::= <template-param>
  3458. // ::= <substitution>
  3459. //
  3460. // If this is followed by some <template-args>, and we're permitted to
  3461. // parse them, take the second production.
  3462. if (TryToParseTemplateArgs && look() == 'I') {
  3463. Node *TA = getDerived().parseTemplateArgs();
  3464. if (TA == nullptr)
  3465. return nullptr;
  3466. Result = make<NameWithTemplateArgs>(Result, TA);
  3467. }
  3468. break;
  3469. }
  3470. // ::= P <type> # pointer
  3471. case 'P': {
  3472. ++First;
  3473. Node *Ptr = getDerived().parseType();
  3474. if (Ptr == nullptr)
  3475. return nullptr;
  3476. Result = make<PointerType>(Ptr);
  3477. break;
  3478. }
  3479. // ::= R <type> # l-value reference
  3480. case 'R': {
  3481. ++First;
  3482. Node *Ref = getDerived().parseType();
  3483. if (Ref == nullptr)
  3484. return nullptr;
  3485. Result = make<ReferenceType>(Ref, ReferenceKind::LValue);
  3486. break;
  3487. }
  3488. // ::= O <type> # r-value reference (C++11)
  3489. case 'O': {
  3490. ++First;
  3491. Node *Ref = getDerived().parseType();
  3492. if (Ref == nullptr)
  3493. return nullptr;
  3494. Result = make<ReferenceType>(Ref, ReferenceKind::RValue);
  3495. break;
  3496. }
  3497. // ::= C <type> # complex pair (C99)
  3498. case 'C': {
  3499. ++First;
  3500. Node *P = getDerived().parseType();
  3501. if (P == nullptr)
  3502. return nullptr;
  3503. Result = make<PostfixQualifiedType>(P, " complex");
  3504. break;
  3505. }
  3506. // ::= G <type> # imaginary (C99)
  3507. case 'G': {
  3508. ++First;
  3509. Node *P = getDerived().parseType();
  3510. if (P == nullptr)
  3511. return P;
  3512. Result = make<PostfixQualifiedType>(P, " imaginary");
  3513. break;
  3514. }
  3515. // ::= <substitution> # See Compression below
  3516. case 'S': {
  3517. if (look(1) != 't') {
  3518. bool IsSubst = false;
  3519. Result = getDerived().parseUnscopedName(nullptr, &IsSubst);
  3520. if (!Result)
  3521. return nullptr;
  3522. // Sub could be either of:
  3523. // <type> ::= <substitution>
  3524. // <type> ::= <template-template-param> <template-args>
  3525. //
  3526. // <template-template-param> ::= <template-param>
  3527. // ::= <substitution>
  3528. //
  3529. // If this is followed by some <template-args>, and we're permitted to
  3530. // parse them, take the second production.
  3531. if (look() == 'I' && (!IsSubst || TryToParseTemplateArgs)) {
  3532. if (!IsSubst)
  3533. Subs.push_back(Result);
  3534. Node *TA = getDerived().parseTemplateArgs();
  3535. if (TA == nullptr)
  3536. return nullptr;
  3537. Result = make<NameWithTemplateArgs>(Result, TA);
  3538. } else if (IsSubst) {
  3539. // If all we parsed was a substitution, don't re-insert into the
  3540. // substitution table.
  3541. return Result;
  3542. }
  3543. break;
  3544. }
  3545. DEMANGLE_FALLTHROUGH;
  3546. }
  3547. // ::= <class-enum-type>
  3548. default: {
  3549. Result = getDerived().parseClassEnumType();
  3550. break;
  3551. }
  3552. }
  3553. // If we parsed a type, insert it into the substitution table. Note that all
  3554. // <builtin-type>s and <substitution>s have already bailed out, because they
  3555. // don't get substitutions.
  3556. if (Result != nullptr)
  3557. Subs.push_back(Result);
  3558. return Result;
  3559. }
  3560. template <typename Derived, typename Alloc>
  3561. Node *AbstractManglingParser<Derived, Alloc>::parsePrefixExpr(StringView Kind,
  3562. Node::Prec Prec) {
  3563. Node *E = getDerived().parseExpr();
  3564. if (E == nullptr)
  3565. return nullptr;
  3566. return make<PrefixExpr>(Kind, E, Prec);
  3567. }
  3568. template <typename Derived, typename Alloc>
  3569. Node *AbstractManglingParser<Derived, Alloc>::parseBinaryExpr(StringView Kind,
  3570. Node::Prec Prec) {
  3571. Node *LHS = getDerived().parseExpr();
  3572. if (LHS == nullptr)
  3573. return nullptr;
  3574. Node *RHS = getDerived().parseExpr();
  3575. if (RHS == nullptr)
  3576. return nullptr;
  3577. return make<BinaryExpr>(LHS, Kind, RHS, Prec);
  3578. }
  3579. template <typename Derived, typename Alloc>
  3580. Node *
  3581. AbstractManglingParser<Derived, Alloc>::parseIntegerLiteral(StringView Lit) {
  3582. StringView Tmp = parseNumber(true);
  3583. if (!Tmp.empty() && consumeIf('E'))
  3584. return make<IntegerLiteral>(Lit, Tmp);
  3585. return nullptr;
  3586. }
  3587. // <CV-Qualifiers> ::= [r] [V] [K]
  3588. template <typename Alloc, typename Derived>
  3589. Qualifiers AbstractManglingParser<Alloc, Derived>::parseCVQualifiers() {
  3590. Qualifiers CVR = QualNone;
  3591. if (consumeIf('r'))
  3592. CVR |= QualRestrict;
  3593. if (consumeIf('V'))
  3594. CVR |= QualVolatile;
  3595. if (consumeIf('K'))
  3596. CVR |= QualConst;
  3597. return CVR;
  3598. }
  3599. // <function-param> ::= fp <top-level CV-Qualifiers> _ # L == 0, first parameter
  3600. // ::= fp <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L == 0, second and later parameters
  3601. // ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> _ # L > 0, first parameter
  3602. // ::= fL <L-1 non-negative number> p <top-level CV-Qualifiers> <parameter-2 non-negative number> _ # L > 0, second and later parameters
  3603. // ::= fpT # 'this' expression (not part of standard?)
  3604. template <typename Derived, typename Alloc>
  3605. Node *AbstractManglingParser<Derived, Alloc>::parseFunctionParam() {
  3606. if (consumeIf("fpT"))
  3607. return make<NameType>("this");
  3608. if (consumeIf("fp")) {
  3609. parseCVQualifiers();
  3610. StringView Num = parseNumber();
  3611. if (!consumeIf('_'))
  3612. return nullptr;
  3613. return make<FunctionParam>(Num);
  3614. }
  3615. if (consumeIf("fL")) {
  3616. if (parseNumber().empty())
  3617. return nullptr;
  3618. if (!consumeIf('p'))
  3619. return nullptr;
  3620. parseCVQualifiers();
  3621. StringView Num = parseNumber();
  3622. if (!consumeIf('_'))
  3623. return nullptr;
  3624. return make<FunctionParam>(Num);
  3625. }
  3626. return nullptr;
  3627. }
  3628. // cv <type> <expression> # conversion with one argument
  3629. // cv <type> _ <expression>* E # conversion with a different number of arguments
  3630. template <typename Derived, typename Alloc>
  3631. Node *AbstractManglingParser<Derived, Alloc>::parseConversionExpr() {
  3632. if (!consumeIf("cv"))
  3633. return nullptr;
  3634. Node *Ty;
  3635. {
  3636. ScopedOverride<bool> SaveTemp(TryToParseTemplateArgs, false);
  3637. Ty = getDerived().parseType();
  3638. }
  3639. if (Ty == nullptr)
  3640. return nullptr;
  3641. if (consumeIf('_')) {
  3642. size_t ExprsBegin = Names.size();
  3643. while (!consumeIf('E')) {
  3644. Node *E = getDerived().parseExpr();
  3645. if (E == nullptr)
  3646. return E;
  3647. Names.push_back(E);
  3648. }
  3649. NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
  3650. return make<ConversionExpr>(Ty, Exprs);
  3651. }
  3652. Node *E[1] = {getDerived().parseExpr()};
  3653. if (E[0] == nullptr)
  3654. return nullptr;
  3655. return make<ConversionExpr>(Ty, makeNodeArray(E, E + 1));
  3656. }
  3657. // <expr-primary> ::= L <type> <value number> E # integer literal
  3658. // ::= L <type> <value float> E # floating literal
  3659. // ::= L <string type> E # string literal
  3660. // ::= L <nullptr type> E # nullptr literal (i.e., "LDnE")
  3661. // ::= L <lambda type> E # lambda expression
  3662. // FIXME: ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C 2000)
  3663. // ::= L <mangled-name> E # external name
  3664. template <typename Derived, typename Alloc>
  3665. Node *AbstractManglingParser<Derived, Alloc>::parseExprPrimary() {
  3666. if (!consumeIf('L'))
  3667. return nullptr;
  3668. switch (look()) {
  3669. case 'w':
  3670. ++First;
  3671. return getDerived().parseIntegerLiteral("wchar_t");
  3672. case 'b':
  3673. if (consumeIf("b0E"))
  3674. return make<BoolExpr>(0);
  3675. if (consumeIf("b1E"))
  3676. return make<BoolExpr>(1);
  3677. return nullptr;
  3678. case 'c':
  3679. ++First;
  3680. return getDerived().parseIntegerLiteral("char");
  3681. case 'a':
  3682. ++First;
  3683. return getDerived().parseIntegerLiteral("signed char");
  3684. case 'h':
  3685. ++First;
  3686. return getDerived().parseIntegerLiteral("unsigned char");
  3687. case 's':
  3688. ++First;
  3689. return getDerived().parseIntegerLiteral("short");
  3690. case 't':
  3691. ++First;
  3692. return getDerived().parseIntegerLiteral("unsigned short");
  3693. case 'i':
  3694. ++First;
  3695. return getDerived().parseIntegerLiteral("");
  3696. case 'j':
  3697. ++First;
  3698. return getDerived().parseIntegerLiteral("u");
  3699. case 'l':
  3700. ++First;
  3701. return getDerived().parseIntegerLiteral("l");
  3702. case 'm':
  3703. ++First;
  3704. return getDerived().parseIntegerLiteral("ul");
  3705. case 'x':
  3706. ++First;
  3707. return getDerived().parseIntegerLiteral("ll");
  3708. case 'y':
  3709. ++First;
  3710. return getDerived().parseIntegerLiteral("ull");
  3711. case 'n':
  3712. ++First;
  3713. return getDerived().parseIntegerLiteral("__int128");
  3714. case 'o':
  3715. ++First;
  3716. return getDerived().parseIntegerLiteral("unsigned __int128");
  3717. case 'f':
  3718. ++First;
  3719. return getDerived().template parseFloatingLiteral<float>();
  3720. case 'd':
  3721. ++First;
  3722. return getDerived().template parseFloatingLiteral<double>();
  3723. case 'e':
  3724. ++First;
  3725. #if defined(__powerpc__) || defined(__s390__)
  3726. // Handle cases where long doubles encoded with e have the same size
  3727. // and representation as doubles.
  3728. return getDerived().template parseFloatingLiteral<double>();
  3729. #else
  3730. return getDerived().template parseFloatingLiteral<long double>();
  3731. #endif
  3732. case '_':
  3733. if (consumeIf("_Z")) {
  3734. Node *R = getDerived().parseEncoding();
  3735. if (R != nullptr && consumeIf('E'))
  3736. return R;
  3737. }
  3738. return nullptr;
  3739. case 'A': {
  3740. Node *T = getDerived().parseType();
  3741. if (T == nullptr)
  3742. return nullptr;
  3743. // FIXME: We need to include the string contents in the mangling.
  3744. if (consumeIf('E'))
  3745. return make<StringLiteral>(T);
  3746. return nullptr;
  3747. }
  3748. case 'D':
  3749. if (consumeIf("Dn") && (consumeIf('0'), consumeIf('E')))
  3750. return make<NameType>("nullptr");
  3751. return nullptr;
  3752. case 'T':
  3753. // Invalid mangled name per
  3754. // http://sourcerytools.com/pipermail/cxx-abi-dev/2011-August/002422.html
  3755. return nullptr;
  3756. case 'U': {
  3757. // FIXME: Should we support LUb... for block literals?
  3758. if (look(1) != 'l')
  3759. return nullptr;
  3760. Node *T = parseUnnamedTypeName(nullptr);
  3761. if (!T || !consumeIf('E'))
  3762. return nullptr;
  3763. return make<LambdaExpr>(T);
  3764. }
  3765. default: {
  3766. // might be named type
  3767. Node *T = getDerived().parseType();
  3768. if (T == nullptr)
  3769. return nullptr;
  3770. StringView N = parseNumber(/*AllowNegative=*/true);
  3771. if (N.empty())
  3772. return nullptr;
  3773. if (!consumeIf('E'))
  3774. return nullptr;
  3775. return make<EnumLiteral>(T, N);
  3776. }
  3777. }
  3778. }
  3779. // <braced-expression> ::= <expression>
  3780. // ::= di <field source-name> <braced-expression> # .name = expr
  3781. // ::= dx <index expression> <braced-expression> # [expr] = expr
  3782. // ::= dX <range begin expression> <range end expression> <braced-expression>
  3783. template <typename Derived, typename Alloc>
  3784. Node *AbstractManglingParser<Derived, Alloc>::parseBracedExpr() {
  3785. if (look() == 'd') {
  3786. switch (look(1)) {
  3787. case 'i': {
  3788. First += 2;
  3789. Node *Field = getDerived().parseSourceName(/*NameState=*/nullptr);
  3790. if (Field == nullptr)
  3791. return nullptr;
  3792. Node *Init = getDerived().parseBracedExpr();
  3793. if (Init == nullptr)
  3794. return nullptr;
  3795. return make<BracedExpr>(Field, Init, /*isArray=*/false);
  3796. }
  3797. case 'x': {
  3798. First += 2;
  3799. Node *Index = getDerived().parseExpr();
  3800. if (Index == nullptr)
  3801. return nullptr;
  3802. Node *Init = getDerived().parseBracedExpr();
  3803. if (Init == nullptr)
  3804. return nullptr;
  3805. return make<BracedExpr>(Index, Init, /*isArray=*/true);
  3806. }
  3807. case 'X': {
  3808. First += 2;
  3809. Node *RangeBegin = getDerived().parseExpr();
  3810. if (RangeBegin == nullptr)
  3811. return nullptr;
  3812. Node *RangeEnd = getDerived().parseExpr();
  3813. if (RangeEnd == nullptr)
  3814. return nullptr;
  3815. Node *Init = getDerived().parseBracedExpr();
  3816. if (Init == nullptr)
  3817. return nullptr;
  3818. return make<BracedRangeExpr>(RangeBegin, RangeEnd, Init);
  3819. }
  3820. }
  3821. }
  3822. return getDerived().parseExpr();
  3823. }
  3824. // (not yet in the spec)
  3825. // <fold-expr> ::= fL <binary-operator-name> <expression> <expression>
  3826. // ::= fR <binary-operator-name> <expression> <expression>
  3827. // ::= fl <binary-operator-name> <expression>
  3828. // ::= fr <binary-operator-name> <expression>
  3829. template <typename Derived, typename Alloc>
  3830. Node *AbstractManglingParser<Derived, Alloc>::parseFoldExpr() {
  3831. if (!consumeIf('f'))
  3832. return nullptr;
  3833. bool IsLeftFold = false, HasInitializer = false;
  3834. switch (look()) {
  3835. default:
  3836. return nullptr;
  3837. case 'L':
  3838. IsLeftFold = true;
  3839. HasInitializer = true;
  3840. break;
  3841. case 'R':
  3842. HasInitializer = true;
  3843. break;
  3844. case 'l':
  3845. IsLeftFold = true;
  3846. break;
  3847. case 'r':
  3848. break;
  3849. }
  3850. ++First;
  3851. const auto *Op = parseOperatorEncoding();
  3852. if (!Op)
  3853. return nullptr;
  3854. if (!(Op->getKind() == OperatorInfo::Binary
  3855. || (Op->getKind() == OperatorInfo::Member
  3856. && Op->getName().back() == '*')))
  3857. return nullptr;
  3858. Node *Pack = getDerived().parseExpr();
  3859. if (Pack == nullptr)
  3860. return nullptr;
  3861. Node *Init = nullptr;
  3862. if (HasInitializer) {
  3863. Init = getDerived().parseExpr();
  3864. if (Init == nullptr)
  3865. return nullptr;
  3866. }
  3867. if (IsLeftFold && Init)
  3868. std::swap(Pack, Init);
  3869. return make<FoldExpr>(IsLeftFold, Op->getSymbol(), Pack, Init);
  3870. }
  3871. // <expression> ::= mc <parameter type> <expr> [<offset number>] E
  3872. //
  3873. // Not yet in the spec: https://github.com/itanium-cxx-abi/cxx-abi/issues/47
  3874. template <typename Derived, typename Alloc>
  3875. Node *
  3876. AbstractManglingParser<Derived, Alloc>::parsePointerToMemberConversionExpr(
  3877. Node::Prec Prec) {
  3878. Node *Ty = getDerived().parseType();
  3879. if (!Ty)
  3880. return nullptr;
  3881. Node *Expr = getDerived().parseExpr();
  3882. if (!Expr)
  3883. return nullptr;
  3884. StringView Offset = getDerived().parseNumber(true);
  3885. if (!consumeIf('E'))
  3886. return nullptr;
  3887. return make<PointerToMemberConversionExpr>(Ty, Expr, Offset, Prec);
  3888. }
  3889. // <expression> ::= so <referent type> <expr> [<offset number>] <union-selector>* [p] E
  3890. // <union-selector> ::= _ [<number>]
  3891. //
  3892. // Not yet in the spec: https://github.com/itanium-cxx-abi/cxx-abi/issues/47
  3893. template <typename Derived, typename Alloc>
  3894. Node *AbstractManglingParser<Derived, Alloc>::parseSubobjectExpr() {
  3895. Node *Ty = getDerived().parseType();
  3896. if (!Ty)
  3897. return nullptr;
  3898. Node *Expr = getDerived().parseExpr();
  3899. if (!Expr)
  3900. return nullptr;
  3901. StringView Offset = getDerived().parseNumber(true);
  3902. size_t SelectorsBegin = Names.size();
  3903. while (consumeIf('_')) {
  3904. Node *Selector = make<NameType>(parseNumber());
  3905. if (!Selector)
  3906. return nullptr;
  3907. Names.push_back(Selector);
  3908. }
  3909. bool OnePastTheEnd = consumeIf('p');
  3910. if (!consumeIf('E'))
  3911. return nullptr;
  3912. return make<SubobjectExpr>(
  3913. Ty, Expr, Offset, popTrailingNodeArray(SelectorsBegin), OnePastTheEnd);
  3914. }
  3915. // <expression> ::= <unary operator-name> <expression>
  3916. // ::= <binary operator-name> <expression> <expression>
  3917. // ::= <ternary operator-name> <expression> <expression> <expression>
  3918. // ::= cl <expression>+ E # call
  3919. // ::= cv <type> <expression> # conversion with one argument
  3920. // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
  3921. // ::= [gs] nw <expression>* _ <type> E # new (expr-list) type
  3922. // ::= [gs] nw <expression>* _ <type> <initializer> # new (expr-list) type (init)
  3923. // ::= [gs] na <expression>* _ <type> E # new[] (expr-list) type
  3924. // ::= [gs] na <expression>* _ <type> <initializer> # new[] (expr-list) type (init)
  3925. // ::= [gs] dl <expression> # delete expression
  3926. // ::= [gs] da <expression> # delete[] expression
  3927. // ::= pp_ <expression> # prefix ++
  3928. // ::= mm_ <expression> # prefix --
  3929. // ::= ti <type> # typeid (type)
  3930. // ::= te <expression> # typeid (expression)
  3931. // ::= dc <type> <expression> # dynamic_cast<type> (expression)
  3932. // ::= sc <type> <expression> # static_cast<type> (expression)
  3933. // ::= cc <type> <expression> # const_cast<type> (expression)
  3934. // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
  3935. // ::= st <type> # sizeof (a type)
  3936. // ::= sz <expression> # sizeof (an expression)
  3937. // ::= at <type> # alignof (a type)
  3938. // ::= az <expression> # alignof (an expression)
  3939. // ::= nx <expression> # noexcept (expression)
  3940. // ::= <template-param>
  3941. // ::= <function-param>
  3942. // ::= dt <expression> <unresolved-name> # expr.name
  3943. // ::= pt <expression> <unresolved-name> # expr->name
  3944. // ::= ds <expression> <expression> # expr.*expr
  3945. // ::= sZ <template-param> # size of a parameter pack
  3946. // ::= sZ <function-param> # size of a function parameter pack
  3947. // ::= sP <template-arg>* E # sizeof...(T), size of a captured template parameter pack from an alias template
  3948. // ::= sp <expression> # pack expansion
  3949. // ::= tw <expression> # throw expression
  3950. // ::= tr # throw with no operand (rethrow)
  3951. // ::= <unresolved-name> # f(p), N::f(p), ::f(p),
  3952. // # freestanding dependent name (e.g., T::x),
  3953. // # objectless nonstatic member reference
  3954. // ::= fL <binary-operator-name> <expression> <expression>
  3955. // ::= fR <binary-operator-name> <expression> <expression>
  3956. // ::= fl <binary-operator-name> <expression>
  3957. // ::= fr <binary-operator-name> <expression>
  3958. // ::= <expr-primary>
  3959. template <typename Derived, typename Alloc>
  3960. Node *AbstractManglingParser<Derived, Alloc>::parseExpr() {
  3961. bool Global = consumeIf("gs");
  3962. const auto *Op = parseOperatorEncoding();
  3963. if (Op) {
  3964. auto Sym = Op->getSymbol();
  3965. switch (Op->getKind()) {
  3966. case OperatorInfo::Binary:
  3967. // Binary operator: lhs @ rhs
  3968. return getDerived().parseBinaryExpr(Sym, Op->getPrecedence());
  3969. case OperatorInfo::Prefix:
  3970. // Prefix unary operator: @ expr
  3971. return getDerived().parsePrefixExpr(Sym, Op->getPrecedence());
  3972. case OperatorInfo::Postfix: {
  3973. // Postfix unary operator: expr @
  3974. if (consumeIf('_'))
  3975. return getDerived().parsePrefixExpr(Sym, Op->getPrecedence());
  3976. Node *Ex = getDerived().parseExpr();
  3977. if (Ex == nullptr)
  3978. return nullptr;
  3979. return make<PostfixExpr>(Ex, Sym, Op->getPrecedence());
  3980. }
  3981. case OperatorInfo::Array: {
  3982. // Array Index: lhs [ rhs ]
  3983. Node *Base = getDerived().parseExpr();
  3984. if (Base == nullptr)
  3985. return nullptr;
  3986. Node *Index = getDerived().parseExpr();
  3987. if (Index == nullptr)
  3988. return nullptr;
  3989. return make<ArraySubscriptExpr>(Base, Index, Op->getPrecedence());
  3990. }
  3991. case OperatorInfo::Member: {
  3992. // Member access lhs @ rhs
  3993. Node *LHS = getDerived().parseExpr();
  3994. if (LHS == nullptr)
  3995. return nullptr;
  3996. Node *RHS = getDerived().parseExpr();
  3997. if (RHS == nullptr)
  3998. return nullptr;
  3999. return make<MemberExpr>(LHS, Sym, RHS, Op->getPrecedence());
  4000. }
  4001. case OperatorInfo::New: {
  4002. // New
  4003. // # new (expr-list) type [(init)]
  4004. // [gs] nw <expression>* _ <type> [pi <expression>*] E
  4005. // # new[] (expr-list) type [(init)]
  4006. // [gs] na <expression>* _ <type> [pi <expression>*] E
  4007. size_t Exprs = Names.size();
  4008. while (!consumeIf('_')) {
  4009. Node *Ex = getDerived().parseExpr();
  4010. if (Ex == nullptr)
  4011. return nullptr;
  4012. Names.push_back(Ex);
  4013. }
  4014. NodeArray ExprList = popTrailingNodeArray(Exprs);
  4015. Node *Ty = getDerived().parseType();
  4016. if (Ty == nullptr)
  4017. return nullptr;
  4018. bool HaveInits = consumeIf("pi");
  4019. size_t InitsBegin = Names.size();
  4020. while (!consumeIf('E')) {
  4021. if (!HaveInits)
  4022. return nullptr;
  4023. Node *Init = getDerived().parseExpr();
  4024. if (Init == nullptr)
  4025. return Init;
  4026. Names.push_back(Init);
  4027. }
  4028. NodeArray Inits = popTrailingNodeArray(InitsBegin);
  4029. return make<NewExpr>(ExprList, Ty, Inits, Global,
  4030. /*IsArray=*/Op->getFlag(), Op->getPrecedence());
  4031. }
  4032. case OperatorInfo::Del: {
  4033. // Delete
  4034. Node *Ex = getDerived().parseExpr();
  4035. if (Ex == nullptr)
  4036. return nullptr;
  4037. return make<DeleteExpr>(Ex, Global, /*IsArray=*/Op->getFlag(),
  4038. Op->getPrecedence());
  4039. }
  4040. case OperatorInfo::Call: {
  4041. // Function Call
  4042. Node *Callee = getDerived().parseExpr();
  4043. if (Callee == nullptr)
  4044. return nullptr;
  4045. size_t ExprsBegin = Names.size();
  4046. while (!consumeIf('E')) {
  4047. Node *E = getDerived().parseExpr();
  4048. if (E == nullptr)
  4049. return nullptr;
  4050. Names.push_back(E);
  4051. }
  4052. return make<CallExpr>(Callee, popTrailingNodeArray(ExprsBegin),
  4053. Op->getPrecedence());
  4054. }
  4055. case OperatorInfo::CCast: {
  4056. // C Cast: (type)expr
  4057. Node *Ty;
  4058. {
  4059. ScopedOverride<bool> SaveTemp(TryToParseTemplateArgs, false);
  4060. Ty = getDerived().parseType();
  4061. }
  4062. if (Ty == nullptr)
  4063. return nullptr;
  4064. size_t ExprsBegin = Names.size();
  4065. bool IsMany = consumeIf('_');
  4066. while (!consumeIf('E')) {
  4067. Node *E = getDerived().parseExpr();
  4068. if (E == nullptr)
  4069. return E;
  4070. Names.push_back(E);
  4071. if (!IsMany)
  4072. break;
  4073. }
  4074. NodeArray Exprs = popTrailingNodeArray(ExprsBegin);
  4075. if (!IsMany && Exprs.size() != 1)
  4076. return nullptr;
  4077. return make<ConversionExpr>(Ty, Exprs, Op->getPrecedence());
  4078. }
  4079. case OperatorInfo::Conditional: {
  4080. // Conditional operator: expr ? expr : expr
  4081. Node *Cond = getDerived().parseExpr();
  4082. if (Cond == nullptr)
  4083. return nullptr;
  4084. Node *LHS = getDerived().parseExpr();
  4085. if (LHS == nullptr)
  4086. return nullptr;
  4087. Node *RHS = getDerived().parseExpr();
  4088. if (RHS == nullptr)
  4089. return nullptr;
  4090. return make<ConditionalExpr>(Cond, LHS, RHS, Op->getPrecedence());
  4091. }
  4092. case OperatorInfo::NamedCast: {
  4093. // Named cast operation, @<type>(expr)
  4094. Node *Ty = getDerived().parseType();
  4095. if (Ty == nullptr)
  4096. return nullptr;
  4097. Node *Ex = getDerived().parseExpr();
  4098. if (Ex == nullptr)
  4099. return nullptr;
  4100. return make<CastExpr>(Sym, Ty, Ex, Op->getPrecedence());
  4101. }
  4102. case OperatorInfo::OfIdOp: {
  4103. // [sizeof/alignof/typeid] ( <type>|<expr> )
  4104. Node *Arg =
  4105. Op->getFlag() ? getDerived().parseType() : getDerived().parseExpr();
  4106. if (!Arg)
  4107. return nullptr;
  4108. return make<EnclosingExpr>(Sym, Arg, Op->getPrecedence());
  4109. }
  4110. case OperatorInfo::NameOnly: {
  4111. // Not valid as an expression operand.
  4112. return nullptr;
  4113. }
  4114. }
  4115. DEMANGLE_UNREACHABLE;
  4116. }
  4117. if (numLeft() < 2)
  4118. return nullptr;
  4119. if (look() == 'L')
  4120. return getDerived().parseExprPrimary();
  4121. if (look() == 'T')
  4122. return getDerived().parseTemplateParam();
  4123. if (look() == 'f') {
  4124. // Disambiguate a fold expression from a <function-param>.
  4125. if (look(1) == 'p' || (look(1) == 'L' && std::isdigit(look(2))))
  4126. return getDerived().parseFunctionParam();
  4127. return getDerived().parseFoldExpr();
  4128. }
  4129. if (consumeIf("il")) {
  4130. size_t InitsBegin = Names.size();
  4131. while (!consumeIf('E')) {
  4132. Node *E = getDerived().parseBracedExpr();
  4133. if (E == nullptr)
  4134. return nullptr;
  4135. Names.push_back(E);
  4136. }
  4137. return make<InitListExpr>(nullptr, popTrailingNodeArray(InitsBegin));
  4138. }
  4139. if (consumeIf("mc"))
  4140. return parsePointerToMemberConversionExpr(Node::Prec::Unary);
  4141. if (consumeIf("nx")) {
  4142. Node *Ex = getDerived().parseExpr();
  4143. if (Ex == nullptr)
  4144. return Ex;
  4145. return make<EnclosingExpr>("noexcept ", Ex, Node::Prec::Unary);
  4146. }
  4147. if (consumeIf("so"))
  4148. return parseSubobjectExpr();
  4149. if (consumeIf("sp")) {
  4150. Node *Child = getDerived().parseExpr();
  4151. if (Child == nullptr)
  4152. return nullptr;
  4153. return make<ParameterPackExpansion>(Child);
  4154. }
  4155. if (consumeIf("sZ")) {
  4156. if (look() == 'T') {
  4157. Node *R = getDerived().parseTemplateParam();
  4158. if (R == nullptr)
  4159. return nullptr;
  4160. return make<SizeofParamPackExpr>(R);
  4161. }
  4162. Node *FP = getDerived().parseFunctionParam();
  4163. if (FP == nullptr)
  4164. return nullptr;
  4165. return make<EnclosingExpr>("sizeof... ", FP);
  4166. }
  4167. if (consumeIf("sP")) {
  4168. size_t ArgsBegin = Names.size();
  4169. while (!consumeIf('E')) {
  4170. Node *Arg = getDerived().parseTemplateArg();
  4171. if (Arg == nullptr)
  4172. return nullptr;
  4173. Names.push_back(Arg);
  4174. }
  4175. auto *Pack = make<NodeArrayNode>(popTrailingNodeArray(ArgsBegin));
  4176. if (!Pack)
  4177. return nullptr;
  4178. return make<EnclosingExpr>("sizeof... ", Pack);
  4179. }
  4180. if (consumeIf("tl")) {
  4181. Node *Ty = getDerived().parseType();
  4182. if (Ty == nullptr)
  4183. return nullptr;
  4184. size_t InitsBegin = Names.size();
  4185. while (!consumeIf('E')) {
  4186. Node *E = getDerived().parseBracedExpr();
  4187. if (E == nullptr)
  4188. return nullptr;
  4189. Names.push_back(E);
  4190. }
  4191. return make<InitListExpr>(Ty, popTrailingNodeArray(InitsBegin));
  4192. }
  4193. if (consumeIf("tr"))
  4194. return make<NameType>("throw");
  4195. if (consumeIf("tw")) {
  4196. Node *Ex = getDerived().parseExpr();
  4197. if (Ex == nullptr)
  4198. return nullptr;
  4199. return make<ThrowExpr>(Ex);
  4200. }
  4201. if (consumeIf('u')) {
  4202. Node *Name = getDerived().parseSourceName(/*NameState=*/nullptr);
  4203. if (!Name)
  4204. return nullptr;
  4205. // Special case legacy __uuidof mangling. The 't' and 'z' appear where the
  4206. // standard encoding expects a <template-arg>, and would be otherwise be
  4207. // interpreted as <type> node 'short' or 'ellipsis'. However, neither
  4208. // __uuidof(short) nor __uuidof(...) can actually appear, so there is no
  4209. // actual conflict here.
  4210. bool IsUUID = false;
  4211. Node *UUID = nullptr;
  4212. if (Name->getBaseName() == "__uuidof") {
  4213. if (consumeIf('t')) {
  4214. UUID = getDerived().parseType();
  4215. IsUUID = true;
  4216. } else if (consumeIf('z')) {
  4217. UUID = getDerived().parseExpr();
  4218. IsUUID = true;
  4219. }
  4220. }
  4221. size_t ExprsBegin = Names.size();
  4222. if (IsUUID) {
  4223. if (UUID == nullptr)
  4224. return nullptr;
  4225. Names.push_back(UUID);
  4226. } else {
  4227. while (!consumeIf('E')) {
  4228. Node *E = getDerived().parseTemplateArg();
  4229. if (E == nullptr)
  4230. return E;
  4231. Names.push_back(E);
  4232. }
  4233. }
  4234. return make<CallExpr>(Name, popTrailingNodeArray(ExprsBegin),
  4235. Node::Prec::Postfix);
  4236. }
  4237. // Only unresolved names remain.
  4238. return getDerived().parseUnresolvedName(Global);
  4239. }
  4240. // <call-offset> ::= h <nv-offset> _
  4241. // ::= v <v-offset> _
  4242. //
  4243. // <nv-offset> ::= <offset number>
  4244. // # non-virtual base override
  4245. //
  4246. // <v-offset> ::= <offset number> _ <virtual offset number>
  4247. // # virtual base override, with vcall offset
  4248. template <typename Alloc, typename Derived>
  4249. bool AbstractManglingParser<Alloc, Derived>::parseCallOffset() {
  4250. // Just scan through the call offset, we never add this information into the
  4251. // output.
  4252. if (consumeIf('h'))
  4253. return parseNumber(true).empty() || !consumeIf('_');
  4254. if (consumeIf('v'))
  4255. return parseNumber(true).empty() || !consumeIf('_') ||
  4256. parseNumber(true).empty() || !consumeIf('_');
  4257. return true;
  4258. }
  4259. // <special-name> ::= TV <type> # virtual table
  4260. // ::= TT <type> # VTT structure (construction vtable index)
  4261. // ::= TI <type> # typeinfo structure
  4262. // ::= TS <type> # typeinfo name (null-terminated byte string)
  4263. // ::= Tc <call-offset> <call-offset> <base encoding>
  4264. // # base is the nominal target function of thunk
  4265. // # first call-offset is 'this' adjustment
  4266. // # second call-offset is result adjustment
  4267. // ::= T <call-offset> <base encoding>
  4268. // # base is the nominal target function of thunk
  4269. // # Guard variable for one-time initialization
  4270. // ::= GV <object name>
  4271. // # No <type>
  4272. // ::= TW <object name> # Thread-local wrapper
  4273. // ::= TH <object name> # Thread-local initialization
  4274. // ::= GR <object name> _ # First temporary
  4275. // ::= GR <object name> <seq-id> _ # Subsequent temporaries
  4276. // # construction vtable for second-in-first
  4277. // extension ::= TC <first type> <number> _ <second type>
  4278. // extension ::= GR <object name> # reference temporary for object
  4279. // extension ::= GI <module name> # module global initializer
  4280. template <typename Derived, typename Alloc>
  4281. Node *AbstractManglingParser<Derived, Alloc>::parseSpecialName() {
  4282. switch (look()) {
  4283. case 'T':
  4284. switch (look(1)) {
  4285. // TA <template-arg> # template parameter object
  4286. //
  4287. // Not yet in the spec: https://github.com/itanium-cxx-abi/cxx-abi/issues/63
  4288. case 'A': {
  4289. First += 2;
  4290. Node *Arg = getDerived().parseTemplateArg();
  4291. if (Arg == nullptr)
  4292. return nullptr;
  4293. return make<SpecialName>("template parameter object for ", Arg);
  4294. }
  4295. // TV <type> # virtual table
  4296. case 'V': {
  4297. First += 2;
  4298. Node *Ty = getDerived().parseType();
  4299. if (Ty == nullptr)
  4300. return nullptr;
  4301. return make<SpecialName>("vtable for ", Ty);
  4302. }
  4303. // TT <type> # VTT structure (construction vtable index)
  4304. case 'T': {
  4305. First += 2;
  4306. Node *Ty = getDerived().parseType();
  4307. if (Ty == nullptr)
  4308. return nullptr;
  4309. return make<SpecialName>("VTT for ", Ty);
  4310. }
  4311. // TI <type> # typeinfo structure
  4312. case 'I': {
  4313. First += 2;
  4314. Node *Ty = getDerived().parseType();
  4315. if (Ty == nullptr)
  4316. return nullptr;
  4317. return make<SpecialName>("typeinfo for ", Ty);
  4318. }
  4319. // TS <type> # typeinfo name (null-terminated byte string)
  4320. case 'S': {
  4321. First += 2;
  4322. Node *Ty = getDerived().parseType();
  4323. if (Ty == nullptr)
  4324. return nullptr;
  4325. return make<SpecialName>("typeinfo name for ", Ty);
  4326. }
  4327. // Tc <call-offset> <call-offset> <base encoding>
  4328. case 'c': {
  4329. First += 2;
  4330. if (parseCallOffset() || parseCallOffset())
  4331. return nullptr;
  4332. Node *Encoding = getDerived().parseEncoding();
  4333. if (Encoding == nullptr)
  4334. return nullptr;
  4335. return make<SpecialName>("covariant return thunk to ", Encoding);
  4336. }
  4337. // extension ::= TC <first type> <number> _ <second type>
  4338. // # construction vtable for second-in-first
  4339. case 'C': {
  4340. First += 2;
  4341. Node *FirstType = getDerived().parseType();
  4342. if (FirstType == nullptr)
  4343. return nullptr;
  4344. if (parseNumber(true).empty() || !consumeIf('_'))
  4345. return nullptr;
  4346. Node *SecondType = getDerived().parseType();
  4347. if (SecondType == nullptr)
  4348. return nullptr;
  4349. return make<CtorVtableSpecialName>(SecondType, FirstType);
  4350. }
  4351. // TW <object name> # Thread-local wrapper
  4352. case 'W': {
  4353. First += 2;
  4354. Node *Name = getDerived().parseName();
  4355. if (Name == nullptr)
  4356. return nullptr;
  4357. return make<SpecialName>("thread-local wrapper routine for ", Name);
  4358. }
  4359. // TH <object name> # Thread-local initialization
  4360. case 'H': {
  4361. First += 2;
  4362. Node *Name = getDerived().parseName();
  4363. if (Name == nullptr)
  4364. return nullptr;
  4365. return make<SpecialName>("thread-local initialization routine for ", Name);
  4366. }
  4367. // T <call-offset> <base encoding>
  4368. default: {
  4369. ++First;
  4370. bool IsVirt = look() == 'v';
  4371. if (parseCallOffset())
  4372. return nullptr;
  4373. Node *BaseEncoding = getDerived().parseEncoding();
  4374. if (BaseEncoding == nullptr)
  4375. return nullptr;
  4376. if (IsVirt)
  4377. return make<SpecialName>("virtual thunk to ", BaseEncoding);
  4378. else
  4379. return make<SpecialName>("non-virtual thunk to ", BaseEncoding);
  4380. }
  4381. }
  4382. case 'G':
  4383. switch (look(1)) {
  4384. // GV <object name> # Guard variable for one-time initialization
  4385. case 'V': {
  4386. First += 2;
  4387. Node *Name = getDerived().parseName();
  4388. if (Name == nullptr)
  4389. return nullptr;
  4390. return make<SpecialName>("guard variable for ", Name);
  4391. }
  4392. // GR <object name> # reference temporary for object
  4393. // GR <object name> _ # First temporary
  4394. // GR <object name> <seq-id> _ # Subsequent temporaries
  4395. case 'R': {
  4396. First += 2;
  4397. Node *Name = getDerived().parseName();
  4398. if (Name == nullptr)
  4399. return nullptr;
  4400. size_t Count;
  4401. bool ParsedSeqId = !parseSeqId(&Count);
  4402. if (!consumeIf('_') && ParsedSeqId)
  4403. return nullptr;
  4404. return make<SpecialName>("reference temporary for ", Name);
  4405. }
  4406. // GI <module-name> v
  4407. case 'I': {
  4408. First += 2;
  4409. ModuleName *Module = nullptr;
  4410. if (getDerived().parseModuleNameOpt(Module))
  4411. return nullptr;
  4412. if (Module == nullptr)
  4413. return nullptr;
  4414. return make<SpecialName>("initializer for module ", Module);
  4415. }
  4416. }
  4417. }
  4418. return nullptr;
  4419. }
  4420. // <encoding> ::= <function name> <bare-function-type>
  4421. // ::= <data name>
  4422. // ::= <special-name>
  4423. template <typename Derived, typename Alloc>
  4424. Node *AbstractManglingParser<Derived, Alloc>::parseEncoding() {
  4425. // The template parameters of an encoding are unrelated to those of the
  4426. // enclosing context.
  4427. class SaveTemplateParams {
  4428. AbstractManglingParser *Parser;
  4429. decltype(TemplateParams) OldParams;
  4430. decltype(OuterTemplateParams) OldOuterParams;
  4431. public:
  4432. SaveTemplateParams(AbstractManglingParser *TheParser) : Parser(TheParser) {
  4433. OldParams = std::move(Parser->TemplateParams);
  4434. OldOuterParams = std::move(Parser->OuterTemplateParams);
  4435. Parser->TemplateParams.clear();
  4436. Parser->OuterTemplateParams.clear();
  4437. }
  4438. ~SaveTemplateParams() {
  4439. Parser->TemplateParams = std::move(OldParams);
  4440. Parser->OuterTemplateParams = std::move(OldOuterParams);
  4441. }
  4442. } SaveTemplateParams(this);
  4443. if (look() == 'G' || look() == 'T')
  4444. return getDerived().parseSpecialName();
  4445. auto IsEndOfEncoding = [&] {
  4446. // The set of chars that can potentially follow an <encoding> (none of which
  4447. // can start a <type>). Enumerating these allows us to avoid speculative
  4448. // parsing.
  4449. return numLeft() == 0 || look() == 'E' || look() == '.' || look() == '_';
  4450. };
  4451. NameState NameInfo(this);
  4452. Node *Name = getDerived().parseName(&NameInfo);
  4453. if (Name == nullptr)
  4454. return nullptr;
  4455. if (resolveForwardTemplateRefs(NameInfo))
  4456. return nullptr;
  4457. if (IsEndOfEncoding())
  4458. return Name;
  4459. Node *Attrs = nullptr;
  4460. if (consumeIf("Ua9enable_ifI")) {
  4461. size_t BeforeArgs = Names.size();
  4462. while (!consumeIf('E')) {
  4463. Node *Arg = getDerived().parseTemplateArg();
  4464. if (Arg == nullptr)
  4465. return nullptr;
  4466. Names.push_back(Arg);
  4467. }
  4468. Attrs = make<EnableIfAttr>(popTrailingNodeArray(BeforeArgs));
  4469. if (!Attrs)
  4470. return nullptr;
  4471. }
  4472. Node *ReturnType = nullptr;
  4473. if (!NameInfo.CtorDtorConversion && NameInfo.EndsWithTemplateArgs) {
  4474. ReturnType = getDerived().parseType();
  4475. if (ReturnType == nullptr)
  4476. return nullptr;
  4477. }
  4478. if (consumeIf('v'))
  4479. return make<FunctionEncoding>(ReturnType, Name, NodeArray(),
  4480. Attrs, NameInfo.CVQualifiers,
  4481. NameInfo.ReferenceQualifier);
  4482. size_t ParamsBegin = Names.size();
  4483. do {
  4484. Node *Ty = getDerived().parseType();
  4485. if (Ty == nullptr)
  4486. return nullptr;
  4487. Names.push_back(Ty);
  4488. } while (!IsEndOfEncoding());
  4489. return make<FunctionEncoding>(ReturnType, Name,
  4490. popTrailingNodeArray(ParamsBegin),
  4491. Attrs, NameInfo.CVQualifiers,
  4492. NameInfo.ReferenceQualifier);
  4493. }
  4494. template <class Float>
  4495. struct FloatData;
  4496. template <>
  4497. struct FloatData<float>
  4498. {
  4499. static const size_t mangled_size = 8;
  4500. static const size_t max_demangled_size = 24;
  4501. static constexpr const char* spec = "%af";
  4502. };
  4503. template <>
  4504. struct FloatData<double>
  4505. {
  4506. static const size_t mangled_size = 16;
  4507. static const size_t max_demangled_size = 32;
  4508. static constexpr const char* spec = "%a";
  4509. };
  4510. template <>
  4511. struct FloatData<long double>
  4512. {
  4513. #if defined(__mips__) && defined(__mips_n64) || defined(__aarch64__) || \
  4514. defined(__wasm__) || defined(__riscv) || defined(__loongarch__)
  4515. static const size_t mangled_size = 32;
  4516. #elif defined(__arm__) || defined(__mips__) || defined(__hexagon__)
  4517. static const size_t mangled_size = 16;
  4518. #else
  4519. static const size_t mangled_size = 20; // May need to be adjusted to 16 or 24 on other platforms
  4520. #endif
  4521. // `-0x1.ffffffffffffffffffffffffffffp+16383` + 'L' + '\0' == 42 bytes.
  4522. // 28 'f's * 4 bits == 112 bits, which is the number of mantissa bits.
  4523. // Negatives are one character longer than positives.
  4524. // `0x1.` and `p` are constant, and exponents `+16383` and `-16382` are the
  4525. // same length. 1 sign bit, 112 mantissa bits, and 15 exponent bits == 128.
  4526. static const size_t max_demangled_size = 42;
  4527. static constexpr const char *spec = "%LaL";
  4528. };
  4529. template <typename Alloc, typename Derived>
  4530. template <class Float>
  4531. Node *AbstractManglingParser<Alloc, Derived>::parseFloatingLiteral() {
  4532. const size_t N = FloatData<Float>::mangled_size;
  4533. if (numLeft() <= N)
  4534. return nullptr;
  4535. StringView Data(First, First + N);
  4536. for (char C : Data)
  4537. if (!std::isxdigit(C))
  4538. return nullptr;
  4539. First += N;
  4540. if (!consumeIf('E'))
  4541. return nullptr;
  4542. return make<FloatLiteralImpl<Float>>(Data);
  4543. }
  4544. // <seq-id> ::= <0-9A-Z>+
  4545. template <typename Alloc, typename Derived>
  4546. bool AbstractManglingParser<Alloc, Derived>::parseSeqId(size_t *Out) {
  4547. if (!(look() >= '0' && look() <= '9') &&
  4548. !(look() >= 'A' && look() <= 'Z'))
  4549. return true;
  4550. size_t Id = 0;
  4551. while (true) {
  4552. if (look() >= '0' && look() <= '9') {
  4553. Id *= 36;
  4554. Id += static_cast<size_t>(look() - '0');
  4555. } else if (look() >= 'A' && look() <= 'Z') {
  4556. Id *= 36;
  4557. Id += static_cast<size_t>(look() - 'A') + 10;
  4558. } else {
  4559. *Out = Id;
  4560. return false;
  4561. }
  4562. ++First;
  4563. }
  4564. }
  4565. // <substitution> ::= S <seq-id> _
  4566. // ::= S_
  4567. // <substitution> ::= Sa # ::std::allocator
  4568. // <substitution> ::= Sb # ::std::basic_string
  4569. // <substitution> ::= Ss # ::std::basic_string < char,
  4570. // ::std::char_traits<char>,
  4571. // ::std::allocator<char> >
  4572. // <substitution> ::= Si # ::std::basic_istream<char, std::char_traits<char> >
  4573. // <substitution> ::= So # ::std::basic_ostream<char, std::char_traits<char> >
  4574. // <substitution> ::= Sd # ::std::basic_iostream<char, std::char_traits<char> >
  4575. // The St case is handled specially in parseNestedName.
  4576. template <typename Derived, typename Alloc>
  4577. Node *AbstractManglingParser<Derived, Alloc>::parseSubstitution() {
  4578. if (!consumeIf('S'))
  4579. return nullptr;
  4580. if (look() >= 'a' && look() <= 'z') {
  4581. SpecialSubKind Kind;
  4582. switch (look()) {
  4583. case 'a':
  4584. Kind = SpecialSubKind::allocator;
  4585. break;
  4586. case 'b':
  4587. Kind = SpecialSubKind::basic_string;
  4588. break;
  4589. case 'd':
  4590. Kind = SpecialSubKind::iostream;
  4591. break;
  4592. case 'i':
  4593. Kind = SpecialSubKind::istream;
  4594. break;
  4595. case 'o':
  4596. Kind = SpecialSubKind::ostream;
  4597. break;
  4598. case 's':
  4599. Kind = SpecialSubKind::string;
  4600. break;
  4601. default:
  4602. return nullptr;
  4603. }
  4604. ++First;
  4605. auto *SpecialSub = make<SpecialSubstitution>(Kind);
  4606. if (!SpecialSub)
  4607. return nullptr;
  4608. // Itanium C++ ABI 5.1.2: If a name that would use a built-in <substitution>
  4609. // has ABI tags, the tags are appended to the substitution; the result is a
  4610. // substitutable component.
  4611. Node *WithTags = getDerived().parseAbiTags(SpecialSub);
  4612. if (WithTags != SpecialSub) {
  4613. Subs.push_back(WithTags);
  4614. SpecialSub = WithTags;
  4615. }
  4616. return SpecialSub;
  4617. }
  4618. // ::= S_
  4619. if (consumeIf('_')) {
  4620. if (Subs.empty())
  4621. return nullptr;
  4622. return Subs[0];
  4623. }
  4624. // ::= S <seq-id> _
  4625. size_t Index = 0;
  4626. if (parseSeqId(&Index))
  4627. return nullptr;
  4628. ++Index;
  4629. if (!consumeIf('_') || Index >= Subs.size())
  4630. return nullptr;
  4631. return Subs[Index];
  4632. }
  4633. // <template-param> ::= T_ # first template parameter
  4634. // ::= T <parameter-2 non-negative number> _
  4635. // ::= TL <level-1> __
  4636. // ::= TL <level-1> _ <parameter-2 non-negative number> _
  4637. template <typename Derived, typename Alloc>
  4638. Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParam() {
  4639. if (!consumeIf('T'))
  4640. return nullptr;
  4641. size_t Level = 0;
  4642. if (consumeIf('L')) {
  4643. if (parsePositiveInteger(&Level))
  4644. return nullptr;
  4645. ++Level;
  4646. if (!consumeIf('_'))
  4647. return nullptr;
  4648. }
  4649. size_t Index = 0;
  4650. if (!consumeIf('_')) {
  4651. if (parsePositiveInteger(&Index))
  4652. return nullptr;
  4653. ++Index;
  4654. if (!consumeIf('_'))
  4655. return nullptr;
  4656. }
  4657. // If we're in a context where this <template-param> refers to a
  4658. // <template-arg> further ahead in the mangled name (currently just conversion
  4659. // operator types), then we should only look it up in the right context.
  4660. // This can only happen at the outermost level.
  4661. if (PermitForwardTemplateReferences && Level == 0) {
  4662. Node *ForwardRef = make<ForwardTemplateReference>(Index);
  4663. if (!ForwardRef)
  4664. return nullptr;
  4665. assert(ForwardRef->getKind() == Node::KForwardTemplateReference);
  4666. ForwardTemplateRefs.push_back(
  4667. static_cast<ForwardTemplateReference *>(ForwardRef));
  4668. return ForwardRef;
  4669. }
  4670. if (Level >= TemplateParams.size() || !TemplateParams[Level] ||
  4671. Index >= TemplateParams[Level]->size()) {
  4672. // Itanium ABI 5.1.8: In a generic lambda, uses of auto in the parameter
  4673. // list are mangled as the corresponding artificial template type parameter.
  4674. if (ParsingLambdaParamsAtLevel == Level && Level <= TemplateParams.size()) {
  4675. // This will be popped by the ScopedTemplateParamList in
  4676. // parseUnnamedTypeName.
  4677. if (Level == TemplateParams.size())
  4678. TemplateParams.push_back(nullptr);
  4679. return make<NameType>("auto");
  4680. }
  4681. return nullptr;
  4682. }
  4683. return (*TemplateParams[Level])[Index];
  4684. }
  4685. // <template-param-decl> ::= Ty # type parameter
  4686. // ::= Tn <type> # non-type parameter
  4687. // ::= Tt <template-param-decl>* E # template parameter
  4688. // ::= Tp <template-param-decl> # parameter pack
  4689. template <typename Derived, typename Alloc>
  4690. Node *AbstractManglingParser<Derived, Alloc>::parseTemplateParamDecl() {
  4691. auto InventTemplateParamName = [&](TemplateParamKind Kind) {
  4692. unsigned Index = NumSyntheticTemplateParameters[(int)Kind]++;
  4693. Node *N = make<SyntheticTemplateParamName>(Kind, Index);
  4694. if (N) TemplateParams.back()->push_back(N);
  4695. return N;
  4696. };
  4697. if (consumeIf("Ty")) {
  4698. Node *Name = InventTemplateParamName(TemplateParamKind::Type);
  4699. if (!Name)
  4700. return nullptr;
  4701. return make<TypeTemplateParamDecl>(Name);
  4702. }
  4703. if (consumeIf("Tn")) {
  4704. Node *Name = InventTemplateParamName(TemplateParamKind::NonType);
  4705. if (!Name)
  4706. return nullptr;
  4707. Node *Type = parseType();
  4708. if (!Type)
  4709. return nullptr;
  4710. return make<NonTypeTemplateParamDecl>(Name, Type);
  4711. }
  4712. if (consumeIf("Tt")) {
  4713. Node *Name = InventTemplateParamName(TemplateParamKind::Template);
  4714. if (!Name)
  4715. return nullptr;
  4716. size_t ParamsBegin = Names.size();
  4717. ScopedTemplateParamList TemplateTemplateParamParams(this);
  4718. while (!consumeIf("E")) {
  4719. Node *P = parseTemplateParamDecl();
  4720. if (!P)
  4721. return nullptr;
  4722. Names.push_back(P);
  4723. }
  4724. NodeArray Params = popTrailingNodeArray(ParamsBegin);
  4725. return make<TemplateTemplateParamDecl>(Name, Params);
  4726. }
  4727. if (consumeIf("Tp")) {
  4728. Node *P = parseTemplateParamDecl();
  4729. if (!P)
  4730. return nullptr;
  4731. return make<TemplateParamPackDecl>(P);
  4732. }
  4733. return nullptr;
  4734. }
  4735. // <template-arg> ::= <type> # type or template
  4736. // ::= X <expression> E # expression
  4737. // ::= <expr-primary> # simple expressions
  4738. // ::= J <template-arg>* E # argument pack
  4739. // ::= LZ <encoding> E # extension
  4740. template <typename Derived, typename Alloc>
  4741. Node *AbstractManglingParser<Derived, Alloc>::parseTemplateArg() {
  4742. switch (look()) {
  4743. case 'X': {
  4744. ++First;
  4745. Node *Arg = getDerived().parseExpr();
  4746. if (Arg == nullptr || !consumeIf('E'))
  4747. return nullptr;
  4748. return Arg;
  4749. }
  4750. case 'I': // 'I' here is an old GCC mangling ABI. It is common in outside binaries.
  4751. case 'J': {
  4752. ++First;
  4753. size_t ArgsBegin = Names.size();
  4754. while (!consumeIf('E')) {
  4755. Node *Arg = getDerived().parseTemplateArg();
  4756. if (Arg == nullptr)
  4757. return nullptr;
  4758. Names.push_back(Arg);
  4759. }
  4760. NodeArray Args = popTrailingNodeArray(ArgsBegin);
  4761. return make<TemplateArgumentPack>(Args);
  4762. }
  4763. case 'L': {
  4764. // ::= LZ <encoding> E # extension
  4765. if (look(1) == 'Z') {
  4766. First += 2;
  4767. Node *Arg = getDerived().parseEncoding();
  4768. if (Arg == nullptr || !consumeIf('E'))
  4769. return nullptr;
  4770. return Arg;
  4771. }
  4772. // ::= <expr-primary> # simple expressions
  4773. return getDerived().parseExprPrimary();
  4774. }
  4775. default:
  4776. return getDerived().parseType();
  4777. }
  4778. }
  4779. // <template-args> ::= I <template-arg>* E
  4780. // extension, the abi says <template-arg>+
  4781. template <typename Derived, typename Alloc>
  4782. Node *
  4783. AbstractManglingParser<Derived, Alloc>::parseTemplateArgs(bool TagTemplates) {
  4784. if (!consumeIf('I'))
  4785. return nullptr;
  4786. // <template-params> refer to the innermost <template-args>. Clear out any
  4787. // outer args that we may have inserted into TemplateParams.
  4788. if (TagTemplates) {
  4789. TemplateParams.clear();
  4790. TemplateParams.push_back(&OuterTemplateParams);
  4791. OuterTemplateParams.clear();
  4792. }
  4793. size_t ArgsBegin = Names.size();
  4794. while (!consumeIf('E')) {
  4795. if (TagTemplates) {
  4796. auto OldParams = std::move(TemplateParams);
  4797. Node *Arg = getDerived().parseTemplateArg();
  4798. TemplateParams = std::move(OldParams);
  4799. if (Arg == nullptr)
  4800. return nullptr;
  4801. Names.push_back(Arg);
  4802. Node *TableEntry = Arg;
  4803. if (Arg->getKind() == Node::KTemplateArgumentPack) {
  4804. TableEntry = make<ParameterPack>(
  4805. static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
  4806. if (!TableEntry)
  4807. return nullptr;
  4808. }
  4809. TemplateParams.back()->push_back(TableEntry);
  4810. } else {
  4811. Node *Arg = getDerived().parseTemplateArg();
  4812. if (Arg == nullptr)
  4813. return nullptr;
  4814. Names.push_back(Arg);
  4815. }
  4816. }
  4817. return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
  4818. }
  4819. // <mangled-name> ::= _Z <encoding>
  4820. // ::= <type>
  4821. // extension ::= ___Z <encoding> _block_invoke
  4822. // extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
  4823. // extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
  4824. template <typename Derived, typename Alloc>
  4825. Node *AbstractManglingParser<Derived, Alloc>::parse() {
  4826. if (consumeIf("_Z") || consumeIf("__Z")) {
  4827. Node *Encoding = getDerived().parseEncoding();
  4828. if (Encoding == nullptr)
  4829. return nullptr;
  4830. if (look() == '.') {
  4831. Encoding = make<DotSuffix>(Encoding, StringView(First, Last));
  4832. First = Last;
  4833. }
  4834. if (numLeft() != 0)
  4835. return nullptr;
  4836. return Encoding;
  4837. }
  4838. if (consumeIf("___Z") || consumeIf("____Z")) {
  4839. Node *Encoding = getDerived().parseEncoding();
  4840. if (Encoding == nullptr || !consumeIf("_block_invoke"))
  4841. return nullptr;
  4842. bool RequireNumber = consumeIf('_');
  4843. if (parseNumber().empty() && RequireNumber)
  4844. return nullptr;
  4845. if (look() == '.')
  4846. First = Last;
  4847. if (numLeft() != 0)
  4848. return nullptr;
  4849. return make<SpecialName>("invocation function for block in ", Encoding);
  4850. }
  4851. Node *Ty = getDerived().parseType();
  4852. if (numLeft() != 0)
  4853. return nullptr;
  4854. return Ty;
  4855. }
  4856. template <typename Alloc>
  4857. struct ManglingParser : AbstractManglingParser<ManglingParser<Alloc>, Alloc> {
  4858. using AbstractManglingParser<ManglingParser<Alloc>,
  4859. Alloc>::AbstractManglingParser;
  4860. };
  4861. DEMANGLE_NAMESPACE_END
  4862. #endif // DEMANGLE_ITANIUMDEMANGLE_H
  4863. #ifdef __GNUC__
  4864. #pragma GCC diagnostic pop
  4865. #endif