c-index-test.c 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955
  1. /* c-index-test.c */
  2. #include "clang/Config/config.h"
  3. #include "clang-c/Index.h"
  4. #include "clang-c/CXCompilationDatabase.h"
  5. #include "clang-c/BuildSystem.h"
  6. #include "clang-c/Documentation.h"
  7. #include <ctype.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <assert.h>
  12. #ifdef CLANG_HAVE_LIBXML
  13. #include <libxml/parser.h>
  14. #include <libxml/relaxng.h>
  15. #include <libxml/xmlerror.h>
  16. #endif
  17. #ifdef _WIN32
  18. # include <direct.h>
  19. #else
  20. # include <unistd.h>
  21. #endif
  22. extern int indextest_core_main(int argc, const char **argv);
  23. /******************************************************************************/
  24. /* Utility functions. */
  25. /******************************************************************************/
  26. #ifdef _MSC_VER
  27. char *basename(const char* path)
  28. {
  29. char* base1 = (char*)strrchr(path, '/');
  30. char* base2 = (char*)strrchr(path, '\\');
  31. if (base1 && base2)
  32. return((base1 > base2) ? base1 + 1 : base2 + 1);
  33. else if (base1)
  34. return(base1 + 1);
  35. else if (base2)
  36. return(base2 + 1);
  37. return((char*)path);
  38. }
  39. char *dirname(char* path)
  40. {
  41. char* base1 = (char*)strrchr(path, '/');
  42. char* base2 = (char*)strrchr(path, '\\');
  43. if (base1 && base2)
  44. if (base1 > base2)
  45. *base1 = 0;
  46. else
  47. *base2 = 0;
  48. else if (base1)
  49. *base1 = 0;
  50. else if (base2)
  51. *base2 = 0;
  52. return path;
  53. }
  54. #else
  55. extern char *basename(const char *);
  56. extern char *dirname(char *);
  57. #endif
  58. /** Return the default parsing options. */
  59. static unsigned getDefaultParsingOptions() {
  60. unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
  61. if (getenv("CINDEXTEST_EDITING"))
  62. options |= clang_defaultEditingTranslationUnitOptions();
  63. if (getenv("CINDEXTEST_COMPLETION_CACHING"))
  64. options |= CXTranslationUnit_CacheCompletionResults;
  65. if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
  66. options &= ~CXTranslationUnit_CacheCompletionResults;
  67. if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
  68. options |= CXTranslationUnit_SkipFunctionBodies;
  69. if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
  70. options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
  71. if (getenv("CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
  72. options |= CXTranslationUnit_CreatePreambleOnFirstParse;
  73. if (getenv("CINDEXTEST_KEEP_GOING"))
  74. options |= CXTranslationUnit_KeepGoing;
  75. if (getenv("CINDEXTEST_LIMIT_SKIP_FUNCTION_BODIES_TO_PREAMBLE"))
  76. options |= CXTranslationUnit_LimitSkipFunctionBodiesToPreamble;
  77. if (getenv("CINDEXTEST_INCLUDE_ATTRIBUTED_TYPES"))
  78. options |= CXTranslationUnit_IncludeAttributedTypes;
  79. if (getenv("CINDEXTEST_VISIT_IMPLICIT_ATTRIBUTES"))
  80. options |= CXTranslationUnit_VisitImplicitAttributes;
  81. if (getenv("CINDEXTEST_IGNORE_NONERRORS_FROM_INCLUDED_FILES"))
  82. options |= CXTranslationUnit_IgnoreNonErrorsFromIncludedFiles;
  83. return options;
  84. }
  85. static void ModifyPrintingPolicyAccordingToEnv(CXPrintingPolicy Policy) {
  86. struct Mapping {
  87. const char *name;
  88. enum CXPrintingPolicyProperty property;
  89. };
  90. struct Mapping mappings[] = {
  91. {"CINDEXTEST_PRINTINGPOLICY_INDENTATION", CXPrintingPolicy_Indentation},
  92. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSPECIFIERS",
  93. CXPrintingPolicy_SuppressSpecifiers},
  94. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTAGKEYWORD",
  95. CXPrintingPolicy_SuppressTagKeyword},
  96. {"CINDEXTEST_PRINTINGPOLICY_INCLUDETAGDEFINITION",
  97. CXPrintingPolicy_IncludeTagDefinition},
  98. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSCOPE",
  99. CXPrintingPolicy_SuppressScope},
  100. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSUNWRITTENSCOPE",
  101. CXPrintingPolicy_SuppressUnwrittenScope},
  102. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSINITIALIZERS",
  103. CXPrintingPolicy_SuppressInitializers},
  104. {"CINDEXTEST_PRINTINGPOLICY_CONSTANTARRAYSIZEASWRITTEN",
  105. CXPrintingPolicy_ConstantArraySizeAsWritten},
  106. {"CINDEXTEST_PRINTINGPOLICY_ANONYMOUSTAGLOCATIONS",
  107. CXPrintingPolicy_AnonymousTagLocations},
  108. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSSTRONGLIFETIME",
  109. CXPrintingPolicy_SuppressStrongLifetime},
  110. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSLIFETIMEQUALIFIERS",
  111. CXPrintingPolicy_SuppressLifetimeQualifiers},
  112. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSTEMPLATEARGSINCXXCONSTRUCTORS",
  113. CXPrintingPolicy_SuppressTemplateArgsInCXXConstructors},
  114. {"CINDEXTEST_PRINTINGPOLICY_BOOL", CXPrintingPolicy_Bool},
  115. {"CINDEXTEST_PRINTINGPOLICY_RESTRICT", CXPrintingPolicy_Restrict},
  116. {"CINDEXTEST_PRINTINGPOLICY_ALIGNOF", CXPrintingPolicy_Alignof},
  117. {"CINDEXTEST_PRINTINGPOLICY_UNDERSCOREALIGNOF",
  118. CXPrintingPolicy_UnderscoreAlignof},
  119. {"CINDEXTEST_PRINTINGPOLICY_USEVOIDFORZEROPARAMS",
  120. CXPrintingPolicy_UseVoidForZeroParams},
  121. {"CINDEXTEST_PRINTINGPOLICY_TERSEOUTPUT", CXPrintingPolicy_TerseOutput},
  122. {"CINDEXTEST_PRINTINGPOLICY_POLISHFORDECLARATION",
  123. CXPrintingPolicy_PolishForDeclaration},
  124. {"CINDEXTEST_PRINTINGPOLICY_HALF", CXPrintingPolicy_Half},
  125. {"CINDEXTEST_PRINTINGPOLICY_MSWCHAR", CXPrintingPolicy_MSWChar},
  126. {"CINDEXTEST_PRINTINGPOLICY_INCLUDENEWLINES",
  127. CXPrintingPolicy_IncludeNewlines},
  128. {"CINDEXTEST_PRINTINGPOLICY_MSVCFORMATTING",
  129. CXPrintingPolicy_MSVCFormatting},
  130. {"CINDEXTEST_PRINTINGPOLICY_CONSTANTSASWRITTEN",
  131. CXPrintingPolicy_ConstantsAsWritten},
  132. {"CINDEXTEST_PRINTINGPOLICY_SUPPRESSIMPLICITBASE",
  133. CXPrintingPolicy_SuppressImplicitBase},
  134. {"CINDEXTEST_PRINTINGPOLICY_FULLYQUALIFIEDNAME",
  135. CXPrintingPolicy_FullyQualifiedName},
  136. };
  137. unsigned i;
  138. for (i = 0; i < sizeof(mappings) / sizeof(struct Mapping); i++) {
  139. char *value = getenv(mappings[i].name);
  140. if (value) {
  141. clang_PrintingPolicy_setProperty(Policy, mappings[i].property,
  142. (unsigned)strtoul(value, 0L, 10));
  143. }
  144. }
  145. }
  146. /** Returns 0 in case of success, non-zero in case of a failure. */
  147. static int checkForErrors(CXTranslationUnit TU);
  148. static void describeLibclangFailure(enum CXErrorCode Err) {
  149. switch (Err) {
  150. case CXError_Success:
  151. fprintf(stderr, "Success\n");
  152. return;
  153. case CXError_Failure:
  154. fprintf(stderr, "Failure (no details available)\n");
  155. return;
  156. case CXError_Crashed:
  157. fprintf(stderr, "Failure: libclang crashed\n");
  158. return;
  159. case CXError_InvalidArguments:
  160. fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
  161. return;
  162. case CXError_ASTReadError:
  163. fprintf(stderr, "Failure: AST deserialization error occurred\n");
  164. return;
  165. }
  166. }
  167. static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
  168. unsigned end_line, unsigned end_column) {
  169. fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
  170. end_line, end_column);
  171. }
  172. static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
  173. CXTranslationUnit *TU) {
  174. enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
  175. if (Err != CXError_Success) {
  176. fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
  177. describeLibclangFailure(Err);
  178. *TU = 0;
  179. return 0;
  180. }
  181. return 1;
  182. }
  183. void free_remapped_files(struct CXUnsavedFile *unsaved_files,
  184. int num_unsaved_files) {
  185. int i;
  186. for (i = 0; i != num_unsaved_files; ++i) {
  187. free((char *)unsaved_files[i].Filename);
  188. free((char *)unsaved_files[i].Contents);
  189. }
  190. free(unsaved_files);
  191. }
  192. static int parse_remapped_files_with_opt(const char *opt_name,
  193. int argc, const char **argv,
  194. int start_arg,
  195. struct CXUnsavedFile **unsaved_files,
  196. int *num_unsaved_files) {
  197. int i;
  198. int arg;
  199. int prefix_len = strlen(opt_name);
  200. int arg_indices[20];
  201. *unsaved_files = 0;
  202. *num_unsaved_files = 0;
  203. /* Count the number of remapped files. */
  204. for (arg = start_arg; arg < argc; ++arg) {
  205. if (strncmp(argv[arg], opt_name, prefix_len))
  206. continue;
  207. assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
  208. arg_indices[*num_unsaved_files] = arg;
  209. ++*num_unsaved_files;
  210. }
  211. if (*num_unsaved_files == 0)
  212. return 0;
  213. *unsaved_files
  214. = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
  215. *num_unsaved_files);
  216. assert(*unsaved_files);
  217. for (i = 0; i != *num_unsaved_files; ++i) {
  218. struct CXUnsavedFile *unsaved = *unsaved_files + i;
  219. const char *arg_string = argv[arg_indices[i]] + prefix_len;
  220. int filename_len;
  221. char *filename;
  222. char *contents;
  223. FILE *to_file;
  224. const char *sep = strchr(arg_string, ',');
  225. if (!sep) {
  226. fprintf(stderr,
  227. "error: %sfrom:to argument is missing comma\n", opt_name);
  228. free_remapped_files(*unsaved_files, i);
  229. *unsaved_files = 0;
  230. *num_unsaved_files = 0;
  231. return -1;
  232. }
  233. /* Open the file that we're remapping to. */
  234. to_file = fopen(sep + 1, "rb");
  235. if (!to_file) {
  236. fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
  237. sep + 1);
  238. free_remapped_files(*unsaved_files, i);
  239. *unsaved_files = 0;
  240. *num_unsaved_files = 0;
  241. return -1;
  242. }
  243. /* Determine the length of the file we're remapping to. */
  244. fseek(to_file, 0, SEEK_END);
  245. unsaved->Length = ftell(to_file);
  246. fseek(to_file, 0, SEEK_SET);
  247. /* Read the contents of the file we're remapping to. */
  248. contents = (char *)malloc(unsaved->Length + 1);
  249. assert(contents);
  250. if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
  251. fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
  252. (feof(to_file) ? "EOF" : "error"), sep + 1);
  253. fclose(to_file);
  254. free_remapped_files(*unsaved_files, i);
  255. free(contents);
  256. *unsaved_files = 0;
  257. *num_unsaved_files = 0;
  258. return -1;
  259. }
  260. contents[unsaved->Length] = 0;
  261. unsaved->Contents = contents;
  262. /* Close the file. */
  263. fclose(to_file);
  264. /* Copy the file name that we're remapping from. */
  265. filename_len = sep - arg_string;
  266. filename = (char *)malloc(filename_len + 1);
  267. assert(filename);
  268. memcpy(filename, arg_string, filename_len);
  269. filename[filename_len] = 0;
  270. unsaved->Filename = filename;
  271. }
  272. return 0;
  273. }
  274. static int parse_remapped_files(int argc, const char **argv, int start_arg,
  275. struct CXUnsavedFile **unsaved_files,
  276. int *num_unsaved_files) {
  277. return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
  278. unsaved_files, num_unsaved_files);
  279. }
  280. static int parse_remapped_files_with_try(int try_idx,
  281. int argc, const char **argv,
  282. int start_arg,
  283. struct CXUnsavedFile **unsaved_files,
  284. int *num_unsaved_files) {
  285. struct CXUnsavedFile *unsaved_files_no_try_idx;
  286. int num_unsaved_files_no_try_idx;
  287. struct CXUnsavedFile *unsaved_files_try_idx;
  288. int num_unsaved_files_try_idx;
  289. int ret;
  290. char opt_name[32];
  291. ret = parse_remapped_files(argc, argv, start_arg,
  292. &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
  293. if (ret)
  294. return ret;
  295. sprintf(opt_name, "-remap-file-%d=", try_idx);
  296. ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
  297. &unsaved_files_try_idx, &num_unsaved_files_try_idx);
  298. if (ret)
  299. return ret;
  300. if (num_unsaved_files_no_try_idx == 0) {
  301. *unsaved_files = unsaved_files_try_idx;
  302. *num_unsaved_files = num_unsaved_files_try_idx;
  303. return 0;
  304. }
  305. if (num_unsaved_files_try_idx == 0) {
  306. *unsaved_files = unsaved_files_no_try_idx;
  307. *num_unsaved_files = num_unsaved_files_no_try_idx;
  308. return 0;
  309. }
  310. *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
  311. *unsaved_files
  312. = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
  313. sizeof(struct CXUnsavedFile) *
  314. *num_unsaved_files);
  315. assert(*unsaved_files);
  316. memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
  317. unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
  318. num_unsaved_files_try_idx);
  319. free(unsaved_files_try_idx);
  320. return 0;
  321. }
  322. static const char *parse_comments_schema(int argc, const char **argv) {
  323. const char *CommentsSchemaArg = "-comments-xml-schema=";
  324. const char *CommentSchemaFile = NULL;
  325. if (argc == 0)
  326. return CommentSchemaFile;
  327. if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
  328. CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
  329. return CommentSchemaFile;
  330. }
  331. /******************************************************************************/
  332. /* Pretty-printing. */
  333. /******************************************************************************/
  334. static const char *FileCheckPrefix = "CHECK";
  335. static void PrintCString(const char *CStr) {
  336. if (CStr != NULL && CStr[0] != '\0') {
  337. for ( ; *CStr; ++CStr) {
  338. const char C = *CStr;
  339. switch (C) {
  340. case '\n': printf("\\n"); break;
  341. case '\r': printf("\\r"); break;
  342. case '\t': printf("\\t"); break;
  343. case '\v': printf("\\v"); break;
  344. case '\f': printf("\\f"); break;
  345. default: putchar(C); break;
  346. }
  347. }
  348. }
  349. }
  350. static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
  351. printf(" %s=[", Prefix);
  352. PrintCString(CStr);
  353. printf("]");
  354. }
  355. static void PrintCXStringAndDispose(CXString Str) {
  356. PrintCString(clang_getCString(Str));
  357. clang_disposeString(Str);
  358. }
  359. static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
  360. PrintCStringWithPrefix(Prefix, clang_getCString(Str));
  361. }
  362. static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
  363. CXString Str) {
  364. PrintCStringWithPrefix(Prefix, clang_getCString(Str));
  365. clang_disposeString(Str);
  366. }
  367. static void PrintRange(CXSourceRange R, const char *str) {
  368. CXFile begin_file, end_file;
  369. unsigned begin_line, begin_column, end_line, end_column;
  370. clang_getSpellingLocation(clang_getRangeStart(R),
  371. &begin_file, &begin_line, &begin_column, 0);
  372. clang_getSpellingLocation(clang_getRangeEnd(R),
  373. &end_file, &end_line, &end_column, 0);
  374. if (!begin_file || !end_file)
  375. return;
  376. if (str)
  377. printf(" %s=", str);
  378. PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
  379. }
  380. static enum DisplayType {
  381. DisplayType_Spelling,
  382. DisplayType_DisplayName,
  383. DisplayType_Pretty
  384. } wanted_display_type = DisplayType_Spelling;
  385. static void printVersion(const char *Prefix, CXVersion Version) {
  386. if (Version.Major < 0)
  387. return;
  388. printf("%s%d", Prefix, Version.Major);
  389. if (Version.Minor < 0)
  390. return;
  391. printf(".%d", Version.Minor);
  392. if (Version.Subminor < 0)
  393. return;
  394. printf(".%d", Version.Subminor);
  395. }
  396. struct CommentASTDumpingContext {
  397. int IndentLevel;
  398. };
  399. static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
  400. CXComment Comment) {
  401. unsigned i;
  402. unsigned e;
  403. enum CXCommentKind Kind = clang_Comment_getKind(Comment);
  404. Ctx->IndentLevel++;
  405. for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
  406. printf(" ");
  407. printf("(");
  408. switch (Kind) {
  409. case CXComment_Null:
  410. printf("CXComment_Null");
  411. break;
  412. case CXComment_Text:
  413. printf("CXComment_Text");
  414. PrintCXStringWithPrefixAndDispose("Text",
  415. clang_TextComment_getText(Comment));
  416. if (clang_Comment_isWhitespace(Comment))
  417. printf(" IsWhitespace");
  418. if (clang_InlineContentComment_hasTrailingNewline(Comment))
  419. printf(" HasTrailingNewline");
  420. break;
  421. case CXComment_InlineCommand:
  422. printf("CXComment_InlineCommand");
  423. PrintCXStringWithPrefixAndDispose(
  424. "CommandName",
  425. clang_InlineCommandComment_getCommandName(Comment));
  426. switch (clang_InlineCommandComment_getRenderKind(Comment)) {
  427. case CXCommentInlineCommandRenderKind_Normal:
  428. printf(" RenderNormal");
  429. break;
  430. case CXCommentInlineCommandRenderKind_Bold:
  431. printf(" RenderBold");
  432. break;
  433. case CXCommentInlineCommandRenderKind_Monospaced:
  434. printf(" RenderMonospaced");
  435. break;
  436. case CXCommentInlineCommandRenderKind_Emphasized:
  437. printf(" RenderEmphasized");
  438. break;
  439. }
  440. for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
  441. i != e; ++i) {
  442. printf(" Arg[%u]=", i);
  443. PrintCXStringAndDispose(
  444. clang_InlineCommandComment_getArgText(Comment, i));
  445. }
  446. if (clang_InlineContentComment_hasTrailingNewline(Comment))
  447. printf(" HasTrailingNewline");
  448. break;
  449. case CXComment_HTMLStartTag: {
  450. unsigned NumAttrs;
  451. printf("CXComment_HTMLStartTag");
  452. PrintCXStringWithPrefixAndDispose(
  453. "Name",
  454. clang_HTMLTagComment_getTagName(Comment));
  455. NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
  456. if (NumAttrs != 0) {
  457. printf(" Attrs:");
  458. for (i = 0; i != NumAttrs; ++i) {
  459. printf(" ");
  460. PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
  461. printf("=");
  462. PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
  463. }
  464. }
  465. if (clang_HTMLStartTagComment_isSelfClosing(Comment))
  466. printf(" SelfClosing");
  467. if (clang_InlineContentComment_hasTrailingNewline(Comment))
  468. printf(" HasTrailingNewline");
  469. break;
  470. }
  471. case CXComment_HTMLEndTag:
  472. printf("CXComment_HTMLEndTag");
  473. PrintCXStringWithPrefixAndDispose(
  474. "Name",
  475. clang_HTMLTagComment_getTagName(Comment));
  476. if (clang_InlineContentComment_hasTrailingNewline(Comment))
  477. printf(" HasTrailingNewline");
  478. break;
  479. case CXComment_Paragraph:
  480. printf("CXComment_Paragraph");
  481. if (clang_Comment_isWhitespace(Comment))
  482. printf(" IsWhitespace");
  483. break;
  484. case CXComment_BlockCommand:
  485. printf("CXComment_BlockCommand");
  486. PrintCXStringWithPrefixAndDispose(
  487. "CommandName",
  488. clang_BlockCommandComment_getCommandName(Comment));
  489. for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
  490. i != e; ++i) {
  491. printf(" Arg[%u]=", i);
  492. PrintCXStringAndDispose(
  493. clang_BlockCommandComment_getArgText(Comment, i));
  494. }
  495. break;
  496. case CXComment_ParamCommand:
  497. printf("CXComment_ParamCommand");
  498. switch (clang_ParamCommandComment_getDirection(Comment)) {
  499. case CXCommentParamPassDirection_In:
  500. printf(" in");
  501. break;
  502. case CXCommentParamPassDirection_Out:
  503. printf(" out");
  504. break;
  505. case CXCommentParamPassDirection_InOut:
  506. printf(" in,out");
  507. break;
  508. }
  509. if (clang_ParamCommandComment_isDirectionExplicit(Comment))
  510. printf(" explicitly");
  511. else
  512. printf(" implicitly");
  513. PrintCXStringWithPrefixAndDispose(
  514. "ParamName",
  515. clang_ParamCommandComment_getParamName(Comment));
  516. if (clang_ParamCommandComment_isParamIndexValid(Comment))
  517. printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
  518. else
  519. printf(" ParamIndex=Invalid");
  520. break;
  521. case CXComment_TParamCommand:
  522. printf("CXComment_TParamCommand");
  523. PrintCXStringWithPrefixAndDispose(
  524. "ParamName",
  525. clang_TParamCommandComment_getParamName(Comment));
  526. if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
  527. printf(" ParamPosition={");
  528. for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
  529. i != e; ++i) {
  530. printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
  531. if (i != e - 1)
  532. printf(", ");
  533. }
  534. printf("}");
  535. } else
  536. printf(" ParamPosition=Invalid");
  537. break;
  538. case CXComment_VerbatimBlockCommand:
  539. printf("CXComment_VerbatimBlockCommand");
  540. PrintCXStringWithPrefixAndDispose(
  541. "CommandName",
  542. clang_BlockCommandComment_getCommandName(Comment));
  543. break;
  544. case CXComment_VerbatimBlockLine:
  545. printf("CXComment_VerbatimBlockLine");
  546. PrintCXStringWithPrefixAndDispose(
  547. "Text",
  548. clang_VerbatimBlockLineComment_getText(Comment));
  549. break;
  550. case CXComment_VerbatimLine:
  551. printf("CXComment_VerbatimLine");
  552. PrintCXStringWithPrefixAndDispose(
  553. "Text",
  554. clang_VerbatimLineComment_getText(Comment));
  555. break;
  556. case CXComment_FullComment:
  557. printf("CXComment_FullComment");
  558. break;
  559. }
  560. if (Kind != CXComment_Null) {
  561. const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
  562. unsigned i;
  563. for (i = 0; i != NumChildren; ++i) {
  564. printf("\n// %s: ", FileCheckPrefix);
  565. DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
  566. }
  567. }
  568. printf(")");
  569. Ctx->IndentLevel--;
  570. }
  571. static void DumpCXComment(CXComment Comment) {
  572. struct CommentASTDumpingContext Ctx;
  573. Ctx.IndentLevel = 1;
  574. printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
  575. DumpCXCommentInternal(&Ctx, Comment);
  576. printf("]");
  577. }
  578. static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
  579. #ifdef CLANG_HAVE_LIBXML
  580. xmlRelaxNGParserCtxtPtr RNGParser;
  581. xmlRelaxNGPtr Schema;
  582. xmlDocPtr Doc;
  583. xmlRelaxNGValidCtxtPtr ValidationCtxt;
  584. int status;
  585. if (!CommentSchemaFile)
  586. return;
  587. RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
  588. if (!RNGParser) {
  589. printf(" libXMLError");
  590. return;
  591. }
  592. Schema = xmlRelaxNGParse(RNGParser);
  593. Doc = xmlParseDoc((const xmlChar *) Str);
  594. if (!Doc) {
  595. xmlErrorPtr Error = xmlGetLastError();
  596. printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
  597. return;
  598. }
  599. ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
  600. status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
  601. if (!status)
  602. printf(" CommentXMLValid");
  603. else if (status > 0) {
  604. xmlErrorPtr Error = xmlGetLastError();
  605. printf(" CommentXMLInvalid [not valid XML: %s]", Error->message);
  606. } else
  607. printf(" libXMLError");
  608. xmlRelaxNGFreeValidCtxt(ValidationCtxt);
  609. xmlFreeDoc(Doc);
  610. xmlRelaxNGFree(Schema);
  611. xmlRelaxNGFreeParserCtxt(RNGParser);
  612. #endif
  613. }
  614. static void PrintCursorComments(CXCursor Cursor,
  615. const char *CommentSchemaFile) {
  616. {
  617. CXString RawComment;
  618. const char *RawCommentCString;
  619. CXString BriefComment;
  620. const char *BriefCommentCString;
  621. RawComment = clang_Cursor_getRawCommentText(Cursor);
  622. RawCommentCString = clang_getCString(RawComment);
  623. if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
  624. PrintCStringWithPrefix("RawComment", RawCommentCString);
  625. PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
  626. BriefComment = clang_Cursor_getBriefCommentText(Cursor);
  627. BriefCommentCString = clang_getCString(BriefComment);
  628. if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
  629. PrintCStringWithPrefix("BriefComment", BriefCommentCString);
  630. clang_disposeString(BriefComment);
  631. }
  632. clang_disposeString(RawComment);
  633. }
  634. {
  635. CXComment Comment = clang_Cursor_getParsedComment(Cursor);
  636. if (clang_Comment_getKind(Comment) != CXComment_Null) {
  637. PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
  638. clang_FullComment_getAsHTML(Comment));
  639. {
  640. CXString XML;
  641. XML = clang_FullComment_getAsXML(Comment);
  642. PrintCXStringWithPrefix("FullCommentAsXML", XML);
  643. ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
  644. clang_disposeString(XML);
  645. }
  646. DumpCXComment(Comment);
  647. }
  648. }
  649. }
  650. typedef struct {
  651. unsigned line;
  652. unsigned col;
  653. } LineCol;
  654. static int lineCol_cmp(const void *p1, const void *p2) {
  655. const LineCol *lhs = p1;
  656. const LineCol *rhs = p2;
  657. if (lhs->line != rhs->line)
  658. return (int)lhs->line - (int)rhs->line;
  659. return (int)lhs->col - (int)rhs->col;
  660. }
  661. static CXString CursorToText(CXCursor Cursor) {
  662. CXString text;
  663. switch (wanted_display_type) {
  664. case DisplayType_Spelling:
  665. return clang_getCursorSpelling(Cursor);
  666. case DisplayType_DisplayName:
  667. return clang_getCursorDisplayName(Cursor);
  668. case DisplayType_Pretty: {
  669. CXPrintingPolicy Policy = clang_getCursorPrintingPolicy(Cursor);
  670. ModifyPrintingPolicyAccordingToEnv(Policy);
  671. text = clang_getCursorPrettyPrinted(Cursor, Policy);
  672. clang_PrintingPolicy_dispose(Policy);
  673. return text;
  674. }
  675. }
  676. assert(0 && "unknown display type"); /* no llvm_unreachable in C. */
  677. /* Set to NULL to prevent uninitialized variable warnings. */
  678. text.data = NULL;
  679. text.private_flags = 0;
  680. return text;
  681. }
  682. static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
  683. CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
  684. if (clang_isInvalid(Cursor.kind)) {
  685. CXString ks = clang_getCursorKindSpelling(Cursor.kind);
  686. printf("Invalid Cursor => %s", clang_getCString(ks));
  687. clang_disposeString(ks);
  688. }
  689. else {
  690. CXString string, ks;
  691. CXCursor Referenced;
  692. unsigned line, column;
  693. CXCursor SpecializationOf;
  694. CXCursor *overridden;
  695. unsigned num_overridden;
  696. unsigned RefNameRangeNr;
  697. CXSourceRange CursorExtent;
  698. CXSourceRange RefNameRange;
  699. int AlwaysUnavailable;
  700. int AlwaysDeprecated;
  701. CXString UnavailableMessage;
  702. CXString DeprecatedMessage;
  703. CXPlatformAvailability PlatformAvailability[2];
  704. int NumPlatformAvailability;
  705. int I;
  706. ks = clang_getCursorKindSpelling(Cursor.kind);
  707. string = CursorToText(Cursor);
  708. printf("%s=%s", clang_getCString(ks),
  709. clang_getCString(string));
  710. clang_disposeString(ks);
  711. clang_disposeString(string);
  712. Referenced = clang_getCursorReferenced(Cursor);
  713. if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
  714. if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
  715. unsigned I, N = clang_getNumOverloadedDecls(Referenced);
  716. printf("[");
  717. for (I = 0; I != N; ++I) {
  718. CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
  719. CXSourceLocation Loc;
  720. if (I)
  721. printf(", ");
  722. Loc = clang_getCursorLocation(Ovl);
  723. clang_getSpellingLocation(Loc, 0, &line, &column, 0);
  724. printf("%d:%d", line, column);
  725. }
  726. printf("]");
  727. } else {
  728. CXSourceLocation Loc = clang_getCursorLocation(Referenced);
  729. clang_getSpellingLocation(Loc, 0, &line, &column, 0);
  730. printf(":%d:%d", line, column);
  731. }
  732. if (clang_getCursorKind(Referenced) == CXCursor_TypedefDecl) {
  733. CXType T = clang_getCursorType(Referenced);
  734. if (clang_Type_isTransparentTagTypedef(T)) {
  735. CXType Underlying = clang_getTypedefDeclUnderlyingType(Referenced);
  736. CXString S = clang_getTypeSpelling(Underlying);
  737. printf(" (Transparent: %s)", clang_getCString(S));
  738. clang_disposeString(S);
  739. }
  740. }
  741. }
  742. if (clang_isCursorDefinition(Cursor))
  743. printf(" (Definition)");
  744. switch (clang_getCursorAvailability(Cursor)) {
  745. case CXAvailability_Available:
  746. break;
  747. case CXAvailability_Deprecated:
  748. printf(" (deprecated)");
  749. break;
  750. case CXAvailability_NotAvailable:
  751. printf(" (unavailable)");
  752. break;
  753. case CXAvailability_NotAccessible:
  754. printf(" (inaccessible)");
  755. break;
  756. }
  757. NumPlatformAvailability
  758. = clang_getCursorPlatformAvailability(Cursor,
  759. &AlwaysDeprecated,
  760. &DeprecatedMessage,
  761. &AlwaysUnavailable,
  762. &UnavailableMessage,
  763. PlatformAvailability, 2);
  764. if (AlwaysUnavailable) {
  765. printf(" (always unavailable: \"%s\")",
  766. clang_getCString(UnavailableMessage));
  767. } else if (AlwaysDeprecated) {
  768. printf(" (always deprecated: \"%s\")",
  769. clang_getCString(DeprecatedMessage));
  770. } else {
  771. for (I = 0; I != NumPlatformAvailability; ++I) {
  772. if (I >= 2)
  773. break;
  774. printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
  775. if (PlatformAvailability[I].Unavailable)
  776. printf(", unavailable");
  777. else {
  778. printVersion(", introduced=", PlatformAvailability[I].Introduced);
  779. printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
  780. printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
  781. }
  782. if (clang_getCString(PlatformAvailability[I].Message)[0])
  783. printf(", message=\"%s\"",
  784. clang_getCString(PlatformAvailability[I].Message));
  785. printf(")");
  786. }
  787. }
  788. for (I = 0; I != NumPlatformAvailability; ++I) {
  789. if (I >= 2)
  790. break;
  791. clang_disposeCXPlatformAvailability(PlatformAvailability + I);
  792. }
  793. clang_disposeString(DeprecatedMessage);
  794. clang_disposeString(UnavailableMessage);
  795. if (clang_CXXConstructor_isDefaultConstructor(Cursor))
  796. printf(" (default constructor)");
  797. if (clang_CXXConstructor_isMoveConstructor(Cursor))
  798. printf(" (move constructor)");
  799. if (clang_CXXConstructor_isCopyConstructor(Cursor))
  800. printf(" (copy constructor)");
  801. if (clang_CXXConstructor_isConvertingConstructor(Cursor))
  802. printf(" (converting constructor)");
  803. if (clang_CXXField_isMutable(Cursor))
  804. printf(" (mutable)");
  805. if (clang_CXXMethod_isDefaulted(Cursor))
  806. printf(" (defaulted)");
  807. if (clang_CXXMethod_isStatic(Cursor))
  808. printf(" (static)");
  809. if (clang_CXXMethod_isVirtual(Cursor))
  810. printf(" (virtual)");
  811. if (clang_CXXMethod_isConst(Cursor))
  812. printf(" (const)");
  813. if (clang_CXXMethod_isPureVirtual(Cursor))
  814. printf(" (pure)");
  815. if (clang_CXXRecord_isAbstract(Cursor))
  816. printf(" (abstract)");
  817. if (clang_EnumDecl_isScoped(Cursor))
  818. printf(" (scoped)");
  819. if (clang_Cursor_isVariadic(Cursor))
  820. printf(" (variadic)");
  821. if (clang_Cursor_isObjCOptional(Cursor))
  822. printf(" (@optional)");
  823. if (clang_isInvalidDeclaration(Cursor))
  824. printf(" (invalid)");
  825. switch (clang_getCursorExceptionSpecificationType(Cursor))
  826. {
  827. case CXCursor_ExceptionSpecificationKind_None:
  828. break;
  829. case CXCursor_ExceptionSpecificationKind_DynamicNone:
  830. printf(" (noexcept dynamic none)");
  831. break;
  832. case CXCursor_ExceptionSpecificationKind_Dynamic:
  833. printf(" (noexcept dynamic)");
  834. break;
  835. case CXCursor_ExceptionSpecificationKind_MSAny:
  836. printf(" (noexcept dynamic any)");
  837. break;
  838. case CXCursor_ExceptionSpecificationKind_BasicNoexcept:
  839. printf(" (noexcept)");
  840. break;
  841. case CXCursor_ExceptionSpecificationKind_ComputedNoexcept:
  842. printf(" (computed-noexcept)");
  843. break;
  844. case CXCursor_ExceptionSpecificationKind_Unevaluated:
  845. case CXCursor_ExceptionSpecificationKind_Uninstantiated:
  846. case CXCursor_ExceptionSpecificationKind_Unparsed:
  847. break;
  848. }
  849. {
  850. CXString language;
  851. CXString definedIn;
  852. unsigned generated;
  853. if (clang_Cursor_isExternalSymbol(Cursor, &language, &definedIn,
  854. &generated)) {
  855. printf(" (external lang: %s, defined: %s, gen: %d)",
  856. clang_getCString(language), clang_getCString(definedIn), generated);
  857. clang_disposeString(language);
  858. clang_disposeString(definedIn);
  859. }
  860. }
  861. if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
  862. CXType T =
  863. clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
  864. CXString S = clang_getTypeKindSpelling(T.kind);
  865. printf(" [IBOutletCollection=%s]", clang_getCString(S));
  866. clang_disposeString(S);
  867. }
  868. if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
  869. enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
  870. unsigned isVirtual = clang_isVirtualBase(Cursor);
  871. const char *accessStr = 0;
  872. switch (access) {
  873. case CX_CXXInvalidAccessSpecifier:
  874. accessStr = "invalid"; break;
  875. case CX_CXXPublic:
  876. accessStr = "public"; break;
  877. case CX_CXXProtected:
  878. accessStr = "protected"; break;
  879. case CX_CXXPrivate:
  880. accessStr = "private"; break;
  881. }
  882. printf(" [access=%s isVirtual=%s]", accessStr,
  883. isVirtual ? "true" : "false");
  884. }
  885. SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
  886. if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
  887. CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
  888. CXString Name = clang_getCursorSpelling(SpecializationOf);
  889. clang_getSpellingLocation(Loc, 0, &line, &column, 0);
  890. printf(" [Specialization of %s:%d:%d]",
  891. clang_getCString(Name), line, column);
  892. clang_disposeString(Name);
  893. if (Cursor.kind == CXCursor_FunctionDecl) {
  894. /* Collect the template parameter kinds from the base template. */
  895. int NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
  896. int I;
  897. if (NumTemplateArgs < 0) {
  898. printf(" [no template arg info]");
  899. }
  900. for (I = 0; I < NumTemplateArgs; I++) {
  901. enum CXTemplateArgumentKind TAK =
  902. clang_Cursor_getTemplateArgumentKind(Cursor, I);
  903. switch(TAK) {
  904. case CXTemplateArgumentKind_Type:
  905. {
  906. CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
  907. CXString S = clang_getTypeSpelling(T);
  908. printf(" [Template arg %d: kind: %d, type: %s]",
  909. I, TAK, clang_getCString(S));
  910. clang_disposeString(S);
  911. }
  912. break;
  913. case CXTemplateArgumentKind_Integral:
  914. printf(" [Template arg %d: kind: %d, intval: %lld]",
  915. I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
  916. break;
  917. default:
  918. printf(" [Template arg %d: kind: %d]\n", I, TAK);
  919. }
  920. }
  921. }
  922. }
  923. clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
  924. if (num_overridden) {
  925. unsigned I;
  926. LineCol lineCols[50];
  927. assert(num_overridden <= 50);
  928. printf(" [Overrides ");
  929. for (I = 0; I != num_overridden; ++I) {
  930. CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
  931. clang_getSpellingLocation(Loc, 0, &line, &column, 0);
  932. lineCols[I].line = line;
  933. lineCols[I].col = column;
  934. }
  935. /* Make the order of the override list deterministic. */
  936. qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
  937. for (I = 0; I != num_overridden; ++I) {
  938. if (I)
  939. printf(", ");
  940. printf("@%d:%d", lineCols[I].line, lineCols[I].col);
  941. }
  942. printf("]");
  943. clang_disposeOverriddenCursors(overridden);
  944. }
  945. if (Cursor.kind == CXCursor_InclusionDirective) {
  946. CXFile File = clang_getIncludedFile(Cursor);
  947. CXString Included = clang_getFileName(File);
  948. printf(" (%s)", clang_getCString(Included));
  949. clang_disposeString(Included);
  950. if (clang_isFileMultipleIncludeGuarded(TU, File))
  951. printf(" [multi-include guarded]");
  952. }
  953. CursorExtent = clang_getCursorExtent(Cursor);
  954. RefNameRange = clang_getCursorReferenceNameRange(Cursor,
  955. CXNameRange_WantQualifier
  956. | CXNameRange_WantSinglePiece
  957. | CXNameRange_WantTemplateArgs,
  958. 0);
  959. if (!clang_equalRanges(CursorExtent, RefNameRange))
  960. PrintRange(RefNameRange, "SingleRefName");
  961. for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
  962. RefNameRange = clang_getCursorReferenceNameRange(Cursor,
  963. CXNameRange_WantQualifier
  964. | CXNameRange_WantTemplateArgs,
  965. RefNameRangeNr);
  966. if (clang_equalRanges(clang_getNullRange(), RefNameRange))
  967. break;
  968. if (!clang_equalRanges(CursorExtent, RefNameRange))
  969. PrintRange(RefNameRange, "RefName");
  970. }
  971. PrintCursorComments(Cursor, CommentSchemaFile);
  972. {
  973. unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
  974. if (PropAttrs != CXObjCPropertyAttr_noattr) {
  975. printf(" [");
  976. #define PRINT_PROP_ATTR(A) \
  977. if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
  978. PRINT_PROP_ATTR(readonly);
  979. PRINT_PROP_ATTR(getter);
  980. PRINT_PROP_ATTR(assign);
  981. PRINT_PROP_ATTR(readwrite);
  982. PRINT_PROP_ATTR(retain);
  983. PRINT_PROP_ATTR(copy);
  984. PRINT_PROP_ATTR(nonatomic);
  985. PRINT_PROP_ATTR(setter);
  986. PRINT_PROP_ATTR(atomic);
  987. PRINT_PROP_ATTR(weak);
  988. PRINT_PROP_ATTR(strong);
  989. PRINT_PROP_ATTR(unsafe_unretained);
  990. PRINT_PROP_ATTR(class);
  991. printf("]");
  992. }
  993. }
  994. if (Cursor.kind == CXCursor_ObjCPropertyDecl) {
  995. CXString Name = clang_Cursor_getObjCPropertyGetterName(Cursor);
  996. CXString Spelling = clang_getCursorSpelling(Cursor);
  997. const char *CName = clang_getCString(Name);
  998. const char *CSpelling = clang_getCString(Spelling);
  999. if (CName && strcmp(CName, CSpelling)) {
  1000. printf(" (getter=%s)", CName);
  1001. }
  1002. clang_disposeString(Spelling);
  1003. clang_disposeString(Name);
  1004. }
  1005. if (Cursor.kind == CXCursor_ObjCPropertyDecl) {
  1006. CXString Name = clang_Cursor_getObjCPropertySetterName(Cursor);
  1007. CXString Spelling = clang_getCursorSpelling(Cursor);
  1008. const char *CName = clang_getCString(Name);
  1009. const char *CSpelling = clang_getCString(Spelling);
  1010. char *DefaultSetter = malloc(strlen(CSpelling) + 5);
  1011. sprintf(DefaultSetter, "set%s:", CSpelling);
  1012. DefaultSetter[3] &= ~(1 << 5); /* Make uppercase */
  1013. if (CName && strcmp(CName, DefaultSetter)) {
  1014. printf(" (setter=%s)", CName);
  1015. }
  1016. free(DefaultSetter);
  1017. clang_disposeString(Spelling);
  1018. clang_disposeString(Name);
  1019. }
  1020. {
  1021. unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
  1022. if (QT != CXObjCDeclQualifier_None) {
  1023. printf(" [");
  1024. #define PRINT_OBJC_QUAL(A) \
  1025. if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
  1026. PRINT_OBJC_QUAL(In);
  1027. PRINT_OBJC_QUAL(Inout);
  1028. PRINT_OBJC_QUAL(Out);
  1029. PRINT_OBJC_QUAL(Bycopy);
  1030. PRINT_OBJC_QUAL(Byref);
  1031. PRINT_OBJC_QUAL(Oneway);
  1032. printf("]");
  1033. }
  1034. }
  1035. }
  1036. }
  1037. static const char* GetCursorSource(CXCursor Cursor) {
  1038. CXSourceLocation Loc = clang_getCursorLocation(Cursor);
  1039. CXString source;
  1040. CXFile file;
  1041. clang_getExpansionLocation(Loc, &file, 0, 0, 0);
  1042. source = clang_getFileName(file);
  1043. if (!clang_getCString(source)) {
  1044. clang_disposeString(source);
  1045. return "<invalid loc>";
  1046. }
  1047. else {
  1048. const char *b = basename(clang_getCString(source));
  1049. clang_disposeString(source);
  1050. return b;
  1051. }
  1052. }
  1053. static CXString createCXString(const char *CS) {
  1054. CXString Str;
  1055. Str.data = (const void *) CS;
  1056. Str.private_flags = 0;
  1057. return Str;
  1058. }
  1059. /******************************************************************************/
  1060. /* Callbacks. */
  1061. /******************************************************************************/
  1062. typedef void (*PostVisitTU)(CXTranslationUnit);
  1063. void PrintDiagnostic(CXDiagnostic Diagnostic) {
  1064. FILE *out = stderr;
  1065. CXFile file;
  1066. CXString Msg;
  1067. unsigned display_opts = CXDiagnostic_DisplaySourceLocation
  1068. | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
  1069. | CXDiagnostic_DisplayOption;
  1070. unsigned i, num_fixits;
  1071. if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
  1072. return;
  1073. Msg = clang_formatDiagnostic(Diagnostic, display_opts);
  1074. fprintf(stderr, "%s\n", clang_getCString(Msg));
  1075. clang_disposeString(Msg);
  1076. clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
  1077. &file, 0, 0, 0);
  1078. if (!file)
  1079. return;
  1080. num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
  1081. fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
  1082. for (i = 0; i != num_fixits; ++i) {
  1083. CXSourceRange range;
  1084. CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
  1085. CXSourceLocation start = clang_getRangeStart(range);
  1086. CXSourceLocation end = clang_getRangeEnd(range);
  1087. unsigned start_line, start_column, end_line, end_column;
  1088. CXFile start_file, end_file;
  1089. clang_getSpellingLocation(start, &start_file, &start_line,
  1090. &start_column, 0);
  1091. clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
  1092. if (clang_equalLocations(start, end)) {
  1093. /* Insertion. */
  1094. if (start_file == file)
  1095. fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
  1096. clang_getCString(insertion_text), start_line, start_column);
  1097. } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
  1098. /* Removal. */
  1099. if (start_file == file && end_file == file) {
  1100. fprintf(out, "FIX-IT: Remove ");
  1101. PrintExtent(out, start_line, start_column, end_line, end_column);
  1102. fprintf(out, "\n");
  1103. }
  1104. } else {
  1105. /* Replacement. */
  1106. if (start_file == end_file) {
  1107. fprintf(out, "FIX-IT: Replace ");
  1108. PrintExtent(out, start_line, start_column, end_line, end_column);
  1109. fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
  1110. }
  1111. }
  1112. clang_disposeString(insertion_text);
  1113. }
  1114. }
  1115. void PrintDiagnosticSet(CXDiagnosticSet Set) {
  1116. int i = 0, n = clang_getNumDiagnosticsInSet(Set);
  1117. for ( ; i != n ; ++i) {
  1118. CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
  1119. CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
  1120. PrintDiagnostic(Diag);
  1121. if (ChildDiags)
  1122. PrintDiagnosticSet(ChildDiags);
  1123. }
  1124. }
  1125. void PrintDiagnostics(CXTranslationUnit TU) {
  1126. CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
  1127. PrintDiagnosticSet(TUSet);
  1128. clang_disposeDiagnosticSet(TUSet);
  1129. }
  1130. void PrintMemoryUsage(CXTranslationUnit TU) {
  1131. unsigned long total = 0;
  1132. unsigned i = 0;
  1133. CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
  1134. fprintf(stderr, "Memory usage:\n");
  1135. for (i = 0 ; i != usage.numEntries; ++i) {
  1136. const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
  1137. unsigned long amount = usage.entries[i].amount;
  1138. total += amount;
  1139. fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
  1140. ((double) amount)/(1024*1024));
  1141. }
  1142. fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
  1143. ((double) total)/(1024*1024));
  1144. clang_disposeCXTUResourceUsage(usage);
  1145. }
  1146. /******************************************************************************/
  1147. /* Logic for testing traversal. */
  1148. /******************************************************************************/
  1149. static void PrintCursorExtent(CXCursor C) {
  1150. CXSourceRange extent = clang_getCursorExtent(C);
  1151. PrintRange(extent, "Extent");
  1152. }
  1153. /* Data used by the visitors. */
  1154. typedef struct {
  1155. CXTranslationUnit TU;
  1156. enum CXCursorKind *Filter;
  1157. const char *CommentSchemaFile;
  1158. } VisitorData;
  1159. enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
  1160. CXCursor Parent,
  1161. CXClientData ClientData) {
  1162. VisitorData *Data = (VisitorData *)ClientData;
  1163. if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
  1164. CXSourceLocation Loc = clang_getCursorLocation(Cursor);
  1165. unsigned line, column;
  1166. clang_getSpellingLocation(Loc, 0, &line, &column, 0);
  1167. printf("// %s: %s:%d:%d: ", FileCheckPrefix,
  1168. GetCursorSource(Cursor), line, column);
  1169. PrintCursor(Cursor, Data->CommentSchemaFile);
  1170. PrintCursorExtent(Cursor);
  1171. if (clang_isDeclaration(Cursor.kind)) {
  1172. enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
  1173. const char *accessStr = 0;
  1174. switch (access) {
  1175. case CX_CXXInvalidAccessSpecifier: break;
  1176. case CX_CXXPublic:
  1177. accessStr = "public"; break;
  1178. case CX_CXXProtected:
  1179. accessStr = "protected"; break;
  1180. case CX_CXXPrivate:
  1181. accessStr = "private"; break;
  1182. }
  1183. if (accessStr)
  1184. printf(" [access=%s]", accessStr);
  1185. }
  1186. printf("\n");
  1187. return CXChildVisit_Recurse;
  1188. }
  1189. return CXChildVisit_Continue;
  1190. }
  1191. static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
  1192. CXCursor Parent,
  1193. CXClientData ClientData) {
  1194. const char *startBuf, *endBuf;
  1195. unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
  1196. CXCursor Ref;
  1197. VisitorData *Data = (VisitorData *)ClientData;
  1198. if (Cursor.kind != CXCursor_FunctionDecl ||
  1199. !clang_isCursorDefinition(Cursor))
  1200. return CXChildVisit_Continue;
  1201. clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
  1202. &startLine, &startColumn,
  1203. &endLine, &endColumn);
  1204. /* Probe the entire body, looking for both decls and refs. */
  1205. curLine = startLine;
  1206. curColumn = startColumn;
  1207. while (startBuf < endBuf) {
  1208. CXSourceLocation Loc;
  1209. CXFile file;
  1210. CXString source;
  1211. if (*startBuf == '\n') {
  1212. startBuf++;
  1213. curLine++;
  1214. curColumn = 1;
  1215. } else if (*startBuf != '\t')
  1216. curColumn++;
  1217. Loc = clang_getCursorLocation(Cursor);
  1218. clang_getSpellingLocation(Loc, &file, 0, 0, 0);
  1219. source = clang_getFileName(file);
  1220. if (clang_getCString(source)) {
  1221. CXSourceLocation RefLoc
  1222. = clang_getLocation(Data->TU, file, curLine, curColumn);
  1223. Ref = clang_getCursor(Data->TU, RefLoc);
  1224. if (Ref.kind == CXCursor_NoDeclFound) {
  1225. /* Nothing found here; that's fine. */
  1226. } else if (Ref.kind != CXCursor_FunctionDecl) {
  1227. printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
  1228. curLine, curColumn);
  1229. PrintCursor(Ref, Data->CommentSchemaFile);
  1230. printf("\n");
  1231. }
  1232. }
  1233. clang_disposeString(source);
  1234. startBuf++;
  1235. }
  1236. return CXChildVisit_Continue;
  1237. }
  1238. /******************************************************************************/
  1239. /* USR testing. */
  1240. /******************************************************************************/
  1241. enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
  1242. CXClientData ClientData) {
  1243. VisitorData *Data = (VisitorData *)ClientData;
  1244. if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
  1245. CXString USR = clang_getCursorUSR(C);
  1246. const char *cstr = clang_getCString(USR);
  1247. if (!cstr || cstr[0] == '\0') {
  1248. clang_disposeString(USR);
  1249. return CXChildVisit_Recurse;
  1250. }
  1251. printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
  1252. PrintCursorExtent(C);
  1253. printf("\n");
  1254. clang_disposeString(USR);
  1255. return CXChildVisit_Recurse;
  1256. }
  1257. return CXChildVisit_Continue;
  1258. }
  1259. /******************************************************************************/
  1260. /* Inclusion stack testing. */
  1261. /******************************************************************************/
  1262. void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
  1263. unsigned includeStackLen, CXClientData data) {
  1264. unsigned i;
  1265. CXString fname;
  1266. fname = clang_getFileName(includedFile);
  1267. printf("file: %s\nincluded by:\n", clang_getCString(fname));
  1268. clang_disposeString(fname);
  1269. for (i = 0; i < includeStackLen; ++i) {
  1270. CXFile includingFile;
  1271. unsigned line, column;
  1272. clang_getSpellingLocation(includeStack[i], &includingFile, &line,
  1273. &column, 0);
  1274. fname = clang_getFileName(includingFile);
  1275. printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
  1276. clang_disposeString(fname);
  1277. }
  1278. printf("\n");
  1279. }
  1280. void PrintInclusionStack(CXTranslationUnit TU) {
  1281. clang_getInclusions(TU, InclusionVisitor, NULL);
  1282. }
  1283. /******************************************************************************/
  1284. /* Linkage testing. */
  1285. /******************************************************************************/
  1286. static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
  1287. CXClientData d) {
  1288. const char *linkage = 0;
  1289. if (clang_isInvalid(clang_getCursorKind(cursor)))
  1290. return CXChildVisit_Recurse;
  1291. switch (clang_getCursorLinkage(cursor)) {
  1292. case CXLinkage_Invalid: break;
  1293. case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
  1294. case CXLinkage_Internal: linkage = "Internal"; break;
  1295. case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
  1296. case CXLinkage_External: linkage = "External"; break;
  1297. }
  1298. if (linkage) {
  1299. PrintCursor(cursor, NULL);
  1300. printf("linkage=%s\n", linkage);
  1301. }
  1302. return CXChildVisit_Recurse;
  1303. }
  1304. /******************************************************************************/
  1305. /* Visibility testing. */
  1306. /******************************************************************************/
  1307. static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
  1308. CXClientData d) {
  1309. const char *visibility = 0;
  1310. if (clang_isInvalid(clang_getCursorKind(cursor)))
  1311. return CXChildVisit_Recurse;
  1312. switch (clang_getCursorVisibility(cursor)) {
  1313. case CXVisibility_Invalid: break;
  1314. case CXVisibility_Hidden: visibility = "Hidden"; break;
  1315. case CXVisibility_Protected: visibility = "Protected"; break;
  1316. case CXVisibility_Default: visibility = "Default"; break;
  1317. }
  1318. if (visibility) {
  1319. PrintCursor(cursor, NULL);
  1320. printf("visibility=%s\n", visibility);
  1321. }
  1322. return CXChildVisit_Recurse;
  1323. }
  1324. /******************************************************************************/
  1325. /* Typekind testing. */
  1326. /******************************************************************************/
  1327. static void PrintTypeAndTypeKind(CXType T, const char *Format) {
  1328. CXString TypeSpelling, TypeKindSpelling;
  1329. TypeSpelling = clang_getTypeSpelling(T);
  1330. TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
  1331. printf(Format,
  1332. clang_getCString(TypeSpelling),
  1333. clang_getCString(TypeKindSpelling));
  1334. clang_disposeString(TypeSpelling);
  1335. clang_disposeString(TypeKindSpelling);
  1336. }
  1337. static enum CXVisitorResult FieldVisitor(CXCursor C,
  1338. CXClientData client_data) {
  1339. (*(int *) client_data)+=1;
  1340. return CXVisit_Continue;
  1341. }
  1342. static void PrintTypeTemplateArgs(CXType T, const char *Format) {
  1343. int NumTArgs = clang_Type_getNumTemplateArguments(T);
  1344. if (NumTArgs != -1 && NumTArgs != 0) {
  1345. int i;
  1346. CXType TArg;
  1347. printf(Format, NumTArgs);
  1348. for (i = 0; i < NumTArgs; ++i) {
  1349. TArg = clang_Type_getTemplateArgumentAsType(T, i);
  1350. if (TArg.kind != CXType_Invalid) {
  1351. PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
  1352. }
  1353. }
  1354. /* Ensure that the returned type is invalid when indexing off-by-one. */
  1355. TArg = clang_Type_getTemplateArgumentAsType(T, i);
  1356. assert(TArg.kind == CXType_Invalid);
  1357. printf("]");
  1358. }
  1359. }
  1360. static void PrintNullabilityKind(CXType T, const char *Format) {
  1361. enum CXTypeNullabilityKind N = clang_Type_getNullability(T);
  1362. const char *nullability = 0;
  1363. switch (N) {
  1364. case CXTypeNullability_NonNull: nullability = "nonnull"; break;
  1365. case CXTypeNullability_Nullable: nullability = "nullable"; break;
  1366. case CXTypeNullability_Unspecified: nullability = "unspecified"; break;
  1367. case CXTypeNullability_Invalid: break;
  1368. }
  1369. if (nullability) {
  1370. printf(Format, nullability);
  1371. }
  1372. }
  1373. static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
  1374. CXClientData d) {
  1375. if (!clang_isInvalid(clang_getCursorKind(cursor))) {
  1376. CXType T = clang_getCursorType(cursor);
  1377. CXType PT = clang_getPointeeType(T);
  1378. enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
  1379. PrintCursor(cursor, NULL);
  1380. PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
  1381. PrintNullabilityKind(T, " [nullability=%s]");
  1382. if (clang_isConstQualifiedType(T))
  1383. printf(" const");
  1384. if (clang_isVolatileQualifiedType(T))
  1385. printf(" volatile");
  1386. if (clang_isRestrictQualifiedType(T))
  1387. printf(" restrict");
  1388. if (RQ == CXRefQualifier_LValue)
  1389. printf(" lvalue-ref-qualifier");
  1390. if (RQ == CXRefQualifier_RValue)
  1391. printf(" rvalue-ref-qualifier");
  1392. /* Print the template argument types if they exist. */
  1393. PrintTypeTemplateArgs(T, " [templateargs/%d=");
  1394. /* Print the canonical type if it is different. */
  1395. {
  1396. CXType CT = clang_getCanonicalType(T);
  1397. if (!clang_equalTypes(T, CT)) {
  1398. PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
  1399. PrintTypeTemplateArgs(CT, " [canonicaltemplateargs/%d=");
  1400. }
  1401. }
  1402. /* Print the modified type if it exists. */
  1403. {
  1404. CXType MT = clang_Type_getModifiedType(T);
  1405. if (MT.kind != CXType_Invalid) {
  1406. PrintTypeAndTypeKind(MT, " [modifiedtype=%s] [modifiedtypekind=%s]");
  1407. }
  1408. }
  1409. /* Print the return type if it exists. */
  1410. {
  1411. CXType RT = clang_getCursorResultType(cursor);
  1412. if (RT.kind != CXType_Invalid) {
  1413. PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
  1414. }
  1415. PrintNullabilityKind(RT, " [resultnullability=%s]");
  1416. }
  1417. /* Print the argument types if they exist. */
  1418. {
  1419. int NumArgs = clang_Cursor_getNumArguments(cursor);
  1420. if (NumArgs != -1 && NumArgs != 0) {
  1421. int i;
  1422. printf(" [args=");
  1423. for (i = 0; i < NumArgs; ++i) {
  1424. CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
  1425. if (T.kind != CXType_Invalid) {
  1426. PrintTypeAndTypeKind(T, " [%s] [%s]");
  1427. PrintNullabilityKind(T, " [%s]");
  1428. }
  1429. }
  1430. printf("]");
  1431. }
  1432. }
  1433. /* Print ObjC base types, type arguments, and protocol list if available. */
  1434. {
  1435. CXType BT = clang_Type_getObjCObjectBaseType(PT);
  1436. if (BT.kind != CXType_Invalid) {
  1437. PrintTypeAndTypeKind(BT, " [basetype=%s] [basekind=%s]");
  1438. }
  1439. }
  1440. {
  1441. unsigned NumTypeArgs = clang_Type_getNumObjCTypeArgs(PT);
  1442. if (NumTypeArgs > 0) {
  1443. unsigned i;
  1444. printf(" [typeargs=");
  1445. for (i = 0; i < NumTypeArgs; ++i) {
  1446. CXType TA = clang_Type_getObjCTypeArg(PT, i);
  1447. if (TA.kind != CXType_Invalid) {
  1448. PrintTypeAndTypeKind(TA, " [%s] [%s]");
  1449. }
  1450. }
  1451. printf("]");
  1452. }
  1453. }
  1454. {
  1455. unsigned NumProtocols = clang_Type_getNumObjCProtocolRefs(PT);
  1456. if (NumProtocols > 0) {
  1457. unsigned i;
  1458. printf(" [protocols=");
  1459. for (i = 0; i < NumProtocols; ++i) {
  1460. CXCursor P = clang_Type_getObjCProtocolDecl(PT, i);
  1461. if (!clang_isInvalid(clang_getCursorKind(P))) {
  1462. PrintCursor(P, NULL);
  1463. }
  1464. }
  1465. printf("]");
  1466. }
  1467. }
  1468. /* Print if this is a non-POD type. */
  1469. printf(" [isPOD=%d]", clang_isPODType(T));
  1470. /* Print the pointee type. */
  1471. {
  1472. if (PT.kind != CXType_Invalid) {
  1473. PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
  1474. }
  1475. }
  1476. /* Print the number of fields if they exist. */
  1477. {
  1478. int numFields = 0;
  1479. if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
  1480. if (numFields != 0) {
  1481. printf(" [nbFields=%d]", numFields);
  1482. }
  1483. }
  1484. }
  1485. /* Print if it is an anonymous record or namespace. */
  1486. {
  1487. unsigned isAnon = clang_Cursor_isAnonymous(cursor);
  1488. if (isAnon != 0) {
  1489. printf(" [isAnon=%d]", isAnon);
  1490. }
  1491. }
  1492. /* Print if it is an anonymous record decl */
  1493. {
  1494. unsigned isAnonRecDecl = clang_Cursor_isAnonymousRecordDecl(cursor);
  1495. printf(" [isAnonRecDecl=%d]", isAnonRecDecl);
  1496. }
  1497. /* Print if it is an inline namespace decl */
  1498. {
  1499. unsigned isInlineNamespace = clang_Cursor_isInlineNamespace(cursor);
  1500. if (isInlineNamespace != 0)
  1501. printf(" [isInlineNamespace=%d]", isInlineNamespace);
  1502. }
  1503. printf("\n");
  1504. }
  1505. return CXChildVisit_Recurse;
  1506. }
  1507. static void PrintSingleTypeSize(CXType T, const char *TypeKindFormat,
  1508. const char *SizeFormat,
  1509. const char *AlignFormat) {
  1510. PrintTypeAndTypeKind(T, TypeKindFormat);
  1511. /* Print the type sizeof if applicable. */
  1512. {
  1513. long long Size = clang_Type_getSizeOf(T);
  1514. if (Size >= 0 || Size < -1 ) {
  1515. printf(SizeFormat, Size);
  1516. }
  1517. }
  1518. /* Print the type alignof if applicable. */
  1519. {
  1520. long long Align = clang_Type_getAlignOf(T);
  1521. if (Align >= 0 || Align < -1) {
  1522. printf(AlignFormat, Align);
  1523. }
  1524. }
  1525. /* Print the return type if it exists. */
  1526. {
  1527. CXType RT = clang_getResultType(T);
  1528. if (RT.kind != CXType_Invalid)
  1529. PrintSingleTypeSize(RT, " [resulttype=%s] [resulttypekind=%s]",
  1530. " [resultsizeof=%lld]", " [resultalignof=%lld]");
  1531. }
  1532. }
  1533. static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
  1534. CXClientData d) {
  1535. CXType T;
  1536. enum CXCursorKind K = clang_getCursorKind(cursor);
  1537. if (clang_isInvalid(K))
  1538. return CXChildVisit_Recurse;
  1539. T = clang_getCursorType(cursor);
  1540. PrintCursor(cursor, NULL);
  1541. PrintSingleTypeSize(T, " [type=%s] [typekind=%s]", " [sizeof=%lld]",
  1542. " [alignof=%lld]");
  1543. /* Print the record field offset if applicable. */
  1544. {
  1545. CXString FieldSpelling = clang_getCursorSpelling(cursor);
  1546. const char *FieldName = clang_getCString(FieldSpelling);
  1547. /* recurse to get the first parent record that is not anonymous. */
  1548. unsigned RecordIsAnonymous = 0;
  1549. if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
  1550. CXCursor Record;
  1551. CXCursor Parent = p;
  1552. do {
  1553. Record = Parent;
  1554. Parent = clang_getCursorSemanticParent(Record);
  1555. RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
  1556. /* Recurse as long as the parent is a CXType_Record and the Record
  1557. is anonymous */
  1558. } while ( clang_getCursorType(Parent).kind == CXType_Record &&
  1559. RecordIsAnonymous > 0);
  1560. {
  1561. long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
  1562. FieldName);
  1563. long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
  1564. if (Offset == Offset2){
  1565. printf(" [offsetof=%lld]", Offset);
  1566. } else {
  1567. /* Offsets will be different in anonymous records. */
  1568. printf(" [offsetof=%lld/%lld]", Offset, Offset2);
  1569. }
  1570. }
  1571. }
  1572. clang_disposeString(FieldSpelling);
  1573. }
  1574. /* Print if its a bitfield */
  1575. {
  1576. int IsBitfield = clang_Cursor_isBitField(cursor);
  1577. if (IsBitfield)
  1578. printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
  1579. }
  1580. printf("\n");
  1581. return CXChildVisit_Recurse;
  1582. }
  1583. /******************************************************************************/
  1584. /* Mangling testing. */
  1585. /******************************************************************************/
  1586. static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
  1587. CXClientData d) {
  1588. CXString MangledName;
  1589. if (clang_isUnexposed(clang_getCursorKind(cursor)))
  1590. return CXChildVisit_Recurse;
  1591. PrintCursor(cursor, NULL);
  1592. MangledName = clang_Cursor_getMangling(cursor);
  1593. printf(" [mangled=%s]\n", clang_getCString(MangledName));
  1594. clang_disposeString(MangledName);
  1595. return CXChildVisit_Continue;
  1596. }
  1597. static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
  1598. CXClientData d) {
  1599. unsigned I, E;
  1600. CXStringSet *Manglings = NULL;
  1601. if (clang_isUnexposed(clang_getCursorKind(cursor)))
  1602. return CXChildVisit_Recurse;
  1603. if (!clang_isDeclaration(clang_getCursorKind(cursor)))
  1604. return CXChildVisit_Recurse;
  1605. if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
  1606. return CXChildVisit_Continue;
  1607. PrintCursor(cursor, NULL);
  1608. Manglings = clang_Cursor_getCXXManglings(cursor);
  1609. if (Manglings) {
  1610. for (I = 0, E = Manglings->Count; I < E; ++I)
  1611. printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
  1612. clang_disposeStringSet(Manglings);
  1613. printf("\n");
  1614. }
  1615. Manglings = clang_Cursor_getObjCManglings(cursor);
  1616. if (Manglings) {
  1617. for (I = 0, E = Manglings->Count; I < E; ++I)
  1618. printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
  1619. clang_disposeStringSet(Manglings);
  1620. printf("\n");
  1621. }
  1622. return CXChildVisit_Recurse;
  1623. }
  1624. /******************************************************************************/
  1625. /* Bitwidth testing. */
  1626. /******************************************************************************/
  1627. static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
  1628. CXClientData d) {
  1629. int Bitwidth;
  1630. if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
  1631. return CXChildVisit_Recurse;
  1632. Bitwidth = clang_getFieldDeclBitWidth(cursor);
  1633. if (Bitwidth >= 0) {
  1634. PrintCursor(cursor, NULL);
  1635. printf(" bitwidth=%d\n", Bitwidth);
  1636. }
  1637. return CXChildVisit_Recurse;
  1638. }
  1639. /******************************************************************************/
  1640. /* Type declaration testing */
  1641. /******************************************************************************/
  1642. static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
  1643. CXClientData d) {
  1644. CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
  1645. if (clang_isDeclaration(typeDeclaration.kind)) {
  1646. PrintCursor(cursor, NULL);
  1647. PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
  1648. }
  1649. return CXChildVisit_Recurse;
  1650. }
  1651. /******************************************************************************/
  1652. /* Declaration attributes testing */
  1653. /******************************************************************************/
  1654. static enum CXChildVisitResult PrintDeclAttributes(CXCursor cursor, CXCursor p,
  1655. CXClientData d) {
  1656. if (clang_isDeclaration(cursor.kind)) {
  1657. printf("\n");
  1658. PrintCursor(cursor, NULL);
  1659. return CXChildVisit_Recurse;
  1660. } else if (clang_isAttribute(cursor.kind)) {
  1661. printf(" ");
  1662. PrintCursor(cursor, NULL);
  1663. }
  1664. return CXChildVisit_Continue;
  1665. }
  1666. /******************************************************************************/
  1667. /* Target information testing. */
  1668. /******************************************************************************/
  1669. static int print_target_info(int argc, const char **argv) {
  1670. CXIndex Idx;
  1671. CXTranslationUnit TU;
  1672. CXTargetInfo TargetInfo;
  1673. CXString Triple;
  1674. const char *FileName;
  1675. enum CXErrorCode Err;
  1676. int PointerWidth;
  1677. if (argc == 0) {
  1678. fprintf(stderr, "No filename specified\n");
  1679. return 1;
  1680. }
  1681. FileName = argv[1];
  1682. Idx = clang_createIndex(0, 1);
  1683. Err = clang_parseTranslationUnit2(Idx, FileName, argv, argc, NULL, 0,
  1684. getDefaultParsingOptions(), &TU);
  1685. if (Err != CXError_Success) {
  1686. fprintf(stderr, "Couldn't parse translation unit!\n");
  1687. describeLibclangFailure(Err);
  1688. clang_disposeIndex(Idx);
  1689. return 1;
  1690. }
  1691. TargetInfo = clang_getTranslationUnitTargetInfo(TU);
  1692. Triple = clang_TargetInfo_getTriple(TargetInfo);
  1693. printf("TargetTriple: %s\n", clang_getCString(Triple));
  1694. clang_disposeString(Triple);
  1695. PointerWidth = clang_TargetInfo_getPointerWidth(TargetInfo);
  1696. printf("PointerWidth: %d\n", PointerWidth);
  1697. clang_TargetInfo_dispose(TargetInfo);
  1698. clang_disposeTranslationUnit(TU);
  1699. clang_disposeIndex(Idx);
  1700. return 0;
  1701. }
  1702. /******************************************************************************/
  1703. /* Loading ASTs/source. */
  1704. /******************************************************************************/
  1705. static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
  1706. const char *filter, const char *prefix,
  1707. CXCursorVisitor Visitor,
  1708. PostVisitTU PV,
  1709. const char *CommentSchemaFile) {
  1710. if (prefix)
  1711. FileCheckPrefix = prefix;
  1712. if (Visitor) {
  1713. enum CXCursorKind K = CXCursor_NotImplemented;
  1714. enum CXCursorKind *ck = &K;
  1715. VisitorData Data;
  1716. /* Perform some simple filtering. */
  1717. if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
  1718. else if (!strcmp(filter, "all-display") ||
  1719. !strcmp(filter, "local-display")) {
  1720. ck = NULL;
  1721. wanted_display_type = DisplayType_DisplayName;
  1722. }
  1723. else if (!strcmp(filter, "all-pretty") ||
  1724. !strcmp(filter, "local-pretty")) {
  1725. ck = NULL;
  1726. wanted_display_type = DisplayType_Pretty;
  1727. }
  1728. else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
  1729. else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
  1730. else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
  1731. else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
  1732. else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
  1733. else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
  1734. else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
  1735. else {
  1736. fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
  1737. return 1;
  1738. }
  1739. Data.TU = TU;
  1740. Data.Filter = ck;
  1741. Data.CommentSchemaFile = CommentSchemaFile;
  1742. clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
  1743. }
  1744. if (PV)
  1745. PV(TU);
  1746. PrintDiagnostics(TU);
  1747. if (checkForErrors(TU) != 0) {
  1748. clang_disposeTranslationUnit(TU);
  1749. return -1;
  1750. }
  1751. clang_disposeTranslationUnit(TU);
  1752. return 0;
  1753. }
  1754. int perform_test_load_tu(const char *file, const char *filter,
  1755. const char *prefix, CXCursorVisitor Visitor,
  1756. PostVisitTU PV) {
  1757. CXIndex Idx;
  1758. CXTranslationUnit TU;
  1759. int result;
  1760. Idx = clang_createIndex(/* excludeDeclsFromPCH */
  1761. !strcmp(filter, "local") ? 1 : 0,
  1762. /* displayDiagnostics=*/1);
  1763. if (!CreateTranslationUnit(Idx, file, &TU)) {
  1764. clang_disposeIndex(Idx);
  1765. return 1;
  1766. }
  1767. result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
  1768. clang_disposeIndex(Idx);
  1769. return result;
  1770. }
  1771. int perform_test_load_source(int argc, const char **argv,
  1772. const char *filter, CXCursorVisitor Visitor,
  1773. PostVisitTU PV) {
  1774. CXIndex Idx;
  1775. CXTranslationUnit TU;
  1776. const char *CommentSchemaFile;
  1777. struct CXUnsavedFile *unsaved_files = 0;
  1778. int num_unsaved_files = 0;
  1779. enum CXErrorCode Err;
  1780. int result;
  1781. unsigned Repeats = 0;
  1782. unsigned I;
  1783. const char *InvocationPath;
  1784. Idx = clang_createIndex(/* excludeDeclsFromPCH */
  1785. (!strcmp(filter, "local") ||
  1786. !strcmp(filter, "local-display") ||
  1787. !strcmp(filter, "local-pretty"))
  1788. ? 1
  1789. : 0,
  1790. /* displayDiagnostics=*/1);
  1791. InvocationPath = getenv("CINDEXTEST_INVOCATION_EMISSION_PATH");
  1792. if (InvocationPath)
  1793. clang_CXIndex_setInvocationEmissionPathOption(Idx, InvocationPath);
  1794. if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
  1795. argc--;
  1796. argv++;
  1797. }
  1798. if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
  1799. clang_disposeIndex(Idx);
  1800. return -1;
  1801. }
  1802. if (getenv("CINDEXTEST_EDITING"))
  1803. Repeats = 5;
  1804. Err = clang_parseTranslationUnit2(Idx, 0,
  1805. argv + num_unsaved_files,
  1806. argc - num_unsaved_files,
  1807. unsaved_files, num_unsaved_files,
  1808. getDefaultParsingOptions(), &TU);
  1809. if (Err != CXError_Success) {
  1810. fprintf(stderr, "Unable to load translation unit!\n");
  1811. describeLibclangFailure(Err);
  1812. free_remapped_files(unsaved_files, num_unsaved_files);
  1813. clang_disposeIndex(Idx);
  1814. return 1;
  1815. }
  1816. for (I = 0; I != Repeats; ++I) {
  1817. if (checkForErrors(TU) != 0)
  1818. return -1;
  1819. if (Repeats > 1) {
  1820. clang_suspendTranslationUnit(TU);
  1821. Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
  1822. clang_defaultReparseOptions(TU));
  1823. if (Err != CXError_Success) {
  1824. describeLibclangFailure(Err);
  1825. free_remapped_files(unsaved_files, num_unsaved_files);
  1826. clang_disposeIndex(Idx);
  1827. return 1;
  1828. }
  1829. }
  1830. }
  1831. result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
  1832. CommentSchemaFile);
  1833. free_remapped_files(unsaved_files, num_unsaved_files);
  1834. clang_disposeIndex(Idx);
  1835. return result;
  1836. }
  1837. int perform_test_reparse_source(int argc, const char **argv, int trials,
  1838. const char *filter, CXCursorVisitor Visitor,
  1839. PostVisitTU PV) {
  1840. CXIndex Idx;
  1841. CXTranslationUnit TU;
  1842. struct CXUnsavedFile *unsaved_files = 0;
  1843. int num_unsaved_files = 0;
  1844. int compiler_arg_idx = 0;
  1845. enum CXErrorCode Err;
  1846. int result, i;
  1847. int trial;
  1848. int remap_after_trial = 0;
  1849. char *endptr = 0;
  1850. Idx = clang_createIndex(/* excludeDeclsFromPCH */
  1851. !strcmp(filter, "local") ? 1 : 0,
  1852. /* displayDiagnostics=*/1);
  1853. if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
  1854. clang_disposeIndex(Idx);
  1855. return -1;
  1856. }
  1857. for (i = 0; i < argc; ++i) {
  1858. if (strcmp(argv[i], "--") == 0)
  1859. break;
  1860. }
  1861. if (i < argc)
  1862. compiler_arg_idx = i+1;
  1863. if (num_unsaved_files > compiler_arg_idx)
  1864. compiler_arg_idx = num_unsaved_files;
  1865. /* Load the initial translation unit -- we do this without honoring remapped
  1866. * files, so that we have a way to test results after changing the source. */
  1867. Err = clang_parseTranslationUnit2(Idx, 0,
  1868. argv + compiler_arg_idx,
  1869. argc - compiler_arg_idx,
  1870. 0, 0, getDefaultParsingOptions(), &TU);
  1871. if (Err != CXError_Success) {
  1872. fprintf(stderr, "Unable to load translation unit!\n");
  1873. describeLibclangFailure(Err);
  1874. free_remapped_files(unsaved_files, num_unsaved_files);
  1875. clang_disposeIndex(Idx);
  1876. return 1;
  1877. }
  1878. if (checkForErrors(TU) != 0)
  1879. return -1;
  1880. if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
  1881. remap_after_trial =
  1882. strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
  1883. }
  1884. for (trial = 0; trial < trials; ++trial) {
  1885. free_remapped_files(unsaved_files, num_unsaved_files);
  1886. if (parse_remapped_files_with_try(trial, argc, argv, 0,
  1887. &unsaved_files, &num_unsaved_files)) {
  1888. clang_disposeTranslationUnit(TU);
  1889. clang_disposeIndex(Idx);
  1890. return -1;
  1891. }
  1892. Err = clang_reparseTranslationUnit(
  1893. TU,
  1894. trial >= remap_after_trial ? num_unsaved_files : 0,
  1895. trial >= remap_after_trial ? unsaved_files : 0,
  1896. clang_defaultReparseOptions(TU));
  1897. if (Err != CXError_Success) {
  1898. fprintf(stderr, "Unable to reparse translation unit!\n");
  1899. describeLibclangFailure(Err);
  1900. clang_disposeTranslationUnit(TU);
  1901. free_remapped_files(unsaved_files, num_unsaved_files);
  1902. clang_disposeIndex(Idx);
  1903. return -1;
  1904. }
  1905. if (checkForErrors(TU) != 0)
  1906. return -1;
  1907. }
  1908. result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
  1909. free_remapped_files(unsaved_files, num_unsaved_files);
  1910. clang_disposeIndex(Idx);
  1911. return result;
  1912. }
  1913. static int perform_single_file_parse(const char *filename) {
  1914. CXIndex Idx;
  1915. CXTranslationUnit TU;
  1916. enum CXErrorCode Err;
  1917. int result;
  1918. Idx = clang_createIndex(/* excludeDeclsFromPCH */1,
  1919. /* displayDiagnostics=*/1);
  1920. Err = clang_parseTranslationUnit2(Idx, filename,
  1921. /*command_line_args=*/NULL,
  1922. /*num_command_line_args=*/0,
  1923. /*unsaved_files=*/NULL,
  1924. /*num_unsaved_files=*/0,
  1925. CXTranslationUnit_SingleFileParse, &TU);
  1926. if (Err != CXError_Success) {
  1927. fprintf(stderr, "Unable to load translation unit!\n");
  1928. describeLibclangFailure(Err);
  1929. clang_disposeIndex(Idx);
  1930. return 1;
  1931. }
  1932. result = perform_test_load(Idx, TU, /*filter=*/"all", /*prefix=*/NULL, FilteredPrintingVisitor, /*PostVisit=*/NULL,
  1933. /*CommentSchemaFile=*/NULL);
  1934. clang_disposeIndex(Idx);
  1935. return result;
  1936. }
  1937. /******************************************************************************/
  1938. /* Logic for testing clang_getCursor(). */
  1939. /******************************************************************************/
  1940. static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
  1941. unsigned start_line, unsigned start_col,
  1942. unsigned end_line, unsigned end_col,
  1943. const char *prefix) {
  1944. printf("// %s: ", FileCheckPrefix);
  1945. if (prefix)
  1946. printf("-%s", prefix);
  1947. PrintExtent(stdout, start_line, start_col, end_line, end_col);
  1948. printf(" ");
  1949. PrintCursor(cursor, NULL);
  1950. printf("\n");
  1951. }
  1952. static int perform_file_scan(const char *ast_file, const char *source_file,
  1953. const char *prefix) {
  1954. CXIndex Idx;
  1955. CXTranslationUnit TU;
  1956. FILE *fp;
  1957. CXCursor prevCursor = clang_getNullCursor();
  1958. CXFile file;
  1959. unsigned line = 1, col = 1;
  1960. unsigned start_line = 1, start_col = 1;
  1961. if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
  1962. /* displayDiagnostics=*/1))) {
  1963. fprintf(stderr, "Could not create Index\n");
  1964. return 1;
  1965. }
  1966. if (!CreateTranslationUnit(Idx, ast_file, &TU))
  1967. return 1;
  1968. if ((fp = fopen(source_file, "r")) == NULL) {
  1969. fprintf(stderr, "Could not open '%s'\n", source_file);
  1970. clang_disposeTranslationUnit(TU);
  1971. return 1;
  1972. }
  1973. file = clang_getFile(TU, source_file);
  1974. for (;;) {
  1975. CXCursor cursor;
  1976. int c = fgetc(fp);
  1977. if (c == '\n') {
  1978. ++line;
  1979. col = 1;
  1980. } else
  1981. ++col;
  1982. /* Check the cursor at this position, and dump the previous one if we have
  1983. * found something new.
  1984. */
  1985. cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
  1986. if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
  1987. prevCursor.kind != CXCursor_InvalidFile) {
  1988. print_cursor_file_scan(TU, prevCursor, start_line, start_col,
  1989. line, col, prefix);
  1990. start_line = line;
  1991. start_col = col;
  1992. }
  1993. if (c == EOF)
  1994. break;
  1995. prevCursor = cursor;
  1996. }
  1997. fclose(fp);
  1998. clang_disposeTranslationUnit(TU);
  1999. clang_disposeIndex(Idx);
  2000. return 0;
  2001. }
  2002. /******************************************************************************/
  2003. /* Logic for testing clang code completion. */
  2004. /******************************************************************************/
  2005. /* Parse file:line:column from the input string. Returns 0 on success, non-zero
  2006. on failure. If successful, the pointer *filename will contain newly-allocated
  2007. memory (that will be owned by the caller) to store the file name. */
  2008. int parse_file_line_column(const char *input, char **filename, unsigned *line,
  2009. unsigned *column, unsigned *second_line,
  2010. unsigned *second_column) {
  2011. /* Find the second colon. */
  2012. const char *last_colon = strrchr(input, ':');
  2013. unsigned values[4], i;
  2014. unsigned num_values = (second_line && second_column)? 4 : 2;
  2015. char *endptr = 0;
  2016. if (!last_colon || last_colon == input) {
  2017. if (num_values == 4)
  2018. fprintf(stderr, "could not parse filename:line:column:line:column in "
  2019. "'%s'\n", input);
  2020. else
  2021. fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
  2022. return 1;
  2023. }
  2024. for (i = 0; i != num_values; ++i) {
  2025. const char *prev_colon;
  2026. /* Parse the next line or column. */
  2027. values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
  2028. if (*endptr != 0 && *endptr != ':') {
  2029. fprintf(stderr, "could not parse %s in '%s'\n",
  2030. (i % 2 ? "column" : "line"), input);
  2031. return 1;
  2032. }
  2033. if (i + 1 == num_values)
  2034. break;
  2035. /* Find the previous colon. */
  2036. prev_colon = last_colon - 1;
  2037. while (prev_colon != input && *prev_colon != ':')
  2038. --prev_colon;
  2039. if (prev_colon == input) {
  2040. fprintf(stderr, "could not parse %s in '%s'\n",
  2041. (i % 2 == 0? "column" : "line"), input);
  2042. return 1;
  2043. }
  2044. last_colon = prev_colon;
  2045. }
  2046. *line = values[0];
  2047. *column = values[1];
  2048. if (second_line && second_column) {
  2049. *second_line = values[2];
  2050. *second_column = values[3];
  2051. }
  2052. /* Copy the file name. */
  2053. *filename = (char*)malloc(last_colon - input + 1);
  2054. assert(*filename);
  2055. memcpy(*filename, input, last_colon - input);
  2056. (*filename)[last_colon - input] = 0;
  2057. return 0;
  2058. }
  2059. const char *
  2060. clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
  2061. switch (Kind) {
  2062. case CXCompletionChunk_Optional: return "Optional";
  2063. case CXCompletionChunk_TypedText: return "TypedText";
  2064. case CXCompletionChunk_Text: return "Text";
  2065. case CXCompletionChunk_Placeholder: return "Placeholder";
  2066. case CXCompletionChunk_Informative: return "Informative";
  2067. case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
  2068. case CXCompletionChunk_LeftParen: return "LeftParen";
  2069. case CXCompletionChunk_RightParen: return "RightParen";
  2070. case CXCompletionChunk_LeftBracket: return "LeftBracket";
  2071. case CXCompletionChunk_RightBracket: return "RightBracket";
  2072. case CXCompletionChunk_LeftBrace: return "LeftBrace";
  2073. case CXCompletionChunk_RightBrace: return "RightBrace";
  2074. case CXCompletionChunk_LeftAngle: return "LeftAngle";
  2075. case CXCompletionChunk_RightAngle: return "RightAngle";
  2076. case CXCompletionChunk_Comma: return "Comma";
  2077. case CXCompletionChunk_ResultType: return "ResultType";
  2078. case CXCompletionChunk_Colon: return "Colon";
  2079. case CXCompletionChunk_SemiColon: return "SemiColon";
  2080. case CXCompletionChunk_Equal: return "Equal";
  2081. case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
  2082. case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
  2083. }
  2084. return "Unknown";
  2085. }
  2086. static int checkForErrors(CXTranslationUnit TU) {
  2087. unsigned Num, i;
  2088. CXDiagnostic Diag;
  2089. CXString DiagStr;
  2090. if (!getenv("CINDEXTEST_FAILONERROR"))
  2091. return 0;
  2092. Num = clang_getNumDiagnostics(TU);
  2093. for (i = 0; i != Num; ++i) {
  2094. Diag = clang_getDiagnostic(TU, i);
  2095. if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
  2096. DiagStr = clang_formatDiagnostic(Diag,
  2097. clang_defaultDiagnosticDisplayOptions());
  2098. fprintf(stderr, "%s\n", clang_getCString(DiagStr));
  2099. clang_disposeString(DiagStr);
  2100. clang_disposeDiagnostic(Diag);
  2101. return -1;
  2102. }
  2103. clang_disposeDiagnostic(Diag);
  2104. }
  2105. return 0;
  2106. }
  2107. static void print_completion_string(CXCompletionString completion_string,
  2108. FILE *file) {
  2109. int I, N;
  2110. N = clang_getNumCompletionChunks(completion_string);
  2111. for (I = 0; I != N; ++I) {
  2112. CXString text;
  2113. const char *cstr;
  2114. enum CXCompletionChunkKind Kind
  2115. = clang_getCompletionChunkKind(completion_string, I);
  2116. if (Kind == CXCompletionChunk_Optional) {
  2117. fprintf(file, "{Optional ");
  2118. print_completion_string(
  2119. clang_getCompletionChunkCompletionString(completion_string, I),
  2120. file);
  2121. fprintf(file, "}");
  2122. continue;
  2123. }
  2124. if (Kind == CXCompletionChunk_VerticalSpace) {
  2125. fprintf(file, "{VerticalSpace }");
  2126. continue;
  2127. }
  2128. text = clang_getCompletionChunkText(completion_string, I);
  2129. cstr = clang_getCString(text);
  2130. fprintf(file, "{%s %s}",
  2131. clang_getCompletionChunkKindSpelling(Kind),
  2132. cstr ? cstr : "");
  2133. clang_disposeString(text);
  2134. }
  2135. }
  2136. static void print_line_column(CXSourceLocation location, FILE *file) {
  2137. unsigned line, column;
  2138. clang_getExpansionLocation(location, NULL, &line, &column, NULL);
  2139. fprintf(file, "%d:%d", line, column);
  2140. }
  2141. static void print_token_range(CXTranslationUnit translation_unit,
  2142. CXSourceLocation start, FILE *file) {
  2143. CXToken *token = clang_getToken(translation_unit, start);
  2144. fprintf(file, "{");
  2145. if (token != NULL) {
  2146. CXSourceRange token_range = clang_getTokenExtent(translation_unit, *token);
  2147. print_line_column(clang_getRangeStart(token_range), file);
  2148. fprintf(file, "-");
  2149. print_line_column(clang_getRangeEnd(token_range), file);
  2150. clang_disposeTokens(translation_unit, token, 1);
  2151. }
  2152. fprintf(file, "}");
  2153. }
  2154. static void print_completion_result(CXTranslationUnit translation_unit,
  2155. CXCodeCompleteResults *completion_results,
  2156. unsigned index,
  2157. FILE *file) {
  2158. CXCompletionResult *completion_result = completion_results->Results + index;
  2159. CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
  2160. unsigned annotationCount;
  2161. enum CXCursorKind ParentKind;
  2162. CXString ParentName;
  2163. CXString BriefComment;
  2164. CXString Annotation;
  2165. const char *BriefCommentCString;
  2166. unsigned i;
  2167. fprintf(file, "%s:", clang_getCString(ks));
  2168. clang_disposeString(ks);
  2169. print_completion_string(completion_result->CompletionString, file);
  2170. fprintf(file, " (%u)",
  2171. clang_getCompletionPriority(completion_result->CompletionString));
  2172. switch (clang_getCompletionAvailability(completion_result->CompletionString)){
  2173. case CXAvailability_Available:
  2174. break;
  2175. case CXAvailability_Deprecated:
  2176. fprintf(file, " (deprecated)");
  2177. break;
  2178. case CXAvailability_NotAvailable:
  2179. fprintf(file, " (unavailable)");
  2180. break;
  2181. case CXAvailability_NotAccessible:
  2182. fprintf(file, " (inaccessible)");
  2183. break;
  2184. }
  2185. annotationCount = clang_getCompletionNumAnnotations(
  2186. completion_result->CompletionString);
  2187. if (annotationCount) {
  2188. unsigned i;
  2189. fprintf(file, " (");
  2190. for (i = 0; i < annotationCount; ++i) {
  2191. if (i != 0)
  2192. fprintf(file, ", ");
  2193. Annotation =
  2194. clang_getCompletionAnnotation(completion_result->CompletionString, i);
  2195. fprintf(file, "\"%s\"", clang_getCString(Annotation));
  2196. clang_disposeString(Annotation);
  2197. }
  2198. fprintf(file, ")");
  2199. }
  2200. if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
  2201. ParentName = clang_getCompletionParent(completion_result->CompletionString,
  2202. &ParentKind);
  2203. if (ParentKind != CXCursor_NotImplemented) {
  2204. CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
  2205. fprintf(file, " (parent: %s '%s')",
  2206. clang_getCString(KindSpelling),
  2207. clang_getCString(ParentName));
  2208. clang_disposeString(KindSpelling);
  2209. }
  2210. clang_disposeString(ParentName);
  2211. }
  2212. BriefComment = clang_getCompletionBriefComment(
  2213. completion_result->CompletionString);
  2214. BriefCommentCString = clang_getCString(BriefComment);
  2215. if (BriefCommentCString && *BriefCommentCString != '\0') {
  2216. fprintf(file, "(brief comment: %s)", BriefCommentCString);
  2217. }
  2218. clang_disposeString(BriefComment);
  2219. for (i = 0; i < clang_getCompletionNumFixIts(completion_results, index);
  2220. ++i) {
  2221. CXSourceRange correction_range;
  2222. CXString FixIt = clang_getCompletionFixIt(completion_results, index, i,
  2223. &correction_range);
  2224. fprintf(file, " (requires fix-it: ");
  2225. print_token_range(translation_unit, clang_getRangeStart(correction_range),
  2226. file);
  2227. fprintf(file, " to \"%s\")", clang_getCString(FixIt));
  2228. clang_disposeString(FixIt);
  2229. }
  2230. fprintf(file, "\n");
  2231. }
  2232. void print_completion_contexts(unsigned long long contexts, FILE *file) {
  2233. fprintf(file, "Completion contexts:\n");
  2234. if (contexts == CXCompletionContext_Unknown) {
  2235. fprintf(file, "Unknown\n");
  2236. }
  2237. if (contexts & CXCompletionContext_AnyType) {
  2238. fprintf(file, "Any type\n");
  2239. }
  2240. if (contexts & CXCompletionContext_AnyValue) {
  2241. fprintf(file, "Any value\n");
  2242. }
  2243. if (contexts & CXCompletionContext_ObjCObjectValue) {
  2244. fprintf(file, "Objective-C object value\n");
  2245. }
  2246. if (contexts & CXCompletionContext_ObjCSelectorValue) {
  2247. fprintf(file, "Objective-C selector value\n");
  2248. }
  2249. if (contexts & CXCompletionContext_CXXClassTypeValue) {
  2250. fprintf(file, "C++ class type value\n");
  2251. }
  2252. if (contexts & CXCompletionContext_DotMemberAccess) {
  2253. fprintf(file, "Dot member access\n");
  2254. }
  2255. if (contexts & CXCompletionContext_ArrowMemberAccess) {
  2256. fprintf(file, "Arrow member access\n");
  2257. }
  2258. if (contexts & CXCompletionContext_ObjCPropertyAccess) {
  2259. fprintf(file, "Objective-C property access\n");
  2260. }
  2261. if (contexts & CXCompletionContext_EnumTag) {
  2262. fprintf(file, "Enum tag\n");
  2263. }
  2264. if (contexts & CXCompletionContext_UnionTag) {
  2265. fprintf(file, "Union tag\n");
  2266. }
  2267. if (contexts & CXCompletionContext_StructTag) {
  2268. fprintf(file, "Struct tag\n");
  2269. }
  2270. if (contexts & CXCompletionContext_ClassTag) {
  2271. fprintf(file, "Class name\n");
  2272. }
  2273. if (contexts & CXCompletionContext_Namespace) {
  2274. fprintf(file, "Namespace or namespace alias\n");
  2275. }
  2276. if (contexts & CXCompletionContext_NestedNameSpecifier) {
  2277. fprintf(file, "Nested name specifier\n");
  2278. }
  2279. if (contexts & CXCompletionContext_ObjCInterface) {
  2280. fprintf(file, "Objective-C interface\n");
  2281. }
  2282. if (contexts & CXCompletionContext_ObjCProtocol) {
  2283. fprintf(file, "Objective-C protocol\n");
  2284. }
  2285. if (contexts & CXCompletionContext_ObjCCategory) {
  2286. fprintf(file, "Objective-C category\n");
  2287. }
  2288. if (contexts & CXCompletionContext_ObjCInstanceMessage) {
  2289. fprintf(file, "Objective-C instance method\n");
  2290. }
  2291. if (contexts & CXCompletionContext_ObjCClassMessage) {
  2292. fprintf(file, "Objective-C class method\n");
  2293. }
  2294. if (contexts & CXCompletionContext_ObjCSelectorName) {
  2295. fprintf(file, "Objective-C selector name\n");
  2296. }
  2297. if (contexts & CXCompletionContext_MacroName) {
  2298. fprintf(file, "Macro name\n");
  2299. }
  2300. if (contexts & CXCompletionContext_NaturalLanguage) {
  2301. fprintf(file, "Natural language\n");
  2302. }
  2303. }
  2304. int perform_code_completion(int argc, const char **argv, int timing_only) {
  2305. const char *input = argv[1];
  2306. char *filename = 0;
  2307. unsigned line;
  2308. unsigned column;
  2309. CXIndex CIdx;
  2310. int errorCode;
  2311. struct CXUnsavedFile *unsaved_files = 0;
  2312. int num_unsaved_files = 0;
  2313. CXCodeCompleteResults *results = 0;
  2314. enum CXErrorCode Err;
  2315. CXTranslationUnit TU;
  2316. unsigned I, Repeats = 1;
  2317. unsigned completionOptions = clang_defaultCodeCompleteOptions();
  2318. const char *InvocationPath;
  2319. if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
  2320. completionOptions |= CXCodeComplete_IncludeCodePatterns;
  2321. if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
  2322. completionOptions |= CXCodeComplete_IncludeBriefComments;
  2323. if (getenv("CINDEXTEST_COMPLETION_SKIP_PREAMBLE"))
  2324. completionOptions |= CXCodeComplete_SkipPreamble;
  2325. if (getenv("CINDEXTEST_COMPLETION_INCLUDE_FIXITS"))
  2326. completionOptions |= CXCodeComplete_IncludeCompletionsWithFixIts;
  2327. if (timing_only)
  2328. input += strlen("-code-completion-timing=");
  2329. else
  2330. input += strlen("-code-completion-at=");
  2331. if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
  2332. 0, 0)))
  2333. return errorCode;
  2334. if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
  2335. return -1;
  2336. CIdx = clang_createIndex(0, 0);
  2337. InvocationPath = getenv("CINDEXTEST_INVOCATION_EMISSION_PATH");
  2338. if (InvocationPath)
  2339. clang_CXIndex_setInvocationEmissionPathOption(CIdx, InvocationPath);
  2340. if (getenv("CINDEXTEST_EDITING"))
  2341. Repeats = 5;
  2342. Err = clang_parseTranslationUnit2(CIdx, 0,
  2343. argv + num_unsaved_files + 2,
  2344. argc - num_unsaved_files - 2,
  2345. 0, 0, getDefaultParsingOptions(), &TU);
  2346. if (Err != CXError_Success) {
  2347. fprintf(stderr, "Unable to load translation unit!\n");
  2348. describeLibclangFailure(Err);
  2349. return 1;
  2350. }
  2351. Err = clang_reparseTranslationUnit(TU, 0, 0,
  2352. clang_defaultReparseOptions(TU));
  2353. if (Err != CXError_Success) {
  2354. fprintf(stderr, "Unable to reparse translation unit!\n");
  2355. describeLibclangFailure(Err);
  2356. clang_disposeTranslationUnit(TU);
  2357. return 1;
  2358. }
  2359. for (I = 0; I != Repeats; ++I) {
  2360. results = clang_codeCompleteAt(TU, filename, line, column,
  2361. unsaved_files, num_unsaved_files,
  2362. completionOptions);
  2363. if (!results) {
  2364. fprintf(stderr, "Unable to perform code completion!\n");
  2365. return 1;
  2366. }
  2367. if (I != Repeats-1)
  2368. clang_disposeCodeCompleteResults(results);
  2369. }
  2370. if (results) {
  2371. unsigned i, n = results->NumResults, containerIsIncomplete = 0;
  2372. unsigned long long contexts;
  2373. enum CXCursorKind containerKind;
  2374. CXString objCSelector;
  2375. const char *selectorString;
  2376. if (!timing_only) {
  2377. /* Sort the code-completion results based on the typed text. */
  2378. clang_sortCodeCompletionResults(results->Results, results->NumResults);
  2379. for (i = 0; i != n; ++i)
  2380. print_completion_result(TU, results, i, stdout);
  2381. }
  2382. n = clang_codeCompleteGetNumDiagnostics(results);
  2383. for (i = 0; i != n; ++i) {
  2384. CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
  2385. PrintDiagnostic(diag);
  2386. clang_disposeDiagnostic(diag);
  2387. }
  2388. contexts = clang_codeCompleteGetContexts(results);
  2389. print_completion_contexts(contexts, stdout);
  2390. containerKind = clang_codeCompleteGetContainerKind(results,
  2391. &containerIsIncomplete);
  2392. if (containerKind != CXCursor_InvalidCode) {
  2393. /* We have found a container */
  2394. CXString containerUSR, containerKindSpelling;
  2395. containerKindSpelling = clang_getCursorKindSpelling(containerKind);
  2396. printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
  2397. clang_disposeString(containerKindSpelling);
  2398. if (containerIsIncomplete) {
  2399. printf("Container is incomplete\n");
  2400. }
  2401. else {
  2402. printf("Container is complete\n");
  2403. }
  2404. containerUSR = clang_codeCompleteGetContainerUSR(results);
  2405. printf("Container USR: %s\n", clang_getCString(containerUSR));
  2406. clang_disposeString(containerUSR);
  2407. }
  2408. objCSelector = clang_codeCompleteGetObjCSelector(results);
  2409. selectorString = clang_getCString(objCSelector);
  2410. if (selectorString && strlen(selectorString) > 0) {
  2411. printf("Objective-C selector: %s\n", selectorString);
  2412. }
  2413. clang_disposeString(objCSelector);
  2414. clang_disposeCodeCompleteResults(results);
  2415. }
  2416. clang_disposeTranslationUnit(TU);
  2417. clang_disposeIndex(CIdx);
  2418. free(filename);
  2419. free_remapped_files(unsaved_files, num_unsaved_files);
  2420. return 0;
  2421. }
  2422. typedef struct {
  2423. char *filename;
  2424. unsigned line;
  2425. unsigned column;
  2426. } CursorSourceLocation;
  2427. typedef void (*cursor_handler_t)(CXCursor cursor);
  2428. static int inspect_cursor_at(int argc, const char **argv,
  2429. const char *locations_flag,
  2430. cursor_handler_t handler) {
  2431. CXIndex CIdx;
  2432. int errorCode;
  2433. struct CXUnsavedFile *unsaved_files = 0;
  2434. int num_unsaved_files = 0;
  2435. enum CXErrorCode Err;
  2436. CXTranslationUnit TU;
  2437. CXCursor Cursor;
  2438. CursorSourceLocation *Locations = 0;
  2439. unsigned NumLocations = 0, Loc;
  2440. unsigned Repeats = 1;
  2441. unsigned I;
  2442. /* Count the number of locations. */
  2443. while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
  2444. ++NumLocations;
  2445. /* Parse the locations. */
  2446. assert(NumLocations > 0 && "Unable to count locations?");
  2447. Locations = (CursorSourceLocation *)malloc(
  2448. NumLocations * sizeof(CursorSourceLocation));
  2449. assert(Locations);
  2450. for (Loc = 0; Loc < NumLocations; ++Loc) {
  2451. const char *input = argv[Loc + 1] + strlen(locations_flag);
  2452. if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
  2453. &Locations[Loc].line,
  2454. &Locations[Loc].column, 0, 0)))
  2455. return errorCode;
  2456. }
  2457. if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
  2458. &num_unsaved_files))
  2459. return -1;
  2460. if (getenv("CINDEXTEST_EDITING"))
  2461. Repeats = 5;
  2462. /* Parse the translation unit. When we're testing clang_getCursor() after
  2463. reparsing, don't remap unsaved files until the second parse. */
  2464. CIdx = clang_createIndex(1, 1);
  2465. Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
  2466. argv + num_unsaved_files + 1 + NumLocations,
  2467. argc - num_unsaved_files - 2 - NumLocations,
  2468. unsaved_files,
  2469. Repeats > 1? 0 : num_unsaved_files,
  2470. getDefaultParsingOptions(), &TU);
  2471. if (Err != CXError_Success) {
  2472. fprintf(stderr, "unable to parse input\n");
  2473. describeLibclangFailure(Err);
  2474. return -1;
  2475. }
  2476. if (checkForErrors(TU) != 0)
  2477. return -1;
  2478. for (I = 0; I != Repeats; ++I) {
  2479. if (Repeats > 1) {
  2480. Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
  2481. clang_defaultReparseOptions(TU));
  2482. if (Err != CXError_Success) {
  2483. describeLibclangFailure(Err);
  2484. clang_disposeTranslationUnit(TU);
  2485. return 1;
  2486. }
  2487. }
  2488. if (checkForErrors(TU) != 0)
  2489. return -1;
  2490. for (Loc = 0; Loc < NumLocations; ++Loc) {
  2491. CXFile file = clang_getFile(TU, Locations[Loc].filename);
  2492. if (!file)
  2493. continue;
  2494. Cursor = clang_getCursor(TU,
  2495. clang_getLocation(TU, file, Locations[Loc].line,
  2496. Locations[Loc].column));
  2497. if (checkForErrors(TU) != 0)
  2498. return -1;
  2499. if (I + 1 == Repeats) {
  2500. handler(Cursor);
  2501. free(Locations[Loc].filename);
  2502. }
  2503. }
  2504. }
  2505. PrintDiagnostics(TU);
  2506. clang_disposeTranslationUnit(TU);
  2507. clang_disposeIndex(CIdx);
  2508. free(Locations);
  2509. free_remapped_files(unsaved_files, num_unsaved_files);
  2510. return 0;
  2511. }
  2512. static void inspect_print_cursor(CXCursor Cursor) {
  2513. CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
  2514. CXCompletionString completionString = clang_getCursorCompletionString(
  2515. Cursor);
  2516. CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
  2517. CXString Spelling;
  2518. const char *cspell;
  2519. unsigned line, column;
  2520. clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
  2521. printf("%d:%d ", line, column);
  2522. PrintCursor(Cursor, NULL);
  2523. PrintCursorExtent(Cursor);
  2524. Spelling = clang_getCursorSpelling(Cursor);
  2525. cspell = clang_getCString(Spelling);
  2526. if (cspell && strlen(cspell) != 0) {
  2527. unsigned pieceIndex;
  2528. printf(" Spelling=%s (", cspell);
  2529. for (pieceIndex = 0; ; ++pieceIndex) {
  2530. CXSourceRange range =
  2531. clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
  2532. if (clang_Range_isNull(range))
  2533. break;
  2534. PrintRange(range, 0);
  2535. }
  2536. printf(")");
  2537. }
  2538. clang_disposeString(Spelling);
  2539. if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
  2540. printf(" Selector index=%d",
  2541. clang_Cursor_getObjCSelectorIndex(Cursor));
  2542. if (clang_Cursor_isDynamicCall(Cursor))
  2543. printf(" Dynamic-call");
  2544. if (Cursor.kind == CXCursor_ObjCMessageExpr ||
  2545. Cursor.kind == CXCursor_MemberRefExpr) {
  2546. CXType T = clang_Cursor_getReceiverType(Cursor);
  2547. if (T.kind != CXType_Invalid) {
  2548. CXString S = clang_getTypeKindSpelling(T.kind);
  2549. printf(" Receiver-type=%s", clang_getCString(S));
  2550. clang_disposeString(S);
  2551. }
  2552. }
  2553. {
  2554. CXModule mod = clang_Cursor_getModule(Cursor);
  2555. CXFile astFile;
  2556. CXString name, astFilename;
  2557. unsigned i, numHeaders;
  2558. if (mod) {
  2559. astFile = clang_Module_getASTFile(mod);
  2560. astFilename = clang_getFileName(astFile);
  2561. name = clang_Module_getFullName(mod);
  2562. numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
  2563. printf(" ModuleName=%s (%s) system=%d Headers(%d):",
  2564. clang_getCString(name), clang_getCString(astFilename),
  2565. clang_Module_isSystem(mod), numHeaders);
  2566. clang_disposeString(name);
  2567. clang_disposeString(astFilename);
  2568. for (i = 0; i < numHeaders; ++i) {
  2569. CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
  2570. CXString filename = clang_getFileName(file);
  2571. printf("\n%s", clang_getCString(filename));
  2572. clang_disposeString(filename);
  2573. }
  2574. }
  2575. }
  2576. if (completionString != NULL) {
  2577. printf("\nCompletion string: ");
  2578. print_completion_string(completionString, stdout);
  2579. }
  2580. printf("\n");
  2581. }
  2582. static void display_evaluate_results(CXEvalResult result) {
  2583. switch (clang_EvalResult_getKind(result)) {
  2584. case CXEval_Int:
  2585. {
  2586. printf("Kind: Int, ");
  2587. if (clang_EvalResult_isUnsignedInt(result)) {
  2588. unsigned long long val = clang_EvalResult_getAsUnsigned(result);
  2589. printf("unsigned, Value: %llu", val);
  2590. } else {
  2591. long long val = clang_EvalResult_getAsLongLong(result);
  2592. printf("Value: %lld", val);
  2593. }
  2594. break;
  2595. }
  2596. case CXEval_Float:
  2597. {
  2598. double val = clang_EvalResult_getAsDouble(result);
  2599. printf("Kind: Float , Value: %f", val);
  2600. break;
  2601. }
  2602. case CXEval_ObjCStrLiteral:
  2603. {
  2604. const char* str = clang_EvalResult_getAsStr(result);
  2605. printf("Kind: ObjCString , Value: %s", str);
  2606. break;
  2607. }
  2608. case CXEval_StrLiteral:
  2609. {
  2610. const char* str = clang_EvalResult_getAsStr(result);
  2611. printf("Kind: CString , Value: %s", str);
  2612. break;
  2613. }
  2614. case CXEval_CFStr:
  2615. {
  2616. const char* str = clang_EvalResult_getAsStr(result);
  2617. printf("Kind: CFString , Value: %s", str);
  2618. break;
  2619. }
  2620. default:
  2621. printf("Unexposed");
  2622. break;
  2623. }
  2624. }
  2625. static void inspect_evaluate_cursor(CXCursor Cursor) {
  2626. CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
  2627. CXString Spelling;
  2628. const char *cspell;
  2629. unsigned line, column;
  2630. CXEvalResult ER;
  2631. clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
  2632. printf("%d:%d ", line, column);
  2633. PrintCursor(Cursor, NULL);
  2634. PrintCursorExtent(Cursor);
  2635. Spelling = clang_getCursorSpelling(Cursor);
  2636. cspell = clang_getCString(Spelling);
  2637. if (cspell && strlen(cspell) != 0) {
  2638. unsigned pieceIndex;
  2639. printf(" Spelling=%s (", cspell);
  2640. for (pieceIndex = 0; ; ++pieceIndex) {
  2641. CXSourceRange range =
  2642. clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
  2643. if (clang_Range_isNull(range))
  2644. break;
  2645. PrintRange(range, 0);
  2646. }
  2647. printf(")");
  2648. }
  2649. clang_disposeString(Spelling);
  2650. ER = clang_Cursor_Evaluate(Cursor);
  2651. if (!ER) {
  2652. printf("Not Evaluatable");
  2653. } else {
  2654. display_evaluate_results(ER);
  2655. clang_EvalResult_dispose(ER);
  2656. }
  2657. printf("\n");
  2658. }
  2659. static void inspect_macroinfo_cursor(CXCursor Cursor) {
  2660. CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
  2661. CXString Spelling;
  2662. const char *cspell;
  2663. unsigned line, column;
  2664. clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
  2665. printf("%d:%d ", line, column);
  2666. PrintCursor(Cursor, NULL);
  2667. PrintCursorExtent(Cursor);
  2668. Spelling = clang_getCursorSpelling(Cursor);
  2669. cspell = clang_getCString(Spelling);
  2670. if (cspell && strlen(cspell) != 0) {
  2671. unsigned pieceIndex;
  2672. printf(" Spelling=%s (", cspell);
  2673. for (pieceIndex = 0; ; ++pieceIndex) {
  2674. CXSourceRange range =
  2675. clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
  2676. if (clang_Range_isNull(range))
  2677. break;
  2678. PrintRange(range, 0);
  2679. }
  2680. printf(")");
  2681. }
  2682. clang_disposeString(Spelling);
  2683. if (clang_Cursor_isMacroBuiltin(Cursor)) {
  2684. printf("[builtin macro]");
  2685. } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
  2686. printf("[function macro]");
  2687. }
  2688. printf("\n");
  2689. }
  2690. static enum CXVisitorResult findFileRefsVisit(void *context,
  2691. CXCursor cursor, CXSourceRange range) {
  2692. if (clang_Range_isNull(range))
  2693. return CXVisit_Continue;
  2694. PrintCursor(cursor, NULL);
  2695. PrintRange(range, "");
  2696. printf("\n");
  2697. return CXVisit_Continue;
  2698. }
  2699. static int find_file_refs_at(int argc, const char **argv) {
  2700. CXIndex CIdx;
  2701. int errorCode;
  2702. struct CXUnsavedFile *unsaved_files = 0;
  2703. int num_unsaved_files = 0;
  2704. enum CXErrorCode Err;
  2705. CXTranslationUnit TU;
  2706. CXCursor Cursor;
  2707. CursorSourceLocation *Locations = 0;
  2708. unsigned NumLocations = 0, Loc;
  2709. unsigned Repeats = 1;
  2710. unsigned I;
  2711. /* Count the number of locations. */
  2712. while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
  2713. ++NumLocations;
  2714. /* Parse the locations. */
  2715. assert(NumLocations > 0 && "Unable to count locations?");
  2716. Locations = (CursorSourceLocation *)malloc(
  2717. NumLocations * sizeof(CursorSourceLocation));
  2718. assert(Locations);
  2719. for (Loc = 0; Loc < NumLocations; ++Loc) {
  2720. const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
  2721. if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
  2722. &Locations[Loc].line,
  2723. &Locations[Loc].column, 0, 0)))
  2724. return errorCode;
  2725. }
  2726. if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
  2727. &num_unsaved_files))
  2728. return -1;
  2729. if (getenv("CINDEXTEST_EDITING"))
  2730. Repeats = 5;
  2731. /* Parse the translation unit. When we're testing clang_getCursor() after
  2732. reparsing, don't remap unsaved files until the second parse. */
  2733. CIdx = clang_createIndex(1, 1);
  2734. Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
  2735. argv + num_unsaved_files + 1 + NumLocations,
  2736. argc - num_unsaved_files - 2 - NumLocations,
  2737. unsaved_files,
  2738. Repeats > 1? 0 : num_unsaved_files,
  2739. getDefaultParsingOptions(), &TU);
  2740. if (Err != CXError_Success) {
  2741. fprintf(stderr, "unable to parse input\n");
  2742. describeLibclangFailure(Err);
  2743. clang_disposeTranslationUnit(TU);
  2744. return -1;
  2745. }
  2746. if (checkForErrors(TU) != 0)
  2747. return -1;
  2748. for (I = 0; I != Repeats; ++I) {
  2749. if (Repeats > 1) {
  2750. Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
  2751. clang_defaultReparseOptions(TU));
  2752. if (Err != CXError_Success) {
  2753. describeLibclangFailure(Err);
  2754. clang_disposeTranslationUnit(TU);
  2755. return 1;
  2756. }
  2757. }
  2758. if (checkForErrors(TU) != 0)
  2759. return -1;
  2760. for (Loc = 0; Loc < NumLocations; ++Loc) {
  2761. CXFile file = clang_getFile(TU, Locations[Loc].filename);
  2762. if (!file)
  2763. continue;
  2764. Cursor = clang_getCursor(TU,
  2765. clang_getLocation(TU, file, Locations[Loc].line,
  2766. Locations[Loc].column));
  2767. if (checkForErrors(TU) != 0)
  2768. return -1;
  2769. if (I + 1 == Repeats) {
  2770. CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
  2771. PrintCursor(Cursor, NULL);
  2772. printf("\n");
  2773. clang_findReferencesInFile(Cursor, file, visitor);
  2774. free(Locations[Loc].filename);
  2775. if (checkForErrors(TU) != 0)
  2776. return -1;
  2777. }
  2778. }
  2779. }
  2780. PrintDiagnostics(TU);
  2781. clang_disposeTranslationUnit(TU);
  2782. clang_disposeIndex(CIdx);
  2783. free(Locations);
  2784. free_remapped_files(unsaved_files, num_unsaved_files);
  2785. return 0;
  2786. }
  2787. static enum CXVisitorResult findFileIncludesVisit(void *context,
  2788. CXCursor cursor, CXSourceRange range) {
  2789. PrintCursor(cursor, NULL);
  2790. PrintRange(range, "");
  2791. printf("\n");
  2792. return CXVisit_Continue;
  2793. }
  2794. static int find_file_includes_in(int argc, const char **argv) {
  2795. CXIndex CIdx;
  2796. struct CXUnsavedFile *unsaved_files = 0;
  2797. int num_unsaved_files = 0;
  2798. enum CXErrorCode Err;
  2799. CXTranslationUnit TU;
  2800. const char **Filenames = 0;
  2801. unsigned NumFilenames = 0;
  2802. unsigned Repeats = 1;
  2803. unsigned I, FI;
  2804. /* Count the number of locations. */
  2805. while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
  2806. ++NumFilenames;
  2807. /* Parse the locations. */
  2808. assert(NumFilenames > 0 && "Unable to count filenames?");
  2809. Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
  2810. assert(Filenames);
  2811. for (I = 0; I < NumFilenames; ++I) {
  2812. const char *input = argv[I + 1] + strlen("-file-includes-in=");
  2813. /* Copy the file name. */
  2814. Filenames[I] = input;
  2815. }
  2816. if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
  2817. &num_unsaved_files))
  2818. return -1;
  2819. if (getenv("CINDEXTEST_EDITING"))
  2820. Repeats = 2;
  2821. /* Parse the translation unit. When we're testing clang_getCursor() after
  2822. reparsing, don't remap unsaved files until the second parse. */
  2823. CIdx = clang_createIndex(1, 1);
  2824. Err = clang_parseTranslationUnit2(
  2825. CIdx, argv[argc - 1],
  2826. argv + num_unsaved_files + 1 + NumFilenames,
  2827. argc - num_unsaved_files - 2 - NumFilenames,
  2828. unsaved_files,
  2829. Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
  2830. if (Err != CXError_Success) {
  2831. fprintf(stderr, "unable to parse input\n");
  2832. describeLibclangFailure(Err);
  2833. clang_disposeTranslationUnit(TU);
  2834. return -1;
  2835. }
  2836. if (checkForErrors(TU) != 0)
  2837. return -1;
  2838. for (I = 0; I != Repeats; ++I) {
  2839. if (Repeats > 1) {
  2840. Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
  2841. clang_defaultReparseOptions(TU));
  2842. if (Err != CXError_Success) {
  2843. describeLibclangFailure(Err);
  2844. clang_disposeTranslationUnit(TU);
  2845. return 1;
  2846. }
  2847. }
  2848. if (checkForErrors(TU) != 0)
  2849. return -1;
  2850. for (FI = 0; FI < NumFilenames; ++FI) {
  2851. CXFile file = clang_getFile(TU, Filenames[FI]);
  2852. if (!file)
  2853. continue;
  2854. if (checkForErrors(TU) != 0)
  2855. return -1;
  2856. if (I + 1 == Repeats) {
  2857. CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
  2858. clang_findIncludesInFile(TU, file, visitor);
  2859. if (checkForErrors(TU) != 0)
  2860. return -1;
  2861. }
  2862. }
  2863. }
  2864. PrintDiagnostics(TU);
  2865. clang_disposeTranslationUnit(TU);
  2866. clang_disposeIndex(CIdx);
  2867. free((void *)Filenames);
  2868. free_remapped_files(unsaved_files, num_unsaved_files);
  2869. return 0;
  2870. }
  2871. #define MAX_IMPORTED_ASTFILES 200
  2872. typedef struct {
  2873. char **filenames;
  2874. unsigned num_files;
  2875. } ImportedASTFilesData;
  2876. static ImportedASTFilesData *importedASTs_create() {
  2877. ImportedASTFilesData *p;
  2878. p = malloc(sizeof(ImportedASTFilesData));
  2879. assert(p);
  2880. p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
  2881. assert(p->filenames);
  2882. p->num_files = 0;
  2883. return p;
  2884. }
  2885. static void importedASTs_dispose(ImportedASTFilesData *p) {
  2886. unsigned i;
  2887. if (!p)
  2888. return;
  2889. for (i = 0; i < p->num_files; ++i)
  2890. free(p->filenames[i]);
  2891. free(p->filenames);
  2892. free(p);
  2893. }
  2894. static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
  2895. unsigned i;
  2896. assert(p && file);
  2897. for (i = 0; i < p->num_files; ++i)
  2898. if (strcmp(file, p->filenames[i]) == 0)
  2899. return;
  2900. assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
  2901. p->filenames[p->num_files++] = strdup(file);
  2902. }
  2903. typedef struct IndexDataStringList_ {
  2904. struct IndexDataStringList_ *next;
  2905. char data[1]; /* Dynamically sized. */
  2906. } IndexDataStringList;
  2907. typedef struct {
  2908. const char *check_prefix;
  2909. int first_check_printed;
  2910. int fail_for_error;
  2911. int abort;
  2912. CXString main_filename;
  2913. ImportedASTFilesData *importedASTs;
  2914. IndexDataStringList *strings;
  2915. CXTranslationUnit TU;
  2916. } IndexData;
  2917. static void free_client_data(IndexData *index_data) {
  2918. IndexDataStringList *node = index_data->strings;
  2919. while (node) {
  2920. IndexDataStringList *next = node->next;
  2921. free(node);
  2922. node = next;
  2923. }
  2924. index_data->strings = NULL;
  2925. }
  2926. static void printCheck(IndexData *data) {
  2927. if (data->check_prefix) {
  2928. if (data->first_check_printed) {
  2929. printf("// %s-NEXT: ", data->check_prefix);
  2930. } else {
  2931. printf("// %s : ", data->check_prefix);
  2932. data->first_check_printed = 1;
  2933. }
  2934. }
  2935. }
  2936. static void printCXIndexFile(CXIdxClientFile file) {
  2937. CXString filename = clang_getFileName((CXFile)file);
  2938. printf("%s", clang_getCString(filename));
  2939. clang_disposeString(filename);
  2940. }
  2941. static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
  2942. IndexData *index_data;
  2943. CXString filename;
  2944. const char *cname;
  2945. CXIdxClientFile file;
  2946. unsigned line, column;
  2947. const char *main_filename;
  2948. int isMainFile;
  2949. index_data = (IndexData *)client_data;
  2950. clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
  2951. if (line == 0) {
  2952. printf("<invalid>");
  2953. return;
  2954. }
  2955. if (!file) {
  2956. printf("<no idxfile>");
  2957. return;
  2958. }
  2959. filename = clang_getFileName((CXFile)file);
  2960. cname = clang_getCString(filename);
  2961. main_filename = clang_getCString(index_data->main_filename);
  2962. if (strcmp(cname, main_filename) == 0)
  2963. isMainFile = 1;
  2964. else
  2965. isMainFile = 0;
  2966. clang_disposeString(filename);
  2967. if (!isMainFile) {
  2968. printCXIndexFile(file);
  2969. printf(":");
  2970. }
  2971. printf("%d:%d", line, column);
  2972. }
  2973. static unsigned digitCount(unsigned val) {
  2974. unsigned c = 1;
  2975. while (1) {
  2976. if (val < 10)
  2977. return c;
  2978. ++c;
  2979. val /= 10;
  2980. }
  2981. }
  2982. static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
  2983. const CXIdxEntityInfo *info,
  2984. CXIdxLoc loc) {
  2985. IndexData *index_data;
  2986. IndexDataStringList *node;
  2987. const char *name;
  2988. char *newStr;
  2989. CXIdxClientFile file;
  2990. unsigned line, column;
  2991. name = info->name;
  2992. if (!name)
  2993. name = "<anon-tag>";
  2994. clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
  2995. node =
  2996. (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
  2997. digitCount(line) + digitCount(column) + 2);
  2998. assert(node);
  2999. newStr = node->data;
  3000. sprintf(newStr, "%s:%d:%d", name, line, column);
  3001. /* Remember string so it can be freed later. */
  3002. index_data = (IndexData *)client_data;
  3003. node->next = index_data->strings;
  3004. index_data->strings = node;
  3005. return (CXIdxClientContainer)newStr;
  3006. }
  3007. static void printCXIndexContainer(const CXIdxContainerInfo *info) {
  3008. CXIdxClientContainer container;
  3009. container = clang_index_getClientContainer(info);
  3010. if (!container)
  3011. printf("[<<NULL>>]");
  3012. else
  3013. printf("[%s]", (const char *)container);
  3014. }
  3015. static const char *getEntityKindString(CXIdxEntityKind kind) {
  3016. switch (kind) {
  3017. case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
  3018. case CXIdxEntity_Typedef: return "typedef";
  3019. case CXIdxEntity_Function: return "function";
  3020. case CXIdxEntity_Variable: return "variable";
  3021. case CXIdxEntity_Field: return "field";
  3022. case CXIdxEntity_EnumConstant: return "enumerator";
  3023. case CXIdxEntity_ObjCClass: return "objc-class";
  3024. case CXIdxEntity_ObjCProtocol: return "objc-protocol";
  3025. case CXIdxEntity_ObjCCategory: return "objc-category";
  3026. case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
  3027. case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
  3028. case CXIdxEntity_ObjCProperty: return "objc-property";
  3029. case CXIdxEntity_ObjCIvar: return "objc-ivar";
  3030. case CXIdxEntity_Enum: return "enum";
  3031. case CXIdxEntity_Struct: return "struct";
  3032. case CXIdxEntity_Union: return "union";
  3033. case CXIdxEntity_CXXClass: return "c++-class";
  3034. case CXIdxEntity_CXXNamespace: return "namespace";
  3035. case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
  3036. case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
  3037. case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
  3038. case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
  3039. case CXIdxEntity_CXXConstructor: return "constructor";
  3040. case CXIdxEntity_CXXDestructor: return "destructor";
  3041. case CXIdxEntity_CXXConversionFunction: return "conversion-func";
  3042. case CXIdxEntity_CXXTypeAlias: return "type-alias";
  3043. case CXIdxEntity_CXXInterface: return "c++-__interface";
  3044. }
  3045. assert(0 && "Garbage entity kind");
  3046. return 0;
  3047. }
  3048. static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
  3049. switch (kind) {
  3050. case CXIdxEntity_NonTemplate: return "";
  3051. case CXIdxEntity_Template: return "-template";
  3052. case CXIdxEntity_TemplatePartialSpecialization:
  3053. return "-template-partial-spec";
  3054. case CXIdxEntity_TemplateSpecialization: return "-template-spec";
  3055. }
  3056. assert(0 && "Garbage entity kind");
  3057. return 0;
  3058. }
  3059. static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
  3060. switch (kind) {
  3061. case CXIdxEntityLang_None: return "<none>";
  3062. case CXIdxEntityLang_C: return "C";
  3063. case CXIdxEntityLang_ObjC: return "ObjC";
  3064. case CXIdxEntityLang_CXX: return "C++";
  3065. case CXIdxEntityLang_Swift: return "Swift";
  3066. }
  3067. assert(0 && "Garbage language kind");
  3068. return 0;
  3069. }
  3070. static void printEntityInfo(const char *cb,
  3071. CXClientData client_data,
  3072. const CXIdxEntityInfo *info) {
  3073. const char *name;
  3074. IndexData *index_data;
  3075. unsigned i;
  3076. index_data = (IndexData *)client_data;
  3077. printCheck(index_data);
  3078. if (!info) {
  3079. printf("%s: <<NULL>>", cb);
  3080. return;
  3081. }
  3082. name = info->name;
  3083. if (!name)
  3084. name = "<anon-tag>";
  3085. printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
  3086. getEntityTemplateKindString(info->templateKind));
  3087. printf(" | name: %s", name);
  3088. printf(" | USR: %s", info->USR);
  3089. printf(" | lang: %s", getEntityLanguageString(info->lang));
  3090. for (i = 0; i != info->numAttributes; ++i) {
  3091. const CXIdxAttrInfo *Attr = info->attributes[i];
  3092. printf(" <attribute>: ");
  3093. PrintCursor(Attr->cursor, NULL);
  3094. }
  3095. }
  3096. static void printBaseClassInfo(CXClientData client_data,
  3097. const CXIdxBaseClassInfo *info) {
  3098. printEntityInfo(" <base>", client_data, info->base);
  3099. printf(" | cursor: ");
  3100. PrintCursor(info->cursor, NULL);
  3101. printf(" | loc: ");
  3102. printCXIndexLoc(info->loc, client_data);
  3103. }
  3104. static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
  3105. CXClientData client_data) {
  3106. unsigned i;
  3107. for (i = 0; i < ProtoInfo->numProtocols; ++i) {
  3108. printEntityInfo(" <protocol>", client_data,
  3109. ProtoInfo->protocols[i]->protocol);
  3110. printf(" | cursor: ");
  3111. PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
  3112. printf(" | loc: ");
  3113. printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
  3114. printf("\n");
  3115. }
  3116. }
  3117. static void printSymbolRole(CXSymbolRole role) {
  3118. if (role & CXSymbolRole_Declaration)
  3119. printf(" decl");
  3120. if (role & CXSymbolRole_Definition)
  3121. printf(" def");
  3122. if (role & CXSymbolRole_Reference)
  3123. printf(" ref");
  3124. if (role & CXSymbolRole_Read)
  3125. printf(" read");
  3126. if (role & CXSymbolRole_Write)
  3127. printf(" write");
  3128. if (role & CXSymbolRole_Call)
  3129. printf(" call");
  3130. if (role & CXSymbolRole_Dynamic)
  3131. printf(" dyn");
  3132. if (role & CXSymbolRole_AddressOf)
  3133. printf(" addr");
  3134. if (role & CXSymbolRole_Implicit)
  3135. printf(" implicit");
  3136. }
  3137. static void index_diagnostic(CXClientData client_data,
  3138. CXDiagnosticSet diagSet, void *reserved) {
  3139. CXString str;
  3140. const char *cstr;
  3141. unsigned numDiags, i;
  3142. CXDiagnostic diag;
  3143. IndexData *index_data;
  3144. index_data = (IndexData *)client_data;
  3145. printCheck(index_data);
  3146. numDiags = clang_getNumDiagnosticsInSet(diagSet);
  3147. for (i = 0; i != numDiags; ++i) {
  3148. diag = clang_getDiagnosticInSet(diagSet, i);
  3149. str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
  3150. cstr = clang_getCString(str);
  3151. printf("[diagnostic]: %s\n", cstr);
  3152. clang_disposeString(str);
  3153. if (getenv("CINDEXTEST_FAILONERROR") &&
  3154. clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
  3155. index_data->fail_for_error = 1;
  3156. }
  3157. }
  3158. }
  3159. static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
  3160. CXFile file, void *reserved) {
  3161. IndexData *index_data;
  3162. index_data = (IndexData *)client_data;
  3163. printCheck(index_data);
  3164. index_data->main_filename = clang_getFileName(file);
  3165. printf("[enteredMainFile]: ");
  3166. printCXIndexFile((CXIdxClientFile)file);
  3167. printf("\n");
  3168. return (CXIdxClientFile)file;
  3169. }
  3170. static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
  3171. const CXIdxIncludedFileInfo *info) {
  3172. IndexData *index_data;
  3173. CXModule Mod;
  3174. index_data = (IndexData *)client_data;
  3175. printCheck(index_data);
  3176. printf("[ppIncludedFile]: ");
  3177. printCXIndexFile((CXIdxClientFile)info->file);
  3178. printf(" | name: \"%s\"", info->filename);
  3179. printf(" | hash loc: ");
  3180. printCXIndexLoc(info->hashLoc, client_data);
  3181. printf(" | isImport: %d | isAngled: %d | isModule: %d",
  3182. info->isImport, info->isAngled, info->isModuleImport);
  3183. Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
  3184. if (Mod) {
  3185. CXString str = clang_Module_getFullName(Mod);
  3186. const char *cstr = clang_getCString(str);
  3187. printf(" | module: %s", cstr);
  3188. clang_disposeString(str);
  3189. }
  3190. printf("\n");
  3191. return (CXIdxClientFile)info->file;
  3192. }
  3193. static CXIdxClientFile index_importedASTFile(CXClientData client_data,
  3194. const CXIdxImportedASTFileInfo *info) {
  3195. IndexData *index_data;
  3196. index_data = (IndexData *)client_data;
  3197. printCheck(index_data);
  3198. if (index_data->importedASTs) {
  3199. CXString filename = clang_getFileName(info->file);
  3200. importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
  3201. clang_disposeString(filename);
  3202. }
  3203. printf("[importedASTFile]: ");
  3204. printCXIndexFile((CXIdxClientFile)info->file);
  3205. if (info->module) {
  3206. CXString name = clang_Module_getFullName(info->module);
  3207. printf(" | loc: ");
  3208. printCXIndexLoc(info->loc, client_data);
  3209. printf(" | name: \"%s\"", clang_getCString(name));
  3210. printf(" | isImplicit: %d\n", info->isImplicit);
  3211. clang_disposeString(name);
  3212. } else {
  3213. /* PCH file, the rest are not relevant. */
  3214. printf("\n");
  3215. }
  3216. return (CXIdxClientFile)info->file;
  3217. }
  3218. static CXIdxClientContainer
  3219. index_startedTranslationUnit(CXClientData client_data, void *reserved) {
  3220. IndexData *index_data;
  3221. index_data = (IndexData *)client_data;
  3222. printCheck(index_data);
  3223. printf("[startedTranslationUnit]\n");
  3224. return (CXIdxClientContainer)"TU";
  3225. }
  3226. static void index_indexDeclaration(CXClientData client_data,
  3227. const CXIdxDeclInfo *info) {
  3228. IndexData *index_data;
  3229. const CXIdxObjCCategoryDeclInfo *CatInfo;
  3230. const CXIdxObjCInterfaceDeclInfo *InterInfo;
  3231. const CXIdxObjCProtocolRefListInfo *ProtoInfo;
  3232. const CXIdxObjCPropertyDeclInfo *PropInfo;
  3233. const CXIdxCXXClassDeclInfo *CXXClassInfo;
  3234. unsigned i;
  3235. index_data = (IndexData *)client_data;
  3236. printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
  3237. printf(" | cursor: ");
  3238. PrintCursor(info->cursor, NULL);
  3239. printf(" | loc: ");
  3240. printCXIndexLoc(info->loc, client_data);
  3241. printf(" | semantic-container: ");
  3242. printCXIndexContainer(info->semanticContainer);
  3243. printf(" | lexical-container: ");
  3244. printCXIndexContainer(info->lexicalContainer);
  3245. printf(" | isRedecl: %d", info->isRedeclaration);
  3246. printf(" | isDef: %d", info->isDefinition);
  3247. if (info->flags & CXIdxDeclFlag_Skipped) {
  3248. assert(!info->isContainer);
  3249. printf(" | isContainer: skipped");
  3250. } else {
  3251. printf(" | isContainer: %d", info->isContainer);
  3252. }
  3253. printf(" | isImplicit: %d\n", info->isImplicit);
  3254. for (i = 0; i != info->numAttributes; ++i) {
  3255. const CXIdxAttrInfo *Attr = info->attributes[i];
  3256. printf(" <attribute>: ");
  3257. PrintCursor(Attr->cursor, NULL);
  3258. printf("\n");
  3259. }
  3260. if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
  3261. const char *kindName = 0;
  3262. CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
  3263. switch (K) {
  3264. case CXIdxObjCContainer_ForwardRef:
  3265. kindName = "forward-ref"; break;
  3266. case CXIdxObjCContainer_Interface:
  3267. kindName = "interface"; break;
  3268. case CXIdxObjCContainer_Implementation:
  3269. kindName = "implementation"; break;
  3270. }
  3271. printCheck(index_data);
  3272. printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
  3273. }
  3274. if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
  3275. printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
  3276. CatInfo->objcClass);
  3277. printf(" | cursor: ");
  3278. PrintCursor(CatInfo->classCursor, NULL);
  3279. printf(" | loc: ");
  3280. printCXIndexLoc(CatInfo->classLoc, client_data);
  3281. printf("\n");
  3282. }
  3283. if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
  3284. if (InterInfo->superInfo) {
  3285. printBaseClassInfo(client_data, InterInfo->superInfo);
  3286. printf("\n");
  3287. }
  3288. }
  3289. if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
  3290. printProtocolList(ProtoInfo, client_data);
  3291. }
  3292. if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
  3293. if (PropInfo->getter) {
  3294. printEntityInfo(" <getter>", client_data, PropInfo->getter);
  3295. printf("\n");
  3296. }
  3297. if (PropInfo->setter) {
  3298. printEntityInfo(" <setter>", client_data, PropInfo->setter);
  3299. printf("\n");
  3300. }
  3301. }
  3302. if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
  3303. for (i = 0; i != CXXClassInfo->numBases; ++i) {
  3304. printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
  3305. printf("\n");
  3306. }
  3307. }
  3308. if (info->declAsContainer)
  3309. clang_index_setClientContainer(
  3310. info->declAsContainer,
  3311. makeClientContainer(client_data, info->entityInfo, info->loc));
  3312. }
  3313. static void index_indexEntityReference(CXClientData client_data,
  3314. const CXIdxEntityRefInfo *info) {
  3315. printEntityInfo("[indexEntityReference]", client_data,
  3316. info->referencedEntity);
  3317. printf(" | cursor: ");
  3318. PrintCursor(info->cursor, NULL);
  3319. printf(" | loc: ");
  3320. printCXIndexLoc(info->loc, client_data);
  3321. printEntityInfo(" | <parent>:", client_data, info->parentEntity);
  3322. printf(" | container: ");
  3323. printCXIndexContainer(info->container);
  3324. printf(" | refkind: ");
  3325. switch (info->kind) {
  3326. case CXIdxEntityRef_Direct: printf("direct"); break;
  3327. case CXIdxEntityRef_Implicit: printf("implicit"); break;
  3328. }
  3329. printf(" | role:");
  3330. printSymbolRole(info->role);
  3331. printf("\n");
  3332. }
  3333. static int index_abortQuery(CXClientData client_data, void *reserved) {
  3334. IndexData *index_data;
  3335. index_data = (IndexData *)client_data;
  3336. return index_data->abort;
  3337. }
  3338. static IndexerCallbacks IndexCB = {
  3339. index_abortQuery,
  3340. index_diagnostic,
  3341. index_enteredMainFile,
  3342. index_ppIncludedFile,
  3343. index_importedASTFile,
  3344. index_startedTranslationUnit,
  3345. index_indexDeclaration,
  3346. index_indexEntityReference
  3347. };
  3348. static unsigned getIndexOptions(void) {
  3349. unsigned index_opts;
  3350. index_opts = 0;
  3351. if (getenv("CINDEXTEST_SUPPRESSREFS"))
  3352. index_opts |= CXIndexOpt_SuppressRedundantRefs;
  3353. if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
  3354. index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
  3355. if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
  3356. index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
  3357. if (getenv("CINDEXTEST_INDEXIMPLICITTEMPLATEINSTANTIATIONS"))
  3358. index_opts |= CXIndexOpt_IndexImplicitTemplateInstantiations;
  3359. return index_opts;
  3360. }
  3361. static int index_compile_args(int num_args, const char **args,
  3362. CXIndexAction idxAction,
  3363. ImportedASTFilesData *importedASTs,
  3364. const char *check_prefix) {
  3365. IndexData index_data;
  3366. unsigned index_opts;
  3367. int result;
  3368. if (num_args == 0) {
  3369. fprintf(stderr, "no compiler arguments\n");
  3370. return -1;
  3371. }
  3372. index_data.check_prefix = check_prefix;
  3373. index_data.first_check_printed = 0;
  3374. index_data.fail_for_error = 0;
  3375. index_data.abort = 0;
  3376. index_data.main_filename = createCXString("");
  3377. index_data.importedASTs = importedASTs;
  3378. index_data.strings = NULL;
  3379. index_data.TU = NULL;
  3380. index_opts = getIndexOptions();
  3381. result = clang_indexSourceFile(idxAction, &index_data,
  3382. &IndexCB,sizeof(IndexCB), index_opts,
  3383. 0, args, num_args, 0, 0, 0,
  3384. getDefaultParsingOptions());
  3385. if (result != CXError_Success)
  3386. describeLibclangFailure(result);
  3387. if (index_data.fail_for_error)
  3388. result = -1;
  3389. clang_disposeString(index_data.main_filename);
  3390. free_client_data(&index_data);
  3391. return result;
  3392. }
  3393. static int index_ast_file(const char *ast_file,
  3394. CXIndex Idx,
  3395. CXIndexAction idxAction,
  3396. ImportedASTFilesData *importedASTs,
  3397. const char *check_prefix) {
  3398. CXTranslationUnit TU;
  3399. IndexData index_data;
  3400. unsigned index_opts;
  3401. int result;
  3402. if (!CreateTranslationUnit(Idx, ast_file, &TU))
  3403. return -1;
  3404. index_data.check_prefix = check_prefix;
  3405. index_data.first_check_printed = 0;
  3406. index_data.fail_for_error = 0;
  3407. index_data.abort = 0;
  3408. index_data.main_filename = createCXString("");
  3409. index_data.importedASTs = importedASTs;
  3410. index_data.strings = NULL;
  3411. index_data.TU = TU;
  3412. index_opts = getIndexOptions();
  3413. result = clang_indexTranslationUnit(idxAction, &index_data,
  3414. &IndexCB,sizeof(IndexCB),
  3415. index_opts, TU);
  3416. if (index_data.fail_for_error)
  3417. result = -1;
  3418. clang_disposeTranslationUnit(TU);
  3419. clang_disposeString(index_data.main_filename);
  3420. free_client_data(&index_data);
  3421. return result;
  3422. }
  3423. static int index_file(int argc, const char **argv, int full) {
  3424. const char *check_prefix;
  3425. CXIndex Idx;
  3426. CXIndexAction idxAction;
  3427. ImportedASTFilesData *importedASTs;
  3428. int result;
  3429. check_prefix = 0;
  3430. if (argc > 0) {
  3431. if (strstr(argv[0], "-check-prefix=") == argv[0]) {
  3432. check_prefix = argv[0] + strlen("-check-prefix=");
  3433. ++argv;
  3434. --argc;
  3435. }
  3436. }
  3437. if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
  3438. /* displayDiagnostics=*/1))) {
  3439. fprintf(stderr, "Could not create Index\n");
  3440. return 1;
  3441. }
  3442. idxAction = clang_IndexAction_create(Idx);
  3443. importedASTs = 0;
  3444. if (full)
  3445. importedASTs = importedASTs_create();
  3446. result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
  3447. if (result != 0)
  3448. goto finished;
  3449. if (full) {
  3450. unsigned i;
  3451. for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
  3452. result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
  3453. importedASTs, check_prefix);
  3454. }
  3455. }
  3456. finished:
  3457. importedASTs_dispose(importedASTs);
  3458. clang_IndexAction_dispose(idxAction);
  3459. clang_disposeIndex(Idx);
  3460. return result;
  3461. }
  3462. static int index_tu(int argc, const char **argv) {
  3463. const char *check_prefix;
  3464. CXIndex Idx;
  3465. CXIndexAction idxAction;
  3466. int result;
  3467. check_prefix = 0;
  3468. if (argc > 0) {
  3469. if (strstr(argv[0], "-check-prefix=") == argv[0]) {
  3470. check_prefix = argv[0] + strlen("-check-prefix=");
  3471. ++argv;
  3472. --argc;
  3473. }
  3474. }
  3475. if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
  3476. /* displayDiagnostics=*/1))) {
  3477. fprintf(stderr, "Could not create Index\n");
  3478. return 1;
  3479. }
  3480. idxAction = clang_IndexAction_create(Idx);
  3481. result = index_ast_file(argv[0], Idx, idxAction,
  3482. /*importedASTs=*/0, check_prefix);
  3483. clang_IndexAction_dispose(idxAction);
  3484. clang_disposeIndex(Idx);
  3485. return result;
  3486. }
  3487. static int index_compile_db(int argc, const char **argv) {
  3488. const char *check_prefix;
  3489. CXIndex Idx;
  3490. CXIndexAction idxAction;
  3491. int errorCode = 0;
  3492. check_prefix = 0;
  3493. if (argc > 0) {
  3494. if (strstr(argv[0], "-check-prefix=") == argv[0]) {
  3495. check_prefix = argv[0] + strlen("-check-prefix=");
  3496. ++argv;
  3497. --argc;
  3498. }
  3499. }
  3500. if (argc == 0) {
  3501. fprintf(stderr, "no compilation database\n");
  3502. return -1;
  3503. }
  3504. if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
  3505. /* displayDiagnostics=*/1))) {
  3506. fprintf(stderr, "Could not create Index\n");
  3507. return 1;
  3508. }
  3509. idxAction = clang_IndexAction_create(Idx);
  3510. {
  3511. const char *database = argv[0];
  3512. CXCompilationDatabase db = 0;
  3513. CXCompileCommands CCmds = 0;
  3514. CXCompileCommand CCmd;
  3515. CXCompilationDatabase_Error ec;
  3516. CXString wd;
  3517. #define MAX_COMPILE_ARGS 512
  3518. CXString cxargs[MAX_COMPILE_ARGS];
  3519. const char *args[MAX_COMPILE_ARGS];
  3520. char *tmp;
  3521. unsigned len;
  3522. char *buildDir;
  3523. int i, a, numCmds, numArgs;
  3524. len = strlen(database);
  3525. tmp = (char *) malloc(len+1);
  3526. assert(tmp);
  3527. memcpy(tmp, database, len+1);
  3528. buildDir = dirname(tmp);
  3529. db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
  3530. if (db) {
  3531. if (ec!=CXCompilationDatabase_NoError) {
  3532. printf("unexpected error %d code while loading compilation database\n", ec);
  3533. errorCode = -1;
  3534. goto cdb_end;
  3535. }
  3536. if (chdir(buildDir) != 0) {
  3537. printf("Could not chdir to %s\n", buildDir);
  3538. errorCode = -1;
  3539. goto cdb_end;
  3540. }
  3541. CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
  3542. if (!CCmds) {
  3543. printf("compilation db is empty\n");
  3544. errorCode = -1;
  3545. goto cdb_end;
  3546. }
  3547. numCmds = clang_CompileCommands_getSize(CCmds);
  3548. if (numCmds==0) {
  3549. fprintf(stderr, "should not get an empty compileCommand set\n");
  3550. errorCode = -1;
  3551. goto cdb_end;
  3552. }
  3553. for (i=0; i<numCmds && errorCode == 0; ++i) {
  3554. CCmd = clang_CompileCommands_getCommand(CCmds, i);
  3555. wd = clang_CompileCommand_getDirectory(CCmd);
  3556. if (chdir(clang_getCString(wd)) != 0) {
  3557. printf("Could not chdir to %s\n", clang_getCString(wd));
  3558. errorCode = -1;
  3559. goto cdb_end;
  3560. }
  3561. clang_disposeString(wd);
  3562. numArgs = clang_CompileCommand_getNumArgs(CCmd);
  3563. if (numArgs > MAX_COMPILE_ARGS){
  3564. fprintf(stderr, "got more compile arguments than maximum\n");
  3565. errorCode = -1;
  3566. goto cdb_end;
  3567. }
  3568. for (a=0; a<numArgs; ++a) {
  3569. cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
  3570. args[a] = clang_getCString(cxargs[a]);
  3571. }
  3572. errorCode = index_compile_args(numArgs, args, idxAction,
  3573. /*importedASTs=*/0, check_prefix);
  3574. for (a=0; a<numArgs; ++a)
  3575. clang_disposeString(cxargs[a]);
  3576. }
  3577. } else {
  3578. printf("database loading failed with error code %d.\n", ec);
  3579. errorCode = -1;
  3580. }
  3581. cdb_end:
  3582. clang_CompileCommands_dispose(CCmds);
  3583. clang_CompilationDatabase_dispose(db);
  3584. free(tmp);
  3585. }
  3586. clang_IndexAction_dispose(idxAction);
  3587. clang_disposeIndex(Idx);
  3588. return errorCode;
  3589. }
  3590. int perform_token_annotation(int argc, const char **argv) {
  3591. const char *input = argv[1];
  3592. char *filename = 0;
  3593. unsigned line, second_line;
  3594. unsigned column, second_column;
  3595. CXIndex CIdx;
  3596. CXTranslationUnit TU = 0;
  3597. int errorCode;
  3598. struct CXUnsavedFile *unsaved_files = 0;
  3599. int num_unsaved_files = 0;
  3600. CXToken *tokens;
  3601. unsigned num_tokens;
  3602. CXSourceRange range;
  3603. CXSourceLocation startLoc, endLoc;
  3604. CXFile file = 0;
  3605. CXCursor *cursors = 0;
  3606. CXSourceRangeList *skipped_ranges = 0;
  3607. enum CXErrorCode Err;
  3608. unsigned i;
  3609. input += strlen("-test-annotate-tokens=");
  3610. if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
  3611. &second_line, &second_column)))
  3612. return errorCode;
  3613. if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
  3614. free(filename);
  3615. return -1;
  3616. }
  3617. CIdx = clang_createIndex(0, 1);
  3618. Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
  3619. argv + num_unsaved_files + 2,
  3620. argc - num_unsaved_files - 3,
  3621. unsaved_files,
  3622. num_unsaved_files,
  3623. getDefaultParsingOptions(), &TU);
  3624. if (Err != CXError_Success) {
  3625. fprintf(stderr, "unable to parse input\n");
  3626. describeLibclangFailure(Err);
  3627. clang_disposeIndex(CIdx);
  3628. free(filename);
  3629. free_remapped_files(unsaved_files, num_unsaved_files);
  3630. return -1;
  3631. }
  3632. errorCode = 0;
  3633. if (checkForErrors(TU) != 0) {
  3634. errorCode = -1;
  3635. goto teardown;
  3636. }
  3637. if (getenv("CINDEXTEST_EDITING")) {
  3638. for (i = 0; i < 5; ++i) {
  3639. Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
  3640. clang_defaultReparseOptions(TU));
  3641. if (Err != CXError_Success) {
  3642. fprintf(stderr, "Unable to reparse translation unit!\n");
  3643. describeLibclangFailure(Err);
  3644. errorCode = -1;
  3645. goto teardown;
  3646. }
  3647. }
  3648. }
  3649. if (checkForErrors(TU) != 0) {
  3650. errorCode = -1;
  3651. goto teardown;
  3652. }
  3653. file = clang_getFile(TU, filename);
  3654. if (!file) {
  3655. fprintf(stderr, "file %s is not in this translation unit\n", filename);
  3656. errorCode = -1;
  3657. goto teardown;
  3658. }
  3659. startLoc = clang_getLocation(TU, file, line, column);
  3660. if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
  3661. fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
  3662. column);
  3663. errorCode = -1;
  3664. goto teardown;
  3665. }
  3666. endLoc = clang_getLocation(TU, file, second_line, second_column);
  3667. if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
  3668. fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
  3669. second_line, second_column);
  3670. errorCode = -1;
  3671. goto teardown;
  3672. }
  3673. range = clang_getRange(startLoc, endLoc);
  3674. clang_tokenize(TU, range, &tokens, &num_tokens);
  3675. if (checkForErrors(TU) != 0) {
  3676. errorCode = -1;
  3677. goto teardown;
  3678. }
  3679. cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
  3680. assert(cursors);
  3681. clang_annotateTokens(TU, tokens, num_tokens, cursors);
  3682. if (checkForErrors(TU) != 0) {
  3683. errorCode = -1;
  3684. goto teardown;
  3685. }
  3686. skipped_ranges = clang_getSkippedRanges(TU, file);
  3687. for (i = 0; i != skipped_ranges->count; ++i) {
  3688. unsigned start_line, start_column, end_line, end_column;
  3689. clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
  3690. 0, &start_line, &start_column, 0);
  3691. clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
  3692. 0, &end_line, &end_column, 0);
  3693. printf("Skipping: ");
  3694. PrintExtent(stdout, start_line, start_column, end_line, end_column);
  3695. printf("\n");
  3696. }
  3697. clang_disposeSourceRangeList(skipped_ranges);
  3698. for (i = 0; i != num_tokens; ++i) {
  3699. const char *kind = "<unknown>";
  3700. CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
  3701. CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
  3702. unsigned start_line, start_column, end_line, end_column;
  3703. switch (clang_getTokenKind(tokens[i])) {
  3704. case CXToken_Punctuation: kind = "Punctuation"; break;
  3705. case CXToken_Keyword: kind = "Keyword"; break;
  3706. case CXToken_Identifier: kind = "Identifier"; break;
  3707. case CXToken_Literal: kind = "Literal"; break;
  3708. case CXToken_Comment: kind = "Comment"; break;
  3709. }
  3710. clang_getSpellingLocation(clang_getRangeStart(extent),
  3711. 0, &start_line, &start_column, 0);
  3712. clang_getSpellingLocation(clang_getRangeEnd(extent),
  3713. 0, &end_line, &end_column, 0);
  3714. printf("%s: \"%s\" ", kind, clang_getCString(spelling));
  3715. clang_disposeString(spelling);
  3716. PrintExtent(stdout, start_line, start_column, end_line, end_column);
  3717. if (!clang_isInvalid(cursors[i].kind)) {
  3718. printf(" ");
  3719. PrintCursor(cursors[i], NULL);
  3720. }
  3721. printf("\n");
  3722. }
  3723. free(cursors);
  3724. clang_disposeTokens(TU, tokens, num_tokens);
  3725. teardown:
  3726. PrintDiagnostics(TU);
  3727. clang_disposeTranslationUnit(TU);
  3728. clang_disposeIndex(CIdx);
  3729. free(filename);
  3730. free_remapped_files(unsaved_files, num_unsaved_files);
  3731. return errorCode;
  3732. }
  3733. static int
  3734. perform_test_compilation_db(const char *database, int argc, const char **argv) {
  3735. CXCompilationDatabase db;
  3736. CXCompileCommands CCmds;
  3737. CXCompileCommand CCmd;
  3738. CXCompilationDatabase_Error ec;
  3739. CXString wd;
  3740. CXString arg;
  3741. int errorCode = 0;
  3742. char *tmp;
  3743. unsigned len;
  3744. char *buildDir;
  3745. int i, j, a, numCmds, numArgs;
  3746. len = strlen(database);
  3747. tmp = (char *) malloc(len+1);
  3748. assert(tmp);
  3749. memcpy(tmp, database, len+1);
  3750. buildDir = dirname(tmp);
  3751. db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
  3752. if (db) {
  3753. if (ec!=CXCompilationDatabase_NoError) {
  3754. printf("unexpected error %d code while loading compilation database\n", ec);
  3755. errorCode = -1;
  3756. goto cdb_end;
  3757. }
  3758. for (i=0; i<argc && errorCode==0; ) {
  3759. if (strcmp(argv[i],"lookup")==0){
  3760. CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
  3761. if (!CCmds) {
  3762. printf("file %s not found in compilation db\n", argv[i+1]);
  3763. errorCode = -1;
  3764. break;
  3765. }
  3766. numCmds = clang_CompileCommands_getSize(CCmds);
  3767. if (numCmds==0) {
  3768. fprintf(stderr, "should not get an empty compileCommand set for file"
  3769. " '%s'\n", argv[i+1]);
  3770. errorCode = -1;
  3771. break;
  3772. }
  3773. for (j=0; j<numCmds; ++j) {
  3774. CCmd = clang_CompileCommands_getCommand(CCmds, j);
  3775. wd = clang_CompileCommand_getDirectory(CCmd);
  3776. printf("workdir:'%s'", clang_getCString(wd));
  3777. clang_disposeString(wd);
  3778. printf(" cmdline:'");
  3779. numArgs = clang_CompileCommand_getNumArgs(CCmd);
  3780. for (a=0; a<numArgs; ++a) {
  3781. if (a) printf(" ");
  3782. arg = clang_CompileCommand_getArg(CCmd, a);
  3783. printf("%s", clang_getCString(arg));
  3784. clang_disposeString(arg);
  3785. }
  3786. printf("'\n");
  3787. }
  3788. clang_CompileCommands_dispose(CCmds);
  3789. i += 2;
  3790. }
  3791. }
  3792. clang_CompilationDatabase_dispose(db);
  3793. } else {
  3794. printf("database loading failed with error code %d.\n", ec);
  3795. errorCode = -1;
  3796. }
  3797. cdb_end:
  3798. free(tmp);
  3799. return errorCode;
  3800. }
  3801. /******************************************************************************/
  3802. /* USR printing. */
  3803. /******************************************************************************/
  3804. static int insufficient_usr(const char *kind, const char *usage) {
  3805. fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
  3806. return 1;
  3807. }
  3808. static unsigned isUSR(const char *s) {
  3809. return s[0] == 'c' && s[1] == ':';
  3810. }
  3811. static int not_usr(const char *s, const char *arg) {
  3812. fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
  3813. return 1;
  3814. }
  3815. static void print_usr(CXString usr) {
  3816. const char *s = clang_getCString(usr);
  3817. printf("%s\n", s);
  3818. clang_disposeString(usr);
  3819. }
  3820. static void display_usrs() {
  3821. fprintf(stderr, "-print-usrs options:\n"
  3822. " ObjCCategory <class name> <category name>\n"
  3823. " ObjCClass <class name>\n"
  3824. " ObjCIvar <ivar name> <class USR>\n"
  3825. " ObjCMethod <selector> [0=class method|1=instance method] "
  3826. "<class USR>\n"
  3827. " ObjCProperty <property name> <class USR>\n"
  3828. " ObjCProtocol <protocol name>\n");
  3829. }
  3830. int print_usrs(const char **I, const char **E) {
  3831. while (I != E) {
  3832. const char *kind = *I;
  3833. unsigned len = strlen(kind);
  3834. switch (len) {
  3835. case 8:
  3836. if (memcmp(kind, "ObjCIvar", 8) == 0) {
  3837. if (I + 2 >= E)
  3838. return insufficient_usr(kind, "<ivar name> <class USR>");
  3839. if (!isUSR(I[2]))
  3840. return not_usr("<class USR>", I[2]);
  3841. else {
  3842. CXString x = createCXString(I[2]);
  3843. print_usr(clang_constructUSR_ObjCIvar(I[1], x));
  3844. }
  3845. I += 3;
  3846. continue;
  3847. }
  3848. break;
  3849. case 9:
  3850. if (memcmp(kind, "ObjCClass", 9) == 0) {
  3851. if (I + 1 >= E)
  3852. return insufficient_usr(kind, "<class name>");
  3853. print_usr(clang_constructUSR_ObjCClass(I[1]));
  3854. I += 2;
  3855. continue;
  3856. }
  3857. break;
  3858. case 10:
  3859. if (memcmp(kind, "ObjCMethod", 10) == 0) {
  3860. if (I + 3 >= E)
  3861. return insufficient_usr(kind, "<method selector> "
  3862. "[0=class method|1=instance method] <class USR>");
  3863. if (!isUSR(I[3]))
  3864. return not_usr("<class USR>", I[3]);
  3865. else {
  3866. CXString x = createCXString(I[3]);
  3867. print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
  3868. }
  3869. I += 4;
  3870. continue;
  3871. }
  3872. break;
  3873. case 12:
  3874. if (memcmp(kind, "ObjCCategory", 12) == 0) {
  3875. if (I + 2 >= E)
  3876. return insufficient_usr(kind, "<class name> <category name>");
  3877. print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
  3878. I += 3;
  3879. continue;
  3880. }
  3881. if (memcmp(kind, "ObjCProtocol", 12) == 0) {
  3882. if (I + 1 >= E)
  3883. return insufficient_usr(kind, "<protocol name>");
  3884. print_usr(clang_constructUSR_ObjCProtocol(I[1]));
  3885. I += 2;
  3886. continue;
  3887. }
  3888. if (memcmp(kind, "ObjCProperty", 12) == 0) {
  3889. if (I + 2 >= E)
  3890. return insufficient_usr(kind, "<property name> <class USR>");
  3891. if (!isUSR(I[2]))
  3892. return not_usr("<class USR>", I[2]);
  3893. else {
  3894. CXString x = createCXString(I[2]);
  3895. print_usr(clang_constructUSR_ObjCProperty(I[1], x));
  3896. }
  3897. I += 3;
  3898. continue;
  3899. }
  3900. break;
  3901. default:
  3902. break;
  3903. }
  3904. break;
  3905. }
  3906. if (I != E) {
  3907. fprintf(stderr, "Invalid USR kind: %s\n", *I);
  3908. display_usrs();
  3909. return 1;
  3910. }
  3911. return 0;
  3912. }
  3913. int print_usrs_file(const char *file_name) {
  3914. char line[2048];
  3915. const char *args[128];
  3916. unsigned numChars = 0;
  3917. FILE *fp = fopen(file_name, "r");
  3918. if (!fp) {
  3919. fprintf(stderr, "error: cannot open '%s'\n", file_name);
  3920. return 1;
  3921. }
  3922. /* This code is not really all that safe, but it works fine for testing. */
  3923. while (!feof(fp)) {
  3924. char c = fgetc(fp);
  3925. if (c == '\n') {
  3926. unsigned i = 0;
  3927. const char *s = 0;
  3928. if (numChars == 0)
  3929. continue;
  3930. line[numChars] = '\0';
  3931. numChars = 0;
  3932. if (line[0] == '/' && line[1] == '/')
  3933. continue;
  3934. s = strtok(line, " ");
  3935. while (s) {
  3936. args[i] = s;
  3937. ++i;
  3938. s = strtok(0, " ");
  3939. }
  3940. if (print_usrs(&args[0], &args[i]))
  3941. return 1;
  3942. }
  3943. else
  3944. line[numChars++] = c;
  3945. }
  3946. fclose(fp);
  3947. return 0;
  3948. }
  3949. /******************************************************************************/
  3950. /* Command line processing. */
  3951. /******************************************************************************/
  3952. int write_pch_file(const char *filename, int argc, const char *argv[]) {
  3953. CXIndex Idx;
  3954. CXTranslationUnit TU;
  3955. struct CXUnsavedFile *unsaved_files = 0;
  3956. int num_unsaved_files = 0;
  3957. enum CXErrorCode Err;
  3958. int result = 0;
  3959. Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
  3960. if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
  3961. clang_disposeIndex(Idx);
  3962. return -1;
  3963. }
  3964. Err = clang_parseTranslationUnit2(
  3965. Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
  3966. unsaved_files, num_unsaved_files,
  3967. CXTranslationUnit_Incomplete |
  3968. CXTranslationUnit_DetailedPreprocessingRecord |
  3969. CXTranslationUnit_ForSerialization,
  3970. &TU);
  3971. if (Err != CXError_Success) {
  3972. fprintf(stderr, "Unable to load translation unit!\n");
  3973. describeLibclangFailure(Err);
  3974. free_remapped_files(unsaved_files, num_unsaved_files);
  3975. clang_disposeTranslationUnit(TU);
  3976. clang_disposeIndex(Idx);
  3977. return 1;
  3978. }
  3979. switch (clang_saveTranslationUnit(TU, filename,
  3980. clang_defaultSaveOptions(TU))) {
  3981. case CXSaveError_None:
  3982. break;
  3983. case CXSaveError_TranslationErrors:
  3984. fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
  3985. filename);
  3986. result = 2;
  3987. break;
  3988. case CXSaveError_InvalidTU:
  3989. fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
  3990. filename);
  3991. result = 3;
  3992. break;
  3993. case CXSaveError_Unknown:
  3994. default:
  3995. fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
  3996. result = 1;
  3997. break;
  3998. }
  3999. clang_disposeTranslationUnit(TU);
  4000. free_remapped_files(unsaved_files, num_unsaved_files);
  4001. clang_disposeIndex(Idx);
  4002. return result;
  4003. }
  4004. /******************************************************************************/
  4005. /* Serialized diagnostics. */
  4006. /******************************************************************************/
  4007. static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
  4008. switch (error) {
  4009. case CXLoadDiag_CannotLoad: return "Cannot Load File";
  4010. case CXLoadDiag_None: break;
  4011. case CXLoadDiag_Unknown: return "Unknown";
  4012. case CXLoadDiag_InvalidFile: return "Invalid File";
  4013. }
  4014. return "None";
  4015. }
  4016. static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
  4017. switch (severity) {
  4018. case CXDiagnostic_Note: return "note";
  4019. case CXDiagnostic_Error: return "error";
  4020. case CXDiagnostic_Fatal: return "fatal";
  4021. case CXDiagnostic_Ignored: return "ignored";
  4022. case CXDiagnostic_Warning: return "warning";
  4023. }
  4024. return "unknown";
  4025. }
  4026. static void printIndent(unsigned indent) {
  4027. if (indent == 0)
  4028. return;
  4029. fprintf(stderr, "+");
  4030. --indent;
  4031. while (indent > 0) {
  4032. fprintf(stderr, "-");
  4033. --indent;
  4034. }
  4035. }
  4036. static void printLocation(CXSourceLocation L) {
  4037. CXFile File;
  4038. CXString FileName;
  4039. unsigned line, column, offset;
  4040. clang_getExpansionLocation(L, &File, &line, &column, &offset);
  4041. FileName = clang_getFileName(File);
  4042. fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
  4043. clang_disposeString(FileName);
  4044. }
  4045. static void printRanges(CXDiagnostic D, unsigned indent) {
  4046. unsigned i, n = clang_getDiagnosticNumRanges(D);
  4047. for (i = 0; i < n; ++i) {
  4048. CXSourceLocation Start, End;
  4049. CXSourceRange SR = clang_getDiagnosticRange(D, i);
  4050. Start = clang_getRangeStart(SR);
  4051. End = clang_getRangeEnd(SR);
  4052. printIndent(indent);
  4053. fprintf(stderr, "Range: ");
  4054. printLocation(Start);
  4055. fprintf(stderr, " ");
  4056. printLocation(End);
  4057. fprintf(stderr, "\n");
  4058. }
  4059. }
  4060. static void printFixIts(CXDiagnostic D, unsigned indent) {
  4061. unsigned i, n = clang_getDiagnosticNumFixIts(D);
  4062. fprintf(stderr, "Number FIXITs = %d\n", n);
  4063. for (i = 0 ; i < n; ++i) {
  4064. CXSourceRange ReplacementRange;
  4065. CXString text;
  4066. text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
  4067. printIndent(indent);
  4068. fprintf(stderr, "FIXIT: (");
  4069. printLocation(clang_getRangeStart(ReplacementRange));
  4070. fprintf(stderr, " - ");
  4071. printLocation(clang_getRangeEnd(ReplacementRange));
  4072. fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
  4073. clang_disposeString(text);
  4074. }
  4075. }
  4076. static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
  4077. unsigned i, n;
  4078. if (!Diags)
  4079. return;
  4080. n = clang_getNumDiagnosticsInSet(Diags);
  4081. for (i = 0; i < n; ++i) {
  4082. CXSourceLocation DiagLoc;
  4083. CXDiagnostic D;
  4084. CXFile File;
  4085. CXString FileName, DiagSpelling, DiagOption, DiagCat;
  4086. unsigned line, column, offset;
  4087. const char *DiagOptionStr = 0, *DiagCatStr = 0;
  4088. D = clang_getDiagnosticInSet(Diags, i);
  4089. DiagLoc = clang_getDiagnosticLocation(D);
  4090. clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
  4091. FileName = clang_getFileName(File);
  4092. DiagSpelling = clang_getDiagnosticSpelling(D);
  4093. printIndent(indent);
  4094. fprintf(stderr, "%s:%d:%d: %s: %s",
  4095. clang_getCString(FileName),
  4096. line,
  4097. column,
  4098. getSeverityString(clang_getDiagnosticSeverity(D)),
  4099. clang_getCString(DiagSpelling));
  4100. DiagOption = clang_getDiagnosticOption(D, 0);
  4101. DiagOptionStr = clang_getCString(DiagOption);
  4102. if (DiagOptionStr) {
  4103. fprintf(stderr, " [%s]", DiagOptionStr);
  4104. }
  4105. DiagCat = clang_getDiagnosticCategoryText(D);
  4106. DiagCatStr = clang_getCString(DiagCat);
  4107. if (DiagCatStr) {
  4108. fprintf(stderr, " [%s]", DiagCatStr);
  4109. }
  4110. fprintf(stderr, "\n");
  4111. printRanges(D, indent);
  4112. printFixIts(D, indent);
  4113. /* Print subdiagnostics. */
  4114. printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
  4115. clang_disposeString(FileName);
  4116. clang_disposeString(DiagSpelling);
  4117. clang_disposeString(DiagOption);
  4118. clang_disposeString(DiagCat);
  4119. }
  4120. }
  4121. static int read_diagnostics(const char *filename) {
  4122. enum CXLoadDiag_Error error;
  4123. CXString errorString;
  4124. CXDiagnosticSet Diags = 0;
  4125. Diags = clang_loadDiagnostics(filename, &error, &errorString);
  4126. if (!Diags) {
  4127. fprintf(stderr, "Trouble deserializing file (%s): %s\n",
  4128. getDiagnosticCodeStr(error),
  4129. clang_getCString(errorString));
  4130. clang_disposeString(errorString);
  4131. return 1;
  4132. }
  4133. printDiagnosticSet(Diags, 0);
  4134. fprintf(stderr, "Number of diagnostics: %d\n",
  4135. clang_getNumDiagnosticsInSet(Diags));
  4136. clang_disposeDiagnosticSet(Diags);
  4137. return 0;
  4138. }
  4139. static int perform_print_build_session_timestamp(void) {
  4140. printf("%lld\n", clang_getBuildSessionTimestamp());
  4141. return 0;
  4142. }
  4143. /******************************************************************************/
  4144. /* Command line processing. */
  4145. /******************************************************************************/
  4146. static CXCursorVisitor GetVisitor(const char *s) {
  4147. if (s[0] == '\0')
  4148. return FilteredPrintingVisitor;
  4149. if (strcmp(s, "-usrs") == 0)
  4150. return USRVisitor;
  4151. if (strncmp(s, "-memory-usage", 13) == 0)
  4152. return GetVisitor(s + 13);
  4153. return NULL;
  4154. }
  4155. static void print_usage(void) {
  4156. fprintf(stderr,
  4157. "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
  4158. " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
  4159. " c-index-test -cursor-at=<site> <compiler arguments>\n"
  4160. " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
  4161. " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
  4162. " c-index-test -file-refs-at=<site> <compiler arguments>\n"
  4163. " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
  4164. fprintf(stderr,
  4165. " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
  4166. " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
  4167. " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
  4168. " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
  4169. " c-index-test -test-file-scan <AST file> <source file> "
  4170. "[FileCheck prefix]\n");
  4171. fprintf(stderr,
  4172. " c-index-test -test-load-tu <AST file> <symbol filter> "
  4173. "[FileCheck prefix]\n"
  4174. " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
  4175. "[FileCheck prefix]\n"
  4176. " c-index-test -test-load-source <symbol filter> {<args>}*\n");
  4177. fprintf(stderr,
  4178. " c-index-test -test-load-source-memory-usage "
  4179. "<symbol filter> {<args>}*\n"
  4180. " c-index-test -test-load-source-reparse <trials> <symbol filter> "
  4181. " {<args>}*\n"
  4182. " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
  4183. " c-index-test -test-load-source-usrs-memory-usage "
  4184. "<symbol filter> {<args>}*\n"
  4185. " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
  4186. " c-index-test -test-inclusion-stack-source {<args>}*\n"
  4187. " c-index-test -test-inclusion-stack-tu <AST file>\n");
  4188. fprintf(stderr,
  4189. " c-index-test -test-print-linkage-source {<args>}*\n"
  4190. " c-index-test -test-print-visibility {<args>}*\n"
  4191. " c-index-test -test-print-type {<args>}*\n"
  4192. " c-index-test -test-print-type-size {<args>}*\n"
  4193. " c-index-test -test-print-bitwidth {<args>}*\n"
  4194. " c-index-test -test-print-target-info {<args>}*\n"
  4195. " c-index-test -test-print-type-declaration {<args>}*\n"
  4196. " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
  4197. " c-index-test -print-usr-file <file>\n");
  4198. fprintf(stderr,
  4199. " c-index-test -write-pch <file> <compiler arguments>\n"
  4200. " c-index-test -compilation-db [lookup <filename>] database\n");
  4201. fprintf(stderr,
  4202. " c-index-test -print-build-session-timestamp\n");
  4203. fprintf(stderr,
  4204. " c-index-test -read-diagnostics <file>\n\n");
  4205. fprintf(stderr,
  4206. " <symbol filter> values:\n%s",
  4207. " all - load all symbols, including those from PCH\n"
  4208. " local - load all symbols except those in PCH\n"
  4209. " category - only load ObjC categories (non-PCH)\n"
  4210. " interface - only load ObjC interfaces (non-PCH)\n"
  4211. " protocol - only load ObjC protocols (non-PCH)\n"
  4212. " function - only load functions (non-PCH)\n"
  4213. " typedef - only load typdefs (non-PCH)\n"
  4214. " scan-function - scan function bodies (non-PCH)\n\n");
  4215. }
  4216. /***/
  4217. int cindextest_main(int argc, const char **argv) {
  4218. clang_enableStackTraces();
  4219. if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
  4220. return read_diagnostics(argv[2]);
  4221. if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
  4222. return perform_code_completion(argc, argv, 0);
  4223. if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
  4224. return perform_code_completion(argc, argv, 1);
  4225. if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
  4226. return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
  4227. if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
  4228. return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
  4229. inspect_evaluate_cursor);
  4230. if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
  4231. return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
  4232. inspect_macroinfo_cursor);
  4233. if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
  4234. return find_file_refs_at(argc, argv);
  4235. if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
  4236. return find_file_includes_in(argc, argv);
  4237. if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
  4238. return index_file(argc - 2, argv + 2, /*full=*/0);
  4239. if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
  4240. return index_file(argc - 2, argv + 2, /*full=*/1);
  4241. if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
  4242. return index_tu(argc - 2, argv + 2);
  4243. if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
  4244. return index_compile_db(argc - 2, argv + 2);
  4245. else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
  4246. CXCursorVisitor I = GetVisitor(argv[1] + 13);
  4247. if (I)
  4248. return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
  4249. NULL);
  4250. }
  4251. else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
  4252. CXCursorVisitor I = GetVisitor(argv[1] + 25);
  4253. if (I) {
  4254. int trials = atoi(argv[2]);
  4255. return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
  4256. NULL);
  4257. }
  4258. }
  4259. else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
  4260. CXCursorVisitor I = GetVisitor(argv[1] + 17);
  4261. PostVisitTU postVisit = 0;
  4262. if (strstr(argv[1], "-memory-usage"))
  4263. postVisit = PrintMemoryUsage;
  4264. if (I)
  4265. return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
  4266. postVisit);
  4267. }
  4268. else if (argc >= 3 && strcmp(argv[1], "-single-file-parse") == 0)
  4269. return perform_single_file_parse(argv[2]);
  4270. else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
  4271. return perform_file_scan(argv[2], argv[3],
  4272. argc >= 5 ? argv[4] : 0);
  4273. else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
  4274. return perform_token_annotation(argc, argv);
  4275. else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
  4276. return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
  4277. PrintInclusionStack);
  4278. else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
  4279. return perform_test_load_tu(argv[2], "all", NULL, NULL,
  4280. PrintInclusionStack);
  4281. else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
  4282. return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
  4283. NULL);
  4284. else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
  4285. return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
  4286. NULL);
  4287. else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
  4288. return perform_test_load_source(argc - 2, argv + 2, "all",
  4289. PrintType, 0);
  4290. else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
  4291. return perform_test_load_source(argc - 2, argv + 2, "all",
  4292. PrintTypeSize, 0);
  4293. else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
  4294. return perform_test_load_source(argc - 2, argv + 2, "all",
  4295. PrintTypeDeclaration, 0);
  4296. else if (argc > 2 && strcmp(argv[1], "-test-print-decl-attributes") == 0)
  4297. return perform_test_load_source(argc - 2, argv + 2, "all",
  4298. PrintDeclAttributes, 0);
  4299. else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
  4300. return perform_test_load_source(argc - 2, argv + 2, "all",
  4301. PrintBitWidth, 0);
  4302. else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
  4303. return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
  4304. else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
  4305. return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
  4306. else if (argc > 2 && strcmp(argv[1], "-test-print-target-info") == 0)
  4307. return print_target_info(argc - 2, argv + 2);
  4308. else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
  4309. if (argc > 2)
  4310. return print_usrs(argv + 2, argv + argc);
  4311. else {
  4312. display_usrs();
  4313. return 1;
  4314. }
  4315. }
  4316. else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
  4317. return print_usrs_file(argv[2]);
  4318. else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
  4319. return write_pch_file(argv[2], argc - 3, argv + 3);
  4320. else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
  4321. return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
  4322. else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
  4323. return perform_print_build_session_timestamp();
  4324. print_usage();
  4325. return 1;
  4326. }
  4327. /***/
  4328. /* We intentionally run in a separate thread to ensure we at least minimal
  4329. * testing of a multithreaded environment (for example, having a reduced stack
  4330. * size). */
  4331. typedef struct thread_info {
  4332. int (*main_func)(int argc, const char **argv);
  4333. int argc;
  4334. const char **argv;
  4335. int result;
  4336. } thread_info;
  4337. void thread_runner(void *client_data_v) {
  4338. thread_info *client_data = client_data_v;
  4339. client_data->result = client_data->main_func(client_data->argc,
  4340. client_data->argv);
  4341. }
  4342. static void flush_atexit(void) {
  4343. /* stdout, and surprisingly even stderr, are not always flushed on process
  4344. * and thread exit, particularly when the system is under heavy load. */
  4345. fflush(stdout);
  4346. fflush(stderr);
  4347. }
  4348. int main(int argc, const char **argv) {
  4349. thread_info client_data;
  4350. atexit(flush_atexit);
  4351. #ifdef CLANG_HAVE_LIBXML
  4352. LIBXML_TEST_VERSION
  4353. #endif
  4354. if (argc > 1 && strcmp(argv[1], "core") == 0)
  4355. return indextest_core_main(argc, argv);
  4356. client_data.main_func = cindextest_main;
  4357. client_data.argc = argc;
  4358. client_data.argv = argv;
  4359. if (getenv("CINDEXTEST_NOTHREADS"))
  4360. return client_data.main_func(client_data.argc, client_data.argv);
  4361. clang_executeOnThread(thread_runner, &client_data, 0);
  4362. return client_data.result;
  4363. }