CIndex.cpp 301 KB

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