CIndex.cpp 301 KB

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