c-index-test.c revision 838d3c23204f52ae27a9f5e9a254238a7ac5d41b
1/* c-index-test.c */ 2 3#include "clang-c/Index.h" 4#include <ctype.h> 5#include <stdlib.h> 6#include <stdio.h> 7#include <string.h> 8#include <assert.h> 9 10/******************************************************************************/ 11/* Utility functions. */ 12/******************************************************************************/ 13 14#ifdef _MSC_VER 15char *basename(const char* path) 16{ 17 char* base1 = (char*)strrchr(path, '/'); 18 char* base2 = (char*)strrchr(path, '\\'); 19 if (base1 && base2) 20 return((base1 > base2) ? base1 + 1 : base2 + 1); 21 else if (base1) 22 return(base1 + 1); 23 else if (base2) 24 return(base2 + 1); 25 26 return((char*)path); 27} 28#else 29extern char *basename(const char *); 30#endif 31 32/** \brief Return the default parsing options. */ 33static unsigned getDefaultParsingOptions() { 34 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord; 35 36 if (getenv("CINDEXTEST_EDITING")) 37 options |= clang_defaultEditingTranslationUnitOptions(); 38 if (getenv("CINDEXTEST_COMPLETION_CACHING")) 39 options |= CXTranslationUnit_CacheCompletionResults; 40 if (getenv("CINDEXTEST_NESTED_MACROS")) 41 options |= CXTranslationUnit_NestedMacroExpansions; 42 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING")) 43 options &= ~CXTranslationUnit_CacheCompletionResults; 44 45 return options; 46} 47 48static int checkForErrors(CXTranslationUnit TU); 49 50static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column, 51 unsigned end_line, unsigned end_column) { 52 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column, 53 end_line, end_column); 54} 55 56static unsigned CreateTranslationUnit(CXIndex Idx, const char *file, 57 CXTranslationUnit *TU) { 58 59 *TU = clang_createTranslationUnit(Idx, file); 60 if (!*TU) { 61 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file); 62 return 0; 63 } 64 return 1; 65} 66 67void free_remapped_files(struct CXUnsavedFile *unsaved_files, 68 int num_unsaved_files) { 69 int i; 70 for (i = 0; i != num_unsaved_files; ++i) { 71 free((char *)unsaved_files[i].Filename); 72 free((char *)unsaved_files[i].Contents); 73 } 74 free(unsaved_files); 75} 76 77int parse_remapped_files(int argc, const char **argv, int start_arg, 78 struct CXUnsavedFile **unsaved_files, 79 int *num_unsaved_files) { 80 int i; 81 int arg; 82 int prefix_len = strlen("-remap-file="); 83 *unsaved_files = 0; 84 *num_unsaved_files = 0; 85 86 /* Count the number of remapped files. */ 87 for (arg = start_arg; arg < argc; ++arg) { 88 if (strncmp(argv[arg], "-remap-file=", prefix_len)) 89 break; 90 91 ++*num_unsaved_files; 92 } 93 94 if (*num_unsaved_files == 0) 95 return 0; 96 97 *unsaved_files 98 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) * 99 *num_unsaved_files); 100 for (arg = start_arg, i = 0; i != *num_unsaved_files; ++i, ++arg) { 101 struct CXUnsavedFile *unsaved = *unsaved_files + i; 102 const char *arg_string = argv[arg] + prefix_len; 103 int filename_len; 104 char *filename; 105 char *contents; 106 FILE *to_file; 107 const char *semi = strchr(arg_string, ';'); 108 if (!semi) { 109 fprintf(stderr, 110 "error: -remap-file=from;to argument is missing semicolon\n"); 111 free_remapped_files(*unsaved_files, i); 112 *unsaved_files = 0; 113 *num_unsaved_files = 0; 114 return -1; 115 } 116 117 /* Open the file that we're remapping to. */ 118 to_file = fopen(semi + 1, "rb"); 119 if (!to_file) { 120 fprintf(stderr, "error: cannot open file %s that we are remapping to\n", 121 semi + 1); 122 free_remapped_files(*unsaved_files, i); 123 *unsaved_files = 0; 124 *num_unsaved_files = 0; 125 return -1; 126 } 127 128 /* Determine the length of the file we're remapping to. */ 129 fseek(to_file, 0, SEEK_END); 130 unsaved->Length = ftell(to_file); 131 fseek(to_file, 0, SEEK_SET); 132 133 /* Read the contents of the file we're remapping to. */ 134 contents = (char *)malloc(unsaved->Length + 1); 135 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) { 136 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n", 137 (feof(to_file) ? "EOF" : "error"), semi + 1); 138 fclose(to_file); 139 free_remapped_files(*unsaved_files, i); 140 *unsaved_files = 0; 141 *num_unsaved_files = 0; 142 return -1; 143 } 144 contents[unsaved->Length] = 0; 145 unsaved->Contents = contents; 146 147 /* Close the file. */ 148 fclose(to_file); 149 150 /* Copy the file name that we're remapping from. */ 151 filename_len = semi - arg_string; 152 filename = (char *)malloc(filename_len + 1); 153 memcpy(filename, arg_string, filename_len); 154 filename[filename_len] = 0; 155 unsaved->Filename = filename; 156 } 157 158 return 0; 159} 160 161/******************************************************************************/ 162/* Pretty-printing. */ 163/******************************************************************************/ 164 165static void PrintRange(CXSourceRange R, const char *str) { 166 CXFile begin_file, end_file; 167 unsigned begin_line, begin_column, end_line, end_column; 168 169 clang_getSpellingLocation(clang_getRangeStart(R), 170 &begin_file, &begin_line, &begin_column, 0); 171 clang_getSpellingLocation(clang_getRangeEnd(R), 172 &end_file, &end_line, &end_column, 0); 173 if (!begin_file || !end_file) 174 return; 175 176 printf(" %s=", str); 177 PrintExtent(stdout, begin_line, begin_column, end_line, end_column); 178} 179 180int want_display_name = 0; 181 182static void PrintCursor(CXCursor Cursor) { 183 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor); 184 if (clang_isInvalid(Cursor.kind)) { 185 CXString ks = clang_getCursorKindSpelling(Cursor.kind); 186 printf("Invalid Cursor => %s", clang_getCString(ks)); 187 clang_disposeString(ks); 188 } 189 else { 190 CXString string, ks; 191 CXCursor Referenced; 192 unsigned line, column; 193 CXCursor SpecializationOf; 194 CXCursor *overridden; 195 unsigned num_overridden; 196 unsigned RefNameRangeNr; 197 CXSourceRange CursorExtent; 198 CXSourceRange RefNameRange; 199 200 ks = clang_getCursorKindSpelling(Cursor.kind); 201 string = want_display_name? clang_getCursorDisplayName(Cursor) 202 : clang_getCursorSpelling(Cursor); 203 printf("%s=%s", clang_getCString(ks), 204 clang_getCString(string)); 205 clang_disposeString(ks); 206 clang_disposeString(string); 207 208 Referenced = clang_getCursorReferenced(Cursor); 209 if (!clang_equalCursors(Referenced, clang_getNullCursor())) { 210 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) { 211 unsigned I, N = clang_getNumOverloadedDecls(Referenced); 212 printf("["); 213 for (I = 0; I != N; ++I) { 214 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I); 215 CXSourceLocation Loc; 216 if (I) 217 printf(", "); 218 219 Loc = clang_getCursorLocation(Ovl); 220 clang_getSpellingLocation(Loc, 0, &line, &column, 0); 221 printf("%d:%d", line, column); 222 } 223 printf("]"); 224 } else { 225 CXSourceLocation Loc = clang_getCursorLocation(Referenced); 226 clang_getSpellingLocation(Loc, 0, &line, &column, 0); 227 printf(":%d:%d", line, column); 228 } 229 } 230 231 if (clang_isCursorDefinition(Cursor)) 232 printf(" (Definition)"); 233 234 switch (clang_getCursorAvailability(Cursor)) { 235 case CXAvailability_Available: 236 break; 237 238 case CXAvailability_Deprecated: 239 printf(" (deprecated)"); 240 break; 241 242 case CXAvailability_NotAvailable: 243 printf(" (unavailable)"); 244 break; 245 246 case CXAvailability_NotAccessible: 247 printf(" (inaccessible)"); 248 break; 249 } 250 251 if (clang_CXXMethod_isStatic(Cursor)) 252 printf(" (static)"); 253 if (clang_CXXMethod_isVirtual(Cursor)) 254 printf(" (virtual)"); 255 256 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 257 CXType T = 258 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor)); 259 CXString S = clang_getTypeKindSpelling(T.kind); 260 printf(" [IBOutletCollection=%s]", clang_getCString(S)); 261 clang_disposeString(S); 262 } 263 264 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 265 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor); 266 unsigned isVirtual = clang_isVirtualBase(Cursor); 267 const char *accessStr = 0; 268 269 switch (access) { 270 case CX_CXXInvalidAccessSpecifier: 271 accessStr = "invalid"; break; 272 case CX_CXXPublic: 273 accessStr = "public"; break; 274 case CX_CXXProtected: 275 accessStr = "protected"; break; 276 case CX_CXXPrivate: 277 accessStr = "private"; break; 278 } 279 280 printf(" [access=%s isVirtual=%s]", accessStr, 281 isVirtual ? "true" : "false"); 282 } 283 284 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor); 285 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) { 286 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf); 287 CXString Name = clang_getCursorSpelling(SpecializationOf); 288 clang_getSpellingLocation(Loc, 0, &line, &column, 0); 289 printf(" [Specialization of %s:%d:%d]", 290 clang_getCString(Name), line, column); 291 clang_disposeString(Name); 292 } 293 294 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden); 295 if (num_overridden) { 296 unsigned I; 297 printf(" [Overrides "); 298 for (I = 0; I != num_overridden; ++I) { 299 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]); 300 clang_getSpellingLocation(Loc, 0, &line, &column, 0); 301 if (I) 302 printf(", "); 303 printf("@%d:%d", line, column); 304 } 305 printf("]"); 306 clang_disposeOverriddenCursors(overridden); 307 } 308 309 if (Cursor.kind == CXCursor_InclusionDirective) { 310 CXFile File = clang_getIncludedFile(Cursor); 311 CXString Included = clang_getFileName(File); 312 printf(" (%s)", clang_getCString(Included)); 313 clang_disposeString(Included); 314 315 if (clang_isFileMultipleIncludeGuarded(TU, File)) 316 printf(" [multi-include guarded]"); 317 } 318 319 CursorExtent = clang_getCursorExtent(Cursor); 320 RefNameRange = clang_getCursorReferenceNameRange(Cursor, 321 CXNameRange_WantQualifier 322 | CXNameRange_WantSinglePiece 323 | CXNameRange_WantTemplateArgs, 324 0); 325 if (!clang_equalRanges(CursorExtent, RefNameRange)) 326 PrintRange(RefNameRange, "SingleRefName"); 327 328 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) { 329 RefNameRange = clang_getCursorReferenceNameRange(Cursor, 330 CXNameRange_WantQualifier 331 | CXNameRange_WantTemplateArgs, 332 RefNameRangeNr); 333 if (clang_equalRanges(clang_getNullRange(), RefNameRange)) 334 break; 335 if (!clang_equalRanges(CursorExtent, RefNameRange)) 336 PrintRange(RefNameRange, "RefName"); 337 } 338 } 339} 340 341static const char* GetCursorSource(CXCursor Cursor) { 342 CXSourceLocation Loc = clang_getCursorLocation(Cursor); 343 CXString source; 344 CXFile file; 345 clang_getExpansionLocation(Loc, &file, 0, 0, 0); 346 source = clang_getFileName(file); 347 if (!clang_getCString(source)) { 348 clang_disposeString(source); 349 return "<invalid loc>"; 350 } 351 else { 352 const char *b = basename(clang_getCString(source)); 353 clang_disposeString(source); 354 return b; 355 } 356} 357 358/******************************************************************************/ 359/* Callbacks. */ 360/******************************************************************************/ 361 362typedef void (*PostVisitTU)(CXTranslationUnit); 363 364void PrintDiagnostic(CXDiagnostic Diagnostic) { 365 FILE *out = stderr; 366 CXFile file; 367 CXString Msg; 368 unsigned display_opts = CXDiagnostic_DisplaySourceLocation 369 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges 370 | CXDiagnostic_DisplayOption; 371 unsigned i, num_fixits; 372 373 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored) 374 return; 375 376 Msg = clang_formatDiagnostic(Diagnostic, display_opts); 377 fprintf(stderr, "%s\n", clang_getCString(Msg)); 378 clang_disposeString(Msg); 379 380 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic), 381 &file, 0, 0, 0); 382 if (!file) 383 return; 384 385 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic); 386 for (i = 0; i != num_fixits; ++i) { 387 CXSourceRange range; 388 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range); 389 CXSourceLocation start = clang_getRangeStart(range); 390 CXSourceLocation end = clang_getRangeEnd(range); 391 unsigned start_line, start_column, end_line, end_column; 392 CXFile start_file, end_file; 393 clang_getSpellingLocation(start, &start_file, &start_line, 394 &start_column, 0); 395 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0); 396 if (clang_equalLocations(start, end)) { 397 /* Insertion. */ 398 if (start_file == file) 399 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n", 400 clang_getCString(insertion_text), start_line, start_column); 401 } else if (strcmp(clang_getCString(insertion_text), "") == 0) { 402 /* Removal. */ 403 if (start_file == file && end_file == file) { 404 fprintf(out, "FIX-IT: Remove "); 405 PrintExtent(out, start_line, start_column, end_line, end_column); 406 fprintf(out, "\n"); 407 } 408 } else { 409 /* Replacement. */ 410 if (start_file == end_file) { 411 fprintf(out, "FIX-IT: Replace "); 412 PrintExtent(out, start_line, start_column, end_line, end_column); 413 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text)); 414 } 415 break; 416 } 417 clang_disposeString(insertion_text); 418 } 419} 420 421void PrintDiagnostics(CXTranslationUnit TU) { 422 int i, n = clang_getNumDiagnostics(TU); 423 for (i = 0; i != n; ++i) { 424 CXDiagnostic Diag = clang_getDiagnostic(TU, i); 425 PrintDiagnostic(Diag); 426 clang_disposeDiagnostic(Diag); 427 } 428} 429 430void PrintMemoryUsage(CXTranslationUnit TU) { 431 unsigned long total = 0; 432 unsigned i = 0; 433 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU); 434 fprintf(stderr, "Memory usage:\n"); 435 for (i = 0 ; i != usage.numEntries; ++i) { 436 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind); 437 unsigned long amount = usage.entries[i].amount; 438 total += amount; 439 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount, 440 ((double) amount)/(1024*1024)); 441 } 442 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total, 443 ((double) total)/(1024*1024)); 444 clang_disposeCXTUResourceUsage(usage); 445} 446 447/******************************************************************************/ 448/* Logic for testing traversal. */ 449/******************************************************************************/ 450 451static const char *FileCheckPrefix = "CHECK"; 452 453static void PrintCursorExtent(CXCursor C) { 454 CXSourceRange extent = clang_getCursorExtent(C); 455 PrintRange(extent, "Extent"); 456} 457 458/* Data used by all of the visitors. */ 459typedef struct { 460 CXTranslationUnit TU; 461 enum CXCursorKind *Filter; 462} VisitorData; 463 464 465enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor, 466 CXCursor Parent, 467 CXClientData ClientData) { 468 VisitorData *Data = (VisitorData *)ClientData; 469 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) { 470 CXSourceLocation Loc = clang_getCursorLocation(Cursor); 471 unsigned line, column; 472 clang_getSpellingLocation(Loc, 0, &line, &column, 0); 473 printf("// %s: %s:%d:%d: ", FileCheckPrefix, 474 GetCursorSource(Cursor), line, column); 475 PrintCursor(Cursor); 476 PrintCursorExtent(Cursor); 477 printf("\n"); 478 return CXChildVisit_Recurse; 479 } 480 481 return CXChildVisit_Continue; 482} 483 484static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor, 485 CXCursor Parent, 486 CXClientData ClientData) { 487 const char *startBuf, *endBuf; 488 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn; 489 CXCursor Ref; 490 VisitorData *Data = (VisitorData *)ClientData; 491 492 if (Cursor.kind != CXCursor_FunctionDecl || 493 !clang_isCursorDefinition(Cursor)) 494 return CXChildVisit_Continue; 495 496 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf, 497 &startLine, &startColumn, 498 &endLine, &endColumn); 499 /* Probe the entire body, looking for both decls and refs. */ 500 curLine = startLine; 501 curColumn = startColumn; 502 503 while (startBuf < endBuf) { 504 CXSourceLocation Loc; 505 CXFile file; 506 CXString source; 507 508 if (*startBuf == '\n') { 509 startBuf++; 510 curLine++; 511 curColumn = 1; 512 } else if (*startBuf != '\t') 513 curColumn++; 514 515 Loc = clang_getCursorLocation(Cursor); 516 clang_getSpellingLocation(Loc, &file, 0, 0, 0); 517 518 source = clang_getFileName(file); 519 if (clang_getCString(source)) { 520 CXSourceLocation RefLoc 521 = clang_getLocation(Data->TU, file, curLine, curColumn); 522 Ref = clang_getCursor(Data->TU, RefLoc); 523 if (Ref.kind == CXCursor_NoDeclFound) { 524 /* Nothing found here; that's fine. */ 525 } else if (Ref.kind != CXCursor_FunctionDecl) { 526 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref), 527 curLine, curColumn); 528 PrintCursor(Ref); 529 printf("\n"); 530 } 531 } 532 clang_disposeString(source); 533 startBuf++; 534 } 535 536 return CXChildVisit_Continue; 537} 538 539/******************************************************************************/ 540/* USR testing. */ 541/******************************************************************************/ 542 543enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent, 544 CXClientData ClientData) { 545 VisitorData *Data = (VisitorData *)ClientData; 546 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) { 547 CXString USR = clang_getCursorUSR(C); 548 const char *cstr = clang_getCString(USR); 549 if (!cstr || cstr[0] == '\0') { 550 clang_disposeString(USR); 551 return CXChildVisit_Recurse; 552 } 553 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr); 554 555 PrintCursorExtent(C); 556 printf("\n"); 557 clang_disposeString(USR); 558 559 return CXChildVisit_Recurse; 560 } 561 562 return CXChildVisit_Continue; 563} 564 565/******************************************************************************/ 566/* Inclusion stack testing. */ 567/******************************************************************************/ 568 569void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack, 570 unsigned includeStackLen, CXClientData data) { 571 572 unsigned i; 573 CXString fname; 574 575 fname = clang_getFileName(includedFile); 576 printf("file: %s\nincluded by:\n", clang_getCString(fname)); 577 clang_disposeString(fname); 578 579 for (i = 0; i < includeStackLen; ++i) { 580 CXFile includingFile; 581 unsigned line, column; 582 clang_getSpellingLocation(includeStack[i], &includingFile, &line, 583 &column, 0); 584 fname = clang_getFileName(includingFile); 585 printf(" %s:%d:%d\n", clang_getCString(fname), line, column); 586 clang_disposeString(fname); 587 } 588 printf("\n"); 589} 590 591void PrintInclusionStack(CXTranslationUnit TU) { 592 clang_getInclusions(TU, InclusionVisitor, NULL); 593} 594 595/******************************************************************************/ 596/* Linkage testing. */ 597/******************************************************************************/ 598 599static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p, 600 CXClientData d) { 601 const char *linkage = 0; 602 603 if (clang_isInvalid(clang_getCursorKind(cursor))) 604 return CXChildVisit_Recurse; 605 606 switch (clang_getCursorLinkage(cursor)) { 607 case CXLinkage_Invalid: break; 608 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break; 609 case CXLinkage_Internal: linkage = "Internal"; break; 610 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break; 611 case CXLinkage_External: linkage = "External"; break; 612 } 613 614 if (linkage) { 615 PrintCursor(cursor); 616 printf("linkage=%s\n", linkage); 617 } 618 619 return CXChildVisit_Recurse; 620} 621 622/******************************************************************************/ 623/* Typekind testing. */ 624/******************************************************************************/ 625 626static enum CXChildVisitResult PrintTypeKind(CXCursor cursor, CXCursor p, 627 CXClientData d) { 628 if (!clang_isInvalid(clang_getCursorKind(cursor))) { 629 CXType T = clang_getCursorType(cursor); 630 CXString S = clang_getTypeKindSpelling(T.kind); 631 PrintCursor(cursor); 632 printf(" typekind=%s", clang_getCString(S)); 633 if (clang_isConstQualifiedType(T)) 634 printf(" const"); 635 if (clang_isVolatileQualifiedType(T)) 636 printf(" volatile"); 637 if (clang_isRestrictQualifiedType(T)) 638 printf(" restrict"); 639 clang_disposeString(S); 640 /* Print the canonical type if it is different. */ 641 { 642 CXType CT = clang_getCanonicalType(T); 643 if (!clang_equalTypes(T, CT)) { 644 CXString CS = clang_getTypeKindSpelling(CT.kind); 645 printf(" [canonical=%s]", clang_getCString(CS)); 646 clang_disposeString(CS); 647 } 648 } 649 /* Print the return type if it exists. */ 650 { 651 CXType RT = clang_getCursorResultType(cursor); 652 if (RT.kind != CXType_Invalid) { 653 CXString RS = clang_getTypeKindSpelling(RT.kind); 654 printf(" [result=%s]", clang_getCString(RS)); 655 clang_disposeString(RS); 656 } 657 } 658 /* Print if this is a non-POD type. */ 659 printf(" [isPOD=%d]", clang_isPODType(T)); 660 661 printf("\n"); 662 } 663 return CXChildVisit_Recurse; 664} 665 666 667/******************************************************************************/ 668/* Loading ASTs/source. */ 669/******************************************************************************/ 670 671static int perform_test_load(CXIndex Idx, CXTranslationUnit TU, 672 const char *filter, const char *prefix, 673 CXCursorVisitor Visitor, 674 PostVisitTU PV) { 675 676 if (prefix) 677 FileCheckPrefix = prefix; 678 679 if (Visitor) { 680 enum CXCursorKind K = CXCursor_NotImplemented; 681 enum CXCursorKind *ck = &K; 682 VisitorData Data; 683 684 /* Perform some simple filtering. */ 685 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL; 686 else if (!strcmp(filter, "all-display") || 687 !strcmp(filter, "local-display")) { 688 ck = NULL; 689 want_display_name = 1; 690 } 691 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0; 692 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl; 693 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl; 694 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl; 695 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl; 696 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl; 697 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor; 698 else { 699 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter); 700 return 1; 701 } 702 703 Data.TU = TU; 704 Data.Filter = ck; 705 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data); 706 } 707 708 if (PV) 709 PV(TU); 710 711 PrintDiagnostics(TU); 712 if (checkForErrors(TU) != 0) { 713 clang_disposeTranslationUnit(TU); 714 return -1; 715 } 716 717 clang_disposeTranslationUnit(TU); 718 return 0; 719} 720 721int perform_test_load_tu(const char *file, const char *filter, 722 const char *prefix, CXCursorVisitor Visitor, 723 PostVisitTU PV) { 724 CXIndex Idx; 725 CXTranslationUnit TU; 726 int result; 727 Idx = clang_createIndex(/* excludeDeclsFromPCH */ 728 !strcmp(filter, "local") ? 1 : 0, 729 /* displayDiagnosics=*/1); 730 731 if (!CreateTranslationUnit(Idx, file, &TU)) { 732 clang_disposeIndex(Idx); 733 return 1; 734 } 735 736 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV); 737 clang_disposeIndex(Idx); 738 return result; 739} 740 741int perform_test_load_source(int argc, const char **argv, 742 const char *filter, CXCursorVisitor Visitor, 743 PostVisitTU PV) { 744 CXIndex Idx; 745 CXTranslationUnit TU; 746 struct CXUnsavedFile *unsaved_files = 0; 747 int num_unsaved_files = 0; 748 int result; 749 750 Idx = clang_createIndex(/* excludeDeclsFromPCH */ 751 (!strcmp(filter, "local") || 752 !strcmp(filter, "local-display"))? 1 : 0, 753 /* displayDiagnosics=*/0); 754 755 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) { 756 clang_disposeIndex(Idx); 757 return -1; 758 } 759 760 TU = clang_parseTranslationUnit(Idx, 0, 761 argv + num_unsaved_files, 762 argc - num_unsaved_files, 763 unsaved_files, num_unsaved_files, 764 getDefaultParsingOptions()); 765 if (!TU) { 766 fprintf(stderr, "Unable to load translation unit!\n"); 767 free_remapped_files(unsaved_files, num_unsaved_files); 768 clang_disposeIndex(Idx); 769 return 1; 770 } 771 772 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV); 773 free_remapped_files(unsaved_files, num_unsaved_files); 774 clang_disposeIndex(Idx); 775 return result; 776} 777 778int perform_test_reparse_source(int argc, const char **argv, int trials, 779 const char *filter, CXCursorVisitor Visitor, 780 PostVisitTU PV) { 781 CXIndex Idx; 782 CXTranslationUnit TU; 783 struct CXUnsavedFile *unsaved_files = 0; 784 int num_unsaved_files = 0; 785 int result; 786 int trial; 787 int remap_after_trial = 0; 788 char *endptr = 0; 789 790 Idx = clang_createIndex(/* excludeDeclsFromPCH */ 791 !strcmp(filter, "local") ? 1 : 0, 792 /* displayDiagnosics=*/0); 793 794 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) { 795 clang_disposeIndex(Idx); 796 return -1; 797 } 798 799 /* Load the initial translation unit -- we do this without honoring remapped 800 * files, so that we have a way to test results after changing the source. */ 801 TU = clang_parseTranslationUnit(Idx, 0, 802 argv + num_unsaved_files, 803 argc - num_unsaved_files, 804 0, 0, getDefaultParsingOptions()); 805 if (!TU) { 806 fprintf(stderr, "Unable to load translation unit!\n"); 807 free_remapped_files(unsaved_files, num_unsaved_files); 808 clang_disposeIndex(Idx); 809 return 1; 810 } 811 812 if (checkForErrors(TU) != 0) 813 return -1; 814 815 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) { 816 remap_after_trial = 817 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10); 818 } 819 820 for (trial = 0; trial < trials; ++trial) { 821 if (clang_reparseTranslationUnit(TU, 822 trial >= remap_after_trial ? num_unsaved_files : 0, 823 trial >= remap_after_trial ? unsaved_files : 0, 824 clang_defaultReparseOptions(TU))) { 825 fprintf(stderr, "Unable to reparse translation unit!\n"); 826 clang_disposeTranslationUnit(TU); 827 free_remapped_files(unsaved_files, num_unsaved_files); 828 clang_disposeIndex(Idx); 829 return -1; 830 } 831 832 if (checkForErrors(TU) != 0) 833 return -1; 834 } 835 836 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV); 837 838 free_remapped_files(unsaved_files, num_unsaved_files); 839 clang_disposeIndex(Idx); 840 return result; 841} 842 843/******************************************************************************/ 844/* Logic for testing clang_getCursor(). */ 845/******************************************************************************/ 846 847static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor, 848 unsigned start_line, unsigned start_col, 849 unsigned end_line, unsigned end_col, 850 const char *prefix) { 851 printf("// %s: ", FileCheckPrefix); 852 if (prefix) 853 printf("-%s", prefix); 854 PrintExtent(stdout, start_line, start_col, end_line, end_col); 855 printf(" "); 856 PrintCursor(cursor); 857 printf("\n"); 858} 859 860static int perform_file_scan(const char *ast_file, const char *source_file, 861 const char *prefix) { 862 CXIndex Idx; 863 CXTranslationUnit TU; 864 FILE *fp; 865 CXCursor prevCursor = clang_getNullCursor(); 866 CXFile file; 867 unsigned line = 1, col = 1; 868 unsigned start_line = 1, start_col = 1; 869 870 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1, 871 /* displayDiagnosics=*/1))) { 872 fprintf(stderr, "Could not create Index\n"); 873 return 1; 874 } 875 876 if (!CreateTranslationUnit(Idx, ast_file, &TU)) 877 return 1; 878 879 if ((fp = fopen(source_file, "r")) == NULL) { 880 fprintf(stderr, "Could not open '%s'\n", source_file); 881 return 1; 882 } 883 884 file = clang_getFile(TU, source_file); 885 for (;;) { 886 CXCursor cursor; 887 int c = fgetc(fp); 888 889 if (c == '\n') { 890 ++line; 891 col = 1; 892 } else 893 ++col; 894 895 /* Check the cursor at this position, and dump the previous one if we have 896 * found something new. 897 */ 898 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col)); 899 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) && 900 prevCursor.kind != CXCursor_InvalidFile) { 901 print_cursor_file_scan(TU, prevCursor, start_line, start_col, 902 line, col, prefix); 903 start_line = line; 904 start_col = col; 905 } 906 if (c == EOF) 907 break; 908 909 prevCursor = cursor; 910 } 911 912 fclose(fp); 913 clang_disposeTranslationUnit(TU); 914 clang_disposeIndex(Idx); 915 return 0; 916} 917 918/******************************************************************************/ 919/* Logic for testing clang code completion. */ 920/******************************************************************************/ 921 922/* Parse file:line:column from the input string. Returns 0 on success, non-zero 923 on failure. If successful, the pointer *filename will contain newly-allocated 924 memory (that will be owned by the caller) to store the file name. */ 925int parse_file_line_column(const char *input, char **filename, unsigned *line, 926 unsigned *column, unsigned *second_line, 927 unsigned *second_column) { 928 /* Find the second colon. */ 929 const char *last_colon = strrchr(input, ':'); 930 unsigned values[4], i; 931 unsigned num_values = (second_line && second_column)? 4 : 2; 932 933 char *endptr = 0; 934 if (!last_colon || last_colon == input) { 935 if (num_values == 4) 936 fprintf(stderr, "could not parse filename:line:column:line:column in " 937 "'%s'\n", input); 938 else 939 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input); 940 return 1; 941 } 942 943 for (i = 0; i != num_values; ++i) { 944 const char *prev_colon; 945 946 /* Parse the next line or column. */ 947 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10); 948 if (*endptr != 0 && *endptr != ':') { 949 fprintf(stderr, "could not parse %s in '%s'\n", 950 (i % 2 ? "column" : "line"), input); 951 return 1; 952 } 953 954 if (i + 1 == num_values) 955 break; 956 957 /* Find the previous colon. */ 958 prev_colon = last_colon - 1; 959 while (prev_colon != input && *prev_colon != ':') 960 --prev_colon; 961 if (prev_colon == input) { 962 fprintf(stderr, "could not parse %s in '%s'\n", 963 (i % 2 == 0? "column" : "line"), input); 964 return 1; 965 } 966 967 last_colon = prev_colon; 968 } 969 970 *line = values[0]; 971 *column = values[1]; 972 973 if (second_line && second_column) { 974 *second_line = values[2]; 975 *second_column = values[3]; 976 } 977 978 /* Copy the file name. */ 979 *filename = (char*)malloc(last_colon - input + 1); 980 memcpy(*filename, input, last_colon - input); 981 (*filename)[last_colon - input] = 0; 982 return 0; 983} 984 985const char * 986clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) { 987 switch (Kind) { 988 case CXCompletionChunk_Optional: return "Optional"; 989 case CXCompletionChunk_TypedText: return "TypedText"; 990 case CXCompletionChunk_Text: return "Text"; 991 case CXCompletionChunk_Placeholder: return "Placeholder"; 992 case CXCompletionChunk_Informative: return "Informative"; 993 case CXCompletionChunk_CurrentParameter: return "CurrentParameter"; 994 case CXCompletionChunk_LeftParen: return "LeftParen"; 995 case CXCompletionChunk_RightParen: return "RightParen"; 996 case CXCompletionChunk_LeftBracket: return "LeftBracket"; 997 case CXCompletionChunk_RightBracket: return "RightBracket"; 998 case CXCompletionChunk_LeftBrace: return "LeftBrace"; 999 case CXCompletionChunk_RightBrace: return "RightBrace"; 1000 case CXCompletionChunk_LeftAngle: return "LeftAngle"; 1001 case CXCompletionChunk_RightAngle: return "RightAngle"; 1002 case CXCompletionChunk_Comma: return "Comma"; 1003 case CXCompletionChunk_ResultType: return "ResultType"; 1004 case CXCompletionChunk_Colon: return "Colon"; 1005 case CXCompletionChunk_SemiColon: return "SemiColon"; 1006 case CXCompletionChunk_Equal: return "Equal"; 1007 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace"; 1008 case CXCompletionChunk_VerticalSpace: return "VerticalSpace"; 1009 } 1010 1011 return "Unknown"; 1012} 1013 1014static int checkForErrors(CXTranslationUnit TU) { 1015 unsigned Num, i; 1016 CXDiagnostic Diag; 1017 CXString DiagStr; 1018 1019 if (!getenv("CINDEXTEST_FAILONERROR")) 1020 return 0; 1021 1022 Num = clang_getNumDiagnostics(TU); 1023 for (i = 0; i != Num; ++i) { 1024 Diag = clang_getDiagnostic(TU, i); 1025 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) { 1026 DiagStr = clang_formatDiagnostic(Diag, 1027 clang_defaultDiagnosticDisplayOptions()); 1028 fprintf(stderr, "%s\n", clang_getCString(DiagStr)); 1029 clang_disposeString(DiagStr); 1030 clang_disposeDiagnostic(Diag); 1031 return -1; 1032 } 1033 clang_disposeDiagnostic(Diag); 1034 } 1035 1036 return 0; 1037} 1038 1039void print_completion_string(CXCompletionString completion_string, FILE *file) { 1040 int I, N; 1041 1042 N = clang_getNumCompletionChunks(completion_string); 1043 for (I = 0; I != N; ++I) { 1044 CXString text; 1045 const char *cstr; 1046 enum CXCompletionChunkKind Kind 1047 = clang_getCompletionChunkKind(completion_string, I); 1048 1049 if (Kind == CXCompletionChunk_Optional) { 1050 fprintf(file, "{Optional "); 1051 print_completion_string( 1052 clang_getCompletionChunkCompletionString(completion_string, I), 1053 file); 1054 fprintf(file, "}"); 1055 continue; 1056 } 1057 1058 if (Kind == CXCompletionChunk_VerticalSpace) { 1059 fprintf(file, "{VerticalSpace }"); 1060 continue; 1061 } 1062 1063 text = clang_getCompletionChunkText(completion_string, I); 1064 cstr = clang_getCString(text); 1065 fprintf(file, "{%s %s}", 1066 clang_getCompletionChunkKindSpelling(Kind), 1067 cstr ? cstr : ""); 1068 clang_disposeString(text); 1069 } 1070 1071} 1072 1073void print_completion_result(CXCompletionResult *completion_result, 1074 CXClientData client_data) { 1075 FILE *file = (FILE *)client_data; 1076 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind); 1077 unsigned annotationCount; 1078 1079 fprintf(file, "%s:", clang_getCString(ks)); 1080 clang_disposeString(ks); 1081 1082 print_completion_string(completion_result->CompletionString, file); 1083 fprintf(file, " (%u)", 1084 clang_getCompletionPriority(completion_result->CompletionString)); 1085 switch (clang_getCompletionAvailability(completion_result->CompletionString)){ 1086 case CXAvailability_Available: 1087 break; 1088 1089 case CXAvailability_Deprecated: 1090 fprintf(file, " (deprecated)"); 1091 break; 1092 1093 case CXAvailability_NotAvailable: 1094 fprintf(file, " (unavailable)"); 1095 break; 1096 1097 case CXAvailability_NotAccessible: 1098 fprintf(file, " (inaccessible)"); 1099 break; 1100 } 1101 1102 annotationCount = clang_getCompletionNumAnnotations( 1103 completion_result->CompletionString); 1104 if (annotationCount) { 1105 unsigned i; 1106 fprintf(file, " ("); 1107 for (i = 0; i < annotationCount; ++i) { 1108 if (i != 0) 1109 fprintf(file, ", "); 1110 fprintf(file, "\"%s\"", 1111 clang_getCString(clang_getCompletionAnnotation( 1112 completion_result->CompletionString, i))); 1113 } 1114 fprintf(file, ")"); 1115 } 1116 1117 fprintf(file, "\n"); 1118} 1119 1120void print_completion_contexts(unsigned long long contexts, FILE *file) { 1121 fprintf(file, "Completion contexts:\n"); 1122 if (contexts == CXCompletionContext_Unknown) { 1123 fprintf(file, "Unknown\n"); 1124 } 1125 if (contexts & CXCompletionContext_AnyType) { 1126 fprintf(file, "Any type\n"); 1127 } 1128 if (contexts & CXCompletionContext_AnyValue) { 1129 fprintf(file, "Any value\n"); 1130 } 1131 if (contexts & CXCompletionContext_ObjCObjectValue) { 1132 fprintf(file, "Objective-C object value\n"); 1133 } 1134 if (contexts & CXCompletionContext_ObjCSelectorValue) { 1135 fprintf(file, "Objective-C selector value\n"); 1136 } 1137 if (contexts & CXCompletionContext_CXXClassTypeValue) { 1138 fprintf(file, "C++ class type value\n"); 1139 } 1140 if (contexts & CXCompletionContext_DotMemberAccess) { 1141 fprintf(file, "Dot member access\n"); 1142 } 1143 if (contexts & CXCompletionContext_ArrowMemberAccess) { 1144 fprintf(file, "Arrow member access\n"); 1145 } 1146 if (contexts & CXCompletionContext_ObjCPropertyAccess) { 1147 fprintf(file, "Objective-C property access\n"); 1148 } 1149 if (contexts & CXCompletionContext_EnumTag) { 1150 fprintf(file, "Enum tag\n"); 1151 } 1152 if (contexts & CXCompletionContext_UnionTag) { 1153 fprintf(file, "Union tag\n"); 1154 } 1155 if (contexts & CXCompletionContext_StructTag) { 1156 fprintf(file, "Struct tag\n"); 1157 } 1158 if (contexts & CXCompletionContext_ClassTag) { 1159 fprintf(file, "Class name\n"); 1160 } 1161 if (contexts & CXCompletionContext_Namespace) { 1162 fprintf(file, "Namespace or namespace alias\n"); 1163 } 1164 if (contexts & CXCompletionContext_NestedNameSpecifier) { 1165 fprintf(file, "Nested name specifier\n"); 1166 } 1167 if (contexts & CXCompletionContext_ObjCInterface) { 1168 fprintf(file, "Objective-C interface\n"); 1169 } 1170 if (contexts & CXCompletionContext_ObjCProtocol) { 1171 fprintf(file, "Objective-C protocol\n"); 1172 } 1173 if (contexts & CXCompletionContext_ObjCCategory) { 1174 fprintf(file, "Objective-C category\n"); 1175 } 1176 if (contexts & CXCompletionContext_ObjCInstanceMessage) { 1177 fprintf(file, "Objective-C instance method\n"); 1178 } 1179 if (contexts & CXCompletionContext_ObjCClassMessage) { 1180 fprintf(file, "Objective-C class method\n"); 1181 } 1182 if (contexts & CXCompletionContext_ObjCSelectorName) { 1183 fprintf(file, "Objective-C selector name\n"); 1184 } 1185 if (contexts & CXCompletionContext_MacroName) { 1186 fprintf(file, "Macro name\n"); 1187 } 1188 if (contexts & CXCompletionContext_NaturalLanguage) { 1189 fprintf(file, "Natural language\n"); 1190 } 1191} 1192 1193int my_stricmp(const char *s1, const char *s2) { 1194 while (*s1 && *s2) { 1195 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2); 1196 if (c1 < c2) 1197 return -1; 1198 else if (c1 > c2) 1199 return 1; 1200 1201 ++s1; 1202 ++s2; 1203 } 1204 1205 if (*s1) 1206 return 1; 1207 else if (*s2) 1208 return -1; 1209 return 0; 1210} 1211 1212int perform_code_completion(int argc, const char **argv, int timing_only) { 1213 const char *input = argv[1]; 1214 char *filename = 0; 1215 unsigned line; 1216 unsigned column; 1217 CXIndex CIdx; 1218 int errorCode; 1219 struct CXUnsavedFile *unsaved_files = 0; 1220 int num_unsaved_files = 0; 1221 CXCodeCompleteResults *results = 0; 1222 CXTranslationUnit TU = 0; 1223 unsigned I, Repeats = 1; 1224 unsigned completionOptions = clang_defaultCodeCompleteOptions(); 1225 1226 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS")) 1227 completionOptions |= CXCodeComplete_IncludeCodePatterns; 1228 1229 if (timing_only) 1230 input += strlen("-code-completion-timing="); 1231 else 1232 input += strlen("-code-completion-at="); 1233 1234 if ((errorCode = parse_file_line_column(input, &filename, &line, &column, 1235 0, 0))) 1236 return errorCode; 1237 1238 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) 1239 return -1; 1240 1241 CIdx = clang_createIndex(0, 0); 1242 1243 if (getenv("CINDEXTEST_EDITING")) 1244 Repeats = 5; 1245 1246 TU = clang_parseTranslationUnit(CIdx, 0, 1247 argv + num_unsaved_files + 2, 1248 argc - num_unsaved_files - 2, 1249 0, 0, getDefaultParsingOptions()); 1250 if (!TU) { 1251 fprintf(stderr, "Unable to load translation unit!\n"); 1252 return 1; 1253 } 1254 1255 if (clang_reparseTranslationUnit(TU, 0, 0, clang_defaultReparseOptions(TU))) { 1256 fprintf(stderr, "Unable to reparse translation init!\n"); 1257 return 1; 1258 } 1259 1260 for (I = 0; I != Repeats; ++I) { 1261 results = clang_codeCompleteAt(TU, filename, line, column, 1262 unsaved_files, num_unsaved_files, 1263 completionOptions); 1264 if (!results) { 1265 fprintf(stderr, "Unable to perform code completion!\n"); 1266 return 1; 1267 } 1268 if (I != Repeats-1) 1269 clang_disposeCodeCompleteResults(results); 1270 } 1271 1272 if (results) { 1273 unsigned i, n = results->NumResults, containerIsIncomplete = 0; 1274 unsigned long long contexts; 1275 enum CXCursorKind containerKind; 1276 CXString objCSelector; 1277 const char *selectorString; 1278 if (!timing_only) { 1279 /* Sort the code-completion results based on the typed text. */ 1280 clang_sortCodeCompletionResults(results->Results, results->NumResults); 1281 1282 for (i = 0; i != n; ++i) 1283 print_completion_result(results->Results + i, stdout); 1284 } 1285 n = clang_codeCompleteGetNumDiagnostics(results); 1286 for (i = 0; i != n; ++i) { 1287 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i); 1288 PrintDiagnostic(diag); 1289 clang_disposeDiagnostic(diag); 1290 } 1291 1292 contexts = clang_codeCompleteGetContexts(results); 1293 print_completion_contexts(contexts, stdout); 1294 1295 containerKind = clang_codeCompleteGetContainerKind(results, 1296 &containerIsIncomplete); 1297 1298 if (containerKind != CXCursor_InvalidCode) { 1299 /* We have found a container */ 1300 CXString containerUSR, containerKindSpelling; 1301 containerKindSpelling = clang_getCursorKindSpelling(containerKind); 1302 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling)); 1303 clang_disposeString(containerKindSpelling); 1304 1305 if (containerIsIncomplete) { 1306 printf("Container is incomplete\n"); 1307 } 1308 else { 1309 printf("Container is complete\n"); 1310 } 1311 1312 containerUSR = clang_codeCompleteGetContainerUSR(results); 1313 printf("Container USR: %s\n", clang_getCString(containerUSR)); 1314 clang_disposeString(containerUSR); 1315 } 1316 1317 objCSelector = clang_codeCompleteGetObjCSelector(results); 1318 selectorString = clang_getCString(objCSelector); 1319 if (selectorString && strlen(selectorString) > 0) { 1320 printf("Objective-C selector: %s\n", selectorString); 1321 } 1322 clang_disposeString(objCSelector); 1323 1324 clang_disposeCodeCompleteResults(results); 1325 } 1326 clang_disposeTranslationUnit(TU); 1327 clang_disposeIndex(CIdx); 1328 free(filename); 1329 1330 free_remapped_files(unsaved_files, num_unsaved_files); 1331 1332 return 0; 1333} 1334 1335typedef struct { 1336 char *filename; 1337 unsigned line; 1338 unsigned column; 1339} CursorSourceLocation; 1340 1341static int inspect_cursor_at(int argc, const char **argv) { 1342 CXIndex CIdx; 1343 int errorCode; 1344 struct CXUnsavedFile *unsaved_files = 0; 1345 int num_unsaved_files = 0; 1346 CXTranslationUnit TU; 1347 CXCursor Cursor; 1348 CursorSourceLocation *Locations = 0; 1349 unsigned NumLocations = 0, Loc; 1350 unsigned Repeats = 1; 1351 unsigned I; 1352 1353 /* Count the number of locations. */ 1354 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1]) 1355 ++NumLocations; 1356 1357 /* Parse the locations. */ 1358 assert(NumLocations > 0 && "Unable to count locations?"); 1359 Locations = (CursorSourceLocation *)malloc( 1360 NumLocations * sizeof(CursorSourceLocation)); 1361 for (Loc = 0; Loc < NumLocations; ++Loc) { 1362 const char *input = argv[Loc + 1] + strlen("-cursor-at="); 1363 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename, 1364 &Locations[Loc].line, 1365 &Locations[Loc].column, 0, 0))) 1366 return errorCode; 1367 } 1368 1369 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files, 1370 &num_unsaved_files)) 1371 return -1; 1372 1373 if (getenv("CINDEXTEST_EDITING")) 1374 Repeats = 5; 1375 1376 /* Parse the translation unit. When we're testing clang_getCursor() after 1377 reparsing, don't remap unsaved files until the second parse. */ 1378 CIdx = clang_createIndex(1, 1); 1379 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1], 1380 argv + num_unsaved_files + 1 + NumLocations, 1381 argc - num_unsaved_files - 2 - NumLocations, 1382 unsaved_files, 1383 Repeats > 1? 0 : num_unsaved_files, 1384 getDefaultParsingOptions()); 1385 1386 if (!TU) { 1387 fprintf(stderr, "unable to parse input\n"); 1388 return -1; 1389 } 1390 1391 if (checkForErrors(TU) != 0) 1392 return -1; 1393 1394 for (I = 0; I != Repeats; ++I) { 1395 if (Repeats > 1 && 1396 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files, 1397 clang_defaultReparseOptions(TU))) { 1398 clang_disposeTranslationUnit(TU); 1399 return 1; 1400 } 1401 1402 if (checkForErrors(TU) != 0) 1403 return -1; 1404 1405 for (Loc = 0; Loc < NumLocations; ++Loc) { 1406 CXFile file = clang_getFile(TU, Locations[Loc].filename); 1407 if (!file) 1408 continue; 1409 1410 Cursor = clang_getCursor(TU, 1411 clang_getLocation(TU, file, Locations[Loc].line, 1412 Locations[Loc].column)); 1413 1414 if (checkForErrors(TU) != 0) 1415 return -1; 1416 1417 if (I + 1 == Repeats) { 1418 CXCompletionString completionString = clang_getCursorCompletionString( 1419 Cursor); 1420 PrintCursor(Cursor); 1421 if (completionString != NULL) { 1422 printf("\nCompletion string: "); 1423 print_completion_string(completionString, stdout); 1424 } 1425 printf("\n"); 1426 free(Locations[Loc].filename); 1427 } 1428 } 1429 } 1430 1431 PrintDiagnostics(TU); 1432 clang_disposeTranslationUnit(TU); 1433 clang_disposeIndex(CIdx); 1434 free(Locations); 1435 free_remapped_files(unsaved_files, num_unsaved_files); 1436 return 0; 1437} 1438 1439static enum CXVisitorResult findFileRefsVisit(void *context, 1440 CXCursor cursor, CXSourceRange range) { 1441 if (clang_Range_isNull(range)) 1442 return CXVisit_Continue; 1443 1444 PrintCursor(cursor); 1445 PrintRange(range, ""); 1446 printf("\n"); 1447 return CXVisit_Continue; 1448} 1449 1450static int find_file_refs_at(int argc, const char **argv) { 1451 CXIndex CIdx; 1452 int errorCode; 1453 struct CXUnsavedFile *unsaved_files = 0; 1454 int num_unsaved_files = 0; 1455 CXTranslationUnit TU; 1456 CXCursor Cursor; 1457 CursorSourceLocation *Locations = 0; 1458 unsigned NumLocations = 0, Loc; 1459 unsigned Repeats = 1; 1460 unsigned I; 1461 1462 /* Count the number of locations. */ 1463 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1]) 1464 ++NumLocations; 1465 1466 /* Parse the locations. */ 1467 assert(NumLocations > 0 && "Unable to count locations?"); 1468 Locations = (CursorSourceLocation *)malloc( 1469 NumLocations * sizeof(CursorSourceLocation)); 1470 for (Loc = 0; Loc < NumLocations; ++Loc) { 1471 const char *input = argv[Loc + 1] + strlen("-file-refs-at="); 1472 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename, 1473 &Locations[Loc].line, 1474 &Locations[Loc].column, 0, 0))) 1475 return errorCode; 1476 } 1477 1478 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files, 1479 &num_unsaved_files)) 1480 return -1; 1481 1482 if (getenv("CINDEXTEST_EDITING")) 1483 Repeats = 5; 1484 1485 /* Parse the translation unit. When we're testing clang_getCursor() after 1486 reparsing, don't remap unsaved files until the second parse. */ 1487 CIdx = clang_createIndex(1, 1); 1488 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1], 1489 argv + num_unsaved_files + 1 + NumLocations, 1490 argc - num_unsaved_files - 2 - NumLocations, 1491 unsaved_files, 1492 Repeats > 1? 0 : num_unsaved_files, 1493 getDefaultParsingOptions()); 1494 1495 if (!TU) { 1496 fprintf(stderr, "unable to parse input\n"); 1497 return -1; 1498 } 1499 1500 if (checkForErrors(TU) != 0) 1501 return -1; 1502 1503 for (I = 0; I != Repeats; ++I) { 1504 if (Repeats > 1 && 1505 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files, 1506 clang_defaultReparseOptions(TU))) { 1507 clang_disposeTranslationUnit(TU); 1508 return 1; 1509 } 1510 1511 if (checkForErrors(TU) != 0) 1512 return -1; 1513 1514 for (Loc = 0; Loc < NumLocations; ++Loc) { 1515 CXFile file = clang_getFile(TU, Locations[Loc].filename); 1516 if (!file) 1517 continue; 1518 1519 Cursor = clang_getCursor(TU, 1520 clang_getLocation(TU, file, Locations[Loc].line, 1521 Locations[Loc].column)); 1522 1523 if (checkForErrors(TU) != 0) 1524 return -1; 1525 1526 if (I + 1 == Repeats) { 1527 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit }; 1528 PrintCursor(Cursor); 1529 printf("\n"); 1530 clang_findReferencesInFile(Cursor, file, visitor); 1531 free(Locations[Loc].filename); 1532 1533 if (checkForErrors(TU) != 0) 1534 return -1; 1535 } 1536 } 1537 } 1538 1539 PrintDiagnostics(TU); 1540 clang_disposeTranslationUnit(TU); 1541 clang_disposeIndex(CIdx); 1542 free(Locations); 1543 free_remapped_files(unsaved_files, num_unsaved_files); 1544 return 0; 1545} 1546 1547typedef struct { 1548 const char *check_prefix; 1549 int first_check_printed; 1550 int fail_for_error; 1551 int abort; 1552} IndexData; 1553 1554static void printCheck(IndexData *data) { 1555 if (data->check_prefix) { 1556 if (data->first_check_printed) { 1557 printf("// %s-NEXT: ", data->check_prefix); 1558 } else { 1559 printf("// %s : ", data->check_prefix); 1560 data->first_check_printed = 1; 1561 } 1562 } 1563} 1564 1565static void printCXIndexFile(CXIdxClientFile file) { 1566 CXString filename = clang_getFileName((CXFile)file); 1567 printf("%s", clang_getCString(filename)); 1568 clang_disposeString(filename); 1569} 1570 1571static void printCXIndexLoc(CXIdxLoc loc) { 1572 CXString filename; 1573 const char *cname, *end; 1574 CXIdxClientFile file; 1575 unsigned line, column; 1576 int isHeader; 1577 1578 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0); 1579 if (line == 0) { 1580 printf("<null loc>"); 1581 return; 1582 } 1583 filename = clang_getFileName((CXFile)file); 1584 cname = clang_getCString(filename); 1585 end = cname + strlen(cname); 1586 isHeader = (end[-2] == '.' && end[-1] == 'h'); 1587 1588 if (isHeader) { 1589 printCXIndexFile(file); 1590 printf(":"); 1591 } 1592 printf("%d:%d", line, column); 1593} 1594 1595static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info, 1596 CXIdxLoc loc) { 1597 const char *name; 1598 char *newStr; 1599 CXIdxClientFile file; 1600 unsigned line, column; 1601 1602 name = info->name; 1603 if (!name) 1604 name = "<anon-tag>"; 1605 1606 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0); 1607 /* FIXME: free these.*/ 1608 newStr = (char *)malloc(strlen(name) + 10); 1609 sprintf(newStr, "%s:%d:%d", name, line, column); 1610 return (CXIdxClientContainer)newStr; 1611} 1612 1613static void printCXIndexContainer(const CXIdxContainerInfo *info) { 1614 CXIdxClientContainer container; 1615 container = clang_index_getClientContainer(info); 1616 if (!container) 1617 printf("[<<NULL>>]"); 1618 else 1619 printf("[%s]", (const char *)container); 1620} 1621 1622static const char *getEntityKindString(CXIdxEntityKind kind) { 1623 switch (kind) { 1624 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>"; 1625 case CXIdxEntity_Typedef: return "typedef"; 1626 case CXIdxEntity_Function: return "function"; 1627 case CXIdxEntity_Variable: return "variable"; 1628 case CXIdxEntity_Field: return "field"; 1629 case CXIdxEntity_EnumConstant: return "enumerator"; 1630 case CXIdxEntity_ObjCClass: return "objc-class"; 1631 case CXIdxEntity_ObjCProtocol: return "objc-protocol"; 1632 case CXIdxEntity_ObjCCategory: return "objc-category"; 1633 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method"; 1634 case CXIdxEntity_ObjCClassMethod: return "objc-class-method"; 1635 case CXIdxEntity_ObjCProperty: return "objc-property"; 1636 case CXIdxEntity_ObjCIvar: return "objc-ivar"; 1637 case CXIdxEntity_Enum: return "enum"; 1638 case CXIdxEntity_Struct: return "struct"; 1639 case CXIdxEntity_Union: return "union"; 1640 case CXIdxEntity_CXXClass: return "c++-class"; 1641 case CXIdxEntity_CXXNamespace: return "namespace"; 1642 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias"; 1643 case CXIdxEntity_CXXStaticVariable: return "c++-static-var"; 1644 case CXIdxEntity_CXXStaticMethod: return "c++-static-method"; 1645 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method"; 1646 case CXIdxEntity_CXXConstructor: return "constructor"; 1647 case CXIdxEntity_CXXDestructor: return "destructor"; 1648 case CXIdxEntity_CXXConversionFunction: return "conversion-func"; 1649 case CXIdxEntity_CXXTypeAlias: return "type-alias"; 1650 } 1651 assert(0 && "Garbage entity kind"); 1652 return 0; 1653} 1654 1655static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) { 1656 switch (kind) { 1657 case CXIdxEntity_NonTemplate: return ""; 1658 case CXIdxEntity_Template: return "-template"; 1659 case CXIdxEntity_TemplatePartialSpecialization: 1660 return "-template-partial-spec"; 1661 case CXIdxEntity_TemplateSpecialization: return "-template-spec"; 1662 } 1663 assert(0 && "Garbage entity kind"); 1664 return 0; 1665} 1666 1667static const char *getEntityLanguageString(CXIdxEntityLanguage kind) { 1668 switch (kind) { 1669 case CXIdxEntityLang_None: return "<none>"; 1670 case CXIdxEntityLang_C: return "C"; 1671 case CXIdxEntityLang_ObjC: return "ObjC"; 1672 case CXIdxEntityLang_CXX: return "C++"; 1673 } 1674 assert(0 && "Garbage language kind"); 1675 return 0; 1676} 1677 1678static void printEntityInfo(const char *cb, 1679 CXClientData client_data, 1680 const CXIdxEntityInfo *info) { 1681 const char *name; 1682 IndexData *index_data; 1683 index_data = (IndexData *)client_data; 1684 printCheck(index_data); 1685 1686 if (!info) { 1687 printf("%s: <<NULL>>", cb); 1688 return; 1689 } 1690 1691 name = info->name; 1692 if (!name) 1693 name = "<anon-tag>"; 1694 1695 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind), 1696 getEntityTemplateKindString(info->templateKind)); 1697 printf(" | lang: %s", getEntityLanguageString(info->lang)); 1698 printf(" | name: %s", name); 1699 printf(" | USR: %s", info->USR); 1700} 1701 1702static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo, 1703 CXClientData client_data) { 1704 unsigned i; 1705 for (i = 0; i < ProtoInfo->numProtocols; ++i) { 1706 printEntityInfo(" <protocol>", client_data, 1707 ProtoInfo->protocols[i]->protocol); 1708 printf(" | cursor: "); 1709 PrintCursor(ProtoInfo->protocols[i]->cursor); 1710 printf(" | loc: "); 1711 printCXIndexLoc(ProtoInfo->protocols[i]->loc); 1712 printf("\n"); 1713 } 1714} 1715 1716static void index_diagnostic(CXClientData client_data, 1717 CXDiagnosticSet diagSet, void *reserved) { 1718 CXString str; 1719 const char *cstr; 1720 unsigned numDiags, i; 1721 CXDiagnostic diag; 1722 IndexData *index_data; 1723 index_data = (IndexData *)client_data; 1724 printCheck(index_data); 1725 1726 numDiags = clang_getNumDiagnosticsInSet(diagSet); 1727 for (i = 0; i != numDiags; ++i) { 1728 diag = clang_getDiagnosticInSet(diagSet, i); 1729 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions()); 1730 cstr = clang_getCString(str); 1731 printf("[diagnostic]: %s\n", cstr); 1732 clang_disposeString(str); 1733 1734 if (getenv("CINDEXTEST_FAILONERROR") && 1735 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) { 1736 index_data->fail_for_error = 1; 1737 } 1738 } 1739} 1740 1741static CXIdxClientFile index_enteredMainFile(CXClientData client_data, 1742 CXFile file, void *reserved) { 1743 IndexData *index_data; 1744 index_data = (IndexData *)client_data; 1745 printCheck(index_data); 1746 1747 printf("[enteredMainFile]: "); 1748 printCXIndexFile((CXIdxClientFile)file); 1749 printf("\n"); 1750 1751 return (CXIdxClientFile)file; 1752} 1753 1754static CXIdxClientFile index_ppIncludedFile(CXClientData client_data, 1755 const CXIdxIncludedFileInfo *info) { 1756 IndexData *index_data; 1757 index_data = (IndexData *)client_data; 1758 printCheck(index_data); 1759 1760 printf("[ppIncludedFile]: "); 1761 printCXIndexFile((CXIdxClientFile)info->file); 1762 printf(" | name: \"%s\"", info->filename); 1763 printf(" | hash loc: "); 1764 printCXIndexLoc(info->hashLoc); 1765 printf(" | isImport: %d | isAngled: %d\n", info->isImport, info->isAngled); 1766 1767 return (CXIdxClientFile)info->file; 1768} 1769 1770static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data, 1771 void *reserved) { 1772 IndexData *index_data; 1773 index_data = (IndexData *)client_data; 1774 printCheck(index_data); 1775 1776 printf("[startedTranslationUnit]\n"); 1777 return (CXIdxClientContainer)"TU"; 1778} 1779 1780static void index_indexDeclaration(CXClientData client_data, 1781 const CXIdxDeclInfo *info) { 1782 IndexData *index_data; 1783 const CXIdxObjCCategoryDeclInfo *CatInfo; 1784 const CXIdxObjCInterfaceDeclInfo *InterInfo; 1785 const CXIdxObjCProtocolRefListInfo *ProtoInfo; 1786 unsigned i; 1787 index_data = (IndexData *)client_data; 1788 1789 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo); 1790 printf(" | cursor: "); 1791 PrintCursor(info->cursor); 1792 printf(" | loc: "); 1793 printCXIndexLoc(info->loc); 1794 printf(" | container: "); 1795 printCXIndexContainer(info->container); 1796 printf(" | isRedecl: %d", info->isRedeclaration); 1797 printf(" | isDef: %d", info->isDefinition); 1798 printf(" | isContainer: %d", info->isContainer); 1799 printf(" | isImplicit: %d\n", info->isImplicit); 1800 1801 for (i = 0; i != info->numAttributes; ++i) { 1802 const CXIdxAttrInfo *Attr = info->attributes[i]; 1803 printf(" <attribute>: "); 1804 PrintCursor(Attr->cursor); 1805 printf("\n"); 1806 } 1807 1808 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) { 1809 const char *kindName = 0; 1810 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind; 1811 switch (K) { 1812 case CXIdxObjCContainer_ForwardRef: 1813 kindName = "forward-ref"; break; 1814 case CXIdxObjCContainer_Interface: 1815 kindName = "interface"; break; 1816 case CXIdxObjCContainer_Implementation: 1817 kindName = "implementation"; break; 1818 } 1819 printCheck(index_data); 1820 printf(" <ObjCContainerInfo>: kind: %s\n", kindName); 1821 } 1822 1823 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) { 1824 printEntityInfo(" <ObjCCategoryInfo>: class", client_data, 1825 CatInfo->objcClass); 1826 printf(" | cursor: "); 1827 PrintCursor(CatInfo->classCursor); 1828 printf(" | loc: "); 1829 printCXIndexLoc(CatInfo->classLoc); 1830 printf("\n"); 1831 } 1832 1833 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) { 1834 if (InterInfo->superInfo) { 1835 printEntityInfo(" <base>", client_data, 1836 InterInfo->superInfo->base); 1837 printf(" | cursor: "); 1838 PrintCursor(InterInfo->superInfo->cursor); 1839 printf(" | loc: "); 1840 printCXIndexLoc(InterInfo->superInfo->loc); 1841 printf("\n"); 1842 } 1843 } 1844 1845 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) { 1846 printProtocolList(ProtoInfo, client_data); 1847 } 1848 1849 if (info->declAsContainer) 1850 clang_index_setClientContainer(info->declAsContainer, 1851 makeClientContainer(info->entityInfo, info->loc)); 1852} 1853 1854static void index_indexEntityReference(CXClientData client_data, 1855 const CXIdxEntityRefInfo *info) { 1856 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity); 1857 printf(" | cursor: "); 1858 PrintCursor(info->cursor); 1859 printf(" | loc: "); 1860 printCXIndexLoc(info->loc); 1861 printEntityInfo(" | <parent>:", client_data, info->parentEntity); 1862 printf(" | container: "); 1863 printCXIndexContainer(info->container); 1864 printf(" | refkind: "); 1865 switch (info->kind) { 1866 case CXIdxEntityRef_Direct: printf("direct"); break; 1867 case CXIdxEntityRef_Implicit: printf("implicit"); break; 1868 } 1869 printf("\n"); 1870} 1871 1872static int index_abortQuery(CXClientData client_data, void *reserved) { 1873 IndexData *index_data; 1874 index_data = (IndexData *)client_data; 1875 return index_data->abort; 1876} 1877 1878static IndexerCallbacks IndexCB = { 1879 index_abortQuery, 1880 index_diagnostic, 1881 index_enteredMainFile, 1882 index_ppIncludedFile, 1883 0, /*importedASTFile*/ 1884 index_startedTranslationUnit, 1885 index_indexDeclaration, 1886 index_indexEntityReference 1887}; 1888 1889static int index_file(int argc, const char **argv) { 1890 const char *check_prefix; 1891 CXIndex Idx; 1892 CXIndexAction idxAction; 1893 IndexData index_data; 1894 unsigned index_opts; 1895 int result; 1896 1897 check_prefix = 0; 1898 if (argc > 0) { 1899 if (strstr(argv[0], "-check-prefix=") == argv[0]) { 1900 check_prefix = argv[0] + strlen("-check-prefix="); 1901 ++argv; 1902 --argc; 1903 } 1904 } 1905 1906 if (argc == 0) { 1907 fprintf(stderr, "no compiler arguments\n"); 1908 return -1; 1909 } 1910 1911 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1, 1912 /* displayDiagnosics=*/1))) { 1913 fprintf(stderr, "Could not create Index\n"); 1914 return 1; 1915 } 1916 idxAction = 0; 1917 result = 1; 1918 1919 index_data.check_prefix = check_prefix; 1920 index_data.first_check_printed = 0; 1921 index_data.fail_for_error = 0; 1922 index_data.abort = 0; 1923 1924 index_opts = 0; 1925 if (getenv("CINDEXTEST_SUPPRESSREFS")) 1926 index_opts |= CXIndexOpt_SuppressRedundantRefs; 1927 1928 idxAction = clang_IndexAction_create(Idx); 1929 result = clang_indexSourceFile(idxAction, &index_data, 1930 &IndexCB,sizeof(IndexCB), index_opts, 1931 0, argv, argc, 0, 0, 0, 0); 1932 if (index_data.fail_for_error) 1933 result = -1; 1934 1935 clang_IndexAction_dispose(idxAction); 1936 clang_disposeIndex(Idx); 1937 return result; 1938} 1939 1940static int index_tu(int argc, const char **argv) { 1941 CXIndex Idx; 1942 CXIndexAction idxAction; 1943 CXTranslationUnit TU; 1944 const char *check_prefix; 1945 IndexData index_data; 1946 unsigned index_opts; 1947 int result; 1948 1949 check_prefix = 0; 1950 if (argc > 0) { 1951 if (strstr(argv[0], "-check-prefix=") == argv[0]) { 1952 check_prefix = argv[0] + strlen("-check-prefix="); 1953 ++argv; 1954 --argc; 1955 } 1956 } 1957 1958 if (argc == 0) { 1959 fprintf(stderr, "no ast file\n"); 1960 return -1; 1961 } 1962 1963 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1, 1964 /* displayDiagnosics=*/1))) { 1965 fprintf(stderr, "Could not create Index\n"); 1966 return 1; 1967 } 1968 idxAction = 0; 1969 result = 1; 1970 1971 if (!CreateTranslationUnit(Idx, argv[0], &TU)) 1972 goto finished; 1973 1974 index_data.check_prefix = check_prefix; 1975 index_data.first_check_printed = 0; 1976 index_data.fail_for_error = 0; 1977 index_data.abort = 0; 1978 1979 index_opts = 0; 1980 if (getenv("CINDEXTEST_SUPPRESSREFS")) 1981 index_opts |= CXIndexOpt_SuppressRedundantRefs; 1982 1983 idxAction = clang_IndexAction_create(Idx); 1984 result = clang_indexTranslationUnit(idxAction, &index_data, 1985 &IndexCB,sizeof(IndexCB), 1986 index_opts, TU); 1987 if (index_data.fail_for_error) 1988 goto finished; 1989 1990 finished: 1991 clang_IndexAction_dispose(idxAction); 1992 clang_disposeIndex(Idx); 1993 1994 return result; 1995} 1996 1997int perform_token_annotation(int argc, const char **argv) { 1998 const char *input = argv[1]; 1999 char *filename = 0; 2000 unsigned line, second_line; 2001 unsigned column, second_column; 2002 CXIndex CIdx; 2003 CXTranslationUnit TU = 0; 2004 int errorCode; 2005 struct CXUnsavedFile *unsaved_files = 0; 2006 int num_unsaved_files = 0; 2007 CXToken *tokens; 2008 unsigned num_tokens; 2009 CXSourceRange range; 2010 CXSourceLocation startLoc, endLoc; 2011 CXFile file = 0; 2012 CXCursor *cursors = 0; 2013 unsigned i; 2014 2015 input += strlen("-test-annotate-tokens="); 2016 if ((errorCode = parse_file_line_column(input, &filename, &line, &column, 2017 &second_line, &second_column))) 2018 return errorCode; 2019 2020 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) 2021 return -1; 2022 2023 CIdx = clang_createIndex(0, 1); 2024 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1], 2025 argv + num_unsaved_files + 2, 2026 argc - num_unsaved_files - 3, 2027 unsaved_files, 2028 num_unsaved_files, 2029 getDefaultParsingOptions()); 2030 if (!TU) { 2031 fprintf(stderr, "unable to parse input\n"); 2032 clang_disposeIndex(CIdx); 2033 free(filename); 2034 free_remapped_files(unsaved_files, num_unsaved_files); 2035 return -1; 2036 } 2037 errorCode = 0; 2038 2039 if (checkForErrors(TU) != 0) 2040 return -1; 2041 2042 if (getenv("CINDEXTEST_EDITING")) { 2043 for (i = 0; i < 5; ++i) { 2044 if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files, 2045 clang_defaultReparseOptions(TU))) { 2046 fprintf(stderr, "Unable to reparse translation unit!\n"); 2047 errorCode = -1; 2048 goto teardown; 2049 } 2050 } 2051 } 2052 2053 if (checkForErrors(TU) != 0) { 2054 errorCode = -1; 2055 goto teardown; 2056 } 2057 2058 file = clang_getFile(TU, filename); 2059 if (!file) { 2060 fprintf(stderr, "file %s is not in this translation unit\n", filename); 2061 errorCode = -1; 2062 goto teardown; 2063 } 2064 2065 startLoc = clang_getLocation(TU, file, line, column); 2066 if (clang_equalLocations(clang_getNullLocation(), startLoc)) { 2067 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line, 2068 column); 2069 errorCode = -1; 2070 goto teardown; 2071 } 2072 2073 endLoc = clang_getLocation(TU, file, second_line, second_column); 2074 if (clang_equalLocations(clang_getNullLocation(), endLoc)) { 2075 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, 2076 second_line, second_column); 2077 errorCode = -1; 2078 goto teardown; 2079 } 2080 2081 range = clang_getRange(startLoc, endLoc); 2082 clang_tokenize(TU, range, &tokens, &num_tokens); 2083 2084 if (checkForErrors(TU) != 0) { 2085 errorCode = -1; 2086 goto teardown; 2087 } 2088 2089 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor)); 2090 clang_annotateTokens(TU, tokens, num_tokens, cursors); 2091 2092 if (checkForErrors(TU) != 0) { 2093 errorCode = -1; 2094 goto teardown; 2095 } 2096 2097 for (i = 0; i != num_tokens; ++i) { 2098 const char *kind = "<unknown>"; 2099 CXString spelling = clang_getTokenSpelling(TU, tokens[i]); 2100 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]); 2101 unsigned start_line, start_column, end_line, end_column; 2102 2103 switch (clang_getTokenKind(tokens[i])) { 2104 case CXToken_Punctuation: kind = "Punctuation"; break; 2105 case CXToken_Keyword: kind = "Keyword"; break; 2106 case CXToken_Identifier: kind = "Identifier"; break; 2107 case CXToken_Literal: kind = "Literal"; break; 2108 case CXToken_Comment: kind = "Comment"; break; 2109 } 2110 clang_getSpellingLocation(clang_getRangeStart(extent), 2111 0, &start_line, &start_column, 0); 2112 clang_getSpellingLocation(clang_getRangeEnd(extent), 2113 0, &end_line, &end_column, 0); 2114 printf("%s: \"%s\" ", kind, clang_getCString(spelling)); 2115 PrintExtent(stdout, start_line, start_column, end_line, end_column); 2116 if (!clang_isInvalid(cursors[i].kind)) { 2117 printf(" "); 2118 PrintCursor(cursors[i]); 2119 } 2120 printf("\n"); 2121 } 2122 free(cursors); 2123 clang_disposeTokens(TU, tokens, num_tokens); 2124 2125 teardown: 2126 PrintDiagnostics(TU); 2127 clang_disposeTranslationUnit(TU); 2128 clang_disposeIndex(CIdx); 2129 free(filename); 2130 free_remapped_files(unsaved_files, num_unsaved_files); 2131 return errorCode; 2132} 2133 2134/******************************************************************************/ 2135/* USR printing. */ 2136/******************************************************************************/ 2137 2138static int insufficient_usr(const char *kind, const char *usage) { 2139 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage); 2140 return 1; 2141} 2142 2143static unsigned isUSR(const char *s) { 2144 return s[0] == 'c' && s[1] == ':'; 2145} 2146 2147static int not_usr(const char *s, const char *arg) { 2148 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg); 2149 return 1; 2150} 2151 2152static void print_usr(CXString usr) { 2153 const char *s = clang_getCString(usr); 2154 printf("%s\n", s); 2155 clang_disposeString(usr); 2156} 2157 2158static void display_usrs() { 2159 fprintf(stderr, "-print-usrs options:\n" 2160 " ObjCCategory <class name> <category name>\n" 2161 " ObjCClass <class name>\n" 2162 " ObjCIvar <ivar name> <class USR>\n" 2163 " ObjCMethod <selector> [0=class method|1=instance method] " 2164 "<class USR>\n" 2165 " ObjCProperty <property name> <class USR>\n" 2166 " ObjCProtocol <protocol name>\n"); 2167} 2168 2169int print_usrs(const char **I, const char **E) { 2170 while (I != E) { 2171 const char *kind = *I; 2172 unsigned len = strlen(kind); 2173 switch (len) { 2174 case 8: 2175 if (memcmp(kind, "ObjCIvar", 8) == 0) { 2176 if (I + 2 >= E) 2177 return insufficient_usr(kind, "<ivar name> <class USR>"); 2178 if (!isUSR(I[2])) 2179 return not_usr("<class USR>", I[2]); 2180 else { 2181 CXString x; 2182 x.data = (void*) I[2]; 2183 x.private_flags = 0; 2184 print_usr(clang_constructUSR_ObjCIvar(I[1], x)); 2185 } 2186 2187 I += 3; 2188 continue; 2189 } 2190 break; 2191 case 9: 2192 if (memcmp(kind, "ObjCClass", 9) == 0) { 2193 if (I + 1 >= E) 2194 return insufficient_usr(kind, "<class name>"); 2195 print_usr(clang_constructUSR_ObjCClass(I[1])); 2196 I += 2; 2197 continue; 2198 } 2199 break; 2200 case 10: 2201 if (memcmp(kind, "ObjCMethod", 10) == 0) { 2202 if (I + 3 >= E) 2203 return insufficient_usr(kind, "<method selector> " 2204 "[0=class method|1=instance method] <class USR>"); 2205 if (!isUSR(I[3])) 2206 return not_usr("<class USR>", I[3]); 2207 else { 2208 CXString x; 2209 x.data = (void*) I[3]; 2210 x.private_flags = 0; 2211 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x)); 2212 } 2213 I += 4; 2214 continue; 2215 } 2216 break; 2217 case 12: 2218 if (memcmp(kind, "ObjCCategory", 12) == 0) { 2219 if (I + 2 >= E) 2220 return insufficient_usr(kind, "<class name> <category name>"); 2221 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2])); 2222 I += 3; 2223 continue; 2224 } 2225 if (memcmp(kind, "ObjCProtocol", 12) == 0) { 2226 if (I + 1 >= E) 2227 return insufficient_usr(kind, "<protocol name>"); 2228 print_usr(clang_constructUSR_ObjCProtocol(I[1])); 2229 I += 2; 2230 continue; 2231 } 2232 if (memcmp(kind, "ObjCProperty", 12) == 0) { 2233 if (I + 2 >= E) 2234 return insufficient_usr(kind, "<property name> <class USR>"); 2235 if (!isUSR(I[2])) 2236 return not_usr("<class USR>", I[2]); 2237 else { 2238 CXString x; 2239 x.data = (void*) I[2]; 2240 x.private_flags = 0; 2241 print_usr(clang_constructUSR_ObjCProperty(I[1], x)); 2242 } 2243 I += 3; 2244 continue; 2245 } 2246 break; 2247 default: 2248 break; 2249 } 2250 break; 2251 } 2252 2253 if (I != E) { 2254 fprintf(stderr, "Invalid USR kind: %s\n", *I); 2255 display_usrs(); 2256 return 1; 2257 } 2258 return 0; 2259} 2260 2261int print_usrs_file(const char *file_name) { 2262 char line[2048]; 2263 const char *args[128]; 2264 unsigned numChars = 0; 2265 2266 FILE *fp = fopen(file_name, "r"); 2267 if (!fp) { 2268 fprintf(stderr, "error: cannot open '%s'\n", file_name); 2269 return 1; 2270 } 2271 2272 /* This code is not really all that safe, but it works fine for testing. */ 2273 while (!feof(fp)) { 2274 char c = fgetc(fp); 2275 if (c == '\n') { 2276 unsigned i = 0; 2277 const char *s = 0; 2278 2279 if (numChars == 0) 2280 continue; 2281 2282 line[numChars] = '\0'; 2283 numChars = 0; 2284 2285 if (line[0] == '/' && line[1] == '/') 2286 continue; 2287 2288 s = strtok(line, " "); 2289 while (s) { 2290 args[i] = s; 2291 ++i; 2292 s = strtok(0, " "); 2293 } 2294 if (print_usrs(&args[0], &args[i])) 2295 return 1; 2296 } 2297 else 2298 line[numChars++] = c; 2299 } 2300 2301 fclose(fp); 2302 return 0; 2303} 2304 2305/******************************************************************************/ 2306/* Command line processing. */ 2307/******************************************************************************/ 2308int write_pch_file(const char *filename, int argc, const char *argv[]) { 2309 CXIndex Idx; 2310 CXTranslationUnit TU; 2311 struct CXUnsavedFile *unsaved_files = 0; 2312 int num_unsaved_files = 0; 2313 int result = 0; 2314 2315 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnosics=*/1); 2316 2317 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) { 2318 clang_disposeIndex(Idx); 2319 return -1; 2320 } 2321 2322 TU = clang_parseTranslationUnit(Idx, 0, 2323 argv + num_unsaved_files, 2324 argc - num_unsaved_files, 2325 unsaved_files, 2326 num_unsaved_files, 2327 CXTranslationUnit_Incomplete); 2328 if (!TU) { 2329 fprintf(stderr, "Unable to load translation unit!\n"); 2330 free_remapped_files(unsaved_files, num_unsaved_files); 2331 clang_disposeIndex(Idx); 2332 return 1; 2333 } 2334 2335 switch (clang_saveTranslationUnit(TU, filename, 2336 clang_defaultSaveOptions(TU))) { 2337 case CXSaveError_None: 2338 break; 2339 2340 case CXSaveError_TranslationErrors: 2341 fprintf(stderr, "Unable to write PCH file %s: translation errors\n", 2342 filename); 2343 result = 2; 2344 break; 2345 2346 case CXSaveError_InvalidTU: 2347 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n", 2348 filename); 2349 result = 3; 2350 break; 2351 2352 case CXSaveError_Unknown: 2353 default: 2354 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename); 2355 result = 1; 2356 break; 2357 } 2358 2359 clang_disposeTranslationUnit(TU); 2360 free_remapped_files(unsaved_files, num_unsaved_files); 2361 clang_disposeIndex(Idx); 2362 return result; 2363} 2364 2365/******************************************************************************/ 2366/* Serialized diagnostics. */ 2367/******************************************************************************/ 2368 2369static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) { 2370 switch (error) { 2371 case CXLoadDiag_CannotLoad: return "Cannot Load File"; 2372 case CXLoadDiag_None: break; 2373 case CXLoadDiag_Unknown: return "Unknown"; 2374 case CXLoadDiag_InvalidFile: return "Invalid File"; 2375 } 2376 return "None"; 2377} 2378 2379static const char *getSeverityString(enum CXDiagnosticSeverity severity) { 2380 switch (severity) { 2381 case CXDiagnostic_Note: return "note"; 2382 case CXDiagnostic_Error: return "error"; 2383 case CXDiagnostic_Fatal: return "fatal"; 2384 case CXDiagnostic_Ignored: return "ignored"; 2385 case CXDiagnostic_Warning: return "warning"; 2386 } 2387 return "unknown"; 2388} 2389 2390static void printIndent(unsigned indent) { 2391 if (indent == 0) 2392 return; 2393 fprintf(stderr, "+"); 2394 --indent; 2395 while (indent > 0) { 2396 fprintf(stderr, "-"); 2397 --indent; 2398 } 2399} 2400 2401static void printLocation(CXSourceLocation L) { 2402 CXFile File; 2403 CXString FileName; 2404 unsigned line, column, offset; 2405 2406 clang_getExpansionLocation(L, &File, &line, &column, &offset); 2407 FileName = clang_getFileName(File); 2408 2409 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column); 2410 clang_disposeString(FileName); 2411} 2412 2413static void printRanges(CXDiagnostic D, unsigned indent) { 2414 unsigned i, n = clang_getDiagnosticNumRanges(D); 2415 2416 for (i = 0; i < n; ++i) { 2417 CXSourceLocation Start, End; 2418 CXSourceRange SR = clang_getDiagnosticRange(D, i); 2419 Start = clang_getRangeStart(SR); 2420 End = clang_getRangeEnd(SR); 2421 2422 printIndent(indent); 2423 fprintf(stderr, "Range: "); 2424 printLocation(Start); 2425 fprintf(stderr, " "); 2426 printLocation(End); 2427 fprintf(stderr, "\n"); 2428 } 2429} 2430 2431static void printFixIts(CXDiagnostic D, unsigned indent) { 2432 unsigned i, n = clang_getDiagnosticNumFixIts(D); 2433 for (i = 0 ; i < n; ++i) { 2434 CXSourceRange ReplacementRange; 2435 CXString text; 2436 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange); 2437 2438 printIndent(indent); 2439 fprintf(stderr, "FIXIT: ("); 2440 printLocation(clang_getRangeStart(ReplacementRange)); 2441 fprintf(stderr, " - "); 2442 printLocation(clang_getRangeEnd(ReplacementRange)); 2443 fprintf(stderr, "): \"%s\"\n", clang_getCString(text)); 2444 clang_disposeString(text); 2445 } 2446} 2447 2448static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) { 2449 unsigned i, n; 2450 2451 if (!Diags) 2452 return; 2453 2454 n = clang_getNumDiagnosticsInSet(Diags); 2455 for (i = 0; i < n; ++i) { 2456 CXSourceLocation DiagLoc; 2457 CXDiagnostic D; 2458 CXFile File; 2459 CXString FileName, DiagSpelling, DiagOption; 2460 unsigned line, column, offset; 2461 const char *DiagOptionStr = 0; 2462 2463 D = clang_getDiagnosticInSet(Diags, i); 2464 DiagLoc = clang_getDiagnosticLocation(D); 2465 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset); 2466 FileName = clang_getFileName(File); 2467 DiagSpelling = clang_getDiagnosticSpelling(D); 2468 2469 printIndent(indent); 2470 2471 fprintf(stderr, "%s:%d:%d: %s: %s", 2472 clang_getCString(FileName), 2473 line, 2474 column, 2475 getSeverityString(clang_getDiagnosticSeverity(D)), 2476 clang_getCString(DiagSpelling)); 2477 2478 DiagOption = clang_getDiagnosticOption(D, 0); 2479 DiagOptionStr = clang_getCString(DiagOption); 2480 if (DiagOptionStr) { 2481 fprintf(stderr, " [%s]", DiagOptionStr); 2482 } 2483 2484 fprintf(stderr, "\n"); 2485 2486 printRanges(D, indent); 2487 printFixIts(D, indent); 2488 2489 /* Print subdiagnostics. */ 2490 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2); 2491 2492 clang_disposeString(FileName); 2493 clang_disposeString(DiagSpelling); 2494 clang_disposeString(DiagOption); 2495 } 2496} 2497 2498static int read_diagnostics(const char *filename) { 2499 enum CXLoadDiag_Error error; 2500 CXString errorString; 2501 CXDiagnosticSet Diags = 0; 2502 2503 Diags = clang_loadDiagnostics(filename, &error, &errorString); 2504 if (!Diags) { 2505 fprintf(stderr, "Trouble deserializing file (%s): %s\n", 2506 getDiagnosticCodeStr(error), 2507 clang_getCString(errorString)); 2508 clang_disposeString(errorString); 2509 return 1; 2510 } 2511 2512 printDiagnosticSet(Diags, 0); 2513 fprintf(stderr, "Number of diagnostics: %d\n", 2514 clang_getNumDiagnosticsInSet(Diags)); 2515 clang_disposeDiagnosticSet(Diags); 2516 return 0; 2517} 2518 2519/******************************************************************************/ 2520/* Command line processing. */ 2521/******************************************************************************/ 2522 2523static CXCursorVisitor GetVisitor(const char *s) { 2524 if (s[0] == '\0') 2525 return FilteredPrintingVisitor; 2526 if (strcmp(s, "-usrs") == 0) 2527 return USRVisitor; 2528 if (strncmp(s, "-memory-usage", 13) == 0) 2529 return GetVisitor(s + 13); 2530 return NULL; 2531} 2532 2533static void print_usage(void) { 2534 fprintf(stderr, 2535 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n" 2536 " c-index-test -code-completion-timing=<site> <compiler arguments>\n" 2537 " c-index-test -cursor-at=<site> <compiler arguments>\n" 2538 " c-index-test -file-refs-at=<site> <compiler arguments>\n" 2539 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n" 2540 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n" 2541 " c-index-test -test-file-scan <AST file> <source file> " 2542 "[FileCheck prefix]\n"); 2543 fprintf(stderr, 2544 " c-index-test -test-load-tu <AST file> <symbol filter> " 2545 "[FileCheck prefix]\n" 2546 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> " 2547 "[FileCheck prefix]\n" 2548 " c-index-test -test-load-source <symbol filter> {<args>}*\n"); 2549 fprintf(stderr, 2550 " c-index-test -test-load-source-memory-usage " 2551 "<symbol filter> {<args>}*\n" 2552 " c-index-test -test-load-source-reparse <trials> <symbol filter> " 2553 " {<args>}*\n" 2554 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n" 2555 " c-index-test -test-load-source-usrs-memory-usage " 2556 "<symbol filter> {<args>}*\n" 2557 " c-index-test -test-annotate-tokens=<range> {<args>}*\n" 2558 " c-index-test -test-inclusion-stack-source {<args>}*\n" 2559 " c-index-test -test-inclusion-stack-tu <AST file>\n"); 2560 fprintf(stderr, 2561 " c-index-test -test-print-linkage-source {<args>}*\n" 2562 " c-index-test -test-print-typekind {<args>}*\n" 2563 " c-index-test -print-usr [<CursorKind> {<args>}]*\n" 2564 " c-index-test -print-usr-file <file>\n" 2565 " c-index-test -write-pch <file> <compiler arguments>\n"); 2566 fprintf(stderr, 2567 " c-index-test -read-diagnostics <file>\n\n"); 2568 fprintf(stderr, 2569 " <symbol filter> values:\n%s", 2570 " all - load all symbols, including those from PCH\n" 2571 " local - load all symbols except those in PCH\n" 2572 " category - only load ObjC categories (non-PCH)\n" 2573 " interface - only load ObjC interfaces (non-PCH)\n" 2574 " protocol - only load ObjC protocols (non-PCH)\n" 2575 " function - only load functions (non-PCH)\n" 2576 " typedef - only load typdefs (non-PCH)\n" 2577 " scan-function - scan function bodies (non-PCH)\n\n"); 2578} 2579 2580/***/ 2581 2582int cindextest_main(int argc, const char **argv) { 2583 clang_enableStackTraces(); 2584 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0) 2585 return read_diagnostics(argv[2]); 2586 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1]) 2587 return perform_code_completion(argc, argv, 0); 2588 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1]) 2589 return perform_code_completion(argc, argv, 1); 2590 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1]) 2591 return inspect_cursor_at(argc, argv); 2592 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1]) 2593 return find_file_refs_at(argc, argv); 2594 if (argc > 2 && strcmp(argv[1], "-index-file") == 0) 2595 return index_file(argc - 2, argv + 2); 2596 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0) 2597 return index_tu(argc - 2, argv + 2); 2598 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) { 2599 CXCursorVisitor I = GetVisitor(argv[1] + 13); 2600 if (I) 2601 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I, 2602 NULL); 2603 } 2604 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){ 2605 CXCursorVisitor I = GetVisitor(argv[1] + 25); 2606 if (I) { 2607 int trials = atoi(argv[2]); 2608 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I, 2609 NULL); 2610 } 2611 } 2612 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) { 2613 CXCursorVisitor I = GetVisitor(argv[1] + 17); 2614 2615 PostVisitTU postVisit = 0; 2616 if (strstr(argv[1], "-memory-usage")) 2617 postVisit = PrintMemoryUsage; 2618 2619 if (I) 2620 return perform_test_load_source(argc - 3, argv + 3, argv[2], I, 2621 postVisit); 2622 } 2623 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0) 2624 return perform_file_scan(argv[2], argv[3], 2625 argc >= 5 ? argv[4] : 0); 2626 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1]) 2627 return perform_token_annotation(argc, argv); 2628 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0) 2629 return perform_test_load_source(argc - 2, argv + 2, "all", NULL, 2630 PrintInclusionStack); 2631 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0) 2632 return perform_test_load_tu(argv[2], "all", NULL, NULL, 2633 PrintInclusionStack); 2634 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0) 2635 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage, 2636 NULL); 2637 else if (argc > 2 && strcmp(argv[1], "-test-print-typekind") == 0) 2638 return perform_test_load_source(argc - 2, argv + 2, "all", 2639 PrintTypeKind, 0); 2640 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) { 2641 if (argc > 2) 2642 return print_usrs(argv + 2, argv + argc); 2643 else { 2644 display_usrs(); 2645 return 1; 2646 } 2647 } 2648 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0) 2649 return print_usrs_file(argv[2]); 2650 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0) 2651 return write_pch_file(argv[2], argc - 3, argv + 3); 2652 2653 print_usage(); 2654 return 1; 2655} 2656 2657/***/ 2658 2659/* We intentionally run in a separate thread to ensure we at least minimal 2660 * testing of a multithreaded environment (for example, having a reduced stack 2661 * size). */ 2662 2663typedef struct thread_info { 2664 int argc; 2665 const char **argv; 2666 int result; 2667} thread_info; 2668void thread_runner(void *client_data_v) { 2669 thread_info *client_data = client_data_v; 2670 client_data->result = cindextest_main(client_data->argc, client_data->argv); 2671} 2672 2673int main(int argc, const char **argv) { 2674 thread_info client_data; 2675 2676 if (getenv("CINDEXTEST_NOTHREADS")) 2677 return cindextest_main(argc, argv); 2678 2679 client_data.argc = argc; 2680 client_data.argv = argv; 2681 clang_executeOnThread(thread_runner, &client_data, 0); 2682 return client_data.result; 2683} 2684