blob: b77c88de58fa44906952feeeb4563f784d1b16c0 [file] [log] [blame]
Steve Naroff2b8ee6c2009-09-01 15:55:40 +00001/* c-index-test.c */
Steve Naroff50398192009-08-28 15:28:48 +00002
3#include "clang-c/Index.h"
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00004#include "clang-c/CXCompilationDatabase.h"
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00005#include "llvm/Config/config.h"
Douglas Gregor1e5e6682010-08-26 13:48:20 +00006#include <ctype.h>
Douglas Gregor0c8296d2009-11-07 00:00:49 +00007#include <stdlib.h>
Steve Naroff89922f82009-08-31 00:59:03 +00008#include <stdio.h>
Steve Naroffaf08ddc2009-09-03 15:49:00 +00009#include <string.h>
Douglas Gregorf2c87bd2010-01-15 19:40:17 +000010#include <assert.h>
Steve Naroffaf08ddc2009-09-03 15:49:00 +000011
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +000012#ifdef CLANG_HAVE_LIBXML
13#include <libxml/parser.h>
14#include <libxml/relaxng.h>
15#include <libxml/xmlerror.h>
16#endif
17
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +000018#ifdef _WIN32
19# include <direct.h>
20#else
21# include <unistd.h>
22#endif
23
Ted Kremenek0d435192009-11-17 18:13:31 +000024/******************************************************************************/
25/* Utility functions. */
26/******************************************************************************/
27
John Thompson2e06fc82009-10-27 13:42:56 +000028#ifdef _MSC_VER
29char *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}
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000042char *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)
NAKAMURA Takumi0fb474a2012-06-30 11:47:18 +000052 *base1 = 0;
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000053 else if (base2)
NAKAMURA Takumi0fb474a2012-06-30 11:47:18 +000054 *base2 = 0;
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000055
56 return path;
57}
John Thompson2e06fc82009-10-27 13:42:56 +000058#else
Steve Naroffff9e18c2009-09-24 20:03:06 +000059extern char *basename(const char *);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000060extern char *dirname(char *);
John Thompson2e06fc82009-10-27 13:42:56 +000061#endif
Steve Naroffff9e18c2009-09-24 20:03:06 +000062
Douglas Gregor45ba9a12010-07-25 17:39:21 +000063/** \brief Return the default parsing options. */
Douglas Gregor44c181a2010-07-23 00:33:23 +000064static unsigned getDefaultParsingOptions() {
65 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
66
67 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregorb1c031b2010-08-09 22:28:58 +000068 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregor87c08a52010-08-13 22:48:40 +000069 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
70 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidisdcaca012011-11-03 02:20:25 +000071 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
72 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6a91d382012-04-12 10:11:59 +000073 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
74 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +000075 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
76 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Douglas Gregor44c181a2010-07-23 00:33:23 +000077
78 return options;
79}
80
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +000081static int checkForErrors(CXTranslationUnit TU);
82
Daniel Dunbar51b058c2010-02-14 08:32:24 +000083static 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,
Daniel Dunbard52864b2010-02-14 10:02:57 +000086 end_line, end_column);
Daniel Dunbar51b058c2010-02-14 08:32:24 +000087}
88
Ted Kremenek1c6da172009-11-17 19:37:36 +000089static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
90 CXTranslationUnit *TU) {
Ted Kremeneke68fff62010-02-17 00:41:32 +000091
Douglas Gregora88084b2010-02-18 18:08:43 +000092 *TU = clang_createTranslationUnit(Idx, file);
Dan Gohman6be2a222010-07-26 21:44:15 +000093 if (!*TU) {
Ted Kremenek1c6da172009-11-17 19:37:36 +000094 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
95 return 0;
Ted Kremeneke68fff62010-02-17 00:41:32 +000096 }
Ted Kremenek1c6da172009-11-17 19:37:36 +000097 return 1;
98}
99
Douglas Gregor4db64a42010-01-23 00:14:00 +0000100void 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 }
Douglas Gregor653a55f2010-08-19 20:50:29 +0000107 free(unsaved_files);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000108}
109
110int 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;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000118
Douglas Gregor4db64a42010-01-23 00:14:00 +0000119 /* 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;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000123
Douglas Gregor4db64a42010-01-23 00:14:00 +0000124 ++*num_unsaved_files;
125 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000126
Douglas Gregor4db64a42010-01-23 00:14:00 +0000127 if (*num_unsaved_files == 0)
128 return 0;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000129
Douglas Gregor4db64a42010-01-23 00:14:00 +0000130 *unsaved_files
Douglas Gregor653a55f2010-08-19 20:50:29 +0000131 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
132 *num_unsaved_files);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000133 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) {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000142 fprintf(stderr,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000143 "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 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000149
Douglas Gregor4db64a42010-01-23 00:14:00 +0000150 /* Open the file that we're remapping to. */
Francois Pichetc44fe4b2010-10-12 01:01:43 +0000151 to_file = fopen(semi + 1, "rb");
Douglas Gregor4db64a42010-01-23 00:14:00 +0000152 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 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000160
Douglas Gregor4db64a42010-01-23 00:14:00 +0000161 /* 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);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000165
Douglas Gregor4db64a42010-01-23 00:14:00 +0000166 /* 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);
Richard Smithe07c5f82012-07-05 08:20:49 +0000173 free(contents);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000174 *unsaved_files = 0;
175 *num_unsaved_files = 0;
176 return -1;
177 }
178 contents[unsaved->Length] = 0;
179 unsaved->Contents = contents;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000180
Douglas Gregor4db64a42010-01-23 00:14:00 +0000181 /* Close the file. */
182 fclose(to_file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000183
Douglas Gregor4db64a42010-01-23 00:14:00 +0000184 /* 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 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000191
Douglas Gregor4db64a42010-01-23 00:14:00 +0000192 return 0;
193}
194
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000195static 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
Ted Kremenek0d435192009-11-17 18:13:31 +0000208/******************************************************************************/
209/* Pretty-printing. */
210/******************************************************************************/
211
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000212static const char *FileCheckPrefix = "CHECK";
213
214static void PrintCString(const char *CStr) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +0000215 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 }
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000228}
229
230static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
231 printf(" %s=[", Prefix);
232 PrintCString(CStr);
Dmitri Gribenko2d44d772012-06-26 20:39:18 +0000233 printf("]");
234}
235
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000236static void PrintCXStringAndDispose(CXString Str) {
237 PrintCString(clang_getCString(Str));
238 clang_disposeString(Str);
239}
240
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000241static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
242 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
243}
244
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000245static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
246 CXString Str) {
247 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
248 clang_disposeString(Str);
249}
250
Douglas Gregor430d7a12011-07-25 17:48:11 +0000251static 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
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +0000262 if (str)
263 printf(" %s=", str);
Douglas Gregor430d7a12011-07-25 17:48:11 +0000264 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
265}
266
Douglas Gregor358559d2010-10-02 22:49:11 +0000267int want_display_name = 0;
268
Douglas Gregorcc889662012-05-08 00:14:45 +0000269static 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
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000283struct CommentASTDumpingContext {
284 int IndentLevel;
285};
286
287static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
288 CXComment Comment) {
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000289 unsigned i;
290 unsigned e;
291 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
292
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000293 Ctx->IndentLevel++;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000294 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000295 printf(" ");
296
297 printf("(");
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000298 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));
Dmitri Gribenko2d66a502012-07-23 16:43:01 +0000316 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 }
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000330 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000331 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;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000339 case CXComment_HTMLStartTag: {
340 unsigned NumAttrs;
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000341 printf("CXComment_HTMLStartTag");
342 PrintCXStringWithPrefixAndDispose(
343 "Name",
344 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000345 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000346 if (NumAttrs != 0) {
347 printf(" Attrs:");
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000348 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000349 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;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000360 }
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000361 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));
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000379 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000380 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;
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000411 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;
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000428 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);
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000452 unsigned i;
453 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000454 printf("\n// %s: ", FileCheckPrefix);
455 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
456 }
457 }
458 printf(")");
459 Ctx->IndentLevel--;
460}
461
462static 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
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000470typedef struct {
471 const char *CommentSchemaFile;
472#ifdef CLANG_HAVE_LIBXML
473 xmlRelaxNGParserCtxtPtr RNGParser;
474 xmlRelaxNGPtr Schema;
475#endif
476} CommentXMLValidationData;
477
478static 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
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000521static void PrintCursorComments(CXCursor Cursor,
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000522 CommentXMLValidationData *ValidationData) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000523 {
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));
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000549 {
550 CXString XML;
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000551 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000552 PrintCXStringWithPrefix("FullCommentAsXML", XML);
553 ValidateCommentXML(clang_getCString(XML), ValidationData);
554 clang_disposeString(XML);
555 }
556
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000557 DumpCXComment(Comment);
558 }
559 }
560}
561
Argyrios Kyrtzidisb3dd9882012-08-22 23:15:52 +0000562typedef struct {
563 unsigned line;
564 unsigned col;
565} LineCol;
566
567static 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
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000575static void PrintCursor(CXCursor Cursor,
576 CommentXMLValidationData *ValidationData) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000577 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000578 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 }
Steve Naroff699a07d2009-09-25 21:32:34 +0000583 else {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000584 CXString string, ks;
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000585 CXCursor Referenced;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000586 unsigned line, column;
Douglas Gregore0329ac2010-09-02 00:07:54 +0000587 CXCursor SpecializationOf;
Douglas Gregor9f592342010-10-01 20:25:15 +0000588 CXCursor *overridden;
589 unsigned num_overridden;
Douglas Gregor430d7a12011-07-25 17:48:11 +0000590 unsigned RefNameRangeNr;
591 CXSourceRange CursorExtent;
592 CXSourceRange RefNameRange;
Douglas Gregorcc889662012-05-08 00:14:45 +0000593 int AlwaysUnavailable;
594 int AlwaysDeprecated;
595 CXString UnavailableMessage;
596 CXString DeprecatedMessage;
597 CXPlatformAvailability PlatformAvailability[2];
598 int NumPlatformAvailability;
599 int I;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000600
Ted Kremeneke68fff62010-02-17 00:41:32 +0000601 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor358559d2010-10-02 22:49:11 +0000602 string = want_display_name? clang_getCursorDisplayName(Cursor)
603 : clang_getCursorSpelling(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000604 printf("%s=%s", clang_getCString(ks),
605 clang_getCString(string));
606 clang_disposeString(ks);
Steve Naroffef0cef62009-11-09 17:45:52 +0000607 clang_disposeString(string);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000608
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000609 Referenced = clang_getCursorReferenced(Cursor);
610 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000611 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);
Douglas Gregor1f6206e2010-09-14 00:20:32 +0000616 CXSourceLocation Loc;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000617 if (I)
618 printf(", ");
619
Douglas Gregor1f6206e2010-09-14 00:20:32 +0000620 Loc = clang_getCursorLocation(Ovl);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000621 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000622 printf("%d:%d", line, column);
623 }
624 printf("]");
625 } else {
626 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000627 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000628 printf(":%d:%d", line, column);
629 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000630 }
Douglas Gregorb6998662010-01-19 19:34:47 +0000631
632 if (clang_isCursorDefinition(Cursor))
633 printf(" (Definition)");
Douglas Gregor58ddb602010-08-23 23:00:57 +0000634
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;
Erik Verbruggend1205962011-10-06 07:27:49 +0000646
647 case CXAvailability_NotAccessible:
648 printf(" (inaccessible)");
649 break;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000650 }
Ted Kremenek95f33552010-08-26 01:42:22 +0000651
Douglas Gregorcc889662012-05-08 00:14:45 +0000652 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
Douglas Gregorb83d4d72011-05-13 15:54:42 +0000693 if (clang_CXXMethod_isStatic(Cursor))
694 printf(" (static)");
695 if (clang_CXXMethod_isVirtual(Cursor))
696 printf(" (virtual)");
697
Ted Kremenek95f33552010-08-26 01:42:22 +0000698 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
699 CXType T =
700 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
701 CXString S = clang_getTypeKindSpelling(T.kind);
702 printf(" [IBOutletCollection=%s]", clang_getCString(S));
703 clang_disposeString(S);
704 }
Ted Kremenek3064ef92010-08-27 21:34:58 +0000705
706 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
707 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
708 unsigned isVirtual = clang_isVirtualBase(Cursor);
709 const char *accessStr = 0;
710
711 switch (access) {
712 case CX_CXXInvalidAccessSpecifier:
713 accessStr = "invalid"; break;
714 case CX_CXXPublic:
715 accessStr = "public"; break;
716 case CX_CXXProtected:
717 accessStr = "protected"; break;
718 case CX_CXXPrivate:
719 accessStr = "private"; break;
720 }
721
722 printf(" [access=%s isVirtual=%s]", accessStr,
723 isVirtual ? "true" : "false");
724 }
Douglas Gregore0329ac2010-09-02 00:07:54 +0000725
726 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
727 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
728 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
729 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000730 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregore0329ac2010-09-02 00:07:54 +0000731 printf(" [Specialization of %s:%d:%d]",
732 clang_getCString(Name), line, column);
733 clang_disposeString(Name);
734 }
Douglas Gregor9f592342010-10-01 20:25:15 +0000735
736 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
737 if (num_overridden) {
738 unsigned I;
Argyrios Kyrtzidisb3dd9882012-08-22 23:15:52 +0000739 LineCol lineCols[50];
740 assert(num_overridden <= 50);
Douglas Gregor9f592342010-10-01 20:25:15 +0000741 printf(" [Overrides ");
742 for (I = 0; I != num_overridden; ++I) {
743 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000744 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidisb3dd9882012-08-22 23:15:52 +0000745 lineCols[I].line = line;
746 lineCols[I].col = column;
747 }
Michael Liao64221492012-08-30 00:45:32 +0000748 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidisb3dd9882012-08-22 23:15:52 +0000749 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
750 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor9f592342010-10-01 20:25:15 +0000751 if (I)
752 printf(", ");
Argyrios Kyrtzidisb3dd9882012-08-22 23:15:52 +0000753 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor9f592342010-10-01 20:25:15 +0000754 }
755 printf("]");
756 clang_disposeOverriddenCursors(overridden);
757 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000758
759 if (Cursor.kind == CXCursor_InclusionDirective) {
760 CXFile File = clang_getIncludedFile(Cursor);
761 CXString Included = clang_getFileName(File);
762 printf(" (%s)", clang_getCString(Included));
763 clang_disposeString(Included);
Douglas Gregordd3e5542011-05-04 00:14:37 +0000764
765 if (clang_isFileMultipleIncludeGuarded(TU, File))
766 printf(" [multi-include guarded]");
Douglas Gregorecdcb882010-10-20 22:00:55 +0000767 }
Douglas Gregor430d7a12011-07-25 17:48:11 +0000768
769 CursorExtent = clang_getCursorExtent(Cursor);
770 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
771 CXNameRange_WantQualifier
772 | CXNameRange_WantSinglePiece
773 | CXNameRange_WantTemplateArgs,
774 0);
775 if (!clang_equalRanges(CursorExtent, RefNameRange))
776 PrintRange(RefNameRange, "SingleRefName");
777
778 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
779 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
780 CXNameRange_WantQualifier
781 | CXNameRange_WantTemplateArgs,
782 RefNameRangeNr);
783 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
784 break;
785 if (!clang_equalRanges(CursorExtent, RefNameRange))
786 PrintRange(RefNameRange, "RefName");
787 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000788
Dmitri Gribenkoe4330a32012-09-10 20:32:42 +0000789 PrintCursorComments(Cursor, ValidationData);
Steve Naroff699a07d2009-09-25 21:32:34 +0000790 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000791}
Steve Naroff89922f82009-08-31 00:59:03 +0000792
Ted Kremeneke68fff62010-02-17 00:41:32 +0000793static const char* GetCursorSource(CXCursor Cursor) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000794 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenek74844072010-02-17 00:41:20 +0000795 CXString source;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000796 CXFile file;
Argyrios Kyrtzidisb4efaa02011-11-03 02:20:36 +0000797 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000798 source = clang_getFileName(file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000799 if (!clang_getCString(source)) {
Ted Kremenek74844072010-02-17 00:41:20 +0000800 clang_disposeString(source);
801 return "<invalid loc>";
802 }
803 else {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000804 const char *b = basename(clang_getCString(source));
Ted Kremenek74844072010-02-17 00:41:20 +0000805 clang_disposeString(source);
806 return b;
807 }
Ted Kremenek9298cfc2009-11-17 05:31:58 +0000808}
809
Ted Kremenek0d435192009-11-17 18:13:31 +0000810/******************************************************************************/
Ted Kremenekce2ae882010-01-26 17:59:48 +0000811/* Callbacks. */
812/******************************************************************************/
813
814typedef void (*PostVisitTU)(CXTranslationUnit);
815
Douglas Gregora88084b2010-02-18 18:08:43 +0000816void PrintDiagnostic(CXDiagnostic Diagnostic) {
817 FILE *out = stderr;
Douglas Gregor5352ac02010-01-28 00:27:43 +0000818 CXFile file;
Douglas Gregor274f1902010-02-22 23:17:23 +0000819 CXString Msg;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000820 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000821 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
822 | CXDiagnostic_DisplayOption;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000823 unsigned i, num_fixits;
Ted Kremenekf7b714d2010-03-25 02:00:39 +0000824
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000825 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor5352ac02010-01-28 00:27:43 +0000826 return;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000827
Douglas Gregor274f1902010-02-22 23:17:23 +0000828 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
829 fprintf(stderr, "%s\n", clang_getCString(Msg));
830 clang_disposeString(Msg);
Ted Kremenekf7b714d2010-03-25 02:00:39 +0000831
Douglas Gregora9b06d42010-11-09 06:24:54 +0000832 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
833 &file, 0, 0, 0);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000834 if (!file)
835 return;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000836
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000837 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek3739b322012-03-20 20:49:45 +0000838 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000839 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor473d7012010-02-19 18:16:06 +0000840 CXSourceRange range;
841 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
842 CXSourceLocation start = clang_getRangeStart(range);
843 CXSourceLocation end = clang_getRangeEnd(range);
844 unsigned start_line, start_column, end_line, end_column;
845 CXFile start_file, end_file;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000846 clang_getSpellingLocation(start, &start_file, &start_line,
847 &start_column, 0);
848 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor473d7012010-02-19 18:16:06 +0000849 if (clang_equalLocations(start, end)) {
850 /* Insertion. */
851 if (start_file == file)
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000852 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor473d7012010-02-19 18:16:06 +0000853 clang_getCString(insertion_text), start_line, start_column);
854 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
855 /* Removal. */
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000856 if (start_file == file && end_file == file) {
857 fprintf(out, "FIX-IT: Remove ");
858 PrintExtent(out, start_line, start_column, end_line, end_column);
859 fprintf(out, "\n");
Douglas Gregor51c6d382010-01-29 00:41:11 +0000860 }
Douglas Gregor473d7012010-02-19 18:16:06 +0000861 } else {
862 /* Replacement. */
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000863 if (start_file == end_file) {
864 fprintf(out, "FIX-IT: Replace ");
865 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor473d7012010-02-19 18:16:06 +0000866 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor436f3f02010-02-18 22:27:07 +0000867 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000868 break;
869 }
Douglas Gregor473d7012010-02-19 18:16:06 +0000870 clang_disposeString(insertion_text);
Douglas Gregor51c6d382010-01-29 00:41:11 +0000871 }
Douglas Gregor5352ac02010-01-28 00:27:43 +0000872}
873
Ted Kremenek7473b1c2012-02-14 02:46:03 +0000874void PrintDiagnosticSet(CXDiagnosticSet Set) {
875 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
876 for ( ; i != n ; ++i) {
877 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
878 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregora88084b2010-02-18 18:08:43 +0000879 PrintDiagnostic(Diag);
Ted Kremenek7473b1c2012-02-14 02:46:03 +0000880 if (ChildDiags)
881 PrintDiagnosticSet(ChildDiags);
882 }
883}
884
885void PrintDiagnostics(CXTranslationUnit TU) {
886 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
887 PrintDiagnosticSet(TUSet);
888 clang_disposeDiagnosticSet(TUSet);
Douglas Gregora88084b2010-02-18 18:08:43 +0000889}
890
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000891void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayb2273232011-08-29 16:37:29 +0000892 unsigned long total = 0;
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000893 unsigned i = 0;
Ted Kremenekf7870022011-04-20 16:41:07 +0000894 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet3c683362011-04-18 23:33:22 +0000895 fprintf(stderr, "Memory usage:\n");
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000896 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenekf7870022011-04-20 16:41:07 +0000897 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000898 unsigned long amount = usage.entries[i].amount;
899 total += amount;
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000900 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000901 ((double) amount)/(1024*1024));
902 }
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000903 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000904 ((double) total)/(1024*1024));
Ted Kremenekf7870022011-04-20 16:41:07 +0000905 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000906}
907
Ted Kremenekce2ae882010-01-26 17:59:48 +0000908/******************************************************************************/
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000909/* Logic for testing traversal. */
Ted Kremenek0d435192009-11-17 18:13:31 +0000910/******************************************************************************/
911
Douglas Gregora7bde202010-01-19 00:34:46 +0000912static void PrintCursorExtent(CXCursor C) {
913 CXSourceRange extent = clang_getCursorExtent(C);
Douglas Gregor430d7a12011-07-25 17:48:11 +0000914 PrintRange(extent, "Extent");
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000915}
916
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000917/* Data used by the visitors. */
918typedef struct {
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000919 CXTranslationUnit TU;
920 enum CXCursorKind *Filter;
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000921 CommentXMLValidationData ValidationData;
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000922} VisitorData;
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000923
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000924
Ted Kremeneke68fff62010-02-17 00:41:32 +0000925enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000926 CXCursor Parent,
927 CXClientData ClientData) {
928 VisitorData *Data = (VisitorData *)ClientData;
929 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000930 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000931 unsigned line, column;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000932 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000933 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor1db19de2010-01-19 21:36:55 +0000934 GetCursorSource(Cursor), line, column);
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +0000935 PrintCursor(Cursor, &Data->ValidationData);
Douglas Gregora7bde202010-01-19 00:34:46 +0000936 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis04b67482013-04-11 17:02:10 +0000937 if (clang_isDeclaration(Cursor.kind)) {
938 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
939 const char *accessStr = 0;
940
941 switch (access) {
942 case CX_CXXInvalidAccessSpecifier: break;
943 case CX_CXXPublic:
944 accessStr = "public"; break;
945 case CX_CXXProtected:
946 accessStr = "protected"; break;
947 case CX_CXXPrivate:
948 accessStr = "private"; break;
949 }
950
951 if (accessStr)
952 printf(" [access=%s]", accessStr);
953 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000954 printf("\n");
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000955 return CXChildVisit_Recurse;
Steve Naroff2d4d6292009-08-31 14:26:51 +0000956 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000957
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000958 return CXChildVisit_Continue;
Steve Naroff89922f82009-08-31 00:59:03 +0000959}
Steve Naroff50398192009-08-28 15:28:48 +0000960
Ted Kremeneke68fff62010-02-17 00:41:32 +0000961static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000962 CXCursor Parent,
963 CXClientData ClientData) {
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000964 const char *startBuf, *endBuf;
965 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
966 CXCursor Ref;
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000967 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000968
Douglas Gregorb6998662010-01-19 19:34:47 +0000969 if (Cursor.kind != CXCursor_FunctionDecl ||
970 !clang_isCursorDefinition(Cursor))
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000971 return CXChildVisit_Continue;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000972
973 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
974 &startLine, &startColumn,
975 &endLine, &endColumn);
976 /* Probe the entire body, looking for both decls and refs. */
977 curLine = startLine;
978 curColumn = startColumn;
979
980 while (startBuf < endBuf) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000981 CXSourceLocation Loc;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000982 CXFile file;
Ted Kremenek74844072010-02-17 00:41:20 +0000983 CXString source;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000984
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000985 if (*startBuf == '\n') {
986 startBuf++;
987 curLine++;
988 curColumn = 1;
989 } else if (*startBuf != '\t')
990 curColumn++;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000991
Douglas Gregor98258af2010-01-18 22:46:11 +0000992 Loc = clang_getCursorLocation(Cursor);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000993 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000994
Douglas Gregor1db19de2010-01-19 21:36:55 +0000995 source = clang_getFileName(file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000996 if (clang_getCString(source)) {
Douglas Gregorb9790342010-01-22 21:44:22 +0000997 CXSourceLocation RefLoc
998 = clang_getLocation(Data->TU, file, curLine, curColumn);
999 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor98258af2010-01-18 22:46:11 +00001000 if (Ref.kind == CXCursor_NoDeclFound) {
1001 /* Nothing found here; that's fine. */
1002 } else if (Ref.kind != CXCursor_FunctionDecl) {
1003 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1004 curLine, curColumn);
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001005 PrintCursor(Ref, &Data->ValidationData);
Douglas Gregor98258af2010-01-18 22:46:11 +00001006 printf("\n");
1007 }
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001008 }
Ted Kremenek74844072010-02-17 00:41:20 +00001009 clang_disposeString(source);
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001010 startBuf++;
1011 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001012
Douglas Gregore5b72ba2010-01-20 21:32:04 +00001013 return CXChildVisit_Continue;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001014}
1015
Ted Kremenek7d405622010-01-12 23:34:26 +00001016/******************************************************************************/
1017/* USR testing. */
1018/******************************************************************************/
1019
Douglas Gregore5b72ba2010-01-20 21:32:04 +00001020enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1021 CXClientData ClientData) {
1022 VisitorData *Data = (VisitorData *)ClientData;
1023 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Ted Kremenekcf84aa42010-01-18 20:23:29 +00001024 CXString USR = clang_getCursorUSR(C);
Ted Kremeneke542f772010-04-20 23:15:40 +00001025 const char *cstr = clang_getCString(USR);
1026 if (!cstr || cstr[0] == '\0') {
Ted Kremenek7d405622010-01-12 23:34:26 +00001027 clang_disposeString(USR);
Ted Kremeneke74ef122010-04-16 21:31:52 +00001028 return CXChildVisit_Recurse;
Ted Kremenek7d405622010-01-12 23:34:26 +00001029 }
Ted Kremeneke542f772010-04-20 23:15:40 +00001030 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1031
Douglas Gregora7bde202010-01-19 00:34:46 +00001032 PrintCursorExtent(C);
Ted Kremenek7d405622010-01-12 23:34:26 +00001033 printf("\n");
1034 clang_disposeString(USR);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001035
Douglas Gregore5b72ba2010-01-20 21:32:04 +00001036 return CXChildVisit_Recurse;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001037 }
1038
Douglas Gregore5b72ba2010-01-20 21:32:04 +00001039 return CXChildVisit_Continue;
Ted Kremenek7d405622010-01-12 23:34:26 +00001040}
1041
1042/******************************************************************************/
Ted Kremenek16b55a72010-01-26 19:31:51 +00001043/* Inclusion stack testing. */
1044/******************************************************************************/
1045
1046void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1047 unsigned includeStackLen, CXClientData data) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001048
Ted Kremenek16b55a72010-01-26 19:31:51 +00001049 unsigned i;
Ted Kremenek74844072010-02-17 00:41:20 +00001050 CXString fname;
1051
1052 fname = clang_getFileName(includedFile);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001053 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenek74844072010-02-17 00:41:20 +00001054 clang_disposeString(fname);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001055
Ted Kremenek16b55a72010-01-26 19:31:51 +00001056 for (i = 0; i < includeStackLen; ++i) {
1057 CXFile includingFile;
1058 unsigned line, column;
Douglas Gregora9b06d42010-11-09 06:24:54 +00001059 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1060 &column, 0);
Ted Kremenek74844072010-02-17 00:41:20 +00001061 fname = clang_getFileName(includingFile);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001062 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenek74844072010-02-17 00:41:20 +00001063 clang_disposeString(fname);
Ted Kremenek16b55a72010-01-26 19:31:51 +00001064 }
1065 printf("\n");
1066}
1067
1068void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001069 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek16b55a72010-01-26 19:31:51 +00001070}
1071
1072/******************************************************************************/
Ted Kremenek3bed5272010-03-03 06:37:58 +00001073/* Linkage testing. */
1074/******************************************************************************/
1075
1076static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1077 CXClientData d) {
1078 const char *linkage = 0;
1079
1080 if (clang_isInvalid(clang_getCursorKind(cursor)))
1081 return CXChildVisit_Recurse;
1082
1083 switch (clang_getCursorLinkage(cursor)) {
1084 case CXLinkage_Invalid: break;
Douglas Gregorc2a2b3c2010-03-04 19:36:27 +00001085 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1086 case CXLinkage_Internal: linkage = "Internal"; break;
1087 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1088 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek3bed5272010-03-03 06:37:58 +00001089 }
1090
1091 if (linkage) {
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001092 PrintCursor(cursor, NULL);
Ted Kremenek3bed5272010-03-03 06:37:58 +00001093 printf("linkage=%s\n", linkage);
1094 }
1095
1096 return CXChildVisit_Recurse;
1097}
1098
1099/******************************************************************************/
Ted Kremenek8e0ac172010-05-14 21:29:26 +00001100/* Typekind testing. */
1101/******************************************************************************/
1102
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00001103static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1104 CXString TypeSpelling, TypeKindSpelling;
1105
1106 TypeSpelling = clang_getTypeSpelling(T);
1107 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1108 printf(Format,
1109 clang_getCString(TypeSpelling),
1110 clang_getCString(TypeKindSpelling));
1111 clang_disposeString(TypeSpelling);
1112 clang_disposeString(TypeKindSpelling);
1113}
1114
1115static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1116 CXClientData d) {
Ted Kremenek8e0ac172010-05-14 21:29:26 +00001117 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
1118 CXType T = clang_getCursorType(cursor);
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001119 PrintCursor(cursor, NULL);
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00001120 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregore72fb6f2011-01-27 16:27:11 +00001121 if (clang_isConstQualifiedType(T))
1122 printf(" const");
1123 if (clang_isVolatileQualifiedType(T))
1124 printf(" volatile");
1125 if (clang_isRestrictQualifiedType(T))
1126 printf(" restrict");
Benjamin Kramere1403d22010-06-22 09:29:44 +00001127 /* Print the canonical type if it is different. */
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001128 {
1129 CXType CT = clang_getCanonicalType(T);
1130 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00001131 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001132 }
1133 }
Benjamin Kramere1403d22010-06-22 09:29:44 +00001134 /* Print the return type if it exists. */
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001135 {
Ted Kremenek9a140842010-06-21 20:48:56 +00001136 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001137 if (RT.kind != CXType_Invalid) {
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00001138 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001139 }
1140 }
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001141 /* Print the argument types if they exist. */
1142 {
1143 int numArgs = clang_Cursor_getNumArguments(cursor);
1144 if (numArgs != -1 && numArgs != 0) {
Argyrios Kyrtzidis47f11652012-04-11 19:54:09 +00001145 int i;
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001146 printf(" [args=");
Argyrios Kyrtzidis47f11652012-04-11 19:54:09 +00001147 for (i = 0; i < numArgs; ++i) {
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001148 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
1149 if (T.kind != CXType_Invalid) {
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00001150 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001151 }
1152 }
1153 printf("]");
1154 }
1155 }
Ted Kremenek3ce9e7d2010-07-30 00:14:11 +00001156 /* Print if this is a non-POD type. */
1157 printf(" [isPOD=%d]", clang_isPODType(T));
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001158
Ted Kremenek8e0ac172010-05-14 21:29:26 +00001159 printf("\n");
1160 }
1161 return CXChildVisit_Recurse;
1162}
1163
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00001164static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1165 CXClientData d) {
1166 CXType T;
1167 enum CXCursorKind K = clang_getCursorKind(cursor);
1168 if (clang_isInvalid(K))
1169 return CXChildVisit_Recurse;
1170 T = clang_getCursorType(cursor);
1171 PrintCursor(cursor, NULL);
1172 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1173 /* Print the type sizeof if applicable. */
1174 {
1175 long long Size = clang_Type_getSizeOf(T);
1176 if (Size >= 0 || Size < -1 ) {
1177 printf(" [sizeof=%lld]", Size);
1178 }
1179 }
1180 /* Print the type alignof if applicable. */
1181 {
1182 long long Align = clang_Type_getAlignOf(T);
1183 if (Align >= 0 || Align < -1) {
1184 printf(" [alignof=%lld]", Align);
1185 }
1186 }
1187 /* Print the record field offset if applicable. */
1188 {
1189 const char *FieldName = clang_getCString(clang_getCursorSpelling(cursor));
1190 /* recurse to get the root anonymous record parent */
1191 CXCursor Parent, Root;
1192 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl ) {
1193 const char *RootParentName;
1194 Root = Parent = p;
1195 do {
1196 Root = Parent;
1197 RootParentName = clang_getCString(clang_getCursorSpelling(Root));
1198 Parent = clang_getCursorSemanticParent(Root);
1199 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1200 !strcmp(RootParentName, "") );
1201 /* if RootParentName is "", record is anonymous. */
1202 {
1203 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Root),
1204 FieldName);
1205 printf(" [offsetof=%lld]", Offset);
1206 }
1207 }
1208 }
1209 /* Print if its a bitfield */
1210 {
1211 int IsBitfield = clang_Cursor_isBitField(cursor);
1212 if (IsBitfield)
1213 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1214 }
1215 printf("\n");
1216 return CXChildVisit_Recurse;
1217}
1218
Dmitri Gribenko1eb60822012-12-04 15:13:46 +00001219/******************************************************************************/
1220/* Bitwidth testing. */
1221/******************************************************************************/
1222
1223static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1224 CXClientData d) {
NAKAMURA Takumi02c1b862012-12-04 15:32:03 +00001225 int Bitwidth;
Dmitri Gribenko1eb60822012-12-04 15:13:46 +00001226 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1227 return CXChildVisit_Recurse;
1228
NAKAMURA Takumi02c1b862012-12-04 15:32:03 +00001229 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenko1eb60822012-12-04 15:13:46 +00001230 if (Bitwidth >= 0) {
1231 PrintCursor(cursor, NULL);
1232 printf(" bitwidth=%d\n", Bitwidth);
1233 }
1234
1235 return CXChildVisit_Recurse;
1236}
Ted Kremenek8e0ac172010-05-14 21:29:26 +00001237
1238/******************************************************************************/
Ted Kremenek7d405622010-01-12 23:34:26 +00001239/* Loading ASTs/source. */
1240/******************************************************************************/
1241
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001242static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek98271562010-01-12 18:53:15 +00001243 const char *filter, const char *prefix,
Ted Kremenekce2ae882010-01-26 17:59:48 +00001244 CXCursorVisitor Visitor,
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001245 PostVisitTU PV,
1246 const char *CommentSchemaFile) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001247
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00001248 if (prefix)
Ted Kremeneke68fff62010-02-17 00:41:32 +00001249 FileCheckPrefix = prefix;
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001250
1251 if (Visitor) {
1252 enum CXCursorKind K = CXCursor_NotImplemented;
1253 enum CXCursorKind *ck = &K;
1254 VisitorData Data;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001255
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001256 /* Perform some simple filtering. */
1257 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor358559d2010-10-02 22:49:11 +00001258 else if (!strcmp(filter, "all-display") ||
1259 !strcmp(filter, "local-display")) {
1260 ck = NULL;
1261 want_display_name = 1;
1262 }
Daniel Dunbarb1ffee62010-02-10 20:42:40 +00001263 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001264 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1265 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1266 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1267 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1268 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1269 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1270 else {
1271 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1272 return 1;
1273 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001274
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001275 Data.TU = TU;
1276 Data.Filter = ck;
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001277 Data.ValidationData.CommentSchemaFile = CommentSchemaFile;
1278#ifdef CLANG_HAVE_LIBXML
1279 Data.ValidationData.RNGParser = NULL;
1280 Data.ValidationData.Schema = NULL;
1281#endif
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001282 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek0d435192009-11-17 18:13:31 +00001283 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001284
Ted Kremenekce2ae882010-01-26 17:59:48 +00001285 if (PV)
1286 PV(TU);
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001287
Douglas Gregora88084b2010-02-18 18:08:43 +00001288 PrintDiagnostics(TU);
Argyrios Kyrtzidis16ac8be2011-11-13 23:39:14 +00001289 if (checkForErrors(TU) != 0) {
1290 clang_disposeTranslationUnit(TU);
1291 return -1;
1292 }
1293
Ted Kremenek0d435192009-11-17 18:13:31 +00001294 clang_disposeTranslationUnit(TU);
1295 return 0;
1296}
1297
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00001298int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekce2ae882010-01-26 17:59:48 +00001299 const char *prefix, CXCursorVisitor Visitor,
1300 PostVisitTU PV) {
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001301 CXIndex Idx;
1302 CXTranslationUnit TU;
Ted Kremenek020a0952010-02-11 07:41:25 +00001303 int result;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001304 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001305 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitfc093362013-03-01 21:41:22 +00001306 /* displayDiagnostics=*/1);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001307
Ted Kremenek020a0952010-02-11 07:41:25 +00001308 if (!CreateTranslationUnit(Idx, file, &TU)) {
1309 clang_disposeIndex(Idx);
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001310 return 1;
Ted Kremenek020a0952010-02-11 07:41:25 +00001311 }
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001312
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001313 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek020a0952010-02-11 07:41:25 +00001314 clang_disposeIndex(Idx);
1315 return result;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001316}
1317
Ted Kremenekce2ae882010-01-26 17:59:48 +00001318int perform_test_load_source(int argc, const char **argv,
1319 const char *filter, CXCursorVisitor Visitor,
1320 PostVisitTU PV) {
Daniel Dunbarada487d2009-12-01 02:03:10 +00001321 CXIndex Idx;
1322 CXTranslationUnit TU;
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001323 const char *CommentSchemaFile;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001324 struct CXUnsavedFile *unsaved_files = 0;
1325 int num_unsaved_files = 0;
1326 int result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001327
Daniel Dunbarada487d2009-12-01 02:03:10 +00001328 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor358559d2010-10-02 22:49:11 +00001329 (!strcmp(filter, "local") ||
1330 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidiscd6dcb32013-04-09 20:29:24 +00001331 /* displayDiagnostics=*/1);
Daniel Dunbarada487d2009-12-01 02:03:10 +00001332
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001333 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1334 argc--;
1335 argv++;
1336 }
1337
Ted Kremenek020a0952010-02-11 07:41:25 +00001338 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1339 clang_disposeIndex(Idx);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001340 return -1;
Ted Kremenek020a0952010-02-11 07:41:25 +00001341 }
Douglas Gregor4db64a42010-01-23 00:14:00 +00001342
Douglas Gregordca8ee82011-05-06 16:33:08 +00001343 TU = clang_parseTranslationUnit(Idx, 0,
1344 argv + num_unsaved_files,
1345 argc - num_unsaved_files,
1346 unsaved_files, num_unsaved_files,
1347 getDefaultParsingOptions());
Daniel Dunbarada487d2009-12-01 02:03:10 +00001348 if (!TU) {
1349 fprintf(stderr, "Unable to load translation unit!\n");
Douglas Gregorabc563f2010-07-19 21:46:24 +00001350 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek020a0952010-02-11 07:41:25 +00001351 clang_disposeIndex(Idx);
Daniel Dunbarada487d2009-12-01 02:03:10 +00001352 return 1;
1353 }
1354
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001355 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1356 CommentSchemaFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001357 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek020a0952010-02-11 07:41:25 +00001358 clang_disposeIndex(Idx);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001359 return result;
Daniel Dunbarada487d2009-12-01 02:03:10 +00001360}
1361
Douglas Gregorabc563f2010-07-19 21:46:24 +00001362int perform_test_reparse_source(int argc, const char **argv, int trials,
1363 const char *filter, CXCursorVisitor Visitor,
1364 PostVisitTU PV) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001365 CXIndex Idx;
1366 CXTranslationUnit TU;
1367 struct CXUnsavedFile *unsaved_files = 0;
1368 int num_unsaved_files = 0;
1369 int result;
1370 int trial;
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001371 int remap_after_trial = 0;
1372 char *endptr = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001373
1374 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1375 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidiscd6dcb32013-04-09 20:29:24 +00001376 /* displayDiagnostics=*/1);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001377
Douglas Gregorabc563f2010-07-19 21:46:24 +00001378 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1379 clang_disposeIndex(Idx);
1380 return -1;
1381 }
1382
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001383 /* Load the initial translation unit -- we do this without honoring remapped
1384 * files, so that we have a way to test results after changing the source. */
Douglas Gregor44c181a2010-07-23 00:33:23 +00001385 TU = clang_parseTranslationUnit(Idx, 0,
1386 argv + num_unsaved_files,
1387 argc - num_unsaved_files,
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001388 0, 0, getDefaultParsingOptions());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001389 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
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001396 if (checkForErrors(TU) != 0)
1397 return -1;
1398
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001399 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1400 remap_after_trial =
1401 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1402 }
1403
Douglas Gregorabc563f2010-07-19 21:46:24 +00001404 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001405 if (clang_reparseTranslationUnit(TU,
1406 trial >= remap_after_trial ? num_unsaved_files : 0,
1407 trial >= remap_after_trial ? unsaved_files : 0,
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001408 clang_defaultReparseOptions(TU))) {
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001409 fprintf(stderr, "Unable to reparse translation unit!\n");
Douglas Gregorabc563f2010-07-19 21:46:24 +00001410 clang_disposeTranslationUnit(TU);
1411 free_remapped_files(unsaved_files, num_unsaved_files);
1412 clang_disposeIndex(Idx);
1413 return -1;
1414 }
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001415
1416 if (checkForErrors(TU) != 0)
1417 return -1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001418 }
1419
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001420 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001421
Douglas Gregorabc563f2010-07-19 21:46:24 +00001422 free_remapped_files(unsaved_files, num_unsaved_files);
1423 clang_disposeIndex(Idx);
1424 return result;
1425}
1426
Ted Kremenek0d435192009-11-17 18:13:31 +00001427/******************************************************************************/
Ted Kremenek1c6da172009-11-17 19:37:36 +00001428/* Logic for testing clang_getCursor(). */
1429/******************************************************************************/
1430
Douglas Gregordd3e5542011-05-04 00:14:37 +00001431static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek1c6da172009-11-17 19:37:36 +00001432 unsigned start_line, unsigned start_col,
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001433 unsigned end_line, unsigned end_col,
1434 const char *prefix) {
Ted Kremenek9096a202010-01-07 01:17:12 +00001435 printf("// %s: ", FileCheckPrefix);
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001436 if (prefix)
1437 printf("-%s", prefix);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00001438 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1439 printf(" ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00001440 PrintCursor(cursor, NULL);
Ted Kremenek1c6da172009-11-17 19:37:36 +00001441 printf("\n");
1442}
1443
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001444static int perform_file_scan(const char *ast_file, const char *source_file,
1445 const char *prefix) {
Ted Kremenek1c6da172009-11-17 19:37:36 +00001446 CXIndex Idx;
1447 CXTranslationUnit TU;
1448 FILE *fp;
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001449 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregorb9790342010-01-22 21:44:22 +00001450 CXFile file;
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001451 unsigned line = 1, col = 1;
Daniel Dunbar8f0bf812010-02-14 08:32:51 +00001452 unsigned start_line = 1, start_col = 1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001453
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001454 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitfc093362013-03-01 21:41:22 +00001455 /* displayDiagnostics=*/1))) {
Ted Kremenek1c6da172009-11-17 19:37:36 +00001456 fprintf(stderr, "Could not create Index\n");
1457 return 1;
1458 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001459
Ted Kremenek1c6da172009-11-17 19:37:36 +00001460 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1461 return 1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001462
Ted Kremenek1c6da172009-11-17 19:37:36 +00001463 if ((fp = fopen(source_file, "r")) == NULL) {
1464 fprintf(stderr, "Could not open '%s'\n", source_file);
1465 return 1;
1466 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001467
Douglas Gregorb9790342010-01-22 21:44:22 +00001468 file = clang_getFile(TU, source_file);
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001469 for (;;) {
1470 CXCursor cursor;
1471 int c = fgetc(fp);
Benjamin Kramera9933b92009-11-17 20:51:40 +00001472
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001473 if (c == '\n') {
1474 ++line;
1475 col = 1;
1476 } else
1477 ++col;
1478
1479 /* Check the cursor at this position, and dump the previous one if we have
1480 * found something new.
1481 */
1482 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1483 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1484 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregordd3e5542011-05-04 00:14:37 +00001485 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbard52864b2010-02-14 10:02:57 +00001486 line, col, prefix);
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001487 start_line = line;
1488 start_col = col;
Benjamin Kramera9933b92009-11-17 20:51:40 +00001489 }
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001490 if (c == EOF)
1491 break;
Benjamin Kramera9933b92009-11-17 20:51:40 +00001492
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001493 prevCursor = cursor;
Ted Kremenek1c6da172009-11-17 19:37:36 +00001494 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001495
Ted Kremenek1c6da172009-11-17 19:37:36 +00001496 fclose(fp);
Douglas Gregor4f5e21e2011-01-31 22:04:05 +00001497 clang_disposeTranslationUnit(TU);
1498 clang_disposeIndex(Idx);
Ted Kremenek1c6da172009-11-17 19:37:36 +00001499 return 0;
1500}
1501
1502/******************************************************************************/
Douglas Gregor32be4a52010-10-11 21:37:58 +00001503/* Logic for testing clang code completion. */
Ted Kremenek0d435192009-11-17 18:13:31 +00001504/******************************************************************************/
1505
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001506/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1507 on failure. If successful, the pointer *filename will contain newly-allocated
1508 memory (that will be owned by the caller) to store the file name. */
Ted Kremeneke68fff62010-02-17 00:41:32 +00001509int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001510 unsigned *column, unsigned *second_line,
1511 unsigned *second_column) {
Douglas Gregor88d23952009-11-09 18:19:57 +00001512 /* Find the second colon. */
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001513 const char *last_colon = strrchr(input, ':');
1514 unsigned values[4], i;
1515 unsigned num_values = (second_line && second_column)? 4 : 2;
1516
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001517 char *endptr = 0;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001518 if (!last_colon || last_colon == input) {
1519 if (num_values == 4)
1520 fprintf(stderr, "could not parse filename:line:column:line:column in "
1521 "'%s'\n", input);
1522 else
1523 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001524 return 1;
1525 }
1526
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001527 for (i = 0; i != num_values; ++i) {
1528 const char *prev_colon;
1529
1530 /* Parse the next line or column. */
1531 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1532 if (*endptr != 0 && *endptr != ':') {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001533 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001534 (i % 2 ? "column" : "line"), input);
1535 return 1;
1536 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001537
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001538 if (i + 1 == num_values)
1539 break;
1540
1541 /* Find the previous colon. */
1542 prev_colon = last_colon - 1;
1543 while (prev_colon != input && *prev_colon != ':')
1544 --prev_colon;
1545 if (prev_colon == input) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001546 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001547 (i % 2 == 0? "column" : "line"), input);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001548 return 1;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001549 }
1550
1551 last_colon = prev_colon;
Douglas Gregor88d23952009-11-09 18:19:57 +00001552 }
1553
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001554 *line = values[0];
1555 *column = values[1];
Ted Kremeneke68fff62010-02-17 00:41:32 +00001556
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001557 if (second_line && second_column) {
1558 *second_line = values[2];
1559 *second_column = values[3];
1560 }
1561
Douglas Gregor88d23952009-11-09 18:19:57 +00001562 /* Copy the file name. */
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001563 *filename = (char*)malloc(last_colon - input + 1);
1564 memcpy(*filename, input, last_colon - input);
1565 (*filename)[last_colon - input] = 0;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001566 return 0;
1567}
1568
1569const char *
1570clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1571 switch (Kind) {
1572 case CXCompletionChunk_Optional: return "Optional";
1573 case CXCompletionChunk_TypedText: return "TypedText";
1574 case CXCompletionChunk_Text: return "Text";
1575 case CXCompletionChunk_Placeholder: return "Placeholder";
1576 case CXCompletionChunk_Informative: return "Informative";
1577 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1578 case CXCompletionChunk_LeftParen: return "LeftParen";
1579 case CXCompletionChunk_RightParen: return "RightParen";
1580 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1581 case CXCompletionChunk_RightBracket: return "RightBracket";
1582 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1583 case CXCompletionChunk_RightBrace: return "RightBrace";
1584 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1585 case CXCompletionChunk_RightAngle: return "RightAngle";
1586 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001587 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor01dfea02010-01-10 23:08:15 +00001588 case CXCompletionChunk_Colon: return "Colon";
1589 case CXCompletionChunk_SemiColon: return "SemiColon";
1590 case CXCompletionChunk_Equal: return "Equal";
1591 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1592 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001593 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001594
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001595 return "Unknown";
1596}
1597
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001598static int checkForErrors(CXTranslationUnit TU) {
1599 unsigned Num, i;
1600 CXDiagnostic Diag;
1601 CXString DiagStr;
1602
1603 if (!getenv("CINDEXTEST_FAILONERROR"))
1604 return 0;
1605
1606 Num = clang_getNumDiagnostics(TU);
1607 for (i = 0; i != Num; ++i) {
1608 Diag = clang_getDiagnostic(TU, i);
1609 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1610 DiagStr = clang_formatDiagnostic(Diag,
1611 clang_defaultDiagnosticDisplayOptions());
1612 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1613 clang_disposeString(DiagStr);
1614 clang_disposeDiagnostic(Diag);
1615 return -1;
1616 }
1617 clang_disposeDiagnostic(Diag);
1618 }
1619
1620 return 0;
1621}
1622
Douglas Gregor3ac73852009-11-09 16:04:45 +00001623void print_completion_string(CXCompletionString completion_string, FILE *file) {
Daniel Dunbarf8297f12009-11-07 18:34:24 +00001624 int I, N;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001625
Douglas Gregor3ac73852009-11-09 16:04:45 +00001626 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001627 for (I = 0; I != N; ++I) {
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001628 CXString text;
1629 const char *cstr;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001630 enum CXCompletionChunkKind Kind
Douglas Gregor3ac73852009-11-09 16:04:45 +00001631 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001632
Douglas Gregor3ac73852009-11-09 16:04:45 +00001633 if (Kind == CXCompletionChunk_Optional) {
1634 fprintf(file, "{Optional ");
1635 print_completion_string(
Ted Kremeneke68fff62010-02-17 00:41:32 +00001636 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor3ac73852009-11-09 16:04:45 +00001637 file);
1638 fprintf(file, "}");
1639 continue;
Douglas Gregor5a9c0bc2010-10-08 20:39:29 +00001640 }
1641
1642 if (Kind == CXCompletionChunk_VerticalSpace) {
1643 fprintf(file, "{VerticalSpace }");
1644 continue;
Douglas Gregor3ac73852009-11-09 16:04:45 +00001645 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001646
Douglas Gregord5a20892009-11-09 17:05:28 +00001647 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001648 cstr = clang_getCString(text);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001649 fprintf(file, "{%s %s}",
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001650 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001651 cstr ? cstr : "");
1652 clang_disposeString(text);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001653 }
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001654
Douglas Gregor3ac73852009-11-09 16:04:45 +00001655}
1656
1657void print_completion_result(CXCompletionResult *completion_result,
1658 CXClientData client_data) {
1659 FILE *file = (FILE *)client_data;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001660 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen6164ea12011-10-14 15:31:08 +00001661 unsigned annotationCount;
Douglas Gregorba103062012-03-27 23:34:16 +00001662 enum CXCursorKind ParentKind;
1663 CXString ParentName;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001664 CXString BriefComment;
1665 const char *BriefCommentCString;
Douglas Gregorba103062012-03-27 23:34:16 +00001666
Ted Kremeneke68fff62010-02-17 00:41:32 +00001667 fprintf(file, "%s:", clang_getCString(ks));
1668 clang_disposeString(ks);
1669
Douglas Gregor3ac73852009-11-09 16:04:45 +00001670 print_completion_string(completion_result->CompletionString, file);
Douglas Gregor58ddb602010-08-23 23:00:57 +00001671 fprintf(file, " (%u)",
Douglas Gregor12e13132010-05-26 22:00:08 +00001672 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregor58ddb602010-08-23 23:00:57 +00001673 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1674 case CXAvailability_Available:
1675 break;
1676
1677 case CXAvailability_Deprecated:
1678 fprintf(file, " (deprecated)");
1679 break;
1680
1681 case CXAvailability_NotAvailable:
1682 fprintf(file, " (unavailable)");
1683 break;
Erik Verbruggend1205962011-10-06 07:27:49 +00001684
1685 case CXAvailability_NotAccessible:
1686 fprintf(file, " (inaccessible)");
1687 break;
Douglas Gregor58ddb602010-08-23 23:00:57 +00001688 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00001689
1690 annotationCount = clang_getCompletionNumAnnotations(
1691 completion_result->CompletionString);
1692 if (annotationCount) {
1693 unsigned i;
1694 fprintf(file, " (");
1695 for (i = 0; i < annotationCount; ++i) {
1696 if (i != 0)
1697 fprintf(file, ", ");
1698 fprintf(file, "\"%s\"",
1699 clang_getCString(clang_getCompletionAnnotation(
1700 completion_result->CompletionString, i)));
1701 }
1702 fprintf(file, ")");
1703 }
1704
Douglas Gregorba103062012-03-27 23:34:16 +00001705 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1706 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1707 &ParentKind);
1708 if (ParentKind != CXCursor_NotImplemented) {
1709 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
1710 fprintf(file, " (parent: %s '%s')",
1711 clang_getCString(KindSpelling),
1712 clang_getCString(ParentName));
1713 clang_disposeString(KindSpelling);
1714 }
1715 clang_disposeString(ParentName);
1716 }
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001717
1718 BriefComment = clang_getCompletionBriefComment(
1719 completion_result->CompletionString);
1720 BriefCommentCString = clang_getCString(BriefComment);
1721 if (BriefCommentCString && *BriefCommentCString != '\0') {
1722 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1723 }
1724 clang_disposeString(BriefComment);
Douglas Gregorba103062012-03-27 23:34:16 +00001725
Douglas Gregor58ddb602010-08-23 23:00:57 +00001726 fprintf(file, "\n");
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001727}
1728
Douglas Gregor3da626b2011-07-07 16:03:39 +00001729void print_completion_contexts(unsigned long long contexts, FILE *file) {
1730 fprintf(file, "Completion contexts:\n");
1731 if (contexts == CXCompletionContext_Unknown) {
1732 fprintf(file, "Unknown\n");
1733 }
1734 if (contexts & CXCompletionContext_AnyType) {
1735 fprintf(file, "Any type\n");
1736 }
1737 if (contexts & CXCompletionContext_AnyValue) {
1738 fprintf(file, "Any value\n");
1739 }
1740 if (contexts & CXCompletionContext_ObjCObjectValue) {
1741 fprintf(file, "Objective-C object value\n");
1742 }
1743 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1744 fprintf(file, "Objective-C selector value\n");
1745 }
1746 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1747 fprintf(file, "C++ class type value\n");
1748 }
1749 if (contexts & CXCompletionContext_DotMemberAccess) {
1750 fprintf(file, "Dot member access\n");
1751 }
1752 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1753 fprintf(file, "Arrow member access\n");
1754 }
1755 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1756 fprintf(file, "Objective-C property access\n");
1757 }
1758 if (contexts & CXCompletionContext_EnumTag) {
1759 fprintf(file, "Enum tag\n");
1760 }
1761 if (contexts & CXCompletionContext_UnionTag) {
1762 fprintf(file, "Union tag\n");
1763 }
1764 if (contexts & CXCompletionContext_StructTag) {
1765 fprintf(file, "Struct tag\n");
1766 }
1767 if (contexts & CXCompletionContext_ClassTag) {
1768 fprintf(file, "Class name\n");
1769 }
1770 if (contexts & CXCompletionContext_Namespace) {
1771 fprintf(file, "Namespace or namespace alias\n");
1772 }
1773 if (contexts & CXCompletionContext_NestedNameSpecifier) {
1774 fprintf(file, "Nested name specifier\n");
1775 }
1776 if (contexts & CXCompletionContext_ObjCInterface) {
1777 fprintf(file, "Objective-C interface\n");
1778 }
1779 if (contexts & CXCompletionContext_ObjCProtocol) {
1780 fprintf(file, "Objective-C protocol\n");
1781 }
1782 if (contexts & CXCompletionContext_ObjCCategory) {
1783 fprintf(file, "Objective-C category\n");
1784 }
1785 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1786 fprintf(file, "Objective-C instance method\n");
1787 }
1788 if (contexts & CXCompletionContext_ObjCClassMessage) {
1789 fprintf(file, "Objective-C class method\n");
1790 }
1791 if (contexts & CXCompletionContext_ObjCSelectorName) {
1792 fprintf(file, "Objective-C selector name\n");
1793 }
1794 if (contexts & CXCompletionContext_MacroName) {
1795 fprintf(file, "Macro name\n");
1796 }
1797 if (contexts & CXCompletionContext_NaturalLanguage) {
1798 fprintf(file, "Natural language\n");
1799 }
1800}
1801
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001802int my_stricmp(const char *s1, const char *s2) {
1803 while (*s1 && *s2) {
NAKAMURA Takumi6d555212011-03-09 03:02:28 +00001804 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001805 if (c1 < c2)
1806 return -1;
1807 else if (c1 > c2)
1808 return 1;
1809
1810 ++s1;
1811 ++s2;
1812 }
1813
1814 if (*s1)
1815 return 1;
1816 else if (*s2)
1817 return -1;
1818 return 0;
1819}
1820
Douglas Gregor1982c182010-07-12 18:38:41 +00001821int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001822 const char *input = argv[1];
1823 char *filename = 0;
1824 unsigned line;
1825 unsigned column;
Daniel Dunbarf8297f12009-11-07 18:34:24 +00001826 CXIndex CIdx;
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001827 int errorCode;
Douglas Gregor735df882009-12-02 09:21:34 +00001828 struct CXUnsavedFile *unsaved_files = 0;
1829 int num_unsaved_files = 0;
Douglas Gregorec6762c2009-12-18 16:20:58 +00001830 CXCodeCompleteResults *results = 0;
Dawn Perchik25d9b002010-09-30 22:26:05 +00001831 CXTranslationUnit TU = 0;
Douglas Gregor32be4a52010-10-11 21:37:58 +00001832 unsigned I, Repeats = 1;
1833 unsigned completionOptions = clang_defaultCodeCompleteOptions();
1834
1835 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
1836 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001837 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
1838 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregordf95a132010-08-09 20:45:32 +00001839
Douglas Gregor1982c182010-07-12 18:38:41 +00001840 if (timing_only)
1841 input += strlen("-code-completion-timing=");
1842 else
1843 input += strlen("-code-completion-at=");
1844
Ted Kremeneke68fff62010-02-17 00:41:32 +00001845 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001846 0, 0)))
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001847 return errorCode;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001848
Douglas Gregor735df882009-12-02 09:21:34 +00001849 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
1850 return -1;
1851
Douglas Gregor32be4a52010-10-11 21:37:58 +00001852 CIdx = clang_createIndex(0, 0);
1853
1854 if (getenv("CINDEXTEST_EDITING"))
1855 Repeats = 5;
1856
1857 TU = clang_parseTranslationUnit(CIdx, 0,
1858 argv + num_unsaved_files + 2,
1859 argc - num_unsaved_files - 2,
1860 0, 0, getDefaultParsingOptions());
1861 if (!TU) {
1862 fprintf(stderr, "Unable to load translation unit!\n");
1863 return 1;
1864 }
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001865
1866 if (clang_reparseTranslationUnit(TU, 0, 0, clang_defaultReparseOptions(TU))) {
1867 fprintf(stderr, "Unable to reparse translation init!\n");
1868 return 1;
1869 }
Douglas Gregor32be4a52010-10-11 21:37:58 +00001870
1871 for (I = 0; I != Repeats; ++I) {
1872 results = clang_codeCompleteAt(TU, filename, line, column,
1873 unsaved_files, num_unsaved_files,
1874 completionOptions);
1875 if (!results) {
1876 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar2de41c92010-08-19 23:44:06 +00001877 return 1;
1878 }
Douglas Gregor32be4a52010-10-11 21:37:58 +00001879 if (I != Repeats-1)
1880 clang_disposeCodeCompleteResults(results);
1881 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001882
Douglas Gregorec6762c2009-12-18 16:20:58 +00001883 if (results) {
Douglas Gregore081a612011-07-21 01:05:26 +00001884 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor3da626b2011-07-07 16:03:39 +00001885 unsigned long long contexts;
Douglas Gregore081a612011-07-21 01:05:26 +00001886 enum CXCursorKind containerKind;
Douglas Gregor0a47d692011-07-26 15:24:30 +00001887 CXString objCSelector;
1888 const char *selectorString;
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001889 if (!timing_only) {
1890 /* Sort the code-completion results based on the typed text. */
1891 clang_sortCodeCompletionResults(results->Results, results->NumResults);
1892
Douglas Gregor1982c182010-07-12 18:38:41 +00001893 for (i = 0; i != n; ++i)
1894 print_completion_result(results->Results + i, stdout);
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001895 }
Douglas Gregora88084b2010-02-18 18:08:43 +00001896 n = clang_codeCompleteGetNumDiagnostics(results);
1897 for (i = 0; i != n; ++i) {
1898 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
1899 PrintDiagnostic(diag);
1900 clang_disposeDiagnostic(diag);
1901 }
Douglas Gregor3da626b2011-07-07 16:03:39 +00001902
1903 contexts = clang_codeCompleteGetContexts(results);
1904 print_completion_contexts(contexts, stdout);
1905
Douglas Gregor0a47d692011-07-26 15:24:30 +00001906 containerKind = clang_codeCompleteGetContainerKind(results,
1907 &containerIsIncomplete);
Douglas Gregore081a612011-07-21 01:05:26 +00001908
1909 if (containerKind != CXCursor_InvalidCode) {
1910 /* We have found a container */
1911 CXString containerUSR, containerKindSpelling;
1912 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
1913 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
1914 clang_disposeString(containerKindSpelling);
1915
1916 if (containerIsIncomplete) {
1917 printf("Container is incomplete\n");
1918 }
1919 else {
1920 printf("Container is complete\n");
1921 }
1922
1923 containerUSR = clang_codeCompleteGetContainerUSR(results);
1924 printf("Container USR: %s\n", clang_getCString(containerUSR));
1925 clang_disposeString(containerUSR);
1926 }
1927
Douglas Gregor0a47d692011-07-26 15:24:30 +00001928 objCSelector = clang_codeCompleteGetObjCSelector(results);
1929 selectorString = clang_getCString(objCSelector);
1930 if (selectorString && strlen(selectorString) > 0) {
1931 printf("Objective-C selector: %s\n", selectorString);
1932 }
1933 clang_disposeString(objCSelector);
1934
Douglas Gregorec6762c2009-12-18 16:20:58 +00001935 clang_disposeCodeCompleteResults(results);
1936 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001937 clang_disposeTranslationUnit(TU);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001938 clang_disposeIndex(CIdx);
1939 free(filename);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001940
Douglas Gregor735df882009-12-02 09:21:34 +00001941 free_remapped_files(unsaved_files, num_unsaved_files);
1942
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001943 return 0;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001944}
1945
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001946typedef struct {
1947 char *filename;
1948 unsigned line;
1949 unsigned column;
1950} CursorSourceLocation;
1951
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001952static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001953 CXIndex CIdx;
1954 int errorCode;
1955 struct CXUnsavedFile *unsaved_files = 0;
1956 int num_unsaved_files = 0;
1957 CXTranslationUnit TU;
1958 CXCursor Cursor;
1959 CursorSourceLocation *Locations = 0;
1960 unsigned NumLocations = 0, Loc;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001961 unsigned Repeats = 1;
Douglas Gregorbdc4b362010-11-30 06:04:54 +00001962 unsigned I;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001963
Ted Kremeneke68fff62010-02-17 00:41:32 +00001964 /* Count the number of locations. */
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001965 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
1966 ++NumLocations;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001967
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001968 /* Parse the locations. */
1969 assert(NumLocations > 0 && "Unable to count locations?");
1970 Locations = (CursorSourceLocation *)malloc(
1971 NumLocations * sizeof(CursorSourceLocation));
1972 for (Loc = 0; Loc < NumLocations; ++Loc) {
1973 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001974 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
1975 &Locations[Loc].line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001976 &Locations[Loc].column, 0, 0)))
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001977 return errorCode;
1978 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001979
1980 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001981 &num_unsaved_files))
1982 return -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001983
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001984 if (getenv("CINDEXTEST_EDITING"))
1985 Repeats = 5;
1986
1987 /* Parse the translation unit. When we're testing clang_getCursor() after
1988 reparsing, don't remap unsaved files until the second parse. */
1989 CIdx = clang_createIndex(1, 1);
1990 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
1991 argv + num_unsaved_files + 1 + NumLocations,
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001992 argc - num_unsaved_files - 2 - NumLocations,
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001993 unsaved_files,
1994 Repeats > 1? 0 : num_unsaved_files,
1995 getDefaultParsingOptions());
1996
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001997 if (!TU) {
1998 fprintf(stderr, "unable to parse input\n");
1999 return -1;
2000 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002001
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002002 if (checkForErrors(TU) != 0)
2003 return -1;
2004
Douglas Gregorbdc4b362010-11-30 06:04:54 +00002005 for (I = 0; I != Repeats; ++I) {
Douglas Gregor8e08dec2010-11-30 05:52:55 +00002006 if (Repeats > 1 &&
2007 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2008 clang_defaultReparseOptions(TU))) {
2009 clang_disposeTranslationUnit(TU);
2010 return 1;
2011 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002012
2013 if (checkForErrors(TU) != 0)
2014 return -1;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00002015
2016 for (Loc = 0; Loc < NumLocations; ++Loc) {
2017 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2018 if (!file)
2019 continue;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002020
Douglas Gregor8e08dec2010-11-30 05:52:55 +00002021 Cursor = clang_getCursor(TU,
2022 clang_getLocation(TU, file, Locations[Loc].line,
2023 Locations[Loc].column));
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002024
2025 if (checkForErrors(TU) != 0)
2026 return -1;
2027
Douglas Gregor8e08dec2010-11-30 05:52:55 +00002028 if (I + 1 == Repeats) {
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002029 CXCompletionString completionString = clang_getCursorCompletionString(
2030 Cursor);
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00002031 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2032 CXString Spelling;
2033 const char *cspell;
2034 unsigned line, column;
2035 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2036 printf("%d:%d ", line, column);
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002037 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00002038 PrintCursorExtent(Cursor);
2039 Spelling = clang_getCursorSpelling(Cursor);
2040 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00002041 if (cspell && strlen(cspell) != 0) {
2042 unsigned pieceIndex;
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00002043 printf(" Spelling=%s (", cspell);
2044 for (pieceIndex = 0; ; ++pieceIndex) {
Benjamin Kramer6c235bc2012-03-31 10:23:28 +00002045 CXSourceRange range =
2046 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00002047 if (clang_Range_isNull(range))
2048 break;
2049 PrintRange(range, 0);
2050 }
2051 printf(")");
2052 }
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00002053 clang_disposeString(Spelling);
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00002054 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2055 printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisf39a7ae2012-07-02 23:54:36 +00002056 if (clang_Cursor_isDynamicCall(Cursor))
2057 printf(" Dynamic-call");
Argyrios Kyrtzidise4a990f2012-11-01 02:01:34 +00002058 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2059 CXType T = clang_Cursor_getReceiverType(Cursor);
2060 CXString S = clang_getTypeKindSpelling(T.kind);
2061 printf(" Receiver-type=%s", clang_getCString(S));
2062 clang_disposeString(S);
2063 }
Argyrios Kyrtzidisf39a7ae2012-07-02 23:54:36 +00002064
Argyrios Kyrtzidis5d04b1a2012-10-05 00:22:37 +00002065 {
2066 CXModule mod = clang_Cursor_getModule(Cursor);
2067 CXString name;
2068 unsigned i, numHeaders;
2069 if (mod) {
2070 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00002071 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis5d04b1a2012-10-05 00:22:37 +00002072 printf(" ModuleName=%s Headers(%d):",
2073 clang_getCString(name), numHeaders);
2074 clang_disposeString(name);
2075 for (i = 0; i < numHeaders; ++i) {
Argyrios Kyrtzidisc1d22392013-03-13 21:13:43 +00002076 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
Argyrios Kyrtzidis5d04b1a2012-10-05 00:22:37 +00002077 CXString filename = clang_getFileName(file);
2078 printf("\n%s", clang_getCString(filename));
2079 clang_disposeString(filename);
2080 }
2081 }
2082 }
2083
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002084 if (completionString != NULL) {
2085 printf("\nCompletion string: ");
2086 print_completion_string(completionString, stdout);
2087 }
Douglas Gregor8e08dec2010-11-30 05:52:55 +00002088 printf("\n");
2089 free(Locations[Loc].filename);
2090 }
2091 }
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00002092 }
Douglas Gregor8e08dec2010-11-30 05:52:55 +00002093
Douglas Gregora88084b2010-02-18 18:08:43 +00002094 PrintDiagnostics(TU);
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00002095 clang_disposeTranslationUnit(TU);
2096 clang_disposeIndex(CIdx);
2097 free(Locations);
2098 free_remapped_files(unsaved_files, num_unsaved_files);
2099 return 0;
2100}
2101
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002102static enum CXVisitorResult findFileRefsVisit(void *context,
2103 CXCursor cursor, CXSourceRange range) {
2104 if (clang_Range_isNull(range))
2105 return CXVisit_Continue;
2106
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002107 PrintCursor(cursor, NULL);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002108 PrintRange(range, "");
2109 printf("\n");
2110 return CXVisit_Continue;
2111}
2112
2113static int find_file_refs_at(int argc, const char **argv) {
2114 CXIndex CIdx;
2115 int errorCode;
2116 struct CXUnsavedFile *unsaved_files = 0;
2117 int num_unsaved_files = 0;
2118 CXTranslationUnit TU;
2119 CXCursor Cursor;
2120 CursorSourceLocation *Locations = 0;
2121 unsigned NumLocations = 0, Loc;
2122 unsigned Repeats = 1;
2123 unsigned I;
2124
2125 /* Count the number of locations. */
2126 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2127 ++NumLocations;
2128
2129 /* Parse the locations. */
2130 assert(NumLocations > 0 && "Unable to count locations?");
2131 Locations = (CursorSourceLocation *)malloc(
2132 NumLocations * sizeof(CursorSourceLocation));
2133 for (Loc = 0; Loc < NumLocations; ++Loc) {
2134 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2135 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2136 &Locations[Loc].line,
2137 &Locations[Loc].column, 0, 0)))
2138 return errorCode;
2139 }
2140
2141 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2142 &num_unsaved_files))
2143 return -1;
2144
2145 if (getenv("CINDEXTEST_EDITING"))
2146 Repeats = 5;
2147
2148 /* Parse the translation unit. When we're testing clang_getCursor() after
2149 reparsing, don't remap unsaved files until the second parse. */
2150 CIdx = clang_createIndex(1, 1);
2151 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2152 argv + num_unsaved_files + 1 + NumLocations,
2153 argc - num_unsaved_files - 2 - NumLocations,
2154 unsaved_files,
2155 Repeats > 1? 0 : num_unsaved_files,
2156 getDefaultParsingOptions());
2157
2158 if (!TU) {
2159 fprintf(stderr, "unable to parse input\n");
2160 return -1;
2161 }
2162
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002163 if (checkForErrors(TU) != 0)
2164 return -1;
2165
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002166 for (I = 0; I != Repeats; ++I) {
2167 if (Repeats > 1 &&
2168 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2169 clang_defaultReparseOptions(TU))) {
2170 clang_disposeTranslationUnit(TU);
2171 return 1;
2172 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002173
2174 if (checkForErrors(TU) != 0)
2175 return -1;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002176
2177 for (Loc = 0; Loc < NumLocations; ++Loc) {
2178 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2179 if (!file)
2180 continue;
2181
2182 Cursor = clang_getCursor(TU,
2183 clang_getLocation(TU, file, Locations[Loc].line,
2184 Locations[Loc].column));
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002185
2186 if (checkForErrors(TU) != 0)
2187 return -1;
2188
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002189 if (I + 1 == Repeats) {
Erik Verbruggen26fc0f92011-10-06 11:38:08 +00002190 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002191 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002192 printf("\n");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002193 clang_findReferencesInFile(Cursor, file, visitor);
2194 free(Locations[Loc].filename);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002195
2196 if (checkForErrors(TU) != 0)
2197 return -1;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002198 }
2199 }
2200 }
2201
2202 PrintDiagnostics(TU);
2203 clang_disposeTranslationUnit(TU);
2204 clang_disposeIndex(CIdx);
2205 free(Locations);
2206 free_remapped_files(unsaved_files, num_unsaved_files);
2207 return 0;
2208}
2209
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00002210static enum CXVisitorResult findFileIncludesVisit(void *context,
2211 CXCursor cursor, CXSourceRange range) {
2212 PrintCursor(cursor, NULL);
2213 PrintRange(range, "");
2214 printf("\n");
2215 return CXVisit_Continue;
2216}
2217
2218static int find_file_includes_in(int argc, const char **argv) {
2219 CXIndex CIdx;
2220 struct CXUnsavedFile *unsaved_files = 0;
2221 int num_unsaved_files = 0;
2222 CXTranslationUnit TU;
2223 const char **Filenames = 0;
2224 unsigned NumFilenames = 0;
2225 unsigned Repeats = 1;
2226 unsigned I, FI;
2227
2228 /* Count the number of locations. */
2229 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2230 ++NumFilenames;
2231
2232 /* Parse the locations. */
2233 assert(NumFilenames > 0 && "Unable to count filenames?");
2234 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2235 for (I = 0; I < NumFilenames; ++I) {
2236 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2237 /* Copy the file name. */
2238 Filenames[I] = input;
2239 }
2240
2241 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2242 &num_unsaved_files))
2243 return -1;
2244
2245 if (getenv("CINDEXTEST_EDITING"))
2246 Repeats = 2;
2247
2248 /* Parse the translation unit. When we're testing clang_getCursor() after
2249 reparsing, don't remap unsaved files until the second parse. */
2250 CIdx = clang_createIndex(1, 1);
2251 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2252 argv + num_unsaved_files + 1 + NumFilenames,
2253 argc - num_unsaved_files - 2 - NumFilenames,
2254 unsaved_files,
2255 Repeats > 1? 0 : num_unsaved_files,
2256 getDefaultParsingOptions());
2257
2258 if (!TU) {
2259 fprintf(stderr, "unable to parse input\n");
2260 return -1;
2261 }
2262
2263 if (checkForErrors(TU) != 0)
2264 return -1;
2265
2266 for (I = 0; I != Repeats; ++I) {
2267 if (Repeats > 1 &&
2268 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2269 clang_defaultReparseOptions(TU))) {
2270 clang_disposeTranslationUnit(TU);
2271 return 1;
2272 }
2273
2274 if (checkForErrors(TU) != 0)
2275 return -1;
2276
2277 for (FI = 0; FI < NumFilenames; ++FI) {
2278 CXFile file = clang_getFile(TU, Filenames[FI]);
2279 if (!file)
2280 continue;
2281
2282 if (checkForErrors(TU) != 0)
2283 return -1;
2284
2285 if (I + 1 == Repeats) {
2286 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2287 clang_findIncludesInFile(TU, file, visitor);
2288
2289 if (checkForErrors(TU) != 0)
2290 return -1;
2291 }
2292 }
2293 }
2294
2295 PrintDiagnostics(TU);
2296 clang_disposeTranslationUnit(TU);
2297 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis5256c1f2013-03-11 16:03:17 +00002298 free((void *)Filenames);
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00002299 free_remapped_files(unsaved_files, num_unsaved_files);
2300 return 0;
2301}
2302
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002303#define MAX_IMPORTED_ASTFILES 200
2304
2305typedef struct {
2306 char **filenames;
2307 unsigned num_files;
2308} ImportedASTFilesData;
2309
2310static ImportedASTFilesData *importedASTs_create() {
2311 ImportedASTFilesData *p;
2312 p = malloc(sizeof(ImportedASTFilesData));
2313 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2314 p->num_files = 0;
2315 return p;
2316}
2317
2318static void importedASTs_dispose(ImportedASTFilesData *p) {
2319 unsigned i;
2320 if (!p)
2321 return;
2322
2323 for (i = 0; i < p->num_files; ++i)
2324 free(p->filenames[i]);
2325 free(p->filenames);
2326 free(p);
2327}
2328
2329static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2330 unsigned i;
2331 assert(p && file);
2332 for (i = 0; i < p->num_files; ++i)
2333 if (strcmp(file, p->filenames[i]) == 0)
2334 return;
2335 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2336 p->filenames[p->num_files++] = strdup(file);
2337}
2338
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002339typedef struct {
2340 const char *check_prefix;
2341 int first_check_printed;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002342 int fail_for_error;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002343 int abort;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002344 const char *main_filename;
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002345 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002346} IndexData;
2347
2348static void printCheck(IndexData *data) {
2349 if (data->check_prefix) {
2350 if (data->first_check_printed) {
2351 printf("// %s-NEXT: ", data->check_prefix);
2352 } else {
2353 printf("// %s : ", data->check_prefix);
2354 data->first_check_printed = 1;
2355 }
2356 }
2357}
2358
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002359static void printCXIndexFile(CXIdxClientFile file) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002360 CXString filename = clang_getFileName((CXFile)file);
2361 printf("%s", clang_getCString(filename));
2362 clang_disposeString(filename);
2363}
2364
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002365static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2366 IndexData *index_data;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002367 CXString filename;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002368 const char *cname;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002369 CXIdxClientFile file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002370 unsigned line, column;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002371 int isMainFile;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002372
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002373 index_data = (IndexData *)client_data;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002374 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2375 if (line == 0) {
Argyrios Kyrtzidis8003fd62012-10-11 19:00:44 +00002376 printf("<invalid>");
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002377 return;
2378 }
Argyrios Kyrtzidisc2be04e2011-12-13 18:47:35 +00002379 if (!file) {
2380 printf("<no idxfile>");
2381 return;
2382 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002383 filename = clang_getFileName((CXFile)file);
2384 cname = clang_getCString(filename);
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002385 if (strcmp(cname, index_data->main_filename) == 0)
2386 isMainFile = 1;
2387 else
2388 isMainFile = 0;
2389 clang_disposeString(filename);
2390
2391 if (!isMainFile) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002392 printCXIndexFile(file);
2393 printf(":");
2394 }
2395 printf("%d:%d", line, column);
2396}
2397
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002398static unsigned digitCount(unsigned val) {
2399 unsigned c = 1;
2400 while (1) {
2401 if (val < 10)
2402 return c;
2403 ++c;
2404 val /= 10;
2405 }
2406}
2407
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002408static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2409 CXIdxLoc loc) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002410 const char *name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002411 char *newStr;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002412 CXIdxClientFile file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002413 unsigned line, column;
2414
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002415 name = info->name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002416 if (!name)
2417 name = "<anon-tag>";
2418
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002419 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Argyrios Kyrtzidisf89bc052011-10-20 17:21:46 +00002420 /* FIXME: free these.*/
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002421 newStr = (char *)malloc(strlen(name) +
2422 digitCount(line) + digitCount(column) + 3);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002423 sprintf(newStr, "%s:%d:%d", name, line, column);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002424 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002425}
2426
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002427static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2428 CXIdxClientContainer container;
2429 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidis3e340a62011-11-16 02:35:05 +00002430 if (!container)
2431 printf("[<<NULL>>]");
2432 else
2433 printf("[%s]", (const char *)container);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002434}
2435
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002436static const char *getEntityKindString(CXIdxEntityKind kind) {
2437 switch (kind) {
2438 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2439 case CXIdxEntity_Typedef: return "typedef";
2440 case CXIdxEntity_Function: return "function";
2441 case CXIdxEntity_Variable: return "variable";
2442 case CXIdxEntity_Field: return "field";
2443 case CXIdxEntity_EnumConstant: return "enumerator";
2444 case CXIdxEntity_ObjCClass: return "objc-class";
2445 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2446 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002447 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2448 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002449 case CXIdxEntity_ObjCProperty: return "objc-property";
2450 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2451 case CXIdxEntity_Enum: return "enum";
2452 case CXIdxEntity_Struct: return "struct";
2453 case CXIdxEntity_Union: return "union";
2454 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002455 case CXIdxEntity_CXXNamespace: return "namespace";
2456 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2457 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2458 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2459 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2460 case CXIdxEntity_CXXConstructor: return "constructor";
2461 case CXIdxEntity_CXXDestructor: return "destructor";
2462 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2463 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikie35adca02012-08-31 21:55:26 +00002464 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002465 }
2466 assert(0 && "Garbage entity kind");
2467 return 0;
2468}
2469
2470static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2471 switch (kind) {
2472 case CXIdxEntity_NonTemplate: return "";
2473 case CXIdxEntity_Template: return "-template";
2474 case CXIdxEntity_TemplatePartialSpecialization:
2475 return "-template-partial-spec";
2476 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002477 }
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002478 assert(0 && "Garbage entity kind");
2479 return 0;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002480}
2481
Argyrios Kyrtzidis838d3c22011-12-07 20:44:12 +00002482static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2483 switch (kind) {
2484 case CXIdxEntityLang_None: return "<none>";
2485 case CXIdxEntityLang_C: return "C";
2486 case CXIdxEntityLang_ObjC: return "ObjC";
2487 case CXIdxEntityLang_CXX: return "C++";
2488 }
2489 assert(0 && "Garbage language kind");
2490 return 0;
2491}
2492
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002493static void printEntityInfo(const char *cb,
2494 CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002495 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002496 const char *name;
2497 IndexData *index_data;
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002498 unsigned i;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002499 index_data = (IndexData *)client_data;
2500 printCheck(index_data);
2501
Argyrios Kyrtzidisc6b4a502011-11-16 02:34:59 +00002502 if (!info) {
2503 printf("%s: <<NULL>>", cb);
2504 return;
2505 }
2506
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002507 name = info->name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002508 if (!name)
2509 name = "<anon-tag>";
2510
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002511 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2512 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002513 printf(" | name: %s", name);
2514 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisc2be04e2011-12-13 18:47:35 +00002515 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002516
2517 for (i = 0; i != info->numAttributes; ++i) {
2518 const CXIdxAttrInfo *Attr = info->attributes[i];
2519 printf(" <attribute>: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002520 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002521 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002522}
2523
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002524static void printBaseClassInfo(CXClientData client_data,
2525 const CXIdxBaseClassInfo *info) {
2526 printEntityInfo(" <base>", client_data, info->base);
2527 printf(" | cursor: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002528 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002529 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002530 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002531}
2532
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002533static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2534 CXClientData client_data) {
2535 unsigned i;
2536 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2537 printEntityInfo(" <protocol>", client_data,
2538 ProtoInfo->protocols[i]->protocol);
2539 printf(" | cursor: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002540 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002541 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002542 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002543 printf("\n");
2544 }
2545}
2546
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002547static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002548 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002549 CXString str;
2550 const char *cstr;
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002551 unsigned numDiags, i;
2552 CXDiagnostic diag;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002553 IndexData *index_data;
2554 index_data = (IndexData *)client_data;
2555 printCheck(index_data);
2556
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002557 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2558 for (i = 0; i != numDiags; ++i) {
2559 diag = clang_getDiagnosticInSet(diagSet, i);
2560 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2561 cstr = clang_getCString(str);
2562 printf("[diagnostic]: %s\n", cstr);
2563 clang_disposeString(str);
2564
2565 if (getenv("CINDEXTEST_FAILONERROR") &&
2566 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2567 index_data->fail_for_error = 1;
2568 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002569 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002570}
2571
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002572static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2573 CXFile file, void *reserved) {
2574 IndexData *index_data;
Argyrios Kyrtzidis62d7fea2012-03-15 18:48:52 +00002575 CXString filename;
2576
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002577 index_data = (IndexData *)client_data;
2578 printCheck(index_data);
2579
Argyrios Kyrtzidis62d7fea2012-03-15 18:48:52 +00002580 filename = clang_getFileName(file);
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002581 index_data->main_filename = clang_getCString(filename);
2582 clang_disposeString(filename);
2583
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002584 printf("[enteredMainFile]: ");
2585 printCXIndexFile((CXIdxClientFile)file);
2586 printf("\n");
2587
2588 return (CXIdxClientFile)file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002589}
2590
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002591static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002592 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002593 IndexData *index_data;
2594 index_data = (IndexData *)client_data;
2595 printCheck(index_data);
2596
Argyrios Kyrtzidis66042b32011-11-05 04:03:35 +00002597 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002598 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002599 printf(" | name: \"%s\"", info->filename);
2600 printf(" | hash loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002601 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidis8d7a24e2012-10-18 00:17:05 +00002602 printf(" | isImport: %d | isAngled: %d | isModule: %d\n",
2603 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002604
2605 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002606}
2607
Argyrios Kyrtzidis2c3e05c2012-10-02 16:10:38 +00002608static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2609 const CXIdxImportedASTFileInfo *info) {
2610 IndexData *index_data;
2611 index_data = (IndexData *)client_data;
2612 printCheck(index_data);
2613
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002614 if (index_data->importedASTs) {
2615 CXString filename = clang_getFileName(info->file);
2616 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2617 clang_disposeString(filename);
2618 }
2619
Argyrios Kyrtzidis2c3e05c2012-10-02 16:10:38 +00002620 printf("[importedASTFile]: ");
2621 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidis134d1e8a2012-10-05 00:22:40 +00002622 if (info->module) {
2623 CXString name = clang_Module_getFullName(info->module);
2624 printf(" | loc: ");
2625 printCXIndexLoc(info->loc, client_data);
2626 printf(" | name: \"%s\"", clang_getCString(name));
2627 printf(" | isImplicit: %d\n", info->isImplicit);
2628 clang_disposeString(name);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002629 } else {
NAKAMURA Takumi3c5527e2012-10-12 14:25:52 +00002630 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002631 printf("\n");
Argyrios Kyrtzidis134d1e8a2012-10-05 00:22:40 +00002632 }
Argyrios Kyrtzidis2c3e05c2012-10-02 16:10:38 +00002633
2634 return (CXIdxClientFile)info->file;
2635}
2636
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002637static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002638 void *reserved) {
2639 IndexData *index_data;
2640 index_data = (IndexData *)client_data;
2641 printCheck(index_data);
2642
Argyrios Kyrtzidis66042b32011-11-05 04:03:35 +00002643 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002644 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002645}
2646
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002647static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002648 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002649 IndexData *index_data;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002650 const CXIdxObjCCategoryDeclInfo *CatInfo;
2651 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002652 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis792db262012-02-28 17:50:33 +00002653 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002654 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002655 unsigned i;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002656 index_data = (IndexData *)client_data;
2657
2658 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2659 printf(" | cursor: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002660 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002661 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002662 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb1febb62011-12-07 20:44:19 +00002663 printf(" | semantic-container: ");
2664 printCXIndexContainer(info->semanticContainer);
2665 printf(" | lexical-container: ");
2666 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002667 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002668 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis838eb7e2012-12-06 19:41:16 +00002669 if (info->flags & CXIdxDeclFlag_Skipped) {
2670 assert(!info->isContainer);
2671 printf(" | isContainer: skipped");
2672 } else {
2673 printf(" | isContainer: %d", info->isContainer);
2674 }
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002675 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002676
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002677 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi87adb0b2011-11-18 00:51:03 +00002678 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002679 printf(" <attribute>: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002680 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002681 printf("\n");
2682 }
2683
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002684 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2685 const char *kindName = 0;
2686 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2687 switch (K) {
2688 case CXIdxObjCContainer_ForwardRef:
2689 kindName = "forward-ref"; break;
2690 case CXIdxObjCContainer_Interface:
2691 kindName = "interface"; break;
2692 case CXIdxObjCContainer_Implementation:
2693 kindName = "implementation"; break;
2694 }
2695 printCheck(index_data);
2696 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2697 }
2698
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002699 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002700 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
2701 CatInfo->objcClass);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002702 printf(" | cursor: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002703 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002704 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002705 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002706 printf("\n");
2707 }
2708
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002709 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2710 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002711 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002712 printf("\n");
2713 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002714 }
2715
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002716 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2717 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002718 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002719
Argyrios Kyrtzidis792db262012-02-28 17:50:33 +00002720 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2721 if (PropInfo->getter) {
2722 printEntityInfo(" <getter>", client_data, PropInfo->getter);
2723 printf("\n");
2724 }
2725 if (PropInfo->setter) {
2726 printEntityInfo(" <setter>", client_data, PropInfo->setter);
2727 printf("\n");
2728 }
2729 }
2730
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002731 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2732 for (i = 0; i != CXXClassInfo->numBases; ++i) {
2733 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2734 printf("\n");
2735 }
2736 }
2737
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002738 if (info->declAsContainer)
2739 clang_index_setClientContainer(info->declAsContainer,
2740 makeClientContainer(info->entityInfo, info->loc));
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002741}
2742
2743static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002744 const CXIdxEntityRefInfo *info) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002745 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002746 printf(" | cursor: ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00002747 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002748 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002749 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002750 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002751 printf(" | container: ");
2752 printCXIndexContainer(info->container);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002753 printf(" | refkind: ");
Argyrios Kyrtzidisaca19be2011-10-18 15:50:50 +00002754 switch (info->kind) {
2755 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002756 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidisaca19be2011-10-18 15:50:50 +00002757 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002758 printf("\n");
2759}
2760
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002761static int index_abortQuery(CXClientData client_data, void *reserved) {
2762 IndexData *index_data;
2763 index_data = (IndexData *)client_data;
2764 return index_data->abort;
2765}
2766
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002767static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002768 index_abortQuery,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002769 index_diagnostic,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002770 index_enteredMainFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002771 index_ppIncludedFile,
Argyrios Kyrtzidis2c3e05c2012-10-02 16:10:38 +00002772 index_importedASTFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002773 index_startedTranslationUnit,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002774 index_indexDeclaration,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002775 index_indexEntityReference
2776};
2777
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002778static unsigned getIndexOptions(void) {
2779 unsigned index_opts;
2780 index_opts = 0;
2781 if (getenv("CINDEXTEST_SUPPRESSREFS"))
2782 index_opts |= CXIndexOpt_SuppressRedundantRefs;
2783 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
2784 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis838eb7e2012-12-06 19:41:16 +00002785 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
2786 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002787
2788 return index_opts;
2789}
2790
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002791static int index_compile_args(int num_args, const char **args,
2792 CXIndexAction idxAction,
2793 ImportedASTFilesData *importedASTs,
2794 const char *check_prefix) {
2795 IndexData index_data;
2796 unsigned index_opts;
2797 int result;
2798
2799 if (num_args == 0) {
2800 fprintf(stderr, "no compiler arguments\n");
2801 return -1;
2802 }
2803
2804 index_data.check_prefix = check_prefix;
2805 index_data.first_check_printed = 0;
2806 index_data.fail_for_error = 0;
2807 index_data.abort = 0;
2808 index_data.main_filename = "";
2809 index_data.importedASTs = importedASTs;
2810
2811 index_opts = getIndexOptions();
2812 result = clang_indexSourceFile(idxAction, &index_data,
2813 &IndexCB,sizeof(IndexCB), index_opts,
2814 0, args, num_args, 0, 0, 0,
2815 getDefaultParsingOptions());
2816 if (index_data.fail_for_error)
2817 result = -1;
2818
2819 return result;
2820}
2821
2822static int index_ast_file(const char *ast_file,
2823 CXIndex Idx,
2824 CXIndexAction idxAction,
2825 ImportedASTFilesData *importedASTs,
2826 const char *check_prefix) {
2827 CXTranslationUnit TU;
2828 IndexData index_data;
2829 unsigned index_opts;
2830 int result;
2831
2832 if (!CreateTranslationUnit(Idx, ast_file, &TU))
2833 return -1;
2834
2835 index_data.check_prefix = check_prefix;
2836 index_data.first_check_printed = 0;
2837 index_data.fail_for_error = 0;
2838 index_data.abort = 0;
2839 index_data.main_filename = "";
2840 index_data.importedASTs = importedASTs;
2841
2842 index_opts = getIndexOptions();
2843 result = clang_indexTranslationUnit(idxAction, &index_data,
2844 &IndexCB,sizeof(IndexCB),
2845 index_opts, TU);
2846 if (index_data.fail_for_error)
2847 result = -1;
2848
2849 clang_disposeTranslationUnit(TU);
2850 return result;
2851}
2852
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002853static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002854 const char *check_prefix;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002855 CXIndex Idx;
2856 CXIndexAction idxAction;
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002857 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002858 int result;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002859
2860 check_prefix = 0;
2861 if (argc > 0) {
2862 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2863 check_prefix = argv[0] + strlen("-check-prefix=");
2864 ++argv;
2865 --argc;
2866 }
2867 }
2868
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002869 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitfc093362013-03-01 21:41:22 +00002870 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002871 fprintf(stderr, "Could not create Index\n");
2872 return 1;
2873 }
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002874 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002875 importedASTs = 0;
2876 if (full)
2877 importedASTs = importedASTs_create();
2878
2879 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
2880 if (result != 0)
2881 goto finished;
2882
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002883 if (full) {
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002884 unsigned i;
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002885 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
2886 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
2887 importedASTs, check_prefix);
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002888 }
2889 }
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002890
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00002891finished:
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002892 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002893 clang_IndexAction_dispose(idxAction);
2894 clang_disposeIndex(Idx);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002895 return result;
2896}
2897
2898static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002899 const char *check_prefix;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002900 CXIndex Idx;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002901 CXIndexAction idxAction;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002902 int result;
2903
2904 check_prefix = 0;
2905 if (argc > 0) {
2906 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2907 check_prefix = argv[0] + strlen("-check-prefix=");
2908 ++argv;
2909 --argc;
2910 }
2911 }
2912
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002913 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitfc093362013-03-01 21:41:22 +00002914 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002915 fprintf(stderr, "Could not create Index\n");
2916 return 1;
2917 }
2918 idxAction = clang_IndexAction_create(Idx);
2919
2920 result = index_ast_file(argv[0], Idx, idxAction,
2921 /*importedASTs=*/0, check_prefix);
2922
2923 clang_IndexAction_dispose(idxAction);
2924 clang_disposeIndex(Idx);
2925 return result;
2926}
2927
2928static int index_compile_db(int argc, const char **argv) {
2929 const char *check_prefix;
2930 CXIndex Idx;
2931 CXIndexAction idxAction;
2932 int errorCode = 0;
2933
2934 check_prefix = 0;
2935 if (argc > 0) {
2936 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2937 check_prefix = argv[0] + strlen("-check-prefix=");
2938 ++argv;
2939 --argc;
2940 }
2941 }
2942
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002943 if (argc == 0) {
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002944 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002945 return -1;
2946 }
2947
2948 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitfc093362013-03-01 21:41:22 +00002949 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002950 fprintf(stderr, "Could not create Index\n");
2951 return 1;
2952 }
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002953 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002954
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002955 {
2956 const char *database = argv[0];
2957 CXCompilationDatabase db = 0;
2958 CXCompileCommands CCmds = 0;
2959 CXCompileCommand CCmd;
2960 CXCompilationDatabase_Error ec;
2961 CXString wd;
2962#define MAX_COMPILE_ARGS 512
2963 CXString cxargs[MAX_COMPILE_ARGS];
2964 const char *args[MAX_COMPILE_ARGS];
2965 char *tmp;
2966 unsigned len;
2967 char *buildDir;
2968 int i, a, numCmds, numArgs;
2969
2970 len = strlen(database);
2971 tmp = (char *) malloc(len+1);
2972 memcpy(tmp, database, len+1);
2973 buildDir = dirname(tmp);
2974
2975 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
2976
2977 if (db) {
2978
2979 if (ec!=CXCompilationDatabase_NoError) {
2980 printf("unexpected error %d code while loading compilation database\n", ec);
2981 errorCode = -1;
2982 goto cdb_end;
2983 }
2984
Argyrios Kyrtzidis2bff7e52012-12-17 20:19:56 +00002985 if (chdir(buildDir) != 0) {
2986 printf("Could not chdir to %s\n", buildDir);
2987 errorCode = -1;
2988 goto cdb_end;
2989 }
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002990
Argyrios Kyrtzidis2bff7e52012-12-17 20:19:56 +00002991 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00002992 if (!CCmds) {
2993 printf("compilation db is empty\n");
2994 errorCode = -1;
2995 goto cdb_end;
2996 }
2997
2998 numCmds = clang_CompileCommands_getSize(CCmds);
2999
3000 if (numCmds==0) {
3001 fprintf(stderr, "should not get an empty compileCommand set\n");
3002 errorCode = -1;
3003 goto cdb_end;
3004 }
3005
3006 for (i=0; i<numCmds && errorCode == 0; ++i) {
3007 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3008
3009 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidis2bff7e52012-12-17 20:19:56 +00003010 if (chdir(clang_getCString(wd)) != 0) {
3011 printf("Could not chdir to %s\n", clang_getCString(wd));
3012 errorCode = -1;
3013 goto cdb_end;
3014 }
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00003015 clang_disposeString(wd);
3016
3017 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3018 if (numArgs > MAX_COMPILE_ARGS){
3019 fprintf(stderr, "got more compile arguments than maximum\n");
3020 errorCode = -1;
3021 goto cdb_end;
3022 }
3023 for (a=0; a<numArgs; ++a) {
3024 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3025 args[a] = clang_getCString(cxargs[a]);
3026 }
3027
3028 errorCode = index_compile_args(numArgs, args, idxAction,
3029 /*importedASTs=*/0, check_prefix);
3030
3031 for (a=0; a<numArgs; ++a)
3032 clang_disposeString(cxargs[a]);
3033 }
3034 } else {
3035 printf("database loading failed with error code %d.\n", ec);
3036 errorCode = -1;
3037 }
3038
3039 cdb_end:
3040 clang_CompileCommands_dispose(CCmds);
3041 clang_CompilationDatabase_dispose(db);
3042 free(tmp);
3043
3044 }
3045
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00003046 clang_IndexAction_dispose(idxAction);
3047 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00003048 return errorCode;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003049}
3050
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003051int perform_token_annotation(int argc, const char **argv) {
3052 const char *input = argv[1];
3053 char *filename = 0;
3054 unsigned line, second_line;
3055 unsigned column, second_column;
3056 CXIndex CIdx;
3057 CXTranslationUnit TU = 0;
3058 int errorCode;
3059 struct CXUnsavedFile *unsaved_files = 0;
3060 int num_unsaved_files = 0;
3061 CXToken *tokens;
3062 unsigned num_tokens;
3063 CXSourceRange range;
3064 CXSourceLocation startLoc, endLoc;
3065 CXFile file = 0;
3066 CXCursor *cursors = 0;
3067 unsigned i;
3068
3069 input += strlen("-test-annotate-tokens=");
3070 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3071 &second_line, &second_column)))
3072 return errorCode;
3073
Richard Smithe07c5f82012-07-05 08:20:49 +00003074 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3075 free(filename);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003076 return -1;
Richard Smithe07c5f82012-07-05 08:20:49 +00003077 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003078
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003079 CIdx = clang_createIndex(0, 1);
Douglas Gregordca8ee82011-05-06 16:33:08 +00003080 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
3081 argv + num_unsaved_files + 2,
3082 argc - num_unsaved_files - 3,
3083 unsaved_files,
3084 num_unsaved_files,
3085 getDefaultParsingOptions());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003086 if (!TU) {
3087 fprintf(stderr, "unable to parse input\n");
3088 clang_disposeIndex(CIdx);
3089 free(filename);
3090 free_remapped_files(unsaved_files, num_unsaved_files);
3091 return -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00003092 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003093 errorCode = 0;
3094
Richard Smithe07c5f82012-07-05 08:20:49 +00003095 if (checkForErrors(TU) != 0) {
3096 errorCode = -1;
3097 goto teardown;
3098 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00003099
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00003100 if (getenv("CINDEXTEST_EDITING")) {
3101 for (i = 0; i < 5; ++i) {
3102 if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3103 clang_defaultReparseOptions(TU))) {
3104 fprintf(stderr, "Unable to reparse translation unit!\n");
3105 errorCode = -1;
3106 goto teardown;
3107 }
3108 }
3109 }
3110
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00003111 if (checkForErrors(TU) != 0) {
3112 errorCode = -1;
3113 goto teardown;
3114 }
3115
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003116 file = clang_getFile(TU, filename);
3117 if (!file) {
3118 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3119 errorCode = -1;
3120 goto teardown;
3121 }
3122
3123 startLoc = clang_getLocation(TU, file, line, column);
3124 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003125 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003126 column);
3127 errorCode = -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00003128 goto teardown;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003129 }
3130
3131 endLoc = clang_getLocation(TU, file, second_line, second_column);
3132 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00003133 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003134 second_line, second_column);
3135 errorCode = -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00003136 goto teardown;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003137 }
3138
3139 range = clang_getRange(startLoc, endLoc);
3140 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00003141
3142 if (checkForErrors(TU) != 0) {
3143 errorCode = -1;
3144 goto teardown;
3145 }
3146
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003147 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3148 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00003149
3150 if (checkForErrors(TU) != 0) {
3151 errorCode = -1;
3152 goto teardown;
3153 }
3154
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003155 for (i = 0; i != num_tokens; ++i) {
3156 const char *kind = "<unknown>";
3157 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3158 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
3159 unsigned start_line, start_column, end_line, end_column;
3160
3161 switch (clang_getTokenKind(tokens[i])) {
3162 case CXToken_Punctuation: kind = "Punctuation"; break;
3163 case CXToken_Keyword: kind = "Keyword"; break;
3164 case CXToken_Identifier: kind = "Identifier"; break;
3165 case CXToken_Literal: kind = "Literal"; break;
3166 case CXToken_Comment: kind = "Comment"; break;
3167 }
Douglas Gregora9b06d42010-11-09 06:24:54 +00003168 clang_getSpellingLocation(clang_getRangeStart(extent),
3169 0, &start_line, &start_column, 0);
3170 clang_getSpellingLocation(clang_getRangeEnd(extent),
3171 0, &end_line, &end_column, 0);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00003172 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Kramer342742a2012-04-14 09:11:51 +00003173 clang_disposeString(spelling);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00003174 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003175 if (!clang_isInvalid(cursors[i].kind)) {
3176 printf(" ");
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00003177 PrintCursor(cursors[i], NULL);
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003178 }
3179 printf("\n");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003180 }
3181 free(cursors);
Ted Kremenek93f5e6a2010-10-20 21:22:15 +00003182 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003183
3184 teardown:
Douglas Gregora88084b2010-02-18 18:08:43 +00003185 PrintDiagnostics(TU);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003186 clang_disposeTranslationUnit(TU);
3187 clang_disposeIndex(CIdx);
3188 free(filename);
3189 free_remapped_files(unsaved_files, num_unsaved_files);
3190 return errorCode;
3191}
3192
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003193static int
3194perform_test_compilation_db(const char *database, int argc, const char **argv) {
3195 CXCompilationDatabase db;
3196 CXCompileCommands CCmds;
3197 CXCompileCommand CCmd;
3198 CXCompilationDatabase_Error ec;
3199 CXString wd;
3200 CXString arg;
3201 int errorCode = 0;
3202 char *tmp;
3203 unsigned len;
3204 char *buildDir;
3205 int i, j, a, numCmds, numArgs;
3206
3207 len = strlen(database);
3208 tmp = (char *) malloc(len+1);
3209 memcpy(tmp, database, len+1);
3210 buildDir = dirname(tmp);
3211
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003212 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003213
3214 if (db) {
3215
3216 if (ec!=CXCompilationDatabase_NoError) {
3217 printf("unexpected error %d code while loading compilation database\n", ec);
3218 errorCode = -1;
3219 goto cdb_end;
3220 }
3221
3222 for (i=0; i<argc && errorCode==0; ) {
3223 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003224 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003225
3226 if (!CCmds) {
3227 printf("file %s not found in compilation db\n", argv[i+1]);
3228 errorCode = -1;
3229 break;
3230 }
3231
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003232 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003233
3234 if (numCmds==0) {
3235 fprintf(stderr, "should not get an empty compileCommand set for file"
3236 " '%s'\n", argv[i+1]);
3237 errorCode = -1;
3238 break;
3239 }
3240
3241 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003242 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003243
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003244 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003245 printf("workdir:'%s'", clang_getCString(wd));
3246 clang_disposeString(wd);
3247
3248 printf(" cmdline:'");
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003249 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003250 for (a=0; a<numArgs; ++a) {
3251 if (a) printf(" ");
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003252 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003253 printf("%s", clang_getCString(arg));
3254 clang_disposeString(arg);
3255 }
3256 printf("'\n");
3257 }
3258
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003259 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003260
3261 i += 2;
3262 }
3263 }
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00003264 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003265 } else {
3266 printf("database loading failed with error code %d.\n", ec);
3267 errorCode = -1;
3268 }
3269
3270cdb_end:
3271 free(tmp);
3272
3273 return errorCode;
3274}
3275
Ted Kremenek0d435192009-11-17 18:13:31 +00003276/******************************************************************************/
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003277/* USR printing. */
3278/******************************************************************************/
3279
3280static int insufficient_usr(const char *kind, const char *usage) {
3281 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3282 return 1;
3283}
3284
3285static unsigned isUSR(const char *s) {
3286 return s[0] == 'c' && s[1] == ':';
3287}
3288
3289static int not_usr(const char *s, const char *arg) {
3290 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3291 return 1;
3292}
3293
3294static void print_usr(CXString usr) {
3295 const char *s = clang_getCString(usr);
3296 printf("%s\n", s);
3297 clang_disposeString(usr);
3298}
3299
3300static void display_usrs() {
3301 fprintf(stderr, "-print-usrs options:\n"
3302 " ObjCCategory <class name> <category name>\n"
3303 " ObjCClass <class name>\n"
3304 " ObjCIvar <ivar name> <class USR>\n"
3305 " ObjCMethod <selector> [0=class method|1=instance method] "
3306 "<class USR>\n"
3307 " ObjCProperty <property name> <class USR>\n"
3308 " ObjCProtocol <protocol name>\n");
3309}
3310
3311int print_usrs(const char **I, const char **E) {
3312 while (I != E) {
3313 const char *kind = *I;
3314 unsigned len = strlen(kind);
3315 switch (len) {
3316 case 8:
3317 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3318 if (I + 2 >= E)
3319 return insufficient_usr(kind, "<ivar name> <class USR>");
3320 if (!isUSR(I[2]))
3321 return not_usr("<class USR>", I[2]);
3322 else {
3323 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00003324 x.data = (void*) I[2];
Ted Kremeneked122732010-11-16 01:56:27 +00003325 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003326 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3327 }
3328
3329 I += 3;
3330 continue;
3331 }
3332 break;
3333 case 9:
3334 if (memcmp(kind, "ObjCClass", 9) == 0) {
3335 if (I + 1 >= E)
3336 return insufficient_usr(kind, "<class name>");
3337 print_usr(clang_constructUSR_ObjCClass(I[1]));
3338 I += 2;
3339 continue;
3340 }
3341 break;
3342 case 10:
3343 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3344 if (I + 3 >= E)
3345 return insufficient_usr(kind, "<method selector> "
3346 "[0=class method|1=instance method] <class USR>");
3347 if (!isUSR(I[3]))
3348 return not_usr("<class USR>", I[3]);
3349 else {
3350 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00003351 x.data = (void*) I[3];
Ted Kremeneked122732010-11-16 01:56:27 +00003352 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003353 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3354 }
3355 I += 4;
3356 continue;
3357 }
3358 break;
3359 case 12:
3360 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3361 if (I + 2 >= E)
3362 return insufficient_usr(kind, "<class name> <category name>");
3363 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3364 I += 3;
3365 continue;
3366 }
3367 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3368 if (I + 1 >= E)
3369 return insufficient_usr(kind, "<protocol name>");
3370 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3371 I += 2;
3372 continue;
3373 }
3374 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3375 if (I + 2 >= E)
3376 return insufficient_usr(kind, "<property name> <class USR>");
3377 if (!isUSR(I[2]))
3378 return not_usr("<class USR>", I[2]);
3379 else {
3380 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00003381 x.data = (void*) I[2];
Ted Kremeneked122732010-11-16 01:56:27 +00003382 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003383 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3384 }
3385 I += 3;
3386 continue;
3387 }
3388 break;
3389 default:
3390 break;
3391 }
3392 break;
3393 }
3394
3395 if (I != E) {
3396 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3397 display_usrs();
3398 return 1;
3399 }
3400 return 0;
3401}
3402
3403int print_usrs_file(const char *file_name) {
3404 char line[2048];
3405 const char *args[128];
3406 unsigned numChars = 0;
3407
3408 FILE *fp = fopen(file_name, "r");
3409 if (!fp) {
3410 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3411 return 1;
3412 }
3413
3414 /* This code is not really all that safe, but it works fine for testing. */
3415 while (!feof(fp)) {
3416 char c = fgetc(fp);
3417 if (c == '\n') {
3418 unsigned i = 0;
3419 const char *s = 0;
3420
3421 if (numChars == 0)
3422 continue;
3423
3424 line[numChars] = '\0';
3425 numChars = 0;
3426
3427 if (line[0] == '/' && line[1] == '/')
3428 continue;
3429
3430 s = strtok(line, " ");
3431 while (s) {
3432 args[i] = s;
3433 ++i;
3434 s = strtok(0, " ");
3435 }
3436 if (print_usrs(&args[0], &args[i]))
3437 return 1;
3438 }
3439 else
3440 line[numChars++] = c;
3441 }
3442
3443 fclose(fp);
3444 return 0;
3445}
3446
3447/******************************************************************************/
Ted Kremenek0d435192009-11-17 18:13:31 +00003448/* Command line processing. */
3449/******************************************************************************/
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003450int write_pch_file(const char *filename, int argc, const char *argv[]) {
3451 CXIndex Idx;
3452 CXTranslationUnit TU;
3453 struct CXUnsavedFile *unsaved_files = 0;
3454 int num_unsaved_files = 0;
Francois Pichet08aa6222011-07-06 22:09:44 +00003455 int result = 0;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003456
Stefanus Du Toitfc093362013-03-01 21:41:22 +00003457 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003458
3459 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3460 clang_disposeIndex(Idx);
3461 return -1;
3462 }
3463
3464 TU = clang_parseTranslationUnit(Idx, 0,
3465 argv + num_unsaved_files,
3466 argc - num_unsaved_files,
3467 unsaved_files,
3468 num_unsaved_files,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00003469 CXTranslationUnit_Incomplete |
3470 CXTranslationUnit_ForSerialization);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003471 if (!TU) {
3472 fprintf(stderr, "Unable to load translation unit!\n");
3473 free_remapped_files(unsaved_files, num_unsaved_files);
3474 clang_disposeIndex(Idx);
3475 return 1;
3476 }
3477
Douglas Gregor39c411f2011-07-06 16:43:36 +00003478 switch (clang_saveTranslationUnit(TU, filename,
3479 clang_defaultSaveOptions(TU))) {
3480 case CXSaveError_None:
3481 break;
3482
3483 case CXSaveError_TranslationErrors:
3484 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3485 filename);
3486 result = 2;
3487 break;
3488
3489 case CXSaveError_InvalidTU:
3490 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3491 filename);
3492 result = 3;
3493 break;
3494
3495 case CXSaveError_Unknown:
3496 default:
3497 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3498 result = 1;
3499 break;
3500 }
3501
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003502 clang_disposeTranslationUnit(TU);
3503 free_remapped_files(unsaved_files, num_unsaved_files);
3504 clang_disposeIndex(Idx);
Douglas Gregor39c411f2011-07-06 16:43:36 +00003505 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003506}
3507
3508/******************************************************************************/
Ted Kremenek15322172011-11-10 08:43:12 +00003509/* Serialized diagnostics. */
3510/******************************************************************************/
3511
3512static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3513 switch (error) {
3514 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3515 case CXLoadDiag_None: break;
3516 case CXLoadDiag_Unknown: return "Unknown";
3517 case CXLoadDiag_InvalidFile: return "Invalid File";
3518 }
3519 return "None";
3520}
3521
3522static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3523 switch (severity) {
3524 case CXDiagnostic_Note: return "note";
3525 case CXDiagnostic_Error: return "error";
3526 case CXDiagnostic_Fatal: return "fatal";
3527 case CXDiagnostic_Ignored: return "ignored";
3528 case CXDiagnostic_Warning: return "warning";
3529 }
3530 return "unknown";
3531}
3532
3533static void printIndent(unsigned indent) {
Ted Kremeneka7e8a832011-11-11 00:46:43 +00003534 if (indent == 0)
3535 return;
3536 fprintf(stderr, "+");
3537 --indent;
Ted Kremenek15322172011-11-10 08:43:12 +00003538 while (indent > 0) {
Ted Kremeneka7e8a832011-11-11 00:46:43 +00003539 fprintf(stderr, "-");
Ted Kremenek15322172011-11-10 08:43:12 +00003540 --indent;
3541 }
3542}
3543
3544static void printLocation(CXSourceLocation L) {
3545 CXFile File;
3546 CXString FileName;
3547 unsigned line, column, offset;
3548
3549 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3550 FileName = clang_getFileName(File);
3551
3552 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3553 clang_disposeString(FileName);
3554}
3555
3556static void printRanges(CXDiagnostic D, unsigned indent) {
3557 unsigned i, n = clang_getDiagnosticNumRanges(D);
3558
3559 for (i = 0; i < n; ++i) {
3560 CXSourceLocation Start, End;
3561 CXSourceRange SR = clang_getDiagnosticRange(D, i);
3562 Start = clang_getRangeStart(SR);
3563 End = clang_getRangeEnd(SR);
3564
3565 printIndent(indent);
3566 fprintf(stderr, "Range: ");
3567 printLocation(Start);
3568 fprintf(stderr, " ");
3569 printLocation(End);
3570 fprintf(stderr, "\n");
3571 }
3572}
3573
3574static void printFixIts(CXDiagnostic D, unsigned indent) {
3575 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek3739b322012-03-20 20:49:45 +00003576 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenek15322172011-11-10 08:43:12 +00003577 for (i = 0 ; i < n; ++i) {
3578 CXSourceRange ReplacementRange;
3579 CXString text;
3580 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3581
3582 printIndent(indent);
3583 fprintf(stderr, "FIXIT: (");
3584 printLocation(clang_getRangeStart(ReplacementRange));
3585 fprintf(stderr, " - ");
3586 printLocation(clang_getRangeEnd(ReplacementRange));
3587 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3588 clang_disposeString(text);
3589 }
3590}
3591
3592static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi91909432011-11-10 09:30:15 +00003593 unsigned i, n;
3594
Ted Kremenek15322172011-11-10 08:43:12 +00003595 if (!Diags)
3596 return;
3597
NAKAMURA Takumi91909432011-11-10 09:30:15 +00003598 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenek15322172011-11-10 08:43:12 +00003599 for (i = 0; i < n; ++i) {
3600 CXSourceLocation DiagLoc;
3601 CXDiagnostic D;
3602 CXFile File;
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003603 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenek15322172011-11-10 08:43:12 +00003604 unsigned line, column, offset;
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003605 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenek15322172011-11-10 08:43:12 +00003606
3607 D = clang_getDiagnosticInSet(Diags, i);
3608 DiagLoc = clang_getDiagnosticLocation(D);
3609 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3610 FileName = clang_getFileName(File);
3611 DiagSpelling = clang_getDiagnosticSpelling(D);
3612
3613 printIndent(indent);
3614
3615 fprintf(stderr, "%s:%d:%d: %s: %s",
3616 clang_getCString(FileName),
3617 line,
3618 column,
3619 getSeverityString(clang_getDiagnosticSeverity(D)),
3620 clang_getCString(DiagSpelling));
3621
3622 DiagOption = clang_getDiagnosticOption(D, 0);
3623 DiagOptionStr = clang_getCString(DiagOption);
3624 if (DiagOptionStr) {
3625 fprintf(stderr, " [%s]", DiagOptionStr);
3626 }
3627
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003628 DiagCat = clang_getDiagnosticCategoryText(D);
3629 DiagCatStr = clang_getCString(DiagCat);
3630 if (DiagCatStr) {
3631 fprintf(stderr, " [%s]", DiagCatStr);
3632 }
3633
Ted Kremenek15322172011-11-10 08:43:12 +00003634 fprintf(stderr, "\n");
3635
3636 printRanges(D, indent);
3637 printFixIts(D, indent);
3638
NAKAMURA Takumia4ca95a2011-11-10 10:07:57 +00003639 /* Print subdiagnostics. */
Ted Kremenek15322172011-11-10 08:43:12 +00003640 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3641
3642 clang_disposeString(FileName);
3643 clang_disposeString(DiagSpelling);
3644 clang_disposeString(DiagOption);
3645 }
3646}
3647
3648static int read_diagnostics(const char *filename) {
3649 enum CXLoadDiag_Error error;
3650 CXString errorString;
3651 CXDiagnosticSet Diags = 0;
3652
3653 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3654 if (!Diags) {
3655 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3656 getDiagnosticCodeStr(error),
3657 clang_getCString(errorString));
3658 clang_disposeString(errorString);
3659 return 1;
3660 }
3661
3662 printDiagnosticSet(Diags, 0);
Ted Kremeneka7e8a832011-11-11 00:46:43 +00003663 fprintf(stderr, "Number of diagnostics: %d\n",
3664 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenek15322172011-11-10 08:43:12 +00003665 clang_disposeDiagnosticSet(Diags);
3666 return 0;
3667}
3668
3669/******************************************************************************/
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003670/* Command line processing. */
3671/******************************************************************************/
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003672
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003673static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek7d405622010-01-12 23:34:26 +00003674 if (s[0] == '\0')
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003675 return FilteredPrintingVisitor;
Ted Kremenek7d405622010-01-12 23:34:26 +00003676 if (strcmp(s, "-usrs") == 0)
3677 return USRVisitor;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003678 if (strncmp(s, "-memory-usage", 13) == 0)
3679 return GetVisitor(s + 13);
Ted Kremenek7d405622010-01-12 23:34:26 +00003680 return NULL;
3681}
3682
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003683static void print_usage(void) {
3684 fprintf(stderr,
Ted Kremenek0d435192009-11-17 18:13:31 +00003685 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003686 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003687 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00003688 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
3689 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi35849722012-10-24 22:52:04 +00003690 fprintf(stderr,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003691 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00003692 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00003693 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00003694 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00003695 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen26fc0f92011-10-06 11:38:08 +00003696 "[FileCheck prefix]\n");
3697 fprintf(stderr,
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00003698 " c-index-test -test-load-tu <AST file> <symbol filter> "
3699 "[FileCheck prefix]\n"
Ted Kremenek7d405622010-01-12 23:34:26 +00003700 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
3701 "[FileCheck prefix]\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003702 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003703 fprintf(stderr,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003704 " c-index-test -test-load-source-memory-usage "
3705 "<symbol filter> {<args>}*\n"
Douglas Gregorabc563f2010-07-19 21:46:24 +00003706 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
3707 " {<args>}*\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003708 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003709 " c-index-test -test-load-source-usrs-memory-usage "
3710 "<symbol filter> {<args>}*\n"
Ted Kremenek16b55a72010-01-26 19:31:51 +00003711 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
3712 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00003713 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth53513d22010-07-22 06:29:13 +00003714 fprintf(stderr,
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00003715 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00003716 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003717 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenko1eb60822012-12-04 15:13:46 +00003718 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003719 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003720 " c-index-test -print-usr-file <file>\n"
Ted Kremenek15322172011-11-10 08:43:12 +00003721 " c-index-test -write-pch <file> <compiler arguments>\n");
3722 fprintf(stderr,
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003723 " c-index-test -compilation-db [lookup <filename>] database\n");
3724 fprintf(stderr,
Ted Kremenek15322172011-11-10 08:43:12 +00003725 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregorcaf4bd32010-07-20 14:34:35 +00003726 fprintf(stderr,
Ted Kremenek7d405622010-01-12 23:34:26 +00003727 " <symbol filter> values:\n%s",
Ted Kremenek0d435192009-11-17 18:13:31 +00003728 " all - load all symbols, including those from PCH\n"
3729 " local - load all symbols except those in PCH\n"
3730 " category - only load ObjC categories (non-PCH)\n"
3731 " interface - only load ObjC interfaces (non-PCH)\n"
3732 " protocol - only load ObjC protocols (non-PCH)\n"
3733 " function - only load functions (non-PCH)\n"
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00003734 " typedef - only load typdefs (non-PCH)\n"
3735 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003736}
3737
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003738/***/
3739
3740int cindextest_main(int argc, const char **argv) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003741 clang_enableStackTraces();
Ted Kremenek15322172011-11-10 08:43:12 +00003742 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
3743 return read_diagnostics(argv[2]);
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003744 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor1982c182010-07-12 18:38:41 +00003745 return perform_code_completion(argc, argv, 0);
3746 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
3747 return perform_code_completion(argc, argv, 1);
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003748 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
3749 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003750 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
3751 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidisee2d5fd2013-03-08 02:32:34 +00003752 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
3753 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003754 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidis11db1822012-10-24 18:29:15 +00003755 return index_file(argc - 2, argv + 2, /*full=*/0);
3756 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
3757 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00003758 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
3759 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisd10682f2012-12-05 21:53:37 +00003760 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
3761 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek7d405622010-01-12 23:34:26 +00003762 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003763 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek7d405622010-01-12 23:34:26 +00003764 if (I)
Ted Kremenekce2ae882010-01-26 17:59:48 +00003765 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
3766 NULL);
Ted Kremenek7d405622010-01-12 23:34:26 +00003767 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00003768 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
3769 CXCursorVisitor I = GetVisitor(argv[1] + 25);
3770 if (I) {
3771 int trials = atoi(argv[2]);
3772 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
3773 NULL);
3774 }
3775 }
Ted Kremenek7d405622010-01-12 23:34:26 +00003776 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003777 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003778
3779 PostVisitTU postVisit = 0;
3780 if (strstr(argv[1], "-memory-usage"))
3781 postVisit = PrintMemoryUsage;
3782
Ted Kremenek7d405622010-01-12 23:34:26 +00003783 if (I)
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003784 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
3785 postVisit);
Ted Kremenek7d405622010-01-12 23:34:26 +00003786 }
3787 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00003788 return perform_file_scan(argv[2], argv[3],
3789 argc >= 5 ? argv[4] : 0);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003790 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
3791 return perform_token_annotation(argc, argv);
Ted Kremenek16b55a72010-01-26 19:31:51 +00003792 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
3793 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
3794 PrintInclusionStack);
3795 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
3796 return perform_test_load_tu(argv[2], "all", NULL, NULL,
3797 PrintInclusionStack);
Ted Kremenek3bed5272010-03-03 06:37:58 +00003798 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
3799 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
3800 NULL);
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00003801 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek8e0ac172010-05-14 21:29:26 +00003802 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenkoae03d8e2013-02-15 21:15:49 +00003803 PrintType, 0);
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003804 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
3805 return perform_test_load_source(argc - 2, argv + 2, "all",
3806 PrintTypeSize, 0);
Dmitri Gribenko1eb60822012-12-04 15:13:46 +00003807 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
3808 return perform_test_load_source(argc - 2, argv + 2, "all",
3809 PrintBitWidth, 0);
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003810 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
3811 if (argc > 2)
3812 return print_usrs(argv + 2, argv + argc);
3813 else {
3814 display_usrs();
3815 return 1;
3816 }
3817 }
3818 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
3819 return print_usrs_file(argv[2]);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003820 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
3821 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003822 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
3823 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
3824
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003825 print_usage();
3826 return 1;
Steve Naroff50398192009-08-28 15:28:48 +00003827}
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003828
3829/***/
3830
3831/* We intentionally run in a separate thread to ensure we at least minimal
3832 * testing of a multithreaded environment (for example, having a reduced stack
3833 * size). */
3834
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003835typedef struct thread_info {
3836 int argc;
3837 const char **argv;
3838 int result;
3839} thread_info;
Benjamin Kramer84294912010-11-04 19:11:31 +00003840void thread_runner(void *client_data_v) {
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003841 thread_info *client_data = client_data_v;
3842 client_data->result = cindextest_main(client_data->argc, client_data->argv);
NAKAMURA Takumi3be55cd2012-04-07 06:59:28 +00003843#ifdef __CYGWIN__
3844 fflush(stdout); /* stdout is not flushed on Cygwin. */
3845#endif
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003846}
3847
3848int main(int argc, const char **argv) {
Benjamin Kramerd1a4f682012-08-10 10:06:13 +00003849 thread_info client_data;
3850
Dmitri Gribenkof303d4c2012-08-07 17:54:38 +00003851#ifdef CLANG_HAVE_LIBXML
3852 LIBXML_TEST_VERSION
3853#endif
3854
Douglas Gregor61605982010-10-27 16:00:01 +00003855 if (getenv("CINDEXTEST_NOTHREADS"))
3856 return cindextest_main(argc, argv);
3857
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003858 client_data.argc = argc;
3859 client_data.argv = argv;
Daniel Dunbara32a6e12010-11-04 01:26:31 +00003860 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003861 return client_data.result;
3862}