blob: 4af25488953ec6464d4a429d828968f50acb75aa [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"
Douglas Gregor1e5e6682010-08-26 13:48:20 +00005#include <ctype.h>
Douglas Gregor0c8296d2009-11-07 00:00:49 +00006#include <stdlib.h>
Steve Naroff89922f82009-08-31 00:59:03 +00007#include <stdio.h>
Steve Naroffaf08ddc2009-09-03 15:49:00 +00008#include <string.h>
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00009#include <assert.h>
Steve Naroffaf08ddc2009-09-03 15:49:00 +000010
Ted Kremenek0d435192009-11-17 18:13:31 +000011/******************************************************************************/
12/* Utility functions. */
13/******************************************************************************/
14
John Thompson2e06fc82009-10-27 13:42:56 +000015#ifdef _MSC_VER
16char *basename(const char* path)
17{
18 char* base1 = (char*)strrchr(path, '/');
19 char* base2 = (char*)strrchr(path, '\\');
20 if (base1 && base2)
21 return((base1 > base2) ? base1 + 1 : base2 + 1);
22 else if (base1)
23 return(base1 + 1);
24 else if (base2)
25 return(base2 + 1);
26
27 return((char*)path);
28}
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000029char *dirname(char* path)
30{
31 char* base1 = (char*)strrchr(path, '/');
32 char* base2 = (char*)strrchr(path, '\\');
33 if (base1 && base2)
34 if (base1 > base2)
35 *base1 = 0;
36 else
37 *base2 = 0;
38 else if (base1)
NAKAMURA Takumi0fb474a2012-06-30 11:47:18 +000039 *base1 = 0;
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000040 else if (base2)
NAKAMURA Takumi0fb474a2012-06-30 11:47:18 +000041 *base2 = 0;
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000042
43 return path;
44}
John Thompson2e06fc82009-10-27 13:42:56 +000045#else
Steve Naroffff9e18c2009-09-24 20:03:06 +000046extern char *basename(const char *);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +000047extern char *dirname(char *);
John Thompson2e06fc82009-10-27 13:42:56 +000048#endif
Steve Naroffff9e18c2009-09-24 20:03:06 +000049
Douglas Gregor45ba9a12010-07-25 17:39:21 +000050/** \brief Return the default parsing options. */
Douglas Gregor44c181a2010-07-23 00:33:23 +000051static unsigned getDefaultParsingOptions() {
52 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
53
54 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregorb1c031b2010-08-09 22:28:58 +000055 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregor87c08a52010-08-13 22:48:40 +000056 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
57 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidisdcaca012011-11-03 02:20:25 +000058 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
59 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6a91d382012-04-12 10:11:59 +000060 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
61 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +000062 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
63 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Douglas Gregor44c181a2010-07-23 00:33:23 +000064
65 return options;
66}
67
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +000068static int checkForErrors(CXTranslationUnit TU);
69
Daniel Dunbar51b058c2010-02-14 08:32:24 +000070static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
71 unsigned end_line, unsigned end_column) {
72 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 end_line, end_column);
Daniel Dunbar51b058c2010-02-14 08:32:24 +000074}
75
Ted Kremenek1c6da172009-11-17 19:37:36 +000076static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
77 CXTranslationUnit *TU) {
Ted Kremeneke68fff62010-02-17 00:41:32 +000078
Douglas Gregora88084b2010-02-18 18:08:43 +000079 *TU = clang_createTranslationUnit(Idx, file);
Dan Gohman6be2a222010-07-26 21:44:15 +000080 if (!*TU) {
Ted Kremenek1c6da172009-11-17 19:37:36 +000081 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
82 return 0;
Ted Kremeneke68fff62010-02-17 00:41:32 +000083 }
Ted Kremenek1c6da172009-11-17 19:37:36 +000084 return 1;
85}
86
Douglas Gregor4db64a42010-01-23 00:14:00 +000087void free_remapped_files(struct CXUnsavedFile *unsaved_files,
88 int num_unsaved_files) {
89 int i;
90 for (i = 0; i != num_unsaved_files; ++i) {
91 free((char *)unsaved_files[i].Filename);
92 free((char *)unsaved_files[i].Contents);
93 }
Douglas Gregor653a55f2010-08-19 20:50:29 +000094 free(unsaved_files);
Douglas Gregor4db64a42010-01-23 00:14:00 +000095}
96
97int parse_remapped_files(int argc, const char **argv, int start_arg,
98 struct CXUnsavedFile **unsaved_files,
99 int *num_unsaved_files) {
100 int i;
101 int arg;
102 int prefix_len = strlen("-remap-file=");
103 *unsaved_files = 0;
104 *num_unsaved_files = 0;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000105
Douglas Gregor4db64a42010-01-23 00:14:00 +0000106 /* Count the number of remapped files. */
107 for (arg = start_arg; arg < argc; ++arg) {
108 if (strncmp(argv[arg], "-remap-file=", prefix_len))
109 break;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000110
Douglas Gregor4db64a42010-01-23 00:14:00 +0000111 ++*num_unsaved_files;
112 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000113
Douglas Gregor4db64a42010-01-23 00:14:00 +0000114 if (*num_unsaved_files == 0)
115 return 0;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000116
Douglas Gregor4db64a42010-01-23 00:14:00 +0000117 *unsaved_files
Douglas Gregor653a55f2010-08-19 20:50:29 +0000118 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
119 *num_unsaved_files);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000120 for (arg = start_arg, i = 0; i != *num_unsaved_files; ++i, ++arg) {
121 struct CXUnsavedFile *unsaved = *unsaved_files + i;
122 const char *arg_string = argv[arg] + prefix_len;
123 int filename_len;
124 char *filename;
125 char *contents;
126 FILE *to_file;
127 const char *semi = strchr(arg_string, ';');
128 if (!semi) {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000129 fprintf(stderr,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000130 "error: -remap-file=from;to argument is missing semicolon\n");
131 free_remapped_files(*unsaved_files, i);
132 *unsaved_files = 0;
133 *num_unsaved_files = 0;
134 return -1;
135 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000136
Douglas Gregor4db64a42010-01-23 00:14:00 +0000137 /* Open the file that we're remapping to. */
Francois Pichetc44fe4b2010-10-12 01:01:43 +0000138 to_file = fopen(semi + 1, "rb");
Douglas Gregor4db64a42010-01-23 00:14:00 +0000139 if (!to_file) {
140 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
141 semi + 1);
142 free_remapped_files(*unsaved_files, i);
143 *unsaved_files = 0;
144 *num_unsaved_files = 0;
145 return -1;
146 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000147
Douglas Gregor4db64a42010-01-23 00:14:00 +0000148 /* Determine the length of the file we're remapping to. */
149 fseek(to_file, 0, SEEK_END);
150 unsaved->Length = ftell(to_file);
151 fseek(to_file, 0, SEEK_SET);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000152
Douglas Gregor4db64a42010-01-23 00:14:00 +0000153 /* Read the contents of the file we're remapping to. */
154 contents = (char *)malloc(unsaved->Length + 1);
155 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
156 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
157 (feof(to_file) ? "EOF" : "error"), semi + 1);
158 fclose(to_file);
159 free_remapped_files(*unsaved_files, i);
Richard Smithe07c5f82012-07-05 08:20:49 +0000160 free(contents);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000161 *unsaved_files = 0;
162 *num_unsaved_files = 0;
163 return -1;
164 }
165 contents[unsaved->Length] = 0;
166 unsaved->Contents = contents;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000167
Douglas Gregor4db64a42010-01-23 00:14:00 +0000168 /* Close the file. */
169 fclose(to_file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000170
Douglas Gregor4db64a42010-01-23 00:14:00 +0000171 /* Copy the file name that we're remapping from. */
172 filename_len = semi - arg_string;
173 filename = (char *)malloc(filename_len + 1);
174 memcpy(filename, arg_string, filename_len);
175 filename[filename_len] = 0;
176 unsaved->Filename = filename;
177 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000178
Douglas Gregor4db64a42010-01-23 00:14:00 +0000179 return 0;
180}
181
Ted Kremenek0d435192009-11-17 18:13:31 +0000182/******************************************************************************/
183/* Pretty-printing. */
184/******************************************************************************/
185
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000186static const char *FileCheckPrefix = "CHECK";
187
188static void PrintCString(const char *CStr) {
Dmitri Gribenko2d44d772012-06-26 20:39:18 +0000189 if (CStr != NULL && CStr[0] != '\0') {
190 for ( ; *CStr; ++CStr) {
191 const char C = *CStr;
192 switch (C) {
193 case '\n': printf("\\n"); break;
194 case '\r': printf("\\r"); break;
195 case '\t': printf("\\t"); break;
196 case '\v': printf("\\v"); break;
197 case '\f': printf("\\f"); break;
198 default: putchar(C); break;
199 }
200 }
201 }
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000202}
203
204static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
205 printf(" %s=[", Prefix);
206 PrintCString(CStr);
Dmitri Gribenko2d44d772012-06-26 20:39:18 +0000207 printf("]");
208}
209
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000210static void PrintCXStringAndDispose(CXString Str) {
211 PrintCString(clang_getCString(Str));
212 clang_disposeString(Str);
213}
214
215static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
216 CXString Str) {
217 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
218 clang_disposeString(Str);
219}
220
Douglas Gregor430d7a12011-07-25 17:48:11 +0000221static void PrintRange(CXSourceRange R, const char *str) {
222 CXFile begin_file, end_file;
223 unsigned begin_line, begin_column, end_line, end_column;
224
225 clang_getSpellingLocation(clang_getRangeStart(R),
226 &begin_file, &begin_line, &begin_column, 0);
227 clang_getSpellingLocation(clang_getRangeEnd(R),
228 &end_file, &end_line, &end_column, 0);
229 if (!begin_file || !end_file)
230 return;
231
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +0000232 if (str)
233 printf(" %s=", str);
Douglas Gregor430d7a12011-07-25 17:48:11 +0000234 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
235}
236
Douglas Gregor358559d2010-10-02 22:49:11 +0000237int want_display_name = 0;
238
Douglas Gregorcc889662012-05-08 00:14:45 +0000239static void printVersion(const char *Prefix, CXVersion Version) {
240 if (Version.Major < 0)
241 return;
242 printf("%s%d", Prefix, Version.Major);
243
244 if (Version.Minor < 0)
245 return;
246 printf(".%d", Version.Minor);
247
248 if (Version.Subminor < 0)
249 return;
250 printf(".%d", Version.Subminor);
251}
252
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000253struct CommentASTDumpingContext {
254 int IndentLevel;
255};
256
257static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
258 CXComment Comment) {
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000259 unsigned i;
260 unsigned e;
261 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
262
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000263 Ctx->IndentLevel++;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000264 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000265 printf(" ");
266
267 printf("(");
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000268 switch (Kind) {
269 case CXComment_Null:
270 printf("CXComment_Null");
271 break;
272 case CXComment_Text:
273 printf("CXComment_Text");
274 PrintCXStringWithPrefixAndDispose("Text",
275 clang_TextComment_getText(Comment));
276 if (clang_Comment_isWhitespace(Comment))
277 printf(" IsWhitespace");
278 if (clang_InlineContentComment_hasTrailingNewline(Comment))
279 printf(" HasTrailingNewline");
280 break;
281 case CXComment_InlineCommand:
282 printf("CXComment_InlineCommand");
283 PrintCXStringWithPrefixAndDispose(
284 "CommandName",
285 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenko2d66a502012-07-23 16:43:01 +0000286 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
287 case CXCommentInlineCommandRenderKind_Normal:
288 printf(" RenderNormal");
289 break;
290 case CXCommentInlineCommandRenderKind_Bold:
291 printf(" RenderBold");
292 break;
293 case CXCommentInlineCommandRenderKind_Monospaced:
294 printf(" RenderMonospaced");
295 break;
296 case CXCommentInlineCommandRenderKind_Emphasized:
297 printf(" RenderEmphasized");
298 break;
299 }
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000300 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000301 i != e; ++i) {
302 printf(" Arg[%u]=", i);
303 PrintCXStringAndDispose(
304 clang_InlineCommandComment_getArgText(Comment, i));
305 }
306 if (clang_InlineContentComment_hasTrailingNewline(Comment))
307 printf(" HasTrailingNewline");
308 break;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000309 case CXComment_HTMLStartTag: {
310 unsigned NumAttrs;
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000311 printf("CXComment_HTMLStartTag");
312 PrintCXStringWithPrefixAndDispose(
313 "Name",
314 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000315 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000316 if (NumAttrs != 0) {
317 printf(" Attrs:");
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000318 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000319 printf(" ");
320 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
321 printf("=");
322 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
323 }
324 }
325 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
326 printf(" SelfClosing");
327 if (clang_InlineContentComment_hasTrailingNewline(Comment))
328 printf(" HasTrailingNewline");
329 break;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000330 }
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000331 case CXComment_HTMLEndTag:
332 printf("CXComment_HTMLEndTag");
333 PrintCXStringWithPrefixAndDispose(
334 "Name",
335 clang_HTMLTagComment_getTagName(Comment));
336 if (clang_InlineContentComment_hasTrailingNewline(Comment))
337 printf(" HasTrailingNewline");
338 break;
339 case CXComment_Paragraph:
340 printf("CXComment_Paragraph");
341 if (clang_Comment_isWhitespace(Comment))
342 printf(" IsWhitespace");
343 break;
344 case CXComment_BlockCommand:
345 printf("CXComment_BlockCommand");
346 PrintCXStringWithPrefixAndDispose(
347 "CommandName",
348 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000349 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000350 i != e; ++i) {
351 printf(" Arg[%u]=", i);
352 PrintCXStringAndDispose(
353 clang_BlockCommandComment_getArgText(Comment, i));
354 }
355 break;
356 case CXComment_ParamCommand:
357 printf("CXComment_ParamCommand");
358 switch (clang_ParamCommandComment_getDirection(Comment)) {
359 case CXCommentParamPassDirection_In:
360 printf(" in");
361 break;
362 case CXCommentParamPassDirection_Out:
363 printf(" out");
364 break;
365 case CXCommentParamPassDirection_InOut:
366 printf(" in,out");
367 break;
368 }
369 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
370 printf(" explicitly");
371 else
372 printf(" implicitly");
373 PrintCXStringWithPrefixAndDispose(
374 "ParamName",
375 clang_ParamCommandComment_getParamName(Comment));
376 if (clang_ParamCommandComment_isParamIndexValid(Comment))
377 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
378 else
379 printf(" ParamIndex=Invalid");
380 break;
Dmitri Gribenko96b09862012-07-31 22:37:06 +0000381 case CXComment_TParamCommand:
382 printf("CXComment_TParamCommand");
383 PrintCXStringWithPrefixAndDispose(
384 "ParamName",
385 clang_TParamCommandComment_getParamName(Comment));
386 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
387 printf(" ParamPosition={");
388 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
389 i != e; ++i) {
390 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
391 if (i != e - 1)
392 printf(", ");
393 }
394 printf("}");
395 } else
396 printf(" ParamPosition=Invalid");
397 break;
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000398 case CXComment_VerbatimBlockCommand:
399 printf("CXComment_VerbatimBlockCommand");
400 PrintCXStringWithPrefixAndDispose(
401 "CommandName",
402 clang_BlockCommandComment_getCommandName(Comment));
403 break;
404 case CXComment_VerbatimBlockLine:
405 printf("CXComment_VerbatimBlockLine");
406 PrintCXStringWithPrefixAndDispose(
407 "Text",
408 clang_VerbatimBlockLineComment_getText(Comment));
409 break;
410 case CXComment_VerbatimLine:
411 printf("CXComment_VerbatimLine");
412 PrintCXStringWithPrefixAndDispose(
413 "Text",
414 clang_VerbatimLineComment_getText(Comment));
415 break;
416 case CXComment_FullComment:
417 printf("CXComment_FullComment");
418 break;
419 }
420 if (Kind != CXComment_Null) {
421 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000422 unsigned i;
423 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000424 printf("\n// %s: ", FileCheckPrefix);
425 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
426 }
427 }
428 printf(")");
429 Ctx->IndentLevel--;
430}
431
432static void DumpCXComment(CXComment Comment) {
433 struct CommentASTDumpingContext Ctx;
434 Ctx.IndentLevel = 1;
435 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
436 DumpCXCommentInternal(&Ctx, Comment);
437 printf("]");
438}
439
440static void PrintCursorComments(CXCursor Cursor) {
441 {
442 CXString RawComment;
443 const char *RawCommentCString;
444 CXString BriefComment;
445 const char *BriefCommentCString;
446
447 RawComment = clang_Cursor_getRawCommentText(Cursor);
448 RawCommentCString = clang_getCString(RawComment);
449 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
450 PrintCStringWithPrefix("RawComment", RawCommentCString);
451 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
452
453 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
454 BriefCommentCString = clang_getCString(BriefComment);
455 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
456 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
457 clang_disposeString(BriefComment);
458 }
459 clang_disposeString(RawComment);
460 }
461
462 {
463 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
464 if (clang_Comment_getKind(Comment) != CXComment_Null) {
465 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
466 clang_FullComment_getAsHTML(Comment));
467 DumpCXComment(Comment);
468 }
469 }
470}
471
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000472static void PrintCursor(CXCursor Cursor) {
473 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000474 if (clang_isInvalid(Cursor.kind)) {
475 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
476 printf("Invalid Cursor => %s", clang_getCString(ks));
477 clang_disposeString(ks);
478 }
Steve Naroff699a07d2009-09-25 21:32:34 +0000479 else {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000480 CXString string, ks;
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000481 CXCursor Referenced;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000482 unsigned line, column;
Douglas Gregore0329ac2010-09-02 00:07:54 +0000483 CXCursor SpecializationOf;
Douglas Gregor9f592342010-10-01 20:25:15 +0000484 CXCursor *overridden;
485 unsigned num_overridden;
Douglas Gregor430d7a12011-07-25 17:48:11 +0000486 unsigned RefNameRangeNr;
487 CXSourceRange CursorExtent;
488 CXSourceRange RefNameRange;
Douglas Gregorcc889662012-05-08 00:14:45 +0000489 int AlwaysUnavailable;
490 int AlwaysDeprecated;
491 CXString UnavailableMessage;
492 CXString DeprecatedMessage;
493 CXPlatformAvailability PlatformAvailability[2];
494 int NumPlatformAvailability;
495 int I;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000496
Ted Kremeneke68fff62010-02-17 00:41:32 +0000497 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor358559d2010-10-02 22:49:11 +0000498 string = want_display_name? clang_getCursorDisplayName(Cursor)
499 : clang_getCursorSpelling(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000500 printf("%s=%s", clang_getCString(ks),
501 clang_getCString(string));
502 clang_disposeString(ks);
Steve Naroffef0cef62009-11-09 17:45:52 +0000503 clang_disposeString(string);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000504
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000505 Referenced = clang_getCursorReferenced(Cursor);
506 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000507 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
508 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
509 printf("[");
510 for (I = 0; I != N; ++I) {
511 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor1f6206e2010-09-14 00:20:32 +0000512 CXSourceLocation Loc;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000513 if (I)
514 printf(", ");
515
Douglas Gregor1f6206e2010-09-14 00:20:32 +0000516 Loc = clang_getCursorLocation(Ovl);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000517 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000518 printf("%d:%d", line, column);
519 }
520 printf("]");
521 } else {
522 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000523 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000524 printf(":%d:%d", line, column);
525 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000526 }
Douglas Gregorb6998662010-01-19 19:34:47 +0000527
528 if (clang_isCursorDefinition(Cursor))
529 printf(" (Definition)");
Douglas Gregor58ddb602010-08-23 23:00:57 +0000530
531 switch (clang_getCursorAvailability(Cursor)) {
532 case CXAvailability_Available:
533 break;
534
535 case CXAvailability_Deprecated:
536 printf(" (deprecated)");
537 break;
538
539 case CXAvailability_NotAvailable:
540 printf(" (unavailable)");
541 break;
Erik Verbruggend1205962011-10-06 07:27:49 +0000542
543 case CXAvailability_NotAccessible:
544 printf(" (inaccessible)");
545 break;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000546 }
Ted Kremenek95f33552010-08-26 01:42:22 +0000547
Douglas Gregorcc889662012-05-08 00:14:45 +0000548 NumPlatformAvailability
549 = clang_getCursorPlatformAvailability(Cursor,
550 &AlwaysDeprecated,
551 &DeprecatedMessage,
552 &AlwaysUnavailable,
553 &UnavailableMessage,
554 PlatformAvailability, 2);
555 if (AlwaysUnavailable) {
556 printf(" (always unavailable: \"%s\")",
557 clang_getCString(UnavailableMessage));
558 } else if (AlwaysDeprecated) {
559 printf(" (always deprecated: \"%s\")",
560 clang_getCString(DeprecatedMessage));
561 } else {
562 for (I = 0; I != NumPlatformAvailability; ++I) {
563 if (I >= 2)
564 break;
565
566 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
567 if (PlatformAvailability[I].Unavailable)
568 printf(", unavailable");
569 else {
570 printVersion(", introduced=", PlatformAvailability[I].Introduced);
571 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
572 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
573 }
574 if (clang_getCString(PlatformAvailability[I].Message)[0])
575 printf(", message=\"%s\"",
576 clang_getCString(PlatformAvailability[I].Message));
577 printf(")");
578 }
579 }
580 for (I = 0; I != NumPlatformAvailability; ++I) {
581 if (I >= 2)
582 break;
583 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
584 }
585
586 clang_disposeString(DeprecatedMessage);
587 clang_disposeString(UnavailableMessage);
588
Douglas Gregorb83d4d72011-05-13 15:54:42 +0000589 if (clang_CXXMethod_isStatic(Cursor))
590 printf(" (static)");
591 if (clang_CXXMethod_isVirtual(Cursor))
592 printf(" (virtual)");
593
Ted Kremenek95f33552010-08-26 01:42:22 +0000594 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
595 CXType T =
596 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
597 CXString S = clang_getTypeKindSpelling(T.kind);
598 printf(" [IBOutletCollection=%s]", clang_getCString(S));
599 clang_disposeString(S);
600 }
Ted Kremenek3064ef92010-08-27 21:34:58 +0000601
602 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
603 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
604 unsigned isVirtual = clang_isVirtualBase(Cursor);
605 const char *accessStr = 0;
606
607 switch (access) {
608 case CX_CXXInvalidAccessSpecifier:
609 accessStr = "invalid"; break;
610 case CX_CXXPublic:
611 accessStr = "public"; break;
612 case CX_CXXProtected:
613 accessStr = "protected"; break;
614 case CX_CXXPrivate:
615 accessStr = "private"; break;
616 }
617
618 printf(" [access=%s isVirtual=%s]", accessStr,
619 isVirtual ? "true" : "false");
620 }
Douglas Gregore0329ac2010-09-02 00:07:54 +0000621
622 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
623 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
624 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
625 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000626 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregore0329ac2010-09-02 00:07:54 +0000627 printf(" [Specialization of %s:%d:%d]",
628 clang_getCString(Name), line, column);
629 clang_disposeString(Name);
630 }
Douglas Gregor9f592342010-10-01 20:25:15 +0000631
632 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
633 if (num_overridden) {
634 unsigned I;
635 printf(" [Overrides ");
636 for (I = 0; I != num_overridden; ++I) {
637 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000638 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor9f592342010-10-01 20:25:15 +0000639 if (I)
640 printf(", ");
641 printf("@%d:%d", line, column);
642 }
643 printf("]");
644 clang_disposeOverriddenCursors(overridden);
645 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000646
647 if (Cursor.kind == CXCursor_InclusionDirective) {
648 CXFile File = clang_getIncludedFile(Cursor);
649 CXString Included = clang_getFileName(File);
650 printf(" (%s)", clang_getCString(Included));
651 clang_disposeString(Included);
Douglas Gregordd3e5542011-05-04 00:14:37 +0000652
653 if (clang_isFileMultipleIncludeGuarded(TU, File))
654 printf(" [multi-include guarded]");
Douglas Gregorecdcb882010-10-20 22:00:55 +0000655 }
Douglas Gregor430d7a12011-07-25 17:48:11 +0000656
657 CursorExtent = clang_getCursorExtent(Cursor);
658 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
659 CXNameRange_WantQualifier
660 | CXNameRange_WantSinglePiece
661 | CXNameRange_WantTemplateArgs,
662 0);
663 if (!clang_equalRanges(CursorExtent, RefNameRange))
664 PrintRange(RefNameRange, "SingleRefName");
665
666 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
667 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
668 CXNameRange_WantQualifier
669 | CXNameRange_WantTemplateArgs,
670 RefNameRangeNr);
671 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
672 break;
673 if (!clang_equalRanges(CursorExtent, RefNameRange))
674 PrintRange(RefNameRange, "RefName");
675 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000676
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000677 PrintCursorComments(Cursor);
Steve Naroff699a07d2009-09-25 21:32:34 +0000678 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000679}
Steve Naroff89922f82009-08-31 00:59:03 +0000680
Ted Kremeneke68fff62010-02-17 00:41:32 +0000681static const char* GetCursorSource(CXCursor Cursor) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000682 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenek74844072010-02-17 00:41:20 +0000683 CXString source;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000684 CXFile file;
Argyrios Kyrtzidisb4efaa02011-11-03 02:20:36 +0000685 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000686 source = clang_getFileName(file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000687 if (!clang_getCString(source)) {
Ted Kremenek74844072010-02-17 00:41:20 +0000688 clang_disposeString(source);
689 return "<invalid loc>";
690 }
691 else {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000692 const char *b = basename(clang_getCString(source));
Ted Kremenek74844072010-02-17 00:41:20 +0000693 clang_disposeString(source);
694 return b;
695 }
Ted Kremenek9298cfc2009-11-17 05:31:58 +0000696}
697
Ted Kremenek0d435192009-11-17 18:13:31 +0000698/******************************************************************************/
Ted Kremenekce2ae882010-01-26 17:59:48 +0000699/* Callbacks. */
700/******************************************************************************/
701
702typedef void (*PostVisitTU)(CXTranslationUnit);
703
Douglas Gregora88084b2010-02-18 18:08:43 +0000704void PrintDiagnostic(CXDiagnostic Diagnostic) {
705 FILE *out = stderr;
Douglas Gregor5352ac02010-01-28 00:27:43 +0000706 CXFile file;
Douglas Gregor274f1902010-02-22 23:17:23 +0000707 CXString Msg;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000708 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000709 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
710 | CXDiagnostic_DisplayOption;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000711 unsigned i, num_fixits;
Ted Kremenekf7b714d2010-03-25 02:00:39 +0000712
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000713 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor5352ac02010-01-28 00:27:43 +0000714 return;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000715
Douglas Gregor274f1902010-02-22 23:17:23 +0000716 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
717 fprintf(stderr, "%s\n", clang_getCString(Msg));
718 clang_disposeString(Msg);
Ted Kremenekf7b714d2010-03-25 02:00:39 +0000719
Douglas Gregora9b06d42010-11-09 06:24:54 +0000720 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
721 &file, 0, 0, 0);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000722 if (!file)
723 return;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000724
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000725 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek3739b322012-03-20 20:49:45 +0000726 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000727 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor473d7012010-02-19 18:16:06 +0000728 CXSourceRange range;
729 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
730 CXSourceLocation start = clang_getRangeStart(range);
731 CXSourceLocation end = clang_getRangeEnd(range);
732 unsigned start_line, start_column, end_line, end_column;
733 CXFile start_file, end_file;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000734 clang_getSpellingLocation(start, &start_file, &start_line,
735 &start_column, 0);
736 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor473d7012010-02-19 18:16:06 +0000737 if (clang_equalLocations(start, end)) {
738 /* Insertion. */
739 if (start_file == file)
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000740 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor473d7012010-02-19 18:16:06 +0000741 clang_getCString(insertion_text), start_line, start_column);
742 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
743 /* Removal. */
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000744 if (start_file == file && end_file == file) {
745 fprintf(out, "FIX-IT: Remove ");
746 PrintExtent(out, start_line, start_column, end_line, end_column);
747 fprintf(out, "\n");
Douglas Gregor51c6d382010-01-29 00:41:11 +0000748 }
Douglas Gregor473d7012010-02-19 18:16:06 +0000749 } else {
750 /* Replacement. */
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000751 if (start_file == end_file) {
752 fprintf(out, "FIX-IT: Replace ");
753 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor473d7012010-02-19 18:16:06 +0000754 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor436f3f02010-02-18 22:27:07 +0000755 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000756 break;
757 }
Douglas Gregor473d7012010-02-19 18:16:06 +0000758 clang_disposeString(insertion_text);
Douglas Gregor51c6d382010-01-29 00:41:11 +0000759 }
Douglas Gregor5352ac02010-01-28 00:27:43 +0000760}
761
Ted Kremenek7473b1c2012-02-14 02:46:03 +0000762void PrintDiagnosticSet(CXDiagnosticSet Set) {
763 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
764 for ( ; i != n ; ++i) {
765 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
766 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregora88084b2010-02-18 18:08:43 +0000767 PrintDiagnostic(Diag);
Ted Kremenek7473b1c2012-02-14 02:46:03 +0000768 if (ChildDiags)
769 PrintDiagnosticSet(ChildDiags);
770 }
771}
772
773void PrintDiagnostics(CXTranslationUnit TU) {
774 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
775 PrintDiagnosticSet(TUSet);
776 clang_disposeDiagnosticSet(TUSet);
Douglas Gregora88084b2010-02-18 18:08:43 +0000777}
778
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000779void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayb2273232011-08-29 16:37:29 +0000780 unsigned long total = 0;
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000781 unsigned i = 0;
Ted Kremenekf7870022011-04-20 16:41:07 +0000782 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet3c683362011-04-18 23:33:22 +0000783 fprintf(stderr, "Memory usage:\n");
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000784 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenekf7870022011-04-20 16:41:07 +0000785 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000786 unsigned long amount = usage.entries[i].amount;
787 total += amount;
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000788 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000789 ((double) amount)/(1024*1024));
790 }
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000791 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000792 ((double) total)/(1024*1024));
Ted Kremenekf7870022011-04-20 16:41:07 +0000793 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000794}
795
Ted Kremenekce2ae882010-01-26 17:59:48 +0000796/******************************************************************************/
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000797/* Logic for testing traversal. */
Ted Kremenek0d435192009-11-17 18:13:31 +0000798/******************************************************************************/
799
Douglas Gregora7bde202010-01-19 00:34:46 +0000800static void PrintCursorExtent(CXCursor C) {
801 CXSourceRange extent = clang_getCursorExtent(C);
Douglas Gregor430d7a12011-07-25 17:48:11 +0000802 PrintRange(extent, "Extent");
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000803}
804
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000805/* Data used by all of the visitors. */
806typedef struct {
807 CXTranslationUnit TU;
808 enum CXCursorKind *Filter;
809} VisitorData;
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000810
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000811
Ted Kremeneke68fff62010-02-17 00:41:32 +0000812enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000813 CXCursor Parent,
814 CXClientData ClientData) {
815 VisitorData *Data = (VisitorData *)ClientData;
816 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000817 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000818 unsigned line, column;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000819 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000820 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor1db19de2010-01-19 21:36:55 +0000821 GetCursorSource(Cursor), line, column);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000822 PrintCursor(Cursor);
Douglas Gregora7bde202010-01-19 00:34:46 +0000823 PrintCursorExtent(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000824 printf("\n");
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000825 return CXChildVisit_Recurse;
Steve Naroff2d4d6292009-08-31 14:26:51 +0000826 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000827
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000828 return CXChildVisit_Continue;
Steve Naroff89922f82009-08-31 00:59:03 +0000829}
Steve Naroff50398192009-08-28 15:28:48 +0000830
Ted Kremeneke68fff62010-02-17 00:41:32 +0000831static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000832 CXCursor Parent,
833 CXClientData ClientData) {
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000834 const char *startBuf, *endBuf;
835 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
836 CXCursor Ref;
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000837 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000838
Douglas Gregorb6998662010-01-19 19:34:47 +0000839 if (Cursor.kind != CXCursor_FunctionDecl ||
840 !clang_isCursorDefinition(Cursor))
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000841 return CXChildVisit_Continue;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000842
843 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
844 &startLine, &startColumn,
845 &endLine, &endColumn);
846 /* Probe the entire body, looking for both decls and refs. */
847 curLine = startLine;
848 curColumn = startColumn;
849
850 while (startBuf < endBuf) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000851 CXSourceLocation Loc;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000852 CXFile file;
Ted Kremenek74844072010-02-17 00:41:20 +0000853 CXString source;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000854
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000855 if (*startBuf == '\n') {
856 startBuf++;
857 curLine++;
858 curColumn = 1;
859 } else if (*startBuf != '\t')
860 curColumn++;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000861
Douglas Gregor98258af2010-01-18 22:46:11 +0000862 Loc = clang_getCursorLocation(Cursor);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000863 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000864
Douglas Gregor1db19de2010-01-19 21:36:55 +0000865 source = clang_getFileName(file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000866 if (clang_getCString(source)) {
Douglas Gregorb9790342010-01-22 21:44:22 +0000867 CXSourceLocation RefLoc
868 = clang_getLocation(Data->TU, file, curLine, curColumn);
869 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor98258af2010-01-18 22:46:11 +0000870 if (Ref.kind == CXCursor_NoDeclFound) {
871 /* Nothing found here; that's fine. */
872 } else if (Ref.kind != CXCursor_FunctionDecl) {
873 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
874 curLine, curColumn);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000875 PrintCursor(Ref);
Douglas Gregor98258af2010-01-18 22:46:11 +0000876 printf("\n");
877 }
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000878 }
Ted Kremenek74844072010-02-17 00:41:20 +0000879 clang_disposeString(source);
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000880 startBuf++;
881 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000882
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000883 return CXChildVisit_Continue;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000884}
885
Ted Kremenek7d405622010-01-12 23:34:26 +0000886/******************************************************************************/
887/* USR testing. */
888/******************************************************************************/
889
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000890enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
891 CXClientData ClientData) {
892 VisitorData *Data = (VisitorData *)ClientData;
893 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Ted Kremenekcf84aa42010-01-18 20:23:29 +0000894 CXString USR = clang_getCursorUSR(C);
Ted Kremeneke542f772010-04-20 23:15:40 +0000895 const char *cstr = clang_getCString(USR);
896 if (!cstr || cstr[0] == '\0') {
Ted Kremenek7d405622010-01-12 23:34:26 +0000897 clang_disposeString(USR);
Ted Kremeneke74ef122010-04-16 21:31:52 +0000898 return CXChildVisit_Recurse;
Ted Kremenek7d405622010-01-12 23:34:26 +0000899 }
Ted Kremeneke542f772010-04-20 23:15:40 +0000900 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
901
Douglas Gregora7bde202010-01-19 00:34:46 +0000902 PrintCursorExtent(C);
Ted Kremenek7d405622010-01-12 23:34:26 +0000903 printf("\n");
904 clang_disposeString(USR);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000905
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000906 return CXChildVisit_Recurse;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000907 }
908
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000909 return CXChildVisit_Continue;
Ted Kremenek7d405622010-01-12 23:34:26 +0000910}
911
912/******************************************************************************/
Ted Kremenek16b55a72010-01-26 19:31:51 +0000913/* Inclusion stack testing. */
914/******************************************************************************/
915
916void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
917 unsigned includeStackLen, CXClientData data) {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000918
Ted Kremenek16b55a72010-01-26 19:31:51 +0000919 unsigned i;
Ted Kremenek74844072010-02-17 00:41:20 +0000920 CXString fname;
921
922 fname = clang_getFileName(includedFile);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000923 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenek74844072010-02-17 00:41:20 +0000924 clang_disposeString(fname);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000925
Ted Kremenek16b55a72010-01-26 19:31:51 +0000926 for (i = 0; i < includeStackLen; ++i) {
927 CXFile includingFile;
928 unsigned line, column;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000929 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
930 &column, 0);
Ted Kremenek74844072010-02-17 00:41:20 +0000931 fname = clang_getFileName(includingFile);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000932 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenek74844072010-02-17 00:41:20 +0000933 clang_disposeString(fname);
Ted Kremenek16b55a72010-01-26 19:31:51 +0000934 }
935 printf("\n");
936}
937
938void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000939 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek16b55a72010-01-26 19:31:51 +0000940}
941
942/******************************************************************************/
Ted Kremenek3bed5272010-03-03 06:37:58 +0000943/* Linkage testing. */
944/******************************************************************************/
945
946static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
947 CXClientData d) {
948 const char *linkage = 0;
949
950 if (clang_isInvalid(clang_getCursorKind(cursor)))
951 return CXChildVisit_Recurse;
952
953 switch (clang_getCursorLinkage(cursor)) {
954 case CXLinkage_Invalid: break;
Douglas Gregorc2a2b3c2010-03-04 19:36:27 +0000955 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
956 case CXLinkage_Internal: linkage = "Internal"; break;
957 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
958 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek3bed5272010-03-03 06:37:58 +0000959 }
960
961 if (linkage) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000962 PrintCursor(cursor);
Ted Kremenek3bed5272010-03-03 06:37:58 +0000963 printf("linkage=%s\n", linkage);
964 }
965
966 return CXChildVisit_Recurse;
967}
968
969/******************************************************************************/
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000970/* Typekind testing. */
971/******************************************************************************/
972
973static enum CXChildVisitResult PrintTypeKind(CXCursor cursor, CXCursor p,
974 CXClientData d) {
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000975 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
976 CXType T = clang_getCursorType(cursor);
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000977 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000978 PrintCursor(cursor);
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000979 printf(" typekind=%s", clang_getCString(S));
Douglas Gregore72fb6f2011-01-27 16:27:11 +0000980 if (clang_isConstQualifiedType(T))
981 printf(" const");
982 if (clang_isVolatileQualifiedType(T))
983 printf(" volatile");
984 if (clang_isRestrictQualifiedType(T))
985 printf(" restrict");
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000986 clang_disposeString(S);
Benjamin Kramere1403d22010-06-22 09:29:44 +0000987 /* Print the canonical type if it is different. */
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000988 {
989 CXType CT = clang_getCanonicalType(T);
990 if (!clang_equalTypes(T, CT)) {
991 CXString CS = clang_getTypeKindSpelling(CT.kind);
992 printf(" [canonical=%s]", clang_getCString(CS));
993 clang_disposeString(CS);
994 }
995 }
Benjamin Kramere1403d22010-06-22 09:29:44 +0000996 /* Print the return type if it exists. */
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000997 {
Ted Kremenek9a140842010-06-21 20:48:56 +0000998 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000999 if (RT.kind != CXType_Invalid) {
1000 CXString RS = clang_getTypeKindSpelling(RT.kind);
1001 printf(" [result=%s]", clang_getCString(RS));
1002 clang_disposeString(RS);
1003 }
1004 }
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001005 /* Print the argument types if they exist. */
1006 {
1007 int numArgs = clang_Cursor_getNumArguments(cursor);
1008 if (numArgs != -1 && numArgs != 0) {
Argyrios Kyrtzidis47f11652012-04-11 19:54:09 +00001009 int i;
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001010 printf(" [args=");
Argyrios Kyrtzidis47f11652012-04-11 19:54:09 +00001011 for (i = 0; i < numArgs; ++i) {
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +00001012 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
1013 if (T.kind != CXType_Invalid) {
1014 CXString S = clang_getTypeKindSpelling(T.kind);
1015 printf(" %s", clang_getCString(S));
1016 clang_disposeString(S);
1017 }
1018 }
1019 printf("]");
1020 }
1021 }
Ted Kremenek3ce9e7d2010-07-30 00:14:11 +00001022 /* Print if this is a non-POD type. */
1023 printf(" [isPOD=%d]", clang_isPODType(T));
Ted Kremenek04c3cf32010-06-21 20:15:39 +00001024
Ted Kremenek8e0ac172010-05-14 21:29:26 +00001025 printf("\n");
1026 }
1027 return CXChildVisit_Recurse;
1028}
1029
1030
1031/******************************************************************************/
Ted Kremenek7d405622010-01-12 23:34:26 +00001032/* Loading ASTs/source. */
1033/******************************************************************************/
1034
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001035static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek98271562010-01-12 18:53:15 +00001036 const char *filter, const char *prefix,
Ted Kremenekce2ae882010-01-26 17:59:48 +00001037 CXCursorVisitor Visitor,
1038 PostVisitTU PV) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001039
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00001040 if (prefix)
Ted Kremeneke68fff62010-02-17 00:41:32 +00001041 FileCheckPrefix = prefix;
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001042
1043 if (Visitor) {
1044 enum CXCursorKind K = CXCursor_NotImplemented;
1045 enum CXCursorKind *ck = &K;
1046 VisitorData Data;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001047
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001048 /* Perform some simple filtering. */
1049 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor358559d2010-10-02 22:49:11 +00001050 else if (!strcmp(filter, "all-display") ||
1051 !strcmp(filter, "local-display")) {
1052 ck = NULL;
1053 want_display_name = 1;
1054 }
Daniel Dunbarb1ffee62010-02-10 20:42:40 +00001055 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001056 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1057 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1058 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1059 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1060 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1061 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1062 else {
1063 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1064 return 1;
1065 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001066
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001067 Data.TU = TU;
1068 Data.Filter = ck;
1069 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek0d435192009-11-17 18:13:31 +00001070 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001071
Ted Kremenekce2ae882010-01-26 17:59:48 +00001072 if (PV)
1073 PV(TU);
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001074
Douglas Gregora88084b2010-02-18 18:08:43 +00001075 PrintDiagnostics(TU);
Argyrios Kyrtzidis16ac8be2011-11-13 23:39:14 +00001076 if (checkForErrors(TU) != 0) {
1077 clang_disposeTranslationUnit(TU);
1078 return -1;
1079 }
1080
Ted Kremenek0d435192009-11-17 18:13:31 +00001081 clang_disposeTranslationUnit(TU);
1082 return 0;
1083}
1084
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00001085int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekce2ae882010-01-26 17:59:48 +00001086 const char *prefix, CXCursorVisitor Visitor,
1087 PostVisitTU PV) {
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001088 CXIndex Idx;
1089 CXTranslationUnit TU;
Ted Kremenek020a0952010-02-11 07:41:25 +00001090 int result;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001091 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001092 !strcmp(filter, "local") ? 1 : 0,
1093 /* displayDiagnosics=*/1);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001094
Ted Kremenek020a0952010-02-11 07:41:25 +00001095 if (!CreateTranslationUnit(Idx, file, &TU)) {
1096 clang_disposeIndex(Idx);
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001097 return 1;
Ted Kremenek020a0952010-02-11 07:41:25 +00001098 }
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001099
Ted Kremenek020a0952010-02-11 07:41:25 +00001100 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV);
1101 clang_disposeIndex(Idx);
1102 return result;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001103}
1104
Ted Kremenekce2ae882010-01-26 17:59:48 +00001105int perform_test_load_source(int argc, const char **argv,
1106 const char *filter, CXCursorVisitor Visitor,
1107 PostVisitTU PV) {
Daniel Dunbarada487d2009-12-01 02:03:10 +00001108 CXIndex Idx;
1109 CXTranslationUnit TU;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001110 struct CXUnsavedFile *unsaved_files = 0;
1111 int num_unsaved_files = 0;
1112 int result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001113
Daniel Dunbarada487d2009-12-01 02:03:10 +00001114 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor358559d2010-10-02 22:49:11 +00001115 (!strcmp(filter, "local") ||
1116 !strcmp(filter, "local-display"))? 1 : 0,
Douglas Gregor4814fb52011-02-03 23:41:12 +00001117 /* displayDiagnosics=*/0);
Daniel Dunbarada487d2009-12-01 02:03:10 +00001118
Ted Kremenek020a0952010-02-11 07:41:25 +00001119 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1120 clang_disposeIndex(Idx);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001121 return -1;
Ted Kremenek020a0952010-02-11 07:41:25 +00001122 }
Douglas Gregor4db64a42010-01-23 00:14:00 +00001123
Douglas Gregordca8ee82011-05-06 16:33:08 +00001124 TU = clang_parseTranslationUnit(Idx, 0,
1125 argv + num_unsaved_files,
1126 argc - num_unsaved_files,
1127 unsaved_files, num_unsaved_files,
1128 getDefaultParsingOptions());
Daniel Dunbarada487d2009-12-01 02:03:10 +00001129 if (!TU) {
1130 fprintf(stderr, "Unable to load translation unit!\n");
Douglas Gregorabc563f2010-07-19 21:46:24 +00001131 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek020a0952010-02-11 07:41:25 +00001132 clang_disposeIndex(Idx);
Daniel Dunbarada487d2009-12-01 02:03:10 +00001133 return 1;
1134 }
1135
Ted Kremenekce2ae882010-01-26 17:59:48 +00001136 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001137 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek020a0952010-02-11 07:41:25 +00001138 clang_disposeIndex(Idx);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001139 return result;
Daniel Dunbarada487d2009-12-01 02:03:10 +00001140}
1141
Douglas Gregorabc563f2010-07-19 21:46:24 +00001142int perform_test_reparse_source(int argc, const char **argv, int trials,
1143 const char *filter, CXCursorVisitor Visitor,
1144 PostVisitTU PV) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001145 CXIndex Idx;
1146 CXTranslationUnit TU;
1147 struct CXUnsavedFile *unsaved_files = 0;
1148 int num_unsaved_files = 0;
1149 int result;
1150 int trial;
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001151 int remap_after_trial = 0;
1152 char *endptr = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001153
1154 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1155 !strcmp(filter, "local") ? 1 : 0,
Douglas Gregor1aa27302011-01-27 18:02:58 +00001156 /* displayDiagnosics=*/0);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001157
Douglas Gregorabc563f2010-07-19 21:46:24 +00001158 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1159 clang_disposeIndex(Idx);
1160 return -1;
1161 }
1162
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001163 /* Load the initial translation unit -- we do this without honoring remapped
1164 * files, so that we have a way to test results after changing the source. */
Douglas Gregor44c181a2010-07-23 00:33:23 +00001165 TU = clang_parseTranslationUnit(Idx, 0,
1166 argv + num_unsaved_files,
1167 argc - num_unsaved_files,
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001168 0, 0, getDefaultParsingOptions());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001169 if (!TU) {
1170 fprintf(stderr, "Unable to load translation unit!\n");
1171 free_remapped_files(unsaved_files, num_unsaved_files);
1172 clang_disposeIndex(Idx);
1173 return 1;
1174 }
1175
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001176 if (checkForErrors(TU) != 0)
1177 return -1;
1178
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001179 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1180 remap_after_trial =
1181 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1182 }
1183
Douglas Gregorabc563f2010-07-19 21:46:24 +00001184 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001185 if (clang_reparseTranslationUnit(TU,
1186 trial >= remap_after_trial ? num_unsaved_files : 0,
1187 trial >= remap_after_trial ? unsaved_files : 0,
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001188 clang_defaultReparseOptions(TU))) {
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001189 fprintf(stderr, "Unable to reparse translation unit!\n");
Douglas Gregorabc563f2010-07-19 21:46:24 +00001190 clang_disposeTranslationUnit(TU);
1191 free_remapped_files(unsaved_files, num_unsaved_files);
1192 clang_disposeIndex(Idx);
1193 return -1;
1194 }
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001195
1196 if (checkForErrors(TU) != 0)
1197 return -1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001198 }
1199
1200 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001201
Douglas Gregorabc563f2010-07-19 21:46:24 +00001202 free_remapped_files(unsaved_files, num_unsaved_files);
1203 clang_disposeIndex(Idx);
1204 return result;
1205}
1206
Ted Kremenek0d435192009-11-17 18:13:31 +00001207/******************************************************************************/
Ted Kremenek1c6da172009-11-17 19:37:36 +00001208/* Logic for testing clang_getCursor(). */
1209/******************************************************************************/
1210
Douglas Gregordd3e5542011-05-04 00:14:37 +00001211static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek1c6da172009-11-17 19:37:36 +00001212 unsigned start_line, unsigned start_col,
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001213 unsigned end_line, unsigned end_col,
1214 const char *prefix) {
Ted Kremenek9096a202010-01-07 01:17:12 +00001215 printf("// %s: ", FileCheckPrefix);
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001216 if (prefix)
1217 printf("-%s", prefix);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00001218 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1219 printf(" ");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001220 PrintCursor(cursor);
Ted Kremenek1c6da172009-11-17 19:37:36 +00001221 printf("\n");
1222}
1223
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001224static int perform_file_scan(const char *ast_file, const char *source_file,
1225 const char *prefix) {
Ted Kremenek1c6da172009-11-17 19:37:36 +00001226 CXIndex Idx;
1227 CXTranslationUnit TU;
1228 FILE *fp;
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001229 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregorb9790342010-01-22 21:44:22 +00001230 CXFile file;
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001231 unsigned line = 1, col = 1;
Daniel Dunbar8f0bf812010-02-14 08:32:51 +00001232 unsigned start_line = 1, start_col = 1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001233
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001234 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
1235 /* displayDiagnosics=*/1))) {
Ted Kremenek1c6da172009-11-17 19:37:36 +00001236 fprintf(stderr, "Could not create Index\n");
1237 return 1;
1238 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001239
Ted Kremenek1c6da172009-11-17 19:37:36 +00001240 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1241 return 1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001242
Ted Kremenek1c6da172009-11-17 19:37:36 +00001243 if ((fp = fopen(source_file, "r")) == NULL) {
1244 fprintf(stderr, "Could not open '%s'\n", source_file);
1245 return 1;
1246 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001247
Douglas Gregorb9790342010-01-22 21:44:22 +00001248 file = clang_getFile(TU, source_file);
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001249 for (;;) {
1250 CXCursor cursor;
1251 int c = fgetc(fp);
Benjamin Kramera9933b92009-11-17 20:51:40 +00001252
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001253 if (c == '\n') {
1254 ++line;
1255 col = 1;
1256 } else
1257 ++col;
1258
1259 /* Check the cursor at this position, and dump the previous one if we have
1260 * found something new.
1261 */
1262 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1263 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1264 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregordd3e5542011-05-04 00:14:37 +00001265 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbard52864b2010-02-14 10:02:57 +00001266 line, col, prefix);
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001267 start_line = line;
1268 start_col = col;
Benjamin Kramera9933b92009-11-17 20:51:40 +00001269 }
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001270 if (c == EOF)
1271 break;
Benjamin Kramera9933b92009-11-17 20:51:40 +00001272
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001273 prevCursor = cursor;
Ted Kremenek1c6da172009-11-17 19:37:36 +00001274 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001275
Ted Kremenek1c6da172009-11-17 19:37:36 +00001276 fclose(fp);
Douglas Gregor4f5e21e2011-01-31 22:04:05 +00001277 clang_disposeTranslationUnit(TU);
1278 clang_disposeIndex(Idx);
Ted Kremenek1c6da172009-11-17 19:37:36 +00001279 return 0;
1280}
1281
1282/******************************************************************************/
Douglas Gregor32be4a52010-10-11 21:37:58 +00001283/* Logic for testing clang code completion. */
Ted Kremenek0d435192009-11-17 18:13:31 +00001284/******************************************************************************/
1285
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001286/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1287 on failure. If successful, the pointer *filename will contain newly-allocated
1288 memory (that will be owned by the caller) to store the file name. */
Ted Kremeneke68fff62010-02-17 00:41:32 +00001289int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001290 unsigned *column, unsigned *second_line,
1291 unsigned *second_column) {
Douglas Gregor88d23952009-11-09 18:19:57 +00001292 /* Find the second colon. */
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001293 const char *last_colon = strrchr(input, ':');
1294 unsigned values[4], i;
1295 unsigned num_values = (second_line && second_column)? 4 : 2;
1296
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001297 char *endptr = 0;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001298 if (!last_colon || last_colon == input) {
1299 if (num_values == 4)
1300 fprintf(stderr, "could not parse filename:line:column:line:column in "
1301 "'%s'\n", input);
1302 else
1303 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001304 return 1;
1305 }
1306
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001307 for (i = 0; i != num_values; ++i) {
1308 const char *prev_colon;
1309
1310 /* Parse the next line or column. */
1311 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1312 if (*endptr != 0 && *endptr != ':') {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001313 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001314 (i % 2 ? "column" : "line"), input);
1315 return 1;
1316 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001317
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001318 if (i + 1 == num_values)
1319 break;
1320
1321 /* Find the previous colon. */
1322 prev_colon = last_colon - 1;
1323 while (prev_colon != input && *prev_colon != ':')
1324 --prev_colon;
1325 if (prev_colon == input) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001326 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001327 (i % 2 == 0? "column" : "line"), input);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001328 return 1;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001329 }
1330
1331 last_colon = prev_colon;
Douglas Gregor88d23952009-11-09 18:19:57 +00001332 }
1333
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001334 *line = values[0];
1335 *column = values[1];
Ted Kremeneke68fff62010-02-17 00:41:32 +00001336
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001337 if (second_line && second_column) {
1338 *second_line = values[2];
1339 *second_column = values[3];
1340 }
1341
Douglas Gregor88d23952009-11-09 18:19:57 +00001342 /* Copy the file name. */
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001343 *filename = (char*)malloc(last_colon - input + 1);
1344 memcpy(*filename, input, last_colon - input);
1345 (*filename)[last_colon - input] = 0;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001346 return 0;
1347}
1348
1349const char *
1350clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1351 switch (Kind) {
1352 case CXCompletionChunk_Optional: return "Optional";
1353 case CXCompletionChunk_TypedText: return "TypedText";
1354 case CXCompletionChunk_Text: return "Text";
1355 case CXCompletionChunk_Placeholder: return "Placeholder";
1356 case CXCompletionChunk_Informative: return "Informative";
1357 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1358 case CXCompletionChunk_LeftParen: return "LeftParen";
1359 case CXCompletionChunk_RightParen: return "RightParen";
1360 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1361 case CXCompletionChunk_RightBracket: return "RightBracket";
1362 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1363 case CXCompletionChunk_RightBrace: return "RightBrace";
1364 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1365 case CXCompletionChunk_RightAngle: return "RightAngle";
1366 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001367 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor01dfea02010-01-10 23:08:15 +00001368 case CXCompletionChunk_Colon: return "Colon";
1369 case CXCompletionChunk_SemiColon: return "SemiColon";
1370 case CXCompletionChunk_Equal: return "Equal";
1371 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1372 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001373 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001374
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001375 return "Unknown";
1376}
1377
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001378static int checkForErrors(CXTranslationUnit TU) {
1379 unsigned Num, i;
1380 CXDiagnostic Diag;
1381 CXString DiagStr;
1382
1383 if (!getenv("CINDEXTEST_FAILONERROR"))
1384 return 0;
1385
1386 Num = clang_getNumDiagnostics(TU);
1387 for (i = 0; i != Num; ++i) {
1388 Diag = clang_getDiagnostic(TU, i);
1389 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1390 DiagStr = clang_formatDiagnostic(Diag,
1391 clang_defaultDiagnosticDisplayOptions());
1392 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1393 clang_disposeString(DiagStr);
1394 clang_disposeDiagnostic(Diag);
1395 return -1;
1396 }
1397 clang_disposeDiagnostic(Diag);
1398 }
1399
1400 return 0;
1401}
1402
Douglas Gregor3ac73852009-11-09 16:04:45 +00001403void print_completion_string(CXCompletionString completion_string, FILE *file) {
Daniel Dunbarf8297f12009-11-07 18:34:24 +00001404 int I, N;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001405
Douglas Gregor3ac73852009-11-09 16:04:45 +00001406 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001407 for (I = 0; I != N; ++I) {
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001408 CXString text;
1409 const char *cstr;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001410 enum CXCompletionChunkKind Kind
Douglas Gregor3ac73852009-11-09 16:04:45 +00001411 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001412
Douglas Gregor3ac73852009-11-09 16:04:45 +00001413 if (Kind == CXCompletionChunk_Optional) {
1414 fprintf(file, "{Optional ");
1415 print_completion_string(
Ted Kremeneke68fff62010-02-17 00:41:32 +00001416 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor3ac73852009-11-09 16:04:45 +00001417 file);
1418 fprintf(file, "}");
1419 continue;
Douglas Gregor5a9c0bc2010-10-08 20:39:29 +00001420 }
1421
1422 if (Kind == CXCompletionChunk_VerticalSpace) {
1423 fprintf(file, "{VerticalSpace }");
1424 continue;
Douglas Gregor3ac73852009-11-09 16:04:45 +00001425 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001426
Douglas Gregord5a20892009-11-09 17:05:28 +00001427 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001428 cstr = clang_getCString(text);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001429 fprintf(file, "{%s %s}",
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001430 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001431 cstr ? cstr : "");
1432 clang_disposeString(text);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001433 }
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001434
Douglas Gregor3ac73852009-11-09 16:04:45 +00001435}
1436
1437void print_completion_result(CXCompletionResult *completion_result,
1438 CXClientData client_data) {
1439 FILE *file = (FILE *)client_data;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001440 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen6164ea12011-10-14 15:31:08 +00001441 unsigned annotationCount;
Douglas Gregorba103062012-03-27 23:34:16 +00001442 enum CXCursorKind ParentKind;
1443 CXString ParentName;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001444 CXString BriefComment;
1445 const char *BriefCommentCString;
Douglas Gregorba103062012-03-27 23:34:16 +00001446
Ted Kremeneke68fff62010-02-17 00:41:32 +00001447 fprintf(file, "%s:", clang_getCString(ks));
1448 clang_disposeString(ks);
1449
Douglas Gregor3ac73852009-11-09 16:04:45 +00001450 print_completion_string(completion_result->CompletionString, file);
Douglas Gregor58ddb602010-08-23 23:00:57 +00001451 fprintf(file, " (%u)",
Douglas Gregor12e13132010-05-26 22:00:08 +00001452 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregor58ddb602010-08-23 23:00:57 +00001453 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1454 case CXAvailability_Available:
1455 break;
1456
1457 case CXAvailability_Deprecated:
1458 fprintf(file, " (deprecated)");
1459 break;
1460
1461 case CXAvailability_NotAvailable:
1462 fprintf(file, " (unavailable)");
1463 break;
Erik Verbruggend1205962011-10-06 07:27:49 +00001464
1465 case CXAvailability_NotAccessible:
1466 fprintf(file, " (inaccessible)");
1467 break;
Douglas Gregor58ddb602010-08-23 23:00:57 +00001468 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00001469
1470 annotationCount = clang_getCompletionNumAnnotations(
1471 completion_result->CompletionString);
1472 if (annotationCount) {
1473 unsigned i;
1474 fprintf(file, " (");
1475 for (i = 0; i < annotationCount; ++i) {
1476 if (i != 0)
1477 fprintf(file, ", ");
1478 fprintf(file, "\"%s\"",
1479 clang_getCString(clang_getCompletionAnnotation(
1480 completion_result->CompletionString, i)));
1481 }
1482 fprintf(file, ")");
1483 }
1484
Douglas Gregorba103062012-03-27 23:34:16 +00001485 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1486 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1487 &ParentKind);
1488 if (ParentKind != CXCursor_NotImplemented) {
1489 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
1490 fprintf(file, " (parent: %s '%s')",
1491 clang_getCString(KindSpelling),
1492 clang_getCString(ParentName));
1493 clang_disposeString(KindSpelling);
1494 }
1495 clang_disposeString(ParentName);
1496 }
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001497
1498 BriefComment = clang_getCompletionBriefComment(
1499 completion_result->CompletionString);
1500 BriefCommentCString = clang_getCString(BriefComment);
1501 if (BriefCommentCString && *BriefCommentCString != '\0') {
1502 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1503 }
1504 clang_disposeString(BriefComment);
Douglas Gregorba103062012-03-27 23:34:16 +00001505
Douglas Gregor58ddb602010-08-23 23:00:57 +00001506 fprintf(file, "\n");
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001507}
1508
Douglas Gregor3da626b2011-07-07 16:03:39 +00001509void print_completion_contexts(unsigned long long contexts, FILE *file) {
1510 fprintf(file, "Completion contexts:\n");
1511 if (contexts == CXCompletionContext_Unknown) {
1512 fprintf(file, "Unknown\n");
1513 }
1514 if (contexts & CXCompletionContext_AnyType) {
1515 fprintf(file, "Any type\n");
1516 }
1517 if (contexts & CXCompletionContext_AnyValue) {
1518 fprintf(file, "Any value\n");
1519 }
1520 if (contexts & CXCompletionContext_ObjCObjectValue) {
1521 fprintf(file, "Objective-C object value\n");
1522 }
1523 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1524 fprintf(file, "Objective-C selector value\n");
1525 }
1526 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1527 fprintf(file, "C++ class type value\n");
1528 }
1529 if (contexts & CXCompletionContext_DotMemberAccess) {
1530 fprintf(file, "Dot member access\n");
1531 }
1532 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1533 fprintf(file, "Arrow member access\n");
1534 }
1535 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1536 fprintf(file, "Objective-C property access\n");
1537 }
1538 if (contexts & CXCompletionContext_EnumTag) {
1539 fprintf(file, "Enum tag\n");
1540 }
1541 if (contexts & CXCompletionContext_UnionTag) {
1542 fprintf(file, "Union tag\n");
1543 }
1544 if (contexts & CXCompletionContext_StructTag) {
1545 fprintf(file, "Struct tag\n");
1546 }
1547 if (contexts & CXCompletionContext_ClassTag) {
1548 fprintf(file, "Class name\n");
1549 }
1550 if (contexts & CXCompletionContext_Namespace) {
1551 fprintf(file, "Namespace or namespace alias\n");
1552 }
1553 if (contexts & CXCompletionContext_NestedNameSpecifier) {
1554 fprintf(file, "Nested name specifier\n");
1555 }
1556 if (contexts & CXCompletionContext_ObjCInterface) {
1557 fprintf(file, "Objective-C interface\n");
1558 }
1559 if (contexts & CXCompletionContext_ObjCProtocol) {
1560 fprintf(file, "Objective-C protocol\n");
1561 }
1562 if (contexts & CXCompletionContext_ObjCCategory) {
1563 fprintf(file, "Objective-C category\n");
1564 }
1565 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1566 fprintf(file, "Objective-C instance method\n");
1567 }
1568 if (contexts & CXCompletionContext_ObjCClassMessage) {
1569 fprintf(file, "Objective-C class method\n");
1570 }
1571 if (contexts & CXCompletionContext_ObjCSelectorName) {
1572 fprintf(file, "Objective-C selector name\n");
1573 }
1574 if (contexts & CXCompletionContext_MacroName) {
1575 fprintf(file, "Macro name\n");
1576 }
1577 if (contexts & CXCompletionContext_NaturalLanguage) {
1578 fprintf(file, "Natural language\n");
1579 }
1580}
1581
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001582int my_stricmp(const char *s1, const char *s2) {
1583 while (*s1 && *s2) {
NAKAMURA Takumi6d555212011-03-09 03:02:28 +00001584 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001585 if (c1 < c2)
1586 return -1;
1587 else if (c1 > c2)
1588 return 1;
1589
1590 ++s1;
1591 ++s2;
1592 }
1593
1594 if (*s1)
1595 return 1;
1596 else if (*s2)
1597 return -1;
1598 return 0;
1599}
1600
Douglas Gregor1982c182010-07-12 18:38:41 +00001601int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001602 const char *input = argv[1];
1603 char *filename = 0;
1604 unsigned line;
1605 unsigned column;
Daniel Dunbarf8297f12009-11-07 18:34:24 +00001606 CXIndex CIdx;
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001607 int errorCode;
Douglas Gregor735df882009-12-02 09:21:34 +00001608 struct CXUnsavedFile *unsaved_files = 0;
1609 int num_unsaved_files = 0;
Douglas Gregorec6762c2009-12-18 16:20:58 +00001610 CXCodeCompleteResults *results = 0;
Dawn Perchik25d9b002010-09-30 22:26:05 +00001611 CXTranslationUnit TU = 0;
Douglas Gregor32be4a52010-10-11 21:37:58 +00001612 unsigned I, Repeats = 1;
1613 unsigned completionOptions = clang_defaultCodeCompleteOptions();
1614
1615 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
1616 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001617 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
1618 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregordf95a132010-08-09 20:45:32 +00001619
Douglas Gregor1982c182010-07-12 18:38:41 +00001620 if (timing_only)
1621 input += strlen("-code-completion-timing=");
1622 else
1623 input += strlen("-code-completion-at=");
1624
Ted Kremeneke68fff62010-02-17 00:41:32 +00001625 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001626 0, 0)))
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001627 return errorCode;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001628
Douglas Gregor735df882009-12-02 09:21:34 +00001629 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
1630 return -1;
1631
Douglas Gregor32be4a52010-10-11 21:37:58 +00001632 CIdx = clang_createIndex(0, 0);
1633
1634 if (getenv("CINDEXTEST_EDITING"))
1635 Repeats = 5;
1636
1637 TU = clang_parseTranslationUnit(CIdx, 0,
1638 argv + num_unsaved_files + 2,
1639 argc - num_unsaved_files - 2,
1640 0, 0, getDefaultParsingOptions());
1641 if (!TU) {
1642 fprintf(stderr, "Unable to load translation unit!\n");
1643 return 1;
1644 }
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001645
1646 if (clang_reparseTranslationUnit(TU, 0, 0, clang_defaultReparseOptions(TU))) {
1647 fprintf(stderr, "Unable to reparse translation init!\n");
1648 return 1;
1649 }
Douglas Gregor32be4a52010-10-11 21:37:58 +00001650
1651 for (I = 0; I != Repeats; ++I) {
1652 results = clang_codeCompleteAt(TU, filename, line, column,
1653 unsaved_files, num_unsaved_files,
1654 completionOptions);
1655 if (!results) {
1656 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar2de41c92010-08-19 23:44:06 +00001657 return 1;
1658 }
Douglas Gregor32be4a52010-10-11 21:37:58 +00001659 if (I != Repeats-1)
1660 clang_disposeCodeCompleteResults(results);
1661 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001662
Douglas Gregorec6762c2009-12-18 16:20:58 +00001663 if (results) {
Douglas Gregore081a612011-07-21 01:05:26 +00001664 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor3da626b2011-07-07 16:03:39 +00001665 unsigned long long contexts;
Douglas Gregore081a612011-07-21 01:05:26 +00001666 enum CXCursorKind containerKind;
Douglas Gregor0a47d692011-07-26 15:24:30 +00001667 CXString objCSelector;
1668 const char *selectorString;
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001669 if (!timing_only) {
1670 /* Sort the code-completion results based on the typed text. */
1671 clang_sortCodeCompletionResults(results->Results, results->NumResults);
1672
Douglas Gregor1982c182010-07-12 18:38:41 +00001673 for (i = 0; i != n; ++i)
1674 print_completion_result(results->Results + i, stdout);
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001675 }
Douglas Gregora88084b2010-02-18 18:08:43 +00001676 n = clang_codeCompleteGetNumDiagnostics(results);
1677 for (i = 0; i != n; ++i) {
1678 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
1679 PrintDiagnostic(diag);
1680 clang_disposeDiagnostic(diag);
1681 }
Douglas Gregor3da626b2011-07-07 16:03:39 +00001682
1683 contexts = clang_codeCompleteGetContexts(results);
1684 print_completion_contexts(contexts, stdout);
1685
Douglas Gregor0a47d692011-07-26 15:24:30 +00001686 containerKind = clang_codeCompleteGetContainerKind(results,
1687 &containerIsIncomplete);
Douglas Gregore081a612011-07-21 01:05:26 +00001688
1689 if (containerKind != CXCursor_InvalidCode) {
1690 /* We have found a container */
1691 CXString containerUSR, containerKindSpelling;
1692 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
1693 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
1694 clang_disposeString(containerKindSpelling);
1695
1696 if (containerIsIncomplete) {
1697 printf("Container is incomplete\n");
1698 }
1699 else {
1700 printf("Container is complete\n");
1701 }
1702
1703 containerUSR = clang_codeCompleteGetContainerUSR(results);
1704 printf("Container USR: %s\n", clang_getCString(containerUSR));
1705 clang_disposeString(containerUSR);
1706 }
1707
Douglas Gregor0a47d692011-07-26 15:24:30 +00001708 objCSelector = clang_codeCompleteGetObjCSelector(results);
1709 selectorString = clang_getCString(objCSelector);
1710 if (selectorString && strlen(selectorString) > 0) {
1711 printf("Objective-C selector: %s\n", selectorString);
1712 }
1713 clang_disposeString(objCSelector);
1714
Douglas Gregorec6762c2009-12-18 16:20:58 +00001715 clang_disposeCodeCompleteResults(results);
1716 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001717 clang_disposeTranslationUnit(TU);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001718 clang_disposeIndex(CIdx);
1719 free(filename);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001720
Douglas Gregor735df882009-12-02 09:21:34 +00001721 free_remapped_files(unsaved_files, num_unsaved_files);
1722
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001723 return 0;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001724}
1725
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001726typedef struct {
1727 char *filename;
1728 unsigned line;
1729 unsigned column;
1730} CursorSourceLocation;
1731
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001732static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001733 CXIndex CIdx;
1734 int errorCode;
1735 struct CXUnsavedFile *unsaved_files = 0;
1736 int num_unsaved_files = 0;
1737 CXTranslationUnit TU;
1738 CXCursor Cursor;
1739 CursorSourceLocation *Locations = 0;
1740 unsigned NumLocations = 0, Loc;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001741 unsigned Repeats = 1;
Douglas Gregorbdc4b362010-11-30 06:04:54 +00001742 unsigned I;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001743
Ted Kremeneke68fff62010-02-17 00:41:32 +00001744 /* Count the number of locations. */
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001745 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
1746 ++NumLocations;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001747
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001748 /* Parse the locations. */
1749 assert(NumLocations > 0 && "Unable to count locations?");
1750 Locations = (CursorSourceLocation *)malloc(
1751 NumLocations * sizeof(CursorSourceLocation));
1752 for (Loc = 0; Loc < NumLocations; ++Loc) {
1753 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001754 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
1755 &Locations[Loc].line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001756 &Locations[Loc].column, 0, 0)))
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001757 return errorCode;
1758 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001759
1760 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001761 &num_unsaved_files))
1762 return -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001763
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001764 if (getenv("CINDEXTEST_EDITING"))
1765 Repeats = 5;
1766
1767 /* Parse the translation unit. When we're testing clang_getCursor() after
1768 reparsing, don't remap unsaved files until the second parse. */
1769 CIdx = clang_createIndex(1, 1);
1770 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
1771 argv + num_unsaved_files + 1 + NumLocations,
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001772 argc - num_unsaved_files - 2 - NumLocations,
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001773 unsaved_files,
1774 Repeats > 1? 0 : num_unsaved_files,
1775 getDefaultParsingOptions());
1776
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001777 if (!TU) {
1778 fprintf(stderr, "unable to parse input\n");
1779 return -1;
1780 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001781
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001782 if (checkForErrors(TU) != 0)
1783 return -1;
1784
Douglas Gregorbdc4b362010-11-30 06:04:54 +00001785 for (I = 0; I != Repeats; ++I) {
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001786 if (Repeats > 1 &&
1787 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1788 clang_defaultReparseOptions(TU))) {
1789 clang_disposeTranslationUnit(TU);
1790 return 1;
1791 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001792
1793 if (checkForErrors(TU) != 0)
1794 return -1;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001795
1796 for (Loc = 0; Loc < NumLocations; ++Loc) {
1797 CXFile file = clang_getFile(TU, Locations[Loc].filename);
1798 if (!file)
1799 continue;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001800
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001801 Cursor = clang_getCursor(TU,
1802 clang_getLocation(TU, file, Locations[Loc].line,
1803 Locations[Loc].column));
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001804
1805 if (checkForErrors(TU) != 0)
1806 return -1;
1807
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001808 if (I + 1 == Repeats) {
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001809 CXCompletionString completionString = clang_getCursorCompletionString(
1810 Cursor);
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00001811 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
1812 CXString Spelling;
1813 const char *cspell;
1814 unsigned line, column;
1815 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
1816 printf("%d:%d ", line, column);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001817 PrintCursor(Cursor);
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00001818 PrintCursorExtent(Cursor);
1819 Spelling = clang_getCursorSpelling(Cursor);
1820 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00001821 if (cspell && strlen(cspell) != 0) {
1822 unsigned pieceIndex;
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00001823 printf(" Spelling=%s (", cspell);
1824 for (pieceIndex = 0; ; ++pieceIndex) {
Benjamin Kramer6c235bc2012-03-31 10:23:28 +00001825 CXSourceRange range =
1826 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00001827 if (clang_Range_isNull(range))
1828 break;
1829 PrintRange(range, 0);
1830 }
1831 printf(")");
1832 }
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00001833 clang_disposeString(Spelling);
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00001834 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
1835 printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisf39a7ae2012-07-02 23:54:36 +00001836 if (clang_Cursor_isDynamicCall(Cursor))
1837 printf(" Dynamic-call");
1838
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001839 if (completionString != NULL) {
1840 printf("\nCompletion string: ");
1841 print_completion_string(completionString, stdout);
1842 }
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001843 printf("\n");
1844 free(Locations[Loc].filename);
1845 }
1846 }
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001847 }
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001848
Douglas Gregora88084b2010-02-18 18:08:43 +00001849 PrintDiagnostics(TU);
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001850 clang_disposeTranslationUnit(TU);
1851 clang_disposeIndex(CIdx);
1852 free(Locations);
1853 free_remapped_files(unsaved_files, num_unsaved_files);
1854 return 0;
1855}
1856
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001857static enum CXVisitorResult findFileRefsVisit(void *context,
1858 CXCursor cursor, CXSourceRange range) {
1859 if (clang_Range_isNull(range))
1860 return CXVisit_Continue;
1861
1862 PrintCursor(cursor);
1863 PrintRange(range, "");
1864 printf("\n");
1865 return CXVisit_Continue;
1866}
1867
1868static int find_file_refs_at(int argc, const char **argv) {
1869 CXIndex CIdx;
1870 int errorCode;
1871 struct CXUnsavedFile *unsaved_files = 0;
1872 int num_unsaved_files = 0;
1873 CXTranslationUnit TU;
1874 CXCursor Cursor;
1875 CursorSourceLocation *Locations = 0;
1876 unsigned NumLocations = 0, Loc;
1877 unsigned Repeats = 1;
1878 unsigned I;
1879
1880 /* Count the number of locations. */
1881 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
1882 ++NumLocations;
1883
1884 /* Parse the locations. */
1885 assert(NumLocations > 0 && "Unable to count locations?");
1886 Locations = (CursorSourceLocation *)malloc(
1887 NumLocations * sizeof(CursorSourceLocation));
1888 for (Loc = 0; Loc < NumLocations; ++Loc) {
1889 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
1890 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
1891 &Locations[Loc].line,
1892 &Locations[Loc].column, 0, 0)))
1893 return errorCode;
1894 }
1895
1896 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
1897 &num_unsaved_files))
1898 return -1;
1899
1900 if (getenv("CINDEXTEST_EDITING"))
1901 Repeats = 5;
1902
1903 /* Parse the translation unit. When we're testing clang_getCursor() after
1904 reparsing, don't remap unsaved files until the second parse. */
1905 CIdx = clang_createIndex(1, 1);
1906 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
1907 argv + num_unsaved_files + 1 + NumLocations,
1908 argc - num_unsaved_files - 2 - NumLocations,
1909 unsaved_files,
1910 Repeats > 1? 0 : num_unsaved_files,
1911 getDefaultParsingOptions());
1912
1913 if (!TU) {
1914 fprintf(stderr, "unable to parse input\n");
1915 return -1;
1916 }
1917
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001918 if (checkForErrors(TU) != 0)
1919 return -1;
1920
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001921 for (I = 0; I != Repeats; ++I) {
1922 if (Repeats > 1 &&
1923 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1924 clang_defaultReparseOptions(TU))) {
1925 clang_disposeTranslationUnit(TU);
1926 return 1;
1927 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001928
1929 if (checkForErrors(TU) != 0)
1930 return -1;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001931
1932 for (Loc = 0; Loc < NumLocations; ++Loc) {
1933 CXFile file = clang_getFile(TU, Locations[Loc].filename);
1934 if (!file)
1935 continue;
1936
1937 Cursor = clang_getCursor(TU,
1938 clang_getLocation(TU, file, Locations[Loc].line,
1939 Locations[Loc].column));
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001940
1941 if (checkForErrors(TU) != 0)
1942 return -1;
1943
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001944 if (I + 1 == Repeats) {
Erik Verbruggen26fc0f92011-10-06 11:38:08 +00001945 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001946 PrintCursor(Cursor);
1947 printf("\n");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001948 clang_findReferencesInFile(Cursor, file, visitor);
1949 free(Locations[Loc].filename);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001950
1951 if (checkForErrors(TU) != 0)
1952 return -1;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001953 }
1954 }
1955 }
1956
1957 PrintDiagnostics(TU);
1958 clang_disposeTranslationUnit(TU);
1959 clang_disposeIndex(CIdx);
1960 free(Locations);
1961 free_remapped_files(unsaved_files, num_unsaved_files);
1962 return 0;
1963}
1964
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001965typedef struct {
1966 const char *check_prefix;
1967 int first_check_printed;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001968 int fail_for_error;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001969 int abort;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001970 const char *main_filename;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001971} IndexData;
1972
1973static void printCheck(IndexData *data) {
1974 if (data->check_prefix) {
1975 if (data->first_check_printed) {
1976 printf("// %s-NEXT: ", data->check_prefix);
1977 } else {
1978 printf("// %s : ", data->check_prefix);
1979 data->first_check_printed = 1;
1980 }
1981 }
1982}
1983
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00001984static void printCXIndexFile(CXIdxClientFile file) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001985 CXString filename = clang_getFileName((CXFile)file);
1986 printf("%s", clang_getCString(filename));
1987 clang_disposeString(filename);
1988}
1989
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001990static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
1991 IndexData *index_data;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001992 CXString filename;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001993 const char *cname;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00001994 CXIdxClientFile file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001995 unsigned line, column;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001996 int isMainFile;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001997
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001998 index_data = (IndexData *)client_data;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001999 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2000 if (line == 0) {
2001 printf("<null loc>");
2002 return;
2003 }
Argyrios Kyrtzidisc2be04e2011-12-13 18:47:35 +00002004 if (!file) {
2005 printf("<no idxfile>");
2006 return;
2007 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002008 filename = clang_getFileName((CXFile)file);
2009 cname = clang_getCString(filename);
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002010 if (strcmp(cname, index_data->main_filename) == 0)
2011 isMainFile = 1;
2012 else
2013 isMainFile = 0;
2014 clang_disposeString(filename);
2015
2016 if (!isMainFile) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002017 printCXIndexFile(file);
2018 printf(":");
2019 }
2020 printf("%d:%d", line, column);
2021}
2022
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002023static unsigned digitCount(unsigned val) {
2024 unsigned c = 1;
2025 while (1) {
2026 if (val < 10)
2027 return c;
2028 ++c;
2029 val /= 10;
2030 }
2031}
2032
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002033static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2034 CXIdxLoc loc) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002035 const char *name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002036 char *newStr;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002037 CXIdxClientFile file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002038 unsigned line, column;
2039
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002040 name = info->name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002041 if (!name)
2042 name = "<anon-tag>";
2043
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002044 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Argyrios Kyrtzidisf89bc052011-10-20 17:21:46 +00002045 /* FIXME: free these.*/
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002046 newStr = (char *)malloc(strlen(name) +
2047 digitCount(line) + digitCount(column) + 3);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002048 sprintf(newStr, "%s:%d:%d", name, line, column);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002049 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002050}
2051
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002052static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2053 CXIdxClientContainer container;
2054 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidis3e340a62011-11-16 02:35:05 +00002055 if (!container)
2056 printf("[<<NULL>>]");
2057 else
2058 printf("[%s]", (const char *)container);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002059}
2060
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002061static const char *getEntityKindString(CXIdxEntityKind kind) {
2062 switch (kind) {
2063 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2064 case CXIdxEntity_Typedef: return "typedef";
2065 case CXIdxEntity_Function: return "function";
2066 case CXIdxEntity_Variable: return "variable";
2067 case CXIdxEntity_Field: return "field";
2068 case CXIdxEntity_EnumConstant: return "enumerator";
2069 case CXIdxEntity_ObjCClass: return "objc-class";
2070 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2071 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002072 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2073 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002074 case CXIdxEntity_ObjCProperty: return "objc-property";
2075 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2076 case CXIdxEntity_Enum: return "enum";
2077 case CXIdxEntity_Struct: return "struct";
2078 case CXIdxEntity_Union: return "union";
2079 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002080 case CXIdxEntity_CXXNamespace: return "namespace";
2081 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2082 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2083 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2084 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2085 case CXIdxEntity_CXXConstructor: return "constructor";
2086 case CXIdxEntity_CXXDestructor: return "destructor";
2087 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2088 case CXIdxEntity_CXXTypeAlias: return "type-alias";
2089 }
2090 assert(0 && "Garbage entity kind");
2091 return 0;
2092}
2093
2094static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2095 switch (kind) {
2096 case CXIdxEntity_NonTemplate: return "";
2097 case CXIdxEntity_Template: return "-template";
2098 case CXIdxEntity_TemplatePartialSpecialization:
2099 return "-template-partial-spec";
2100 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002101 }
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002102 assert(0 && "Garbage entity kind");
2103 return 0;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002104}
2105
Argyrios Kyrtzidis838d3c22011-12-07 20:44:12 +00002106static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2107 switch (kind) {
2108 case CXIdxEntityLang_None: return "<none>";
2109 case CXIdxEntityLang_C: return "C";
2110 case CXIdxEntityLang_ObjC: return "ObjC";
2111 case CXIdxEntityLang_CXX: return "C++";
2112 }
2113 assert(0 && "Garbage language kind");
2114 return 0;
2115}
2116
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002117static void printEntityInfo(const char *cb,
2118 CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002119 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002120 const char *name;
2121 IndexData *index_data;
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002122 unsigned i;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002123 index_data = (IndexData *)client_data;
2124 printCheck(index_data);
2125
Argyrios Kyrtzidisc6b4a502011-11-16 02:34:59 +00002126 if (!info) {
2127 printf("%s: <<NULL>>", cb);
2128 return;
2129 }
2130
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002131 name = info->name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002132 if (!name)
2133 name = "<anon-tag>";
2134
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002135 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2136 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002137 printf(" | name: %s", name);
2138 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisc2be04e2011-12-13 18:47:35 +00002139 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002140
2141 for (i = 0; i != info->numAttributes; ++i) {
2142 const CXIdxAttrInfo *Attr = info->attributes[i];
2143 printf(" <attribute>: ");
2144 PrintCursor(Attr->cursor);
2145 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002146}
2147
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002148static void printBaseClassInfo(CXClientData client_data,
2149 const CXIdxBaseClassInfo *info) {
2150 printEntityInfo(" <base>", client_data, info->base);
2151 printf(" | cursor: ");
2152 PrintCursor(info->cursor);
2153 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002154 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002155}
2156
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002157static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2158 CXClientData client_data) {
2159 unsigned i;
2160 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2161 printEntityInfo(" <protocol>", client_data,
2162 ProtoInfo->protocols[i]->protocol);
2163 printf(" | cursor: ");
2164 PrintCursor(ProtoInfo->protocols[i]->cursor);
2165 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002166 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002167 printf("\n");
2168 }
2169}
2170
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002171static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002172 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002173 CXString str;
2174 const char *cstr;
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002175 unsigned numDiags, i;
2176 CXDiagnostic diag;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002177 IndexData *index_data;
2178 index_data = (IndexData *)client_data;
2179 printCheck(index_data);
2180
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002181 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2182 for (i = 0; i != numDiags; ++i) {
2183 diag = clang_getDiagnosticInSet(diagSet, i);
2184 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2185 cstr = clang_getCString(str);
2186 printf("[diagnostic]: %s\n", cstr);
2187 clang_disposeString(str);
2188
2189 if (getenv("CINDEXTEST_FAILONERROR") &&
2190 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2191 index_data->fail_for_error = 1;
2192 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002193 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002194}
2195
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002196static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2197 CXFile file, void *reserved) {
2198 IndexData *index_data;
Argyrios Kyrtzidis62d7fea2012-03-15 18:48:52 +00002199 CXString filename;
2200
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002201 index_data = (IndexData *)client_data;
2202 printCheck(index_data);
2203
Argyrios Kyrtzidis62d7fea2012-03-15 18:48:52 +00002204 filename = clang_getFileName(file);
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002205 index_data->main_filename = clang_getCString(filename);
2206 clang_disposeString(filename);
2207
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002208 printf("[enteredMainFile]: ");
2209 printCXIndexFile((CXIdxClientFile)file);
2210 printf("\n");
2211
2212 return (CXIdxClientFile)file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002213}
2214
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002215static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002216 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002217 IndexData *index_data;
2218 index_data = (IndexData *)client_data;
2219 printCheck(index_data);
2220
Argyrios Kyrtzidis66042b32011-11-05 04:03:35 +00002221 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002222 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002223 printf(" | name: \"%s\"", info->filename);
2224 printf(" | hash loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002225 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002226 printf(" | isImport: %d | isAngled: %d\n", info->isImport, info->isAngled);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002227
2228 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002229}
2230
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002231static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002232 void *reserved) {
2233 IndexData *index_data;
2234 index_data = (IndexData *)client_data;
2235 printCheck(index_data);
2236
Argyrios Kyrtzidis66042b32011-11-05 04:03:35 +00002237 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002238 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002239}
2240
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002241static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002242 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002243 IndexData *index_data;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002244 const CXIdxObjCCategoryDeclInfo *CatInfo;
2245 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002246 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis792db262012-02-28 17:50:33 +00002247 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002248 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002249 unsigned i;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002250 index_data = (IndexData *)client_data;
2251
2252 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2253 printf(" | cursor: ");
2254 PrintCursor(info->cursor);
2255 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002256 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb1febb62011-12-07 20:44:19 +00002257 printf(" | semantic-container: ");
2258 printCXIndexContainer(info->semanticContainer);
2259 printf(" | lexical-container: ");
2260 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002261 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002262 printf(" | isDef: %d", info->isDefinition);
2263 printf(" | isContainer: %d", info->isContainer);
2264 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002265
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002266 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi87adb0b2011-11-18 00:51:03 +00002267 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002268 printf(" <attribute>: ");
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002269 PrintCursor(Attr->cursor);
2270 printf("\n");
2271 }
2272
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002273 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2274 const char *kindName = 0;
2275 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2276 switch (K) {
2277 case CXIdxObjCContainer_ForwardRef:
2278 kindName = "forward-ref"; break;
2279 case CXIdxObjCContainer_Interface:
2280 kindName = "interface"; break;
2281 case CXIdxObjCContainer_Implementation:
2282 kindName = "implementation"; break;
2283 }
2284 printCheck(index_data);
2285 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2286 }
2287
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002288 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002289 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
2290 CatInfo->objcClass);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002291 printf(" | cursor: ");
2292 PrintCursor(CatInfo->classCursor);
2293 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002294 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002295 printf("\n");
2296 }
2297
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002298 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2299 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002300 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002301 printf("\n");
2302 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002303 }
2304
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002305 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2306 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002307 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002308
Argyrios Kyrtzidis792db262012-02-28 17:50:33 +00002309 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2310 if (PropInfo->getter) {
2311 printEntityInfo(" <getter>", client_data, PropInfo->getter);
2312 printf("\n");
2313 }
2314 if (PropInfo->setter) {
2315 printEntityInfo(" <setter>", client_data, PropInfo->setter);
2316 printf("\n");
2317 }
2318 }
2319
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002320 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2321 for (i = 0; i != CXXClassInfo->numBases; ++i) {
2322 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2323 printf("\n");
2324 }
2325 }
2326
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002327 if (info->declAsContainer)
2328 clang_index_setClientContainer(info->declAsContainer,
2329 makeClientContainer(info->entityInfo, info->loc));
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002330}
2331
2332static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002333 const CXIdxEntityRefInfo *info) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002334 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002335 printf(" | cursor: ");
2336 PrintCursor(info->cursor);
2337 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002338 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002339 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002340 printf(" | container: ");
2341 printCXIndexContainer(info->container);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002342 printf(" | refkind: ");
Argyrios Kyrtzidisaca19be2011-10-18 15:50:50 +00002343 switch (info->kind) {
2344 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002345 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidisaca19be2011-10-18 15:50:50 +00002346 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002347 printf("\n");
2348}
2349
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002350static int index_abortQuery(CXClientData client_data, void *reserved) {
2351 IndexData *index_data;
2352 index_data = (IndexData *)client_data;
2353 return index_data->abort;
2354}
2355
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002356static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002357 index_abortQuery,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002358 index_diagnostic,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002359 index_enteredMainFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002360 index_ppIncludedFile,
Argyrios Kyrtzidisf89bc052011-10-20 17:21:46 +00002361 0, /*importedASTFile*/
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002362 index_startedTranslationUnit,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002363 index_indexDeclaration,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002364 index_indexEntityReference
2365};
2366
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002367static unsigned getIndexOptions(void) {
2368 unsigned index_opts;
2369 index_opts = 0;
2370 if (getenv("CINDEXTEST_SUPPRESSREFS"))
2371 index_opts |= CXIndexOpt_SuppressRedundantRefs;
2372 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
2373 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
2374
2375 return index_opts;
2376}
2377
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002378static int index_file(int argc, const char **argv) {
2379 const char *check_prefix;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002380 CXIndex Idx;
2381 CXIndexAction idxAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002382 IndexData index_data;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002383 unsigned index_opts;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002384 int result;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002385
2386 check_prefix = 0;
2387 if (argc > 0) {
2388 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2389 check_prefix = argv[0] + strlen("-check-prefix=");
2390 ++argv;
2391 --argc;
2392 }
2393 }
2394
2395 if (argc == 0) {
2396 fprintf(stderr, "no compiler arguments\n");
2397 return -1;
2398 }
2399
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002400 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2401 /* displayDiagnosics=*/1))) {
2402 fprintf(stderr, "Could not create Index\n");
2403 return 1;
2404 }
2405 idxAction = 0;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002406
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002407 index_data.check_prefix = check_prefix;
2408 index_data.first_check_printed = 0;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002409 index_data.fail_for_error = 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002410 index_data.abort = 0;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002411
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002412 index_opts = getIndexOptions();
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002413 idxAction = clang_IndexAction_create(Idx);
2414 result = clang_indexSourceFile(idxAction, &index_data,
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002415 &IndexCB,sizeof(IndexCB), index_opts,
Argyrios Kyrtzidisc6b4a502011-11-16 02:34:59 +00002416 0, argv, argc, 0, 0, 0, 0);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002417 if (index_data.fail_for_error)
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002418 result = -1;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002419
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002420 clang_IndexAction_dispose(idxAction);
2421 clang_disposeIndex(Idx);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002422 return result;
2423}
2424
2425static int index_tu(int argc, const char **argv) {
2426 CXIndex Idx;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002427 CXIndexAction idxAction;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002428 CXTranslationUnit TU;
2429 const char *check_prefix;
2430 IndexData index_data;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002431 unsigned index_opts;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002432 int result;
2433
2434 check_prefix = 0;
2435 if (argc > 0) {
2436 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2437 check_prefix = argv[0] + strlen("-check-prefix=");
2438 ++argv;
2439 --argc;
2440 }
2441 }
2442
2443 if (argc == 0) {
2444 fprintf(stderr, "no ast file\n");
2445 return -1;
2446 }
2447
2448 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2449 /* displayDiagnosics=*/1))) {
2450 fprintf(stderr, "Could not create Index\n");
2451 return 1;
2452 }
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002453 idxAction = 0;
2454 result = 1;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002455
2456 if (!CreateTranslationUnit(Idx, argv[0], &TU))
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002457 goto finished;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002458
2459 index_data.check_prefix = check_prefix;
2460 index_data.first_check_printed = 0;
2461 index_data.fail_for_error = 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002462 index_data.abort = 0;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002463
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002464 index_opts = getIndexOptions();
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002465 idxAction = clang_IndexAction_create(Idx);
2466 result = clang_indexTranslationUnit(idxAction, &index_data,
2467 &IndexCB,sizeof(IndexCB),
2468 index_opts, TU);
2469 if (index_data.fail_for_error)
2470 goto finished;
2471
2472 finished:
2473 clang_IndexAction_dispose(idxAction);
2474 clang_disposeIndex(Idx);
2475
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002476 return result;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002477}
2478
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002479int perform_token_annotation(int argc, const char **argv) {
2480 const char *input = argv[1];
2481 char *filename = 0;
2482 unsigned line, second_line;
2483 unsigned column, second_column;
2484 CXIndex CIdx;
2485 CXTranslationUnit TU = 0;
2486 int errorCode;
2487 struct CXUnsavedFile *unsaved_files = 0;
2488 int num_unsaved_files = 0;
2489 CXToken *tokens;
2490 unsigned num_tokens;
2491 CXSourceRange range;
2492 CXSourceLocation startLoc, endLoc;
2493 CXFile file = 0;
2494 CXCursor *cursors = 0;
2495 unsigned i;
2496
2497 input += strlen("-test-annotate-tokens=");
2498 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
2499 &second_line, &second_column)))
2500 return errorCode;
2501
Richard Smithe07c5f82012-07-05 08:20:49 +00002502 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
2503 free(filename);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002504 return -1;
Richard Smithe07c5f82012-07-05 08:20:49 +00002505 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002506
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002507 CIdx = clang_createIndex(0, 1);
Douglas Gregordca8ee82011-05-06 16:33:08 +00002508 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2509 argv + num_unsaved_files + 2,
2510 argc - num_unsaved_files - 3,
2511 unsaved_files,
2512 num_unsaved_files,
2513 getDefaultParsingOptions());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002514 if (!TU) {
2515 fprintf(stderr, "unable to parse input\n");
2516 clang_disposeIndex(CIdx);
2517 free(filename);
2518 free_remapped_files(unsaved_files, num_unsaved_files);
2519 return -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002520 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002521 errorCode = 0;
2522
Richard Smithe07c5f82012-07-05 08:20:49 +00002523 if (checkForErrors(TU) != 0) {
2524 errorCode = -1;
2525 goto teardown;
2526 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002527
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002528 if (getenv("CINDEXTEST_EDITING")) {
2529 for (i = 0; i < 5; ++i) {
2530 if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2531 clang_defaultReparseOptions(TU))) {
2532 fprintf(stderr, "Unable to reparse translation unit!\n");
2533 errorCode = -1;
2534 goto teardown;
2535 }
2536 }
2537 }
2538
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002539 if (checkForErrors(TU) != 0) {
2540 errorCode = -1;
2541 goto teardown;
2542 }
2543
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002544 file = clang_getFile(TU, filename);
2545 if (!file) {
2546 fprintf(stderr, "file %s is not in this translation unit\n", filename);
2547 errorCode = -1;
2548 goto teardown;
2549 }
2550
2551 startLoc = clang_getLocation(TU, file, line, column);
2552 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002553 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002554 column);
2555 errorCode = -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002556 goto teardown;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002557 }
2558
2559 endLoc = clang_getLocation(TU, file, second_line, second_column);
2560 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002561 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002562 second_line, second_column);
2563 errorCode = -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002564 goto teardown;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002565 }
2566
2567 range = clang_getRange(startLoc, endLoc);
2568 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002569
2570 if (checkForErrors(TU) != 0) {
2571 errorCode = -1;
2572 goto teardown;
2573 }
2574
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002575 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
2576 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002577
2578 if (checkForErrors(TU) != 0) {
2579 errorCode = -1;
2580 goto teardown;
2581 }
2582
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002583 for (i = 0; i != num_tokens; ++i) {
2584 const char *kind = "<unknown>";
2585 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
2586 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
2587 unsigned start_line, start_column, end_line, end_column;
2588
2589 switch (clang_getTokenKind(tokens[i])) {
2590 case CXToken_Punctuation: kind = "Punctuation"; break;
2591 case CXToken_Keyword: kind = "Keyword"; break;
2592 case CXToken_Identifier: kind = "Identifier"; break;
2593 case CXToken_Literal: kind = "Literal"; break;
2594 case CXToken_Comment: kind = "Comment"; break;
2595 }
Douglas Gregora9b06d42010-11-09 06:24:54 +00002596 clang_getSpellingLocation(clang_getRangeStart(extent),
2597 0, &start_line, &start_column, 0);
2598 clang_getSpellingLocation(clang_getRangeEnd(extent),
2599 0, &end_line, &end_column, 0);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00002600 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Kramer342742a2012-04-14 09:11:51 +00002601 clang_disposeString(spelling);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00002602 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002603 if (!clang_isInvalid(cursors[i].kind)) {
2604 printf(" ");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002605 PrintCursor(cursors[i]);
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002606 }
2607 printf("\n");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002608 }
2609 free(cursors);
Ted Kremenek93f5e6a2010-10-20 21:22:15 +00002610 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002611
2612 teardown:
Douglas Gregora88084b2010-02-18 18:08:43 +00002613 PrintDiagnostics(TU);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002614 clang_disposeTranslationUnit(TU);
2615 clang_disposeIndex(CIdx);
2616 free(filename);
2617 free_remapped_files(unsaved_files, num_unsaved_files);
2618 return errorCode;
2619}
2620
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002621static int
2622perform_test_compilation_db(const char *database, int argc, const char **argv) {
2623 CXCompilationDatabase db;
2624 CXCompileCommands CCmds;
2625 CXCompileCommand CCmd;
2626 CXCompilationDatabase_Error ec;
2627 CXString wd;
2628 CXString arg;
2629 int errorCode = 0;
2630 char *tmp;
2631 unsigned len;
2632 char *buildDir;
2633 int i, j, a, numCmds, numArgs;
2634
2635 len = strlen(database);
2636 tmp = (char *) malloc(len+1);
2637 memcpy(tmp, database, len+1);
2638 buildDir = dirname(tmp);
2639
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002640 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002641
2642 if (db) {
2643
2644 if (ec!=CXCompilationDatabase_NoError) {
2645 printf("unexpected error %d code while loading compilation database\n", ec);
2646 errorCode = -1;
2647 goto cdb_end;
2648 }
2649
2650 for (i=0; i<argc && errorCode==0; ) {
2651 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002652 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002653
2654 if (!CCmds) {
2655 printf("file %s not found in compilation db\n", argv[i+1]);
2656 errorCode = -1;
2657 break;
2658 }
2659
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002660 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002661
2662 if (numCmds==0) {
2663 fprintf(stderr, "should not get an empty compileCommand set for file"
2664 " '%s'\n", argv[i+1]);
2665 errorCode = -1;
2666 break;
2667 }
2668
2669 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002670 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002671
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002672 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002673 printf("workdir:'%s'", clang_getCString(wd));
2674 clang_disposeString(wd);
2675
2676 printf(" cmdline:'");
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002677 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002678 for (a=0; a<numArgs; ++a) {
2679 if (a) printf(" ");
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002680 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002681 printf("%s", clang_getCString(arg));
2682 clang_disposeString(arg);
2683 }
2684 printf("'\n");
2685 }
2686
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002687 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002688
2689 i += 2;
2690 }
2691 }
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002692 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002693 } else {
2694 printf("database loading failed with error code %d.\n", ec);
2695 errorCode = -1;
2696 }
2697
2698cdb_end:
2699 free(tmp);
2700
2701 return errorCode;
2702}
2703
Ted Kremenek0d435192009-11-17 18:13:31 +00002704/******************************************************************************/
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002705/* USR printing. */
2706/******************************************************************************/
2707
2708static int insufficient_usr(const char *kind, const char *usage) {
2709 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
2710 return 1;
2711}
2712
2713static unsigned isUSR(const char *s) {
2714 return s[0] == 'c' && s[1] == ':';
2715}
2716
2717static int not_usr(const char *s, const char *arg) {
2718 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
2719 return 1;
2720}
2721
2722static void print_usr(CXString usr) {
2723 const char *s = clang_getCString(usr);
2724 printf("%s\n", s);
2725 clang_disposeString(usr);
2726}
2727
2728static void display_usrs() {
2729 fprintf(stderr, "-print-usrs options:\n"
2730 " ObjCCategory <class name> <category name>\n"
2731 " ObjCClass <class name>\n"
2732 " ObjCIvar <ivar name> <class USR>\n"
2733 " ObjCMethod <selector> [0=class method|1=instance method] "
2734 "<class USR>\n"
2735 " ObjCProperty <property name> <class USR>\n"
2736 " ObjCProtocol <protocol name>\n");
2737}
2738
2739int print_usrs(const char **I, const char **E) {
2740 while (I != E) {
2741 const char *kind = *I;
2742 unsigned len = strlen(kind);
2743 switch (len) {
2744 case 8:
2745 if (memcmp(kind, "ObjCIvar", 8) == 0) {
2746 if (I + 2 >= E)
2747 return insufficient_usr(kind, "<ivar name> <class USR>");
2748 if (!isUSR(I[2]))
2749 return not_usr("<class USR>", I[2]);
2750 else {
2751 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002752 x.data = (void*) I[2];
Ted Kremeneked122732010-11-16 01:56:27 +00002753 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002754 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
2755 }
2756
2757 I += 3;
2758 continue;
2759 }
2760 break;
2761 case 9:
2762 if (memcmp(kind, "ObjCClass", 9) == 0) {
2763 if (I + 1 >= E)
2764 return insufficient_usr(kind, "<class name>");
2765 print_usr(clang_constructUSR_ObjCClass(I[1]));
2766 I += 2;
2767 continue;
2768 }
2769 break;
2770 case 10:
2771 if (memcmp(kind, "ObjCMethod", 10) == 0) {
2772 if (I + 3 >= E)
2773 return insufficient_usr(kind, "<method selector> "
2774 "[0=class method|1=instance method] <class USR>");
2775 if (!isUSR(I[3]))
2776 return not_usr("<class USR>", I[3]);
2777 else {
2778 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002779 x.data = (void*) I[3];
Ted Kremeneked122732010-11-16 01:56:27 +00002780 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002781 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
2782 }
2783 I += 4;
2784 continue;
2785 }
2786 break;
2787 case 12:
2788 if (memcmp(kind, "ObjCCategory", 12) == 0) {
2789 if (I + 2 >= E)
2790 return insufficient_usr(kind, "<class name> <category name>");
2791 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
2792 I += 3;
2793 continue;
2794 }
2795 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
2796 if (I + 1 >= E)
2797 return insufficient_usr(kind, "<protocol name>");
2798 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
2799 I += 2;
2800 continue;
2801 }
2802 if (memcmp(kind, "ObjCProperty", 12) == 0) {
2803 if (I + 2 >= E)
2804 return insufficient_usr(kind, "<property name> <class USR>");
2805 if (!isUSR(I[2]))
2806 return not_usr("<class USR>", I[2]);
2807 else {
2808 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002809 x.data = (void*) I[2];
Ted Kremeneked122732010-11-16 01:56:27 +00002810 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002811 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
2812 }
2813 I += 3;
2814 continue;
2815 }
2816 break;
2817 default:
2818 break;
2819 }
2820 break;
2821 }
2822
2823 if (I != E) {
2824 fprintf(stderr, "Invalid USR kind: %s\n", *I);
2825 display_usrs();
2826 return 1;
2827 }
2828 return 0;
2829}
2830
2831int print_usrs_file(const char *file_name) {
2832 char line[2048];
2833 const char *args[128];
2834 unsigned numChars = 0;
2835
2836 FILE *fp = fopen(file_name, "r");
2837 if (!fp) {
2838 fprintf(stderr, "error: cannot open '%s'\n", file_name);
2839 return 1;
2840 }
2841
2842 /* This code is not really all that safe, but it works fine for testing. */
2843 while (!feof(fp)) {
2844 char c = fgetc(fp);
2845 if (c == '\n') {
2846 unsigned i = 0;
2847 const char *s = 0;
2848
2849 if (numChars == 0)
2850 continue;
2851
2852 line[numChars] = '\0';
2853 numChars = 0;
2854
2855 if (line[0] == '/' && line[1] == '/')
2856 continue;
2857
2858 s = strtok(line, " ");
2859 while (s) {
2860 args[i] = s;
2861 ++i;
2862 s = strtok(0, " ");
2863 }
2864 if (print_usrs(&args[0], &args[i]))
2865 return 1;
2866 }
2867 else
2868 line[numChars++] = c;
2869 }
2870
2871 fclose(fp);
2872 return 0;
2873}
2874
2875/******************************************************************************/
Ted Kremenek0d435192009-11-17 18:13:31 +00002876/* Command line processing. */
2877/******************************************************************************/
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002878int write_pch_file(const char *filename, int argc, const char *argv[]) {
2879 CXIndex Idx;
2880 CXTranslationUnit TU;
2881 struct CXUnsavedFile *unsaved_files = 0;
2882 int num_unsaved_files = 0;
Francois Pichet08aa6222011-07-06 22:09:44 +00002883 int result = 0;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002884
2885 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnosics=*/1);
2886
2887 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
2888 clang_disposeIndex(Idx);
2889 return -1;
2890 }
2891
2892 TU = clang_parseTranslationUnit(Idx, 0,
2893 argv + num_unsaved_files,
2894 argc - num_unsaved_files,
2895 unsaved_files,
2896 num_unsaved_files,
2897 CXTranslationUnit_Incomplete);
2898 if (!TU) {
2899 fprintf(stderr, "Unable to load translation unit!\n");
2900 free_remapped_files(unsaved_files, num_unsaved_files);
2901 clang_disposeIndex(Idx);
2902 return 1;
2903 }
2904
Douglas Gregor39c411f2011-07-06 16:43:36 +00002905 switch (clang_saveTranslationUnit(TU, filename,
2906 clang_defaultSaveOptions(TU))) {
2907 case CXSaveError_None:
2908 break;
2909
2910 case CXSaveError_TranslationErrors:
2911 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
2912 filename);
2913 result = 2;
2914 break;
2915
2916 case CXSaveError_InvalidTU:
2917 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
2918 filename);
2919 result = 3;
2920 break;
2921
2922 case CXSaveError_Unknown:
2923 default:
2924 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
2925 result = 1;
2926 break;
2927 }
2928
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002929 clang_disposeTranslationUnit(TU);
2930 free_remapped_files(unsaved_files, num_unsaved_files);
2931 clang_disposeIndex(Idx);
Douglas Gregor39c411f2011-07-06 16:43:36 +00002932 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002933}
2934
2935/******************************************************************************/
Ted Kremenek15322172011-11-10 08:43:12 +00002936/* Serialized diagnostics. */
2937/******************************************************************************/
2938
2939static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
2940 switch (error) {
2941 case CXLoadDiag_CannotLoad: return "Cannot Load File";
2942 case CXLoadDiag_None: break;
2943 case CXLoadDiag_Unknown: return "Unknown";
2944 case CXLoadDiag_InvalidFile: return "Invalid File";
2945 }
2946 return "None";
2947}
2948
2949static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
2950 switch (severity) {
2951 case CXDiagnostic_Note: return "note";
2952 case CXDiagnostic_Error: return "error";
2953 case CXDiagnostic_Fatal: return "fatal";
2954 case CXDiagnostic_Ignored: return "ignored";
2955 case CXDiagnostic_Warning: return "warning";
2956 }
2957 return "unknown";
2958}
2959
2960static void printIndent(unsigned indent) {
Ted Kremeneka7e8a832011-11-11 00:46:43 +00002961 if (indent == 0)
2962 return;
2963 fprintf(stderr, "+");
2964 --indent;
Ted Kremenek15322172011-11-10 08:43:12 +00002965 while (indent > 0) {
Ted Kremeneka7e8a832011-11-11 00:46:43 +00002966 fprintf(stderr, "-");
Ted Kremenek15322172011-11-10 08:43:12 +00002967 --indent;
2968 }
2969}
2970
2971static void printLocation(CXSourceLocation L) {
2972 CXFile File;
2973 CXString FileName;
2974 unsigned line, column, offset;
2975
2976 clang_getExpansionLocation(L, &File, &line, &column, &offset);
2977 FileName = clang_getFileName(File);
2978
2979 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
2980 clang_disposeString(FileName);
2981}
2982
2983static void printRanges(CXDiagnostic D, unsigned indent) {
2984 unsigned i, n = clang_getDiagnosticNumRanges(D);
2985
2986 for (i = 0; i < n; ++i) {
2987 CXSourceLocation Start, End;
2988 CXSourceRange SR = clang_getDiagnosticRange(D, i);
2989 Start = clang_getRangeStart(SR);
2990 End = clang_getRangeEnd(SR);
2991
2992 printIndent(indent);
2993 fprintf(stderr, "Range: ");
2994 printLocation(Start);
2995 fprintf(stderr, " ");
2996 printLocation(End);
2997 fprintf(stderr, "\n");
2998 }
2999}
3000
3001static void printFixIts(CXDiagnostic D, unsigned indent) {
3002 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek3739b322012-03-20 20:49:45 +00003003 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenek15322172011-11-10 08:43:12 +00003004 for (i = 0 ; i < n; ++i) {
3005 CXSourceRange ReplacementRange;
3006 CXString text;
3007 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3008
3009 printIndent(indent);
3010 fprintf(stderr, "FIXIT: (");
3011 printLocation(clang_getRangeStart(ReplacementRange));
3012 fprintf(stderr, " - ");
3013 printLocation(clang_getRangeEnd(ReplacementRange));
3014 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3015 clang_disposeString(text);
3016 }
3017}
3018
3019static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi91909432011-11-10 09:30:15 +00003020 unsigned i, n;
3021
Ted Kremenek15322172011-11-10 08:43:12 +00003022 if (!Diags)
3023 return;
3024
NAKAMURA Takumi91909432011-11-10 09:30:15 +00003025 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenek15322172011-11-10 08:43:12 +00003026 for (i = 0; i < n; ++i) {
3027 CXSourceLocation DiagLoc;
3028 CXDiagnostic D;
3029 CXFile File;
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003030 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenek15322172011-11-10 08:43:12 +00003031 unsigned line, column, offset;
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003032 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenek15322172011-11-10 08:43:12 +00003033
3034 D = clang_getDiagnosticInSet(Diags, i);
3035 DiagLoc = clang_getDiagnosticLocation(D);
3036 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3037 FileName = clang_getFileName(File);
3038 DiagSpelling = clang_getDiagnosticSpelling(D);
3039
3040 printIndent(indent);
3041
3042 fprintf(stderr, "%s:%d:%d: %s: %s",
3043 clang_getCString(FileName),
3044 line,
3045 column,
3046 getSeverityString(clang_getDiagnosticSeverity(D)),
3047 clang_getCString(DiagSpelling));
3048
3049 DiagOption = clang_getDiagnosticOption(D, 0);
3050 DiagOptionStr = clang_getCString(DiagOption);
3051 if (DiagOptionStr) {
3052 fprintf(stderr, " [%s]", DiagOptionStr);
3053 }
3054
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003055 DiagCat = clang_getDiagnosticCategoryText(D);
3056 DiagCatStr = clang_getCString(DiagCat);
3057 if (DiagCatStr) {
3058 fprintf(stderr, " [%s]", DiagCatStr);
3059 }
3060
Ted Kremenek15322172011-11-10 08:43:12 +00003061 fprintf(stderr, "\n");
3062
3063 printRanges(D, indent);
3064 printFixIts(D, indent);
3065
NAKAMURA Takumia4ca95a2011-11-10 10:07:57 +00003066 /* Print subdiagnostics. */
Ted Kremenek15322172011-11-10 08:43:12 +00003067 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3068
3069 clang_disposeString(FileName);
3070 clang_disposeString(DiagSpelling);
3071 clang_disposeString(DiagOption);
3072 }
3073}
3074
3075static int read_diagnostics(const char *filename) {
3076 enum CXLoadDiag_Error error;
3077 CXString errorString;
3078 CXDiagnosticSet Diags = 0;
3079
3080 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3081 if (!Diags) {
3082 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3083 getDiagnosticCodeStr(error),
3084 clang_getCString(errorString));
3085 clang_disposeString(errorString);
3086 return 1;
3087 }
3088
3089 printDiagnosticSet(Diags, 0);
Ted Kremeneka7e8a832011-11-11 00:46:43 +00003090 fprintf(stderr, "Number of diagnostics: %d\n",
3091 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenek15322172011-11-10 08:43:12 +00003092 clang_disposeDiagnosticSet(Diags);
3093 return 0;
3094}
3095
3096/******************************************************************************/
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003097/* Command line processing. */
3098/******************************************************************************/
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003099
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003100static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek7d405622010-01-12 23:34:26 +00003101 if (s[0] == '\0')
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003102 return FilteredPrintingVisitor;
Ted Kremenek7d405622010-01-12 23:34:26 +00003103 if (strcmp(s, "-usrs") == 0)
3104 return USRVisitor;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003105 if (strncmp(s, "-memory-usage", 13) == 0)
3106 return GetVisitor(s + 13);
Ted Kremenek7d405622010-01-12 23:34:26 +00003107 return NULL;
3108}
3109
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003110static void print_usage(void) {
3111 fprintf(stderr,
Ted Kremenek0d435192009-11-17 18:13:31 +00003112 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003113 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003114 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003115 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003116 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00003117 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00003118 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen26fc0f92011-10-06 11:38:08 +00003119 "[FileCheck prefix]\n");
3120 fprintf(stderr,
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00003121 " c-index-test -test-load-tu <AST file> <symbol filter> "
3122 "[FileCheck prefix]\n"
Ted Kremenek7d405622010-01-12 23:34:26 +00003123 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
3124 "[FileCheck prefix]\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003125 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003126 fprintf(stderr,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003127 " c-index-test -test-load-source-memory-usage "
3128 "<symbol filter> {<args>}*\n"
Douglas Gregorabc563f2010-07-19 21:46:24 +00003129 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
3130 " {<args>}*\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003131 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003132 " c-index-test -test-load-source-usrs-memory-usage "
3133 "<symbol filter> {<args>}*\n"
Ted Kremenek16b55a72010-01-26 19:31:51 +00003134 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
3135 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00003136 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth53513d22010-07-22 06:29:13 +00003137 fprintf(stderr,
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00003138 " c-index-test -test-print-linkage-source {<args>}*\n"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003139 " c-index-test -test-print-typekind {<args>}*\n"
3140 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003141 " c-index-test -print-usr-file <file>\n"
Ted Kremenek15322172011-11-10 08:43:12 +00003142 " c-index-test -write-pch <file> <compiler arguments>\n");
3143 fprintf(stderr,
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003144 " c-index-test -compilation-db [lookup <filename>] database\n");
3145 fprintf(stderr,
Ted Kremenek15322172011-11-10 08:43:12 +00003146 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregorcaf4bd32010-07-20 14:34:35 +00003147 fprintf(stderr,
Ted Kremenek7d405622010-01-12 23:34:26 +00003148 " <symbol filter> values:\n%s",
Ted Kremenek0d435192009-11-17 18:13:31 +00003149 " all - load all symbols, including those from PCH\n"
3150 " local - load all symbols except those in PCH\n"
3151 " category - only load ObjC categories (non-PCH)\n"
3152 " interface - only load ObjC interfaces (non-PCH)\n"
3153 " protocol - only load ObjC protocols (non-PCH)\n"
3154 " function - only load functions (non-PCH)\n"
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00003155 " typedef - only load typdefs (non-PCH)\n"
3156 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003157}
3158
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003159/***/
3160
3161int cindextest_main(int argc, const char **argv) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003162 clang_enableStackTraces();
Ted Kremenek15322172011-11-10 08:43:12 +00003163 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
3164 return read_diagnostics(argv[2]);
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003165 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor1982c182010-07-12 18:38:41 +00003166 return perform_code_completion(argc, argv, 0);
3167 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
3168 return perform_code_completion(argc, argv, 1);
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003169 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
3170 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003171 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
3172 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003173 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
3174 return index_file(argc - 2, argv + 2);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00003175 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
3176 return index_tu(argc - 2, argv + 2);
Ted Kremenek7d405622010-01-12 23:34:26 +00003177 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003178 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek7d405622010-01-12 23:34:26 +00003179 if (I)
Ted Kremenekce2ae882010-01-26 17:59:48 +00003180 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
3181 NULL);
Ted Kremenek7d405622010-01-12 23:34:26 +00003182 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00003183 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
3184 CXCursorVisitor I = GetVisitor(argv[1] + 25);
3185 if (I) {
3186 int trials = atoi(argv[2]);
3187 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
3188 NULL);
3189 }
3190 }
Ted Kremenek7d405622010-01-12 23:34:26 +00003191 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003192 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003193
3194 PostVisitTU postVisit = 0;
3195 if (strstr(argv[1], "-memory-usage"))
3196 postVisit = PrintMemoryUsage;
3197
Ted Kremenek7d405622010-01-12 23:34:26 +00003198 if (I)
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003199 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
3200 postVisit);
Ted Kremenek7d405622010-01-12 23:34:26 +00003201 }
3202 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00003203 return perform_file_scan(argv[2], argv[3],
3204 argc >= 5 ? argv[4] : 0);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003205 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
3206 return perform_token_annotation(argc, argv);
Ted Kremenek16b55a72010-01-26 19:31:51 +00003207 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
3208 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
3209 PrintInclusionStack);
3210 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
3211 return perform_test_load_tu(argv[2], "all", NULL, NULL,
3212 PrintInclusionStack);
Ted Kremenek3bed5272010-03-03 06:37:58 +00003213 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
3214 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
3215 NULL);
Ted Kremenek8e0ac172010-05-14 21:29:26 +00003216 else if (argc > 2 && strcmp(argv[1], "-test-print-typekind") == 0)
3217 return perform_test_load_source(argc - 2, argv + 2, "all",
3218 PrintTypeKind, 0);
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003219 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
3220 if (argc > 2)
3221 return print_usrs(argv + 2, argv + argc);
3222 else {
3223 display_usrs();
3224 return 1;
3225 }
3226 }
3227 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
3228 return print_usrs_file(argv[2]);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003229 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
3230 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003231 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
3232 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
3233
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003234 print_usage();
3235 return 1;
Steve Naroff50398192009-08-28 15:28:48 +00003236}
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003237
3238/***/
3239
3240/* We intentionally run in a separate thread to ensure we at least minimal
3241 * testing of a multithreaded environment (for example, having a reduced stack
3242 * size). */
3243
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003244typedef struct thread_info {
3245 int argc;
3246 const char **argv;
3247 int result;
3248} thread_info;
Benjamin Kramer84294912010-11-04 19:11:31 +00003249void thread_runner(void *client_data_v) {
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003250 thread_info *client_data = client_data_v;
3251 client_data->result = cindextest_main(client_data->argc, client_data->argv);
NAKAMURA Takumi3be55cd2012-04-07 06:59:28 +00003252#ifdef __CYGWIN__
3253 fflush(stdout); /* stdout is not flushed on Cygwin. */
3254#endif
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003255}
3256
3257int main(int argc, const char **argv) {
3258 thread_info client_data;
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003259
Douglas Gregor61605982010-10-27 16:00:01 +00003260 if (getenv("CINDEXTEST_NOTHREADS"))
3261 return cindextest_main(argc, argv);
3262
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003263 client_data.argc = argc;
3264 client_data.argv = argv;
Daniel Dunbara32a6e12010-11-04 01:26:31 +00003265 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003266 return client_data.result;
3267}