3 #include "clang-c/Index.h"
4 #include "clang-c/CXCompilationDatabase.h"
5 #include "llvm/Config/config.h"
12 #ifdef CLANG_HAVE_LIBXML
13 #include <libxml/parser.h>
14 #include <libxml/relaxng.h>
15 #include <libxml/xmlerror.h>
24 /******************************************************************************/
25 /* Utility functions. */
26 /******************************************************************************/
29 char *basename(const char* path)
31 char* base1 = (char*)strrchr(path, '/');
32 char* base2 = (char*)strrchr(path, '\\');
34 return((base1 > base2) ? base1 + 1 : base2 + 1);
42 char *dirname(char* path)
44 char* base1 = (char*)strrchr(path, '/');
45 char* base2 = (char*)strrchr(path, '\\');
59 extern char *basename(const char *);
60 extern char *dirname(char *);
63 /** \brief Return the default parsing options. */
64 static unsigned getDefaultParsingOptions() {
65 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
67 if (getenv("CINDEXTEST_EDITING"))
68 options |= clang_defaultEditingTranslationUnitOptions();
69 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
70 options |= CXTranslationUnit_CacheCompletionResults;
71 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
72 options &= ~CXTranslationUnit_CacheCompletionResults;
73 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
74 options |= CXTranslationUnit_SkipFunctionBodies;
75 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
76 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
81 static int checkForErrors(CXTranslationUnit TU);
83 static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
84 unsigned end_line, unsigned end_column) {
85 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
86 end_line, end_column);
89 static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
90 CXTranslationUnit *TU) {
92 *TU = clang_createTranslationUnit(Idx, file);
94 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
100 void free_remapped_files(struct CXUnsavedFile *unsaved_files,
101 int num_unsaved_files) {
103 for (i = 0; i != num_unsaved_files; ++i) {
104 free((char *)unsaved_files[i].Filename);
105 free((char *)unsaved_files[i].Contents);
110 int parse_remapped_files(int argc, const char **argv, int start_arg,
111 struct CXUnsavedFile **unsaved_files,
112 int *num_unsaved_files) {
115 int prefix_len = strlen("-remap-file=");
117 *num_unsaved_files = 0;
119 /* Count the number of remapped files. */
120 for (arg = start_arg; arg < argc; ++arg) {
121 if (strncmp(argv[arg], "-remap-file=", prefix_len))
124 ++*num_unsaved_files;
127 if (*num_unsaved_files == 0)
131 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
133 for (arg = start_arg, i = 0; i != *num_unsaved_files; ++i, ++arg) {
134 struct CXUnsavedFile *unsaved = *unsaved_files + i;
135 const char *arg_string = argv[arg] + prefix_len;
140 const char *semi = strchr(arg_string, ';');
143 "error: -remap-file=from;to argument is missing semicolon\n");
144 free_remapped_files(*unsaved_files, i);
146 *num_unsaved_files = 0;
150 /* Open the file that we're remapping to. */
151 to_file = fopen(semi + 1, "rb");
153 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
155 free_remapped_files(*unsaved_files, i);
157 *num_unsaved_files = 0;
161 /* Determine the length of the file we're remapping to. */
162 fseek(to_file, 0, SEEK_END);
163 unsaved->Length = ftell(to_file);
164 fseek(to_file, 0, SEEK_SET);
166 /* Read the contents of the file we're remapping to. */
167 contents = (char *)malloc(unsaved->Length + 1);
168 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
169 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
170 (feof(to_file) ? "EOF" : "error"), semi + 1);
172 free_remapped_files(*unsaved_files, i);
175 *num_unsaved_files = 0;
178 contents[unsaved->Length] = 0;
179 unsaved->Contents = contents;
181 /* Close the file. */
184 /* Copy the file name that we're remapping from. */
185 filename_len = semi - arg_string;
186 filename = (char *)malloc(filename_len + 1);
187 memcpy(filename, arg_string, filename_len);
188 filename[filename_len] = 0;
189 unsaved->Filename = filename;
195 static const char *parse_comments_schema(int argc, const char **argv) {
196 const char *CommentsSchemaArg = "-comments-xml-schema=";
197 const char *CommentSchemaFile = NULL;
200 return CommentSchemaFile;
202 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
203 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
205 return CommentSchemaFile;
208 /******************************************************************************/
209 /* Pretty-printing. */
210 /******************************************************************************/
212 static const char *FileCheckPrefix = "CHECK";
214 static void PrintCString(const char *CStr) {
215 if (CStr != NULL && CStr[0] != '\0') {
216 for ( ; *CStr; ++CStr) {
217 const char C = *CStr;
219 case '\n': printf("\\n"); break;
220 case '\r': printf("\\r"); break;
221 case '\t': printf("\\t"); break;
222 case '\v': printf("\\v"); break;
223 case '\f': printf("\\f"); break;
224 default: putchar(C); break;
230 static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
231 printf(" %s=[", Prefix);
236 static void PrintCXStringAndDispose(CXString Str) {
237 PrintCString(clang_getCString(Str));
238 clang_disposeString(Str);
241 static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
242 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
245 static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
247 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
248 clang_disposeString(Str);
251 static void PrintRange(CXSourceRange R, const char *str) {
252 CXFile begin_file, end_file;
253 unsigned begin_line, begin_column, end_line, end_column;
255 clang_getSpellingLocation(clang_getRangeStart(R),
256 &begin_file, &begin_line, &begin_column, 0);
257 clang_getSpellingLocation(clang_getRangeEnd(R),
258 &end_file, &end_line, &end_column, 0);
259 if (!begin_file || !end_file)
264 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
267 int want_display_name = 0;
269 static void printVersion(const char *Prefix, CXVersion Version) {
270 if (Version.Major < 0)
272 printf("%s%d", Prefix, Version.Major);
274 if (Version.Minor < 0)
276 printf(".%d", Version.Minor);
278 if (Version.Subminor < 0)
280 printf(".%d", Version.Subminor);
283 struct CommentASTDumpingContext {
287 static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
291 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
294 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
300 printf("CXComment_Null");
303 printf("CXComment_Text");
304 PrintCXStringWithPrefixAndDispose("Text",
305 clang_TextComment_getText(Comment));
306 if (clang_Comment_isWhitespace(Comment))
307 printf(" IsWhitespace");
308 if (clang_InlineContentComment_hasTrailingNewline(Comment))
309 printf(" HasTrailingNewline");
311 case CXComment_InlineCommand:
312 printf("CXComment_InlineCommand");
313 PrintCXStringWithPrefixAndDispose(
315 clang_InlineCommandComment_getCommandName(Comment));
316 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
317 case CXCommentInlineCommandRenderKind_Normal:
318 printf(" RenderNormal");
320 case CXCommentInlineCommandRenderKind_Bold:
321 printf(" RenderBold");
323 case CXCommentInlineCommandRenderKind_Monospaced:
324 printf(" RenderMonospaced");
326 case CXCommentInlineCommandRenderKind_Emphasized:
327 printf(" RenderEmphasized");
330 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
332 printf(" Arg[%u]=", i);
333 PrintCXStringAndDispose(
334 clang_InlineCommandComment_getArgText(Comment, i));
336 if (clang_InlineContentComment_hasTrailingNewline(Comment))
337 printf(" HasTrailingNewline");
339 case CXComment_HTMLStartTag: {
341 printf("CXComment_HTMLStartTag");
342 PrintCXStringWithPrefixAndDispose(
344 clang_HTMLTagComment_getTagName(Comment));
345 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
348 for (i = 0; i != NumAttrs; ++i) {
350 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
352 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
355 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
356 printf(" SelfClosing");
357 if (clang_InlineContentComment_hasTrailingNewline(Comment))
358 printf(" HasTrailingNewline");
361 case CXComment_HTMLEndTag:
362 printf("CXComment_HTMLEndTag");
363 PrintCXStringWithPrefixAndDispose(
365 clang_HTMLTagComment_getTagName(Comment));
366 if (clang_InlineContentComment_hasTrailingNewline(Comment))
367 printf(" HasTrailingNewline");
369 case CXComment_Paragraph:
370 printf("CXComment_Paragraph");
371 if (clang_Comment_isWhitespace(Comment))
372 printf(" IsWhitespace");
374 case CXComment_BlockCommand:
375 printf("CXComment_BlockCommand");
376 PrintCXStringWithPrefixAndDispose(
378 clang_BlockCommandComment_getCommandName(Comment));
379 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
381 printf(" Arg[%u]=", i);
382 PrintCXStringAndDispose(
383 clang_BlockCommandComment_getArgText(Comment, i));
386 case CXComment_ParamCommand:
387 printf("CXComment_ParamCommand");
388 switch (clang_ParamCommandComment_getDirection(Comment)) {
389 case CXCommentParamPassDirection_In:
392 case CXCommentParamPassDirection_Out:
395 case CXCommentParamPassDirection_InOut:
399 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
400 printf(" explicitly");
402 printf(" implicitly");
403 PrintCXStringWithPrefixAndDispose(
405 clang_ParamCommandComment_getParamName(Comment));
406 if (clang_ParamCommandComment_isParamIndexValid(Comment))
407 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
409 printf(" ParamIndex=Invalid");
411 case CXComment_TParamCommand:
412 printf("CXComment_TParamCommand");
413 PrintCXStringWithPrefixAndDispose(
415 clang_TParamCommandComment_getParamName(Comment));
416 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
417 printf(" ParamPosition={");
418 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
420 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
426 printf(" ParamPosition=Invalid");
428 case CXComment_VerbatimBlockCommand:
429 printf("CXComment_VerbatimBlockCommand");
430 PrintCXStringWithPrefixAndDispose(
432 clang_BlockCommandComment_getCommandName(Comment));
434 case CXComment_VerbatimBlockLine:
435 printf("CXComment_VerbatimBlockLine");
436 PrintCXStringWithPrefixAndDispose(
438 clang_VerbatimBlockLineComment_getText(Comment));
440 case CXComment_VerbatimLine:
441 printf("CXComment_VerbatimLine");
442 PrintCXStringWithPrefixAndDispose(
444 clang_VerbatimLineComment_getText(Comment));
446 case CXComment_FullComment:
447 printf("CXComment_FullComment");
450 if (Kind != CXComment_Null) {
451 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
453 for (i = 0; i != NumChildren; ++i) {
454 printf("\n// %s: ", FileCheckPrefix);
455 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
462 static void DumpCXComment(CXComment Comment) {
463 struct CommentASTDumpingContext Ctx;
465 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
466 DumpCXCommentInternal(&Ctx, Comment);
471 const char *CommentSchemaFile;
472 #ifdef CLANG_HAVE_LIBXML
473 xmlRelaxNGParserCtxtPtr RNGParser;
474 xmlRelaxNGPtr Schema;
476 } CommentXMLValidationData;
478 static void ValidateCommentXML(const char *Str,
479 CommentXMLValidationData *ValidationData) {
480 #ifdef CLANG_HAVE_LIBXML
482 xmlRelaxNGValidCtxtPtr ValidationCtxt;
485 if (!ValidationData || !ValidationData->CommentSchemaFile)
488 if (!ValidationData->RNGParser) {
489 ValidationData->RNGParser =
490 xmlRelaxNGNewParserCtxt(ValidationData->CommentSchemaFile);
491 ValidationData->Schema = xmlRelaxNGParse(ValidationData->RNGParser);
493 if (!ValidationData->RNGParser) {
494 printf(" libXMLError");
498 Doc = xmlParseDoc((const xmlChar *) Str);
501 xmlErrorPtr Error = xmlGetLastError();
502 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
506 ValidationCtxt = xmlRelaxNGNewValidCtxt(ValidationData->Schema);
507 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
509 printf(" CommentXMLValid");
510 else if (status > 0) {
511 xmlErrorPtr Error = xmlGetLastError();
512 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
514 printf(" libXMLError");
516 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
521 static void PrintCursorComments(CXCursor Cursor,
522 CommentXMLValidationData *ValidationData) {
525 const char *RawCommentCString;
526 CXString BriefComment;
527 const char *BriefCommentCString;
529 RawComment = clang_Cursor_getRawCommentText(Cursor);
530 RawCommentCString = clang_getCString(RawComment);
531 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
532 PrintCStringWithPrefix("RawComment", RawCommentCString);
533 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
535 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
536 BriefCommentCString = clang_getCString(BriefComment);
537 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
538 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
539 clang_disposeString(BriefComment);
541 clang_disposeString(RawComment);
545 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
546 if (clang_Comment_getKind(Comment) != CXComment_Null) {
547 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
548 clang_FullComment_getAsHTML(Comment));
551 XML = clang_FullComment_getAsXML(Comment);
552 PrintCXStringWithPrefix("FullCommentAsXML", XML);
553 ValidateCommentXML(clang_getCString(XML), ValidationData);
554 clang_disposeString(XML);
557 DumpCXComment(Comment);
567 static int lineCol_cmp(const void *p1, const void *p2) {
568 const LineCol *lhs = p1;
569 const LineCol *rhs = p2;
570 if (lhs->line != rhs->line)
571 return (int)lhs->line - (int)rhs->line;
572 return (int)lhs->col - (int)rhs->col;
575 static void PrintCursor(CXCursor Cursor,
576 CommentXMLValidationData *ValidationData) {
577 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
578 if (clang_isInvalid(Cursor.kind)) {
579 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
580 printf("Invalid Cursor => %s", clang_getCString(ks));
581 clang_disposeString(ks);
586 unsigned line, column;
587 CXCursor SpecializationOf;
588 CXCursor *overridden;
589 unsigned num_overridden;
590 unsigned RefNameRangeNr;
591 CXSourceRange CursorExtent;
592 CXSourceRange RefNameRange;
593 int AlwaysUnavailable;
594 int AlwaysDeprecated;
595 CXString UnavailableMessage;
596 CXString DeprecatedMessage;
597 CXPlatformAvailability PlatformAvailability[2];
598 int NumPlatformAvailability;
601 ks = clang_getCursorKindSpelling(Cursor.kind);
602 string = want_display_name? clang_getCursorDisplayName(Cursor)
603 : clang_getCursorSpelling(Cursor);
604 printf("%s=%s", clang_getCString(ks),
605 clang_getCString(string));
606 clang_disposeString(ks);
607 clang_disposeString(string);
609 Referenced = clang_getCursorReferenced(Cursor);
610 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
611 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
612 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
614 for (I = 0; I != N; ++I) {
615 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
616 CXSourceLocation Loc;
620 Loc = clang_getCursorLocation(Ovl);
621 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
622 printf("%d:%d", line, column);
626 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
627 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
628 printf(":%d:%d", line, column);
632 if (clang_isCursorDefinition(Cursor))
633 printf(" (Definition)");
635 switch (clang_getCursorAvailability(Cursor)) {
636 case CXAvailability_Available:
639 case CXAvailability_Deprecated:
640 printf(" (deprecated)");
643 case CXAvailability_NotAvailable:
644 printf(" (unavailable)");
647 case CXAvailability_NotAccessible:
648 printf(" (inaccessible)");
652 NumPlatformAvailability
653 = clang_getCursorPlatformAvailability(Cursor,
658 PlatformAvailability, 2);
659 if (AlwaysUnavailable) {
660 printf(" (always unavailable: \"%s\")",
661 clang_getCString(UnavailableMessage));
662 } else if (AlwaysDeprecated) {
663 printf(" (always deprecated: \"%s\")",
664 clang_getCString(DeprecatedMessage));
666 for (I = 0; I != NumPlatformAvailability; ++I) {
670 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
671 if (PlatformAvailability[I].Unavailable)
672 printf(", unavailable");
674 printVersion(", introduced=", PlatformAvailability[I].Introduced);
675 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
676 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
678 if (clang_getCString(PlatformAvailability[I].Message)[0])
679 printf(", message=\"%s\"",
680 clang_getCString(PlatformAvailability[I].Message));
684 for (I = 0; I != NumPlatformAvailability; ++I) {
687 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
690 clang_disposeString(DeprecatedMessage);
691 clang_disposeString(UnavailableMessage);
693 if (clang_CXXMethod_isStatic(Cursor))
695 if (clang_CXXMethod_isVirtual(Cursor))
696 printf(" (virtual)");
698 if (clang_Cursor_isVariadic(Cursor))
699 printf(" (variadic)");
701 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
703 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
704 CXString S = clang_getTypeKindSpelling(T.kind);
705 printf(" [IBOutletCollection=%s]", clang_getCString(S));
706 clang_disposeString(S);
709 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
710 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
711 unsigned isVirtual = clang_isVirtualBase(Cursor);
712 const char *accessStr = 0;
715 case CX_CXXInvalidAccessSpecifier:
716 accessStr = "invalid"; break;
718 accessStr = "public"; break;
719 case CX_CXXProtected:
720 accessStr = "protected"; break;
722 accessStr = "private"; break;
725 printf(" [access=%s isVirtual=%s]", accessStr,
726 isVirtual ? "true" : "false");
729 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
730 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
731 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
732 CXString Name = clang_getCursorSpelling(SpecializationOf);
733 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
734 printf(" [Specialization of %s:%d:%d]",
735 clang_getCString(Name), line, column);
736 clang_disposeString(Name);
739 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
740 if (num_overridden) {
742 LineCol lineCols[50];
743 assert(num_overridden <= 50);
744 printf(" [Overrides ");
745 for (I = 0; I != num_overridden; ++I) {
746 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
747 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
748 lineCols[I].line = line;
749 lineCols[I].col = column;
751 /* Make the order of the override list deterministic. */
752 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
753 for (I = 0; I != num_overridden; ++I) {
756 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
759 clang_disposeOverriddenCursors(overridden);
762 if (Cursor.kind == CXCursor_InclusionDirective) {
763 CXFile File = clang_getIncludedFile(Cursor);
764 CXString Included = clang_getFileName(File);
765 printf(" (%s)", clang_getCString(Included));
766 clang_disposeString(Included);
768 if (clang_isFileMultipleIncludeGuarded(TU, File))
769 printf(" [multi-include guarded]");
772 CursorExtent = clang_getCursorExtent(Cursor);
773 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
774 CXNameRange_WantQualifier
775 | CXNameRange_WantSinglePiece
776 | CXNameRange_WantTemplateArgs,
778 if (!clang_equalRanges(CursorExtent, RefNameRange))
779 PrintRange(RefNameRange, "SingleRefName");
781 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
782 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
783 CXNameRange_WantQualifier
784 | CXNameRange_WantTemplateArgs,
786 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
788 if (!clang_equalRanges(CursorExtent, RefNameRange))
789 PrintRange(RefNameRange, "RefName");
792 PrintCursorComments(Cursor, ValidationData);
795 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
796 if (PropAttrs != CXObjCPropertyAttr_noattr) {
798 #define PRINT_PROP_ATTR(A) \
799 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
800 PRINT_PROP_ATTR(readonly);
801 PRINT_PROP_ATTR(getter);
802 PRINT_PROP_ATTR(assign);
803 PRINT_PROP_ATTR(readwrite);
804 PRINT_PROP_ATTR(retain);
805 PRINT_PROP_ATTR(copy);
806 PRINT_PROP_ATTR(nonatomic);
807 PRINT_PROP_ATTR(setter);
808 PRINT_PROP_ATTR(atomic);
809 PRINT_PROP_ATTR(weak);
810 PRINT_PROP_ATTR(strong);
811 PRINT_PROP_ATTR(unsafe_unretained);
817 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
818 if (QT != CXObjCDeclQualifier_None) {
820 #define PRINT_OBJC_QUAL(A) \
821 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
823 PRINT_OBJC_QUAL(Inout);
824 PRINT_OBJC_QUAL(Out);
825 PRINT_OBJC_QUAL(Bycopy);
826 PRINT_OBJC_QUAL(Byref);
827 PRINT_OBJC_QUAL(Oneway);
834 static const char* GetCursorSource(CXCursor Cursor) {
835 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
838 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
839 source = clang_getFileName(file);
840 if (!clang_getCString(source)) {
841 clang_disposeString(source);
842 return "<invalid loc>";
845 const char *b = basename(clang_getCString(source));
846 clang_disposeString(source);
851 /******************************************************************************/
853 /******************************************************************************/
855 typedef void (*PostVisitTU)(CXTranslationUnit);
857 void PrintDiagnostic(CXDiagnostic Diagnostic) {
861 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
862 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
863 | CXDiagnostic_DisplayOption;
864 unsigned i, num_fixits;
866 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
869 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
870 fprintf(stderr, "%s\n", clang_getCString(Msg));
871 clang_disposeString(Msg);
873 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
878 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
879 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
880 for (i = 0; i != num_fixits; ++i) {
882 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
883 CXSourceLocation start = clang_getRangeStart(range);
884 CXSourceLocation end = clang_getRangeEnd(range);
885 unsigned start_line, start_column, end_line, end_column;
886 CXFile start_file, end_file;
887 clang_getSpellingLocation(start, &start_file, &start_line,
889 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
890 if (clang_equalLocations(start, end)) {
892 if (start_file == file)
893 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
894 clang_getCString(insertion_text), start_line, start_column);
895 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
897 if (start_file == file && end_file == file) {
898 fprintf(out, "FIX-IT: Remove ");
899 PrintExtent(out, start_line, start_column, end_line, end_column);
904 if (start_file == end_file) {
905 fprintf(out, "FIX-IT: Replace ");
906 PrintExtent(out, start_line, start_column, end_line, end_column);
907 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
911 clang_disposeString(insertion_text);
915 void PrintDiagnosticSet(CXDiagnosticSet Set) {
916 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
917 for ( ; i != n ; ++i) {
918 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
919 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
920 PrintDiagnostic(Diag);
922 PrintDiagnosticSet(ChildDiags);
926 void PrintDiagnostics(CXTranslationUnit TU) {
927 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
928 PrintDiagnosticSet(TUSet);
929 clang_disposeDiagnosticSet(TUSet);
932 void PrintMemoryUsage(CXTranslationUnit TU) {
933 unsigned long total = 0;
935 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
936 fprintf(stderr, "Memory usage:\n");
937 for (i = 0 ; i != usage.numEntries; ++i) {
938 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
939 unsigned long amount = usage.entries[i].amount;
941 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
942 ((double) amount)/(1024*1024));
944 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
945 ((double) total)/(1024*1024));
946 clang_disposeCXTUResourceUsage(usage);
949 /******************************************************************************/
950 /* Logic for testing traversal. */
951 /******************************************************************************/
953 static void PrintCursorExtent(CXCursor C) {
954 CXSourceRange extent = clang_getCursorExtent(C);
955 PrintRange(extent, "Extent");
958 /* Data used by the visitors. */
960 CXTranslationUnit TU;
961 enum CXCursorKind *Filter;
962 CommentXMLValidationData ValidationData;
966 enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
968 CXClientData ClientData) {
969 VisitorData *Data = (VisitorData *)ClientData;
970 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
971 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
972 unsigned line, column;
973 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
974 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
975 GetCursorSource(Cursor), line, column);
976 PrintCursor(Cursor, &Data->ValidationData);
977 PrintCursorExtent(Cursor);
978 if (clang_isDeclaration(Cursor.kind)) {
979 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
980 const char *accessStr = 0;
983 case CX_CXXInvalidAccessSpecifier: break;
985 accessStr = "public"; break;
986 case CX_CXXProtected:
987 accessStr = "protected"; break;
989 accessStr = "private"; break;
993 printf(" [access=%s]", accessStr);
996 return CXChildVisit_Recurse;
999 return CXChildVisit_Continue;
1002 static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
1004 CXClientData ClientData) {
1005 const char *startBuf, *endBuf;
1006 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1008 VisitorData *Data = (VisitorData *)ClientData;
1010 if (Cursor.kind != CXCursor_FunctionDecl ||
1011 !clang_isCursorDefinition(Cursor))
1012 return CXChildVisit_Continue;
1014 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1015 &startLine, &startColumn,
1016 &endLine, &endColumn);
1017 /* Probe the entire body, looking for both decls and refs. */
1018 curLine = startLine;
1019 curColumn = startColumn;
1021 while (startBuf < endBuf) {
1022 CXSourceLocation Loc;
1026 if (*startBuf == '\n') {
1030 } else if (*startBuf != '\t')
1033 Loc = clang_getCursorLocation(Cursor);
1034 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
1036 source = clang_getFileName(file);
1037 if (clang_getCString(source)) {
1038 CXSourceLocation RefLoc
1039 = clang_getLocation(Data->TU, file, curLine, curColumn);
1040 Ref = clang_getCursor(Data->TU, RefLoc);
1041 if (Ref.kind == CXCursor_NoDeclFound) {
1042 /* Nothing found here; that's fine. */
1043 } else if (Ref.kind != CXCursor_FunctionDecl) {
1044 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1045 curLine, curColumn);
1046 PrintCursor(Ref, &Data->ValidationData);
1050 clang_disposeString(source);
1054 return CXChildVisit_Continue;
1057 /******************************************************************************/
1059 /******************************************************************************/
1061 enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1062 CXClientData ClientData) {
1063 VisitorData *Data = (VisitorData *)ClientData;
1064 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
1065 CXString USR = clang_getCursorUSR(C);
1066 const char *cstr = clang_getCString(USR);
1067 if (!cstr || cstr[0] == '\0') {
1068 clang_disposeString(USR);
1069 return CXChildVisit_Recurse;
1071 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1073 PrintCursorExtent(C);
1075 clang_disposeString(USR);
1077 return CXChildVisit_Recurse;
1080 return CXChildVisit_Continue;
1083 /******************************************************************************/
1084 /* Inclusion stack testing. */
1085 /******************************************************************************/
1087 void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1088 unsigned includeStackLen, CXClientData data) {
1093 fname = clang_getFileName(includedFile);
1094 printf("file: %s\nincluded by:\n", clang_getCString(fname));
1095 clang_disposeString(fname);
1097 for (i = 0; i < includeStackLen; ++i) {
1098 CXFile includingFile;
1099 unsigned line, column;
1100 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1102 fname = clang_getFileName(includingFile);
1103 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
1104 clang_disposeString(fname);
1109 void PrintInclusionStack(CXTranslationUnit TU) {
1110 clang_getInclusions(TU, InclusionVisitor, NULL);
1113 /******************************************************************************/
1114 /* Linkage testing. */
1115 /******************************************************************************/
1117 static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1119 const char *linkage = 0;
1121 if (clang_isInvalid(clang_getCursorKind(cursor)))
1122 return CXChildVisit_Recurse;
1124 switch (clang_getCursorLinkage(cursor)) {
1125 case CXLinkage_Invalid: break;
1126 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1127 case CXLinkage_Internal: linkage = "Internal"; break;
1128 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1129 case CXLinkage_External: linkage = "External"; break;
1133 PrintCursor(cursor, NULL);
1134 printf("linkage=%s\n", linkage);
1137 return CXChildVisit_Recurse;
1140 /******************************************************************************/
1141 /* Typekind testing. */
1142 /******************************************************************************/
1144 static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1145 CXString TypeSpelling, TypeKindSpelling;
1147 TypeSpelling = clang_getTypeSpelling(T);
1148 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1150 clang_getCString(TypeSpelling),
1151 clang_getCString(TypeKindSpelling));
1152 clang_disposeString(TypeSpelling);
1153 clang_disposeString(TypeKindSpelling);
1156 static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1158 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
1159 CXType T = clang_getCursorType(cursor);
1160 PrintCursor(cursor, NULL);
1161 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1162 if (clang_isConstQualifiedType(T))
1164 if (clang_isVolatileQualifiedType(T))
1165 printf(" volatile");
1166 if (clang_isRestrictQualifiedType(T))
1167 printf(" restrict");
1168 /* Print the canonical type if it is different. */
1170 CXType CT = clang_getCanonicalType(T);
1171 if (!clang_equalTypes(T, CT)) {
1172 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
1175 /* Print the return type if it exists. */
1177 CXType RT = clang_getCursorResultType(cursor);
1178 if (RT.kind != CXType_Invalid) {
1179 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
1182 /* Print the argument types if they exist. */
1184 int numArgs = clang_Cursor_getNumArguments(cursor);
1185 if (numArgs != -1 && numArgs != 0) {
1188 for (i = 0; i < numArgs; ++i) {
1189 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
1190 if (T.kind != CXType_Invalid) {
1191 PrintTypeAndTypeKind(T, " [%s] [%s]");
1197 /* Print if this is a non-POD type. */
1198 printf(" [isPOD=%d]", clang_isPODType(T));
1202 return CXChildVisit_Recurse;
1205 static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1208 enum CXCursorKind K = clang_getCursorKind(cursor);
1209 if (clang_isInvalid(K))
1210 return CXChildVisit_Recurse;
1211 T = clang_getCursorType(cursor);
1212 PrintCursor(cursor, NULL);
1213 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1214 /* Print the type sizeof if applicable. */
1216 long long Size = clang_Type_getSizeOf(T);
1217 if (Size >= 0 || Size < -1 ) {
1218 printf(" [sizeof=%lld]", Size);
1221 /* Print the type alignof if applicable. */
1223 long long Align = clang_Type_getAlignOf(T);
1224 if (Align >= 0 || Align < -1) {
1225 printf(" [alignof=%lld]", Align);
1228 /* Print the record field offset if applicable. */
1230 const char *FieldName = clang_getCString(clang_getCursorSpelling(cursor));
1231 /* recurse to get the root anonymous record parent */
1232 CXCursor Parent, Root;
1233 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl ) {
1234 const char *RootParentName;
1238 RootParentName = clang_getCString(clang_getCursorSpelling(Root));
1239 Parent = clang_getCursorSemanticParent(Root);
1240 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1241 !strcmp(RootParentName, "") );
1242 /* if RootParentName is "", record is anonymous. */
1244 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Root),
1246 printf(" [offsetof=%lld]", Offset);
1250 /* Print if its a bitfield */
1252 int IsBitfield = clang_Cursor_isBitField(cursor);
1254 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1257 return CXChildVisit_Recurse;
1260 /******************************************************************************/
1261 /* Bitwidth testing. */
1262 /******************************************************************************/
1264 static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1267 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1268 return CXChildVisit_Recurse;
1270 Bitwidth = clang_getFieldDeclBitWidth(cursor);
1271 if (Bitwidth >= 0) {
1272 PrintCursor(cursor, NULL);
1273 printf(" bitwidth=%d\n", Bitwidth);
1276 return CXChildVisit_Recurse;
1279 /******************************************************************************/
1280 /* Loading ASTs/source. */
1281 /******************************************************************************/
1283 static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
1284 const char *filter, const char *prefix,
1285 CXCursorVisitor Visitor,
1287 const char *CommentSchemaFile) {
1290 FileCheckPrefix = prefix;
1293 enum CXCursorKind K = CXCursor_NotImplemented;
1294 enum CXCursorKind *ck = &K;
1297 /* Perform some simple filtering. */
1298 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
1299 else if (!strcmp(filter, "all-display") ||
1300 !strcmp(filter, "local-display")) {
1302 want_display_name = 1;
1304 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
1305 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1306 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1307 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1308 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1309 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1310 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1312 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1318 Data.ValidationData.CommentSchemaFile = CommentSchemaFile;
1319 #ifdef CLANG_HAVE_LIBXML
1320 Data.ValidationData.RNGParser = NULL;
1321 Data.ValidationData.Schema = NULL;
1323 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
1329 PrintDiagnostics(TU);
1330 if (checkForErrors(TU) != 0) {
1331 clang_disposeTranslationUnit(TU);
1335 clang_disposeTranslationUnit(TU);
1339 int perform_test_load_tu(const char *file, const char *filter,
1340 const char *prefix, CXCursorVisitor Visitor,
1343 CXTranslationUnit TU;
1345 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1346 !strcmp(filter, "local") ? 1 : 0,
1347 /* displayDiagnostics=*/1);
1349 if (!CreateTranslationUnit(Idx, file, &TU)) {
1350 clang_disposeIndex(Idx);
1354 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
1355 clang_disposeIndex(Idx);
1359 int perform_test_load_source(int argc, const char **argv,
1360 const char *filter, CXCursorVisitor Visitor,
1363 CXTranslationUnit TU;
1364 const char *CommentSchemaFile;
1365 struct CXUnsavedFile *unsaved_files = 0;
1366 int num_unsaved_files = 0;
1369 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1370 (!strcmp(filter, "local") ||
1371 !strcmp(filter, "local-display"))? 1 : 0,
1372 /* displayDiagnostics=*/1);
1374 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1379 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1380 clang_disposeIndex(Idx);
1384 TU = clang_parseTranslationUnit(Idx, 0,
1385 argv + num_unsaved_files,
1386 argc - num_unsaved_files,
1387 unsaved_files, num_unsaved_files,
1388 getDefaultParsingOptions());
1390 fprintf(stderr, "Unable to load translation unit!\n");
1391 free_remapped_files(unsaved_files, num_unsaved_files);
1392 clang_disposeIndex(Idx);
1396 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1398 free_remapped_files(unsaved_files, num_unsaved_files);
1399 clang_disposeIndex(Idx);
1403 int perform_test_reparse_source(int argc, const char **argv, int trials,
1404 const char *filter, CXCursorVisitor Visitor,
1407 CXTranslationUnit TU;
1408 struct CXUnsavedFile *unsaved_files = 0;
1409 int num_unsaved_files = 0;
1412 int remap_after_trial = 0;
1415 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1416 !strcmp(filter, "local") ? 1 : 0,
1417 /* displayDiagnostics=*/1);
1419 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1420 clang_disposeIndex(Idx);
1424 /* Load the initial translation unit -- we do this without honoring remapped
1425 * files, so that we have a way to test results after changing the source. */
1426 TU = clang_parseTranslationUnit(Idx, 0,
1427 argv + num_unsaved_files,
1428 argc - num_unsaved_files,
1429 0, 0, getDefaultParsingOptions());
1431 fprintf(stderr, "Unable to load translation unit!\n");
1432 free_remapped_files(unsaved_files, num_unsaved_files);
1433 clang_disposeIndex(Idx);
1437 if (checkForErrors(TU) != 0)
1440 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1442 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1445 for (trial = 0; trial < trials; ++trial) {
1446 if (clang_reparseTranslationUnit(TU,
1447 trial >= remap_after_trial ? num_unsaved_files : 0,
1448 trial >= remap_after_trial ? unsaved_files : 0,
1449 clang_defaultReparseOptions(TU))) {
1450 fprintf(stderr, "Unable to reparse translation unit!\n");
1451 clang_disposeTranslationUnit(TU);
1452 free_remapped_files(unsaved_files, num_unsaved_files);
1453 clang_disposeIndex(Idx);
1457 if (checkForErrors(TU) != 0)
1461 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
1463 free_remapped_files(unsaved_files, num_unsaved_files);
1464 clang_disposeIndex(Idx);
1468 /******************************************************************************/
1469 /* Logic for testing clang_getCursor(). */
1470 /******************************************************************************/
1472 static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
1473 unsigned start_line, unsigned start_col,
1474 unsigned end_line, unsigned end_col,
1475 const char *prefix) {
1476 printf("// %s: ", FileCheckPrefix);
1478 printf("-%s", prefix);
1479 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1481 PrintCursor(cursor, NULL);
1485 static int perform_file_scan(const char *ast_file, const char *source_file,
1486 const char *prefix) {
1488 CXTranslationUnit TU;
1490 CXCursor prevCursor = clang_getNullCursor();
1492 unsigned line = 1, col = 1;
1493 unsigned start_line = 1, start_col = 1;
1495 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
1496 /* displayDiagnostics=*/1))) {
1497 fprintf(stderr, "Could not create Index\n");
1501 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1504 if ((fp = fopen(source_file, "r")) == NULL) {
1505 fprintf(stderr, "Could not open '%s'\n", source_file);
1509 file = clang_getFile(TU, source_file);
1520 /* Check the cursor at this position, and dump the previous one if we have
1521 * found something new.
1523 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1524 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1525 prevCursor.kind != CXCursor_InvalidFile) {
1526 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
1534 prevCursor = cursor;
1538 clang_disposeTranslationUnit(TU);
1539 clang_disposeIndex(Idx);
1543 /******************************************************************************/
1544 /* Logic for testing clang code completion. */
1545 /******************************************************************************/
1547 /* Parse file:line:column from the input string. Returns 0 on success, non-zero
1548 on failure. If successful, the pointer *filename will contain newly-allocated
1549 memory (that will be owned by the caller) to store the file name. */
1550 int parse_file_line_column(const char *input, char **filename, unsigned *line,
1551 unsigned *column, unsigned *second_line,
1552 unsigned *second_column) {
1553 /* Find the second colon. */
1554 const char *last_colon = strrchr(input, ':');
1555 unsigned values[4], i;
1556 unsigned num_values = (second_line && second_column)? 4 : 2;
1559 if (!last_colon || last_colon == input) {
1560 if (num_values == 4)
1561 fprintf(stderr, "could not parse filename:line:column:line:column in "
1564 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
1568 for (i = 0; i != num_values; ++i) {
1569 const char *prev_colon;
1571 /* Parse the next line or column. */
1572 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1573 if (*endptr != 0 && *endptr != ':') {
1574 fprintf(stderr, "could not parse %s in '%s'\n",
1575 (i % 2 ? "column" : "line"), input);
1579 if (i + 1 == num_values)
1582 /* Find the previous colon. */
1583 prev_colon = last_colon - 1;
1584 while (prev_colon != input && *prev_colon != ':')
1586 if (prev_colon == input) {
1587 fprintf(stderr, "could not parse %s in '%s'\n",
1588 (i % 2 == 0? "column" : "line"), input);
1592 last_colon = prev_colon;
1596 *column = values[1];
1598 if (second_line && second_column) {
1599 *second_line = values[2];
1600 *second_column = values[3];
1603 /* Copy the file name. */
1604 *filename = (char*)malloc(last_colon - input + 1);
1605 memcpy(*filename, input, last_colon - input);
1606 (*filename)[last_colon - input] = 0;
1611 clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1613 case CXCompletionChunk_Optional: return "Optional";
1614 case CXCompletionChunk_TypedText: return "TypedText";
1615 case CXCompletionChunk_Text: return "Text";
1616 case CXCompletionChunk_Placeholder: return "Placeholder";
1617 case CXCompletionChunk_Informative: return "Informative";
1618 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1619 case CXCompletionChunk_LeftParen: return "LeftParen";
1620 case CXCompletionChunk_RightParen: return "RightParen";
1621 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1622 case CXCompletionChunk_RightBracket: return "RightBracket";
1623 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1624 case CXCompletionChunk_RightBrace: return "RightBrace";
1625 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1626 case CXCompletionChunk_RightAngle: return "RightAngle";
1627 case CXCompletionChunk_Comma: return "Comma";
1628 case CXCompletionChunk_ResultType: return "ResultType";
1629 case CXCompletionChunk_Colon: return "Colon";
1630 case CXCompletionChunk_SemiColon: return "SemiColon";
1631 case CXCompletionChunk_Equal: return "Equal";
1632 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1633 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
1639 static int checkForErrors(CXTranslationUnit TU) {
1644 if (!getenv("CINDEXTEST_FAILONERROR"))
1647 Num = clang_getNumDiagnostics(TU);
1648 for (i = 0; i != Num; ++i) {
1649 Diag = clang_getDiagnostic(TU, i);
1650 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1651 DiagStr = clang_formatDiagnostic(Diag,
1652 clang_defaultDiagnosticDisplayOptions());
1653 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1654 clang_disposeString(DiagStr);
1655 clang_disposeDiagnostic(Diag);
1658 clang_disposeDiagnostic(Diag);
1664 void print_completion_string(CXCompletionString completion_string, FILE *file) {
1667 N = clang_getNumCompletionChunks(completion_string);
1668 for (I = 0; I != N; ++I) {
1671 enum CXCompletionChunkKind Kind
1672 = clang_getCompletionChunkKind(completion_string, I);
1674 if (Kind == CXCompletionChunk_Optional) {
1675 fprintf(file, "{Optional ");
1676 print_completion_string(
1677 clang_getCompletionChunkCompletionString(completion_string, I),
1683 if (Kind == CXCompletionChunk_VerticalSpace) {
1684 fprintf(file, "{VerticalSpace }");
1688 text = clang_getCompletionChunkText(completion_string, I);
1689 cstr = clang_getCString(text);
1690 fprintf(file, "{%s %s}",
1691 clang_getCompletionChunkKindSpelling(Kind),
1693 clang_disposeString(text);
1698 void print_completion_result(CXCompletionResult *completion_result,
1699 CXClientData client_data) {
1700 FILE *file = (FILE *)client_data;
1701 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
1702 unsigned annotationCount;
1703 enum CXCursorKind ParentKind;
1704 CXString ParentName;
1705 CXString BriefComment;
1706 const char *BriefCommentCString;
1708 fprintf(file, "%s:", clang_getCString(ks));
1709 clang_disposeString(ks);
1711 print_completion_string(completion_result->CompletionString, file);
1712 fprintf(file, " (%u)",
1713 clang_getCompletionPriority(completion_result->CompletionString));
1714 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1715 case CXAvailability_Available:
1718 case CXAvailability_Deprecated:
1719 fprintf(file, " (deprecated)");
1722 case CXAvailability_NotAvailable:
1723 fprintf(file, " (unavailable)");
1726 case CXAvailability_NotAccessible:
1727 fprintf(file, " (inaccessible)");
1731 annotationCount = clang_getCompletionNumAnnotations(
1732 completion_result->CompletionString);
1733 if (annotationCount) {
1735 fprintf(file, " (");
1736 for (i = 0; i < annotationCount; ++i) {
1738 fprintf(file, ", ");
1739 fprintf(file, "\"%s\"",
1740 clang_getCString(clang_getCompletionAnnotation(
1741 completion_result->CompletionString, i)));
1746 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1747 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1749 if (ParentKind != CXCursor_NotImplemented) {
1750 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
1751 fprintf(file, " (parent: %s '%s')",
1752 clang_getCString(KindSpelling),
1753 clang_getCString(ParentName));
1754 clang_disposeString(KindSpelling);
1756 clang_disposeString(ParentName);
1759 BriefComment = clang_getCompletionBriefComment(
1760 completion_result->CompletionString);
1761 BriefCommentCString = clang_getCString(BriefComment);
1762 if (BriefCommentCString && *BriefCommentCString != '\0') {
1763 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1765 clang_disposeString(BriefComment);
1767 fprintf(file, "\n");
1770 void print_completion_contexts(unsigned long long contexts, FILE *file) {
1771 fprintf(file, "Completion contexts:\n");
1772 if (contexts == CXCompletionContext_Unknown) {
1773 fprintf(file, "Unknown\n");
1775 if (contexts & CXCompletionContext_AnyType) {
1776 fprintf(file, "Any type\n");
1778 if (contexts & CXCompletionContext_AnyValue) {
1779 fprintf(file, "Any value\n");
1781 if (contexts & CXCompletionContext_ObjCObjectValue) {
1782 fprintf(file, "Objective-C object value\n");
1784 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1785 fprintf(file, "Objective-C selector value\n");
1787 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1788 fprintf(file, "C++ class type value\n");
1790 if (contexts & CXCompletionContext_DotMemberAccess) {
1791 fprintf(file, "Dot member access\n");
1793 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1794 fprintf(file, "Arrow member access\n");
1796 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1797 fprintf(file, "Objective-C property access\n");
1799 if (contexts & CXCompletionContext_EnumTag) {
1800 fprintf(file, "Enum tag\n");
1802 if (contexts & CXCompletionContext_UnionTag) {
1803 fprintf(file, "Union tag\n");
1805 if (contexts & CXCompletionContext_StructTag) {
1806 fprintf(file, "Struct tag\n");
1808 if (contexts & CXCompletionContext_ClassTag) {
1809 fprintf(file, "Class name\n");
1811 if (contexts & CXCompletionContext_Namespace) {
1812 fprintf(file, "Namespace or namespace alias\n");
1814 if (contexts & CXCompletionContext_NestedNameSpecifier) {
1815 fprintf(file, "Nested name specifier\n");
1817 if (contexts & CXCompletionContext_ObjCInterface) {
1818 fprintf(file, "Objective-C interface\n");
1820 if (contexts & CXCompletionContext_ObjCProtocol) {
1821 fprintf(file, "Objective-C protocol\n");
1823 if (contexts & CXCompletionContext_ObjCCategory) {
1824 fprintf(file, "Objective-C category\n");
1826 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1827 fprintf(file, "Objective-C instance method\n");
1829 if (contexts & CXCompletionContext_ObjCClassMessage) {
1830 fprintf(file, "Objective-C class method\n");
1832 if (contexts & CXCompletionContext_ObjCSelectorName) {
1833 fprintf(file, "Objective-C selector name\n");
1835 if (contexts & CXCompletionContext_MacroName) {
1836 fprintf(file, "Macro name\n");
1838 if (contexts & CXCompletionContext_NaturalLanguage) {
1839 fprintf(file, "Natural language\n");
1843 int my_stricmp(const char *s1, const char *s2) {
1844 while (*s1 && *s2) {
1845 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
1862 int perform_code_completion(int argc, const char **argv, int timing_only) {
1863 const char *input = argv[1];
1869 struct CXUnsavedFile *unsaved_files = 0;
1870 int num_unsaved_files = 0;
1871 CXCodeCompleteResults *results = 0;
1872 CXTranslationUnit TU = 0;
1873 unsigned I, Repeats = 1;
1874 unsigned completionOptions = clang_defaultCodeCompleteOptions();
1876 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
1877 completionOptions |= CXCodeComplete_IncludeCodePatterns;
1878 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
1879 completionOptions |= CXCodeComplete_IncludeBriefComments;
1882 input += strlen("-code-completion-timing=");
1884 input += strlen("-code-completion-at=");
1886 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
1890 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
1893 CIdx = clang_createIndex(0, 0);
1895 if (getenv("CINDEXTEST_EDITING"))
1898 TU = clang_parseTranslationUnit(CIdx, 0,
1899 argv + num_unsaved_files + 2,
1900 argc - num_unsaved_files - 2,
1901 0, 0, getDefaultParsingOptions());
1903 fprintf(stderr, "Unable to load translation unit!\n");
1907 if (clang_reparseTranslationUnit(TU, 0, 0, clang_defaultReparseOptions(TU))) {
1908 fprintf(stderr, "Unable to reparse translation init!\n");
1912 for (I = 0; I != Repeats; ++I) {
1913 results = clang_codeCompleteAt(TU, filename, line, column,
1914 unsaved_files, num_unsaved_files,
1917 fprintf(stderr, "Unable to perform code completion!\n");
1921 clang_disposeCodeCompleteResults(results);
1925 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
1926 unsigned long long contexts;
1927 enum CXCursorKind containerKind;
1928 CXString objCSelector;
1929 const char *selectorString;
1931 /* Sort the code-completion results based on the typed text. */
1932 clang_sortCodeCompletionResults(results->Results, results->NumResults);
1934 for (i = 0; i != n; ++i)
1935 print_completion_result(results->Results + i, stdout);
1937 n = clang_codeCompleteGetNumDiagnostics(results);
1938 for (i = 0; i != n; ++i) {
1939 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
1940 PrintDiagnostic(diag);
1941 clang_disposeDiagnostic(diag);
1944 contexts = clang_codeCompleteGetContexts(results);
1945 print_completion_contexts(contexts, stdout);
1947 containerKind = clang_codeCompleteGetContainerKind(results,
1948 &containerIsIncomplete);
1950 if (containerKind != CXCursor_InvalidCode) {
1951 /* We have found a container */
1952 CXString containerUSR, containerKindSpelling;
1953 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
1954 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
1955 clang_disposeString(containerKindSpelling);
1957 if (containerIsIncomplete) {
1958 printf("Container is incomplete\n");
1961 printf("Container is complete\n");
1964 containerUSR = clang_codeCompleteGetContainerUSR(results);
1965 printf("Container USR: %s\n", clang_getCString(containerUSR));
1966 clang_disposeString(containerUSR);
1969 objCSelector = clang_codeCompleteGetObjCSelector(results);
1970 selectorString = clang_getCString(objCSelector);
1971 if (selectorString && strlen(selectorString) > 0) {
1972 printf("Objective-C selector: %s\n", selectorString);
1974 clang_disposeString(objCSelector);
1976 clang_disposeCodeCompleteResults(results);
1978 clang_disposeTranslationUnit(TU);
1979 clang_disposeIndex(CIdx);
1982 free_remapped_files(unsaved_files, num_unsaved_files);
1991 } CursorSourceLocation;
1993 static int inspect_cursor_at(int argc, const char **argv) {
1996 struct CXUnsavedFile *unsaved_files = 0;
1997 int num_unsaved_files = 0;
1998 CXTranslationUnit TU;
2000 CursorSourceLocation *Locations = 0;
2001 unsigned NumLocations = 0, Loc;
2002 unsigned Repeats = 1;
2005 /* Count the number of locations. */
2006 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2009 /* Parse the locations. */
2010 assert(NumLocations > 0 && "Unable to count locations?");
2011 Locations = (CursorSourceLocation *)malloc(
2012 NumLocations * sizeof(CursorSourceLocation));
2013 for (Loc = 0; Loc < NumLocations; ++Loc) {
2014 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
2015 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2016 &Locations[Loc].line,
2017 &Locations[Loc].column, 0, 0)))
2021 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2022 &num_unsaved_files))
2025 if (getenv("CINDEXTEST_EDITING"))
2028 /* Parse the translation unit. When we're testing clang_getCursor() after
2029 reparsing, don't remap unsaved files until the second parse. */
2030 CIdx = clang_createIndex(1, 1);
2031 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2032 argv + num_unsaved_files + 1 + NumLocations,
2033 argc - num_unsaved_files - 2 - NumLocations,
2035 Repeats > 1? 0 : num_unsaved_files,
2036 getDefaultParsingOptions());
2039 fprintf(stderr, "unable to parse input\n");
2043 if (checkForErrors(TU) != 0)
2046 for (I = 0; I != Repeats; ++I) {
2048 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2049 clang_defaultReparseOptions(TU))) {
2050 clang_disposeTranslationUnit(TU);
2054 if (checkForErrors(TU) != 0)
2057 for (Loc = 0; Loc < NumLocations; ++Loc) {
2058 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2062 Cursor = clang_getCursor(TU,
2063 clang_getLocation(TU, file, Locations[Loc].line,
2064 Locations[Loc].column));
2066 if (checkForErrors(TU) != 0)
2069 if (I + 1 == Repeats) {
2070 CXCompletionString completionString = clang_getCursorCompletionString(
2072 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2075 unsigned line, column;
2076 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2077 printf("%d:%d ", line, column);
2078 PrintCursor(Cursor, NULL);
2079 PrintCursorExtent(Cursor);
2080 Spelling = clang_getCursorSpelling(Cursor);
2081 cspell = clang_getCString(Spelling);
2082 if (cspell && strlen(cspell) != 0) {
2083 unsigned pieceIndex;
2084 printf(" Spelling=%s (", cspell);
2085 for (pieceIndex = 0; ; ++pieceIndex) {
2086 CXSourceRange range =
2087 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2088 if (clang_Range_isNull(range))
2090 PrintRange(range, 0);
2094 clang_disposeString(Spelling);
2095 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2096 printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
2097 if (clang_Cursor_isDynamicCall(Cursor))
2098 printf(" Dynamic-call");
2099 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2100 CXType T = clang_Cursor_getReceiverType(Cursor);
2101 CXString S = clang_getTypeKindSpelling(T.kind);
2102 printf(" Receiver-type=%s", clang_getCString(S));
2103 clang_disposeString(S);
2107 CXModule mod = clang_Cursor_getModule(Cursor);
2109 CXString name, astFilename;
2110 unsigned i, numHeaders;
2112 astFile = clang_Module_getASTFile(mod);
2113 astFilename = clang_getFileName(astFile);
2114 name = clang_Module_getFullName(mod);
2115 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2116 printf(" ModuleName=%s (%s) Headers(%d):",
2117 clang_getCString(name), clang_getCString(astFilename),
2119 clang_disposeString(name);
2120 clang_disposeString(astFilename);
2121 for (i = 0; i < numHeaders; ++i) {
2122 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2123 CXString filename = clang_getFileName(file);
2124 printf("\n%s", clang_getCString(filename));
2125 clang_disposeString(filename);
2130 if (completionString != NULL) {
2131 printf("\nCompletion string: ");
2132 print_completion_string(completionString, stdout);
2135 free(Locations[Loc].filename);
2140 PrintDiagnostics(TU);
2141 clang_disposeTranslationUnit(TU);
2142 clang_disposeIndex(CIdx);
2144 free_remapped_files(unsaved_files, num_unsaved_files);
2148 static enum CXVisitorResult findFileRefsVisit(void *context,
2149 CXCursor cursor, CXSourceRange range) {
2150 if (clang_Range_isNull(range))
2151 return CXVisit_Continue;
2153 PrintCursor(cursor, NULL);
2154 PrintRange(range, "");
2156 return CXVisit_Continue;
2159 static int find_file_refs_at(int argc, const char **argv) {
2162 struct CXUnsavedFile *unsaved_files = 0;
2163 int num_unsaved_files = 0;
2164 CXTranslationUnit TU;
2166 CursorSourceLocation *Locations = 0;
2167 unsigned NumLocations = 0, Loc;
2168 unsigned Repeats = 1;
2171 /* Count the number of locations. */
2172 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2175 /* Parse the locations. */
2176 assert(NumLocations > 0 && "Unable to count locations?");
2177 Locations = (CursorSourceLocation *)malloc(
2178 NumLocations * sizeof(CursorSourceLocation));
2179 for (Loc = 0; Loc < NumLocations; ++Loc) {
2180 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2181 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2182 &Locations[Loc].line,
2183 &Locations[Loc].column, 0, 0)))
2187 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2188 &num_unsaved_files))
2191 if (getenv("CINDEXTEST_EDITING"))
2194 /* Parse the translation unit. When we're testing clang_getCursor() after
2195 reparsing, don't remap unsaved files until the second parse. */
2196 CIdx = clang_createIndex(1, 1);
2197 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2198 argv + num_unsaved_files + 1 + NumLocations,
2199 argc - num_unsaved_files - 2 - NumLocations,
2201 Repeats > 1? 0 : num_unsaved_files,
2202 getDefaultParsingOptions());
2205 fprintf(stderr, "unable to parse input\n");
2209 if (checkForErrors(TU) != 0)
2212 for (I = 0; I != Repeats; ++I) {
2214 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2215 clang_defaultReparseOptions(TU))) {
2216 clang_disposeTranslationUnit(TU);
2220 if (checkForErrors(TU) != 0)
2223 for (Loc = 0; Loc < NumLocations; ++Loc) {
2224 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2228 Cursor = clang_getCursor(TU,
2229 clang_getLocation(TU, file, Locations[Loc].line,
2230 Locations[Loc].column));
2232 if (checkForErrors(TU) != 0)
2235 if (I + 1 == Repeats) {
2236 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
2237 PrintCursor(Cursor, NULL);
2239 clang_findReferencesInFile(Cursor, file, visitor);
2240 free(Locations[Loc].filename);
2242 if (checkForErrors(TU) != 0)
2248 PrintDiagnostics(TU);
2249 clang_disposeTranslationUnit(TU);
2250 clang_disposeIndex(CIdx);
2252 free_remapped_files(unsaved_files, num_unsaved_files);
2256 static enum CXVisitorResult findFileIncludesVisit(void *context,
2257 CXCursor cursor, CXSourceRange range) {
2258 PrintCursor(cursor, NULL);
2259 PrintRange(range, "");
2261 return CXVisit_Continue;
2264 static int find_file_includes_in(int argc, const char **argv) {
2266 struct CXUnsavedFile *unsaved_files = 0;
2267 int num_unsaved_files = 0;
2268 CXTranslationUnit TU;
2269 const char **Filenames = 0;
2270 unsigned NumFilenames = 0;
2271 unsigned Repeats = 1;
2274 /* Count the number of locations. */
2275 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2278 /* Parse the locations. */
2279 assert(NumFilenames > 0 && "Unable to count filenames?");
2280 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2281 for (I = 0; I < NumFilenames; ++I) {
2282 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2283 /* Copy the file name. */
2284 Filenames[I] = input;
2287 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2288 &num_unsaved_files))
2291 if (getenv("CINDEXTEST_EDITING"))
2294 /* Parse the translation unit. When we're testing clang_getCursor() after
2295 reparsing, don't remap unsaved files until the second parse. */
2296 CIdx = clang_createIndex(1, 1);
2297 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2298 argv + num_unsaved_files + 1 + NumFilenames,
2299 argc - num_unsaved_files - 2 - NumFilenames,
2301 Repeats > 1? 0 : num_unsaved_files,
2302 getDefaultParsingOptions());
2305 fprintf(stderr, "unable to parse input\n");
2309 if (checkForErrors(TU) != 0)
2312 for (I = 0; I != Repeats; ++I) {
2314 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2315 clang_defaultReparseOptions(TU))) {
2316 clang_disposeTranslationUnit(TU);
2320 if (checkForErrors(TU) != 0)
2323 for (FI = 0; FI < NumFilenames; ++FI) {
2324 CXFile file = clang_getFile(TU, Filenames[FI]);
2328 if (checkForErrors(TU) != 0)
2331 if (I + 1 == Repeats) {
2332 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2333 clang_findIncludesInFile(TU, file, visitor);
2335 if (checkForErrors(TU) != 0)
2341 PrintDiagnostics(TU);
2342 clang_disposeTranslationUnit(TU);
2343 clang_disposeIndex(CIdx);
2344 free((void *)Filenames);
2345 free_remapped_files(unsaved_files, num_unsaved_files);
2349 #define MAX_IMPORTED_ASTFILES 200
2354 } ImportedASTFilesData;
2356 static ImportedASTFilesData *importedASTs_create() {
2357 ImportedASTFilesData *p;
2358 p = malloc(sizeof(ImportedASTFilesData));
2359 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2364 static void importedASTs_dispose(ImportedASTFilesData *p) {
2369 for (i = 0; i < p->num_files; ++i)
2370 free(p->filenames[i]);
2375 static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2378 for (i = 0; i < p->num_files; ++i)
2379 if (strcmp(file, p->filenames[i]) == 0)
2381 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2382 p->filenames[p->num_files++] = strdup(file);
2386 const char *check_prefix;
2387 int first_check_printed;
2390 const char *main_filename;
2391 ImportedASTFilesData *importedASTs;
2394 static void printCheck(IndexData *data) {
2395 if (data->check_prefix) {
2396 if (data->first_check_printed) {
2397 printf("// %s-NEXT: ", data->check_prefix);
2399 printf("// %s : ", data->check_prefix);
2400 data->first_check_printed = 1;
2405 static void printCXIndexFile(CXIdxClientFile file) {
2406 CXString filename = clang_getFileName((CXFile)file);
2407 printf("%s", clang_getCString(filename));
2408 clang_disposeString(filename);
2411 static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2412 IndexData *index_data;
2415 CXIdxClientFile file;
2416 unsigned line, column;
2419 index_data = (IndexData *)client_data;
2420 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2422 printf("<invalid>");
2426 printf("<no idxfile>");
2429 filename = clang_getFileName((CXFile)file);
2430 cname = clang_getCString(filename);
2431 if (strcmp(cname, index_data->main_filename) == 0)
2435 clang_disposeString(filename);
2438 printCXIndexFile(file);
2441 printf("%d:%d", line, column);
2444 static unsigned digitCount(unsigned val) {
2454 static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2458 CXIdxClientFile file;
2459 unsigned line, column;
2463 name = "<anon-tag>";
2465 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2466 /* FIXME: free these.*/
2467 newStr = (char *)malloc(strlen(name) +
2468 digitCount(line) + digitCount(column) + 3);
2469 sprintf(newStr, "%s:%d:%d", name, line, column);
2470 return (CXIdxClientContainer)newStr;
2473 static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2474 CXIdxClientContainer container;
2475 container = clang_index_getClientContainer(info);
2477 printf("[<<NULL>>]");
2479 printf("[%s]", (const char *)container);
2482 static const char *getEntityKindString(CXIdxEntityKind kind) {
2484 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2485 case CXIdxEntity_Typedef: return "typedef";
2486 case CXIdxEntity_Function: return "function";
2487 case CXIdxEntity_Variable: return "variable";
2488 case CXIdxEntity_Field: return "field";
2489 case CXIdxEntity_EnumConstant: return "enumerator";
2490 case CXIdxEntity_ObjCClass: return "objc-class";
2491 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2492 case CXIdxEntity_ObjCCategory: return "objc-category";
2493 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2494 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
2495 case CXIdxEntity_ObjCProperty: return "objc-property";
2496 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2497 case CXIdxEntity_Enum: return "enum";
2498 case CXIdxEntity_Struct: return "struct";
2499 case CXIdxEntity_Union: return "union";
2500 case CXIdxEntity_CXXClass: return "c++-class";
2501 case CXIdxEntity_CXXNamespace: return "namespace";
2502 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2503 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2504 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2505 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2506 case CXIdxEntity_CXXConstructor: return "constructor";
2507 case CXIdxEntity_CXXDestructor: return "destructor";
2508 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2509 case CXIdxEntity_CXXTypeAlias: return "type-alias";
2510 case CXIdxEntity_CXXInterface: return "c++-__interface";
2512 assert(0 && "Garbage entity kind");
2516 static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2518 case CXIdxEntity_NonTemplate: return "";
2519 case CXIdxEntity_Template: return "-template";
2520 case CXIdxEntity_TemplatePartialSpecialization:
2521 return "-template-partial-spec";
2522 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
2524 assert(0 && "Garbage entity kind");
2528 static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2530 case CXIdxEntityLang_None: return "<none>";
2531 case CXIdxEntityLang_C: return "C";
2532 case CXIdxEntityLang_ObjC: return "ObjC";
2533 case CXIdxEntityLang_CXX: return "C++";
2535 assert(0 && "Garbage language kind");
2539 static void printEntityInfo(const char *cb,
2540 CXClientData client_data,
2541 const CXIdxEntityInfo *info) {
2543 IndexData *index_data;
2545 index_data = (IndexData *)client_data;
2546 printCheck(index_data);
2549 printf("%s: <<NULL>>", cb);
2555 name = "<anon-tag>";
2557 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2558 getEntityTemplateKindString(info->templateKind));
2559 printf(" | name: %s", name);
2560 printf(" | USR: %s", info->USR);
2561 printf(" | lang: %s", getEntityLanguageString(info->lang));
2563 for (i = 0; i != info->numAttributes; ++i) {
2564 const CXIdxAttrInfo *Attr = info->attributes[i];
2565 printf(" <attribute>: ");
2566 PrintCursor(Attr->cursor, NULL);
2570 static void printBaseClassInfo(CXClientData client_data,
2571 const CXIdxBaseClassInfo *info) {
2572 printEntityInfo(" <base>", client_data, info->base);
2573 printf(" | cursor: ");
2574 PrintCursor(info->cursor, NULL);
2576 printCXIndexLoc(info->loc, client_data);
2579 static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2580 CXClientData client_data) {
2582 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2583 printEntityInfo(" <protocol>", client_data,
2584 ProtoInfo->protocols[i]->protocol);
2585 printf(" | cursor: ");
2586 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
2588 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
2593 static void index_diagnostic(CXClientData client_data,
2594 CXDiagnosticSet diagSet, void *reserved) {
2597 unsigned numDiags, i;
2599 IndexData *index_data;
2600 index_data = (IndexData *)client_data;
2601 printCheck(index_data);
2603 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2604 for (i = 0; i != numDiags; ++i) {
2605 diag = clang_getDiagnosticInSet(diagSet, i);
2606 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2607 cstr = clang_getCString(str);
2608 printf("[diagnostic]: %s\n", cstr);
2609 clang_disposeString(str);
2611 if (getenv("CINDEXTEST_FAILONERROR") &&
2612 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2613 index_data->fail_for_error = 1;
2618 static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2619 CXFile file, void *reserved) {
2620 IndexData *index_data;
2623 index_data = (IndexData *)client_data;
2624 printCheck(index_data);
2626 filename = clang_getFileName(file);
2627 index_data->main_filename = clang_getCString(filename);
2628 clang_disposeString(filename);
2630 printf("[enteredMainFile]: ");
2631 printCXIndexFile((CXIdxClientFile)file);
2634 return (CXIdxClientFile)file;
2637 static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
2638 const CXIdxIncludedFileInfo *info) {
2639 IndexData *index_data;
2640 index_data = (IndexData *)client_data;
2641 printCheck(index_data);
2643 printf("[ppIncludedFile]: ");
2644 printCXIndexFile((CXIdxClientFile)info->file);
2645 printf(" | name: \"%s\"", info->filename);
2646 printf(" | hash loc: ");
2647 printCXIndexLoc(info->hashLoc, client_data);
2648 printf(" | isImport: %d | isAngled: %d | isModule: %d\n",
2649 info->isImport, info->isAngled, info->isModuleImport);
2651 return (CXIdxClientFile)info->file;
2654 static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2655 const CXIdxImportedASTFileInfo *info) {
2656 IndexData *index_data;
2657 index_data = (IndexData *)client_data;
2658 printCheck(index_data);
2660 if (index_data->importedASTs) {
2661 CXString filename = clang_getFileName(info->file);
2662 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2663 clang_disposeString(filename);
2666 printf("[importedASTFile]: ");
2667 printCXIndexFile((CXIdxClientFile)info->file);
2669 CXString name = clang_Module_getFullName(info->module);
2671 printCXIndexLoc(info->loc, client_data);
2672 printf(" | name: \"%s\"", clang_getCString(name));
2673 printf(" | isImplicit: %d\n", info->isImplicit);
2674 clang_disposeString(name);
2676 /* PCH file, the rest are not relevant. */
2680 return (CXIdxClientFile)info->file;
2683 static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
2685 IndexData *index_data;
2686 index_data = (IndexData *)client_data;
2687 printCheck(index_data);
2689 printf("[startedTranslationUnit]\n");
2690 return (CXIdxClientContainer)"TU";
2693 static void index_indexDeclaration(CXClientData client_data,
2694 const CXIdxDeclInfo *info) {
2695 IndexData *index_data;
2696 const CXIdxObjCCategoryDeclInfo *CatInfo;
2697 const CXIdxObjCInterfaceDeclInfo *InterInfo;
2698 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
2699 const CXIdxObjCPropertyDeclInfo *PropInfo;
2700 const CXIdxCXXClassDeclInfo *CXXClassInfo;
2702 index_data = (IndexData *)client_data;
2704 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2705 printf(" | cursor: ");
2706 PrintCursor(info->cursor, NULL);
2708 printCXIndexLoc(info->loc, client_data);
2709 printf(" | semantic-container: ");
2710 printCXIndexContainer(info->semanticContainer);
2711 printf(" | lexical-container: ");
2712 printCXIndexContainer(info->lexicalContainer);
2713 printf(" | isRedecl: %d", info->isRedeclaration);
2714 printf(" | isDef: %d", info->isDefinition);
2715 if (info->flags & CXIdxDeclFlag_Skipped) {
2716 assert(!info->isContainer);
2717 printf(" | isContainer: skipped");
2719 printf(" | isContainer: %d", info->isContainer);
2721 printf(" | isImplicit: %d\n", info->isImplicit);
2723 for (i = 0; i != info->numAttributes; ++i) {
2724 const CXIdxAttrInfo *Attr = info->attributes[i];
2725 printf(" <attribute>: ");
2726 PrintCursor(Attr->cursor, NULL);
2730 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2731 const char *kindName = 0;
2732 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2734 case CXIdxObjCContainer_ForwardRef:
2735 kindName = "forward-ref"; break;
2736 case CXIdxObjCContainer_Interface:
2737 kindName = "interface"; break;
2738 case CXIdxObjCContainer_Implementation:
2739 kindName = "implementation"; break;
2741 printCheck(index_data);
2742 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2745 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
2746 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
2747 CatInfo->objcClass);
2748 printf(" | cursor: ");
2749 PrintCursor(CatInfo->classCursor, NULL);
2751 printCXIndexLoc(CatInfo->classLoc, client_data);
2755 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2756 if (InterInfo->superInfo) {
2757 printBaseClassInfo(client_data, InterInfo->superInfo);
2762 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2763 printProtocolList(ProtoInfo, client_data);
2766 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2767 if (PropInfo->getter) {
2768 printEntityInfo(" <getter>", client_data, PropInfo->getter);
2771 if (PropInfo->setter) {
2772 printEntityInfo(" <setter>", client_data, PropInfo->setter);
2777 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2778 for (i = 0; i != CXXClassInfo->numBases; ++i) {
2779 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2784 if (info->declAsContainer)
2785 clang_index_setClientContainer(info->declAsContainer,
2786 makeClientContainer(info->entityInfo, info->loc));
2789 static void index_indexEntityReference(CXClientData client_data,
2790 const CXIdxEntityRefInfo *info) {
2791 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
2792 printf(" | cursor: ");
2793 PrintCursor(info->cursor, NULL);
2795 printCXIndexLoc(info->loc, client_data);
2796 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
2797 printf(" | container: ");
2798 printCXIndexContainer(info->container);
2799 printf(" | refkind: ");
2800 switch (info->kind) {
2801 case CXIdxEntityRef_Direct: printf("direct"); break;
2802 case CXIdxEntityRef_Implicit: printf("implicit"); break;
2807 static int index_abortQuery(CXClientData client_data, void *reserved) {
2808 IndexData *index_data;
2809 index_data = (IndexData *)client_data;
2810 return index_data->abort;
2813 static IndexerCallbacks IndexCB = {
2816 index_enteredMainFile,
2817 index_ppIncludedFile,
2818 index_importedASTFile,
2819 index_startedTranslationUnit,
2820 index_indexDeclaration,
2821 index_indexEntityReference
2824 static unsigned getIndexOptions(void) {
2825 unsigned index_opts;
2827 if (getenv("CINDEXTEST_SUPPRESSREFS"))
2828 index_opts |= CXIndexOpt_SuppressRedundantRefs;
2829 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
2830 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
2831 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
2832 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
2837 static int index_compile_args(int num_args, const char **args,
2838 CXIndexAction idxAction,
2839 ImportedASTFilesData *importedASTs,
2840 const char *check_prefix) {
2841 IndexData index_data;
2842 unsigned index_opts;
2845 if (num_args == 0) {
2846 fprintf(stderr, "no compiler arguments\n");
2850 index_data.check_prefix = check_prefix;
2851 index_data.first_check_printed = 0;
2852 index_data.fail_for_error = 0;
2853 index_data.abort = 0;
2854 index_data.main_filename = "";
2855 index_data.importedASTs = importedASTs;
2857 index_opts = getIndexOptions();
2858 result = clang_indexSourceFile(idxAction, &index_data,
2859 &IndexCB,sizeof(IndexCB), index_opts,
2860 0, args, num_args, 0, 0, 0,
2861 getDefaultParsingOptions());
2862 if (index_data.fail_for_error)
2868 static int index_ast_file(const char *ast_file,
2870 CXIndexAction idxAction,
2871 ImportedASTFilesData *importedASTs,
2872 const char *check_prefix) {
2873 CXTranslationUnit TU;
2874 IndexData index_data;
2875 unsigned index_opts;
2878 if (!CreateTranslationUnit(Idx, ast_file, &TU))
2881 index_data.check_prefix = check_prefix;
2882 index_data.first_check_printed = 0;
2883 index_data.fail_for_error = 0;
2884 index_data.abort = 0;
2885 index_data.main_filename = "";
2886 index_data.importedASTs = importedASTs;
2888 index_opts = getIndexOptions();
2889 result = clang_indexTranslationUnit(idxAction, &index_data,
2890 &IndexCB,sizeof(IndexCB),
2892 if (index_data.fail_for_error)
2895 clang_disposeTranslationUnit(TU);
2899 static int index_file(int argc, const char **argv, int full) {
2900 const char *check_prefix;
2902 CXIndexAction idxAction;
2903 ImportedASTFilesData *importedASTs;
2908 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2909 check_prefix = argv[0] + strlen("-check-prefix=");
2915 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2916 /* displayDiagnostics=*/1))) {
2917 fprintf(stderr, "Could not create Index\n");
2920 idxAction = clang_IndexAction_create(Idx);
2923 importedASTs = importedASTs_create();
2925 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
2931 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
2932 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
2933 importedASTs, check_prefix);
2938 importedASTs_dispose(importedASTs);
2939 clang_IndexAction_dispose(idxAction);
2940 clang_disposeIndex(Idx);
2944 static int index_tu(int argc, const char **argv) {
2945 const char *check_prefix;
2947 CXIndexAction idxAction;
2952 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2953 check_prefix = argv[0] + strlen("-check-prefix=");
2959 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2960 /* displayDiagnostics=*/1))) {
2961 fprintf(stderr, "Could not create Index\n");
2964 idxAction = clang_IndexAction_create(Idx);
2966 result = index_ast_file(argv[0], Idx, idxAction,
2967 /*importedASTs=*/0, check_prefix);
2969 clang_IndexAction_dispose(idxAction);
2970 clang_disposeIndex(Idx);
2974 static int index_compile_db(int argc, const char **argv) {
2975 const char *check_prefix;
2977 CXIndexAction idxAction;
2982 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2983 check_prefix = argv[0] + strlen("-check-prefix=");
2990 fprintf(stderr, "no compilation database\n");
2994 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2995 /* displayDiagnostics=*/1))) {
2996 fprintf(stderr, "Could not create Index\n");
2999 idxAction = clang_IndexAction_create(Idx);
3002 const char *database = argv[0];
3003 CXCompilationDatabase db = 0;
3004 CXCompileCommands CCmds = 0;
3005 CXCompileCommand CCmd;
3006 CXCompilationDatabase_Error ec;
3008 #define MAX_COMPILE_ARGS 512
3009 CXString cxargs[MAX_COMPILE_ARGS];
3010 const char *args[MAX_COMPILE_ARGS];
3014 int i, a, numCmds, numArgs;
3016 len = strlen(database);
3017 tmp = (char *) malloc(len+1);
3018 memcpy(tmp, database, len+1);
3019 buildDir = dirname(tmp);
3021 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3025 if (ec!=CXCompilationDatabase_NoError) {
3026 printf("unexpected error %d code while loading compilation database\n", ec);
3031 if (chdir(buildDir) != 0) {
3032 printf("Could not chdir to %s\n", buildDir);
3037 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
3039 printf("compilation db is empty\n");
3044 numCmds = clang_CompileCommands_getSize(CCmds);
3047 fprintf(stderr, "should not get an empty compileCommand set\n");
3052 for (i=0; i<numCmds && errorCode == 0; ++i) {
3053 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3055 wd = clang_CompileCommand_getDirectory(CCmd);
3056 if (chdir(clang_getCString(wd)) != 0) {
3057 printf("Could not chdir to %s\n", clang_getCString(wd));
3061 clang_disposeString(wd);
3063 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3064 if (numArgs > MAX_COMPILE_ARGS){
3065 fprintf(stderr, "got more compile arguments than maximum\n");
3069 for (a=0; a<numArgs; ++a) {
3070 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3071 args[a] = clang_getCString(cxargs[a]);
3074 errorCode = index_compile_args(numArgs, args, idxAction,
3075 /*importedASTs=*/0, check_prefix);
3077 for (a=0; a<numArgs; ++a)
3078 clang_disposeString(cxargs[a]);
3081 printf("database loading failed with error code %d.\n", ec);
3086 clang_CompileCommands_dispose(CCmds);
3087 clang_CompilationDatabase_dispose(db);
3092 clang_IndexAction_dispose(idxAction);
3093 clang_disposeIndex(Idx);
3097 int perform_token_annotation(int argc, const char **argv) {
3098 const char *input = argv[1];
3100 unsigned line, second_line;
3101 unsigned column, second_column;
3103 CXTranslationUnit TU = 0;
3105 struct CXUnsavedFile *unsaved_files = 0;
3106 int num_unsaved_files = 0;
3108 unsigned num_tokens;
3109 CXSourceRange range;
3110 CXSourceLocation startLoc, endLoc;
3112 CXCursor *cursors = 0;
3115 input += strlen("-test-annotate-tokens=");
3116 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3117 &second_line, &second_column)))
3120 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3125 CIdx = clang_createIndex(0, 1);
3126 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
3127 argv + num_unsaved_files + 2,
3128 argc - num_unsaved_files - 3,
3131 getDefaultParsingOptions());
3133 fprintf(stderr, "unable to parse input\n");
3134 clang_disposeIndex(CIdx);
3136 free_remapped_files(unsaved_files, num_unsaved_files);
3141 if (checkForErrors(TU) != 0) {
3146 if (getenv("CINDEXTEST_EDITING")) {
3147 for (i = 0; i < 5; ++i) {
3148 if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3149 clang_defaultReparseOptions(TU))) {
3150 fprintf(stderr, "Unable to reparse translation unit!\n");
3157 if (checkForErrors(TU) != 0) {
3162 file = clang_getFile(TU, filename);
3164 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3169 startLoc = clang_getLocation(TU, file, line, column);
3170 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
3171 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
3177 endLoc = clang_getLocation(TU, file, second_line, second_column);
3178 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
3179 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
3180 second_line, second_column);
3185 range = clang_getRange(startLoc, endLoc);
3186 clang_tokenize(TU, range, &tokens, &num_tokens);
3188 if (checkForErrors(TU) != 0) {
3193 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3194 clang_annotateTokens(TU, tokens, num_tokens, cursors);
3196 if (checkForErrors(TU) != 0) {
3201 for (i = 0; i != num_tokens; ++i) {
3202 const char *kind = "<unknown>";
3203 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3204 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
3205 unsigned start_line, start_column, end_line, end_column;
3207 switch (clang_getTokenKind(tokens[i])) {
3208 case CXToken_Punctuation: kind = "Punctuation"; break;
3209 case CXToken_Keyword: kind = "Keyword"; break;
3210 case CXToken_Identifier: kind = "Identifier"; break;
3211 case CXToken_Literal: kind = "Literal"; break;
3212 case CXToken_Comment: kind = "Comment"; break;
3214 clang_getSpellingLocation(clang_getRangeStart(extent),
3215 0, &start_line, &start_column, 0);
3216 clang_getSpellingLocation(clang_getRangeEnd(extent),
3217 0, &end_line, &end_column, 0);
3218 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
3219 clang_disposeString(spelling);
3220 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3221 if (!clang_isInvalid(cursors[i].kind)) {
3223 PrintCursor(cursors[i], NULL);
3228 clang_disposeTokens(TU, tokens, num_tokens);
3231 PrintDiagnostics(TU);
3232 clang_disposeTranslationUnit(TU);
3233 clang_disposeIndex(CIdx);
3235 free_remapped_files(unsaved_files, num_unsaved_files);
3240 perform_test_compilation_db(const char *database, int argc, const char **argv) {
3241 CXCompilationDatabase db;
3242 CXCompileCommands CCmds;
3243 CXCompileCommand CCmd;
3244 CXCompilationDatabase_Error ec;
3251 int i, j, a, numCmds, numArgs;
3253 len = strlen(database);
3254 tmp = (char *) malloc(len+1);
3255 memcpy(tmp, database, len+1);
3256 buildDir = dirname(tmp);
3258 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3262 if (ec!=CXCompilationDatabase_NoError) {
3263 printf("unexpected error %d code while loading compilation database\n", ec);
3268 for (i=0; i<argc && errorCode==0; ) {
3269 if (strcmp(argv[i],"lookup")==0){
3270 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
3273 printf("file %s not found in compilation db\n", argv[i+1]);
3278 numCmds = clang_CompileCommands_getSize(CCmds);
3281 fprintf(stderr, "should not get an empty compileCommand set for file"
3282 " '%s'\n", argv[i+1]);
3287 for (j=0; j<numCmds; ++j) {
3288 CCmd = clang_CompileCommands_getCommand(CCmds, j);
3290 wd = clang_CompileCommand_getDirectory(CCmd);
3291 printf("workdir:'%s'", clang_getCString(wd));
3292 clang_disposeString(wd);
3294 printf(" cmdline:'");
3295 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3296 for (a=0; a<numArgs; ++a) {
3298 arg = clang_CompileCommand_getArg(CCmd, a);
3299 printf("%s", clang_getCString(arg));
3300 clang_disposeString(arg);
3305 clang_CompileCommands_dispose(CCmds);
3310 clang_CompilationDatabase_dispose(db);
3312 printf("database loading failed with error code %d.\n", ec);
3322 /******************************************************************************/
3324 /******************************************************************************/
3326 static int insufficient_usr(const char *kind, const char *usage) {
3327 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3331 static unsigned isUSR(const char *s) {
3332 return s[0] == 'c' && s[1] == ':';
3335 static int not_usr(const char *s, const char *arg) {
3336 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3340 static void print_usr(CXString usr) {
3341 const char *s = clang_getCString(usr);
3343 clang_disposeString(usr);
3346 static void display_usrs() {
3347 fprintf(stderr, "-print-usrs options:\n"
3348 " ObjCCategory <class name> <category name>\n"
3349 " ObjCClass <class name>\n"
3350 " ObjCIvar <ivar name> <class USR>\n"
3351 " ObjCMethod <selector> [0=class method|1=instance method] "
3353 " ObjCProperty <property name> <class USR>\n"
3354 " ObjCProtocol <protocol name>\n");
3357 int print_usrs(const char **I, const char **E) {
3359 const char *kind = *I;
3360 unsigned len = strlen(kind);
3363 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3365 return insufficient_usr(kind, "<ivar name> <class USR>");
3367 return not_usr("<class USR>", I[2]);
3370 x.data = (void*) I[2];
3371 x.private_flags = 0;
3372 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3380 if (memcmp(kind, "ObjCClass", 9) == 0) {
3382 return insufficient_usr(kind, "<class name>");
3383 print_usr(clang_constructUSR_ObjCClass(I[1]));
3389 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3391 return insufficient_usr(kind, "<method selector> "
3392 "[0=class method|1=instance method] <class USR>");
3394 return not_usr("<class USR>", I[3]);
3397 x.data = (void*) I[3];
3398 x.private_flags = 0;
3399 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3406 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3408 return insufficient_usr(kind, "<class name> <category name>");
3409 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3413 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3415 return insufficient_usr(kind, "<protocol name>");
3416 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3420 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3422 return insufficient_usr(kind, "<property name> <class USR>");
3424 return not_usr("<class USR>", I[2]);
3427 x.data = (void*) I[2];
3428 x.private_flags = 0;
3429 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3442 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3449 int print_usrs_file(const char *file_name) {
3451 const char *args[128];
3452 unsigned numChars = 0;
3454 FILE *fp = fopen(file_name, "r");
3456 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3460 /* This code is not really all that safe, but it works fine for testing. */
3470 line[numChars] = '\0';
3473 if (line[0] == '/' && line[1] == '/')
3476 s = strtok(line, " ");
3482 if (print_usrs(&args[0], &args[i]))
3486 line[numChars++] = c;
3493 /******************************************************************************/
3494 /* Command line processing. */
3495 /******************************************************************************/
3496 int write_pch_file(const char *filename, int argc, const char *argv[]) {
3498 CXTranslationUnit TU;
3499 struct CXUnsavedFile *unsaved_files = 0;
3500 int num_unsaved_files = 0;
3503 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
3505 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3506 clang_disposeIndex(Idx);
3510 TU = clang_parseTranslationUnit(Idx, 0,
3511 argv + num_unsaved_files,
3512 argc - num_unsaved_files,
3515 CXTranslationUnit_Incomplete |
3516 CXTranslationUnit_DetailedPreprocessingRecord|
3517 CXTranslationUnit_ForSerialization);
3519 fprintf(stderr, "Unable to load translation unit!\n");
3520 free_remapped_files(unsaved_files, num_unsaved_files);
3521 clang_disposeIndex(Idx);
3525 switch (clang_saveTranslationUnit(TU, filename,
3526 clang_defaultSaveOptions(TU))) {
3527 case CXSaveError_None:
3530 case CXSaveError_TranslationErrors:
3531 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3536 case CXSaveError_InvalidTU:
3537 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3542 case CXSaveError_Unknown:
3544 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3549 clang_disposeTranslationUnit(TU);
3550 free_remapped_files(unsaved_files, num_unsaved_files);
3551 clang_disposeIndex(Idx);
3555 /******************************************************************************/
3556 /* Serialized diagnostics. */
3557 /******************************************************************************/
3559 static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3561 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3562 case CXLoadDiag_None: break;
3563 case CXLoadDiag_Unknown: return "Unknown";
3564 case CXLoadDiag_InvalidFile: return "Invalid File";
3569 static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3571 case CXDiagnostic_Note: return "note";
3572 case CXDiagnostic_Error: return "error";
3573 case CXDiagnostic_Fatal: return "fatal";
3574 case CXDiagnostic_Ignored: return "ignored";
3575 case CXDiagnostic_Warning: return "warning";
3580 static void printIndent(unsigned indent) {
3583 fprintf(stderr, "+");
3585 while (indent > 0) {
3586 fprintf(stderr, "-");
3591 static void printLocation(CXSourceLocation L) {
3594 unsigned line, column, offset;
3596 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3597 FileName = clang_getFileName(File);
3599 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3600 clang_disposeString(FileName);
3603 static void printRanges(CXDiagnostic D, unsigned indent) {
3604 unsigned i, n = clang_getDiagnosticNumRanges(D);
3606 for (i = 0; i < n; ++i) {
3607 CXSourceLocation Start, End;
3608 CXSourceRange SR = clang_getDiagnosticRange(D, i);
3609 Start = clang_getRangeStart(SR);
3610 End = clang_getRangeEnd(SR);
3612 printIndent(indent);
3613 fprintf(stderr, "Range: ");
3614 printLocation(Start);
3615 fprintf(stderr, " ");
3617 fprintf(stderr, "\n");
3621 static void printFixIts(CXDiagnostic D, unsigned indent) {
3622 unsigned i, n = clang_getDiagnosticNumFixIts(D);
3623 fprintf(stderr, "Number FIXITs = %d\n", n);
3624 for (i = 0 ; i < n; ++i) {
3625 CXSourceRange ReplacementRange;
3627 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3629 printIndent(indent);
3630 fprintf(stderr, "FIXIT: (");
3631 printLocation(clang_getRangeStart(ReplacementRange));
3632 fprintf(stderr, " - ");
3633 printLocation(clang_getRangeEnd(ReplacementRange));
3634 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3635 clang_disposeString(text);
3639 static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
3645 n = clang_getNumDiagnosticsInSet(Diags);
3646 for (i = 0; i < n; ++i) {
3647 CXSourceLocation DiagLoc;
3650 CXString FileName, DiagSpelling, DiagOption, DiagCat;
3651 unsigned line, column, offset;
3652 const char *DiagOptionStr = 0, *DiagCatStr = 0;
3654 D = clang_getDiagnosticInSet(Diags, i);
3655 DiagLoc = clang_getDiagnosticLocation(D);
3656 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3657 FileName = clang_getFileName(File);
3658 DiagSpelling = clang_getDiagnosticSpelling(D);
3660 printIndent(indent);
3662 fprintf(stderr, "%s:%d:%d: %s: %s",
3663 clang_getCString(FileName),
3666 getSeverityString(clang_getDiagnosticSeverity(D)),
3667 clang_getCString(DiagSpelling));
3669 DiagOption = clang_getDiagnosticOption(D, 0);
3670 DiagOptionStr = clang_getCString(DiagOption);
3671 if (DiagOptionStr) {
3672 fprintf(stderr, " [%s]", DiagOptionStr);
3675 DiagCat = clang_getDiagnosticCategoryText(D);
3676 DiagCatStr = clang_getCString(DiagCat);
3678 fprintf(stderr, " [%s]", DiagCatStr);
3681 fprintf(stderr, "\n");
3683 printRanges(D, indent);
3684 printFixIts(D, indent);
3686 /* Print subdiagnostics. */
3687 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3689 clang_disposeString(FileName);
3690 clang_disposeString(DiagSpelling);
3691 clang_disposeString(DiagOption);
3695 static int read_diagnostics(const char *filename) {
3696 enum CXLoadDiag_Error error;
3697 CXString errorString;
3698 CXDiagnosticSet Diags = 0;
3700 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3702 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3703 getDiagnosticCodeStr(error),
3704 clang_getCString(errorString));
3705 clang_disposeString(errorString);
3709 printDiagnosticSet(Diags, 0);
3710 fprintf(stderr, "Number of diagnostics: %d\n",
3711 clang_getNumDiagnosticsInSet(Diags));
3712 clang_disposeDiagnosticSet(Diags);
3716 /******************************************************************************/
3717 /* Command line processing. */
3718 /******************************************************************************/
3720 static CXCursorVisitor GetVisitor(const char *s) {
3722 return FilteredPrintingVisitor;
3723 if (strcmp(s, "-usrs") == 0)
3725 if (strncmp(s, "-memory-usage", 13) == 0)
3726 return GetVisitor(s + 13);
3730 static void print_usage(void) {
3732 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
3733 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
3734 " c-index-test -cursor-at=<site> <compiler arguments>\n"
3735 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
3736 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
3738 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
3739 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
3740 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
3741 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
3742 " c-index-test -test-file-scan <AST file> <source file> "
3743 "[FileCheck prefix]\n");
3745 " c-index-test -test-load-tu <AST file> <symbol filter> "
3746 "[FileCheck prefix]\n"
3747 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
3748 "[FileCheck prefix]\n"
3749 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
3751 " c-index-test -test-load-source-memory-usage "
3752 "<symbol filter> {<args>}*\n"
3753 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
3755 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
3756 " c-index-test -test-load-source-usrs-memory-usage "
3757 "<symbol filter> {<args>}*\n"
3758 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
3759 " c-index-test -test-inclusion-stack-source {<args>}*\n"
3760 " c-index-test -test-inclusion-stack-tu <AST file>\n");
3762 " c-index-test -test-print-linkage-source {<args>}*\n"
3763 " c-index-test -test-print-type {<args>}*\n"
3764 " c-index-test -test-print-type-size {<args>}*\n"
3765 " c-index-test -test-print-bitwidth {<args>}*\n"
3766 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
3767 " c-index-test -print-usr-file <file>\n"
3768 " c-index-test -write-pch <file> <compiler arguments>\n");
3770 " c-index-test -compilation-db [lookup <filename>] database\n");
3772 " c-index-test -read-diagnostics <file>\n\n");
3774 " <symbol filter> values:\n%s",
3775 " all - load all symbols, including those from PCH\n"
3776 " local - load all symbols except those in PCH\n"
3777 " category - only load ObjC categories (non-PCH)\n"
3778 " interface - only load ObjC interfaces (non-PCH)\n"
3779 " protocol - only load ObjC protocols (non-PCH)\n"
3780 " function - only load functions (non-PCH)\n"
3781 " typedef - only load typdefs (non-PCH)\n"
3782 " scan-function - scan function bodies (non-PCH)\n\n");
3787 int cindextest_main(int argc, const char **argv) {
3788 clang_enableStackTraces();
3789 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
3790 return read_diagnostics(argv[2]);
3791 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
3792 return perform_code_completion(argc, argv, 0);
3793 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
3794 return perform_code_completion(argc, argv, 1);
3795 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
3796 return inspect_cursor_at(argc, argv);
3797 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
3798 return find_file_refs_at(argc, argv);
3799 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
3800 return find_file_includes_in(argc, argv);
3801 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
3802 return index_file(argc - 2, argv + 2, /*full=*/0);
3803 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
3804 return index_file(argc - 2, argv + 2, /*full=*/1);
3805 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
3806 return index_tu(argc - 2, argv + 2);
3807 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
3808 return index_compile_db(argc - 2, argv + 2);
3809 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
3810 CXCursorVisitor I = GetVisitor(argv[1] + 13);
3812 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
3815 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
3816 CXCursorVisitor I = GetVisitor(argv[1] + 25);
3818 int trials = atoi(argv[2]);
3819 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
3823 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
3824 CXCursorVisitor I = GetVisitor(argv[1] + 17);
3826 PostVisitTU postVisit = 0;
3827 if (strstr(argv[1], "-memory-usage"))
3828 postVisit = PrintMemoryUsage;
3831 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
3834 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
3835 return perform_file_scan(argv[2], argv[3],
3836 argc >= 5 ? argv[4] : 0);
3837 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
3838 return perform_token_annotation(argc, argv);
3839 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
3840 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
3841 PrintInclusionStack);
3842 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
3843 return perform_test_load_tu(argv[2], "all", NULL, NULL,
3844 PrintInclusionStack);
3845 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
3846 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
3848 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
3849 return perform_test_load_source(argc - 2, argv + 2, "all",
3851 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
3852 return perform_test_load_source(argc - 2, argv + 2, "all",
3854 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
3855 return perform_test_load_source(argc - 2, argv + 2, "all",
3857 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
3859 return print_usrs(argv + 2, argv + argc);
3865 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
3866 return print_usrs_file(argv[2]);
3867 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
3868 return write_pch_file(argv[2], argc - 3, argv + 3);
3869 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
3870 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
3878 /* We intentionally run in a separate thread to ensure we at least minimal
3879 * testing of a multithreaded environment (for example, having a reduced stack
3882 typedef struct thread_info {
3887 void thread_runner(void *client_data_v) {
3888 thread_info *client_data = client_data_v;
3889 client_data->result = cindextest_main(client_data->argc, client_data->argv);
3891 fflush(stdout); /* stdout is not flushed on Cygwin. */
3895 int main(int argc, const char **argv) {
3896 thread_info client_data;
3898 #ifdef CLANG_HAVE_LIBXML
3902 if (getenv("CINDEXTEST_NOTHREADS"))
3903 return cindextest_main(argc, argv);
3905 client_data.argc = argc;
3906 client_data.argv = argv;
3907 clang_executeOnThread(thread_runner, &client_data, 0);
3908 return client_data.result;