CIndex.cpp 292 KB

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