CIndex.cpp 301 KB

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