ItaniumDemangle.h 168 KB

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