]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tools/c-index-test/c-index-test.c
Vendor import of clang tags/RELEASE_33/final r183502 (effectively, 3.3
[FreeBSD/FreeBSD.git] / tools / c-index-test / c-index-test.c
1 /* c-index-test.c */
2
3 #include "clang-c/Index.h"
4 #include "clang-c/CXCompilationDatabase.h"
5 #include "llvm/Config/config.h"
6 #include <ctype.h>
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <assert.h>
11
12 #ifdef CLANG_HAVE_LIBXML
13 #include <libxml/parser.h>
14 #include <libxml/relaxng.h>
15 #include <libxml/xmlerror.h>
16 #endif
17
18 #ifdef _WIN32
19 #  include <direct.h>
20 #else
21 #  include <unistd.h>
22 #endif
23
24 /******************************************************************************/
25 /* Utility functions.                                                         */
26 /******************************************************************************/
27
28 #ifdef _MSC_VER
29 char *basename(const char* path)
30 {
31     char* base1 = (char*)strrchr(path, '/');
32     char* base2 = (char*)strrchr(path, '\\');
33     if (base1 && base2)
34         return((base1 > base2) ? base1 + 1 : base2 + 1);
35     else if (base1)
36         return(base1 + 1);
37     else if (base2)
38         return(base2 + 1);
39
40     return((char*)path);
41 }
42 char *dirname(char* path)
43 {
44     char* base1 = (char*)strrchr(path, '/');
45     char* base2 = (char*)strrchr(path, '\\');
46     if (base1 && base2)
47         if (base1 > base2)
48           *base1 = 0;
49         else
50           *base2 = 0;
51     else if (base1)
52         *base1 = 0;
53     else if (base2)
54         *base2 = 0;
55
56     return path;
57 }
58 #else
59 extern char *basename(const char *);
60 extern char *dirname(char *);
61 #endif
62
63 /** \brief Return the default parsing options. */
64 static unsigned getDefaultParsingOptions() {
65   unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
66
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;
77   
78   return options;
79 }
80
81 static int checkForErrors(CXTranslationUnit TU);
82
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);
87 }
88
89 static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
90                                       CXTranslationUnit *TU) {
91
92   *TU = clang_createTranslationUnit(Idx, file);
93   if (!*TU) {
94     fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
95     return 0;
96   }
97   return 1;
98 }
99
100 void free_remapped_files(struct CXUnsavedFile *unsaved_files,
101                          int num_unsaved_files) {
102   int i;
103   for (i = 0; i != num_unsaved_files; ++i) {
104     free((char *)unsaved_files[i].Filename);
105     free((char *)unsaved_files[i].Contents);
106   }
107   free(unsaved_files);
108 }
109
110 int parse_remapped_files(int argc, const char **argv, int start_arg,
111                          struct CXUnsavedFile **unsaved_files,
112                          int *num_unsaved_files) {
113   int i;
114   int arg;
115   int prefix_len = strlen("-remap-file=");
116   *unsaved_files = 0;
117   *num_unsaved_files = 0;
118
119   /* Count the number of remapped files. */
120   for (arg = start_arg; arg < argc; ++arg) {
121     if (strncmp(argv[arg], "-remap-file=", prefix_len))
122       break;
123
124     ++*num_unsaved_files;
125   }
126
127   if (*num_unsaved_files == 0)
128     return 0;
129
130   *unsaved_files
131     = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
132                                      *num_unsaved_files);
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;
136     int filename_len;
137     char *filename;
138     char *contents;
139     FILE *to_file;
140     const char *semi = strchr(arg_string, ';');
141     if (!semi) {
142       fprintf(stderr,
143               "error: -remap-file=from;to argument is missing semicolon\n");
144       free_remapped_files(*unsaved_files, i);
145       *unsaved_files = 0;
146       *num_unsaved_files = 0;
147       return -1;
148     }
149
150     /* Open the file that we're remapping to. */
151     to_file = fopen(semi + 1, "rb");
152     if (!to_file) {
153       fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
154               semi + 1);
155       free_remapped_files(*unsaved_files, i);
156       *unsaved_files = 0;
157       *num_unsaved_files = 0;
158       return -1;
159     }
160
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);
165
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);
171       fclose(to_file);
172       free_remapped_files(*unsaved_files, i);
173       free(contents);
174       *unsaved_files = 0;
175       *num_unsaved_files = 0;
176       return -1;
177     }
178     contents[unsaved->Length] = 0;
179     unsaved->Contents = contents;
180
181     /* Close the file. */
182     fclose(to_file);
183
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;
190   }
191
192   return 0;
193 }
194
195 static const char *parse_comments_schema(int argc, const char **argv) {
196   const char *CommentsSchemaArg = "-comments-xml-schema=";
197   const char *CommentSchemaFile = NULL;
198
199   if (argc == 0)
200     return CommentSchemaFile;
201
202   if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
203     CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
204
205   return CommentSchemaFile;
206 }
207
208 /******************************************************************************/
209 /* Pretty-printing.                                                           */
210 /******************************************************************************/
211
212 static const char *FileCheckPrefix = "CHECK";
213
214 static void PrintCString(const char *CStr) {
215   if (CStr != NULL && CStr[0] != '\0') {
216     for ( ; *CStr; ++CStr) {
217       const char C = *CStr;
218       switch (C) {
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;
225       }
226     }
227   }
228 }
229
230 static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
231   printf(" %s=[", Prefix);
232   PrintCString(CStr);
233   printf("]");
234 }
235
236 static void PrintCXStringAndDispose(CXString Str) {
237   PrintCString(clang_getCString(Str));
238   clang_disposeString(Str);
239 }
240
241 static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
242   PrintCStringWithPrefix(Prefix, clang_getCString(Str));
243 }
244
245 static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
246                                               CXString Str) {
247   PrintCStringWithPrefix(Prefix, clang_getCString(Str));
248   clang_disposeString(Str);
249 }
250
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;
254
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)
260     return;
261
262   if (str)
263     printf(" %s=", str);
264   PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
265 }
266
267 int want_display_name = 0;
268
269 static void printVersion(const char *Prefix, CXVersion Version) {
270   if (Version.Major < 0)
271     return;
272   printf("%s%d", Prefix, Version.Major);
273   
274   if (Version.Minor < 0)
275     return;
276   printf(".%d", Version.Minor);
277
278   if (Version.Subminor < 0)
279     return;
280   printf(".%d", Version.Subminor);
281 }
282
283 struct CommentASTDumpingContext {
284   int IndentLevel;
285 };
286
287 static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
288                                   CXComment Comment) {
289   unsigned i;
290   unsigned e;
291   enum CXCommentKind Kind = clang_Comment_getKind(Comment);
292
293   Ctx->IndentLevel++;
294   for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
295     printf("  ");
296
297   printf("(");
298   switch (Kind) {
299   case CXComment_Null:
300     printf("CXComment_Null");
301     break;
302   case CXComment_Text:
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");
310     break;
311   case CXComment_InlineCommand:
312     printf("CXComment_InlineCommand");
313     PrintCXStringWithPrefixAndDispose(
314         "CommandName",
315         clang_InlineCommandComment_getCommandName(Comment));
316     switch (clang_InlineCommandComment_getRenderKind(Comment)) {
317     case CXCommentInlineCommandRenderKind_Normal:
318       printf(" RenderNormal");
319       break;
320     case CXCommentInlineCommandRenderKind_Bold:
321       printf(" RenderBold");
322       break;
323     case CXCommentInlineCommandRenderKind_Monospaced:
324       printf(" RenderMonospaced");
325       break;
326     case CXCommentInlineCommandRenderKind_Emphasized:
327       printf(" RenderEmphasized");
328       break;
329     }
330     for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
331          i != e; ++i) {
332       printf(" Arg[%u]=", i);
333       PrintCXStringAndDispose(
334           clang_InlineCommandComment_getArgText(Comment, i));
335     }
336     if (clang_InlineContentComment_hasTrailingNewline(Comment))
337       printf(" HasTrailingNewline");
338     break;
339   case CXComment_HTMLStartTag: {
340     unsigned NumAttrs;
341     printf("CXComment_HTMLStartTag");
342     PrintCXStringWithPrefixAndDispose(
343         "Name",
344         clang_HTMLTagComment_getTagName(Comment));
345     NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
346     if (NumAttrs != 0) {
347       printf(" Attrs:");
348       for (i = 0; i != NumAttrs; ++i) {
349         printf(" ");
350         PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
351         printf("=");
352         PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
353       }
354     }
355     if (clang_HTMLStartTagComment_isSelfClosing(Comment))
356       printf(" SelfClosing");
357     if (clang_InlineContentComment_hasTrailingNewline(Comment))
358       printf(" HasTrailingNewline");
359     break;
360   }
361   case CXComment_HTMLEndTag:
362     printf("CXComment_HTMLEndTag");
363     PrintCXStringWithPrefixAndDispose(
364         "Name",
365         clang_HTMLTagComment_getTagName(Comment));
366     if (clang_InlineContentComment_hasTrailingNewline(Comment))
367       printf(" HasTrailingNewline");
368     break;
369   case CXComment_Paragraph:
370     printf("CXComment_Paragraph");
371     if (clang_Comment_isWhitespace(Comment))
372       printf(" IsWhitespace");
373     break;
374   case CXComment_BlockCommand:
375     printf("CXComment_BlockCommand");
376     PrintCXStringWithPrefixAndDispose(
377         "CommandName",
378         clang_BlockCommandComment_getCommandName(Comment));
379     for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
380          i != e; ++i) {
381       printf(" Arg[%u]=", i);
382       PrintCXStringAndDispose(
383           clang_BlockCommandComment_getArgText(Comment, i));
384     }
385     break;
386   case CXComment_ParamCommand:
387     printf("CXComment_ParamCommand");
388     switch (clang_ParamCommandComment_getDirection(Comment)) {
389     case CXCommentParamPassDirection_In:
390       printf(" in");
391       break;
392     case CXCommentParamPassDirection_Out:
393       printf(" out");
394       break;
395     case CXCommentParamPassDirection_InOut:
396       printf(" in,out");
397       break;
398     }
399     if (clang_ParamCommandComment_isDirectionExplicit(Comment))
400       printf(" explicitly");
401     else
402       printf(" implicitly");
403     PrintCXStringWithPrefixAndDispose(
404         "ParamName",
405         clang_ParamCommandComment_getParamName(Comment));
406     if (clang_ParamCommandComment_isParamIndexValid(Comment))
407       printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
408     else
409       printf(" ParamIndex=Invalid");
410     break;
411   case CXComment_TParamCommand:
412     printf("CXComment_TParamCommand");
413     PrintCXStringWithPrefixAndDispose(
414         "ParamName",
415         clang_TParamCommandComment_getParamName(Comment));
416     if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
417       printf(" ParamPosition={");
418       for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
419            i != e; ++i) {
420         printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
421         if (i != e - 1)
422           printf(", ");
423       }
424       printf("}");
425     } else
426       printf(" ParamPosition=Invalid");
427     break;
428   case CXComment_VerbatimBlockCommand:
429     printf("CXComment_VerbatimBlockCommand");
430     PrintCXStringWithPrefixAndDispose(
431         "CommandName",
432         clang_BlockCommandComment_getCommandName(Comment));
433     break;
434   case CXComment_VerbatimBlockLine:
435     printf("CXComment_VerbatimBlockLine");
436     PrintCXStringWithPrefixAndDispose(
437         "Text",
438         clang_VerbatimBlockLineComment_getText(Comment));
439     break;
440   case CXComment_VerbatimLine:
441     printf("CXComment_VerbatimLine");
442     PrintCXStringWithPrefixAndDispose(
443         "Text",
444         clang_VerbatimLineComment_getText(Comment));
445     break;
446   case CXComment_FullComment:
447     printf("CXComment_FullComment");
448     break;
449   }
450   if (Kind != CXComment_Null) {
451     const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
452     unsigned i;
453     for (i = 0; i != NumChildren; ++i) {
454       printf("\n// %s: ", FileCheckPrefix);
455       DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
456     }
457   }
458   printf(")");
459   Ctx->IndentLevel--;
460 }
461
462 static void DumpCXComment(CXComment Comment) {
463   struct CommentASTDumpingContext Ctx;
464   Ctx.IndentLevel = 1;
465   printf("\n// %s:  CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
466   DumpCXCommentInternal(&Ctx, Comment);
467   printf("]");
468 }
469
470 typedef struct {
471   const char *CommentSchemaFile;
472 #ifdef CLANG_HAVE_LIBXML
473   xmlRelaxNGParserCtxtPtr RNGParser;
474   xmlRelaxNGPtr Schema;
475 #endif
476 } CommentXMLValidationData;
477
478 static void ValidateCommentXML(const char *Str,
479                                CommentXMLValidationData *ValidationData) {
480 #ifdef CLANG_HAVE_LIBXML
481   xmlDocPtr Doc;
482   xmlRelaxNGValidCtxtPtr ValidationCtxt;
483   int status;
484
485   if (!ValidationData || !ValidationData->CommentSchemaFile)
486     return;
487
488   if (!ValidationData->RNGParser) {
489     ValidationData->RNGParser =
490         xmlRelaxNGNewParserCtxt(ValidationData->CommentSchemaFile);
491     ValidationData->Schema = xmlRelaxNGParse(ValidationData->RNGParser);
492   }
493   if (!ValidationData->RNGParser) {
494     printf(" libXMLError");
495     return;
496   }
497
498   Doc = xmlParseDoc((const xmlChar *) Str);
499
500   if (!Doc) {
501     xmlErrorPtr Error = xmlGetLastError();
502     printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
503     return;
504   }
505
506   ValidationCtxt = xmlRelaxNGNewValidCtxt(ValidationData->Schema);
507   status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
508   if (!status)
509     printf(" CommentXMLValid");
510   else if (status > 0) {
511     xmlErrorPtr Error = xmlGetLastError();
512     printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
513   } else
514     printf(" libXMLError");
515
516   xmlRelaxNGFreeValidCtxt(ValidationCtxt);
517   xmlFreeDoc(Doc);
518 #endif
519 }
520
521 static void PrintCursorComments(CXCursor Cursor,
522                                 CommentXMLValidationData *ValidationData) {
523   {
524     CXString RawComment;
525     const char *RawCommentCString;
526     CXString BriefComment;
527     const char *BriefCommentCString;
528
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");
534
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);
540     }
541     clang_disposeString(RawComment);
542   }
543
544   {
545     CXComment Comment = clang_Cursor_getParsedComment(Cursor);
546     if (clang_Comment_getKind(Comment) != CXComment_Null) {
547       PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
548                                         clang_FullComment_getAsHTML(Comment));
549       {
550         CXString XML;
551         XML = clang_FullComment_getAsXML(Comment);
552         PrintCXStringWithPrefix("FullCommentAsXML", XML);
553         ValidateCommentXML(clang_getCString(XML), ValidationData);
554         clang_disposeString(XML);
555       }
556
557       DumpCXComment(Comment);
558     }
559   }
560 }
561
562 typedef struct {
563   unsigned line;
564   unsigned col;
565 } LineCol;
566
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;
573 }
574
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);
582   }
583   else {
584     CXString string, ks;
585     CXCursor Referenced;
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;
599     int I;
600
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);
608
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);
613         printf("[");
614         for (I = 0; I != N; ++I) {
615           CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
616           CXSourceLocation Loc;
617           if (I)
618             printf(", ");
619           
620           Loc = clang_getCursorLocation(Ovl);
621           clang_getSpellingLocation(Loc, 0, &line, &column, 0);
622           printf("%d:%d", line, column);          
623         }
624         printf("]");
625       } else {
626         CXSourceLocation Loc = clang_getCursorLocation(Referenced);
627         clang_getSpellingLocation(Loc, 0, &line, &column, 0);
628         printf(":%d:%d", line, column);
629       }
630     }
631
632     if (clang_isCursorDefinition(Cursor))
633       printf(" (Definition)");
634     
635     switch (clang_getCursorAvailability(Cursor)) {
636       case CXAvailability_Available:
637         break;
638         
639       case CXAvailability_Deprecated:
640         printf(" (deprecated)");
641         break;
642         
643       case CXAvailability_NotAvailable:
644         printf(" (unavailable)");
645         break;
646
647       case CXAvailability_NotAccessible:
648         printf(" (inaccessible)");
649         break;
650     }
651     
652     NumPlatformAvailability
653       = clang_getCursorPlatformAvailability(Cursor,
654                                             &AlwaysDeprecated,
655                                             &DeprecatedMessage,
656                                             &AlwaysUnavailable,
657                                             &UnavailableMessage,
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));
665     } else {
666       for (I = 0; I != NumPlatformAvailability; ++I) {
667         if (I >= 2)
668           break;
669         
670         printf("  (%s", clang_getCString(PlatformAvailability[I].Platform));
671         if (PlatformAvailability[I].Unavailable)
672           printf(", unavailable");
673         else {
674           printVersion(", introduced=", PlatformAvailability[I].Introduced);
675           printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
676           printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
677         }
678         if (clang_getCString(PlatformAvailability[I].Message)[0])
679           printf(", message=\"%s\"",
680                  clang_getCString(PlatformAvailability[I].Message));
681         printf(")");
682       }
683     }
684     for (I = 0; I != NumPlatformAvailability; ++I) {
685       if (I >= 2)
686         break;
687       clang_disposeCXPlatformAvailability(PlatformAvailability + I);
688     }
689     
690     clang_disposeString(DeprecatedMessage);
691     clang_disposeString(UnavailableMessage);
692     
693     if (clang_CXXMethod_isStatic(Cursor))
694       printf(" (static)");
695     if (clang_CXXMethod_isVirtual(Cursor))
696       printf(" (virtual)");
697
698     if (clang_Cursor_isVariadic(Cursor))
699       printf(" (variadic)");
700     
701     if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
702       CXType T =
703         clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
704       CXString S = clang_getTypeKindSpelling(T.kind);
705       printf(" [IBOutletCollection=%s]", clang_getCString(S));
706       clang_disposeString(S);
707     }
708     
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;
713
714       switch (access) {
715         case CX_CXXInvalidAccessSpecifier:
716           accessStr = "invalid"; break;
717         case CX_CXXPublic:
718           accessStr = "public"; break;
719         case CX_CXXProtected:
720           accessStr = "protected"; break;
721         case CX_CXXPrivate:
722           accessStr = "private"; break;
723       }      
724       
725       printf(" [access=%s isVirtual=%s]", accessStr,
726              isVirtual ? "true" : "false");
727     }
728     
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);
737     }
738
739     clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
740     if (num_overridden) {      
741       unsigned I;
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;
750       }
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) {
754         if (I)
755           printf(", ");
756         printf("@%d:%d", lineCols[I].line, lineCols[I].col);
757       }
758       printf("]");
759       clang_disposeOverriddenCursors(overridden);
760     }
761     
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);
767       
768       if (clang_isFileMultipleIncludeGuarded(TU, File))
769         printf("  [multi-include guarded]");
770     }
771     
772     CursorExtent = clang_getCursorExtent(Cursor);
773     RefNameRange = clang_getCursorReferenceNameRange(Cursor, 
774                                                    CXNameRange_WantQualifier
775                                                  | CXNameRange_WantSinglePiece
776                                                  | CXNameRange_WantTemplateArgs,
777                                                      0);
778     if (!clang_equalRanges(CursorExtent, RefNameRange))
779       PrintRange(RefNameRange, "SingleRefName");
780     
781     for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
782       RefNameRange = clang_getCursorReferenceNameRange(Cursor, 
783                                                    CXNameRange_WantQualifier
784                                                  | CXNameRange_WantTemplateArgs,
785                                                        RefNameRangeNr);
786       if (clang_equalRanges(clang_getNullRange(), RefNameRange))
787         break;
788       if (!clang_equalRanges(CursorExtent, RefNameRange))
789         PrintRange(RefNameRange, "RefName");
790     }
791
792     PrintCursorComments(Cursor, ValidationData);
793
794     {
795       unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
796       if (PropAttrs != CXObjCPropertyAttr_noattr) {
797         printf(" [");
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);
812         printf("]");
813       }
814     }
815
816     {
817       unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
818       if (QT != CXObjCDeclQualifier_None) {
819         printf(" [");
820         #define PRINT_OBJC_QUAL(A) \
821           if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
822         PRINT_OBJC_QUAL(In);
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);
828         printf("]");
829       }
830     }
831   }
832 }
833
834 static const char* GetCursorSource(CXCursor Cursor) {
835   CXSourceLocation Loc = clang_getCursorLocation(Cursor);
836   CXString source;
837   CXFile file;
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>";
843   }
844   else {
845     const char *b = basename(clang_getCString(source));
846     clang_disposeString(source);
847     return b;
848   }
849 }
850
851 /******************************************************************************/
852 /* Callbacks.                                                                 */
853 /******************************************************************************/
854
855 typedef void (*PostVisitTU)(CXTranslationUnit);
856
857 void PrintDiagnostic(CXDiagnostic Diagnostic) {
858   FILE *out = stderr;
859   CXFile file;
860   CXString Msg;
861   unsigned display_opts = CXDiagnostic_DisplaySourceLocation
862     | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
863     | CXDiagnostic_DisplayOption;
864   unsigned i, num_fixits;
865
866   if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
867     return;
868
869   Msg = clang_formatDiagnostic(Diagnostic, display_opts);
870   fprintf(stderr, "%s\n", clang_getCString(Msg));
871   clang_disposeString(Msg);
872
873   clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
874                             &file, 0, 0, 0);
875   if (!file)
876     return;
877
878   num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
879   fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
880   for (i = 0; i != num_fixits; ++i) {
881     CXSourceRange range;
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,
888                               &start_column, 0);
889     clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
890     if (clang_equalLocations(start, end)) {
891       /* Insertion. */
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) {
896       /* Removal. */
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);
900         fprintf(out, "\n");
901       }
902     } else {
903       /* Replacement. */
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));
908       }
909       break;
910     }
911     clang_disposeString(insertion_text);
912   }
913 }
914
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);
921     if (ChildDiags)
922       PrintDiagnosticSet(ChildDiags);
923   }  
924 }
925
926 void PrintDiagnostics(CXTranslationUnit TU) {
927   CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
928   PrintDiagnosticSet(TUSet);
929   clang_disposeDiagnosticSet(TUSet);
930 }
931
932 void PrintMemoryUsage(CXTranslationUnit TU) {
933   unsigned long total = 0;
934   unsigned i = 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;
940     total += amount;
941     fprintf(stderr, "  %s : %ld bytes (%f MBytes)\n", name, amount,
942             ((double) amount)/(1024*1024));
943   }
944   fprintf(stderr, "  TOTAL = %ld bytes (%f MBytes)\n", total,
945           ((double) total)/(1024*1024));
946   clang_disposeCXTUResourceUsage(usage);  
947 }
948
949 /******************************************************************************/
950 /* Logic for testing traversal.                                               */
951 /******************************************************************************/
952
953 static void PrintCursorExtent(CXCursor C) {
954   CXSourceRange extent = clang_getCursorExtent(C);
955   PrintRange(extent, "Extent");
956 }
957
958 /* Data used by the visitors. */
959 typedef struct {
960   CXTranslationUnit TU;
961   enum CXCursorKind *Filter;
962   CommentXMLValidationData ValidationData;
963 } VisitorData;
964
965
966 enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
967                                                 CXCursor Parent,
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;
981
982       switch (access) {
983         case CX_CXXInvalidAccessSpecifier: break;
984         case CX_CXXPublic:
985           accessStr = "public"; break;
986         case CX_CXXProtected:
987           accessStr = "protected"; break;
988         case CX_CXXPrivate:
989           accessStr = "private"; break;
990       }
991
992       if (accessStr)
993         printf(" [access=%s]", accessStr);
994     }
995     printf("\n");
996     return CXChildVisit_Recurse;
997   }
998
999   return CXChildVisit_Continue;
1000 }
1001
1002 static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
1003                                                    CXCursor Parent,
1004                                                    CXClientData ClientData) {
1005   const char *startBuf, *endBuf;
1006   unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1007   CXCursor Ref;
1008   VisitorData *Data = (VisitorData *)ClientData;
1009
1010   if (Cursor.kind != CXCursor_FunctionDecl ||
1011       !clang_isCursorDefinition(Cursor))
1012     return CXChildVisit_Continue;
1013
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;
1020
1021   while (startBuf < endBuf) {
1022     CXSourceLocation Loc;
1023     CXFile file;
1024     CXString source;
1025
1026     if (*startBuf == '\n') {
1027       startBuf++;
1028       curLine++;
1029       curColumn = 1;
1030     } else if (*startBuf != '\t')
1031       curColumn++;
1032
1033     Loc = clang_getCursorLocation(Cursor);
1034     clang_getSpellingLocation(Loc, &file, 0, 0, 0);
1035
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);
1047         printf("\n");
1048       }
1049     }
1050     clang_disposeString(source);
1051     startBuf++;
1052   }
1053
1054   return CXChildVisit_Continue;
1055 }
1056
1057 /******************************************************************************/
1058 /* USR testing.                                                               */
1059 /******************************************************************************/
1060
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;
1070     }
1071     printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1072
1073     PrintCursorExtent(C);
1074     printf("\n");
1075     clang_disposeString(USR);
1076
1077     return CXChildVisit_Recurse;
1078   }
1079
1080   return CXChildVisit_Continue;
1081 }
1082
1083 /******************************************************************************/
1084 /* Inclusion stack testing.                                                   */
1085 /******************************************************************************/
1086
1087 void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1088                       unsigned includeStackLen, CXClientData data) {
1089
1090   unsigned i;
1091   CXString fname;
1092
1093   fname = clang_getFileName(includedFile);
1094   printf("file: %s\nincluded by:\n", clang_getCString(fname));
1095   clang_disposeString(fname);
1096
1097   for (i = 0; i < includeStackLen; ++i) {
1098     CXFile includingFile;
1099     unsigned line, column;
1100     clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1101                               &column, 0);
1102     fname = clang_getFileName(includingFile);
1103     printf("  %s:%d:%d\n", clang_getCString(fname), line, column);
1104     clang_disposeString(fname);
1105   }
1106   printf("\n");
1107 }
1108
1109 void PrintInclusionStack(CXTranslationUnit TU) {
1110   clang_getInclusions(TU, InclusionVisitor, NULL);
1111 }
1112
1113 /******************************************************************************/
1114 /* Linkage testing.                                                           */
1115 /******************************************************************************/
1116
1117 static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1118                                             CXClientData d) {
1119   const char *linkage = 0;
1120
1121   if (clang_isInvalid(clang_getCursorKind(cursor)))
1122     return CXChildVisit_Recurse;
1123
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;
1130   }
1131
1132   if (linkage) {
1133     PrintCursor(cursor, NULL);
1134     printf("linkage=%s\n", linkage);
1135   }
1136
1137   return CXChildVisit_Recurse;
1138 }
1139
1140 /******************************************************************************/
1141 /* Typekind testing.                                                          */
1142 /******************************************************************************/
1143
1144 static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1145   CXString TypeSpelling, TypeKindSpelling;
1146
1147   TypeSpelling = clang_getTypeSpelling(T);
1148   TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1149   printf(Format,
1150          clang_getCString(TypeSpelling),
1151          clang_getCString(TypeKindSpelling));
1152   clang_disposeString(TypeSpelling);
1153   clang_disposeString(TypeKindSpelling);
1154 }
1155
1156 static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1157                                          CXClientData d) {
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))
1163       printf(" const");
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. */
1169     {
1170       CXType CT = clang_getCanonicalType(T);
1171       if (!clang_equalTypes(T, CT)) {
1172         PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
1173       }
1174     }
1175     /* Print the return type if it exists. */
1176     {
1177       CXType RT = clang_getCursorResultType(cursor);
1178       if (RT.kind != CXType_Invalid) {
1179         PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
1180       }
1181     }
1182     /* Print the argument types if they exist. */
1183     {
1184       int numArgs = clang_Cursor_getNumArguments(cursor);
1185       if (numArgs != -1 && numArgs != 0) {
1186         int i;
1187         printf(" [args=");
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]");
1192           }
1193         }
1194         printf("]");
1195       }
1196     }
1197     /* Print if this is a non-POD type. */
1198     printf(" [isPOD=%d]", clang_isPODType(T));
1199
1200     printf("\n");
1201   }
1202   return CXChildVisit_Recurse;
1203 }
1204
1205 static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1206                                              CXClientData d) {
1207   CXType T;
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. */
1215   {
1216     long long Size = clang_Type_getSizeOf(T);
1217     if (Size >= 0 || Size < -1 ) {
1218       printf(" [sizeof=%lld]", Size);
1219     }
1220   }
1221   /* Print the type alignof if applicable. */
1222   {
1223     long long Align = clang_Type_getAlignOf(T);
1224     if (Align >= 0 || Align < -1) {
1225       printf(" [alignof=%lld]", Align);
1226     }
1227   }
1228   /* Print the record field offset if applicable. */
1229   {
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;
1235       Root = Parent = p;
1236       do {
1237         Root = Parent;
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. */
1243       {
1244         long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Root),
1245                                                   FieldName);
1246         printf(" [offsetof=%lld]", Offset);
1247       }
1248     }
1249   }
1250   /* Print if its a bitfield */
1251   {
1252     int IsBitfield = clang_Cursor_isBitField(cursor);
1253     if (IsBitfield)
1254       printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1255   }
1256   printf("\n");
1257   return CXChildVisit_Recurse;
1258 }
1259
1260 /******************************************************************************/
1261 /* Bitwidth testing.                                                          */
1262 /******************************************************************************/
1263
1264 static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1265                                              CXClientData d) {
1266   int Bitwidth;
1267   if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1268     return CXChildVisit_Recurse;
1269
1270   Bitwidth = clang_getFieldDeclBitWidth(cursor);
1271   if (Bitwidth >= 0) {
1272     PrintCursor(cursor, NULL);
1273     printf(" bitwidth=%d\n", Bitwidth);
1274   }
1275
1276   return CXChildVisit_Recurse;
1277 }
1278
1279 /******************************************************************************/
1280 /* Loading ASTs/source.                                                       */
1281 /******************************************************************************/
1282
1283 static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
1284                              const char *filter, const char *prefix,
1285                              CXCursorVisitor Visitor,
1286                              PostVisitTU PV,
1287                              const char *CommentSchemaFile) {
1288
1289   if (prefix)
1290     FileCheckPrefix = prefix;
1291
1292   if (Visitor) {
1293     enum CXCursorKind K = CXCursor_NotImplemented;
1294     enum CXCursorKind *ck = &K;
1295     VisitorData Data;
1296
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")) {
1301       ck = NULL;
1302       want_display_name = 1;
1303     }
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;
1311     else {
1312       fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1313       return 1;
1314     }
1315
1316     Data.TU = TU;
1317     Data.Filter = ck;
1318     Data.ValidationData.CommentSchemaFile = CommentSchemaFile;
1319 #ifdef CLANG_HAVE_LIBXML
1320     Data.ValidationData.RNGParser = NULL;
1321     Data.ValidationData.Schema = NULL;
1322 #endif
1323     clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
1324   }
1325
1326   if (PV)
1327     PV(TU);
1328
1329   PrintDiagnostics(TU);
1330   if (checkForErrors(TU) != 0) {
1331     clang_disposeTranslationUnit(TU);
1332     return -1;
1333   }
1334
1335   clang_disposeTranslationUnit(TU);
1336   return 0;
1337 }
1338
1339 int perform_test_load_tu(const char *file, const char *filter,
1340                          const char *prefix, CXCursorVisitor Visitor,
1341                          PostVisitTU PV) {
1342   CXIndex Idx;
1343   CXTranslationUnit TU;
1344   int result;
1345   Idx = clang_createIndex(/* excludeDeclsFromPCH */
1346                           !strcmp(filter, "local") ? 1 : 0,
1347                           /* displayDiagnostics=*/1);
1348
1349   if (!CreateTranslationUnit(Idx, file, &TU)) {
1350     clang_disposeIndex(Idx);
1351     return 1;
1352   }
1353
1354   result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
1355   clang_disposeIndex(Idx);
1356   return result;
1357 }
1358
1359 int perform_test_load_source(int argc, const char **argv,
1360                              const char *filter, CXCursorVisitor Visitor,
1361                              PostVisitTU PV) {
1362   CXIndex Idx;
1363   CXTranslationUnit TU;
1364   const char *CommentSchemaFile;
1365   struct CXUnsavedFile *unsaved_files = 0;
1366   int num_unsaved_files = 0;
1367   int result;
1368   
1369   Idx = clang_createIndex(/* excludeDeclsFromPCH */
1370                           (!strcmp(filter, "local") || 
1371                            !strcmp(filter, "local-display"))? 1 : 0,
1372                           /* displayDiagnostics=*/1);
1373
1374   if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1375     argc--;
1376     argv++;
1377   }
1378
1379   if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1380     clang_disposeIndex(Idx);
1381     return -1;
1382   }
1383
1384   TU = clang_parseTranslationUnit(Idx, 0,
1385                                   argv + num_unsaved_files,
1386                                   argc - num_unsaved_files,
1387                                   unsaved_files, num_unsaved_files, 
1388                                   getDefaultParsingOptions());
1389   if (!TU) {
1390     fprintf(stderr, "Unable to load translation unit!\n");
1391     free_remapped_files(unsaved_files, num_unsaved_files);
1392     clang_disposeIndex(Idx);
1393     return 1;
1394   }
1395
1396   result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1397                              CommentSchemaFile);
1398   free_remapped_files(unsaved_files, num_unsaved_files);
1399   clang_disposeIndex(Idx);
1400   return result;
1401 }
1402
1403 int perform_test_reparse_source(int argc, const char **argv, int trials,
1404                                 const char *filter, CXCursorVisitor Visitor,
1405                                 PostVisitTU PV) {
1406   CXIndex Idx;
1407   CXTranslationUnit TU;
1408   struct CXUnsavedFile *unsaved_files = 0;
1409   int num_unsaved_files = 0;
1410   int result;
1411   int trial;
1412   int remap_after_trial = 0;
1413   char *endptr = 0;
1414   
1415   Idx = clang_createIndex(/* excludeDeclsFromPCH */
1416                           !strcmp(filter, "local") ? 1 : 0,
1417                           /* displayDiagnostics=*/1);
1418   
1419   if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1420     clang_disposeIndex(Idx);
1421     return -1;
1422   }
1423   
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());
1430   if (!TU) {
1431     fprintf(stderr, "Unable to load translation unit!\n");
1432     free_remapped_files(unsaved_files, num_unsaved_files);
1433     clang_disposeIndex(Idx);
1434     return 1;
1435   }
1436   
1437   if (checkForErrors(TU) != 0)
1438     return -1;
1439
1440   if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1441     remap_after_trial =
1442         strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1443   }
1444
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);
1454       return -1;      
1455     }
1456
1457     if (checkForErrors(TU) != 0)
1458       return -1;
1459   }
1460   
1461   result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
1462
1463   free_remapped_files(unsaved_files, num_unsaved_files);
1464   clang_disposeIndex(Idx);
1465   return result;
1466 }
1467
1468 /******************************************************************************/
1469 /* Logic for testing clang_getCursor().                                       */
1470 /******************************************************************************/
1471
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);
1477   if (prefix)
1478     printf("-%s", prefix);
1479   PrintExtent(stdout, start_line, start_col, end_line, end_col);
1480   printf(" ");
1481   PrintCursor(cursor, NULL);
1482   printf("\n");
1483 }
1484
1485 static int perform_file_scan(const char *ast_file, const char *source_file,
1486                              const char *prefix) {
1487   CXIndex Idx;
1488   CXTranslationUnit TU;
1489   FILE *fp;
1490   CXCursor prevCursor = clang_getNullCursor();
1491   CXFile file;
1492   unsigned line = 1, col = 1;
1493   unsigned start_line = 1, start_col = 1;
1494
1495   if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
1496                                 /* displayDiagnostics=*/1))) {
1497     fprintf(stderr, "Could not create Index\n");
1498     return 1;
1499   }
1500
1501   if (!CreateTranslationUnit(Idx, ast_file, &TU))
1502     return 1;
1503
1504   if ((fp = fopen(source_file, "r")) == NULL) {
1505     fprintf(stderr, "Could not open '%s'\n", source_file);
1506     return 1;
1507   }
1508
1509   file = clang_getFile(TU, source_file);
1510   for (;;) {
1511     CXCursor cursor;
1512     int c = fgetc(fp);
1513
1514     if (c == '\n') {
1515       ++line;
1516       col = 1;
1517     } else
1518       ++col;
1519
1520     /* Check the cursor at this position, and dump the previous one if we have
1521      * found something new.
1522      */
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,
1527                              line, col, prefix);
1528       start_line = line;
1529       start_col = col;
1530     }
1531     if (c == EOF)
1532       break;
1533
1534     prevCursor = cursor;
1535   }
1536
1537   fclose(fp);
1538   clang_disposeTranslationUnit(TU);
1539   clang_disposeIndex(Idx);
1540   return 0;
1541 }
1542
1543 /******************************************************************************/
1544 /* Logic for testing clang code completion.                                   */
1545 /******************************************************************************/
1546
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;
1557
1558   char *endptr = 0;
1559   if (!last_colon || last_colon == input) {
1560     if (num_values == 4)
1561       fprintf(stderr, "could not parse filename:line:column:line:column in "
1562               "'%s'\n", input);
1563     else
1564       fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
1565     return 1;
1566   }
1567
1568   for (i = 0; i != num_values; ++i) {
1569     const char *prev_colon;
1570
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);
1576       return 1;
1577     }
1578
1579     if (i + 1 == num_values)
1580       break;
1581
1582     /* Find the previous colon. */
1583     prev_colon = last_colon - 1;
1584     while (prev_colon != input && *prev_colon != ':')
1585       --prev_colon;
1586     if (prev_colon == input) {
1587       fprintf(stderr, "could not parse %s in '%s'\n",
1588               (i % 2 == 0? "column" : "line"), input);
1589       return 1;
1590     }
1591
1592     last_colon = prev_colon;
1593   }
1594
1595   *line = values[0];
1596   *column = values[1];
1597
1598   if (second_line && second_column) {
1599     *second_line = values[2];
1600     *second_column = values[3];
1601   }
1602
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;
1607   return 0;
1608 }
1609
1610 const char *
1611 clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1612   switch (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";
1634   }
1635
1636   return "Unknown";
1637 }
1638
1639 static int checkForErrors(CXTranslationUnit TU) {
1640   unsigned Num, i;
1641   CXDiagnostic Diag;
1642   CXString DiagStr;
1643
1644   if (!getenv("CINDEXTEST_FAILONERROR"))
1645     return 0;
1646
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);
1656       return -1;
1657     }
1658     clang_disposeDiagnostic(Diag);
1659   }
1660
1661   return 0;
1662 }
1663
1664 void print_completion_string(CXCompletionString completion_string, FILE *file) {
1665   int I, N;
1666
1667   N = clang_getNumCompletionChunks(completion_string);
1668   for (I = 0; I != N; ++I) {
1669     CXString text;
1670     const char *cstr;
1671     enum CXCompletionChunkKind Kind
1672       = clang_getCompletionChunkKind(completion_string, I);
1673
1674     if (Kind == CXCompletionChunk_Optional) {
1675       fprintf(file, "{Optional ");
1676       print_completion_string(
1677                 clang_getCompletionChunkCompletionString(completion_string, I),
1678                               file);
1679       fprintf(file, "}");
1680       continue;
1681     } 
1682
1683     if (Kind == CXCompletionChunk_VerticalSpace) {
1684       fprintf(file, "{VerticalSpace  }");
1685       continue;
1686     }
1687
1688     text = clang_getCompletionChunkText(completion_string, I);
1689     cstr = clang_getCString(text);
1690     fprintf(file, "{%s %s}",
1691             clang_getCompletionChunkKindSpelling(Kind),
1692             cstr ? cstr : "");
1693     clang_disposeString(text);
1694   }
1695
1696 }
1697
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;
1707   
1708   fprintf(file, "%s:", clang_getCString(ks));
1709   clang_disposeString(ks);
1710
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:
1716     break;
1717     
1718   case CXAvailability_Deprecated:
1719     fprintf(file, " (deprecated)");
1720     break;
1721     
1722   case CXAvailability_NotAvailable:
1723     fprintf(file, " (unavailable)");
1724     break;
1725
1726   case CXAvailability_NotAccessible:
1727     fprintf(file, " (inaccessible)");
1728     break;
1729   }
1730
1731   annotationCount = clang_getCompletionNumAnnotations(
1732         completion_result->CompletionString);
1733   if (annotationCount) {
1734     unsigned i;
1735     fprintf(file, " (");
1736     for (i = 0; i < annotationCount; ++i) {
1737       if (i != 0)
1738         fprintf(file, ", ");
1739       fprintf(file, "\"%s\"",
1740               clang_getCString(clang_getCompletionAnnotation(
1741                                  completion_result->CompletionString, i)));
1742     }
1743     fprintf(file, ")");
1744   }
1745
1746   if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1747     ParentName = clang_getCompletionParent(completion_result->CompletionString,
1748                                            &ParentKind);
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);
1755     }
1756     clang_disposeString(ParentName);
1757   }
1758
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);
1764   }
1765   clang_disposeString(BriefComment);
1766   
1767   fprintf(file, "\n");
1768 }
1769
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");
1774   }
1775   if (contexts & CXCompletionContext_AnyType) {
1776     fprintf(file, "Any type\n");
1777   }
1778   if (contexts & CXCompletionContext_AnyValue) {
1779     fprintf(file, "Any value\n");
1780   }
1781   if (contexts & CXCompletionContext_ObjCObjectValue) {
1782     fprintf(file, "Objective-C object value\n");
1783   }
1784   if (contexts & CXCompletionContext_ObjCSelectorValue) {
1785     fprintf(file, "Objective-C selector value\n");
1786   }
1787   if (contexts & CXCompletionContext_CXXClassTypeValue) {
1788     fprintf(file, "C++ class type value\n");
1789   }
1790   if (contexts & CXCompletionContext_DotMemberAccess) {
1791     fprintf(file, "Dot member access\n");
1792   }
1793   if (contexts & CXCompletionContext_ArrowMemberAccess) {
1794     fprintf(file, "Arrow member access\n");
1795   }
1796   if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1797     fprintf(file, "Objective-C property access\n");
1798   }
1799   if (contexts & CXCompletionContext_EnumTag) {
1800     fprintf(file, "Enum tag\n");
1801   }
1802   if (contexts & CXCompletionContext_UnionTag) {
1803     fprintf(file, "Union tag\n");
1804   }
1805   if (contexts & CXCompletionContext_StructTag) {
1806     fprintf(file, "Struct tag\n");
1807   }
1808   if (contexts & CXCompletionContext_ClassTag) {
1809     fprintf(file, "Class name\n");
1810   }
1811   if (contexts & CXCompletionContext_Namespace) {
1812     fprintf(file, "Namespace or namespace alias\n");
1813   }
1814   if (contexts & CXCompletionContext_NestedNameSpecifier) {
1815     fprintf(file, "Nested name specifier\n");
1816   }
1817   if (contexts & CXCompletionContext_ObjCInterface) {
1818     fprintf(file, "Objective-C interface\n");
1819   }
1820   if (contexts & CXCompletionContext_ObjCProtocol) {
1821     fprintf(file, "Objective-C protocol\n");
1822   }
1823   if (contexts & CXCompletionContext_ObjCCategory) {
1824     fprintf(file, "Objective-C category\n");
1825   }
1826   if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1827     fprintf(file, "Objective-C instance method\n");
1828   }
1829   if (contexts & CXCompletionContext_ObjCClassMessage) {
1830     fprintf(file, "Objective-C class method\n");
1831   }
1832   if (contexts & CXCompletionContext_ObjCSelectorName) {
1833     fprintf(file, "Objective-C selector name\n");
1834   }
1835   if (contexts & CXCompletionContext_MacroName) {
1836     fprintf(file, "Macro name\n");
1837   }
1838   if (contexts & CXCompletionContext_NaturalLanguage) {
1839     fprintf(file, "Natural language\n");
1840   }
1841 }
1842
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);
1846     if (c1 < c2)
1847       return -1;
1848     else if (c1 > c2)
1849       return 1;
1850     
1851     ++s1;
1852     ++s2;
1853   }
1854   
1855   if (*s1)
1856     return 1;
1857   else if (*s2)
1858     return -1;
1859   return 0;
1860 }
1861
1862 int perform_code_completion(int argc, const char **argv, int timing_only) {
1863   const char *input = argv[1];
1864   char *filename = 0;
1865   unsigned line;
1866   unsigned column;
1867   CXIndex CIdx;
1868   int errorCode;
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();
1875   
1876   if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
1877     completionOptions |= CXCodeComplete_IncludeCodePatterns;
1878   if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
1879     completionOptions |= CXCodeComplete_IncludeBriefComments;
1880   
1881   if (timing_only)
1882     input += strlen("-code-completion-timing=");
1883   else
1884     input += strlen("-code-completion-at=");
1885
1886   if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
1887                                           0, 0)))
1888     return errorCode;
1889
1890   if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
1891     return -1;
1892
1893   CIdx = clang_createIndex(0, 0);
1894   
1895   if (getenv("CINDEXTEST_EDITING"))
1896     Repeats = 5;
1897   
1898   TU = clang_parseTranslationUnit(CIdx, 0,
1899                                   argv + num_unsaved_files + 2,
1900                                   argc - num_unsaved_files - 2,
1901                                   0, 0, getDefaultParsingOptions());
1902   if (!TU) {
1903     fprintf(stderr, "Unable to load translation unit!\n");
1904     return 1;
1905   }
1906
1907   if (clang_reparseTranslationUnit(TU, 0, 0, clang_defaultReparseOptions(TU))) {
1908     fprintf(stderr, "Unable to reparse translation init!\n");
1909     return 1;
1910   }
1911   
1912   for (I = 0; I != Repeats; ++I) {
1913     results = clang_codeCompleteAt(TU, filename, line, column,
1914                                    unsaved_files, num_unsaved_files,
1915                                    completionOptions);
1916     if (!results) {
1917       fprintf(stderr, "Unable to perform code completion!\n");
1918       return 1;
1919     }
1920     if (I != Repeats-1)
1921       clang_disposeCodeCompleteResults(results);
1922   }
1923
1924   if (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;
1930     if (!timing_only) {      
1931       /* Sort the code-completion results based on the typed text. */
1932       clang_sortCodeCompletionResults(results->Results, results->NumResults);
1933
1934       for (i = 0; i != n; ++i)
1935         print_completion_result(results->Results + i, stdout);
1936     }
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);
1942     }
1943     
1944     contexts = clang_codeCompleteGetContexts(results);
1945     print_completion_contexts(contexts, stdout);
1946     
1947     containerKind = clang_codeCompleteGetContainerKind(results,
1948                                                        &containerIsIncomplete);
1949     
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);
1956       
1957       if (containerIsIncomplete) {
1958         printf("Container is incomplete\n");
1959       }
1960       else {
1961         printf("Container is complete\n");
1962       }
1963       
1964       containerUSR = clang_codeCompleteGetContainerUSR(results);
1965       printf("Container USR: %s\n", clang_getCString(containerUSR));
1966       clang_disposeString(containerUSR);
1967     }
1968     
1969     objCSelector = clang_codeCompleteGetObjCSelector(results);
1970     selectorString = clang_getCString(objCSelector);
1971     if (selectorString && strlen(selectorString) > 0) {
1972       printf("Objective-C selector: %s\n", selectorString);
1973     }
1974     clang_disposeString(objCSelector);
1975     
1976     clang_disposeCodeCompleteResults(results);
1977   }
1978   clang_disposeTranslationUnit(TU);
1979   clang_disposeIndex(CIdx);
1980   free(filename);
1981
1982   free_remapped_files(unsaved_files, num_unsaved_files);
1983
1984   return 0;
1985 }
1986
1987 typedef struct {
1988   char *filename;
1989   unsigned line;
1990   unsigned column;
1991 } CursorSourceLocation;
1992
1993 static int inspect_cursor_at(int argc, const char **argv) {
1994   CXIndex CIdx;
1995   int errorCode;
1996   struct CXUnsavedFile *unsaved_files = 0;
1997   int num_unsaved_files = 0;
1998   CXTranslationUnit TU;
1999   CXCursor Cursor;
2000   CursorSourceLocation *Locations = 0;
2001   unsigned NumLocations = 0, Loc;
2002   unsigned Repeats = 1;
2003   unsigned I;
2004   
2005   /* Count the number of locations. */
2006   while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2007     ++NumLocations;
2008
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)))
2018       return errorCode;
2019   }
2020
2021   if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2022                            &num_unsaved_files))
2023     return -1;
2024
2025   if (getenv("CINDEXTEST_EDITING"))
2026     Repeats = 5;
2027
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,
2034                                   unsaved_files,
2035                                   Repeats > 1? 0 : num_unsaved_files,
2036                                   getDefaultParsingOptions());
2037                                                  
2038   if (!TU) {
2039     fprintf(stderr, "unable to parse input\n");
2040     return -1;
2041   }
2042
2043   if (checkForErrors(TU) != 0)
2044     return -1;
2045
2046   for (I = 0; I != Repeats; ++I) {
2047     if (Repeats > 1 &&
2048         clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files, 
2049                                      clang_defaultReparseOptions(TU))) {
2050       clang_disposeTranslationUnit(TU);
2051       return 1;
2052     }
2053
2054     if (checkForErrors(TU) != 0)
2055       return -1;
2056     
2057     for (Loc = 0; Loc < NumLocations; ++Loc) {
2058       CXFile file = clang_getFile(TU, Locations[Loc].filename);
2059       if (!file)
2060         continue;
2061
2062       Cursor = clang_getCursor(TU,
2063                                clang_getLocation(TU, file, Locations[Loc].line,
2064                                                  Locations[Loc].column));
2065
2066       if (checkForErrors(TU) != 0)
2067         return -1;
2068
2069       if (I + 1 == Repeats) {
2070         CXCompletionString completionString = clang_getCursorCompletionString(
2071                                                                         Cursor);
2072         CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2073         CXString Spelling;
2074         const char *cspell;
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))
2089               break;
2090             PrintRange(range, 0);
2091           }
2092           printf(")");
2093         }
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);
2104         }
2105
2106         {
2107           CXModule mod = clang_Cursor_getModule(Cursor);
2108           CXFile astFile;
2109           CXString name, astFilename;
2110           unsigned i, numHeaders;
2111           if (mod) {
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),
2118                    numHeaders);
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);
2126             }
2127           }
2128         }
2129
2130         if (completionString != NULL) {
2131           printf("\nCompletion string: ");
2132           print_completion_string(completionString, stdout);
2133         }
2134         printf("\n");
2135         free(Locations[Loc].filename);
2136       }
2137     }
2138   }
2139   
2140   PrintDiagnostics(TU);
2141   clang_disposeTranslationUnit(TU);
2142   clang_disposeIndex(CIdx);
2143   free(Locations);
2144   free_remapped_files(unsaved_files, num_unsaved_files);
2145   return 0;
2146 }
2147
2148 static enum CXVisitorResult findFileRefsVisit(void *context,
2149                                          CXCursor cursor, CXSourceRange range) {
2150   if (clang_Range_isNull(range))
2151     return CXVisit_Continue;
2152
2153   PrintCursor(cursor, NULL);
2154   PrintRange(range, "");
2155   printf("\n");
2156   return CXVisit_Continue;
2157 }
2158
2159 static int find_file_refs_at(int argc, const char **argv) {
2160   CXIndex CIdx;
2161   int errorCode;
2162   struct CXUnsavedFile *unsaved_files = 0;
2163   int num_unsaved_files = 0;
2164   CXTranslationUnit TU;
2165   CXCursor Cursor;
2166   CursorSourceLocation *Locations = 0;
2167   unsigned NumLocations = 0, Loc;
2168   unsigned Repeats = 1;
2169   unsigned I;
2170   
2171   /* Count the number of locations. */
2172   while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2173     ++NumLocations;
2174
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)))
2184       return errorCode;
2185   }
2186
2187   if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2188                            &num_unsaved_files))
2189     return -1;
2190
2191   if (getenv("CINDEXTEST_EDITING"))
2192     Repeats = 5;
2193
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,
2200                                   unsaved_files,
2201                                   Repeats > 1? 0 : num_unsaved_files,
2202                                   getDefaultParsingOptions());
2203                                                  
2204   if (!TU) {
2205     fprintf(stderr, "unable to parse input\n");
2206     return -1;
2207   }
2208
2209   if (checkForErrors(TU) != 0)
2210     return -1;
2211
2212   for (I = 0; I != Repeats; ++I) {
2213     if (Repeats > 1 &&
2214         clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files, 
2215                                      clang_defaultReparseOptions(TU))) {
2216       clang_disposeTranslationUnit(TU);
2217       return 1;
2218     }
2219
2220     if (checkForErrors(TU) != 0)
2221       return -1;
2222     
2223     for (Loc = 0; Loc < NumLocations; ++Loc) {
2224       CXFile file = clang_getFile(TU, Locations[Loc].filename);
2225       if (!file)
2226         continue;
2227
2228       Cursor = clang_getCursor(TU,
2229                                clang_getLocation(TU, file, Locations[Loc].line,
2230                                                  Locations[Loc].column));
2231
2232       if (checkForErrors(TU) != 0)
2233         return -1;
2234
2235       if (I + 1 == Repeats) {
2236         CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
2237         PrintCursor(Cursor, NULL);
2238         printf("\n");
2239         clang_findReferencesInFile(Cursor, file, visitor);
2240         free(Locations[Loc].filename);
2241
2242         if (checkForErrors(TU) != 0)
2243           return -1;
2244       }
2245     }
2246   }
2247   
2248   PrintDiagnostics(TU);
2249   clang_disposeTranslationUnit(TU);
2250   clang_disposeIndex(CIdx);
2251   free(Locations);
2252   free_remapped_files(unsaved_files, num_unsaved_files);
2253   return 0;
2254 }
2255
2256 static enum CXVisitorResult findFileIncludesVisit(void *context,
2257                                          CXCursor cursor, CXSourceRange range) {
2258   PrintCursor(cursor, NULL);
2259   PrintRange(range, "");
2260   printf("\n");
2261   return CXVisit_Continue;
2262 }
2263
2264 static int find_file_includes_in(int argc, const char **argv) {
2265   CXIndex CIdx;
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;
2272   unsigned I, FI;
2273
2274   /* Count the number of locations. */
2275   while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2276     ++NumFilenames;
2277
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;
2285   }
2286
2287   if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2288                            &num_unsaved_files))
2289     return -1;
2290
2291   if (getenv("CINDEXTEST_EDITING"))
2292     Repeats = 2;
2293
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,
2300                                   unsaved_files,
2301                                   Repeats > 1? 0 : num_unsaved_files,
2302                                   getDefaultParsingOptions());
2303
2304   if (!TU) {
2305     fprintf(stderr, "unable to parse input\n");
2306     return -1;
2307   }
2308
2309   if (checkForErrors(TU) != 0)
2310     return -1;
2311
2312   for (I = 0; I != Repeats; ++I) {
2313     if (Repeats > 1 &&
2314         clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2315                                      clang_defaultReparseOptions(TU))) {
2316       clang_disposeTranslationUnit(TU);
2317       return 1;
2318     }
2319
2320     if (checkForErrors(TU) != 0)
2321       return -1;
2322
2323     for (FI = 0; FI < NumFilenames; ++FI) {
2324       CXFile file = clang_getFile(TU, Filenames[FI]);
2325       if (!file)
2326         continue;
2327
2328       if (checkForErrors(TU) != 0)
2329         return -1;
2330
2331       if (I + 1 == Repeats) {
2332         CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2333         clang_findIncludesInFile(TU, file, visitor);
2334
2335         if (checkForErrors(TU) != 0)
2336           return -1;
2337       }
2338     }
2339   }
2340
2341   PrintDiagnostics(TU);
2342   clang_disposeTranslationUnit(TU);
2343   clang_disposeIndex(CIdx);
2344   free((void *)Filenames);
2345   free_remapped_files(unsaved_files, num_unsaved_files);
2346   return 0;
2347 }
2348
2349 #define MAX_IMPORTED_ASTFILES 200
2350
2351 typedef struct {
2352   char **filenames;
2353   unsigned num_files;
2354 } ImportedASTFilesData;
2355
2356 static ImportedASTFilesData *importedASTs_create() {
2357   ImportedASTFilesData *p;
2358   p = malloc(sizeof(ImportedASTFilesData));
2359   p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2360   p->num_files = 0;
2361   return p;
2362 }
2363
2364 static void importedASTs_dispose(ImportedASTFilesData *p) {
2365   unsigned i;
2366   if (!p)
2367     return;
2368
2369   for (i = 0; i < p->num_files; ++i)
2370     free(p->filenames[i]);
2371   free(p->filenames);
2372   free(p);
2373 }
2374
2375 static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2376   unsigned i;
2377   assert(p && file);
2378   for (i = 0; i < p->num_files; ++i)
2379     if (strcmp(file, p->filenames[i]) == 0)
2380       return;
2381   assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2382   p->filenames[p->num_files++] = strdup(file);
2383 }
2384
2385 typedef struct {
2386   const char *check_prefix;
2387   int first_check_printed;
2388   int fail_for_error;
2389   int abort;
2390   const char *main_filename;
2391   ImportedASTFilesData *importedASTs;
2392 } IndexData;
2393
2394 static void printCheck(IndexData *data) {
2395   if (data->check_prefix) {
2396     if (data->first_check_printed) {
2397       printf("// %s-NEXT: ", data->check_prefix);
2398     } else {
2399       printf("// %s     : ", data->check_prefix);
2400       data->first_check_printed = 1;
2401     }
2402   }
2403 }
2404
2405 static void printCXIndexFile(CXIdxClientFile file) {
2406   CXString filename = clang_getFileName((CXFile)file);
2407   printf("%s", clang_getCString(filename));
2408   clang_disposeString(filename);
2409 }
2410
2411 static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2412   IndexData *index_data;
2413   CXString filename;
2414   const char *cname;
2415   CXIdxClientFile file;
2416   unsigned line, column;
2417   int isMainFile;
2418   
2419   index_data = (IndexData *)client_data;
2420   clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2421   if (line == 0) {
2422     printf("<invalid>");
2423     return;
2424   }
2425   if (!file) {
2426     printf("<no idxfile>");
2427     return;
2428   }
2429   filename = clang_getFileName((CXFile)file);
2430   cname = clang_getCString(filename);
2431   if (strcmp(cname, index_data->main_filename) == 0)
2432     isMainFile = 1;
2433   else
2434     isMainFile = 0;
2435   clang_disposeString(filename);
2436
2437   if (!isMainFile) {
2438     printCXIndexFile(file);
2439     printf(":");
2440   }
2441   printf("%d:%d", line, column);
2442 }
2443
2444 static unsigned digitCount(unsigned val) {
2445   unsigned c = 1;
2446   while (1) {
2447     if (val < 10)
2448       return c;
2449     ++c;
2450     val /= 10;
2451   }
2452 }
2453
2454 static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2455                                                 CXIdxLoc loc) {
2456   const char *name;
2457   char *newStr;
2458   CXIdxClientFile file;
2459   unsigned line, column;
2460   
2461   name = info->name;
2462   if (!name)
2463     name = "<anon-tag>";
2464
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;
2471 }
2472
2473 static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2474   CXIdxClientContainer container;
2475   container = clang_index_getClientContainer(info);
2476   if (!container)
2477     printf("[<<NULL>>]");
2478   else
2479     printf("[%s]", (const char *)container);
2480 }
2481
2482 static const char *getEntityKindString(CXIdxEntityKind kind) {
2483   switch (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";
2511   }
2512   assert(0 && "Garbage entity kind");
2513   return 0;
2514 }
2515
2516 static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2517   switch (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";
2523   }
2524   assert(0 && "Garbage entity kind");
2525   return 0;
2526 }
2527
2528 static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2529   switch (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++";
2534   }
2535   assert(0 && "Garbage language kind");
2536   return 0;
2537 }
2538
2539 static void printEntityInfo(const char *cb,
2540                             CXClientData client_data,
2541                             const CXIdxEntityInfo *info) {
2542   const char *name;
2543   IndexData *index_data;
2544   unsigned i;
2545   index_data = (IndexData *)client_data;
2546   printCheck(index_data);
2547
2548   if (!info) {
2549     printf("%s: <<NULL>>", cb);
2550     return;
2551   }
2552
2553   name = info->name;
2554   if (!name)
2555     name = "<anon-tag>";
2556
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));
2562
2563   for (i = 0; i != info->numAttributes; ++i) {
2564     const CXIdxAttrInfo *Attr = info->attributes[i];
2565     printf("     <attribute>: ");
2566     PrintCursor(Attr->cursor, NULL);
2567   }
2568 }
2569
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);
2575   printf(" | loc: ");
2576   printCXIndexLoc(info->loc, client_data);
2577 }
2578
2579 static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2580                               CXClientData client_data) {
2581   unsigned i;
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);
2587     printf(" | loc: ");
2588     printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
2589     printf("\n");
2590   }
2591 }
2592
2593 static void index_diagnostic(CXClientData client_data,
2594                              CXDiagnosticSet diagSet, void *reserved) {
2595   CXString str;
2596   const char *cstr;
2597   unsigned numDiags, i;
2598   CXDiagnostic diag;
2599   IndexData *index_data;
2600   index_data = (IndexData *)client_data;
2601   printCheck(index_data);
2602
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);  
2610   
2611     if (getenv("CINDEXTEST_FAILONERROR") &&
2612         clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2613       index_data->fail_for_error = 1;
2614     }
2615   }
2616 }
2617
2618 static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2619                                        CXFile file, void *reserved) {
2620   IndexData *index_data;
2621   CXString filename;
2622
2623   index_data = (IndexData *)client_data;
2624   printCheck(index_data);
2625
2626   filename = clang_getFileName(file);
2627   index_data->main_filename = clang_getCString(filename);
2628   clang_disposeString(filename);
2629
2630   printf("[enteredMainFile]: ");
2631   printCXIndexFile((CXIdxClientFile)file);
2632   printf("\n");
2633
2634   return (CXIdxClientFile)file;
2635 }
2636
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);
2642
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);
2650
2651   return (CXIdxClientFile)info->file;
2652 }
2653
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);
2659
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);
2664   }
2665   
2666   printf("[importedASTFile]: ");
2667   printCXIndexFile((CXIdxClientFile)info->file);
2668   if (info->module) {
2669     CXString name = clang_Module_getFullName(info->module);
2670     printf(" | loc: ");
2671     printCXIndexLoc(info->loc, client_data);
2672     printf(" | name: \"%s\"", clang_getCString(name));
2673     printf(" | isImplicit: %d\n", info->isImplicit);
2674     clang_disposeString(name);
2675   } else {
2676     /* PCH file, the rest are not relevant. */
2677     printf("\n");
2678   }
2679
2680   return (CXIdxClientFile)info->file;
2681 }
2682
2683 static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
2684                                                    void *reserved) {
2685   IndexData *index_data;
2686   index_data = (IndexData *)client_data;
2687   printCheck(index_data);
2688
2689   printf("[startedTranslationUnit]\n");
2690   return (CXIdxClientContainer)"TU";
2691 }
2692
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;
2701   unsigned i;
2702   index_data = (IndexData *)client_data;
2703
2704   printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2705   printf(" | cursor: ");
2706   PrintCursor(info->cursor, NULL);
2707   printf(" | loc: ");
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");
2718   } else {
2719     printf(" | isContainer: %d", info->isContainer);
2720   }
2721   printf(" | isImplicit: %d\n", info->isImplicit);
2722
2723   for (i = 0; i != info->numAttributes; ++i) {
2724     const CXIdxAttrInfo *Attr = info->attributes[i];
2725     printf("     <attribute>: ");
2726     PrintCursor(Attr->cursor, NULL);
2727     printf("\n");
2728   }
2729
2730   if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2731     const char *kindName = 0;
2732     CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2733     switch (K) {
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;
2740     }
2741     printCheck(index_data);
2742     printf("     <ObjCContainerInfo>: kind: %s\n", kindName);
2743   }
2744
2745   if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
2746     printEntityInfo("     <ObjCCategoryInfo>: class", client_data,
2747                     CatInfo->objcClass);
2748     printf(" | cursor: ");
2749     PrintCursor(CatInfo->classCursor, NULL);
2750     printf(" | loc: ");
2751     printCXIndexLoc(CatInfo->classLoc, client_data);
2752     printf("\n");
2753   }
2754
2755   if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2756     if (InterInfo->superInfo) {
2757       printBaseClassInfo(client_data, InterInfo->superInfo);
2758       printf("\n");
2759     }
2760   }
2761
2762   if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2763     printProtocolList(ProtoInfo, client_data);
2764   }
2765
2766   if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2767     if (PropInfo->getter) {
2768       printEntityInfo("     <getter>", client_data, PropInfo->getter);
2769       printf("\n");
2770     }
2771     if (PropInfo->setter) {
2772       printEntityInfo("     <setter>", client_data, PropInfo->setter);
2773       printf("\n");
2774     }
2775   }
2776
2777   if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2778     for (i = 0; i != CXXClassInfo->numBases; ++i) {
2779       printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2780       printf("\n");
2781     }
2782   }
2783
2784   if (info->declAsContainer)
2785     clang_index_setClientContainer(info->declAsContainer,
2786                               makeClientContainer(info->entityInfo, info->loc));
2787 }
2788
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);
2794   printf(" | loc: ");
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;
2803   }
2804   printf("\n");
2805 }
2806
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;
2811 }
2812
2813 static IndexerCallbacks IndexCB = {
2814   index_abortQuery,
2815   index_diagnostic,
2816   index_enteredMainFile,
2817   index_ppIncludedFile,
2818   index_importedASTFile,
2819   index_startedTranslationUnit,
2820   index_indexDeclaration,
2821   index_indexEntityReference
2822 };
2823
2824 static unsigned getIndexOptions(void) {
2825   unsigned index_opts;
2826   index_opts = 0;
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;
2833
2834   return index_opts;
2835 }
2836
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;
2843   int result;
2844
2845   if (num_args == 0) {
2846     fprintf(stderr, "no compiler arguments\n");
2847     return -1;
2848   }
2849
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;
2856
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)
2863     result = -1;
2864
2865   return result;
2866 }
2867
2868 static int index_ast_file(const char *ast_file,
2869                           CXIndex Idx,
2870                           CXIndexAction idxAction,
2871                           ImportedASTFilesData *importedASTs,
2872                           const char *check_prefix) {
2873   CXTranslationUnit TU;
2874   IndexData index_data;
2875   unsigned index_opts;
2876   int result;
2877
2878   if (!CreateTranslationUnit(Idx, ast_file, &TU))
2879     return -1;
2880
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;
2887
2888   index_opts = getIndexOptions();
2889   result = clang_indexTranslationUnit(idxAction, &index_data,
2890                                       &IndexCB,sizeof(IndexCB),
2891                                       index_opts, TU);
2892   if (index_data.fail_for_error)
2893     result = -1;
2894
2895   clang_disposeTranslationUnit(TU);
2896   return result;
2897 }
2898
2899 static int index_file(int argc, const char **argv, int full) {
2900   const char *check_prefix;
2901   CXIndex Idx;
2902   CXIndexAction idxAction;
2903   ImportedASTFilesData *importedASTs;
2904   int result;
2905
2906   check_prefix = 0;
2907   if (argc > 0) {
2908     if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2909       check_prefix = argv[0] + strlen("-check-prefix=");
2910       ++argv;
2911       --argc;
2912     }
2913   }
2914
2915   if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2916                                 /* displayDiagnostics=*/1))) {
2917     fprintf(stderr, "Could not create Index\n");
2918     return 1;
2919   }
2920   idxAction = clang_IndexAction_create(Idx);
2921   importedASTs = 0;
2922   if (full)
2923     importedASTs = importedASTs_create();
2924
2925   result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
2926   if (result != 0)
2927     goto finished;
2928
2929   if (full) {
2930     unsigned i;
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);
2934     }
2935   }
2936
2937 finished:
2938   importedASTs_dispose(importedASTs);
2939   clang_IndexAction_dispose(idxAction);
2940   clang_disposeIndex(Idx);
2941   return result;
2942 }
2943
2944 static int index_tu(int argc, const char **argv) {
2945   const char *check_prefix;
2946   CXIndex Idx;
2947   CXIndexAction idxAction;
2948   int result;
2949
2950   check_prefix = 0;
2951   if (argc > 0) {
2952     if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2953       check_prefix = argv[0] + strlen("-check-prefix=");
2954       ++argv;
2955       --argc;
2956     }
2957   }
2958
2959   if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2960                                 /* displayDiagnostics=*/1))) {
2961     fprintf(stderr, "Could not create Index\n");
2962     return 1;
2963   }
2964   idxAction = clang_IndexAction_create(Idx);
2965
2966   result = index_ast_file(argv[0], Idx, idxAction,
2967                           /*importedASTs=*/0, check_prefix);
2968
2969   clang_IndexAction_dispose(idxAction);
2970   clang_disposeIndex(Idx);
2971   return result;
2972 }
2973
2974 static int index_compile_db(int argc, const char **argv) {
2975   const char *check_prefix;
2976   CXIndex Idx;
2977   CXIndexAction idxAction;
2978   int errorCode = 0;
2979
2980   check_prefix = 0;
2981   if (argc > 0) {
2982     if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2983       check_prefix = argv[0] + strlen("-check-prefix=");
2984       ++argv;
2985       --argc;
2986     }
2987   }
2988
2989   if (argc == 0) {
2990     fprintf(stderr, "no compilation database\n");
2991     return -1;
2992   }
2993
2994   if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2995                                 /* displayDiagnostics=*/1))) {
2996     fprintf(stderr, "Could not create Index\n");
2997     return 1;
2998   }
2999   idxAction = clang_IndexAction_create(Idx);
3000
3001   {
3002     const char *database = argv[0];
3003     CXCompilationDatabase db = 0;
3004     CXCompileCommands CCmds = 0;
3005     CXCompileCommand CCmd;
3006     CXCompilationDatabase_Error ec;
3007     CXString wd;
3008 #define MAX_COMPILE_ARGS 512
3009     CXString cxargs[MAX_COMPILE_ARGS];
3010     const char *args[MAX_COMPILE_ARGS];
3011     char *tmp;
3012     unsigned len;
3013     char *buildDir;
3014     int i, a, numCmds, numArgs;
3015
3016     len = strlen(database);
3017     tmp = (char *) malloc(len+1);
3018     memcpy(tmp, database, len+1);
3019     buildDir = dirname(tmp);
3020
3021     db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3022
3023     if (db) {
3024
3025       if (ec!=CXCompilationDatabase_NoError) {
3026         printf("unexpected error %d code while loading compilation database\n", ec);
3027         errorCode = -1;
3028         goto cdb_end;
3029       }
3030
3031       if (chdir(buildDir) != 0) {
3032         printf("Could not chdir to %s\n", buildDir);
3033         errorCode = -1;
3034         goto cdb_end;
3035       }
3036
3037       CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
3038       if (!CCmds) {
3039         printf("compilation db is empty\n");
3040         errorCode = -1;
3041         goto cdb_end;
3042       }
3043
3044       numCmds = clang_CompileCommands_getSize(CCmds);
3045
3046       if (numCmds==0) {
3047         fprintf(stderr, "should not get an empty compileCommand set\n");
3048         errorCode = -1;
3049         goto cdb_end;
3050       }
3051
3052       for (i=0; i<numCmds && errorCode == 0; ++i) {
3053         CCmd = clang_CompileCommands_getCommand(CCmds, i);
3054
3055         wd = clang_CompileCommand_getDirectory(CCmd);
3056         if (chdir(clang_getCString(wd)) != 0) {
3057           printf("Could not chdir to %s\n", clang_getCString(wd));
3058           errorCode = -1;
3059           goto cdb_end;
3060         }
3061         clang_disposeString(wd);
3062
3063         numArgs = clang_CompileCommand_getNumArgs(CCmd);
3064         if (numArgs > MAX_COMPILE_ARGS){
3065           fprintf(stderr, "got more compile arguments than maximum\n");
3066           errorCode = -1;
3067           goto cdb_end;
3068         }
3069         for (a=0; a<numArgs; ++a) {
3070           cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3071           args[a] = clang_getCString(cxargs[a]);
3072         }
3073
3074         errorCode = index_compile_args(numArgs, args, idxAction,
3075                                        /*importedASTs=*/0, check_prefix);
3076
3077         for (a=0; a<numArgs; ++a)
3078           clang_disposeString(cxargs[a]);
3079       }
3080     } else {
3081       printf("database loading failed with error code %d.\n", ec);
3082       errorCode = -1;
3083     }
3084
3085   cdb_end:
3086     clang_CompileCommands_dispose(CCmds);
3087     clang_CompilationDatabase_dispose(db);
3088     free(tmp);
3089
3090   }
3091
3092   clang_IndexAction_dispose(idxAction);
3093   clang_disposeIndex(Idx);
3094   return errorCode;
3095 }
3096
3097 int perform_token_annotation(int argc, const char **argv) {
3098   const char *input = argv[1];
3099   char *filename = 0;
3100   unsigned line, second_line;
3101   unsigned column, second_column;
3102   CXIndex CIdx;
3103   CXTranslationUnit TU = 0;
3104   int errorCode;
3105   struct CXUnsavedFile *unsaved_files = 0;
3106   int num_unsaved_files = 0;
3107   CXToken *tokens;
3108   unsigned num_tokens;
3109   CXSourceRange range;
3110   CXSourceLocation startLoc, endLoc;
3111   CXFile file = 0;
3112   CXCursor *cursors = 0;
3113   unsigned i;
3114
3115   input += strlen("-test-annotate-tokens=");
3116   if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3117                                           &second_line, &second_column)))
3118     return errorCode;
3119
3120   if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3121     free(filename);
3122     return -1;
3123   }
3124
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,
3129                                   unsaved_files,
3130                                   num_unsaved_files,
3131                                   getDefaultParsingOptions());
3132   if (!TU) {
3133     fprintf(stderr, "unable to parse input\n");
3134     clang_disposeIndex(CIdx);
3135     free(filename);
3136     free_remapped_files(unsaved_files, num_unsaved_files);
3137     return -1;
3138   }
3139   errorCode = 0;
3140
3141   if (checkForErrors(TU) != 0) {
3142     errorCode = -1;
3143     goto teardown;
3144   }
3145
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");
3151         errorCode = -1;
3152         goto teardown;
3153       }
3154     }
3155   }
3156
3157   if (checkForErrors(TU) != 0) {
3158     errorCode = -1;
3159     goto teardown;
3160   }
3161
3162   file = clang_getFile(TU, filename);
3163   if (!file) {
3164     fprintf(stderr, "file %s is not in this translation unit\n", filename);
3165     errorCode = -1;
3166     goto teardown;
3167   }
3168
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,
3172             column);
3173     errorCode = -1;
3174     goto teardown;
3175   }
3176
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);
3181     errorCode = -1;
3182     goto teardown;
3183   }
3184
3185   range = clang_getRange(startLoc, endLoc);
3186   clang_tokenize(TU, range, &tokens, &num_tokens);
3187
3188   if (checkForErrors(TU) != 0) {
3189     errorCode = -1;
3190     goto teardown;
3191   }
3192
3193   cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3194   clang_annotateTokens(TU, tokens, num_tokens, cursors);
3195
3196   if (checkForErrors(TU) != 0) {
3197     errorCode = -1;
3198     goto teardown;
3199   }
3200
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;
3206
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;
3213     }
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)) {
3222       printf(" ");
3223       PrintCursor(cursors[i], NULL);
3224     }
3225     printf("\n");
3226   }
3227   free(cursors);
3228   clang_disposeTokens(TU, tokens, num_tokens);
3229
3230  teardown:
3231   PrintDiagnostics(TU);
3232   clang_disposeTranslationUnit(TU);
3233   clang_disposeIndex(CIdx);
3234   free(filename);
3235   free_remapped_files(unsaved_files, num_unsaved_files);
3236   return errorCode;
3237 }
3238
3239 static int
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;
3245   CXString wd;
3246   CXString arg;
3247   int errorCode = 0;
3248   char *tmp;
3249   unsigned len;
3250   char *buildDir;
3251   int i, j, a, numCmds, numArgs;
3252
3253   len = strlen(database);
3254   tmp = (char *) malloc(len+1);
3255   memcpy(tmp, database, len+1);
3256   buildDir = dirname(tmp);
3257
3258   db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3259
3260   if (db) {
3261
3262     if (ec!=CXCompilationDatabase_NoError) {
3263       printf("unexpected error %d code while loading compilation database\n", ec);
3264       errorCode = -1;
3265       goto cdb_end;
3266     }
3267
3268     for (i=0; i<argc && errorCode==0; ) {
3269       if (strcmp(argv[i],"lookup")==0){
3270         CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
3271
3272         if (!CCmds) {
3273           printf("file %s not found in compilation db\n", argv[i+1]);
3274           errorCode = -1;
3275           break;
3276         }
3277
3278         numCmds = clang_CompileCommands_getSize(CCmds);
3279
3280         if (numCmds==0) {
3281           fprintf(stderr, "should not get an empty compileCommand set for file"
3282                           " '%s'\n", argv[i+1]);
3283           errorCode = -1;
3284           break;
3285         }
3286
3287         for (j=0; j<numCmds; ++j) {
3288           CCmd = clang_CompileCommands_getCommand(CCmds, j);
3289
3290           wd = clang_CompileCommand_getDirectory(CCmd);
3291           printf("workdir:'%s'", clang_getCString(wd));
3292           clang_disposeString(wd);
3293
3294           printf(" cmdline:'");
3295           numArgs = clang_CompileCommand_getNumArgs(CCmd);
3296           for (a=0; a<numArgs; ++a) {
3297             if (a) printf(" ");
3298             arg = clang_CompileCommand_getArg(CCmd, a);
3299             printf("%s", clang_getCString(arg));
3300             clang_disposeString(arg);
3301           }
3302           printf("'\n");
3303         }
3304
3305         clang_CompileCommands_dispose(CCmds);
3306
3307         i += 2;
3308       }
3309     }
3310     clang_CompilationDatabase_dispose(db);
3311   } else {
3312     printf("database loading failed with error code %d.\n", ec);
3313     errorCode = -1;
3314   }
3315
3316 cdb_end:
3317   free(tmp);
3318
3319   return errorCode;
3320 }
3321
3322 /******************************************************************************/
3323 /* USR printing.                                                              */
3324 /******************************************************************************/
3325
3326 static int insufficient_usr(const char *kind, const char *usage) {
3327   fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3328   return 1;
3329 }
3330
3331 static unsigned isUSR(const char *s) {
3332   return s[0] == 'c' && s[1] == ':';
3333 }
3334
3335 static int not_usr(const char *s, const char *arg) {
3336   fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3337   return 1;
3338 }
3339
3340 static void print_usr(CXString usr) {
3341   const char *s = clang_getCString(usr);
3342   printf("%s\n", s);
3343   clang_disposeString(usr);
3344 }
3345
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] "
3352             "<class USR>\n"
3353           " ObjCProperty <property name> <class USR>\n"
3354           " ObjCProtocol <protocol name>\n");
3355 }
3356
3357 int print_usrs(const char **I, const char **E) {
3358   while (I != E) {
3359     const char *kind = *I;
3360     unsigned len = strlen(kind);
3361     switch (len) {
3362       case 8:
3363         if (memcmp(kind, "ObjCIvar", 8) == 0) {
3364           if (I + 2 >= E)
3365             return insufficient_usr(kind, "<ivar name> <class USR>");
3366           if (!isUSR(I[2]))
3367             return not_usr("<class USR>", I[2]);
3368           else {
3369             CXString x;
3370             x.data = (void*) I[2];
3371             x.private_flags = 0;
3372             print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3373           }
3374
3375           I += 3;
3376           continue;
3377         }
3378         break;
3379       case 9:
3380         if (memcmp(kind, "ObjCClass", 9) == 0) {
3381           if (I + 1 >= E)
3382             return insufficient_usr(kind, "<class name>");
3383           print_usr(clang_constructUSR_ObjCClass(I[1]));
3384           I += 2;
3385           continue;
3386         }
3387         break;
3388       case 10:
3389         if (memcmp(kind, "ObjCMethod", 10) == 0) {
3390           if (I + 3 >= E)
3391             return insufficient_usr(kind, "<method selector> "
3392                 "[0=class method|1=instance method] <class USR>");
3393           if (!isUSR(I[3]))
3394             return not_usr("<class USR>", I[3]);
3395           else {
3396             CXString x;
3397             x.data = (void*) I[3];
3398             x.private_flags = 0;
3399             print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3400           }
3401           I += 4;
3402           continue;
3403         }
3404         break;
3405       case 12:
3406         if (memcmp(kind, "ObjCCategory", 12) == 0) {
3407           if (I + 2 >= E)
3408             return insufficient_usr(kind, "<class name> <category name>");
3409           print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3410           I += 3;
3411           continue;
3412         }
3413         if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3414           if (I + 1 >= E)
3415             return insufficient_usr(kind, "<protocol name>");
3416           print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3417           I += 2;
3418           continue;
3419         }
3420         if (memcmp(kind, "ObjCProperty", 12) == 0) {
3421           if (I + 2 >= E)
3422             return insufficient_usr(kind, "<property name> <class USR>");
3423           if (!isUSR(I[2]))
3424             return not_usr("<class USR>", I[2]);
3425           else {
3426             CXString x;
3427             x.data = (void*) I[2];
3428             x.private_flags = 0;
3429             print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3430           }
3431           I += 3;
3432           continue;
3433         }
3434         break;
3435       default:
3436         break;
3437     }
3438     break;
3439   }
3440
3441   if (I != E) {
3442     fprintf(stderr, "Invalid USR kind: %s\n", *I);
3443     display_usrs();
3444     return 1;
3445   }
3446   return 0;
3447 }
3448
3449 int print_usrs_file(const char *file_name) {
3450   char line[2048];
3451   const char *args[128];
3452   unsigned numChars = 0;
3453
3454   FILE *fp = fopen(file_name, "r");
3455   if (!fp) {
3456     fprintf(stderr, "error: cannot open '%s'\n", file_name);
3457     return 1;
3458   }
3459
3460   /* This code is not really all that safe, but it works fine for testing. */
3461   while (!feof(fp)) {
3462     char c = fgetc(fp);
3463     if (c == '\n') {
3464       unsigned i = 0;
3465       const char *s = 0;
3466
3467       if (numChars == 0)
3468         continue;
3469
3470       line[numChars] = '\0';
3471       numChars = 0;
3472
3473       if (line[0] == '/' && line[1] == '/')
3474         continue;
3475
3476       s = strtok(line, " ");
3477       while (s) {
3478         args[i] = s;
3479         ++i;
3480         s = strtok(0, " ");
3481       }
3482       if (print_usrs(&args[0], &args[i]))
3483         return 1;
3484     }
3485     else
3486       line[numChars++] = c;
3487   }
3488
3489   fclose(fp);
3490   return 0;
3491 }
3492
3493 /******************************************************************************/
3494 /* Command line processing.                                                   */
3495 /******************************************************************************/
3496 int write_pch_file(const char *filename, int argc, const char *argv[]) {
3497   CXIndex Idx;
3498   CXTranslationUnit TU;
3499   struct CXUnsavedFile *unsaved_files = 0;
3500   int num_unsaved_files = 0;
3501   int result = 0;
3502   
3503   Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
3504   
3505   if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3506     clang_disposeIndex(Idx);
3507     return -1;
3508   }
3509   
3510   TU = clang_parseTranslationUnit(Idx, 0,
3511                                   argv + num_unsaved_files,
3512                                   argc - num_unsaved_files,
3513                                   unsaved_files,
3514                                   num_unsaved_files,
3515                                   CXTranslationUnit_Incomplete |
3516                                   CXTranslationUnit_DetailedPreprocessingRecord|
3517                                     CXTranslationUnit_ForSerialization);
3518   if (!TU) {
3519     fprintf(stderr, "Unable to load translation unit!\n");
3520     free_remapped_files(unsaved_files, num_unsaved_files);
3521     clang_disposeIndex(Idx);
3522     return 1;
3523   }
3524
3525   switch (clang_saveTranslationUnit(TU, filename, 
3526                                     clang_defaultSaveOptions(TU))) {
3527   case CXSaveError_None:
3528     break;
3529
3530   case CXSaveError_TranslationErrors:
3531     fprintf(stderr, "Unable to write PCH file %s: translation errors\n", 
3532             filename);
3533     result = 2;    
3534     break;
3535
3536   case CXSaveError_InvalidTU:
3537     fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n", 
3538             filename);
3539     result = 3;    
3540     break;
3541
3542   case CXSaveError_Unknown:
3543   default:
3544     fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3545     result = 1;
3546     break;
3547   }
3548   
3549   clang_disposeTranslationUnit(TU);
3550   free_remapped_files(unsaved_files, num_unsaved_files);
3551   clang_disposeIndex(Idx);
3552   return result;
3553 }
3554
3555 /******************************************************************************/
3556 /* Serialized diagnostics.                                                    */
3557 /******************************************************************************/
3558
3559 static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3560   switch (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";
3565   }
3566   return "None";
3567 }
3568
3569 static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3570   switch (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";
3576   }
3577   return "unknown";
3578 }
3579
3580 static void printIndent(unsigned indent) {
3581   if (indent == 0)
3582     return;
3583   fprintf(stderr, "+");
3584   --indent;
3585   while (indent > 0) {
3586     fprintf(stderr, "-");
3587     --indent;
3588   }
3589 }
3590
3591 static void printLocation(CXSourceLocation L) {
3592   CXFile File;
3593   CXString FileName;
3594   unsigned line, column, offset;
3595   
3596   clang_getExpansionLocation(L, &File, &line, &column, &offset);
3597   FileName = clang_getFileName(File);
3598   
3599   fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3600   clang_disposeString(FileName);
3601 }
3602
3603 static void printRanges(CXDiagnostic D, unsigned indent) {
3604   unsigned i, n = clang_getDiagnosticNumRanges(D);
3605   
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);
3611     
3612     printIndent(indent);
3613     fprintf(stderr, "Range: ");
3614     printLocation(Start);
3615     fprintf(stderr, " ");
3616     printLocation(End);
3617     fprintf(stderr, "\n");
3618   }
3619 }
3620
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;
3626     CXString text;
3627     text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3628     
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);
3636   }  
3637 }
3638
3639 static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
3640   unsigned i, n;
3641
3642   if (!Diags)
3643     return;
3644   
3645   n = clang_getNumDiagnosticsInSet(Diags);
3646   for (i = 0; i < n; ++i) {
3647     CXSourceLocation DiagLoc;
3648     CXDiagnostic D;
3649     CXFile File;
3650     CXString FileName, DiagSpelling, DiagOption, DiagCat;
3651     unsigned line, column, offset;
3652     const char *DiagOptionStr = 0, *DiagCatStr = 0;
3653     
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);
3659     
3660     printIndent(indent);
3661     
3662     fprintf(stderr, "%s:%d:%d: %s: %s",
3663             clang_getCString(FileName),
3664             line,
3665             column,
3666             getSeverityString(clang_getDiagnosticSeverity(D)),
3667             clang_getCString(DiagSpelling));
3668
3669     DiagOption = clang_getDiagnosticOption(D, 0);
3670     DiagOptionStr = clang_getCString(DiagOption);
3671     if (DiagOptionStr) {
3672       fprintf(stderr, " [%s]", DiagOptionStr);
3673     }
3674     
3675     DiagCat = clang_getDiagnosticCategoryText(D);
3676     DiagCatStr = clang_getCString(DiagCat);
3677     if (DiagCatStr) {
3678       fprintf(stderr, " [%s]", DiagCatStr);
3679     }
3680     
3681     fprintf(stderr, "\n");
3682     
3683     printRanges(D, indent);
3684     printFixIts(D, indent);
3685     
3686     /* Print subdiagnostics. */
3687     printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3688
3689     clang_disposeString(FileName);
3690     clang_disposeString(DiagSpelling);
3691     clang_disposeString(DiagOption);
3692   }  
3693 }
3694
3695 static int read_diagnostics(const char *filename) {
3696   enum CXLoadDiag_Error error;
3697   CXString errorString;
3698   CXDiagnosticSet Diags = 0;
3699   
3700   Diags = clang_loadDiagnostics(filename, &error, &errorString);
3701   if (!Diags) {
3702     fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3703             getDiagnosticCodeStr(error),
3704             clang_getCString(errorString));
3705     clang_disposeString(errorString);
3706     return 1;
3707   }
3708   
3709   printDiagnosticSet(Diags, 0);
3710   fprintf(stderr, "Number of diagnostics: %d\n",
3711           clang_getNumDiagnosticsInSet(Diags));
3712   clang_disposeDiagnosticSet(Diags);
3713   return 0;
3714 }
3715
3716 /******************************************************************************/
3717 /* Command line processing.                                                   */
3718 /******************************************************************************/
3719
3720 static CXCursorVisitor GetVisitor(const char *s) {
3721   if (s[0] == '\0')
3722     return FilteredPrintingVisitor;
3723   if (strcmp(s, "-usrs") == 0)
3724     return USRVisitor;
3725   if (strncmp(s, "-memory-usage", 13) == 0)
3726     return GetVisitor(s + 13);
3727   return NULL;
3728 }
3729
3730 static void print_usage(void) {
3731   fprintf(stderr,
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");
3737   fprintf(stderr,
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");
3744   fprintf(stderr,
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");
3750   fprintf(stderr,
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> "
3754     "          {<args>}*\n"
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");
3761   fprintf(stderr,
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");
3769   fprintf(stderr,
3770     "       c-index-test -compilation-db [lookup <filename>] database\n");
3771   fprintf(stderr,
3772     "       c-index-test -read-diagnostics <file>\n\n");
3773   fprintf(stderr,
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");
3783 }
3784
3785 /***/
3786
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);
3811     if (I)
3812       return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
3813                                   NULL);
3814   }
3815   else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
3816     CXCursorVisitor I = GetVisitor(argv[1] + 25);
3817     if (I) {
3818       int trials = atoi(argv[2]);
3819       return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I, 
3820                                          NULL);
3821     }
3822   }
3823   else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
3824     CXCursorVisitor I = GetVisitor(argv[1] + 17);
3825     
3826     PostVisitTU postVisit = 0;
3827     if (strstr(argv[1], "-memory-usage"))
3828       postVisit = PrintMemoryUsage;
3829     
3830     if (I)
3831       return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
3832                                       postVisit);
3833   }
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,
3847                                     NULL);
3848   else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
3849     return perform_test_load_source(argc - 2, argv + 2, "all",
3850                                     PrintType, 0);
3851   else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
3852     return perform_test_load_source(argc - 2, argv + 2, "all",
3853                                     PrintTypeSize, 0);
3854   else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
3855     return perform_test_load_source(argc - 2, argv + 2, "all",
3856                                     PrintBitWidth, 0);
3857   else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
3858     if (argc > 2)
3859       return print_usrs(argv + 2, argv + argc);
3860     else {
3861       display_usrs();
3862       return 1;
3863     }
3864   }
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);
3871
3872   print_usage();
3873   return 1;
3874 }
3875
3876 /***/
3877
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
3880  * size). */
3881
3882 typedef struct thread_info {
3883   int argc;
3884   const char **argv;
3885   int result;
3886 } 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);
3890 #ifdef __CYGWIN__
3891   fflush(stdout);  /* stdout is not flushed on Cygwin. */
3892 #endif
3893 }
3894
3895 int main(int argc, const char **argv) {
3896   thread_info client_data;
3897
3898 #ifdef CLANG_HAVE_LIBXML
3899   LIBXML_TEST_VERSION
3900 #endif
3901
3902   if (getenv("CINDEXTEST_NOTHREADS"))
3903     return cindextest_main(argc, argv);
3904
3905   client_data.argc = argc;
3906   client_data.argv = argv;
3907   clang_executeOnThread(thread_runner, &client_data, 0);
3908   return client_data.result;
3909 }