ASTMatchers.h 251 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file implements matchers to be used together with the MatchFinder to
  15. // match AST nodes.
  16. //
  17. // Matchers are created by generator functions, which can be combined in
  18. // a functional in-language DSL to express queries over the C++ AST.
  19. //
  20. // For example, to match a class with a certain name, one would call:
  21. // cxxRecordDecl(hasName("MyClass"))
  22. // which returns a matcher that can be used to find all AST nodes that declare
  23. // a class named 'MyClass'.
  24. //
  25. // For more complicated match expressions we're often interested in accessing
  26. // multiple parts of the matched AST nodes once a match is found. In that case,
  27. // call `.bind("name")` on match expressions that match the nodes you want to
  28. // access.
  29. //
  30. // For example, when we're interested in child classes of a certain class, we
  31. // would write:
  32. // cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child")))
  33. // When the match is found via the MatchFinder, a user provided callback will
  34. // be called with a BoundNodes instance that contains a mapping from the
  35. // strings that we provided for the `.bind()` calls to the nodes that were
  36. // matched.
  37. // In the given example, each time our matcher finds a match we get a callback
  38. // where "child" is bound to the RecordDecl node of the matching child
  39. // class declaration.
  40. //
  41. // See ASTMatchersInternal.h for a more in-depth explanation of the
  42. // implementation details of the matcher framework.
  43. //
  44. // See ASTMatchFinder.h for how to use the generated matchers to run over
  45. // an AST.
  46. //
  47. //===----------------------------------------------------------------------===//
  48. #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
  49. #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
  50. #include "clang/AST/ASTContext.h"
  51. #include "clang/AST/ASTTypeTraits.h"
  52. #include "clang/AST/Attr.h"
  53. #include "clang/AST/CXXInheritance.h"
  54. #include "clang/AST/Decl.h"
  55. #include "clang/AST/DeclCXX.h"
  56. #include "clang/AST/DeclFriend.h"
  57. #include "clang/AST/DeclObjC.h"
  58. #include "clang/AST/DeclTemplate.h"
  59. #include "clang/AST/Expr.h"
  60. #include "clang/AST/ExprCXX.h"
  61. #include "clang/AST/ExprObjC.h"
  62. #include "clang/AST/LambdaCapture.h"
  63. #include "clang/AST/NestedNameSpecifier.h"
  64. #include "clang/AST/OpenMPClause.h"
  65. #include "clang/AST/OperationKinds.h"
  66. #include "clang/AST/ParentMapContext.h"
  67. #include "clang/AST/Stmt.h"
  68. #include "clang/AST/StmtCXX.h"
  69. #include "clang/AST/StmtObjC.h"
  70. #include "clang/AST/StmtOpenMP.h"
  71. #include "clang/AST/TemplateBase.h"
  72. #include "clang/AST/TemplateName.h"
  73. #include "clang/AST/Type.h"
  74. #include "clang/AST/TypeLoc.h"
  75. #include "clang/ASTMatchers/ASTMatchersInternal.h"
  76. #include "clang/ASTMatchers/ASTMatchersMacros.h"
  77. #include "clang/Basic/AttrKinds.h"
  78. #include "clang/Basic/ExceptionSpecificationType.h"
  79. #include "clang/Basic/FileManager.h"
  80. #include "clang/Basic/IdentifierTable.h"
  81. #include "clang/Basic/LLVM.h"
  82. #include "clang/Basic/SourceManager.h"
  83. #include "clang/Basic/Specifiers.h"
  84. #include "clang/Basic/TypeTraits.h"
  85. #include "llvm/ADT/ArrayRef.h"
  86. #include "llvm/ADT/SmallVector.h"
  87. #include "llvm/ADT/StringRef.h"
  88. #include "llvm/Support/Casting.h"
  89. #include "llvm/Support/Compiler.h"
  90. #include "llvm/Support/ErrorHandling.h"
  91. #include "llvm/Support/Regex.h"
  92. #include <cassert>
  93. #include <cstddef>
  94. #include <iterator>
  95. #include <limits>
  96. #include <optional>
  97. #include <string>
  98. #include <utility>
  99. #include <vector>
  100. namespace clang {
  101. namespace ast_matchers {
  102. /// Maps string IDs to AST nodes matched by parts of a matcher.
  103. ///
  104. /// The bound nodes are generated by calling \c bind("id") on the node matchers
  105. /// of the nodes we want to access later.
  106. ///
  107. /// The instances of BoundNodes are created by \c MatchFinder when the user's
  108. /// callbacks are executed every time a match is found.
  109. class BoundNodes {
  110. public:
  111. /// Returns the AST node bound to \c ID.
  112. ///
  113. /// Returns NULL if there was no node bound to \c ID or if there is a node but
  114. /// it cannot be converted to the specified type.
  115. template <typename T>
  116. const T *getNodeAs(StringRef ID) const {
  117. return MyBoundNodes.getNodeAs<T>(ID);
  118. }
  119. /// Type of mapping from binding identifiers to bound nodes. This type
  120. /// is an associative container with a key type of \c std::string and a value
  121. /// type of \c clang::DynTypedNode
  122. using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
  123. /// Retrieve mapping from binding identifiers to bound nodes.
  124. const IDToNodeMap &getMap() const {
  125. return MyBoundNodes.getMap();
  126. }
  127. private:
  128. friend class internal::BoundNodesTreeBuilder;
  129. /// Create BoundNodes from a pre-filled map of bindings.
  130. BoundNodes(internal::BoundNodesMap &MyBoundNodes)
  131. : MyBoundNodes(MyBoundNodes) {}
  132. internal::BoundNodesMap MyBoundNodes;
  133. };
  134. /// Types of matchers for the top-level classes in the AST class
  135. /// hierarchy.
  136. /// @{
  137. using DeclarationMatcher = internal::Matcher<Decl>;
  138. using StatementMatcher = internal::Matcher<Stmt>;
  139. using TypeMatcher = internal::Matcher<QualType>;
  140. using TypeLocMatcher = internal::Matcher<TypeLoc>;
  141. using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
  142. using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
  143. using CXXBaseSpecifierMatcher = internal::Matcher<CXXBaseSpecifier>;
  144. using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
  145. using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
  146. using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
  147. using LambdaCaptureMatcher = internal::Matcher<LambdaCapture>;
  148. using AttrMatcher = internal::Matcher<Attr>;
  149. /// @}
  150. /// Matches any node.
  151. ///
  152. /// Useful when another matcher requires a child matcher, but there's no
  153. /// additional constraint. This will often be used with an explicit conversion
  154. /// to an \c internal::Matcher<> type such as \c TypeMatcher.
  155. ///
  156. /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
  157. /// \code
  158. /// "int* p" and "void f()" in
  159. /// int* p;
  160. /// void f();
  161. /// \endcode
  162. ///
  163. /// Usable as: Any Matcher
  164. inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
  165. /// Matches the top declaration context.
  166. ///
  167. /// Given
  168. /// \code
  169. /// int X;
  170. /// namespace NS {
  171. /// int Y;
  172. /// } // namespace NS
  173. /// \endcode
  174. /// decl(hasDeclContext(translationUnitDecl()))
  175. /// matches "int X", but not "int Y".
  176. extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
  177. translationUnitDecl;
  178. /// Matches typedef declarations.
  179. ///
  180. /// Given
  181. /// \code
  182. /// typedef int X;
  183. /// using Y = int;
  184. /// \endcode
  185. /// typedefDecl()
  186. /// matches "typedef int X", but not "using Y = int"
  187. extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
  188. typedefDecl;
  189. /// Matches typedef name declarations.
  190. ///
  191. /// Given
  192. /// \code
  193. /// typedef int X;
  194. /// using Y = int;
  195. /// \endcode
  196. /// typedefNameDecl()
  197. /// matches "typedef int X" and "using Y = int"
  198. extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
  199. typedefNameDecl;
  200. /// Matches type alias declarations.
  201. ///
  202. /// Given
  203. /// \code
  204. /// typedef int X;
  205. /// using Y = int;
  206. /// \endcode
  207. /// typeAliasDecl()
  208. /// matches "using Y = int", but not "typedef int X"
  209. extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
  210. typeAliasDecl;
  211. /// Matches type alias template declarations.
  212. ///
  213. /// typeAliasTemplateDecl() matches
  214. /// \code
  215. /// template <typename T>
  216. /// using Y = X<T>;
  217. /// \endcode
  218. extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
  219. typeAliasTemplateDecl;
  220. /// Matches AST nodes that were expanded within the main-file.
  221. ///
  222. /// Example matches X but not Y
  223. /// (matcher = cxxRecordDecl(isExpansionInMainFile())
  224. /// \code
  225. /// #include <Y.h>
  226. /// class X {};
  227. /// \endcode
  228. /// Y.h:
  229. /// \code
  230. /// class Y {};
  231. /// \endcode
  232. ///
  233. /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
  234. AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
  235. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
  236. auto &SourceManager = Finder->getASTContext().getSourceManager();
  237. return SourceManager.isInMainFile(
  238. SourceManager.getExpansionLoc(Node.getBeginLoc()));
  239. }
  240. /// Matches AST nodes that were expanded within system-header-files.
  241. ///
  242. /// Example matches Y but not X
  243. /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
  244. /// \code
  245. /// #include <SystemHeader.h>
  246. /// class X {};
  247. /// \endcode
  248. /// SystemHeader.h:
  249. /// \code
  250. /// class Y {};
  251. /// \endcode
  252. ///
  253. /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
  254. AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
  255. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
  256. auto &SourceManager = Finder->getASTContext().getSourceManager();
  257. auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
  258. if (ExpansionLoc.isInvalid()) {
  259. return false;
  260. }
  261. return SourceManager.isInSystemHeader(ExpansionLoc);
  262. }
  263. /// Matches AST nodes that were expanded within files whose name is
  264. /// partially matching a given regex.
  265. ///
  266. /// Example matches Y but not X
  267. /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
  268. /// \code
  269. /// #include "ASTMatcher.h"
  270. /// class X {};
  271. /// \endcode
  272. /// ASTMatcher.h:
  273. /// \code
  274. /// class Y {};
  275. /// \endcode
  276. ///
  277. /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
  278. AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
  279. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt,
  280. TypeLoc),
  281. RegExp) {
  282. auto &SourceManager = Finder->getASTContext().getSourceManager();
  283. auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
  284. if (ExpansionLoc.isInvalid()) {
  285. return false;
  286. }
  287. auto FileEntry =
  288. SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
  289. if (!FileEntry) {
  290. return false;
  291. }
  292. auto Filename = FileEntry->getName();
  293. return RegExp->match(Filename);
  294. }
  295. /// Matches statements that are (transitively) expanded from the named macro.
  296. /// Does not match if only part of the statement is expanded from that macro or
  297. /// if different parts of the statement are expanded from different
  298. /// appearances of the macro.
  299. AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
  300. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
  301. std::string, MacroName) {
  302. // Verifies that the statement' beginning and ending are both expanded from
  303. // the same instance of the given macro.
  304. auto& Context = Finder->getASTContext();
  305. std::optional<SourceLocation> B =
  306. internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
  307. if (!B) return false;
  308. std::optional<SourceLocation> E =
  309. internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
  310. if (!E) return false;
  311. return *B == *E;
  312. }
  313. /// Matches declarations.
  314. ///
  315. /// Examples matches \c X, \c C, and the friend declaration inside \c C;
  316. /// \code
  317. /// void X();
  318. /// class C {
  319. /// friend X;
  320. /// };
  321. /// \endcode
  322. extern const internal::VariadicAllOfMatcher<Decl> decl;
  323. /// Matches decomposition-declarations.
  324. ///
  325. /// Examples matches the declaration node with \c foo and \c bar, but not
  326. /// \c number.
  327. /// (matcher = declStmt(has(decompositionDecl())))
  328. ///
  329. /// \code
  330. /// int number = 42;
  331. /// auto [foo, bar] = std::make_pair{42, 42};
  332. /// \endcode
  333. extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl>
  334. decompositionDecl;
  335. /// Matches binding declarations
  336. /// Example matches \c foo and \c bar
  337. /// (matcher = bindingDecl()
  338. ///
  339. /// \code
  340. /// auto [foo, bar] = std::make_pair{42, 42};
  341. /// \endcode
  342. extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl>
  343. bindingDecl;
  344. /// Matches a declaration of a linkage specification.
  345. ///
  346. /// Given
  347. /// \code
  348. /// extern "C" {}
  349. /// \endcode
  350. /// linkageSpecDecl()
  351. /// matches "extern "C" {}"
  352. extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
  353. linkageSpecDecl;
  354. /// Matches a declaration of anything that could have a name.
  355. ///
  356. /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
  357. /// \code
  358. /// typedef int X;
  359. /// struct S {
  360. /// union {
  361. /// int i;
  362. /// } U;
  363. /// };
  364. /// \endcode
  365. extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
  366. /// Matches a declaration of label.
  367. ///
  368. /// Given
  369. /// \code
  370. /// goto FOO;
  371. /// FOO: bar();
  372. /// \endcode
  373. /// labelDecl()
  374. /// matches 'FOO:'
  375. extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
  376. /// Matches a declaration of a namespace.
  377. ///
  378. /// Given
  379. /// \code
  380. /// namespace {}
  381. /// namespace test {}
  382. /// \endcode
  383. /// namespaceDecl()
  384. /// matches "namespace {}" and "namespace test {}"
  385. extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
  386. namespaceDecl;
  387. /// Matches a declaration of a namespace alias.
  388. ///
  389. /// Given
  390. /// \code
  391. /// namespace test {}
  392. /// namespace alias = ::test;
  393. /// \endcode
  394. /// namespaceAliasDecl()
  395. /// matches "namespace alias" but not "namespace test"
  396. extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
  397. namespaceAliasDecl;
  398. /// Matches class, struct, and union declarations.
  399. ///
  400. /// Example matches \c X, \c Z, \c U, and \c S
  401. /// \code
  402. /// class X;
  403. /// template<class T> class Z {};
  404. /// struct S {};
  405. /// union U {};
  406. /// \endcode
  407. extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
  408. /// Matches C++ class declarations.
  409. ///
  410. /// Example matches \c X, \c Z
  411. /// \code
  412. /// class X;
  413. /// template<class T> class Z {};
  414. /// \endcode
  415. extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
  416. cxxRecordDecl;
  417. /// Matches C++ class template declarations.
  418. ///
  419. /// Example matches \c Z
  420. /// \code
  421. /// template<class T> class Z {};
  422. /// \endcode
  423. extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
  424. classTemplateDecl;
  425. /// Matches C++ class template specializations.
  426. ///
  427. /// Given
  428. /// \code
  429. /// template<typename T> class A {};
  430. /// template<> class A<double> {};
  431. /// A<int> a;
  432. /// \endcode
  433. /// classTemplateSpecializationDecl()
  434. /// matches the specializations \c A<int> and \c A<double>
  435. extern const internal::VariadicDynCastAllOfMatcher<
  436. Decl, ClassTemplateSpecializationDecl>
  437. classTemplateSpecializationDecl;
  438. /// Matches C++ class template partial specializations.
  439. ///
  440. /// Given
  441. /// \code
  442. /// template<class T1, class T2, int I>
  443. /// class A {};
  444. ///
  445. /// template<class T, int I>
  446. /// class A<T, T*, I> {};
  447. ///
  448. /// template<>
  449. /// class A<int, int, 1> {};
  450. /// \endcode
  451. /// classTemplatePartialSpecializationDecl()
  452. /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
  453. extern const internal::VariadicDynCastAllOfMatcher<
  454. Decl, ClassTemplatePartialSpecializationDecl>
  455. classTemplatePartialSpecializationDecl;
  456. /// Matches declarator declarations (field, variable, function
  457. /// and non-type template parameter declarations).
  458. ///
  459. /// Given
  460. /// \code
  461. /// class X { int y; };
  462. /// \endcode
  463. /// declaratorDecl()
  464. /// matches \c int y.
  465. extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
  466. declaratorDecl;
  467. /// Matches parameter variable declarations.
  468. ///
  469. /// Given
  470. /// \code
  471. /// void f(int x);
  472. /// \endcode
  473. /// parmVarDecl()
  474. /// matches \c int x.
  475. extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
  476. parmVarDecl;
  477. /// Matches C++ access specifier declarations.
  478. ///
  479. /// Given
  480. /// \code
  481. /// class C {
  482. /// public:
  483. /// int a;
  484. /// };
  485. /// \endcode
  486. /// accessSpecDecl()
  487. /// matches 'public:'
  488. extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
  489. accessSpecDecl;
  490. /// Matches class bases.
  491. ///
  492. /// Examples matches \c public virtual B.
  493. /// \code
  494. /// class B {};
  495. /// class C : public virtual B {};
  496. /// \endcode
  497. extern const internal::VariadicAllOfMatcher<CXXBaseSpecifier> cxxBaseSpecifier;
  498. /// Matches constructor initializers.
  499. ///
  500. /// Examples matches \c i(42).
  501. /// \code
  502. /// class C {
  503. /// C() : i(42) {}
  504. /// int i;
  505. /// };
  506. /// \endcode
  507. extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
  508. cxxCtorInitializer;
  509. /// Matches template arguments.
  510. ///
  511. /// Given
  512. /// \code
  513. /// template <typename T> struct C {};
  514. /// C<int> c;
  515. /// \endcode
  516. /// templateArgument()
  517. /// matches 'int' in C<int>.
  518. extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
  519. /// Matches template arguments (with location info).
  520. ///
  521. /// Given
  522. /// \code
  523. /// template <typename T> struct C {};
  524. /// C<int> c;
  525. /// \endcode
  526. /// templateArgumentLoc()
  527. /// matches 'int' in C<int>.
  528. extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
  529. templateArgumentLoc;
  530. /// Matches template name.
  531. ///
  532. /// Given
  533. /// \code
  534. /// template <typename T> class X { };
  535. /// X<int> xi;
  536. /// \endcode
  537. /// templateName()
  538. /// matches 'X' in X<int>.
  539. extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
  540. /// Matches non-type template parameter declarations.
  541. ///
  542. /// Given
  543. /// \code
  544. /// template <typename T, int N> struct C {};
  545. /// \endcode
  546. /// nonTypeTemplateParmDecl()
  547. /// matches 'N', but not 'T'.
  548. extern const internal::VariadicDynCastAllOfMatcher<Decl,
  549. NonTypeTemplateParmDecl>
  550. nonTypeTemplateParmDecl;
  551. /// Matches template type parameter declarations.
  552. ///
  553. /// Given
  554. /// \code
  555. /// template <typename T, int N> struct C {};
  556. /// \endcode
  557. /// templateTypeParmDecl()
  558. /// matches 'T', but not 'N'.
  559. extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
  560. templateTypeParmDecl;
  561. /// Matches template template parameter declarations.
  562. ///
  563. /// Given
  564. /// \code
  565. /// template <template <typename> class Z, int N> struct C {};
  566. /// \endcode
  567. /// templateTypeParmDecl()
  568. /// matches 'Z', but not 'N'.
  569. extern const internal::VariadicDynCastAllOfMatcher<Decl,
  570. TemplateTemplateParmDecl>
  571. templateTemplateParmDecl;
  572. /// Matches public C++ declarations and C++ base specifers that specify public
  573. /// inheritance.
  574. ///
  575. /// Examples:
  576. /// \code
  577. /// class C {
  578. /// public: int a; // fieldDecl(isPublic()) matches 'a'
  579. /// protected: int b;
  580. /// private: int c;
  581. /// };
  582. /// \endcode
  583. ///
  584. /// \code
  585. /// class Base {};
  586. /// class Derived1 : public Base {}; // matches 'Base'
  587. /// struct Derived2 : Base {}; // matches 'Base'
  588. /// \endcode
  589. AST_POLYMORPHIC_MATCHER(isPublic,
  590. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
  591. CXXBaseSpecifier)) {
  592. return getAccessSpecifier(Node) == AS_public;
  593. }
  594. /// Matches protected C++ declarations and C++ base specifers that specify
  595. /// protected inheritance.
  596. ///
  597. /// Examples:
  598. /// \code
  599. /// class C {
  600. /// public: int a;
  601. /// protected: int b; // fieldDecl(isProtected()) matches 'b'
  602. /// private: int c;
  603. /// };
  604. /// \endcode
  605. ///
  606. /// \code
  607. /// class Base {};
  608. /// class Derived : protected Base {}; // matches 'Base'
  609. /// \endcode
  610. AST_POLYMORPHIC_MATCHER(isProtected,
  611. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
  612. CXXBaseSpecifier)) {
  613. return getAccessSpecifier(Node) == AS_protected;
  614. }
  615. /// Matches private C++ declarations and C++ base specifers that specify private
  616. /// inheritance.
  617. ///
  618. /// Examples:
  619. /// \code
  620. /// class C {
  621. /// public: int a;
  622. /// protected: int b;
  623. /// private: int c; // fieldDecl(isPrivate()) matches 'c'
  624. /// };
  625. /// \endcode
  626. ///
  627. /// \code
  628. /// struct Base {};
  629. /// struct Derived1 : private Base {}; // matches 'Base'
  630. /// class Derived2 : Base {}; // matches 'Base'
  631. /// \endcode
  632. AST_POLYMORPHIC_MATCHER(isPrivate,
  633. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
  634. CXXBaseSpecifier)) {
  635. return getAccessSpecifier(Node) == AS_private;
  636. }
  637. /// Matches non-static data members that are bit-fields.
  638. ///
  639. /// Given
  640. /// \code
  641. /// class C {
  642. /// int a : 2;
  643. /// int b;
  644. /// };
  645. /// \endcode
  646. /// fieldDecl(isBitField())
  647. /// matches 'int a;' but not 'int b;'.
  648. AST_MATCHER(FieldDecl, isBitField) {
  649. return Node.isBitField();
  650. }
  651. /// Matches non-static data members that are bit-fields of the specified
  652. /// bit width.
  653. ///
  654. /// Given
  655. /// \code
  656. /// class C {
  657. /// int a : 2;
  658. /// int b : 4;
  659. /// int c : 2;
  660. /// };
  661. /// \endcode
  662. /// fieldDecl(hasBitWidth(2))
  663. /// matches 'int a;' and 'int c;' but not 'int b;'.
  664. AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
  665. return Node.isBitField() &&
  666. Node.getBitWidthValue(Finder->getASTContext()) == Width;
  667. }
  668. /// Matches non-static data members that have an in-class initializer.
  669. ///
  670. /// Given
  671. /// \code
  672. /// class C {
  673. /// int a = 2;
  674. /// int b = 3;
  675. /// int c;
  676. /// };
  677. /// \endcode
  678. /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
  679. /// matches 'int a;' but not 'int b;'.
  680. /// fieldDecl(hasInClassInitializer(anything()))
  681. /// matches 'int a;' and 'int b;' but not 'int c;'.
  682. AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
  683. InnerMatcher) {
  684. const Expr *Initializer = Node.getInClassInitializer();
  685. return (Initializer != nullptr &&
  686. InnerMatcher.matches(*Initializer, Finder, Builder));
  687. }
  688. /// Determines whether the function is "main", which is the entry point
  689. /// into an executable program.
  690. AST_MATCHER(FunctionDecl, isMain) {
  691. return Node.isMain();
  692. }
  693. /// Matches the specialized template of a specialization declaration.
  694. ///
  695. /// Given
  696. /// \code
  697. /// template<typename T> class A {}; #1
  698. /// template<> class A<int> {}; #2
  699. /// \endcode
  700. /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
  701. /// matches '#2' with classTemplateDecl() matching the class template
  702. /// declaration of 'A' at #1.
  703. AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
  704. internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
  705. const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
  706. return (Decl != nullptr &&
  707. InnerMatcher.matches(*Decl, Finder, Builder));
  708. }
  709. /// Matches an entity that has been implicitly added by the compiler (e.g.
  710. /// implicit default/copy constructors).
  711. AST_POLYMORPHIC_MATCHER(isImplicit,
  712. AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Attr,
  713. LambdaCapture)) {
  714. return Node.isImplicit();
  715. }
  716. /// Matches classTemplateSpecializations, templateSpecializationType and
  717. /// functionDecl that have at least one TemplateArgument matching the given
  718. /// InnerMatcher.
  719. ///
  720. /// Given
  721. /// \code
  722. /// template<typename T> class A {};
  723. /// template<> class A<double> {};
  724. /// A<int> a;
  725. ///
  726. /// template<typename T> f() {};
  727. /// void func() { f<int>(); };
  728. /// \endcode
  729. ///
  730. /// \endcode
  731. /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
  732. /// refersToType(asString("int"))))
  733. /// matches the specialization \c A<int>
  734. ///
  735. /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
  736. /// matches the specialization \c f<int>
  737. AST_POLYMORPHIC_MATCHER_P(
  738. hasAnyTemplateArgument,
  739. AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
  740. TemplateSpecializationType,
  741. FunctionDecl),
  742. internal::Matcher<TemplateArgument>, InnerMatcher) {
  743. ArrayRef<TemplateArgument> List =
  744. internal::getTemplateSpecializationArgs(Node);
  745. return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
  746. Builder) != List.end();
  747. }
  748. /// Causes all nested matchers to be matched with the specified traversal kind.
  749. ///
  750. /// Given
  751. /// \code
  752. /// void foo()
  753. /// {
  754. /// int i = 3.0;
  755. /// }
  756. /// \endcode
  757. /// The matcher
  758. /// \code
  759. /// traverse(TK_IgnoreUnlessSpelledInSource,
  760. /// varDecl(hasInitializer(floatLiteral().bind("init")))
  761. /// )
  762. /// \endcode
  763. /// matches the variable declaration with "init" bound to the "3.0".
  764. template <typename T>
  765. internal::Matcher<T> traverse(TraversalKind TK,
  766. const internal::Matcher<T> &InnerMatcher) {
  767. return internal::DynTypedMatcher::constructRestrictedWrapper(
  768. new internal::TraversalMatcher<T>(TK, InnerMatcher),
  769. InnerMatcher.getID().first)
  770. .template unconditionalConvertTo<T>();
  771. }
  772. template <typename T>
  773. internal::BindableMatcher<T>
  774. traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
  775. return internal::BindableMatcher<T>(
  776. internal::DynTypedMatcher::constructRestrictedWrapper(
  777. new internal::TraversalMatcher<T>(TK, InnerMatcher),
  778. InnerMatcher.getID().first)
  779. .template unconditionalConvertTo<T>());
  780. }
  781. template <typename... T>
  782. internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
  783. traverse(TraversalKind TK,
  784. const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
  785. return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
  786. TK, InnerMatcher);
  787. }
  788. template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
  789. typename T, typename ToTypes>
  790. internal::TraversalWrapper<
  791. internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
  792. traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
  793. ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
  794. return internal::TraversalWrapper<
  795. internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
  796. ToTypes>>(TK, InnerMatcher);
  797. }
  798. template <template <typename T, typename... P> class MatcherT, typename... P,
  799. typename ReturnTypesF>
  800. internal::TraversalWrapper<
  801. internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>
  802. traverse(TraversalKind TK,
  803. const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>
  804. &InnerMatcher) {
  805. return internal::TraversalWrapper<
  806. internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK,
  807. InnerMatcher);
  808. }
  809. template <typename... T>
  810. internal::Matcher<typename internal::GetClade<T...>::Type>
  811. traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
  812. return traverse(TK, InnerMatcher.with());
  813. }
  814. /// Matches expressions that match InnerMatcher after any implicit AST
  815. /// nodes are stripped off.
  816. ///
  817. /// Parentheses and explicit casts are not discarded.
  818. /// Given
  819. /// \code
  820. /// class C {};
  821. /// C a = C();
  822. /// C b;
  823. /// C c = b;
  824. /// \endcode
  825. /// The matchers
  826. /// \code
  827. /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
  828. /// \endcode
  829. /// would match the declarations for a, b, and c.
  830. /// While
  831. /// \code
  832. /// varDecl(hasInitializer(cxxConstructExpr()))
  833. /// \endcode
  834. /// only match the declarations for b and c.
  835. AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
  836. InnerMatcher) {
  837. return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
  838. }
  839. /// Matches expressions that match InnerMatcher after any implicit casts
  840. /// are stripped off.
  841. ///
  842. /// Parentheses and explicit casts are not discarded.
  843. /// Given
  844. /// \code
  845. /// int arr[5];
  846. /// int a = 0;
  847. /// char b = 0;
  848. /// const int c = a;
  849. /// int *d = arr;
  850. /// long e = (long) 0l;
  851. /// \endcode
  852. /// The matchers
  853. /// \code
  854. /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
  855. /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
  856. /// \endcode
  857. /// would match the declarations for a, b, c, and d, but not e.
  858. /// While
  859. /// \code
  860. /// varDecl(hasInitializer(integerLiteral()))
  861. /// varDecl(hasInitializer(declRefExpr()))
  862. /// \endcode
  863. /// only match the declarations for a.
  864. AST_MATCHER_P(Expr, ignoringImpCasts,
  865. internal::Matcher<Expr>, InnerMatcher) {
  866. return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
  867. }
  868. /// Matches expressions that match InnerMatcher after parentheses and
  869. /// casts are stripped off.
  870. ///
  871. /// Implicit and non-C Style casts are also discarded.
  872. /// Given
  873. /// \code
  874. /// int a = 0;
  875. /// char b = (0);
  876. /// void* c = reinterpret_cast<char*>(0);
  877. /// char d = char(0);
  878. /// \endcode
  879. /// The matcher
  880. /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
  881. /// would match the declarations for a, b, c, and d.
  882. /// while
  883. /// varDecl(hasInitializer(integerLiteral()))
  884. /// only match the declaration for a.
  885. AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
  886. return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
  887. }
  888. /// Matches expressions that match InnerMatcher after implicit casts and
  889. /// parentheses are stripped off.
  890. ///
  891. /// Explicit casts are not discarded.
  892. /// Given
  893. /// \code
  894. /// int arr[5];
  895. /// int a = 0;
  896. /// char b = (0);
  897. /// const int c = a;
  898. /// int *d = (arr);
  899. /// long e = ((long) 0l);
  900. /// \endcode
  901. /// The matchers
  902. /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
  903. /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
  904. /// would match the declarations for a, b, c, and d, but not e.
  905. /// while
  906. /// varDecl(hasInitializer(integerLiteral()))
  907. /// varDecl(hasInitializer(declRefExpr()))
  908. /// would only match the declaration for a.
  909. AST_MATCHER_P(Expr, ignoringParenImpCasts,
  910. internal::Matcher<Expr>, InnerMatcher) {
  911. return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
  912. }
  913. /// Matches types that match InnerMatcher after any parens are stripped.
  914. ///
  915. /// Given
  916. /// \code
  917. /// void (*fp)(void);
  918. /// \endcode
  919. /// The matcher
  920. /// \code
  921. /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
  922. /// \endcode
  923. /// would match the declaration for fp.
  924. AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
  925. InnerMatcher, 0) {
  926. return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
  927. }
  928. /// Overload \c ignoringParens for \c Expr.
  929. ///
  930. /// Given
  931. /// \code
  932. /// const char* str = ("my-string");
  933. /// \endcode
  934. /// The matcher
  935. /// \code
  936. /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
  937. /// \endcode
  938. /// would match the implicit cast resulting from the assignment.
  939. AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
  940. InnerMatcher, 1) {
  941. const Expr *E = Node.IgnoreParens();
  942. return InnerMatcher.matches(*E, Finder, Builder);
  943. }
  944. /// Matches expressions that are instantiation-dependent even if it is
  945. /// neither type- nor value-dependent.
  946. ///
  947. /// In the following example, the expression sizeof(sizeof(T() + T()))
  948. /// is instantiation-dependent (since it involves a template parameter T),
  949. /// but is neither type- nor value-dependent, since the type of the inner
  950. /// sizeof is known (std::size_t) and therefore the size of the outer
  951. /// sizeof is known.
  952. /// \code
  953. /// template<typename T>
  954. /// void f(T x, T y) { sizeof(sizeof(T() + T()); }
  955. /// \endcode
  956. /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
  957. AST_MATCHER(Expr, isInstantiationDependent) {
  958. return Node.isInstantiationDependent();
  959. }
  960. /// Matches expressions that are type-dependent because the template type
  961. /// is not yet instantiated.
  962. ///
  963. /// For example, the expressions "x" and "x + y" are type-dependent in
  964. /// the following code, but "y" is not type-dependent:
  965. /// \code
  966. /// template<typename T>
  967. /// void add(T x, int y) {
  968. /// x + y;
  969. /// }
  970. /// \endcode
  971. /// expr(isTypeDependent()) matches x + y
  972. AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
  973. /// Matches expression that are value-dependent because they contain a
  974. /// non-type template parameter.
  975. ///
  976. /// For example, the array bound of "Chars" in the following example is
  977. /// value-dependent.
  978. /// \code
  979. /// template<int Size> int f() { return Size; }
  980. /// \endcode
  981. /// expr(isValueDependent()) matches return Size
  982. AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
  983. /// Matches classTemplateSpecializations, templateSpecializationType and
  984. /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
  985. ///
  986. /// Given
  987. /// \code
  988. /// template<typename T, typename U> class A {};
  989. /// A<bool, int> b;
  990. /// A<int, bool> c;
  991. ///
  992. /// template<typename T> void f() {}
  993. /// void func() { f<int>(); };
  994. /// \endcode
  995. /// classTemplateSpecializationDecl(hasTemplateArgument(
  996. /// 1, refersToType(asString("int"))))
  997. /// matches the specialization \c A<bool, int>
  998. ///
  999. /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
  1000. /// matches the specialization \c f<int>
  1001. AST_POLYMORPHIC_MATCHER_P2(
  1002. hasTemplateArgument,
  1003. AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
  1004. TemplateSpecializationType,
  1005. FunctionDecl),
  1006. unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
  1007. ArrayRef<TemplateArgument> List =
  1008. internal::getTemplateSpecializationArgs(Node);
  1009. if (List.size() <= N)
  1010. return false;
  1011. return InnerMatcher.matches(List[N], Finder, Builder);
  1012. }
  1013. /// Matches if the number of template arguments equals \p N.
  1014. ///
  1015. /// Given
  1016. /// \code
  1017. /// template<typename T> struct C {};
  1018. /// C<int> c;
  1019. /// \endcode
  1020. /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
  1021. /// matches C<int>.
  1022. AST_POLYMORPHIC_MATCHER_P(
  1023. templateArgumentCountIs,
  1024. AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
  1025. TemplateSpecializationType),
  1026. unsigned, N) {
  1027. return internal::getTemplateSpecializationArgs(Node).size() == N;
  1028. }
  1029. /// Matches a TemplateArgument that refers to a certain type.
  1030. ///
  1031. /// Given
  1032. /// \code
  1033. /// struct X {};
  1034. /// template<typename T> struct A {};
  1035. /// A<X> a;
  1036. /// \endcode
  1037. /// classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
  1038. /// recordType(hasDeclaration(recordDecl(hasName("X")))))))
  1039. /// matches the specialization of \c struct A generated by \c A<X>.
  1040. AST_MATCHER_P(TemplateArgument, refersToType,
  1041. internal::Matcher<QualType>, InnerMatcher) {
  1042. if (Node.getKind() != TemplateArgument::Type)
  1043. return false;
  1044. return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
  1045. }
  1046. /// Matches a TemplateArgument that refers to a certain template.
  1047. ///
  1048. /// Given
  1049. /// \code
  1050. /// template<template <typename> class S> class X {};
  1051. /// template<typename T> class Y {};
  1052. /// X<Y> xi;
  1053. /// \endcode
  1054. /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
  1055. /// refersToTemplate(templateName())))
  1056. /// matches the specialization \c X<Y>
  1057. AST_MATCHER_P(TemplateArgument, refersToTemplate,
  1058. internal::Matcher<TemplateName>, InnerMatcher) {
  1059. if (Node.getKind() != TemplateArgument::Template)
  1060. return false;
  1061. return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
  1062. }
  1063. /// Matches a canonical TemplateArgument that refers to a certain
  1064. /// declaration.
  1065. ///
  1066. /// Given
  1067. /// \code
  1068. /// struct B { int next; };
  1069. /// template<int(B::*next_ptr)> struct A {};
  1070. /// A<&B::next> a;
  1071. /// \endcode
  1072. /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
  1073. /// refersToDeclaration(fieldDecl(hasName("next")))))
  1074. /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
  1075. /// \c B::next
  1076. AST_MATCHER_P(TemplateArgument, refersToDeclaration,
  1077. internal::Matcher<Decl>, InnerMatcher) {
  1078. if (Node.getKind() == TemplateArgument::Declaration)
  1079. return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
  1080. return false;
  1081. }
  1082. /// Matches a sugar TemplateArgument that refers to a certain expression.
  1083. ///
  1084. /// Given
  1085. /// \code
  1086. /// struct B { int next; };
  1087. /// template<int(B::*next_ptr)> struct A {};
  1088. /// A<&B::next> a;
  1089. /// \endcode
  1090. /// templateSpecializationType(hasAnyTemplateArgument(
  1091. /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
  1092. /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
  1093. /// \c B::next
  1094. AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
  1095. if (Node.getKind() == TemplateArgument::Expression)
  1096. return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
  1097. return false;
  1098. }
  1099. /// Matches a TemplateArgument that is an integral value.
  1100. ///
  1101. /// Given
  1102. /// \code
  1103. /// template<int T> struct C {};
  1104. /// C<42> c;
  1105. /// \endcode
  1106. /// classTemplateSpecializationDecl(
  1107. /// hasAnyTemplateArgument(isIntegral()))
  1108. /// matches the implicit instantiation of C in C<42>
  1109. /// with isIntegral() matching 42.
  1110. AST_MATCHER(TemplateArgument, isIntegral) {
  1111. return Node.getKind() == TemplateArgument::Integral;
  1112. }
  1113. /// Matches a TemplateArgument that refers to an integral type.
  1114. ///
  1115. /// Given
  1116. /// \code
  1117. /// template<int T> struct C {};
  1118. /// C<42> c;
  1119. /// \endcode
  1120. /// classTemplateSpecializationDecl(
  1121. /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
  1122. /// matches the implicit instantiation of C in C<42>.
  1123. AST_MATCHER_P(TemplateArgument, refersToIntegralType,
  1124. internal::Matcher<QualType>, InnerMatcher) {
  1125. if (Node.getKind() != TemplateArgument::Integral)
  1126. return false;
  1127. return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
  1128. }
  1129. /// Matches a TemplateArgument of integral type with a given value.
  1130. ///
  1131. /// Note that 'Value' is a string as the template argument's value is
  1132. /// an arbitrary precision integer. 'Value' must be euqal to the canonical
  1133. /// representation of that integral value in base 10.
  1134. ///
  1135. /// Given
  1136. /// \code
  1137. /// template<int T> struct C {};
  1138. /// C<42> c;
  1139. /// \endcode
  1140. /// classTemplateSpecializationDecl(
  1141. /// hasAnyTemplateArgument(equalsIntegralValue("42")))
  1142. /// matches the implicit instantiation of C in C<42>.
  1143. AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
  1144. std::string, Value) {
  1145. if (Node.getKind() != TemplateArgument::Integral)
  1146. return false;
  1147. return toString(Node.getAsIntegral(), 10) == Value;
  1148. }
  1149. /// Matches an Objective-C autorelease pool statement.
  1150. ///
  1151. /// Given
  1152. /// \code
  1153. /// @autoreleasepool {
  1154. /// int x = 0;
  1155. /// }
  1156. /// \endcode
  1157. /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
  1158. /// inside the autorelease pool.
  1159. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1160. ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
  1161. /// Matches any value declaration.
  1162. ///
  1163. /// Example matches A, B, C and F
  1164. /// \code
  1165. /// enum X { A, B, C };
  1166. /// void F();
  1167. /// \endcode
  1168. extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
  1169. /// Matches C++ constructor declarations.
  1170. ///
  1171. /// Example matches Foo::Foo() and Foo::Foo(int)
  1172. /// \code
  1173. /// class Foo {
  1174. /// public:
  1175. /// Foo();
  1176. /// Foo(int);
  1177. /// int DoSomething();
  1178. /// };
  1179. /// \endcode
  1180. extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
  1181. cxxConstructorDecl;
  1182. /// Matches explicit C++ destructor declarations.
  1183. ///
  1184. /// Example matches Foo::~Foo()
  1185. /// \code
  1186. /// class Foo {
  1187. /// public:
  1188. /// virtual ~Foo();
  1189. /// };
  1190. /// \endcode
  1191. extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
  1192. cxxDestructorDecl;
  1193. /// Matches enum declarations.
  1194. ///
  1195. /// Example matches X
  1196. /// \code
  1197. /// enum X {
  1198. /// A, B, C
  1199. /// };
  1200. /// \endcode
  1201. extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
  1202. /// Matches enum constants.
  1203. ///
  1204. /// Example matches A, B, C
  1205. /// \code
  1206. /// enum X {
  1207. /// A, B, C
  1208. /// };
  1209. /// \endcode
  1210. extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
  1211. enumConstantDecl;
  1212. /// Matches tag declarations.
  1213. ///
  1214. /// Example matches X, Z, U, S, E
  1215. /// \code
  1216. /// class X;
  1217. /// template<class T> class Z {};
  1218. /// struct S {};
  1219. /// union U {};
  1220. /// enum E {
  1221. /// A, B, C
  1222. /// };
  1223. /// \endcode
  1224. extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
  1225. /// Matches method declarations.
  1226. ///
  1227. /// Example matches y
  1228. /// \code
  1229. /// class X { void y(); };
  1230. /// \endcode
  1231. extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
  1232. cxxMethodDecl;
  1233. /// Matches conversion operator declarations.
  1234. ///
  1235. /// Example matches the operator.
  1236. /// \code
  1237. /// class X { operator int() const; };
  1238. /// \endcode
  1239. extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
  1240. cxxConversionDecl;
  1241. /// Matches user-defined and implicitly generated deduction guide.
  1242. ///
  1243. /// Example matches the deduction guide.
  1244. /// \code
  1245. /// template<typename T>
  1246. /// class X { X(int) };
  1247. /// X(int) -> X<int>;
  1248. /// \endcode
  1249. extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
  1250. cxxDeductionGuideDecl;
  1251. /// Matches variable declarations.
  1252. ///
  1253. /// Note: this does not match declarations of member variables, which are
  1254. /// "field" declarations in Clang parlance.
  1255. ///
  1256. /// Example matches a
  1257. /// \code
  1258. /// int a;
  1259. /// \endcode
  1260. extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
  1261. /// Matches field declarations.
  1262. ///
  1263. /// Given
  1264. /// \code
  1265. /// class X { int m; };
  1266. /// \endcode
  1267. /// fieldDecl()
  1268. /// matches 'm'.
  1269. extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
  1270. /// Matches indirect field declarations.
  1271. ///
  1272. /// Given
  1273. /// \code
  1274. /// struct X { struct { int a; }; };
  1275. /// \endcode
  1276. /// indirectFieldDecl()
  1277. /// matches 'a'.
  1278. extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
  1279. indirectFieldDecl;
  1280. /// Matches function declarations.
  1281. ///
  1282. /// Example matches f
  1283. /// \code
  1284. /// void f();
  1285. /// \endcode
  1286. extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
  1287. functionDecl;
  1288. /// Matches C++ function template declarations.
  1289. ///
  1290. /// Example matches f
  1291. /// \code
  1292. /// template<class T> void f(T t) {}
  1293. /// \endcode
  1294. extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
  1295. functionTemplateDecl;
  1296. /// Matches friend declarations.
  1297. ///
  1298. /// Given
  1299. /// \code
  1300. /// class X { friend void foo(); };
  1301. /// \endcode
  1302. /// friendDecl()
  1303. /// matches 'friend void foo()'.
  1304. extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
  1305. /// Matches statements.
  1306. ///
  1307. /// Given
  1308. /// \code
  1309. /// { ++a; }
  1310. /// \endcode
  1311. /// stmt()
  1312. /// matches both the compound statement '{ ++a; }' and '++a'.
  1313. extern const internal::VariadicAllOfMatcher<Stmt> stmt;
  1314. /// Matches declaration statements.
  1315. ///
  1316. /// Given
  1317. /// \code
  1318. /// int a;
  1319. /// \endcode
  1320. /// declStmt()
  1321. /// matches 'int a'.
  1322. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
  1323. /// Matches member expressions.
  1324. ///
  1325. /// Given
  1326. /// \code
  1327. /// class Y {
  1328. /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
  1329. /// int a; static int b;
  1330. /// };
  1331. /// \endcode
  1332. /// memberExpr()
  1333. /// matches this->x, x, y.x, a, this->b
  1334. extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
  1335. /// Matches unresolved member expressions.
  1336. ///
  1337. /// Given
  1338. /// \code
  1339. /// struct X {
  1340. /// template <class T> void f();
  1341. /// void g();
  1342. /// };
  1343. /// template <class T> void h() { X x; x.f<T>(); x.g(); }
  1344. /// \endcode
  1345. /// unresolvedMemberExpr()
  1346. /// matches x.f<T>
  1347. extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
  1348. unresolvedMemberExpr;
  1349. /// Matches member expressions where the actual member referenced could not be
  1350. /// resolved because the base expression or the member name was dependent.
  1351. ///
  1352. /// Given
  1353. /// \code
  1354. /// template <class T> void f() { T t; t.g(); }
  1355. /// \endcode
  1356. /// cxxDependentScopeMemberExpr()
  1357. /// matches t.g
  1358. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1359. CXXDependentScopeMemberExpr>
  1360. cxxDependentScopeMemberExpr;
  1361. /// Matches call expressions.
  1362. ///
  1363. /// Example matches x.y() and y()
  1364. /// \code
  1365. /// X x;
  1366. /// x.y();
  1367. /// y();
  1368. /// \endcode
  1369. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
  1370. /// Matches call expressions which were resolved using ADL.
  1371. ///
  1372. /// Example matches y(x) but not y(42) or NS::y(x).
  1373. /// \code
  1374. /// namespace NS {
  1375. /// struct X {};
  1376. /// void y(X);
  1377. /// }
  1378. ///
  1379. /// void y(...);
  1380. ///
  1381. /// void test() {
  1382. /// NS::X x;
  1383. /// y(x); // Matches
  1384. /// NS::y(x); // Doesn't match
  1385. /// y(42); // Doesn't match
  1386. /// using NS::y;
  1387. /// y(x); // Found by both unqualified lookup and ADL, doesn't match
  1388. // }
  1389. /// \endcode
  1390. AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
  1391. /// Matches lambda expressions.
  1392. ///
  1393. /// Example matches [&](){return 5;}
  1394. /// \code
  1395. /// [&](){return 5;}
  1396. /// \endcode
  1397. extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
  1398. /// Matches member call expressions.
  1399. ///
  1400. /// Example matches x.y()
  1401. /// \code
  1402. /// X x;
  1403. /// x.y();
  1404. /// \endcode
  1405. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
  1406. cxxMemberCallExpr;
  1407. /// Matches ObjectiveC Message invocation expressions.
  1408. ///
  1409. /// The innermost message send invokes the "alloc" class method on the
  1410. /// NSString class, while the outermost message send invokes the
  1411. /// "initWithString" instance method on the object returned from
  1412. /// NSString's "alloc". This matcher should match both message sends.
  1413. /// \code
  1414. /// [[NSString alloc] initWithString:@"Hello"]
  1415. /// \endcode
  1416. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
  1417. objcMessageExpr;
  1418. /// Matches ObjectiveC String literal expressions.
  1419. ///
  1420. /// Example matches @"abcd"
  1421. /// \code
  1422. /// NSString *s = @"abcd";
  1423. /// \endcode
  1424. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
  1425. objcStringLiteral;
  1426. /// Matches Objective-C interface declarations.
  1427. ///
  1428. /// Example matches Foo
  1429. /// \code
  1430. /// @interface Foo
  1431. /// @end
  1432. /// \endcode
  1433. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
  1434. objcInterfaceDecl;
  1435. /// Matches Objective-C implementation declarations.
  1436. ///
  1437. /// Example matches Foo
  1438. /// \code
  1439. /// @implementation Foo
  1440. /// @end
  1441. /// \endcode
  1442. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
  1443. objcImplementationDecl;
  1444. /// Matches Objective-C protocol declarations.
  1445. ///
  1446. /// Example matches FooDelegate
  1447. /// \code
  1448. /// @protocol FooDelegate
  1449. /// @end
  1450. /// \endcode
  1451. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
  1452. objcProtocolDecl;
  1453. /// Matches Objective-C category declarations.
  1454. ///
  1455. /// Example matches Foo (Additions)
  1456. /// \code
  1457. /// @interface Foo (Additions)
  1458. /// @end
  1459. /// \endcode
  1460. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
  1461. objcCategoryDecl;
  1462. /// Matches Objective-C category definitions.
  1463. ///
  1464. /// Example matches Foo (Additions)
  1465. /// \code
  1466. /// @implementation Foo (Additions)
  1467. /// @end
  1468. /// \endcode
  1469. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
  1470. objcCategoryImplDecl;
  1471. /// Matches Objective-C method declarations.
  1472. ///
  1473. /// Example matches both declaration and definition of -[Foo method]
  1474. /// \code
  1475. /// @interface Foo
  1476. /// - (void)method;
  1477. /// @end
  1478. ///
  1479. /// @implementation Foo
  1480. /// - (void)method {}
  1481. /// @end
  1482. /// \endcode
  1483. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
  1484. objcMethodDecl;
  1485. /// Matches block declarations.
  1486. ///
  1487. /// Example matches the declaration of the nameless block printing an input
  1488. /// integer.
  1489. ///
  1490. /// \code
  1491. /// myFunc(^(int p) {
  1492. /// printf("%d", p);
  1493. /// })
  1494. /// \endcode
  1495. extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
  1496. blockDecl;
  1497. /// Matches Objective-C instance variable declarations.
  1498. ///
  1499. /// Example matches _enabled
  1500. /// \code
  1501. /// @implementation Foo {
  1502. /// BOOL _enabled;
  1503. /// }
  1504. /// @end
  1505. /// \endcode
  1506. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
  1507. objcIvarDecl;
  1508. /// Matches Objective-C property declarations.
  1509. ///
  1510. /// Example matches enabled
  1511. /// \code
  1512. /// @interface Foo
  1513. /// @property BOOL enabled;
  1514. /// @end
  1515. /// \endcode
  1516. extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
  1517. objcPropertyDecl;
  1518. /// Matches Objective-C \@throw statements.
  1519. ///
  1520. /// Example matches \@throw
  1521. /// \code
  1522. /// @throw obj;
  1523. /// \endcode
  1524. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
  1525. objcThrowStmt;
  1526. /// Matches Objective-C @try statements.
  1527. ///
  1528. /// Example matches @try
  1529. /// \code
  1530. /// @try {}
  1531. /// @catch (...) {}
  1532. /// \endcode
  1533. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
  1534. objcTryStmt;
  1535. /// Matches Objective-C @catch statements.
  1536. ///
  1537. /// Example matches @catch
  1538. /// \code
  1539. /// @try {}
  1540. /// @catch (...) {}
  1541. /// \endcode
  1542. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
  1543. objcCatchStmt;
  1544. /// Matches Objective-C @finally statements.
  1545. ///
  1546. /// Example matches @finally
  1547. /// \code
  1548. /// @try {}
  1549. /// @finally {}
  1550. /// \endcode
  1551. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
  1552. objcFinallyStmt;
  1553. /// Matches expressions that introduce cleanups to be run at the end
  1554. /// of the sub-expression's evaluation.
  1555. ///
  1556. /// Example matches std::string()
  1557. /// \code
  1558. /// const std::string str = std::string();
  1559. /// \endcode
  1560. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
  1561. exprWithCleanups;
  1562. /// Matches init list expressions.
  1563. ///
  1564. /// Given
  1565. /// \code
  1566. /// int a[] = { 1, 2 };
  1567. /// struct B { int x, y; };
  1568. /// B b = { 5, 6 };
  1569. /// \endcode
  1570. /// initListExpr()
  1571. /// matches "{ 1, 2 }" and "{ 5, 6 }"
  1572. extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
  1573. initListExpr;
  1574. /// Matches the syntactic form of init list expressions
  1575. /// (if expression have it).
  1576. AST_MATCHER_P(InitListExpr, hasSyntacticForm,
  1577. internal::Matcher<Expr>, InnerMatcher) {
  1578. const Expr *SyntForm = Node.getSyntacticForm();
  1579. return (SyntForm != nullptr &&
  1580. InnerMatcher.matches(*SyntForm, Finder, Builder));
  1581. }
  1582. /// Matches C++ initializer list expressions.
  1583. ///
  1584. /// Given
  1585. /// \code
  1586. /// std::vector<int> a({ 1, 2, 3 });
  1587. /// std::vector<int> b = { 4, 5 };
  1588. /// int c[] = { 6, 7 };
  1589. /// std::pair<int, int> d = { 8, 9 };
  1590. /// \endcode
  1591. /// cxxStdInitializerListExpr()
  1592. /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
  1593. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1594. CXXStdInitializerListExpr>
  1595. cxxStdInitializerListExpr;
  1596. /// Matches implicit initializers of init list expressions.
  1597. ///
  1598. /// Given
  1599. /// \code
  1600. /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
  1601. /// \endcode
  1602. /// implicitValueInitExpr()
  1603. /// matches "[0].y" (implicitly)
  1604. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
  1605. implicitValueInitExpr;
  1606. /// Matches paren list expressions.
  1607. /// ParenListExprs don't have a predefined type and are used for late parsing.
  1608. /// In the final AST, they can be met in template declarations.
  1609. ///
  1610. /// Given
  1611. /// \code
  1612. /// template<typename T> class X {
  1613. /// void f() {
  1614. /// X x(*this);
  1615. /// int a = 0, b = 1; int i = (a, b);
  1616. /// }
  1617. /// };
  1618. /// \endcode
  1619. /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
  1620. /// has a predefined type and is a ParenExpr, not a ParenListExpr.
  1621. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
  1622. parenListExpr;
  1623. /// Matches substitutions of non-type template parameters.
  1624. ///
  1625. /// Given
  1626. /// \code
  1627. /// template <int N>
  1628. /// struct A { static const int n = N; };
  1629. /// struct B : public A<42> {};
  1630. /// \endcode
  1631. /// substNonTypeTemplateParmExpr()
  1632. /// matches "N" in the right-hand side of "static const int n = N;"
  1633. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1634. SubstNonTypeTemplateParmExpr>
  1635. substNonTypeTemplateParmExpr;
  1636. /// Matches using declarations.
  1637. ///
  1638. /// Given
  1639. /// \code
  1640. /// namespace X { int x; }
  1641. /// using X::x;
  1642. /// \endcode
  1643. /// usingDecl()
  1644. /// matches \code using X::x \endcode
  1645. extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
  1646. /// Matches using-enum declarations.
  1647. ///
  1648. /// Given
  1649. /// \code
  1650. /// namespace X { enum x {...}; }
  1651. /// using enum X::x;
  1652. /// \endcode
  1653. /// usingEnumDecl()
  1654. /// matches \code using enum X::x \endcode
  1655. extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
  1656. usingEnumDecl;
  1657. /// Matches using namespace declarations.
  1658. ///
  1659. /// Given
  1660. /// \code
  1661. /// namespace X { int x; }
  1662. /// using namespace X;
  1663. /// \endcode
  1664. /// usingDirectiveDecl()
  1665. /// matches \code using namespace X \endcode
  1666. extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
  1667. usingDirectiveDecl;
  1668. /// Matches reference to a name that can be looked up during parsing
  1669. /// but could not be resolved to a specific declaration.
  1670. ///
  1671. /// Given
  1672. /// \code
  1673. /// template<typename T>
  1674. /// T foo() { T a; return a; }
  1675. /// template<typename T>
  1676. /// void bar() {
  1677. /// foo<T>();
  1678. /// }
  1679. /// \endcode
  1680. /// unresolvedLookupExpr()
  1681. /// matches \code foo<T>() \endcode
  1682. extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
  1683. unresolvedLookupExpr;
  1684. /// Matches unresolved using value declarations.
  1685. ///
  1686. /// Given
  1687. /// \code
  1688. /// template<typename X>
  1689. /// class C : private X {
  1690. /// using X::x;
  1691. /// };
  1692. /// \endcode
  1693. /// unresolvedUsingValueDecl()
  1694. /// matches \code using X::x \endcode
  1695. extern const internal::VariadicDynCastAllOfMatcher<Decl,
  1696. UnresolvedUsingValueDecl>
  1697. unresolvedUsingValueDecl;
  1698. /// Matches unresolved using value declarations that involve the
  1699. /// typename.
  1700. ///
  1701. /// Given
  1702. /// \code
  1703. /// template <typename T>
  1704. /// struct Base { typedef T Foo; };
  1705. ///
  1706. /// template<typename T>
  1707. /// struct S : private Base<T> {
  1708. /// using typename Base<T>::Foo;
  1709. /// };
  1710. /// \endcode
  1711. /// unresolvedUsingTypenameDecl()
  1712. /// matches \code using Base<T>::Foo \endcode
  1713. extern const internal::VariadicDynCastAllOfMatcher<Decl,
  1714. UnresolvedUsingTypenameDecl>
  1715. unresolvedUsingTypenameDecl;
  1716. /// Matches a constant expression wrapper.
  1717. ///
  1718. /// Example matches the constant in the case statement:
  1719. /// (matcher = constantExpr())
  1720. /// \code
  1721. /// switch (a) {
  1722. /// case 37: break;
  1723. /// }
  1724. /// \endcode
  1725. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
  1726. constantExpr;
  1727. /// Matches parentheses used in expressions.
  1728. ///
  1729. /// Example matches (foo() + 1)
  1730. /// \code
  1731. /// int foo() { return 1; }
  1732. /// int a = (foo() + 1);
  1733. /// \endcode
  1734. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
  1735. /// Matches constructor call expressions (including implicit ones).
  1736. ///
  1737. /// Example matches string(ptr, n) and ptr within arguments of f
  1738. /// (matcher = cxxConstructExpr())
  1739. /// \code
  1740. /// void f(const string &a, const string &b);
  1741. /// char *ptr;
  1742. /// int n;
  1743. /// f(string(ptr, n), ptr);
  1744. /// \endcode
  1745. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
  1746. cxxConstructExpr;
  1747. /// Matches unresolved constructor call expressions.
  1748. ///
  1749. /// Example matches T(t) in return statement of f
  1750. /// (matcher = cxxUnresolvedConstructExpr())
  1751. /// \code
  1752. /// template <typename T>
  1753. /// void f(const T& t) { return T(t); }
  1754. /// \endcode
  1755. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1756. CXXUnresolvedConstructExpr>
  1757. cxxUnresolvedConstructExpr;
  1758. /// Matches implicit and explicit this expressions.
  1759. ///
  1760. /// Example matches the implicit this expression in "return i".
  1761. /// (matcher = cxxThisExpr())
  1762. /// \code
  1763. /// struct foo {
  1764. /// int i;
  1765. /// int f() { return i; }
  1766. /// };
  1767. /// \endcode
  1768. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
  1769. cxxThisExpr;
  1770. /// Matches nodes where temporaries are created.
  1771. ///
  1772. /// Example matches FunctionTakesString(GetStringByValue())
  1773. /// (matcher = cxxBindTemporaryExpr())
  1774. /// \code
  1775. /// FunctionTakesString(GetStringByValue());
  1776. /// FunctionTakesStringByPointer(GetStringPointer());
  1777. /// \endcode
  1778. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
  1779. cxxBindTemporaryExpr;
  1780. /// Matches nodes where temporaries are materialized.
  1781. ///
  1782. /// Example: Given
  1783. /// \code
  1784. /// struct T {void func();};
  1785. /// T f();
  1786. /// void g(T);
  1787. /// \endcode
  1788. /// materializeTemporaryExpr() matches 'f()' in these statements
  1789. /// \code
  1790. /// T u(f());
  1791. /// g(f());
  1792. /// f().func();
  1793. /// \endcode
  1794. /// but does not match
  1795. /// \code
  1796. /// f();
  1797. /// \endcode
  1798. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1799. MaterializeTemporaryExpr>
  1800. materializeTemporaryExpr;
  1801. /// Matches new expressions.
  1802. ///
  1803. /// Given
  1804. /// \code
  1805. /// new X;
  1806. /// \endcode
  1807. /// cxxNewExpr()
  1808. /// matches 'new X'.
  1809. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
  1810. /// Matches delete expressions.
  1811. ///
  1812. /// Given
  1813. /// \code
  1814. /// delete X;
  1815. /// \endcode
  1816. /// cxxDeleteExpr()
  1817. /// matches 'delete X'.
  1818. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
  1819. cxxDeleteExpr;
  1820. /// Matches noexcept expressions.
  1821. ///
  1822. /// Given
  1823. /// \code
  1824. /// bool a() noexcept;
  1825. /// bool b() noexcept(true);
  1826. /// bool c() noexcept(false);
  1827. /// bool d() noexcept(noexcept(a()));
  1828. /// bool e = noexcept(b()) || noexcept(c());
  1829. /// \endcode
  1830. /// cxxNoexceptExpr()
  1831. /// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
  1832. /// doesn't match the noexcept specifier in the declarations a, b, c or d.
  1833. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
  1834. cxxNoexceptExpr;
  1835. /// Matches array subscript expressions.
  1836. ///
  1837. /// Given
  1838. /// \code
  1839. /// int i = a[1];
  1840. /// \endcode
  1841. /// arraySubscriptExpr()
  1842. /// matches "a[1]"
  1843. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
  1844. arraySubscriptExpr;
  1845. /// Matches the value of a default argument at the call site.
  1846. ///
  1847. /// Example matches the CXXDefaultArgExpr placeholder inserted for the
  1848. /// default value of the second parameter in the call expression f(42)
  1849. /// (matcher = cxxDefaultArgExpr())
  1850. /// \code
  1851. /// void f(int x, int y = 0);
  1852. /// f(42);
  1853. /// \endcode
  1854. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
  1855. cxxDefaultArgExpr;
  1856. /// Matches overloaded operator calls.
  1857. ///
  1858. /// Note that if an operator isn't overloaded, it won't match. Instead, use
  1859. /// binaryOperator matcher.
  1860. /// Currently it does not match operators such as new delete.
  1861. /// FIXME: figure out why these do not match?
  1862. ///
  1863. /// Example matches both operator<<((o << b), c) and operator<<(o, b)
  1864. /// (matcher = cxxOperatorCallExpr())
  1865. /// \code
  1866. /// ostream &operator<< (ostream &out, int i) { };
  1867. /// ostream &o; int b = 1, c = 1;
  1868. /// o << b << c;
  1869. /// \endcode
  1870. /// See also the binaryOperation() matcher for more-general matching of binary
  1871. /// uses of this AST node.
  1872. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
  1873. cxxOperatorCallExpr;
  1874. /// Matches rewritten binary operators
  1875. ///
  1876. /// Example matches use of "<":
  1877. /// \code
  1878. /// #include <compare>
  1879. /// struct HasSpaceshipMem {
  1880. /// int a;
  1881. /// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
  1882. /// };
  1883. /// void compare() {
  1884. /// HasSpaceshipMem hs1, hs2;
  1885. /// if (hs1 < hs2)
  1886. /// return;
  1887. /// }
  1888. /// \endcode
  1889. /// See also the binaryOperation() matcher for more-general matching
  1890. /// of this AST node.
  1891. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  1892. CXXRewrittenBinaryOperator>
  1893. cxxRewrittenBinaryOperator;
  1894. /// Matches expressions.
  1895. ///
  1896. /// Example matches x()
  1897. /// \code
  1898. /// void f() { x(); }
  1899. /// \endcode
  1900. extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
  1901. /// Matches expressions that refer to declarations.
  1902. ///
  1903. /// Example matches x in if (x)
  1904. /// \code
  1905. /// bool x;
  1906. /// if (x) {}
  1907. /// \endcode
  1908. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
  1909. declRefExpr;
  1910. /// Matches a reference to an ObjCIvar.
  1911. ///
  1912. /// Example: matches "a" in "init" method:
  1913. /// \code
  1914. /// @implementation A {
  1915. /// NSString *a;
  1916. /// }
  1917. /// - (void) init {
  1918. /// a = @"hello";
  1919. /// }
  1920. /// \endcode
  1921. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
  1922. objcIvarRefExpr;
  1923. /// Matches a reference to a block.
  1924. ///
  1925. /// Example: matches "^{}":
  1926. /// \code
  1927. /// void f() { ^{}(); }
  1928. /// \endcode
  1929. extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
  1930. /// Matches if statements.
  1931. ///
  1932. /// Example matches 'if (x) {}'
  1933. /// \code
  1934. /// if (x) {}
  1935. /// \endcode
  1936. extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
  1937. /// Matches for statements.
  1938. ///
  1939. /// Example matches 'for (;;) {}'
  1940. /// \code
  1941. /// for (;;) {}
  1942. /// int i[] = {1, 2, 3}; for (auto a : i);
  1943. /// \endcode
  1944. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
  1945. /// Matches the increment statement of a for loop.
  1946. ///
  1947. /// Example:
  1948. /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
  1949. /// matches '++x' in
  1950. /// \code
  1951. /// for (x; x < N; ++x) { }
  1952. /// \endcode
  1953. AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
  1954. InnerMatcher) {
  1955. const Stmt *const Increment = Node.getInc();
  1956. return (Increment != nullptr &&
  1957. InnerMatcher.matches(*Increment, Finder, Builder));
  1958. }
  1959. /// Matches the initialization statement of a for loop.
  1960. ///
  1961. /// Example:
  1962. /// forStmt(hasLoopInit(declStmt()))
  1963. /// matches 'int x = 0' in
  1964. /// \code
  1965. /// for (int x = 0; x < N; ++x) { }
  1966. /// \endcode
  1967. AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
  1968. InnerMatcher) {
  1969. const Stmt *const Init = Node.getInit();
  1970. return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
  1971. }
  1972. /// Matches range-based for statements.
  1973. ///
  1974. /// cxxForRangeStmt() matches 'for (auto a : i)'
  1975. /// \code
  1976. /// int i[] = {1, 2, 3}; for (auto a : i);
  1977. /// for(int j = 0; j < 5; ++j);
  1978. /// \endcode
  1979. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
  1980. cxxForRangeStmt;
  1981. /// Matches the initialization statement of a for loop.
  1982. ///
  1983. /// Example:
  1984. /// forStmt(hasLoopVariable(anything()))
  1985. /// matches 'int x' in
  1986. /// \code
  1987. /// for (int x : a) { }
  1988. /// \endcode
  1989. AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
  1990. InnerMatcher) {
  1991. const VarDecl *const Var = Node.getLoopVariable();
  1992. return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
  1993. }
  1994. /// Matches the range initialization statement of a for loop.
  1995. ///
  1996. /// Example:
  1997. /// forStmt(hasRangeInit(anything()))
  1998. /// matches 'a' in
  1999. /// \code
  2000. /// for (int x : a) { }
  2001. /// \endcode
  2002. AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
  2003. InnerMatcher) {
  2004. const Expr *const Init = Node.getRangeInit();
  2005. return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
  2006. }
  2007. /// Matches while statements.
  2008. ///
  2009. /// Given
  2010. /// \code
  2011. /// while (true) {}
  2012. /// \endcode
  2013. /// whileStmt()
  2014. /// matches 'while (true) {}'.
  2015. extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
  2016. /// Matches do statements.
  2017. ///
  2018. /// Given
  2019. /// \code
  2020. /// do {} while (true);
  2021. /// \endcode
  2022. /// doStmt()
  2023. /// matches 'do {} while(true)'
  2024. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
  2025. /// Matches break statements.
  2026. ///
  2027. /// Given
  2028. /// \code
  2029. /// while (true) { break; }
  2030. /// \endcode
  2031. /// breakStmt()
  2032. /// matches 'break'
  2033. extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
  2034. /// Matches continue statements.
  2035. ///
  2036. /// Given
  2037. /// \code
  2038. /// while (true) { continue; }
  2039. /// \endcode
  2040. /// continueStmt()
  2041. /// matches 'continue'
  2042. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
  2043. continueStmt;
  2044. /// Matches co_return statements.
  2045. ///
  2046. /// Given
  2047. /// \code
  2048. /// while (true) { co_return; }
  2049. /// \endcode
  2050. /// coreturnStmt()
  2051. /// matches 'co_return'
  2052. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
  2053. coreturnStmt;
  2054. /// Matches return statements.
  2055. ///
  2056. /// Given
  2057. /// \code
  2058. /// return 1;
  2059. /// \endcode
  2060. /// returnStmt()
  2061. /// matches 'return 1'
  2062. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
  2063. /// Matches goto statements.
  2064. ///
  2065. /// Given
  2066. /// \code
  2067. /// goto FOO;
  2068. /// FOO: bar();
  2069. /// \endcode
  2070. /// gotoStmt()
  2071. /// matches 'goto FOO'
  2072. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
  2073. /// Matches label statements.
  2074. ///
  2075. /// Given
  2076. /// \code
  2077. /// goto FOO;
  2078. /// FOO: bar();
  2079. /// \endcode
  2080. /// labelStmt()
  2081. /// matches 'FOO:'
  2082. extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
  2083. /// Matches address of label statements (GNU extension).
  2084. ///
  2085. /// Given
  2086. /// \code
  2087. /// FOO: bar();
  2088. /// void *ptr = &&FOO;
  2089. /// goto *bar;
  2090. /// \endcode
  2091. /// addrLabelExpr()
  2092. /// matches '&&FOO'
  2093. extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
  2094. addrLabelExpr;
  2095. /// Matches switch statements.
  2096. ///
  2097. /// Given
  2098. /// \code
  2099. /// switch(a) { case 42: break; default: break; }
  2100. /// \endcode
  2101. /// switchStmt()
  2102. /// matches 'switch(a)'.
  2103. extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
  2104. /// Matches case and default statements inside switch statements.
  2105. ///
  2106. /// Given
  2107. /// \code
  2108. /// switch(a) { case 42: break; default: break; }
  2109. /// \endcode
  2110. /// switchCase()
  2111. /// matches 'case 42:' and 'default:'.
  2112. extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
  2113. /// Matches case statements inside switch statements.
  2114. ///
  2115. /// Given
  2116. /// \code
  2117. /// switch(a) { case 42: break; default: break; }
  2118. /// \endcode
  2119. /// caseStmt()
  2120. /// matches 'case 42:'.
  2121. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
  2122. /// Matches default statements inside switch statements.
  2123. ///
  2124. /// Given
  2125. /// \code
  2126. /// switch(a) { case 42: break; default: break; }
  2127. /// \endcode
  2128. /// defaultStmt()
  2129. /// matches 'default:'.
  2130. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
  2131. defaultStmt;
  2132. /// Matches compound statements.
  2133. ///
  2134. /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
  2135. /// \code
  2136. /// for (;;) {{}}
  2137. /// \endcode
  2138. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
  2139. compoundStmt;
  2140. /// Matches catch statements.
  2141. ///
  2142. /// \code
  2143. /// try {} catch(int i) {}
  2144. /// \endcode
  2145. /// cxxCatchStmt()
  2146. /// matches 'catch(int i)'
  2147. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
  2148. cxxCatchStmt;
  2149. /// Matches try statements.
  2150. ///
  2151. /// \code
  2152. /// try {} catch(int i) {}
  2153. /// \endcode
  2154. /// cxxTryStmt()
  2155. /// matches 'try {}'
  2156. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
  2157. /// Matches throw expressions.
  2158. ///
  2159. /// \code
  2160. /// try { throw 5; } catch(int i) {}
  2161. /// \endcode
  2162. /// cxxThrowExpr()
  2163. /// matches 'throw 5'
  2164. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
  2165. cxxThrowExpr;
  2166. /// Matches null statements.
  2167. ///
  2168. /// \code
  2169. /// foo();;
  2170. /// \endcode
  2171. /// nullStmt()
  2172. /// matches the second ';'
  2173. extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
  2174. /// Matches asm statements.
  2175. ///
  2176. /// \code
  2177. /// int i = 100;
  2178. /// __asm("mov al, 2");
  2179. /// \endcode
  2180. /// asmStmt()
  2181. /// matches '__asm("mov al, 2")'
  2182. extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
  2183. /// Matches bool literals.
  2184. ///
  2185. /// Example matches true
  2186. /// \code
  2187. /// true
  2188. /// \endcode
  2189. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
  2190. cxxBoolLiteral;
  2191. /// Matches string literals (also matches wide string literals).
  2192. ///
  2193. /// Example matches "abcd", L"abcd"
  2194. /// \code
  2195. /// char *s = "abcd";
  2196. /// wchar_t *ws = L"abcd";
  2197. /// \endcode
  2198. extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
  2199. stringLiteral;
  2200. /// Matches character literals (also matches wchar_t).
  2201. ///
  2202. /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
  2203. /// though.
  2204. ///
  2205. /// Example matches 'a', L'a'
  2206. /// \code
  2207. /// char ch = 'a';
  2208. /// wchar_t chw = L'a';
  2209. /// \endcode
  2210. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
  2211. characterLiteral;
  2212. /// Matches integer literals of all sizes / encodings, e.g.
  2213. /// 1, 1L, 0x1 and 1U.
  2214. ///
  2215. /// Does not match character-encoded integers such as L'a'.
  2216. extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
  2217. integerLiteral;
  2218. /// Matches float literals of all sizes / encodings, e.g.
  2219. /// 1.0, 1.0f, 1.0L and 1e10.
  2220. ///
  2221. /// Does not match implicit conversions such as
  2222. /// \code
  2223. /// float a = 10;
  2224. /// \endcode
  2225. extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
  2226. floatLiteral;
  2227. /// Matches imaginary literals, which are based on integer and floating
  2228. /// point literals e.g.: 1i, 1.0i
  2229. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
  2230. imaginaryLiteral;
  2231. /// Matches fixed point literals
  2232. extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
  2233. fixedPointLiteral;
  2234. /// Matches user defined literal operator call.
  2235. ///
  2236. /// Example match: "foo"_suffix
  2237. extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
  2238. userDefinedLiteral;
  2239. /// Matches compound (i.e. non-scalar) literals
  2240. ///
  2241. /// Example match: {1}, (1, 2)
  2242. /// \code
  2243. /// int array[4] = {1};
  2244. /// vector int myvec = (vector int)(1, 2);
  2245. /// \endcode
  2246. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
  2247. compoundLiteralExpr;
  2248. /// Matches co_await expressions.
  2249. ///
  2250. /// Given
  2251. /// \code
  2252. /// co_await 1;
  2253. /// \endcode
  2254. /// coawaitExpr()
  2255. /// matches 'co_await 1'
  2256. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
  2257. coawaitExpr;
  2258. /// Matches co_await expressions where the type of the promise is dependent
  2259. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
  2260. dependentCoawaitExpr;
  2261. /// Matches co_yield expressions.
  2262. ///
  2263. /// Given
  2264. /// \code
  2265. /// co_yield 1;
  2266. /// \endcode
  2267. /// coyieldExpr()
  2268. /// matches 'co_yield 1'
  2269. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
  2270. coyieldExpr;
  2271. /// Matches nullptr literal.
  2272. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
  2273. cxxNullPtrLiteralExpr;
  2274. /// Matches GNU __builtin_choose_expr.
  2275. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
  2276. chooseExpr;
  2277. /// Matches GNU __null expression.
  2278. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
  2279. gnuNullExpr;
  2280. /// Matches C11 _Generic expression.
  2281. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
  2282. genericSelectionExpr;
  2283. /// Matches atomic builtins.
  2284. /// Example matches __atomic_load_n(ptr, 1)
  2285. /// \code
  2286. /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
  2287. /// \endcode
  2288. extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
  2289. /// Matches statement expression (GNU extension).
  2290. ///
  2291. /// Example match: ({ int X = 4; X; })
  2292. /// \code
  2293. /// int C = ({ int X = 4; X; });
  2294. /// \endcode
  2295. extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
  2296. /// Matches binary operator expressions.
  2297. ///
  2298. /// Example matches a || b
  2299. /// \code
  2300. /// !(a || b)
  2301. /// \endcode
  2302. /// See also the binaryOperation() matcher for more-general matching.
  2303. extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
  2304. binaryOperator;
  2305. /// Matches unary operator expressions.
  2306. ///
  2307. /// Example matches !a
  2308. /// \code
  2309. /// !a || b
  2310. /// \endcode
  2311. extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
  2312. unaryOperator;
  2313. /// Matches conditional operator expressions.
  2314. ///
  2315. /// Example matches a ? b : c
  2316. /// \code
  2317. /// (a ? b : c) + 42
  2318. /// \endcode
  2319. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
  2320. conditionalOperator;
  2321. /// Matches binary conditional operator expressions (GNU extension).
  2322. ///
  2323. /// Example matches a ?: b
  2324. /// \code
  2325. /// (a ?: b) + 42;
  2326. /// \endcode
  2327. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  2328. BinaryConditionalOperator>
  2329. binaryConditionalOperator;
  2330. /// Matches opaque value expressions. They are used as helpers
  2331. /// to reference another expressions and can be met
  2332. /// in BinaryConditionalOperators, for example.
  2333. ///
  2334. /// Example matches 'a'
  2335. /// \code
  2336. /// (a ?: c) + 42;
  2337. /// \endcode
  2338. extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
  2339. opaqueValueExpr;
  2340. /// Matches a C++ static_assert declaration.
  2341. ///
  2342. /// Example:
  2343. /// staticAssertDecl()
  2344. /// matches
  2345. /// static_assert(sizeof(S) == sizeof(int))
  2346. /// in
  2347. /// \code
  2348. /// struct S {
  2349. /// int x;
  2350. /// };
  2351. /// static_assert(sizeof(S) == sizeof(int));
  2352. /// \endcode
  2353. extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
  2354. staticAssertDecl;
  2355. /// Matches a reinterpret_cast expression.
  2356. ///
  2357. /// Either the source expression or the destination type can be matched
  2358. /// using has(), but hasDestinationType() is more specific and can be
  2359. /// more readable.
  2360. ///
  2361. /// Example matches reinterpret_cast<char*>(&p) in
  2362. /// \code
  2363. /// void* p = reinterpret_cast<char*>(&p);
  2364. /// \endcode
  2365. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
  2366. cxxReinterpretCastExpr;
  2367. /// Matches a C++ static_cast expression.
  2368. ///
  2369. /// \see hasDestinationType
  2370. /// \see reinterpretCast
  2371. ///
  2372. /// Example:
  2373. /// cxxStaticCastExpr()
  2374. /// matches
  2375. /// static_cast<long>(8)
  2376. /// in
  2377. /// \code
  2378. /// long eight(static_cast<long>(8));
  2379. /// \endcode
  2380. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
  2381. cxxStaticCastExpr;
  2382. /// Matches a dynamic_cast expression.
  2383. ///
  2384. /// Example:
  2385. /// cxxDynamicCastExpr()
  2386. /// matches
  2387. /// dynamic_cast<D*>(&b);
  2388. /// in
  2389. /// \code
  2390. /// struct B { virtual ~B() {} }; struct D : B {};
  2391. /// B b;
  2392. /// D* p = dynamic_cast<D*>(&b);
  2393. /// \endcode
  2394. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
  2395. cxxDynamicCastExpr;
  2396. /// Matches a const_cast expression.
  2397. ///
  2398. /// Example: Matches const_cast<int*>(&r) in
  2399. /// \code
  2400. /// int n = 42;
  2401. /// const int &r(n);
  2402. /// int* p = const_cast<int*>(&r);
  2403. /// \endcode
  2404. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
  2405. cxxConstCastExpr;
  2406. /// Matches a C-style cast expression.
  2407. ///
  2408. /// Example: Matches (int) 2.2f in
  2409. /// \code
  2410. /// int i = (int) 2.2f;
  2411. /// \endcode
  2412. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
  2413. cStyleCastExpr;
  2414. /// Matches explicit cast expressions.
  2415. ///
  2416. /// Matches any cast expression written in user code, whether it be a
  2417. /// C-style cast, a functional-style cast, or a keyword cast.
  2418. ///
  2419. /// Does not match implicit conversions.
  2420. ///
  2421. /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
  2422. /// Clang uses the term "cast" to apply to implicit conversions as well as to
  2423. /// actual cast expressions.
  2424. ///
  2425. /// \see hasDestinationType.
  2426. ///
  2427. /// Example: matches all five of the casts in
  2428. /// \code
  2429. /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
  2430. /// \endcode
  2431. /// but does not match the implicit conversion in
  2432. /// \code
  2433. /// long ell = 42;
  2434. /// \endcode
  2435. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
  2436. explicitCastExpr;
  2437. /// Matches the implicit cast nodes of Clang's AST.
  2438. ///
  2439. /// This matches many different places, including function call return value
  2440. /// eliding, as well as any type conversions.
  2441. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
  2442. implicitCastExpr;
  2443. /// Matches any cast nodes of Clang's AST.
  2444. ///
  2445. /// Example: castExpr() matches each of the following:
  2446. /// \code
  2447. /// (int) 3;
  2448. /// const_cast<Expr *>(SubExpr);
  2449. /// char c = 0;
  2450. /// \endcode
  2451. /// but does not match
  2452. /// \code
  2453. /// int i = (0);
  2454. /// int k = 0;
  2455. /// \endcode
  2456. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
  2457. /// Matches functional cast expressions
  2458. ///
  2459. /// Example: Matches Foo(bar);
  2460. /// \code
  2461. /// Foo f = bar;
  2462. /// Foo g = (Foo) bar;
  2463. /// Foo h = Foo(bar);
  2464. /// \endcode
  2465. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
  2466. cxxFunctionalCastExpr;
  2467. /// Matches functional cast expressions having N != 1 arguments
  2468. ///
  2469. /// Example: Matches Foo(bar, bar)
  2470. /// \code
  2471. /// Foo h = Foo(bar, bar);
  2472. /// \endcode
  2473. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
  2474. cxxTemporaryObjectExpr;
  2475. /// Matches predefined identifier expressions [C99 6.4.2.2].
  2476. ///
  2477. /// Example: Matches __func__
  2478. /// \code
  2479. /// printf("%s", __func__);
  2480. /// \endcode
  2481. extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
  2482. predefinedExpr;
  2483. /// Matches C99 designated initializer expressions [C99 6.7.8].
  2484. ///
  2485. /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
  2486. /// \code
  2487. /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
  2488. /// \endcode
  2489. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
  2490. designatedInitExpr;
  2491. /// Matches designated initializer expressions that contain
  2492. /// a specific number of designators.
  2493. ///
  2494. /// Example: Given
  2495. /// \code
  2496. /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
  2497. /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
  2498. /// \endcode
  2499. /// designatorCountIs(2)
  2500. /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
  2501. /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
  2502. AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
  2503. return Node.size() == N;
  2504. }
  2505. /// Matches \c QualTypes in the clang AST.
  2506. extern const internal::VariadicAllOfMatcher<QualType> qualType;
  2507. /// Matches \c Types in the clang AST.
  2508. extern const internal::VariadicAllOfMatcher<Type> type;
  2509. /// Matches \c TypeLocs in the clang AST.
  2510. extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
  2511. /// Matches if any of the given matchers matches.
  2512. ///
  2513. /// Unlike \c anyOf, \c eachOf will generate a match result for each
  2514. /// matching submatcher.
  2515. ///
  2516. /// For example, in:
  2517. /// \code
  2518. /// class A { int a; int b; };
  2519. /// \endcode
  2520. /// The matcher:
  2521. /// \code
  2522. /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
  2523. /// has(fieldDecl(hasName("b")).bind("v"))))
  2524. /// \endcode
  2525. /// will generate two results binding "v", the first of which binds
  2526. /// the field declaration of \c a, the second the field declaration of
  2527. /// \c b.
  2528. ///
  2529. /// Usable as: Any Matcher
  2530. extern const internal::VariadicOperatorMatcherFunc<
  2531. 2, std::numeric_limits<unsigned>::max()>
  2532. eachOf;
  2533. /// Matches if any of the given matchers matches.
  2534. ///
  2535. /// Usable as: Any Matcher
  2536. extern const internal::VariadicOperatorMatcherFunc<
  2537. 2, std::numeric_limits<unsigned>::max()>
  2538. anyOf;
  2539. /// Matches if all given matchers match.
  2540. ///
  2541. /// Usable as: Any Matcher
  2542. extern const internal::VariadicOperatorMatcherFunc<
  2543. 2, std::numeric_limits<unsigned>::max()>
  2544. allOf;
  2545. /// Matches any node regardless of the submatcher.
  2546. ///
  2547. /// However, \c optionally will retain any bindings generated by the submatcher.
  2548. /// Useful when additional information which may or may not present about a main
  2549. /// matching node is desired.
  2550. ///
  2551. /// For example, in:
  2552. /// \code
  2553. /// class Foo {
  2554. /// int bar;
  2555. /// }
  2556. /// \endcode
  2557. /// The matcher:
  2558. /// \code
  2559. /// cxxRecordDecl(
  2560. /// optionally(has(
  2561. /// fieldDecl(hasName("bar")).bind("var")
  2562. /// ))).bind("record")
  2563. /// \endcode
  2564. /// will produce a result binding for both "record" and "var".
  2565. /// The matcher will produce a "record" binding for even if there is no data
  2566. /// member named "bar" in that class.
  2567. ///
  2568. /// Usable as: Any Matcher
  2569. extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
  2570. /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
  2571. ///
  2572. /// Given
  2573. /// \code
  2574. /// Foo x = bar;
  2575. /// int y = sizeof(x) + alignof(x);
  2576. /// \endcode
  2577. /// unaryExprOrTypeTraitExpr()
  2578. /// matches \c sizeof(x) and \c alignof(x)
  2579. extern const internal::VariadicDynCastAllOfMatcher<Stmt,
  2580. UnaryExprOrTypeTraitExpr>
  2581. unaryExprOrTypeTraitExpr;
  2582. /// Matches any of the \p NodeMatchers with InnerMatchers nested within
  2583. ///
  2584. /// Given
  2585. /// \code
  2586. /// if (true);
  2587. /// for (; true; );
  2588. /// \endcode
  2589. /// with the matcher
  2590. /// \code
  2591. /// mapAnyOf(ifStmt, forStmt).with(
  2592. /// hasCondition(cxxBoolLiteralExpr(equals(true)))
  2593. /// ).bind("trueCond")
  2594. /// \endcode
  2595. /// matches the \c if and the \c for. It is equivalent to:
  2596. /// \code
  2597. /// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
  2598. /// anyOf(
  2599. /// ifStmt(trueCond).bind("trueCond"),
  2600. /// forStmt(trueCond).bind("trueCond")
  2601. /// );
  2602. /// \endcode
  2603. ///
  2604. /// The with() chain-call accepts zero or more matchers which are combined
  2605. /// as-if with allOf() in each of the node matchers.
  2606. /// Usable as: Any Matcher
  2607. template <typename T, typename... U>
  2608. auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
  2609. return internal::MapAnyOfHelper<U...>();
  2610. }
  2611. /// Matches nodes which can be used with binary operators.
  2612. ///
  2613. /// The code
  2614. /// \code
  2615. /// var1 != var2;
  2616. /// \endcode
  2617. /// might be represented in the clang AST as a binaryOperator, a
  2618. /// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
  2619. ///
  2620. /// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
  2621. /// least one is a class type (cxxOperatorCallExpr)
  2622. /// * whether the code appears in a template declaration, if at least one of the
  2623. /// vars is a dependent-type (binaryOperator)
  2624. /// * whether the code relies on a rewritten binary operator, such as a
  2625. /// spaceship operator or an inverted equality operator
  2626. /// (cxxRewrittenBinaryOperator)
  2627. ///
  2628. /// This matcher elides details in places where the matchers for the nodes are
  2629. /// compatible.
  2630. ///
  2631. /// Given
  2632. /// \code
  2633. /// binaryOperation(
  2634. /// hasOperatorName("!="),
  2635. /// hasLHS(expr().bind("lhs")),
  2636. /// hasRHS(expr().bind("rhs"))
  2637. /// )
  2638. /// \endcode
  2639. /// matches each use of "!=" in:
  2640. /// \code
  2641. /// struct S{
  2642. /// bool operator!=(const S&) const;
  2643. /// };
  2644. ///
  2645. /// void foo()
  2646. /// {
  2647. /// 1 != 2;
  2648. /// S() != S();
  2649. /// }
  2650. ///
  2651. /// template<typename T>
  2652. /// void templ()
  2653. /// {
  2654. /// 1 != 2;
  2655. /// T() != S();
  2656. /// }
  2657. /// struct HasOpEq
  2658. /// {
  2659. /// bool operator==(const HasOpEq &) const;
  2660. /// };
  2661. ///
  2662. /// void inverse()
  2663. /// {
  2664. /// HasOpEq s1;
  2665. /// HasOpEq s2;
  2666. /// if (s1 != s2)
  2667. /// return;
  2668. /// }
  2669. ///
  2670. /// struct HasSpaceship
  2671. /// {
  2672. /// bool operator<=>(const HasOpEq &) const;
  2673. /// };
  2674. ///
  2675. /// void use_spaceship()
  2676. /// {
  2677. /// HasSpaceship s1;
  2678. /// HasSpaceship s2;
  2679. /// if (s1 != s2)
  2680. /// return;
  2681. /// }
  2682. /// \endcode
  2683. extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
  2684. CXXRewrittenBinaryOperator>
  2685. binaryOperation;
  2686. /// Matches function calls and constructor calls
  2687. ///
  2688. /// Because CallExpr and CXXConstructExpr do not share a common
  2689. /// base class with API accessing arguments etc, AST Matchers for code
  2690. /// which should match both are typically duplicated. This matcher
  2691. /// removes the need for duplication.
  2692. ///
  2693. /// Given code
  2694. /// \code
  2695. /// struct ConstructorTakesInt
  2696. /// {
  2697. /// ConstructorTakesInt(int i) {}
  2698. /// };
  2699. ///
  2700. /// void callTakesInt(int i)
  2701. /// {
  2702. /// }
  2703. ///
  2704. /// void doCall()
  2705. /// {
  2706. /// callTakesInt(42);
  2707. /// }
  2708. ///
  2709. /// void doConstruct()
  2710. /// {
  2711. /// ConstructorTakesInt cti(42);
  2712. /// }
  2713. /// \endcode
  2714. ///
  2715. /// The matcher
  2716. /// \code
  2717. /// invocation(hasArgument(0, integerLiteral(equals(42))))
  2718. /// \endcode
  2719. /// matches the expression in both doCall and doConstruct
  2720. extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
  2721. /// Matches unary expressions that have a specific type of argument.
  2722. ///
  2723. /// Given
  2724. /// \code
  2725. /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
  2726. /// \endcode
  2727. /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
  2728. /// matches \c sizeof(a) and \c alignof(c)
  2729. AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
  2730. internal::Matcher<QualType>, InnerMatcher) {
  2731. const QualType ArgumentType = Node.getTypeOfArgument();
  2732. return InnerMatcher.matches(ArgumentType, Finder, Builder);
  2733. }
  2734. /// Matches unary expressions of a certain kind.
  2735. ///
  2736. /// Given
  2737. /// \code
  2738. /// int x;
  2739. /// int s = sizeof(x) + alignof(x)
  2740. /// \endcode
  2741. /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
  2742. /// matches \c sizeof(x)
  2743. ///
  2744. /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
  2745. /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
  2746. AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
  2747. return Node.getKind() == Kind;
  2748. }
  2749. /// Same as unaryExprOrTypeTraitExpr, but only matching
  2750. /// alignof.
  2751. inline internal::BindableMatcher<Stmt> alignOfExpr(
  2752. const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
  2753. return stmt(unaryExprOrTypeTraitExpr(
  2754. allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
  2755. InnerMatcher)));
  2756. }
  2757. /// Same as unaryExprOrTypeTraitExpr, but only matching
  2758. /// sizeof.
  2759. inline internal::BindableMatcher<Stmt> sizeOfExpr(
  2760. const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
  2761. return stmt(unaryExprOrTypeTraitExpr(
  2762. allOf(ofKind(UETT_SizeOf), InnerMatcher)));
  2763. }
  2764. /// Matches NamedDecl nodes that have the specified name.
  2765. ///
  2766. /// Supports specifying enclosing namespaces or classes by prefixing the name
  2767. /// with '<enclosing>::'.
  2768. /// Does not match typedefs of an underlying type with the given name.
  2769. ///
  2770. /// Example matches X (Name == "X")
  2771. /// \code
  2772. /// class X;
  2773. /// \endcode
  2774. ///
  2775. /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
  2776. /// \code
  2777. /// namespace a { namespace b { class X; } }
  2778. /// \endcode
  2779. inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
  2780. return internal::Matcher<NamedDecl>(
  2781. new internal::HasNameMatcher({std::string(Name)}));
  2782. }
  2783. /// Matches NamedDecl nodes that have any of the specified names.
  2784. ///
  2785. /// This matcher is only provided as a performance optimization of hasName.
  2786. /// \code
  2787. /// hasAnyName(a, b, c)
  2788. /// \endcode
  2789. /// is equivalent to, but faster than
  2790. /// \code
  2791. /// anyOf(hasName(a), hasName(b), hasName(c))
  2792. /// \endcode
  2793. extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
  2794. internal::hasAnyNameFunc>
  2795. hasAnyName;
  2796. /// Matches NamedDecl nodes whose fully qualified names contain
  2797. /// a substring matched by the given RegExp.
  2798. ///
  2799. /// Supports specifying enclosing namespaces or classes by
  2800. /// prefixing the name with '<enclosing>::'. Does not match typedefs
  2801. /// of an underlying type with the given name.
  2802. ///
  2803. /// Example matches X (regexp == "::X")
  2804. /// \code
  2805. /// class X;
  2806. /// \endcode
  2807. ///
  2808. /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
  2809. /// \code
  2810. /// namespace foo { namespace bar { class X; } }
  2811. /// \endcode
  2812. AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
  2813. std::string FullNameString = "::" + Node.getQualifiedNameAsString();
  2814. return RegExp->match(FullNameString);
  2815. }
  2816. /// Matches overloaded operator names.
  2817. ///
  2818. /// Matches overloaded operator names specified in strings without the
  2819. /// "operator" prefix: e.g. "<<".
  2820. ///
  2821. /// Given:
  2822. /// \code
  2823. /// class A { int operator*(); };
  2824. /// const A &operator<<(const A &a, const A &b);
  2825. /// A a;
  2826. /// a << a; // <-- This matches
  2827. /// \endcode
  2828. ///
  2829. /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
  2830. /// specified line and
  2831. /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
  2832. /// matches the declaration of \c A.
  2833. ///
  2834. /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
  2835. inline internal::PolymorphicMatcher<
  2836. internal::HasOverloadedOperatorNameMatcher,
  2837. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl),
  2838. std::vector<std::string>>
  2839. hasOverloadedOperatorName(StringRef Name) {
  2840. return internal::PolymorphicMatcher<
  2841. internal::HasOverloadedOperatorNameMatcher,
  2842. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl),
  2843. std::vector<std::string>>({std::string(Name)});
  2844. }
  2845. /// Matches overloaded operator names.
  2846. ///
  2847. /// Matches overloaded operator names specified in strings without the
  2848. /// "operator" prefix: e.g. "<<".
  2849. ///
  2850. /// hasAnyOverloadedOperatorName("+", "-")
  2851. /// Is equivalent to
  2852. /// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
  2853. extern const internal::VariadicFunction<
  2854. internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
  2855. AST_POLYMORPHIC_SUPPORTED_TYPES(
  2856. CXXOperatorCallExpr, FunctionDecl),
  2857. std::vector<std::string>>,
  2858. StringRef, internal::hasAnyOverloadedOperatorNameFunc>
  2859. hasAnyOverloadedOperatorName;
  2860. /// Matches template-dependent, but known, member names.
  2861. ///
  2862. /// In template declarations, dependent members are not resolved and so can
  2863. /// not be matched to particular named declarations.
  2864. ///
  2865. /// This matcher allows to match on the known name of members.
  2866. ///
  2867. /// Given
  2868. /// \code
  2869. /// template <typename T>
  2870. /// struct S {
  2871. /// void mem();
  2872. /// };
  2873. /// template <typename T>
  2874. /// void x() {
  2875. /// S<T> s;
  2876. /// s.mem();
  2877. /// }
  2878. /// \endcode
  2879. /// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
  2880. AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
  2881. return Node.getMember().getAsString() == N;
  2882. }
  2883. /// Matches template-dependent, but known, member names against an already-bound
  2884. /// node
  2885. ///
  2886. /// In template declarations, dependent members are not resolved and so can
  2887. /// not be matched to particular named declarations.
  2888. ///
  2889. /// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
  2890. /// and CXXMethodDecl nodes.
  2891. ///
  2892. /// Given
  2893. /// \code
  2894. /// template <typename T>
  2895. /// struct S {
  2896. /// void mem();
  2897. /// };
  2898. /// template <typename T>
  2899. /// void x() {
  2900. /// S<T> s;
  2901. /// s.mem();
  2902. /// }
  2903. /// \endcode
  2904. /// The matcher
  2905. /// @code
  2906. /// \c cxxDependentScopeMemberExpr(
  2907. /// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
  2908. /// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
  2909. /// cxxMethodDecl(hasName("mem")).bind("templMem")
  2910. /// )))))
  2911. /// )))),
  2912. /// memberHasSameNameAsBoundNode("templMem")
  2913. /// )
  2914. /// @endcode
  2915. /// first matches and binds the @c mem member of the @c S template, then
  2916. /// compares its name to the usage in @c s.mem() in the @c x function template
  2917. AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
  2918. std::string, BindingID) {
  2919. auto MemberName = Node.getMember().getAsString();
  2920. return Builder->removeBindings(
  2921. [this, MemberName](const BoundNodesMap &Nodes) {
  2922. const auto &BN = Nodes.getNode(this->BindingID);
  2923. if (const auto *ND = BN.get<NamedDecl>()) {
  2924. if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
  2925. return true;
  2926. return ND->getName() != MemberName;
  2927. }
  2928. return true;
  2929. });
  2930. }
  2931. /// Matches C++ classes that are directly or indirectly derived from a class
  2932. /// matching \c Base, or Objective-C classes that directly or indirectly
  2933. /// subclass a class matching \c Base.
  2934. ///
  2935. /// Note that a class is not considered to be derived from itself.
  2936. ///
  2937. /// Example matches Y, Z, C (Base == hasName("X"))
  2938. /// \code
  2939. /// class X;
  2940. /// class Y : public X {}; // directly derived
  2941. /// class Z : public Y {}; // indirectly derived
  2942. /// typedef X A;
  2943. /// typedef A B;
  2944. /// class C : public B {}; // derived from a typedef of X
  2945. /// \endcode
  2946. ///
  2947. /// In the following example, Bar matches isDerivedFrom(hasName("X")):
  2948. /// \code
  2949. /// class Foo;
  2950. /// typedef Foo X;
  2951. /// class Bar : public Foo {}; // derived from a type that X is a typedef of
  2952. /// \endcode
  2953. ///
  2954. /// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
  2955. /// \code
  2956. /// @interface NSObject @end
  2957. /// @interface Bar : NSObject @end
  2958. /// \endcode
  2959. ///
  2960. /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
  2961. AST_POLYMORPHIC_MATCHER_P(
  2962. isDerivedFrom,
  2963. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
  2964. internal::Matcher<NamedDecl>, Base) {
  2965. // Check if the node is a C++ struct/union/class.
  2966. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
  2967. return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
  2968. // The node must be an Objective-C class.
  2969. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
  2970. return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
  2971. /*Directly=*/false);
  2972. }
  2973. /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
  2974. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  2975. isDerivedFrom,
  2976. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
  2977. std::string, BaseName, 1) {
  2978. if (BaseName.empty())
  2979. return false;
  2980. const auto M = isDerivedFrom(hasName(BaseName));
  2981. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
  2982. return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
  2983. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
  2984. return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
  2985. }
  2986. /// Matches C++ classes that have a direct or indirect base matching \p
  2987. /// BaseSpecMatcher.
  2988. ///
  2989. /// Example:
  2990. /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
  2991. /// \code
  2992. /// class Foo;
  2993. /// class Bar : Foo {};
  2994. /// class Baz : Bar {};
  2995. /// class SpecialBase;
  2996. /// class Proxy : SpecialBase {}; // matches Proxy
  2997. /// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
  2998. /// \endcode
  2999. ///
  3000. // FIXME: Refactor this and isDerivedFrom to reuse implementation.
  3001. AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
  3002. BaseSpecMatcher) {
  3003. return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
  3004. }
  3005. /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
  3006. ///
  3007. /// Example:
  3008. /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
  3009. /// \code
  3010. /// class Foo;
  3011. /// class Bar : Foo {};
  3012. /// class Baz : Bar {};
  3013. /// class SpecialBase;
  3014. /// class Proxy : SpecialBase {}; // matches Proxy
  3015. /// class IndirectlyDerived : Proxy {}; // doesn't match
  3016. /// \endcode
  3017. AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
  3018. BaseSpecMatcher) {
  3019. return Node.hasDefinition() &&
  3020. llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
  3021. return BaseSpecMatcher.matches(Base, Finder, Builder);
  3022. });
  3023. }
  3024. /// Similar to \c isDerivedFrom(), but also matches classes that directly
  3025. /// match \c Base.
  3026. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3027. isSameOrDerivedFrom,
  3028. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
  3029. internal::Matcher<NamedDecl>, Base, 0) {
  3030. const auto M = anyOf(Base, isDerivedFrom(Base));
  3031. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
  3032. return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
  3033. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
  3034. return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
  3035. }
  3036. /// Overloaded method as shortcut for
  3037. /// \c isSameOrDerivedFrom(hasName(...)).
  3038. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3039. isSameOrDerivedFrom,
  3040. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
  3041. std::string, BaseName, 1) {
  3042. if (BaseName.empty())
  3043. return false;
  3044. const auto M = isSameOrDerivedFrom(hasName(BaseName));
  3045. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
  3046. return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
  3047. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
  3048. return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
  3049. }
  3050. /// Matches C++ or Objective-C classes that are directly derived from a class
  3051. /// matching \c Base.
  3052. ///
  3053. /// Note that a class is not considered to be derived from itself.
  3054. ///
  3055. /// Example matches Y, C (Base == hasName("X"))
  3056. /// \code
  3057. /// class X;
  3058. /// class Y : public X {}; // directly derived
  3059. /// class Z : public Y {}; // indirectly derived
  3060. /// typedef X A;
  3061. /// typedef A B;
  3062. /// class C : public B {}; // derived from a typedef of X
  3063. /// \endcode
  3064. ///
  3065. /// In the following example, Bar matches isDerivedFrom(hasName("X")):
  3066. /// \code
  3067. /// class Foo;
  3068. /// typedef Foo X;
  3069. /// class Bar : public Foo {}; // derived from a type that X is a typedef of
  3070. /// \endcode
  3071. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3072. isDirectlyDerivedFrom,
  3073. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
  3074. internal::Matcher<NamedDecl>, Base, 0) {
  3075. // Check if the node is a C++ struct/union/class.
  3076. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
  3077. return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
  3078. // The node must be an Objective-C class.
  3079. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
  3080. return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
  3081. /*Directly=*/true);
  3082. }
  3083. /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
  3084. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3085. isDirectlyDerivedFrom,
  3086. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
  3087. std::string, BaseName, 1) {
  3088. if (BaseName.empty())
  3089. return false;
  3090. const auto M = isDirectlyDerivedFrom(hasName(BaseName));
  3091. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
  3092. return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
  3093. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
  3094. return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
  3095. }
  3096. /// Matches the first method of a class or struct that satisfies \c
  3097. /// InnerMatcher.
  3098. ///
  3099. /// Given:
  3100. /// \code
  3101. /// class A { void func(); };
  3102. /// class B { void member(); };
  3103. /// \endcode
  3104. ///
  3105. /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
  3106. /// \c A but not \c B.
  3107. AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
  3108. InnerMatcher) {
  3109. BoundNodesTreeBuilder Result(*Builder);
  3110. auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
  3111. Node.method_end(), Finder, &Result);
  3112. if (MatchIt == Node.method_end())
  3113. return false;
  3114. if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
  3115. return false;
  3116. *Builder = std::move(Result);
  3117. return true;
  3118. }
  3119. /// Matches the generated class of lambda expressions.
  3120. ///
  3121. /// Given:
  3122. /// \code
  3123. /// auto x = []{};
  3124. /// \endcode
  3125. ///
  3126. /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
  3127. /// \c decltype(x)
  3128. AST_MATCHER(CXXRecordDecl, isLambda) {
  3129. return Node.isLambda();
  3130. }
  3131. /// Matches AST nodes that have child AST nodes that match the
  3132. /// provided matcher.
  3133. ///
  3134. /// Example matches X, Y
  3135. /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
  3136. /// \code
  3137. /// class X {}; // Matches X, because X::X is a class of name X inside X.
  3138. /// class Y { class X {}; };
  3139. /// class Z { class Y { class X {}; }; }; // Does not match Z.
  3140. /// \endcode
  3141. ///
  3142. /// ChildT must be an AST base type.
  3143. ///
  3144. /// Usable as: Any Matcher
  3145. /// Note that has is direct matcher, so it also matches things like implicit
  3146. /// casts and paren casts. If you are matching with expr then you should
  3147. /// probably consider using ignoringParenImpCasts like:
  3148. /// has(ignoringParenImpCasts(expr())).
  3149. extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
  3150. /// Matches AST nodes that have descendant AST nodes that match the
  3151. /// provided matcher.
  3152. ///
  3153. /// Example matches X, Y, Z
  3154. /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
  3155. /// \code
  3156. /// class X {}; // Matches X, because X::X is a class of name X inside X.
  3157. /// class Y { class X {}; };
  3158. /// class Z { class Y { class X {}; }; };
  3159. /// \endcode
  3160. ///
  3161. /// DescendantT must be an AST base type.
  3162. ///
  3163. /// Usable as: Any Matcher
  3164. extern const internal::ArgumentAdaptingMatcherFunc<
  3165. internal::HasDescendantMatcher>
  3166. hasDescendant;
  3167. /// Matches AST nodes that have child AST nodes that match the
  3168. /// provided matcher.
  3169. ///
  3170. /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
  3171. /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
  3172. /// \code
  3173. /// class X {};
  3174. /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
  3175. /// // inside Y.
  3176. /// class Z { class Y { class X {}; }; }; // Does not match Z.
  3177. /// \endcode
  3178. ///
  3179. /// ChildT must be an AST base type.
  3180. ///
  3181. /// As opposed to 'has', 'forEach' will cause a match for each result that
  3182. /// matches instead of only on the first one.
  3183. ///
  3184. /// Usable as: Any Matcher
  3185. extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
  3186. forEach;
  3187. /// Matches AST nodes that have descendant AST nodes that match the
  3188. /// provided matcher.
  3189. ///
  3190. /// Example matches X, A, A::X, B, B::C, B::C::X
  3191. /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
  3192. /// \code
  3193. /// class X {};
  3194. /// class A { class X {}; }; // Matches A, because A::X is a class of name
  3195. /// // X inside A.
  3196. /// class B { class C { class X {}; }; };
  3197. /// \endcode
  3198. ///
  3199. /// DescendantT must be an AST base type.
  3200. ///
  3201. /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
  3202. /// each result that matches instead of only on the first one.
  3203. ///
  3204. /// Note: Recursively combined ForEachDescendant can cause many matches:
  3205. /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
  3206. /// forEachDescendant(cxxRecordDecl())
  3207. /// )))
  3208. /// will match 10 times (plus injected class name matches) on:
  3209. /// \code
  3210. /// class A { class B { class C { class D { class E {}; }; }; }; };
  3211. /// \endcode
  3212. ///
  3213. /// Usable as: Any Matcher
  3214. extern const internal::ArgumentAdaptingMatcherFunc<
  3215. internal::ForEachDescendantMatcher>
  3216. forEachDescendant;
  3217. /// Matches if the node or any descendant matches.
  3218. ///
  3219. /// Generates results for each match.
  3220. ///
  3221. /// For example, in:
  3222. /// \code
  3223. /// class A { class B {}; class C {}; };
  3224. /// \endcode
  3225. /// The matcher:
  3226. /// \code
  3227. /// cxxRecordDecl(hasName("::A"),
  3228. /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
  3229. /// \endcode
  3230. /// will generate results for \c A, \c B and \c C.
  3231. ///
  3232. /// Usable as: Any Matcher
  3233. template <typename T>
  3234. internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
  3235. return eachOf(Matcher, forEachDescendant(Matcher));
  3236. }
  3237. /// Matches AST nodes that have a parent that matches the provided
  3238. /// matcher.
  3239. ///
  3240. /// Given
  3241. /// \code
  3242. /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
  3243. /// \endcode
  3244. /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
  3245. ///
  3246. /// Usable as: Any Matcher
  3247. extern const internal::ArgumentAdaptingMatcherFunc<
  3248. internal::HasParentMatcher,
  3249. internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
  3250. internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
  3251. hasParent;
  3252. /// Matches AST nodes that have an ancestor that matches the provided
  3253. /// matcher.
  3254. ///
  3255. /// Given
  3256. /// \code
  3257. /// void f() { if (true) { int x = 42; } }
  3258. /// void g() { for (;;) { int x = 43; } }
  3259. /// \endcode
  3260. /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
  3261. ///
  3262. /// Usable as: Any Matcher
  3263. extern const internal::ArgumentAdaptingMatcherFunc<
  3264. internal::HasAncestorMatcher,
  3265. internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
  3266. internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
  3267. hasAncestor;
  3268. /// Matches if the provided matcher does not match.
  3269. ///
  3270. /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
  3271. /// \code
  3272. /// class X {};
  3273. /// class Y {};
  3274. /// \endcode
  3275. ///
  3276. /// Usable as: Any Matcher
  3277. extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
  3278. /// Matches a node if the declaration associated with that node
  3279. /// matches the given matcher.
  3280. ///
  3281. /// The associated declaration is:
  3282. /// - for type nodes, the declaration of the underlying type
  3283. /// - for CallExpr, the declaration of the callee
  3284. /// - for MemberExpr, the declaration of the referenced member
  3285. /// - for CXXConstructExpr, the declaration of the constructor
  3286. /// - for CXXNewExpr, the declaration of the operator new
  3287. /// - for ObjCIvarExpr, the declaration of the ivar
  3288. ///
  3289. /// For type nodes, hasDeclaration will generally match the declaration of the
  3290. /// sugared type. Given
  3291. /// \code
  3292. /// class X {};
  3293. /// typedef X Y;
  3294. /// Y y;
  3295. /// \endcode
  3296. /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
  3297. /// typedefDecl. A common use case is to match the underlying, desugared type.
  3298. /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
  3299. /// \code
  3300. /// varDecl(hasType(hasUnqualifiedDesugaredType(
  3301. /// recordType(hasDeclaration(decl())))))
  3302. /// \endcode
  3303. /// In this matcher, the decl will match the CXXRecordDecl of class X.
  3304. ///
  3305. /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
  3306. /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
  3307. /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
  3308. /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
  3309. /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
  3310. /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
  3311. /// Matcher<UnresolvedUsingType>
  3312. inline internal::PolymorphicMatcher<
  3313. internal::HasDeclarationMatcher,
  3314. void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
  3315. hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
  3316. return internal::PolymorphicMatcher<
  3317. internal::HasDeclarationMatcher,
  3318. void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
  3319. InnerMatcher);
  3320. }
  3321. /// Matches a \c NamedDecl whose underlying declaration matches the given
  3322. /// matcher.
  3323. ///
  3324. /// Given
  3325. /// \code
  3326. /// namespace N { template<class T> void f(T t); }
  3327. /// template <class T> void g() { using N::f; f(T()); }
  3328. /// \endcode
  3329. /// \c unresolvedLookupExpr(hasAnyDeclaration(
  3330. /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
  3331. /// matches the use of \c f in \c g() .
  3332. AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
  3333. InnerMatcher) {
  3334. const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
  3335. return UnderlyingDecl != nullptr &&
  3336. InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
  3337. }
  3338. /// Matches on the implicit object argument of a member call expression, after
  3339. /// stripping off any parentheses or implicit casts.
  3340. ///
  3341. /// Given
  3342. /// \code
  3343. /// class Y { public: void m(); };
  3344. /// Y g();
  3345. /// class X : public Y {};
  3346. /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
  3347. /// \endcode
  3348. /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
  3349. /// matches `y.m()` and `(g()).m()`.
  3350. /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
  3351. /// matches `x.m()`.
  3352. /// cxxMemberCallExpr(on(callExpr()))
  3353. /// matches `(g()).m()`.
  3354. ///
  3355. /// FIXME: Overload to allow directly matching types?
  3356. AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
  3357. InnerMatcher) {
  3358. const Expr *ExprNode = Node.getImplicitObjectArgument()
  3359. ->IgnoreParenImpCasts();
  3360. return (ExprNode != nullptr &&
  3361. InnerMatcher.matches(*ExprNode, Finder, Builder));
  3362. }
  3363. /// Matches on the receiver of an ObjectiveC Message expression.
  3364. ///
  3365. /// Example
  3366. /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
  3367. /// matches the [webView ...] message invocation.
  3368. /// \code
  3369. /// NSString *webViewJavaScript = ...
  3370. /// UIWebView *webView = ...
  3371. /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
  3372. /// \endcode
  3373. AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
  3374. InnerMatcher) {
  3375. const QualType TypeDecl = Node.getReceiverType();
  3376. return InnerMatcher.matches(TypeDecl, Finder, Builder);
  3377. }
  3378. /// Returns true when the Objective-C method declaration is a class method.
  3379. ///
  3380. /// Example
  3381. /// matcher = objcMethodDecl(isClassMethod())
  3382. /// matches
  3383. /// \code
  3384. /// @interface I + (void)foo; @end
  3385. /// \endcode
  3386. /// but not
  3387. /// \code
  3388. /// @interface I - (void)bar; @end
  3389. /// \endcode
  3390. AST_MATCHER(ObjCMethodDecl, isClassMethod) {
  3391. return Node.isClassMethod();
  3392. }
  3393. /// Returns true when the Objective-C method declaration is an instance method.
  3394. ///
  3395. /// Example
  3396. /// matcher = objcMethodDecl(isInstanceMethod())
  3397. /// matches
  3398. /// \code
  3399. /// @interface I - (void)bar; @end
  3400. /// \endcode
  3401. /// but not
  3402. /// \code
  3403. /// @interface I + (void)foo; @end
  3404. /// \endcode
  3405. AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
  3406. return Node.isInstanceMethod();
  3407. }
  3408. /// Returns true when the Objective-C message is sent to a class.
  3409. ///
  3410. /// Example
  3411. /// matcher = objcMessageExpr(isClassMessage())
  3412. /// matches
  3413. /// \code
  3414. /// [NSString stringWithFormat:@"format"];
  3415. /// \endcode
  3416. /// but not
  3417. /// \code
  3418. /// NSString *x = @"hello";
  3419. /// [x containsString:@"h"];
  3420. /// \endcode
  3421. AST_MATCHER(ObjCMessageExpr, isClassMessage) {
  3422. return Node.isClassMessage();
  3423. }
  3424. /// Returns true when the Objective-C message is sent to an instance.
  3425. ///
  3426. /// Example
  3427. /// matcher = objcMessageExpr(isInstanceMessage())
  3428. /// matches
  3429. /// \code
  3430. /// NSString *x = @"hello";
  3431. /// [x containsString:@"h"];
  3432. /// \endcode
  3433. /// but not
  3434. /// \code
  3435. /// [NSString stringWithFormat:@"format"];
  3436. /// \endcode
  3437. AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
  3438. return Node.isInstanceMessage();
  3439. }
  3440. /// Matches if the Objective-C message is sent to an instance,
  3441. /// and the inner matcher matches on that instance.
  3442. ///
  3443. /// For example the method call in
  3444. /// \code
  3445. /// NSString *x = @"hello";
  3446. /// [x containsString:@"h"];
  3447. /// \endcode
  3448. /// is matched by
  3449. /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
  3450. AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
  3451. InnerMatcher) {
  3452. const Expr *ReceiverNode = Node.getInstanceReceiver();
  3453. return (ReceiverNode != nullptr &&
  3454. InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
  3455. Builder));
  3456. }
  3457. /// Matches when BaseName == Selector.getAsString()
  3458. ///
  3459. /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
  3460. /// matches the outer message expr in the code below, but NOT the message
  3461. /// invocation for self.bodyView.
  3462. /// \code
  3463. /// [self.bodyView loadHTMLString:html baseURL:NULL];
  3464. /// \endcode
  3465. AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
  3466. Selector Sel = Node.getSelector();
  3467. return BaseName == Sel.getAsString();
  3468. }
  3469. /// Matches when at least one of the supplied string equals to the
  3470. /// Selector.getAsString()
  3471. ///
  3472. /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
  3473. /// matches both of the expressions below:
  3474. /// \code
  3475. /// [myObj methodA:argA];
  3476. /// [myObj methodB:argB];
  3477. /// \endcode
  3478. extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
  3479. StringRef,
  3480. internal::hasAnySelectorFunc>
  3481. hasAnySelector;
  3482. /// Matches ObjC selectors whose name contains
  3483. /// a substring matched by the given RegExp.
  3484. /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
  3485. /// matches the outer message expr in the code below, but NOT the message
  3486. /// invocation for self.bodyView.
  3487. /// \code
  3488. /// [self.bodyView loadHTMLString:html baseURL:NULL];
  3489. /// \endcode
  3490. AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
  3491. std::string SelectorString = Node.getSelector().getAsString();
  3492. return RegExp->match(SelectorString);
  3493. }
  3494. /// Matches when the selector is the empty selector
  3495. ///
  3496. /// Matches only when the selector of the objCMessageExpr is NULL. This may
  3497. /// represent an error condition in the tree!
  3498. AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
  3499. return Node.getSelector().isNull();
  3500. }
  3501. /// Matches when the selector is a Unary Selector
  3502. ///
  3503. /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
  3504. /// matches self.bodyView in the code below, but NOT the outer message
  3505. /// invocation of "loadHTMLString:baseURL:".
  3506. /// \code
  3507. /// [self.bodyView loadHTMLString:html baseURL:NULL];
  3508. /// \endcode
  3509. AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
  3510. return Node.getSelector().isUnarySelector();
  3511. }
  3512. /// Matches when the selector is a keyword selector
  3513. ///
  3514. /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
  3515. /// message expression in
  3516. ///
  3517. /// \code
  3518. /// UIWebView *webView = ...;
  3519. /// CGRect bodyFrame = webView.frame;
  3520. /// bodyFrame.size.height = self.bodyContentHeight;
  3521. /// webView.frame = bodyFrame;
  3522. /// // ^---- matches here
  3523. /// \endcode
  3524. AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
  3525. return Node.getSelector().isKeywordSelector();
  3526. }
  3527. /// Matches when the selector has the specified number of arguments
  3528. ///
  3529. /// matcher = objCMessageExpr(numSelectorArgs(0));
  3530. /// matches self.bodyView in the code below
  3531. ///
  3532. /// matcher = objCMessageExpr(numSelectorArgs(2));
  3533. /// matches the invocation of "loadHTMLString:baseURL:" but not that
  3534. /// of self.bodyView
  3535. /// \code
  3536. /// [self.bodyView loadHTMLString:html baseURL:NULL];
  3537. /// \endcode
  3538. AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
  3539. return Node.getSelector().getNumArgs() == N;
  3540. }
  3541. /// Matches if the call expression's callee expression matches.
  3542. ///
  3543. /// Given
  3544. /// \code
  3545. /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
  3546. /// void f() { f(); }
  3547. /// \endcode
  3548. /// callExpr(callee(expr()))
  3549. /// matches this->x(), x(), y.x(), f()
  3550. /// with callee(...)
  3551. /// matching this->x, x, y.x, f respectively
  3552. ///
  3553. /// Note: Callee cannot take the more general internal::Matcher<Expr>
  3554. /// because this introduces ambiguous overloads with calls to Callee taking a
  3555. /// internal::Matcher<Decl>, as the matcher hierarchy is purely
  3556. /// implemented in terms of implicit casts.
  3557. AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
  3558. InnerMatcher) {
  3559. const Expr *ExprNode = Node.getCallee();
  3560. return (ExprNode != nullptr &&
  3561. InnerMatcher.matches(*ExprNode, Finder, Builder));
  3562. }
  3563. /// Matches 1) if the call expression's callee's declaration matches the
  3564. /// given matcher; or 2) if the Obj-C message expression's callee's method
  3565. /// declaration matches the given matcher.
  3566. ///
  3567. /// Example matches y.x() (matcher = callExpr(callee(
  3568. /// cxxMethodDecl(hasName("x")))))
  3569. /// \code
  3570. /// class Y { public: void x(); };
  3571. /// void z() { Y y; y.x(); }
  3572. /// \endcode
  3573. ///
  3574. /// Example 2. Matches [I foo] with
  3575. /// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
  3576. ///
  3577. /// \code
  3578. /// @interface I: NSObject
  3579. /// +(void)foo;
  3580. /// @end
  3581. /// ...
  3582. /// [I foo]
  3583. /// \endcode
  3584. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3585. callee, AST_POLYMORPHIC_SUPPORTED_TYPES(ObjCMessageExpr, CallExpr),
  3586. internal::Matcher<Decl>, InnerMatcher, 1) {
  3587. if (const auto *CallNode = dyn_cast<CallExpr>(&Node))
  3588. return callExpr(hasDeclaration(InnerMatcher))
  3589. .matches(Node, Finder, Builder);
  3590. else {
  3591. // The dynamic cast below is guaranteed to succeed as there are only 2
  3592. // supported return types.
  3593. const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
  3594. const Decl *DeclNode = MsgNode->getMethodDecl();
  3595. return (DeclNode != nullptr &&
  3596. InnerMatcher.matches(*DeclNode, Finder, Builder));
  3597. }
  3598. }
  3599. /// Matches if the expression's or declaration's type matches a type
  3600. /// matcher.
  3601. ///
  3602. /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
  3603. /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
  3604. /// and U (matcher = typedefDecl(hasType(asString("int")))
  3605. /// and friend class X (matcher = friendDecl(hasType("X"))
  3606. /// and public virtual X (matcher = cxxBaseSpecifier(hasType(
  3607. /// asString("class X")))
  3608. /// \code
  3609. /// class X {};
  3610. /// void y(X &x) { x; X z; }
  3611. /// typedef int U;
  3612. /// class Y { friend class X; };
  3613. /// class Z : public virtual X {};
  3614. /// \endcode
  3615. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3616. hasType,
  3617. AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
  3618. ValueDecl, CXXBaseSpecifier),
  3619. internal::Matcher<QualType>, InnerMatcher, 0) {
  3620. QualType QT = internal::getUnderlyingType(Node);
  3621. if (!QT.isNull())
  3622. return InnerMatcher.matches(QT, Finder, Builder);
  3623. return false;
  3624. }
  3625. /// Overloaded to match the declaration of the expression's or value
  3626. /// declaration's type.
  3627. ///
  3628. /// In case of a value declaration (for example a variable declaration),
  3629. /// this resolves one layer of indirection. For example, in the value
  3630. /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
  3631. /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
  3632. /// declaration of x.
  3633. ///
  3634. /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
  3635. /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
  3636. /// and friend class X (matcher = friendDecl(hasType("X"))
  3637. /// and public virtual X (matcher = cxxBaseSpecifier(hasType(
  3638. /// cxxRecordDecl(hasName("X"))))
  3639. /// \code
  3640. /// class X {};
  3641. /// void y(X &x) { x; X z; }
  3642. /// class Y { friend class X; };
  3643. /// class Z : public virtual X {};
  3644. /// \endcode
  3645. ///
  3646. /// Example matches class Derived
  3647. /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
  3648. /// \code
  3649. /// class Base {};
  3650. /// class Derived : Base {};
  3651. /// \endcode
  3652. ///
  3653. /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
  3654. /// Matcher<CXXBaseSpecifier>
  3655. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
  3656. hasType,
  3657. AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
  3658. CXXBaseSpecifier),
  3659. internal::Matcher<Decl>, InnerMatcher, 1) {
  3660. QualType QT = internal::getUnderlyingType(Node);
  3661. if (!QT.isNull())
  3662. return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
  3663. return false;
  3664. }
  3665. /// Matches if the type location of a node matches the inner matcher.
  3666. ///
  3667. /// Examples:
  3668. /// \code
  3669. /// int x;
  3670. /// \endcode
  3671. /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
  3672. /// matches int x
  3673. ///
  3674. /// \code
  3675. /// auto x = int(3);
  3676. /// \endcode
  3677. /// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
  3678. /// matches int(3)
  3679. ///
  3680. /// \code
  3681. /// struct Foo { Foo(int, int); };
  3682. /// auto x = Foo(1, 2);
  3683. /// \endcode
  3684. /// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
  3685. /// matches Foo(1, 2)
  3686. ///
  3687. /// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
  3688. /// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
  3689. /// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
  3690. /// Matcher<CXXUnresolvedConstructExpr>,
  3691. /// Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>,
  3692. /// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
  3693. /// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
  3694. /// Matcher<TypedefNameDecl>
  3695. AST_POLYMORPHIC_MATCHER_P(
  3696. hasTypeLoc,
  3697. AST_POLYMORPHIC_SUPPORTED_TYPES(
  3698. BlockDecl, CXXBaseSpecifier, CXXCtorInitializer, CXXFunctionalCastExpr,
  3699. CXXNewExpr, CXXTemporaryObjectExpr, CXXUnresolvedConstructExpr,
  3700. ClassTemplateSpecializationDecl, CompoundLiteralExpr, DeclaratorDecl,
  3701. ExplicitCastExpr, ObjCPropertyDecl, TemplateArgumentLoc,
  3702. TypedefNameDecl),
  3703. internal::Matcher<TypeLoc>, Inner) {
  3704. TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
  3705. if (source == nullptr) {
  3706. // This happens for example for implicit destructors.
  3707. return false;
  3708. }
  3709. return Inner.matches(source->getTypeLoc(), Finder, Builder);
  3710. }
  3711. /// Matches if the matched type is represented by the given string.
  3712. ///
  3713. /// Given
  3714. /// \code
  3715. /// class Y { public: void x(); };
  3716. /// void z() { Y* y; y->x(); }
  3717. /// \endcode
  3718. /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
  3719. /// matches y->x()
  3720. AST_MATCHER_P(QualType, asString, std::string, Name) {
  3721. return Name == Node.getAsString();
  3722. }
  3723. /// Matches if the matched type is a pointer type and the pointee type
  3724. /// matches the specified matcher.
  3725. ///
  3726. /// Example matches y->x()
  3727. /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
  3728. /// cxxRecordDecl(hasName("Y")))))))
  3729. /// \code
  3730. /// class Y { public: void x(); };
  3731. /// void z() { Y *y; y->x(); }
  3732. /// \endcode
  3733. AST_MATCHER_P(
  3734. QualType, pointsTo, internal::Matcher<QualType>,
  3735. InnerMatcher) {
  3736. return (!Node.isNull() && Node->isAnyPointerType() &&
  3737. InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
  3738. }
  3739. /// Overloaded to match the pointee type's declaration.
  3740. AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
  3741. InnerMatcher, 1) {
  3742. return pointsTo(qualType(hasDeclaration(InnerMatcher)))
  3743. .matches(Node, Finder, Builder);
  3744. }
  3745. /// Matches if the matched type matches the unqualified desugared
  3746. /// type of the matched node.
  3747. ///
  3748. /// For example, in:
  3749. /// \code
  3750. /// class A {};
  3751. /// using B = A;
  3752. /// \endcode
  3753. /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
  3754. /// both B and A.
  3755. AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
  3756. InnerMatcher) {
  3757. return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
  3758. Builder);
  3759. }
  3760. /// Matches if the matched type is a reference type and the referenced
  3761. /// type matches the specified matcher.
  3762. ///
  3763. /// Example matches X &x and const X &y
  3764. /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
  3765. /// \code
  3766. /// class X {
  3767. /// void a(X b) {
  3768. /// X &x = b;
  3769. /// const X &y = b;
  3770. /// }
  3771. /// };
  3772. /// \endcode
  3773. AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
  3774. InnerMatcher) {
  3775. return (!Node.isNull() && Node->isReferenceType() &&
  3776. InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
  3777. }
  3778. /// Matches QualTypes whose canonical type matches InnerMatcher.
  3779. ///
  3780. /// Given:
  3781. /// \code
  3782. /// typedef int &int_ref;
  3783. /// int a;
  3784. /// int_ref b = a;
  3785. /// \endcode
  3786. ///
  3787. /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
  3788. /// declaration of b but \c
  3789. /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
  3790. AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
  3791. InnerMatcher) {
  3792. if (Node.isNull())
  3793. return false;
  3794. return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
  3795. }
  3796. /// Overloaded to match the referenced type's declaration.
  3797. AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
  3798. InnerMatcher, 1) {
  3799. return references(qualType(hasDeclaration(InnerMatcher)))
  3800. .matches(Node, Finder, Builder);
  3801. }
  3802. /// Matches on the implicit object argument of a member call expression. Unlike
  3803. /// `on`, matches the argument directly without stripping away anything.
  3804. ///
  3805. /// Given
  3806. /// \code
  3807. /// class Y { public: void m(); };
  3808. /// Y g();
  3809. /// class X : public Y { void g(); };
  3810. /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
  3811. /// \endcode
  3812. /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
  3813. /// cxxRecordDecl(hasName("Y")))))
  3814. /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
  3815. /// cxxMemberCallExpr(on(callExpr()))
  3816. /// does not match `(g()).m()`, because the parens are not ignored.
  3817. ///
  3818. /// FIXME: Overload to allow directly matching types?
  3819. AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
  3820. internal::Matcher<Expr>, InnerMatcher) {
  3821. const Expr *ExprNode = Node.getImplicitObjectArgument();
  3822. return (ExprNode != nullptr &&
  3823. InnerMatcher.matches(*ExprNode, Finder, Builder));
  3824. }
  3825. /// Matches if the type of the expression's implicit object argument either
  3826. /// matches the InnerMatcher, or is a pointer to a type that matches the
  3827. /// InnerMatcher.
  3828. ///
  3829. /// Given
  3830. /// \code
  3831. /// class Y { public: void m(); };
  3832. /// class X : public Y { void g(); };
  3833. /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
  3834. /// \endcode
  3835. /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
  3836. /// cxxRecordDecl(hasName("Y")))))
  3837. /// matches `y.m()`, `p->m()` and `x.m()`.
  3838. /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
  3839. /// cxxRecordDecl(hasName("X")))))
  3840. /// matches `x.g()`.
  3841. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
  3842. internal::Matcher<QualType>, InnerMatcher, 0) {
  3843. return onImplicitObjectArgument(
  3844. anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
  3845. .matches(Node, Finder, Builder);
  3846. }
  3847. /// Overloaded to match the type's declaration.
  3848. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
  3849. internal::Matcher<Decl>, InnerMatcher, 1) {
  3850. return onImplicitObjectArgument(
  3851. anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
  3852. .matches(Node, Finder, Builder);
  3853. }
  3854. /// Matches a DeclRefExpr that refers to a declaration that matches the
  3855. /// specified matcher.
  3856. ///
  3857. /// Example matches x in if(x)
  3858. /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
  3859. /// \code
  3860. /// bool x;
  3861. /// if (x) {}
  3862. /// \endcode
  3863. AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
  3864. InnerMatcher) {
  3865. const Decl *DeclNode = Node.getDecl();
  3866. return (DeclNode != nullptr &&
  3867. InnerMatcher.matches(*DeclNode, Finder, Builder));
  3868. }
  3869. /// Matches if a node refers to a declaration through a specific
  3870. /// using shadow declaration.
  3871. ///
  3872. /// Examples:
  3873. /// \code
  3874. /// namespace a { int f(); }
  3875. /// using a::f;
  3876. /// int x = f();
  3877. /// \endcode
  3878. /// declRefExpr(throughUsingDecl(anything()))
  3879. /// matches \c f
  3880. ///
  3881. /// \code
  3882. /// namespace a { class X{}; }
  3883. /// using a::X;
  3884. /// X x;
  3885. /// \endcode
  3886. /// typeLoc(loc(usingType(throughUsingDecl(anything()))))
  3887. /// matches \c X
  3888. ///
  3889. /// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
  3890. AST_POLYMORPHIC_MATCHER_P(throughUsingDecl,
  3891. AST_POLYMORPHIC_SUPPORTED_TYPES(DeclRefExpr,
  3892. UsingType),
  3893. internal::Matcher<UsingShadowDecl>, Inner) {
  3894. const NamedDecl *FoundDecl = Node.getFoundDecl();
  3895. if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
  3896. return Inner.matches(*UsingDecl, Finder, Builder);
  3897. return false;
  3898. }
  3899. /// Matches an \c OverloadExpr if any of the declarations in the set of
  3900. /// overloads matches the given matcher.
  3901. ///
  3902. /// Given
  3903. /// \code
  3904. /// template <typename T> void foo(T);
  3905. /// template <typename T> void bar(T);
  3906. /// template <typename T> void baz(T t) {
  3907. /// foo(t);
  3908. /// bar(t);
  3909. /// }
  3910. /// \endcode
  3911. /// unresolvedLookupExpr(hasAnyDeclaration(
  3912. /// functionTemplateDecl(hasName("foo"))))
  3913. /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
  3914. AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
  3915. InnerMatcher) {
  3916. return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
  3917. Node.decls_end(), Finder,
  3918. Builder) != Node.decls_end();
  3919. }
  3920. /// Matches the Decl of a DeclStmt which has a single declaration.
  3921. ///
  3922. /// Given
  3923. /// \code
  3924. /// int a, b;
  3925. /// int c;
  3926. /// \endcode
  3927. /// declStmt(hasSingleDecl(anything()))
  3928. /// matches 'int c;' but not 'int a, b;'.
  3929. AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
  3930. if (Node.isSingleDecl()) {
  3931. const Decl *FoundDecl = Node.getSingleDecl();
  3932. return InnerMatcher.matches(*FoundDecl, Finder, Builder);
  3933. }
  3934. return false;
  3935. }
  3936. /// Matches a variable declaration that has an initializer expression
  3937. /// that matches the given matcher.
  3938. ///
  3939. /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
  3940. /// \code
  3941. /// bool y() { return true; }
  3942. /// bool x = y();
  3943. /// \endcode
  3944. AST_MATCHER_P(
  3945. VarDecl, hasInitializer, internal::Matcher<Expr>,
  3946. InnerMatcher) {
  3947. const Expr *Initializer = Node.getAnyInitializer();
  3948. return (Initializer != nullptr &&
  3949. InnerMatcher.matches(*Initializer, Finder, Builder));
  3950. }
  3951. /// Matches a variable serving as the implicit variable for a lambda init-
  3952. /// capture.
  3953. ///
  3954. /// Example matches x (matcher = varDecl(isInitCapture()))
  3955. /// \code
  3956. /// auto f = [x=3]() { return x; };
  3957. /// \endcode
  3958. AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
  3959. /// Matches each lambda capture in a lambda expression.
  3960. ///
  3961. /// Given
  3962. /// \code
  3963. /// int main() {
  3964. /// int x, y;
  3965. /// float z;
  3966. /// auto f = [=]() { return x + y + z; };
  3967. /// }
  3968. /// \endcode
  3969. /// lambdaExpr(forEachLambdaCapture(
  3970. /// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
  3971. /// will trigger two matches, binding for 'x' and 'y' respectively.
  3972. AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
  3973. internal::Matcher<LambdaCapture>, InnerMatcher) {
  3974. BoundNodesTreeBuilder Result;
  3975. bool Matched = false;
  3976. for (const auto &Capture : Node.captures()) {
  3977. if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
  3978. continue;
  3979. BoundNodesTreeBuilder CaptureBuilder(*Builder);
  3980. if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
  3981. Matched = true;
  3982. Result.addMatch(CaptureBuilder);
  3983. }
  3984. }
  3985. *Builder = std::move(Result);
  3986. return Matched;
  3987. }
  3988. /// \brief Matches a static variable with local scope.
  3989. ///
  3990. /// Example matches y (matcher = varDecl(isStaticLocal()))
  3991. /// \code
  3992. /// void f() {
  3993. /// int x;
  3994. /// static int y;
  3995. /// }
  3996. /// static int z;
  3997. /// \endcode
  3998. AST_MATCHER(VarDecl, isStaticLocal) {
  3999. return Node.isStaticLocal();
  4000. }
  4001. /// Matches a variable declaration that has function scope and is a
  4002. /// non-static local variable.
  4003. ///
  4004. /// Example matches x (matcher = varDecl(hasLocalStorage())
  4005. /// \code
  4006. /// void f() {
  4007. /// int x;
  4008. /// static int y;
  4009. /// }
  4010. /// int z;
  4011. /// \endcode
  4012. AST_MATCHER(VarDecl, hasLocalStorage) {
  4013. return Node.hasLocalStorage();
  4014. }
  4015. /// Matches a variable declaration that does not have local storage.
  4016. ///
  4017. /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
  4018. /// \code
  4019. /// void f() {
  4020. /// int x;
  4021. /// static int y;
  4022. /// }
  4023. /// int z;
  4024. /// \endcode
  4025. AST_MATCHER(VarDecl, hasGlobalStorage) {
  4026. return Node.hasGlobalStorage();
  4027. }
  4028. /// Matches a variable declaration that has automatic storage duration.
  4029. ///
  4030. /// Example matches x, but not y, z, or a.
  4031. /// (matcher = varDecl(hasAutomaticStorageDuration())
  4032. /// \code
  4033. /// void f() {
  4034. /// int x;
  4035. /// static int y;
  4036. /// thread_local int z;
  4037. /// }
  4038. /// int a;
  4039. /// \endcode
  4040. AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
  4041. return Node.getStorageDuration() == SD_Automatic;
  4042. }
  4043. /// Matches a variable declaration that has static storage duration.
  4044. /// It includes the variable declared at namespace scope and those declared
  4045. /// with "static" and "extern" storage class specifiers.
  4046. ///
  4047. /// \code
  4048. /// void f() {
  4049. /// int x;
  4050. /// static int y;
  4051. /// thread_local int z;
  4052. /// }
  4053. /// int a;
  4054. /// static int b;
  4055. /// extern int c;
  4056. /// varDecl(hasStaticStorageDuration())
  4057. /// matches the function declaration y, a, b and c.
  4058. /// \endcode
  4059. AST_MATCHER(VarDecl, hasStaticStorageDuration) {
  4060. return Node.getStorageDuration() == SD_Static;
  4061. }
  4062. /// Matches a variable declaration that has thread storage duration.
  4063. ///
  4064. /// Example matches z, but not x, z, or a.
  4065. /// (matcher = varDecl(hasThreadStorageDuration())
  4066. /// \code
  4067. /// void f() {
  4068. /// int x;
  4069. /// static int y;
  4070. /// thread_local int z;
  4071. /// }
  4072. /// int a;
  4073. /// \endcode
  4074. AST_MATCHER(VarDecl, hasThreadStorageDuration) {
  4075. return Node.getStorageDuration() == SD_Thread;
  4076. }
  4077. /// Matches a variable declaration that is an exception variable from
  4078. /// a C++ catch block, or an Objective-C \@catch statement.
  4079. ///
  4080. /// Example matches x (matcher = varDecl(isExceptionVariable())
  4081. /// \code
  4082. /// void f(int y) {
  4083. /// try {
  4084. /// } catch (int x) {
  4085. /// }
  4086. /// }
  4087. /// \endcode
  4088. AST_MATCHER(VarDecl, isExceptionVariable) {
  4089. return Node.isExceptionVariable();
  4090. }
  4091. /// Checks that a call expression or a constructor call expression has
  4092. /// a specific number of arguments (including absent default arguments).
  4093. ///
  4094. /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
  4095. /// \code
  4096. /// void f(int x, int y);
  4097. /// f(0, 0);
  4098. /// \endcode
  4099. AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
  4100. AST_POLYMORPHIC_SUPPORTED_TYPES(
  4101. CallExpr, CXXConstructExpr,
  4102. CXXUnresolvedConstructExpr, ObjCMessageExpr),
  4103. unsigned, N) {
  4104. unsigned NumArgs = Node.getNumArgs();
  4105. if (!Finder->isTraversalIgnoringImplicitNodes())
  4106. return NumArgs == N;
  4107. while (NumArgs) {
  4108. if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
  4109. break;
  4110. --NumArgs;
  4111. }
  4112. return NumArgs == N;
  4113. }
  4114. /// Matches the n'th argument of a call expression or a constructor
  4115. /// call expression.
  4116. ///
  4117. /// Example matches y in x(y)
  4118. /// (matcher = callExpr(hasArgument(0, declRefExpr())))
  4119. /// \code
  4120. /// void x(int) { int y; x(y); }
  4121. /// \endcode
  4122. AST_POLYMORPHIC_MATCHER_P2(hasArgument,
  4123. AST_POLYMORPHIC_SUPPORTED_TYPES(
  4124. CallExpr, CXXConstructExpr,
  4125. CXXUnresolvedConstructExpr, ObjCMessageExpr),
  4126. unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
  4127. if (N >= Node.getNumArgs())
  4128. return false;
  4129. const Expr *Arg = Node.getArg(N);
  4130. if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
  4131. return false;
  4132. return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
  4133. }
  4134. /// Matches the n'th item of an initializer list expression.
  4135. ///
  4136. /// Example matches y.
  4137. /// (matcher = initListExpr(hasInit(0, expr())))
  4138. /// \code
  4139. /// int x{y}.
  4140. /// \endcode
  4141. AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
  4142. ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
  4143. return N < Node.getNumInits() &&
  4144. InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
  4145. }
  4146. /// Matches declaration statements that contain a specific number of
  4147. /// declarations.
  4148. ///
  4149. /// Example: Given
  4150. /// \code
  4151. /// int a, b;
  4152. /// int c;
  4153. /// int d = 2, e;
  4154. /// \endcode
  4155. /// declCountIs(2)
  4156. /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
  4157. AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
  4158. return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
  4159. }
  4160. /// Matches the n'th declaration of a declaration statement.
  4161. ///
  4162. /// Note that this does not work for global declarations because the AST
  4163. /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
  4164. /// DeclStmt's.
  4165. /// Example: Given non-global declarations
  4166. /// \code
  4167. /// int a, b = 0;
  4168. /// int c;
  4169. /// int d = 2, e;
  4170. /// \endcode
  4171. /// declStmt(containsDeclaration(
  4172. /// 0, varDecl(hasInitializer(anything()))))
  4173. /// matches only 'int d = 2, e;', and
  4174. /// declStmt(containsDeclaration(1, varDecl()))
  4175. /// \code
  4176. /// matches 'int a, b = 0' as well as 'int d = 2, e;'
  4177. /// but 'int c;' is not matched.
  4178. /// \endcode
  4179. AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
  4180. internal::Matcher<Decl>, InnerMatcher) {
  4181. const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
  4182. if (N >= NumDecls)
  4183. return false;
  4184. DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
  4185. std::advance(Iterator, N);
  4186. return InnerMatcher.matches(**Iterator, Finder, Builder);
  4187. }
  4188. /// Matches a C++ catch statement that has a catch-all handler.
  4189. ///
  4190. /// Given
  4191. /// \code
  4192. /// try {
  4193. /// // ...
  4194. /// } catch (int) {
  4195. /// // ...
  4196. /// } catch (...) {
  4197. /// // ...
  4198. /// }
  4199. /// \endcode
  4200. /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
  4201. AST_MATCHER(CXXCatchStmt, isCatchAll) {
  4202. return Node.getExceptionDecl() == nullptr;
  4203. }
  4204. /// Matches a constructor initializer.
  4205. ///
  4206. /// Given
  4207. /// \code
  4208. /// struct Foo {
  4209. /// Foo() : foo_(1) { }
  4210. /// int foo_;
  4211. /// };
  4212. /// \endcode
  4213. /// cxxRecordDecl(has(cxxConstructorDecl(
  4214. /// hasAnyConstructorInitializer(anything())
  4215. /// )))
  4216. /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
  4217. AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
  4218. internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
  4219. auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
  4220. Node.init_end(), Finder, Builder);
  4221. if (MatchIt == Node.init_end())
  4222. return false;
  4223. return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
  4224. }
  4225. /// Matches the field declaration of a constructor initializer.
  4226. ///
  4227. /// Given
  4228. /// \code
  4229. /// struct Foo {
  4230. /// Foo() : foo_(1) { }
  4231. /// int foo_;
  4232. /// };
  4233. /// \endcode
  4234. /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
  4235. /// forField(hasName("foo_"))))))
  4236. /// matches Foo
  4237. /// with forField matching foo_
  4238. AST_MATCHER_P(CXXCtorInitializer, forField,
  4239. internal::Matcher<FieldDecl>, InnerMatcher) {
  4240. const FieldDecl *NodeAsDecl = Node.getAnyMember();
  4241. return (NodeAsDecl != nullptr &&
  4242. InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
  4243. }
  4244. /// Matches the initializer expression of a constructor initializer.
  4245. ///
  4246. /// Given
  4247. /// \code
  4248. /// struct Foo {
  4249. /// Foo() : foo_(1) { }
  4250. /// int foo_;
  4251. /// };
  4252. /// \endcode
  4253. /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
  4254. /// withInitializer(integerLiteral(equals(1)))))))
  4255. /// matches Foo
  4256. /// with withInitializer matching (1)
  4257. AST_MATCHER_P(CXXCtorInitializer, withInitializer,
  4258. internal::Matcher<Expr>, InnerMatcher) {
  4259. const Expr* NodeAsExpr = Node.getInit();
  4260. return (NodeAsExpr != nullptr &&
  4261. InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
  4262. }
  4263. /// Matches a constructor initializer if it is explicitly written in
  4264. /// code (as opposed to implicitly added by the compiler).
  4265. ///
  4266. /// Given
  4267. /// \code
  4268. /// struct Foo {
  4269. /// Foo() { }
  4270. /// Foo(int) : foo_("A") { }
  4271. /// string foo_;
  4272. /// };
  4273. /// \endcode
  4274. /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
  4275. /// will match Foo(int), but not Foo()
  4276. AST_MATCHER(CXXCtorInitializer, isWritten) {
  4277. return Node.isWritten();
  4278. }
  4279. /// Matches a constructor initializer if it is initializing a base, as
  4280. /// opposed to a member.
  4281. ///
  4282. /// Given
  4283. /// \code
  4284. /// struct B {};
  4285. /// struct D : B {
  4286. /// int I;
  4287. /// D(int i) : I(i) {}
  4288. /// };
  4289. /// struct E : B {
  4290. /// E() : B() {}
  4291. /// };
  4292. /// \endcode
  4293. /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
  4294. /// will match E(), but not match D(int).
  4295. AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
  4296. return Node.isBaseInitializer();
  4297. }
  4298. /// Matches a constructor initializer if it is initializing a member, as
  4299. /// opposed to a base.
  4300. ///
  4301. /// Given
  4302. /// \code
  4303. /// struct B {};
  4304. /// struct D : B {
  4305. /// int I;
  4306. /// D(int i) : I(i) {}
  4307. /// };
  4308. /// struct E : B {
  4309. /// E() : B() {}
  4310. /// };
  4311. /// \endcode
  4312. /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
  4313. /// will match D(int), but not match E().
  4314. AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
  4315. return Node.isMemberInitializer();
  4316. }
  4317. /// Matches any argument of a call expression or a constructor call
  4318. /// expression, or an ObjC-message-send expression.
  4319. ///
  4320. /// Given
  4321. /// \code
  4322. /// void x(int, int, int) { int y; x(1, y, 42); }
  4323. /// \endcode
  4324. /// callExpr(hasAnyArgument(declRefExpr()))
  4325. /// matches x(1, y, 42)
  4326. /// with hasAnyArgument(...)
  4327. /// matching y
  4328. ///
  4329. /// For ObjectiveC, given
  4330. /// \code
  4331. /// @interface I - (void) f:(int) y; @end
  4332. /// void foo(I *i) { [i f:12]; }
  4333. /// \endcode
  4334. /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
  4335. /// matches [i f:12]
  4336. AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
  4337. AST_POLYMORPHIC_SUPPORTED_TYPES(
  4338. CallExpr, CXXConstructExpr,
  4339. CXXUnresolvedConstructExpr, ObjCMessageExpr),
  4340. internal::Matcher<Expr>, InnerMatcher) {
  4341. for (const Expr *Arg : Node.arguments()) {
  4342. if (Finder->isTraversalIgnoringImplicitNodes() &&
  4343. isa<CXXDefaultArgExpr>(Arg))
  4344. break;
  4345. BoundNodesTreeBuilder Result(*Builder);
  4346. if (InnerMatcher.matches(*Arg, Finder, &Result)) {
  4347. *Builder = std::move(Result);
  4348. return true;
  4349. }
  4350. }
  4351. return false;
  4352. }
  4353. /// Matches lambda captures.
  4354. ///
  4355. /// Given
  4356. /// \code
  4357. /// int main() {
  4358. /// int x;
  4359. /// auto f = [x](){};
  4360. /// auto g = [x = 1](){};
  4361. /// }
  4362. /// \endcode
  4363. /// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
  4364. /// `lambdaCapture()` matches `x` and `x=1`.
  4365. extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
  4366. /// Matches any capture in a lambda expression.
  4367. ///
  4368. /// Given
  4369. /// \code
  4370. /// void foo() {
  4371. /// int t = 5;
  4372. /// auto f = [=](){ return t; };
  4373. /// }
  4374. /// \endcode
  4375. /// lambdaExpr(hasAnyCapture(lambdaCapture())) and
  4376. /// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
  4377. /// both match `[=](){ return t; }`.
  4378. AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
  4379. InnerMatcher) {
  4380. for (const LambdaCapture &Capture : Node.captures()) {
  4381. clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
  4382. if (InnerMatcher.matches(Capture, Finder, &Result)) {
  4383. *Builder = std::move(Result);
  4384. return true;
  4385. }
  4386. }
  4387. return false;
  4388. }
  4389. /// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
  4390. /// `VarDecl` can be a separate variable that is captured by value or
  4391. /// reference, or a synthesized variable if the capture has an initializer.
  4392. ///
  4393. /// Given
  4394. /// \code
  4395. /// void foo() {
  4396. /// int x;
  4397. /// auto f = [x](){};
  4398. /// auto g = [x = 1](){};
  4399. /// }
  4400. /// \endcode
  4401. /// In the matcher
  4402. /// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
  4403. /// capturesVar(hasName("x")) matches `x` and `x = 1`.
  4404. AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
  4405. InnerMatcher) {
  4406. auto *capturedVar = Node.getCapturedVar();
  4407. return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
  4408. }
  4409. /// Matches a `LambdaCapture` that refers to 'this'.
  4410. ///
  4411. /// Given
  4412. /// \code
  4413. /// class C {
  4414. /// int cc;
  4415. /// int f() {
  4416. /// auto l = [this]() { return cc; };
  4417. /// return l();
  4418. /// }
  4419. /// };
  4420. /// \endcode
  4421. /// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
  4422. /// matches `[this]() { return cc; }`.
  4423. AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
  4424. /// Matches a constructor call expression which uses list initialization.
  4425. AST_MATCHER(CXXConstructExpr, isListInitialization) {
  4426. return Node.isListInitialization();
  4427. }
  4428. /// Matches a constructor call expression which requires
  4429. /// zero initialization.
  4430. ///
  4431. /// Given
  4432. /// \code
  4433. /// void foo() {
  4434. /// struct point { double x; double y; };
  4435. /// point pt[2] = { { 1.0, 2.0 } };
  4436. /// }
  4437. /// \endcode
  4438. /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
  4439. /// will match the implicit array filler for pt[1].
  4440. AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
  4441. return Node.requiresZeroInitialization();
  4442. }
  4443. /// Matches the n'th parameter of a function or an ObjC method
  4444. /// declaration or a block.
  4445. ///
  4446. /// Given
  4447. /// \code
  4448. /// class X { void f(int x) {} };
  4449. /// \endcode
  4450. /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
  4451. /// matches f(int x) {}
  4452. /// with hasParameter(...)
  4453. /// matching int x
  4454. ///
  4455. /// For ObjectiveC, given
  4456. /// \code
  4457. /// @interface I - (void) f:(int) y; @end
  4458. /// \endcode
  4459. //
  4460. /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
  4461. /// matches the declaration of method f with hasParameter
  4462. /// matching y.
  4463. AST_POLYMORPHIC_MATCHER_P2(hasParameter,
  4464. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4465. ObjCMethodDecl,
  4466. BlockDecl),
  4467. unsigned, N, internal::Matcher<ParmVarDecl>,
  4468. InnerMatcher) {
  4469. return (N < Node.parameters().size()
  4470. && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
  4471. }
  4472. /// Matches all arguments and their respective ParmVarDecl.
  4473. ///
  4474. /// Given
  4475. /// \code
  4476. /// void f(int i);
  4477. /// int y;
  4478. /// f(y);
  4479. /// \endcode
  4480. /// callExpr(
  4481. /// forEachArgumentWithParam(
  4482. /// declRefExpr(to(varDecl(hasName("y")))),
  4483. /// parmVarDecl(hasType(isInteger()))
  4484. /// ))
  4485. /// matches f(y);
  4486. /// with declRefExpr(...)
  4487. /// matching int y
  4488. /// and parmVarDecl(...)
  4489. /// matching int i
  4490. AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
  4491. AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
  4492. CXXConstructExpr),
  4493. internal::Matcher<Expr>, ArgMatcher,
  4494. internal::Matcher<ParmVarDecl>, ParamMatcher) {
  4495. BoundNodesTreeBuilder Result;
  4496. // The first argument of an overloaded member operator is the implicit object
  4497. // argument of the method which should not be matched against a parameter, so
  4498. // we skip over it here.
  4499. BoundNodesTreeBuilder Matches;
  4500. unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
  4501. .matches(Node, Finder, &Matches)
  4502. ? 1
  4503. : 0;
  4504. int ParamIndex = 0;
  4505. bool Matched = false;
  4506. for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
  4507. BoundNodesTreeBuilder ArgMatches(*Builder);
  4508. if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
  4509. Finder, &ArgMatches)) {
  4510. BoundNodesTreeBuilder ParamMatches(ArgMatches);
  4511. if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
  4512. hasParameter(ParamIndex, ParamMatcher)))),
  4513. callExpr(callee(functionDecl(
  4514. hasParameter(ParamIndex, ParamMatcher))))))
  4515. .matches(Node, Finder, &ParamMatches)) {
  4516. Result.addMatch(ParamMatches);
  4517. Matched = true;
  4518. }
  4519. }
  4520. ++ParamIndex;
  4521. }
  4522. *Builder = std::move(Result);
  4523. return Matched;
  4524. }
  4525. /// Matches all arguments and their respective types for a \c CallExpr or
  4526. /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
  4527. /// it works on calls through function pointers as well.
  4528. ///
  4529. /// The difference is, that function pointers do not provide access to a
  4530. /// \c ParmVarDecl, but only the \c QualType for each argument.
  4531. ///
  4532. /// Given
  4533. /// \code
  4534. /// void f(int i);
  4535. /// int y;
  4536. /// f(y);
  4537. /// void (*f_ptr)(int) = f;
  4538. /// f_ptr(y);
  4539. /// \endcode
  4540. /// callExpr(
  4541. /// forEachArgumentWithParamType(
  4542. /// declRefExpr(to(varDecl(hasName("y")))),
  4543. /// qualType(isInteger()).bind("type)
  4544. /// ))
  4545. /// matches f(y) and f_ptr(y)
  4546. /// with declRefExpr(...)
  4547. /// matching int y
  4548. /// and qualType(...)
  4549. /// matching int
  4550. AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
  4551. AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
  4552. CXXConstructExpr),
  4553. internal::Matcher<Expr>, ArgMatcher,
  4554. internal::Matcher<QualType>, ParamMatcher) {
  4555. BoundNodesTreeBuilder Result;
  4556. // The first argument of an overloaded member operator is the implicit object
  4557. // argument of the method which should not be matched against a parameter, so
  4558. // we skip over it here.
  4559. BoundNodesTreeBuilder Matches;
  4560. unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
  4561. .matches(Node, Finder, &Matches)
  4562. ? 1
  4563. : 0;
  4564. const FunctionProtoType *FProto = nullptr;
  4565. if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
  4566. if (const auto *Value =
  4567. dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
  4568. QualType QT = Value->getType().getCanonicalType();
  4569. // This does not necessarily lead to a `FunctionProtoType`,
  4570. // e.g. K&R functions do not have a function prototype.
  4571. if (QT->isFunctionPointerType())
  4572. FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
  4573. if (QT->isMemberFunctionPointerType()) {
  4574. const auto *MP = QT->getAs<MemberPointerType>();
  4575. assert(MP && "Must be member-pointer if its a memberfunctionpointer");
  4576. FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
  4577. assert(FProto &&
  4578. "The call must have happened through a member function "
  4579. "pointer");
  4580. }
  4581. }
  4582. }
  4583. unsigned ParamIndex = 0;
  4584. bool Matched = false;
  4585. unsigned NumArgs = Node.getNumArgs();
  4586. if (FProto && FProto->isVariadic())
  4587. NumArgs = std::min(NumArgs, FProto->getNumParams());
  4588. for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
  4589. BoundNodesTreeBuilder ArgMatches(*Builder);
  4590. if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
  4591. &ArgMatches)) {
  4592. BoundNodesTreeBuilder ParamMatches(ArgMatches);
  4593. // This test is cheaper compared to the big matcher in the next if.
  4594. // Therefore, please keep this order.
  4595. if (FProto && FProto->getNumParams() > ParamIndex) {
  4596. QualType ParamType = FProto->getParamType(ParamIndex);
  4597. if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
  4598. Result.addMatch(ParamMatches);
  4599. Matched = true;
  4600. continue;
  4601. }
  4602. }
  4603. if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
  4604. hasParameter(ParamIndex, hasType(ParamMatcher))))),
  4605. callExpr(callee(functionDecl(
  4606. hasParameter(ParamIndex, hasType(ParamMatcher)))))))
  4607. .matches(Node, Finder, &ParamMatches)) {
  4608. Result.addMatch(ParamMatches);
  4609. Matched = true;
  4610. continue;
  4611. }
  4612. }
  4613. }
  4614. *Builder = std::move(Result);
  4615. return Matched;
  4616. }
  4617. /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
  4618. /// list. The parameter list could be that of either a block, function, or
  4619. /// objc-method.
  4620. ///
  4621. ///
  4622. /// Given
  4623. ///
  4624. /// \code
  4625. /// void f(int a, int b, int c) {
  4626. /// }
  4627. /// \endcode
  4628. ///
  4629. /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
  4630. ///
  4631. /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
  4632. AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
  4633. const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
  4634. if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
  4635. return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
  4636. if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
  4637. return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
  4638. if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
  4639. return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
  4640. return false;
  4641. }
  4642. /// Matches any parameter of a function or an ObjC method declaration or a
  4643. /// block.
  4644. ///
  4645. /// Does not match the 'this' parameter of a method.
  4646. ///
  4647. /// Given
  4648. /// \code
  4649. /// class X { void f(int x, int y, int z) {} };
  4650. /// \endcode
  4651. /// cxxMethodDecl(hasAnyParameter(hasName("y")))
  4652. /// matches f(int x, int y, int z) {}
  4653. /// with hasAnyParameter(...)
  4654. /// matching int y
  4655. ///
  4656. /// For ObjectiveC, given
  4657. /// \code
  4658. /// @interface I - (void) f:(int) y; @end
  4659. /// \endcode
  4660. //
  4661. /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
  4662. /// matches the declaration of method f with hasParameter
  4663. /// matching y.
  4664. ///
  4665. /// For blocks, given
  4666. /// \code
  4667. /// b = ^(int y) { printf("%d", y) };
  4668. /// \endcode
  4669. ///
  4670. /// the matcher blockDecl(hasAnyParameter(hasName("y")))
  4671. /// matches the declaration of the block b with hasParameter
  4672. /// matching y.
  4673. AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
  4674. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4675. ObjCMethodDecl,
  4676. BlockDecl),
  4677. internal::Matcher<ParmVarDecl>,
  4678. InnerMatcher) {
  4679. return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
  4680. Node.param_end(), Finder,
  4681. Builder) != Node.param_end();
  4682. }
  4683. /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
  4684. /// specific parameter count.
  4685. ///
  4686. /// Given
  4687. /// \code
  4688. /// void f(int i) {}
  4689. /// void g(int i, int j) {}
  4690. /// void h(int i, int j);
  4691. /// void j(int i);
  4692. /// void k(int x, int y, int z, ...);
  4693. /// \endcode
  4694. /// functionDecl(parameterCountIs(2))
  4695. /// matches \c g and \c h
  4696. /// functionProtoType(parameterCountIs(2))
  4697. /// matches \c g and \c h
  4698. /// functionProtoType(parameterCountIs(3))
  4699. /// matches \c k
  4700. AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
  4701. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4702. FunctionProtoType),
  4703. unsigned, N) {
  4704. return Node.getNumParams() == N;
  4705. }
  4706. /// Matches classTemplateSpecialization, templateSpecializationType and
  4707. /// functionDecl nodes where the template argument matches the inner matcher.
  4708. /// This matcher may produce multiple matches.
  4709. ///
  4710. /// Given
  4711. /// \code
  4712. /// template <typename T, unsigned N, unsigned M>
  4713. /// struct Matrix {};
  4714. ///
  4715. /// constexpr unsigned R = 2;
  4716. /// Matrix<int, R * 2, R * 4> M;
  4717. ///
  4718. /// template <typename T, typename U>
  4719. /// void f(T&& t, U&& u) {}
  4720. ///
  4721. /// bool B = false;
  4722. /// f(R, B);
  4723. /// \endcode
  4724. /// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
  4725. /// matches twice, with expr() matching 'R * 2' and 'R * 4'
  4726. /// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
  4727. /// matches the specialization f<unsigned, bool> twice, for 'unsigned'
  4728. /// and 'bool'
  4729. AST_POLYMORPHIC_MATCHER_P(
  4730. forEachTemplateArgument,
  4731. AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
  4732. TemplateSpecializationType, FunctionDecl),
  4733. clang::ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
  4734. ArrayRef<TemplateArgument> TemplateArgs =
  4735. clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
  4736. clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
  4737. bool Matched = false;
  4738. for (const auto &Arg : TemplateArgs) {
  4739. clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
  4740. if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
  4741. Matched = true;
  4742. Result.addMatch(ArgBuilder);
  4743. }
  4744. }
  4745. *Builder = std::move(Result);
  4746. return Matched;
  4747. }
  4748. /// Matches \c FunctionDecls that have a noreturn attribute.
  4749. ///
  4750. /// Given
  4751. /// \code
  4752. /// void nope();
  4753. /// [[noreturn]] void a();
  4754. /// __attribute__((noreturn)) void b();
  4755. /// struct c { [[noreturn]] c(); };
  4756. /// \endcode
  4757. /// functionDecl(isNoReturn())
  4758. /// matches all of those except
  4759. /// \code
  4760. /// void nope();
  4761. /// \endcode
  4762. AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
  4763. /// Matches the return type of a function declaration.
  4764. ///
  4765. /// Given:
  4766. /// \code
  4767. /// class X { int f() { return 1; } };
  4768. /// \endcode
  4769. /// cxxMethodDecl(returns(asString("int")))
  4770. /// matches int f() { return 1; }
  4771. AST_MATCHER_P(FunctionDecl, returns,
  4772. internal::Matcher<QualType>, InnerMatcher) {
  4773. return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
  4774. }
  4775. /// Matches extern "C" function or variable declarations.
  4776. ///
  4777. /// Given:
  4778. /// \code
  4779. /// extern "C" void f() {}
  4780. /// extern "C" { void g() {} }
  4781. /// void h() {}
  4782. /// extern "C" int x = 1;
  4783. /// extern "C" int y = 2;
  4784. /// int z = 3;
  4785. /// \endcode
  4786. /// functionDecl(isExternC())
  4787. /// matches the declaration of f and g, but not the declaration of h.
  4788. /// varDecl(isExternC())
  4789. /// matches the declaration of x and y, but not the declaration of z.
  4790. AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4791. VarDecl)) {
  4792. return Node.isExternC();
  4793. }
  4794. /// Matches variable/function declarations that have "static" storage
  4795. /// class specifier ("static" keyword) written in the source.
  4796. ///
  4797. /// Given:
  4798. /// \code
  4799. /// static void f() {}
  4800. /// static int i = 0;
  4801. /// extern int j;
  4802. /// int k;
  4803. /// \endcode
  4804. /// functionDecl(isStaticStorageClass())
  4805. /// matches the function declaration f.
  4806. /// varDecl(isStaticStorageClass())
  4807. /// matches the variable declaration i.
  4808. AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
  4809. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4810. VarDecl)) {
  4811. return Node.getStorageClass() == SC_Static;
  4812. }
  4813. /// Matches deleted function declarations.
  4814. ///
  4815. /// Given:
  4816. /// \code
  4817. /// void Func();
  4818. /// void DeletedFunc() = delete;
  4819. /// \endcode
  4820. /// functionDecl(isDeleted())
  4821. /// matches the declaration of DeletedFunc, but not Func.
  4822. AST_MATCHER(FunctionDecl, isDeleted) {
  4823. return Node.isDeleted();
  4824. }
  4825. /// Matches defaulted function declarations.
  4826. ///
  4827. /// Given:
  4828. /// \code
  4829. /// class A { ~A(); };
  4830. /// class B { ~B() = default; };
  4831. /// \endcode
  4832. /// functionDecl(isDefaulted())
  4833. /// matches the declaration of ~B, but not ~A.
  4834. AST_MATCHER(FunctionDecl, isDefaulted) {
  4835. return Node.isDefaulted();
  4836. }
  4837. /// Matches weak function declarations.
  4838. ///
  4839. /// Given:
  4840. /// \code
  4841. /// void foo() __attribute__((__weakref__("__foo")));
  4842. /// void bar();
  4843. /// \endcode
  4844. /// functionDecl(isWeak())
  4845. /// matches the weak declaration "foo", but not "bar".
  4846. AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
  4847. /// Matches functions that have a dynamic exception specification.
  4848. ///
  4849. /// Given:
  4850. /// \code
  4851. /// void f();
  4852. /// void g() noexcept;
  4853. /// void h() noexcept(true);
  4854. /// void i() noexcept(false);
  4855. /// void j() throw();
  4856. /// void k() throw(int);
  4857. /// void l() throw(...);
  4858. /// \endcode
  4859. /// functionDecl(hasDynamicExceptionSpec()) and
  4860. /// functionProtoType(hasDynamicExceptionSpec())
  4861. /// match the declarations of j, k, and l, but not f, g, h, or i.
  4862. AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
  4863. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4864. FunctionProtoType)) {
  4865. if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
  4866. return FnTy->hasDynamicExceptionSpec();
  4867. return false;
  4868. }
  4869. /// Matches functions that have a non-throwing exception specification.
  4870. ///
  4871. /// Given:
  4872. /// \code
  4873. /// void f();
  4874. /// void g() noexcept;
  4875. /// void h() throw();
  4876. /// void i() throw(int);
  4877. /// void j() noexcept(false);
  4878. /// \endcode
  4879. /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
  4880. /// match the declarations of g, and h, but not f, i or j.
  4881. AST_POLYMORPHIC_MATCHER(isNoThrow,
  4882. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
  4883. FunctionProtoType)) {
  4884. const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
  4885. // If the function does not have a prototype, then it is assumed to be a
  4886. // throwing function (as it would if the function did not have any exception
  4887. // specification).
  4888. if (!FnTy)
  4889. return false;
  4890. // Assume the best for any unresolved exception specification.
  4891. if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
  4892. return true;
  4893. return FnTy->isNothrow();
  4894. }
  4895. /// Matches consteval function declarations and if consteval/if ! consteval
  4896. /// statements.
  4897. ///
  4898. /// Given:
  4899. /// \code
  4900. /// consteval int a();
  4901. /// void b() { if consteval {} }
  4902. /// void c() { if ! consteval {} }
  4903. /// void d() { if ! consteval {} else {} }
  4904. /// \endcode
  4905. /// functionDecl(isConsteval())
  4906. /// matches the declaration of "int a()".
  4907. /// ifStmt(isConsteval())
  4908. /// matches the if statement in "void b()", "void c()", "void d()".
  4909. AST_POLYMORPHIC_MATCHER(isConsteval,
  4910. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, IfStmt)) {
  4911. return Node.isConsteval();
  4912. }
  4913. /// Matches constexpr variable and function declarations,
  4914. /// and if constexpr.
  4915. ///
  4916. /// Given:
  4917. /// \code
  4918. /// constexpr int foo = 42;
  4919. /// constexpr int bar();
  4920. /// void baz() { if constexpr(1 > 0) {} }
  4921. /// \endcode
  4922. /// varDecl(isConstexpr())
  4923. /// matches the declaration of foo.
  4924. /// functionDecl(isConstexpr())
  4925. /// matches the declaration of bar.
  4926. /// ifStmt(isConstexpr())
  4927. /// matches the if statement in baz.
  4928. AST_POLYMORPHIC_MATCHER(isConstexpr,
  4929. AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
  4930. FunctionDecl,
  4931. IfStmt)) {
  4932. return Node.isConstexpr();
  4933. }
  4934. /// Matches constinit variable declarations.
  4935. ///
  4936. /// Given:
  4937. /// \code
  4938. /// constinit int foo = 42;
  4939. /// constinit const char* bar = "bar";
  4940. /// int baz = 42;
  4941. /// [[clang::require_constant_initialization]] int xyz = 42;
  4942. /// \endcode
  4943. /// varDecl(isConstinit())
  4944. /// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
  4945. AST_MATCHER(VarDecl, isConstinit) {
  4946. if (const auto *CIA = Node.getAttr<ConstInitAttr>())
  4947. return CIA->isConstinit();
  4948. return false;
  4949. }
  4950. /// Matches selection statements with initializer.
  4951. ///
  4952. /// Given:
  4953. /// \code
  4954. /// void foo() {
  4955. /// if (int i = foobar(); i > 0) {}
  4956. /// switch (int i = foobar(); i) {}
  4957. /// for (auto& a = get_range(); auto& x : a) {}
  4958. /// }
  4959. /// void bar() {
  4960. /// if (foobar() > 0) {}
  4961. /// switch (foobar()) {}
  4962. /// for (auto& x : get_range()) {}
  4963. /// }
  4964. /// \endcode
  4965. /// ifStmt(hasInitStatement(anything()))
  4966. /// matches the if statement in foo but not in bar.
  4967. /// switchStmt(hasInitStatement(anything()))
  4968. /// matches the switch statement in foo but not in bar.
  4969. /// cxxForRangeStmt(hasInitStatement(anything()))
  4970. /// matches the range for statement in foo but not in bar.
  4971. AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
  4972. AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt,
  4973. CXXForRangeStmt),
  4974. internal::Matcher<Stmt>, InnerMatcher) {
  4975. const Stmt *Init = Node.getInit();
  4976. return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
  4977. }
  4978. /// Matches the condition expression of an if statement, for loop,
  4979. /// switch statement or conditional operator.
  4980. ///
  4981. /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
  4982. /// \code
  4983. /// if (true) {}
  4984. /// \endcode
  4985. AST_POLYMORPHIC_MATCHER_P(
  4986. hasCondition,
  4987. AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
  4988. SwitchStmt, AbstractConditionalOperator),
  4989. internal::Matcher<Expr>, InnerMatcher) {
  4990. const Expr *const Condition = Node.getCond();
  4991. return (Condition != nullptr &&
  4992. InnerMatcher.matches(*Condition, Finder, Builder));
  4993. }
  4994. /// Matches the then-statement of an if statement.
  4995. ///
  4996. /// Examples matches the if statement
  4997. /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
  4998. /// \code
  4999. /// if (false) true; else false;
  5000. /// \endcode
  5001. AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
  5002. const Stmt *const Then = Node.getThen();
  5003. return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
  5004. }
  5005. /// Matches the else-statement of an if statement.
  5006. ///
  5007. /// Examples matches the if statement
  5008. /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
  5009. /// \code
  5010. /// if (false) false; else true;
  5011. /// \endcode
  5012. AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
  5013. const Stmt *const Else = Node.getElse();
  5014. return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
  5015. }
  5016. /// Matches if a node equals a previously bound node.
  5017. ///
  5018. /// Matches a node if it equals the node previously bound to \p ID.
  5019. ///
  5020. /// Given
  5021. /// \code
  5022. /// class X { int a; int b; };
  5023. /// \endcode
  5024. /// cxxRecordDecl(
  5025. /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
  5026. /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
  5027. /// matches the class \c X, as \c a and \c b have the same type.
  5028. ///
  5029. /// Note that when multiple matches are involved via \c forEach* matchers,
  5030. /// \c equalsBoundNodes acts as a filter.
  5031. /// For example:
  5032. /// compoundStmt(
  5033. /// forEachDescendant(varDecl().bind("d")),
  5034. /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
  5035. /// will trigger a match for each combination of variable declaration
  5036. /// and reference to that variable declaration within a compound statement.
  5037. AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
  5038. AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
  5039. QualType),
  5040. std::string, ID) {
  5041. // FIXME: Figure out whether it makes sense to allow this
  5042. // on any other node types.
  5043. // For *Loc it probably does not make sense, as those seem
  5044. // unique. For NestedNameSepcifier it might make sense, as
  5045. // those also have pointer identity, but I'm not sure whether
  5046. // they're ever reused.
  5047. internal::NotEqualsBoundNodePredicate Predicate;
  5048. Predicate.ID = ID;
  5049. Predicate.Node = DynTypedNode::create(Node);
  5050. return Builder->removeBindings(Predicate);
  5051. }
  5052. /// Matches the condition variable statement in an if statement.
  5053. ///
  5054. /// Given
  5055. /// \code
  5056. /// if (A* a = GetAPointer()) {}
  5057. /// \endcode
  5058. /// hasConditionVariableStatement(...)
  5059. /// matches 'A* a = GetAPointer()'.
  5060. AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
  5061. internal::Matcher<DeclStmt>, InnerMatcher) {
  5062. const DeclStmt* const DeclarationStatement =
  5063. Node.getConditionVariableDeclStmt();
  5064. return DeclarationStatement != nullptr &&
  5065. InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
  5066. }
  5067. /// Matches the index expression of an array subscript expression.
  5068. ///
  5069. /// Given
  5070. /// \code
  5071. /// int i[5];
  5072. /// void f() { i[1] = 42; }
  5073. /// \endcode
  5074. /// arraySubscriptExpression(hasIndex(integerLiteral()))
  5075. /// matches \c i[1] with the \c integerLiteral() matching \c 1
  5076. AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
  5077. internal::Matcher<Expr>, InnerMatcher) {
  5078. if (const Expr* Expression = Node.getIdx())
  5079. return InnerMatcher.matches(*Expression, Finder, Builder);
  5080. return false;
  5081. }
  5082. /// Matches the base expression of an array subscript expression.
  5083. ///
  5084. /// Given
  5085. /// \code
  5086. /// int i[5];
  5087. /// void f() { i[1] = 42; }
  5088. /// \endcode
  5089. /// arraySubscriptExpression(hasBase(implicitCastExpr(
  5090. /// hasSourceExpression(declRefExpr()))))
  5091. /// matches \c i[1] with the \c declRefExpr() matching \c i
  5092. AST_MATCHER_P(ArraySubscriptExpr, hasBase,
  5093. internal::Matcher<Expr>, InnerMatcher) {
  5094. if (const Expr* Expression = Node.getBase())
  5095. return InnerMatcher.matches(*Expression, Finder, Builder);
  5096. return false;
  5097. }
  5098. /// Matches a 'for', 'while', 'do' statement or a function definition that has
  5099. /// a given body. Note that in case of functions this matcher only matches the
  5100. /// definition itself and not the other declarations of the same function.
  5101. ///
  5102. /// Given
  5103. /// \code
  5104. /// for (;;) {}
  5105. /// \endcode
  5106. /// forStmt(hasBody(compoundStmt()))
  5107. /// matches 'for (;;) {}'
  5108. /// with compoundStmt()
  5109. /// matching '{}'
  5110. ///
  5111. /// Given
  5112. /// \code
  5113. /// void f();
  5114. /// void f() {}
  5115. /// \endcode
  5116. /// functionDecl(hasBody(compoundStmt()))
  5117. /// matches 'void f() {}'
  5118. /// with compoundStmt()
  5119. /// matching '{}'
  5120. /// but does not match 'void f();'
  5121. AST_POLYMORPHIC_MATCHER_P(hasBody,
  5122. AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
  5123. WhileStmt,
  5124. CXXForRangeStmt,
  5125. FunctionDecl),
  5126. internal::Matcher<Stmt>, InnerMatcher) {
  5127. if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
  5128. return false;
  5129. const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
  5130. return (Statement != nullptr &&
  5131. InnerMatcher.matches(*Statement, Finder, Builder));
  5132. }
  5133. /// Matches a function declaration that has a given body present in the AST.
  5134. /// Note that this matcher matches all the declarations of a function whose
  5135. /// body is present in the AST.
  5136. ///
  5137. /// Given
  5138. /// \code
  5139. /// void f();
  5140. /// void f() {}
  5141. /// void g();
  5142. /// \endcode
  5143. /// functionDecl(hasAnyBody(compoundStmt()))
  5144. /// matches both 'void f();'
  5145. /// and 'void f() {}'
  5146. /// with compoundStmt()
  5147. /// matching '{}'
  5148. /// but does not match 'void g();'
  5149. AST_MATCHER_P(FunctionDecl, hasAnyBody,
  5150. internal::Matcher<Stmt>, InnerMatcher) {
  5151. const Stmt *const Statement = Node.getBody();
  5152. return (Statement != nullptr &&
  5153. InnerMatcher.matches(*Statement, Finder, Builder));
  5154. }
  5155. /// Matches compound statements where at least one substatement matches
  5156. /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
  5157. ///
  5158. /// Given
  5159. /// \code
  5160. /// { {}; 1+2; }
  5161. /// \endcode
  5162. /// hasAnySubstatement(compoundStmt())
  5163. /// matches '{ {}; 1+2; }'
  5164. /// with compoundStmt()
  5165. /// matching '{}'
  5166. AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
  5167. AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
  5168. StmtExpr),
  5169. internal::Matcher<Stmt>, InnerMatcher) {
  5170. const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
  5171. return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
  5172. CS->body_end(), Finder,
  5173. Builder) != CS->body_end();
  5174. }
  5175. /// Checks that a compound statement contains a specific number of
  5176. /// child statements.
  5177. ///
  5178. /// Example: Given
  5179. /// \code
  5180. /// { for (;;) {} }
  5181. /// \endcode
  5182. /// compoundStmt(statementCountIs(0)))
  5183. /// matches '{}'
  5184. /// but does not match the outer compound statement.
  5185. AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
  5186. return Node.size() == N;
  5187. }
  5188. /// Matches literals that are equal to the given value of type ValueT.
  5189. ///
  5190. /// Given
  5191. /// \code
  5192. /// f('\0', false, 3.14, 42);
  5193. /// \endcode
  5194. /// characterLiteral(equals(0))
  5195. /// matches '\0'
  5196. /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
  5197. /// match false
  5198. /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
  5199. /// match 3.14
  5200. /// integerLiteral(equals(42))
  5201. /// matches 42
  5202. ///
  5203. /// Note that you cannot directly match a negative numeric literal because the
  5204. /// minus sign is not part of the literal: It is a unary operator whose operand
  5205. /// is the positive numeric literal. Instead, you must use a unaryOperator()
  5206. /// matcher to match the minus sign:
  5207. ///
  5208. /// unaryOperator(hasOperatorName("-"),
  5209. /// hasUnaryOperand(integerLiteral(equals(13))))
  5210. ///
  5211. /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
  5212. /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
  5213. template <typename ValueT>
  5214. internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
  5215. void(internal::AllNodeBaseTypes), ValueT>
  5216. equals(const ValueT &Value) {
  5217. return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
  5218. void(internal::AllNodeBaseTypes), ValueT>(
  5219. Value);
  5220. }
  5221. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
  5222. AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
  5223. CXXBoolLiteralExpr,
  5224. IntegerLiteral),
  5225. bool, Value, 0) {
  5226. return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
  5227. .matchesNode(Node);
  5228. }
  5229. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
  5230. AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
  5231. CXXBoolLiteralExpr,
  5232. IntegerLiteral),
  5233. unsigned, Value, 1) {
  5234. return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
  5235. .matchesNode(Node);
  5236. }
  5237. AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
  5238. AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
  5239. CXXBoolLiteralExpr,
  5240. FloatingLiteral,
  5241. IntegerLiteral),
  5242. double, Value, 2) {
  5243. return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
  5244. .matchesNode(Node);
  5245. }
  5246. /// Matches the operator Name of operator expressions (binary or
  5247. /// unary).
  5248. ///
  5249. /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
  5250. /// \code
  5251. /// !(a || b)
  5252. /// \endcode
  5253. AST_POLYMORPHIC_MATCHER_P(
  5254. hasOperatorName,
  5255. AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
  5256. CXXRewrittenBinaryOperator, UnaryOperator),
  5257. std::string, Name) {
  5258. if (std::optional<StringRef> OpName = internal::getOpName(Node))
  5259. return *OpName == Name;
  5260. return false;
  5261. }
  5262. /// Matches operator expressions (binary or unary) that have any of the
  5263. /// specified names.
  5264. ///
  5265. /// hasAnyOperatorName("+", "-")
  5266. /// Is equivalent to
  5267. /// anyOf(hasOperatorName("+"), hasOperatorName("-"))
  5268. extern const internal::VariadicFunction<
  5269. internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
  5270. AST_POLYMORPHIC_SUPPORTED_TYPES(
  5271. BinaryOperator, CXXOperatorCallExpr,
  5272. CXXRewrittenBinaryOperator, UnaryOperator),
  5273. std::vector<std::string>>,
  5274. StringRef, internal::hasAnyOperatorNameFunc>
  5275. hasAnyOperatorName;
  5276. /// Matches all kinds of assignment operators.
  5277. ///
  5278. /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
  5279. /// \code
  5280. /// if (a == b)
  5281. /// a += b;
  5282. /// \endcode
  5283. ///
  5284. /// Example 2: matches s1 = s2
  5285. /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
  5286. /// \code
  5287. /// struct S { S& operator=(const S&); };
  5288. /// void x() { S s1, s2; s1 = s2; }
  5289. /// \endcode
  5290. AST_POLYMORPHIC_MATCHER(
  5291. isAssignmentOperator,
  5292. AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
  5293. CXXRewrittenBinaryOperator)) {
  5294. return Node.isAssignmentOp();
  5295. }
  5296. /// Matches comparison operators.
  5297. ///
  5298. /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
  5299. /// \code
  5300. /// if (a == b)
  5301. /// a += b;
  5302. /// \endcode
  5303. ///
  5304. /// Example 2: matches s1 < s2
  5305. /// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
  5306. /// \code
  5307. /// struct S { bool operator<(const S& other); };
  5308. /// void x(S s1, S s2) { bool b1 = s1 < s2; }
  5309. /// \endcode
  5310. AST_POLYMORPHIC_MATCHER(
  5311. isComparisonOperator,
  5312. AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
  5313. CXXRewrittenBinaryOperator)) {
  5314. return Node.isComparisonOp();
  5315. }
  5316. /// Matches the left hand side of binary operator expressions.
  5317. ///
  5318. /// Example matches a (matcher = binaryOperator(hasLHS()))
  5319. /// \code
  5320. /// a || b
  5321. /// \endcode
  5322. AST_POLYMORPHIC_MATCHER_P(hasLHS,
  5323. AST_POLYMORPHIC_SUPPORTED_TYPES(
  5324. BinaryOperator, CXXOperatorCallExpr,
  5325. CXXRewrittenBinaryOperator, ArraySubscriptExpr),
  5326. internal::Matcher<Expr>, InnerMatcher) {
  5327. const Expr *LeftHandSide = internal::getLHS(Node);
  5328. return (LeftHandSide != nullptr &&
  5329. InnerMatcher.matches(*LeftHandSide, Finder, Builder));
  5330. }
  5331. /// Matches the right hand side of binary operator expressions.
  5332. ///
  5333. /// Example matches b (matcher = binaryOperator(hasRHS()))
  5334. /// \code
  5335. /// a || b
  5336. /// \endcode
  5337. AST_POLYMORPHIC_MATCHER_P(hasRHS,
  5338. AST_POLYMORPHIC_SUPPORTED_TYPES(
  5339. BinaryOperator, CXXOperatorCallExpr,
  5340. CXXRewrittenBinaryOperator, ArraySubscriptExpr),
  5341. internal::Matcher<Expr>, InnerMatcher) {
  5342. const Expr *RightHandSide = internal::getRHS(Node);
  5343. return (RightHandSide != nullptr &&
  5344. InnerMatcher.matches(*RightHandSide, Finder, Builder));
  5345. }
  5346. /// Matches if either the left hand side or the right hand side of a
  5347. /// binary operator matches.
  5348. AST_POLYMORPHIC_MATCHER_P(
  5349. hasEitherOperand,
  5350. AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
  5351. CXXRewrittenBinaryOperator),
  5352. internal::Matcher<Expr>, InnerMatcher) {
  5353. return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
  5354. anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
  5355. .matches(Node, Finder, Builder);
  5356. }
  5357. /// Matches if both matchers match with opposite sides of the binary operator.
  5358. ///
  5359. /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
  5360. /// integerLiteral(equals(2)))
  5361. /// \code
  5362. /// 1 + 2 // Match
  5363. /// 2 + 1 // Match
  5364. /// 1 + 1 // No match
  5365. /// 2 + 2 // No match
  5366. /// \endcode
  5367. AST_POLYMORPHIC_MATCHER_P2(
  5368. hasOperands,
  5369. AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
  5370. CXXRewrittenBinaryOperator),
  5371. internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
  5372. return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
  5373. anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
  5374. allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
  5375. .matches(Node, Finder, Builder);
  5376. }
  5377. /// Matches if the operand of a unary operator matches.
  5378. ///
  5379. /// Example matches true (matcher = hasUnaryOperand(
  5380. /// cxxBoolLiteral(equals(true))))
  5381. /// \code
  5382. /// !true
  5383. /// \endcode
  5384. AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,
  5385. AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator,
  5386. CXXOperatorCallExpr),
  5387. internal::Matcher<Expr>, InnerMatcher) {
  5388. const Expr *const Operand = internal::getSubExpr(Node);
  5389. return (Operand != nullptr &&
  5390. InnerMatcher.matches(*Operand, Finder, Builder));
  5391. }
  5392. /// Matches if the cast's source expression
  5393. /// or opaque value's source expression matches the given matcher.
  5394. ///
  5395. /// Example 1: matches "a string"
  5396. /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
  5397. /// \code
  5398. /// class URL { URL(string); };
  5399. /// URL url = "a string";
  5400. /// \endcode
  5401. ///
  5402. /// Example 2: matches 'b' (matcher =
  5403. /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
  5404. /// \code
  5405. /// int a = b ?: 1;
  5406. /// \endcode
  5407. AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
  5408. AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
  5409. OpaqueValueExpr),
  5410. internal::Matcher<Expr>, InnerMatcher) {
  5411. const Expr *const SubExpression =
  5412. internal::GetSourceExpressionMatcher<NodeType>::get(Node);
  5413. return (SubExpression != nullptr &&
  5414. InnerMatcher.matches(*SubExpression, Finder, Builder));
  5415. }
  5416. /// Matches casts that has a given cast kind.
  5417. ///
  5418. /// Example: matches the implicit cast around \c 0
  5419. /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
  5420. /// \code
  5421. /// int *p = 0;
  5422. /// \endcode
  5423. ///
  5424. /// If the matcher is use from clang-query, CastKind parameter
  5425. /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
  5426. AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
  5427. return Node.getCastKind() == Kind;
  5428. }
  5429. /// Matches casts whose destination type matches a given matcher.
  5430. ///
  5431. /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
  5432. /// actual casts "explicit" casts.)
  5433. AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
  5434. internal::Matcher<QualType>, InnerMatcher) {
  5435. const QualType NodeType = Node.getTypeAsWritten();
  5436. return InnerMatcher.matches(NodeType, Finder, Builder);
  5437. }
  5438. /// Matches implicit casts whose destination type matches a given
  5439. /// matcher.
  5440. AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
  5441. internal::Matcher<QualType>, InnerMatcher) {
  5442. return InnerMatcher.matches(Node.getType(), Finder, Builder);
  5443. }
  5444. /// Matches TagDecl object that are spelled with "struct."
  5445. ///
  5446. /// Example matches S, but not C, U or E.
  5447. /// \code
  5448. /// struct S {};
  5449. /// class C {};
  5450. /// union U {};
  5451. /// enum E {};
  5452. /// \endcode
  5453. AST_MATCHER(TagDecl, isStruct) {
  5454. return Node.isStruct();
  5455. }
  5456. /// Matches TagDecl object that are spelled with "union."
  5457. ///
  5458. /// Example matches U, but not C, S or E.
  5459. /// \code
  5460. /// struct S {};
  5461. /// class C {};
  5462. /// union U {};
  5463. /// enum E {};
  5464. /// \endcode
  5465. AST_MATCHER(TagDecl, isUnion) {
  5466. return Node.isUnion();
  5467. }
  5468. /// Matches TagDecl object that are spelled with "class."
  5469. ///
  5470. /// Example matches C, but not S, U or E.
  5471. /// \code
  5472. /// struct S {};
  5473. /// class C {};
  5474. /// union U {};
  5475. /// enum E {};
  5476. /// \endcode
  5477. AST_MATCHER(TagDecl, isClass) {
  5478. return Node.isClass();
  5479. }
  5480. /// Matches TagDecl object that are spelled with "enum."
  5481. ///
  5482. /// Example matches E, but not C, S or U.
  5483. /// \code
  5484. /// struct S {};
  5485. /// class C {};
  5486. /// union U {};
  5487. /// enum E {};
  5488. /// \endcode
  5489. AST_MATCHER(TagDecl, isEnum) {
  5490. return Node.isEnum();
  5491. }
  5492. /// Matches the true branch expression of a conditional operator.
  5493. ///
  5494. /// Example 1 (conditional ternary operator): matches a
  5495. /// \code
  5496. /// condition ? a : b
  5497. /// \endcode
  5498. ///
  5499. /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
  5500. /// \code
  5501. /// condition ?: b
  5502. /// \endcode
  5503. AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
  5504. internal::Matcher<Expr>, InnerMatcher) {
  5505. const Expr *Expression = Node.getTrueExpr();
  5506. return (Expression != nullptr &&
  5507. InnerMatcher.matches(*Expression, Finder, Builder));
  5508. }
  5509. /// Matches the false branch expression of a conditional operator
  5510. /// (binary or ternary).
  5511. ///
  5512. /// Example matches b
  5513. /// \code
  5514. /// condition ? a : b
  5515. /// condition ?: b
  5516. /// \endcode
  5517. AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
  5518. internal::Matcher<Expr>, InnerMatcher) {
  5519. const Expr *Expression = Node.getFalseExpr();
  5520. return (Expression != nullptr &&
  5521. InnerMatcher.matches(*Expression, Finder, Builder));
  5522. }
  5523. /// Matches if a declaration has a body attached.
  5524. ///
  5525. /// Example matches A, va, fa
  5526. /// \code
  5527. /// class A {};
  5528. /// class B; // Doesn't match, as it has no body.
  5529. /// int va;
  5530. /// extern int vb; // Doesn't match, as it doesn't define the variable.
  5531. /// void fa() {}
  5532. /// void fb(); // Doesn't match, as it has no body.
  5533. /// @interface X
  5534. /// - (void)ma; // Doesn't match, interface is declaration.
  5535. /// @end
  5536. /// @implementation X
  5537. /// - (void)ma {}
  5538. /// @end
  5539. /// \endcode
  5540. ///
  5541. /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
  5542. /// Matcher<ObjCMethodDecl>
  5543. AST_POLYMORPHIC_MATCHER(isDefinition,
  5544. AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
  5545. ObjCMethodDecl,
  5546. FunctionDecl)) {
  5547. return Node.isThisDeclarationADefinition();
  5548. }
  5549. /// Matches if a function declaration is variadic.
  5550. ///
  5551. /// Example matches f, but not g or h. The function i will not match, even when
  5552. /// compiled in C mode.
  5553. /// \code
  5554. /// void f(...);
  5555. /// void g(int);
  5556. /// template <typename... Ts> void h(Ts...);
  5557. /// void i();
  5558. /// \endcode
  5559. AST_MATCHER(FunctionDecl, isVariadic) {
  5560. return Node.isVariadic();
  5561. }
  5562. /// Matches the class declaration that the given method declaration
  5563. /// belongs to.
  5564. ///
  5565. /// FIXME: Generalize this for other kinds of declarations.
  5566. /// FIXME: What other kind of declarations would we need to generalize
  5567. /// this to?
  5568. ///
  5569. /// Example matches A() in the last line
  5570. /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
  5571. /// ofClass(hasName("A"))))))
  5572. /// \code
  5573. /// class A {
  5574. /// public:
  5575. /// A();
  5576. /// };
  5577. /// A a = A();
  5578. /// \endcode
  5579. AST_MATCHER_P(CXXMethodDecl, ofClass,
  5580. internal::Matcher<CXXRecordDecl>, InnerMatcher) {
  5581. ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
  5582. const CXXRecordDecl *Parent = Node.getParent();
  5583. return (Parent != nullptr &&
  5584. InnerMatcher.matches(*Parent, Finder, Builder));
  5585. }
  5586. /// Matches each method overridden by the given method. This matcher may
  5587. /// produce multiple matches.
  5588. ///
  5589. /// Given
  5590. /// \code
  5591. /// class A { virtual void f(); };
  5592. /// class B : public A { void f(); };
  5593. /// class C : public B { void f(); };
  5594. /// \endcode
  5595. /// cxxMethodDecl(ofClass(hasName("C")),
  5596. /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
  5597. /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
  5598. /// that B::f is not overridden by C::f).
  5599. ///
  5600. /// The check can produce multiple matches in case of multiple inheritance, e.g.
  5601. /// \code
  5602. /// class A1 { virtual void f(); };
  5603. /// class A2 { virtual void f(); };
  5604. /// class C : public A1, public A2 { void f(); };
  5605. /// \endcode
  5606. /// cxxMethodDecl(ofClass(hasName("C")),
  5607. /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
  5608. /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
  5609. /// once with "b" binding "A2::f" and "d" binding "C::f".
  5610. AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
  5611. internal::Matcher<CXXMethodDecl>, InnerMatcher) {
  5612. BoundNodesTreeBuilder Result;
  5613. bool Matched = false;
  5614. for (const auto *Overridden : Node.overridden_methods()) {
  5615. BoundNodesTreeBuilder OverriddenBuilder(*Builder);
  5616. const bool OverriddenMatched =
  5617. InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
  5618. if (OverriddenMatched) {
  5619. Matched = true;
  5620. Result.addMatch(OverriddenBuilder);
  5621. }
  5622. }
  5623. *Builder = std::move(Result);
  5624. return Matched;
  5625. }
  5626. /// Matches declarations of virtual methods and C++ base specifers that specify
  5627. /// virtual inheritance.
  5628. ///
  5629. /// Example:
  5630. /// \code
  5631. /// class A {
  5632. /// public:
  5633. /// virtual void x(); // matches x
  5634. /// };
  5635. /// \endcode
  5636. ///
  5637. /// Example:
  5638. /// \code
  5639. /// class Base {};
  5640. /// class DirectlyDerived : virtual Base {}; // matches Base
  5641. /// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
  5642. /// \endcode
  5643. ///
  5644. /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
  5645. AST_POLYMORPHIC_MATCHER(isVirtual,
  5646. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
  5647. CXXBaseSpecifier)) {
  5648. return Node.isVirtual();
  5649. }
  5650. /// Matches if the given method declaration has an explicit "virtual".
  5651. ///
  5652. /// Given
  5653. /// \code
  5654. /// class A {
  5655. /// public:
  5656. /// virtual void x();
  5657. /// };
  5658. /// class B : public A {
  5659. /// public:
  5660. /// void x();
  5661. /// };
  5662. /// \endcode
  5663. /// matches A::x but not B::x
  5664. AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
  5665. return Node.isVirtualAsWritten();
  5666. }
  5667. AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
  5668. return Node.isInheritingConstructor();
  5669. }
  5670. /// Matches if the given method or class declaration is final.
  5671. ///
  5672. /// Given:
  5673. /// \code
  5674. /// class A final {};
  5675. ///
  5676. /// struct B {
  5677. /// virtual void f();
  5678. /// };
  5679. ///
  5680. /// struct C : B {
  5681. /// void f() final;
  5682. /// };
  5683. /// \endcode
  5684. /// matches A and C::f, but not B, C, or B::f
  5685. AST_POLYMORPHIC_MATCHER(isFinal,
  5686. AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
  5687. CXXMethodDecl)) {
  5688. return Node.template hasAttr<FinalAttr>();
  5689. }
  5690. /// Matches if the given method declaration is pure.
  5691. ///
  5692. /// Given
  5693. /// \code
  5694. /// class A {
  5695. /// public:
  5696. /// virtual void x() = 0;
  5697. /// };
  5698. /// \endcode
  5699. /// matches A::x
  5700. AST_MATCHER(CXXMethodDecl, isPure) {
  5701. return Node.isPure();
  5702. }
  5703. /// Matches if the given method declaration is const.
  5704. ///
  5705. /// Given
  5706. /// \code
  5707. /// struct A {
  5708. /// void foo() const;
  5709. /// void bar();
  5710. /// };
  5711. /// \endcode
  5712. ///
  5713. /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
  5714. AST_MATCHER(CXXMethodDecl, isConst) {
  5715. return Node.isConst();
  5716. }
  5717. /// Matches if the given method declaration declares a copy assignment
  5718. /// operator.
  5719. ///
  5720. /// Given
  5721. /// \code
  5722. /// struct A {
  5723. /// A &operator=(const A &);
  5724. /// A &operator=(A &&);
  5725. /// };
  5726. /// \endcode
  5727. ///
  5728. /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
  5729. /// the second one.
  5730. AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
  5731. return Node.isCopyAssignmentOperator();
  5732. }
  5733. /// Matches if the given method declaration declares a move assignment
  5734. /// operator.
  5735. ///
  5736. /// Given
  5737. /// \code
  5738. /// struct A {
  5739. /// A &operator=(const A &);
  5740. /// A &operator=(A &&);
  5741. /// };
  5742. /// \endcode
  5743. ///
  5744. /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
  5745. /// the first one.
  5746. AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
  5747. return Node.isMoveAssignmentOperator();
  5748. }
  5749. /// Matches if the given method declaration overrides another method.
  5750. ///
  5751. /// Given
  5752. /// \code
  5753. /// class A {
  5754. /// public:
  5755. /// virtual void x();
  5756. /// };
  5757. /// class B : public A {
  5758. /// public:
  5759. /// virtual void x();
  5760. /// };
  5761. /// \endcode
  5762. /// matches B::x
  5763. AST_MATCHER(CXXMethodDecl, isOverride) {
  5764. return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
  5765. }
  5766. /// Matches method declarations that are user-provided.
  5767. ///
  5768. /// Given
  5769. /// \code
  5770. /// struct S {
  5771. /// S(); // #1
  5772. /// S(const S &) = default; // #2
  5773. /// S(S &&) = delete; // #3
  5774. /// };
  5775. /// \endcode
  5776. /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
  5777. AST_MATCHER(CXXMethodDecl, isUserProvided) {
  5778. return Node.isUserProvided();
  5779. }
  5780. /// Matches member expressions that are called with '->' as opposed
  5781. /// to '.'.
  5782. ///
  5783. /// Member calls on the implicit this pointer match as called with '->'.
  5784. ///
  5785. /// Given
  5786. /// \code
  5787. /// class Y {
  5788. /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
  5789. /// template <class T> void f() { this->f<T>(); f<T>(); }
  5790. /// int a;
  5791. /// static int b;
  5792. /// };
  5793. /// template <class T>
  5794. /// class Z {
  5795. /// void x() { this->m; }
  5796. /// };
  5797. /// \endcode
  5798. /// memberExpr(isArrow())
  5799. /// matches this->x, x, y.x, a, this->b
  5800. /// cxxDependentScopeMemberExpr(isArrow())
  5801. /// matches this->m
  5802. /// unresolvedMemberExpr(isArrow())
  5803. /// matches this->f<T>, f<T>
  5804. AST_POLYMORPHIC_MATCHER(
  5805. isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
  5806. CXXDependentScopeMemberExpr)) {
  5807. return Node.isArrow();
  5808. }
  5809. /// Matches QualType nodes that are of integer type.
  5810. ///
  5811. /// Given
  5812. /// \code
  5813. /// void a(int);
  5814. /// void b(long);
  5815. /// void c(double);
  5816. /// \endcode
  5817. /// functionDecl(hasAnyParameter(hasType(isInteger())))
  5818. /// matches "a(int)", "b(long)", but not "c(double)".
  5819. AST_MATCHER(QualType, isInteger) {
  5820. return Node->isIntegerType();
  5821. }
  5822. /// Matches QualType nodes that are of unsigned integer type.
  5823. ///
  5824. /// Given
  5825. /// \code
  5826. /// void a(int);
  5827. /// void b(unsigned long);
  5828. /// void c(double);
  5829. /// \endcode
  5830. /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
  5831. /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
  5832. AST_MATCHER(QualType, isUnsignedInteger) {
  5833. return Node->isUnsignedIntegerType();
  5834. }
  5835. /// Matches QualType nodes that are of signed integer type.
  5836. ///
  5837. /// Given
  5838. /// \code
  5839. /// void a(int);
  5840. /// void b(unsigned long);
  5841. /// void c(double);
  5842. /// \endcode
  5843. /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
  5844. /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
  5845. AST_MATCHER(QualType, isSignedInteger) {
  5846. return Node->isSignedIntegerType();
  5847. }
  5848. /// Matches QualType nodes that are of character type.
  5849. ///
  5850. /// Given
  5851. /// \code
  5852. /// void a(char);
  5853. /// void b(wchar_t);
  5854. /// void c(double);
  5855. /// \endcode
  5856. /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
  5857. /// matches "a(char)", "b(wchar_t)", but not "c(double)".
  5858. AST_MATCHER(QualType, isAnyCharacter) {
  5859. return Node->isAnyCharacterType();
  5860. }
  5861. /// Matches QualType nodes that are of any pointer type; this includes
  5862. /// the Objective-C object pointer type, which is different despite being
  5863. /// syntactically similar.
  5864. ///
  5865. /// Given
  5866. /// \code
  5867. /// int *i = nullptr;
  5868. ///
  5869. /// @interface Foo
  5870. /// @end
  5871. /// Foo *f;
  5872. ///
  5873. /// int j;
  5874. /// \endcode
  5875. /// varDecl(hasType(isAnyPointer()))
  5876. /// matches "int *i" and "Foo *f", but not "int j".
  5877. AST_MATCHER(QualType, isAnyPointer) {
  5878. return Node->isAnyPointerType();
  5879. }
  5880. /// Matches QualType nodes that are const-qualified, i.e., that
  5881. /// include "top-level" const.
  5882. ///
  5883. /// Given
  5884. /// \code
  5885. /// void a(int);
  5886. /// void b(int const);
  5887. /// void c(const int);
  5888. /// void d(const int*);
  5889. /// void e(int const) {};
  5890. /// \endcode
  5891. /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
  5892. /// matches "void b(int const)", "void c(const int)" and
  5893. /// "void e(int const) {}". It does not match d as there
  5894. /// is no top-level const on the parameter type "const int *".
  5895. AST_MATCHER(QualType, isConstQualified) {
  5896. return Node.isConstQualified();
  5897. }
  5898. /// Matches QualType nodes that are volatile-qualified, i.e., that
  5899. /// include "top-level" volatile.
  5900. ///
  5901. /// Given
  5902. /// \code
  5903. /// void a(int);
  5904. /// void b(int volatile);
  5905. /// void c(volatile int);
  5906. /// void d(volatile int*);
  5907. /// void e(int volatile) {};
  5908. /// \endcode
  5909. /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
  5910. /// matches "void b(int volatile)", "void c(volatile int)" and
  5911. /// "void e(int volatile) {}". It does not match d as there
  5912. /// is no top-level volatile on the parameter type "volatile int *".
  5913. AST_MATCHER(QualType, isVolatileQualified) {
  5914. return Node.isVolatileQualified();
  5915. }
  5916. /// Matches QualType nodes that have local CV-qualifiers attached to
  5917. /// the node, not hidden within a typedef.
  5918. ///
  5919. /// Given
  5920. /// \code
  5921. /// typedef const int const_int;
  5922. /// const_int i;
  5923. /// int *const j;
  5924. /// int *volatile k;
  5925. /// int m;
  5926. /// \endcode
  5927. /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
  5928. /// \c i is const-qualified but the qualifier is not local.
  5929. AST_MATCHER(QualType, hasLocalQualifiers) {
  5930. return Node.hasLocalQualifiers();
  5931. }
  5932. /// Matches a member expression where the member is matched by a
  5933. /// given matcher.
  5934. ///
  5935. /// Given
  5936. /// \code
  5937. /// struct { int first, second; } first, second;
  5938. /// int i(second.first);
  5939. /// int j(first.second);
  5940. /// \endcode
  5941. /// memberExpr(member(hasName("first")))
  5942. /// matches second.first
  5943. /// but not first.second (because the member name there is "second").
  5944. AST_MATCHER_P(MemberExpr, member,
  5945. internal::Matcher<ValueDecl>, InnerMatcher) {
  5946. return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
  5947. }
  5948. /// Matches a member expression where the object expression is matched by a
  5949. /// given matcher. Implicit object expressions are included; that is, it matches
  5950. /// use of implicit `this`.
  5951. ///
  5952. /// Given
  5953. /// \code
  5954. /// struct X {
  5955. /// int m;
  5956. /// int f(X x) { x.m; return m; }
  5957. /// };
  5958. /// \endcode
  5959. /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
  5960. /// matches `x.m`, but not `m`; however,
  5961. /// memberExpr(hasObjectExpression(hasType(pointsTo(
  5962. // cxxRecordDecl(hasName("X"))))))
  5963. /// matches `m` (aka. `this->m`), but not `x.m`.
  5964. AST_POLYMORPHIC_MATCHER_P(
  5965. hasObjectExpression,
  5966. AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
  5967. CXXDependentScopeMemberExpr),
  5968. internal::Matcher<Expr>, InnerMatcher) {
  5969. if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
  5970. if (E->isImplicitAccess())
  5971. return false;
  5972. if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
  5973. if (E->isImplicitAccess())
  5974. return false;
  5975. return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
  5976. }
  5977. /// Matches any using shadow declaration.
  5978. ///
  5979. /// Given
  5980. /// \code
  5981. /// namespace X { void b(); }
  5982. /// using X::b;
  5983. /// \endcode
  5984. /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
  5985. /// matches \code using X::b \endcode
  5986. AST_MATCHER_P(BaseUsingDecl, hasAnyUsingShadowDecl,
  5987. internal::Matcher<UsingShadowDecl>, InnerMatcher) {
  5988. return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
  5989. Node.shadow_end(), Finder,
  5990. Builder) != Node.shadow_end();
  5991. }
  5992. /// Matches a using shadow declaration where the target declaration is
  5993. /// matched by the given matcher.
  5994. ///
  5995. /// Given
  5996. /// \code
  5997. /// namespace X { int a; void b(); }
  5998. /// using X::a;
  5999. /// using X::b;
  6000. /// \endcode
  6001. /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
  6002. /// matches \code using X::b \endcode
  6003. /// but not \code using X::a \endcode
  6004. AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
  6005. internal::Matcher<NamedDecl>, InnerMatcher) {
  6006. return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
  6007. }
  6008. /// Matches template instantiations of function, class, or static
  6009. /// member variable template instantiations.
  6010. ///
  6011. /// Given
  6012. /// \code
  6013. /// template <typename T> class X {}; class A {}; X<A> x;
  6014. /// \endcode
  6015. /// or
  6016. /// \code
  6017. /// template <typename T> class X {}; class A {}; template class X<A>;
  6018. /// \endcode
  6019. /// or
  6020. /// \code
  6021. /// template <typename T> class X {}; class A {}; extern template class X<A>;
  6022. /// \endcode
  6023. /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
  6024. /// matches the template instantiation of X<A>.
  6025. ///
  6026. /// But given
  6027. /// \code
  6028. /// template <typename T> class X {}; class A {};
  6029. /// template <> class X<A> {}; X<A> x;
  6030. /// \endcode
  6031. /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
  6032. /// does not match, as X<A> is an explicit template specialization.
  6033. ///
  6034. /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
  6035. AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
  6036. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
  6037. CXXRecordDecl)) {
  6038. return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
  6039. Node.getTemplateSpecializationKind() ==
  6040. TSK_ExplicitInstantiationDefinition ||
  6041. Node.getTemplateSpecializationKind() ==
  6042. TSK_ExplicitInstantiationDeclaration);
  6043. }
  6044. /// Matches declarations that are template instantiations or are inside
  6045. /// template instantiations.
  6046. ///
  6047. /// Given
  6048. /// \code
  6049. /// template<typename T> void A(T t) { T i; }
  6050. /// A(0);
  6051. /// A(0U);
  6052. /// \endcode
  6053. /// functionDecl(isInstantiated())
  6054. /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
  6055. AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
  6056. auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
  6057. functionDecl(isTemplateInstantiation())));
  6058. return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
  6059. }
  6060. /// Matches statements inside of a template instantiation.
  6061. ///
  6062. /// Given
  6063. /// \code
  6064. /// int j;
  6065. /// template<typename T> void A(T t) { T i; j += 42;}
  6066. /// A(0);
  6067. /// A(0U);
  6068. /// \endcode
  6069. /// declStmt(isInTemplateInstantiation())
  6070. /// matches 'int i;' and 'unsigned i'.
  6071. /// unless(stmt(isInTemplateInstantiation()))
  6072. /// will NOT match j += 42; as it's shared between the template definition and
  6073. /// instantiation.
  6074. AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
  6075. return stmt(
  6076. hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
  6077. functionDecl(isTemplateInstantiation())))));
  6078. }
  6079. /// Matches explicit template specializations of function, class, or
  6080. /// static member variable template instantiations.
  6081. ///
  6082. /// Given
  6083. /// \code
  6084. /// template<typename T> void A(T t) { }
  6085. /// template<> void A(int N) { }
  6086. /// \endcode
  6087. /// functionDecl(isExplicitTemplateSpecialization())
  6088. /// matches the specialization A<int>().
  6089. ///
  6090. /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
  6091. AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
  6092. AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
  6093. CXXRecordDecl)) {
  6094. return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
  6095. }
  6096. /// Matches \c TypeLocs for which the given inner
  6097. /// QualType-matcher matches.
  6098. AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
  6099. internal::Matcher<QualType>, InnerMatcher, 0) {
  6100. return internal::BindableMatcher<TypeLoc>(
  6101. new internal::TypeLocTypeMatcher(InnerMatcher));
  6102. }
  6103. /// Matches `QualifiedTypeLoc`s in the clang AST.
  6104. ///
  6105. /// Given
  6106. /// \code
  6107. /// const int x = 0;
  6108. /// \endcode
  6109. /// qualifiedTypeLoc()
  6110. /// matches `const int`.
  6111. extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, QualifiedTypeLoc>
  6112. qualifiedTypeLoc;
  6113. /// Matches `QualifiedTypeLoc`s that have an unqualified `TypeLoc` matching
  6114. /// `InnerMatcher`.
  6115. ///
  6116. /// Given
  6117. /// \code
  6118. /// int* const x;
  6119. /// const int y;
  6120. /// \endcode
  6121. /// qualifiedTypeLoc(hasUnqualifiedLoc(pointerTypeLoc()))
  6122. /// matches the `TypeLoc` of the variable declaration of `x`, but not `y`.
  6123. AST_MATCHER_P(QualifiedTypeLoc, hasUnqualifiedLoc, internal::Matcher<TypeLoc>,
  6124. InnerMatcher) {
  6125. return InnerMatcher.matches(Node.getUnqualifiedLoc(), Finder, Builder);
  6126. }
  6127. /// Matches a function declared with the specified return `TypeLoc`.
  6128. ///
  6129. /// Given
  6130. /// \code
  6131. /// int f() { return 5; }
  6132. /// void g() {}
  6133. /// \endcode
  6134. /// functionDecl(hasReturnTypeLoc(loc(asString("int"))))
  6135. /// matches the declaration of `f`, but not `g`.
  6136. AST_MATCHER_P(FunctionDecl, hasReturnTypeLoc, internal::Matcher<TypeLoc>,
  6137. ReturnMatcher) {
  6138. auto Loc = Node.getFunctionTypeLoc();
  6139. return Loc && ReturnMatcher.matches(Loc.getReturnLoc(), Finder, Builder);
  6140. }
  6141. /// Matches pointer `TypeLoc`s.
  6142. ///
  6143. /// Given
  6144. /// \code
  6145. /// int* x;
  6146. /// \endcode
  6147. /// pointerTypeLoc()
  6148. /// matches `int*`.
  6149. extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, PointerTypeLoc>
  6150. pointerTypeLoc;
  6151. /// Matches pointer `TypeLoc`s that have a pointee `TypeLoc` matching
  6152. /// `PointeeMatcher`.
  6153. ///
  6154. /// Given
  6155. /// \code
  6156. /// int* x;
  6157. /// \endcode
  6158. /// pointerTypeLoc(hasPointeeLoc(loc(asString("int"))))
  6159. /// matches `int*`.
  6160. AST_MATCHER_P(PointerTypeLoc, hasPointeeLoc, internal::Matcher<TypeLoc>,
  6161. PointeeMatcher) {
  6162. return PointeeMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
  6163. }
  6164. /// Matches reference `TypeLoc`s.
  6165. ///
  6166. /// Given
  6167. /// \code
  6168. /// int x = 3;
  6169. /// int& l = x;
  6170. /// int&& r = 3;
  6171. /// \endcode
  6172. /// referenceTypeLoc()
  6173. /// matches `int&` and `int&&`.
  6174. extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ReferenceTypeLoc>
  6175. referenceTypeLoc;
  6176. /// Matches reference `TypeLoc`s that have a referent `TypeLoc` matching
  6177. /// `ReferentMatcher`.
  6178. ///
  6179. /// Given
  6180. /// \code
  6181. /// int x = 3;
  6182. /// int& xx = x;
  6183. /// \endcode
  6184. /// referenceTypeLoc(hasReferentLoc(loc(asString("int"))))
  6185. /// matches `int&`.
  6186. AST_MATCHER_P(ReferenceTypeLoc, hasReferentLoc, internal::Matcher<TypeLoc>,
  6187. ReferentMatcher) {
  6188. return ReferentMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
  6189. }
  6190. /// Matches template specialization `TypeLoc`s.
  6191. ///
  6192. /// Given
  6193. /// \code
  6194. /// template <typename T> class C {};
  6195. /// C<char> var;
  6196. /// \endcode
  6197. /// varDecl(hasTypeLoc(templateSpecializationTypeLoc(typeLoc())))
  6198. /// matches `C<char> var`.
  6199. extern const internal::VariadicDynCastAllOfMatcher<
  6200. TypeLoc, TemplateSpecializationTypeLoc>
  6201. templateSpecializationTypeLoc;
  6202. /// Matches template specialization `TypeLoc`s that have at least one
  6203. /// `TemplateArgumentLoc` matching the given `InnerMatcher`.
  6204. ///
  6205. /// Given
  6206. /// \code
  6207. /// template<typename T> class A {};
  6208. /// A<int> a;
  6209. /// \endcode
  6210. /// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasAnyTemplateArgumentLoc(
  6211. /// hasTypeLoc(loc(asString("int")))))))
  6212. /// matches `A<int> a`.
  6213. AST_MATCHER_P(TemplateSpecializationTypeLoc, hasAnyTemplateArgumentLoc,
  6214. internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
  6215. for (unsigned Index = 0, N = Node.getNumArgs(); Index < N; ++Index) {
  6216. clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
  6217. if (InnerMatcher.matches(Node.getArgLoc(Index), Finder, &Result)) {
  6218. *Builder = std::move(Result);
  6219. return true;
  6220. }
  6221. }
  6222. return false;
  6223. }
  6224. /// Matches template specialization `TypeLoc`s where the n'th
  6225. /// `TemplateArgumentLoc` matches the given `InnerMatcher`.
  6226. ///
  6227. /// Given
  6228. /// \code
  6229. /// template<typename T, typename U> class A {};
  6230. /// A<double, int> b;
  6231. /// A<int, double> c;
  6232. /// \endcode
  6233. /// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasTemplateArgumentLoc(0,
  6234. /// hasTypeLoc(loc(asString("double")))))))
  6235. /// matches `A<double, int> b`, but not `A<int, double> c`.
  6236. AST_POLYMORPHIC_MATCHER_P2(
  6237. hasTemplateArgumentLoc,
  6238. AST_POLYMORPHIC_SUPPORTED_TYPES(DeclRefExpr, TemplateSpecializationTypeLoc),
  6239. unsigned, Index, internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
  6240. return internal::MatchTemplateArgLocAt(Node, Index, InnerMatcher, Finder,
  6241. Builder);
  6242. }
  6243. /// Matches C or C++ elaborated `TypeLoc`s.
  6244. ///
  6245. /// Given
  6246. /// \code
  6247. /// struct s {};
  6248. /// struct s ss;
  6249. /// \endcode
  6250. /// elaboratedTypeLoc()
  6251. /// matches the `TypeLoc` of the variable declaration of `ss`.
  6252. extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ElaboratedTypeLoc>
  6253. elaboratedTypeLoc;
  6254. /// Matches elaborated `TypeLoc`s that have a named `TypeLoc` matching
  6255. /// `InnerMatcher`.
  6256. ///
  6257. /// Given
  6258. /// \code
  6259. /// template <typename T>
  6260. /// class C {};
  6261. /// class C<int> c;
  6262. ///
  6263. /// class D {};
  6264. /// class D d;
  6265. /// \endcode
  6266. /// elaboratedTypeLoc(hasNamedTypeLoc(templateSpecializationTypeLoc()));
  6267. /// matches the `TypeLoc` of the variable declaration of `c`, but not `d`.
  6268. AST_MATCHER_P(ElaboratedTypeLoc, hasNamedTypeLoc, internal::Matcher<TypeLoc>,
  6269. InnerMatcher) {
  6270. return InnerMatcher.matches(Node.getNamedTypeLoc(), Finder, Builder);
  6271. }
  6272. /// Matches type \c bool.
  6273. ///
  6274. /// Given
  6275. /// \code
  6276. /// struct S { bool func(); };
  6277. /// \endcode
  6278. /// functionDecl(returns(booleanType()))
  6279. /// matches "bool func();"
  6280. AST_MATCHER(Type, booleanType) {
  6281. return Node.isBooleanType();
  6282. }
  6283. /// Matches type \c void.
  6284. ///
  6285. /// Given
  6286. /// \code
  6287. /// struct S { void func(); };
  6288. /// \endcode
  6289. /// functionDecl(returns(voidType()))
  6290. /// matches "void func();"
  6291. AST_MATCHER(Type, voidType) {
  6292. return Node.isVoidType();
  6293. }
  6294. template <typename NodeType>
  6295. using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
  6296. /// Matches builtin Types.
  6297. ///
  6298. /// Given
  6299. /// \code
  6300. /// struct A {};
  6301. /// A a;
  6302. /// int b;
  6303. /// float c;
  6304. /// bool d;
  6305. /// \endcode
  6306. /// builtinType()
  6307. /// matches "int b", "float c" and "bool d"
  6308. extern const AstTypeMatcher<BuiltinType> builtinType;
  6309. /// Matches all kinds of arrays.
  6310. ///
  6311. /// Given
  6312. /// \code
  6313. /// int a[] = { 2, 3 };
  6314. /// int b[4];
  6315. /// void f() { int c[a[0]]; }
  6316. /// \endcode
  6317. /// arrayType()
  6318. /// matches "int a[]", "int b[4]" and "int c[a[0]]";
  6319. extern const AstTypeMatcher<ArrayType> arrayType;
  6320. /// Matches C99 complex types.
  6321. ///
  6322. /// Given
  6323. /// \code
  6324. /// _Complex float f;
  6325. /// \endcode
  6326. /// complexType()
  6327. /// matches "_Complex float f"
  6328. extern const AstTypeMatcher<ComplexType> complexType;
  6329. /// Matches any real floating-point type (float, double, long double).
  6330. ///
  6331. /// Given
  6332. /// \code
  6333. /// int i;
  6334. /// float f;
  6335. /// \endcode
  6336. /// realFloatingPointType()
  6337. /// matches "float f" but not "int i"
  6338. AST_MATCHER(Type, realFloatingPointType) {
  6339. return Node.isRealFloatingType();
  6340. }
  6341. /// Matches arrays and C99 complex types that have a specific element
  6342. /// type.
  6343. ///
  6344. /// Given
  6345. /// \code
  6346. /// struct A {};
  6347. /// A a[7];
  6348. /// int b[7];
  6349. /// \endcode
  6350. /// arrayType(hasElementType(builtinType()))
  6351. /// matches "int b[7]"
  6352. ///
  6353. /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
  6354. AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
  6355. AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
  6356. ComplexType));
  6357. /// Matches C arrays with a specified constant size.
  6358. ///
  6359. /// Given
  6360. /// \code
  6361. /// void() {
  6362. /// int a[2];
  6363. /// int b[] = { 2, 3 };
  6364. /// int c[b[0]];
  6365. /// }
  6366. /// \endcode
  6367. /// constantArrayType()
  6368. /// matches "int a[2]"
  6369. extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
  6370. /// Matches nodes that have the specified size.
  6371. ///
  6372. /// Given
  6373. /// \code
  6374. /// int a[42];
  6375. /// int b[2 * 21];
  6376. /// int c[41], d[43];
  6377. /// char *s = "abcd";
  6378. /// wchar_t *ws = L"abcd";
  6379. /// char *w = "a";
  6380. /// \endcode
  6381. /// constantArrayType(hasSize(42))
  6382. /// matches "int a[42]" and "int b[2 * 21]"
  6383. /// stringLiteral(hasSize(4))
  6384. /// matches "abcd", L"abcd"
  6385. AST_POLYMORPHIC_MATCHER_P(hasSize,
  6386. AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
  6387. StringLiteral),
  6388. unsigned, N) {
  6389. return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
  6390. }
  6391. /// Matches C++ arrays whose size is a value-dependent expression.
  6392. ///
  6393. /// Given
  6394. /// \code
  6395. /// template<typename T, int Size>
  6396. /// class array {
  6397. /// T data[Size];
  6398. /// };
  6399. /// \endcode
  6400. /// dependentSizedArrayType
  6401. /// matches "T data[Size]"
  6402. extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
  6403. /// Matches C arrays with unspecified size.
  6404. ///
  6405. /// Given
  6406. /// \code
  6407. /// int a[] = { 2, 3 };
  6408. /// int b[42];
  6409. /// void f(int c[]) { int d[a[0]]; };
  6410. /// \endcode
  6411. /// incompleteArrayType()
  6412. /// matches "int a[]" and "int c[]"
  6413. extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
  6414. /// Matches C arrays with a specified size that is not an
  6415. /// integer-constant-expression.
  6416. ///
  6417. /// Given
  6418. /// \code
  6419. /// void f() {
  6420. /// int a[] = { 2, 3 }
  6421. /// int b[42];
  6422. /// int c[a[0]];
  6423. /// }
  6424. /// \endcode
  6425. /// variableArrayType()
  6426. /// matches "int c[a[0]]"
  6427. extern const AstTypeMatcher<VariableArrayType> variableArrayType;
  6428. /// Matches \c VariableArrayType nodes that have a specific size
  6429. /// expression.
  6430. ///
  6431. /// Given
  6432. /// \code
  6433. /// void f(int b) {
  6434. /// int a[b];
  6435. /// }
  6436. /// \endcode
  6437. /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
  6438. /// varDecl(hasName("b")))))))
  6439. /// matches "int a[b]"
  6440. AST_MATCHER_P(VariableArrayType, hasSizeExpr,
  6441. internal::Matcher<Expr>, InnerMatcher) {
  6442. return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
  6443. }
  6444. /// Matches atomic types.
  6445. ///
  6446. /// Given
  6447. /// \code
  6448. /// _Atomic(int) i;
  6449. /// \endcode
  6450. /// atomicType()
  6451. /// matches "_Atomic(int) i"
  6452. extern const AstTypeMatcher<AtomicType> atomicType;
  6453. /// Matches atomic types with a specific value type.
  6454. ///
  6455. /// Given
  6456. /// \code
  6457. /// _Atomic(int) i;
  6458. /// _Atomic(float) f;
  6459. /// \endcode
  6460. /// atomicType(hasValueType(isInteger()))
  6461. /// matches "_Atomic(int) i"
  6462. ///
  6463. /// Usable as: Matcher<AtomicType>
  6464. AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
  6465. AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
  6466. /// Matches types nodes representing C++11 auto types.
  6467. ///
  6468. /// Given:
  6469. /// \code
  6470. /// auto n = 4;
  6471. /// int v[] = { 2, 3 }
  6472. /// for (auto i : v) { }
  6473. /// \endcode
  6474. /// autoType()
  6475. /// matches "auto n" and "auto i"
  6476. extern const AstTypeMatcher<AutoType> autoType;
  6477. /// Matches types nodes representing C++11 decltype(<expr>) types.
  6478. ///
  6479. /// Given:
  6480. /// \code
  6481. /// short i = 1;
  6482. /// int j = 42;
  6483. /// decltype(i + j) result = i + j;
  6484. /// \endcode
  6485. /// decltypeType()
  6486. /// matches "decltype(i + j)"
  6487. extern const AstTypeMatcher<DecltypeType> decltypeType;
  6488. /// Matches \c AutoType nodes where the deduced type is a specific type.
  6489. ///
  6490. /// Note: There is no \c TypeLoc for the deduced type and thus no
  6491. /// \c getDeducedLoc() matcher.
  6492. ///
  6493. /// Given
  6494. /// \code
  6495. /// auto a = 1;
  6496. /// auto b = 2.0;
  6497. /// \endcode
  6498. /// autoType(hasDeducedType(isInteger()))
  6499. /// matches "auto a"
  6500. ///
  6501. /// Usable as: Matcher<AutoType>
  6502. AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
  6503. AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
  6504. /// Matches \c DecltypeType or \c UsingType nodes to find the underlying type.
  6505. ///
  6506. /// Given
  6507. /// \code
  6508. /// decltype(1) a = 1;
  6509. /// decltype(2.0) b = 2.0;
  6510. /// \endcode
  6511. /// decltypeType(hasUnderlyingType(isInteger()))
  6512. /// matches the type of "a"
  6513. ///
  6514. /// Usable as: Matcher<DecltypeType>, Matcher<UsingType>
  6515. AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
  6516. AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType,
  6517. UsingType));
  6518. /// Matches \c FunctionType nodes.
  6519. ///
  6520. /// Given
  6521. /// \code
  6522. /// int (*f)(int);
  6523. /// void g();
  6524. /// \endcode
  6525. /// functionType()
  6526. /// matches "int (*f)(int)" and the type of "g".
  6527. extern const AstTypeMatcher<FunctionType> functionType;
  6528. /// Matches \c FunctionProtoType nodes.
  6529. ///
  6530. /// Given
  6531. /// \code
  6532. /// int (*f)(int);
  6533. /// void g();
  6534. /// \endcode
  6535. /// functionProtoType()
  6536. /// matches "int (*f)(int)" and the type of "g" in C++ mode.
  6537. /// In C mode, "g" is not matched because it does not contain a prototype.
  6538. extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
  6539. /// Matches \c ParenType nodes.
  6540. ///
  6541. /// Given
  6542. /// \code
  6543. /// int (*ptr_to_array)[4];
  6544. /// int *array_of_ptrs[4];
  6545. /// \endcode
  6546. ///
  6547. /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
  6548. /// \c array_of_ptrs.
  6549. extern const AstTypeMatcher<ParenType> parenType;
  6550. /// Matches \c ParenType nodes where the inner type is a specific type.
  6551. ///
  6552. /// Given
  6553. /// \code
  6554. /// int (*ptr_to_array)[4];
  6555. /// int (*ptr_to_func)(int);
  6556. /// \endcode
  6557. ///
  6558. /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
  6559. /// \c ptr_to_func but not \c ptr_to_array.
  6560. ///
  6561. /// Usable as: Matcher<ParenType>
  6562. AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
  6563. AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
  6564. /// Matches block pointer types, i.e. types syntactically represented as
  6565. /// "void (^)(int)".
  6566. ///
  6567. /// The \c pointee is always required to be a \c FunctionType.
  6568. extern const AstTypeMatcher<BlockPointerType> blockPointerType;
  6569. /// Matches member pointer types.
  6570. /// Given
  6571. /// \code
  6572. /// struct A { int i; }
  6573. /// A::* ptr = A::i;
  6574. /// \endcode
  6575. /// memberPointerType()
  6576. /// matches "A::* ptr"
  6577. extern const AstTypeMatcher<MemberPointerType> memberPointerType;
  6578. /// Matches pointer types, but does not match Objective-C object pointer
  6579. /// types.
  6580. ///
  6581. /// Given
  6582. /// \code
  6583. /// int *a;
  6584. /// int &b = *a;
  6585. /// int c = 5;
  6586. ///
  6587. /// @interface Foo
  6588. /// @end
  6589. /// Foo *f;
  6590. /// \endcode
  6591. /// pointerType()
  6592. /// matches "int *a", but does not match "Foo *f".
  6593. extern const AstTypeMatcher<PointerType> pointerType;
  6594. /// Matches an Objective-C object pointer type, which is different from
  6595. /// a pointer type, despite being syntactically similar.
  6596. ///
  6597. /// Given
  6598. /// \code
  6599. /// int *a;
  6600. ///
  6601. /// @interface Foo
  6602. /// @end
  6603. /// Foo *f;
  6604. /// \endcode
  6605. /// pointerType()
  6606. /// matches "Foo *f", but does not match "int *a".
  6607. extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
  6608. /// Matches both lvalue and rvalue reference types.
  6609. ///
  6610. /// Given
  6611. /// \code
  6612. /// int *a;
  6613. /// int &b = *a;
  6614. /// int &&c = 1;
  6615. /// auto &d = b;
  6616. /// auto &&e = c;
  6617. /// auto &&f = 2;
  6618. /// int g = 5;
  6619. /// \endcode
  6620. ///
  6621. /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
  6622. extern const AstTypeMatcher<ReferenceType> referenceType;
  6623. /// Matches lvalue reference types.
  6624. ///
  6625. /// Given:
  6626. /// \code
  6627. /// int *a;
  6628. /// int &b = *a;
  6629. /// int &&c = 1;
  6630. /// auto &d = b;
  6631. /// auto &&e = c;
  6632. /// auto &&f = 2;
  6633. /// int g = 5;
  6634. /// \endcode
  6635. ///
  6636. /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
  6637. /// matched since the type is deduced as int& by reference collapsing rules.
  6638. extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
  6639. /// Matches rvalue reference types.
  6640. ///
  6641. /// Given:
  6642. /// \code
  6643. /// int *a;
  6644. /// int &b = *a;
  6645. /// int &&c = 1;
  6646. /// auto &d = b;
  6647. /// auto &&e = c;
  6648. /// auto &&f = 2;
  6649. /// int g = 5;
  6650. /// \endcode
  6651. ///
  6652. /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
  6653. /// matched as it is deduced to int& by reference collapsing rules.
  6654. extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
  6655. /// Narrows PointerType (and similar) matchers to those where the
  6656. /// \c pointee matches a given matcher.
  6657. ///
  6658. /// Given
  6659. /// \code
  6660. /// int *a;
  6661. /// int const *b;
  6662. /// float const *f;
  6663. /// \endcode
  6664. /// pointerType(pointee(isConstQualified(), isInteger()))
  6665. /// matches "int const *b"
  6666. ///
  6667. /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
  6668. /// Matcher<PointerType>, Matcher<ReferenceType>
  6669. AST_TYPELOC_TRAVERSE_MATCHER_DECL(
  6670. pointee, getPointee,
  6671. AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
  6672. PointerType, ReferenceType));
  6673. /// Matches typedef types.
  6674. ///
  6675. /// Given
  6676. /// \code
  6677. /// typedef int X;
  6678. /// \endcode
  6679. /// typedefType()
  6680. /// matches "typedef int X"
  6681. extern const AstTypeMatcher<TypedefType> typedefType;
  6682. /// Matches enum types.
  6683. ///
  6684. /// Given
  6685. /// \code
  6686. /// enum C { Green };
  6687. /// enum class S { Red };
  6688. ///
  6689. /// C c;
  6690. /// S s;
  6691. /// \endcode
  6692. //
  6693. /// \c enumType() matches the type of the variable declarations of both \c c and
  6694. /// \c s.
  6695. extern const AstTypeMatcher<EnumType> enumType;
  6696. /// Matches template specialization types.
  6697. ///
  6698. /// Given
  6699. /// \code
  6700. /// template <typename T>
  6701. /// class C { };
  6702. ///
  6703. /// template class C<int>; // A
  6704. /// C<char> var; // B
  6705. /// \endcode
  6706. ///
  6707. /// \c templateSpecializationType() matches the type of the explicit
  6708. /// instantiation in \c A and the type of the variable declaration in \c B.
  6709. extern const AstTypeMatcher<TemplateSpecializationType>
  6710. templateSpecializationType;
  6711. /// Matches C++17 deduced template specialization types, e.g. deduced class
  6712. /// template types.
  6713. ///
  6714. /// Given
  6715. /// \code
  6716. /// template <typename T>
  6717. /// class C { public: C(T); };
  6718. ///
  6719. /// C c(123);
  6720. /// \endcode
  6721. /// \c deducedTemplateSpecializationType() matches the type in the declaration
  6722. /// of the variable \c c.
  6723. extern const AstTypeMatcher<DeducedTemplateSpecializationType>
  6724. deducedTemplateSpecializationType;
  6725. /// Matches types nodes representing unary type transformations.
  6726. ///
  6727. /// Given:
  6728. /// \code
  6729. /// typedef __underlying_type(T) type;
  6730. /// \endcode
  6731. /// unaryTransformType()
  6732. /// matches "__underlying_type(T)"
  6733. extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
  6734. /// Matches record types (e.g. structs, classes).
  6735. ///
  6736. /// Given
  6737. /// \code
  6738. /// class C {};
  6739. /// struct S {};
  6740. ///
  6741. /// C c;
  6742. /// S s;
  6743. /// \endcode
  6744. ///
  6745. /// \c recordType() matches the type of the variable declarations of both \c c
  6746. /// and \c s.
  6747. extern const AstTypeMatcher<RecordType> recordType;
  6748. /// Matches tag types (record and enum types).
  6749. ///
  6750. /// Given
  6751. /// \code
  6752. /// enum E {};
  6753. /// class C {};
  6754. ///
  6755. /// E e;
  6756. /// C c;
  6757. /// \endcode
  6758. ///
  6759. /// \c tagType() matches the type of the variable declarations of both \c e
  6760. /// and \c c.
  6761. extern const AstTypeMatcher<TagType> tagType;
  6762. /// Matches types specified with an elaborated type keyword or with a
  6763. /// qualified name.
  6764. ///
  6765. /// Given
  6766. /// \code
  6767. /// namespace N {
  6768. /// namespace M {
  6769. /// class D {};
  6770. /// }
  6771. /// }
  6772. /// class C {};
  6773. ///
  6774. /// class C c;
  6775. /// N::M::D d;
  6776. /// \endcode
  6777. ///
  6778. /// \c elaboratedType() matches the type of the variable declarations of both
  6779. /// \c c and \c d.
  6780. extern const AstTypeMatcher<ElaboratedType> elaboratedType;
  6781. /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
  6782. /// matches \c InnerMatcher if the qualifier exists.
  6783. ///
  6784. /// Given
  6785. /// \code
  6786. /// namespace N {
  6787. /// namespace M {
  6788. /// class D {};
  6789. /// }
  6790. /// }
  6791. /// N::M::D d;
  6792. /// \endcode
  6793. ///
  6794. /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
  6795. /// matches the type of the variable declaration of \c d.
  6796. AST_MATCHER_P(ElaboratedType, hasQualifier,
  6797. internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
  6798. if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
  6799. return InnerMatcher.matches(*Qualifier, Finder, Builder);
  6800. return false;
  6801. }
  6802. /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
  6803. ///
  6804. /// Given
  6805. /// \code
  6806. /// namespace N {
  6807. /// namespace M {
  6808. /// class D {};
  6809. /// }
  6810. /// }
  6811. /// N::M::D d;
  6812. /// \endcode
  6813. ///
  6814. /// \c elaboratedType(namesType(recordType(
  6815. /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
  6816. /// declaration of \c d.
  6817. AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
  6818. InnerMatcher) {
  6819. return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
  6820. }
  6821. /// Matches types specified through a using declaration.
  6822. ///
  6823. /// Given
  6824. /// \code
  6825. /// namespace a { struct S {}; }
  6826. /// using a::S;
  6827. /// S s;
  6828. /// \endcode
  6829. ///
  6830. /// \c usingType() matches the type of the variable declaration of \c s.
  6831. extern const AstTypeMatcher<UsingType> usingType;
  6832. /// Matches types that represent the result of substituting a type for a
  6833. /// template type parameter.
  6834. ///
  6835. /// Given
  6836. /// \code
  6837. /// template <typename T>
  6838. /// void F(T t) {
  6839. /// int i = 1 + t;
  6840. /// }
  6841. /// \endcode
  6842. ///
  6843. /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
  6844. extern const AstTypeMatcher<SubstTemplateTypeParmType>
  6845. substTemplateTypeParmType;
  6846. /// Matches template type parameter substitutions that have a replacement
  6847. /// type that matches the provided matcher.
  6848. ///
  6849. /// Given
  6850. /// \code
  6851. /// template <typename T>
  6852. /// double F(T t);
  6853. /// int i;
  6854. /// double j = F(i);
  6855. /// \endcode
  6856. ///
  6857. /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
  6858. AST_TYPE_TRAVERSE_MATCHER(
  6859. hasReplacementType, getReplacementType,
  6860. AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
  6861. /// Matches template type parameter types.
  6862. ///
  6863. /// Example matches T, but not int.
  6864. /// (matcher = templateTypeParmType())
  6865. /// \code
  6866. /// template <typename T> void f(int i);
  6867. /// \endcode
  6868. extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
  6869. /// Matches injected class name types.
  6870. ///
  6871. /// Example matches S s, but not S<T> s.
  6872. /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
  6873. /// \code
  6874. /// template <typename T> struct S {
  6875. /// void f(S s);
  6876. /// void g(S<T> s);
  6877. /// };
  6878. /// \endcode
  6879. extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
  6880. /// Matches decayed type
  6881. /// Example matches i[] in declaration of f.
  6882. /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
  6883. /// Example matches i[1].
  6884. /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
  6885. /// \code
  6886. /// void f(int i[]) {
  6887. /// i[1] = 0;
  6888. /// }
  6889. /// \endcode
  6890. extern const AstTypeMatcher<DecayedType> decayedType;
  6891. /// Matches the decayed type, whoes decayed type matches \c InnerMatcher
  6892. AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
  6893. InnerType) {
  6894. return InnerType.matches(Node.getDecayedType(), Finder, Builder);
  6895. }
  6896. /// Matches declarations whose declaration context, interpreted as a
  6897. /// Decl, matches \c InnerMatcher.
  6898. ///
  6899. /// Given
  6900. /// \code
  6901. /// namespace N {
  6902. /// namespace M {
  6903. /// class D {};
  6904. /// }
  6905. /// }
  6906. /// \endcode
  6907. ///
  6908. /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
  6909. /// declaration of \c class \c D.
  6910. AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
  6911. const DeclContext *DC = Node.getDeclContext();
  6912. if (!DC) return false;
  6913. return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
  6914. }
  6915. /// Matches nested name specifiers.
  6916. ///
  6917. /// Given
  6918. /// \code
  6919. /// namespace ns {
  6920. /// struct A { static void f(); };
  6921. /// void A::f() {}
  6922. /// void g() { A::f(); }
  6923. /// }
  6924. /// ns::A a;
  6925. /// \endcode
  6926. /// nestedNameSpecifier()
  6927. /// matches "ns::" and both "A::"
  6928. extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
  6929. nestedNameSpecifier;
  6930. /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
  6931. extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
  6932. nestedNameSpecifierLoc;
  6933. /// Matches \c NestedNameSpecifierLocs for which the given inner
  6934. /// NestedNameSpecifier-matcher matches.
  6935. AST_MATCHER_FUNCTION_P_OVERLOAD(
  6936. internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
  6937. internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
  6938. return internal::BindableMatcher<NestedNameSpecifierLoc>(
  6939. new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
  6940. InnerMatcher));
  6941. }
  6942. /// Matches nested name specifiers that specify a type matching the
  6943. /// given \c QualType matcher without qualifiers.
  6944. ///
  6945. /// Given
  6946. /// \code
  6947. /// struct A { struct B { struct C {}; }; };
  6948. /// A::B::C c;
  6949. /// \endcode
  6950. /// nestedNameSpecifier(specifiesType(
  6951. /// hasDeclaration(cxxRecordDecl(hasName("A")))
  6952. /// ))
  6953. /// matches "A::"
  6954. AST_MATCHER_P(NestedNameSpecifier, specifiesType,
  6955. internal::Matcher<QualType>, InnerMatcher) {
  6956. if (!Node.getAsType())
  6957. return false;
  6958. return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
  6959. }
  6960. /// Matches nested name specifier locs that specify a type matching the
  6961. /// given \c TypeLoc.
  6962. ///
  6963. /// Given
  6964. /// \code
  6965. /// struct A { struct B { struct C {}; }; };
  6966. /// A::B::C c;
  6967. /// \endcode
  6968. /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
  6969. /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
  6970. /// matches "A::"
  6971. AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
  6972. internal::Matcher<TypeLoc>, InnerMatcher) {
  6973. return Node && Node.getNestedNameSpecifier()->getAsType() &&
  6974. InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
  6975. }
  6976. /// Matches on the prefix of a \c NestedNameSpecifier.
  6977. ///
  6978. /// Given
  6979. /// \code
  6980. /// struct A { struct B { struct C {}; }; };
  6981. /// A::B::C c;
  6982. /// \endcode
  6983. /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
  6984. /// matches "A::"
  6985. AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
  6986. internal::Matcher<NestedNameSpecifier>, InnerMatcher,
  6987. 0) {
  6988. const NestedNameSpecifier *NextNode = Node.getPrefix();
  6989. if (!NextNode)
  6990. return false;
  6991. return InnerMatcher.matches(*NextNode, Finder, Builder);
  6992. }
  6993. /// Matches on the prefix of a \c NestedNameSpecifierLoc.
  6994. ///
  6995. /// Given
  6996. /// \code
  6997. /// struct A { struct B { struct C {}; }; };
  6998. /// A::B::C c;
  6999. /// \endcode
  7000. /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
  7001. /// matches "A::"
  7002. AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
  7003. internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
  7004. 1) {
  7005. NestedNameSpecifierLoc NextNode = Node.getPrefix();
  7006. if (!NextNode)
  7007. return false;
  7008. return InnerMatcher.matches(NextNode, Finder, Builder);
  7009. }
  7010. /// Matches nested name specifiers that specify a namespace matching the
  7011. /// given namespace matcher.
  7012. ///
  7013. /// Given
  7014. /// \code
  7015. /// namespace ns { struct A {}; }
  7016. /// ns::A a;
  7017. /// \endcode
  7018. /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
  7019. /// matches "ns::"
  7020. AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
  7021. internal::Matcher<NamespaceDecl>, InnerMatcher) {
  7022. if (!Node.getAsNamespace())
  7023. return false;
  7024. return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
  7025. }
  7026. /// Matches attributes.
  7027. /// Attributes may be attached with a variety of different syntaxes (including
  7028. /// keywords, C++11 attributes, GNU ``__attribute``` and MSVC `__declspec``,
  7029. /// and ``#pragma``s). They may also be implicit.
  7030. ///
  7031. /// Given
  7032. /// \code
  7033. /// struct [[nodiscard]] Foo{};
  7034. /// void bar(int * __attribute__((nonnull)) );
  7035. /// __declspec(noinline) void baz();
  7036. ///
  7037. /// #pragma omp declare simd
  7038. /// int min();
  7039. /// \endcode
  7040. /// attr()
  7041. /// matches "nodiscard", "nonnull", "noinline", and the whole "#pragma" line.
  7042. extern const internal::VariadicAllOfMatcher<Attr> attr;
  7043. /// Overloads for the \c equalsNode matcher.
  7044. /// FIXME: Implement for other node types.
  7045. /// @{
  7046. /// Matches if a node equals another node.
  7047. ///
  7048. /// \c Decl has pointer identity in the AST.
  7049. AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
  7050. return &Node == Other;
  7051. }
  7052. /// Matches if a node equals another node.
  7053. ///
  7054. /// \c Stmt has pointer identity in the AST.
  7055. AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
  7056. return &Node == Other;
  7057. }
  7058. /// Matches if a node equals another node.
  7059. ///
  7060. /// \c Type has pointer identity in the AST.
  7061. AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
  7062. return &Node == Other;
  7063. }
  7064. /// @}
  7065. /// Matches each case or default statement belonging to the given switch
  7066. /// statement. This matcher may produce multiple matches.
  7067. ///
  7068. /// Given
  7069. /// \code
  7070. /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
  7071. /// \endcode
  7072. /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
  7073. /// matches four times, with "c" binding each of "case 1:", "case 2:",
  7074. /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
  7075. /// "switch (1)", "switch (2)" and "switch (2)".
  7076. AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
  7077. InnerMatcher) {
  7078. BoundNodesTreeBuilder Result;
  7079. // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
  7080. // iteration order. We should use the more general iterating matchers once
  7081. // they are capable of expressing this matcher (for example, it should ignore
  7082. // case statements belonging to nested switch statements).
  7083. bool Matched = false;
  7084. for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
  7085. SC = SC->getNextSwitchCase()) {
  7086. BoundNodesTreeBuilder CaseBuilder(*Builder);
  7087. bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
  7088. if (CaseMatched) {
  7089. Matched = true;
  7090. Result.addMatch(CaseBuilder);
  7091. }
  7092. }
  7093. *Builder = std::move(Result);
  7094. return Matched;
  7095. }
  7096. /// Matches each constructor initializer in a constructor definition.
  7097. ///
  7098. /// Given
  7099. /// \code
  7100. /// class A { A() : i(42), j(42) {} int i; int j; };
  7101. /// \endcode
  7102. /// cxxConstructorDecl(forEachConstructorInitializer(
  7103. /// forField(decl().bind("x"))
  7104. /// ))
  7105. /// will trigger two matches, binding for 'i' and 'j' respectively.
  7106. AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
  7107. internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
  7108. BoundNodesTreeBuilder Result;
  7109. bool Matched = false;
  7110. for (const auto *I : Node.inits()) {
  7111. if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
  7112. continue;
  7113. BoundNodesTreeBuilder InitBuilder(*Builder);
  7114. if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
  7115. Matched = true;
  7116. Result.addMatch(InitBuilder);
  7117. }
  7118. }
  7119. *Builder = std::move(Result);
  7120. return Matched;
  7121. }
  7122. /// Matches constructor declarations that are copy constructors.
  7123. ///
  7124. /// Given
  7125. /// \code
  7126. /// struct S {
  7127. /// S(); // #1
  7128. /// S(const S &); // #2
  7129. /// S(S &&); // #3
  7130. /// };
  7131. /// \endcode
  7132. /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
  7133. AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
  7134. return Node.isCopyConstructor();
  7135. }
  7136. /// Matches constructor declarations that are move constructors.
  7137. ///
  7138. /// Given
  7139. /// \code
  7140. /// struct S {
  7141. /// S(); // #1
  7142. /// S(const S &); // #2
  7143. /// S(S &&); // #3
  7144. /// };
  7145. /// \endcode
  7146. /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
  7147. AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
  7148. return Node.isMoveConstructor();
  7149. }
  7150. /// Matches constructor declarations that are default constructors.
  7151. ///
  7152. /// Given
  7153. /// \code
  7154. /// struct S {
  7155. /// S(); // #1
  7156. /// S(const S &); // #2
  7157. /// S(S &&); // #3
  7158. /// };
  7159. /// \endcode
  7160. /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
  7161. AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
  7162. return Node.isDefaultConstructor();
  7163. }
  7164. /// Matches constructors that delegate to another constructor.
  7165. ///
  7166. /// Given
  7167. /// \code
  7168. /// struct S {
  7169. /// S(); // #1
  7170. /// S(int) {} // #2
  7171. /// S(S &&) : S() {} // #3
  7172. /// };
  7173. /// S::S() : S(0) {} // #4
  7174. /// \endcode
  7175. /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
  7176. /// #1 or #2.
  7177. AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
  7178. return Node.isDelegatingConstructor();
  7179. }
  7180. /// Matches constructor, conversion function, and deduction guide declarations
  7181. /// that have an explicit specifier if this explicit specifier is resolved to
  7182. /// true.
  7183. ///
  7184. /// Given
  7185. /// \code
  7186. /// template<bool b>
  7187. /// struct S {
  7188. /// S(int); // #1
  7189. /// explicit S(double); // #2
  7190. /// operator int(); // #3
  7191. /// explicit operator bool(); // #4
  7192. /// explicit(false) S(bool) // # 7
  7193. /// explicit(true) S(char) // # 8
  7194. /// explicit(b) S(S) // # 9
  7195. /// };
  7196. /// S(int) -> S<true> // #5
  7197. /// explicit S(double) -> S<false> // #6
  7198. /// \endcode
  7199. /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
  7200. /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
  7201. /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
  7202. AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
  7203. CXXConstructorDecl, CXXConversionDecl,
  7204. CXXDeductionGuideDecl)) {
  7205. return Node.isExplicit();
  7206. }
  7207. /// Matches the expression in an explicit specifier if present in the given
  7208. /// declaration.
  7209. ///
  7210. /// Given
  7211. /// \code
  7212. /// template<bool b>
  7213. /// struct S {
  7214. /// S(int); // #1
  7215. /// explicit S(double); // #2
  7216. /// operator int(); // #3
  7217. /// explicit operator bool(); // #4
  7218. /// explicit(false) S(bool) // # 7
  7219. /// explicit(true) S(char) // # 8
  7220. /// explicit(b) S(S) // # 9
  7221. /// };
  7222. /// S(int) -> S<true> // #5
  7223. /// explicit S(double) -> S<false> // #6
  7224. /// \endcode
  7225. /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
  7226. /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
  7227. /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
  7228. AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
  7229. InnerMatcher) {
  7230. ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
  7231. if (!ES.getExpr())
  7232. return false;
  7233. ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
  7234. return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
  7235. }
  7236. /// Matches functions, variables and namespace declarations that are marked with
  7237. /// the inline keyword.
  7238. ///
  7239. /// Given
  7240. /// \code
  7241. /// inline void f();
  7242. /// void g();
  7243. /// namespace n {
  7244. /// inline namespace m {}
  7245. /// }
  7246. /// inline int Foo = 5;
  7247. /// \endcode
  7248. /// functionDecl(isInline()) will match ::f().
  7249. /// namespaceDecl(isInline()) will match n::m.
  7250. /// varDecl(isInline()) will match Foo;
  7251. AST_POLYMORPHIC_MATCHER(isInline, AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
  7252. FunctionDecl,
  7253. VarDecl)) {
  7254. // This is required because the spelling of the function used to determine
  7255. // whether inline is specified or not differs between the polymorphic types.
  7256. if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
  7257. return FD->isInlineSpecified();
  7258. if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
  7259. return NSD->isInline();
  7260. if (const auto *VD = dyn_cast<VarDecl>(&Node))
  7261. return VD->isInline();
  7262. llvm_unreachable("Not a valid polymorphic type");
  7263. }
  7264. /// Matches anonymous namespace declarations.
  7265. ///
  7266. /// Given
  7267. /// \code
  7268. /// namespace n {
  7269. /// namespace {} // #1
  7270. /// }
  7271. /// \endcode
  7272. /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
  7273. AST_MATCHER(NamespaceDecl, isAnonymous) {
  7274. return Node.isAnonymousNamespace();
  7275. }
  7276. /// Matches declarations in the namespace `std`, but not in nested namespaces.
  7277. ///
  7278. /// Given
  7279. /// \code
  7280. /// class vector {};
  7281. /// namespace foo {
  7282. /// class vector {};
  7283. /// namespace std {
  7284. /// class vector {};
  7285. /// }
  7286. /// }
  7287. /// namespace std {
  7288. /// inline namespace __1 {
  7289. /// class vector {}; // #1
  7290. /// namespace experimental {
  7291. /// class vector {};
  7292. /// }
  7293. /// }
  7294. /// }
  7295. /// \endcode
  7296. /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
  7297. AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
  7298. /// Matches declarations in an anonymous namespace.
  7299. ///
  7300. /// Given
  7301. /// \code
  7302. /// class vector {};
  7303. /// namespace foo {
  7304. /// class vector {};
  7305. /// namespace {
  7306. /// class vector {}; // #1
  7307. /// }
  7308. /// }
  7309. /// namespace {
  7310. /// class vector {}; // #2
  7311. /// namespace foo {
  7312. /// class vector{}; // #3
  7313. /// }
  7314. /// }
  7315. /// \endcode
  7316. /// cxxRecordDecl(hasName("vector"), isInAnonymousNamespace()) will match
  7317. /// #1, #2 and #3.
  7318. AST_MATCHER(Decl, isInAnonymousNamespace) {
  7319. return Node.isInAnonymousNamespace();
  7320. }
  7321. /// If the given case statement does not use the GNU case range
  7322. /// extension, matches the constant given in the statement.
  7323. ///
  7324. /// Given
  7325. /// \code
  7326. /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
  7327. /// \endcode
  7328. /// caseStmt(hasCaseConstant(integerLiteral()))
  7329. /// matches "case 1:"
  7330. AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
  7331. InnerMatcher) {
  7332. if (Node.getRHS())
  7333. return false;
  7334. return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
  7335. }
  7336. /// Matches declaration that has a given attribute.
  7337. ///
  7338. /// Given
  7339. /// \code
  7340. /// __attribute__((device)) void f() { ... }
  7341. /// \endcode
  7342. /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
  7343. /// f. If the matcher is used from clang-query, attr::Kind parameter should be
  7344. /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
  7345. AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
  7346. for (const auto *Attr : Node.attrs()) {
  7347. if (Attr->getKind() == AttrKind)
  7348. return true;
  7349. }
  7350. return false;
  7351. }
  7352. /// Matches the return value expression of a return statement
  7353. ///
  7354. /// Given
  7355. /// \code
  7356. /// return a + b;
  7357. /// \endcode
  7358. /// hasReturnValue(binaryOperator())
  7359. /// matches 'return a + b'
  7360. /// with binaryOperator()
  7361. /// matching 'a + b'
  7362. AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
  7363. InnerMatcher) {
  7364. if (const auto *RetValue = Node.getRetValue())
  7365. return InnerMatcher.matches(*RetValue, Finder, Builder);
  7366. return false;
  7367. }
  7368. /// Matches CUDA kernel call expression.
  7369. ///
  7370. /// Example matches,
  7371. /// \code
  7372. /// kernel<<<i,j>>>();
  7373. /// \endcode
  7374. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
  7375. cudaKernelCallExpr;
  7376. /// Matches expressions that resolve to a null pointer constant, such as
  7377. /// GNU's __null, C++11's nullptr, or C's NULL macro.
  7378. ///
  7379. /// Given:
  7380. /// \code
  7381. /// void *v1 = NULL;
  7382. /// void *v2 = nullptr;
  7383. /// void *v3 = __null; // GNU extension
  7384. /// char *cp = (char *)0;
  7385. /// int *ip = 0;
  7386. /// int i = 0;
  7387. /// \endcode
  7388. /// expr(nullPointerConstant())
  7389. /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
  7390. /// initializer for i.
  7391. AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
  7392. return anyOf(
  7393. gnuNullExpr(), cxxNullPtrLiteralExpr(),
  7394. integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
  7395. }
  7396. /// Matches the DecompositionDecl the binding belongs to.
  7397. ///
  7398. /// For example, in:
  7399. /// \code
  7400. /// void foo()
  7401. /// {
  7402. /// int arr[3];
  7403. /// auto &[f, s, t] = arr;
  7404. ///
  7405. /// f = 42;
  7406. /// }
  7407. /// \endcode
  7408. /// The matcher:
  7409. /// \code
  7410. /// bindingDecl(hasName("f"),
  7411. /// forDecomposition(decompositionDecl())
  7412. /// \endcode
  7413. /// matches 'f' in 'auto &[f, s, t]'.
  7414. AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>,
  7415. InnerMatcher) {
  7416. if (const ValueDecl *VD = Node.getDecomposedDecl())
  7417. return InnerMatcher.matches(*VD, Finder, Builder);
  7418. return false;
  7419. }
  7420. /// Matches the Nth binding of a DecompositionDecl.
  7421. ///
  7422. /// For example, in:
  7423. /// \code
  7424. /// void foo()
  7425. /// {
  7426. /// int arr[3];
  7427. /// auto &[f, s, t] = arr;
  7428. ///
  7429. /// f = 42;
  7430. /// }
  7431. /// \endcode
  7432. /// The matcher:
  7433. /// \code
  7434. /// decompositionDecl(hasBinding(0,
  7435. /// bindingDecl(hasName("f").bind("fBinding"))))
  7436. /// \endcode
  7437. /// matches the decomposition decl with 'f' bound to "fBinding".
  7438. AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N,
  7439. internal::Matcher<BindingDecl>, InnerMatcher) {
  7440. if (Node.bindings().size() <= N)
  7441. return false;
  7442. return InnerMatcher.matches(*Node.bindings()[N], Finder, Builder);
  7443. }
  7444. /// Matches any binding of a DecompositionDecl.
  7445. ///
  7446. /// For example, in:
  7447. /// \code
  7448. /// void foo()
  7449. /// {
  7450. /// int arr[3];
  7451. /// auto &[f, s, t] = arr;
  7452. ///
  7453. /// f = 42;
  7454. /// }
  7455. /// \endcode
  7456. /// The matcher:
  7457. /// \code
  7458. /// decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding"))))
  7459. /// \endcode
  7460. /// matches the decomposition decl with 'f' bound to "fBinding".
  7461. AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>,
  7462. InnerMatcher) {
  7463. return llvm::any_of(Node.bindings(), [&](const auto *Binding) {
  7464. return InnerMatcher.matches(*Binding, Finder, Builder);
  7465. });
  7466. }
  7467. /// Matches declaration of the function the statement belongs to.
  7468. ///
  7469. /// Deprecated. Use forCallable() to correctly handle the situation when
  7470. /// the declaration is not a function (but a block or an Objective-C method).
  7471. /// forFunction() not only fails to take non-functions into account but also
  7472. /// may match the wrong declaration in their presence.
  7473. ///
  7474. /// Given:
  7475. /// \code
  7476. /// F& operator=(const F& o) {
  7477. /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
  7478. /// return *this;
  7479. /// }
  7480. /// \endcode
  7481. /// returnStmt(forFunction(hasName("operator=")))
  7482. /// matches 'return *this'
  7483. /// but does not match 'return v > 0'
  7484. AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
  7485. InnerMatcher) {
  7486. const auto &Parents = Finder->getASTContext().getParents(Node);
  7487. llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
  7488. while (!Stack.empty()) {
  7489. const auto &CurNode = Stack.back();
  7490. Stack.pop_back();
  7491. if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
  7492. if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
  7493. return true;
  7494. }
  7495. } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
  7496. if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
  7497. Builder)) {
  7498. return true;
  7499. }
  7500. } else {
  7501. llvm::append_range(Stack, Finder->getASTContext().getParents(CurNode));
  7502. }
  7503. }
  7504. return false;
  7505. }
  7506. /// Matches declaration of the function, method, or block the statement
  7507. /// belongs to.
  7508. ///
  7509. /// Given:
  7510. /// \code
  7511. /// F& operator=(const F& o) {
  7512. /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
  7513. /// return *this;
  7514. /// }
  7515. /// \endcode
  7516. /// returnStmt(forCallable(functionDecl(hasName("operator="))))
  7517. /// matches 'return *this'
  7518. /// but does not match 'return v > 0'
  7519. ///
  7520. /// Given:
  7521. /// \code
  7522. /// -(void) foo {
  7523. /// int x = 1;
  7524. /// dispatch_sync(queue, ^{ int y = 2; });
  7525. /// }
  7526. /// \endcode
  7527. /// declStmt(forCallable(objcMethodDecl()))
  7528. /// matches 'int x = 1'
  7529. /// but does not match 'int y = 2'.
  7530. /// whereas declStmt(forCallable(blockDecl()))
  7531. /// matches 'int y = 2'
  7532. /// but does not match 'int x = 1'.
  7533. AST_MATCHER_P(Stmt, forCallable, internal::Matcher<Decl>, InnerMatcher) {
  7534. const auto &Parents = Finder->getASTContext().getParents(Node);
  7535. llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
  7536. while (!Stack.empty()) {
  7537. const auto &CurNode = Stack.back();
  7538. Stack.pop_back();
  7539. if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
  7540. if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
  7541. return true;
  7542. }
  7543. } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
  7544. if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
  7545. Builder)) {
  7546. return true;
  7547. }
  7548. } else if (const auto *ObjCMethodDeclNode = CurNode.get<ObjCMethodDecl>()) {
  7549. if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, Builder)) {
  7550. return true;
  7551. }
  7552. } else if (const auto *BlockDeclNode = CurNode.get<BlockDecl>()) {
  7553. if (InnerMatcher.matches(*BlockDeclNode, Finder, Builder)) {
  7554. return true;
  7555. }
  7556. } else {
  7557. llvm::append_range(Stack, Finder->getASTContext().getParents(CurNode));
  7558. }
  7559. }
  7560. return false;
  7561. }
  7562. /// Matches a declaration that has external formal linkage.
  7563. ///
  7564. /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
  7565. /// \code
  7566. /// void f() {
  7567. /// int x;
  7568. /// static int y;
  7569. /// }
  7570. /// int z;
  7571. /// \endcode
  7572. ///
  7573. /// Example matches f() because it has external formal linkage despite being
  7574. /// unique to the translation unit as though it has internal likage
  7575. /// (matcher = functionDecl(hasExternalFormalLinkage()))
  7576. ///
  7577. /// \code
  7578. /// namespace {
  7579. /// void f() {}
  7580. /// }
  7581. /// \endcode
  7582. AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
  7583. return Node.hasExternalFormalLinkage();
  7584. }
  7585. /// Matches a declaration that has default arguments.
  7586. ///
  7587. /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
  7588. /// \code
  7589. /// void x(int val) {}
  7590. /// void y(int val = 0) {}
  7591. /// \endcode
  7592. ///
  7593. /// Deprecated. Use hasInitializer() instead to be able to
  7594. /// match on the contents of the default argument. For example:
  7595. ///
  7596. /// \code
  7597. /// void x(int val = 7) {}
  7598. /// void y(int val = 42) {}
  7599. /// \endcode
  7600. /// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
  7601. /// matches the parameter of y
  7602. ///
  7603. /// A matcher such as
  7604. /// parmVarDecl(hasInitializer(anything()))
  7605. /// is equivalent to parmVarDecl(hasDefaultArgument()).
  7606. AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
  7607. return Node.hasDefaultArg();
  7608. }
  7609. /// Matches array new expressions.
  7610. ///
  7611. /// Given:
  7612. /// \code
  7613. /// MyClass *p1 = new MyClass[10];
  7614. /// \endcode
  7615. /// cxxNewExpr(isArray())
  7616. /// matches the expression 'new MyClass[10]'.
  7617. AST_MATCHER(CXXNewExpr, isArray) {
  7618. return Node.isArray();
  7619. }
  7620. /// Matches placement new expression arguments.
  7621. ///
  7622. /// Given:
  7623. /// \code
  7624. /// MyClass *p1 = new (Storage, 16) MyClass();
  7625. /// \endcode
  7626. /// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
  7627. /// matches the expression 'new (Storage, 16) MyClass()'.
  7628. AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
  7629. internal::Matcher<Expr>, InnerMatcher) {
  7630. return Node.getNumPlacementArgs() > Index &&
  7631. InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
  7632. }
  7633. /// Matches any placement new expression arguments.
  7634. ///
  7635. /// Given:
  7636. /// \code
  7637. /// MyClass *p1 = new (Storage) MyClass();
  7638. /// \endcode
  7639. /// cxxNewExpr(hasAnyPlacementArg(anything()))
  7640. /// matches the expression 'new (Storage, 16) MyClass()'.
  7641. AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
  7642. InnerMatcher) {
  7643. return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
  7644. return InnerMatcher.matches(*Arg, Finder, Builder);
  7645. });
  7646. }
  7647. /// Matches array new expressions with a given array size.
  7648. ///
  7649. /// Given:
  7650. /// \code
  7651. /// MyClass *p1 = new MyClass[10];
  7652. /// \endcode
  7653. /// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
  7654. /// matches the expression 'new MyClass[10]'.
  7655. AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
  7656. return Node.isArray() && *Node.getArraySize() &&
  7657. InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
  7658. }
  7659. /// Matches a class declaration that is defined.
  7660. ///
  7661. /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
  7662. /// \code
  7663. /// class x {};
  7664. /// class y;
  7665. /// \endcode
  7666. AST_MATCHER(CXXRecordDecl, hasDefinition) {
  7667. return Node.hasDefinition();
  7668. }
  7669. /// Matches C++11 scoped enum declaration.
  7670. ///
  7671. /// Example matches Y (matcher = enumDecl(isScoped()))
  7672. /// \code
  7673. /// enum X {};
  7674. /// enum class Y {};
  7675. /// \endcode
  7676. AST_MATCHER(EnumDecl, isScoped) {
  7677. return Node.isScoped();
  7678. }
  7679. /// Matches a function declared with a trailing return type.
  7680. ///
  7681. /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
  7682. /// \code
  7683. /// int X() {}
  7684. /// auto Y() -> int {}
  7685. /// \endcode
  7686. AST_MATCHER(FunctionDecl, hasTrailingReturn) {
  7687. if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
  7688. return F->hasTrailingReturn();
  7689. return false;
  7690. }
  7691. /// Matches expressions that match InnerMatcher that are possibly wrapped in an
  7692. /// elidable constructor and other corresponding bookkeeping nodes.
  7693. ///
  7694. /// In C++17, elidable copy constructors are no longer being generated in the
  7695. /// AST as it is not permitted by the standard. They are, however, part of the
  7696. /// AST in C++14 and earlier. So, a matcher must abstract over these differences
  7697. /// to work in all language modes. This matcher skips elidable constructor-call
  7698. /// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
  7699. /// various implicit nodes inside the constructor calls, all of which will not
  7700. /// appear in the C++17 AST.
  7701. ///
  7702. /// Given
  7703. ///
  7704. /// \code
  7705. /// struct H {};
  7706. /// H G();
  7707. /// void f() {
  7708. /// H D = G();
  7709. /// }
  7710. /// \endcode
  7711. ///
  7712. /// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
  7713. /// matches ``H D = G()`` in C++11 through C++17 (and beyond).
  7714. AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
  7715. ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
  7716. // E tracks the node that we are examining.
  7717. const Expr *E = &Node;
  7718. // If present, remove an outer `ExprWithCleanups` corresponding to the
  7719. // underlying `CXXConstructExpr`. This check won't cover all cases of added
  7720. // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
  7721. // EWC is placed on the outermost node of the expression, which this may not
  7722. // be), but, it still improves the coverage of this matcher.
  7723. if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
  7724. E = CleanupsExpr->getSubExpr();
  7725. if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
  7726. if (CtorExpr->isElidable()) {
  7727. if (const auto *MaterializeTemp =
  7728. dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
  7729. return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
  7730. Builder);
  7731. }
  7732. }
  7733. }
  7734. return InnerMatcher.matches(Node, Finder, Builder);
  7735. }
  7736. //----------------------------------------------------------------------------//
  7737. // OpenMP handling.
  7738. //----------------------------------------------------------------------------//
  7739. /// Matches any ``#pragma omp`` executable directive.
  7740. ///
  7741. /// Given
  7742. ///
  7743. /// \code
  7744. /// #pragma omp parallel
  7745. /// #pragma omp parallel default(none)
  7746. /// #pragma omp taskyield
  7747. /// \endcode
  7748. ///
  7749. /// ``ompExecutableDirective()`` matches ``omp parallel``,
  7750. /// ``omp parallel default(none)`` and ``omp taskyield``.
  7751. extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
  7752. ompExecutableDirective;
  7753. /// Matches standalone OpenMP directives,
  7754. /// i.e., directives that can't have a structured block.
  7755. ///
  7756. /// Given
  7757. ///
  7758. /// \code
  7759. /// #pragma omp parallel
  7760. /// {}
  7761. /// #pragma omp taskyield
  7762. /// \endcode
  7763. ///
  7764. /// ``ompExecutableDirective(isStandaloneDirective()))`` matches
  7765. /// ``omp taskyield``.
  7766. AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
  7767. return Node.isStandaloneDirective();
  7768. }
  7769. /// Matches the structured-block of the OpenMP executable directive
  7770. ///
  7771. /// Prerequisite: the executable directive must not be standalone directive.
  7772. /// If it is, it will never match.
  7773. ///
  7774. /// Given
  7775. ///
  7776. /// \code
  7777. /// #pragma omp parallel
  7778. /// ;
  7779. /// #pragma omp parallel
  7780. /// {}
  7781. /// \endcode
  7782. ///
  7783. /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
  7784. AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
  7785. internal::Matcher<Stmt>, InnerMatcher) {
  7786. if (Node.isStandaloneDirective())
  7787. return false; // Standalone directives have no structured blocks.
  7788. return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
  7789. }
  7790. /// Matches any clause in an OpenMP directive.
  7791. ///
  7792. /// Given
  7793. ///
  7794. /// \code
  7795. /// #pragma omp parallel
  7796. /// #pragma omp parallel default(none)
  7797. /// \endcode
  7798. ///
  7799. /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
  7800. /// ``omp parallel default(none)``.
  7801. AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
  7802. internal::Matcher<OMPClause>, InnerMatcher) {
  7803. ArrayRef<OMPClause *> Clauses = Node.clauses();
  7804. return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
  7805. Clauses.end(), Finder,
  7806. Builder) != Clauses.end();
  7807. }
  7808. /// Matches OpenMP ``default`` clause.
  7809. ///
  7810. /// Given
  7811. ///
  7812. /// \code
  7813. /// #pragma omp parallel default(none)
  7814. /// #pragma omp parallel default(shared)
  7815. /// #pragma omp parallel default(private)
  7816. /// #pragma omp parallel default(firstprivate)
  7817. /// #pragma omp parallel
  7818. /// \endcode
  7819. ///
  7820. /// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``,
  7821. /// `` default(private)`` and ``default(firstprivate)``
  7822. extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
  7823. ompDefaultClause;
  7824. /// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
  7825. ///
  7826. /// Given
  7827. ///
  7828. /// \code
  7829. /// #pragma omp parallel
  7830. /// #pragma omp parallel default(none)
  7831. /// #pragma omp parallel default(shared)
  7832. /// #pragma omp parallel default(private)
  7833. /// #pragma omp parallel default(firstprivate)
  7834. /// \endcode
  7835. ///
  7836. /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
  7837. AST_MATCHER(OMPDefaultClause, isNoneKind) {
  7838. return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
  7839. }
  7840. /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
  7841. ///
  7842. /// Given
  7843. ///
  7844. /// \code
  7845. /// #pragma omp parallel
  7846. /// #pragma omp parallel default(none)
  7847. /// #pragma omp parallel default(shared)
  7848. /// #pragma omp parallel default(private)
  7849. /// #pragma omp parallel default(firstprivate)
  7850. /// \endcode
  7851. ///
  7852. /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
  7853. AST_MATCHER(OMPDefaultClause, isSharedKind) {
  7854. return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
  7855. }
  7856. /// Matches if the OpenMP ``default`` clause has ``private`` kind
  7857. /// specified.
  7858. ///
  7859. /// Given
  7860. ///
  7861. /// \code
  7862. /// #pragma omp parallel
  7863. /// #pragma omp parallel default(none)
  7864. /// #pragma omp parallel default(shared)
  7865. /// #pragma omp parallel default(private)
  7866. /// #pragma omp parallel default(firstprivate)
  7867. /// \endcode
  7868. ///
  7869. /// ``ompDefaultClause(isPrivateKind())`` matches only
  7870. /// ``default(private)``.
  7871. AST_MATCHER(OMPDefaultClause, isPrivateKind) {
  7872. return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_private;
  7873. }
  7874. /// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
  7875. /// specified.
  7876. ///
  7877. /// Given
  7878. ///
  7879. /// \code
  7880. /// #pragma omp parallel
  7881. /// #pragma omp parallel default(none)
  7882. /// #pragma omp parallel default(shared)
  7883. /// #pragma omp parallel default(private)
  7884. /// #pragma omp parallel default(firstprivate)
  7885. /// \endcode
  7886. ///
  7887. /// ``ompDefaultClause(isFirstPrivateKind())`` matches only
  7888. /// ``default(firstprivate)``.
  7889. AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
  7890. return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
  7891. }
  7892. /// Matches if the OpenMP directive is allowed to contain the specified OpenMP
  7893. /// clause kind.
  7894. ///
  7895. /// Given
  7896. ///
  7897. /// \code
  7898. /// #pragma omp parallel
  7899. /// #pragma omp parallel for
  7900. /// #pragma omp for
  7901. /// \endcode
  7902. ///
  7903. /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
  7904. /// ``omp parallel`` and ``omp parallel for``.
  7905. ///
  7906. /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
  7907. /// should be passed as a quoted string. e.g.,
  7908. /// ``isAllowedToContainClauseKind("OMPC_default").``
  7909. AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
  7910. OpenMPClauseKind, CKind) {
  7911. return llvm::omp::isAllowedClauseForDirective(
  7912. Node.getDirectiveKind(), CKind,
  7913. Finder->getASTContext().getLangOpts().OpenMP);
  7914. }
  7915. //----------------------------------------------------------------------------//
  7916. // End OpenMP handling.
  7917. //----------------------------------------------------------------------------//
  7918. } // namespace ast_matchers
  7919. } // namespace clang
  7920. #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
  7921. #ifdef __GNUC__
  7922. #pragma GCC diagnostic pop
  7923. #endif