ItaniumDemangle.h 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513
  1. //===--- ItaniumDemangle.h -----------*- mode:c++;eval:(read-only-mode) -*-===//
  2. // Do not edit! See README.txt.
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-FileCopyrightText: Part of the LLVM Project
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Generic itanium demangler library.
  11. // There are two copies of this file in the source tree. The one under
  12. // libcxxabi is the original and the one under llvm is the copy. Use
  13. // cp-to-llvm.sh to update the copy. See README.txt for more details.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #ifndef DEMANGLE_ITANIUMDEMANGLE_H
  17. #define DEMANGLE_ITANIUMDEMANGLE_H
  18. #include "DemangleConfig.h"
  19. #include "StringViewExtras.h"
  20. #include "Utility.h"
  21. #include <algorithm>
  22. #include <cassert>
  23. #include <cctype>
  24. #include <cstdio>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <limits>
  28. #include <new>
  29. #include <string_view>
  30. #include <type_traits>
  31. #include <utility>
  32. DEMANGLE_NAMESPACE_BEGIN
  33. template <class T, size_t N> class PODSmallVector {
  34. static_assert(std::is_pod<T>::value,
  35. "T is required to be a plain old data type");
  36. T *First = nullptr;
  37. T *Last = nullptr;
  38. T *Cap = nullptr;
  39. T Inline[N] = {0};
  40. bool isInline() const { return First == Inline; }
  41. void clearInline() {
  42. First = Inline;
  43. Last = Inline;
  44. Cap = Inline + N;
  45. }
  46. void reserve(size_t NewCap) {
  47. size_t S = size();
  48. if (isInline()) {
  49. auto *Tmp = static_cast<T *>(std::malloc(NewCap * sizeof(T)));
  50. if (Tmp == nullptr)
  51. std::terminate();
  52. std::copy(First, Last, Tmp);
  53. First = Tmp;
  54. } else {
  55. First = static_cast<T *>(std::realloc(First, NewCap * sizeof(T)));
  56. if (First == nullptr)
  57. std::terminate();
  58. }
  59. Last = First + S;
  60. Cap = First + NewCap;
  61. }
  62. public:
  63. PODSmallVector() : First(Inline), Last(First), Cap(Inline + N) {}
  64. PODSmallVector(const PODSmallVector &) = delete;
  65. PODSmallVector &operator=(const PODSmallVector &) = delete;
  66. PODSmallVector(PODSmallVector &&Other) : PODSmallVector() {
  67. if (Other.isInline()) {
  68. std::copy(Other.begin(), Other.end(), First);
  69. Last = First + Other.size();
  70. Other.clear();
  71. return;
  72. }
  73. First = Other.First;
  74. Last = Other.Last;
  75. Cap = Other.Cap;
  76. Other.clearInline();
  77. }
  78. PODSmallVector &operator=(PODSmallVector &&Other) {
  79. if (Other.isInline()) {
  80. if (!isInline()) {
  81. std::free(First);
  82. clearInline();
  83. }
  84. std::copy(Other.begin(), Other.end(), First);
  85. Last = First + Other.size();
  86. Other.clear();
  87. return *this;
  88. }
  89. if (isInline()) {
  90. First = Other.First;
  91. Last = Other.Last;
  92. Cap = Other.Cap;
  93. Other.clearInline();
  94. return *this;
  95. }
  96. std::swap(First, Other.First);
  97. std::swap(Last, Other.Last);
  98. std::swap(Cap, Other.Cap);
  99. Other.clear();
  100. return *this;
  101. }
  102. // NOLINTNEXTLINE(readability-identifier-naming)
  103. void push_back(const T &Elem) {
  104. if (Last == Cap)
  105. reserve(size() * 2);
  106. *Last++ = Elem;
  107. }
  108. // NOLINTNEXTLINE(readability-identifier-naming)
  109. void pop_back() {
  110. assert(Last != First && "Popping empty vector!");
  111. --Last;
  112. }
  113. void dropBack(size_t Index) {
  114. assert(Index <= size() && "dropBack() can't expand!");
  115. Last = First + Index;
  116. }
  117. T *begin() { return First; }
  118. T *end() { return Last; }
  119. bool empty() const { return First == Last; }
  120. size_t size() const { return static_cast<size_t>(Last - First); }
  121. T &back() {
  122. assert(Last != First && "Calling back() on empty vector!");
  123. return *(Last - 1);
  124. }
  125. T &operator[](size_t Index) {
  126. assert(Index < size() && "Invalid access!");
  127. return *(begin() + Index);
  128. }
  129. void clear() { Last = First; }
  130. ~PODSmallVector() {
  131. if (!isInline())
  132. std::free(First);
  133. }
  134. };
  135. // Base class of all AST nodes. The AST is built by the parser, then is
  136. // traversed by the printLeft/Right functions to produce a demangled string.
  137. class Node {
  138. public:
  139. enum Kind : unsigned char {
  140. #define NODE(NodeKind) K##NodeKind,
  141. #include "ItaniumNodes.def"
  142. };
  143. /// Three-way bool to track a cached value. Unknown is possible if this node
  144. /// has an unexpanded parameter pack below it that may affect this cache.
  145. enum class Cache : unsigned char { Yes, No, Unknown, };
  146. /// Operator precedence for expression nodes. Used to determine required
  147. /// parens in expression emission.
  148. enum class Prec {
  149. Primary,
  150. Postfix,
  151. Unary,
  152. Cast,
  153. PtrMem,
  154. Multiplicative,
  155. Additive,
  156. Shift,
  157. Spaceship,
  158. Relational,
  159. Equality,
  160. And,
  161. Xor,
  162. Ior,
  163. AndIf,
  164. OrIf,
  165. Conditional,
  166. Assign,
  167. Comma,
  168. Default,
  169. };
  170. private:
  171. Kind K;
  172. Prec Precedence : 6;
  173. // FIXME: Make these protected.
  174. public:
  175. /// Tracks if this node has a component on its right side, in which case we
  176. /// need to call printRight.
  177. Cache RHSComponentCache : 2;
  178. /// Track if this node is a (possibly qualified) array type. This can affect
  179. /// how we format the output string.
  180. Cache ArrayCache : 2;
  181. /// Track if this node is a (possibly qualified) function type. This can
  182. /// affect how we format the output string.
  183. Cache FunctionCache : 2;
  184. public:
  185. Node(Kind K_, Prec Precedence_ = Prec::Primary,
  186. Cache RHSComponentCache_ = Cache::No, Cache ArrayCache_ = Cache::No,
  187. Cache FunctionCache_ = Cache::No)
  188. : K(K_), Precedence(Precedence_), RHSComponentCache(RHSComponentCache_),
  189. ArrayCache(ArrayCache_), FunctionCache(FunctionCache_) {}
  190. Node(Kind K_, Cache RHSComponentCache_, Cache ArrayCache_ = Cache::No,
  191. Cache FunctionCache_ = Cache::No)
  192. : Node(K_, Prec::Primary, RHSComponentCache_, ArrayCache_,
  193. FunctionCache_) {}
  194. /// Visit the most-derived object corresponding to this object.
  195. template<typename Fn> void visit(Fn F) const;
  196. // The following function is provided by all derived classes:
  197. //
  198. // Call F with arguments that, when passed to the constructor of this node,
  199. // would construct an equivalent node.
  200. //template<typename Fn> void match(Fn F) const;
  201. bool hasRHSComponent(OutputBuffer &OB) const {
  202. if (RHSComponentCache != Cache::Unknown)
  203. return RHSComponentCache == Cache::Yes;
  204. return hasRHSComponentSlow(OB);
  205. }
  206. bool hasArray(OutputBuffer &OB) const {
  207. if (ArrayCache != Cache::Unknown)
  208. return ArrayCache == Cache::Yes;
  209. return hasArraySlow(OB);
  210. }
  211. bool hasFunction(OutputBuffer &OB) const {
  212. if (FunctionCache != Cache::Unknown)
  213. return FunctionCache == Cache::Yes;
  214. return hasFunctionSlow(OB);
  215. }
  216. Kind getKind() const { return K; }
  217. Prec getPrecedence() const { return Precedence; }
  218. virtual bool hasRHSComponentSlow(OutputBuffer &) const { return false; }
  219. virtual bool hasArraySlow(OutputBuffer &) const { return false; }
  220. virtual bool hasFunctionSlow(OutputBuffer &) const { return false; }
  221. // Dig through "glue" nodes like ParameterPack and ForwardTemplateReference to
  222. // get at a node that actually represents some concrete syntax.
  223. virtual const Node *getSyntaxNode(OutputBuffer &) const { return this; }
  224. // Print this node as an expression operand, surrounding it in parentheses if
  225. // its precedence is [Strictly] weaker than P.
  226. void printAsOperand(OutputBuffer &OB, Prec P = Prec::Default,
  227. bool StrictlyWorse = false) const {
  228. bool Paren =
  229. unsigned(getPrecedence()) >= unsigned(P) + unsigned(StrictlyWorse);
  230. if (Paren)
  231. OB.printOpen();
  232. print(OB);
  233. if (Paren)
  234. OB.printClose();
  235. }
  236. void print(OutputBuffer &OB) const {
  237. printLeft(OB);
  238. if (RHSComponentCache != Cache::No)
  239. printRight(OB);
  240. }
  241. // Print the "left" side of this Node into OutputBuffer.
  242. virtual void printLeft(OutputBuffer &) const = 0;
  243. // Print the "right". This distinction is necessary to represent C++ types
  244. // that appear on the RHS of their subtype, such as arrays or functions.
  245. // Since most types don't have such a component, provide a default
  246. // implementation.
  247. virtual void printRight(OutputBuffer &) const {}
  248. virtual std::string_view getBaseName() const { return {}; }
  249. // Silence compiler warnings, this dtor will never be called.
  250. virtual ~Node() = default;
  251. #ifndef NDEBUG
  252. DEMANGLE_DUMP_METHOD void dump() const;
  253. #endif
  254. };
  255. class NodeArray {
  256. Node **Elements;
  257. size_t NumElements;
  258. public:
  259. NodeArray() : Elements(nullptr), NumElements(0) {}
  260. NodeArray(Node **Elements_, size_t NumElements_)
  261. : Elements(Elements_), NumElements(NumElements_) {}
  262. bool empty() const { return NumElements == 0; }
  263. size_t size() const { return NumElements; }
  264. Node **begin() const { return Elements; }
  265. Node **end() const { return Elements + NumElements; }
  266. Node *operator[](size_t Idx) const { return Elements[Idx]; }
  267. void printWithComma(OutputBuffer &OB) const {
  268. bool FirstElement = true;
  269. for (size_t Idx = 0; Idx != NumElements; ++Idx) {
  270. size_t BeforeComma = OB.getCurrentPosition();
  271. if (!FirstElement)
  272. OB += ", ";
  273. size_t AfterComma = OB.getCurrentPosition();
  274. Elements[Idx]->printAsOperand(OB, Node::Prec::Comma);
  275. // Elements[Idx] is an empty parameter pack expansion, we should erase the
  276. // comma we just printed.
  277. if (AfterComma == OB.getCurrentPosition()) {
  278. OB.setCurrentPosition(BeforeComma);
  279. continue;
  280. }
  281. FirstElement = false;
  282. }
  283. }
  284. };
  285. struct NodeArrayNode : Node {
  286. NodeArray Array;
  287. NodeArrayNode(NodeArray Array_) : Node(KNodeArrayNode), Array(Array_) {}
  288. template<typename Fn> void match(Fn F) const { F(Array); }
  289. void printLeft(OutputBuffer &OB) const override { Array.printWithComma(OB); }
  290. };
  291. class DotSuffix final : public Node {
  292. const Node *Prefix;
  293. const std::string_view Suffix;
  294. public:
  295. DotSuffix(const Node *Prefix_, std::string_view Suffix_)
  296. : Node(KDotSuffix), Prefix(Prefix_), Suffix(Suffix_) {}
  297. template<typename Fn> void match(Fn F) const { F(Prefix, Suffix); }
  298. void printLeft(OutputBuffer &OB) const override {
  299. Prefix->print(OB);
  300. OB += " (";
  301. OB += Suffix;
  302. OB += ")";
  303. }
  304. };
  305. class VendorExtQualType final : public Node {
  306. const Node *Ty;
  307. std::string_view Ext;
  308. const Node *TA;
  309. public:
  310. VendorExtQualType(const Node *Ty_, std::string_view Ext_, const Node *TA_)
  311. : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_), TA(TA_) {}
  312. const Node *getTy() const { return Ty; }
  313. std::string_view getExt() const { return Ext; }
  314. const Node *getTA() const { return TA; }
  315. template <typename Fn> void match(Fn F) const { F(Ty, Ext, TA); }
  316. void printLeft(OutputBuffer &OB) const override {
  317. Ty->print(OB);
  318. OB += " ";
  319. OB += Ext;
  320. if (TA != nullptr)
  321. TA->print(OB);
  322. }
  323. };
  324. enum FunctionRefQual : unsigned char {
  325. FrefQualNone,
  326. FrefQualLValue,
  327. FrefQualRValue,
  328. };
  329. enum Qualifiers {
  330. QualNone = 0,
  331. QualConst = 0x1,
  332. QualVolatile = 0x2,
  333. QualRestrict = 0x4,
  334. };
  335. inline Qualifiers operator|=(Qualifiers &Q1, Qualifiers Q2) {
  336. return Q1 = static_cast<Qualifiers>(Q1 | Q2);
  337. }
  338. class QualType final : public Node {
  339. protected:
  340. const Qualifiers Quals;
  341. const Node *Child;
  342. void printQuals(OutputBuffer &OB) const {
  343. if (Quals & QualConst)
  344. OB += " const";
  345. if (Quals & QualVolatile)
  346. OB += " volatile";
  347. if (Quals & QualRestrict)
  348. OB += " restrict";
  349. }
  350. public:
  351. QualType(const Node *Child_, Qualifiers Quals_)
  352. : Node(KQualType, Child_->RHSComponentCache,
  353. Child_->ArrayCache, Child_->FunctionCache),
  354. Quals(Quals_), Child(Child_) {}
  355. Qualifiers getQuals() const { return Quals; }
  356. const Node *getChild() const { return Child; }
  357. template<typename Fn> void match(Fn F) const { F(Child, Quals); }
  358. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  359. return Child->hasRHSComponent(OB);
  360. }
  361. bool hasArraySlow(OutputBuffer &OB) const override {
  362. return Child->hasArray(OB);
  363. }
  364. bool hasFunctionSlow(OutputBuffer &OB) const override {
  365. return Child->hasFunction(OB);
  366. }
  367. void printLeft(OutputBuffer &OB) const override {
  368. Child->printLeft(OB);
  369. printQuals(OB);
  370. }
  371. void printRight(OutputBuffer &OB) const override { Child->printRight(OB); }
  372. };
  373. class ConversionOperatorType final : public Node {
  374. const Node *Ty;
  375. public:
  376. ConversionOperatorType(const Node *Ty_)
  377. : Node(KConversionOperatorType), Ty(Ty_) {}
  378. template<typename Fn> void match(Fn F) const { F(Ty); }
  379. void printLeft(OutputBuffer &OB) const override {
  380. OB += "operator ";
  381. Ty->print(OB);
  382. }
  383. };
  384. class PostfixQualifiedType final : public Node {
  385. const Node *Ty;
  386. const std::string_view Postfix;
  387. public:
  388. PostfixQualifiedType(const Node *Ty_, std::string_view Postfix_)
  389. : Node(KPostfixQualifiedType), Ty(Ty_), Postfix(Postfix_) {}
  390. template<typename Fn> void match(Fn F) const { F(Ty, Postfix); }
  391. void printLeft(OutputBuffer &OB) const override {
  392. Ty->printLeft(OB);
  393. OB += Postfix;
  394. }
  395. };
  396. class NameType final : public Node {
  397. const std::string_view Name;
  398. public:
  399. NameType(std::string_view Name_) : Node(KNameType), Name(Name_) {}
  400. template<typename Fn> void match(Fn F) const { F(Name); }
  401. std::string_view getName() const { return Name; }
  402. std::string_view getBaseName() const override { return Name; }
  403. void printLeft(OutputBuffer &OB) const override { OB += Name; }
  404. };
  405. class BitIntType final : public Node {
  406. const Node *Size;
  407. bool Signed;
  408. public:
  409. BitIntType(const Node *Size_, bool Signed_)
  410. : Node(KBitIntType), Size(Size_), Signed(Signed_) {}
  411. template <typename Fn> void match(Fn F) const { F(Size, Signed); }
  412. void printLeft(OutputBuffer &OB) const override {
  413. if (!Signed)
  414. OB += "unsigned ";
  415. OB += "_BitInt";
  416. OB.printOpen();
  417. Size->printAsOperand(OB);
  418. OB.printClose();
  419. }
  420. };
  421. class ElaboratedTypeSpefType : public Node {
  422. std::string_view Kind;
  423. Node *Child;
  424. public:
  425. ElaboratedTypeSpefType(std::string_view Kind_, Node *Child_)
  426. : Node(KElaboratedTypeSpefType), Kind(Kind_), Child(Child_) {}
  427. template<typename Fn> void match(Fn F) const { F(Kind, Child); }
  428. void printLeft(OutputBuffer &OB) const override {
  429. OB += Kind;
  430. OB += ' ';
  431. Child->print(OB);
  432. }
  433. };
  434. struct AbiTagAttr : Node {
  435. Node *Base;
  436. std::string_view Tag;
  437. AbiTagAttr(Node *Base_, std::string_view Tag_)
  438. : Node(KAbiTagAttr, Base_->RHSComponentCache, Base_->ArrayCache,
  439. Base_->FunctionCache),
  440. Base(Base_), Tag(Tag_) {}
  441. template<typename Fn> void match(Fn F) const { F(Base, Tag); }
  442. std::string_view getBaseName() const override { return Base->getBaseName(); }
  443. void printLeft(OutputBuffer &OB) const override {
  444. Base->printLeft(OB);
  445. OB += "[abi:";
  446. OB += Tag;
  447. OB += "]";
  448. }
  449. };
  450. class EnableIfAttr : public Node {
  451. NodeArray Conditions;
  452. public:
  453. EnableIfAttr(NodeArray Conditions_)
  454. : Node(KEnableIfAttr), Conditions(Conditions_) {}
  455. template<typename Fn> void match(Fn F) const { F(Conditions); }
  456. void printLeft(OutputBuffer &OB) const override {
  457. OB += " [enable_if:";
  458. Conditions.printWithComma(OB);
  459. OB += ']';
  460. }
  461. };
  462. class ObjCProtoName : public Node {
  463. const Node *Ty;
  464. std::string_view Protocol;
  465. friend class PointerType;
  466. public:
  467. ObjCProtoName(const Node *Ty_, std::string_view Protocol_)
  468. : Node(KObjCProtoName), Ty(Ty_), Protocol(Protocol_) {}
  469. template<typename Fn> void match(Fn F) const { F(Ty, Protocol); }
  470. bool isObjCObject() const {
  471. return Ty->getKind() == KNameType &&
  472. static_cast<const NameType *>(Ty)->getName() == "objc_object";
  473. }
  474. void printLeft(OutputBuffer &OB) const override {
  475. Ty->print(OB);
  476. OB += "<";
  477. OB += Protocol;
  478. OB += ">";
  479. }
  480. };
  481. class PointerType final : public Node {
  482. const Node *Pointee;
  483. public:
  484. PointerType(const Node *Pointee_)
  485. : Node(KPointerType, Pointee_->RHSComponentCache),
  486. Pointee(Pointee_) {}
  487. const Node *getPointee() const { return Pointee; }
  488. template<typename Fn> void match(Fn F) const { F(Pointee); }
  489. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  490. return Pointee->hasRHSComponent(OB);
  491. }
  492. void printLeft(OutputBuffer &OB) const override {
  493. // We rewrite objc_object<SomeProtocol>* into id<SomeProtocol>.
  494. if (Pointee->getKind() != KObjCProtoName ||
  495. !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
  496. Pointee->printLeft(OB);
  497. if (Pointee->hasArray(OB))
  498. OB += " ";
  499. if (Pointee->hasArray(OB) || Pointee->hasFunction(OB))
  500. OB += "(";
  501. OB += "*";
  502. } else {
  503. const auto *objcProto = static_cast<const ObjCProtoName *>(Pointee);
  504. OB += "id<";
  505. OB += objcProto->Protocol;
  506. OB += ">";
  507. }
  508. }
  509. void printRight(OutputBuffer &OB) const override {
  510. if (Pointee->getKind() != KObjCProtoName ||
  511. !static_cast<const ObjCProtoName *>(Pointee)->isObjCObject()) {
  512. if (Pointee->hasArray(OB) || Pointee->hasFunction(OB))
  513. OB += ")";
  514. Pointee->printRight(OB);
  515. }
  516. }
  517. };
  518. enum class ReferenceKind {
  519. LValue,
  520. RValue,
  521. };
  522. // Represents either a LValue or an RValue reference type.
  523. class ReferenceType : public Node {
  524. const Node *Pointee;
  525. ReferenceKind RK;
  526. mutable bool Printing = false;
  527. // Dig through any refs to refs, collapsing the ReferenceTypes as we go. The
  528. // rule here is rvalue ref to rvalue ref collapses to a rvalue ref, and any
  529. // other combination collapses to a lvalue ref.
  530. //
  531. // A combination of a TemplateForwardReference and a back-ref Substitution
  532. // from an ill-formed string may have created a cycle; use cycle detection to
  533. // avoid looping forever.
  534. std::pair<ReferenceKind, const Node *> collapse(OutputBuffer &OB) const {
  535. auto SoFar = std::make_pair(RK, Pointee);
  536. // Track the chain of nodes for the Floyd's 'tortoise and hare'
  537. // cycle-detection algorithm, since getSyntaxNode(S) is impure
  538. PODSmallVector<const Node *, 8> Prev;
  539. for (;;) {
  540. const Node *SN = SoFar.second->getSyntaxNode(OB);
  541. if (SN->getKind() != KReferenceType)
  542. break;
  543. auto *RT = static_cast<const ReferenceType *>(SN);
  544. SoFar.second = RT->Pointee;
  545. SoFar.first = std::min(SoFar.first, RT->RK);
  546. // The middle of Prev is the 'slow' pointer moving at half speed
  547. Prev.push_back(SoFar.second);
  548. if (Prev.size() > 1 && SoFar.second == Prev[(Prev.size() - 1) / 2]) {
  549. // Cycle detected
  550. SoFar.second = nullptr;
  551. break;
  552. }
  553. }
  554. return SoFar;
  555. }
  556. public:
  557. ReferenceType(const Node *Pointee_, ReferenceKind RK_)
  558. : Node(KReferenceType, Pointee_->RHSComponentCache),
  559. Pointee(Pointee_), RK(RK_) {}
  560. template<typename Fn> void match(Fn F) const { F(Pointee, RK); }
  561. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  562. return Pointee->hasRHSComponent(OB);
  563. }
  564. void printLeft(OutputBuffer &OB) const override {
  565. if (Printing)
  566. return;
  567. ScopedOverride<bool> SavePrinting(Printing, true);
  568. std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
  569. if (!Collapsed.second)
  570. return;
  571. Collapsed.second->printLeft(OB);
  572. if (Collapsed.second->hasArray(OB))
  573. OB += " ";
  574. if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
  575. OB += "(";
  576. OB += (Collapsed.first == ReferenceKind::LValue ? "&" : "&&");
  577. }
  578. void printRight(OutputBuffer &OB) const override {
  579. if (Printing)
  580. return;
  581. ScopedOverride<bool> SavePrinting(Printing, true);
  582. std::pair<ReferenceKind, const Node *> Collapsed = collapse(OB);
  583. if (!Collapsed.second)
  584. return;
  585. if (Collapsed.second->hasArray(OB) || Collapsed.second->hasFunction(OB))
  586. OB += ")";
  587. Collapsed.second->printRight(OB);
  588. }
  589. };
  590. class PointerToMemberType final : public Node {
  591. const Node *ClassType;
  592. const Node *MemberType;
  593. public:
  594. PointerToMemberType(const Node *ClassType_, const Node *MemberType_)
  595. : Node(KPointerToMemberType, MemberType_->RHSComponentCache),
  596. ClassType(ClassType_), MemberType(MemberType_) {}
  597. template<typename Fn> void match(Fn F) const { F(ClassType, MemberType); }
  598. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  599. return MemberType->hasRHSComponent(OB);
  600. }
  601. void printLeft(OutputBuffer &OB) const override {
  602. MemberType->printLeft(OB);
  603. if (MemberType->hasArray(OB) || MemberType->hasFunction(OB))
  604. OB += "(";
  605. else
  606. OB += " ";
  607. ClassType->print(OB);
  608. OB += "::*";
  609. }
  610. void printRight(OutputBuffer &OB) const override {
  611. if (MemberType->hasArray(OB) || MemberType->hasFunction(OB))
  612. OB += ")";
  613. MemberType->printRight(OB);
  614. }
  615. };
  616. class ArrayType final : public Node {
  617. const Node *Base;
  618. Node *Dimension;
  619. public:
  620. ArrayType(const Node *Base_, Node *Dimension_)
  621. : Node(KArrayType,
  622. /*RHSComponentCache=*/Cache::Yes,
  623. /*ArrayCache=*/Cache::Yes),
  624. Base(Base_), Dimension(Dimension_) {}
  625. template<typename Fn> void match(Fn F) const { F(Base, Dimension); }
  626. bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
  627. bool hasArraySlow(OutputBuffer &) const override { return true; }
  628. void printLeft(OutputBuffer &OB) const override { Base->printLeft(OB); }
  629. void printRight(OutputBuffer &OB) const override {
  630. if (OB.back() != ']')
  631. OB += " ";
  632. OB += "[";
  633. if (Dimension)
  634. Dimension->print(OB);
  635. OB += "]";
  636. Base->printRight(OB);
  637. }
  638. };
  639. class FunctionType final : public Node {
  640. const Node *Ret;
  641. NodeArray Params;
  642. Qualifiers CVQuals;
  643. FunctionRefQual RefQual;
  644. const Node *ExceptionSpec;
  645. public:
  646. FunctionType(const Node *Ret_, NodeArray Params_, Qualifiers CVQuals_,
  647. FunctionRefQual RefQual_, const Node *ExceptionSpec_)
  648. : Node(KFunctionType,
  649. /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
  650. /*FunctionCache=*/Cache::Yes),
  651. Ret(Ret_), Params(Params_), CVQuals(CVQuals_), RefQual(RefQual_),
  652. ExceptionSpec(ExceptionSpec_) {}
  653. template<typename Fn> void match(Fn F) const {
  654. F(Ret, Params, CVQuals, RefQual, ExceptionSpec);
  655. }
  656. bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
  657. bool hasFunctionSlow(OutputBuffer &) const override { return true; }
  658. // Handle C++'s ... quirky decl grammar by using the left & right
  659. // distinction. Consider:
  660. // int (*f(float))(char) {}
  661. // f is a function that takes a float and returns a pointer to a function
  662. // that takes a char and returns an int. If we're trying to print f, start
  663. // by printing out the return types's left, then print our parameters, then
  664. // finally print right of the return type.
  665. void printLeft(OutputBuffer &OB) const override {
  666. Ret->printLeft(OB);
  667. OB += " ";
  668. }
  669. void printRight(OutputBuffer &OB) const override {
  670. OB.printOpen();
  671. Params.printWithComma(OB);
  672. OB.printClose();
  673. Ret->printRight(OB);
  674. if (CVQuals & QualConst)
  675. OB += " const";
  676. if (CVQuals & QualVolatile)
  677. OB += " volatile";
  678. if (CVQuals & QualRestrict)
  679. OB += " restrict";
  680. if (RefQual == FrefQualLValue)
  681. OB += " &";
  682. else if (RefQual == FrefQualRValue)
  683. OB += " &&";
  684. if (ExceptionSpec != nullptr) {
  685. OB += ' ';
  686. ExceptionSpec->print(OB);
  687. }
  688. }
  689. };
  690. class NoexceptSpec : public Node {
  691. const Node *E;
  692. public:
  693. NoexceptSpec(const Node *E_) : Node(KNoexceptSpec), E(E_) {}
  694. template<typename Fn> void match(Fn F) const { F(E); }
  695. void printLeft(OutputBuffer &OB) const override {
  696. OB += "noexcept";
  697. OB.printOpen();
  698. E->printAsOperand(OB);
  699. OB.printClose();
  700. }
  701. };
  702. class DynamicExceptionSpec : public Node {
  703. NodeArray Types;
  704. public:
  705. DynamicExceptionSpec(NodeArray Types_)
  706. : Node(KDynamicExceptionSpec), Types(Types_) {}
  707. template<typename Fn> void match(Fn F) const { F(Types); }
  708. void printLeft(OutputBuffer &OB) const override {
  709. OB += "throw";
  710. OB.printOpen();
  711. Types.printWithComma(OB);
  712. OB.printClose();
  713. }
  714. };
  715. class FunctionEncoding final : public Node {
  716. const Node *Ret;
  717. const Node *Name;
  718. NodeArray Params;
  719. const Node *Attrs;
  720. Qualifiers CVQuals;
  721. FunctionRefQual RefQual;
  722. public:
  723. FunctionEncoding(const Node *Ret_, const Node *Name_, NodeArray Params_,
  724. const Node *Attrs_, Qualifiers CVQuals_,
  725. FunctionRefQual RefQual_)
  726. : Node(KFunctionEncoding,
  727. /*RHSComponentCache=*/Cache::Yes, /*ArrayCache=*/Cache::No,
  728. /*FunctionCache=*/Cache::Yes),
  729. Ret(Ret_), Name(Name_), Params(Params_), Attrs(Attrs_),
  730. CVQuals(CVQuals_), RefQual(RefQual_) {}
  731. template<typename Fn> void match(Fn F) const {
  732. F(Ret, Name, Params, Attrs, CVQuals, RefQual);
  733. }
  734. Qualifiers getCVQuals() const { return CVQuals; }
  735. FunctionRefQual getRefQual() const { return RefQual; }
  736. NodeArray getParams() const { return Params; }
  737. const Node *getReturnType() const { return Ret; }
  738. bool hasRHSComponentSlow(OutputBuffer &) const override { return true; }
  739. bool hasFunctionSlow(OutputBuffer &) const override { return true; }
  740. const Node *getName() const { return Name; }
  741. void printLeft(OutputBuffer &OB) const override {
  742. if (Ret) {
  743. Ret->printLeft(OB);
  744. if (!Ret->hasRHSComponent(OB))
  745. OB += " ";
  746. }
  747. Name->print(OB);
  748. }
  749. void printRight(OutputBuffer &OB) const override {
  750. OB.printOpen();
  751. Params.printWithComma(OB);
  752. OB.printClose();
  753. if (Ret)
  754. Ret->printRight(OB);
  755. if (CVQuals & QualConst)
  756. OB += " const";
  757. if (CVQuals & QualVolatile)
  758. OB += " volatile";
  759. if (CVQuals & QualRestrict)
  760. OB += " restrict";
  761. if (RefQual == FrefQualLValue)
  762. OB += " &";
  763. else if (RefQual == FrefQualRValue)
  764. OB += " &&";
  765. if (Attrs != nullptr)
  766. Attrs->print(OB);
  767. }
  768. };
  769. class LiteralOperator : public Node {
  770. const Node *OpName;
  771. public:
  772. LiteralOperator(const Node *OpName_)
  773. : Node(KLiteralOperator), OpName(OpName_) {}
  774. template<typename Fn> void match(Fn F) const { F(OpName); }
  775. void printLeft(OutputBuffer &OB) const override {
  776. OB += "operator\"\" ";
  777. OpName->print(OB);
  778. }
  779. };
  780. class SpecialName final : public Node {
  781. const std::string_view Special;
  782. const Node *Child;
  783. public:
  784. SpecialName(std::string_view Special_, const Node *Child_)
  785. : Node(KSpecialName), Special(Special_), Child(Child_) {}
  786. template<typename Fn> void match(Fn F) const { F(Special, Child); }
  787. void printLeft(OutputBuffer &OB) const override {
  788. OB += Special;
  789. Child->print(OB);
  790. }
  791. };
  792. class CtorVtableSpecialName final : public Node {
  793. const Node *FirstType;
  794. const Node *SecondType;
  795. public:
  796. CtorVtableSpecialName(const Node *FirstType_, const Node *SecondType_)
  797. : Node(KCtorVtableSpecialName),
  798. FirstType(FirstType_), SecondType(SecondType_) {}
  799. template<typename Fn> void match(Fn F) const { F(FirstType, SecondType); }
  800. void printLeft(OutputBuffer &OB) const override {
  801. OB += "construction vtable for ";
  802. FirstType->print(OB);
  803. OB += "-in-";
  804. SecondType->print(OB);
  805. }
  806. };
  807. struct NestedName : Node {
  808. Node *Qual;
  809. Node *Name;
  810. NestedName(Node *Qual_, Node *Name_)
  811. : Node(KNestedName), Qual(Qual_), Name(Name_) {}
  812. template<typename Fn> void match(Fn F) const { F(Qual, Name); }
  813. std::string_view getBaseName() const override { return Name->getBaseName(); }
  814. void printLeft(OutputBuffer &OB) const override {
  815. Qual->print(OB);
  816. OB += "::";
  817. Name->print(OB);
  818. }
  819. };
  820. struct ModuleName : Node {
  821. ModuleName *Parent;
  822. Node *Name;
  823. bool IsPartition;
  824. ModuleName(ModuleName *Parent_, Node *Name_, bool IsPartition_ = false)
  825. : Node(KModuleName), Parent(Parent_), Name(Name_),
  826. IsPartition(IsPartition_) {}
  827. template <typename Fn> void match(Fn F) const {
  828. F(Parent, Name, IsPartition);
  829. }
  830. void printLeft(OutputBuffer &OB) const override {
  831. if (Parent)
  832. Parent->print(OB);
  833. if (Parent || IsPartition)
  834. OB += IsPartition ? ':' : '.';
  835. Name->print(OB);
  836. }
  837. };
  838. struct ModuleEntity : Node {
  839. ModuleName *Module;
  840. Node *Name;
  841. ModuleEntity(ModuleName *Module_, Node *Name_)
  842. : Node(KModuleEntity), Module(Module_), Name(Name_) {}
  843. template <typename Fn> void match(Fn F) const { F(Module, Name); }
  844. std::string_view getBaseName() const override { return Name->getBaseName(); }
  845. void printLeft(OutputBuffer &OB) const override {
  846. Name->print(OB);
  847. OB += '@';
  848. Module->print(OB);
  849. }
  850. };
  851. struct LocalName : Node {
  852. Node *Encoding;
  853. Node *Entity;
  854. LocalName(Node *Encoding_, Node *Entity_)
  855. : Node(KLocalName), Encoding(Encoding_), Entity(Entity_) {}
  856. template<typename Fn> void match(Fn F) const { F(Encoding, Entity); }
  857. void printLeft(OutputBuffer &OB) const override {
  858. Encoding->print(OB);
  859. OB += "::";
  860. Entity->print(OB);
  861. }
  862. };
  863. class QualifiedName final : public Node {
  864. // qualifier::name
  865. const Node *Qualifier;
  866. const Node *Name;
  867. public:
  868. QualifiedName(const Node *Qualifier_, const Node *Name_)
  869. : Node(KQualifiedName), Qualifier(Qualifier_), Name(Name_) {}
  870. template<typename Fn> void match(Fn F) const { F(Qualifier, Name); }
  871. std::string_view getBaseName() const override { return Name->getBaseName(); }
  872. void printLeft(OutputBuffer &OB) const override {
  873. Qualifier->print(OB);
  874. OB += "::";
  875. Name->print(OB);
  876. }
  877. };
  878. class VectorType final : public Node {
  879. const Node *BaseType;
  880. const Node *Dimension;
  881. public:
  882. VectorType(const Node *BaseType_, const Node *Dimension_)
  883. : Node(KVectorType), BaseType(BaseType_), Dimension(Dimension_) {}
  884. const Node *getBaseType() const { return BaseType; }
  885. const Node *getDimension() const { return Dimension; }
  886. template<typename Fn> void match(Fn F) const { F(BaseType, Dimension); }
  887. void printLeft(OutputBuffer &OB) const override {
  888. BaseType->print(OB);
  889. OB += " vector[";
  890. if (Dimension)
  891. Dimension->print(OB);
  892. OB += "]";
  893. }
  894. };
  895. class PixelVectorType final : public Node {
  896. const Node *Dimension;
  897. public:
  898. PixelVectorType(const Node *Dimension_)
  899. : Node(KPixelVectorType), Dimension(Dimension_) {}
  900. template<typename Fn> void match(Fn F) const { F(Dimension); }
  901. void printLeft(OutputBuffer &OB) const override {
  902. // FIXME: This should demangle as "vector pixel".
  903. OB += "pixel vector[";
  904. Dimension->print(OB);
  905. OB += "]";
  906. }
  907. };
  908. class BinaryFPType final : public Node {
  909. const Node *Dimension;
  910. public:
  911. BinaryFPType(const Node *Dimension_)
  912. : Node(KBinaryFPType), Dimension(Dimension_) {}
  913. template<typename Fn> void match(Fn F) const { F(Dimension); }
  914. void printLeft(OutputBuffer &OB) const override {
  915. OB += "_Float";
  916. Dimension->print(OB);
  917. }
  918. };
  919. enum class TemplateParamKind { Type, NonType, Template };
  920. /// An invented name for a template parameter for which we don't have a
  921. /// corresponding template argument.
  922. ///
  923. /// This node is created when parsing the <lambda-sig> for a lambda with
  924. /// explicit template arguments, which might be referenced in the parameter
  925. /// types appearing later in the <lambda-sig>.
  926. class SyntheticTemplateParamName final : public Node {
  927. TemplateParamKind Kind;
  928. unsigned Index;
  929. public:
  930. SyntheticTemplateParamName(TemplateParamKind Kind_, unsigned Index_)
  931. : Node(KSyntheticTemplateParamName), Kind(Kind_), Index(Index_) {}
  932. template<typename Fn> void match(Fn F) const { F(Kind, Index); }
  933. void printLeft(OutputBuffer &OB) const override {
  934. switch (Kind) {
  935. case TemplateParamKind::Type:
  936. OB += "$T";
  937. break;
  938. case TemplateParamKind::NonType:
  939. OB += "$N";
  940. break;
  941. case TemplateParamKind::Template:
  942. OB += "$TT";
  943. break;
  944. }
  945. if (Index > 0)
  946. OB << Index - 1;
  947. }
  948. };
  949. /// A template type parameter declaration, 'typename T'.
  950. class TypeTemplateParamDecl final : public Node {
  951. Node *Name;
  952. public:
  953. TypeTemplateParamDecl(Node *Name_)
  954. : Node(KTypeTemplateParamDecl, Cache::Yes), Name(Name_) {}
  955. template<typename Fn> void match(Fn F) const { F(Name); }
  956. void printLeft(OutputBuffer &OB) const override { OB += "typename "; }
  957. void printRight(OutputBuffer &OB) const override { Name->print(OB); }
  958. };
  959. /// A non-type template parameter declaration, 'int N'.
  960. class NonTypeTemplateParamDecl final : public Node {
  961. Node *Name;
  962. Node *Type;
  963. public:
  964. NonTypeTemplateParamDecl(Node *Name_, Node *Type_)
  965. : Node(KNonTypeTemplateParamDecl, Cache::Yes), Name(Name_), Type(Type_) {}
  966. template<typename Fn> void match(Fn F) const { F(Name, Type); }
  967. void printLeft(OutputBuffer &OB) const override {
  968. Type->printLeft(OB);
  969. if (!Type->hasRHSComponent(OB))
  970. OB += " ";
  971. }
  972. void printRight(OutputBuffer &OB) const override {
  973. Name->print(OB);
  974. Type->printRight(OB);
  975. }
  976. };
  977. /// A template template parameter declaration,
  978. /// 'template<typename T> typename N'.
  979. class TemplateTemplateParamDecl final : public Node {
  980. Node *Name;
  981. NodeArray Params;
  982. public:
  983. TemplateTemplateParamDecl(Node *Name_, NodeArray Params_)
  984. : Node(KTemplateTemplateParamDecl, Cache::Yes), Name(Name_),
  985. Params(Params_) {}
  986. template<typename Fn> void match(Fn F) const { F(Name, Params); }
  987. void printLeft(OutputBuffer &OB) const override {
  988. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  989. OB += "template<";
  990. Params.printWithComma(OB);
  991. OB += "> typename ";
  992. }
  993. void printRight(OutputBuffer &OB) const override { Name->print(OB); }
  994. };
  995. /// A template parameter pack declaration, 'typename ...T'.
  996. class TemplateParamPackDecl final : public Node {
  997. Node *Param;
  998. public:
  999. TemplateParamPackDecl(Node *Param_)
  1000. : Node(KTemplateParamPackDecl, Cache::Yes), Param(Param_) {}
  1001. template<typename Fn> void match(Fn F) const { F(Param); }
  1002. void printLeft(OutputBuffer &OB) const override {
  1003. Param->printLeft(OB);
  1004. OB += "...";
  1005. }
  1006. void printRight(OutputBuffer &OB) const override { Param->printRight(OB); }
  1007. };
  1008. /// An unexpanded parameter pack (either in the expression or type context). If
  1009. /// this AST is correct, this node will have a ParameterPackExpansion node above
  1010. /// it.
  1011. ///
  1012. /// This node is created when some <template-args> are found that apply to an
  1013. /// <encoding>, and is stored in the TemplateParams table. In order for this to
  1014. /// appear in the final AST, it has to referenced via a <template-param> (ie,
  1015. /// T_).
  1016. class ParameterPack final : public Node {
  1017. NodeArray Data;
  1018. // Setup OutputBuffer for a pack expansion, unless we're already expanding
  1019. // one.
  1020. void initializePackExpansion(OutputBuffer &OB) const {
  1021. if (OB.CurrentPackMax == std::numeric_limits<unsigned>::max()) {
  1022. OB.CurrentPackMax = static_cast<unsigned>(Data.size());
  1023. OB.CurrentPackIndex = 0;
  1024. }
  1025. }
  1026. public:
  1027. ParameterPack(NodeArray Data_) : Node(KParameterPack), Data(Data_) {
  1028. ArrayCache = FunctionCache = RHSComponentCache = Cache::Unknown;
  1029. if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
  1030. return P->ArrayCache == Cache::No;
  1031. }))
  1032. ArrayCache = Cache::No;
  1033. if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
  1034. return P->FunctionCache == Cache::No;
  1035. }))
  1036. FunctionCache = Cache::No;
  1037. if (std::all_of(Data.begin(), Data.end(), [](Node* P) {
  1038. return P->RHSComponentCache == Cache::No;
  1039. }))
  1040. RHSComponentCache = Cache::No;
  1041. }
  1042. template<typename Fn> void match(Fn F) const { F(Data); }
  1043. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  1044. initializePackExpansion(OB);
  1045. size_t Idx = OB.CurrentPackIndex;
  1046. return Idx < Data.size() && Data[Idx]->hasRHSComponent(OB);
  1047. }
  1048. bool hasArraySlow(OutputBuffer &OB) const override {
  1049. initializePackExpansion(OB);
  1050. size_t Idx = OB.CurrentPackIndex;
  1051. return Idx < Data.size() && Data[Idx]->hasArray(OB);
  1052. }
  1053. bool hasFunctionSlow(OutputBuffer &OB) const override {
  1054. initializePackExpansion(OB);
  1055. size_t Idx = OB.CurrentPackIndex;
  1056. return Idx < Data.size() && Data[Idx]->hasFunction(OB);
  1057. }
  1058. const Node *getSyntaxNode(OutputBuffer &OB) const override {
  1059. initializePackExpansion(OB);
  1060. size_t Idx = OB.CurrentPackIndex;
  1061. return Idx < Data.size() ? Data[Idx]->getSyntaxNode(OB) : this;
  1062. }
  1063. void printLeft(OutputBuffer &OB) const override {
  1064. initializePackExpansion(OB);
  1065. size_t Idx = OB.CurrentPackIndex;
  1066. if (Idx < Data.size())
  1067. Data[Idx]->printLeft(OB);
  1068. }
  1069. void printRight(OutputBuffer &OB) const override {
  1070. initializePackExpansion(OB);
  1071. size_t Idx = OB.CurrentPackIndex;
  1072. if (Idx < Data.size())
  1073. Data[Idx]->printRight(OB);
  1074. }
  1075. };
  1076. /// A variadic template argument. This node represents an occurrence of
  1077. /// J<something>E in some <template-args>. It isn't itself unexpanded, unless
  1078. /// one of it's Elements is. The parser inserts a ParameterPack into the
  1079. /// TemplateParams table if the <template-args> this pack belongs to apply to an
  1080. /// <encoding>.
  1081. class TemplateArgumentPack final : public Node {
  1082. NodeArray Elements;
  1083. public:
  1084. TemplateArgumentPack(NodeArray Elements_)
  1085. : Node(KTemplateArgumentPack), Elements(Elements_) {}
  1086. template<typename Fn> void match(Fn F) const { F(Elements); }
  1087. NodeArray getElements() const { return Elements; }
  1088. void printLeft(OutputBuffer &OB) const override {
  1089. Elements.printWithComma(OB);
  1090. }
  1091. };
  1092. /// A pack expansion. Below this node, there are some unexpanded ParameterPacks
  1093. /// which each have Child->ParameterPackSize elements.
  1094. class ParameterPackExpansion final : public Node {
  1095. const Node *Child;
  1096. public:
  1097. ParameterPackExpansion(const Node *Child_)
  1098. : Node(KParameterPackExpansion), Child(Child_) {}
  1099. template<typename Fn> void match(Fn F) const { F(Child); }
  1100. const Node *getChild() const { return Child; }
  1101. void printLeft(OutputBuffer &OB) const override {
  1102. constexpr unsigned Max = std::numeric_limits<unsigned>::max();
  1103. ScopedOverride<unsigned> SavePackIdx(OB.CurrentPackIndex, Max);
  1104. ScopedOverride<unsigned> SavePackMax(OB.CurrentPackMax, Max);
  1105. size_t StreamPos = OB.getCurrentPosition();
  1106. // Print the first element in the pack. If Child contains a ParameterPack,
  1107. // it will set up S.CurrentPackMax and print the first element.
  1108. Child->print(OB);
  1109. // No ParameterPack was found in Child. This can occur if we've found a pack
  1110. // expansion on a <function-param>.
  1111. if (OB.CurrentPackMax == Max) {
  1112. OB += "...";
  1113. return;
  1114. }
  1115. // We found a ParameterPack, but it has no elements. Erase whatever we may
  1116. // of printed.
  1117. if (OB.CurrentPackMax == 0) {
  1118. OB.setCurrentPosition(StreamPos);
  1119. return;
  1120. }
  1121. // Else, iterate through the rest of the elements in the pack.
  1122. for (unsigned I = 1, E = OB.CurrentPackMax; I < E; ++I) {
  1123. OB += ", ";
  1124. OB.CurrentPackIndex = I;
  1125. Child->print(OB);
  1126. }
  1127. }
  1128. };
  1129. class TemplateArgs final : public Node {
  1130. NodeArray Params;
  1131. public:
  1132. TemplateArgs(NodeArray Params_) : Node(KTemplateArgs), Params(Params_) {}
  1133. template<typename Fn> void match(Fn F) const { F(Params); }
  1134. NodeArray getParams() { return Params; }
  1135. void printLeft(OutputBuffer &OB) const override {
  1136. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  1137. OB += "<";
  1138. Params.printWithComma(OB);
  1139. OB += ">";
  1140. }
  1141. };
  1142. /// A forward-reference to a template argument that was not known at the point
  1143. /// where the template parameter name was parsed in a mangling.
  1144. ///
  1145. /// This is created when demangling the name of a specialization of a
  1146. /// conversion function template:
  1147. ///
  1148. /// \code
  1149. /// struct A {
  1150. /// template<typename T> operator T*();
  1151. /// };
  1152. /// \endcode
  1153. ///
  1154. /// When demangling a specialization of the conversion function template, we
  1155. /// encounter the name of the template (including the \c T) before we reach
  1156. /// the template argument list, so we cannot substitute the parameter name
  1157. /// for the corresponding argument while parsing. Instead, we create a
  1158. /// \c ForwardTemplateReference node that is resolved after we parse the
  1159. /// template arguments.
  1160. struct ForwardTemplateReference : Node {
  1161. size_t Index;
  1162. Node *Ref = nullptr;
  1163. // If we're currently printing this node. It is possible (though invalid) for
  1164. // a forward template reference to refer to itself via a substitution. This
  1165. // creates a cyclic AST, which will stack overflow printing. To fix this, bail
  1166. // out if more than one print* function is active.
  1167. mutable bool Printing = false;
  1168. ForwardTemplateReference(size_t Index_)
  1169. : Node(KForwardTemplateReference, Cache::Unknown, Cache::Unknown,
  1170. Cache::Unknown),
  1171. Index(Index_) {}
  1172. // We don't provide a matcher for these, because the value of the node is
  1173. // not determined by its construction parameters, and it generally needs
  1174. // special handling.
  1175. template<typename Fn> void match(Fn F) const = delete;
  1176. bool hasRHSComponentSlow(OutputBuffer &OB) const override {
  1177. if (Printing)
  1178. return false;
  1179. ScopedOverride<bool> SavePrinting(Printing, true);
  1180. return Ref->hasRHSComponent(OB);
  1181. }
  1182. bool hasArraySlow(OutputBuffer &OB) const override {
  1183. if (Printing)
  1184. return false;
  1185. ScopedOverride<bool> SavePrinting(Printing, true);
  1186. return Ref->hasArray(OB);
  1187. }
  1188. bool hasFunctionSlow(OutputBuffer &OB) const override {
  1189. if (Printing)
  1190. return false;
  1191. ScopedOverride<bool> SavePrinting(Printing, true);
  1192. return Ref->hasFunction(OB);
  1193. }
  1194. const Node *getSyntaxNode(OutputBuffer &OB) const override {
  1195. if (Printing)
  1196. return this;
  1197. ScopedOverride<bool> SavePrinting(Printing, true);
  1198. return Ref->getSyntaxNode(OB);
  1199. }
  1200. void printLeft(OutputBuffer &OB) const override {
  1201. if (Printing)
  1202. return;
  1203. ScopedOverride<bool> SavePrinting(Printing, true);
  1204. Ref->printLeft(OB);
  1205. }
  1206. void printRight(OutputBuffer &OB) const override {
  1207. if (Printing)
  1208. return;
  1209. ScopedOverride<bool> SavePrinting(Printing, true);
  1210. Ref->printRight(OB);
  1211. }
  1212. };
  1213. struct NameWithTemplateArgs : Node {
  1214. // name<template_args>
  1215. Node *Name;
  1216. Node *TemplateArgs;
  1217. NameWithTemplateArgs(Node *Name_, Node *TemplateArgs_)
  1218. : Node(KNameWithTemplateArgs), Name(Name_), TemplateArgs(TemplateArgs_) {}
  1219. template<typename Fn> void match(Fn F) const { F(Name, TemplateArgs); }
  1220. std::string_view getBaseName() const override { return Name->getBaseName(); }
  1221. void printLeft(OutputBuffer &OB) const override {
  1222. Name->print(OB);
  1223. TemplateArgs->print(OB);
  1224. }
  1225. };
  1226. class GlobalQualifiedName final : public Node {
  1227. Node *Child;
  1228. public:
  1229. GlobalQualifiedName(Node* Child_)
  1230. : Node(KGlobalQualifiedName), Child(Child_) {}
  1231. template<typename Fn> void match(Fn F) const { F(Child); }
  1232. std::string_view getBaseName() const override { return Child->getBaseName(); }
  1233. void printLeft(OutputBuffer &OB) const override {
  1234. OB += "::";
  1235. Child->print(OB);
  1236. }
  1237. };
  1238. enum class SpecialSubKind {
  1239. allocator,
  1240. basic_string,
  1241. string,
  1242. istream,
  1243. ostream,
  1244. iostream,
  1245. };
  1246. class SpecialSubstitution;
  1247. class ExpandedSpecialSubstitution : public Node {
  1248. protected:
  1249. SpecialSubKind SSK;
  1250. ExpandedSpecialSubstitution(SpecialSubKind SSK_, Kind K_)
  1251. : Node(K_), SSK(SSK_) {}
  1252. public:
  1253. ExpandedSpecialSubstitution(SpecialSubKind SSK_)
  1254. : ExpandedSpecialSubstitution(SSK_, KExpandedSpecialSubstitution) {}
  1255. inline ExpandedSpecialSubstitution(SpecialSubstitution const *);
  1256. template<typename Fn> void match(Fn F) const { F(SSK); }
  1257. protected:
  1258. bool isInstantiation() const {
  1259. return unsigned(SSK) >= unsigned(SpecialSubKind::string);
  1260. }
  1261. std::string_view getBaseName() const override {
  1262. switch (SSK) {
  1263. case SpecialSubKind::allocator:
  1264. return {"allocator"};
  1265. case SpecialSubKind::basic_string:
  1266. return {"basic_string"};
  1267. case SpecialSubKind::string:
  1268. return {"basic_string"};
  1269. case SpecialSubKind::istream:
  1270. return {"basic_istream"};
  1271. case SpecialSubKind::ostream:
  1272. return {"basic_ostream"};
  1273. case SpecialSubKind::iostream:
  1274. return {"basic_iostream"};
  1275. }
  1276. DEMANGLE_UNREACHABLE;
  1277. }
  1278. private:
  1279. void printLeft(OutputBuffer &OB) const override {
  1280. OB << "std::" << getBaseName();
  1281. if (isInstantiation()) {
  1282. OB << "<char, std::char_traits<char>";
  1283. if (SSK == SpecialSubKind::string)
  1284. OB << ", std::allocator<char>";
  1285. OB << ">";
  1286. }
  1287. }
  1288. };
  1289. class SpecialSubstitution final : public ExpandedSpecialSubstitution {
  1290. public:
  1291. SpecialSubstitution(SpecialSubKind SSK_)
  1292. : ExpandedSpecialSubstitution(SSK_, KSpecialSubstitution) {}
  1293. template<typename Fn> void match(Fn F) const { F(SSK); }
  1294. std::string_view getBaseName() const override {
  1295. std::string_view SV = ExpandedSpecialSubstitution::getBaseName();
  1296. if (isInstantiation()) {
  1297. // The instantiations are typedefs that drop the "basic_" prefix.
  1298. assert(llvm::itanium_demangle::starts_with(SV, "basic_"));
  1299. SV.remove_prefix(sizeof("basic_") - 1);
  1300. }
  1301. return SV;
  1302. }
  1303. void printLeft(OutputBuffer &OB) const override {
  1304. OB << "std::" << getBaseName();
  1305. }
  1306. };
  1307. inline ExpandedSpecialSubstitution::ExpandedSpecialSubstitution(
  1308. SpecialSubstitution const *SS)
  1309. : ExpandedSpecialSubstitution(SS->SSK) {}
  1310. class CtorDtorName final : public Node {
  1311. const Node *Basename;
  1312. const bool IsDtor;
  1313. const int Variant;
  1314. public:
  1315. CtorDtorName(const Node *Basename_, bool IsDtor_, int Variant_)
  1316. : Node(KCtorDtorName), Basename(Basename_), IsDtor(IsDtor_),
  1317. Variant(Variant_) {}
  1318. template<typename Fn> void match(Fn F) const { F(Basename, IsDtor, Variant); }
  1319. void printLeft(OutputBuffer &OB) const override {
  1320. if (IsDtor)
  1321. OB += "~";
  1322. OB += Basename->getBaseName();
  1323. }
  1324. };
  1325. class DtorName : public Node {
  1326. const Node *Base;
  1327. public:
  1328. DtorName(const Node *Base_) : Node(KDtorName), Base(Base_) {}
  1329. template<typename Fn> void match(Fn F) const { F(Base); }
  1330. void printLeft(OutputBuffer &OB) const override {
  1331. OB += "~";
  1332. Base->printLeft(OB);
  1333. }
  1334. };
  1335. class UnnamedTypeName : public Node {
  1336. const std::string_view Count;
  1337. public:
  1338. UnnamedTypeName(std::string_view Count_)
  1339. : Node(KUnnamedTypeName), Count(Count_) {}
  1340. template<typename Fn> void match(Fn F) const { F(Count); }
  1341. void printLeft(OutputBuffer &OB) const override {
  1342. OB += "'unnamed";
  1343. OB += Count;
  1344. OB += "\'";
  1345. }
  1346. };
  1347. class ClosureTypeName : public Node {
  1348. NodeArray TemplateParams;
  1349. NodeArray Params;
  1350. std::string_view Count;
  1351. public:
  1352. ClosureTypeName(NodeArray TemplateParams_, NodeArray Params_,
  1353. std::string_view Count_)
  1354. : Node(KClosureTypeName), TemplateParams(TemplateParams_),
  1355. Params(Params_), Count(Count_) {}
  1356. template<typename Fn> void match(Fn F) const {
  1357. F(TemplateParams, Params, Count);
  1358. }
  1359. void printDeclarator(OutputBuffer &OB) const {
  1360. if (!TemplateParams.empty()) {
  1361. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  1362. OB += "<";
  1363. TemplateParams.printWithComma(OB);
  1364. OB += ">";
  1365. }
  1366. OB.printOpen();
  1367. Params.printWithComma(OB);
  1368. OB.printClose();
  1369. }
  1370. void printLeft(OutputBuffer &OB) const override {
  1371. OB += "\'lambda";
  1372. OB += Count;
  1373. OB += "\'";
  1374. printDeclarator(OB);
  1375. }
  1376. };
  1377. class StructuredBindingName : public Node {
  1378. NodeArray Bindings;
  1379. public:
  1380. StructuredBindingName(NodeArray Bindings_)
  1381. : Node(KStructuredBindingName), Bindings(Bindings_) {}
  1382. template<typename Fn> void match(Fn F) const { F(Bindings); }
  1383. void printLeft(OutputBuffer &OB) const override {
  1384. OB.printOpen('[');
  1385. Bindings.printWithComma(OB);
  1386. OB.printClose(']');
  1387. }
  1388. };
  1389. // -- Expression Nodes --
  1390. class BinaryExpr : public Node {
  1391. const Node *LHS;
  1392. const std::string_view InfixOperator;
  1393. const Node *RHS;
  1394. public:
  1395. BinaryExpr(const Node *LHS_, std::string_view InfixOperator_,
  1396. const Node *RHS_, Prec Prec_)
  1397. : Node(KBinaryExpr, Prec_), LHS(LHS_), InfixOperator(InfixOperator_),
  1398. RHS(RHS_) {}
  1399. template <typename Fn> void match(Fn F) const {
  1400. F(LHS, InfixOperator, RHS, getPrecedence());
  1401. }
  1402. void printLeft(OutputBuffer &OB) const override {
  1403. bool ParenAll = OB.isGtInsideTemplateArgs() &&
  1404. (InfixOperator == ">" || InfixOperator == ">>");
  1405. if (ParenAll)
  1406. OB.printOpen();
  1407. // Assignment is right associative, with special LHS precedence.
  1408. bool IsAssign = getPrecedence() == Prec::Assign;
  1409. LHS->printAsOperand(OB, IsAssign ? Prec::OrIf : getPrecedence(), !IsAssign);
  1410. // No space before comma operator
  1411. if (!(InfixOperator == ","))
  1412. OB += " ";
  1413. OB += InfixOperator;
  1414. OB += " ";
  1415. RHS->printAsOperand(OB, getPrecedence(), IsAssign);
  1416. if (ParenAll)
  1417. OB.printClose();
  1418. }
  1419. };
  1420. class ArraySubscriptExpr : public Node {
  1421. const Node *Op1;
  1422. const Node *Op2;
  1423. public:
  1424. ArraySubscriptExpr(const Node *Op1_, const Node *Op2_, Prec Prec_)
  1425. : Node(KArraySubscriptExpr, Prec_), Op1(Op1_), Op2(Op2_) {}
  1426. template <typename Fn> void match(Fn F) const {
  1427. F(Op1, Op2, getPrecedence());
  1428. }
  1429. void printLeft(OutputBuffer &OB) const override {
  1430. Op1->printAsOperand(OB, getPrecedence());
  1431. OB.printOpen('[');
  1432. Op2->printAsOperand(OB);
  1433. OB.printClose(']');
  1434. }
  1435. };
  1436. class PostfixExpr : public Node {
  1437. const Node *Child;
  1438. const std::string_view Operator;
  1439. public:
  1440. PostfixExpr(const Node *Child_, std::string_view Operator_, Prec Prec_)
  1441. : Node(KPostfixExpr, Prec_), Child(Child_), Operator(Operator_) {}
  1442. template <typename Fn> void match(Fn F) const {
  1443. F(Child, Operator, getPrecedence());
  1444. }
  1445. void printLeft(OutputBuffer &OB) const override {
  1446. Child->printAsOperand(OB, getPrecedence(), true);
  1447. OB += Operator;
  1448. }
  1449. };
  1450. class ConditionalExpr : public Node {
  1451. const Node *Cond;
  1452. const Node *Then;
  1453. const Node *Else;
  1454. public:
  1455. ConditionalExpr(const Node *Cond_, const Node *Then_, const Node *Else_,
  1456. Prec Prec_)
  1457. : Node(KConditionalExpr, Prec_), Cond(Cond_), Then(Then_), Else(Else_) {}
  1458. template <typename Fn> void match(Fn F) const {
  1459. F(Cond, Then, Else, getPrecedence());
  1460. }
  1461. void printLeft(OutputBuffer &OB) const override {
  1462. Cond->printAsOperand(OB, getPrecedence());
  1463. OB += " ? ";
  1464. Then->printAsOperand(OB);
  1465. OB += " : ";
  1466. Else->printAsOperand(OB, Prec::Assign, true);
  1467. }
  1468. };
  1469. class MemberExpr : public Node {
  1470. const Node *LHS;
  1471. const std::string_view Kind;
  1472. const Node *RHS;
  1473. public:
  1474. MemberExpr(const Node *LHS_, std::string_view Kind_, const Node *RHS_,
  1475. Prec Prec_)
  1476. : Node(KMemberExpr, Prec_), LHS(LHS_), Kind(Kind_), RHS(RHS_) {}
  1477. template <typename Fn> void match(Fn F) const {
  1478. F(LHS, Kind, RHS, getPrecedence());
  1479. }
  1480. void printLeft(OutputBuffer &OB) const override {
  1481. LHS->printAsOperand(OB, getPrecedence(), true);
  1482. OB += Kind;
  1483. RHS->printAsOperand(OB, getPrecedence(), false);
  1484. }
  1485. };
  1486. class SubobjectExpr : public Node {
  1487. const Node *Type;
  1488. const Node *SubExpr;
  1489. std::string_view Offset;
  1490. NodeArray UnionSelectors;
  1491. bool OnePastTheEnd;
  1492. public:
  1493. SubobjectExpr(const Node *Type_, const Node *SubExpr_,
  1494. std::string_view Offset_, NodeArray UnionSelectors_,
  1495. bool OnePastTheEnd_)
  1496. : Node(KSubobjectExpr), Type(Type_), SubExpr(SubExpr_), Offset(Offset_),
  1497. UnionSelectors(UnionSelectors_), OnePastTheEnd(OnePastTheEnd_) {}
  1498. template<typename Fn> void match(Fn F) const {
  1499. F(Type, SubExpr, Offset, UnionSelectors, OnePastTheEnd);
  1500. }
  1501. void printLeft(OutputBuffer &OB) const override {
  1502. SubExpr->print(OB);
  1503. OB += ".<";
  1504. Type->print(OB);
  1505. OB += " at offset ";
  1506. if (Offset.empty()) {
  1507. OB += "0";
  1508. } else if (Offset[0] == 'n') {
  1509. OB += "-";
  1510. OB += std::string_view(Offset.data() + 1, Offset.size() - 1);
  1511. } else {
  1512. OB += Offset;
  1513. }
  1514. OB += ">";
  1515. }
  1516. };
  1517. class EnclosingExpr : public Node {
  1518. const std::string_view Prefix;
  1519. const Node *Infix;
  1520. const std::string_view Postfix;
  1521. public:
  1522. EnclosingExpr(std::string_view Prefix_, const Node *Infix_,
  1523. Prec Prec_ = Prec::Primary)
  1524. : Node(KEnclosingExpr, Prec_), Prefix(Prefix_), Infix(Infix_) {}
  1525. template <typename Fn> void match(Fn F) const {
  1526. F(Prefix, Infix, getPrecedence());
  1527. }
  1528. void printLeft(OutputBuffer &OB) const override {
  1529. OB += Prefix;
  1530. OB.printOpen();
  1531. Infix->print(OB);
  1532. OB.printClose();
  1533. OB += Postfix;
  1534. }
  1535. };
  1536. class CastExpr : public Node {
  1537. // cast_kind<to>(from)
  1538. const std::string_view CastKind;
  1539. const Node *To;
  1540. const Node *From;
  1541. public:
  1542. CastExpr(std::string_view CastKind_, const Node *To_, const Node *From_,
  1543. Prec Prec_)
  1544. : Node(KCastExpr, Prec_), CastKind(CastKind_), To(To_), From(From_) {}
  1545. template <typename Fn> void match(Fn F) const {
  1546. F(CastKind, To, From, getPrecedence());
  1547. }
  1548. void printLeft(OutputBuffer &OB) const override {
  1549. OB += CastKind;
  1550. {
  1551. ScopedOverride<unsigned> LT(OB.GtIsGt, 0);
  1552. OB += "<";
  1553. To->printLeft(OB);
  1554. OB += ">";
  1555. }
  1556. OB.printOpen();
  1557. From->printAsOperand(OB);
  1558. OB.printClose();
  1559. }
  1560. };
  1561. class SizeofParamPackExpr : public Node {
  1562. const Node *Pack;
  1563. public:
  1564. SizeofParamPackExpr(const Node *Pack_)
  1565. : Node(KSizeofParamPackExpr), Pack(Pack_) {}
  1566. template<typename Fn> void match(Fn F) const { F(Pack); }
  1567. void printLeft(OutputBuffer &OB) const override {
  1568. OB += "sizeof...";
  1569. OB.printOpen();
  1570. ParameterPackExpansion PPE(Pack);
  1571. PPE.printLeft(OB);
  1572. OB.printClose();
  1573. }
  1574. };
  1575. class CallExpr : public Node {
  1576. const Node *Callee;
  1577. NodeArray Args;
  1578. public:
  1579. CallExpr(const Node *Callee_, NodeArray Args_, Prec Prec_)
  1580. : Node(KCallExpr, Prec_), Callee(Callee_), Args(Args_) {}
  1581. template <typename Fn> void match(Fn F) const {
  1582. F(Callee, Args, getPrecedence());
  1583. }
  1584. void printLeft(OutputBuffer &OB) const override {
  1585. Callee->print(OB);
  1586. OB.printOpen();
  1587. Args.printWithComma(OB);
  1588. OB.printClose();
  1589. }
  1590. };
  1591. class NewExpr : public Node {
  1592. // new (expr_list) type(init_list)
  1593. NodeArray ExprList;
  1594. Node *Type;
  1595. NodeArray InitList;
  1596. bool IsGlobal; // ::operator new ?
  1597. bool IsArray; // new[] ?
  1598. public:
  1599. NewExpr(NodeArray ExprList_, Node *Type_, NodeArray InitList_, bool IsGlobal_,
  1600. bool IsArray_, Prec Prec_)
  1601. : Node(KNewExpr, Prec_), ExprList(ExprList_), Type(Type_),
  1602. InitList(InitList_), IsGlobal(IsGlobal_), IsArray(IsArray_) {}
  1603. template<typename Fn> void match(Fn F) const {
  1604. F(ExprList, Type, InitList, IsGlobal, IsArray, getPrecedence());
  1605. }
  1606. void printLeft(OutputBuffer &OB) const override {
  1607. if (IsGlobal)
  1608. OB += "::";
  1609. OB += "new";
  1610. if (IsArray)
  1611. OB += "[]";
  1612. if (!ExprList.empty()) {
  1613. OB.printOpen();
  1614. ExprList.printWithComma(OB);
  1615. OB.printClose();
  1616. }
  1617. OB += " ";
  1618. Type->print(OB);
  1619. if (!InitList.empty()) {
  1620. OB.printOpen();
  1621. InitList.printWithComma(OB);
  1622. OB.printClose();
  1623. }
  1624. }
  1625. };
  1626. class DeleteExpr : public Node {
  1627. Node *Op;
  1628. bool IsGlobal;
  1629. bool IsArray;
  1630. public:
  1631. DeleteExpr(Node *Op_, bool IsGlobal_, bool IsArray_, Prec Prec_)
  1632. : Node(KDeleteExpr, Prec_), Op(Op_), IsGlobal(IsGlobal_),
  1633. IsArray(IsArray_) {}
  1634. template <typename Fn> void match(Fn F) const {
  1635. F(Op, IsGlobal, IsArray, getPrecedence());
  1636. }
  1637. void printLeft(OutputBuffer &OB) const override {
  1638. if (IsGlobal)
  1639. OB += "::";
  1640. OB += "delete";
  1641. if (IsArray)
  1642. OB += "[]";
  1643. OB += ' ';
  1644. Op->print(OB);
  1645. }
  1646. };
  1647. class PrefixExpr : public Node {
  1648. std::string_view Prefix;
  1649. Node *Child;
  1650. public:
  1651. PrefixExpr(std::string_view Prefix_, Node *Child_, Prec Prec_)
  1652. : Node(KPrefixExpr, Prec_), Prefix(Prefix_), Child(Child_) {}
  1653. template <typename Fn> void match(Fn F) const {
  1654. F(Prefix, Child, getPrecedence());
  1655. }
  1656. void printLeft(OutputBuffer &OB) const override {
  1657. OB += Prefix;
  1658. Child->printAsOperand(OB, getPrecedence());
  1659. }
  1660. };
  1661. class FunctionParam : public Node {
  1662. std::string_view Number;
  1663. public:
  1664. FunctionParam(std::string_view Number_)
  1665. : Node(KFunctionParam), Number(Number_) {}
  1666. template<typename Fn> void match(Fn F) const { F(Number); }
  1667. void printLeft(OutputBuffer &OB) const override {
  1668. OB += "fp";
  1669. OB += Number;
  1670. }
  1671. };
  1672. class ConversionExpr : public Node {
  1673. const Node *Type;
  1674. NodeArray Expressions;
  1675. public:
  1676. ConversionExpr(const Node *Type_, NodeArray Expressions_, Prec Prec_)
  1677. : Node(KConversionExpr, Prec_), Type(Type_), Expressions(Expressions_) {}
  1678. template <typename Fn> void match(Fn F) const {
  1679. F(Type, Expressions, getPrecedence());
  1680. }
  1681. void printLeft(OutputBuffer &OB) const override {
  1682. OB.printOpen();
  1683. Type->print(OB);
  1684. OB.printClose();
  1685. OB.printOpen();
  1686. Expressions.printWithComma(OB);
  1687. OB.printClose();
  1688. }
  1689. };
  1690. class PointerToMemberConversionExpr : public Node {
  1691. const Node *Type;
  1692. const Node *SubExpr;
  1693. std::string_view Offset;
  1694. public:
  1695. PointerToMemberConversionExpr(const Node *Type_, const Node *SubExpr_,
  1696. std::string_view Offset_, Prec Prec_)
  1697. : Node(KPointerToMemberConversionExpr, Prec_), Type(Type_),
  1698. SubExpr(SubExpr_), Offset(Offset_) {}
  1699. template <typename Fn> void match(Fn F) const {
  1700. F(Type, SubExpr, Offset, getPrecedence());
  1701. }
  1702. void printLeft(OutputBuffer &OB) const override {
  1703. OB.printOpen();
  1704. Type->print(OB);
  1705. OB.printClose();
  1706. OB.printOpen();
  1707. SubExpr->print(OB);
  1708. OB.printClose();
  1709. }
  1710. };
  1711. class InitListExpr : public Node {
  1712. const Node *Ty;
  1713. NodeArray Inits;
  1714. public:
  1715. InitListExpr(const Node *Ty_, NodeArray Inits_)
  1716. : Node(KInitListExpr), Ty(Ty_), Inits(Inits_) {}
  1717. template<typename Fn> void match(Fn F) const { F(Ty, Inits); }
  1718. void printLeft(OutputBuffer &OB) const override {
  1719. if (Ty)
  1720. Ty->print(OB);
  1721. OB += '{';
  1722. Inits.printWithComma(OB);
  1723. OB += '}';
  1724. }
  1725. };
  1726. class BracedExpr : public Node {
  1727. const Node *Elem;
  1728. const Node *Init;
  1729. bool IsArray;
  1730. public:
  1731. BracedExpr(const Node *Elem_, const Node *Init_, bool IsArray_)
  1732. : Node(KBracedExpr), Elem(Elem_), Init(Init_), IsArray(IsArray_) {}
  1733. template<typename Fn> void match(Fn F) const { F(Elem, Init, IsArray); }
  1734. void printLeft(OutputBuffer &OB) const override {
  1735. if (IsArray) {
  1736. OB += '[';
  1737. Elem->print(OB);
  1738. OB += ']';
  1739. } else {
  1740. OB += '.';
  1741. Elem->print(OB);
  1742. }
  1743. if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
  1744. OB += " = ";
  1745. Init->print(OB);
  1746. }
  1747. };
  1748. class BracedRangeExpr : public Node {
  1749. const Node *First;
  1750. const Node *Last;
  1751. const Node *Init;
  1752. public:
  1753. BracedRangeExpr(const Node *First_, const Node *Last_, const Node *Init_)
  1754. : Node(KBracedRangeExpr), First(First_), Last(Last_), Init(Init_) {}
  1755. template<typename Fn> void match(Fn F) const { F(First, Last, Init); }
  1756. void printLeft(OutputBuffer &OB) const override {
  1757. OB += '[';
  1758. First->print(OB);
  1759. OB += " ... ";
  1760. Last->print(OB);
  1761. OB += ']';
  1762. if (Init->getKind() != KBracedExpr && Init->getKind() != KBracedRangeExpr)
  1763. OB += " = ";
  1764. Init->print(OB);
  1765. }
  1766. };
  1767. class FoldExpr : public Node {
  1768. const Node *Pack, *Init;
  1769. std::string_view OperatorName;
  1770. bool IsLeftFold;
  1771. public:
  1772. FoldExpr(bool IsLeftFold_, std::string_view OperatorName_, const Node *Pack_,
  1773. const Node *Init_)
  1774. : Node(KFoldExpr), Pack(Pack_), Init(Init_), OperatorName(OperatorName_),
  1775. IsLeftFold(IsLeftFold_) {}
  1776. template<typename Fn> void match(Fn F) const {
  1777. F(IsLeftFold, OperatorName, Pack, Init);
  1778. }
  1779. void printLeft(OutputBuffer &OB) const override {
  1780. auto PrintPack = [&] {
  1781. OB.printOpen();
  1782. ParameterPackExpansion(Pack).print(OB);
  1783. OB.printClose();
  1784. };
  1785. OB.printOpen();
  1786. // Either '[init op ]... op pack' or 'pack op ...[ op init]'
  1787. // Refactored to '[(init|pack) op ]...[ op (pack|init)]'
  1788. // Fold expr operands are cast-expressions
  1789. if (!IsLeftFold || Init != nullptr) {
  1790. // '(init|pack) op '
  1791. if (IsLeftFold)
  1792. Init->printAsOperand(OB, Prec::Cast, true);
  1793. else
  1794. PrintPack();
  1795. OB << " " << OperatorName << " ";
  1796. }
  1797. OB << "...";
  1798. if (IsLeftFold || Init != nullptr) {
  1799. // ' op (init|pack)'
  1800. OB << " " << OperatorName << " ";
  1801. if (IsLeftFold)
  1802. PrintPack();
  1803. else
  1804. Init->printAsOperand(OB, Prec::Cast, true);
  1805. }
  1806. OB.printClose();
  1807. }
  1808. };
  1809. class ThrowExpr : public Node {
  1810. const Node *Op;
  1811. public:
  1812. ThrowExpr(const Node *Op_) : Node(KThrowExpr), Op(Op_) {}
  1813. template<typename Fn> void match(Fn F) const { F(Op); }
  1814. void printLeft(OutputBuffer &OB) const override {
  1815. OB += "throw ";
  1816. Op->print(OB);
  1817. }
  1818. };
  1819. class BoolExpr : public Node {
  1820. bool Value;
  1821. public:
  1822. BoolExpr(bool Value_) : Node(KBoolExpr), Value(Value_) {}
  1823. template<typename Fn> void match(Fn F) const { F(Value); }
  1824. void printLeft(OutputBuffer &OB) const override {
  1825. OB += Value ? std::string_view("true") : std::string_view("false");
  1826. }
  1827. };
  1828. class StringLiteral : public Node {
  1829. const Node *Type;
  1830. public:
  1831. StringLiteral(const Node *Type_) : Node(KStringLiteral), Type(Type_) {}
  1832. template<typename Fn> void match(Fn F) const { F(Type); }
  1833. void printLeft(OutputBuffer &OB) const override {
  1834. OB += "\"<";
  1835. Type->print(OB);
  1836. OB += ">\"";
  1837. }
  1838. };
  1839. class LambdaExpr : public Node {
  1840. const Node *Type;
  1841. public:
  1842. LambdaExpr(const Node *Type_) : Node(KLambdaExpr), Type(Type_) {}
  1843. template<typename Fn> void match(Fn F) const { F(Type); }
  1844. void printLeft(OutputBuffer &OB) const override {
  1845. OB += "[]";
  1846. if (Type->getKind() == KClosureTypeName)
  1847. static_cast<const ClosureTypeName *>(Type)->printDeclarator(OB);
  1848. OB += "{...}";
  1849. }
  1850. };
  1851. class EnumLiteral : public Node {
  1852. // ty(integer)
  1853. const Node *Ty;
  1854. std::string_view Integer;
  1855. public:
  1856. EnumLiteral(const Node *Ty_, std::string_view Integer_)
  1857. : Node(KEnumLiteral), Ty(Ty_), Integer(Integer_) {}
  1858. template<typename Fn> void match(Fn F) const { F(Ty, Integer); }
  1859. void printLeft(OutputBuffer &OB) const override {
  1860. OB.printOpen();
  1861. Ty->print(OB);
  1862. OB.printClose();
  1863. if (Integer[0] == 'n')
  1864. OB << '-' << std::string_view(Integer.data() + 1, Integer.size() - 1);
  1865. else
  1866. OB << Integer;
  1867. }
  1868. };
  1869. class IntegerLiteral : public Node {
  1870. std::string_view Type;
  1871. std::string_view Value;
  1872. public:
  1873. IntegerLiteral(std::string_view Type_, std::string_view Value_)
  1874. : Node(KIntegerLiteral), Type(Type_), Value(Value_) {}
  1875. template<typename Fn> void match(Fn F) const { F(Type, Value); }
  1876. void printLeft(OutputBuffer &OB) const override {
  1877. if (Type.size() > 3) {
  1878. OB.printOpen();
  1879. OB += Type;
  1880. OB.printClose();
  1881. }
  1882. if (Value[0] == 'n')
  1883. OB << '-' << std::string_view(Value.data() + 1, Value.size() - 1);
  1884. else
  1885. OB += Value;
  1886. if (Type.size() <= 3)
  1887. OB += Type;
  1888. }
  1889. };
  1890. template <class Float> struct FloatData;
  1891. namespace float_literal_impl {
  1892. constexpr Node::Kind getFloatLiteralKind(float *) {
  1893. return Node::KFloatLiteral;
  1894. }
  1895. constexpr Node::Kind getFloatLiteralKind(double *) {
  1896. return Node::KDoubleLiteral;
  1897. }
  1898. constexpr Node::Kind getFloatLiteralKind(long double *) {
  1899. return Node::KLongDoubleLiteral;
  1900. }
  1901. }
  1902. template <class Float> class FloatLiteralImpl : public Node {
  1903. const std::string_view Contents;
  1904. static constexpr Kind KindForClass =
  1905. float_literal_impl::getFloatLiteralKind((Float *)nullptr);
  1906. public:
  1907. FloatLiteralImpl(std::string_view Contents_)
  1908. : Node(KindForClass), Contents(Contents_) {}
  1909. template<typename Fn> void match(Fn F) const { F(Contents); }
  1910. void printLeft(OutputBuffer &OB) const override {
  1911. const size_t N = FloatData<Float>::mangled_size;
  1912. if (Contents.size() >= N) {
  1913. union {
  1914. Float value;
  1915. char buf[sizeof(Float)];
  1916. };
  1917. const char *t = Contents.data();
  1918. const char *last = t + N;
  1919. char *e = buf;
  1920. for (; t != last; ++t, ++e) {
  1921. unsigned d1 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
  1922. : static_cast<unsigned>(*t - 'a' + 10);
  1923. ++t;
  1924. unsigned d0 = isdigit(*t) ? static_cast<unsigned>(*t - '0')
  1925. : static_cast<unsigned>(*t - 'a' + 10);
  1926. *e = static_cast<char>((d1 << 4) + d0);
  1927. }
  1928. #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  1929. std::reverse(buf, e);
  1930. #endif
  1931. char num[FloatData<Float>::max_demangled_size] = {0};
  1932. int n = snprintf(num, sizeof(num), FloatData<Float>::spec, value);
  1933. OB += std::string_view(num, n);
  1934. }
  1935. }
  1936. };
  1937. using FloatLiteral = FloatLiteralImpl<float>;
  1938. using DoubleLiteral = FloatLiteralImpl<double>;
  1939. using LongDoubleLiteral = FloatLiteralImpl<long double>;
  1940. /// Visit the node. Calls \c F(P), where \c P is the node cast to the
  1941. /// appropriate derived class.
  1942. template<typename Fn>
  1943. void Node::visit(Fn F) const {
  1944. switch (K) {
  1945. #define NODE(X) \
  1946. case K##X: \
  1947. return F(static_cast<const X *>(this));
  1948. #include "ItaniumNodes.def"
  1949. }
  1950. assert(0 && "unknown mangling node kind");
  1951. }
  1952. /// Determine the kind of a node from its type.
  1953. template<typename NodeT> struct NodeKind;
  1954. #define NODE(X) \
  1955. template <> struct NodeKind<X> { \
  1956. static constexpr Node::Kind Kind = Node::K##X; \
  1957. static constexpr const char *name() { return #X; } \
  1958. };
  1959. #include "ItaniumNodes.def"
  1960. template <typename Derived, typename Alloc> struct AbstractManglingParser {
  1961. const char *First;
  1962. const char *Last;
  1963. // Name stack, this is used by the parser to hold temporary names that were
  1964. // parsed. The parser collapses multiple names into new nodes to construct
  1965. // the AST. Once the parser is finished, names.size() == 1.
  1966. PODSmallVector<Node *, 32> Names;
  1967. // Substitution table. Itanium supports name substitutions as a means of
  1968. // compression. The string "S42_" refers to the 44nd entry (base-36) in this
  1969. // table.
  1970. PODSmallVector<Node *, 32> Subs;
  1971. using TemplateParamList = PODSmallVector<Node *, 8>;
  1972. class ScopedTemplateParamList {
  1973. AbstractManglingParser *Parser;
  1974. size_t OldNumTemplateParamLists;
  1975. TemplateParamList Params;
  1976. public:
  1977. ScopedTemplateParamList(AbstractManglingParser *TheParser)
  1978. : Parser(TheParser),
  1979. OldNumTemplateParamLists(TheParser->TemplateParams.size()) {
  1980. Parser->TemplateParams.push_back(&Params);
  1981. }
  1982. ~ScopedTemplateParamList() {
  1983. assert(Parser->TemplateParams.size() >= OldNumTemplateParamLists);
  1984. Parser->TemplateParams.dropBack(OldNumTemplateParamLists);
  1985. }
  1986. };
  1987. // Template parameter table. Like the above, but referenced like "T42_".
  1988. // This has a smaller size compared to Subs and Names because it can be
  1989. // stored on the stack.
  1990. TemplateParamList OuterTemplateParams;
  1991. // Lists of template parameters indexed by template parameter depth,
  1992. // referenced like "TL2_4_". If nonempty, element 0 is always
  1993. // OuterTemplateParams; inner elements are always template parameter lists of
  1994. // lambda expressions. For a generic lambda with no explicit template
  1995. // parameter list, the corresponding parameter list pointer will be null.
  1996. PODSmallVector<TemplateParamList *, 4> TemplateParams;
  1997. // Set of unresolved forward <template-param> references. These can occur in a
  1998. // conversion operator's type, and are resolved in the enclosing <encoding>.
  1999. PODSmallVector<ForwardTemplateReference *, 4> ForwardTemplateRefs;
  2000. bool TryToParseTemplateArgs = true;
  2001. bool PermitForwardTemplateReferences = false;
  2002. size_t ParsingLambdaParamsAtLevel = (size_t)-1;
  2003. unsigned NumSyntheticTemplateParameters[3] = {};
  2004. Alloc ASTAllocator;
  2005. AbstractManglingParser(const char *First_, const char *Last_)
  2006. : First(First_), Last(Last_) {}
  2007. Derived &getDerived() { return static_cast<Derived &>(*this); }
  2008. void reset(const char *First_, const char *Last_) {
  2009. First = First_;
  2010. Last = Last_;
  2011. Names.clear();
  2012. Subs.clear();
  2013. TemplateParams.clear();
  2014. ParsingLambdaParamsAtLevel = (size_t)-1;
  2015. TryToParseTemplateArgs = true;
  2016. PermitForwardTemplateReferences = false;
  2017. for (int I = 0; I != 3; ++I)
  2018. NumSyntheticTemplateParameters[I] = 0;
  2019. ASTAllocator.reset();
  2020. }
  2021. template <class T, class... Args> Node *make(Args &&... args) {
  2022. return ASTAllocator.template makeNode<T>(std::forward<Args>(args)...);
  2023. }
  2024. template <class It> NodeArray makeNodeArray(It begin, It end) {
  2025. size_t sz = static_cast<size_t>(end - begin);
  2026. void *mem = ASTAllocator.allocateNodeArray(sz);
  2027. Node **data = new (mem) Node *[sz];
  2028. std::copy(begin, end, data);
  2029. return NodeArray(data, sz);
  2030. }
  2031. NodeArray popTrailingNodeArray(size_t FromPosition) {
  2032. assert(FromPosition <= Names.size());
  2033. NodeArray res =
  2034. makeNodeArray(Names.begin() + (long)FromPosition, Names.end());
  2035. Names.dropBack(FromPosition);
  2036. return res;
  2037. }
  2038. bool consumeIf(std::string_view S) {
  2039. if (llvm::itanium_demangle::starts_with(
  2040. std::string_view(First, Last - First), S)) {
  2041. First += S.size();
  2042. return true;
  2043. }
  2044. return false;
  2045. }
  2046. bool consumeIf(char C) {
  2047. if (First != Last && *First == C) {
  2048. ++First;
  2049. return true;
  2050. }
  2051. return false;
  2052. }
  2053. char consume() { return First != Last ? *First++ : '\0'; }
  2054. char look(unsigned Lookahead = 0) const {
  2055. if (static_cast<size_t>(Last - First) <= Lookahead)
  2056. return '\0';
  2057. return First[Lookahead];
  2058. }
  2059. size_t numLeft() const { return static_cast<size_t>(Last - First); }
  2060. std::string_view parseNumber(bool AllowNegative = false);
  2061. Qualifiers parseCVQualifiers();
  2062. bool parsePositiveInteger(size_t *Out);
  2063. std::string_view parseBareSourceName();
  2064. bool parseSeqId(size_t *Out);
  2065. Node *parseSubstitution();
  2066. Node *parseTemplateParam();
  2067. Node *parseTemplateParamDecl();
  2068. Node *parseTemplateArgs(bool TagTemplates = false);
  2069. Node *parseTemplateArg();
  2070. /// Parse the <expr> production.
  2071. Node *parseExpr();
  2072. Node *parsePrefixExpr(std::string_view Kind, Node::Prec Prec);
  2073. Node *parseBinaryExpr(std::string_view Kind, Node::Prec Prec);
  2074. Node *parseIntegerLiteral(std::string_view Lit);
  2075. Node *parseExprPrimary();
  2076. template <class Float> Node *parseFloatingLiteral();
  2077. Node *parseFunctionParam();
  2078. Node *parseConversionExpr();
  2079. Node *parseBracedExpr();
  2080. Node *parseFoldExpr();
  2081. Node *parsePointerToMemberConversionExpr(Node::Prec Prec);
  2082. Node *parseSubobjectExpr();
  2083. /// Parse the <type> production.
  2084. Node *parseType();
  2085. Node *parseFunctionType();
  2086. Node *parseVectorType();
  2087. Node *parseDecltype();
  2088. Node *parseArrayType();
  2089. Node *parsePointerToMemberType();
  2090. Node *parseClassEnumType();
  2091. Node *parseQualifiedType();
  2092. Node *parseEncoding();
  2093. bool parseCallOffset();
  2094. Node *parseSpecialName();
  2095. /// Holds some extra information about a <name> that is being parsed. This
  2096. /// information is only pertinent if the <name> refers to an <encoding>.
  2097. struct NameState {
  2098. bool CtorDtorConversion = false;
  2099. bool EndsWithTemplateArgs = false;
  2100. Qualifiers CVQualifiers = QualNone;
  2101. FunctionRefQual ReferenceQualifier = FrefQualNone;
  2102. size_t ForwardTemplateRefsBegin;
  2103. NameState(AbstractManglingParser *Enclosing)
  2104. : ForwardTemplateRefsBegin(Enclosing->ForwardTemplateRefs.size()) {}
  2105. };
  2106. bool resolveForwardTemplateRefs(NameState &State) {
  2107. size_t I = State.ForwardTemplateRefsBegin;
  2108. size_t E = ForwardTemplateRefs.size();
  2109. for (; I < E; ++I) {
  2110. size_t Idx = ForwardTemplateRefs[I]->Index;
  2111. if (TemplateParams.empty() || !TemplateParams[0] ||
  2112. Idx >= TemplateParams[0]->size())
  2113. return true;
  2114. ForwardTemplateRefs[I]->Ref = (*TemplateParams[0])[Idx];
  2115. }
  2116. ForwardTemplateRefs.dropBack(State.ForwardTemplateRefsBegin);
  2117. return false;
  2118. }
  2119. /// Parse the <name> production>
  2120. Node *parseName(NameState *State = nullptr);
  2121. Node *parseLocalName(NameState *State);
  2122. Node *parseOperatorName(NameState *State);
  2123. bool parseModuleNameOpt(ModuleName *&Module);
  2124. Node *parseUnqualifiedName(NameState *State, Node *Scope, ModuleName *Module);
  2125. Node *parseUnnamedTypeName(NameState *State);
  2126. Node *parseSourceName(NameState *State);
  2127. Node *parseUnscopedName(NameState *State, bool *isSubstName);
  2128. Node *parseNestedName(NameState *State);
  2129. Node *parseCtorDtorName(Node *&SoFar, NameState *State);
  2130. Node *parseAbiTags(Node *N);
  2131. struct OperatorInfo {
  2132. enum OIKind : unsigned char {
  2133. Prefix, // Prefix unary: @ expr
  2134. Postfix, // Postfix unary: expr @
  2135. Binary, // Binary: lhs @ rhs
  2136. Array, // Array index: lhs [ rhs ]
  2137. Member, // Member access: lhs @ rhs
  2138. New, // New
  2139. Del, // Delete
  2140. Call, // Function call: expr (expr*)
  2141. CCast, // C cast: (type)expr
  2142. Conditional, // Conditional: expr ? expr : expr
  2143. NameOnly, // Overload only, not allowed in expression.
  2144. // Below do not have operator names
  2145. NamedCast, // Named cast, @<type>(expr)
  2146. OfIdOp, // alignof, sizeof, typeid
  2147. Unnameable = NamedCast,
  2148. };
  2149. char Enc[2]; // Encoding
  2150. OIKind Kind; // Kind of operator
  2151. bool Flag : 1; // Entry-specific flag
  2152. Node::Prec Prec : 7; // Precedence
  2153. const char *Name; // Spelling
  2154. public:
  2155. constexpr OperatorInfo(const char (&E)[3], OIKind K, bool F, Node::Prec P,
  2156. const char *N)
  2157. : Enc{E[0], E[1]}, Kind{K}, Flag{F}, Prec{P}, Name{N} {}
  2158. public:
  2159. bool operator<(const OperatorInfo &Other) const {
  2160. return *this < Other.Enc;
  2161. }
  2162. bool operator<(const char *Peek) const {
  2163. return Enc[0] < Peek[0] || (Enc[0] == Peek[0] && Enc[1] < Peek[1]);
  2164. }
  2165. bool operator==(const char *Peek) const {
  2166. return Enc[0] == Peek[0] && Enc[1] == Peek[1];
  2167. }
  2168. bool operator!=(const char *Peek) const { return !this->operator==(Peek); }
  2169. public:
  2170. std::string_view getSymbol() const {
  2171. std::string_view Res = Name;
  2172. if (Kind < Unnameable) {
  2173. assert(llvm::itanium_demangle::starts_with(Res, "operator") &&
  2174. "operator name does not start with 'operator'");
  2175. Res.remove_prefix(sizeof("operator") - 1);
  2176. if (llvm::itanium_demangle::starts_with(Res, ' '))
  2177. Res.remove_prefix(1);
  2178. }
  2179. return Res;
  2180. }
  2181. std::string_view getName() const { return Name; }
  2182. OIKind getKind() const { return Kind; }
  2183. bool getFlag() const { return Flag; }
  2184. Node::Prec getPrecedence() const { return Prec; }
  2185. };
  2186. static const OperatorInfo Ops[];
  2187. static const size_t NumOps;
  2188. const OperatorInfo *parseOperatorEncoding();
  2189. /// Parse the <unresolved-name> production.
  2190. Node *parseUnresolvedName(bool Global);
  2191. Node *parseSimpleId();
  2192. Node *parseBaseUnresolvedName();
  2193. Node *parseUnresolvedType();
  2194. Node *parseDestructorName();
  2195. /// Top-level entry point into the parser.
  2196. Node *parse();
  2197. };
  2198. const char* parse_discriminator(const char* first, const char* last);
  2199. // <name> ::= <nested-name> // N
  2200. // ::= <local-name> # See Scope Encoding below // Z
  2201. // ::= <unscoped-template-name> <template-args>
  2202. // ::= <unscoped-name>
  2203. //
  2204. // <unscoped-template-name> ::= <unscoped-name>
  2205. // ::= <substitution>
  2206. template <typename Derived, typename Alloc>
  2207. Node *AbstractManglingParser<Derived, Alloc>::parseName(NameState *State) {
  2208. if (look() == 'N')
  2209. return getDerived().parseNestedName(State);
  2210. if (look() == 'Z')
  2211. return getDerived().parseLocalName(State);
  2212. Node *Result = nullptr;
  2213. bool IsSubst = false;
  2214. Result = getDerived().parseUnscopedName(State, &IsSubst);
  2215. if (!Result)
  2216. return nullptr;
  2217. if (look() == 'I') {
  2218. // ::= <unscoped-template-name> <template-args>
  2219. if (!IsSubst)
  2220. // An unscoped-template-name is substitutable.
  2221. Subs.push_back(Result);
  2222. Node *TA = getDerived().parseTemplateArgs(State != nullptr);
  2223. if (TA == nullptr)
  2224. return nullptr;
  2225. if (State)
  2226. State->EndsWithTemplateArgs = true;
  2227. Result = make<NameWithTemplateArgs>(Result, TA);
  2228. } else if (IsSubst) {
  2229. // The substitution case must be followed by <template-args>.
  2230. return nullptr;
  2231. }
  2232. return Result;
  2233. }
  2234. // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
  2235. // := Z <function encoding> E s [<discriminator>]
  2236. // := Z <function encoding> Ed [ <parameter number> ] _ <entity name>
  2237. template <typename Derived, typename Alloc>
  2238. Node *AbstractManglingParser<Derived, Alloc>::parseLocalName(NameState *State) {
  2239. if (!consumeIf('Z'))
  2240. return nullptr;
  2241. Node *Encoding = getDerived().parseEncoding();
  2242. if (Encoding == nullptr || !consumeIf('E'))
  2243. return nullptr;
  2244. if (consumeIf('s')) {
  2245. First = parse_discriminator(First, Last);
  2246. auto *StringLitName = make<NameType>("string literal");
  2247. if (!StringLitName)
  2248. return nullptr;
  2249. return make<LocalName>(Encoding, StringLitName);
  2250. }
  2251. if (consumeIf('d')) {
  2252. parseNumber(true);
  2253. if (!consumeIf('_'))
  2254. return nullptr;
  2255. Node *N = getDerived().parseName(State);
  2256. if (N == nullptr)
  2257. return nullptr;
  2258. return make<LocalName>(Encoding, N);
  2259. }
  2260. Node *Entity = getDerived().parseName(State);
  2261. if (Entity == nullptr)
  2262. return nullptr;
  2263. First = parse_discriminator(First, Last);
  2264. return make<LocalName>(Encoding, Entity);
  2265. }
  2266. // <unscoped-name> ::= <unqualified-name>
  2267. // ::= St <unqualified-name> # ::std::
  2268. // [*] extension
  2269. template <typename Derived, typename Alloc>
  2270. Node *
  2271. AbstractManglingParser<Derived, Alloc>::parseUnscopedName(NameState *State,
  2272. bool *IsSubst) {
  2273. Node *Std = nullptr;
  2274. if (consumeIf("St")) {
  2275. Std = make<NameType>("std");
  2276. if (Std == nullptr)
  2277. return nullptr;
  2278. }
  2279. Node *Res = nullptr;
  2280. ModuleName *Module = nullptr;
  2281. if (look() == 'S') {
  2282. Node *S = getDerived().parseSubstitution();
  2283. if (!S)
  2284. return nullptr;
  2285. if (S->getKind() == Node::KModuleName)
  2286. Module = static_cast<ModuleName *>(S);
  2287. else if (IsSubst && Std == nullptr) {
  2288. Res = S;
  2289. *IsSubst = true;
  2290. } else {
  2291. return nullptr;
  2292. }
  2293. }
  2294. if (Res == nullptr || Std != nullptr) {
  2295. Res = getDerived().parseUnqualifiedName(State, Std, Module);
  2296. }
  2297. return Res;
  2298. }
  2299. // <unqualified-name> ::= [<module-name>] L? <operator-name> [<abi-tags>]
  2300. // ::= [<module-name>] <ctor-dtor-name> [<abi-tags>]
  2301. // ::= [<module-name>] L? <source-name> [<abi-tags>]
  2302. // ::= [<module-name>] L? <unnamed-type-name> [<abi-tags>]
  2303. // # structured binding declaration
  2304. // ::= [<module-name>] L? DC <source-name>+ E
  2305. template <typename Derived, typename Alloc>
  2306. Node *AbstractManglingParser<Derived, Alloc>::parseUnqualifiedName(
  2307. NameState *State, Node *Scope, ModuleName *Module) {
  2308. if (getDerived().parseModuleNameOpt(Module))
  2309. return nullptr;
  2310. consumeIf('L');
  2311. Node *Result;
  2312. if (look() >= '1' && look() <= '9') {
  2313. Result = getDerived().parseSourceName(State);
  2314. } else if (look() == 'U') {
  2315. Result = getDerived().parseUnnamedTypeName(State);
  2316. } else if (consumeIf("DC")) {
  2317. // Structured binding
  2318. size_t BindingsBegin = Names.size();
  2319. do {
  2320. Node *Binding = getDerived().parseSourceName(State);
  2321. if (Binding == nullptr)
  2322. return nullptr;
  2323. Names.push_back(Binding);
  2324. } while (!consumeIf('E'));
  2325. Result = make<StructuredBindingName>(popTrailingNodeArray(BindingsBegin));
  2326. } else if (look() == 'C' || look() == 'D') {
  2327. // A <ctor-dtor-name>.
  2328. if (Scope == nullptr || Module != nullptr)
  2329. return nullptr;
  2330. Result = getDerived().parseCtorDtorName(Scope, State);
  2331. } else {
  2332. Result = getDerived().parseOperatorName(State);
  2333. }
  2334. if (Result != nullptr && Module != nullptr)
  2335. Result = make<ModuleEntity>(Module, Result);
  2336. if (Result != nullptr)
  2337. Result = getDerived().parseAbiTags(Result);
  2338. if (Result != nullptr && Scope != nullptr)
  2339. Result = make<NestedName>(Scope, Result);
  2340. return Result;
  2341. }
  2342. // <module-name> ::= <module-subname>
  2343. // ::= <module-name> <module-subname>
  2344. // ::= <substitution> # passed in by caller
  2345. // <module-subname> ::= W <source-name>
  2346. // ::= W P <source-name>
  2347. template <typename Derived, typename Alloc>
  2348. bool AbstractManglingParser<Derived, Alloc>::parseModuleNameOpt(
  2349. ModuleName *&Module) {
  2350. while (consumeIf('W')) {
  2351. bool IsPartition = consumeIf('P');
  2352. Node *Sub = getDerived().parseSourceName(nullptr);
  2353. if (!Sub)
  2354. return true;
  2355. Module =
  2356. static_cast<ModuleName *>(make<ModuleName>(Module, Sub, IsPartition));
  2357. Subs.push_back(Module);
  2358. }
  2359. return false;
  2360. }
  2361. // <unnamed-type-name> ::= Ut [<nonnegative number>] _
  2362. // ::= <closure-type-name>
  2363. //
  2364. // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
  2365. //
  2366. // <lambda-sig> ::= <parameter type>+ # Parameter types or "v" if the lambda has no parameters
  2367. template <typename Derived, typename Alloc>
  2368. Node *
  2369. AbstractManglingParser<Derived, Alloc>::parseUnnamedTypeName(NameState *State) {
  2370. // <template-params> refer to the innermost <template-args>. Clear out any
  2371. // outer args that we may have inserted into TemplateParams.
  2372. if (State != nullptr)
  2373. TemplateParams.clear();
  2374. if (consumeIf("Ut")) {
  2375. std::string_view Count = parseNumber();
  2376. if (!consumeIf('_'))
  2377. return nullptr;
  2378. return make<UnnamedTypeName>(Count);
  2379. }
  2380. if (consumeIf("Ul")) {
  2381. ScopedOverride<size_t> SwapParams(ParsingLambdaParamsAtLevel,
  2382. TemplateParams.size());
  2383. ScopedTemplateParamList LambdaTemplateParams(this);
  2384. size_t ParamsBegin = Names.size();
  2385. while (look() == 'T' &&
  2386. std::string_view("yptn").find(look(1)) != std::string_view::npos) {
  2387. Node *T = parseTemplateParamDecl();
  2388. if (!T)
  2389. return nullptr;
  2390. Names.push_back(T);
  2391. }
  2392. NodeArray TempParams = popTrailingNodeArray(ParamsBegin);
  2393. // FIXME: If TempParams is empty and none of the function parameters
  2394. // includes 'auto', we should remove LambdaTemplateParams from the
  2395. // TemplateParams list. Unfortunately, we don't find out whether there are
  2396. // any 'auto' parameters until too late in an example such as:
  2397. //
  2398. // template<typename T> void f(
  2399. // decltype([](decltype([]<typename T>(T v) {}),
  2400. // auto) {})) {}
  2401. // template<typename T> void f(
  2402. // decltype([](decltype([]<typename T>(T w) {}),
  2403. // int) {})) {}
  2404. //
  2405. // Here, the type of v is at level 2 but the type of w is at level 1. We
  2406. // don't find this out until we encounter the type of the next parameter.
  2407. //
  2408. // However, compilers can't actually cope with the former example in
  2409. // practice, and it's likely to be made ill-formed in future, so we don't
  2410. // need to support it here.
  2411. //
  2412. // If we encounter an 'auto' in the function parameter types, we will
  2413. // recreate a template parameter scope for it, but any intervening lambdas
  2414. // will be parsed in the 'wrong' template parameter depth.
  2415. if (TempParams.empty())
  2416. TemplateParams.pop_back();
  2417. if (!consumeIf("vE")) {
  2418. do {
  2419. Node *P = getDerived().parseType();
  2420. if (P == nullptr)
  2421. return nullptr;
  2422. Names.push_back(P);
  2423. } while (!consumeIf('E'));
  2424. }
  2425. NodeArray Params = popTrailingNodeArray(ParamsBegin);
  2426. std::string_view Count = parseNumber();
  2427. if (!consumeIf('_'))
  2428. return nullptr;
  2429. return make<ClosureTypeName>(TempParams, Params, Count);
  2430. }
  2431. if (consumeIf("Ub")) {
  2432. (void)parseNumber();
  2433. if (!consumeIf('_'))
  2434. return nullptr;
  2435. return make<NameType>("'block-literal'");
  2436. }
  2437. return nullptr;
  2438. }
  2439. // <source-name> ::= <positive length number> <identifier>
  2440. template <typename Derived, typename Alloc>
  2441. Node *AbstractManglingParser<Derived, Alloc>::parseSourceName(NameState *) {
  2442. size_t Length = 0;
  2443. if (parsePositiveInteger(&Length))
  2444. return nullptr;
  2445. if (numLeft() < Length || Length == 0)
  2446. return nullptr;
  2447. std::string_view Name(First, Length);
  2448. First += Length;
  2449. if (llvm::itanium_demangle::starts_with(Name, "_GLOBAL__N"))
  2450. return make<NameType>("(anonymous namespace)");
  2451. return make<NameType>(Name);
  2452. }
  2453. // Operator encodings
  2454. template <typename Derived, typename Alloc>
  2455. const typename AbstractManglingParser<
  2456. Derived, Alloc>::OperatorInfo AbstractManglingParser<Derived,
  2457. Alloc>::Ops[] = {
  2458. // Keep ordered by encoding
  2459. {"aN", OperatorInfo::Binary, false, Node::Prec::Assign, "operator&="},
  2460. {"aS", OperatorInfo::Binary, false, Node::Prec::Assign, "operator="},
  2461. {"aa", OperatorInfo::Binary, false, Node::Prec::AndIf, "operator&&"},
  2462. {"ad", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator&"},
  2463. {"an", OperatorInfo::Binary, false, Node::Prec::And, "operator&"},
  2464. {"at", OperatorInfo::OfIdOp, /*Type*/ true, Node::Prec::Unary, "alignof "},
  2465. {"aw", OperatorInfo::NameOnly, false, Node::Prec::Primary,
  2466. "operator co_await"},
  2467. {"az", OperatorInfo::OfIdOp, /*Type*/ false, Node::Prec::Unary, "alignof "},
  2468. {"cc", OperatorInfo::NamedCast, false, Node::Prec::Postfix, "const_cast"},
  2469. {"cl", OperatorInfo::Call, false, Node::Prec::Postfix, "operator()"},
  2470. {"cm", OperatorInfo::Binary, false, Node::Prec::Comma, "operator,"},
  2471. {"co", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator~"},
  2472. {"cv", OperatorInfo::CCast, false, Node::Prec::Cast, "operator"}, // C Cast
  2473. {"dV", OperatorInfo::Binary, false, Node::Prec::Assign, "operator/="},
  2474. {"da", OperatorInfo::Del, /*Ary*/ true, Node::Prec::Unary,
  2475. "operator delete[]"},
  2476. {"dc", OperatorInfo::NamedCast, false, Node::Prec::Postfix, "dynamic_cast"},
  2477. {"de", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator*"},
  2478. {"dl", OperatorInfo::Del, /*Ary*/ false, Node::Prec::Unary,
  2479. "operator delete"},
  2480. {"ds", OperatorInfo::Member, /*Named*/ false, Node::Prec::PtrMem,
  2481. "operator.*"},
  2482. {"dt", OperatorInfo::Member, /*Named*/ false, Node::Prec::Postfix,
  2483. "operator."},
  2484. {"dv", OperatorInfo::Binary, false, Node::Prec::Assign, "operator/"},
  2485. {"eO", OperatorInfo::Binary, false, Node::Prec::Assign, "operator^="},
  2486. {"eo", OperatorInfo::Binary, false, Node::Prec::Xor, "operator^"},
  2487. {"eq", OperatorInfo::Binary, false, Node::Prec::Equality, "operator=="},
  2488. {"ge", OperatorInfo::Binary, false, Node::Prec::Relational, "operator>="},
  2489. {"gt", OperatorInfo::Binary, false, Node::Prec::Relational, "operator>"},
  2490. {"ix", OperatorInfo::Array, false, Node::Prec::Postfix, "operator[]"},
  2491. {"lS", OperatorInfo::Binary, false, Node::Prec::Assign, "operator<<="},
  2492. {"le", OperatorInfo::Binary, false, Node::Prec::Relational, "operator<="},
  2493. {"ls", OperatorInfo::Binary, false, Node::Prec::Shift, "operator<<"},
  2494. {"lt", OperatorInfo::Binary, false, Node::Prec::Relational, "operator<"},
  2495. {"mI", OperatorInfo::Binary, false, Node::Prec::Assign, "operator-="},
  2496. {"mL", OperatorInfo::Binary, false, Node::Prec::Assign, "operator*="},
  2497. {"mi", OperatorInfo::Binary, false, Node::Prec::Additive, "operator-"},
  2498. {"ml", OperatorInfo::Binary, false, Node::Prec::Multiplicative,
  2499. "operator*"},
  2500. {"mm", OperatorInfo::Postfix, false, Node::Prec::Postfix, "operator--"},
  2501. {"na", OperatorInfo::New, /*Ary*/ true, Node::Prec::Unary,
  2502. "operator new[]"},
  2503. {"ne", OperatorInfo::Binary, false, Node::Prec::Equality, "operator!="},
  2504. {"ng", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator-"},
  2505. {"nt", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator!"},
  2506. {"nw", OperatorInfo::New, /*Ary*/ false, Node::Prec::Unary, "operator new"},
  2507. {"oR", OperatorInfo::Binary, false, Node::Prec::Assign, "operator|="},
  2508. {"oo", OperatorInfo::Binary, false, Node::Prec::OrIf, "operator||"},
  2509. {"or", OperatorInfo::Binary, false, Node::Prec::Ior, "operator|"},
  2510. {"pL", OperatorInfo::Binary, false, Node::Prec::Assign, "operator+="},
  2511. {"pl", OperatorInfo::Binary, false, Node::Prec::Additive, "operator+"},
  2512. {"pm", OperatorInfo::Member, /*Named*/ false, Node::Prec::PtrMem,
  2513. "operator->*"},
  2514. {"pp", OperatorInfo::Postfix, false, Node::Prec::Postfix, "operator++"},
  2515. {"ps", OperatorInfo::Prefix, false, Node::Prec::Unary, "operator+"},
  2516. {"pt", OperatorInfo::Member, /*Named*/ true, Node::Prec::Postfix,
  2517. "operator->"},
  2518. {"qu", OperatorInfo::Conditional, false, Node::Prec::Conditional,
  2519. "operator?"},
  2520. {"rM", OperatorInfo::Binary, false, Node::Prec::Assign, "operator%="},
  2521. {"rS", OperatorInfo::Binary, false, Node::Prec::Assign, "operator>>="},
  2522. {"rc", OperatorInfo::NamedCast, false, Node::Prec::Postfix,
  2523. "reinterpret_cast"},
  2524. {"rm", OperatorInfo::Binary, false, Node::Prec::Multiplicative,
  2525. "operator%"},
  2526. {"rs", OperatorInfo::Binary, false, Node::Prec::Shift, "operator>>"},
  2527. {"sc", OperatorInfo::NamedCast, false, Node::Prec::Postfix, "static_cast"},
  2528. {"ss", OperatorInfo::Binary, false, Node::Prec::Spaceship, "operator<=>"},
  2529. {"st", OperatorInfo::OfIdOp, /*Type*/ true, Node::Prec::Unary, "sizeof "},
  2530. {"sz", OperatorInfo::OfIdOp, /*Type*/ false, Node::Prec::Unary, "sizeof "},
  2531. {"te", OperatorInfo::OfIdOp, /*Type*/ false, Node::Prec::Postfix,
  2532. "typeid "},
  2533. {"ti", OperatorInfo::OfIdOp, /*Type*/ true, Node::Prec::Postfix, "typeid "},
  2534. };
  2535. template <typename Derived, typename Alloc>
  2536. const size_t AbstractManglingParser<Derived, Alloc>::NumOps = sizeof(Ops) /
  2537. sizeof(Ops[0]);
  2538. // If the next 2 chars are an operator encoding, consume them and return their
  2539. // OperatorInfo. Otherwise return nullptr.
  2540. template <typename Derived, typename Alloc>
  2541. const typename AbstractManglingParser<Derived, Alloc>::OperatorInfo *
  2542. AbstractManglingParser<Derived, Alloc>::parseOperatorEncoding() {
  2543. if (numLeft() < 2)
  2544. return nullptr;
  2545. // We can't use lower_bound as that can link to symbols in the C++ library,
  2546. // and this must remain independant of that.
  2547. size_t lower = 0u, upper = NumOps - 1; // Inclusive bounds.
  2548. while (upper != lower) {
  2549. size_t middle = (upper + lower) / 2;
  2550. if (Ops[middle] < First)
  2551. lower = middle + 1;
  2552. else
  2553. upper = middle;
  2554. }
  2555. if (Ops[lower] != First)
  2556. return nullptr;
  2557. First += 2;
  2558. return &Ops[lower];
  2559. }
  2560. // <operator-name> ::= See parseOperatorEncoding()
  2561. // ::= li <source-name> # operator ""
  2562. // ::= v <digit> <source-name> # vendor extended operator
  2563. template <typename Derived, typename Alloc>
  2564. Node *
  2565. AbstractManglingParser<Derived, Alloc>::parseOperatorName(NameState *State) {
  2566. if (const auto *Op = parseOperatorEncoding()) {
  2567. if (Op->getKind() == OperatorInfo::CCast) {
  2568. // ::= cv <type> # (cast)
  2569. ScopedOverride<bool> SaveTemplate(TryToParseTemplateArgs, false);
  2570. // If we're parsing an encoding, State != nullptr and the conversion
  2571. // operators' <type> could have a <template-param> that refers to some
  2572. // <template-arg>s further ahead in the mangled name.
  2573. ScopedOverride<bool> SavePermit(PermitForwardTemplateReferences,
  2574. PermitForwardTemplateReferences ||
  2575. State != nullptr);
  2576. Node *Ty = getDerived().parseType();
  2577. if (Ty == nullptr)
  2578. return nullptr;
  2579. if (State) State->CtorDtorConversion = true;
  2580. return make<ConversionOperatorType>(Ty);
  2581. }
  2582. if (Op->getKind() >= OperatorInfo::Unnameable)
  2583. /* Not a nameable operator. */
  2584. return nullptr;
  2585. if (Op->getKind() == OperatorInfo::Member && !Op->getFlag())
  2586. /* Not a nameable MemberExpr */
  2587. return nullptr;
  2588. return make<NameType>(Op->getName());
  2589. }
  2590. if (consumeIf("li")) {
  2591. // ::= li <source-name> # operator ""
  2592. Node *SN = getDerived().parseSourceName(State);
  2593. if (SN == nullptr)
  2594. return nullptr;
  2595. return make<LiteralOperator>(SN);
  2596. }
  2597. if (consumeIf('v')) {
  2598. // ::= v <digit> <source-name> # vendor extended operator
  2599. if (look() >= '0' && look() <= '9') {
  2600. First++;
  2601. Node *SN = getDerived().parseSourceName(State);
  2602. if (SN == nullptr)
  2603. return nullptr;
  2604. return make<ConversionOperatorType>(SN);
  2605. }
  2606. return nullptr;
  2607. }
  2608. return nullptr;
  2609. }
  2610. // <ctor-dtor-name> ::= C1 # complete object constructor
  2611. // ::= C2 # base object constructor
  2612. // ::= C3 # complete object allocating constructor
  2613. // extension ::= C4 # gcc old-style "[unified]" constructor
  2614. // extension ::= C5 # the COMDAT used for ctors
  2615. // ::= D0 # deleting destructor
  2616. // ::= D1 # complete object destructor
  2617. // ::= D2 # base object destructor
  2618. // extension ::= D4 # gcc old-style "[unified]" destructor
  2619. // extension ::= D5 # the COMDAT used for dtors
  2620. template <typename Derived, typename Alloc>
  2621. Node *
  2622. AbstractManglingParser<Derived, Alloc>::parseCtorDtorName(Node *&SoFar,
  2623. NameState *State) {
  2624. if (SoFar->getKind() == Node::KSpecialSubstitution) {
  2625. // Expand the special substitution.
  2626. SoFar = make<ExpandedSpecialSubstitution>(
  2627. static_cast<SpecialSubstitution *>(SoFar));
  2628. if (!SoFar)
  2629. return nullptr;
  2630. }
  2631. if (consumeIf('C')) {
  2632. bool IsInherited = consumeIf('I');
  2633. if (look() != '1' && look() != '2' && look() != '3' && look() != '4' &&
  2634. look() != '5')
  2635. return nullptr;
  2636. int Variant = look() - '0';
  2637. ++First;
  2638. if (State) State->CtorDtorConversion = true;
  2639. if (IsInherited) {
  2640. if (getDerived().parseName(State) == nullptr)
  2641. return nullptr;
  2642. }
  2643. return make<CtorDtorName>(SoFar, /*IsDtor=*/false, Variant);
  2644. }
  2645. if (look() == 'D' && (look(1) == '0' || look(1) == '1' || look(1) == '2' ||
  2646. look(1) == '4' || look(1) == '5')) {
  2647. int Variant = look(1) - '0';
  2648. First += 2;
  2649. if (State) State->CtorDtorConversion = true;
  2650. return make<CtorDtorName>(SoFar, /*IsDtor=*/true, Variant);
  2651. }
  2652. return nullptr;
  2653. }
  2654. // <nested-name> ::= N [<CV-Qualifiers>] [<ref-qualifier>] <prefix>
  2655. // <unqualified-name> E
  2656. // ::= N [<CV-Qualifiers>] [<ref-qualifier>] <template-prefix>
  2657. // <template-args> E
  2658. //
  2659. // <prefix> ::= <prefix> <unqualified-name>
  2660. // ::= <template-prefix> <template-args>
  2661. // ::= <template-param>
  2662. // ::= <decltype>
  2663. // ::= # empty
  2664. // ::= <substitution>
  2665. // ::= <prefix> <data-member-prefix>
  2666. // [*] extension
  2667. //
  2668. // <data-member-prefix> := <member source-name> [<template-args>] M
  2669. //
  2670. // <template-prefix> ::= <prefix> <template unqualified-name>
  2671. // ::= <template-param>
  2672. // ::= <substitution>
  2673. template <typename Derived, typename Alloc>
  2674. Node *
  2675. AbstractManglingParser<Derived, Alloc>::parseNestedName(NameState *State) {
  2676. if (!consumeIf('N'))
  2677. return nullptr;
  2678. Qualifiers CVTmp = parseCVQualifiers();
  2679. if (State) State->CVQualifiers = CVTmp;
  2680. if (consumeIf('O')) {
  2681. if (State) State->ReferenceQualifier = FrefQualRValue;
  2682. } else if (consumeIf('R')) {
  2683. if (State) State->ReferenceQualifier = FrefQualLValue;
  2684. } else {
  2685. if (State) State->ReferenceQualifier = FrefQualNone;
  2686. }
  2687. Node *SoFar = nullptr;
  2688. while (!consumeIf('E')) {
  2689. if (State)
  2690. // Only set end-with-template on the case that does that.
  2691. State->EndsWithTemplateArgs = false;
  2692. if (look() == 'T') {
  2693. // ::= <template-param>
  2694. if (SoFar != nullptr)
  2695. return nullptr; // Cannot have a prefix.
  2696. SoFar = getDerived().parseTemplateParam();
  2697. } else if (look() == 'I') {
  2698. // ::= <template-prefix> <template-args>
  2699. if (SoFar == nullptr)
  2700. return nullptr; // Must have a prefix.
  2701. Node *TA = getDerived().parseTemplateArgs(State != nullptr);
  2702. if (TA == nullptr)
  2703. return nullptr;
  2704. if (SoFar->getKind() == Node::KNameWithTemplateArgs)
  2705. // Semantically <template-args> <template-args> cannot be generated by a
  2706. // C++ entity. There will always be [something like] a name between
  2707. // them.
  2708. return nullptr;
  2709. if (State)
  2710. State->EndsWithTemplateArgs = true;
  2711. SoFar = make<NameWithTemplateArgs>(SoFar, TA);
  2712. } else if (look() == 'D' && (look(1) == 't' || look(1) == 'T')) {
  2713. // ::= <decltype>
  2714. if (SoFar != nullptr)
  2715. return nullptr; // Cannot have a prefix.
  2716. SoFar = getDerived().parseDecltype();
  2717. } else {
  2718. ModuleName *Module = nullptr;
  2719. if (look() == 'S') {
  2720. // ::= <substitution>
  2721. Node *S = nullptr;
  2722. if (look(1) == 't') {
  2723. First += 2;
  2724. S = make<NameType>("std");
  2725. } else {
  2726. S = getDerived().parseSubstitution();
  2727. }
  2728. if (!S)
  2729. return nullptr;
  2730. if (S->getKind() == Node::KModuleName) {
  2731. Module = static_cast<ModuleName *>(S);
  2732. } else if (SoFar != nullptr) {
  2733. return nullptr; // Cannot have a prefix.
  2734. } else {
  2735. SoFar = S;
  2736. continue; // Do not push a new substitution.
  2737. }
  2738. }
  2739. // ::= [<prefix>] <unqualified-name>
  2740. SoFar = getDerived().parseUnqualifiedName(State, SoFar, Module);
  2741. }
  2742. if (SoFar == nullptr)
  2743. return nullptr;
  2744. Subs.push_back(SoFar);
  2745. // No longer used.
  2746. // <data-member-prefix> := <member source-name> [<template-args>] M
  2747. consumeIf('M');
  2748. }
  2749. if (SoFar == nullptr || Subs.empty())
  2750. return nullptr;
  2751. Subs.pop_back();
  2752. return SoFar;
  2753. }
  2754. // <simple-id> ::= <source-name> [ <template-args> ]
  2755. template <typename Derived, typename Alloc>
  2756. Node *AbstractManglingParser<Derived, Alloc>::parseSimpleId() {
  2757. Node *SN = getDerived().parseSourceName(/*NameState=*/nullptr);
  2758. if (SN == nullptr)
  2759. return nullptr;
  2760. if (look() == 'I') {
  2761. Node *TA = getDerived().parseTemplateArgs();
  2762. if (TA == nullptr)
  2763. return nullptr;
  2764. return make<NameWithTemplateArgs>(SN, TA);
  2765. }
  2766. return SN;
  2767. }
  2768. // <destructor-name> ::= <unresolved-type> # e.g., ~T or ~decltype(f())
  2769. // ::= <simple-id> # e.g., ~A<2*N>
  2770. template <typename Derived, typename Alloc>
  2771. Node *AbstractManglingParser<Derived, Alloc>::parseDestructorName() {
  2772. Node *Result;
  2773. if (std::isdigit(look()))
  2774. Result = getDerived().parseSimpleId();
  2775. else
  2776. Result = getDerived().parseUnresolvedType();
  2777. if (Result == nullptr)
  2778. return nullptr;
  2779. return make<DtorName>(Result);
  2780. }
  2781. // <unresolved-type> ::= <template-param>
  2782. // ::= <decltype>
  2783. // ::= <substitution>
  2784. template <typename Derived, typename Alloc>
  2785. Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedType() {
  2786. if (look() == 'T') {
  2787. Node *TP = getDerived().parseTemplateParam();
  2788. if (TP == nullptr)
  2789. return nullptr;
  2790. Subs.push_back(TP);
  2791. return TP;
  2792. }
  2793. if (look() == 'D') {
  2794. Node *DT = getDerived().parseDecltype();
  2795. if (DT == nullptr)
  2796. return nullptr;
  2797. Subs.push_back(DT);
  2798. return DT;
  2799. }
  2800. return getDerived().parseSubstitution();
  2801. }
  2802. // <base-unresolved-name> ::= <simple-id> # unresolved name
  2803. // extension ::= <operator-name> # unresolved operator-function-id
  2804. // extension ::= <operator-name> <template-args> # unresolved operator template-id
  2805. // ::= on <operator-name> # unresolved operator-function-id
  2806. // ::= on <operator-name> <template-args> # unresolved operator template-id
  2807. // ::= dn <destructor-name> # destructor or pseudo-destructor;
  2808. // # e.g. ~X or ~X<N-1>
  2809. template <typename Derived, typename Alloc>
  2810. Node *AbstractManglingParser<Derived, Alloc>::parseBaseUnresolvedName() {
  2811. if (std::isdigit(look()))
  2812. return getDerived().parseSimpleId();
  2813. if (consumeIf("dn"))
  2814. return getDerived().parseDestructorName();
  2815. consumeIf("on");
  2816. Node *Oper = getDerived().parseOperatorName(/*NameState=*/nullptr);
  2817. if (Oper == nullptr)
  2818. return nullptr;
  2819. if (look() == 'I') {
  2820. Node *TA = getDerived().parseTemplateArgs();
  2821. if (TA == nullptr)
  2822. return nullptr;
  2823. return make<NameWithTemplateArgs>(Oper, TA);
  2824. }
  2825. return Oper;
  2826. }
  2827. // <unresolved-name>
  2828. // extension ::= srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
  2829. // ::= [gs] <base-unresolved-name> # x or (with "gs") ::x
  2830. // ::= [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
  2831. // # A::x, N::y, A<T>::z; "gs" means leading "::"
  2832. // [gs] has been parsed by caller.
  2833. // ::= sr <unresolved-type> <base-unresolved-name> # T::x / decltype(p)::x
  2834. // extension ::= sr <unresolved-type> <template-args> <base-unresolved-name>
  2835. // # T::N::x /decltype(p)::N::x
  2836. // (ignored) ::= srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
  2837. //
  2838. // <unresolved-qualifier-level> ::= <simple-id>
  2839. template <typename Derived, typename Alloc>
  2840. Node *AbstractManglingParser<Derived, Alloc>::parseUnresolvedName(bool Global) {
  2841. Node *SoFar = nullptr;
  2842. // srN <unresolved-type> [<template-args>] <unresolved-qualifier-level>* E <base-unresolved-name>
  2843. // srN <unresolved-type> <unresolved-qualifier-level>+ E <base-unresolved-name>
  2844. if (consumeIf("srN")) {
  2845. SoFar = getDerived().parseUnresolvedType();
  2846. if (SoFar == nullptr)
  2847. return nullptr;
  2848. if (look() == 'I') {
  2849. Node *TA = getDerived().parseTemplateArgs();
  2850. if (TA == nullptr)
  2851. return nullptr;
  2852. SoFar = make<NameWithTemplateArgs>(SoFar, TA);
  2853. if (!SoFar)
  2854. return nullptr;
  2855. }
  2856. while (!consumeIf('E')) {
  2857. Node *Qual = getDerived().parseSimpleId();
  2858. if (Qual == nullptr)
  2859. return nullptr;
  2860. SoFar = make<QualifiedName>(SoFar, Qual);
  2861. if (!SoFar)
  2862. return nullptr;
  2863. }
  2864. Node *Base = getDerived().parseBaseUnresolvedName();
  2865. if (Base == nullptr)
  2866. return nullptr;
  2867. return make<QualifiedName>(SoFar, Base);
  2868. }
  2869. // [gs] <base-unresolved-name> # x or (with "gs") ::x
  2870. if (!consumeIf("sr")) {
  2871. SoFar = getDerived().parseBaseUnresolvedName();
  2872. if (SoFar == nullptr)
  2873. return nullptr;
  2874. if (Global)
  2875. SoFar = make<GlobalQualifiedName>(SoFar);
  2876. return SoFar;
  2877. }
  2878. // [gs] sr <unresolved-qualifier-level>+ E <base-unresolved-name>
  2879. if (std::isdigit(look())) {
  2880. do {
  2881. Node *Qual = getDerived().parseSimpleId();
  2882. if (Qual == nullptr)
  2883. return nullptr;
  2884. if (SoFar)
  2885. SoFar = make<QualifiedName>(SoFar, Qual);
  2886. else if (Global)
  2887. SoFar = make<GlobalQualifiedName>(Qual);
  2888. else
  2889. SoFar = Qual;
  2890. if (!SoFar)
  2891. return nullptr;
  2892. } while (!consumeIf('E'));
  2893. }
  2894. // sr <unresolved-type> <base-unresolved-name>
  2895. // sr <unresolved-type> <template-args> <base-unresolved-name>
  2896. else {
  2897. SoFar = getDerived().parseUnresolvedType();
  2898. if (SoFar == nullptr)
  2899. return nullptr;
  2900. if (look() == 'I') {
  2901. Node *TA = getDerived().parseTemplateArgs();
  2902. if (TA == nullptr)
  2903. return nullptr;
  2904. SoFar = make<NameWithTemplateArgs>(SoFar, TA);
  2905. if (!SoFar)
  2906. return nullptr;
  2907. }
  2908. }
  2909. assert(SoFar != nullptr);
  2910. Node *Base = getDerived().parseBaseUnresolvedName();
  2911. if (Base == nullptr)
  2912. return nullptr;
  2913. return make<QualifiedName>(SoFar, Base);
  2914. }
  2915. // <abi-tags> ::= <abi-tag> [<abi-tags>]
  2916. // <abi-tag> ::= B <source-name>
  2917. template <typename Derived, typename Alloc>
  2918. Node *AbstractManglingParser<Derived, Alloc>::parseAbiTags(Node *N) {
  2919. while (consumeIf('B')) {
  2920. std::string_view SN = parseBareSourceName();
  2921. if (SN.empty())
  2922. return nullptr;
  2923. N = make<AbiTagAttr>(N, SN);
  2924. if (!N)
  2925. return nullptr;
  2926. }
  2927. return N;
  2928. }
  2929. // <number> ::= [n] <non-negative decimal integer>
  2930. template <typename Alloc, typename Derived>
  2931. std::string_view
  2932. AbstractManglingParser<Alloc, Derived>::parseNumber(bool AllowNegative) {
  2933. const char *Tmp = First;
  2934. if (AllowNegative)
  2935. consumeIf('n');
  2936. if (numLeft() == 0 || !std::isdigit(*First))
  2937. return std::string_view();
  2938. while (numLeft() != 0 && std::isdigit(*First))
  2939. ++First;
  2940. return std::string_view(Tmp, First - Tmp);
  2941. }
  2942. // <positive length number> ::= [0-9]*
  2943. template <typename Alloc, typename Derived>
  2944. bool AbstractManglingParser<Alloc, Derived>::parsePositiveInteger(size_t *Out) {
  2945. *Out = 0;
  2946. if (look() < '0' || look() > '9')
  2947. return true;
  2948. while (look() >= '0' && look() <= '9') {
  2949. *Out *= 10;
  2950. *Out += static_cast<size_t>(consume() - '0');
  2951. }
  2952. return false;
  2953. }
  2954. template <typename Alloc, typename Derived>
  2955. std::string_view AbstractManglingParser<Alloc, Derived>::parseBareSourceName() {
  2956. size_t Int = 0;
  2957. if (parsePositiveInteger(&Int) || numLeft() < Int)
  2958. return {};
  2959. std::string_view R(First, Int);
  2960. First += Int;
  2961. return R;
  2962. }
  2963. // <function-type> ::= [<CV-qualifiers>] [<exception-spec>] [Dx] F [Y] <bare-function-type> [<ref-qualifier>] E
  2964. //
  2965. // <exception-spec> ::= Do # non-throwing exception-specification (e.g., noexcept, throw())
  2966. // ::= DO <expression> E # computed (instantiation-dependent) noexcept
  2967. // ::= Dw <type>+ E # dynamic exception specification with instantiation-dependent types
  2968. //
  2969. // <ref-qualifier> ::= R # & ref-qualifier
  2970. // <ref-qualifier> ::= O # && ref-qualifier
  2971. template <typename Derived, typename Alloc>
  2972. Node *AbstractManglingParser<Derived, Alloc>::parseFunctionType() {
  2973. Qualifiers CVQuals = parseCVQualifiers();
  2974. Node *ExceptionSpec = nullptr;
  2975. if (consumeIf("Do")) {
  2976. ExceptionSpec = make<NameType>("noexcept");
  2977. if (!ExceptionSpec)
  2978. return nullptr;
  2979. } else if (consumeIf("DO")) {
  2980. Node *E = getDerived().parseExpr();
  2981. if (E == nullptr || !consumeIf('E'))
  2982. return nullptr;
  2983. ExceptionSpec = make<NoexceptSpec>(E);
  2984. if (!ExceptionSpec)
  2985. return nullptr;
  2986. } else if (consumeIf("Dw")) {
  2987. size_t SpecsBegin = Names.size();
  2988. while (!consumeIf('E')) {
  2989. Node *T = getDerived().parseType();
  2990. if (T == nullptr)
  2991. return nullptr;
  2992. Names.push_back(T);
  2993. }
  2994. ExceptionSpec =
  2995. make<DynamicExceptionSpec>(popTrailingNodeArray(SpecsBegin));
  2996. if (!ExceptionSpec)
  2997. return nullptr;
  2998. }
  2999. consumeIf("Dx"); // transaction safe
  3000. if (!consumeIf('F'))
  3001. return nullptr;
  3002. consumeIf('Y'); // extern "C"
  3003. Node *ReturnType = getDerived().parseType();
  3004. if (ReturnType == nullptr)
  3005. return nullptr;
  3006. FunctionRefQual ReferenceQualifier = FrefQualNone;
  3007. size_t ParamsBegin = Names.size();
  3008. while (true) {
  3009. if (consumeIf('E'))
  3010. break;
  3011. if (consumeIf('v'))
  3012. continue;
  3013. if (consumeIf("RE")) {
  3014. ReferenceQualifier = FrefQualLValue;
  3015. break;
  3016. }
  3017. if (consumeIf("OE")) {
  3018. ReferenceQualifier = FrefQualRValue;
  3019. break;
  3020. }
  3021. Node *T = getDerived().parseType();
  3022. if (T == nullptr)
  3023. return nullptr;
  3024. Names.push_back(T);
  3025. }
  3026. NodeArray Params = popTrailingNodeArray(ParamsBegin);
  3027. return make<FunctionType>(ReturnType, Params, CVQuals,
  3028. ReferenceQualifier, ExceptionSpec);
  3029. }
  3030. // extension:
  3031. // <vector-type> ::= Dv <positive dimension number> _ <extended element type>
  3032. // ::= Dv [<dimension expression>] _ <element type>
  3033. // <extended element type> ::= <element type>
  3034. // ::= p # AltiVec vector pixel
  3035. template <typename Derived, typename Alloc>
  3036. Node *AbstractManglingParser<Derived, Alloc>::parseVectorType() {
  3037. if (!consumeIf("Dv"))
  3038. return nullptr;
  3039. if (look() >= '1' && look() <= '9') {
  3040. Node *DimensionNumber = make<NameType>(parseNumber());
  3041. if (!DimensionNumber)
  3042. return nullptr;
  3043. if (!consumeIf('_'))
  3044. return nullptr;
  3045. if (consumeIf('p'))
  3046. return make<PixelVectorType>(DimensionNumber);
  3047. Node *ElemType = getDerived().parseType();
  3048. if (ElemType == nullptr)
  3049. return nullptr;
  3050. return make<VectorType>(ElemType, DimensionNumber);
  3051. }
  3052. if (!consumeIf('_')) {
  3053. Node *DimExpr = getDerived().parseExpr();
  3054. if (!DimExpr)
  3055. return nullptr;
  3056. if (!consumeIf('_'))
  3057. return nullptr;
  3058. Node *ElemType = getDerived().parseType();
  3059. if (!ElemType)
  3060. return nullptr;
  3061. return make<VectorType>(ElemType, DimExpr);
  3062. }
  3063. Node *ElemType = getDerived().parseType();
  3064. if (!ElemType)
  3065. return nullptr;
  3066. return make<VectorType>(ElemType, /*Dimension=*/nullptr);
  3067. }
  3068. // <decltype> ::= Dt <expression> E # decltype of an id-expression or class member access (C++0x)
  3069. // ::= DT <expression> E # decltype of an expression (C++0x)
  3070. template <typename Derived, typename Alloc>
  3071. Node *AbstractManglingParser<Derived, Alloc>::parseDecltype() {
  3072. if (!consumeIf('D'))
  3073. return nullptr;
  3074. if (!consumeIf('t') && !consumeIf('T'))
  3075. return nullptr;
  3076. Node *E = getDerived().parseExpr();
  3077. if (E == nullptr)
  3078. return nullptr;
  3079. if (!consumeIf('E'))
  3080. return nullptr;
  3081. return make<EnclosingExpr>("decltype", E);
  3082. }
  3083. // <array-type> ::= A <positive dimension number> _ <element type>
  3084. // ::= A [<dimension expression>] _ <element type>
  3085. template <typename Derived, typename Alloc>
  3086. Node *AbstractManglingParser<Derived, Alloc>::parseArrayType() {
  3087. if (!consumeIf('A'))
  3088. return nullptr;
  3089. Node *Dimension = nullptr;
  3090. if (std::isdigit(look())) {
  3091. Dimension = make<NameType>(parseNumber());
  3092. if (!Dimension)
  3093. return nullptr;
  3094. if (!consumeIf('_'))
  3095. return nullptr;
  3096. } else if (!consumeIf('_')) {
  3097. Node *DimExpr = getDerived().parseExpr();
  3098. if (DimExpr == nullptr)
  3099. return nullptr;
  3100. if (!consumeIf('_'))
  3101. return nullptr;
  3102. Dimension = DimExpr;
  3103. }
  3104. Node *Ty = getDerived().parseType();
  3105. if (Ty == nullptr)
  3106. return nullptr;
  3107. return make<ArrayType>(Ty, Dimension);
  3108. }
  3109. // <pointer-to-member-type> ::= M <class type> <member type>
  3110. template <typename Derived, typename Alloc>
  3111. Node *AbstractManglingParser<Derived, Alloc>::parsePointerToMemberType() {
  3112. if (!consumeIf('M'))
  3113. return nullptr;
  3114. Node *ClassType = getDerived().parseType();
  3115. if (ClassType == nullptr)
  3116. return nullptr;
  3117. Node *MemberType = getDerived().parseType();
  3118. if (MemberType == nullptr)
  3119. return nullptr;
  3120. return make<PointerToMemberType>(ClassType, MemberType);
  3121. }
  3122. // <class-enum-type> ::= <name> # non-dependent type name, dependent type name, or dependent typename-specifier
  3123. // ::= Ts <name> # dependent elaborated type specifier using 'struct' or 'class'
  3124. // ::= Tu <name> # dependent elaborated type specifier using 'union'
  3125. // ::= Te <name> # dependent elaborated type specifier using 'enum'
  3126. template <typename Derived, typename Alloc>
  3127. Node *AbstractManglingParser<Derived, Alloc>::parseClassEnumType() {
  3128. std::string_view ElabSpef;
  3129. if (consumeIf("Ts"))
  3130. ElabSpef = "struct";
  3131. else if (consumeIf("Tu"))
  3132. ElabSpef = "union";
  3133. else if (consumeIf("Te"))
  3134. ElabSpef = "enum";
  3135. Node *Name = getDerived().parseName();
  3136. if (Name == nullptr)
  3137. return nullptr;
  3138. if (!ElabSpef.empty())
  3139. return make<ElaboratedTypeSpefType>(ElabSpef, Name);
  3140. return Name;
  3141. }
  3142. // <qualified-type> ::= <qualifiers> <type>
  3143. // <qualifiers> ::= <extended-qualifier>* <CV-qualifiers>
  3144. // <extended-qualifier> ::= U <source-name> [<template-args>] # vendor extended type qualifier
  3145. template <typename Derived, typename Alloc>
  3146. Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
  3147. if (consumeIf('U')) {
  3148. std::string_view Qual = parseBareSourceName();
  3149. if (Qual.empty())
  3150. return nullptr;
  3151. // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
  3152. if (llvm::itanium_demangle::starts_with(Qual, "objcproto")) {
  3153. constexpr size_t Len = sizeof("objcproto") - 1;
  3154. std::string_view ProtoSourceName(Qual.data() + Len, Qual.size() - Len);
  3155. std::string_view Proto;
  3156. {
  3157. ScopedOverride<const char *> SaveFirst(First, ProtoSourceName.data()),
  3158. SaveLast(Last, &*ProtoSourceName.rbegin() + 1);
  3159. Proto = parseBareSourceName();
  3160. }
  3161. if (Proto.empty())
  3162. return nullptr;
  3163. Node *Child = getDerived().parseQualifiedType();
  3164. if (Child == nullptr)
  3165. return nullptr;
  3166. return make<ObjCProtoName>(Child, Proto);
  3167. }
  3168. Node *TA = nullptr;
  3169. if (look() == 'I') {
  3170. TA = getDerived().parseTemplateArgs();
  3171. if (TA == nullptr)
  3172. return nullptr;
  3173. }
  3174. Node *Child = getDerived().parseQualifiedType();
  3175. if (Child == nullptr)
  3176. return nullptr;
  3177. return make<VendorExtQualType>(Child, Qual, TA);
  3178. }
  3179. Qualifiers Quals = parseCVQualifiers();
  3180. Node *Ty = getDerived().parseType();
  3181. if (Ty == nullptr)
  3182. return nullptr;
  3183. if (Quals != QualNone)
  3184. Ty = make<QualType>(Ty, Quals);
  3185. return Ty;
  3186. }
  3187. // <type> ::= <builtin-type>
  3188. // ::= <qualified-type>
  3189. // ::= <function-type>
  3190. // ::= <class-enum-type>
  3191. // ::= <array-type>
  3192. // ::= <pointer-to-member-type>
  3193. // ::= <template-param>
  3194. // ::= <template-template-param> <template-args>
  3195. // ::= <decltype>
  3196. // ::= P <type> # pointer
  3197. // ::= R <type> # l-value reference
  3198. // ::= O <type> # r-value reference (C++11)
  3199. // ::= C <type> # complex pair (C99)
  3200. // ::= G <type> # imaginary (C99)
  3201. // ::= <substitution> # See Compression below
  3202. // extension ::= U <objc-name> <objc-type> # objc-type<identifier>
  3203. // extension ::= <vector-type> # <vector-type> starts with Dv
  3204. //
  3205. // <objc-name> ::= <k0 number> objcproto <k1 number> <identifier> # k0 = 9 + <number of digits in k1> + k1
  3206. // <objc-type> ::= <source-name> # PU<11+>objcproto 11objc_object<source-name> 11objc_object -> id<source-name>
  3207. template <typename Derived, typename Alloc>
  3208. Node *AbstractManglingParser<Derived, Alloc>::parseType() {
  3209. Node *Result = nullptr;
  3210. switch (look()) {
  3211. // ::= <qualified-type>
  3212. case 'r':
  3213. case 'V':
  3214. case 'K': {
  3215. unsigned AfterQuals = 0;
  3216. if (look(AfterQuals) == 'r') ++AfterQuals;
  3217. if (look(AfterQuals) == 'V') ++AfterQuals;
  3218. if (look(AfterQuals) == 'K') ++AfterQuals;
  3219. if (look(AfterQuals) == 'F' ||
  3220. (look(AfterQuals) == 'D' &&
  3221. (look(AfterQuals + 1) == 'o' || look(AfterQuals + 1) == 'O' ||
  3222. look(AfterQuals + 1) == 'w' || look(AfterQuals + 1) == 'x'))) {
  3223. Result = getDerived().parseFunctionType();
  3224. break;
  3225. }
  3226. DEMANGLE_FALLTHROUGH;
  3227. }
  3228. case 'U': {
  3229. Result = getDerived().parseQualifiedType();
  3230. break;
  3231. }
  3232. // <builtin-type> ::= v # void
  3233. case 'v':
  3234. ++First;
  3235. return make<NameType>("void");
  3236. // ::= w # wchar_t
  3237. case 'w':
  3238. ++First;
  3239. return make<NameType>("wchar_t");
  3240. // ::= b # bool
  3241. case 'b':
  3242. ++First;
  3243. return make<NameType>("bool");
  3244. // ::= c # char
  3245. case 'c':
  3246. ++First;
  3247. return make<NameType>("char");
  3248. // ::= a # signed char
  3249. case 'a':
  3250. ++First;
  3251. return make<NameType>("signed char");
  3252. // ::= h # unsigned char
  3253. case 'h':
  3254. ++First;
  3255. return make<NameType>("unsigned char");
  3256. // ::= s # short
  3257. case 's':
  3258. ++First;
  3259. return make<NameType>("short");
  3260. // ::= t # unsigned short
  3261. case 't':
  3262. ++First;
  3263. return make<NameType>("unsigned short");
  3264. // ::= i # int
  3265. case 'i':
  3266. ++First;
  3267. return make<NameType>("int");
  3268. // ::= j # unsigned int
  3269. case 'j':
  3270. ++First;
  3271. return make<NameType>("unsigned int");
  3272. // ::= l # long
  3273. case 'l':
  3274. ++First;
  3275. return make<NameType>("long");
  3276. // ::= m # unsigned long
  3277. case 'm':
  3278. ++First;
  3279. return make<NameType>("unsigned long");
  3280. // ::= x # long long, __int64
  3281. case 'x':
  3282. ++First;
  3283. return make<NameType>("long long");
  3284. // ::= y # unsigned long long, __int64
  3285. case 'y':
  3286. ++First;
  3287. return make<NameType>("unsigned long long");
  3288. // ::= n # __int128
  3289. case 'n':
  3290. ++First;
  3291. return make<NameType>("__int128");
  3292. // ::= o # unsigned __int128
  3293. case 'o':
  3294. ++First;
  3295. return make<NameType>("unsigned __int128");
  3296. // ::= f # float
  3297. case 'f':
  3298. ++First;
  3299. return make<NameType>("float");
  3300. // ::= d # double
  3301. case 'd':
  3302. ++First;
  3303. return make<NameType>("double");
  3304. // ::= e # long double, __float80
  3305. case 'e':
  3306. ++First;
  3307. return make<NameType>("long double");
  3308. // ::= g # __float128
  3309. case 'g':
  3310. ++First;
  3311. return make<NameType>("__float128");
  3312. // ::= z # ellipsis
  3313. case 'z':
  3314. ++First;
  3315. return make<NameType>("...");
  3316. // <builtin-type> ::= u <source-name> # vendor extended type
  3317. case 'u': {
  3318. ++First;
  3319. std::string_view Res = parseBareSourceName();
  3320. if (Res.empty())
  3321. return nullptr;
  3322. // Typically, <builtin-type>s are not considered substitution candidates,
  3323. // but the exception to that exception is vendor extended types (Itanium C++
  3324. // ABI 5.9.1).
  3325. Result = make<NameType>(Res);
  3326. break;
  3327. }
  3328. case 'D':
  3329. switch (look(1)) {
  3330. // ::= Dd # IEEE 754r decimal floating point (64 bits)
  3331. case 'd':
  3332. First += 2;
  3333. return make<NameType>("decimal64");
  3334. // ::= De # IEEE 754r decimal floating point (128 bits)
  3335. case 'e':
  3336. First += 2;
  3337. return make<NameType>("decimal128");
  3338. // ::= Df # IEEE 754r decimal floating point (32 bits)
  3339. case 'f':
  3340. First += 2;
  3341. return make<NameType>("decimal32");
  3342. // ::= Dh # IEEE 754r half-precision floating point (16 bits)
  3343. case 'h':
  3344. First += 2;
  3345. return make<NameType>("half");
  3346. // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point (N bits)
  3347. case 'F': {
  3348. First += 2;
  3349. Node *DimensionNumber = make<NameType>(parseNumber());
  3350. if (!DimensionNumber)
  3351. return nullptr;
  3352. if (!consumeIf('_'))
  3353. return nullptr;
  3354. return make<BinaryFPType>(DimensionNumber);
  3355. }
  3356. // ::= DB <number> _ # C23 signed _BitInt(N)
  3357. // ::= DB <instantiation-dependent expression> _ # C23 signed _BitInt(N)
  3358. // ::= DU <number> _ # C23 unsigned _BitInt(N)
  3359. // ::= DU <instantiation-dependent expression> _ # C23 unsigned _BitInt(N)
  3360. case 'B':
  3361. case 'U': {
  3362. bool Signed = look(1) == 'B';
  3363. First += 2;
  3364. Node *Size = std::isdigit(look()) ? make<NameType>(parseNumber())
  3365. : getDerived().parseExpr();
  3366. if (!Size)
  3367. return nullptr;
  3368. if (!consumeIf('_'))
  3369. return nullptr;
  3370. return make<BitIntType>(Size, Signed);
  3371. }
  3372. // ::= Di # char32_t
  3373. case 'i':
  3374. First += 2;
  3375. return make<NameType>("char32_t");
  3376. // ::= Ds # char16_t
  3377. case 's':
  3378. First += 2;
  3379. return make<NameType>("char16_t");
  3380. // ::= Du # char8_t (C++2a, not yet in the Itanium spec)
  3381. case 'u':
  3382. First += 2;
  3383. return make<NameType>("char8_t");
  3384. // ::= Da # auto (in dependent new-expressions)
  3385. case 'a':
  3386. First += 2;
  3387. return make<NameType>("auto");
  3388. // ::= Dc # decltype(auto)
  3389. case 'c':
  3390. First += 2;
  3391. return make<NameType>("decltype(auto)");
  3392. // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
  3393. case 'n':
  3394. First += 2;
  3395. return make<NameType>("std::nullptr_t");
  3396. // ::= <decltype>
  3397. case 't':
  3398. case 'T': {
  3399. Result = getDerived().parseDecltype();
  3400. break;
  3401. }
  3402. // extension ::= <vector-type> # <vector-type> starts with Dv
  3403. case 'v': {
  3404. Result = getDerived().parseVectorType();
  3405. break;
  3406. }
  3407. // ::= Dp <type> # pack expansion (C++0x)
  3408. case 'p': {
  3409. First += 2;
  3410. Node *Child = getDerived().parseType();
  3411. if (!Child)
  3412. return nullptr;
  3413. Result = make<ParameterPackExpansion>(Child);
  3414. break;
  3415. }
  3416. // Exception specifier on a function type.
  3417. case 'o':
  3418. case 'O':
  3419. case 'w':
  3420. // Transaction safe function type.
  3421. case 'x':
  3422. Result = getDerived().parseFunctionType();
  3423. break;
  3424. }
  3425. break;
  3426. // ::= <function-type>
  3427. case 'F': {
  3428. Result = getDerived().parseFunctionType();
  3429. break;
  3430. }
  3431. // ::= <array-type>
  3432. case 'A': {
  3433. Result = getDerived().parseArrayType();
  3434. break;
  3435. }
  3436. // ::= <pointer-to-member-type>
  3437. case 'M': {
  3438. Result = getDerived().parsePointerToMemberType();
  3439. break;
  3440. }
  3441. // ::= <template-param>
  3442. case 'T': {
  3443. // This could be an elaborate type specifier on a <class-enum-type>.
  3444. if (look(1) == 's' || look(1) == 'u' || look(1) == 'e') {
  3445. Result = getDerived().parseClassEnumType();
  3446. break;
  3447. }
  3448. Result = getDerived().parseTemplateParam();
  3449. if (Result == nullptr)
  3450. return nullptr;
  3451. // Result could be either of:
  3452. // <type> ::= <template-param>
  3453. // <type> ::= <template-template-param> <template-args>
  3454. //
  3455. // <template-template-param> ::= <template-param>
  3456. // ::= <substitution>
  3457. //
  3458. // If this is followed by some <template-args>, and we're permitted to
  3459. // parse them, take the second production.
  3460. if (TryToParseTemplateArgs && look() == 'I') {
  3461. Node *TA = getDerived().parseTemplateArgs();
  3462. if (TA == nullptr)
  3463. return nullptr;
  3464. Result = make<NameWithTemplateArgs>(Result, TA);
  3465. }
  3466. break;
  3467. }
  3468. // ::= P <type> # pointer
  3469. case 'P': {
  3470. ++First;
  3471. Node *Ptr = getDerived().parseType();
  3472. if (Ptr == nullptr)
  3473. return nullptr;
  3474. Result = make<PointerType>(Ptr);
  3475. break;
  3476. }
  3477. // ::= R <type> # l-value reference
  3478. case 'R': {
  3479. ++First;
  3480. Node *Ref = getDerived().parseType();
  3481. if (Ref == nullptr)
  3482. return nullptr;
  3483. Result = make<ReferenceType>(Ref, ReferenceKind::LValue);
  3484. break;
  3485. }
  3486. // ::= O <type> # r-value reference (C++11)
  3487. case 'O': {
  3488. ++First;
  3489. Node *Ref = getDerived().parseType();
  3490. if (Ref == nullptr)
  3491. return nullptr;
  3492. Result = make<ReferenceType>(Ref, ReferenceKind::RValue);
  3493. break;
  3494. }
  3495. // ::= C <type> # complex pair (C99)
  3496. case 'C': {
  3497. ++First;
  3498. Node *P = getDerived().parseType();
  3499. if (P == nullptr)
  3500. return nullptr;
  3501. Result = make<PostfixQualifiedType>(P, " complex");
  3502. break;
  3503. }
  3504. // ::= G <type> # imaginary (C99)
  3505. case 'G': {
  3506. ++First;
  3507. Node *P = getDerived().parseType();
  3508. if (P == nullptr)
  3509. return P;
  3510. Result = make<PostfixQualifiedType>(P, " imaginary");
  3511. break;
  3512. }
  3513. // ::= <substitution> # See Compression below
  3514. case 'S': {
  3515. if (look(1) != 't') {
  3516. bool IsSubst = false;
  3517. Result = getDerived().parseUnscopedName(nullptr, &IsSubst);
  3518. if (!Result)
  3519. return nullptr;
  3520. // Sub could be either of:
  3521. // <type> ::= <substitution>
  3522. // <type> ::= <template-template-param> <template-args>
  3523. //
  3524. // <template-template-param> ::= <template-param>
  3525. // ::= <substitution>
  3526. //
  3527. // If this is followed by some <template-args>, and we're permitted to
  3528. // parse them, take the second production.
  3529. if (look() == 'I' && (!IsSubst || TryToParseTemplateArgs)) {
  3530. if (!IsSubst)
  3531. Subs.push_back(Result);
  3532. Node *TA = getDerived().parseTemplateArgs();
  3533. if (TA == nullptr)
  3534. return nullptr;
  3535. Result = make<NameWithTemplateArgs>(Result, TA);
  3536. } else if (IsSubst) {
  3537. // If all we parsed was a substitution, don't re-insert into the
  3538. // substitution table.
  3539. return Result;
  3540. }
  3541. break;
  3542. }
  3543. DEMANGLE_FALLTHROUGH;
  3544. }
  3545. // ::= <class-enum-type>
  3546. default: {
  3547. Result = getDerived().parseClassEnumType();
  3548. break;
  3549. }
  3550. }
  3551. // If we parsed a type, insert it into the substitution table. Note that all
  3552. // <builtin-type>s and <substitution>s have already bailed out, because they
  3553. // don't get substitutions.
  3554. if (Result != nullptr)
  3555. Subs.push_back(Result);
  3556. return Result;
  3557. }
  3558. template <typename Derived, typename Alloc>
  3559. Node *
  3560. AbstractManglingParser<Derived, Alloc>::parsePrefixExpr(std::string_view Kind,
  3561. Node::Prec Prec) {
  3562. Node *E = getDerived().parseExpr();
  3563. if (E == nullptr)
  3564. return nullptr;
  3565. return make<PrefixExpr>(Kind, E, Prec);
  3566. }
  3567. template <typename Derived, typename Alloc>
  3568. Node *
  3569. AbstractManglingParser<Derived, Alloc>::parseBinaryExpr(std::string_view 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 *AbstractManglingParser<Derived, Alloc>::parseIntegerLiteral(
  3581. std::string_view Lit) {
  3582. std::string_view 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. std::string_view 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. std::string_view 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. std::string_view 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. std::string_view 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. std::string_view 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. std::string_view Data(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 'J': {
  4751. ++First;
  4752. size_t ArgsBegin = Names.size();
  4753. while (!consumeIf('E')) {
  4754. Node *Arg = getDerived().parseTemplateArg();
  4755. if (Arg == nullptr)
  4756. return nullptr;
  4757. Names.push_back(Arg);
  4758. }
  4759. NodeArray Args = popTrailingNodeArray(ArgsBegin);
  4760. return make<TemplateArgumentPack>(Args);
  4761. }
  4762. case 'L': {
  4763. // ::= LZ <encoding> E # extension
  4764. if (look(1) == 'Z') {
  4765. First += 2;
  4766. Node *Arg = getDerived().parseEncoding();
  4767. if (Arg == nullptr || !consumeIf('E'))
  4768. return nullptr;
  4769. return Arg;
  4770. }
  4771. // ::= <expr-primary> # simple expressions
  4772. return getDerived().parseExprPrimary();
  4773. }
  4774. default:
  4775. return getDerived().parseType();
  4776. }
  4777. }
  4778. // <template-args> ::= I <template-arg>* E
  4779. // extension, the abi says <template-arg>+
  4780. template <typename Derived, typename Alloc>
  4781. Node *
  4782. AbstractManglingParser<Derived, Alloc>::parseTemplateArgs(bool TagTemplates) {
  4783. if (!consumeIf('I'))
  4784. return nullptr;
  4785. // <template-params> refer to the innermost <template-args>. Clear out any
  4786. // outer args that we may have inserted into TemplateParams.
  4787. if (TagTemplates) {
  4788. TemplateParams.clear();
  4789. TemplateParams.push_back(&OuterTemplateParams);
  4790. OuterTemplateParams.clear();
  4791. }
  4792. size_t ArgsBegin = Names.size();
  4793. while (!consumeIf('E')) {
  4794. if (TagTemplates) {
  4795. auto OldParams = std::move(TemplateParams);
  4796. Node *Arg = getDerived().parseTemplateArg();
  4797. TemplateParams = std::move(OldParams);
  4798. if (Arg == nullptr)
  4799. return nullptr;
  4800. Names.push_back(Arg);
  4801. Node *TableEntry = Arg;
  4802. if (Arg->getKind() == Node::KTemplateArgumentPack) {
  4803. TableEntry = make<ParameterPack>(
  4804. static_cast<TemplateArgumentPack*>(TableEntry)->getElements());
  4805. if (!TableEntry)
  4806. return nullptr;
  4807. }
  4808. TemplateParams.back()->push_back(TableEntry);
  4809. } else {
  4810. Node *Arg = getDerived().parseTemplateArg();
  4811. if (Arg == nullptr)
  4812. return nullptr;
  4813. Names.push_back(Arg);
  4814. }
  4815. }
  4816. return make<TemplateArgs>(popTrailingNodeArray(ArgsBegin));
  4817. }
  4818. // <mangled-name> ::= _Z <encoding>
  4819. // ::= <type>
  4820. // extension ::= ___Z <encoding> _block_invoke
  4821. // extension ::= ___Z <encoding> _block_invoke<decimal-digit>+
  4822. // extension ::= ___Z <encoding> _block_invoke_<decimal-digit>+
  4823. template <typename Derived, typename Alloc>
  4824. Node *AbstractManglingParser<Derived, Alloc>::parse() {
  4825. if (consumeIf("_Z") || consumeIf("__Z")) {
  4826. Node *Encoding = getDerived().parseEncoding();
  4827. if (Encoding == nullptr)
  4828. return nullptr;
  4829. if (look() == '.') {
  4830. Encoding =
  4831. make<DotSuffix>(Encoding, std::string_view(First, Last - First));
  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