CIndex.cpp 302 KB

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