CIndex.cpp 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234
  1. //===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the main API hooks in the Clang-C Source Indexing
  10. // library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CIndexDiagnostic.h"
  14. #include "CIndexer.h"
  15. #include "CLog.h"
  16. #include "CXCursor.h"
  17. #include "CXSourceLocation.h"
  18. #include "CXString.h"
  19. #include "CXTranslationUnit.h"
  20. #include "CXType.h"
  21. #include "CursorVisitor.h"
  22. #include "clang-c/FatalErrorHandler.h"
  23. #include "clang/AST/Attr.h"
  24. #include "clang/AST/DeclObjCCommon.h"
  25. #include "clang/AST/Mangle.h"
  26. #include "clang/AST/OpenMPClause.h"
  27. #include "clang/AST/StmtVisitor.h"
  28. #include "clang/Basic/Diagnostic.h"
  29. #include "clang/Basic/DiagnosticCategories.h"
  30. #include "clang/Basic/DiagnosticIDs.h"
  31. #include "clang/Basic/Stack.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/Basic/Version.h"
  34. #include "clang/Frontend/ASTUnit.h"
  35. #include "clang/Frontend/CompilerInstance.h"
  36. #include "clang/Index/CommentToXML.h"
  37. #include "clang/Lex/HeaderSearch.h"
  38. #include "clang/Lex/Lexer.h"
  39. #include "clang/Lex/PreprocessingRecord.h"
  40. #include "clang/Lex/Preprocessor.h"
  41. #include "llvm/ADT/Optional.h"
  42. #include "llvm/ADT/STLExtras.h"
  43. #include "llvm/ADT/StringSwitch.h"
  44. #include "llvm/Config/llvm-config.h"
  45. #include "llvm/Support/Compiler.h"
  46. #include "llvm/Support/CrashRecoveryContext.h"
  47. #include "llvm/Support/Format.h"
  48. #include "llvm/Support/ManagedStatic.h"
  49. #include "llvm/Support/MemoryBuffer.h"
  50. #include "llvm/Support/Program.h"
  51. #include "llvm/Support/SaveAndRestore.h"
  52. #include "llvm/Support/Signals.h"
  53. #include "llvm/Support/TargetSelect.h"
  54. #include "llvm/Support/Threading.h"
  55. #include "llvm/Support/Timer.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include "llvm/Support/thread.h"
  58. #include <mutex>
  59. #if LLVM_ENABLE_THREADS != 0 && defined(__APPLE__)
  60. #define USE_DARWIN_THREADS
  61. #endif
  62. #ifdef USE_DARWIN_THREADS
  63. #include <pthread.h>
  64. #endif
  65. using namespace clang;
  66. using namespace clang::cxcursor;
  67. using namespace clang::cxtu;
  68. using namespace clang::cxindex;
  69. CXTranslationUnit cxtu::MakeCXTranslationUnit(CIndexer *CIdx,
  70. std::unique_ptr<ASTUnit> AU) {
  71. if (!AU)
  72. return nullptr;
  73. assert(CIdx);
  74. CXTranslationUnit D = new CXTranslationUnitImpl();
  75. D->CIdx = CIdx;
  76. D->TheASTUnit = AU.release();
  77. D->StringPool = new cxstring::CXStringPool();
  78. D->Diagnostics = nullptr;
  79. D->OverridenCursorsPool = createOverridenCXCursorsPool();
  80. D->CommentToXML = nullptr;
  81. D->ParsingOptions = 0;
  82. D->Arguments = {};
  83. return D;
  84. }
  85. bool cxtu::isASTReadError(ASTUnit *AU) {
  86. for (ASTUnit::stored_diag_iterator D = AU->stored_diag_begin(),
  87. DEnd = AU->stored_diag_end();
  88. D != DEnd; ++D) {
  89. if (D->getLevel() >= DiagnosticsEngine::Error &&
  90. DiagnosticIDs::getCategoryNumberForDiag(D->getID()) ==
  91. diag::DiagCat_AST_Deserialization_Issue)
  92. return true;
  93. }
  94. return false;
  95. }
  96. cxtu::CXTUOwner::~CXTUOwner() {
  97. if (TU)
  98. clang_disposeTranslationUnit(TU);
  99. }
  100. /// Compare two source ranges to determine their relative position in
  101. /// the translation unit.
  102. static RangeComparisonResult RangeCompare(SourceManager &SM, SourceRange R1,
  103. SourceRange R2) {
  104. assert(R1.isValid() && "First range is invalid?");
  105. assert(R2.isValid() && "Second range is invalid?");
  106. if (R1.getEnd() != R2.getBegin() &&
  107. SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
  108. return RangeBefore;
  109. if (R2.getEnd() != R1.getBegin() &&
  110. SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
  111. return RangeAfter;
  112. return RangeOverlap;
  113. }
  114. /// Determine if a source location falls within, before, or after a
  115. /// a given source range.
  116. static RangeComparisonResult LocationCompare(SourceManager &SM,
  117. SourceLocation L, SourceRange R) {
  118. assert(R.isValid() && "First range is invalid?");
  119. assert(L.isValid() && "Second range is invalid?");
  120. if (L == R.getBegin() || L == R.getEnd())
  121. return RangeOverlap;
  122. if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
  123. return RangeBefore;
  124. if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
  125. return RangeAfter;
  126. return RangeOverlap;
  127. }
  128. /// Translate a Clang source range into a CIndex source range.
  129. ///
  130. /// Clang internally represents ranges where the end location points to the
  131. /// start of the token at the end. However, for external clients it is more
  132. /// useful to have a CXSourceRange be a proper half-open interval. This routine
  133. /// does the appropriate translation.
  134. CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
  135. const LangOptions &LangOpts,
  136. const CharSourceRange &R) {
  137. // We want the last character in this location, so we will adjust the
  138. // location accordingly.
  139. SourceLocation EndLoc = R.getEnd();
  140. bool IsTokenRange = R.isTokenRange();
  141. if (EndLoc.isValid() && EndLoc.isMacroID() &&
  142. !SM.isMacroArgExpansion(EndLoc)) {
  143. CharSourceRange Expansion = SM.getExpansionRange(EndLoc);
  144. EndLoc = Expansion.getEnd();
  145. IsTokenRange = Expansion.isTokenRange();
  146. }
  147. if (IsTokenRange && EndLoc.isValid()) {
  148. unsigned Length =
  149. Lexer::MeasureTokenLength(SM.getSpellingLoc(EndLoc), SM, LangOpts);
  150. EndLoc = EndLoc.getLocWithOffset(Length);
  151. }
  152. CXSourceRange Result = {
  153. {&SM, &LangOpts}, R.getBegin().getRawEncoding(), EndLoc.getRawEncoding()};
  154. return Result;
  155. }
  156. CharSourceRange cxloc::translateCXRangeToCharRange(CXSourceRange R) {
  157. return CharSourceRange::getCharRange(
  158. SourceLocation::getFromRawEncoding(R.begin_int_data),
  159. SourceLocation::getFromRawEncoding(R.end_int_data));
  160. }
  161. //===----------------------------------------------------------------------===//
  162. // Cursor visitor.
  163. //===----------------------------------------------------------------------===//
  164. static SourceRange getRawCursorExtent(CXCursor C);
  165. static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr);
  166. RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
  167. return RangeCompare(AU->getSourceManager(), R, RegionOfInterest);
  168. }
  169. /// Visit the given cursor and, if requested by the visitor,
  170. /// its children.
  171. ///
  172. /// \param Cursor the cursor to visit.
  173. ///
  174. /// \param CheckedRegionOfInterest if true, then the caller already checked
  175. /// that this cursor is within the region of interest.
  176. ///
  177. /// \returns true if the visitation should be aborted, false if it
  178. /// should continue.
  179. bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
  180. if (clang_isInvalid(Cursor.kind))
  181. return false;
  182. if (clang_isDeclaration(Cursor.kind)) {
  183. const Decl *D = getCursorDecl(Cursor);
  184. if (!D) {
  185. assert(0 && "Invalid declaration cursor");
  186. return true; // abort.
  187. }
  188. // Ignore implicit declarations, unless it's an objc method because
  189. // currently we should report implicit methods for properties when indexing.
  190. if (D->isImplicit() && !isa<ObjCMethodDecl>(D))
  191. return false;
  192. }
  193. // If we have a range of interest, and this cursor doesn't intersect with it,
  194. // we're done.
  195. if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
  196. SourceRange Range = getRawCursorExtent(Cursor);
  197. if (Range.isInvalid() || CompareRegionOfInterest(Range))
  198. return false;
  199. }
  200. switch (Visitor(Cursor, Parent, ClientData)) {
  201. case CXChildVisit_Break:
  202. return true;
  203. case CXChildVisit_Continue:
  204. return false;
  205. case CXChildVisit_Recurse: {
  206. bool ret = VisitChildren(Cursor);
  207. if (PostChildrenVisitor)
  208. if (PostChildrenVisitor(Cursor, ClientData))
  209. return true;
  210. return ret;
  211. }
  212. }
  213. llvm_unreachable("Invalid CXChildVisitResult!");
  214. }
  215. static bool visitPreprocessedEntitiesInRange(SourceRange R,
  216. PreprocessingRecord &PPRec,
  217. CursorVisitor &Visitor) {
  218. SourceManager &SM = Visitor.getASTUnit()->getSourceManager();
  219. FileID FID;
  220. if (!Visitor.shouldVisitIncludedEntities()) {
  221. // If the begin/end of the range lie in the same FileID, do the optimization
  222. // where we skip preprocessed entities that do not come from the same
  223. // FileID.
  224. FID = SM.getFileID(SM.getFileLoc(R.getBegin()));
  225. if (FID != SM.getFileID(SM.getFileLoc(R.getEnd())))
  226. FID = FileID();
  227. }
  228. const auto &Entities = PPRec.getPreprocessedEntitiesInRange(R);
  229. return Visitor.visitPreprocessedEntities(Entities.begin(), Entities.end(),
  230. PPRec, FID);
  231. }
  232. bool CursorVisitor::visitFileRegion() {
  233. if (RegionOfInterest.isInvalid())
  234. return false;
  235. ASTUnit *Unit = cxtu::getASTUnit(TU);
  236. SourceManager &SM = Unit->getSourceManager();
  237. std::pair<FileID, unsigned> Begin = SM.getDecomposedLoc(
  238. SM.getFileLoc(RegionOfInterest.getBegin())),
  239. End = SM.getDecomposedLoc(
  240. SM.getFileLoc(RegionOfInterest.getEnd()));
  241. if (End.first != Begin.first) {
  242. // If the end does not reside in the same file, try to recover by
  243. // picking the end of the file of begin location.
  244. End.first = Begin.first;
  245. End.second = SM.getFileIDSize(Begin.first);
  246. }
  247. assert(Begin.first == End.first);
  248. if (Begin.second > End.second)
  249. return false;
  250. FileID File = Begin.first;
  251. unsigned Offset = Begin.second;
  252. unsigned Length = End.second - Begin.second;
  253. if (!VisitDeclsOnly && !VisitPreprocessorLast)
  254. if (visitPreprocessedEntitiesInRegion())
  255. return true; // visitation break.
  256. if (visitDeclsFromFileRegion(File, Offset, Length))
  257. return true; // visitation break.
  258. if (!VisitDeclsOnly && VisitPreprocessorLast)
  259. return visitPreprocessedEntitiesInRegion();
  260. return false;
  261. }
  262. static bool isInLexicalContext(Decl *D, DeclContext *DC) {
  263. if (!DC)
  264. return false;
  265. for (DeclContext *DeclDC = D->getLexicalDeclContext(); DeclDC;
  266. DeclDC = DeclDC->getLexicalParent()) {
  267. if (DeclDC == DC)
  268. return true;
  269. }
  270. return false;
  271. }
  272. bool CursorVisitor::visitDeclsFromFileRegion(FileID File, unsigned Offset,
  273. unsigned Length) {
  274. ASTUnit *Unit = cxtu::getASTUnit(TU);
  275. SourceManager &SM = Unit->getSourceManager();
  276. SourceRange Range = RegionOfInterest;
  277. SmallVector<Decl *, 16> Decls;
  278. Unit->findFileRegionDecls(File, Offset, Length, Decls);
  279. // If we didn't find any file level decls for the file, try looking at the
  280. // file that it was included from.
  281. while (Decls.empty() || Decls.front()->isTopLevelDeclInObjCContainer()) {
  282. bool Invalid = false;
  283. const SrcMgr::SLocEntry &SLEntry = SM.getSLocEntry(File, &Invalid);
  284. if (Invalid)
  285. return false;
  286. SourceLocation Outer;
  287. if (SLEntry.isFile())
  288. Outer = SLEntry.getFile().getIncludeLoc();
  289. else
  290. Outer = SLEntry.getExpansion().getExpansionLocStart();
  291. if (Outer.isInvalid())
  292. return false;
  293. std::tie(File, Offset) = SM.getDecomposedExpansionLoc(Outer);
  294. Length = 0;
  295. Unit->findFileRegionDecls(File, Offset, Length, Decls);
  296. }
  297. assert(!Decls.empty());
  298. bool VisitedAtLeastOnce = false;
  299. DeclContext *CurDC = nullptr;
  300. SmallVectorImpl<Decl *>::iterator DIt = Decls.begin();
  301. for (SmallVectorImpl<Decl *>::iterator DE = Decls.end(); DIt != DE; ++DIt) {
  302. Decl *D = *DIt;
  303. if (D->getSourceRange().isInvalid())
  304. continue;
  305. if (isInLexicalContext(D, CurDC))
  306. continue;
  307. CurDC = dyn_cast<DeclContext>(D);
  308. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  309. if (!TD->isFreeStanding())
  310. continue;
  311. RangeComparisonResult CompRes =
  312. RangeCompare(SM, D->getSourceRange(), Range);
  313. if (CompRes == RangeBefore)
  314. continue;
  315. if (CompRes == RangeAfter)
  316. break;
  317. assert(CompRes == RangeOverlap);
  318. VisitedAtLeastOnce = true;
  319. if (isa<ObjCContainerDecl>(D)) {
  320. FileDI_current = &DIt;
  321. FileDE_current = DE;
  322. } else {
  323. FileDI_current = nullptr;
  324. }
  325. if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
  326. return true; // visitation break.
  327. }
  328. if (VisitedAtLeastOnce)
  329. return false;
  330. // No Decls overlapped with the range. Move up the lexical context until there
  331. // is a context that contains the range or we reach the translation unit
  332. // level.
  333. DeclContext *DC = DIt == Decls.begin()
  334. ? (*DIt)->getLexicalDeclContext()
  335. : (*(DIt - 1))->getLexicalDeclContext();
  336. while (DC && !DC->isTranslationUnit()) {
  337. Decl *D = cast<Decl>(DC);
  338. SourceRange CurDeclRange = D->getSourceRange();
  339. if (CurDeclRange.isInvalid())
  340. break;
  341. if (RangeCompare(SM, CurDeclRange, Range) == RangeOverlap) {
  342. if (Visit(MakeCXCursor(D, TU, Range), /*CheckedRegionOfInterest=*/true))
  343. return true; // visitation break.
  344. }
  345. DC = D->getLexicalDeclContext();
  346. }
  347. return false;
  348. }
  349. bool CursorVisitor::visitPreprocessedEntitiesInRegion() {
  350. if (!AU->getPreprocessor().getPreprocessingRecord())
  351. return false;
  352. PreprocessingRecord &PPRec = *AU->getPreprocessor().getPreprocessingRecord();
  353. SourceManager &SM = AU->getSourceManager();
  354. if (RegionOfInterest.isValid()) {
  355. SourceRange MappedRange = AU->mapRangeToPreamble(RegionOfInterest);
  356. SourceLocation B = MappedRange.getBegin();
  357. SourceLocation E = MappedRange.getEnd();
  358. if (AU->isInPreambleFileID(B)) {
  359. if (SM.isLoadedSourceLocation(E))
  360. return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec,
  361. *this);
  362. // Beginning of range lies in the preamble but it also extends beyond
  363. // it into the main file. Split the range into 2 parts, one covering
  364. // the preamble and another covering the main file. This allows subsequent
  365. // calls to visitPreprocessedEntitiesInRange to accept a source range that
  366. // lies in the same FileID, allowing it to skip preprocessed entities that
  367. // do not come from the same FileID.
  368. bool breaked = visitPreprocessedEntitiesInRange(
  369. SourceRange(B, AU->getEndOfPreambleFileID()), PPRec, *this);
  370. if (breaked)
  371. return true;
  372. return visitPreprocessedEntitiesInRange(
  373. SourceRange(AU->getStartOfMainFileID(), E), PPRec, *this);
  374. }
  375. return visitPreprocessedEntitiesInRange(SourceRange(B, E), PPRec, *this);
  376. }
  377. bool OnlyLocalDecls = !AU->isMainFileAST() && AU->getOnlyLocalDecls();
  378. if (OnlyLocalDecls)
  379. return visitPreprocessedEntities(PPRec.local_begin(), PPRec.local_end(),
  380. PPRec);
  381. return visitPreprocessedEntities(PPRec.begin(), PPRec.end(), PPRec);
  382. }
  383. template <typename InputIterator>
  384. bool CursorVisitor::visitPreprocessedEntities(InputIterator First,
  385. InputIterator Last,
  386. PreprocessingRecord &PPRec,
  387. FileID FID) {
  388. for (; First != Last; ++First) {
  389. if (!FID.isInvalid() && !PPRec.isEntityInFileID(First, FID))
  390. continue;
  391. PreprocessedEntity *PPE = *First;
  392. if (!PPE)
  393. continue;
  394. if (MacroExpansion *ME = dyn_cast<MacroExpansion>(PPE)) {
  395. if (Visit(MakeMacroExpansionCursor(ME, TU)))
  396. return true;
  397. continue;
  398. }
  399. if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(PPE)) {
  400. if (Visit(MakeMacroDefinitionCursor(MD, TU)))
  401. return true;
  402. continue;
  403. }
  404. if (InclusionDirective *ID = dyn_cast<InclusionDirective>(PPE)) {
  405. if (Visit(MakeInclusionDirectiveCursor(ID, TU)))
  406. return true;
  407. continue;
  408. }
  409. }
  410. return false;
  411. }
  412. /// Visit the children of the given cursor.
  413. ///
  414. /// \returns true if the visitation should be aborted, false if it
  415. /// should continue.
  416. bool CursorVisitor::VisitChildren(CXCursor Cursor) {
  417. if (clang_isReference(Cursor.kind) &&
  418. Cursor.kind != CXCursor_CXXBaseSpecifier) {
  419. // By definition, references have no children.
  420. return false;
  421. }
  422. // Set the Parent field to Cursor, then back to its old value once we're
  423. // done.
  424. SetParentRAII SetParent(Parent, StmtParent, Cursor);
  425. if (clang_isDeclaration(Cursor.kind)) {
  426. Decl *D = const_cast<Decl *>(getCursorDecl(Cursor));
  427. if (!D)
  428. return false;
  429. return VisitAttributes(D) || Visit(D);
  430. }
  431. if (clang_isStatement(Cursor.kind)) {
  432. if (const Stmt *S = getCursorStmt(Cursor))
  433. return Visit(S);
  434. return false;
  435. }
  436. if (clang_isExpression(Cursor.kind)) {
  437. if (const Expr *E = getCursorExpr(Cursor))
  438. return Visit(E);
  439. return false;
  440. }
  441. if (clang_isTranslationUnit(Cursor.kind)) {
  442. CXTranslationUnit TU = getCursorTU(Cursor);
  443. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  444. int VisitOrder[2] = {VisitPreprocessorLast, !VisitPreprocessorLast};
  445. for (unsigned I = 0; I != 2; ++I) {
  446. if (VisitOrder[I]) {
  447. if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
  448. RegionOfInterest.isInvalid()) {
  449. for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
  450. TLEnd = CXXUnit->top_level_end();
  451. TL != TLEnd; ++TL) {
  452. const Optional<bool> V = handleDeclForVisitation(*TL);
  453. if (!V.hasValue())
  454. continue;
  455. return V.getValue();
  456. }
  457. } else if (VisitDeclContext(
  458. CXXUnit->getASTContext().getTranslationUnitDecl()))
  459. return true;
  460. continue;
  461. }
  462. // Walk the preprocessing record.
  463. if (CXXUnit->getPreprocessor().getPreprocessingRecord())
  464. visitPreprocessedEntitiesInRegion();
  465. }
  466. return false;
  467. }
  468. if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
  469. if (const CXXBaseSpecifier *Base = getCursorCXXBaseSpecifier(Cursor)) {
  470. if (TypeSourceInfo *BaseTSInfo = Base->getTypeSourceInfo()) {
  471. return Visit(BaseTSInfo->getTypeLoc());
  472. }
  473. }
  474. }
  475. if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
  476. const IBOutletCollectionAttr *A =
  477. cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(Cursor));
  478. if (const ObjCObjectType *ObjT = A->getInterface()->getAs<ObjCObjectType>())
  479. return Visit(cxcursor::MakeCursorObjCClassRef(
  480. ObjT->getInterface(),
  481. A->getInterfaceLoc()->getTypeLoc().getBeginLoc(), TU));
  482. }
  483. // If pointing inside a macro definition, check if the token is an identifier
  484. // that was ever defined as a macro. In such a case, create a "pseudo" macro
  485. // expansion cursor for that token.
  486. SourceLocation BeginLoc = RegionOfInterest.getBegin();
  487. if (Cursor.kind == CXCursor_MacroDefinition &&
  488. BeginLoc == RegionOfInterest.getEnd()) {
  489. SourceLocation Loc = AU->mapLocationToPreamble(BeginLoc);
  490. const MacroInfo *MI =
  491. getMacroInfo(cxcursor::getCursorMacroDefinition(Cursor), TU);
  492. if (MacroDefinitionRecord *MacroDef =
  493. checkForMacroInMacroDefinition(MI, Loc, TU))
  494. return Visit(cxcursor::MakeMacroExpansionCursor(MacroDef, BeginLoc, TU));
  495. }
  496. // Nothing to visit at the moment.
  497. return false;
  498. }
  499. bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
  500. if (TypeSourceInfo *TSInfo = B->getSignatureAsWritten())
  501. if (Visit(TSInfo->getTypeLoc()))
  502. return true;
  503. if (Stmt *Body = B->getBody())
  504. return Visit(MakeCXCursor(Body, StmtParent, TU, RegionOfInterest));
  505. return false;
  506. }
  507. Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
  508. if (RegionOfInterest.isValid()) {
  509. SourceRange Range = getFullCursorExtent(Cursor, AU->getSourceManager());
  510. if (Range.isInvalid())
  511. return None;
  512. switch (CompareRegionOfInterest(Range)) {
  513. case RangeBefore:
  514. // This declaration comes before the region of interest; skip it.
  515. return None;
  516. case RangeAfter:
  517. // This declaration comes after the region of interest; we're done.
  518. return false;
  519. case RangeOverlap:
  520. // This declaration overlaps the region of interest; visit it.
  521. break;
  522. }
  523. }
  524. return true;
  525. }
  526. bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
  527. DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
  528. // FIXME: Eventually remove. This part of a hack to support proper
  529. // iteration over all Decls contained lexically within an ObjC container.
  530. SaveAndRestore<DeclContext::decl_iterator *> DI_saved(DI_current, &I);
  531. SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
  532. for (; I != E; ++I) {
  533. Decl *D = *I;
  534. if (D->getLexicalDeclContext() != DC)
  535. continue;
  536. // Filter out synthesized property accessor redeclarations.
  537. if (isa<ObjCImplDecl>(DC))
  538. if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
  539. if (OMD->isSynthesizedAccessorStub())
  540. continue;
  541. const Optional<bool> V = handleDeclForVisitation(D);
  542. if (!V.hasValue())
  543. continue;
  544. return V.getValue();
  545. }
  546. return false;
  547. }
  548. Optional<bool> CursorVisitor::handleDeclForVisitation(const Decl *D) {
  549. CXCursor Cursor = MakeCXCursor(D, TU, RegionOfInterest);
  550. // Ignore synthesized ivars here, otherwise if we have something like:
  551. // @synthesize prop = _prop;
  552. // and '_prop' is not declared, we will encounter a '_prop' ivar before
  553. // encountering the 'prop' synthesize declaration and we will think that
  554. // we passed the region-of-interest.
  555. if (auto *ivarD = dyn_cast<ObjCIvarDecl>(D)) {
  556. if (ivarD->getSynthesize())
  557. return None;
  558. }
  559. // FIXME: ObjCClassRef/ObjCProtocolRef for forward class/protocol
  560. // declarations is a mismatch with the compiler semantics.
  561. if (Cursor.kind == CXCursor_ObjCInterfaceDecl) {
  562. auto *ID = cast<ObjCInterfaceDecl>(D);
  563. if (!ID->isThisDeclarationADefinition())
  564. Cursor = MakeCursorObjCClassRef(ID, ID->getLocation(), TU);
  565. } else if (Cursor.kind == CXCursor_ObjCProtocolDecl) {
  566. auto *PD = cast<ObjCProtocolDecl>(D);
  567. if (!PD->isThisDeclarationADefinition())
  568. Cursor = MakeCursorObjCProtocolRef(PD, PD->getLocation(), TU);
  569. }
  570. const Optional<bool> V = shouldVisitCursor(Cursor);
  571. if (!V.hasValue())
  572. return None;
  573. if (!V.getValue())
  574. return false;
  575. if (Visit(Cursor, true))
  576. return true;
  577. return None;
  578. }
  579. bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
  580. llvm_unreachable("Translation units are visited directly by Visit()");
  581. }
  582. bool CursorVisitor::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  583. if (VisitTemplateParameters(D->getTemplateParameters()))
  584. return true;
  585. return Visit(MakeCXCursor(D->getTemplatedDecl(), TU, RegionOfInterest));
  586. }
  587. bool CursorVisitor::VisitTypeAliasDecl(TypeAliasDecl *D) {
  588. if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
  589. return Visit(TSInfo->getTypeLoc());
  590. return false;
  591. }
  592. bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
  593. if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
  594. return Visit(TSInfo->getTypeLoc());
  595. return false;
  596. }
  597. bool CursorVisitor::VisitTagDecl(TagDecl *D) { return VisitDeclContext(D); }
  598. bool CursorVisitor::VisitClassTemplateSpecializationDecl(
  599. ClassTemplateSpecializationDecl *D) {
  600. bool ShouldVisitBody = false;
  601. switch (D->getSpecializationKind()) {
  602. case TSK_Undeclared:
  603. case TSK_ImplicitInstantiation:
  604. // Nothing to visit
  605. return false;
  606. case TSK_ExplicitInstantiationDeclaration:
  607. case TSK_ExplicitInstantiationDefinition:
  608. break;
  609. case TSK_ExplicitSpecialization:
  610. ShouldVisitBody = true;
  611. break;
  612. }
  613. // Visit the template arguments used in the specialization.
  614. if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
  615. TypeLoc TL = SpecType->getTypeLoc();
  616. if (TemplateSpecializationTypeLoc TSTLoc =
  617. TL.getAs<TemplateSpecializationTypeLoc>()) {
  618. for (unsigned I = 0, N = TSTLoc.getNumArgs(); I != N; ++I)
  619. if (VisitTemplateArgumentLoc(TSTLoc.getArgLoc(I)))
  620. return true;
  621. }
  622. }
  623. return ShouldVisitBody && VisitCXXRecordDecl(D);
  624. }
  625. bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
  626. ClassTemplatePartialSpecializationDecl *D) {
  627. // FIXME: Visit the "outer" template parameter lists on the TagDecl
  628. // before visiting these template parameters.
  629. if (VisitTemplateParameters(D->getTemplateParameters()))
  630. return true;
  631. // Visit the partial specialization arguments.
  632. const ASTTemplateArgumentListInfo *Info = D->getTemplateArgsAsWritten();
  633. const TemplateArgumentLoc *TemplateArgs = Info->getTemplateArgs();
  634. for (unsigned I = 0, N = Info->NumTemplateArgs; I != N; ++I)
  635. if (VisitTemplateArgumentLoc(TemplateArgs[I]))
  636. return true;
  637. return VisitCXXRecordDecl(D);
  638. }
  639. bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
  640. if (const auto *TC = D->getTypeConstraint())
  641. if (Visit(MakeCXCursor(TC->getImmediatelyDeclaredConstraint(), StmtParent,
  642. TU, RegionOfInterest)))
  643. return true;
  644. // Visit the default argument.
  645. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
  646. if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
  647. if (Visit(DefArg->getTypeLoc()))
  648. return true;
  649. return false;
  650. }
  651. bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
  652. if (Expr *Init = D->getInitExpr())
  653. return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
  654. return false;
  655. }
  656. bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
  657. unsigned NumParamList = DD->getNumTemplateParameterLists();
  658. for (unsigned i = 0; i < NumParamList; i++) {
  659. TemplateParameterList *Params = DD->getTemplateParameterList(i);
  660. if (VisitTemplateParameters(Params))
  661. return true;
  662. }
  663. if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
  664. if (Visit(TSInfo->getTypeLoc()))
  665. return true;
  666. // Visit the nested-name-specifier, if present.
  667. if (NestedNameSpecifierLoc QualifierLoc = DD->getQualifierLoc())
  668. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  669. return true;
  670. return false;
  671. }
  672. static bool HasTrailingReturnType(FunctionDecl *ND) {
  673. const QualType Ty = ND->getType();
  674. if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
  675. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(AFT))
  676. return FT->hasTrailingReturn();
  677. }
  678. return false;
  679. }
  680. /// Compare two base or member initializers based on their source order.
  681. static int CompareCXXCtorInitializers(CXXCtorInitializer *const *X,
  682. CXXCtorInitializer *const *Y) {
  683. return (*X)->getSourceOrder() - (*Y)->getSourceOrder();
  684. }
  685. bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
  686. unsigned NumParamList = ND->getNumTemplateParameterLists();
  687. for (unsigned i = 0; i < NumParamList; i++) {
  688. TemplateParameterList *Params = ND->getTemplateParameterList(i);
  689. if (VisitTemplateParameters(Params))
  690. return true;
  691. }
  692. if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
  693. // Visit the function declaration's syntactic components in the order
  694. // written. This requires a bit of work.
  695. TypeLoc TL = TSInfo->getTypeLoc().IgnoreParens();
  696. FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>();
  697. const bool HasTrailingRT = HasTrailingReturnType(ND);
  698. // If we have a function declared directly (without the use of a typedef),
  699. // visit just the return type. Otherwise, just visit the function's type
  700. // now.
  701. if ((FTL && !isa<CXXConversionDecl>(ND) && !HasTrailingRT &&
  702. Visit(FTL.getReturnLoc())) ||
  703. (!FTL && Visit(TL)))
  704. return true;
  705. // Visit the nested-name-specifier, if present.
  706. if (NestedNameSpecifierLoc QualifierLoc = ND->getQualifierLoc())
  707. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  708. return true;
  709. // Visit the declaration name.
  710. if (!isa<CXXDestructorDecl>(ND))
  711. if (VisitDeclarationNameInfo(ND->getNameInfo()))
  712. return true;
  713. // FIXME: Visit explicitly-specified template arguments!
  714. // Visit the function parameters, if we have a function type.
  715. if (FTL && VisitFunctionTypeLoc(FTL, true))
  716. return true;
  717. // Visit the function's trailing return type.
  718. if (FTL && HasTrailingRT && Visit(FTL.getReturnLoc()))
  719. return true;
  720. // FIXME: Attributes?
  721. }
  722. if (ND->doesThisDeclarationHaveABody() && !ND->isLateTemplateParsed()) {
  723. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
  724. // Find the initializers that were written in the source.
  725. SmallVector<CXXCtorInitializer *, 4> WrittenInits;
  726. for (auto *I : Constructor->inits()) {
  727. if (!I->isWritten())
  728. continue;
  729. WrittenInits.push_back(I);
  730. }
  731. // Sort the initializers in source order
  732. llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
  733. &CompareCXXCtorInitializers);
  734. // Visit the initializers in source order
  735. for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
  736. CXXCtorInitializer *Init = WrittenInits[I];
  737. if (Init->isAnyMemberInitializer()) {
  738. if (Visit(MakeCursorMemberRef(Init->getAnyMember(),
  739. Init->getMemberLocation(), TU)))
  740. return true;
  741. } else if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo()) {
  742. if (Visit(TInfo->getTypeLoc()))
  743. return true;
  744. }
  745. // Visit the initializer value.
  746. if (Expr *Initializer = Init->getInit())
  747. if (Visit(MakeCXCursor(Initializer, ND, TU, RegionOfInterest)))
  748. return true;
  749. }
  750. }
  751. if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest)))
  752. return true;
  753. }
  754. return false;
  755. }
  756. bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
  757. if (VisitDeclaratorDecl(D))
  758. return true;
  759. if (Expr *BitWidth = D->getBitWidth())
  760. return Visit(MakeCXCursor(BitWidth, StmtParent, TU, RegionOfInterest));
  761. if (Expr *Init = D->getInClassInitializer())
  762. return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
  763. return false;
  764. }
  765. bool CursorVisitor::VisitVarDecl(VarDecl *D) {
  766. if (VisitDeclaratorDecl(D))
  767. return true;
  768. if (Expr *Init = D->getInit())
  769. return Visit(MakeCXCursor(Init, StmtParent, TU, RegionOfInterest));
  770. return false;
  771. }
  772. bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
  773. if (VisitDeclaratorDecl(D))
  774. return true;
  775. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
  776. if (Expr *DefArg = D->getDefaultArgument())
  777. return Visit(MakeCXCursor(DefArg, StmtParent, TU, RegionOfInterest));
  778. return false;
  779. }
  780. bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  781. // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
  782. // before visiting these template parameters.
  783. if (VisitTemplateParameters(D->getTemplateParameters()))
  784. return true;
  785. auto *FD = D->getTemplatedDecl();
  786. return VisitAttributes(FD) || VisitFunctionDecl(FD);
  787. }
  788. bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  789. // FIXME: Visit the "outer" template parameter lists on the TagDecl
  790. // before visiting these template parameters.
  791. if (VisitTemplateParameters(D->getTemplateParameters()))
  792. return true;
  793. auto *CD = D->getTemplatedDecl();
  794. return VisitAttributes(CD) || VisitCXXRecordDecl(CD);
  795. }
  796. bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
  797. if (VisitTemplateParameters(D->getTemplateParameters()))
  798. return true;
  799. if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
  800. VisitTemplateArgumentLoc(D->getDefaultArgument()))
  801. return true;
  802. return false;
  803. }
  804. bool CursorVisitor::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
  805. // Visit the bound, if it's explicit.
  806. if (D->hasExplicitBound()) {
  807. if (auto TInfo = D->getTypeSourceInfo()) {
  808. if (Visit(TInfo->getTypeLoc()))
  809. return true;
  810. }
  811. }
  812. return false;
  813. }
  814. bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
  815. if (TypeSourceInfo *TSInfo = ND->getReturnTypeSourceInfo())
  816. if (Visit(TSInfo->getTypeLoc()))
  817. return true;
  818. for (const auto *P : ND->parameters()) {
  819. if (Visit(MakeCXCursor(P, TU, RegionOfInterest)))
  820. return true;
  821. }
  822. return ND->isThisDeclarationADefinition() &&
  823. Visit(MakeCXCursor(ND->getBody(), StmtParent, TU, RegionOfInterest));
  824. }
  825. template <typename DeclIt>
  826. static void addRangedDeclsInContainer(DeclIt *DI_current, DeclIt DE_current,
  827. SourceManager &SM, SourceLocation EndLoc,
  828. SmallVectorImpl<Decl *> &Decls) {
  829. DeclIt next = *DI_current;
  830. while (++next != DE_current) {
  831. Decl *D_next = *next;
  832. if (!D_next)
  833. break;
  834. SourceLocation L = D_next->getBeginLoc();
  835. if (!L.isValid())
  836. break;
  837. if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
  838. *DI_current = next;
  839. Decls.push_back(D_next);
  840. continue;
  841. }
  842. break;
  843. }
  844. }
  845. bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
  846. // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
  847. // an @implementation can lexically contain Decls that are not properly
  848. // nested in the AST. When we identify such cases, we need to retrofit
  849. // this nesting here.
  850. if (!DI_current && !FileDI_current)
  851. return VisitDeclContext(D);
  852. // Scan the Decls that immediately come after the container
  853. // in the current DeclContext. If any fall within the
  854. // container's lexical region, stash them into a vector
  855. // for later processing.
  856. SmallVector<Decl *, 24> DeclsInContainer;
  857. SourceLocation EndLoc = D->getSourceRange().getEnd();
  858. SourceManager &SM = AU->getSourceManager();
  859. if (EndLoc.isValid()) {
  860. if (DI_current) {
  861. addRangedDeclsInContainer(DI_current, DE_current, SM, EndLoc,
  862. DeclsInContainer);
  863. } else {
  864. addRangedDeclsInContainer(FileDI_current, FileDE_current, SM, EndLoc,
  865. DeclsInContainer);
  866. }
  867. }
  868. // The common case.
  869. if (DeclsInContainer.empty())
  870. return VisitDeclContext(D);
  871. // Get all the Decls in the DeclContext, and sort them with the
  872. // additional ones we've collected. Then visit them.
  873. for (auto *SubDecl : D->decls()) {
  874. if (!SubDecl || SubDecl->getLexicalDeclContext() != D ||
  875. SubDecl->getBeginLoc().isInvalid())
  876. continue;
  877. DeclsInContainer.push_back(SubDecl);
  878. }
  879. // Now sort the Decls so that they appear in lexical order.
  880. llvm::sort(DeclsInContainer, [&SM](Decl *A, Decl *B) {
  881. SourceLocation L_A = A->getBeginLoc();
  882. SourceLocation L_B = B->getBeginLoc();
  883. return L_A != L_B
  884. ? SM.isBeforeInTranslationUnit(L_A, L_B)
  885. : SM.isBeforeInTranslationUnit(A->getEndLoc(), B->getEndLoc());
  886. });
  887. // Now visit the decls.
  888. for (SmallVectorImpl<Decl *>::iterator I = DeclsInContainer.begin(),
  889. E = DeclsInContainer.end();
  890. I != E; ++I) {
  891. CXCursor Cursor = MakeCXCursor(*I, TU, RegionOfInterest);
  892. const Optional<bool> &V = shouldVisitCursor(Cursor);
  893. if (!V.hasValue())
  894. continue;
  895. if (!V.getValue())
  896. return false;
  897. if (Visit(Cursor, true))
  898. return true;
  899. }
  900. return false;
  901. }
  902. bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
  903. if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
  904. TU)))
  905. return true;
  906. if (VisitObjCTypeParamList(ND->getTypeParamList()))
  907. return true;
  908. ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
  909. for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
  910. E = ND->protocol_end();
  911. I != E; ++I, ++PL)
  912. if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
  913. return true;
  914. return VisitObjCContainerDecl(ND);
  915. }
  916. bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
  917. if (!PID->isThisDeclarationADefinition())
  918. return Visit(MakeCursorObjCProtocolRef(PID, PID->getLocation(), TU));
  919. ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
  920. for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
  921. E = PID->protocol_end();
  922. I != E; ++I, ++PL)
  923. if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
  924. return true;
  925. return VisitObjCContainerDecl(PID);
  926. }
  927. bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
  928. if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
  929. return true;
  930. // FIXME: This implements a workaround with @property declarations also being
  931. // installed in the DeclContext for the @interface. Eventually this code
  932. // should be removed.
  933. ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
  934. if (!CDecl || !CDecl->IsClassExtension())
  935. return false;
  936. ObjCInterfaceDecl *ID = CDecl->getClassInterface();
  937. if (!ID)
  938. return false;
  939. IdentifierInfo *PropertyId = PD->getIdentifier();
  940. ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(
  941. cast<DeclContext>(ID), PropertyId, PD->getQueryKind());
  942. if (!prevDecl)
  943. return false;
  944. // Visit synthesized methods since they will be skipped when visiting
  945. // the @interface.
  946. if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
  947. if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
  948. if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
  949. return true;
  950. if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
  951. if (MD->isPropertyAccessor() && MD->getLexicalDeclContext() == CDecl)
  952. if (Visit(MakeCXCursor(MD, TU, RegionOfInterest)))
  953. return true;
  954. return false;
  955. }
  956. bool CursorVisitor::VisitObjCTypeParamList(ObjCTypeParamList *typeParamList) {
  957. if (!typeParamList)
  958. return false;
  959. for (auto *typeParam : *typeParamList) {
  960. // Visit the type parameter.
  961. if (Visit(MakeCXCursor(typeParam, TU, RegionOfInterest)))
  962. return true;
  963. }
  964. return false;
  965. }
  966. bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
  967. if (!D->isThisDeclarationADefinition()) {
  968. // Forward declaration is treated like a reference.
  969. return Visit(MakeCursorObjCClassRef(D, D->getLocation(), TU));
  970. }
  971. // Objective-C type parameters.
  972. if (VisitObjCTypeParamList(D->getTypeParamListAsWritten()))
  973. return true;
  974. // Issue callbacks for super class.
  975. if (D->getSuperClass() && Visit(MakeCursorObjCSuperClassRef(
  976. D->getSuperClass(), D->getSuperClassLoc(), TU)))
  977. return true;
  978. if (TypeSourceInfo *SuperClassTInfo = D->getSuperClassTInfo())
  979. if (Visit(SuperClassTInfo->getTypeLoc()))
  980. return true;
  981. ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
  982. for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
  983. E = D->protocol_end();
  984. I != E; ++I, ++PL)
  985. if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
  986. return true;
  987. return VisitObjCContainerDecl(D);
  988. }
  989. bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
  990. return VisitObjCContainerDecl(D);
  991. }
  992. bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
  993. // 'ID' could be null when dealing with invalid code.
  994. if (ObjCInterfaceDecl *ID = D->getClassInterface())
  995. if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
  996. return true;
  997. return VisitObjCImplDecl(D);
  998. }
  999. bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
  1000. #if 0
  1001. // Issue callbacks for super class.
  1002. // FIXME: No source location information!
  1003. if (D->getSuperClass() &&
  1004. Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
  1005. D->getSuperClassLoc(),
  1006. TU)))
  1007. return true;
  1008. #endif
  1009. return VisitObjCImplDecl(D);
  1010. }
  1011. bool CursorVisitor::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PD) {
  1012. if (ObjCIvarDecl *Ivar = PD->getPropertyIvarDecl())
  1013. if (PD->isIvarNameSpecified())
  1014. return Visit(MakeCursorMemberRef(Ivar, PD->getPropertyIvarDeclLoc(), TU));
  1015. return false;
  1016. }
  1017. bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
  1018. return VisitDeclContext(D);
  1019. }
  1020. bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  1021. // Visit nested-name-specifier.
  1022. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1023. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1024. return true;
  1025. return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
  1026. D->getTargetNameLoc(), TU));
  1027. }
  1028. bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
  1029. // Visit nested-name-specifier.
  1030. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
  1031. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1032. return true;
  1033. }
  1034. if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
  1035. return true;
  1036. return VisitDeclarationNameInfo(D->getNameInfo());
  1037. }
  1038. bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1039. // Visit nested-name-specifier.
  1040. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1041. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1042. return true;
  1043. return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
  1044. D->getIdentLocation(), TU));
  1045. }
  1046. bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  1047. // Visit nested-name-specifier.
  1048. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc()) {
  1049. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1050. return true;
  1051. }
  1052. return VisitDeclarationNameInfo(D->getNameInfo());
  1053. }
  1054. bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
  1055. UnresolvedUsingTypenameDecl *D) {
  1056. // Visit nested-name-specifier.
  1057. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1058. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1059. return true;
  1060. return false;
  1061. }
  1062. bool CursorVisitor::VisitStaticAssertDecl(StaticAssertDecl *D) {
  1063. if (Visit(MakeCXCursor(D->getAssertExpr(), StmtParent, TU, RegionOfInterest)))
  1064. return true;
  1065. if (StringLiteral *Message = D->getMessage())
  1066. if (Visit(MakeCXCursor(Message, StmtParent, TU, RegionOfInterest)))
  1067. return true;
  1068. return false;
  1069. }
  1070. bool CursorVisitor::VisitFriendDecl(FriendDecl *D) {
  1071. if (NamedDecl *FriendD = D->getFriendDecl()) {
  1072. if (Visit(MakeCXCursor(FriendD, TU, RegionOfInterest)))
  1073. return true;
  1074. } else if (TypeSourceInfo *TI = D->getFriendType()) {
  1075. if (Visit(TI->getTypeLoc()))
  1076. return true;
  1077. }
  1078. return false;
  1079. }
  1080. bool CursorVisitor::VisitDecompositionDecl(DecompositionDecl *D) {
  1081. for (auto *B : D->bindings()) {
  1082. if (Visit(MakeCXCursor(B, TU, RegionOfInterest)))
  1083. return true;
  1084. }
  1085. return VisitVarDecl(D);
  1086. }
  1087. bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
  1088. switch (Name.getName().getNameKind()) {
  1089. case clang::DeclarationName::Identifier:
  1090. case clang::DeclarationName::CXXLiteralOperatorName:
  1091. case clang::DeclarationName::CXXDeductionGuideName:
  1092. case clang::DeclarationName::CXXOperatorName:
  1093. case clang::DeclarationName::CXXUsingDirective:
  1094. return false;
  1095. case clang::DeclarationName::CXXConstructorName:
  1096. case clang::DeclarationName::CXXDestructorName:
  1097. case clang::DeclarationName::CXXConversionFunctionName:
  1098. if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
  1099. return Visit(TSInfo->getTypeLoc());
  1100. return false;
  1101. case clang::DeclarationName::ObjCZeroArgSelector:
  1102. case clang::DeclarationName::ObjCOneArgSelector:
  1103. case clang::DeclarationName::ObjCMultiArgSelector:
  1104. // FIXME: Per-identifier location info?
  1105. return false;
  1106. }
  1107. llvm_unreachable("Invalid DeclarationName::Kind!");
  1108. }
  1109. bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
  1110. SourceRange Range) {
  1111. // FIXME: This whole routine is a hack to work around the lack of proper
  1112. // source information in nested-name-specifiers (PR5791). Since we do have
  1113. // a beginning source location, we can visit the first component of the
  1114. // nested-name-specifier, if it's a single-token component.
  1115. if (!NNS)
  1116. return false;
  1117. // Get the first component in the nested-name-specifier.
  1118. while (NestedNameSpecifier *Prefix = NNS->getPrefix())
  1119. NNS = Prefix;
  1120. switch (NNS->getKind()) {
  1121. case NestedNameSpecifier::Namespace:
  1122. return Visit(
  1123. MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(), TU));
  1124. case NestedNameSpecifier::NamespaceAlias:
  1125. return Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
  1126. Range.getBegin(), TU));
  1127. case NestedNameSpecifier::TypeSpec: {
  1128. // If the type has a form where we know that the beginning of the source
  1129. // range matches up with a reference cursor. Visit the appropriate reference
  1130. // cursor.
  1131. const Type *T = NNS->getAsType();
  1132. if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
  1133. return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
  1134. if (const TagType *Tag = dyn_cast<TagType>(T))
  1135. return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
  1136. if (const TemplateSpecializationType *TST =
  1137. dyn_cast<TemplateSpecializationType>(T))
  1138. return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
  1139. break;
  1140. }
  1141. case NestedNameSpecifier::TypeSpecWithTemplate:
  1142. case NestedNameSpecifier::Global:
  1143. case NestedNameSpecifier::Identifier:
  1144. case NestedNameSpecifier::Super:
  1145. break;
  1146. }
  1147. return false;
  1148. }
  1149. bool CursorVisitor::VisitNestedNameSpecifierLoc(
  1150. NestedNameSpecifierLoc Qualifier) {
  1151. SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
  1152. for (; Qualifier; Qualifier = Qualifier.getPrefix())
  1153. Qualifiers.push_back(Qualifier);
  1154. while (!Qualifiers.empty()) {
  1155. NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
  1156. NestedNameSpecifier *NNS = Q.getNestedNameSpecifier();
  1157. switch (NNS->getKind()) {
  1158. case NestedNameSpecifier::Namespace:
  1159. if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(),
  1160. Q.getLocalBeginLoc(), TU)))
  1161. return true;
  1162. break;
  1163. case NestedNameSpecifier::NamespaceAlias:
  1164. if (Visit(MakeCursorNamespaceRef(NNS->getAsNamespaceAlias(),
  1165. Q.getLocalBeginLoc(), TU)))
  1166. return true;
  1167. break;
  1168. case NestedNameSpecifier::TypeSpec:
  1169. case NestedNameSpecifier::TypeSpecWithTemplate:
  1170. if (Visit(Q.getTypeLoc()))
  1171. return true;
  1172. break;
  1173. case NestedNameSpecifier::Global:
  1174. case NestedNameSpecifier::Identifier:
  1175. case NestedNameSpecifier::Super:
  1176. break;
  1177. }
  1178. }
  1179. return false;
  1180. }
  1181. bool CursorVisitor::VisitTemplateParameters(
  1182. const TemplateParameterList *Params) {
  1183. if (!Params)
  1184. return false;
  1185. for (TemplateParameterList::const_iterator P = Params->begin(),
  1186. PEnd = Params->end();
  1187. P != PEnd; ++P) {
  1188. if (Visit(MakeCXCursor(*P, TU, RegionOfInterest)))
  1189. return true;
  1190. }
  1191. return false;
  1192. }
  1193. bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
  1194. switch (Name.getKind()) {
  1195. case TemplateName::Template:
  1196. return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
  1197. case TemplateName::OverloadedTemplate:
  1198. // Visit the overloaded template set.
  1199. if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
  1200. return true;
  1201. return false;
  1202. case TemplateName::AssumedTemplate:
  1203. // FIXME: Visit DeclarationName?
  1204. return false;
  1205. case TemplateName::DependentTemplate:
  1206. // FIXME: Visit nested-name-specifier.
  1207. return false;
  1208. case TemplateName::QualifiedTemplate:
  1209. // FIXME: Visit nested-name-specifier.
  1210. return Visit(MakeCursorTemplateRef(
  1211. Name.getAsQualifiedTemplateName()->getDecl(), Loc, TU));
  1212. case TemplateName::SubstTemplateTemplateParm:
  1213. return Visit(MakeCursorTemplateRef(
  1214. Name.getAsSubstTemplateTemplateParm()->getParameter(), Loc, TU));
  1215. case TemplateName::SubstTemplateTemplateParmPack:
  1216. return Visit(MakeCursorTemplateRef(
  1217. Name.getAsSubstTemplateTemplateParmPack()->getParameterPack(), Loc,
  1218. TU));
  1219. }
  1220. llvm_unreachable("Invalid TemplateName::Kind!");
  1221. }
  1222. bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
  1223. switch (TAL.getArgument().getKind()) {
  1224. case TemplateArgument::Null:
  1225. case TemplateArgument::Integral:
  1226. case TemplateArgument::Pack:
  1227. return false;
  1228. case TemplateArgument::Type:
  1229. if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
  1230. return Visit(TSInfo->getTypeLoc());
  1231. return false;
  1232. case TemplateArgument::Declaration:
  1233. if (Expr *E = TAL.getSourceDeclExpression())
  1234. return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
  1235. return false;
  1236. case TemplateArgument::NullPtr:
  1237. if (Expr *E = TAL.getSourceNullPtrExpression())
  1238. return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
  1239. return false;
  1240. case TemplateArgument::Expression:
  1241. if (Expr *E = TAL.getSourceExpression())
  1242. return Visit(MakeCXCursor(E, StmtParent, TU, RegionOfInterest));
  1243. return false;
  1244. case TemplateArgument::Template:
  1245. case TemplateArgument::TemplateExpansion:
  1246. if (VisitNestedNameSpecifierLoc(TAL.getTemplateQualifierLoc()))
  1247. return true;
  1248. return VisitTemplateName(TAL.getArgument().getAsTemplateOrTemplatePattern(),
  1249. TAL.getTemplateNameLoc());
  1250. }
  1251. llvm_unreachable("Invalid TemplateArgument::Kind!");
  1252. }
  1253. bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
  1254. return VisitDeclContext(D);
  1255. }
  1256. bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  1257. return Visit(TL.getUnqualifiedLoc());
  1258. }
  1259. bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  1260. ASTContext &Context = AU->getASTContext();
  1261. // Some builtin types (such as Objective-C's "id", "sel", and
  1262. // "Class") have associated declarations. Create cursors for those.
  1263. QualType VisitType;
  1264. switch (TL.getTypePtr()->getKind()) {
  1265. case BuiltinType::Void:
  1266. case BuiltinType::NullPtr:
  1267. case BuiltinType::Dependent:
  1268. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1269. case BuiltinType::Id:
  1270. #include "clang/Basic/OpenCLImageTypes.def"
  1271. #define EXT_OPAQUE_TYPE(ExtTYpe, Id, Ext) case BuiltinType::Id:
  1272. #include "clang/Basic/OpenCLExtensionTypes.def"
  1273. case BuiltinType::OCLSampler:
  1274. case BuiltinType::OCLEvent:
  1275. case BuiltinType::OCLClkEvent:
  1276. case BuiltinType::OCLQueue:
  1277. case BuiltinType::OCLReserveID:
  1278. #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  1279. #include "clang/Basic/AArch64SVEACLETypes.def"
  1280. #define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
  1281. #include "clang/Basic/PPCTypes.def"
  1282. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  1283. #include "clang/Basic/RISCVVTypes.def"
  1284. #define BUILTIN_TYPE(Id, SingletonId)
  1285. #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  1286. #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
  1287. #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
  1288. #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
  1289. #include "clang/AST/BuiltinTypes.def"
  1290. break;
  1291. case BuiltinType::ObjCId:
  1292. VisitType = Context.getObjCIdType();
  1293. break;
  1294. case BuiltinType::ObjCClass:
  1295. VisitType = Context.getObjCClassType();
  1296. break;
  1297. case BuiltinType::ObjCSel:
  1298. VisitType = Context.getObjCSelType();
  1299. break;
  1300. }
  1301. if (!VisitType.isNull()) {
  1302. if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
  1303. return Visit(
  1304. MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), TU));
  1305. }
  1306. return false;
  1307. }
  1308. bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  1309. return Visit(MakeCursorTypeRef(TL.getTypedefNameDecl(), TL.getNameLoc(), TU));
  1310. }
  1311. bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  1312. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1313. }
  1314. bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
  1315. if (TL.isDefinition())
  1316. return Visit(MakeCXCursor(TL.getDecl(), TU, RegionOfInterest));
  1317. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1318. }
  1319. bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  1320. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1321. }
  1322. bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  1323. return Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU));
  1324. }
  1325. bool CursorVisitor::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  1326. if (Visit(MakeCursorTypeRef(TL.getDecl(), TL.getBeginLoc(), TU)))
  1327. return true;
  1328. for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
  1329. if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
  1330. TU)))
  1331. return true;
  1332. }
  1333. return false;
  1334. }
  1335. bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  1336. if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
  1337. return true;
  1338. for (unsigned I = 0, N = TL.getNumTypeArgs(); I != N; ++I) {
  1339. if (Visit(TL.getTypeArgTInfo(I)->getTypeLoc()))
  1340. return true;
  1341. }
  1342. for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
  1343. if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
  1344. TU)))
  1345. return true;
  1346. }
  1347. return false;
  1348. }
  1349. bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  1350. return Visit(TL.getPointeeLoc());
  1351. }
  1352. bool CursorVisitor::VisitParenTypeLoc(ParenTypeLoc TL) {
  1353. return Visit(TL.getInnerLoc());
  1354. }
  1355. bool CursorVisitor::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  1356. return Visit(TL.getInnerLoc());
  1357. }
  1358. bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
  1359. return Visit(TL.getPointeeLoc());
  1360. }
  1361. bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  1362. return Visit(TL.getPointeeLoc());
  1363. }
  1364. bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  1365. return Visit(TL.getPointeeLoc());
  1366. }
  1367. bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  1368. return Visit(TL.getPointeeLoc());
  1369. }
  1370. bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  1371. return Visit(TL.getPointeeLoc());
  1372. }
  1373. bool CursorVisitor::VisitUsingTypeLoc(UsingTypeLoc TL) { return false; }
  1374. bool CursorVisitor::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  1375. return Visit(TL.getModifiedLoc());
  1376. }
  1377. bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
  1378. bool SkipResultType) {
  1379. if (!SkipResultType && Visit(TL.getReturnLoc()))
  1380. return true;
  1381. for (unsigned I = 0, N = TL.getNumParams(); I != N; ++I)
  1382. if (Decl *D = TL.getParam(I))
  1383. if (Visit(MakeCXCursor(D, TU, RegionOfInterest)))
  1384. return true;
  1385. return false;
  1386. }
  1387. bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  1388. if (Visit(TL.getElementLoc()))
  1389. return true;
  1390. if (Expr *Size = TL.getSizeExpr())
  1391. return Visit(MakeCXCursor(Size, StmtParent, TU, RegionOfInterest));
  1392. return false;
  1393. }
  1394. bool CursorVisitor::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  1395. return Visit(TL.getOriginalLoc());
  1396. }
  1397. bool CursorVisitor::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  1398. return Visit(TL.getOriginalLoc());
  1399. }
  1400. bool CursorVisitor::VisitDeducedTemplateSpecializationTypeLoc(
  1401. DeducedTemplateSpecializationTypeLoc TL) {
  1402. if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
  1403. TL.getTemplateNameLoc()))
  1404. return true;
  1405. return false;
  1406. }
  1407. bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
  1408. TemplateSpecializationTypeLoc TL) {
  1409. // Visit the template name.
  1410. if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
  1411. TL.getTemplateNameLoc()))
  1412. return true;
  1413. // Visit the template arguments.
  1414. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
  1415. if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
  1416. return true;
  1417. return false;
  1418. }
  1419. bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  1420. return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
  1421. }
  1422. bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  1423. if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
  1424. return Visit(TSInfo->getTypeLoc());
  1425. return false;
  1426. }
  1427. bool CursorVisitor::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  1428. if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
  1429. return Visit(TSInfo->getTypeLoc());
  1430. return false;
  1431. }
  1432. bool CursorVisitor::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  1433. return VisitNestedNameSpecifierLoc(TL.getQualifierLoc());
  1434. }
  1435. bool CursorVisitor::VisitDependentTemplateSpecializationTypeLoc(
  1436. DependentTemplateSpecializationTypeLoc TL) {
  1437. // Visit the nested-name-specifier, if there is one.
  1438. if (TL.getQualifierLoc() && VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
  1439. return true;
  1440. // Visit the template arguments.
  1441. for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
  1442. if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
  1443. return true;
  1444. return false;
  1445. }
  1446. bool CursorVisitor::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  1447. if (VisitNestedNameSpecifierLoc(TL.getQualifierLoc()))
  1448. return true;
  1449. return Visit(TL.getNamedTypeLoc());
  1450. }
  1451. bool CursorVisitor::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  1452. return Visit(TL.getPatternLoc());
  1453. }
  1454. bool CursorVisitor::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  1455. if (Expr *E = TL.getUnderlyingExpr())
  1456. return Visit(MakeCXCursor(E, StmtParent, TU));
  1457. return false;
  1458. }
  1459. bool CursorVisitor::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  1460. return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
  1461. }
  1462. bool CursorVisitor::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  1463. return Visit(TL.getValueLoc());
  1464. }
  1465. bool CursorVisitor::VisitPipeTypeLoc(PipeTypeLoc TL) {
  1466. return Visit(TL.getValueLoc());
  1467. }
  1468. #define DEFAULT_TYPELOC_IMPL(CLASS, PARENT) \
  1469. bool CursorVisitor::Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
  1470. return Visit##PARENT##Loc(TL); \
  1471. }
  1472. DEFAULT_TYPELOC_IMPL(Complex, Type)
  1473. DEFAULT_TYPELOC_IMPL(ConstantArray, ArrayType)
  1474. DEFAULT_TYPELOC_IMPL(IncompleteArray, ArrayType)
  1475. DEFAULT_TYPELOC_IMPL(VariableArray, ArrayType)
  1476. DEFAULT_TYPELOC_IMPL(DependentSizedArray, ArrayType)
  1477. DEFAULT_TYPELOC_IMPL(DependentAddressSpace, Type)
  1478. DEFAULT_TYPELOC_IMPL(DependentVector, Type)
  1479. DEFAULT_TYPELOC_IMPL(DependentSizedExtVector, Type)
  1480. DEFAULT_TYPELOC_IMPL(Vector, Type)
  1481. DEFAULT_TYPELOC_IMPL(ExtVector, VectorType)
  1482. DEFAULT_TYPELOC_IMPL(ConstantMatrix, MatrixType)
  1483. DEFAULT_TYPELOC_IMPL(DependentSizedMatrix, MatrixType)
  1484. DEFAULT_TYPELOC_IMPL(FunctionProto, FunctionType)
  1485. DEFAULT_TYPELOC_IMPL(FunctionNoProto, FunctionType)
  1486. DEFAULT_TYPELOC_IMPL(Record, TagType)
  1487. DEFAULT_TYPELOC_IMPL(Enum, TagType)
  1488. DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParm, Type)
  1489. DEFAULT_TYPELOC_IMPL(SubstTemplateTypeParmPack, Type)
  1490. DEFAULT_TYPELOC_IMPL(Auto, Type)
  1491. DEFAULT_TYPELOC_IMPL(BitInt, Type)
  1492. DEFAULT_TYPELOC_IMPL(DependentBitInt, Type)
  1493. bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
  1494. // Visit the nested-name-specifier, if present.
  1495. if (NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc())
  1496. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  1497. return true;
  1498. if (D->isCompleteDefinition()) {
  1499. for (const auto &I : D->bases()) {
  1500. if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(&I, TU)))
  1501. return true;
  1502. }
  1503. }
  1504. return VisitTagDecl(D);
  1505. }
  1506. bool CursorVisitor::VisitAttributes(Decl *D) {
  1507. for (const auto *I : D->attrs())
  1508. if ((TU->ParsingOptions & CXTranslationUnit_VisitImplicitAttributes ||
  1509. !I->isImplicit()) &&
  1510. Visit(MakeCXCursor(I, D, TU)))
  1511. return true;
  1512. return false;
  1513. }
  1514. //===----------------------------------------------------------------------===//
  1515. // Data-recursive visitor methods.
  1516. //===----------------------------------------------------------------------===//
  1517. namespace {
  1518. #define DEF_JOB(NAME, DATA, KIND) \
  1519. class NAME : public VisitorJob { \
  1520. public: \
  1521. NAME(const DATA *d, CXCursor parent) \
  1522. : VisitorJob(parent, VisitorJob::KIND, d) {} \
  1523. static bool classof(const VisitorJob *VJ) { \
  1524. return VJ->getKind() == KIND; \
  1525. } \
  1526. const DATA *get() const { return static_cast<const DATA *>(data[0]); } \
  1527. };
  1528. DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
  1529. DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
  1530. DEF_JOB(DeclRefExprParts, DeclRefExpr, DeclRefExprPartsKind)
  1531. DEF_JOB(OverloadExprParts, OverloadExpr, OverloadExprPartsKind)
  1532. DEF_JOB(SizeOfPackExprParts, SizeOfPackExpr, SizeOfPackExprPartsKind)
  1533. DEF_JOB(LambdaExprParts, LambdaExpr, LambdaExprPartsKind)
  1534. DEF_JOB(PostChildrenVisit, void, PostChildrenVisitKind)
  1535. #undef DEF_JOB
  1536. class ExplicitTemplateArgsVisit : public VisitorJob {
  1537. public:
  1538. ExplicitTemplateArgsVisit(const TemplateArgumentLoc *Begin,
  1539. const TemplateArgumentLoc *End, CXCursor parent)
  1540. : VisitorJob(parent, VisitorJob::ExplicitTemplateArgsVisitKind, Begin,
  1541. End) {}
  1542. static bool classof(const VisitorJob *VJ) {
  1543. return VJ->getKind() == ExplicitTemplateArgsVisitKind;
  1544. }
  1545. const TemplateArgumentLoc *begin() const {
  1546. return static_cast<const TemplateArgumentLoc *>(data[0]);
  1547. }
  1548. const TemplateArgumentLoc *end() {
  1549. return static_cast<const TemplateArgumentLoc *>(data[1]);
  1550. }
  1551. };
  1552. class DeclVisit : public VisitorJob {
  1553. public:
  1554. DeclVisit(const Decl *D, CXCursor parent, bool isFirst)
  1555. : VisitorJob(parent, VisitorJob::DeclVisitKind, D,
  1556. isFirst ? (void *)1 : (void *)nullptr) {}
  1557. static bool classof(const VisitorJob *VJ) {
  1558. return VJ->getKind() == DeclVisitKind;
  1559. }
  1560. const Decl *get() const { return static_cast<const Decl *>(data[0]); }
  1561. bool isFirst() const { return data[1] != nullptr; }
  1562. };
  1563. class TypeLocVisit : public VisitorJob {
  1564. public:
  1565. TypeLocVisit(TypeLoc tl, CXCursor parent)
  1566. : VisitorJob(parent, VisitorJob::TypeLocVisitKind,
  1567. tl.getType().getAsOpaquePtr(), tl.getOpaqueData()) {}
  1568. static bool classof(const VisitorJob *VJ) {
  1569. return VJ->getKind() == TypeLocVisitKind;
  1570. }
  1571. TypeLoc get() const {
  1572. QualType T = QualType::getFromOpaquePtr(data[0]);
  1573. return TypeLoc(T, const_cast<void *>(data[1]));
  1574. }
  1575. };
  1576. class LabelRefVisit : public VisitorJob {
  1577. public:
  1578. LabelRefVisit(LabelDecl *LD, SourceLocation labelLoc, CXCursor parent)
  1579. : VisitorJob(parent, VisitorJob::LabelRefVisitKind, LD,
  1580. labelLoc.getPtrEncoding()) {}
  1581. static bool classof(const VisitorJob *VJ) {
  1582. return VJ->getKind() == VisitorJob::LabelRefVisitKind;
  1583. }
  1584. const LabelDecl *get() const {
  1585. return static_cast<const LabelDecl *>(data[0]);
  1586. }
  1587. SourceLocation getLoc() const {
  1588. return SourceLocation::getFromPtrEncoding(data[1]);
  1589. }
  1590. };
  1591. class NestedNameSpecifierLocVisit : public VisitorJob {
  1592. public:
  1593. NestedNameSpecifierLocVisit(NestedNameSpecifierLoc Qualifier, CXCursor parent)
  1594. : VisitorJob(parent, VisitorJob::NestedNameSpecifierLocVisitKind,
  1595. Qualifier.getNestedNameSpecifier(),
  1596. Qualifier.getOpaqueData()) {}
  1597. static bool classof(const VisitorJob *VJ) {
  1598. return VJ->getKind() == VisitorJob::NestedNameSpecifierLocVisitKind;
  1599. }
  1600. NestedNameSpecifierLoc get() const {
  1601. return NestedNameSpecifierLoc(
  1602. const_cast<NestedNameSpecifier *>(
  1603. static_cast<const NestedNameSpecifier *>(data[0])),
  1604. const_cast<void *>(data[1]));
  1605. }
  1606. };
  1607. class DeclarationNameInfoVisit : public VisitorJob {
  1608. public:
  1609. DeclarationNameInfoVisit(const Stmt *S, CXCursor parent)
  1610. : VisitorJob(parent, VisitorJob::DeclarationNameInfoVisitKind, S) {}
  1611. static bool classof(const VisitorJob *VJ) {
  1612. return VJ->getKind() == VisitorJob::DeclarationNameInfoVisitKind;
  1613. }
  1614. DeclarationNameInfo get() const {
  1615. const Stmt *S = static_cast<const Stmt *>(data[0]);
  1616. switch (S->getStmtClass()) {
  1617. default:
  1618. llvm_unreachable("Unhandled Stmt");
  1619. case clang::Stmt::MSDependentExistsStmtClass:
  1620. return cast<MSDependentExistsStmt>(S)->getNameInfo();
  1621. case Stmt::CXXDependentScopeMemberExprClass:
  1622. return cast<CXXDependentScopeMemberExpr>(S)->getMemberNameInfo();
  1623. case Stmt::DependentScopeDeclRefExprClass:
  1624. return cast<DependentScopeDeclRefExpr>(S)->getNameInfo();
  1625. case Stmt::OMPCriticalDirectiveClass:
  1626. return cast<OMPCriticalDirective>(S)->getDirectiveName();
  1627. }
  1628. }
  1629. };
  1630. class MemberRefVisit : public VisitorJob {
  1631. public:
  1632. MemberRefVisit(const FieldDecl *D, SourceLocation L, CXCursor parent)
  1633. : VisitorJob(parent, VisitorJob::MemberRefVisitKind, D,
  1634. L.getPtrEncoding()) {}
  1635. static bool classof(const VisitorJob *VJ) {
  1636. return VJ->getKind() == VisitorJob::MemberRefVisitKind;
  1637. }
  1638. const FieldDecl *get() const {
  1639. return static_cast<const FieldDecl *>(data[0]);
  1640. }
  1641. SourceLocation getLoc() const {
  1642. return SourceLocation::getFromRawEncoding(
  1643. (SourceLocation::UIntTy)(uintptr_t)data[1]);
  1644. }
  1645. };
  1646. class EnqueueVisitor : public ConstStmtVisitor<EnqueueVisitor, void> {
  1647. friend class OMPClauseEnqueue;
  1648. VisitorWorkList &WL;
  1649. CXCursor Parent;
  1650. public:
  1651. EnqueueVisitor(VisitorWorkList &wl, CXCursor parent)
  1652. : WL(wl), Parent(parent) {}
  1653. void VisitAddrLabelExpr(const AddrLabelExpr *E);
  1654. void VisitBlockExpr(const BlockExpr *B);
  1655. void VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  1656. void VisitCompoundStmt(const CompoundStmt *S);
  1657. void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { /* Do nothing. */
  1658. }
  1659. void VisitMSDependentExistsStmt(const MSDependentExistsStmt *S);
  1660. void VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E);
  1661. void VisitCXXNewExpr(const CXXNewExpr *E);
  1662. void VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
  1663. void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E);
  1664. void VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E);
  1665. void VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E);
  1666. void VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  1667. void VisitCXXUnresolvedConstructExpr(const CXXUnresolvedConstructExpr *E);
  1668. void VisitCXXUuidofExpr(const CXXUuidofExpr *E);
  1669. void VisitCXXCatchStmt(const CXXCatchStmt *S);
  1670. void VisitCXXForRangeStmt(const CXXForRangeStmt *S);
  1671. void VisitDeclRefExpr(const DeclRefExpr *D);
  1672. void VisitDeclStmt(const DeclStmt *S);
  1673. void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E);
  1674. void VisitDesignatedInitExpr(const DesignatedInitExpr *E);
  1675. void VisitExplicitCastExpr(const ExplicitCastExpr *E);
  1676. void VisitForStmt(const ForStmt *FS);
  1677. void VisitGotoStmt(const GotoStmt *GS);
  1678. void VisitIfStmt(const IfStmt *If);
  1679. void VisitInitListExpr(const InitListExpr *IE);
  1680. void VisitMemberExpr(const MemberExpr *M);
  1681. void VisitOffsetOfExpr(const OffsetOfExpr *E);
  1682. void VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
  1683. void VisitObjCMessageExpr(const ObjCMessageExpr *M);
  1684. void VisitOverloadExpr(const OverloadExpr *E);
  1685. void VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
  1686. void VisitStmt(const Stmt *S);
  1687. void VisitSwitchStmt(const SwitchStmt *S);
  1688. void VisitWhileStmt(const WhileStmt *W);
  1689. void VisitTypeTraitExpr(const TypeTraitExpr *E);
  1690. void VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
  1691. void VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
  1692. void VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U);
  1693. void VisitVAArgExpr(const VAArgExpr *E);
  1694. void VisitSizeOfPackExpr(const SizeOfPackExpr *E);
  1695. void VisitPseudoObjectExpr(const PseudoObjectExpr *E);
  1696. void VisitOpaqueValueExpr(const OpaqueValueExpr *E);
  1697. void VisitLambdaExpr(const LambdaExpr *E);
  1698. void VisitOMPExecutableDirective(const OMPExecutableDirective *D);
  1699. void VisitOMPLoopBasedDirective(const OMPLoopBasedDirective *D);
  1700. void VisitOMPLoopDirective(const OMPLoopDirective *D);
  1701. void VisitOMPParallelDirective(const OMPParallelDirective *D);
  1702. void VisitOMPSimdDirective(const OMPSimdDirective *D);
  1703. void
  1704. VisitOMPLoopTransformationDirective(const OMPLoopTransformationDirective *D);
  1705. void VisitOMPTileDirective(const OMPTileDirective *D);
  1706. void VisitOMPUnrollDirective(const OMPUnrollDirective *D);
  1707. void VisitOMPForDirective(const OMPForDirective *D);
  1708. void VisitOMPForSimdDirective(const OMPForSimdDirective *D);
  1709. void VisitOMPSectionsDirective(const OMPSectionsDirective *D);
  1710. void VisitOMPSectionDirective(const OMPSectionDirective *D);
  1711. void VisitOMPSingleDirective(const OMPSingleDirective *D);
  1712. void VisitOMPMasterDirective(const OMPMasterDirective *D);
  1713. void VisitOMPCriticalDirective(const OMPCriticalDirective *D);
  1714. void VisitOMPParallelForDirective(const OMPParallelForDirective *D);
  1715. void VisitOMPParallelForSimdDirective(const OMPParallelForSimdDirective *D);
  1716. void VisitOMPParallelMasterDirective(const OMPParallelMasterDirective *D);
  1717. void VisitOMPParallelSectionsDirective(const OMPParallelSectionsDirective *D);
  1718. void VisitOMPTaskDirective(const OMPTaskDirective *D);
  1719. void VisitOMPTaskyieldDirective(const OMPTaskyieldDirective *D);
  1720. void VisitOMPBarrierDirective(const OMPBarrierDirective *D);
  1721. void VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D);
  1722. void VisitOMPTaskgroupDirective(const OMPTaskgroupDirective *D);
  1723. void
  1724. VisitOMPCancellationPointDirective(const OMPCancellationPointDirective *D);
  1725. void VisitOMPCancelDirective(const OMPCancelDirective *D);
  1726. void VisitOMPFlushDirective(const OMPFlushDirective *D);
  1727. void VisitOMPDepobjDirective(const OMPDepobjDirective *D);
  1728. void VisitOMPScanDirective(const OMPScanDirective *D);
  1729. void VisitOMPOrderedDirective(const OMPOrderedDirective *D);
  1730. void VisitOMPAtomicDirective(const OMPAtomicDirective *D);
  1731. void VisitOMPTargetDirective(const OMPTargetDirective *D);
  1732. void VisitOMPTargetDataDirective(const OMPTargetDataDirective *D);
  1733. void VisitOMPTargetEnterDataDirective(const OMPTargetEnterDataDirective *D);
  1734. void VisitOMPTargetExitDataDirective(const OMPTargetExitDataDirective *D);
  1735. void VisitOMPTargetParallelDirective(const OMPTargetParallelDirective *D);
  1736. void
  1737. VisitOMPTargetParallelForDirective(const OMPTargetParallelForDirective *D);
  1738. void VisitOMPTeamsDirective(const OMPTeamsDirective *D);
  1739. void VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D);
  1740. void VisitOMPTaskLoopSimdDirective(const OMPTaskLoopSimdDirective *D);
  1741. void VisitOMPMasterTaskLoopDirective(const OMPMasterTaskLoopDirective *D);
  1742. void
  1743. VisitOMPMasterTaskLoopSimdDirective(const OMPMasterTaskLoopSimdDirective *D);
  1744. void VisitOMPParallelMasterTaskLoopDirective(
  1745. const OMPParallelMasterTaskLoopDirective *D);
  1746. void VisitOMPParallelMasterTaskLoopSimdDirective(
  1747. const OMPParallelMasterTaskLoopSimdDirective *D);
  1748. void VisitOMPDistributeDirective(const OMPDistributeDirective *D);
  1749. void VisitOMPDistributeParallelForDirective(
  1750. const OMPDistributeParallelForDirective *D);
  1751. void VisitOMPDistributeParallelForSimdDirective(
  1752. const OMPDistributeParallelForSimdDirective *D);
  1753. void VisitOMPDistributeSimdDirective(const OMPDistributeSimdDirective *D);
  1754. void VisitOMPTargetParallelForSimdDirective(
  1755. const OMPTargetParallelForSimdDirective *D);
  1756. void VisitOMPTargetSimdDirective(const OMPTargetSimdDirective *D);
  1757. void VisitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective *D);
  1758. void VisitOMPTeamsDistributeSimdDirective(
  1759. const OMPTeamsDistributeSimdDirective *D);
  1760. void VisitOMPTeamsDistributeParallelForSimdDirective(
  1761. const OMPTeamsDistributeParallelForSimdDirective *D);
  1762. void VisitOMPTeamsDistributeParallelForDirective(
  1763. const OMPTeamsDistributeParallelForDirective *D);
  1764. void VisitOMPTargetTeamsDirective(const OMPTargetTeamsDirective *D);
  1765. void VisitOMPTargetTeamsDistributeDirective(
  1766. const OMPTargetTeamsDistributeDirective *D);
  1767. void VisitOMPTargetTeamsDistributeParallelForDirective(
  1768. const OMPTargetTeamsDistributeParallelForDirective *D);
  1769. void VisitOMPTargetTeamsDistributeParallelForSimdDirective(
  1770. const OMPTargetTeamsDistributeParallelForSimdDirective *D);
  1771. void VisitOMPTargetTeamsDistributeSimdDirective(
  1772. const OMPTargetTeamsDistributeSimdDirective *D);
  1773. private:
  1774. void AddDeclarationNameInfo(const Stmt *S);
  1775. void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc Qualifier);
  1776. void AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
  1777. unsigned NumTemplateArgs);
  1778. void AddMemberRef(const FieldDecl *D, SourceLocation L);
  1779. void AddStmt(const Stmt *S);
  1780. void AddDecl(const Decl *D, bool isFirst = true);
  1781. void AddTypeLoc(TypeSourceInfo *TI);
  1782. void EnqueueChildren(const Stmt *S);
  1783. void EnqueueChildren(const OMPClause *S);
  1784. };
  1785. } // namespace
  1786. void EnqueueVisitor::AddDeclarationNameInfo(const Stmt *S) {
  1787. // 'S' should always be non-null, since it comes from the
  1788. // statement we are visiting.
  1789. WL.push_back(DeclarationNameInfoVisit(S, Parent));
  1790. }
  1791. void EnqueueVisitor::AddNestedNameSpecifierLoc(
  1792. NestedNameSpecifierLoc Qualifier) {
  1793. if (Qualifier)
  1794. WL.push_back(NestedNameSpecifierLocVisit(Qualifier, Parent));
  1795. }
  1796. void EnqueueVisitor::AddStmt(const Stmt *S) {
  1797. if (S)
  1798. WL.push_back(StmtVisit(S, Parent));
  1799. }
  1800. void EnqueueVisitor::AddDecl(const Decl *D, bool isFirst) {
  1801. if (D)
  1802. WL.push_back(DeclVisit(D, Parent, isFirst));
  1803. }
  1804. void EnqueueVisitor::AddExplicitTemplateArgs(const TemplateArgumentLoc *A,
  1805. unsigned NumTemplateArgs) {
  1806. WL.push_back(ExplicitTemplateArgsVisit(A, A + NumTemplateArgs, Parent));
  1807. }
  1808. void EnqueueVisitor::AddMemberRef(const FieldDecl *D, SourceLocation L) {
  1809. if (D)
  1810. WL.push_back(MemberRefVisit(D, L, Parent));
  1811. }
  1812. void EnqueueVisitor::AddTypeLoc(TypeSourceInfo *TI) {
  1813. if (TI)
  1814. WL.push_back(TypeLocVisit(TI->getTypeLoc(), Parent));
  1815. }
  1816. void EnqueueVisitor::EnqueueChildren(const Stmt *S) {
  1817. unsigned size = WL.size();
  1818. for (const Stmt *SubStmt : S->children()) {
  1819. AddStmt(SubStmt);
  1820. }
  1821. if (size == WL.size())
  1822. return;
  1823. // Now reverse the entries we just added. This will match the DFS
  1824. // ordering performed by the worklist.
  1825. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
  1826. std::reverse(I, E);
  1827. }
  1828. namespace {
  1829. class OMPClauseEnqueue : public ConstOMPClauseVisitor<OMPClauseEnqueue> {
  1830. EnqueueVisitor *Visitor;
  1831. /// Process clauses with list of variables.
  1832. template <typename T> void VisitOMPClauseList(T *Node);
  1833. public:
  1834. OMPClauseEnqueue(EnqueueVisitor *Visitor) : Visitor(Visitor) {}
  1835. #define GEN_CLANG_CLAUSE_CLASS
  1836. #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(const Class *C);
  1837. #include "llvm/Frontend/OpenMP/OMP.inc"
  1838. void VisitOMPClauseWithPreInit(const OMPClauseWithPreInit *C);
  1839. void VisitOMPClauseWithPostUpdate(const OMPClauseWithPostUpdate *C);
  1840. };
  1841. void OMPClauseEnqueue::VisitOMPClauseWithPreInit(
  1842. const OMPClauseWithPreInit *C) {
  1843. Visitor->AddStmt(C->getPreInitStmt());
  1844. }
  1845. void OMPClauseEnqueue::VisitOMPClauseWithPostUpdate(
  1846. const OMPClauseWithPostUpdate *C) {
  1847. VisitOMPClauseWithPreInit(C);
  1848. Visitor->AddStmt(C->getPostUpdateExpr());
  1849. }
  1850. void OMPClauseEnqueue::VisitOMPIfClause(const OMPIfClause *C) {
  1851. VisitOMPClauseWithPreInit(C);
  1852. Visitor->AddStmt(C->getCondition());
  1853. }
  1854. void OMPClauseEnqueue::VisitOMPFinalClause(const OMPFinalClause *C) {
  1855. Visitor->AddStmt(C->getCondition());
  1856. }
  1857. void OMPClauseEnqueue::VisitOMPNumThreadsClause(const OMPNumThreadsClause *C) {
  1858. VisitOMPClauseWithPreInit(C);
  1859. Visitor->AddStmt(C->getNumThreads());
  1860. }
  1861. void OMPClauseEnqueue::VisitOMPSafelenClause(const OMPSafelenClause *C) {
  1862. Visitor->AddStmt(C->getSafelen());
  1863. }
  1864. void OMPClauseEnqueue::VisitOMPSimdlenClause(const OMPSimdlenClause *C) {
  1865. Visitor->AddStmt(C->getSimdlen());
  1866. }
  1867. void OMPClauseEnqueue::VisitOMPSizesClause(const OMPSizesClause *C) {
  1868. for (auto E : C->getSizesRefs())
  1869. Visitor->AddStmt(E);
  1870. }
  1871. void OMPClauseEnqueue::VisitOMPFullClause(const OMPFullClause *C) {}
  1872. void OMPClauseEnqueue::VisitOMPPartialClause(const OMPPartialClause *C) {
  1873. Visitor->AddStmt(C->getFactor());
  1874. }
  1875. void OMPClauseEnqueue::VisitOMPAllocatorClause(const OMPAllocatorClause *C) {
  1876. Visitor->AddStmt(C->getAllocator());
  1877. }
  1878. void OMPClauseEnqueue::VisitOMPCollapseClause(const OMPCollapseClause *C) {
  1879. Visitor->AddStmt(C->getNumForLoops());
  1880. }
  1881. void OMPClauseEnqueue::VisitOMPDefaultClause(const OMPDefaultClause *C) {}
  1882. void OMPClauseEnqueue::VisitOMPProcBindClause(const OMPProcBindClause *C) {}
  1883. void OMPClauseEnqueue::VisitOMPScheduleClause(const OMPScheduleClause *C) {
  1884. VisitOMPClauseWithPreInit(C);
  1885. Visitor->AddStmt(C->getChunkSize());
  1886. }
  1887. void OMPClauseEnqueue::VisitOMPOrderedClause(const OMPOrderedClause *C) {
  1888. Visitor->AddStmt(C->getNumForLoops());
  1889. }
  1890. void OMPClauseEnqueue::VisitOMPDetachClause(const OMPDetachClause *C) {
  1891. Visitor->AddStmt(C->getEventHandler());
  1892. }
  1893. void OMPClauseEnqueue::VisitOMPNowaitClause(const OMPNowaitClause *) {}
  1894. void OMPClauseEnqueue::VisitOMPUntiedClause(const OMPUntiedClause *) {}
  1895. void OMPClauseEnqueue::VisitOMPMergeableClause(const OMPMergeableClause *) {}
  1896. void OMPClauseEnqueue::VisitOMPReadClause(const OMPReadClause *) {}
  1897. void OMPClauseEnqueue::VisitOMPWriteClause(const OMPWriteClause *) {}
  1898. void OMPClauseEnqueue::VisitOMPUpdateClause(const OMPUpdateClause *) {}
  1899. void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
  1900. void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
  1901. void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
  1902. void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
  1903. void OMPClauseEnqueue::VisitOMPAcquireClause(const OMPAcquireClause *) {}
  1904. void OMPClauseEnqueue::VisitOMPReleaseClause(const OMPReleaseClause *) {}
  1905. void OMPClauseEnqueue::VisitOMPRelaxedClause(const OMPRelaxedClause *) {}
  1906. void OMPClauseEnqueue::VisitOMPThreadsClause(const OMPThreadsClause *) {}
  1907. void OMPClauseEnqueue::VisitOMPSIMDClause(const OMPSIMDClause *) {}
  1908. void OMPClauseEnqueue::VisitOMPNogroupClause(const OMPNogroupClause *) {}
  1909. void OMPClauseEnqueue::VisitOMPInitClause(const OMPInitClause *C) {
  1910. VisitOMPClauseList(C);
  1911. }
  1912. void OMPClauseEnqueue::VisitOMPUseClause(const OMPUseClause *C) {
  1913. Visitor->AddStmt(C->getInteropVar());
  1914. }
  1915. void OMPClauseEnqueue::VisitOMPDestroyClause(const OMPDestroyClause *C) {
  1916. if (C->getInteropVar())
  1917. Visitor->AddStmt(C->getInteropVar());
  1918. }
  1919. void OMPClauseEnqueue::VisitOMPNovariantsClause(const OMPNovariantsClause *C) {
  1920. Visitor->AddStmt(C->getCondition());
  1921. }
  1922. void OMPClauseEnqueue::VisitOMPNocontextClause(const OMPNocontextClause *C) {
  1923. Visitor->AddStmt(C->getCondition());
  1924. }
  1925. void OMPClauseEnqueue::VisitOMPFilterClause(const OMPFilterClause *C) {
  1926. VisitOMPClauseWithPreInit(C);
  1927. Visitor->AddStmt(C->getThreadID());
  1928. }
  1929. void OMPClauseEnqueue::VisitOMPAlignClause(const OMPAlignClause *C) {
  1930. Visitor->AddStmt(C->getAlignment());
  1931. }
  1932. void OMPClauseEnqueue::VisitOMPUnifiedAddressClause(
  1933. const OMPUnifiedAddressClause *) {}
  1934. void OMPClauseEnqueue::VisitOMPUnifiedSharedMemoryClause(
  1935. const OMPUnifiedSharedMemoryClause *) {}
  1936. void OMPClauseEnqueue::VisitOMPReverseOffloadClause(
  1937. const OMPReverseOffloadClause *) {}
  1938. void OMPClauseEnqueue::VisitOMPDynamicAllocatorsClause(
  1939. const OMPDynamicAllocatorsClause *) {}
  1940. void OMPClauseEnqueue::VisitOMPAtomicDefaultMemOrderClause(
  1941. const OMPAtomicDefaultMemOrderClause *) {}
  1942. void OMPClauseEnqueue::VisitOMPDeviceClause(const OMPDeviceClause *C) {
  1943. Visitor->AddStmt(C->getDevice());
  1944. }
  1945. void OMPClauseEnqueue::VisitOMPNumTeamsClause(const OMPNumTeamsClause *C) {
  1946. VisitOMPClauseWithPreInit(C);
  1947. Visitor->AddStmt(C->getNumTeams());
  1948. }
  1949. void OMPClauseEnqueue::VisitOMPThreadLimitClause(
  1950. const OMPThreadLimitClause *C) {
  1951. VisitOMPClauseWithPreInit(C);
  1952. Visitor->AddStmt(C->getThreadLimit());
  1953. }
  1954. void OMPClauseEnqueue::VisitOMPPriorityClause(const OMPPriorityClause *C) {
  1955. Visitor->AddStmt(C->getPriority());
  1956. }
  1957. void OMPClauseEnqueue::VisitOMPGrainsizeClause(const OMPGrainsizeClause *C) {
  1958. Visitor->AddStmt(C->getGrainsize());
  1959. }
  1960. void OMPClauseEnqueue::VisitOMPNumTasksClause(const OMPNumTasksClause *C) {
  1961. Visitor->AddStmt(C->getNumTasks());
  1962. }
  1963. void OMPClauseEnqueue::VisitOMPHintClause(const OMPHintClause *C) {
  1964. Visitor->AddStmt(C->getHint());
  1965. }
  1966. template <typename T> void OMPClauseEnqueue::VisitOMPClauseList(T *Node) {
  1967. for (const auto *I : Node->varlists()) {
  1968. Visitor->AddStmt(I);
  1969. }
  1970. }
  1971. void OMPClauseEnqueue::VisitOMPInclusiveClause(const OMPInclusiveClause *C) {
  1972. VisitOMPClauseList(C);
  1973. }
  1974. void OMPClauseEnqueue::VisitOMPExclusiveClause(const OMPExclusiveClause *C) {
  1975. VisitOMPClauseList(C);
  1976. }
  1977. void OMPClauseEnqueue::VisitOMPAllocateClause(const OMPAllocateClause *C) {
  1978. VisitOMPClauseList(C);
  1979. Visitor->AddStmt(C->getAllocator());
  1980. }
  1981. void OMPClauseEnqueue::VisitOMPPrivateClause(const OMPPrivateClause *C) {
  1982. VisitOMPClauseList(C);
  1983. for (const auto *E : C->private_copies()) {
  1984. Visitor->AddStmt(E);
  1985. }
  1986. }
  1987. void OMPClauseEnqueue::VisitOMPFirstprivateClause(
  1988. const OMPFirstprivateClause *C) {
  1989. VisitOMPClauseList(C);
  1990. VisitOMPClauseWithPreInit(C);
  1991. for (const auto *E : C->private_copies()) {
  1992. Visitor->AddStmt(E);
  1993. }
  1994. for (const auto *E : C->inits()) {
  1995. Visitor->AddStmt(E);
  1996. }
  1997. }
  1998. void OMPClauseEnqueue::VisitOMPLastprivateClause(
  1999. const OMPLastprivateClause *C) {
  2000. VisitOMPClauseList(C);
  2001. VisitOMPClauseWithPostUpdate(C);
  2002. for (auto *E : C->private_copies()) {
  2003. Visitor->AddStmt(E);
  2004. }
  2005. for (auto *E : C->source_exprs()) {
  2006. Visitor->AddStmt(E);
  2007. }
  2008. for (auto *E : C->destination_exprs()) {
  2009. Visitor->AddStmt(E);
  2010. }
  2011. for (auto *E : C->assignment_ops()) {
  2012. Visitor->AddStmt(E);
  2013. }
  2014. }
  2015. void OMPClauseEnqueue::VisitOMPSharedClause(const OMPSharedClause *C) {
  2016. VisitOMPClauseList(C);
  2017. }
  2018. void OMPClauseEnqueue::VisitOMPReductionClause(const OMPReductionClause *C) {
  2019. VisitOMPClauseList(C);
  2020. VisitOMPClauseWithPostUpdate(C);
  2021. for (auto *E : C->privates()) {
  2022. Visitor->AddStmt(E);
  2023. }
  2024. for (auto *E : C->lhs_exprs()) {
  2025. Visitor->AddStmt(E);
  2026. }
  2027. for (auto *E : C->rhs_exprs()) {
  2028. Visitor->AddStmt(E);
  2029. }
  2030. for (auto *E : C->reduction_ops()) {
  2031. Visitor->AddStmt(E);
  2032. }
  2033. if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
  2034. for (auto *E : C->copy_ops()) {
  2035. Visitor->AddStmt(E);
  2036. }
  2037. for (auto *E : C->copy_array_temps()) {
  2038. Visitor->AddStmt(E);
  2039. }
  2040. for (auto *E : C->copy_array_elems()) {
  2041. Visitor->AddStmt(E);
  2042. }
  2043. }
  2044. }
  2045. void OMPClauseEnqueue::VisitOMPTaskReductionClause(
  2046. const OMPTaskReductionClause *C) {
  2047. VisitOMPClauseList(C);
  2048. VisitOMPClauseWithPostUpdate(C);
  2049. for (auto *E : C->privates()) {
  2050. Visitor->AddStmt(E);
  2051. }
  2052. for (auto *E : C->lhs_exprs()) {
  2053. Visitor->AddStmt(E);
  2054. }
  2055. for (auto *E : C->rhs_exprs()) {
  2056. Visitor->AddStmt(E);
  2057. }
  2058. for (auto *E : C->reduction_ops()) {
  2059. Visitor->AddStmt(E);
  2060. }
  2061. }
  2062. void OMPClauseEnqueue::VisitOMPInReductionClause(
  2063. const OMPInReductionClause *C) {
  2064. VisitOMPClauseList(C);
  2065. VisitOMPClauseWithPostUpdate(C);
  2066. for (auto *E : C->privates()) {
  2067. Visitor->AddStmt(E);
  2068. }
  2069. for (auto *E : C->lhs_exprs()) {
  2070. Visitor->AddStmt(E);
  2071. }
  2072. for (auto *E : C->rhs_exprs()) {
  2073. Visitor->AddStmt(E);
  2074. }
  2075. for (auto *E : C->reduction_ops()) {
  2076. Visitor->AddStmt(E);
  2077. }
  2078. for (auto *E : C->taskgroup_descriptors())
  2079. Visitor->AddStmt(E);
  2080. }
  2081. void OMPClauseEnqueue::VisitOMPLinearClause(const OMPLinearClause *C) {
  2082. VisitOMPClauseList(C);
  2083. VisitOMPClauseWithPostUpdate(C);
  2084. for (const auto *E : C->privates()) {
  2085. Visitor->AddStmt(E);
  2086. }
  2087. for (const auto *E : C->inits()) {
  2088. Visitor->AddStmt(E);
  2089. }
  2090. for (const auto *E : C->updates()) {
  2091. Visitor->AddStmt(E);
  2092. }
  2093. for (const auto *E : C->finals()) {
  2094. Visitor->AddStmt(E);
  2095. }
  2096. Visitor->AddStmt(C->getStep());
  2097. Visitor->AddStmt(C->getCalcStep());
  2098. }
  2099. void OMPClauseEnqueue::VisitOMPAlignedClause(const OMPAlignedClause *C) {
  2100. VisitOMPClauseList(C);
  2101. Visitor->AddStmt(C->getAlignment());
  2102. }
  2103. void OMPClauseEnqueue::VisitOMPCopyinClause(const OMPCopyinClause *C) {
  2104. VisitOMPClauseList(C);
  2105. for (auto *E : C->source_exprs()) {
  2106. Visitor->AddStmt(E);
  2107. }
  2108. for (auto *E : C->destination_exprs()) {
  2109. Visitor->AddStmt(E);
  2110. }
  2111. for (auto *E : C->assignment_ops()) {
  2112. Visitor->AddStmt(E);
  2113. }
  2114. }
  2115. void OMPClauseEnqueue::VisitOMPCopyprivateClause(
  2116. const OMPCopyprivateClause *C) {
  2117. VisitOMPClauseList(C);
  2118. for (auto *E : C->source_exprs()) {
  2119. Visitor->AddStmt(E);
  2120. }
  2121. for (auto *E : C->destination_exprs()) {
  2122. Visitor->AddStmt(E);
  2123. }
  2124. for (auto *E : C->assignment_ops()) {
  2125. Visitor->AddStmt(E);
  2126. }
  2127. }
  2128. void OMPClauseEnqueue::VisitOMPFlushClause(const OMPFlushClause *C) {
  2129. VisitOMPClauseList(C);
  2130. }
  2131. void OMPClauseEnqueue::VisitOMPDepobjClause(const OMPDepobjClause *C) {
  2132. Visitor->AddStmt(C->getDepobj());
  2133. }
  2134. void OMPClauseEnqueue::VisitOMPDependClause(const OMPDependClause *C) {
  2135. VisitOMPClauseList(C);
  2136. }
  2137. void OMPClauseEnqueue::VisitOMPMapClause(const OMPMapClause *C) {
  2138. VisitOMPClauseList(C);
  2139. }
  2140. void OMPClauseEnqueue::VisitOMPDistScheduleClause(
  2141. const OMPDistScheduleClause *C) {
  2142. VisitOMPClauseWithPreInit(C);
  2143. Visitor->AddStmt(C->getChunkSize());
  2144. }
  2145. void OMPClauseEnqueue::VisitOMPDefaultmapClause(
  2146. const OMPDefaultmapClause * /*C*/) {}
  2147. void OMPClauseEnqueue::VisitOMPToClause(const OMPToClause *C) {
  2148. VisitOMPClauseList(C);
  2149. }
  2150. void OMPClauseEnqueue::VisitOMPFromClause(const OMPFromClause *C) {
  2151. VisitOMPClauseList(C);
  2152. }
  2153. void OMPClauseEnqueue::VisitOMPUseDevicePtrClause(
  2154. const OMPUseDevicePtrClause *C) {
  2155. VisitOMPClauseList(C);
  2156. }
  2157. void OMPClauseEnqueue::VisitOMPUseDeviceAddrClause(
  2158. const OMPUseDeviceAddrClause *C) {
  2159. VisitOMPClauseList(C);
  2160. }
  2161. void OMPClauseEnqueue::VisitOMPIsDevicePtrClause(
  2162. const OMPIsDevicePtrClause *C) {
  2163. VisitOMPClauseList(C);
  2164. }
  2165. void OMPClauseEnqueue::VisitOMPNontemporalClause(
  2166. const OMPNontemporalClause *C) {
  2167. VisitOMPClauseList(C);
  2168. for (const auto *E : C->private_refs())
  2169. Visitor->AddStmt(E);
  2170. }
  2171. void OMPClauseEnqueue::VisitOMPOrderClause(const OMPOrderClause *C) {}
  2172. void OMPClauseEnqueue::VisitOMPUsesAllocatorsClause(
  2173. const OMPUsesAllocatorsClause *C) {
  2174. for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
  2175. const OMPUsesAllocatorsClause::Data &D = C->getAllocatorData(I);
  2176. Visitor->AddStmt(D.Allocator);
  2177. Visitor->AddStmt(D.AllocatorTraits);
  2178. }
  2179. }
  2180. void OMPClauseEnqueue::VisitOMPAffinityClause(const OMPAffinityClause *C) {
  2181. Visitor->AddStmt(C->getModifier());
  2182. for (const Expr *E : C->varlists())
  2183. Visitor->AddStmt(E);
  2184. }
  2185. void OMPClauseEnqueue::VisitOMPBindClause(const OMPBindClause *C) {}
  2186. } // namespace
  2187. void EnqueueVisitor::EnqueueChildren(const OMPClause *S) {
  2188. unsigned size = WL.size();
  2189. OMPClauseEnqueue Visitor(this);
  2190. Visitor.Visit(S);
  2191. if (size == WL.size())
  2192. return;
  2193. // Now reverse the entries we just added. This will match the DFS
  2194. // ordering performed by the worklist.
  2195. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
  2196. std::reverse(I, E);
  2197. }
  2198. void EnqueueVisitor::VisitAddrLabelExpr(const AddrLabelExpr *E) {
  2199. WL.push_back(LabelRefVisit(E->getLabel(), E->getLabelLoc(), Parent));
  2200. }
  2201. void EnqueueVisitor::VisitBlockExpr(const BlockExpr *B) {
  2202. AddDecl(B->getBlockDecl());
  2203. }
  2204. void EnqueueVisitor::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  2205. EnqueueChildren(E);
  2206. AddTypeLoc(E->getTypeSourceInfo());
  2207. }
  2208. void EnqueueVisitor::VisitCompoundStmt(const CompoundStmt *S) {
  2209. for (auto &I : llvm::reverse(S->body()))
  2210. AddStmt(I);
  2211. }
  2212. void EnqueueVisitor::VisitMSDependentExistsStmt(
  2213. const MSDependentExistsStmt *S) {
  2214. AddStmt(S->getSubStmt());
  2215. AddDeclarationNameInfo(S);
  2216. if (NestedNameSpecifierLoc QualifierLoc = S->getQualifierLoc())
  2217. AddNestedNameSpecifierLoc(QualifierLoc);
  2218. }
  2219. void EnqueueVisitor::VisitCXXDependentScopeMemberExpr(
  2220. const CXXDependentScopeMemberExpr *E) {
  2221. if (E->hasExplicitTemplateArgs())
  2222. AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
  2223. AddDeclarationNameInfo(E);
  2224. if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
  2225. AddNestedNameSpecifierLoc(QualifierLoc);
  2226. if (!E->isImplicitAccess())
  2227. AddStmt(E->getBase());
  2228. }
  2229. void EnqueueVisitor::VisitCXXNewExpr(const CXXNewExpr *E) {
  2230. // Enqueue the initializer , if any.
  2231. AddStmt(E->getInitializer());
  2232. // Enqueue the array size, if any.
  2233. AddStmt(E->getArraySize().getValueOr(nullptr));
  2234. // Enqueue the allocated type.
  2235. AddTypeLoc(E->getAllocatedTypeSourceInfo());
  2236. // Enqueue the placement arguments.
  2237. for (unsigned I = E->getNumPlacementArgs(); I > 0; --I)
  2238. AddStmt(E->getPlacementArg(I - 1));
  2239. }
  2240. void EnqueueVisitor::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CE) {
  2241. for (unsigned I = CE->getNumArgs(); I > 1 /* Yes, this is 1 */; --I)
  2242. AddStmt(CE->getArg(I - 1));
  2243. AddStmt(CE->getCallee());
  2244. AddStmt(CE->getArg(0));
  2245. }
  2246. void EnqueueVisitor::VisitCXXPseudoDestructorExpr(
  2247. const CXXPseudoDestructorExpr *E) {
  2248. // Visit the name of the type being destroyed.
  2249. AddTypeLoc(E->getDestroyedTypeInfo());
  2250. // Visit the scope type that looks disturbingly like the nested-name-specifier
  2251. // but isn't.
  2252. AddTypeLoc(E->getScopeTypeInfo());
  2253. // Visit the nested-name-specifier.
  2254. if (NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc())
  2255. AddNestedNameSpecifierLoc(QualifierLoc);
  2256. // Visit base expression.
  2257. AddStmt(E->getBase());
  2258. }
  2259. void EnqueueVisitor::VisitCXXScalarValueInitExpr(
  2260. const CXXScalarValueInitExpr *E) {
  2261. AddTypeLoc(E->getTypeSourceInfo());
  2262. }
  2263. void EnqueueVisitor::VisitCXXTemporaryObjectExpr(
  2264. const CXXTemporaryObjectExpr *E) {
  2265. EnqueueChildren(E);
  2266. AddTypeLoc(E->getTypeSourceInfo());
  2267. }
  2268. void EnqueueVisitor::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  2269. EnqueueChildren(E);
  2270. if (E->isTypeOperand())
  2271. AddTypeLoc(E->getTypeOperandSourceInfo());
  2272. }
  2273. void EnqueueVisitor::VisitCXXUnresolvedConstructExpr(
  2274. const CXXUnresolvedConstructExpr *E) {
  2275. EnqueueChildren(E);
  2276. AddTypeLoc(E->getTypeSourceInfo());
  2277. }
  2278. void EnqueueVisitor::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
  2279. EnqueueChildren(E);
  2280. if (E->isTypeOperand())
  2281. AddTypeLoc(E->getTypeOperandSourceInfo());
  2282. }
  2283. void EnqueueVisitor::VisitCXXCatchStmt(const CXXCatchStmt *S) {
  2284. EnqueueChildren(S);
  2285. AddDecl(S->getExceptionDecl());
  2286. }
  2287. void EnqueueVisitor::VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  2288. AddStmt(S->getBody());
  2289. AddStmt(S->getRangeInit());
  2290. AddDecl(S->getLoopVariable());
  2291. }
  2292. void EnqueueVisitor::VisitDeclRefExpr(const DeclRefExpr *DR) {
  2293. if (DR->hasExplicitTemplateArgs())
  2294. AddExplicitTemplateArgs(DR->getTemplateArgs(), DR->getNumTemplateArgs());
  2295. WL.push_back(DeclRefExprParts(DR, Parent));
  2296. }
  2297. void EnqueueVisitor::VisitDependentScopeDeclRefExpr(
  2298. const DependentScopeDeclRefExpr *E) {
  2299. if (E->hasExplicitTemplateArgs())
  2300. AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
  2301. AddDeclarationNameInfo(E);
  2302. AddNestedNameSpecifierLoc(E->getQualifierLoc());
  2303. }
  2304. void EnqueueVisitor::VisitDeclStmt(const DeclStmt *S) {
  2305. unsigned size = WL.size();
  2306. bool isFirst = true;
  2307. for (const auto *D : S->decls()) {
  2308. AddDecl(D, isFirst);
  2309. isFirst = false;
  2310. }
  2311. if (size == WL.size())
  2312. return;
  2313. // Now reverse the entries we just added. This will match the DFS
  2314. // ordering performed by the worklist.
  2315. VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
  2316. std::reverse(I, E);
  2317. }
  2318. void EnqueueVisitor::VisitDesignatedInitExpr(const DesignatedInitExpr *E) {
  2319. AddStmt(E->getInit());
  2320. for (const DesignatedInitExpr::Designator &D :
  2321. llvm::reverse(E->designators())) {
  2322. if (D.isFieldDesignator()) {
  2323. if (FieldDecl *Field = D.getField())
  2324. AddMemberRef(Field, D.getFieldLoc());
  2325. continue;
  2326. }
  2327. if (D.isArrayDesignator()) {
  2328. AddStmt(E->getArrayIndex(D));
  2329. continue;
  2330. }
  2331. assert(D.isArrayRangeDesignator() && "Unknown designator kind");
  2332. AddStmt(E->getArrayRangeEnd(D));
  2333. AddStmt(E->getArrayRangeStart(D));
  2334. }
  2335. }
  2336. void EnqueueVisitor::VisitExplicitCastExpr(const ExplicitCastExpr *E) {
  2337. EnqueueChildren(E);
  2338. AddTypeLoc(E->getTypeInfoAsWritten());
  2339. }
  2340. void EnqueueVisitor::VisitForStmt(const ForStmt *FS) {
  2341. AddStmt(FS->getBody());
  2342. AddStmt(FS->getInc());
  2343. AddStmt(FS->getCond());
  2344. AddDecl(FS->getConditionVariable());
  2345. AddStmt(FS->getInit());
  2346. }
  2347. void EnqueueVisitor::VisitGotoStmt(const GotoStmt *GS) {
  2348. WL.push_back(LabelRefVisit(GS->getLabel(), GS->getLabelLoc(), Parent));
  2349. }
  2350. void EnqueueVisitor::VisitIfStmt(const IfStmt *If) {
  2351. AddStmt(If->getElse());
  2352. AddStmt(If->getThen());
  2353. AddStmt(If->getCond());
  2354. AddStmt(If->getInit());
  2355. AddDecl(If->getConditionVariable());
  2356. }
  2357. void EnqueueVisitor::VisitInitListExpr(const InitListExpr *IE) {
  2358. // We care about the syntactic form of the initializer list, only.
  2359. if (InitListExpr *Syntactic = IE->getSyntacticForm())
  2360. IE = Syntactic;
  2361. EnqueueChildren(IE);
  2362. }
  2363. void EnqueueVisitor::VisitMemberExpr(const MemberExpr *M) {
  2364. WL.push_back(MemberExprParts(M, Parent));
  2365. // If the base of the member access expression is an implicit 'this', don't
  2366. // visit it.
  2367. // FIXME: If we ever want to show these implicit accesses, this will be
  2368. // unfortunate. However, clang_getCursor() relies on this behavior.
  2369. if (M->isImplicitAccess())
  2370. return;
  2371. // Ignore base anonymous struct/union fields, otherwise they will shadow the
  2372. // real field that we are interested in.
  2373. if (auto *SubME = dyn_cast<MemberExpr>(M->getBase())) {
  2374. if (auto *FD = dyn_cast_or_null<FieldDecl>(SubME->getMemberDecl())) {
  2375. if (FD->isAnonymousStructOrUnion()) {
  2376. AddStmt(SubME->getBase());
  2377. return;
  2378. }
  2379. }
  2380. }
  2381. AddStmt(M->getBase());
  2382. }
  2383. void EnqueueVisitor::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
  2384. AddTypeLoc(E->getEncodedTypeSourceInfo());
  2385. }
  2386. void EnqueueVisitor::VisitObjCMessageExpr(const ObjCMessageExpr *M) {
  2387. EnqueueChildren(M);
  2388. AddTypeLoc(M->getClassReceiverTypeInfo());
  2389. }
  2390. void EnqueueVisitor::VisitOffsetOfExpr(const OffsetOfExpr *E) {
  2391. // Visit the components of the offsetof expression.
  2392. for (unsigned N = E->getNumComponents(), I = N; I > 0; --I) {
  2393. const OffsetOfNode &Node = E->getComponent(I - 1);
  2394. switch (Node.getKind()) {
  2395. case OffsetOfNode::Array:
  2396. AddStmt(E->getIndexExpr(Node.getArrayExprIndex()));
  2397. break;
  2398. case OffsetOfNode::Field:
  2399. AddMemberRef(Node.getField(), Node.getSourceRange().getEnd());
  2400. break;
  2401. case OffsetOfNode::Identifier:
  2402. case OffsetOfNode::Base:
  2403. continue;
  2404. }
  2405. }
  2406. // Visit the type into which we're computing the offset.
  2407. AddTypeLoc(E->getTypeSourceInfo());
  2408. }
  2409. void EnqueueVisitor::VisitOverloadExpr(const OverloadExpr *E) {
  2410. if (E->hasExplicitTemplateArgs())
  2411. AddExplicitTemplateArgs(E->getTemplateArgs(), E->getNumTemplateArgs());
  2412. WL.push_back(OverloadExprParts(E, Parent));
  2413. }
  2414. void EnqueueVisitor::VisitUnaryExprOrTypeTraitExpr(
  2415. const UnaryExprOrTypeTraitExpr *E) {
  2416. EnqueueChildren(E);
  2417. if (E->isArgumentType())
  2418. AddTypeLoc(E->getArgumentTypeInfo());
  2419. }
  2420. void EnqueueVisitor::VisitStmt(const Stmt *S) { EnqueueChildren(S); }
  2421. void EnqueueVisitor::VisitSwitchStmt(const SwitchStmt *S) {
  2422. AddStmt(S->getBody());
  2423. AddStmt(S->getCond());
  2424. AddDecl(S->getConditionVariable());
  2425. }
  2426. void EnqueueVisitor::VisitWhileStmt(const WhileStmt *W) {
  2427. AddStmt(W->getBody());
  2428. AddStmt(W->getCond());
  2429. AddDecl(W->getConditionVariable());
  2430. }
  2431. void EnqueueVisitor::VisitTypeTraitExpr(const TypeTraitExpr *E) {
  2432. for (unsigned I = E->getNumArgs(); I > 0; --I)
  2433. AddTypeLoc(E->getArg(I - 1));
  2434. }
  2435. void EnqueueVisitor::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
  2436. AddTypeLoc(E->getQueriedTypeSourceInfo());
  2437. }
  2438. void EnqueueVisitor::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
  2439. EnqueueChildren(E);
  2440. }
  2441. void EnqueueVisitor::VisitUnresolvedMemberExpr(const UnresolvedMemberExpr *U) {
  2442. VisitOverloadExpr(U);
  2443. if (!U->isImplicitAccess())
  2444. AddStmt(U->getBase());
  2445. }
  2446. void EnqueueVisitor::VisitVAArgExpr(const VAArgExpr *E) {
  2447. AddStmt(E->getSubExpr());
  2448. AddTypeLoc(E->getWrittenTypeInfo());
  2449. }
  2450. void EnqueueVisitor::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
  2451. WL.push_back(SizeOfPackExprParts(E, Parent));
  2452. }
  2453. void EnqueueVisitor::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
  2454. // If the opaque value has a source expression, just transparently
  2455. // visit that. This is useful for (e.g.) pseudo-object expressions.
  2456. if (Expr *SourceExpr = E->getSourceExpr())
  2457. return Visit(SourceExpr);
  2458. }
  2459. void EnqueueVisitor::VisitLambdaExpr(const LambdaExpr *E) {
  2460. AddStmt(E->getBody());
  2461. WL.push_back(LambdaExprParts(E, Parent));
  2462. }
  2463. void EnqueueVisitor::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
  2464. // Treat the expression like its syntactic form.
  2465. Visit(E->getSyntacticForm());
  2466. }
  2467. void EnqueueVisitor::VisitOMPExecutableDirective(
  2468. const OMPExecutableDirective *D) {
  2469. EnqueueChildren(D);
  2470. for (ArrayRef<OMPClause *>::iterator I = D->clauses().begin(),
  2471. E = D->clauses().end();
  2472. I != E; ++I)
  2473. EnqueueChildren(*I);
  2474. }
  2475. void EnqueueVisitor::VisitOMPLoopBasedDirective(
  2476. const OMPLoopBasedDirective *D) {
  2477. VisitOMPExecutableDirective(D);
  2478. }
  2479. void EnqueueVisitor::VisitOMPLoopDirective(const OMPLoopDirective *D) {
  2480. VisitOMPLoopBasedDirective(D);
  2481. }
  2482. void EnqueueVisitor::VisitOMPParallelDirective(const OMPParallelDirective *D) {
  2483. VisitOMPExecutableDirective(D);
  2484. }
  2485. void EnqueueVisitor::VisitOMPSimdDirective(const OMPSimdDirective *D) {
  2486. VisitOMPLoopDirective(D);
  2487. }
  2488. void EnqueueVisitor::VisitOMPLoopTransformationDirective(
  2489. const OMPLoopTransformationDirective *D) {
  2490. VisitOMPLoopBasedDirective(D);
  2491. }
  2492. void EnqueueVisitor::VisitOMPTileDirective(const OMPTileDirective *D) {
  2493. VisitOMPLoopTransformationDirective(D);
  2494. }
  2495. void EnqueueVisitor::VisitOMPUnrollDirective(const OMPUnrollDirective *D) {
  2496. VisitOMPLoopTransformationDirective(D);
  2497. }
  2498. void EnqueueVisitor::VisitOMPForDirective(const OMPForDirective *D) {
  2499. VisitOMPLoopDirective(D);
  2500. }
  2501. void EnqueueVisitor::VisitOMPForSimdDirective(const OMPForSimdDirective *D) {
  2502. VisitOMPLoopDirective(D);
  2503. }
  2504. void EnqueueVisitor::VisitOMPSectionsDirective(const OMPSectionsDirective *D) {
  2505. VisitOMPExecutableDirective(D);
  2506. }
  2507. void EnqueueVisitor::VisitOMPSectionDirective(const OMPSectionDirective *D) {
  2508. VisitOMPExecutableDirective(D);
  2509. }
  2510. void EnqueueVisitor::VisitOMPSingleDirective(const OMPSingleDirective *D) {
  2511. VisitOMPExecutableDirective(D);
  2512. }
  2513. void EnqueueVisitor::VisitOMPMasterDirective(const OMPMasterDirective *D) {
  2514. VisitOMPExecutableDirective(D);
  2515. }
  2516. void EnqueueVisitor::VisitOMPCriticalDirective(const OMPCriticalDirective *D) {
  2517. VisitOMPExecutableDirective(D);
  2518. AddDeclarationNameInfo(D);
  2519. }
  2520. void EnqueueVisitor::VisitOMPParallelForDirective(
  2521. const OMPParallelForDirective *D) {
  2522. VisitOMPLoopDirective(D);
  2523. }
  2524. void EnqueueVisitor::VisitOMPParallelForSimdDirective(
  2525. const OMPParallelForSimdDirective *D) {
  2526. VisitOMPLoopDirective(D);
  2527. }
  2528. void EnqueueVisitor::VisitOMPParallelMasterDirective(
  2529. const OMPParallelMasterDirective *D) {
  2530. VisitOMPExecutableDirective(D);
  2531. }
  2532. void EnqueueVisitor::VisitOMPParallelSectionsDirective(
  2533. const OMPParallelSectionsDirective *D) {
  2534. VisitOMPExecutableDirective(D);
  2535. }
  2536. void EnqueueVisitor::VisitOMPTaskDirective(const OMPTaskDirective *D) {
  2537. VisitOMPExecutableDirective(D);
  2538. }
  2539. void EnqueueVisitor::VisitOMPTaskyieldDirective(
  2540. const OMPTaskyieldDirective *D) {
  2541. VisitOMPExecutableDirective(D);
  2542. }
  2543. void EnqueueVisitor::VisitOMPBarrierDirective(const OMPBarrierDirective *D) {
  2544. VisitOMPExecutableDirective(D);
  2545. }
  2546. void EnqueueVisitor::VisitOMPTaskwaitDirective(const OMPTaskwaitDirective *D) {
  2547. VisitOMPExecutableDirective(D);
  2548. }
  2549. void EnqueueVisitor::VisitOMPTaskgroupDirective(
  2550. const OMPTaskgroupDirective *D) {
  2551. VisitOMPExecutableDirective(D);
  2552. if (const Expr *E = D->getReductionRef())
  2553. VisitStmt(E);
  2554. }
  2555. void EnqueueVisitor::VisitOMPFlushDirective(const OMPFlushDirective *D) {
  2556. VisitOMPExecutableDirective(D);
  2557. }
  2558. void EnqueueVisitor::VisitOMPDepobjDirective(const OMPDepobjDirective *D) {
  2559. VisitOMPExecutableDirective(D);
  2560. }
  2561. void EnqueueVisitor::VisitOMPScanDirective(const OMPScanDirective *D) {
  2562. VisitOMPExecutableDirective(D);
  2563. }
  2564. void EnqueueVisitor::VisitOMPOrderedDirective(const OMPOrderedDirective *D) {
  2565. VisitOMPExecutableDirective(D);
  2566. }
  2567. void EnqueueVisitor::VisitOMPAtomicDirective(const OMPAtomicDirective *D) {
  2568. VisitOMPExecutableDirective(D);
  2569. }
  2570. void EnqueueVisitor::VisitOMPTargetDirective(const OMPTargetDirective *D) {
  2571. VisitOMPExecutableDirective(D);
  2572. }
  2573. void EnqueueVisitor::VisitOMPTargetDataDirective(
  2574. const OMPTargetDataDirective *D) {
  2575. VisitOMPExecutableDirective(D);
  2576. }
  2577. void EnqueueVisitor::VisitOMPTargetEnterDataDirective(
  2578. const OMPTargetEnterDataDirective *D) {
  2579. VisitOMPExecutableDirective(D);
  2580. }
  2581. void EnqueueVisitor::VisitOMPTargetExitDataDirective(
  2582. const OMPTargetExitDataDirective *D) {
  2583. VisitOMPExecutableDirective(D);
  2584. }
  2585. void EnqueueVisitor::VisitOMPTargetParallelDirective(
  2586. const OMPTargetParallelDirective *D) {
  2587. VisitOMPExecutableDirective(D);
  2588. }
  2589. void EnqueueVisitor::VisitOMPTargetParallelForDirective(
  2590. const OMPTargetParallelForDirective *D) {
  2591. VisitOMPLoopDirective(D);
  2592. }
  2593. void EnqueueVisitor::VisitOMPTeamsDirective(const OMPTeamsDirective *D) {
  2594. VisitOMPExecutableDirective(D);
  2595. }
  2596. void EnqueueVisitor::VisitOMPCancellationPointDirective(
  2597. const OMPCancellationPointDirective *D) {
  2598. VisitOMPExecutableDirective(D);
  2599. }
  2600. void EnqueueVisitor::VisitOMPCancelDirective(const OMPCancelDirective *D) {
  2601. VisitOMPExecutableDirective(D);
  2602. }
  2603. void EnqueueVisitor::VisitOMPTaskLoopDirective(const OMPTaskLoopDirective *D) {
  2604. VisitOMPLoopDirective(D);
  2605. }
  2606. void EnqueueVisitor::VisitOMPTaskLoopSimdDirective(
  2607. const OMPTaskLoopSimdDirective *D) {
  2608. VisitOMPLoopDirective(D);
  2609. }
  2610. void EnqueueVisitor::VisitOMPMasterTaskLoopDirective(
  2611. const OMPMasterTaskLoopDirective *D) {
  2612. VisitOMPLoopDirective(D);
  2613. }
  2614. void EnqueueVisitor::VisitOMPMasterTaskLoopSimdDirective(
  2615. const OMPMasterTaskLoopSimdDirective *D) {
  2616. VisitOMPLoopDirective(D);
  2617. }
  2618. void EnqueueVisitor::VisitOMPParallelMasterTaskLoopDirective(
  2619. const OMPParallelMasterTaskLoopDirective *D) {
  2620. VisitOMPLoopDirective(D);
  2621. }
  2622. void EnqueueVisitor::VisitOMPParallelMasterTaskLoopSimdDirective(
  2623. const OMPParallelMasterTaskLoopSimdDirective *D) {
  2624. VisitOMPLoopDirective(D);
  2625. }
  2626. void EnqueueVisitor::VisitOMPDistributeDirective(
  2627. const OMPDistributeDirective *D) {
  2628. VisitOMPLoopDirective(D);
  2629. }
  2630. void EnqueueVisitor::VisitOMPDistributeParallelForDirective(
  2631. const OMPDistributeParallelForDirective *D) {
  2632. VisitOMPLoopDirective(D);
  2633. }
  2634. void EnqueueVisitor::VisitOMPDistributeParallelForSimdDirective(
  2635. const OMPDistributeParallelForSimdDirective *D) {
  2636. VisitOMPLoopDirective(D);
  2637. }
  2638. void EnqueueVisitor::VisitOMPDistributeSimdDirective(
  2639. const OMPDistributeSimdDirective *D) {
  2640. VisitOMPLoopDirective(D);
  2641. }
  2642. void EnqueueVisitor::VisitOMPTargetParallelForSimdDirective(
  2643. const OMPTargetParallelForSimdDirective *D) {
  2644. VisitOMPLoopDirective(D);
  2645. }
  2646. void EnqueueVisitor::VisitOMPTargetSimdDirective(
  2647. const OMPTargetSimdDirective *D) {
  2648. VisitOMPLoopDirective(D);
  2649. }
  2650. void EnqueueVisitor::VisitOMPTeamsDistributeDirective(
  2651. const OMPTeamsDistributeDirective *D) {
  2652. VisitOMPLoopDirective(D);
  2653. }
  2654. void EnqueueVisitor::VisitOMPTeamsDistributeSimdDirective(
  2655. const OMPTeamsDistributeSimdDirective *D) {
  2656. VisitOMPLoopDirective(D);
  2657. }
  2658. void EnqueueVisitor::VisitOMPTeamsDistributeParallelForSimdDirective(
  2659. const OMPTeamsDistributeParallelForSimdDirective *D) {
  2660. VisitOMPLoopDirective(D);
  2661. }
  2662. void EnqueueVisitor::VisitOMPTeamsDistributeParallelForDirective(
  2663. const OMPTeamsDistributeParallelForDirective *D) {
  2664. VisitOMPLoopDirective(D);
  2665. }
  2666. void EnqueueVisitor::VisitOMPTargetTeamsDirective(
  2667. const OMPTargetTeamsDirective *D) {
  2668. VisitOMPExecutableDirective(D);
  2669. }
  2670. void EnqueueVisitor::VisitOMPTargetTeamsDistributeDirective(
  2671. const OMPTargetTeamsDistributeDirective *D) {
  2672. VisitOMPLoopDirective(D);
  2673. }
  2674. void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForDirective(
  2675. const OMPTargetTeamsDistributeParallelForDirective *D) {
  2676. VisitOMPLoopDirective(D);
  2677. }
  2678. void EnqueueVisitor::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
  2679. const OMPTargetTeamsDistributeParallelForSimdDirective *D) {
  2680. VisitOMPLoopDirective(D);
  2681. }
  2682. void EnqueueVisitor::VisitOMPTargetTeamsDistributeSimdDirective(
  2683. const OMPTargetTeamsDistributeSimdDirective *D) {
  2684. VisitOMPLoopDirective(D);
  2685. }
  2686. void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, const Stmt *S) {
  2687. EnqueueVisitor(WL, MakeCXCursor(S, StmtParent, TU, RegionOfInterest))
  2688. .Visit(S);
  2689. }
  2690. bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
  2691. if (RegionOfInterest.isValid()) {
  2692. SourceRange Range = getRawCursorExtent(C);
  2693. if (Range.isInvalid() || CompareRegionOfInterest(Range))
  2694. return false;
  2695. }
  2696. return true;
  2697. }
  2698. bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
  2699. while (!WL.empty()) {
  2700. // Dequeue the worklist item.
  2701. VisitorJob LI = WL.pop_back_val();
  2702. // Set the Parent field, then back to its old value once we're done.
  2703. SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
  2704. switch (LI.getKind()) {
  2705. case VisitorJob::DeclVisitKind: {
  2706. const Decl *D = cast<DeclVisit>(&LI)->get();
  2707. if (!D)
  2708. continue;
  2709. // For now, perform default visitation for Decls.
  2710. if (Visit(MakeCXCursor(D, TU, RegionOfInterest,
  2711. cast<DeclVisit>(&LI)->isFirst())))
  2712. return true;
  2713. continue;
  2714. }
  2715. case VisitorJob::ExplicitTemplateArgsVisitKind: {
  2716. for (const TemplateArgumentLoc &Arg :
  2717. *cast<ExplicitTemplateArgsVisit>(&LI)) {
  2718. if (VisitTemplateArgumentLoc(Arg))
  2719. return true;
  2720. }
  2721. continue;
  2722. }
  2723. case VisitorJob::TypeLocVisitKind: {
  2724. // Perform default visitation for TypeLocs.
  2725. if (Visit(cast<TypeLocVisit>(&LI)->get()))
  2726. return true;
  2727. continue;
  2728. }
  2729. case VisitorJob::LabelRefVisitKind: {
  2730. const LabelDecl *LS = cast<LabelRefVisit>(&LI)->get();
  2731. if (LabelStmt *stmt = LS->getStmt()) {
  2732. if (Visit(MakeCursorLabelRef(stmt, cast<LabelRefVisit>(&LI)->getLoc(),
  2733. TU))) {
  2734. return true;
  2735. }
  2736. }
  2737. continue;
  2738. }
  2739. case VisitorJob::NestedNameSpecifierLocVisitKind: {
  2740. NestedNameSpecifierLocVisit *V = cast<NestedNameSpecifierLocVisit>(&LI);
  2741. if (VisitNestedNameSpecifierLoc(V->get()))
  2742. return true;
  2743. continue;
  2744. }
  2745. case VisitorJob::DeclarationNameInfoVisitKind: {
  2746. if (VisitDeclarationNameInfo(cast<DeclarationNameInfoVisit>(&LI)->get()))
  2747. return true;
  2748. continue;
  2749. }
  2750. case VisitorJob::MemberRefVisitKind: {
  2751. MemberRefVisit *V = cast<MemberRefVisit>(&LI);
  2752. if (Visit(MakeCursorMemberRef(V->get(), V->getLoc(), TU)))
  2753. return true;
  2754. continue;
  2755. }
  2756. case VisitorJob::StmtVisitKind: {
  2757. const Stmt *S = cast<StmtVisit>(&LI)->get();
  2758. if (!S)
  2759. continue;
  2760. // Update the current cursor.
  2761. CXCursor Cursor = MakeCXCursor(S, StmtParent, TU, RegionOfInterest);
  2762. if (!IsInRegionOfInterest(Cursor))
  2763. continue;
  2764. switch (Visitor(Cursor, Parent, ClientData)) {
  2765. case CXChildVisit_Break:
  2766. return true;
  2767. case CXChildVisit_Continue:
  2768. break;
  2769. case CXChildVisit_Recurse:
  2770. if (PostChildrenVisitor)
  2771. WL.push_back(PostChildrenVisit(nullptr, Cursor));
  2772. EnqueueWorkList(WL, S);
  2773. break;
  2774. }
  2775. continue;
  2776. }
  2777. case VisitorJob::MemberExprPartsKind: {
  2778. // Handle the other pieces in the MemberExpr besides the base.
  2779. const MemberExpr *M = cast<MemberExprParts>(&LI)->get();
  2780. // Visit the nested-name-specifier
  2781. if (NestedNameSpecifierLoc QualifierLoc = M->getQualifierLoc())
  2782. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  2783. return true;
  2784. // Visit the declaration name.
  2785. if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
  2786. return true;
  2787. // Visit the explicitly-specified template arguments, if any.
  2788. if (M->hasExplicitTemplateArgs()) {
  2789. for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
  2790. *ArgEnd = Arg + M->getNumTemplateArgs();
  2791. Arg != ArgEnd; ++Arg) {
  2792. if (VisitTemplateArgumentLoc(*Arg))
  2793. return true;
  2794. }
  2795. }
  2796. continue;
  2797. }
  2798. case VisitorJob::DeclRefExprPartsKind: {
  2799. const DeclRefExpr *DR = cast<DeclRefExprParts>(&LI)->get();
  2800. // Visit nested-name-specifier, if present.
  2801. if (NestedNameSpecifierLoc QualifierLoc = DR->getQualifierLoc())
  2802. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  2803. return true;
  2804. // Visit declaration name.
  2805. if (VisitDeclarationNameInfo(DR->getNameInfo()))
  2806. return true;
  2807. continue;
  2808. }
  2809. case VisitorJob::OverloadExprPartsKind: {
  2810. const OverloadExpr *O = cast<OverloadExprParts>(&LI)->get();
  2811. // Visit the nested-name-specifier.
  2812. if (NestedNameSpecifierLoc QualifierLoc = O->getQualifierLoc())
  2813. if (VisitNestedNameSpecifierLoc(QualifierLoc))
  2814. return true;
  2815. // Visit the declaration name.
  2816. if (VisitDeclarationNameInfo(O->getNameInfo()))
  2817. return true;
  2818. // Visit the overloaded declaration reference.
  2819. if (Visit(MakeCursorOverloadedDeclRef(O, TU)))
  2820. return true;
  2821. continue;
  2822. }
  2823. case VisitorJob::SizeOfPackExprPartsKind: {
  2824. const SizeOfPackExpr *E = cast<SizeOfPackExprParts>(&LI)->get();
  2825. NamedDecl *Pack = E->getPack();
  2826. if (isa<TemplateTypeParmDecl>(Pack)) {
  2827. if (Visit(MakeCursorTypeRef(cast<TemplateTypeParmDecl>(Pack),
  2828. E->getPackLoc(), TU)))
  2829. return true;
  2830. continue;
  2831. }
  2832. if (isa<TemplateTemplateParmDecl>(Pack)) {
  2833. if (Visit(MakeCursorTemplateRef(cast<TemplateTemplateParmDecl>(Pack),
  2834. E->getPackLoc(), TU)))
  2835. return true;
  2836. continue;
  2837. }
  2838. // Non-type template parameter packs and function parameter packs are
  2839. // treated like DeclRefExpr cursors.
  2840. continue;
  2841. }
  2842. case VisitorJob::LambdaExprPartsKind: {
  2843. // Visit non-init captures.
  2844. const LambdaExpr *E = cast<LambdaExprParts>(&LI)->get();
  2845. for (LambdaExpr::capture_iterator C = E->explicit_capture_begin(),
  2846. CEnd = E->explicit_capture_end();
  2847. C != CEnd; ++C) {
  2848. if (!C->capturesVariable())
  2849. continue;
  2850. if (Visit(MakeCursorVariableRef(C->getCapturedVar(), C->getLocation(),
  2851. TU)))
  2852. return true;
  2853. }
  2854. // Visit init captures
  2855. for (auto InitExpr : E->capture_inits()) {
  2856. if (InitExpr && Visit(InitExpr))
  2857. return true;
  2858. }
  2859. TypeLoc TL = E->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
  2860. // Visit parameters and return type, if present.
  2861. if (FunctionTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
  2862. if (E->hasExplicitParameters()) {
  2863. // Visit parameters.
  2864. for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I)
  2865. if (Visit(MakeCXCursor(Proto.getParam(I), TU)))
  2866. return true;
  2867. }
  2868. if (E->hasExplicitResultType()) {
  2869. // Visit result type.
  2870. if (Visit(Proto.getReturnLoc()))
  2871. return true;
  2872. }
  2873. }
  2874. break;
  2875. }
  2876. case VisitorJob::PostChildrenVisitKind:
  2877. if (PostChildrenVisitor(Parent, ClientData))
  2878. return true;
  2879. break;
  2880. }
  2881. }
  2882. return false;
  2883. }
  2884. bool CursorVisitor::Visit(const Stmt *S) {
  2885. VisitorWorkList *WL = nullptr;
  2886. if (!WorkListFreeList.empty()) {
  2887. WL = WorkListFreeList.back();
  2888. WL->clear();
  2889. WorkListFreeList.pop_back();
  2890. } else {
  2891. WL = new VisitorWorkList();
  2892. WorkListCache.push_back(WL);
  2893. }
  2894. EnqueueWorkList(*WL, S);
  2895. bool result = RunVisitorWorkList(*WL);
  2896. WorkListFreeList.push_back(WL);
  2897. return result;
  2898. }
  2899. namespace {
  2900. typedef SmallVector<SourceRange, 4> RefNamePieces;
  2901. RefNamePieces buildPieces(unsigned NameFlags, bool IsMemberRefExpr,
  2902. const DeclarationNameInfo &NI, SourceRange QLoc,
  2903. const SourceRange *TemplateArgsLoc = nullptr) {
  2904. const bool WantQualifier = NameFlags & CXNameRange_WantQualifier;
  2905. const bool WantTemplateArgs = NameFlags & CXNameRange_WantTemplateArgs;
  2906. const bool WantSinglePiece = NameFlags & CXNameRange_WantSinglePiece;
  2907. const DeclarationName::NameKind Kind = NI.getName().getNameKind();
  2908. RefNamePieces Pieces;
  2909. if (WantQualifier && QLoc.isValid())
  2910. Pieces.push_back(QLoc);
  2911. if (Kind != DeclarationName::CXXOperatorName || IsMemberRefExpr)
  2912. Pieces.push_back(NI.getLoc());
  2913. if (WantTemplateArgs && TemplateArgsLoc && TemplateArgsLoc->isValid())
  2914. Pieces.push_back(*TemplateArgsLoc);
  2915. if (Kind == DeclarationName::CXXOperatorName) {
  2916. Pieces.push_back(NI.getInfo().getCXXOperatorNameBeginLoc());
  2917. Pieces.push_back(NI.getInfo().getCXXOperatorNameEndLoc());
  2918. }
  2919. if (WantSinglePiece) {
  2920. SourceRange R(Pieces.front().getBegin(), Pieces.back().getEnd());
  2921. Pieces.clear();
  2922. Pieces.push_back(R);
  2923. }
  2924. return Pieces;
  2925. }
  2926. } // namespace
  2927. //===----------------------------------------------------------------------===//
  2928. // Misc. API hooks.
  2929. //===----------------------------------------------------------------------===//
  2930. namespace {
  2931. struct RegisterFatalErrorHandler {
  2932. RegisterFatalErrorHandler() {
  2933. clang_install_aborting_llvm_fatal_error_handler();
  2934. }
  2935. };
  2936. } // namespace
  2937. static llvm::ManagedStatic<RegisterFatalErrorHandler>
  2938. RegisterFatalErrorHandlerOnce;
  2939. CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
  2940. int displayDiagnostics) {
  2941. // We use crash recovery to make some of our APIs more reliable, implicitly
  2942. // enable it.
  2943. if (!getenv("LIBCLANG_DISABLE_CRASH_RECOVERY"))
  2944. llvm::CrashRecoveryContext::Enable();
  2945. // Look through the managed static to trigger construction of the managed
  2946. // static which registers our fatal error handler. This ensures it is only
  2947. // registered once.
  2948. (void)*RegisterFatalErrorHandlerOnce;
  2949. // Initialize targets for clang module support.
  2950. llvm::InitializeAllTargets();
  2951. llvm::InitializeAllTargetMCs();
  2952. llvm::InitializeAllAsmPrinters();
  2953. llvm::InitializeAllAsmParsers();
  2954. CIndexer *CIdxr = new CIndexer();
  2955. if (excludeDeclarationsFromPCH)
  2956. CIdxr->setOnlyLocalDecls();
  2957. if (displayDiagnostics)
  2958. CIdxr->setDisplayDiagnostics();
  2959. if (getenv("LIBCLANG_BGPRIO_INDEX"))
  2960. CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
  2961. CXGlobalOpt_ThreadBackgroundPriorityForIndexing);
  2962. if (getenv("LIBCLANG_BGPRIO_EDIT"))
  2963. CIdxr->setCXGlobalOptFlags(CIdxr->getCXGlobalOptFlags() |
  2964. CXGlobalOpt_ThreadBackgroundPriorityForEditing);
  2965. return CIdxr;
  2966. }
  2967. void clang_disposeIndex(CXIndex CIdx) {
  2968. if (CIdx)
  2969. delete static_cast<CIndexer *>(CIdx);
  2970. }
  2971. void clang_CXIndex_setGlobalOptions(CXIndex CIdx, unsigned options) {
  2972. if (CIdx)
  2973. static_cast<CIndexer *>(CIdx)->setCXGlobalOptFlags(options);
  2974. }
  2975. unsigned clang_CXIndex_getGlobalOptions(CXIndex CIdx) {
  2976. if (CIdx)
  2977. return static_cast<CIndexer *>(CIdx)->getCXGlobalOptFlags();
  2978. return 0;
  2979. }
  2980. void clang_CXIndex_setInvocationEmissionPathOption(CXIndex CIdx,
  2981. const char *Path) {
  2982. if (CIdx)
  2983. static_cast<CIndexer *>(CIdx)->setInvocationEmissionPath(Path ? Path : "");
  2984. }
  2985. void clang_toggleCrashRecovery(unsigned isEnabled) {
  2986. if (isEnabled)
  2987. llvm::CrashRecoveryContext::Enable();
  2988. else
  2989. llvm::CrashRecoveryContext::Disable();
  2990. }
  2991. CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
  2992. const char *ast_filename) {
  2993. CXTranslationUnit TU;
  2994. enum CXErrorCode Result =
  2995. clang_createTranslationUnit2(CIdx, ast_filename, &TU);
  2996. (void)Result;
  2997. assert((TU && Result == CXError_Success) ||
  2998. (!TU && Result != CXError_Success));
  2999. return TU;
  3000. }
  3001. enum CXErrorCode clang_createTranslationUnit2(CXIndex CIdx,
  3002. const char *ast_filename,
  3003. CXTranslationUnit *out_TU) {
  3004. if (out_TU)
  3005. *out_TU = nullptr;
  3006. if (!CIdx || !ast_filename || !out_TU)
  3007. return CXError_InvalidArguments;
  3008. LOG_FUNC_SECTION { *Log << ast_filename; }
  3009. CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
  3010. FileSystemOptions FileSystemOpts;
  3011. IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
  3012. CompilerInstance::createDiagnostics(new DiagnosticOptions());
  3013. std::unique_ptr<ASTUnit> AU = ASTUnit::LoadFromASTFile(
  3014. ast_filename, CXXIdx->getPCHContainerOperations()->getRawReader(),
  3015. ASTUnit::LoadEverything, Diags, FileSystemOpts, /*UseDebugInfo=*/false,
  3016. CXXIdx->getOnlyLocalDecls(), CaptureDiagsKind::All,
  3017. /*AllowASTWithCompilerErrors=*/true,
  3018. /*UserFilesAreVolatile=*/true);
  3019. *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(AU));
  3020. return *out_TU ? CXError_Success : CXError_Failure;
  3021. }
  3022. unsigned clang_defaultEditingTranslationUnitOptions() {
  3023. return CXTranslationUnit_PrecompiledPreamble |
  3024. CXTranslationUnit_CacheCompletionResults;
  3025. }
  3026. CXTranslationUnit clang_createTranslationUnitFromSourceFile(
  3027. CXIndex CIdx, const char *source_filename, int num_command_line_args,
  3028. const char *const *command_line_args, unsigned num_unsaved_files,
  3029. struct CXUnsavedFile *unsaved_files) {
  3030. unsigned Options = CXTranslationUnit_DetailedPreprocessingRecord;
  3031. return clang_parseTranslationUnit(CIdx, source_filename, command_line_args,
  3032. num_command_line_args, unsaved_files,
  3033. num_unsaved_files, Options);
  3034. }
  3035. static CXErrorCode
  3036. clang_parseTranslationUnit_Impl(CXIndex CIdx, const char *source_filename,
  3037. const char *const *command_line_args,
  3038. int num_command_line_args,
  3039. ArrayRef<CXUnsavedFile> unsaved_files,
  3040. unsigned options, CXTranslationUnit *out_TU) {
  3041. // Set up the initial return values.
  3042. if (out_TU)
  3043. *out_TU = nullptr;
  3044. // Check arguments.
  3045. if (!CIdx || !out_TU)
  3046. return CXError_InvalidArguments;
  3047. CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
  3048. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
  3049. setThreadBackgroundPriority();
  3050. bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
  3051. bool CreatePreambleOnFirstParse =
  3052. options & CXTranslationUnit_CreatePreambleOnFirstParse;
  3053. // FIXME: Add a flag for modules.
  3054. TranslationUnitKind TUKind = (options & (CXTranslationUnit_Incomplete |
  3055. CXTranslationUnit_SingleFileParse))
  3056. ? TU_Prefix
  3057. : TU_Complete;
  3058. bool CacheCodeCompletionResults =
  3059. options & CXTranslationUnit_CacheCompletionResults;
  3060. bool IncludeBriefCommentsInCodeCompletion =
  3061. options & CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
  3062. bool SingleFileParse = options & CXTranslationUnit_SingleFileParse;
  3063. bool ForSerialization = options & CXTranslationUnit_ForSerialization;
  3064. bool RetainExcludedCB =
  3065. options & CXTranslationUnit_RetainExcludedConditionalBlocks;
  3066. SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
  3067. if (options & CXTranslationUnit_SkipFunctionBodies) {
  3068. SkipFunctionBodies =
  3069. (options & CXTranslationUnit_LimitSkipFunctionBodiesToPreamble)
  3070. ? SkipFunctionBodiesScope::Preamble
  3071. : SkipFunctionBodiesScope::PreambleAndMainFile;
  3072. }
  3073. // Configure the diagnostics.
  3074. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  3075. CompilerInstance::createDiagnostics(new DiagnosticOptions));
  3076. if (options & CXTranslationUnit_KeepGoing)
  3077. Diags->setFatalsAsError(true);
  3078. CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::All;
  3079. if (options & CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles)
  3080. CaptureDiagnostics = CaptureDiagsKind::AllWithoutNonErrorsFromIncludes;
  3081. // Recover resources if we crash before exiting this function.
  3082. llvm::CrashRecoveryContextCleanupRegistrar<
  3083. DiagnosticsEngine,
  3084. llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
  3085. DiagCleanup(Diags.get());
  3086. std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
  3087. new std::vector<ASTUnit::RemappedFile>());
  3088. // Recover resources if we crash before exiting this function.
  3089. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
  3090. RemappedCleanup(RemappedFiles.get());
  3091. for (auto &UF : unsaved_files) {
  3092. std::unique_ptr<llvm::MemoryBuffer> MB =
  3093. llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
  3094. RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
  3095. }
  3096. std::unique_ptr<std::vector<const char *>> Args(
  3097. new std::vector<const char *>());
  3098. // Recover resources if we crash before exiting this method.
  3099. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<const char *>>
  3100. ArgsCleanup(Args.get());
  3101. // Since the Clang C library is primarily used by batch tools dealing with
  3102. // (often very broken) source code, where spell-checking can have a
  3103. // significant negative impact on performance (particularly when
  3104. // precompiled headers are involved), we disable it by default.
  3105. // Only do this if we haven't found a spell-checking-related argument.
  3106. bool FoundSpellCheckingArgument = false;
  3107. for (int I = 0; I != num_command_line_args; ++I) {
  3108. if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
  3109. strcmp(command_line_args[I], "-fspell-checking") == 0) {
  3110. FoundSpellCheckingArgument = true;
  3111. break;
  3112. }
  3113. }
  3114. Args->insert(Args->end(), command_line_args,
  3115. command_line_args + num_command_line_args);
  3116. if (!FoundSpellCheckingArgument)
  3117. Args->insert(Args->begin() + 1, "-fno-spell-checking");
  3118. // The 'source_filename' argument is optional. If the caller does not
  3119. // specify it then it is assumed that the source file is specified
  3120. // in the actual argument list.
  3121. // Put the source file after command_line_args otherwise if '-x' flag is
  3122. // present it will be unused.
  3123. if (source_filename)
  3124. Args->push_back(source_filename);
  3125. // Do we need the detailed preprocessing record?
  3126. if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
  3127. Args->push_back("-Xclang");
  3128. Args->push_back("-detailed-preprocessing-record");
  3129. }
  3130. // Suppress any editor placeholder diagnostics.
  3131. Args->push_back("-fallow-editor-placeholders");
  3132. unsigned NumErrors = Diags->getClient()->getNumErrors();
  3133. std::unique_ptr<ASTUnit> ErrUnit;
  3134. // Unless the user specified that they want the preamble on the first parse
  3135. // set it up to be created on the first reparse. This makes the first parse
  3136. // faster, trading for a slower (first) reparse.
  3137. unsigned PrecompilePreambleAfterNParses =
  3138. !PrecompilePreamble ? 0 : 2 - CreatePreambleOnFirstParse;
  3139. LibclangInvocationReporter InvocationReporter(
  3140. *CXXIdx, LibclangInvocationReporter::OperationKind::ParseOperation,
  3141. options, llvm::makeArrayRef(*Args), /*InvocationArgs=*/None,
  3142. unsaved_files);
  3143. std::unique_ptr<ASTUnit> Unit(ASTUnit::LoadFromCommandLine(
  3144. Args->data(), Args->data() + Args->size(),
  3145. CXXIdx->getPCHContainerOperations(), Diags,
  3146. CXXIdx->getClangResourcesPath(), CXXIdx->getOnlyLocalDecls(),
  3147. CaptureDiagnostics, *RemappedFiles.get(),
  3148. /*RemappedFilesKeepOriginalName=*/true, PrecompilePreambleAfterNParses,
  3149. TUKind, CacheCodeCompletionResults, IncludeBriefCommentsInCodeCompletion,
  3150. /*AllowPCHWithCompilerErrors=*/true, SkipFunctionBodies, SingleFileParse,
  3151. /*UserFilesAreVolatile=*/true, ForSerialization, RetainExcludedCB,
  3152. CXXIdx->getPCHContainerOperations()->getRawReader().getFormat(),
  3153. &ErrUnit));
  3154. // Early failures in LoadFromCommandLine may return with ErrUnit unset.
  3155. if (!Unit && !ErrUnit)
  3156. return CXError_ASTReadError;
  3157. if (NumErrors != Diags->getClient()->getNumErrors()) {
  3158. // Make sure to check that 'Unit' is non-NULL.
  3159. if (CXXIdx->getDisplayDiagnostics())
  3160. printDiagsToStderr(Unit ? Unit.get() : ErrUnit.get());
  3161. }
  3162. if (isASTReadError(Unit ? Unit.get() : ErrUnit.get()))
  3163. return CXError_ASTReadError;
  3164. *out_TU = MakeCXTranslationUnit(CXXIdx, std::move(Unit));
  3165. if (CXTranslationUnitImpl *TU = *out_TU) {
  3166. TU->ParsingOptions = options;
  3167. TU->Arguments.reserve(Args->size());
  3168. for (const char *Arg : *Args)
  3169. TU->Arguments.push_back(Arg);
  3170. return CXError_Success;
  3171. }
  3172. return CXError_Failure;
  3173. }
  3174. CXTranslationUnit
  3175. clang_parseTranslationUnit(CXIndex CIdx, const char *source_filename,
  3176. const char *const *command_line_args,
  3177. int num_command_line_args,
  3178. struct CXUnsavedFile *unsaved_files,
  3179. unsigned num_unsaved_files, unsigned options) {
  3180. CXTranslationUnit TU;
  3181. enum CXErrorCode Result = clang_parseTranslationUnit2(
  3182. CIdx, source_filename, command_line_args, num_command_line_args,
  3183. unsaved_files, num_unsaved_files, options, &TU);
  3184. (void)Result;
  3185. assert((TU && Result == CXError_Success) ||
  3186. (!TU && Result != CXError_Success));
  3187. return TU;
  3188. }
  3189. enum CXErrorCode clang_parseTranslationUnit2(
  3190. CXIndex CIdx, const char *source_filename,
  3191. const char *const *command_line_args, int num_command_line_args,
  3192. struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
  3193. unsigned options, CXTranslationUnit *out_TU) {
  3194. noteBottomOfStack();
  3195. SmallVector<const char *, 4> Args;
  3196. Args.push_back("clang");
  3197. Args.append(command_line_args, command_line_args + num_command_line_args);
  3198. return clang_parseTranslationUnit2FullArgv(
  3199. CIdx, source_filename, Args.data(), Args.size(), unsaved_files,
  3200. num_unsaved_files, options, out_TU);
  3201. }
  3202. enum CXErrorCode clang_parseTranslationUnit2FullArgv(
  3203. CXIndex CIdx, const char *source_filename,
  3204. const char *const *command_line_args, int num_command_line_args,
  3205. struct CXUnsavedFile *unsaved_files, unsigned num_unsaved_files,
  3206. unsigned options, CXTranslationUnit *out_TU) {
  3207. LOG_FUNC_SECTION {
  3208. *Log << source_filename << ": ";
  3209. for (int i = 0; i != num_command_line_args; ++i)
  3210. *Log << command_line_args[i] << " ";
  3211. }
  3212. if (num_unsaved_files && !unsaved_files)
  3213. return CXError_InvalidArguments;
  3214. CXErrorCode result = CXError_Failure;
  3215. auto ParseTranslationUnitImpl = [=, &result] {
  3216. noteBottomOfStack();
  3217. result = clang_parseTranslationUnit_Impl(
  3218. CIdx, source_filename, command_line_args, num_command_line_args,
  3219. llvm::makeArrayRef(unsaved_files, num_unsaved_files), options, out_TU);
  3220. };
  3221. llvm::CrashRecoveryContext CRC;
  3222. if (!RunSafely(CRC, ParseTranslationUnitImpl)) {
  3223. fprintf(stderr, "libclang: crash detected during parsing: {\n");
  3224. fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
  3225. fprintf(stderr, " 'command_line_args' : [");
  3226. for (int i = 0; i != num_command_line_args; ++i) {
  3227. if (i)
  3228. fprintf(stderr, ", ");
  3229. fprintf(stderr, "'%s'", command_line_args[i]);
  3230. }
  3231. fprintf(stderr, "],\n");
  3232. fprintf(stderr, " 'unsaved_files' : [");
  3233. for (unsigned i = 0; i != num_unsaved_files; ++i) {
  3234. if (i)
  3235. fprintf(stderr, ", ");
  3236. fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
  3237. unsaved_files[i].Length);
  3238. }
  3239. fprintf(stderr, "],\n");
  3240. fprintf(stderr, " 'options' : %d,\n", options);
  3241. fprintf(stderr, "}\n");
  3242. return CXError_Crashed;
  3243. } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
  3244. if (CXTranslationUnit *TU = out_TU)
  3245. PrintLibclangResourceUsage(*TU);
  3246. }
  3247. return result;
  3248. }
  3249. CXString clang_Type_getObjCEncoding(CXType CT) {
  3250. CXTranslationUnit tu = static_cast<CXTranslationUnit>(CT.data[1]);
  3251. ASTContext &Ctx = getASTUnit(tu)->getASTContext();
  3252. std::string encoding;
  3253. Ctx.getObjCEncodingForType(QualType::getFromOpaquePtr(CT.data[0]), encoding);
  3254. return cxstring::createDup(encoding);
  3255. }
  3256. static const IdentifierInfo *getMacroIdentifier(CXCursor C) {
  3257. if (C.kind == CXCursor_MacroDefinition) {
  3258. if (const MacroDefinitionRecord *MDR = getCursorMacroDefinition(C))
  3259. return MDR->getName();
  3260. } else if (C.kind == CXCursor_MacroExpansion) {
  3261. MacroExpansionCursor ME = getCursorMacroExpansion(C);
  3262. return ME.getName();
  3263. }
  3264. return nullptr;
  3265. }
  3266. unsigned clang_Cursor_isMacroFunctionLike(CXCursor C) {
  3267. const IdentifierInfo *II = getMacroIdentifier(C);
  3268. if (!II) {
  3269. return false;
  3270. }
  3271. ASTUnit *ASTU = getCursorASTUnit(C);
  3272. Preprocessor &PP = ASTU->getPreprocessor();
  3273. if (const MacroInfo *MI = PP.getMacroInfo(II))
  3274. return MI->isFunctionLike();
  3275. return false;
  3276. }
  3277. unsigned clang_Cursor_isMacroBuiltin(CXCursor C) {
  3278. const IdentifierInfo *II = getMacroIdentifier(C);
  3279. if (!II) {
  3280. return false;
  3281. }
  3282. ASTUnit *ASTU = getCursorASTUnit(C);
  3283. Preprocessor &PP = ASTU->getPreprocessor();
  3284. if (const MacroInfo *MI = PP.getMacroInfo(II))
  3285. return MI->isBuiltinMacro();
  3286. return false;
  3287. }
  3288. unsigned clang_Cursor_isFunctionInlined(CXCursor C) {
  3289. const Decl *D = getCursorDecl(C);
  3290. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
  3291. if (!FD) {
  3292. return false;
  3293. }
  3294. return FD->isInlined();
  3295. }
  3296. static StringLiteral *getCFSTR_value(CallExpr *callExpr) {
  3297. if (callExpr->getNumArgs() != 1) {
  3298. return nullptr;
  3299. }
  3300. StringLiteral *S = nullptr;
  3301. auto *arg = callExpr->getArg(0);
  3302. if (arg->getStmtClass() == Stmt::ImplicitCastExprClass) {
  3303. ImplicitCastExpr *I = static_cast<ImplicitCastExpr *>(arg);
  3304. auto *subExpr = I->getSubExprAsWritten();
  3305. if (subExpr->getStmtClass() != Stmt::StringLiteralClass) {
  3306. return nullptr;
  3307. }
  3308. S = static_cast<StringLiteral *>(I->getSubExprAsWritten());
  3309. } else if (arg->getStmtClass() == Stmt::StringLiteralClass) {
  3310. S = static_cast<StringLiteral *>(callExpr->getArg(0));
  3311. } else {
  3312. return nullptr;
  3313. }
  3314. return S;
  3315. }
  3316. struct ExprEvalResult {
  3317. CXEvalResultKind EvalType;
  3318. union {
  3319. unsigned long long unsignedVal;
  3320. long long intVal;
  3321. double floatVal;
  3322. char *stringVal;
  3323. } EvalData;
  3324. bool IsUnsignedInt;
  3325. ~ExprEvalResult() {
  3326. if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
  3327. EvalType != CXEval_Int) {
  3328. delete[] EvalData.stringVal;
  3329. }
  3330. }
  3331. };
  3332. void clang_EvalResult_dispose(CXEvalResult E) {
  3333. delete static_cast<ExprEvalResult *>(E);
  3334. }
  3335. CXEvalResultKind clang_EvalResult_getKind(CXEvalResult E) {
  3336. if (!E) {
  3337. return CXEval_UnExposed;
  3338. }
  3339. return ((ExprEvalResult *)E)->EvalType;
  3340. }
  3341. int clang_EvalResult_getAsInt(CXEvalResult E) {
  3342. return clang_EvalResult_getAsLongLong(E);
  3343. }
  3344. long long clang_EvalResult_getAsLongLong(CXEvalResult E) {
  3345. if (!E) {
  3346. return 0;
  3347. }
  3348. ExprEvalResult *Result = (ExprEvalResult *)E;
  3349. if (Result->IsUnsignedInt)
  3350. return Result->EvalData.unsignedVal;
  3351. return Result->EvalData.intVal;
  3352. }
  3353. unsigned clang_EvalResult_isUnsignedInt(CXEvalResult E) {
  3354. return ((ExprEvalResult *)E)->IsUnsignedInt;
  3355. }
  3356. unsigned long long clang_EvalResult_getAsUnsigned(CXEvalResult E) {
  3357. if (!E) {
  3358. return 0;
  3359. }
  3360. ExprEvalResult *Result = (ExprEvalResult *)E;
  3361. if (Result->IsUnsignedInt)
  3362. return Result->EvalData.unsignedVal;
  3363. return Result->EvalData.intVal;
  3364. }
  3365. double clang_EvalResult_getAsDouble(CXEvalResult E) {
  3366. if (!E) {
  3367. return 0;
  3368. }
  3369. return ((ExprEvalResult *)E)->EvalData.floatVal;
  3370. }
  3371. const char *clang_EvalResult_getAsStr(CXEvalResult E) {
  3372. if (!E) {
  3373. return nullptr;
  3374. }
  3375. return ((ExprEvalResult *)E)->EvalData.stringVal;
  3376. }
  3377. static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
  3378. Expr::EvalResult ER;
  3379. ASTContext &ctx = getCursorContext(C);
  3380. if (!expr)
  3381. return nullptr;
  3382. expr = expr->IgnoreParens();
  3383. if (expr->isValueDependent())
  3384. return nullptr;
  3385. if (!expr->EvaluateAsRValue(ER, ctx))
  3386. return nullptr;
  3387. QualType rettype;
  3388. CallExpr *callExpr;
  3389. auto result = std::make_unique<ExprEvalResult>();
  3390. result->EvalType = CXEval_UnExposed;
  3391. result->IsUnsignedInt = false;
  3392. if (ER.Val.isInt()) {
  3393. result->EvalType = CXEval_Int;
  3394. auto &val = ER.Val.getInt();
  3395. if (val.isUnsigned()) {
  3396. result->IsUnsignedInt = true;
  3397. result->EvalData.unsignedVal = val.getZExtValue();
  3398. } else {
  3399. result->EvalData.intVal = val.getExtValue();
  3400. }
  3401. return result.release();
  3402. }
  3403. if (ER.Val.isFloat()) {
  3404. llvm::SmallVector<char, 100> Buffer;
  3405. ER.Val.getFloat().toString(Buffer);
  3406. std::string floatStr(Buffer.data(), Buffer.size());
  3407. result->EvalType = CXEval_Float;
  3408. bool ignored;
  3409. llvm::APFloat apFloat = ER.Val.getFloat();
  3410. apFloat.convert(llvm::APFloat::IEEEdouble(),
  3411. llvm::APFloat::rmNearestTiesToEven, &ignored);
  3412. result->EvalData.floatVal = apFloat.convertToDouble();
  3413. return result.release();
  3414. }
  3415. if (expr->getStmtClass() == Stmt::ImplicitCastExprClass) {
  3416. const ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(expr);
  3417. auto *subExpr = I->getSubExprAsWritten();
  3418. if (subExpr->getStmtClass() == Stmt::StringLiteralClass ||
  3419. subExpr->getStmtClass() == Stmt::ObjCStringLiteralClass) {
  3420. const StringLiteral *StrE = nullptr;
  3421. const ObjCStringLiteral *ObjCExpr;
  3422. ObjCExpr = dyn_cast<ObjCStringLiteral>(subExpr);
  3423. if (ObjCExpr) {
  3424. StrE = ObjCExpr->getString();
  3425. result->EvalType = CXEval_ObjCStrLiteral;
  3426. } else {
  3427. StrE = cast<StringLiteral>(I->getSubExprAsWritten());
  3428. result->EvalType = CXEval_StrLiteral;
  3429. }
  3430. std::string strRef(StrE->getString().str());
  3431. result->EvalData.stringVal = new char[strRef.size() + 1];
  3432. strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
  3433. strRef.size());
  3434. result->EvalData.stringVal[strRef.size()] = '\0';
  3435. return result.release();
  3436. }
  3437. } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
  3438. expr->getStmtClass() == Stmt::StringLiteralClass) {
  3439. const StringLiteral *StrE = nullptr;
  3440. const ObjCStringLiteral *ObjCExpr;
  3441. ObjCExpr = dyn_cast<ObjCStringLiteral>(expr);
  3442. if (ObjCExpr) {
  3443. StrE = ObjCExpr->getString();
  3444. result->EvalType = CXEval_ObjCStrLiteral;
  3445. } else {
  3446. StrE = cast<StringLiteral>(expr);
  3447. result->EvalType = CXEval_StrLiteral;
  3448. }
  3449. std::string strRef(StrE->getString().str());
  3450. result->EvalData.stringVal = new char[strRef.size() + 1];
  3451. strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
  3452. result->EvalData.stringVal[strRef.size()] = '\0';
  3453. return result.release();
  3454. }
  3455. if (expr->getStmtClass() == Stmt::CStyleCastExprClass) {
  3456. CStyleCastExpr *CC = static_cast<CStyleCastExpr *>(expr);
  3457. rettype = CC->getType();
  3458. if (rettype.getAsString() == "CFStringRef" &&
  3459. CC->getSubExpr()->getStmtClass() == Stmt::CallExprClass) {
  3460. callExpr = static_cast<CallExpr *>(CC->getSubExpr());
  3461. StringLiteral *S = getCFSTR_value(callExpr);
  3462. if (S) {
  3463. std::string strLiteral(S->getString().str());
  3464. result->EvalType = CXEval_CFStr;
  3465. result->EvalData.stringVal = new char[strLiteral.size() + 1];
  3466. strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
  3467. strLiteral.size());
  3468. result->EvalData.stringVal[strLiteral.size()] = '\0';
  3469. return result.release();
  3470. }
  3471. }
  3472. } else if (expr->getStmtClass() == Stmt::CallExprClass) {
  3473. callExpr = static_cast<CallExpr *>(expr);
  3474. rettype = callExpr->getCallReturnType(ctx);
  3475. if (rettype->isVectorType() || callExpr->getNumArgs() > 1)
  3476. return nullptr;
  3477. if (rettype->isIntegralType(ctx) || rettype->isRealFloatingType()) {
  3478. if (callExpr->getNumArgs() == 1 &&
  3479. !callExpr->getArg(0)->getType()->isIntegralType(ctx))
  3480. return nullptr;
  3481. } else if (rettype.getAsString() == "CFStringRef") {
  3482. StringLiteral *S = getCFSTR_value(callExpr);
  3483. if (S) {
  3484. std::string strLiteral(S->getString().str());
  3485. result->EvalType = CXEval_CFStr;
  3486. result->EvalData.stringVal = new char[strLiteral.size() + 1];
  3487. strncpy((char *)result->EvalData.stringVal, strLiteral.c_str(),
  3488. strLiteral.size());
  3489. result->EvalData.stringVal[strLiteral.size()] = '\0';
  3490. return result.release();
  3491. }
  3492. }
  3493. } else if (expr->getStmtClass() == Stmt::DeclRefExprClass) {
  3494. DeclRefExpr *D = static_cast<DeclRefExpr *>(expr);
  3495. ValueDecl *V = D->getDecl();
  3496. if (V->getKind() == Decl::Function) {
  3497. std::string strName = V->getNameAsString();
  3498. result->EvalType = CXEval_Other;
  3499. result->EvalData.stringVal = new char[strName.size() + 1];
  3500. strncpy(result->EvalData.stringVal, strName.c_str(), strName.size());
  3501. result->EvalData.stringVal[strName.size()] = '\0';
  3502. return result.release();
  3503. }
  3504. }
  3505. return nullptr;
  3506. }
  3507. static const Expr *evaluateDeclExpr(const Decl *D) {
  3508. if (!D)
  3509. return nullptr;
  3510. if (auto *Var = dyn_cast<VarDecl>(D))
  3511. return Var->getInit();
  3512. else if (auto *Field = dyn_cast<FieldDecl>(D))
  3513. return Field->getInClassInitializer();
  3514. return nullptr;
  3515. }
  3516. static const Expr *evaluateCompoundStmtExpr(const CompoundStmt *CS) {
  3517. assert(CS && "invalid compound statement");
  3518. for (auto *bodyIterator : CS->body()) {
  3519. if (const auto *E = dyn_cast<Expr>(bodyIterator))
  3520. return E;
  3521. }
  3522. return nullptr;
  3523. }
  3524. CXEvalResult clang_Cursor_Evaluate(CXCursor C) {
  3525. const Expr *E = nullptr;
  3526. if (clang_getCursorKind(C) == CXCursor_CompoundStmt)
  3527. E = evaluateCompoundStmtExpr(cast<CompoundStmt>(getCursorStmt(C)));
  3528. else if (clang_isDeclaration(C.kind))
  3529. E = evaluateDeclExpr(getCursorDecl(C));
  3530. else if (clang_isExpression(C.kind))
  3531. E = getCursorExpr(C);
  3532. if (E)
  3533. return const_cast<CXEvalResult>(
  3534. reinterpret_cast<const void *>(evaluateExpr(const_cast<Expr *>(E), C)));
  3535. return nullptr;
  3536. }
  3537. unsigned clang_Cursor_hasAttrs(CXCursor C) {
  3538. const Decl *D = getCursorDecl(C);
  3539. if (!D) {
  3540. return 0;
  3541. }
  3542. if (D->hasAttrs()) {
  3543. return 1;
  3544. }
  3545. return 0;
  3546. }
  3547. unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
  3548. return CXSaveTranslationUnit_None;
  3549. }
  3550. static CXSaveError clang_saveTranslationUnit_Impl(CXTranslationUnit TU,
  3551. const char *FileName,
  3552. unsigned options) {
  3553. CIndexer *CXXIdx = TU->CIdx;
  3554. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForIndexing))
  3555. setThreadBackgroundPriority();
  3556. bool hadError = cxtu::getASTUnit(TU)->Save(FileName);
  3557. return hadError ? CXSaveError_Unknown : CXSaveError_None;
  3558. }
  3559. int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
  3560. unsigned options) {
  3561. LOG_FUNC_SECTION { *Log << TU << ' ' << FileName; }
  3562. if (isNotUsableTU(TU)) {
  3563. LOG_BAD_TU(TU);
  3564. return CXSaveError_InvalidTU;
  3565. }
  3566. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3567. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  3568. if (!CXXUnit->hasSema())
  3569. return CXSaveError_InvalidTU;
  3570. CXSaveError result;
  3571. auto SaveTranslationUnitImpl = [=, &result]() {
  3572. result = clang_saveTranslationUnit_Impl(TU, FileName, options);
  3573. };
  3574. if (!CXXUnit->getDiagnostics().hasUnrecoverableErrorOccurred()) {
  3575. SaveTranslationUnitImpl();
  3576. if (getenv("LIBCLANG_RESOURCE_USAGE"))
  3577. PrintLibclangResourceUsage(TU);
  3578. return result;
  3579. }
  3580. // We have an AST that has invalid nodes due to compiler errors.
  3581. // Use a crash recovery thread for protection.
  3582. llvm::CrashRecoveryContext CRC;
  3583. if (!RunSafely(CRC, SaveTranslationUnitImpl)) {
  3584. fprintf(stderr, "libclang: crash detected during AST saving: {\n");
  3585. fprintf(stderr, " 'filename' : '%s'\n", FileName);
  3586. fprintf(stderr, " 'options' : %d,\n", options);
  3587. fprintf(stderr, "}\n");
  3588. return CXSaveError_Unknown;
  3589. } else if (getenv("LIBCLANG_RESOURCE_USAGE")) {
  3590. PrintLibclangResourceUsage(TU);
  3591. }
  3592. return result;
  3593. }
  3594. void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
  3595. if (CTUnit) {
  3596. // If the translation unit has been marked as unsafe to free, just discard
  3597. // it.
  3598. ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
  3599. if (Unit && Unit->isUnsafeToFree())
  3600. return;
  3601. delete cxtu::getASTUnit(CTUnit);
  3602. delete CTUnit->StringPool;
  3603. delete static_cast<CXDiagnosticSetImpl *>(CTUnit->Diagnostics);
  3604. disposeOverridenCXCursorsPool(CTUnit->OverridenCursorsPool);
  3605. delete CTUnit->CommentToXML;
  3606. delete CTUnit;
  3607. }
  3608. }
  3609. unsigned clang_suspendTranslationUnit(CXTranslationUnit CTUnit) {
  3610. if (CTUnit) {
  3611. ASTUnit *Unit = cxtu::getASTUnit(CTUnit);
  3612. if (Unit && Unit->isUnsafeToFree())
  3613. return false;
  3614. Unit->ResetForParse();
  3615. return true;
  3616. }
  3617. return false;
  3618. }
  3619. unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
  3620. return CXReparse_None;
  3621. }
  3622. static CXErrorCode
  3623. clang_reparseTranslationUnit_Impl(CXTranslationUnit TU,
  3624. ArrayRef<CXUnsavedFile> unsaved_files,
  3625. unsigned options) {
  3626. // Check arguments.
  3627. if (isNotUsableTU(TU)) {
  3628. LOG_BAD_TU(TU);
  3629. return CXError_InvalidArguments;
  3630. }
  3631. // Reset the associated diagnostics.
  3632. delete static_cast<CXDiagnosticSetImpl *>(TU->Diagnostics);
  3633. TU->Diagnostics = nullptr;
  3634. CIndexer *CXXIdx = TU->CIdx;
  3635. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
  3636. setThreadBackgroundPriority();
  3637. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3638. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  3639. std::unique_ptr<std::vector<ASTUnit::RemappedFile>> RemappedFiles(
  3640. new std::vector<ASTUnit::RemappedFile>());
  3641. // Recover resources if we crash before exiting this function.
  3642. llvm::CrashRecoveryContextCleanupRegistrar<std::vector<ASTUnit::RemappedFile>>
  3643. RemappedCleanup(RemappedFiles.get());
  3644. for (auto &UF : unsaved_files) {
  3645. std::unique_ptr<llvm::MemoryBuffer> MB =
  3646. llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
  3647. RemappedFiles->push_back(std::make_pair(UF.Filename, MB.release()));
  3648. }
  3649. if (!CXXUnit->Reparse(CXXIdx->getPCHContainerOperations(),
  3650. *RemappedFiles.get()))
  3651. return CXError_Success;
  3652. if (isASTReadError(CXXUnit))
  3653. return CXError_ASTReadError;
  3654. return CXError_Failure;
  3655. }
  3656. int clang_reparseTranslationUnit(CXTranslationUnit TU,
  3657. unsigned num_unsaved_files,
  3658. struct CXUnsavedFile *unsaved_files,
  3659. unsigned options) {
  3660. LOG_FUNC_SECTION { *Log << TU; }
  3661. if (num_unsaved_files && !unsaved_files)
  3662. return CXError_InvalidArguments;
  3663. CXErrorCode result;
  3664. auto ReparseTranslationUnitImpl = [=, &result]() {
  3665. result = clang_reparseTranslationUnit_Impl(
  3666. TU, llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
  3667. };
  3668. llvm::CrashRecoveryContext CRC;
  3669. if (!RunSafely(CRC, ReparseTranslationUnitImpl)) {
  3670. fprintf(stderr, "libclang: crash detected during reparsing\n");
  3671. cxtu::getASTUnit(TU)->setUnsafeToFree(true);
  3672. return CXError_Crashed;
  3673. } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
  3674. PrintLibclangResourceUsage(TU);
  3675. return result;
  3676. }
  3677. CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
  3678. if (isNotUsableTU(CTUnit)) {
  3679. LOG_BAD_TU(CTUnit);
  3680. return cxstring::createEmpty();
  3681. }
  3682. ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
  3683. return cxstring::createDup(CXXUnit->getOriginalSourceFileName());
  3684. }
  3685. CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
  3686. if (isNotUsableTU(TU)) {
  3687. LOG_BAD_TU(TU);
  3688. return clang_getNullCursor();
  3689. }
  3690. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3691. return MakeCXCursor(CXXUnit->getASTContext().getTranslationUnitDecl(), TU);
  3692. }
  3693. CXTargetInfo clang_getTranslationUnitTargetInfo(CXTranslationUnit CTUnit) {
  3694. if (isNotUsableTU(CTUnit)) {
  3695. LOG_BAD_TU(CTUnit);
  3696. return nullptr;
  3697. }
  3698. CXTargetInfoImpl *impl = new CXTargetInfoImpl();
  3699. impl->TranslationUnit = CTUnit;
  3700. return impl;
  3701. }
  3702. CXString clang_TargetInfo_getTriple(CXTargetInfo TargetInfo) {
  3703. if (!TargetInfo)
  3704. return cxstring::createEmpty();
  3705. CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
  3706. assert(!isNotUsableTU(CTUnit) &&
  3707. "Unexpected unusable translation unit in TargetInfo");
  3708. ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
  3709. std::string Triple =
  3710. CXXUnit->getASTContext().getTargetInfo().getTriple().normalize();
  3711. return cxstring::createDup(Triple);
  3712. }
  3713. int clang_TargetInfo_getPointerWidth(CXTargetInfo TargetInfo) {
  3714. if (!TargetInfo)
  3715. return -1;
  3716. CXTranslationUnit CTUnit = TargetInfo->TranslationUnit;
  3717. assert(!isNotUsableTU(CTUnit) &&
  3718. "Unexpected unusable translation unit in TargetInfo");
  3719. ASTUnit *CXXUnit = cxtu::getASTUnit(CTUnit);
  3720. return CXXUnit->getASTContext().getTargetInfo().getMaxPointerWidth();
  3721. }
  3722. void clang_TargetInfo_dispose(CXTargetInfo TargetInfo) {
  3723. if (!TargetInfo)
  3724. return;
  3725. delete TargetInfo;
  3726. }
  3727. //===----------------------------------------------------------------------===//
  3728. // CXFile Operations.
  3729. //===----------------------------------------------------------------------===//
  3730. CXString clang_getFileName(CXFile SFile) {
  3731. if (!SFile)
  3732. return cxstring::createNull();
  3733. FileEntry *FEnt = static_cast<FileEntry *>(SFile);
  3734. return cxstring::createRef(FEnt->getName());
  3735. }
  3736. time_t clang_getFileTime(CXFile SFile) {
  3737. if (!SFile)
  3738. return 0;
  3739. FileEntry *FEnt = static_cast<FileEntry *>(SFile);
  3740. return FEnt->getModificationTime();
  3741. }
  3742. CXFile clang_getFile(CXTranslationUnit TU, const char *file_name) {
  3743. if (isNotUsableTU(TU)) {
  3744. LOG_BAD_TU(TU);
  3745. return nullptr;
  3746. }
  3747. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3748. FileManager &FMgr = CXXUnit->getFileManager();
  3749. auto File = FMgr.getFile(file_name);
  3750. if (!File)
  3751. return nullptr;
  3752. return const_cast<FileEntry *>(*File);
  3753. }
  3754. const char *clang_getFileContents(CXTranslationUnit TU, CXFile file,
  3755. size_t *size) {
  3756. if (isNotUsableTU(TU)) {
  3757. LOG_BAD_TU(TU);
  3758. return nullptr;
  3759. }
  3760. const SourceManager &SM = cxtu::getASTUnit(TU)->getSourceManager();
  3761. FileID fid = SM.translateFile(static_cast<FileEntry *>(file));
  3762. llvm::Optional<llvm::MemoryBufferRef> buf = SM.getBufferOrNone(fid);
  3763. if (!buf) {
  3764. if (size)
  3765. *size = 0;
  3766. return nullptr;
  3767. }
  3768. if (size)
  3769. *size = buf->getBufferSize();
  3770. return buf->getBufferStart();
  3771. }
  3772. unsigned clang_isFileMultipleIncludeGuarded(CXTranslationUnit TU, CXFile file) {
  3773. if (isNotUsableTU(TU)) {
  3774. LOG_BAD_TU(TU);
  3775. return 0;
  3776. }
  3777. if (!file)
  3778. return 0;
  3779. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  3780. FileEntry *FEnt = static_cast<FileEntry *>(file);
  3781. return CXXUnit->getPreprocessor()
  3782. .getHeaderSearchInfo()
  3783. .isFileMultipleIncludeGuarded(FEnt);
  3784. }
  3785. int clang_getFileUniqueID(CXFile file, CXFileUniqueID *outID) {
  3786. if (!file || !outID)
  3787. return 1;
  3788. FileEntry *FEnt = static_cast<FileEntry *>(file);
  3789. const llvm::sys::fs::UniqueID &ID = FEnt->getUniqueID();
  3790. outID->data[0] = ID.getDevice();
  3791. outID->data[1] = ID.getFile();
  3792. outID->data[2] = FEnt->getModificationTime();
  3793. return 0;
  3794. }
  3795. int clang_File_isEqual(CXFile file1, CXFile file2) {
  3796. if (file1 == file2)
  3797. return true;
  3798. if (!file1 || !file2)
  3799. return false;
  3800. FileEntry *FEnt1 = static_cast<FileEntry *>(file1);
  3801. FileEntry *FEnt2 = static_cast<FileEntry *>(file2);
  3802. return FEnt1->getUniqueID() == FEnt2->getUniqueID();
  3803. }
  3804. CXString clang_File_tryGetRealPathName(CXFile SFile) {
  3805. if (!SFile)
  3806. return cxstring::createNull();
  3807. FileEntry *FEnt = static_cast<FileEntry *>(SFile);
  3808. return cxstring::createRef(FEnt->tryGetRealPathName());
  3809. }
  3810. //===----------------------------------------------------------------------===//
  3811. // CXCursor Operations.
  3812. //===----------------------------------------------------------------------===//
  3813. static const Decl *getDeclFromExpr(const Stmt *E) {
  3814. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
  3815. return getDeclFromExpr(CE->getSubExpr());
  3816. if (const DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
  3817. return RefExpr->getDecl();
  3818. if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
  3819. return ME->getMemberDecl();
  3820. if (const ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
  3821. return RE->getDecl();
  3822. if (const ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E)) {
  3823. if (PRE->isExplicitProperty())
  3824. return PRE->getExplicitProperty();
  3825. // It could be messaging both getter and setter as in:
  3826. // ++myobj.myprop;
  3827. // in which case prefer to associate the setter since it is less obvious
  3828. // from inspecting the source that the setter is going to get called.
  3829. if (PRE->isMessagingSetter())
  3830. return PRE->getImplicitPropertySetter();
  3831. return PRE->getImplicitPropertyGetter();
  3832. }
  3833. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
  3834. return getDeclFromExpr(POE->getSyntacticForm());
  3835. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
  3836. if (Expr *Src = OVE->getSourceExpr())
  3837. return getDeclFromExpr(Src);
  3838. if (const CallExpr *CE = dyn_cast<CallExpr>(E))
  3839. return getDeclFromExpr(CE->getCallee());
  3840. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
  3841. if (!CE->isElidable())
  3842. return CE->getConstructor();
  3843. if (const CXXInheritedCtorInitExpr *CE =
  3844. dyn_cast<CXXInheritedCtorInitExpr>(E))
  3845. return CE->getConstructor();
  3846. if (const ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
  3847. return OME->getMethodDecl();
  3848. if (const ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
  3849. return PE->getProtocol();
  3850. if (const SubstNonTypeTemplateParmPackExpr *NTTP =
  3851. dyn_cast<SubstNonTypeTemplateParmPackExpr>(E))
  3852. return NTTP->getParameterPack();
  3853. if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
  3854. if (isa<NonTypeTemplateParmDecl>(SizeOfPack->getPack()) ||
  3855. isa<ParmVarDecl>(SizeOfPack->getPack()))
  3856. return SizeOfPack->getPack();
  3857. return nullptr;
  3858. }
  3859. static SourceLocation getLocationFromExpr(const Expr *E) {
  3860. if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
  3861. return getLocationFromExpr(CE->getSubExpr());
  3862. if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
  3863. return /*FIXME:*/ Msg->getLeftLoc();
  3864. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  3865. return DRE->getLocation();
  3866. if (const MemberExpr *Member = dyn_cast<MemberExpr>(E))
  3867. return Member->getMemberLoc();
  3868. if (const ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
  3869. return Ivar->getLocation();
  3870. if (const SizeOfPackExpr *SizeOfPack = dyn_cast<SizeOfPackExpr>(E))
  3871. return SizeOfPack->getPackLoc();
  3872. if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E))
  3873. return PropRef->getLocation();
  3874. return E->getBeginLoc();
  3875. }
  3876. extern "C" {
  3877. unsigned clang_visitChildren(CXCursor parent, CXCursorVisitor visitor,
  3878. CXClientData client_data) {
  3879. CursorVisitor CursorVis(getCursorTU(parent), visitor, client_data,
  3880. /*VisitPreprocessorLast=*/false);
  3881. return CursorVis.VisitChildren(parent);
  3882. }
  3883. #ifndef __has_feature
  3884. #define __has_feature(x) 0
  3885. #endif
  3886. #if __has_feature(blocks)
  3887. typedef enum CXChildVisitResult (^CXCursorVisitorBlock)(CXCursor cursor,
  3888. CXCursor parent);
  3889. static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
  3890. CXClientData client_data) {
  3891. CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
  3892. return block(cursor, parent);
  3893. }
  3894. #else
  3895. // If we are compiled with a compiler that doesn't have native blocks support,
  3896. // define and call the block manually, so the
  3897. typedef struct _CXChildVisitResult {
  3898. void *isa;
  3899. int flags;
  3900. int reserved;
  3901. enum CXChildVisitResult (*invoke)(struct _CXChildVisitResult *, CXCursor,
  3902. CXCursor);
  3903. } * CXCursorVisitorBlock;
  3904. static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
  3905. CXClientData client_data) {
  3906. CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
  3907. return block->invoke(block, cursor, parent);
  3908. }
  3909. #endif
  3910. unsigned clang_visitChildrenWithBlock(CXCursor parent,
  3911. CXCursorVisitorBlock block) {
  3912. return clang_visitChildren(parent, visitWithBlock, block);
  3913. }
  3914. static CXString getDeclSpelling(const Decl *D) {
  3915. if (!D)
  3916. return cxstring::createEmpty();
  3917. const NamedDecl *ND = dyn_cast<NamedDecl>(D);
  3918. if (!ND) {
  3919. if (const ObjCPropertyImplDecl *PropImpl =
  3920. dyn_cast<ObjCPropertyImplDecl>(D))
  3921. if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
  3922. return cxstring::createDup(Property->getIdentifier()->getName());
  3923. if (const ImportDecl *ImportD = dyn_cast<ImportDecl>(D))
  3924. if (Module *Mod = ImportD->getImportedModule())
  3925. return cxstring::createDup(Mod->getFullModuleName());
  3926. return cxstring::createEmpty();
  3927. }
  3928. if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
  3929. return cxstring::createDup(OMD->getSelector().getAsString());
  3930. if (const ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
  3931. // No, this isn't the same as the code below. getIdentifier() is non-virtual
  3932. // and returns different names. NamedDecl returns the class name and
  3933. // ObjCCategoryImplDecl returns the category name.
  3934. return cxstring::createRef(CIMP->getIdentifier()->getNameStart());
  3935. if (isa<UsingDirectiveDecl>(D))
  3936. return cxstring::createEmpty();
  3937. SmallString<1024> S;
  3938. llvm::raw_svector_ostream os(S);
  3939. ND->printName(os);
  3940. return cxstring::createDup(os.str());
  3941. }
  3942. CXString clang_getCursorSpelling(CXCursor C) {
  3943. if (clang_isTranslationUnit(C.kind))
  3944. return clang_getTranslationUnitSpelling(getCursorTU(C));
  3945. if (clang_isReference(C.kind)) {
  3946. switch (C.kind) {
  3947. case CXCursor_ObjCSuperClassRef: {
  3948. const ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
  3949. return cxstring::createRef(Super->getIdentifier()->getNameStart());
  3950. }
  3951. case CXCursor_ObjCClassRef: {
  3952. const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
  3953. return cxstring::createRef(Class->getIdentifier()->getNameStart());
  3954. }
  3955. case CXCursor_ObjCProtocolRef: {
  3956. const ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
  3957. assert(OID && "getCursorSpelling(): Missing protocol decl");
  3958. return cxstring::createRef(OID->getIdentifier()->getNameStart());
  3959. }
  3960. case CXCursor_CXXBaseSpecifier: {
  3961. const CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
  3962. return cxstring::createDup(B->getType().getAsString());
  3963. }
  3964. case CXCursor_TypeRef: {
  3965. const TypeDecl *Type = getCursorTypeRef(C).first;
  3966. assert(Type && "Missing type decl");
  3967. return cxstring::createDup(
  3968. getCursorContext(C).getTypeDeclType(Type).getAsString());
  3969. }
  3970. case CXCursor_TemplateRef: {
  3971. const TemplateDecl *Template = getCursorTemplateRef(C).first;
  3972. assert(Template && "Missing template decl");
  3973. return cxstring::createDup(Template->getNameAsString());
  3974. }
  3975. case CXCursor_NamespaceRef: {
  3976. const NamedDecl *NS = getCursorNamespaceRef(C).first;
  3977. assert(NS && "Missing namespace decl");
  3978. return cxstring::createDup(NS->getNameAsString());
  3979. }
  3980. case CXCursor_MemberRef: {
  3981. const FieldDecl *Field = getCursorMemberRef(C).first;
  3982. assert(Field && "Missing member decl");
  3983. return cxstring::createDup(Field->getNameAsString());
  3984. }
  3985. case CXCursor_LabelRef: {
  3986. const LabelStmt *Label = getCursorLabelRef(C).first;
  3987. assert(Label && "Missing label");
  3988. return cxstring::createRef(Label->getName());
  3989. }
  3990. case CXCursor_OverloadedDeclRef: {
  3991. OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
  3992. if (const Decl *D = Storage.dyn_cast<const Decl *>()) {
  3993. if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
  3994. return cxstring::createDup(ND->getNameAsString());
  3995. return cxstring::createEmpty();
  3996. }
  3997. if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
  3998. return cxstring::createDup(E->getName().getAsString());
  3999. OverloadedTemplateStorage *Ovl =
  4000. Storage.get<OverloadedTemplateStorage *>();
  4001. if (Ovl->size() == 0)
  4002. return cxstring::createEmpty();
  4003. return cxstring::createDup((*Ovl->begin())->getNameAsString());
  4004. }
  4005. case CXCursor_VariableRef: {
  4006. const VarDecl *Var = getCursorVariableRef(C).first;
  4007. assert(Var && "Missing variable decl");
  4008. return cxstring::createDup(Var->getNameAsString());
  4009. }
  4010. default:
  4011. return cxstring::createRef("<not implemented>");
  4012. }
  4013. }
  4014. if (clang_isExpression(C.kind)) {
  4015. const Expr *E = getCursorExpr(C);
  4016. if (C.kind == CXCursor_ObjCStringLiteral ||
  4017. C.kind == CXCursor_StringLiteral) {
  4018. const StringLiteral *SLit;
  4019. if (const ObjCStringLiteral *OSL = dyn_cast<ObjCStringLiteral>(E)) {
  4020. SLit = OSL->getString();
  4021. } else {
  4022. SLit = cast<StringLiteral>(E);
  4023. }
  4024. SmallString<256> Buf;
  4025. llvm::raw_svector_ostream OS(Buf);
  4026. SLit->outputString(OS);
  4027. return cxstring::createDup(OS.str());
  4028. }
  4029. const Decl *D = getDeclFromExpr(getCursorExpr(C));
  4030. if (D)
  4031. return getDeclSpelling(D);
  4032. return cxstring::createEmpty();
  4033. }
  4034. if (clang_isStatement(C.kind)) {
  4035. const Stmt *S = getCursorStmt(C);
  4036. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
  4037. return cxstring::createRef(Label->getName());
  4038. return cxstring::createEmpty();
  4039. }
  4040. if (C.kind == CXCursor_MacroExpansion)
  4041. return cxstring::createRef(
  4042. getCursorMacroExpansion(C).getName()->getNameStart());
  4043. if (C.kind == CXCursor_MacroDefinition)
  4044. return cxstring::createRef(
  4045. getCursorMacroDefinition(C)->getName()->getNameStart());
  4046. if (C.kind == CXCursor_InclusionDirective)
  4047. return cxstring::createDup(getCursorInclusionDirective(C)->getFileName());
  4048. if (clang_isDeclaration(C.kind))
  4049. return getDeclSpelling(getCursorDecl(C));
  4050. if (C.kind == CXCursor_AnnotateAttr) {
  4051. const AnnotateAttr *AA = cast<AnnotateAttr>(cxcursor::getCursorAttr(C));
  4052. return cxstring::createDup(AA->getAnnotation());
  4053. }
  4054. if (C.kind == CXCursor_AsmLabelAttr) {
  4055. const AsmLabelAttr *AA = cast<AsmLabelAttr>(cxcursor::getCursorAttr(C));
  4056. return cxstring::createDup(AA->getLabel());
  4057. }
  4058. if (C.kind == CXCursor_PackedAttr) {
  4059. return cxstring::createRef("packed");
  4060. }
  4061. if (C.kind == CXCursor_VisibilityAttr) {
  4062. const VisibilityAttr *AA = cast<VisibilityAttr>(cxcursor::getCursorAttr(C));
  4063. switch (AA->getVisibility()) {
  4064. case VisibilityAttr::VisibilityType::Default:
  4065. return cxstring::createRef("default");
  4066. case VisibilityAttr::VisibilityType::Hidden:
  4067. return cxstring::createRef("hidden");
  4068. case VisibilityAttr::VisibilityType::Protected:
  4069. return cxstring::createRef("protected");
  4070. }
  4071. llvm_unreachable("unknown visibility type");
  4072. }
  4073. return cxstring::createEmpty();
  4074. }
  4075. CXSourceRange clang_Cursor_getSpellingNameRange(CXCursor C, unsigned pieceIndex,
  4076. unsigned options) {
  4077. if (clang_Cursor_isNull(C))
  4078. return clang_getNullRange();
  4079. ASTContext &Ctx = getCursorContext(C);
  4080. if (clang_isStatement(C.kind)) {
  4081. const Stmt *S = getCursorStmt(C);
  4082. if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) {
  4083. if (pieceIndex > 0)
  4084. return clang_getNullRange();
  4085. return cxloc::translateSourceRange(Ctx, Label->getIdentLoc());
  4086. }
  4087. return clang_getNullRange();
  4088. }
  4089. if (C.kind == CXCursor_ObjCMessageExpr) {
  4090. if (const ObjCMessageExpr *ME =
  4091. dyn_cast_or_null<ObjCMessageExpr>(getCursorExpr(C))) {
  4092. if (pieceIndex >= ME->getNumSelectorLocs())
  4093. return clang_getNullRange();
  4094. return cxloc::translateSourceRange(Ctx, ME->getSelectorLoc(pieceIndex));
  4095. }
  4096. }
  4097. if (C.kind == CXCursor_ObjCInstanceMethodDecl ||
  4098. C.kind == CXCursor_ObjCClassMethodDecl) {
  4099. if (const ObjCMethodDecl *MD =
  4100. dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(C))) {
  4101. if (pieceIndex >= MD->getNumSelectorLocs())
  4102. return clang_getNullRange();
  4103. return cxloc::translateSourceRange(Ctx, MD->getSelectorLoc(pieceIndex));
  4104. }
  4105. }
  4106. if (C.kind == CXCursor_ObjCCategoryDecl ||
  4107. C.kind == CXCursor_ObjCCategoryImplDecl) {
  4108. if (pieceIndex > 0)
  4109. return clang_getNullRange();
  4110. if (const ObjCCategoryDecl *CD =
  4111. dyn_cast_or_null<ObjCCategoryDecl>(getCursorDecl(C)))
  4112. return cxloc::translateSourceRange(Ctx, CD->getCategoryNameLoc());
  4113. if (const ObjCCategoryImplDecl *CID =
  4114. dyn_cast_or_null<ObjCCategoryImplDecl>(getCursorDecl(C)))
  4115. return cxloc::translateSourceRange(Ctx, CID->getCategoryNameLoc());
  4116. }
  4117. if (C.kind == CXCursor_ModuleImportDecl) {
  4118. if (pieceIndex > 0)
  4119. return clang_getNullRange();
  4120. if (const ImportDecl *ImportD =
  4121. dyn_cast_or_null<ImportDecl>(getCursorDecl(C))) {
  4122. ArrayRef<SourceLocation> Locs = ImportD->getIdentifierLocs();
  4123. if (!Locs.empty())
  4124. return cxloc::translateSourceRange(
  4125. Ctx, SourceRange(Locs.front(), Locs.back()));
  4126. }
  4127. return clang_getNullRange();
  4128. }
  4129. if (C.kind == CXCursor_CXXMethod || C.kind == CXCursor_Destructor ||
  4130. C.kind == CXCursor_ConversionFunction ||
  4131. C.kind == CXCursor_FunctionDecl) {
  4132. if (pieceIndex > 0)
  4133. return clang_getNullRange();
  4134. if (const FunctionDecl *FD =
  4135. dyn_cast_or_null<FunctionDecl>(getCursorDecl(C))) {
  4136. DeclarationNameInfo FunctionName = FD->getNameInfo();
  4137. return cxloc::translateSourceRange(Ctx, FunctionName.getSourceRange());
  4138. }
  4139. return clang_getNullRange();
  4140. }
  4141. // FIXME: A CXCursor_InclusionDirective should give the location of the
  4142. // filename, but we don't keep track of this.
  4143. // FIXME: A CXCursor_AnnotateAttr should give the location of the annotation
  4144. // but we don't keep track of this.
  4145. // FIXME: A CXCursor_AsmLabelAttr should give the location of the label
  4146. // but we don't keep track of this.
  4147. // Default handling, give the location of the cursor.
  4148. if (pieceIndex > 0)
  4149. return clang_getNullRange();
  4150. CXSourceLocation CXLoc = clang_getCursorLocation(C);
  4151. SourceLocation Loc = cxloc::translateSourceLocation(CXLoc);
  4152. return cxloc::translateSourceRange(Ctx, Loc);
  4153. }
  4154. CXString clang_Cursor_getMangling(CXCursor C) {
  4155. if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
  4156. return cxstring::createEmpty();
  4157. // Mangling only works for functions and variables.
  4158. const Decl *D = getCursorDecl(C);
  4159. if (!D || !(isa<FunctionDecl>(D) || isa<VarDecl>(D)))
  4160. return cxstring::createEmpty();
  4161. ASTContext &Ctx = D->getASTContext();
  4162. ASTNameGenerator ASTNameGen(Ctx);
  4163. return cxstring::createDup(ASTNameGen.getName(D));
  4164. }
  4165. CXStringSet *clang_Cursor_getCXXManglings(CXCursor C) {
  4166. if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
  4167. return nullptr;
  4168. const Decl *D = getCursorDecl(C);
  4169. if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
  4170. return nullptr;
  4171. ASTContext &Ctx = D->getASTContext();
  4172. ASTNameGenerator ASTNameGen(Ctx);
  4173. std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
  4174. return cxstring::createSet(Manglings);
  4175. }
  4176. CXStringSet *clang_Cursor_getObjCManglings(CXCursor C) {
  4177. if (clang_isInvalid(C.kind) || !clang_isDeclaration(C.kind))
  4178. return nullptr;
  4179. const Decl *D = getCursorDecl(C);
  4180. if (!(isa<ObjCInterfaceDecl>(D) || isa<ObjCImplementationDecl>(D)))
  4181. return nullptr;
  4182. ASTContext &Ctx = D->getASTContext();
  4183. ASTNameGenerator ASTNameGen(Ctx);
  4184. std::vector<std::string> Manglings = ASTNameGen.getAllManglings(D);
  4185. return cxstring::createSet(Manglings);
  4186. }
  4187. CXPrintingPolicy clang_getCursorPrintingPolicy(CXCursor C) {
  4188. if (clang_Cursor_isNull(C))
  4189. return nullptr;
  4190. return new PrintingPolicy(getCursorContext(C).getPrintingPolicy());
  4191. }
  4192. void clang_PrintingPolicy_dispose(CXPrintingPolicy Policy) {
  4193. if (Policy)
  4194. delete static_cast<PrintingPolicy *>(Policy);
  4195. }
  4196. unsigned
  4197. clang_PrintingPolicy_getProperty(CXPrintingPolicy Policy,
  4198. enum CXPrintingPolicyProperty Property) {
  4199. if (!Policy)
  4200. return 0;
  4201. PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
  4202. switch (Property) {
  4203. case CXPrintingPolicy_Indentation:
  4204. return P->Indentation;
  4205. case CXPrintingPolicy_SuppressSpecifiers:
  4206. return P->SuppressSpecifiers;
  4207. case CXPrintingPolicy_SuppressTagKeyword:
  4208. return P->SuppressTagKeyword;
  4209. case CXPrintingPolicy_IncludeTagDefinition:
  4210. return P->IncludeTagDefinition;
  4211. case CXPrintingPolicy_SuppressScope:
  4212. return P->SuppressScope;
  4213. case CXPrintingPolicy_SuppressUnwrittenScope:
  4214. return P->SuppressUnwrittenScope;
  4215. case CXPrintingPolicy_SuppressInitializers:
  4216. return P->SuppressInitializers;
  4217. case CXPrintingPolicy_ConstantArraySizeAsWritten:
  4218. return P->ConstantArraySizeAsWritten;
  4219. case CXPrintingPolicy_AnonymousTagLocations:
  4220. return P->AnonymousTagLocations;
  4221. case CXPrintingPolicy_SuppressStrongLifetime:
  4222. return P->SuppressStrongLifetime;
  4223. case CXPrintingPolicy_SuppressLifetimeQualifiers:
  4224. return P->SuppressLifetimeQualifiers;
  4225. case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
  4226. return P->SuppressTemplateArgsInCXXConstructors;
  4227. case CXPrintingPolicy_Bool:
  4228. return P->Bool;
  4229. case CXPrintingPolicy_Restrict:
  4230. return P->Restrict;
  4231. case CXPrintingPolicy_Alignof:
  4232. return P->Alignof;
  4233. case CXPrintingPolicy_UnderscoreAlignof:
  4234. return P->UnderscoreAlignof;
  4235. case CXPrintingPolicy_UseVoidForZeroParams:
  4236. return P->UseVoidForZeroParams;
  4237. case CXPrintingPolicy_TerseOutput:
  4238. return P->TerseOutput;
  4239. case CXPrintingPolicy_PolishForDeclaration:
  4240. return P->PolishForDeclaration;
  4241. case CXPrintingPolicy_Half:
  4242. return P->Half;
  4243. case CXPrintingPolicy_MSWChar:
  4244. return P->MSWChar;
  4245. case CXPrintingPolicy_IncludeNewlines:
  4246. return P->IncludeNewlines;
  4247. case CXPrintingPolicy_MSVCFormatting:
  4248. return P->MSVCFormatting;
  4249. case CXPrintingPolicy_ConstantsAsWritten:
  4250. return P->ConstantsAsWritten;
  4251. case CXPrintingPolicy_SuppressImplicitBase:
  4252. return P->SuppressImplicitBase;
  4253. case CXPrintingPolicy_FullyQualifiedName:
  4254. return P->FullyQualifiedName;
  4255. }
  4256. assert(false && "Invalid CXPrintingPolicyProperty");
  4257. return 0;
  4258. }
  4259. void clang_PrintingPolicy_setProperty(CXPrintingPolicy Policy,
  4260. enum CXPrintingPolicyProperty Property,
  4261. unsigned Value) {
  4262. if (!Policy)
  4263. return;
  4264. PrintingPolicy *P = static_cast<PrintingPolicy *>(Policy);
  4265. switch (Property) {
  4266. case CXPrintingPolicy_Indentation:
  4267. P->Indentation = Value;
  4268. return;
  4269. case CXPrintingPolicy_SuppressSpecifiers:
  4270. P->SuppressSpecifiers = Value;
  4271. return;
  4272. case CXPrintingPolicy_SuppressTagKeyword:
  4273. P->SuppressTagKeyword = Value;
  4274. return;
  4275. case CXPrintingPolicy_IncludeTagDefinition:
  4276. P->IncludeTagDefinition = Value;
  4277. return;
  4278. case CXPrintingPolicy_SuppressScope:
  4279. P->SuppressScope = Value;
  4280. return;
  4281. case CXPrintingPolicy_SuppressUnwrittenScope:
  4282. P->SuppressUnwrittenScope = Value;
  4283. return;
  4284. case CXPrintingPolicy_SuppressInitializers:
  4285. P->SuppressInitializers = Value;
  4286. return;
  4287. case CXPrintingPolicy_ConstantArraySizeAsWritten:
  4288. P->ConstantArraySizeAsWritten = Value;
  4289. return;
  4290. case CXPrintingPolicy_AnonymousTagLocations:
  4291. P->AnonymousTagLocations = Value;
  4292. return;
  4293. case CXPrintingPolicy_SuppressStrongLifetime:
  4294. P->SuppressStrongLifetime = Value;
  4295. return;
  4296. case CXPrintingPolicy_SuppressLifetimeQualifiers:
  4297. P->SuppressLifetimeQualifiers = Value;
  4298. return;
  4299. case CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors:
  4300. P->SuppressTemplateArgsInCXXConstructors = Value;
  4301. return;
  4302. case CXPrintingPolicy_Bool:
  4303. P->Bool = Value;
  4304. return;
  4305. case CXPrintingPolicy_Restrict:
  4306. P->Restrict = Value;
  4307. return;
  4308. case CXPrintingPolicy_Alignof:
  4309. P->Alignof = Value;
  4310. return;
  4311. case CXPrintingPolicy_UnderscoreAlignof:
  4312. P->UnderscoreAlignof = Value;
  4313. return;
  4314. case CXPrintingPolicy_UseVoidForZeroParams:
  4315. P->UseVoidForZeroParams = Value;
  4316. return;
  4317. case CXPrintingPolicy_TerseOutput:
  4318. P->TerseOutput = Value;
  4319. return;
  4320. case CXPrintingPolicy_PolishForDeclaration:
  4321. P->PolishForDeclaration = Value;
  4322. return;
  4323. case CXPrintingPolicy_Half:
  4324. P->Half = Value;
  4325. return;
  4326. case CXPrintingPolicy_MSWChar:
  4327. P->MSWChar = Value;
  4328. return;
  4329. case CXPrintingPolicy_IncludeNewlines:
  4330. P->IncludeNewlines = Value;
  4331. return;
  4332. case CXPrintingPolicy_MSVCFormatting:
  4333. P->MSVCFormatting = Value;
  4334. return;
  4335. case CXPrintingPolicy_ConstantsAsWritten:
  4336. P->ConstantsAsWritten = Value;
  4337. return;
  4338. case CXPrintingPolicy_SuppressImplicitBase:
  4339. P->SuppressImplicitBase = Value;
  4340. return;
  4341. case CXPrintingPolicy_FullyQualifiedName:
  4342. P->FullyQualifiedName = Value;
  4343. return;
  4344. }
  4345. assert(false && "Invalid CXPrintingPolicyProperty");
  4346. }
  4347. CXString clang_getCursorPrettyPrinted(CXCursor C, CXPrintingPolicy cxPolicy) {
  4348. if (clang_Cursor_isNull(C))
  4349. return cxstring::createEmpty();
  4350. if (clang_isDeclaration(C.kind)) {
  4351. const Decl *D = getCursorDecl(C);
  4352. if (!D)
  4353. return cxstring::createEmpty();
  4354. SmallString<128> Str;
  4355. llvm::raw_svector_ostream OS(Str);
  4356. PrintingPolicy *UserPolicy = static_cast<PrintingPolicy *>(cxPolicy);
  4357. D->print(OS, UserPolicy ? *UserPolicy
  4358. : getCursorContext(C).getPrintingPolicy());
  4359. return cxstring::createDup(OS.str());
  4360. }
  4361. return cxstring::createEmpty();
  4362. }
  4363. CXString clang_getCursorDisplayName(CXCursor C) {
  4364. if (!clang_isDeclaration(C.kind))
  4365. return clang_getCursorSpelling(C);
  4366. const Decl *D = getCursorDecl(C);
  4367. if (!D)
  4368. return cxstring::createEmpty();
  4369. PrintingPolicy Policy = getCursorContext(C).getPrintingPolicy();
  4370. if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  4371. D = FunTmpl->getTemplatedDecl();
  4372. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
  4373. SmallString<64> Str;
  4374. llvm::raw_svector_ostream OS(Str);
  4375. OS << *Function;
  4376. if (Function->getPrimaryTemplate())
  4377. OS << "<>";
  4378. OS << "(";
  4379. for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
  4380. if (I)
  4381. OS << ", ";
  4382. OS << Function->getParamDecl(I)->getType().getAsString(Policy);
  4383. }
  4384. if (Function->isVariadic()) {
  4385. if (Function->getNumParams())
  4386. OS << ", ";
  4387. OS << "...";
  4388. }
  4389. OS << ")";
  4390. return cxstring::createDup(OS.str());
  4391. }
  4392. if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
  4393. SmallString<64> Str;
  4394. llvm::raw_svector_ostream OS(Str);
  4395. OS << *ClassTemplate;
  4396. OS << "<";
  4397. TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
  4398. for (unsigned I = 0, N = Params->size(); I != N; ++I) {
  4399. if (I)
  4400. OS << ", ";
  4401. NamedDecl *Param = Params->getParam(I);
  4402. if (Param->getIdentifier()) {
  4403. OS << Param->getIdentifier()->getName();
  4404. continue;
  4405. }
  4406. // There is no parameter name, which makes this tricky. Try to come up
  4407. // with something useful that isn't too long.
  4408. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  4409. if (const auto *TC = TTP->getTypeConstraint()) {
  4410. TC->getConceptNameInfo().printName(OS, Policy);
  4411. if (TC->hasExplicitTemplateArgs())
  4412. OS << "<...>";
  4413. } else
  4414. OS << (TTP->wasDeclaredWithTypename() ? "typename" : "class");
  4415. else if (NonTypeTemplateParmDecl *NTTP =
  4416. dyn_cast<NonTypeTemplateParmDecl>(Param))
  4417. OS << NTTP->getType().getAsString(Policy);
  4418. else
  4419. OS << "template<...> class";
  4420. }
  4421. OS << ">";
  4422. return cxstring::createDup(OS.str());
  4423. }
  4424. if (const ClassTemplateSpecializationDecl *ClassSpec =
  4425. dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  4426. // If the type was explicitly written, use that.
  4427. if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
  4428. return cxstring::createDup(TSInfo->getType().getAsString(Policy));
  4429. SmallString<128> Str;
  4430. llvm::raw_svector_ostream OS(Str);
  4431. OS << *ClassSpec;
  4432. printTemplateArgumentList(
  4433. OS, ClassSpec->getTemplateArgs().asArray(), Policy,
  4434. ClassSpec->getSpecializedTemplate()->getTemplateParameters());
  4435. return cxstring::createDup(OS.str());
  4436. }
  4437. return clang_getCursorSpelling(C);
  4438. }
  4439. CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
  4440. switch (Kind) {
  4441. case CXCursor_FunctionDecl:
  4442. return cxstring::createRef("FunctionDecl");
  4443. case CXCursor_TypedefDecl:
  4444. return cxstring::createRef("TypedefDecl");
  4445. case CXCursor_EnumDecl:
  4446. return cxstring::createRef("EnumDecl");
  4447. case CXCursor_EnumConstantDecl:
  4448. return cxstring::createRef("EnumConstantDecl");
  4449. case CXCursor_StructDecl:
  4450. return cxstring::createRef("StructDecl");
  4451. case CXCursor_UnionDecl:
  4452. return cxstring::createRef("UnionDecl");
  4453. case CXCursor_ClassDecl:
  4454. return cxstring::createRef("ClassDecl");
  4455. case CXCursor_FieldDecl:
  4456. return cxstring::createRef("FieldDecl");
  4457. case CXCursor_VarDecl:
  4458. return cxstring::createRef("VarDecl");
  4459. case CXCursor_ParmDecl:
  4460. return cxstring::createRef("ParmDecl");
  4461. case CXCursor_ObjCInterfaceDecl:
  4462. return cxstring::createRef("ObjCInterfaceDecl");
  4463. case CXCursor_ObjCCategoryDecl:
  4464. return cxstring::createRef("ObjCCategoryDecl");
  4465. case CXCursor_ObjCProtocolDecl:
  4466. return cxstring::createRef("ObjCProtocolDecl");
  4467. case CXCursor_ObjCPropertyDecl:
  4468. return cxstring::createRef("ObjCPropertyDecl");
  4469. case CXCursor_ObjCIvarDecl:
  4470. return cxstring::createRef("ObjCIvarDecl");
  4471. case CXCursor_ObjCInstanceMethodDecl:
  4472. return cxstring::createRef("ObjCInstanceMethodDecl");
  4473. case CXCursor_ObjCClassMethodDecl:
  4474. return cxstring::createRef("ObjCClassMethodDecl");
  4475. case CXCursor_ObjCImplementationDecl:
  4476. return cxstring::createRef("ObjCImplementationDecl");
  4477. case CXCursor_ObjCCategoryImplDecl:
  4478. return cxstring::createRef("ObjCCategoryImplDecl");
  4479. case CXCursor_CXXMethod:
  4480. return cxstring::createRef("CXXMethod");
  4481. case CXCursor_UnexposedDecl:
  4482. return cxstring::createRef("UnexposedDecl");
  4483. case CXCursor_ObjCSuperClassRef:
  4484. return cxstring::createRef("ObjCSuperClassRef");
  4485. case CXCursor_ObjCProtocolRef:
  4486. return cxstring::createRef("ObjCProtocolRef");
  4487. case CXCursor_ObjCClassRef:
  4488. return cxstring::createRef("ObjCClassRef");
  4489. case CXCursor_TypeRef:
  4490. return cxstring::createRef("TypeRef");
  4491. case CXCursor_TemplateRef:
  4492. return cxstring::createRef("TemplateRef");
  4493. case CXCursor_NamespaceRef:
  4494. return cxstring::createRef("NamespaceRef");
  4495. case CXCursor_MemberRef:
  4496. return cxstring::createRef("MemberRef");
  4497. case CXCursor_LabelRef:
  4498. return cxstring::createRef("LabelRef");
  4499. case CXCursor_OverloadedDeclRef:
  4500. return cxstring::createRef("OverloadedDeclRef");
  4501. case CXCursor_VariableRef:
  4502. return cxstring::createRef("VariableRef");
  4503. case CXCursor_IntegerLiteral:
  4504. return cxstring::createRef("IntegerLiteral");
  4505. case CXCursor_FixedPointLiteral:
  4506. return cxstring::createRef("FixedPointLiteral");
  4507. case CXCursor_FloatingLiteral:
  4508. return cxstring::createRef("FloatingLiteral");
  4509. case CXCursor_ImaginaryLiteral:
  4510. return cxstring::createRef("ImaginaryLiteral");
  4511. case CXCursor_StringLiteral:
  4512. return cxstring::createRef("StringLiteral");
  4513. case CXCursor_CharacterLiteral:
  4514. return cxstring::createRef("CharacterLiteral");
  4515. case CXCursor_ParenExpr:
  4516. return cxstring::createRef("ParenExpr");
  4517. case CXCursor_UnaryOperator:
  4518. return cxstring::createRef("UnaryOperator");
  4519. case CXCursor_ArraySubscriptExpr:
  4520. return cxstring::createRef("ArraySubscriptExpr");
  4521. case CXCursor_OMPArraySectionExpr:
  4522. return cxstring::createRef("OMPArraySectionExpr");
  4523. case CXCursor_OMPArrayShapingExpr:
  4524. return cxstring::createRef("OMPArrayShapingExpr");
  4525. case CXCursor_OMPIteratorExpr:
  4526. return cxstring::createRef("OMPIteratorExpr");
  4527. case CXCursor_BinaryOperator:
  4528. return cxstring::createRef("BinaryOperator");
  4529. case CXCursor_CompoundAssignOperator:
  4530. return cxstring::createRef("CompoundAssignOperator");
  4531. case CXCursor_ConditionalOperator:
  4532. return cxstring::createRef("ConditionalOperator");
  4533. case CXCursor_CStyleCastExpr:
  4534. return cxstring::createRef("CStyleCastExpr");
  4535. case CXCursor_CompoundLiteralExpr:
  4536. return cxstring::createRef("CompoundLiteralExpr");
  4537. case CXCursor_InitListExpr:
  4538. return cxstring::createRef("InitListExpr");
  4539. case CXCursor_AddrLabelExpr:
  4540. return cxstring::createRef("AddrLabelExpr");
  4541. case CXCursor_StmtExpr:
  4542. return cxstring::createRef("StmtExpr");
  4543. case CXCursor_GenericSelectionExpr:
  4544. return cxstring::createRef("GenericSelectionExpr");
  4545. case CXCursor_GNUNullExpr:
  4546. return cxstring::createRef("GNUNullExpr");
  4547. case CXCursor_CXXStaticCastExpr:
  4548. return cxstring::createRef("CXXStaticCastExpr");
  4549. case CXCursor_CXXDynamicCastExpr:
  4550. return cxstring::createRef("CXXDynamicCastExpr");
  4551. case CXCursor_CXXReinterpretCastExpr:
  4552. return cxstring::createRef("CXXReinterpretCastExpr");
  4553. case CXCursor_CXXConstCastExpr:
  4554. return cxstring::createRef("CXXConstCastExpr");
  4555. case CXCursor_CXXFunctionalCastExpr:
  4556. return cxstring::createRef("CXXFunctionalCastExpr");
  4557. case CXCursor_CXXAddrspaceCastExpr:
  4558. return cxstring::createRef("CXXAddrspaceCastExpr");
  4559. case CXCursor_CXXTypeidExpr:
  4560. return cxstring::createRef("CXXTypeidExpr");
  4561. case CXCursor_CXXBoolLiteralExpr:
  4562. return cxstring::createRef("CXXBoolLiteralExpr");
  4563. case CXCursor_CXXNullPtrLiteralExpr:
  4564. return cxstring::createRef("CXXNullPtrLiteralExpr");
  4565. case CXCursor_CXXThisExpr:
  4566. return cxstring::createRef("CXXThisExpr");
  4567. case CXCursor_CXXThrowExpr:
  4568. return cxstring::createRef("CXXThrowExpr");
  4569. case CXCursor_CXXNewExpr:
  4570. return cxstring::createRef("CXXNewExpr");
  4571. case CXCursor_CXXDeleteExpr:
  4572. return cxstring::createRef("CXXDeleteExpr");
  4573. case CXCursor_UnaryExpr:
  4574. return cxstring::createRef("UnaryExpr");
  4575. case CXCursor_ObjCStringLiteral:
  4576. return cxstring::createRef("ObjCStringLiteral");
  4577. case CXCursor_ObjCBoolLiteralExpr:
  4578. return cxstring::createRef("ObjCBoolLiteralExpr");
  4579. case CXCursor_ObjCAvailabilityCheckExpr:
  4580. return cxstring::createRef("ObjCAvailabilityCheckExpr");
  4581. case CXCursor_ObjCSelfExpr:
  4582. return cxstring::createRef("ObjCSelfExpr");
  4583. case CXCursor_ObjCEncodeExpr:
  4584. return cxstring::createRef("ObjCEncodeExpr");
  4585. case CXCursor_ObjCSelectorExpr:
  4586. return cxstring::createRef("ObjCSelectorExpr");
  4587. case CXCursor_ObjCProtocolExpr:
  4588. return cxstring::createRef("ObjCProtocolExpr");
  4589. case CXCursor_ObjCBridgedCastExpr:
  4590. return cxstring::createRef("ObjCBridgedCastExpr");
  4591. case CXCursor_BlockExpr:
  4592. return cxstring::createRef("BlockExpr");
  4593. case CXCursor_PackExpansionExpr:
  4594. return cxstring::createRef("PackExpansionExpr");
  4595. case CXCursor_SizeOfPackExpr:
  4596. return cxstring::createRef("SizeOfPackExpr");
  4597. case CXCursor_LambdaExpr:
  4598. return cxstring::createRef("LambdaExpr");
  4599. case CXCursor_UnexposedExpr:
  4600. return cxstring::createRef("UnexposedExpr");
  4601. case CXCursor_DeclRefExpr:
  4602. return cxstring::createRef("DeclRefExpr");
  4603. case CXCursor_MemberRefExpr:
  4604. return cxstring::createRef("MemberRefExpr");
  4605. case CXCursor_CallExpr:
  4606. return cxstring::createRef("CallExpr");
  4607. case CXCursor_ObjCMessageExpr:
  4608. return cxstring::createRef("ObjCMessageExpr");
  4609. case CXCursor_BuiltinBitCastExpr:
  4610. return cxstring::createRef("BuiltinBitCastExpr");
  4611. case CXCursor_UnexposedStmt:
  4612. return cxstring::createRef("UnexposedStmt");
  4613. case CXCursor_DeclStmt:
  4614. return cxstring::createRef("DeclStmt");
  4615. case CXCursor_LabelStmt:
  4616. return cxstring::createRef("LabelStmt");
  4617. case CXCursor_CompoundStmt:
  4618. return cxstring::createRef("CompoundStmt");
  4619. case CXCursor_CaseStmt:
  4620. return cxstring::createRef("CaseStmt");
  4621. case CXCursor_DefaultStmt:
  4622. return cxstring::createRef("DefaultStmt");
  4623. case CXCursor_IfStmt:
  4624. return cxstring::createRef("IfStmt");
  4625. case CXCursor_SwitchStmt:
  4626. return cxstring::createRef("SwitchStmt");
  4627. case CXCursor_WhileStmt:
  4628. return cxstring::createRef("WhileStmt");
  4629. case CXCursor_DoStmt:
  4630. return cxstring::createRef("DoStmt");
  4631. case CXCursor_ForStmt:
  4632. return cxstring::createRef("ForStmt");
  4633. case CXCursor_GotoStmt:
  4634. return cxstring::createRef("GotoStmt");
  4635. case CXCursor_IndirectGotoStmt:
  4636. return cxstring::createRef("IndirectGotoStmt");
  4637. case CXCursor_ContinueStmt:
  4638. return cxstring::createRef("ContinueStmt");
  4639. case CXCursor_BreakStmt:
  4640. return cxstring::createRef("BreakStmt");
  4641. case CXCursor_ReturnStmt:
  4642. return cxstring::createRef("ReturnStmt");
  4643. case CXCursor_GCCAsmStmt:
  4644. return cxstring::createRef("GCCAsmStmt");
  4645. case CXCursor_MSAsmStmt:
  4646. return cxstring::createRef("MSAsmStmt");
  4647. case CXCursor_ObjCAtTryStmt:
  4648. return cxstring::createRef("ObjCAtTryStmt");
  4649. case CXCursor_ObjCAtCatchStmt:
  4650. return cxstring::createRef("ObjCAtCatchStmt");
  4651. case CXCursor_ObjCAtFinallyStmt:
  4652. return cxstring::createRef("ObjCAtFinallyStmt");
  4653. case CXCursor_ObjCAtThrowStmt:
  4654. return cxstring::createRef("ObjCAtThrowStmt");
  4655. case CXCursor_ObjCAtSynchronizedStmt:
  4656. return cxstring::createRef("ObjCAtSynchronizedStmt");
  4657. case CXCursor_ObjCAutoreleasePoolStmt:
  4658. return cxstring::createRef("ObjCAutoreleasePoolStmt");
  4659. case CXCursor_ObjCForCollectionStmt:
  4660. return cxstring::createRef("ObjCForCollectionStmt");
  4661. case CXCursor_CXXCatchStmt:
  4662. return cxstring::createRef("CXXCatchStmt");
  4663. case CXCursor_CXXTryStmt:
  4664. return cxstring::createRef("CXXTryStmt");
  4665. case CXCursor_CXXForRangeStmt:
  4666. return cxstring::createRef("CXXForRangeStmt");
  4667. case CXCursor_SEHTryStmt:
  4668. return cxstring::createRef("SEHTryStmt");
  4669. case CXCursor_SEHExceptStmt:
  4670. return cxstring::createRef("SEHExceptStmt");
  4671. case CXCursor_SEHFinallyStmt:
  4672. return cxstring::createRef("SEHFinallyStmt");
  4673. case CXCursor_SEHLeaveStmt:
  4674. return cxstring::createRef("SEHLeaveStmt");
  4675. case CXCursor_NullStmt:
  4676. return cxstring::createRef("NullStmt");
  4677. case CXCursor_InvalidFile:
  4678. return cxstring::createRef("InvalidFile");
  4679. case CXCursor_InvalidCode:
  4680. return cxstring::createRef("InvalidCode");
  4681. case CXCursor_NoDeclFound:
  4682. return cxstring::createRef("NoDeclFound");
  4683. case CXCursor_NotImplemented:
  4684. return cxstring::createRef("NotImplemented");
  4685. case CXCursor_TranslationUnit:
  4686. return cxstring::createRef("TranslationUnit");
  4687. case CXCursor_UnexposedAttr:
  4688. return cxstring::createRef("UnexposedAttr");
  4689. case CXCursor_IBActionAttr:
  4690. return cxstring::createRef("attribute(ibaction)");
  4691. case CXCursor_IBOutletAttr:
  4692. return cxstring::createRef("attribute(iboutlet)");
  4693. case CXCursor_IBOutletCollectionAttr:
  4694. return cxstring::createRef("attribute(iboutletcollection)");
  4695. case CXCursor_CXXFinalAttr:
  4696. return cxstring::createRef("attribute(final)");
  4697. case CXCursor_CXXOverrideAttr:
  4698. return cxstring::createRef("attribute(override)");
  4699. case CXCursor_AnnotateAttr:
  4700. return cxstring::createRef("attribute(annotate)");
  4701. case CXCursor_AsmLabelAttr:
  4702. return cxstring::createRef("asm label");
  4703. case CXCursor_PackedAttr:
  4704. return cxstring::createRef("attribute(packed)");
  4705. case CXCursor_PureAttr:
  4706. return cxstring::createRef("attribute(pure)");
  4707. case CXCursor_ConstAttr:
  4708. return cxstring::createRef("attribute(const)");
  4709. case CXCursor_NoDuplicateAttr:
  4710. return cxstring::createRef("attribute(noduplicate)");
  4711. case CXCursor_CUDAConstantAttr:
  4712. return cxstring::createRef("attribute(constant)");
  4713. case CXCursor_CUDADeviceAttr:
  4714. return cxstring::createRef("attribute(device)");
  4715. case CXCursor_CUDAGlobalAttr:
  4716. return cxstring::createRef("attribute(global)");
  4717. case CXCursor_CUDAHostAttr:
  4718. return cxstring::createRef("attribute(host)");
  4719. case CXCursor_CUDASharedAttr:
  4720. return cxstring::createRef("attribute(shared)");
  4721. case CXCursor_VisibilityAttr:
  4722. return cxstring::createRef("attribute(visibility)");
  4723. case CXCursor_DLLExport:
  4724. return cxstring::createRef("attribute(dllexport)");
  4725. case CXCursor_DLLImport:
  4726. return cxstring::createRef("attribute(dllimport)");
  4727. case CXCursor_NSReturnsRetained:
  4728. return cxstring::createRef("attribute(ns_returns_retained)");
  4729. case CXCursor_NSReturnsNotRetained:
  4730. return cxstring::createRef("attribute(ns_returns_not_retained)");
  4731. case CXCursor_NSReturnsAutoreleased:
  4732. return cxstring::createRef("attribute(ns_returns_autoreleased)");
  4733. case CXCursor_NSConsumesSelf:
  4734. return cxstring::createRef("attribute(ns_consumes_self)");
  4735. case CXCursor_NSConsumed:
  4736. return cxstring::createRef("attribute(ns_consumed)");
  4737. case CXCursor_ObjCException:
  4738. return cxstring::createRef("attribute(objc_exception)");
  4739. case CXCursor_ObjCNSObject:
  4740. return cxstring::createRef("attribute(NSObject)");
  4741. case CXCursor_ObjCIndependentClass:
  4742. return cxstring::createRef("attribute(objc_independent_class)");
  4743. case CXCursor_ObjCPreciseLifetime:
  4744. return cxstring::createRef("attribute(objc_precise_lifetime)");
  4745. case CXCursor_ObjCReturnsInnerPointer:
  4746. return cxstring::createRef("attribute(objc_returns_inner_pointer)");
  4747. case CXCursor_ObjCRequiresSuper:
  4748. return cxstring::createRef("attribute(objc_requires_super)");
  4749. case CXCursor_ObjCRootClass:
  4750. return cxstring::createRef("attribute(objc_root_class)");
  4751. case CXCursor_ObjCSubclassingRestricted:
  4752. return cxstring::createRef("attribute(objc_subclassing_restricted)");
  4753. case CXCursor_ObjCExplicitProtocolImpl:
  4754. return cxstring::createRef(
  4755. "attribute(objc_protocol_requires_explicit_implementation)");
  4756. case CXCursor_ObjCDesignatedInitializer:
  4757. return cxstring::createRef("attribute(objc_designated_initializer)");
  4758. case CXCursor_ObjCRuntimeVisible:
  4759. return cxstring::createRef("attribute(objc_runtime_visible)");
  4760. case CXCursor_ObjCBoxable:
  4761. return cxstring::createRef("attribute(objc_boxable)");
  4762. case CXCursor_FlagEnum:
  4763. return cxstring::createRef("attribute(flag_enum)");
  4764. case CXCursor_PreprocessingDirective:
  4765. return cxstring::createRef("preprocessing directive");
  4766. case CXCursor_MacroDefinition:
  4767. return cxstring::createRef("macro definition");
  4768. case CXCursor_MacroExpansion:
  4769. return cxstring::createRef("macro expansion");
  4770. case CXCursor_InclusionDirective:
  4771. return cxstring::createRef("inclusion directive");
  4772. case CXCursor_Namespace:
  4773. return cxstring::createRef("Namespace");
  4774. case CXCursor_LinkageSpec:
  4775. return cxstring::createRef("LinkageSpec");
  4776. case CXCursor_CXXBaseSpecifier:
  4777. return cxstring::createRef("C++ base class specifier");
  4778. case CXCursor_Constructor:
  4779. return cxstring::createRef("CXXConstructor");
  4780. case CXCursor_Destructor:
  4781. return cxstring::createRef("CXXDestructor");
  4782. case CXCursor_ConversionFunction:
  4783. return cxstring::createRef("CXXConversion");
  4784. case CXCursor_TemplateTypeParameter:
  4785. return cxstring::createRef("TemplateTypeParameter");
  4786. case CXCursor_NonTypeTemplateParameter:
  4787. return cxstring::createRef("NonTypeTemplateParameter");
  4788. case CXCursor_TemplateTemplateParameter:
  4789. return cxstring::createRef("TemplateTemplateParameter");
  4790. case CXCursor_FunctionTemplate:
  4791. return cxstring::createRef("FunctionTemplate");
  4792. case CXCursor_ClassTemplate:
  4793. return cxstring::createRef("ClassTemplate");
  4794. case CXCursor_ClassTemplatePartialSpecialization:
  4795. return cxstring::createRef("ClassTemplatePartialSpecialization");
  4796. case CXCursor_NamespaceAlias:
  4797. return cxstring::createRef("NamespaceAlias");
  4798. case CXCursor_UsingDirective:
  4799. return cxstring::createRef("UsingDirective");
  4800. case CXCursor_UsingDeclaration:
  4801. return cxstring::createRef("UsingDeclaration");
  4802. case CXCursor_TypeAliasDecl:
  4803. return cxstring::createRef("TypeAliasDecl");
  4804. case CXCursor_ObjCSynthesizeDecl:
  4805. return cxstring::createRef("ObjCSynthesizeDecl");
  4806. case CXCursor_ObjCDynamicDecl:
  4807. return cxstring::createRef("ObjCDynamicDecl");
  4808. case CXCursor_CXXAccessSpecifier:
  4809. return cxstring::createRef("CXXAccessSpecifier");
  4810. case CXCursor_ModuleImportDecl:
  4811. return cxstring::createRef("ModuleImport");
  4812. case CXCursor_OMPCanonicalLoop:
  4813. return cxstring::createRef("OMPCanonicalLoop");
  4814. case CXCursor_OMPMetaDirective:
  4815. return cxstring::createRef("OMPMetaDirective");
  4816. case CXCursor_OMPParallelDirective:
  4817. return cxstring::createRef("OMPParallelDirective");
  4818. case CXCursor_OMPSimdDirective:
  4819. return cxstring::createRef("OMPSimdDirective");
  4820. case CXCursor_OMPTileDirective:
  4821. return cxstring::createRef("OMPTileDirective");
  4822. case CXCursor_OMPUnrollDirective:
  4823. return cxstring::createRef("OMPUnrollDirective");
  4824. case CXCursor_OMPForDirective:
  4825. return cxstring::createRef("OMPForDirective");
  4826. case CXCursor_OMPForSimdDirective:
  4827. return cxstring::createRef("OMPForSimdDirective");
  4828. case CXCursor_OMPSectionsDirective:
  4829. return cxstring::createRef("OMPSectionsDirective");
  4830. case CXCursor_OMPSectionDirective:
  4831. return cxstring::createRef("OMPSectionDirective");
  4832. case CXCursor_OMPSingleDirective:
  4833. return cxstring::createRef("OMPSingleDirective");
  4834. case CXCursor_OMPMasterDirective:
  4835. return cxstring::createRef("OMPMasterDirective");
  4836. case CXCursor_OMPCriticalDirective:
  4837. return cxstring::createRef("OMPCriticalDirective");
  4838. case CXCursor_OMPParallelForDirective:
  4839. return cxstring::createRef("OMPParallelForDirective");
  4840. case CXCursor_OMPParallelForSimdDirective:
  4841. return cxstring::createRef("OMPParallelForSimdDirective");
  4842. case CXCursor_OMPParallelMasterDirective:
  4843. return cxstring::createRef("OMPParallelMasterDirective");
  4844. case CXCursor_OMPParallelSectionsDirective:
  4845. return cxstring::createRef("OMPParallelSectionsDirective");
  4846. case CXCursor_OMPTaskDirective:
  4847. return cxstring::createRef("OMPTaskDirective");
  4848. case CXCursor_OMPTaskyieldDirective:
  4849. return cxstring::createRef("OMPTaskyieldDirective");
  4850. case CXCursor_OMPBarrierDirective:
  4851. return cxstring::createRef("OMPBarrierDirective");
  4852. case CXCursor_OMPTaskwaitDirective:
  4853. return cxstring::createRef("OMPTaskwaitDirective");
  4854. case CXCursor_OMPTaskgroupDirective:
  4855. return cxstring::createRef("OMPTaskgroupDirective");
  4856. case CXCursor_OMPFlushDirective:
  4857. return cxstring::createRef("OMPFlushDirective");
  4858. case CXCursor_OMPDepobjDirective:
  4859. return cxstring::createRef("OMPDepobjDirective");
  4860. case CXCursor_OMPScanDirective:
  4861. return cxstring::createRef("OMPScanDirective");
  4862. case CXCursor_OMPOrderedDirective:
  4863. return cxstring::createRef("OMPOrderedDirective");
  4864. case CXCursor_OMPAtomicDirective:
  4865. return cxstring::createRef("OMPAtomicDirective");
  4866. case CXCursor_OMPTargetDirective:
  4867. return cxstring::createRef("OMPTargetDirective");
  4868. case CXCursor_OMPTargetDataDirective:
  4869. return cxstring::createRef("OMPTargetDataDirective");
  4870. case CXCursor_OMPTargetEnterDataDirective:
  4871. return cxstring::createRef("OMPTargetEnterDataDirective");
  4872. case CXCursor_OMPTargetExitDataDirective:
  4873. return cxstring::createRef("OMPTargetExitDataDirective");
  4874. case CXCursor_OMPTargetParallelDirective:
  4875. return cxstring::createRef("OMPTargetParallelDirective");
  4876. case CXCursor_OMPTargetParallelForDirective:
  4877. return cxstring::createRef("OMPTargetParallelForDirective");
  4878. case CXCursor_OMPTargetUpdateDirective:
  4879. return cxstring::createRef("OMPTargetUpdateDirective");
  4880. case CXCursor_OMPTeamsDirective:
  4881. return cxstring::createRef("OMPTeamsDirective");
  4882. case CXCursor_OMPCancellationPointDirective:
  4883. return cxstring::createRef("OMPCancellationPointDirective");
  4884. case CXCursor_OMPCancelDirective:
  4885. return cxstring::createRef("OMPCancelDirective");
  4886. case CXCursor_OMPTaskLoopDirective:
  4887. return cxstring::createRef("OMPTaskLoopDirective");
  4888. case CXCursor_OMPTaskLoopSimdDirective:
  4889. return cxstring::createRef("OMPTaskLoopSimdDirective");
  4890. case CXCursor_OMPMasterTaskLoopDirective:
  4891. return cxstring::createRef("OMPMasterTaskLoopDirective");
  4892. case CXCursor_OMPMasterTaskLoopSimdDirective:
  4893. return cxstring::createRef("OMPMasterTaskLoopSimdDirective");
  4894. case CXCursor_OMPParallelMasterTaskLoopDirective:
  4895. return cxstring::createRef("OMPParallelMasterTaskLoopDirective");
  4896. case CXCursor_OMPParallelMasterTaskLoopSimdDirective:
  4897. return cxstring::createRef("OMPParallelMasterTaskLoopSimdDirective");
  4898. case CXCursor_OMPDistributeDirective:
  4899. return cxstring::createRef("OMPDistributeDirective");
  4900. case CXCursor_OMPDistributeParallelForDirective:
  4901. return cxstring::createRef("OMPDistributeParallelForDirective");
  4902. case CXCursor_OMPDistributeParallelForSimdDirective:
  4903. return cxstring::createRef("OMPDistributeParallelForSimdDirective");
  4904. case CXCursor_OMPDistributeSimdDirective:
  4905. return cxstring::createRef("OMPDistributeSimdDirective");
  4906. case CXCursor_OMPTargetParallelForSimdDirective:
  4907. return cxstring::createRef("OMPTargetParallelForSimdDirective");
  4908. case CXCursor_OMPTargetSimdDirective:
  4909. return cxstring::createRef("OMPTargetSimdDirective");
  4910. case CXCursor_OMPTeamsDistributeDirective:
  4911. return cxstring::createRef("OMPTeamsDistributeDirective");
  4912. case CXCursor_OMPTeamsDistributeSimdDirective:
  4913. return cxstring::createRef("OMPTeamsDistributeSimdDirective");
  4914. case CXCursor_OMPTeamsDistributeParallelForSimdDirective:
  4915. return cxstring::createRef("OMPTeamsDistributeParallelForSimdDirective");
  4916. case CXCursor_OMPTeamsDistributeParallelForDirective:
  4917. return cxstring::createRef("OMPTeamsDistributeParallelForDirective");
  4918. case CXCursor_OMPTargetTeamsDirective:
  4919. return cxstring::createRef("OMPTargetTeamsDirective");
  4920. case CXCursor_OMPTargetTeamsDistributeDirective:
  4921. return cxstring::createRef("OMPTargetTeamsDistributeDirective");
  4922. case CXCursor_OMPTargetTeamsDistributeParallelForDirective:
  4923. return cxstring::createRef("OMPTargetTeamsDistributeParallelForDirective");
  4924. case CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective:
  4925. return cxstring::createRef(
  4926. "OMPTargetTeamsDistributeParallelForSimdDirective");
  4927. case CXCursor_OMPTargetTeamsDistributeSimdDirective:
  4928. return cxstring::createRef("OMPTargetTeamsDistributeSimdDirective");
  4929. case CXCursor_OMPInteropDirective:
  4930. return cxstring::createRef("OMPInteropDirective");
  4931. case CXCursor_OMPDispatchDirective:
  4932. return cxstring::createRef("OMPDispatchDirective");
  4933. case CXCursor_OMPMaskedDirective:
  4934. return cxstring::createRef("OMPMaskedDirective");
  4935. case CXCursor_OMPGenericLoopDirective:
  4936. return cxstring::createRef("OMPGenericLoopDirective");
  4937. case CXCursor_OverloadCandidate:
  4938. return cxstring::createRef("OverloadCandidate");
  4939. case CXCursor_TypeAliasTemplateDecl:
  4940. return cxstring::createRef("TypeAliasTemplateDecl");
  4941. case CXCursor_StaticAssert:
  4942. return cxstring::createRef("StaticAssert");
  4943. case CXCursor_FriendDecl:
  4944. return cxstring::createRef("FriendDecl");
  4945. case CXCursor_ConvergentAttr:
  4946. return cxstring::createRef("attribute(convergent)");
  4947. case CXCursor_WarnUnusedAttr:
  4948. return cxstring::createRef("attribute(warn_unused)");
  4949. case CXCursor_WarnUnusedResultAttr:
  4950. return cxstring::createRef("attribute(warn_unused_result)");
  4951. case CXCursor_AlignedAttr:
  4952. return cxstring::createRef("attribute(aligned)");
  4953. }
  4954. llvm_unreachable("Unhandled CXCursorKind");
  4955. }
  4956. struct GetCursorData {
  4957. SourceLocation TokenBeginLoc;
  4958. bool PointsAtMacroArgExpansion;
  4959. bool VisitedObjCPropertyImplDecl;
  4960. SourceLocation VisitedDeclaratorDeclStartLoc;
  4961. CXCursor &BestCursor;
  4962. GetCursorData(SourceManager &SM, SourceLocation tokenBegin,
  4963. CXCursor &outputCursor)
  4964. : TokenBeginLoc(tokenBegin), BestCursor(outputCursor) {
  4965. PointsAtMacroArgExpansion = SM.isMacroArgExpansion(tokenBegin);
  4966. VisitedObjCPropertyImplDecl = false;
  4967. }
  4968. };
  4969. static enum CXChildVisitResult
  4970. GetCursorVisitor(CXCursor cursor, CXCursor parent, CXClientData client_data) {
  4971. GetCursorData *Data = static_cast<GetCursorData *>(client_data);
  4972. CXCursor *BestCursor = &Data->BestCursor;
  4973. // If we point inside a macro argument we should provide info of what the
  4974. // token is so use the actual cursor, don't replace it with a macro expansion
  4975. // cursor.
  4976. if (cursor.kind == CXCursor_MacroExpansion && Data->PointsAtMacroArgExpansion)
  4977. return CXChildVisit_Recurse;
  4978. if (clang_isDeclaration(cursor.kind)) {
  4979. // Avoid having the implicit methods override the property decls.
  4980. if (const ObjCMethodDecl *MD =
  4981. dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
  4982. if (MD->isImplicit())
  4983. return CXChildVisit_Break;
  4984. } else if (const ObjCInterfaceDecl *ID =
  4985. dyn_cast_or_null<ObjCInterfaceDecl>(getCursorDecl(cursor))) {
  4986. // Check that when we have multiple @class references in the same line,
  4987. // that later ones do not override the previous ones.
  4988. // If we have:
  4989. // @class Foo, Bar;
  4990. // source ranges for both start at '@', so 'Bar' will end up overriding
  4991. // 'Foo' even though the cursor location was at 'Foo'.
  4992. if (BestCursor->kind == CXCursor_ObjCInterfaceDecl ||
  4993. BestCursor->kind == CXCursor_ObjCClassRef)
  4994. if (const ObjCInterfaceDecl *PrevID =
  4995. dyn_cast_or_null<ObjCInterfaceDecl>(
  4996. getCursorDecl(*BestCursor))) {
  4997. if (PrevID != ID && !PrevID->isThisDeclarationADefinition() &&
  4998. !ID->isThisDeclarationADefinition())
  4999. return CXChildVisit_Break;
  5000. }
  5001. } else if (const DeclaratorDecl *DD =
  5002. dyn_cast_or_null<DeclaratorDecl>(getCursorDecl(cursor))) {
  5003. SourceLocation StartLoc = DD->getSourceRange().getBegin();
  5004. // Check that when we have multiple declarators in the same line,
  5005. // that later ones do not override the previous ones.
  5006. // If we have:
  5007. // int Foo, Bar;
  5008. // source ranges for both start at 'int', so 'Bar' will end up overriding
  5009. // 'Foo' even though the cursor location was at 'Foo'.
  5010. if (Data->VisitedDeclaratorDeclStartLoc == StartLoc)
  5011. return CXChildVisit_Break;
  5012. Data->VisitedDeclaratorDeclStartLoc = StartLoc;
  5013. } else if (const ObjCPropertyImplDecl *PropImp =
  5014. dyn_cast_or_null<ObjCPropertyImplDecl>(
  5015. getCursorDecl(cursor))) {
  5016. (void)PropImp;
  5017. // Check that when we have multiple @synthesize in the same line,
  5018. // that later ones do not override the previous ones.
  5019. // If we have:
  5020. // @synthesize Foo, Bar;
  5021. // source ranges for both start at '@', so 'Bar' will end up overriding
  5022. // 'Foo' even though the cursor location was at 'Foo'.
  5023. if (Data->VisitedObjCPropertyImplDecl)
  5024. return CXChildVisit_Break;
  5025. Data->VisitedObjCPropertyImplDecl = true;
  5026. }
  5027. }
  5028. if (clang_isExpression(cursor.kind) &&
  5029. clang_isDeclaration(BestCursor->kind)) {
  5030. if (const Decl *D = getCursorDecl(*BestCursor)) {
  5031. // Avoid having the cursor of an expression replace the declaration cursor
  5032. // when the expression source range overlaps the declaration range.
  5033. // This can happen for C++ constructor expressions whose range generally
  5034. // include the variable declaration, e.g.:
  5035. // MyCXXClass foo; // Make sure pointing at 'foo' returns a VarDecl
  5036. // cursor.
  5037. if (D->getLocation().isValid() && Data->TokenBeginLoc.isValid() &&
  5038. D->getLocation() == Data->TokenBeginLoc)
  5039. return CXChildVisit_Break;
  5040. }
  5041. }
  5042. // If our current best cursor is the construction of a temporary object,
  5043. // don't replace that cursor with a type reference, because we want
  5044. // clang_getCursor() to point at the constructor.
  5045. if (clang_isExpression(BestCursor->kind) &&
  5046. isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
  5047. cursor.kind == CXCursor_TypeRef) {
  5048. // Keep the cursor pointing at CXXTemporaryObjectExpr but also mark it
  5049. // as having the actual point on the type reference.
  5050. *BestCursor = getTypeRefedCallExprCursor(*BestCursor);
  5051. return CXChildVisit_Recurse;
  5052. }
  5053. // If we already have an Objective-C superclass reference, don't
  5054. // update it further.
  5055. if (BestCursor->kind == CXCursor_ObjCSuperClassRef)
  5056. return CXChildVisit_Break;
  5057. *BestCursor = cursor;
  5058. return CXChildVisit_Recurse;
  5059. }
  5060. CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
  5061. if (isNotUsableTU(TU)) {
  5062. LOG_BAD_TU(TU);
  5063. return clang_getNullCursor();
  5064. }
  5065. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5066. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  5067. SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
  5068. CXCursor Result = cxcursor::getCursor(TU, SLoc);
  5069. LOG_FUNC_SECTION {
  5070. CXFile SearchFile;
  5071. unsigned SearchLine, SearchColumn;
  5072. CXFile ResultFile;
  5073. unsigned ResultLine, ResultColumn;
  5074. CXString SearchFileName, ResultFileName, KindSpelling, USR;
  5075. const char *IsDef = clang_isCursorDefinition(Result) ? " (Definition)" : "";
  5076. CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
  5077. clang_getFileLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
  5078. nullptr);
  5079. clang_getFileLocation(ResultLoc, &ResultFile, &ResultLine, &ResultColumn,
  5080. nullptr);
  5081. SearchFileName = clang_getFileName(SearchFile);
  5082. ResultFileName = clang_getFileName(ResultFile);
  5083. KindSpelling = clang_getCursorKindSpelling(Result.kind);
  5084. USR = clang_getCursorUSR(Result);
  5085. *Log << llvm::format("(%s:%d:%d) = %s", clang_getCString(SearchFileName),
  5086. SearchLine, SearchColumn,
  5087. clang_getCString(KindSpelling))
  5088. << llvm::format("(%s:%d:%d):%s%s", clang_getCString(ResultFileName),
  5089. ResultLine, ResultColumn, clang_getCString(USR),
  5090. IsDef);
  5091. clang_disposeString(SearchFileName);
  5092. clang_disposeString(ResultFileName);
  5093. clang_disposeString(KindSpelling);
  5094. clang_disposeString(USR);
  5095. CXCursor Definition = clang_getCursorDefinition(Result);
  5096. if (!clang_equalCursors(Definition, clang_getNullCursor())) {
  5097. CXSourceLocation DefinitionLoc = clang_getCursorLocation(Definition);
  5098. CXString DefinitionKindSpelling =
  5099. clang_getCursorKindSpelling(Definition.kind);
  5100. CXFile DefinitionFile;
  5101. unsigned DefinitionLine, DefinitionColumn;
  5102. clang_getFileLocation(DefinitionLoc, &DefinitionFile, &DefinitionLine,
  5103. &DefinitionColumn, nullptr);
  5104. CXString DefinitionFileName = clang_getFileName(DefinitionFile);
  5105. *Log << llvm::format(" -> %s(%s:%d:%d)",
  5106. clang_getCString(DefinitionKindSpelling),
  5107. clang_getCString(DefinitionFileName), DefinitionLine,
  5108. DefinitionColumn);
  5109. clang_disposeString(DefinitionFileName);
  5110. clang_disposeString(DefinitionKindSpelling);
  5111. }
  5112. }
  5113. return Result;
  5114. }
  5115. CXCursor clang_getNullCursor(void) {
  5116. return MakeCXCursorInvalid(CXCursor_InvalidFile);
  5117. }
  5118. unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
  5119. // Clear out the "FirstInDeclGroup" part in a declaration cursor, since we
  5120. // can't set consistently. For example, when visiting a DeclStmt we will set
  5121. // it but we don't set it on the result of clang_getCursorDefinition for
  5122. // a reference of the same declaration.
  5123. // FIXME: Setting "FirstInDeclGroup" in CXCursors is a hack that only works
  5124. // when visiting a DeclStmt currently, the AST should be enhanced to be able
  5125. // to provide that kind of info.
  5126. if (clang_isDeclaration(X.kind))
  5127. X.data[1] = nullptr;
  5128. if (clang_isDeclaration(Y.kind))
  5129. Y.data[1] = nullptr;
  5130. return X == Y;
  5131. }
  5132. unsigned clang_hashCursor(CXCursor C) {
  5133. unsigned Index = 0;
  5134. if (clang_isExpression(C.kind) || clang_isStatement(C.kind))
  5135. Index = 1;
  5136. return llvm::DenseMapInfo<std::pair<unsigned, const void *>>::getHashValue(
  5137. std::make_pair(C.kind, C.data[Index]));
  5138. }
  5139. unsigned clang_isInvalid(enum CXCursorKind K) {
  5140. return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
  5141. }
  5142. unsigned clang_isDeclaration(enum CXCursorKind K) {
  5143. return (K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl) ||
  5144. (K >= CXCursor_FirstExtraDecl && K <= CXCursor_LastExtraDecl);
  5145. }
  5146. unsigned clang_isInvalidDeclaration(CXCursor C) {
  5147. if (clang_isDeclaration(C.kind)) {
  5148. if (const Decl *D = getCursorDecl(C))
  5149. return D->isInvalidDecl();
  5150. }
  5151. return 0;
  5152. }
  5153. unsigned clang_isReference(enum CXCursorKind K) {
  5154. return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
  5155. }
  5156. unsigned clang_isExpression(enum CXCursorKind K) {
  5157. return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
  5158. }
  5159. unsigned clang_isStatement(enum CXCursorKind K) {
  5160. return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
  5161. }
  5162. unsigned clang_isAttribute(enum CXCursorKind K) {
  5163. return K >= CXCursor_FirstAttr && K <= CXCursor_LastAttr;
  5164. }
  5165. unsigned clang_isTranslationUnit(enum CXCursorKind K) {
  5166. return K == CXCursor_TranslationUnit;
  5167. }
  5168. unsigned clang_isPreprocessing(enum CXCursorKind K) {
  5169. return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
  5170. }
  5171. unsigned clang_isUnexposed(enum CXCursorKind K) {
  5172. switch (K) {
  5173. case CXCursor_UnexposedDecl:
  5174. case CXCursor_UnexposedExpr:
  5175. case CXCursor_UnexposedStmt:
  5176. case CXCursor_UnexposedAttr:
  5177. return true;
  5178. default:
  5179. return false;
  5180. }
  5181. }
  5182. CXCursorKind clang_getCursorKind(CXCursor C) { return C.kind; }
  5183. CXSourceLocation clang_getCursorLocation(CXCursor C) {
  5184. if (clang_isReference(C.kind)) {
  5185. switch (C.kind) {
  5186. case CXCursor_ObjCSuperClassRef: {
  5187. std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
  5188. getCursorObjCSuperClassRef(C);
  5189. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5190. }
  5191. case CXCursor_ObjCProtocolRef: {
  5192. std::pair<const ObjCProtocolDecl *, SourceLocation> P =
  5193. getCursorObjCProtocolRef(C);
  5194. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5195. }
  5196. case CXCursor_ObjCClassRef: {
  5197. std::pair<const ObjCInterfaceDecl *, SourceLocation> P =
  5198. getCursorObjCClassRef(C);
  5199. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5200. }
  5201. case CXCursor_TypeRef: {
  5202. std::pair<const TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
  5203. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5204. }
  5205. case CXCursor_TemplateRef: {
  5206. std::pair<const TemplateDecl *, SourceLocation> P =
  5207. getCursorTemplateRef(C);
  5208. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5209. }
  5210. case CXCursor_NamespaceRef: {
  5211. std::pair<const NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
  5212. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5213. }
  5214. case CXCursor_MemberRef: {
  5215. std::pair<const FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
  5216. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5217. }
  5218. case CXCursor_VariableRef: {
  5219. std::pair<const VarDecl *, SourceLocation> P = getCursorVariableRef(C);
  5220. return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
  5221. }
  5222. case CXCursor_CXXBaseSpecifier: {
  5223. const CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
  5224. if (!BaseSpec)
  5225. return clang_getNullLocation();
  5226. if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
  5227. return cxloc::translateSourceLocation(
  5228. getCursorContext(C), TSInfo->getTypeLoc().getBeginLoc());
  5229. return cxloc::translateSourceLocation(getCursorContext(C),
  5230. BaseSpec->getBeginLoc());
  5231. }
  5232. case CXCursor_LabelRef: {
  5233. std::pair<const LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
  5234. return cxloc::translateSourceLocation(getCursorContext(C), P.second);
  5235. }
  5236. case CXCursor_OverloadedDeclRef:
  5237. return cxloc::translateSourceLocation(
  5238. getCursorContext(C), getCursorOverloadedDeclRef(C).second);
  5239. default:
  5240. // FIXME: Need a way to enumerate all non-reference cases.
  5241. llvm_unreachable("Missed a reference kind");
  5242. }
  5243. }
  5244. if (clang_isExpression(C.kind))
  5245. return cxloc::translateSourceLocation(
  5246. getCursorContext(C), getLocationFromExpr(getCursorExpr(C)));
  5247. if (clang_isStatement(C.kind))
  5248. return cxloc::translateSourceLocation(getCursorContext(C),
  5249. getCursorStmt(C)->getBeginLoc());
  5250. if (C.kind == CXCursor_PreprocessingDirective) {
  5251. SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
  5252. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5253. }
  5254. if (C.kind == CXCursor_MacroExpansion) {
  5255. SourceLocation L =
  5256. cxcursor::getCursorMacroExpansion(C).getSourceRange().getBegin();
  5257. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5258. }
  5259. if (C.kind == CXCursor_MacroDefinition) {
  5260. SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
  5261. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5262. }
  5263. if (C.kind == CXCursor_InclusionDirective) {
  5264. SourceLocation L =
  5265. cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
  5266. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5267. }
  5268. if (clang_isAttribute(C.kind)) {
  5269. SourceLocation L = cxcursor::getCursorAttr(C)->getLocation();
  5270. return cxloc::translateSourceLocation(getCursorContext(C), L);
  5271. }
  5272. if (!clang_isDeclaration(C.kind))
  5273. return clang_getNullLocation();
  5274. const Decl *D = getCursorDecl(C);
  5275. if (!D)
  5276. return clang_getNullLocation();
  5277. SourceLocation Loc = D->getLocation();
  5278. // FIXME: Multiple variables declared in a single declaration
  5279. // currently lack the information needed to correctly determine their
  5280. // ranges when accounting for the type-specifier. We use context
  5281. // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
  5282. // and if so, whether it is the first decl.
  5283. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  5284. if (!cxcursor::isFirstInDeclGroup(C))
  5285. Loc = VD->getLocation();
  5286. }
  5287. // For ObjC methods, give the start location of the method name.
  5288. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  5289. Loc = MD->getSelectorStartLoc();
  5290. return cxloc::translateSourceLocation(getCursorContext(C), Loc);
  5291. }
  5292. } // end extern "C"
  5293. CXCursor cxcursor::getCursor(CXTranslationUnit TU, SourceLocation SLoc) {
  5294. assert(TU);
  5295. // Guard against an invalid SourceLocation, or we may assert in one
  5296. // of the following calls.
  5297. if (SLoc.isInvalid())
  5298. return clang_getNullCursor();
  5299. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5300. // Translate the given source location to make it point at the beginning of
  5301. // the token under the cursor.
  5302. SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
  5303. CXXUnit->getASTContext().getLangOpts());
  5304. CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
  5305. if (SLoc.isValid()) {
  5306. GetCursorData ResultData(CXXUnit->getSourceManager(), SLoc, Result);
  5307. CursorVisitor CursorVis(TU, GetCursorVisitor, &ResultData,
  5308. /*VisitPreprocessorLast=*/true,
  5309. /*VisitIncludedEntities=*/false,
  5310. SourceLocation(SLoc));
  5311. CursorVis.visitFileRegion();
  5312. }
  5313. return Result;
  5314. }
  5315. static SourceRange getRawCursorExtent(CXCursor C) {
  5316. if (clang_isReference(C.kind)) {
  5317. switch (C.kind) {
  5318. case CXCursor_ObjCSuperClassRef:
  5319. return getCursorObjCSuperClassRef(C).second;
  5320. case CXCursor_ObjCProtocolRef:
  5321. return getCursorObjCProtocolRef(C).second;
  5322. case CXCursor_ObjCClassRef:
  5323. return getCursorObjCClassRef(C).second;
  5324. case CXCursor_TypeRef:
  5325. return getCursorTypeRef(C).second;
  5326. case CXCursor_TemplateRef:
  5327. return getCursorTemplateRef(C).second;
  5328. case CXCursor_NamespaceRef:
  5329. return getCursorNamespaceRef(C).second;
  5330. case CXCursor_MemberRef:
  5331. return getCursorMemberRef(C).second;
  5332. case CXCursor_CXXBaseSpecifier:
  5333. return getCursorCXXBaseSpecifier(C)->getSourceRange();
  5334. case CXCursor_LabelRef:
  5335. return getCursorLabelRef(C).second;
  5336. case CXCursor_OverloadedDeclRef:
  5337. return getCursorOverloadedDeclRef(C).second;
  5338. case CXCursor_VariableRef:
  5339. return getCursorVariableRef(C).second;
  5340. default:
  5341. // FIXME: Need a way to enumerate all non-reference cases.
  5342. llvm_unreachable("Missed a reference kind");
  5343. }
  5344. }
  5345. if (clang_isExpression(C.kind))
  5346. return getCursorExpr(C)->getSourceRange();
  5347. if (clang_isStatement(C.kind))
  5348. return getCursorStmt(C)->getSourceRange();
  5349. if (clang_isAttribute(C.kind))
  5350. return getCursorAttr(C)->getRange();
  5351. if (C.kind == CXCursor_PreprocessingDirective)
  5352. return cxcursor::getCursorPreprocessingDirective(C);
  5353. if (C.kind == CXCursor_MacroExpansion) {
  5354. ASTUnit *TU = getCursorASTUnit(C);
  5355. SourceRange Range = cxcursor::getCursorMacroExpansion(C).getSourceRange();
  5356. return TU->mapRangeFromPreamble(Range);
  5357. }
  5358. if (C.kind == CXCursor_MacroDefinition) {
  5359. ASTUnit *TU = getCursorASTUnit(C);
  5360. SourceRange Range = cxcursor::getCursorMacroDefinition(C)->getSourceRange();
  5361. return TU->mapRangeFromPreamble(Range);
  5362. }
  5363. if (C.kind == CXCursor_InclusionDirective) {
  5364. ASTUnit *TU = getCursorASTUnit(C);
  5365. SourceRange Range =
  5366. cxcursor::getCursorInclusionDirective(C)->getSourceRange();
  5367. return TU->mapRangeFromPreamble(Range);
  5368. }
  5369. if (C.kind == CXCursor_TranslationUnit) {
  5370. ASTUnit *TU = getCursorASTUnit(C);
  5371. FileID MainID = TU->getSourceManager().getMainFileID();
  5372. SourceLocation Start = TU->getSourceManager().getLocForStartOfFile(MainID);
  5373. SourceLocation End = TU->getSourceManager().getLocForEndOfFile(MainID);
  5374. return SourceRange(Start, End);
  5375. }
  5376. if (clang_isDeclaration(C.kind)) {
  5377. const Decl *D = cxcursor::getCursorDecl(C);
  5378. if (!D)
  5379. return SourceRange();
  5380. SourceRange R = D->getSourceRange();
  5381. // FIXME: Multiple variables declared in a single declaration
  5382. // currently lack the information needed to correctly determine their
  5383. // ranges when accounting for the type-specifier. We use context
  5384. // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
  5385. // and if so, whether it is the first decl.
  5386. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  5387. if (!cxcursor::isFirstInDeclGroup(C))
  5388. R.setBegin(VD->getLocation());
  5389. }
  5390. return R;
  5391. }
  5392. return SourceRange();
  5393. }
  5394. /// Retrieves the "raw" cursor extent, which is then extended to include
  5395. /// the decl-specifier-seq for declarations.
  5396. static SourceRange getFullCursorExtent(CXCursor C, SourceManager &SrcMgr) {
  5397. if (clang_isDeclaration(C.kind)) {
  5398. const Decl *D = cxcursor::getCursorDecl(C);
  5399. if (!D)
  5400. return SourceRange();
  5401. SourceRange R = D->getSourceRange();
  5402. // Adjust the start of the location for declarations preceded by
  5403. // declaration specifiers.
  5404. SourceLocation StartLoc;
  5405. if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
  5406. if (TypeSourceInfo *TI = DD->getTypeSourceInfo())
  5407. StartLoc = TI->getTypeLoc().getBeginLoc();
  5408. } else if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(D)) {
  5409. if (TypeSourceInfo *TI = Typedef->getTypeSourceInfo())
  5410. StartLoc = TI->getTypeLoc().getBeginLoc();
  5411. }
  5412. if (StartLoc.isValid() && R.getBegin().isValid() &&
  5413. SrcMgr.isBeforeInTranslationUnit(StartLoc, R.getBegin()))
  5414. R.setBegin(StartLoc);
  5415. // FIXME: Multiple variables declared in a single declaration
  5416. // currently lack the information needed to correctly determine their
  5417. // ranges when accounting for the type-specifier. We use context
  5418. // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
  5419. // and if so, whether it is the first decl.
  5420. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  5421. if (!cxcursor::isFirstInDeclGroup(C))
  5422. R.setBegin(VD->getLocation());
  5423. }
  5424. return R;
  5425. }
  5426. return getRawCursorExtent(C);
  5427. }
  5428. CXSourceRange clang_getCursorExtent(CXCursor C) {
  5429. SourceRange R = getRawCursorExtent(C);
  5430. if (R.isInvalid())
  5431. return clang_getNullRange();
  5432. return cxloc::translateSourceRange(getCursorContext(C), R);
  5433. }
  5434. CXCursor clang_getCursorReferenced(CXCursor C) {
  5435. if (clang_isInvalid(C.kind))
  5436. return clang_getNullCursor();
  5437. CXTranslationUnit tu = getCursorTU(C);
  5438. if (clang_isDeclaration(C.kind)) {
  5439. const Decl *D = getCursorDecl(C);
  5440. if (!D)
  5441. return clang_getNullCursor();
  5442. if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
  5443. return MakeCursorOverloadedDeclRef(Using, D->getLocation(), tu);
  5444. if (const ObjCPropertyImplDecl *PropImpl =
  5445. dyn_cast<ObjCPropertyImplDecl>(D))
  5446. if (ObjCPropertyDecl *Property = PropImpl->getPropertyDecl())
  5447. return MakeCXCursor(Property, tu);
  5448. return C;
  5449. }
  5450. if (clang_isExpression(C.kind)) {
  5451. const Expr *E = getCursorExpr(C);
  5452. const Decl *D = getDeclFromExpr(E);
  5453. if (D) {
  5454. CXCursor declCursor = MakeCXCursor(D, tu);
  5455. declCursor = getSelectorIdentifierCursor(getSelectorIdentifierIndex(C),
  5456. declCursor);
  5457. return declCursor;
  5458. }
  5459. if (const OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
  5460. return MakeCursorOverloadedDeclRef(Ovl, tu);
  5461. return clang_getNullCursor();
  5462. }
  5463. if (clang_isStatement(C.kind)) {
  5464. const Stmt *S = getCursorStmt(C);
  5465. if (const GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
  5466. if (LabelDecl *label = Goto->getLabel())
  5467. if (LabelStmt *labelS = label->getStmt())
  5468. return MakeCXCursor(labelS, getCursorDecl(C), tu);
  5469. return clang_getNullCursor();
  5470. }
  5471. if (C.kind == CXCursor_MacroExpansion) {
  5472. if (const MacroDefinitionRecord *Def =
  5473. getCursorMacroExpansion(C).getDefinition())
  5474. return MakeMacroDefinitionCursor(Def, tu);
  5475. }
  5476. if (!clang_isReference(C.kind))
  5477. return clang_getNullCursor();
  5478. switch (C.kind) {
  5479. case CXCursor_ObjCSuperClassRef:
  5480. return MakeCXCursor(getCursorObjCSuperClassRef(C).first, tu);
  5481. case CXCursor_ObjCProtocolRef: {
  5482. const ObjCProtocolDecl *Prot = getCursorObjCProtocolRef(C).first;
  5483. if (const ObjCProtocolDecl *Def = Prot->getDefinition())
  5484. return MakeCXCursor(Def, tu);
  5485. return MakeCXCursor(Prot, tu);
  5486. }
  5487. case CXCursor_ObjCClassRef: {
  5488. const ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
  5489. if (const ObjCInterfaceDecl *Def = Class->getDefinition())
  5490. return MakeCXCursor(Def, tu);
  5491. return MakeCXCursor(Class, tu);
  5492. }
  5493. case CXCursor_TypeRef:
  5494. return MakeCXCursor(getCursorTypeRef(C).first, tu);
  5495. case CXCursor_TemplateRef:
  5496. return MakeCXCursor(getCursorTemplateRef(C).first, tu);
  5497. case CXCursor_NamespaceRef:
  5498. return MakeCXCursor(getCursorNamespaceRef(C).first, tu);
  5499. case CXCursor_MemberRef:
  5500. return MakeCXCursor(getCursorMemberRef(C).first, tu);
  5501. case CXCursor_CXXBaseSpecifier: {
  5502. const CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
  5503. return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(), tu));
  5504. }
  5505. case CXCursor_LabelRef:
  5506. // FIXME: We end up faking the "parent" declaration here because we
  5507. // don't want to make CXCursor larger.
  5508. return MakeCXCursor(
  5509. getCursorLabelRef(C).first,
  5510. cxtu::getASTUnit(tu)->getASTContext().getTranslationUnitDecl(), tu);
  5511. case CXCursor_OverloadedDeclRef:
  5512. return C;
  5513. case CXCursor_VariableRef:
  5514. return MakeCXCursor(getCursorVariableRef(C).first, tu);
  5515. default:
  5516. // We would prefer to enumerate all non-reference cursor kinds here.
  5517. llvm_unreachable("Unhandled reference cursor kind");
  5518. }
  5519. }
  5520. CXCursor clang_getCursorDefinition(CXCursor C) {
  5521. if (clang_isInvalid(C.kind))
  5522. return clang_getNullCursor();
  5523. CXTranslationUnit TU = getCursorTU(C);
  5524. bool WasReference = false;
  5525. if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
  5526. C = clang_getCursorReferenced(C);
  5527. WasReference = true;
  5528. }
  5529. if (C.kind == CXCursor_MacroExpansion)
  5530. return clang_getCursorReferenced(C);
  5531. if (!clang_isDeclaration(C.kind))
  5532. return clang_getNullCursor();
  5533. const Decl *D = getCursorDecl(C);
  5534. if (!D)
  5535. return clang_getNullCursor();
  5536. switch (D->getKind()) {
  5537. // Declaration kinds that don't really separate the notions of
  5538. // declaration and definition.
  5539. case Decl::Namespace:
  5540. case Decl::Typedef:
  5541. case Decl::TypeAlias:
  5542. case Decl::TypeAliasTemplate:
  5543. case Decl::TemplateTypeParm:
  5544. case Decl::EnumConstant:
  5545. case Decl::Field:
  5546. case Decl::Binding:
  5547. case Decl::MSProperty:
  5548. case Decl::MSGuid:
  5549. case Decl::TemplateParamObject:
  5550. case Decl::IndirectField:
  5551. case Decl::ObjCIvar:
  5552. case Decl::ObjCAtDefsField:
  5553. case Decl::ImplicitParam:
  5554. case Decl::ParmVar:
  5555. case Decl::NonTypeTemplateParm:
  5556. case Decl::TemplateTemplateParm:
  5557. case Decl::ObjCCategoryImpl:
  5558. case Decl::ObjCImplementation:
  5559. case Decl::AccessSpec:
  5560. case Decl::LinkageSpec:
  5561. case Decl::Export:
  5562. case Decl::ObjCPropertyImpl:
  5563. case Decl::FileScopeAsm:
  5564. case Decl::StaticAssert:
  5565. case Decl::Block:
  5566. case Decl::Captured:
  5567. case Decl::OMPCapturedExpr:
  5568. case Decl::Label: // FIXME: Is this right??
  5569. case Decl::ClassScopeFunctionSpecialization:
  5570. case Decl::CXXDeductionGuide:
  5571. case Decl::Import:
  5572. case Decl::OMPThreadPrivate:
  5573. case Decl::OMPAllocate:
  5574. case Decl::OMPDeclareReduction:
  5575. case Decl::OMPDeclareMapper:
  5576. case Decl::OMPRequires:
  5577. case Decl::ObjCTypeParam:
  5578. case Decl::BuiltinTemplate:
  5579. case Decl::PragmaComment:
  5580. case Decl::PragmaDetectMismatch:
  5581. case Decl::UsingPack:
  5582. case Decl::Concept:
  5583. case Decl::LifetimeExtendedTemporary:
  5584. case Decl::RequiresExprBody:
  5585. case Decl::UnresolvedUsingIfExists:
  5586. return C;
  5587. // Declaration kinds that don't make any sense here, but are
  5588. // nonetheless harmless.
  5589. case Decl::Empty:
  5590. case Decl::TranslationUnit:
  5591. case Decl::ExternCContext:
  5592. break;
  5593. // Declaration kinds for which the definition is not resolvable.
  5594. case Decl::UnresolvedUsingTypename:
  5595. case Decl::UnresolvedUsingValue:
  5596. break;
  5597. case Decl::UsingDirective:
  5598. return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
  5599. TU);
  5600. case Decl::NamespaceAlias:
  5601. return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), TU);
  5602. case Decl::Enum:
  5603. case Decl::Record:
  5604. case Decl::CXXRecord:
  5605. case Decl::ClassTemplateSpecialization:
  5606. case Decl::ClassTemplatePartialSpecialization:
  5607. if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
  5608. return MakeCXCursor(Def, TU);
  5609. return clang_getNullCursor();
  5610. case Decl::Function:
  5611. case Decl::CXXMethod:
  5612. case Decl::CXXConstructor:
  5613. case Decl::CXXDestructor:
  5614. case Decl::CXXConversion: {
  5615. const FunctionDecl *Def = nullptr;
  5616. if (cast<FunctionDecl>(D)->getBody(Def))
  5617. return MakeCXCursor(Def, TU);
  5618. return clang_getNullCursor();
  5619. }
  5620. case Decl::Var:
  5621. case Decl::VarTemplateSpecialization:
  5622. case Decl::VarTemplatePartialSpecialization:
  5623. case Decl::Decomposition: {
  5624. // Ask the variable if it has a definition.
  5625. if (const VarDecl *Def = cast<VarDecl>(D)->getDefinition())
  5626. return MakeCXCursor(Def, TU);
  5627. return clang_getNullCursor();
  5628. }
  5629. case Decl::FunctionTemplate: {
  5630. const FunctionDecl *Def = nullptr;
  5631. if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
  5632. return MakeCXCursor(Def->getDescribedFunctionTemplate(), TU);
  5633. return clang_getNullCursor();
  5634. }
  5635. case Decl::ClassTemplate: {
  5636. if (RecordDecl *Def =
  5637. cast<ClassTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
  5638. return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
  5639. TU);
  5640. return clang_getNullCursor();
  5641. }
  5642. case Decl::VarTemplate: {
  5643. if (VarDecl *Def =
  5644. cast<VarTemplateDecl>(D)->getTemplatedDecl()->getDefinition())
  5645. return MakeCXCursor(cast<VarDecl>(Def)->getDescribedVarTemplate(), TU);
  5646. return clang_getNullCursor();
  5647. }
  5648. case Decl::Using:
  5649. case Decl::UsingEnum:
  5650. return MakeCursorOverloadedDeclRef(cast<BaseUsingDecl>(D), D->getLocation(),
  5651. TU);
  5652. case Decl::UsingShadow:
  5653. case Decl::ConstructorUsingShadow:
  5654. return clang_getCursorDefinition(
  5655. MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(), TU));
  5656. case Decl::ObjCMethod: {
  5657. const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
  5658. if (Method->isThisDeclarationADefinition())
  5659. return C;
  5660. // Dig out the method definition in the associated
  5661. // @implementation, if we have it.
  5662. // FIXME: The ASTs should make finding the definition easier.
  5663. if (const ObjCInterfaceDecl *Class =
  5664. dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
  5665. if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
  5666. if (ObjCMethodDecl *Def = ClassImpl->getMethod(
  5667. Method->getSelector(), Method->isInstanceMethod()))
  5668. if (Def->isThisDeclarationADefinition())
  5669. return MakeCXCursor(Def, TU);
  5670. return clang_getNullCursor();
  5671. }
  5672. case Decl::ObjCCategory:
  5673. if (ObjCCategoryImplDecl *Impl =
  5674. cast<ObjCCategoryDecl>(D)->getImplementation())
  5675. return MakeCXCursor(Impl, TU);
  5676. return clang_getNullCursor();
  5677. case Decl::ObjCProtocol:
  5678. if (const ObjCProtocolDecl *Def =
  5679. cast<ObjCProtocolDecl>(D)->getDefinition())
  5680. return MakeCXCursor(Def, TU);
  5681. return clang_getNullCursor();
  5682. case Decl::ObjCInterface: {
  5683. // There are two notions of a "definition" for an Objective-C
  5684. // class: the interface and its implementation. When we resolved a
  5685. // reference to an Objective-C class, produce the @interface as
  5686. // the definition; when we were provided with the interface,
  5687. // produce the @implementation as the definition.
  5688. const ObjCInterfaceDecl *IFace = cast<ObjCInterfaceDecl>(D);
  5689. if (WasReference) {
  5690. if (const ObjCInterfaceDecl *Def = IFace->getDefinition())
  5691. return MakeCXCursor(Def, TU);
  5692. } else if (ObjCImplementationDecl *Impl = IFace->getImplementation())
  5693. return MakeCXCursor(Impl, TU);
  5694. return clang_getNullCursor();
  5695. }
  5696. case Decl::ObjCProperty:
  5697. // FIXME: We don't really know where to find the
  5698. // ObjCPropertyImplDecls that implement this property.
  5699. return clang_getNullCursor();
  5700. case Decl::ObjCCompatibleAlias:
  5701. if (const ObjCInterfaceDecl *Class =
  5702. cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
  5703. if (const ObjCInterfaceDecl *Def = Class->getDefinition())
  5704. return MakeCXCursor(Def, TU);
  5705. return clang_getNullCursor();
  5706. case Decl::Friend:
  5707. if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
  5708. return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
  5709. return clang_getNullCursor();
  5710. case Decl::FriendTemplate:
  5711. if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
  5712. return clang_getCursorDefinition(MakeCXCursor(Friend, TU));
  5713. return clang_getNullCursor();
  5714. }
  5715. return clang_getNullCursor();
  5716. }
  5717. unsigned clang_isCursorDefinition(CXCursor C) {
  5718. if (!clang_isDeclaration(C.kind))
  5719. return 0;
  5720. return clang_getCursorDefinition(C) == C;
  5721. }
  5722. CXCursor clang_getCanonicalCursor(CXCursor C) {
  5723. if (!clang_isDeclaration(C.kind))
  5724. return C;
  5725. if (const Decl *D = getCursorDecl(C)) {
  5726. if (const ObjCCategoryImplDecl *CatImplD =
  5727. dyn_cast<ObjCCategoryImplDecl>(D))
  5728. if (ObjCCategoryDecl *CatD = CatImplD->getCategoryDecl())
  5729. return MakeCXCursor(CatD, getCursorTU(C));
  5730. if (const ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  5731. if (const ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
  5732. return MakeCXCursor(IFD, getCursorTU(C));
  5733. return MakeCXCursor(D->getCanonicalDecl(), getCursorTU(C));
  5734. }
  5735. return C;
  5736. }
  5737. int clang_Cursor_getObjCSelectorIndex(CXCursor cursor) {
  5738. return cxcursor::getSelectorIdentifierIndexAndLoc(cursor).first;
  5739. }
  5740. unsigned clang_getNumOverloadedDecls(CXCursor C) {
  5741. if (C.kind != CXCursor_OverloadedDeclRef)
  5742. return 0;
  5743. OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
  5744. if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
  5745. return E->getNumDecls();
  5746. if (OverloadedTemplateStorage *S =
  5747. Storage.dyn_cast<OverloadedTemplateStorage *>())
  5748. return S->size();
  5749. const Decl *D = Storage.get<const Decl *>();
  5750. if (const UsingDecl *Using = dyn_cast<UsingDecl>(D))
  5751. return Using->shadow_size();
  5752. return 0;
  5753. }
  5754. CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
  5755. if (cursor.kind != CXCursor_OverloadedDeclRef)
  5756. return clang_getNullCursor();
  5757. if (index >= clang_getNumOverloadedDecls(cursor))
  5758. return clang_getNullCursor();
  5759. CXTranslationUnit TU = getCursorTU(cursor);
  5760. OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
  5761. if (const OverloadExpr *E = Storage.dyn_cast<const OverloadExpr *>())
  5762. return MakeCXCursor(E->decls_begin()[index], TU);
  5763. if (OverloadedTemplateStorage *S =
  5764. Storage.dyn_cast<OverloadedTemplateStorage *>())
  5765. return MakeCXCursor(S->begin()[index], TU);
  5766. const Decl *D = Storage.get<const Decl *>();
  5767. if (const UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
  5768. // FIXME: This is, unfortunately, linear time.
  5769. UsingDecl::shadow_iterator Pos = Using->shadow_begin();
  5770. std::advance(Pos, index);
  5771. return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), TU);
  5772. }
  5773. return clang_getNullCursor();
  5774. }
  5775. void clang_getDefinitionSpellingAndExtent(
  5776. CXCursor C, const char **startBuf, const char **endBuf, unsigned *startLine,
  5777. unsigned *startColumn, unsigned *endLine, unsigned *endColumn) {
  5778. assert(getCursorDecl(C) && "CXCursor has null decl");
  5779. const FunctionDecl *FD = dyn_cast<FunctionDecl>(getCursorDecl(C));
  5780. CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
  5781. SourceManager &SM = FD->getASTContext().getSourceManager();
  5782. *startBuf = SM.getCharacterData(Body->getLBracLoc());
  5783. *endBuf = SM.getCharacterData(Body->getRBracLoc());
  5784. *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
  5785. *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
  5786. *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
  5787. *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
  5788. }
  5789. CXSourceRange clang_getCursorReferenceNameRange(CXCursor C, unsigned NameFlags,
  5790. unsigned PieceIndex) {
  5791. RefNamePieces Pieces;
  5792. switch (C.kind) {
  5793. case CXCursor_MemberRefExpr:
  5794. if (const MemberExpr *E = dyn_cast<MemberExpr>(getCursorExpr(C)))
  5795. Pieces = buildPieces(NameFlags, true, E->getMemberNameInfo(),
  5796. E->getQualifierLoc().getSourceRange());
  5797. break;
  5798. case CXCursor_DeclRefExpr:
  5799. if (const DeclRefExpr *E = dyn_cast<DeclRefExpr>(getCursorExpr(C))) {
  5800. SourceRange TemplateArgLoc(E->getLAngleLoc(), E->getRAngleLoc());
  5801. Pieces =
  5802. buildPieces(NameFlags, false, E->getNameInfo(),
  5803. E->getQualifierLoc().getSourceRange(), &TemplateArgLoc);
  5804. }
  5805. break;
  5806. case CXCursor_CallExpr:
  5807. if (const CXXOperatorCallExpr *OCE =
  5808. dyn_cast<CXXOperatorCallExpr>(getCursorExpr(C))) {
  5809. const Expr *Callee = OCE->getCallee();
  5810. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee))
  5811. Callee = ICE->getSubExpr();
  5812. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee))
  5813. Pieces = buildPieces(NameFlags, false, DRE->getNameInfo(),
  5814. DRE->getQualifierLoc().getSourceRange());
  5815. }
  5816. break;
  5817. default:
  5818. break;
  5819. }
  5820. if (Pieces.empty()) {
  5821. if (PieceIndex == 0)
  5822. return clang_getCursorExtent(C);
  5823. } else if (PieceIndex < Pieces.size()) {
  5824. SourceRange R = Pieces[PieceIndex];
  5825. if (R.isValid())
  5826. return cxloc::translateSourceRange(getCursorContext(C), R);
  5827. }
  5828. return clang_getNullRange();
  5829. }
  5830. void clang_enableStackTraces(void) {
  5831. // FIXME: Provide an argv0 here so we can find llvm-symbolizer.
  5832. llvm::sys::PrintStackTraceOnErrorSignal(StringRef());
  5833. }
  5834. void clang_executeOnThread(void (*fn)(void *), void *user_data,
  5835. unsigned stack_size) {
  5836. llvm::thread Thread(stack_size == 0 ? clang::DesiredStackSize
  5837. : llvm::Optional<unsigned>(stack_size),
  5838. fn, user_data);
  5839. Thread.join();
  5840. }
  5841. //===----------------------------------------------------------------------===//
  5842. // Token-based Operations.
  5843. //===----------------------------------------------------------------------===//
  5844. /* CXToken layout:
  5845. * int_data[0]: a CXTokenKind
  5846. * int_data[1]: starting token location
  5847. * int_data[2]: token length
  5848. * int_data[3]: reserved
  5849. * ptr_data: for identifiers and keywords, an IdentifierInfo*.
  5850. * otherwise unused.
  5851. */
  5852. CXTokenKind clang_getTokenKind(CXToken CXTok) {
  5853. return static_cast<CXTokenKind>(CXTok.int_data[0]);
  5854. }
  5855. CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
  5856. switch (clang_getTokenKind(CXTok)) {
  5857. case CXToken_Identifier:
  5858. case CXToken_Keyword:
  5859. // We know we have an IdentifierInfo*, so use that.
  5860. return cxstring::createRef(
  5861. static_cast<IdentifierInfo *>(CXTok.ptr_data)->getNameStart());
  5862. case CXToken_Literal: {
  5863. // We have stashed the starting pointer in the ptr_data field. Use it.
  5864. const char *Text = static_cast<const char *>(CXTok.ptr_data);
  5865. return cxstring::createDup(StringRef(Text, CXTok.int_data[2]));
  5866. }
  5867. case CXToken_Punctuation:
  5868. case CXToken_Comment:
  5869. break;
  5870. }
  5871. if (isNotUsableTU(TU)) {
  5872. LOG_BAD_TU(TU);
  5873. return cxstring::createEmpty();
  5874. }
  5875. // We have to find the starting buffer pointer the hard way, by
  5876. // deconstructing the source location.
  5877. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5878. if (!CXXUnit)
  5879. return cxstring::createEmpty();
  5880. SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
  5881. std::pair<FileID, unsigned> LocInfo =
  5882. CXXUnit->getSourceManager().getDecomposedSpellingLoc(Loc);
  5883. bool Invalid = false;
  5884. StringRef Buffer =
  5885. CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
  5886. if (Invalid)
  5887. return cxstring::createEmpty();
  5888. return cxstring::createDup(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
  5889. }
  5890. CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
  5891. if (isNotUsableTU(TU)) {
  5892. LOG_BAD_TU(TU);
  5893. return clang_getNullLocation();
  5894. }
  5895. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5896. if (!CXXUnit)
  5897. return clang_getNullLocation();
  5898. return cxloc::translateSourceLocation(
  5899. CXXUnit->getASTContext(),
  5900. SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
  5901. }
  5902. CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
  5903. if (isNotUsableTU(TU)) {
  5904. LOG_BAD_TU(TU);
  5905. return clang_getNullRange();
  5906. }
  5907. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5908. if (!CXXUnit)
  5909. return clang_getNullRange();
  5910. return cxloc::translateSourceRange(
  5911. CXXUnit->getASTContext(),
  5912. SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
  5913. }
  5914. static void getTokens(ASTUnit *CXXUnit, SourceRange Range,
  5915. SmallVectorImpl<CXToken> &CXTokens) {
  5916. SourceManager &SourceMgr = CXXUnit->getSourceManager();
  5917. std::pair<FileID, unsigned> BeginLocInfo =
  5918. SourceMgr.getDecomposedSpellingLoc(Range.getBegin());
  5919. std::pair<FileID, unsigned> EndLocInfo =
  5920. SourceMgr.getDecomposedSpellingLoc(Range.getEnd());
  5921. // Cannot tokenize across files.
  5922. if (BeginLocInfo.first != EndLocInfo.first)
  5923. return;
  5924. // Create a lexer
  5925. bool Invalid = false;
  5926. StringRef Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
  5927. if (Invalid)
  5928. return;
  5929. Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
  5930. CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
  5931. Buffer.data() + BeginLocInfo.second, Buffer.end());
  5932. Lex.SetCommentRetentionState(true);
  5933. // Lex tokens until we hit the end of the range.
  5934. const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
  5935. Token Tok;
  5936. bool previousWasAt = false;
  5937. do {
  5938. // Lex the next token
  5939. Lex.LexFromRawLexer(Tok);
  5940. if (Tok.is(tok::eof))
  5941. break;
  5942. // Initialize the CXToken.
  5943. CXToken CXTok;
  5944. // - Common fields
  5945. CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
  5946. CXTok.int_data[2] = Tok.getLength();
  5947. CXTok.int_data[3] = 0;
  5948. // - Kind-specific fields
  5949. if (Tok.isLiteral()) {
  5950. CXTok.int_data[0] = CXToken_Literal;
  5951. CXTok.ptr_data = const_cast<char *>(Tok.getLiteralData());
  5952. } else if (Tok.is(tok::raw_identifier)) {
  5953. // Lookup the identifier to determine whether we have a keyword.
  5954. IdentifierInfo *II = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok);
  5955. if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
  5956. CXTok.int_data[0] = CXToken_Keyword;
  5957. } else {
  5958. CXTok.int_data[0] =
  5959. Tok.is(tok::identifier) ? CXToken_Identifier : CXToken_Keyword;
  5960. }
  5961. CXTok.ptr_data = II;
  5962. } else if (Tok.is(tok::comment)) {
  5963. CXTok.int_data[0] = CXToken_Comment;
  5964. CXTok.ptr_data = nullptr;
  5965. } else {
  5966. CXTok.int_data[0] = CXToken_Punctuation;
  5967. CXTok.ptr_data = nullptr;
  5968. }
  5969. CXTokens.push_back(CXTok);
  5970. previousWasAt = Tok.is(tok::at);
  5971. } while (Lex.getBufferLocation() < EffectiveBufferEnd);
  5972. }
  5973. CXToken *clang_getToken(CXTranslationUnit TU, CXSourceLocation Location) {
  5974. LOG_FUNC_SECTION { *Log << TU << ' ' << Location; }
  5975. if (isNotUsableTU(TU)) {
  5976. LOG_BAD_TU(TU);
  5977. return nullptr;
  5978. }
  5979. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  5980. if (!CXXUnit)
  5981. return nullptr;
  5982. SourceLocation Begin = cxloc::translateSourceLocation(Location);
  5983. if (Begin.isInvalid())
  5984. return nullptr;
  5985. SourceManager &SM = CXXUnit->getSourceManager();
  5986. std::pair<FileID, unsigned> DecomposedEnd = SM.getDecomposedLoc(Begin);
  5987. DecomposedEnd.second +=
  5988. Lexer::MeasureTokenLength(Begin, SM, CXXUnit->getLangOpts());
  5989. SourceLocation End =
  5990. SM.getComposedLoc(DecomposedEnd.first, DecomposedEnd.second);
  5991. SmallVector<CXToken, 32> CXTokens;
  5992. getTokens(CXXUnit, SourceRange(Begin, End), CXTokens);
  5993. if (CXTokens.empty())
  5994. return nullptr;
  5995. CXTokens.resize(1);
  5996. CXToken *Token = static_cast<CXToken *>(llvm::safe_malloc(sizeof(CXToken)));
  5997. memmove(Token, CXTokens.data(), sizeof(CXToken));
  5998. return Token;
  5999. }
  6000. void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, CXToken **Tokens,
  6001. unsigned *NumTokens) {
  6002. LOG_FUNC_SECTION { *Log << TU << ' ' << Range; }
  6003. if (Tokens)
  6004. *Tokens = nullptr;
  6005. if (NumTokens)
  6006. *NumTokens = 0;
  6007. if (isNotUsableTU(TU)) {
  6008. LOG_BAD_TU(TU);
  6009. return;
  6010. }
  6011. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6012. if (!CXXUnit || !Tokens || !NumTokens)
  6013. return;
  6014. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  6015. SourceRange R = cxloc::translateCXSourceRange(Range);
  6016. if (R.isInvalid())
  6017. return;
  6018. SmallVector<CXToken, 32> CXTokens;
  6019. getTokens(CXXUnit, R, CXTokens);
  6020. if (CXTokens.empty())
  6021. return;
  6022. *Tokens = static_cast<CXToken *>(
  6023. llvm::safe_malloc(sizeof(CXToken) * CXTokens.size()));
  6024. memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
  6025. *NumTokens = CXTokens.size();
  6026. }
  6027. void clang_disposeTokens(CXTranslationUnit TU, CXToken *Tokens,
  6028. unsigned NumTokens) {
  6029. free(Tokens);
  6030. }
  6031. //===----------------------------------------------------------------------===//
  6032. // Token annotation APIs.
  6033. //===----------------------------------------------------------------------===//
  6034. static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
  6035. CXCursor parent,
  6036. CXClientData client_data);
  6037. static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
  6038. CXClientData client_data);
  6039. namespace {
  6040. class AnnotateTokensWorker {
  6041. CXToken *Tokens;
  6042. CXCursor *Cursors;
  6043. unsigned NumTokens;
  6044. unsigned TokIdx;
  6045. unsigned PreprocessingTokIdx;
  6046. CursorVisitor AnnotateVis;
  6047. SourceManager &SrcMgr;
  6048. bool HasContextSensitiveKeywords;
  6049. struct PostChildrenAction {
  6050. CXCursor cursor;
  6051. enum Action { Invalid, Ignore, Postpone } action;
  6052. };
  6053. using PostChildrenActions = SmallVector<PostChildrenAction, 0>;
  6054. struct PostChildrenInfo {
  6055. CXCursor Cursor;
  6056. SourceRange CursorRange;
  6057. unsigned BeforeReachingCursorIdx;
  6058. unsigned BeforeChildrenTokenIdx;
  6059. PostChildrenActions ChildActions;
  6060. };
  6061. SmallVector<PostChildrenInfo, 8> PostChildrenInfos;
  6062. CXToken &getTok(unsigned Idx) {
  6063. assert(Idx < NumTokens);
  6064. return Tokens[Idx];
  6065. }
  6066. const CXToken &getTok(unsigned Idx) const {
  6067. assert(Idx < NumTokens);
  6068. return Tokens[Idx];
  6069. }
  6070. bool MoreTokens() const { return TokIdx < NumTokens; }
  6071. unsigned NextToken() const { return TokIdx; }
  6072. void AdvanceToken() { ++TokIdx; }
  6073. SourceLocation GetTokenLoc(unsigned tokI) {
  6074. return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
  6075. }
  6076. bool isFunctionMacroToken(unsigned tokI) const {
  6077. return getTok(tokI).int_data[3] != 0;
  6078. }
  6079. SourceLocation getFunctionMacroTokenLoc(unsigned tokI) const {
  6080. return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[3]);
  6081. }
  6082. void annotateAndAdvanceTokens(CXCursor, RangeComparisonResult, SourceRange);
  6083. bool annotateAndAdvanceFunctionMacroTokens(CXCursor, RangeComparisonResult,
  6084. SourceRange);
  6085. public:
  6086. AnnotateTokensWorker(CXToken *tokens, CXCursor *cursors, unsigned numTokens,
  6087. CXTranslationUnit TU, SourceRange RegionOfInterest)
  6088. : Tokens(tokens), Cursors(cursors), NumTokens(numTokens), TokIdx(0),
  6089. PreprocessingTokIdx(0),
  6090. AnnotateVis(TU, AnnotateTokensVisitor, this,
  6091. /*VisitPreprocessorLast=*/true,
  6092. /*VisitIncludedEntities=*/false, RegionOfInterest,
  6093. /*VisitDeclsOnly=*/false,
  6094. AnnotateTokensPostChildrenVisitor),
  6095. SrcMgr(cxtu::getASTUnit(TU)->getSourceManager()),
  6096. HasContextSensitiveKeywords(false) {}
  6097. void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
  6098. enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
  6099. bool IsIgnoredChildCursor(CXCursor cursor) const;
  6100. PostChildrenActions DetermineChildActions(CXCursor Cursor) const;
  6101. bool postVisitChildren(CXCursor cursor);
  6102. void HandlePostPonedChildCursors(const PostChildrenInfo &Info);
  6103. void HandlePostPonedChildCursor(CXCursor Cursor, unsigned StartTokenIndex);
  6104. void AnnotateTokens();
  6105. /// Determine whether the annotator saw any cursors that have
  6106. /// context-sensitive keywords.
  6107. bool hasContextSensitiveKeywords() const {
  6108. return HasContextSensitiveKeywords;
  6109. }
  6110. ~AnnotateTokensWorker() { assert(PostChildrenInfos.empty()); }
  6111. };
  6112. } // namespace
  6113. void AnnotateTokensWorker::AnnotateTokens() {
  6114. // Walk the AST within the region of interest, annotating tokens
  6115. // along the way.
  6116. AnnotateVis.visitFileRegion();
  6117. }
  6118. bool AnnotateTokensWorker::IsIgnoredChildCursor(CXCursor cursor) const {
  6119. if (PostChildrenInfos.empty())
  6120. return false;
  6121. for (const auto &ChildAction : PostChildrenInfos.back().ChildActions) {
  6122. if (ChildAction.cursor == cursor &&
  6123. ChildAction.action == PostChildrenAction::Ignore) {
  6124. return true;
  6125. }
  6126. }
  6127. return false;
  6128. }
  6129. const CXXOperatorCallExpr *GetSubscriptOrCallOperator(CXCursor Cursor) {
  6130. if (!clang_isExpression(Cursor.kind))
  6131. return nullptr;
  6132. const Expr *E = getCursorExpr(Cursor);
  6133. if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  6134. const OverloadedOperatorKind Kind = OCE->getOperator();
  6135. if (Kind == OO_Call || Kind == OO_Subscript)
  6136. return OCE;
  6137. }
  6138. return nullptr;
  6139. }
  6140. AnnotateTokensWorker::PostChildrenActions
  6141. AnnotateTokensWorker::DetermineChildActions(CXCursor Cursor) const {
  6142. PostChildrenActions actions;
  6143. // The DeclRefExpr of CXXOperatorCallExpr refering to the custom operator is
  6144. // visited before the arguments to the operator call. For the Call and
  6145. // Subscript operator the range of this DeclRefExpr includes the whole call
  6146. // expression, so that all tokens in that range would be mapped to the
  6147. // operator function, including the tokens of the arguments. To avoid that,
  6148. // ensure to visit this DeclRefExpr as last node.
  6149. if (const auto *OCE = GetSubscriptOrCallOperator(Cursor)) {
  6150. const Expr *Callee = OCE->getCallee();
  6151. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Callee)) {
  6152. const Expr *SubExpr = ICE->getSubExpr();
  6153. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
  6154. const Decl *parentDecl = getCursorDecl(Cursor);
  6155. CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
  6156. // Visit the DeclRefExpr as last.
  6157. CXCursor cxChild = MakeCXCursor(DRE, parentDecl, TU);
  6158. actions.push_back({cxChild, PostChildrenAction::Postpone});
  6159. // The parent of the DeclRefExpr, an ImplicitCastExpr, has an equally
  6160. // wide range as the DeclRefExpr. We can skip visiting this entirely.
  6161. cxChild = MakeCXCursor(ICE, parentDecl, TU);
  6162. actions.push_back({cxChild, PostChildrenAction::Ignore});
  6163. }
  6164. }
  6165. }
  6166. return actions;
  6167. }
  6168. static inline void updateCursorAnnotation(CXCursor &Cursor,
  6169. const CXCursor &updateC) {
  6170. if (clang_isInvalid(updateC.kind) || !clang_isInvalid(Cursor.kind))
  6171. return;
  6172. Cursor = updateC;
  6173. }
  6174. /// It annotates and advances tokens with a cursor until the comparison
  6175. //// between the cursor location and the source range is the same as
  6176. /// \arg compResult.
  6177. ///
  6178. /// Pass RangeBefore to annotate tokens with a cursor until a range is reached.
  6179. /// Pass RangeOverlap to annotate tokens inside a range.
  6180. void AnnotateTokensWorker::annotateAndAdvanceTokens(
  6181. CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
  6182. while (MoreTokens()) {
  6183. const unsigned I = NextToken();
  6184. if (isFunctionMacroToken(I))
  6185. if (!annotateAndAdvanceFunctionMacroTokens(updateC, compResult, range))
  6186. return;
  6187. SourceLocation TokLoc = GetTokenLoc(I);
  6188. if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
  6189. updateCursorAnnotation(Cursors[I], updateC);
  6190. AdvanceToken();
  6191. continue;
  6192. }
  6193. break;
  6194. }
  6195. }
  6196. /// Special annotation handling for macro argument tokens.
  6197. /// \returns true if it advanced beyond all macro tokens, false otherwise.
  6198. bool AnnotateTokensWorker::annotateAndAdvanceFunctionMacroTokens(
  6199. CXCursor updateC, RangeComparisonResult compResult, SourceRange range) {
  6200. assert(MoreTokens());
  6201. assert(isFunctionMacroToken(NextToken()) &&
  6202. "Should be called only for macro arg tokens");
  6203. // This works differently than annotateAndAdvanceTokens; because expanded
  6204. // macro arguments can have arbitrary translation-unit source order, we do not
  6205. // advance the token index one by one until a token fails the range test.
  6206. // We only advance once past all of the macro arg tokens if all of them
  6207. // pass the range test. If one of them fails we keep the token index pointing
  6208. // at the start of the macro arg tokens so that the failing token will be
  6209. // annotated by a subsequent annotation try.
  6210. bool atLeastOneCompFail = false;
  6211. unsigned I = NextToken();
  6212. for (; I < NumTokens && isFunctionMacroToken(I); ++I) {
  6213. SourceLocation TokLoc = getFunctionMacroTokenLoc(I);
  6214. if (TokLoc.isFileID())
  6215. continue; // not macro arg token, it's parens or comma.
  6216. if (LocationCompare(SrcMgr, TokLoc, range) == compResult) {
  6217. if (clang_isInvalid(clang_getCursorKind(Cursors[I])))
  6218. Cursors[I] = updateC;
  6219. } else
  6220. atLeastOneCompFail = true;
  6221. }
  6222. if (atLeastOneCompFail)
  6223. return false;
  6224. TokIdx = I; // All of the tokens were handled, advance beyond all of them.
  6225. return true;
  6226. }
  6227. enum CXChildVisitResult AnnotateTokensWorker::Visit(CXCursor cursor,
  6228. CXCursor parent) {
  6229. SourceRange cursorRange = getRawCursorExtent(cursor);
  6230. if (cursorRange.isInvalid())
  6231. return CXChildVisit_Recurse;
  6232. if (IsIgnoredChildCursor(cursor))
  6233. return CXChildVisit_Continue;
  6234. if (!HasContextSensitiveKeywords) {
  6235. // Objective-C properties can have context-sensitive keywords.
  6236. if (cursor.kind == CXCursor_ObjCPropertyDecl) {
  6237. if (const ObjCPropertyDecl *Property =
  6238. dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(cursor)))
  6239. HasContextSensitiveKeywords =
  6240. Property->getPropertyAttributesAsWritten() != 0;
  6241. }
  6242. // Objective-C methods can have context-sensitive keywords.
  6243. else if (cursor.kind == CXCursor_ObjCInstanceMethodDecl ||
  6244. cursor.kind == CXCursor_ObjCClassMethodDecl) {
  6245. if (const ObjCMethodDecl *Method =
  6246. dyn_cast_or_null<ObjCMethodDecl>(getCursorDecl(cursor))) {
  6247. if (Method->getObjCDeclQualifier())
  6248. HasContextSensitiveKeywords = true;
  6249. else {
  6250. for (const auto *P : Method->parameters()) {
  6251. if (P->getObjCDeclQualifier()) {
  6252. HasContextSensitiveKeywords = true;
  6253. break;
  6254. }
  6255. }
  6256. }
  6257. }
  6258. }
  6259. // C++ methods can have context-sensitive keywords.
  6260. else if (cursor.kind == CXCursor_CXXMethod) {
  6261. if (const CXXMethodDecl *Method =
  6262. dyn_cast_or_null<CXXMethodDecl>(getCursorDecl(cursor))) {
  6263. if (Method->hasAttr<FinalAttr>() || Method->hasAttr<OverrideAttr>())
  6264. HasContextSensitiveKeywords = true;
  6265. }
  6266. }
  6267. // C++ classes can have context-sensitive keywords.
  6268. else if (cursor.kind == CXCursor_StructDecl ||
  6269. cursor.kind == CXCursor_ClassDecl ||
  6270. cursor.kind == CXCursor_ClassTemplate ||
  6271. cursor.kind == CXCursor_ClassTemplatePartialSpecialization) {
  6272. if (const Decl *D = getCursorDecl(cursor))
  6273. if (D->hasAttr<FinalAttr>())
  6274. HasContextSensitiveKeywords = true;
  6275. }
  6276. }
  6277. // Don't override a property annotation with its getter/setter method.
  6278. if (cursor.kind == CXCursor_ObjCInstanceMethodDecl &&
  6279. parent.kind == CXCursor_ObjCPropertyDecl)
  6280. return CXChildVisit_Continue;
  6281. if (clang_isPreprocessing(cursor.kind)) {
  6282. // Items in the preprocessing record are kept separate from items in
  6283. // declarations, so we keep a separate token index.
  6284. unsigned SavedTokIdx = TokIdx;
  6285. TokIdx = PreprocessingTokIdx;
  6286. // Skip tokens up until we catch up to the beginning of the preprocessing
  6287. // entry.
  6288. while (MoreTokens()) {
  6289. const unsigned I = NextToken();
  6290. SourceLocation TokLoc = GetTokenLoc(I);
  6291. switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
  6292. case RangeBefore:
  6293. AdvanceToken();
  6294. continue;
  6295. case RangeAfter:
  6296. case RangeOverlap:
  6297. break;
  6298. }
  6299. break;
  6300. }
  6301. // Look at all of the tokens within this range.
  6302. while (MoreTokens()) {
  6303. const unsigned I = NextToken();
  6304. SourceLocation TokLoc = GetTokenLoc(I);
  6305. switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
  6306. case RangeBefore:
  6307. llvm_unreachable("Infeasible");
  6308. case RangeAfter:
  6309. break;
  6310. case RangeOverlap:
  6311. // For macro expansions, just note where the beginning of the macro
  6312. // expansion occurs.
  6313. if (cursor.kind == CXCursor_MacroExpansion) {
  6314. if (TokLoc == cursorRange.getBegin())
  6315. Cursors[I] = cursor;
  6316. AdvanceToken();
  6317. break;
  6318. }
  6319. // We may have already annotated macro names inside macro definitions.
  6320. if (Cursors[I].kind != CXCursor_MacroExpansion)
  6321. Cursors[I] = cursor;
  6322. AdvanceToken();
  6323. continue;
  6324. }
  6325. break;
  6326. }
  6327. // Save the preprocessing token index; restore the non-preprocessing
  6328. // token index.
  6329. PreprocessingTokIdx = TokIdx;
  6330. TokIdx = SavedTokIdx;
  6331. return CXChildVisit_Recurse;
  6332. }
  6333. if (cursorRange.isInvalid())
  6334. return CXChildVisit_Continue;
  6335. unsigned BeforeReachingCursorIdx = NextToken();
  6336. const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
  6337. const enum CXCursorKind K = clang_getCursorKind(parent);
  6338. const CXCursor updateC =
  6339. (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
  6340. // Attributes are annotated out-of-order, skip tokens until we reach it.
  6341. clang_isAttribute(cursor.kind))
  6342. ? clang_getNullCursor()
  6343. : parent;
  6344. annotateAndAdvanceTokens(updateC, RangeBefore, cursorRange);
  6345. // Avoid having the cursor of an expression "overwrite" the annotation of the
  6346. // variable declaration that it belongs to.
  6347. // This can happen for C++ constructor expressions whose range generally
  6348. // include the variable declaration, e.g.:
  6349. // MyCXXClass foo; // Make sure we don't annotate 'foo' as a CallExpr cursor.
  6350. if (clang_isExpression(cursorK) && MoreTokens()) {
  6351. const Expr *E = getCursorExpr(cursor);
  6352. if (const Decl *D = getCursorDecl(cursor)) {
  6353. const unsigned I = NextToken();
  6354. if (E->getBeginLoc().isValid() && D->getLocation().isValid() &&
  6355. E->getBeginLoc() == D->getLocation() &&
  6356. E->getBeginLoc() == GetTokenLoc(I)) {
  6357. updateCursorAnnotation(Cursors[I], updateC);
  6358. AdvanceToken();
  6359. }
  6360. }
  6361. }
  6362. // Before recursing into the children keep some state that we are going
  6363. // to use in the AnnotateTokensWorker::postVisitChildren callback to do some
  6364. // extra work after the child nodes are visited.
  6365. // Note that we don't call VisitChildren here to avoid traversing statements
  6366. // code-recursively which can blow the stack.
  6367. PostChildrenInfo Info;
  6368. Info.Cursor = cursor;
  6369. Info.CursorRange = cursorRange;
  6370. Info.BeforeReachingCursorIdx = BeforeReachingCursorIdx;
  6371. Info.BeforeChildrenTokenIdx = NextToken();
  6372. Info.ChildActions = DetermineChildActions(cursor);
  6373. PostChildrenInfos.push_back(Info);
  6374. return CXChildVisit_Recurse;
  6375. }
  6376. bool AnnotateTokensWorker::postVisitChildren(CXCursor cursor) {
  6377. if (PostChildrenInfos.empty())
  6378. return false;
  6379. const PostChildrenInfo &Info = PostChildrenInfos.back();
  6380. if (!clang_equalCursors(Info.Cursor, cursor))
  6381. return false;
  6382. HandlePostPonedChildCursors(Info);
  6383. const unsigned BeforeChildren = Info.BeforeChildrenTokenIdx;
  6384. const unsigned AfterChildren = NextToken();
  6385. SourceRange cursorRange = Info.CursorRange;
  6386. // Scan the tokens that are at the end of the cursor, but are not captured
  6387. // but the child cursors.
  6388. annotateAndAdvanceTokens(cursor, RangeOverlap, cursorRange);
  6389. // Scan the tokens that are at the beginning of the cursor, but are not
  6390. // capture by the child cursors.
  6391. for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
  6392. if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
  6393. break;
  6394. Cursors[I] = cursor;
  6395. }
  6396. // Attributes are annotated out-of-order, rewind TokIdx to when we first
  6397. // encountered the attribute cursor.
  6398. if (clang_isAttribute(cursor.kind))
  6399. TokIdx = Info.BeforeReachingCursorIdx;
  6400. PostChildrenInfos.pop_back();
  6401. return false;
  6402. }
  6403. void AnnotateTokensWorker::HandlePostPonedChildCursors(
  6404. const PostChildrenInfo &Info) {
  6405. for (const auto &ChildAction : Info.ChildActions) {
  6406. if (ChildAction.action == PostChildrenAction::Postpone) {
  6407. HandlePostPonedChildCursor(ChildAction.cursor,
  6408. Info.BeforeChildrenTokenIdx);
  6409. }
  6410. }
  6411. }
  6412. void AnnotateTokensWorker::HandlePostPonedChildCursor(
  6413. CXCursor Cursor, unsigned StartTokenIndex) {
  6414. unsigned I = StartTokenIndex;
  6415. // The bracket tokens of a Call or Subscript operator are mapped to
  6416. // CallExpr/CXXOperatorCallExpr because we skipped visiting the corresponding
  6417. // DeclRefExpr. Remap these tokens to the DeclRefExpr cursors.
  6418. for (unsigned RefNameRangeNr = 0; I < NumTokens; RefNameRangeNr++) {
  6419. const CXSourceRange CXRefNameRange = clang_getCursorReferenceNameRange(
  6420. Cursor, CXNameRange_WantQualifier, RefNameRangeNr);
  6421. if (clang_Range_isNull(CXRefNameRange))
  6422. break; // All ranges handled.
  6423. SourceRange RefNameRange = cxloc::translateCXSourceRange(CXRefNameRange);
  6424. while (I < NumTokens) {
  6425. const SourceLocation TokenLocation = GetTokenLoc(I);
  6426. if (!TokenLocation.isValid())
  6427. break;
  6428. // Adapt the end range, because LocationCompare() reports
  6429. // RangeOverlap even for the not-inclusive end location.
  6430. const SourceLocation fixedEnd =
  6431. RefNameRange.getEnd().getLocWithOffset(-1);
  6432. RefNameRange = SourceRange(RefNameRange.getBegin(), fixedEnd);
  6433. const RangeComparisonResult ComparisonResult =
  6434. LocationCompare(SrcMgr, TokenLocation, RefNameRange);
  6435. if (ComparisonResult == RangeOverlap) {
  6436. Cursors[I++] = Cursor;
  6437. } else if (ComparisonResult == RangeBefore) {
  6438. ++I; // Not relevant token, check next one.
  6439. } else if (ComparisonResult == RangeAfter) {
  6440. break; // All tokens updated for current range, check next.
  6441. }
  6442. }
  6443. }
  6444. }
  6445. static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
  6446. CXCursor parent,
  6447. CXClientData client_data) {
  6448. return static_cast<AnnotateTokensWorker *>(client_data)
  6449. ->Visit(cursor, parent);
  6450. }
  6451. static bool AnnotateTokensPostChildrenVisitor(CXCursor cursor,
  6452. CXClientData client_data) {
  6453. return static_cast<AnnotateTokensWorker *>(client_data)
  6454. ->postVisitChildren(cursor);
  6455. }
  6456. namespace {
  6457. /// Uses the macro expansions in the preprocessing record to find
  6458. /// and mark tokens that are macro arguments. This info is used by the
  6459. /// AnnotateTokensWorker.
  6460. class MarkMacroArgTokensVisitor {
  6461. SourceManager &SM;
  6462. CXToken *Tokens;
  6463. unsigned NumTokens;
  6464. unsigned CurIdx;
  6465. public:
  6466. MarkMacroArgTokensVisitor(SourceManager &SM, CXToken *tokens,
  6467. unsigned numTokens)
  6468. : SM(SM), Tokens(tokens), NumTokens(numTokens), CurIdx(0) {}
  6469. CXChildVisitResult visit(CXCursor cursor, CXCursor parent) {
  6470. if (cursor.kind != CXCursor_MacroExpansion)
  6471. return CXChildVisit_Continue;
  6472. SourceRange macroRange = getCursorMacroExpansion(cursor).getSourceRange();
  6473. if (macroRange.getBegin() == macroRange.getEnd())
  6474. return CXChildVisit_Continue; // it's not a function macro.
  6475. for (; CurIdx < NumTokens; ++CurIdx) {
  6476. if (!SM.isBeforeInTranslationUnit(getTokenLoc(CurIdx),
  6477. macroRange.getBegin()))
  6478. break;
  6479. }
  6480. if (CurIdx == NumTokens)
  6481. return CXChildVisit_Break;
  6482. for (; CurIdx < NumTokens; ++CurIdx) {
  6483. SourceLocation tokLoc = getTokenLoc(CurIdx);
  6484. if (!SM.isBeforeInTranslationUnit(tokLoc, macroRange.getEnd()))
  6485. break;
  6486. setFunctionMacroTokenLoc(CurIdx, SM.getMacroArgExpandedLocation(tokLoc));
  6487. }
  6488. if (CurIdx == NumTokens)
  6489. return CXChildVisit_Break;
  6490. return CXChildVisit_Continue;
  6491. }
  6492. private:
  6493. CXToken &getTok(unsigned Idx) {
  6494. assert(Idx < NumTokens);
  6495. return Tokens[Idx];
  6496. }
  6497. const CXToken &getTok(unsigned Idx) const {
  6498. assert(Idx < NumTokens);
  6499. return Tokens[Idx];
  6500. }
  6501. SourceLocation getTokenLoc(unsigned tokI) {
  6502. return SourceLocation::getFromRawEncoding(getTok(tokI).int_data[1]);
  6503. }
  6504. void setFunctionMacroTokenLoc(unsigned tokI, SourceLocation loc) {
  6505. // The third field is reserved and currently not used. Use it here
  6506. // to mark macro arg expanded tokens with their expanded locations.
  6507. getTok(tokI).int_data[3] = loc.getRawEncoding();
  6508. }
  6509. };
  6510. } // end anonymous namespace
  6511. static CXChildVisitResult
  6512. MarkMacroArgTokensVisitorDelegate(CXCursor cursor, CXCursor parent,
  6513. CXClientData client_data) {
  6514. return static_cast<MarkMacroArgTokensVisitor *>(client_data)
  6515. ->visit(cursor, parent);
  6516. }
  6517. /// Used by \c annotatePreprocessorTokens.
  6518. /// \returns true if lexing was finished, false otherwise.
  6519. static bool lexNext(Lexer &Lex, Token &Tok, unsigned &NextIdx,
  6520. unsigned NumTokens) {
  6521. if (NextIdx >= NumTokens)
  6522. return true;
  6523. ++NextIdx;
  6524. Lex.LexFromRawLexer(Tok);
  6525. return Tok.is(tok::eof);
  6526. }
  6527. static void annotatePreprocessorTokens(CXTranslationUnit TU,
  6528. SourceRange RegionOfInterest,
  6529. CXCursor *Cursors, CXToken *Tokens,
  6530. unsigned NumTokens) {
  6531. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6532. Preprocessor &PP = CXXUnit->getPreprocessor();
  6533. SourceManager &SourceMgr = CXXUnit->getSourceManager();
  6534. std::pair<FileID, unsigned> BeginLocInfo =
  6535. SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getBegin());
  6536. std::pair<FileID, unsigned> EndLocInfo =
  6537. SourceMgr.getDecomposedSpellingLoc(RegionOfInterest.getEnd());
  6538. if (BeginLocInfo.first != EndLocInfo.first)
  6539. return;
  6540. StringRef Buffer;
  6541. bool Invalid = false;
  6542. Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
  6543. if (Buffer.empty() || Invalid)
  6544. return;
  6545. Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
  6546. CXXUnit->getASTContext().getLangOpts(), Buffer.begin(),
  6547. Buffer.data() + BeginLocInfo.second, Buffer.end());
  6548. Lex.SetCommentRetentionState(true);
  6549. unsigned NextIdx = 0;
  6550. // Lex tokens in raw mode until we hit the end of the range, to avoid
  6551. // entering #includes or expanding macros.
  6552. while (true) {
  6553. Token Tok;
  6554. if (lexNext(Lex, Tok, NextIdx, NumTokens))
  6555. break;
  6556. unsigned TokIdx = NextIdx - 1;
  6557. assert(Tok.getLocation() ==
  6558. SourceLocation::getFromRawEncoding(Tokens[TokIdx].int_data[1]));
  6559. reprocess:
  6560. if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
  6561. // We have found a preprocessing directive. Annotate the tokens
  6562. // appropriately.
  6563. //
  6564. // FIXME: Some simple tests here could identify macro definitions and
  6565. // #undefs, to provide specific cursor kinds for those.
  6566. SourceLocation BeginLoc = Tok.getLocation();
  6567. if (lexNext(Lex, Tok, NextIdx, NumTokens))
  6568. break;
  6569. MacroInfo *MI = nullptr;
  6570. if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "define") {
  6571. if (lexNext(Lex, Tok, NextIdx, NumTokens))
  6572. break;
  6573. if (Tok.is(tok::raw_identifier)) {
  6574. IdentifierInfo &II =
  6575. PP.getIdentifierTable().get(Tok.getRawIdentifier());
  6576. SourceLocation MappedTokLoc =
  6577. CXXUnit->mapLocationToPreamble(Tok.getLocation());
  6578. MI = getMacroInfo(II, MappedTokLoc, TU);
  6579. }
  6580. }
  6581. bool finished = false;
  6582. do {
  6583. if (lexNext(Lex, Tok, NextIdx, NumTokens)) {
  6584. finished = true;
  6585. break;
  6586. }
  6587. // If we are in a macro definition, check if the token was ever a
  6588. // macro name and annotate it if that's the case.
  6589. if (MI) {
  6590. SourceLocation SaveLoc = Tok.getLocation();
  6591. Tok.setLocation(CXXUnit->mapLocationToPreamble(SaveLoc));
  6592. MacroDefinitionRecord *MacroDef =
  6593. checkForMacroInMacroDefinition(MI, Tok, TU);
  6594. Tok.setLocation(SaveLoc);
  6595. if (MacroDef)
  6596. Cursors[NextIdx - 1] =
  6597. MakeMacroExpansionCursor(MacroDef, Tok.getLocation(), TU);
  6598. }
  6599. } while (!Tok.isAtStartOfLine());
  6600. unsigned LastIdx = finished ? NextIdx - 1 : NextIdx - 2;
  6601. assert(TokIdx <= LastIdx);
  6602. SourceLocation EndLoc =
  6603. SourceLocation::getFromRawEncoding(Tokens[LastIdx].int_data[1]);
  6604. CXCursor Cursor =
  6605. MakePreprocessingDirectiveCursor(SourceRange(BeginLoc, EndLoc), TU);
  6606. for (; TokIdx <= LastIdx; ++TokIdx)
  6607. updateCursorAnnotation(Cursors[TokIdx], Cursor);
  6608. if (finished)
  6609. break;
  6610. goto reprocess;
  6611. }
  6612. }
  6613. }
  6614. // This gets run a separate thread to avoid stack blowout.
  6615. static void clang_annotateTokensImpl(CXTranslationUnit TU, ASTUnit *CXXUnit,
  6616. CXToken *Tokens, unsigned NumTokens,
  6617. CXCursor *Cursors) {
  6618. CIndexer *CXXIdx = TU->CIdx;
  6619. if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
  6620. setThreadBackgroundPriority();
  6621. // Determine the region of interest, which contains all of the tokens.
  6622. SourceRange RegionOfInterest;
  6623. RegionOfInterest.setBegin(
  6624. cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0])));
  6625. RegionOfInterest.setEnd(cxloc::translateSourceLocation(
  6626. clang_getTokenLocation(TU, Tokens[NumTokens - 1])));
  6627. // Relex the tokens within the source range to look for preprocessing
  6628. // directives.
  6629. annotatePreprocessorTokens(TU, RegionOfInterest, Cursors, Tokens, NumTokens);
  6630. // If begin location points inside a macro argument, set it to the expansion
  6631. // location so we can have the full context when annotating semantically.
  6632. {
  6633. SourceManager &SM = CXXUnit->getSourceManager();
  6634. SourceLocation Loc =
  6635. SM.getMacroArgExpandedLocation(RegionOfInterest.getBegin());
  6636. if (Loc.isMacroID())
  6637. RegionOfInterest.setBegin(SM.getExpansionLoc(Loc));
  6638. }
  6639. if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
  6640. // Search and mark tokens that are macro argument expansions.
  6641. MarkMacroArgTokensVisitor Visitor(CXXUnit->getSourceManager(), Tokens,
  6642. NumTokens);
  6643. CursorVisitor MacroArgMarker(
  6644. TU, MarkMacroArgTokensVisitorDelegate, &Visitor,
  6645. /*VisitPreprocessorLast=*/true,
  6646. /*VisitIncludedEntities=*/false, RegionOfInterest);
  6647. MacroArgMarker.visitPreprocessedEntitiesInRegion();
  6648. }
  6649. // Annotate all of the source locations in the region of interest that map to
  6650. // a specific cursor.
  6651. AnnotateTokensWorker W(Tokens, Cursors, NumTokens, TU, RegionOfInterest);
  6652. // FIXME: We use a ridiculous stack size here because the data-recursion
  6653. // algorithm uses a large stack frame than the non-data recursive version,
  6654. // and AnnotationTokensWorker currently transforms the data-recursion
  6655. // algorithm back into a traditional recursion by explicitly calling
  6656. // VisitChildren(). We will need to remove this explicit recursive call.
  6657. W.AnnotateTokens();
  6658. // If we ran into any entities that involve context-sensitive keywords,
  6659. // take another pass through the tokens to mark them as such.
  6660. if (W.hasContextSensitiveKeywords()) {
  6661. for (unsigned I = 0; I != NumTokens; ++I) {
  6662. if (clang_getTokenKind(Tokens[I]) != CXToken_Identifier)
  6663. continue;
  6664. if (Cursors[I].kind == CXCursor_ObjCPropertyDecl) {
  6665. IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
  6666. if (const ObjCPropertyDecl *Property =
  6667. dyn_cast_or_null<ObjCPropertyDecl>(getCursorDecl(Cursors[I]))) {
  6668. if (Property->getPropertyAttributesAsWritten() != 0 &&
  6669. llvm::StringSwitch<bool>(II->getName())
  6670. .Case("readonly", true)
  6671. .Case("assign", true)
  6672. .Case("unsafe_unretained", true)
  6673. .Case("readwrite", true)
  6674. .Case("retain", true)
  6675. .Case("copy", true)
  6676. .Case("nonatomic", true)
  6677. .Case("atomic", true)
  6678. .Case("getter", true)
  6679. .Case("setter", true)
  6680. .Case("strong", true)
  6681. .Case("weak", true)
  6682. .Case("class", true)
  6683. .Default(false))
  6684. Tokens[I].int_data[0] = CXToken_Keyword;
  6685. }
  6686. continue;
  6687. }
  6688. if (Cursors[I].kind == CXCursor_ObjCInstanceMethodDecl ||
  6689. Cursors[I].kind == CXCursor_ObjCClassMethodDecl) {
  6690. IdentifierInfo *II = static_cast<IdentifierInfo *>(Tokens[I].ptr_data);
  6691. if (llvm::StringSwitch<bool>(II->getName())
  6692. .Case("in", true)
  6693. .Case("out", true)
  6694. .Case("inout", true)
  6695. .Case("oneway", true)
  6696. .Case("bycopy", true)
  6697. .Case("byref", true)
  6698. .Default(false))
  6699. Tokens[I].int_data[0] = CXToken_Keyword;
  6700. continue;
  6701. }
  6702. if (Cursors[I].kind == CXCursor_CXXFinalAttr ||
  6703. Cursors[I].kind == CXCursor_CXXOverrideAttr) {
  6704. Tokens[I].int_data[0] = CXToken_Keyword;
  6705. continue;
  6706. }
  6707. }
  6708. }
  6709. }
  6710. void clang_annotateTokens(CXTranslationUnit TU, CXToken *Tokens,
  6711. unsigned NumTokens, CXCursor *Cursors) {
  6712. if (isNotUsableTU(TU)) {
  6713. LOG_BAD_TU(TU);
  6714. return;
  6715. }
  6716. if (NumTokens == 0 || !Tokens || !Cursors) {
  6717. LOG_FUNC_SECTION { *Log << "<null input>"; }
  6718. return;
  6719. }
  6720. LOG_FUNC_SECTION {
  6721. *Log << TU << ' ';
  6722. CXSourceLocation bloc = clang_getTokenLocation(TU, Tokens[0]);
  6723. CXSourceLocation eloc = clang_getTokenLocation(TU, Tokens[NumTokens - 1]);
  6724. *Log << clang_getRange(bloc, eloc);
  6725. }
  6726. // Any token we don't specifically annotate will have a NULL cursor.
  6727. CXCursor C = clang_getNullCursor();
  6728. for (unsigned I = 0; I != NumTokens; ++I)
  6729. Cursors[I] = C;
  6730. ASTUnit *CXXUnit = cxtu::getASTUnit(TU);
  6731. if (!CXXUnit)
  6732. return;
  6733. ASTUnit::ConcurrencyCheck Check(*CXXUnit);
  6734. auto AnnotateTokensImpl = [=]() {
  6735. clang_annotateTokensImpl(TU, CXXUnit, Tokens, NumTokens, Cursors);
  6736. };
  6737. llvm::CrashRecoveryContext CRC;
  6738. if (!RunSafely(CRC, AnnotateTokensImpl, GetSafetyThreadStackSize() * 2)) {
  6739. fprintf(stderr, "libclang: crash detected while annotating tokens\n");
  6740. }
  6741. }
  6742. //===----------------------------------------------------------------------===//
  6743. // Operations for querying linkage of a cursor.
  6744. //===----------------------------------------------------------------------===//
  6745. CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
  6746. if (!clang_isDeclaration(cursor.kind))
  6747. return CXLinkage_Invalid;
  6748. const Decl *D = cxcursor::getCursorDecl(cursor);
  6749. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
  6750. switch (ND->getLinkageInternal()) {
  6751. case NoLinkage:
  6752. case VisibleNoLinkage:
  6753. return CXLinkage_NoLinkage;
  6754. case ModuleInternalLinkage:
  6755. case InternalLinkage:
  6756. return CXLinkage_Internal;
  6757. case UniqueExternalLinkage:
  6758. return CXLinkage_UniqueExternal;
  6759. case ModuleLinkage:
  6760. case ExternalLinkage:
  6761. return CXLinkage_External;
  6762. };
  6763. return CXLinkage_Invalid;
  6764. }
  6765. //===----------------------------------------------------------------------===//
  6766. // Operations for querying visibility of a cursor.
  6767. //===----------------------------------------------------------------------===//
  6768. CXVisibilityKind clang_getCursorVisibility(CXCursor cursor) {
  6769. if (!clang_isDeclaration(cursor.kind))
  6770. return CXVisibility_Invalid;
  6771. const Decl *D = cxcursor::getCursorDecl(cursor);
  6772. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
  6773. switch (ND->getVisibility()) {
  6774. case HiddenVisibility:
  6775. return CXVisibility_Hidden;
  6776. case ProtectedVisibility:
  6777. return CXVisibility_Protected;
  6778. case DefaultVisibility:
  6779. return CXVisibility_Default;
  6780. };
  6781. return CXVisibility_Invalid;
  6782. }
  6783. //===----------------------------------------------------------------------===//
  6784. // Operations for querying language of a cursor.
  6785. //===----------------------------------------------------------------------===//
  6786. static CXLanguageKind getDeclLanguage(const Decl *D) {
  6787. if (!D)
  6788. return CXLanguage_C;
  6789. switch (D->getKind()) {
  6790. default:
  6791. break;
  6792. case Decl::ImplicitParam:
  6793. case Decl::ObjCAtDefsField:
  6794. case Decl::ObjCCategory:
  6795. case Decl::ObjCCategoryImpl:
  6796. case Decl::ObjCCompatibleAlias:
  6797. case Decl::ObjCImplementation:
  6798. case Decl::ObjCInterface:
  6799. case Decl::ObjCIvar:
  6800. case Decl::ObjCMethod:
  6801. case Decl::ObjCProperty:
  6802. case Decl::ObjCPropertyImpl:
  6803. case Decl::ObjCProtocol:
  6804. case Decl::ObjCTypeParam:
  6805. return CXLanguage_ObjC;
  6806. case Decl::CXXConstructor:
  6807. case Decl::CXXConversion:
  6808. case Decl::CXXDestructor:
  6809. case Decl::CXXMethod:
  6810. case Decl::CXXRecord:
  6811. case Decl::ClassTemplate:
  6812. case Decl::ClassTemplatePartialSpecialization:
  6813. case Decl::ClassTemplateSpecialization:
  6814. case Decl::Friend:
  6815. case Decl::FriendTemplate:
  6816. case Decl::FunctionTemplate:
  6817. case Decl::LinkageSpec:
  6818. case Decl::Namespace:
  6819. case Decl::NamespaceAlias:
  6820. case Decl::NonTypeTemplateParm:
  6821. case Decl::StaticAssert:
  6822. case Decl::TemplateTemplateParm:
  6823. case Decl::TemplateTypeParm:
  6824. case Decl::UnresolvedUsingTypename:
  6825. case Decl::UnresolvedUsingValue:
  6826. case Decl::Using:
  6827. case Decl::UsingDirective:
  6828. case Decl::UsingShadow:
  6829. return CXLanguage_CPlusPlus;
  6830. }
  6831. return CXLanguage_C;
  6832. }
  6833. static CXAvailabilityKind getCursorAvailabilityForDecl(const Decl *D) {
  6834. if (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted())
  6835. return CXAvailability_NotAvailable;
  6836. switch (D->getAvailability()) {
  6837. case AR_Available:
  6838. case AR_NotYetIntroduced:
  6839. if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
  6840. return getCursorAvailabilityForDecl(
  6841. cast<Decl>(EnumConst->getDeclContext()));
  6842. return CXAvailability_Available;
  6843. case AR_Deprecated:
  6844. return CXAvailability_Deprecated;
  6845. case AR_Unavailable:
  6846. return CXAvailability_NotAvailable;
  6847. }
  6848. llvm_unreachable("Unknown availability kind!");
  6849. }
  6850. enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
  6851. if (clang_isDeclaration(cursor.kind))
  6852. if (const Decl *D = cxcursor::getCursorDecl(cursor))
  6853. return getCursorAvailabilityForDecl(D);
  6854. return CXAvailability_Available;
  6855. }
  6856. static CXVersion convertVersion(VersionTuple In) {
  6857. CXVersion Out = {-1, -1, -1};
  6858. if (In.empty())
  6859. return Out;
  6860. Out.Major = In.getMajor();
  6861. Optional<unsigned> Minor = In.getMinor();
  6862. if (Minor.hasValue())
  6863. Out.Minor = *Minor;
  6864. else
  6865. return Out;
  6866. Optional<unsigned> Subminor = In.getSubminor();
  6867. if (Subminor.hasValue())
  6868. Out.Subminor = *Subminor;
  6869. return Out;
  6870. }
  6871. static void getCursorPlatformAvailabilityForDecl(
  6872. const Decl *D, int *always_deprecated, CXString *deprecated_message,
  6873. int *always_unavailable, CXString *unavailable_message,
  6874. SmallVectorImpl<AvailabilityAttr *> &AvailabilityAttrs) {
  6875. bool HadAvailAttr = false;
  6876. for (auto A : D->attrs()) {
  6877. if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
  6878. HadAvailAttr = true;
  6879. if (always_deprecated)
  6880. *always_deprecated = 1;
  6881. if (deprecated_message) {
  6882. clang_disposeString(*deprecated_message);
  6883. *deprecated_message = cxstring::createDup(Deprecated->getMessage());
  6884. }
  6885. continue;
  6886. }
  6887. if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(A)) {
  6888. HadAvailAttr = true;
  6889. if (always_unavailable)
  6890. *always_unavailable = 1;
  6891. if (unavailable_message) {
  6892. clang_disposeString(*unavailable_message);
  6893. *unavailable_message = cxstring::createDup(Unavailable->getMessage());
  6894. }
  6895. continue;
  6896. }
  6897. if (AvailabilityAttr *Avail = dyn_cast<AvailabilityAttr>(A)) {
  6898. AvailabilityAttrs.push_back(Avail);
  6899. HadAvailAttr = true;
  6900. }
  6901. }
  6902. if (!HadAvailAttr)
  6903. if (const EnumConstantDecl *EnumConst = dyn_cast<EnumConstantDecl>(D))
  6904. return getCursorPlatformAvailabilityForDecl(
  6905. cast<Decl>(EnumConst->getDeclContext()), always_deprecated,
  6906. deprecated_message, always_unavailable, unavailable_message,
  6907. AvailabilityAttrs);
  6908. if (AvailabilityAttrs.empty())
  6909. return;
  6910. llvm::sort(
  6911. AvailabilityAttrs, [](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
  6912. return LHS->getPlatform()->getName() < RHS->getPlatform()->getName();
  6913. });
  6914. ASTContext &Ctx = D->getASTContext();
  6915. auto It = std::unique(
  6916. AvailabilityAttrs.begin(), AvailabilityAttrs.end(),
  6917. [&Ctx](AvailabilityAttr *LHS, AvailabilityAttr *RHS) {
  6918. if (LHS->getPlatform() != RHS->getPlatform())
  6919. return false;
  6920. if (LHS->getIntroduced() == RHS->getIntroduced() &&
  6921. LHS->getDeprecated() == RHS->getDeprecated() &&
  6922. LHS->getObsoleted() == RHS->getObsoleted() &&
  6923. LHS->getMessage() == RHS->getMessage() &&
  6924. LHS->getReplacement() == RHS->getReplacement())
  6925. return true;
  6926. if ((!LHS->getIntroduced().empty() && !RHS->getIntroduced().empty()) ||
  6927. (!LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) ||
  6928. (!LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()))
  6929. return false;
  6930. if (LHS->getIntroduced().empty() && !RHS->getIntroduced().empty())
  6931. LHS->setIntroduced(Ctx, RHS->getIntroduced());
  6932. if (LHS->getDeprecated().empty() && !RHS->getDeprecated().empty()) {
  6933. LHS->setDeprecated(Ctx, RHS->getDeprecated());
  6934. if (LHS->getMessage().empty())
  6935. LHS->setMessage(Ctx, RHS->getMessage());
  6936. if (LHS->getReplacement().empty())
  6937. LHS->setReplacement(Ctx, RHS->getReplacement());
  6938. }
  6939. if (LHS->getObsoleted().empty() && !RHS->getObsoleted().empty()) {
  6940. LHS->setObsoleted(Ctx, RHS->getObsoleted());
  6941. if (LHS->getMessage().empty())
  6942. LHS->setMessage(Ctx, RHS->getMessage());
  6943. if (LHS->getReplacement().empty())
  6944. LHS->setReplacement(Ctx, RHS->getReplacement());
  6945. }
  6946. return true;
  6947. });
  6948. AvailabilityAttrs.erase(It, AvailabilityAttrs.end());
  6949. }
  6950. int clang_getCursorPlatformAvailability(CXCursor cursor, int *always_deprecated,
  6951. CXString *deprecated_message,
  6952. int *always_unavailable,
  6953. CXString *unavailable_message,
  6954. CXPlatformAvailability *availability,
  6955. int availability_size) {
  6956. if (always_deprecated)
  6957. *always_deprecated = 0;
  6958. if (deprecated_message)
  6959. *deprecated_message = cxstring::createEmpty();
  6960. if (always_unavailable)
  6961. *always_unavailable = 0;
  6962. if (unavailable_message)
  6963. *unavailable_message = cxstring::createEmpty();
  6964. if (!clang_isDeclaration(cursor.kind))
  6965. return 0;
  6966. const Decl *D = cxcursor::getCursorDecl(cursor);
  6967. if (!D)
  6968. return 0;
  6969. SmallVector<AvailabilityAttr *, 8> AvailabilityAttrs;
  6970. getCursorPlatformAvailabilityForDecl(D, always_deprecated, deprecated_message,
  6971. always_unavailable, unavailable_message,
  6972. AvailabilityAttrs);
  6973. for (const auto &Avail :
  6974. llvm::enumerate(llvm::makeArrayRef(AvailabilityAttrs)
  6975. .take_front(availability_size))) {
  6976. availability[Avail.index()].Platform =
  6977. cxstring::createDup(Avail.value()->getPlatform()->getName());
  6978. availability[Avail.index()].Introduced =
  6979. convertVersion(Avail.value()->getIntroduced());
  6980. availability[Avail.index()].Deprecated =
  6981. convertVersion(Avail.value()->getDeprecated());
  6982. availability[Avail.index()].Obsoleted =
  6983. convertVersion(Avail.value()->getObsoleted());
  6984. availability[Avail.index()].Unavailable = Avail.value()->getUnavailable();
  6985. availability[Avail.index()].Message =
  6986. cxstring::createDup(Avail.value()->getMessage());
  6987. }
  6988. return AvailabilityAttrs.size();
  6989. }
  6990. void clang_disposeCXPlatformAvailability(CXPlatformAvailability *availability) {
  6991. clang_disposeString(availability->Platform);
  6992. clang_disposeString(availability->Message);
  6993. }
  6994. CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
  6995. if (clang_isDeclaration(cursor.kind))
  6996. return getDeclLanguage(cxcursor::getCursorDecl(cursor));
  6997. return CXLanguage_Invalid;
  6998. }
  6999. CXTLSKind clang_getCursorTLSKind(CXCursor cursor) {
  7000. const Decl *D = cxcursor::getCursorDecl(cursor);
  7001. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  7002. switch (VD->getTLSKind()) {
  7003. case VarDecl::TLS_None:
  7004. return CXTLS_None;
  7005. case VarDecl::TLS_Dynamic:
  7006. return CXTLS_Dynamic;
  7007. case VarDecl::TLS_Static:
  7008. return CXTLS_Static;
  7009. }
  7010. }
  7011. return CXTLS_None;
  7012. }
  7013. /// If the given cursor is the "templated" declaration
  7014. /// describing a class or function template, return the class or
  7015. /// function template.
  7016. static const Decl *maybeGetTemplateCursor(const Decl *D) {
  7017. if (!D)
  7018. return nullptr;
  7019. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7020. if (FunctionTemplateDecl *FunTmpl = FD->getDescribedFunctionTemplate())
  7021. return FunTmpl;
  7022. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
  7023. if (ClassTemplateDecl *ClassTmpl = RD->getDescribedClassTemplate())
  7024. return ClassTmpl;
  7025. return D;
  7026. }
  7027. enum CX_StorageClass clang_Cursor_getStorageClass(CXCursor C) {
  7028. StorageClass sc = SC_None;
  7029. const Decl *D = getCursorDecl(C);
  7030. if (D) {
  7031. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7032. sc = FD->getStorageClass();
  7033. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  7034. sc = VD->getStorageClass();
  7035. } else {
  7036. return CX_SC_Invalid;
  7037. }
  7038. } else {
  7039. return CX_SC_Invalid;
  7040. }
  7041. switch (sc) {
  7042. case SC_None:
  7043. return CX_SC_None;
  7044. case SC_Extern:
  7045. return CX_SC_Extern;
  7046. case SC_Static:
  7047. return CX_SC_Static;
  7048. case SC_PrivateExtern:
  7049. return CX_SC_PrivateExtern;
  7050. case SC_Auto:
  7051. return CX_SC_Auto;
  7052. case SC_Register:
  7053. return CX_SC_Register;
  7054. }
  7055. llvm_unreachable("Unhandled storage class!");
  7056. }
  7057. CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
  7058. if (clang_isDeclaration(cursor.kind)) {
  7059. if (const Decl *D = getCursorDecl(cursor)) {
  7060. const DeclContext *DC = D->getDeclContext();
  7061. if (!DC)
  7062. return clang_getNullCursor();
  7063. return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
  7064. getCursorTU(cursor));
  7065. }
  7066. }
  7067. if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
  7068. if (const Decl *D = getCursorDecl(cursor))
  7069. return MakeCXCursor(D, getCursorTU(cursor));
  7070. }
  7071. return clang_getNullCursor();
  7072. }
  7073. CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
  7074. if (clang_isDeclaration(cursor.kind)) {
  7075. if (const Decl *D = getCursorDecl(cursor)) {
  7076. const DeclContext *DC = D->getLexicalDeclContext();
  7077. if (!DC)
  7078. return clang_getNullCursor();
  7079. return MakeCXCursor(maybeGetTemplateCursor(cast<Decl>(DC)),
  7080. getCursorTU(cursor));
  7081. }
  7082. }
  7083. // FIXME: Note that we can't easily compute the lexical context of a
  7084. // statement or expression, so we return nothing.
  7085. return clang_getNullCursor();
  7086. }
  7087. CXFile clang_getIncludedFile(CXCursor cursor) {
  7088. if (cursor.kind != CXCursor_InclusionDirective)
  7089. return nullptr;
  7090. const InclusionDirective *ID = getCursorInclusionDirective(cursor);
  7091. return const_cast<FileEntry *>(ID->getFile());
  7092. }
  7093. unsigned clang_Cursor_getObjCPropertyAttributes(CXCursor C, unsigned reserved) {
  7094. if (C.kind != CXCursor_ObjCPropertyDecl)
  7095. return CXObjCPropertyAttr_noattr;
  7096. unsigned Result = CXObjCPropertyAttr_noattr;
  7097. const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
  7098. ObjCPropertyAttribute::Kind Attr = PD->getPropertyAttributesAsWritten();
  7099. #define SET_CXOBJCPROP_ATTR(A) \
  7100. if (Attr & ObjCPropertyAttribute::kind_##A) \
  7101. Result |= CXObjCPropertyAttr_##A
  7102. SET_CXOBJCPROP_ATTR(readonly);
  7103. SET_CXOBJCPROP_ATTR(getter);
  7104. SET_CXOBJCPROP_ATTR(assign);
  7105. SET_CXOBJCPROP_ATTR(readwrite);
  7106. SET_CXOBJCPROP_ATTR(retain);
  7107. SET_CXOBJCPROP_ATTR(copy);
  7108. SET_CXOBJCPROP_ATTR(nonatomic);
  7109. SET_CXOBJCPROP_ATTR(setter);
  7110. SET_CXOBJCPROP_ATTR(atomic);
  7111. SET_CXOBJCPROP_ATTR(weak);
  7112. SET_CXOBJCPROP_ATTR(strong);
  7113. SET_CXOBJCPROP_ATTR(unsafe_unretained);
  7114. SET_CXOBJCPROP_ATTR(class);
  7115. #undef SET_CXOBJCPROP_ATTR
  7116. return Result;
  7117. }
  7118. CXString clang_Cursor_getObjCPropertyGetterName(CXCursor C) {
  7119. if (C.kind != CXCursor_ObjCPropertyDecl)
  7120. return cxstring::createNull();
  7121. const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
  7122. Selector sel = PD->getGetterName();
  7123. if (sel.isNull())
  7124. return cxstring::createNull();
  7125. return cxstring::createDup(sel.getAsString());
  7126. }
  7127. CXString clang_Cursor_getObjCPropertySetterName(CXCursor C) {
  7128. if (C.kind != CXCursor_ObjCPropertyDecl)
  7129. return cxstring::createNull();
  7130. const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(getCursorDecl(C));
  7131. Selector sel = PD->getSetterName();
  7132. if (sel.isNull())
  7133. return cxstring::createNull();
  7134. return cxstring::createDup(sel.getAsString());
  7135. }
  7136. unsigned clang_Cursor_getObjCDeclQualifiers(CXCursor C) {
  7137. if (!clang_isDeclaration(C.kind))
  7138. return CXObjCDeclQualifier_None;
  7139. Decl::ObjCDeclQualifier QT = Decl::OBJC_TQ_None;
  7140. const Decl *D = getCursorDecl(C);
  7141. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  7142. QT = MD->getObjCDeclQualifier();
  7143. else if (const ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
  7144. QT = PD->getObjCDeclQualifier();
  7145. if (QT == Decl::OBJC_TQ_None)
  7146. return CXObjCDeclQualifier_None;
  7147. unsigned Result = CXObjCDeclQualifier_None;
  7148. if (QT & Decl::OBJC_TQ_In)
  7149. Result |= CXObjCDeclQualifier_In;
  7150. if (QT & Decl::OBJC_TQ_Inout)
  7151. Result |= CXObjCDeclQualifier_Inout;
  7152. if (QT & Decl::OBJC_TQ_Out)
  7153. Result |= CXObjCDeclQualifier_Out;
  7154. if (QT & Decl::OBJC_TQ_Bycopy)
  7155. Result |= CXObjCDeclQualifier_Bycopy;
  7156. if (QT & Decl::OBJC_TQ_Byref)
  7157. Result |= CXObjCDeclQualifier_Byref;
  7158. if (QT & Decl::OBJC_TQ_Oneway)
  7159. Result |= CXObjCDeclQualifier_Oneway;
  7160. return Result;
  7161. }
  7162. unsigned clang_Cursor_isObjCOptional(CXCursor C) {
  7163. if (!clang_isDeclaration(C.kind))
  7164. return 0;
  7165. const Decl *D = getCursorDecl(C);
  7166. if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
  7167. return PD->getPropertyImplementation() == ObjCPropertyDecl::Optional;
  7168. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  7169. return MD->getImplementationControl() == ObjCMethodDecl::Optional;
  7170. return 0;
  7171. }
  7172. unsigned clang_Cursor_isVariadic(CXCursor C) {
  7173. if (!clang_isDeclaration(C.kind))
  7174. return 0;
  7175. const Decl *D = getCursorDecl(C);
  7176. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  7177. return FD->isVariadic();
  7178. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
  7179. return MD->isVariadic();
  7180. return 0;
  7181. }
  7182. unsigned clang_Cursor_isExternalSymbol(CXCursor C, CXString *language,
  7183. CXString *definedIn,
  7184. unsigned *isGenerated) {
  7185. if (!clang_isDeclaration(C.kind))
  7186. return 0;
  7187. const Decl *D = getCursorDecl(C);
  7188. if (auto *attr = D->getExternalSourceSymbolAttr()) {
  7189. if (language)
  7190. *language = cxstring::createDup(attr->getLanguage());
  7191. if (definedIn)
  7192. *definedIn = cxstring::createDup(attr->getDefinedIn());
  7193. if (isGenerated)
  7194. *isGenerated = attr->getGeneratedDeclaration();
  7195. return 1;
  7196. }
  7197. return 0;
  7198. }
  7199. CXSourceRange clang_Cursor_getCommentRange(CXCursor C) {
  7200. if (!clang_isDeclaration(C.kind))
  7201. return clang_getNullRange();
  7202. const Decl *D = getCursorDecl(C);
  7203. ASTContext &Context = getCursorContext(C);
  7204. const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
  7205. if (!RC)
  7206. return clang_getNullRange();
  7207. return cxloc::translateSourceRange(Context, RC->getSourceRange());
  7208. }
  7209. CXString clang_Cursor_getRawCommentText(CXCursor C) {
  7210. if (!clang_isDeclaration(C.kind))
  7211. return cxstring::createNull();
  7212. const Decl *D = getCursorDecl(C);
  7213. ASTContext &Context = getCursorContext(C);
  7214. const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
  7215. StringRef RawText =
  7216. RC ? RC->getRawText(Context.getSourceManager()) : StringRef();
  7217. // Don't duplicate the string because RawText points directly into source
  7218. // code.
  7219. return cxstring::createRef(RawText);
  7220. }
  7221. CXString clang_Cursor_getBriefCommentText(CXCursor C) {
  7222. if (!clang_isDeclaration(C.kind))
  7223. return cxstring::createNull();
  7224. const Decl *D = getCursorDecl(C);
  7225. const ASTContext &Context = getCursorContext(C);
  7226. const RawComment *RC = Context.getRawCommentForAnyRedecl(D);
  7227. if (RC) {
  7228. StringRef BriefText = RC->getBriefText(Context);
  7229. // Don't duplicate the string because RawComment ensures that this memory
  7230. // will not go away.
  7231. return cxstring::createRef(BriefText);
  7232. }
  7233. return cxstring::createNull();
  7234. }
  7235. CXModule clang_Cursor_getModule(CXCursor C) {
  7236. if (C.kind == CXCursor_ModuleImportDecl) {
  7237. if (const ImportDecl *ImportD =
  7238. dyn_cast_or_null<ImportDecl>(getCursorDecl(C)))
  7239. return ImportD->getImportedModule();
  7240. }
  7241. return nullptr;
  7242. }
  7243. CXModule clang_getModuleForFile(CXTranslationUnit TU, CXFile File) {
  7244. if (isNotUsableTU(TU)) {
  7245. LOG_BAD_TU(TU);
  7246. return nullptr;
  7247. }
  7248. if (!File)
  7249. return nullptr;
  7250. FileEntry *FE = static_cast<FileEntry *>(File);
  7251. ASTUnit &Unit = *cxtu::getASTUnit(TU);
  7252. HeaderSearch &HS = Unit.getPreprocessor().getHeaderSearchInfo();
  7253. ModuleMap::KnownHeader Header = HS.findModuleForHeader(FE);
  7254. return Header.getModule();
  7255. }
  7256. CXFile clang_Module_getASTFile(CXModule CXMod) {
  7257. if (!CXMod)
  7258. return nullptr;
  7259. Module *Mod = static_cast<Module *>(CXMod);
  7260. if (auto File = Mod->getASTFile())
  7261. return const_cast<FileEntry *>(&File->getFileEntry());
  7262. return nullptr;
  7263. }
  7264. CXModule clang_Module_getParent(CXModule CXMod) {
  7265. if (!CXMod)
  7266. return nullptr;
  7267. Module *Mod = static_cast<Module *>(CXMod);
  7268. return Mod->Parent;
  7269. }
  7270. CXString clang_Module_getName(CXModule CXMod) {
  7271. if (!CXMod)
  7272. return cxstring::createEmpty();
  7273. Module *Mod = static_cast<Module *>(CXMod);
  7274. return cxstring::createDup(Mod->Name);
  7275. }
  7276. CXString clang_Module_getFullName(CXModule CXMod) {
  7277. if (!CXMod)
  7278. return cxstring::createEmpty();
  7279. Module *Mod = static_cast<Module *>(CXMod);
  7280. return cxstring::createDup(Mod->getFullModuleName());
  7281. }
  7282. int clang_Module_isSystem(CXModule CXMod) {
  7283. if (!CXMod)
  7284. return 0;
  7285. Module *Mod = static_cast<Module *>(CXMod);
  7286. return Mod->IsSystem;
  7287. }
  7288. unsigned clang_Module_getNumTopLevelHeaders(CXTranslationUnit TU,
  7289. CXModule CXMod) {
  7290. if (isNotUsableTU(TU)) {
  7291. LOG_BAD_TU(TU);
  7292. return 0;
  7293. }
  7294. if (!CXMod)
  7295. return 0;
  7296. Module *Mod = static_cast<Module *>(CXMod);
  7297. FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
  7298. ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
  7299. return TopHeaders.size();
  7300. }
  7301. CXFile clang_Module_getTopLevelHeader(CXTranslationUnit TU, CXModule CXMod,
  7302. unsigned Index) {
  7303. if (isNotUsableTU(TU)) {
  7304. LOG_BAD_TU(TU);
  7305. return nullptr;
  7306. }
  7307. if (!CXMod)
  7308. return nullptr;
  7309. Module *Mod = static_cast<Module *>(CXMod);
  7310. FileManager &FileMgr = cxtu::getASTUnit(TU)->getFileManager();
  7311. ArrayRef<const FileEntry *> TopHeaders = Mod->getTopHeaders(FileMgr);
  7312. if (Index < TopHeaders.size())
  7313. return const_cast<FileEntry *>(TopHeaders[Index]);
  7314. return nullptr;
  7315. }
  7316. //===----------------------------------------------------------------------===//
  7317. // C++ AST instrospection.
  7318. //===----------------------------------------------------------------------===//
  7319. unsigned clang_CXXConstructor_isDefaultConstructor(CXCursor C) {
  7320. if (!clang_isDeclaration(C.kind))
  7321. return 0;
  7322. const Decl *D = cxcursor::getCursorDecl(C);
  7323. const CXXConstructorDecl *Constructor =
  7324. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7325. return (Constructor && Constructor->isDefaultConstructor()) ? 1 : 0;
  7326. }
  7327. unsigned clang_CXXConstructor_isCopyConstructor(CXCursor C) {
  7328. if (!clang_isDeclaration(C.kind))
  7329. return 0;
  7330. const Decl *D = cxcursor::getCursorDecl(C);
  7331. const CXXConstructorDecl *Constructor =
  7332. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7333. return (Constructor && Constructor->isCopyConstructor()) ? 1 : 0;
  7334. }
  7335. unsigned clang_CXXConstructor_isMoveConstructor(CXCursor C) {
  7336. if (!clang_isDeclaration(C.kind))
  7337. return 0;
  7338. const Decl *D = cxcursor::getCursorDecl(C);
  7339. const CXXConstructorDecl *Constructor =
  7340. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7341. return (Constructor && Constructor->isMoveConstructor()) ? 1 : 0;
  7342. }
  7343. unsigned clang_CXXConstructor_isConvertingConstructor(CXCursor C) {
  7344. if (!clang_isDeclaration(C.kind))
  7345. return 0;
  7346. const Decl *D = cxcursor::getCursorDecl(C);
  7347. const CXXConstructorDecl *Constructor =
  7348. D ? dyn_cast_or_null<CXXConstructorDecl>(D->getAsFunction()) : nullptr;
  7349. // Passing 'false' excludes constructors marked 'explicit'.
  7350. return (Constructor && Constructor->isConvertingConstructor(false)) ? 1 : 0;
  7351. }
  7352. unsigned clang_CXXField_isMutable(CXCursor C) {
  7353. if (!clang_isDeclaration(C.kind))
  7354. return 0;
  7355. if (const auto D = cxcursor::getCursorDecl(C))
  7356. if (const auto FD = dyn_cast_or_null<FieldDecl>(D))
  7357. return FD->isMutable() ? 1 : 0;
  7358. return 0;
  7359. }
  7360. unsigned clang_CXXMethod_isPureVirtual(CXCursor C) {
  7361. if (!clang_isDeclaration(C.kind))
  7362. return 0;
  7363. const Decl *D = cxcursor::getCursorDecl(C);
  7364. const CXXMethodDecl *Method =
  7365. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7366. return (Method && Method->isVirtual() && Method->isPure()) ? 1 : 0;
  7367. }
  7368. unsigned clang_CXXMethod_isConst(CXCursor C) {
  7369. if (!clang_isDeclaration(C.kind))
  7370. return 0;
  7371. const Decl *D = cxcursor::getCursorDecl(C);
  7372. const CXXMethodDecl *Method =
  7373. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7374. return (Method && Method->getMethodQualifiers().hasConst()) ? 1 : 0;
  7375. }
  7376. unsigned clang_CXXMethod_isDefaulted(CXCursor C) {
  7377. if (!clang_isDeclaration(C.kind))
  7378. return 0;
  7379. const Decl *D = cxcursor::getCursorDecl(C);
  7380. const CXXMethodDecl *Method =
  7381. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7382. return (Method && Method->isDefaulted()) ? 1 : 0;
  7383. }
  7384. unsigned clang_CXXMethod_isStatic(CXCursor C) {
  7385. if (!clang_isDeclaration(C.kind))
  7386. return 0;
  7387. const Decl *D = cxcursor::getCursorDecl(C);
  7388. const CXXMethodDecl *Method =
  7389. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7390. return (Method && Method->isStatic()) ? 1 : 0;
  7391. }
  7392. unsigned clang_CXXMethod_isVirtual(CXCursor C) {
  7393. if (!clang_isDeclaration(C.kind))
  7394. return 0;
  7395. const Decl *D = cxcursor::getCursorDecl(C);
  7396. const CXXMethodDecl *Method =
  7397. D ? dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()) : nullptr;
  7398. return (Method && Method->isVirtual()) ? 1 : 0;
  7399. }
  7400. unsigned clang_CXXRecord_isAbstract(CXCursor C) {
  7401. if (!clang_isDeclaration(C.kind))
  7402. return 0;
  7403. const auto *D = cxcursor::getCursorDecl(C);
  7404. const auto *RD = dyn_cast_or_null<CXXRecordDecl>(D);
  7405. if (RD)
  7406. RD = RD->getDefinition();
  7407. return (RD && RD->isAbstract()) ? 1 : 0;
  7408. }
  7409. unsigned clang_EnumDecl_isScoped(CXCursor C) {
  7410. if (!clang_isDeclaration(C.kind))
  7411. return 0;
  7412. const Decl *D = cxcursor::getCursorDecl(C);
  7413. auto *Enum = dyn_cast_or_null<EnumDecl>(D);
  7414. return (Enum && Enum->isScoped()) ? 1 : 0;
  7415. }
  7416. //===----------------------------------------------------------------------===//
  7417. // Attribute introspection.
  7418. //===----------------------------------------------------------------------===//
  7419. CXType clang_getIBOutletCollectionType(CXCursor C) {
  7420. if (C.kind != CXCursor_IBOutletCollectionAttr)
  7421. return cxtype::MakeCXType(QualType(), cxcursor::getCursorTU(C));
  7422. const IBOutletCollectionAttr *A =
  7423. cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
  7424. return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorTU(C));
  7425. }
  7426. //===----------------------------------------------------------------------===//
  7427. // Inspecting memory usage.
  7428. //===----------------------------------------------------------------------===//
  7429. typedef std::vector<CXTUResourceUsageEntry> MemUsageEntries;
  7430. static inline void createCXTUResourceUsageEntry(MemUsageEntries &entries,
  7431. enum CXTUResourceUsageKind k,
  7432. unsigned long amount) {
  7433. CXTUResourceUsageEntry entry = {k, amount};
  7434. entries.push_back(entry);
  7435. }
  7436. const char *clang_getTUResourceUsageName(CXTUResourceUsageKind kind) {
  7437. const char *str = "";
  7438. switch (kind) {
  7439. case CXTUResourceUsage_AST:
  7440. str = "ASTContext: expressions, declarations, and types";
  7441. break;
  7442. case CXTUResourceUsage_Identifiers:
  7443. str = "ASTContext: identifiers";
  7444. break;
  7445. case CXTUResourceUsage_Selectors:
  7446. str = "ASTContext: selectors";
  7447. break;
  7448. case CXTUResourceUsage_GlobalCompletionResults:
  7449. str = "Code completion: cached global results";
  7450. break;
  7451. case CXTUResourceUsage_SourceManagerContentCache:
  7452. str = "SourceManager: content cache allocator";
  7453. break;
  7454. case CXTUResourceUsage_AST_SideTables:
  7455. str = "ASTContext: side tables";
  7456. break;
  7457. case CXTUResourceUsage_SourceManager_Membuffer_Malloc:
  7458. str = "SourceManager: malloc'ed memory buffers";
  7459. break;
  7460. case CXTUResourceUsage_SourceManager_Membuffer_MMap:
  7461. str = "SourceManager: mmap'ed memory buffers";
  7462. break;
  7463. case CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc:
  7464. str = "ExternalASTSource: malloc'ed memory buffers";
  7465. break;
  7466. case CXTUResourceUsage_ExternalASTSource_Membuffer_MMap:
  7467. str = "ExternalASTSource: mmap'ed memory buffers";
  7468. break;
  7469. case CXTUResourceUsage_Preprocessor:
  7470. str = "Preprocessor: malloc'ed memory";
  7471. break;
  7472. case CXTUResourceUsage_PreprocessingRecord:
  7473. str = "Preprocessor: PreprocessingRecord";
  7474. break;
  7475. case CXTUResourceUsage_SourceManager_DataStructures:
  7476. str = "SourceManager: data structures and tables";
  7477. break;
  7478. case CXTUResourceUsage_Preprocessor_HeaderSearch:
  7479. str = "Preprocessor: header search tables";
  7480. break;
  7481. }
  7482. return str;
  7483. }
  7484. CXTUResourceUsage clang_getCXTUResourceUsage(CXTranslationUnit TU) {
  7485. if (isNotUsableTU(TU)) {
  7486. LOG_BAD_TU(TU);
  7487. CXTUResourceUsage usage = {(void *)nullptr, 0, nullptr};
  7488. return usage;
  7489. }
  7490. ASTUnit *astUnit = cxtu::getASTUnit(TU);
  7491. std::unique_ptr<MemUsageEntries> entries(new MemUsageEntries());
  7492. ASTContext &astContext = astUnit->getASTContext();
  7493. // How much memory is used by AST nodes and types?
  7494. createCXTUResourceUsageEntry(
  7495. *entries, CXTUResourceUsage_AST,
  7496. (unsigned long)astContext.getASTAllocatedMemory());
  7497. // How much memory is used by identifiers?
  7498. createCXTUResourceUsageEntry(
  7499. *entries, CXTUResourceUsage_Identifiers,
  7500. (unsigned long)astContext.Idents.getAllocator().getTotalMemory());
  7501. // How much memory is used for selectors?
  7502. createCXTUResourceUsageEntry(
  7503. *entries, CXTUResourceUsage_Selectors,
  7504. (unsigned long)astContext.Selectors.getTotalMemory());
  7505. // How much memory is used by ASTContext's side tables?
  7506. createCXTUResourceUsageEntry(
  7507. *entries, CXTUResourceUsage_AST_SideTables,
  7508. (unsigned long)astContext.getSideTableAllocatedMemory());
  7509. // How much memory is used for caching global code completion results?
  7510. unsigned long completionBytes = 0;
  7511. if (GlobalCodeCompletionAllocator *completionAllocator =
  7512. astUnit->getCachedCompletionAllocator().get()) {
  7513. completionBytes = completionAllocator->getTotalMemory();
  7514. }
  7515. createCXTUResourceUsageEntry(
  7516. *entries, CXTUResourceUsage_GlobalCompletionResults, completionBytes);
  7517. // How much memory is being used by SourceManager's content cache?
  7518. createCXTUResourceUsageEntry(
  7519. *entries, CXTUResourceUsage_SourceManagerContentCache,
  7520. (unsigned long)astContext.getSourceManager().getContentCacheSize());
  7521. // How much memory is being used by the MemoryBuffer's in SourceManager?
  7522. const SourceManager::MemoryBufferSizes &srcBufs =
  7523. astUnit->getSourceManager().getMemoryBufferSizes();
  7524. createCXTUResourceUsageEntry(*entries,
  7525. CXTUResourceUsage_SourceManager_Membuffer_Malloc,
  7526. (unsigned long)srcBufs.malloc_bytes);
  7527. createCXTUResourceUsageEntry(*entries,
  7528. CXTUResourceUsage_SourceManager_Membuffer_MMap,
  7529. (unsigned long)srcBufs.mmap_bytes);
  7530. createCXTUResourceUsageEntry(
  7531. *entries, CXTUResourceUsage_SourceManager_DataStructures,
  7532. (unsigned long)astContext.getSourceManager().getDataStructureSizes());
  7533. // How much memory is being used by the ExternalASTSource?
  7534. if (ExternalASTSource *esrc = astContext.getExternalSource()) {
  7535. const ExternalASTSource::MemoryBufferSizes &sizes =
  7536. esrc->getMemoryBufferSizes();
  7537. createCXTUResourceUsageEntry(
  7538. *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_Malloc,
  7539. (unsigned long)sizes.malloc_bytes);
  7540. createCXTUResourceUsageEntry(
  7541. *entries, CXTUResourceUsage_ExternalASTSource_Membuffer_MMap,
  7542. (unsigned long)sizes.mmap_bytes);
  7543. }
  7544. // How much memory is being used by the Preprocessor?
  7545. Preprocessor &pp = astUnit->getPreprocessor();
  7546. createCXTUResourceUsageEntry(*entries, CXTUResourceUsage_Preprocessor,
  7547. pp.getTotalMemory());
  7548. if (PreprocessingRecord *pRec = pp.getPreprocessingRecord()) {
  7549. createCXTUResourceUsageEntry(*entries,
  7550. CXTUResourceUsage_PreprocessingRecord,
  7551. pRec->getTotalMemory());
  7552. }
  7553. createCXTUResourceUsageEntry(*entries,
  7554. CXTUResourceUsage_Preprocessor_HeaderSearch,
  7555. pp.getHeaderSearchInfo().getTotalMemory());
  7556. CXTUResourceUsage usage = {(void *)entries.get(), (unsigned)entries->size(),
  7557. !entries->empty() ? &(*entries)[0] : nullptr};
  7558. (void)entries.release();
  7559. return usage;
  7560. }
  7561. void clang_disposeCXTUResourceUsage(CXTUResourceUsage usage) {
  7562. if (usage.data)
  7563. delete (MemUsageEntries *)usage.data;
  7564. }
  7565. CXSourceRangeList *clang_getSkippedRanges(CXTranslationUnit TU, CXFile file) {
  7566. CXSourceRangeList *skipped = new CXSourceRangeList;
  7567. skipped->count = 0;
  7568. skipped->ranges = nullptr;
  7569. if (isNotUsableTU(TU)) {
  7570. LOG_BAD_TU(TU);
  7571. return skipped;
  7572. }
  7573. if (!file)
  7574. return skipped;
  7575. ASTUnit *astUnit = cxtu::getASTUnit(TU);
  7576. PreprocessingRecord *ppRec =
  7577. astUnit->getPreprocessor().getPreprocessingRecord();
  7578. if (!ppRec)
  7579. return skipped;
  7580. ASTContext &Ctx = astUnit->getASTContext();
  7581. SourceManager &sm = Ctx.getSourceManager();
  7582. FileEntry *fileEntry = static_cast<FileEntry *>(file);
  7583. FileID wantedFileID = sm.translateFile(fileEntry);
  7584. bool isMainFile = wantedFileID == sm.getMainFileID();
  7585. const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
  7586. std::vector<SourceRange> wantedRanges;
  7587. for (std::vector<SourceRange>::const_iterator i = SkippedRanges.begin(),
  7588. ei = SkippedRanges.end();
  7589. i != ei; ++i) {
  7590. if (sm.getFileID(i->getBegin()) == wantedFileID ||
  7591. sm.getFileID(i->getEnd()) == wantedFileID)
  7592. wantedRanges.push_back(*i);
  7593. else if (isMainFile && (astUnit->isInPreambleFileID(i->getBegin()) ||
  7594. astUnit->isInPreambleFileID(i->getEnd())))
  7595. wantedRanges.push_back(*i);
  7596. }
  7597. skipped->count = wantedRanges.size();
  7598. skipped->ranges = new CXSourceRange[skipped->count];
  7599. for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
  7600. skipped->ranges[i] = cxloc::translateSourceRange(Ctx, wantedRanges[i]);
  7601. return skipped;
  7602. }
  7603. CXSourceRangeList *clang_getAllSkippedRanges(CXTranslationUnit TU) {
  7604. CXSourceRangeList *skipped = new CXSourceRangeList;
  7605. skipped->count = 0;
  7606. skipped->ranges = nullptr;
  7607. if (isNotUsableTU(TU)) {
  7608. LOG_BAD_TU(TU);
  7609. return skipped;
  7610. }
  7611. ASTUnit *astUnit = cxtu::getASTUnit(TU);
  7612. PreprocessingRecord *ppRec =
  7613. astUnit->getPreprocessor().getPreprocessingRecord();
  7614. if (!ppRec)
  7615. return skipped;
  7616. ASTContext &Ctx = astUnit->getASTContext();
  7617. const std::vector<SourceRange> &SkippedRanges = ppRec->getSkippedRanges();
  7618. skipped->count = SkippedRanges.size();
  7619. skipped->ranges = new CXSourceRange[skipped->count];
  7620. for (unsigned i = 0, ei = skipped->count; i != ei; ++i)
  7621. skipped->ranges[i] = cxloc::translateSourceRange(Ctx, SkippedRanges[i]);
  7622. return skipped;
  7623. }
  7624. void clang_disposeSourceRangeList(CXSourceRangeList *ranges) {
  7625. if (ranges) {
  7626. delete[] ranges->ranges;
  7627. delete ranges;
  7628. }
  7629. }
  7630. void clang::PrintLibclangResourceUsage(CXTranslationUnit TU) {
  7631. CXTUResourceUsage Usage = clang_getCXTUResourceUsage(TU);
  7632. for (unsigned I = 0; I != Usage.numEntries; ++I)
  7633. fprintf(stderr, " %s: %lu\n",
  7634. clang_getTUResourceUsageName(Usage.entries[I].kind),
  7635. Usage.entries[I].amount);
  7636. clang_disposeCXTUResourceUsage(Usage);
  7637. }
  7638. CXCursor clang_Cursor_getVarDeclInitializer(CXCursor cursor) {
  7639. const Decl *const D = getCursorDecl(cursor);
  7640. if (!D)
  7641. return clang_getNullCursor();
  7642. const auto *const VD = dyn_cast<VarDecl>(D);
  7643. if (!VD)
  7644. return clang_getNullCursor();
  7645. const Expr *const Init = VD->getInit();
  7646. if (!Init)
  7647. return clang_getNullCursor();
  7648. return cxcursor::MakeCXCursor(Init, VD, cxcursor::getCursorTU(cursor));
  7649. }
  7650. int clang_Cursor_hasVarDeclGlobalStorage(CXCursor cursor) {
  7651. const Decl *const D = getCursorDecl(cursor);
  7652. if (!D)
  7653. return -1;
  7654. const auto *const VD = dyn_cast<VarDecl>(D);
  7655. if (!VD)
  7656. return -1;
  7657. return VD->hasGlobalStorage();
  7658. }
  7659. int clang_Cursor_hasVarDeclExternalStorage(CXCursor cursor) {
  7660. const Decl *const D = getCursorDecl(cursor);
  7661. if (!D)
  7662. return -1;
  7663. const auto *const VD = dyn_cast<VarDecl>(D);
  7664. if (!VD)
  7665. return -1;
  7666. return VD->hasExternalStorage();
  7667. }
  7668. //===----------------------------------------------------------------------===//
  7669. // Misc. utility functions.
  7670. //===----------------------------------------------------------------------===//
  7671. /// Default to using our desired 8 MB stack size on "safety" threads.
  7672. static unsigned SafetyStackThreadSize = DesiredStackSize;
  7673. namespace clang {
  7674. bool RunSafely(llvm::CrashRecoveryContext &CRC, llvm::function_ref<void()> Fn,
  7675. unsigned Size) {
  7676. if (!Size)
  7677. Size = GetSafetyThreadStackSize();
  7678. if (Size && !getenv("LIBCLANG_NOTHREADS"))
  7679. return CRC.RunSafelyOnThread(Fn, Size);
  7680. return CRC.RunSafely(Fn);
  7681. }
  7682. unsigned GetSafetyThreadStackSize() { return SafetyStackThreadSize; }
  7683. void SetSafetyThreadStackSize(unsigned Value) { SafetyStackThreadSize = Value; }
  7684. } // namespace clang
  7685. void clang::setThreadBackgroundPriority() {
  7686. if (getenv("LIBCLANG_BGPRIO_DISABLE"))
  7687. return;
  7688. #if LLVM_ENABLE_THREADS
  7689. llvm::set_thread_priority(llvm::ThreadPriority::Background);
  7690. #endif
  7691. }
  7692. void cxindex::printDiagsToStderr(ASTUnit *Unit) {
  7693. if (!Unit)
  7694. return;
  7695. for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
  7696. DEnd = Unit->stored_diag_end();
  7697. D != DEnd; ++D) {
  7698. CXStoredDiagnostic Diag(*D, Unit->getLangOpts());
  7699. CXString Msg =
  7700. clang_formatDiagnostic(&Diag, clang_defaultDiagnosticDisplayOptions());
  7701. fprintf(stderr, "%s\n", clang_getCString(Msg));
  7702. clang_disposeString(Msg);
  7703. }
  7704. #ifdef _WIN32
  7705. // On Windows, force a flush, since there may be multiple copies of
  7706. // stderr and stdout in the file system, all with different buffers
  7707. // but writing to the same device.
  7708. fflush(stderr);
  7709. #endif
  7710. }
  7711. MacroInfo *cxindex::getMacroInfo(const IdentifierInfo &II,
  7712. SourceLocation MacroDefLoc,
  7713. CXTranslationUnit TU) {
  7714. if (MacroDefLoc.isInvalid() || !TU)
  7715. return nullptr;
  7716. if (!II.hadMacroDefinition())
  7717. return nullptr;
  7718. ASTUnit *Unit = cxtu::getASTUnit(TU);
  7719. Preprocessor &PP = Unit->getPreprocessor();
  7720. MacroDirective *MD = PP.getLocalMacroDirectiveHistory(&II);
  7721. if (MD) {
  7722. for (MacroDirective::DefInfo Def = MD->getDefinition(); Def;
  7723. Def = Def.getPreviousDefinition()) {
  7724. if (MacroDefLoc == Def.getMacroInfo()->getDefinitionLoc())
  7725. return Def.getMacroInfo();
  7726. }
  7727. }
  7728. return nullptr;
  7729. }
  7730. const MacroInfo *cxindex::getMacroInfo(const MacroDefinitionRecord *MacroDef,
  7731. CXTranslationUnit TU) {
  7732. if (!MacroDef || !TU)
  7733. return nullptr;
  7734. const IdentifierInfo *II = MacroDef->getName();
  7735. if (!II)
  7736. return nullptr;
  7737. return getMacroInfo(*II, MacroDef->getLocation(), TU);
  7738. }
  7739. MacroDefinitionRecord *
  7740. cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, const Token &Tok,
  7741. CXTranslationUnit TU) {
  7742. if (!MI || !TU)
  7743. return nullptr;
  7744. if (Tok.isNot(tok::raw_identifier))
  7745. return nullptr;
  7746. if (MI->getNumTokens() == 0)
  7747. return nullptr;
  7748. SourceRange DefRange(MI->getReplacementToken(0).getLocation(),
  7749. MI->getDefinitionEndLoc());
  7750. ASTUnit *Unit = cxtu::getASTUnit(TU);
  7751. // Check that the token is inside the definition and not its argument list.
  7752. SourceManager &SM = Unit->getSourceManager();
  7753. if (SM.isBeforeInTranslationUnit(Tok.getLocation(), DefRange.getBegin()))
  7754. return nullptr;
  7755. if (SM.isBeforeInTranslationUnit(DefRange.getEnd(), Tok.getLocation()))
  7756. return nullptr;
  7757. Preprocessor &PP = Unit->getPreprocessor();
  7758. PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
  7759. if (!PPRec)
  7760. return nullptr;
  7761. IdentifierInfo &II = PP.getIdentifierTable().get(Tok.getRawIdentifier());
  7762. if (!II.hadMacroDefinition())
  7763. return nullptr;
  7764. // Check that the identifier is not one of the macro arguments.
  7765. if (llvm::is_contained(MI->params(), &II))
  7766. return nullptr;
  7767. MacroDirective *InnerMD = PP.getLocalMacroDirectiveHistory(&II);
  7768. if (!InnerMD)
  7769. return nullptr;
  7770. return PPRec->findMacroDefinition(InnerMD->getMacroInfo());
  7771. }
  7772. MacroDefinitionRecord *
  7773. cxindex::checkForMacroInMacroDefinition(const MacroInfo *MI, SourceLocation Loc,
  7774. CXTranslationUnit TU) {
  7775. if (Loc.isInvalid() || !MI || !TU)
  7776. return nullptr;
  7777. if (MI->getNumTokens() == 0)
  7778. return nullptr;
  7779. ASTUnit *Unit = cxtu::getASTUnit(TU);
  7780. Preprocessor &PP = Unit->getPreprocessor();
  7781. if (!PP.getPreprocessingRecord())
  7782. return nullptr;
  7783. Loc = Unit->getSourceManager().getSpellingLoc(Loc);
  7784. Token Tok;
  7785. if (PP.getRawToken(Loc, Tok))
  7786. return nullptr;
  7787. return checkForMacroInMacroDefinition(MI, Tok, TU);
  7788. }
  7789. CXString clang_getClangVersion() {
  7790. return cxstring::createDup(getClangFullVersion());
  7791. }
  7792. Logger &cxindex::Logger::operator<<(CXTranslationUnit TU) {
  7793. if (TU) {
  7794. if (ASTUnit *Unit = cxtu::getASTUnit(TU)) {
  7795. LogOS << '<' << Unit->getMainFileName() << '>';
  7796. if (Unit->isMainFileAST())
  7797. LogOS << " (" << Unit->getASTFileName() << ')';
  7798. return *this;
  7799. }
  7800. } else {
  7801. LogOS << "<NULL TU>";
  7802. }
  7803. return *this;
  7804. }
  7805. Logger &cxindex::Logger::operator<<(const FileEntry *FE) {
  7806. *this << FE->getName();
  7807. return *this;
  7808. }
  7809. Logger &cxindex::Logger::operator<<(CXCursor cursor) {
  7810. CXString cursorName = clang_getCursorDisplayName(cursor);
  7811. *this << cursorName << "@" << clang_getCursorLocation(cursor);
  7812. clang_disposeString(cursorName);
  7813. return *this;
  7814. }
  7815. Logger &cxindex::Logger::operator<<(CXSourceLocation Loc) {
  7816. CXFile File;
  7817. unsigned Line, Column;
  7818. clang_getFileLocation(Loc, &File, &Line, &Column, nullptr);
  7819. CXString FileName = clang_getFileName(File);
  7820. *this << llvm::format("(%s:%d:%d)", clang_getCString(FileName), Line, Column);
  7821. clang_disposeString(FileName);
  7822. return *this;
  7823. }
  7824. Logger &cxindex::Logger::operator<<(CXSourceRange range) {
  7825. CXSourceLocation BLoc = clang_getRangeStart(range);
  7826. CXSourceLocation ELoc = clang_getRangeEnd(range);
  7827. CXFile BFile;
  7828. unsigned BLine, BColumn;
  7829. clang_getFileLocation(BLoc, &BFile, &BLine, &BColumn, nullptr);
  7830. CXFile EFile;
  7831. unsigned ELine, EColumn;
  7832. clang_getFileLocation(ELoc, &EFile, &ELine, &EColumn, nullptr);
  7833. CXString BFileName = clang_getFileName(BFile);
  7834. if (BFile == EFile) {
  7835. *this << llvm::format("[%s %d:%d-%d:%d]", clang_getCString(BFileName),
  7836. BLine, BColumn, ELine, EColumn);
  7837. } else {
  7838. CXString EFileName = clang_getFileName(EFile);
  7839. *this << llvm::format("[%s:%d:%d - ", clang_getCString(BFileName), BLine,
  7840. BColumn)
  7841. << llvm::format("%s:%d:%d]", clang_getCString(EFileName), ELine,
  7842. EColumn);
  7843. clang_disposeString(EFileName);
  7844. }
  7845. clang_disposeString(BFileName);
  7846. return *this;
  7847. }
  7848. Logger &cxindex::Logger::operator<<(CXString Str) {
  7849. *this << clang_getCString(Str);
  7850. return *this;
  7851. }
  7852. Logger &cxindex::Logger::operator<<(const llvm::format_object_base &Fmt) {
  7853. LogOS << Fmt;
  7854. return *this;
  7855. }
  7856. static llvm::ManagedStatic<std::mutex> LoggingMutex;
  7857. cxindex::Logger::~Logger() {
  7858. std::lock_guard<std::mutex> L(*LoggingMutex);
  7859. static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();
  7860. raw_ostream &OS = llvm::errs();
  7861. OS << "[libclang:" << Name << ':';
  7862. #ifdef USE_DARWIN_THREADS
  7863. // TODO: Portability.
  7864. mach_port_t tid = pthread_mach_thread_np(pthread_self());
  7865. OS << tid << ':';
  7866. #endif
  7867. llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
  7868. OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
  7869. OS << Msg << '\n';
  7870. if (Trace) {
  7871. llvm::sys::PrintStackTrace(OS);
  7872. OS << "--------------------------------------------------\n";
  7873. }
  7874. }