c-index-test.c revision 9f59234a91d057cee7c5e3cee91da8696858c692
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 41 return options; 42} 43 44static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column, 45 unsigned end_line, unsigned end_column) { 46 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column, 47 end_line, end_column); 48} 49 50static unsigned CreateTranslationUnit(CXIndex Idx, const char *file, 51 CXTranslationUnit *TU) { 52 53 *TU = clang_createTranslationUnit(Idx, file); 54 if (!*TU) { 55 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file); 56 return 0; 57 } 58 return 1; 59} 60 61void free_remapped_files(struct CXUnsavedFile *unsaved_files, 62 int num_unsaved_files) { 63 int i; 64 for (i = 0; i != num_unsaved_files; ++i) { 65 free((char *)unsaved_files[i].Filename); 66 free((char *)unsaved_files[i].Contents); 67 } 68 free(unsaved_files); 69} 70 71int parse_remapped_files(int argc, const char **argv, int start_arg, 72 struct CXUnsavedFile **unsaved_files, 73 int *num_unsaved_files) { 74 int i; 75 int arg; 76 int prefix_len = strlen("-remap-file="); 77 *unsaved_files = 0; 78 *num_unsaved_files = 0; 79 80 /* Count the number of remapped files. */ 81 for (arg = start_arg; arg < argc; ++arg) { 82 if (strncmp(argv[arg], "-remap-file=", prefix_len)) 83 break; 84 85 ++*num_unsaved_files; 86 } 87 88 if (*num_unsaved_files == 0) 89 return 0; 90 91 *unsaved_files 92 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) * 93 *num_unsaved_files); 94 for (arg = start_arg, i = 0; i != *num_unsaved_files; ++i, ++arg) { 95 struct CXUnsavedFile *unsaved = *unsaved_files + i; 96 const char *arg_string = argv[arg] + prefix_len; 97 int filename_len; 98 char *filename; 99 char *contents; 100 FILE *to_file; 101 const char *semi = strchr(arg_string, ';'); 102 if (!semi) { 103 fprintf(stderr, 104 "error: -remap-file=from;to argument is missing semicolon\n"); 105 free_remapped_files(*unsaved_files, i); 106 *unsaved_files = 0; 107 *num_unsaved_files = 0; 108 return -1; 109 } 110 111 /* Open the file that we're remapping to. */ 112 to_file = fopen(semi + 1, "r"); 113 if (!to_file) { 114 fprintf(stderr, "error: cannot open file %s that we are remapping to\n", 115 semi + 1); 116 free_remapped_files(*unsaved_files, i); 117 *unsaved_files = 0; 118 *num_unsaved_files = 0; 119 return -1; 120 } 121 122 /* Determine the length of the file we're remapping to. */ 123 fseek(to_file, 0, SEEK_END); 124 unsaved->Length = ftell(to_file); 125 fseek(to_file, 0, SEEK_SET); 126 127 /* Read the contents of the file we're remapping to. */ 128 contents = (char *)malloc(unsaved->Length + 1); 129 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) { 130 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n", 131 (feof(to_file) ? "EOF" : "error"), semi + 1); 132 fclose(to_file); 133 free_remapped_files(*unsaved_files, i); 134 *unsaved_files = 0; 135 *num_unsaved_files = 0; 136 return -1; 137 } 138 contents[unsaved->Length] = 0; 139 unsaved->Contents = contents; 140 141 /* Close the file. */ 142 fclose(to_file); 143 144 /* Copy the file name that we're remapping from. */ 145 filename_len = semi - arg_string; 146 filename = (char *)malloc(filename_len + 1); 147 memcpy(filename, arg_string, filename_len); 148 filename[filename_len] = 0; 149 unsaved->Filename = filename; 150 } 151 152 return 0; 153} 154 155/******************************************************************************/ 156/* Pretty-printing. */ 157/******************************************************************************/ 158 159static void PrintCursor(CXCursor Cursor) { 160 if (clang_isInvalid(Cursor.kind)) { 161 CXString ks = clang_getCursorKindSpelling(Cursor.kind); 162 printf("Invalid Cursor => %s", clang_getCString(ks)); 163 clang_disposeString(ks); 164 } 165 else { 166 CXString string, ks; 167 CXCursor Referenced; 168 unsigned line, column; 169 CXCursor SpecializationOf; 170 CXCursor *overridden; 171 unsigned num_overridden; 172 173 ks = clang_getCursorKindSpelling(Cursor.kind); 174 string = clang_getCursorSpelling(Cursor); 175 printf("%s=%s", clang_getCString(ks), 176 clang_getCString(string)); 177 clang_disposeString(ks); 178 clang_disposeString(string); 179 180 Referenced = clang_getCursorReferenced(Cursor); 181 if (!clang_equalCursors(Referenced, clang_getNullCursor())) { 182 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) { 183 unsigned I, N = clang_getNumOverloadedDecls(Referenced); 184 printf("["); 185 for (I = 0; I != N; ++I) { 186 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I); 187 CXSourceLocation Loc; 188 if (I) 189 printf(", "); 190 191 Loc = clang_getCursorLocation(Ovl); 192 clang_getInstantiationLocation(Loc, 0, &line, &column, 0); 193 printf("%d:%d", line, column); 194 } 195 printf("]"); 196 } else { 197 CXSourceLocation Loc = clang_getCursorLocation(Referenced); 198 clang_getInstantiationLocation(Loc, 0, &line, &column, 0); 199 printf(":%d:%d", line, column); 200 } 201 } 202 203 if (clang_isCursorDefinition(Cursor)) 204 printf(" (Definition)"); 205 206 switch (clang_getCursorAvailability(Cursor)) { 207 case CXAvailability_Available: 208 break; 209 210 case CXAvailability_Deprecated: 211 printf(" (deprecated)"); 212 break; 213 214 case CXAvailability_NotAvailable: 215 printf(" (unavailable)"); 216 break; 217 } 218 219 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) { 220 CXType T = 221 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor)); 222 CXString S = clang_getTypeKindSpelling(T.kind); 223 printf(" [IBOutletCollection=%s]", clang_getCString(S)); 224 clang_disposeString(S); 225 } 226 227 if (Cursor.kind == CXCursor_CXXBaseSpecifier) { 228 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor); 229 unsigned isVirtual = clang_isVirtualBase(Cursor); 230 const char *accessStr = 0; 231 232 switch (access) { 233 case CX_CXXInvalidAccessSpecifier: 234 accessStr = "invalid"; break; 235 case CX_CXXPublic: 236 accessStr = "public"; break; 237 case CX_CXXProtected: 238 accessStr = "protected"; break; 239 case CX_CXXPrivate: 240 accessStr = "private"; break; 241 } 242 243 printf(" [access=%s isVirtual=%s]", accessStr, 244 isVirtual ? "true" : "false"); 245 } 246 247 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor); 248 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) { 249 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf); 250 CXString Name = clang_getCursorSpelling(SpecializationOf); 251 clang_getInstantiationLocation(Loc, 0, &line, &column, 0); 252 printf(" [Specialization of %s:%d:%d]", 253 clang_getCString(Name), line, column); 254 clang_disposeString(Name); 255 } 256 257 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden); 258 if (num_overridden) { 259 unsigned I; 260 printf(" [Overrides "); 261 for (I = 0; I != num_overridden; ++I) { 262 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]); 263 clang_getInstantiationLocation(Loc, 0, &line, &column, 0); 264 if (I) 265 printf(", "); 266 printf("@%d:%d", line, column); 267 } 268 printf("]"); 269 clang_disposeOverriddenCursors(overridden); 270 } 271 } 272} 273 274static const char* GetCursorSource(CXCursor Cursor) { 275 CXSourceLocation Loc = clang_getCursorLocation(Cursor); 276 CXString source; 277 CXFile file; 278 clang_getInstantiationLocation(Loc, &file, 0, 0, 0); 279 source = clang_getFileName(file); 280 if (!clang_getCString(source)) { 281 clang_disposeString(source); 282 return "<invalid loc>"; 283 } 284 else { 285 const char *b = basename(clang_getCString(source)); 286 clang_disposeString(source); 287 return b; 288 } 289} 290 291/******************************************************************************/ 292/* Callbacks. */ 293/******************************************************************************/ 294 295typedef void (*PostVisitTU)(CXTranslationUnit); 296 297void PrintDiagnostic(CXDiagnostic Diagnostic) { 298 FILE *out = stderr; 299 CXFile file; 300 CXString Msg; 301 unsigned display_opts = CXDiagnostic_DisplaySourceLocation 302 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges; 303 unsigned i, num_fixits; 304 305 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored) 306 return; 307 308 Msg = clang_formatDiagnostic(Diagnostic, display_opts); 309 fprintf(stderr, "%s\n", clang_getCString(Msg)); 310 clang_disposeString(Msg); 311 312 clang_getInstantiationLocation(clang_getDiagnosticLocation(Diagnostic), 313 &file, 0, 0, 0); 314 if (!file) 315 return; 316 317 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic); 318 for (i = 0; i != num_fixits; ++i) { 319 CXSourceRange range; 320 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range); 321 CXSourceLocation start = clang_getRangeStart(range); 322 CXSourceLocation end = clang_getRangeEnd(range); 323 unsigned start_line, start_column, end_line, end_column; 324 CXFile start_file, end_file; 325 clang_getInstantiationLocation(start, &start_file, &start_line, 326 &start_column, 0); 327 clang_getInstantiationLocation(end, &end_file, &end_line, &end_column, 0); 328 if (clang_equalLocations(start, end)) { 329 /* Insertion. */ 330 if (start_file == file) 331 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n", 332 clang_getCString(insertion_text), start_line, start_column); 333 } else if (strcmp(clang_getCString(insertion_text), "") == 0) { 334 /* Removal. */ 335 if (start_file == file && end_file == file) { 336 fprintf(out, "FIX-IT: Remove "); 337 PrintExtent(out, start_line, start_column, end_line, end_column); 338 fprintf(out, "\n"); 339 } 340 } else { 341 /* Replacement. */ 342 if (start_file == end_file) { 343 fprintf(out, "FIX-IT: Replace "); 344 PrintExtent(out, start_line, start_column, end_line, end_column); 345 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text)); 346 } 347 break; 348 } 349 clang_disposeString(insertion_text); 350 } 351} 352 353void PrintDiagnostics(CXTranslationUnit TU) { 354 int i, n = clang_getNumDiagnostics(TU); 355 for (i = 0; i != n; ++i) { 356 CXDiagnostic Diag = clang_getDiagnostic(TU, i); 357 PrintDiagnostic(Diag); 358 clang_disposeDiagnostic(Diag); 359 } 360} 361 362/******************************************************************************/ 363/* Logic for testing traversal. */ 364/******************************************************************************/ 365 366static const char *FileCheckPrefix = "CHECK"; 367 368static void PrintCursorExtent(CXCursor C) { 369 CXSourceRange extent = clang_getCursorExtent(C); 370 CXFile begin_file, end_file; 371 unsigned begin_line, begin_column, end_line, end_column; 372 373 clang_getInstantiationLocation(clang_getRangeStart(extent), 374 &begin_file, &begin_line, &begin_column, 0); 375 clang_getInstantiationLocation(clang_getRangeEnd(extent), 376 &end_file, &end_line, &end_column, 0); 377 if (!begin_file || !end_file) 378 return; 379 380 printf(" Extent="); 381 PrintExtent(stdout, begin_line, begin_column, end_line, end_column); 382} 383 384/* Data used by all of the visitors. */ 385typedef struct { 386 CXTranslationUnit TU; 387 enum CXCursorKind *Filter; 388} VisitorData; 389 390 391enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor, 392 CXCursor Parent, 393 CXClientData ClientData) { 394 VisitorData *Data = (VisitorData *)ClientData; 395 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) { 396 CXSourceLocation Loc = clang_getCursorLocation(Cursor); 397 unsigned line, column; 398 clang_getInstantiationLocation(Loc, 0, &line, &column, 0); 399 printf("// %s: %s:%d:%d: ", FileCheckPrefix, 400 GetCursorSource(Cursor), line, column); 401 PrintCursor(Cursor); 402 PrintCursorExtent(Cursor); 403 printf("\n"); 404 return CXChildVisit_Recurse; 405 } 406 407 return CXChildVisit_Continue; 408} 409 410static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor, 411 CXCursor Parent, 412 CXClientData ClientData) { 413 const char *startBuf, *endBuf; 414 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn; 415 CXCursor Ref; 416 VisitorData *Data = (VisitorData *)ClientData; 417 418 if (Cursor.kind != CXCursor_FunctionDecl || 419 !clang_isCursorDefinition(Cursor)) 420 return CXChildVisit_Continue; 421 422 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf, 423 &startLine, &startColumn, 424 &endLine, &endColumn); 425 /* Probe the entire body, looking for both decls and refs. */ 426 curLine = startLine; 427 curColumn = startColumn; 428 429 while (startBuf < endBuf) { 430 CXSourceLocation Loc; 431 CXFile file; 432 CXString source; 433 434 if (*startBuf == '\n') { 435 startBuf++; 436 curLine++; 437 curColumn = 1; 438 } else if (*startBuf != '\t') 439 curColumn++; 440 441 Loc = clang_getCursorLocation(Cursor); 442 clang_getInstantiationLocation(Loc, &file, 0, 0, 0); 443 444 source = clang_getFileName(file); 445 if (clang_getCString(source)) { 446 CXSourceLocation RefLoc 447 = clang_getLocation(Data->TU, file, curLine, curColumn); 448 Ref = clang_getCursor(Data->TU, RefLoc); 449 if (Ref.kind == CXCursor_NoDeclFound) { 450 /* Nothing found here; that's fine. */ 451 } else if (Ref.kind != CXCursor_FunctionDecl) { 452 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref), 453 curLine, curColumn); 454 PrintCursor(Ref); 455 printf("\n"); 456 } 457 } 458 clang_disposeString(source); 459 startBuf++; 460 } 461 462 return CXChildVisit_Continue; 463} 464 465/******************************************************************************/ 466/* USR testing. */ 467/******************************************************************************/ 468 469enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent, 470 CXClientData ClientData) { 471 VisitorData *Data = (VisitorData *)ClientData; 472 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) { 473 CXString USR = clang_getCursorUSR(C); 474 const char *cstr = clang_getCString(USR); 475 if (!cstr || cstr[0] == '\0') { 476 clang_disposeString(USR); 477 return CXChildVisit_Recurse; 478 } 479 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr); 480 481 PrintCursorExtent(C); 482 printf("\n"); 483 clang_disposeString(USR); 484 485 return CXChildVisit_Recurse; 486 } 487 488 return CXChildVisit_Continue; 489} 490 491/******************************************************************************/ 492/* Inclusion stack testing. */ 493/******************************************************************************/ 494 495void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack, 496 unsigned includeStackLen, CXClientData data) { 497 498 unsigned i; 499 CXString fname; 500 501 fname = clang_getFileName(includedFile); 502 printf("file: %s\nincluded by:\n", clang_getCString(fname)); 503 clang_disposeString(fname); 504 505 for (i = 0; i < includeStackLen; ++i) { 506 CXFile includingFile; 507 unsigned line, column; 508 clang_getInstantiationLocation(includeStack[i], &includingFile, &line, 509 &column, 0); 510 fname = clang_getFileName(includingFile); 511 printf(" %s:%d:%d\n", clang_getCString(fname), line, column); 512 clang_disposeString(fname); 513 } 514 printf("\n"); 515} 516 517void PrintInclusionStack(CXTranslationUnit TU) { 518 clang_getInclusions(TU, InclusionVisitor, NULL); 519} 520 521/******************************************************************************/ 522/* Linkage testing. */ 523/******************************************************************************/ 524 525static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p, 526 CXClientData d) { 527 const char *linkage = 0; 528 529 if (clang_isInvalid(clang_getCursorKind(cursor))) 530 return CXChildVisit_Recurse; 531 532 switch (clang_getCursorLinkage(cursor)) { 533 case CXLinkage_Invalid: break; 534 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break; 535 case CXLinkage_Internal: linkage = "Internal"; break; 536 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break; 537 case CXLinkage_External: linkage = "External"; break; 538 } 539 540 if (linkage) { 541 PrintCursor(cursor); 542 printf("linkage=%s\n", linkage); 543 } 544 545 return CXChildVisit_Recurse; 546} 547 548/******************************************************************************/ 549/* Typekind testing. */ 550/******************************************************************************/ 551 552static enum CXChildVisitResult PrintTypeKind(CXCursor cursor, CXCursor p, 553 CXClientData d) { 554 555 if (!clang_isInvalid(clang_getCursorKind(cursor))) { 556 CXType T = clang_getCursorType(cursor); 557 CXString S = clang_getTypeKindSpelling(T.kind); 558 PrintCursor(cursor); 559 printf(" typekind=%s", clang_getCString(S)); 560 clang_disposeString(S); 561 /* Print the canonical type if it is different. */ 562 { 563 CXType CT = clang_getCanonicalType(T); 564 if (!clang_equalTypes(T, CT)) { 565 CXString CS = clang_getTypeKindSpelling(CT.kind); 566 printf(" [canonical=%s]", clang_getCString(CS)); 567 clang_disposeString(CS); 568 } 569 } 570 /* Print the return type if it exists. */ 571 { 572 CXType RT = clang_getCursorResultType(cursor); 573 if (RT.kind != CXType_Invalid) { 574 CXString RS = clang_getTypeKindSpelling(RT.kind); 575 printf(" [result=%s]", clang_getCString(RS)); 576 clang_disposeString(RS); 577 } 578 } 579 /* Print if this is a non-POD type. */ 580 printf(" [isPOD=%d]", clang_isPODType(T)); 581 582 printf("\n"); 583 } 584 return CXChildVisit_Recurse; 585} 586 587 588/******************************************************************************/ 589/* Loading ASTs/source. */ 590/******************************************************************************/ 591 592static int perform_test_load(CXIndex Idx, CXTranslationUnit TU, 593 const char *filter, const char *prefix, 594 CXCursorVisitor Visitor, 595 PostVisitTU PV) { 596 597 if (prefix) 598 FileCheckPrefix = prefix; 599 600 if (Visitor) { 601 enum CXCursorKind K = CXCursor_NotImplemented; 602 enum CXCursorKind *ck = &K; 603 VisitorData Data; 604 605 /* Perform some simple filtering. */ 606 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL; 607 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0; 608 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl; 609 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl; 610 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl; 611 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl; 612 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl; 613 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor; 614 else { 615 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter); 616 return 1; 617 } 618 619 Data.TU = TU; 620 Data.Filter = ck; 621 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data); 622 } 623 624 if (PV) 625 PV(TU); 626 627 PrintDiagnostics(TU); 628 clang_disposeTranslationUnit(TU); 629 return 0; 630} 631 632int perform_test_load_tu(const char *file, const char *filter, 633 const char *prefix, CXCursorVisitor Visitor, 634 PostVisitTU PV) { 635 CXIndex Idx; 636 CXTranslationUnit TU; 637 int result; 638 Idx = clang_createIndex(/* excludeDeclsFromPCH */ 639 !strcmp(filter, "local") ? 1 : 0, 640 /* displayDiagnosics=*/1); 641 642 if (!CreateTranslationUnit(Idx, file, &TU)) { 643 clang_disposeIndex(Idx); 644 return 1; 645 } 646 647 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV); 648 clang_disposeIndex(Idx); 649 return result; 650} 651 652int perform_test_load_source(int argc, const char **argv, 653 const char *filter, CXCursorVisitor Visitor, 654 PostVisitTU PV) { 655 const char *UseExternalASTs = 656 getenv("CINDEXTEST_USE_EXTERNAL_AST_GENERATION"); 657 CXIndex Idx; 658 CXTranslationUnit TU; 659 struct CXUnsavedFile *unsaved_files = 0; 660 int num_unsaved_files = 0; 661 int result; 662 663 Idx = clang_createIndex(/* excludeDeclsFromPCH */ 664 !strcmp(filter, "local") ? 1 : 0, 665 /* displayDiagnosics=*/1); 666 667 if (UseExternalASTs && strlen(UseExternalASTs)) 668 clang_setUseExternalASTGeneration(Idx, 1); 669 670 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) { 671 clang_disposeIndex(Idx); 672 return -1; 673 } 674 675 TU = clang_createTranslationUnitFromSourceFile(Idx, 0, 676 argc - num_unsaved_files, 677 argv + num_unsaved_files, 678 num_unsaved_files, 679 unsaved_files); 680 if (!TU) { 681 fprintf(stderr, "Unable to load translation unit!\n"); 682 free_remapped_files(unsaved_files, num_unsaved_files); 683 clang_disposeIndex(Idx); 684 return 1; 685 } 686 687 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV); 688 free_remapped_files(unsaved_files, num_unsaved_files); 689 clang_disposeIndex(Idx); 690 return result; 691} 692 693int perform_test_reparse_source(int argc, const char **argv, int trials, 694 const char *filter, CXCursorVisitor Visitor, 695 PostVisitTU PV) { 696 const char *UseExternalASTs = 697 getenv("CINDEXTEST_USE_EXTERNAL_AST_GENERATION"); 698 CXIndex Idx; 699 CXTranslationUnit TU; 700 struct CXUnsavedFile *unsaved_files = 0; 701 int num_unsaved_files = 0; 702 int result; 703 int trial; 704 705 Idx = clang_createIndex(/* excludeDeclsFromPCH */ 706 !strcmp(filter, "local") ? 1 : 0, 707 /* displayDiagnosics=*/1); 708 709 if (UseExternalASTs && strlen(UseExternalASTs)) 710 clang_setUseExternalASTGeneration(Idx, 1); 711 712 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) { 713 clang_disposeIndex(Idx); 714 return -1; 715 } 716 717 /* Load the initial translation unit -- we do this without honoring remapped 718 * files, so that we have a way to test results after changing the source. */ 719 TU = clang_parseTranslationUnit(Idx, 0, 720 argv + num_unsaved_files, 721 argc - num_unsaved_files, 722 0, 0, getDefaultParsingOptions()); 723 if (!TU) { 724 fprintf(stderr, "Unable to load translation unit!\n"); 725 free_remapped_files(unsaved_files, num_unsaved_files); 726 clang_disposeIndex(Idx); 727 return 1; 728 } 729 730 for (trial = 0; trial < trials; ++trial) { 731 if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files, 732 clang_defaultReparseOptions(TU))) { 733 fprintf(stderr, "Unable to reparse translation unit!\n"); 734 clang_disposeTranslationUnit(TU); 735 free_remapped_files(unsaved_files, num_unsaved_files); 736 clang_disposeIndex(Idx); 737 return -1; 738 } 739 } 740 741 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV); 742 free_remapped_files(unsaved_files, num_unsaved_files); 743 clang_disposeIndex(Idx); 744 return result; 745} 746 747/******************************************************************************/ 748/* Logic for testing clang_getCursor(). */ 749/******************************************************************************/ 750 751static void print_cursor_file_scan(CXCursor cursor, 752 unsigned start_line, unsigned start_col, 753 unsigned end_line, unsigned end_col, 754 const char *prefix) { 755 printf("// %s: ", FileCheckPrefix); 756 if (prefix) 757 printf("-%s", prefix); 758 PrintExtent(stdout, start_line, start_col, end_line, end_col); 759 printf(" "); 760 PrintCursor(cursor); 761 printf("\n"); 762} 763 764static int perform_file_scan(const char *ast_file, const char *source_file, 765 const char *prefix) { 766 CXIndex Idx; 767 CXTranslationUnit TU; 768 FILE *fp; 769 CXCursor prevCursor = clang_getNullCursor(); 770 CXFile file; 771 unsigned line = 1, col = 1; 772 unsigned start_line = 1, start_col = 1; 773 774 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1, 775 /* displayDiagnosics=*/1))) { 776 fprintf(stderr, "Could not create Index\n"); 777 return 1; 778 } 779 780 if (!CreateTranslationUnit(Idx, ast_file, &TU)) 781 return 1; 782 783 if ((fp = fopen(source_file, "r")) == NULL) { 784 fprintf(stderr, "Could not open '%s'\n", source_file); 785 return 1; 786 } 787 788 file = clang_getFile(TU, source_file); 789 for (;;) { 790 CXCursor cursor; 791 int c = fgetc(fp); 792 793 if (c == '\n') { 794 ++line; 795 col = 1; 796 } else 797 ++col; 798 799 /* Check the cursor at this position, and dump the previous one if we have 800 * found something new. 801 */ 802 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col)); 803 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) && 804 prevCursor.kind != CXCursor_InvalidFile) { 805 print_cursor_file_scan(prevCursor, start_line, start_col, 806 line, col, prefix); 807 start_line = line; 808 start_col = col; 809 } 810 if (c == EOF) 811 break; 812 813 prevCursor = cursor; 814 } 815 816 fclose(fp); 817 return 0; 818} 819 820/******************************************************************************/ 821/* Logic for testing clang_codeComplete(). */ 822/******************************************************************************/ 823 824/* Parse file:line:column from the input string. Returns 0 on success, non-zero 825 on failure. If successful, the pointer *filename will contain newly-allocated 826 memory (that will be owned by the caller) to store the file name. */ 827int parse_file_line_column(const char *input, char **filename, unsigned *line, 828 unsigned *column, unsigned *second_line, 829 unsigned *second_column) { 830 /* Find the second colon. */ 831 const char *last_colon = strrchr(input, ':'); 832 unsigned values[4], i; 833 unsigned num_values = (second_line && second_column)? 4 : 2; 834 835 char *endptr = 0; 836 if (!last_colon || last_colon == input) { 837 if (num_values == 4) 838 fprintf(stderr, "could not parse filename:line:column:line:column in " 839 "'%s'\n", input); 840 else 841 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input); 842 return 1; 843 } 844 845 for (i = 0; i != num_values; ++i) { 846 const char *prev_colon; 847 848 /* Parse the next line or column. */ 849 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10); 850 if (*endptr != 0 && *endptr != ':') { 851 fprintf(stderr, "could not parse %s in '%s'\n", 852 (i % 2 ? "column" : "line"), input); 853 return 1; 854 } 855 856 if (i + 1 == num_values) 857 break; 858 859 /* Find the previous colon. */ 860 prev_colon = last_colon - 1; 861 while (prev_colon != input && *prev_colon != ':') 862 --prev_colon; 863 if (prev_colon == input) { 864 fprintf(stderr, "could not parse %s in '%s'\n", 865 (i % 2 == 0? "column" : "line"), input); 866 return 1; 867 } 868 869 last_colon = prev_colon; 870 } 871 872 *line = values[0]; 873 *column = values[1]; 874 875 if (second_line && second_column) { 876 *second_line = values[2]; 877 *second_column = values[3]; 878 } 879 880 /* Copy the file name. */ 881 *filename = (char*)malloc(last_colon - input + 1); 882 memcpy(*filename, input, last_colon - input); 883 (*filename)[last_colon - input] = 0; 884 return 0; 885} 886 887const char * 888clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) { 889 switch (Kind) { 890 case CXCompletionChunk_Optional: return "Optional"; 891 case CXCompletionChunk_TypedText: return "TypedText"; 892 case CXCompletionChunk_Text: return "Text"; 893 case CXCompletionChunk_Placeholder: return "Placeholder"; 894 case CXCompletionChunk_Informative: return "Informative"; 895 case CXCompletionChunk_CurrentParameter: return "CurrentParameter"; 896 case CXCompletionChunk_LeftParen: return "LeftParen"; 897 case CXCompletionChunk_RightParen: return "RightParen"; 898 case CXCompletionChunk_LeftBracket: return "LeftBracket"; 899 case CXCompletionChunk_RightBracket: return "RightBracket"; 900 case CXCompletionChunk_LeftBrace: return "LeftBrace"; 901 case CXCompletionChunk_RightBrace: return "RightBrace"; 902 case CXCompletionChunk_LeftAngle: return "LeftAngle"; 903 case CXCompletionChunk_RightAngle: return "RightAngle"; 904 case CXCompletionChunk_Comma: return "Comma"; 905 case CXCompletionChunk_ResultType: return "ResultType"; 906 case CXCompletionChunk_Colon: return "Colon"; 907 case CXCompletionChunk_SemiColon: return "SemiColon"; 908 case CXCompletionChunk_Equal: return "Equal"; 909 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace"; 910 case CXCompletionChunk_VerticalSpace: return "VerticalSpace"; 911 } 912 913 return "Unknown"; 914} 915 916void print_completion_string(CXCompletionString completion_string, FILE *file) { 917 int I, N; 918 919 N = clang_getNumCompletionChunks(completion_string); 920 for (I = 0; I != N; ++I) { 921 CXString text; 922 const char *cstr; 923 enum CXCompletionChunkKind Kind 924 = clang_getCompletionChunkKind(completion_string, I); 925 926 if (Kind == CXCompletionChunk_Optional) { 927 fprintf(file, "{Optional "); 928 print_completion_string( 929 clang_getCompletionChunkCompletionString(completion_string, I), 930 file); 931 fprintf(file, "}"); 932 continue; 933 } 934 935 text = clang_getCompletionChunkText(completion_string, I); 936 cstr = clang_getCString(text); 937 fprintf(file, "{%s %s}", 938 clang_getCompletionChunkKindSpelling(Kind), 939 cstr ? cstr : ""); 940 clang_disposeString(text); 941 } 942 943} 944 945void print_completion_result(CXCompletionResult *completion_result, 946 CXClientData client_data) { 947 FILE *file = (FILE *)client_data; 948 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind); 949 950 fprintf(file, "%s:", clang_getCString(ks)); 951 clang_disposeString(ks); 952 953 print_completion_string(completion_result->CompletionString, file); 954 fprintf(file, " (%u)", 955 clang_getCompletionPriority(completion_result->CompletionString)); 956 switch (clang_getCompletionAvailability(completion_result->CompletionString)){ 957 case CXAvailability_Available: 958 break; 959 960 case CXAvailability_Deprecated: 961 fprintf(file, " (deprecated)"); 962 break; 963 964 case CXAvailability_NotAvailable: 965 fprintf(file, " (unavailable)"); 966 break; 967 } 968 fprintf(file, "\n"); 969} 970 971int my_stricmp(const char *s1, const char *s2) { 972 while (*s1 && *s2) { 973 int c1 = tolower(*s1), c2 = tolower(*s2); 974 if (c1 < c2) 975 return -1; 976 else if (c1 > c2) 977 return 1; 978 979 ++s1; 980 ++s2; 981 } 982 983 if (*s1) 984 return 1; 985 else if (*s2) 986 return -1; 987 return 0; 988} 989 990int perform_code_completion(int argc, const char **argv, int timing_only) { 991 const char *input = argv[1]; 992 char *filename = 0; 993 unsigned line; 994 unsigned column; 995 CXIndex CIdx; 996 int errorCode; 997 struct CXUnsavedFile *unsaved_files = 0; 998 int num_unsaved_files = 0; 999 CXCodeCompleteResults *results = 0; 1000 CXTranslationUnit TU = 0; 1001 1002 if (timing_only) 1003 input += strlen("-code-completion-timing="); 1004 else 1005 input += strlen("-code-completion-at="); 1006 1007 if ((errorCode = parse_file_line_column(input, &filename, &line, &column, 1008 0, 0))) 1009 return errorCode; 1010 1011 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) 1012 return -1; 1013 1014 CIdx = clang_createIndex(0, 1); 1015 if (getenv("CINDEXTEST_EDITING")) { 1016 unsigned I, Repeats = 5; 1017 TU = clang_parseTranslationUnit(CIdx, 0, 1018 argv + num_unsaved_files + 2, 1019 argc - num_unsaved_files - 2, 1020 0, 0, getDefaultParsingOptions()); 1021 if (!TU) { 1022 fprintf(stderr, "Unable to load translation unit!\n"); 1023 return 1; 1024 } 1025 for (I = 0; I != Repeats; ++I) { 1026 results = clang_codeCompleteAt(TU, filename, line, column, 1027 unsaved_files, num_unsaved_files, 1028 clang_defaultCodeCompleteOptions()); 1029 if (!results) { 1030 fprintf(stderr, "Unable to perform code completion!\n"); 1031 return 1; 1032 } 1033 if (I != Repeats-1) 1034 clang_disposeCodeCompleteResults(results); 1035 } 1036 } else 1037 results = clang_codeComplete(CIdx, 1038 argv[argc - 1], argc - num_unsaved_files - 3, 1039 argv + num_unsaved_files + 2, 1040 num_unsaved_files, unsaved_files, 1041 filename, line, column); 1042 1043 if (results) { 1044 unsigned i, n = results->NumResults; 1045 if (!timing_only) { 1046 /* Sort the code-completion results based on the typed text. */ 1047 clang_sortCodeCompletionResults(results->Results, results->NumResults); 1048 1049 for (i = 0; i != n; ++i) 1050 print_completion_result(results->Results + i, stdout); 1051 } 1052 n = clang_codeCompleteGetNumDiagnostics(results); 1053 for (i = 0; i != n; ++i) { 1054 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i); 1055 PrintDiagnostic(diag); 1056 clang_disposeDiagnostic(diag); 1057 } 1058 clang_disposeCodeCompleteResults(results); 1059 } 1060 clang_disposeTranslationUnit(TU); 1061 clang_disposeIndex(CIdx); 1062 free(filename); 1063 1064 free_remapped_files(unsaved_files, num_unsaved_files); 1065 1066 return 0; 1067} 1068 1069typedef struct { 1070 char *filename; 1071 unsigned line; 1072 unsigned column; 1073} CursorSourceLocation; 1074 1075int inspect_cursor_at(int argc, const char **argv) { 1076 CXIndex CIdx; 1077 int errorCode; 1078 struct CXUnsavedFile *unsaved_files = 0; 1079 int num_unsaved_files = 0; 1080 CXTranslationUnit TU; 1081 CXCursor Cursor; 1082 CursorSourceLocation *Locations = 0; 1083 unsigned NumLocations = 0, Loc; 1084 1085 /* Count the number of locations. */ 1086 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1]) 1087 ++NumLocations; 1088 1089 /* Parse the locations. */ 1090 assert(NumLocations > 0 && "Unable to count locations?"); 1091 Locations = (CursorSourceLocation *)malloc( 1092 NumLocations * sizeof(CursorSourceLocation)); 1093 for (Loc = 0; Loc < NumLocations; ++Loc) { 1094 const char *input = argv[Loc + 1] + strlen("-cursor-at="); 1095 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename, 1096 &Locations[Loc].line, 1097 &Locations[Loc].column, 0, 0))) 1098 return errorCode; 1099 } 1100 1101 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files, 1102 &num_unsaved_files)) 1103 return -1; 1104 1105 CIdx = clang_createIndex(0, 1); 1106 TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1], 1107 argc - num_unsaved_files - 2 - NumLocations, 1108 argv + num_unsaved_files + 1 + NumLocations, 1109 num_unsaved_files, 1110 unsaved_files); 1111 if (!TU) { 1112 fprintf(stderr, "unable to parse input\n"); 1113 return -1; 1114 } 1115 1116 for (Loc = 0; Loc < NumLocations; ++Loc) { 1117 CXFile file = clang_getFile(TU, Locations[Loc].filename); 1118 if (!file) 1119 continue; 1120 1121 Cursor = clang_getCursor(TU, 1122 clang_getLocation(TU, file, Locations[Loc].line, 1123 Locations[Loc].column)); 1124 PrintCursor(Cursor); 1125 printf("\n"); 1126 free(Locations[Loc].filename); 1127 } 1128 1129 PrintDiagnostics(TU); 1130 clang_disposeTranslationUnit(TU); 1131 clang_disposeIndex(CIdx); 1132 free(Locations); 1133 free_remapped_files(unsaved_files, num_unsaved_files); 1134 return 0; 1135} 1136 1137int perform_token_annotation(int argc, const char **argv) { 1138 const char *input = argv[1]; 1139 char *filename = 0; 1140 unsigned line, second_line; 1141 unsigned column, second_column; 1142 CXIndex CIdx; 1143 CXTranslationUnit TU = 0; 1144 int errorCode; 1145 struct CXUnsavedFile *unsaved_files = 0; 1146 int num_unsaved_files = 0; 1147 CXToken *tokens; 1148 unsigned num_tokens; 1149 CXSourceRange range; 1150 CXSourceLocation startLoc, endLoc; 1151 CXFile file = 0; 1152 CXCursor *cursors = 0; 1153 unsigned i; 1154 1155 input += strlen("-test-annotate-tokens="); 1156 if ((errorCode = parse_file_line_column(input, &filename, &line, &column, 1157 &second_line, &second_column))) 1158 return errorCode; 1159 1160 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) 1161 return -1; 1162 1163 CIdx = clang_createIndex(0, 1); 1164 TU = clang_createTranslationUnitFromSourceFile(CIdx, argv[argc - 1], 1165 argc - num_unsaved_files - 3, 1166 argv + num_unsaved_files + 2, 1167 num_unsaved_files, 1168 unsaved_files); 1169 if (!TU) { 1170 fprintf(stderr, "unable to parse input\n"); 1171 clang_disposeIndex(CIdx); 1172 free(filename); 1173 free_remapped_files(unsaved_files, num_unsaved_files); 1174 return -1; 1175 } 1176 errorCode = 0; 1177 1178 file = clang_getFile(TU, filename); 1179 if (!file) { 1180 fprintf(stderr, "file %s is not in this translation unit\n", filename); 1181 errorCode = -1; 1182 goto teardown; 1183 } 1184 1185 startLoc = clang_getLocation(TU, file, line, column); 1186 if (clang_equalLocations(clang_getNullLocation(), startLoc)) { 1187 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line, 1188 column); 1189 errorCode = -1; 1190 goto teardown; 1191 } 1192 1193 endLoc = clang_getLocation(TU, file, second_line, second_column); 1194 if (clang_equalLocations(clang_getNullLocation(), endLoc)) { 1195 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, 1196 second_line, second_column); 1197 errorCode = -1; 1198 goto teardown; 1199 } 1200 1201 range = clang_getRange(startLoc, endLoc); 1202 clang_tokenize(TU, range, &tokens, &num_tokens); 1203 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor)); 1204 clang_annotateTokens(TU, tokens, num_tokens, cursors); 1205 for (i = 0; i != num_tokens; ++i) { 1206 const char *kind = "<unknown>"; 1207 CXString spelling = clang_getTokenSpelling(TU, tokens[i]); 1208 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]); 1209 unsigned start_line, start_column, end_line, end_column; 1210 1211 switch (clang_getTokenKind(tokens[i])) { 1212 case CXToken_Punctuation: kind = "Punctuation"; break; 1213 case CXToken_Keyword: kind = "Keyword"; break; 1214 case CXToken_Identifier: kind = "Identifier"; break; 1215 case CXToken_Literal: kind = "Literal"; break; 1216 case CXToken_Comment: kind = "Comment"; break; 1217 } 1218 clang_getInstantiationLocation(clang_getRangeStart(extent), 1219 0, &start_line, &start_column, 0); 1220 clang_getInstantiationLocation(clang_getRangeEnd(extent), 1221 0, &end_line, &end_column, 0); 1222 printf("%s: \"%s\" ", kind, clang_getCString(spelling)); 1223 PrintExtent(stdout, start_line, start_column, end_line, end_column); 1224 if (!clang_isInvalid(cursors[i].kind)) { 1225 printf(" "); 1226 PrintCursor(cursors[i]); 1227 } 1228 printf("\n"); 1229 } 1230 free(cursors); 1231 1232 teardown: 1233 PrintDiagnostics(TU); 1234 clang_disposeTranslationUnit(TU); 1235 clang_disposeIndex(CIdx); 1236 free(filename); 1237 free_remapped_files(unsaved_files, num_unsaved_files); 1238 return errorCode; 1239} 1240 1241/******************************************************************************/ 1242/* USR printing. */ 1243/******************************************************************************/ 1244 1245static int insufficient_usr(const char *kind, const char *usage) { 1246 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage); 1247 return 1; 1248} 1249 1250static unsigned isUSR(const char *s) { 1251 return s[0] == 'c' && s[1] == ':'; 1252} 1253 1254static int not_usr(const char *s, const char *arg) { 1255 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg); 1256 return 1; 1257} 1258 1259static void print_usr(CXString usr) { 1260 const char *s = clang_getCString(usr); 1261 printf("%s\n", s); 1262 clang_disposeString(usr); 1263} 1264 1265static void display_usrs() { 1266 fprintf(stderr, "-print-usrs options:\n" 1267 " ObjCCategory <class name> <category name>\n" 1268 " ObjCClass <class name>\n" 1269 " ObjCIvar <ivar name> <class USR>\n" 1270 " ObjCMethod <selector> [0=class method|1=instance method] " 1271 "<class USR>\n" 1272 " ObjCProperty <property name> <class USR>\n" 1273 " ObjCProtocol <protocol name>\n"); 1274} 1275 1276int print_usrs(const char **I, const char **E) { 1277 while (I != E) { 1278 const char *kind = *I; 1279 unsigned len = strlen(kind); 1280 switch (len) { 1281 case 8: 1282 if (memcmp(kind, "ObjCIvar", 8) == 0) { 1283 if (I + 2 >= E) 1284 return insufficient_usr(kind, "<ivar name> <class USR>"); 1285 if (!isUSR(I[2])) 1286 return not_usr("<class USR>", I[2]); 1287 else { 1288 CXString x; 1289 x.Spelling = I[2]; 1290 x.MustFreeString = 0; 1291 print_usr(clang_constructUSR_ObjCIvar(I[1], x)); 1292 } 1293 1294 I += 3; 1295 continue; 1296 } 1297 break; 1298 case 9: 1299 if (memcmp(kind, "ObjCClass", 9) == 0) { 1300 if (I + 1 >= E) 1301 return insufficient_usr(kind, "<class name>"); 1302 print_usr(clang_constructUSR_ObjCClass(I[1])); 1303 I += 2; 1304 continue; 1305 } 1306 break; 1307 case 10: 1308 if (memcmp(kind, "ObjCMethod", 10) == 0) { 1309 if (I + 3 >= E) 1310 return insufficient_usr(kind, "<method selector> " 1311 "[0=class method|1=instance method] <class USR>"); 1312 if (!isUSR(I[3])) 1313 return not_usr("<class USR>", I[3]); 1314 else { 1315 CXString x; 1316 x.Spelling = I[3]; 1317 x.MustFreeString = 0; 1318 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x)); 1319 } 1320 I += 4; 1321 continue; 1322 } 1323 break; 1324 case 12: 1325 if (memcmp(kind, "ObjCCategory", 12) == 0) { 1326 if (I + 2 >= E) 1327 return insufficient_usr(kind, "<class name> <category name>"); 1328 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2])); 1329 I += 3; 1330 continue; 1331 } 1332 if (memcmp(kind, "ObjCProtocol", 12) == 0) { 1333 if (I + 1 >= E) 1334 return insufficient_usr(kind, "<protocol name>"); 1335 print_usr(clang_constructUSR_ObjCProtocol(I[1])); 1336 I += 2; 1337 continue; 1338 } 1339 if (memcmp(kind, "ObjCProperty", 12) == 0) { 1340 if (I + 2 >= E) 1341 return insufficient_usr(kind, "<property name> <class USR>"); 1342 if (!isUSR(I[2])) 1343 return not_usr("<class USR>", I[2]); 1344 else { 1345 CXString x; 1346 x.Spelling = I[2]; 1347 x.MustFreeString = 0; 1348 print_usr(clang_constructUSR_ObjCProperty(I[1], x)); 1349 } 1350 I += 3; 1351 continue; 1352 } 1353 break; 1354 default: 1355 break; 1356 } 1357 break; 1358 } 1359 1360 if (I != E) { 1361 fprintf(stderr, "Invalid USR kind: %s\n", *I); 1362 display_usrs(); 1363 return 1; 1364 } 1365 return 0; 1366} 1367 1368int print_usrs_file(const char *file_name) { 1369 char line[2048]; 1370 const char *args[128]; 1371 unsigned numChars = 0; 1372 1373 FILE *fp = fopen(file_name, "r"); 1374 if (!fp) { 1375 fprintf(stderr, "error: cannot open '%s'\n", file_name); 1376 return 1; 1377 } 1378 1379 /* This code is not really all that safe, but it works fine for testing. */ 1380 while (!feof(fp)) { 1381 char c = fgetc(fp); 1382 if (c == '\n') { 1383 unsigned i = 0; 1384 const char *s = 0; 1385 1386 if (numChars == 0) 1387 continue; 1388 1389 line[numChars] = '\0'; 1390 numChars = 0; 1391 1392 if (line[0] == '/' && line[1] == '/') 1393 continue; 1394 1395 s = strtok(line, " "); 1396 while (s) { 1397 args[i] = s; 1398 ++i; 1399 s = strtok(0, " "); 1400 } 1401 if (print_usrs(&args[0], &args[i])) 1402 return 1; 1403 } 1404 else 1405 line[numChars++] = c; 1406 } 1407 1408 fclose(fp); 1409 return 0; 1410} 1411 1412/******************************************************************************/ 1413/* Command line processing. */ 1414/******************************************************************************/ 1415int write_pch_file(const char *filename, int argc, const char *argv[]) { 1416 CXIndex Idx; 1417 CXTranslationUnit TU; 1418 struct CXUnsavedFile *unsaved_files = 0; 1419 int num_unsaved_files = 0; 1420 1421 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnosics=*/1); 1422 1423 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) { 1424 clang_disposeIndex(Idx); 1425 return -1; 1426 } 1427 1428 TU = clang_parseTranslationUnit(Idx, 0, 1429 argv + num_unsaved_files, 1430 argc - num_unsaved_files, 1431 unsaved_files, 1432 num_unsaved_files, 1433 CXTranslationUnit_Incomplete); 1434 if (!TU) { 1435 fprintf(stderr, "Unable to load translation unit!\n"); 1436 free_remapped_files(unsaved_files, num_unsaved_files); 1437 clang_disposeIndex(Idx); 1438 return 1; 1439 } 1440 1441 if (clang_saveTranslationUnit(TU, filename, clang_defaultSaveOptions(TU))) 1442 fprintf(stderr, "Unable to write PCH file %s\n", filename); 1443 clang_disposeTranslationUnit(TU); 1444 free_remapped_files(unsaved_files, num_unsaved_files); 1445 clang_disposeIndex(Idx); 1446 return 0; 1447} 1448 1449/******************************************************************************/ 1450/* Command line processing. */ 1451/******************************************************************************/ 1452 1453static CXCursorVisitor GetVisitor(const char *s) { 1454 if (s[0] == '\0') 1455 return FilteredPrintingVisitor; 1456 if (strcmp(s, "-usrs") == 0) 1457 return USRVisitor; 1458 return NULL; 1459} 1460 1461static void print_usage(void) { 1462 fprintf(stderr, 1463 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n" 1464 " c-index-test -code-completion-timing=<site> <compiler arguments>\n" 1465 " c-index-test -cursor-at=<site> <compiler arguments>\n" 1466 " c-index-test -test-file-scan <AST file> <source file> " 1467 "[FileCheck prefix]\n" 1468 " c-index-test -test-load-tu <AST file> <symbol filter> " 1469 "[FileCheck prefix]\n" 1470 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> " 1471 "[FileCheck prefix]\n" 1472 " c-index-test -test-load-source <symbol filter> {<args>}*\n"); 1473 fprintf(stderr, 1474 " c-index-test -test-load-source-reparse <trials> <symbol filter> " 1475 " {<args>}*\n" 1476 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n" 1477 " c-index-test -test-annotate-tokens=<range> {<args>}*\n" 1478 " c-index-test -test-inclusion-stack-source {<args>}*\n" 1479 " c-index-test -test-inclusion-stack-tu <AST file>\n" 1480 " c-index-test -test-print-linkage-source {<args>}*\n" 1481 " c-index-test -test-print-typekind {<args>}*\n" 1482 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"); 1483 fprintf(stderr, 1484 " c-index-test -print-usr-file <file>\n" 1485 " c-index-test -write-pch <file> <compiler arguments>\n\n"); 1486 fprintf(stderr, 1487 " <symbol filter> values:\n%s", 1488 " all - load all symbols, including those from PCH\n" 1489 " local - load all symbols except those in PCH\n" 1490 " category - only load ObjC categories (non-PCH)\n" 1491 " interface - only load ObjC interfaces (non-PCH)\n" 1492 " protocol - only load ObjC protocols (non-PCH)\n" 1493 " function - only load functions (non-PCH)\n" 1494 " typedef - only load typdefs (non-PCH)\n" 1495 " scan-function - scan function bodies (non-PCH)\n\n"); 1496} 1497 1498/***/ 1499 1500int cindextest_main(int argc, const char **argv) { 1501 clang_enableStackTraces(); 1502 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1]) 1503 return perform_code_completion(argc, argv, 0); 1504 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1]) 1505 return perform_code_completion(argc, argv, 1); 1506 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1]) 1507 return inspect_cursor_at(argc, argv); 1508 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) { 1509 CXCursorVisitor I = GetVisitor(argv[1] + 13); 1510 if (I) 1511 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I, 1512 NULL); 1513 } 1514 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){ 1515 CXCursorVisitor I = GetVisitor(argv[1] + 25); 1516 if (I) { 1517 int trials = atoi(argv[2]); 1518 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I, 1519 NULL); 1520 } 1521 } 1522 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) { 1523 CXCursorVisitor I = GetVisitor(argv[1] + 17); 1524 if (I) 1525 return perform_test_load_source(argc - 3, argv + 3, argv[2], I, NULL); 1526 } 1527 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0) 1528 return perform_file_scan(argv[2], argv[3], 1529 argc >= 5 ? argv[4] : 0); 1530 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1]) 1531 return perform_token_annotation(argc, argv); 1532 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0) 1533 return perform_test_load_source(argc - 2, argv + 2, "all", NULL, 1534 PrintInclusionStack); 1535 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0) 1536 return perform_test_load_tu(argv[2], "all", NULL, NULL, 1537 PrintInclusionStack); 1538 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0) 1539 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage, 1540 NULL); 1541 else if (argc > 2 && strcmp(argv[1], "-test-print-typekind") == 0) 1542 return perform_test_load_source(argc - 2, argv + 2, "all", 1543 PrintTypeKind, 0); 1544 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) { 1545 if (argc > 2) 1546 return print_usrs(argv + 2, argv + argc); 1547 else { 1548 display_usrs(); 1549 return 1; 1550 } 1551 } 1552 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0) 1553 return print_usrs_file(argv[2]); 1554 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0) 1555 return write_pch_file(argv[2], argc - 3, argv + 3); 1556 1557 print_usage(); 1558 return 1; 1559} 1560 1561/***/ 1562 1563/* We intentionally run in a separate thread to ensure we at least minimal 1564 * testing of a multithreaded environment (for example, having a reduced stack 1565 * size). */ 1566 1567#include "llvm/Config/config.h" 1568#ifdef HAVE_PTHREAD_H 1569 1570#include <pthread.h> 1571 1572typedef struct thread_info { 1573 int argc; 1574 const char **argv; 1575 int result; 1576} thread_info; 1577void *thread_runner(void *client_data_v) { 1578 thread_info *client_data = client_data_v; 1579 client_data->result = cindextest_main(client_data->argc, client_data->argv); 1580 return 0; 1581} 1582 1583int main(int argc, const char **argv) { 1584 thread_info client_data; 1585 pthread_t thread; 1586 int res; 1587 1588 client_data.argc = argc; 1589 client_data.argv = argv; 1590 res = pthread_create(&thread, 0, thread_runner, &client_data); 1591 if (res != 0) { 1592 perror("thread creation failed"); 1593 return 1; 1594 } 1595 1596 res = pthread_join(thread, 0); 1597 if (res != 0) { 1598 perror("thread join failed"); 1599 return 1; 1600 } 1601 1602 return client_data.result; 1603} 1604 1605#else 1606 1607int main(int argc, const char **argv) { 1608 return cindextest_main(argc, argv); 1609} 1610 1611#endif 1612