ItaniumDemangle.h 161 KB

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