blob: 574c9f73833f93b9d3fdeed5f94ac042d33923fa [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 Gribenko5ef6ea52012-07-20 22:00:35 +0000286 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000287 i != e; ++i) {
288 printf(" Arg[%u]=", i);
289 PrintCXStringAndDispose(
290 clang_InlineCommandComment_getArgText(Comment, i));
291 }
292 if (clang_InlineContentComment_hasTrailingNewline(Comment))
293 printf(" HasTrailingNewline");
294 break;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000295 case CXComment_HTMLStartTag: {
296 unsigned NumAttrs;
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000297 printf("CXComment_HTMLStartTag");
298 PrintCXStringWithPrefixAndDispose(
299 "Name",
300 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000301 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000302 if (NumAttrs != 0) {
303 printf(" Attrs:");
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000304 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000305 printf(" ");
306 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
307 printf("=");
308 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
309 }
310 }
311 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
312 printf(" SelfClosing");
313 if (clang_InlineContentComment_hasTrailingNewline(Comment))
314 printf(" HasTrailingNewline");
315 break;
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000316 }
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000317 case CXComment_HTMLEndTag:
318 printf("CXComment_HTMLEndTag");
319 PrintCXStringWithPrefixAndDispose(
320 "Name",
321 clang_HTMLTagComment_getTagName(Comment));
322 if (clang_InlineContentComment_hasTrailingNewline(Comment))
323 printf(" HasTrailingNewline");
324 break;
325 case CXComment_Paragraph:
326 printf("CXComment_Paragraph");
327 if (clang_Comment_isWhitespace(Comment))
328 printf(" IsWhitespace");
329 break;
330 case CXComment_BlockCommand:
331 printf("CXComment_BlockCommand");
332 PrintCXStringWithPrefixAndDispose(
333 "CommandName",
334 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000335 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000336 i != e; ++i) {
337 printf(" Arg[%u]=", i);
338 PrintCXStringAndDispose(
339 clang_BlockCommandComment_getArgText(Comment, i));
340 }
341 break;
342 case CXComment_ParamCommand:
343 printf("CXComment_ParamCommand");
344 switch (clang_ParamCommandComment_getDirection(Comment)) {
345 case CXCommentParamPassDirection_In:
346 printf(" in");
347 break;
348 case CXCommentParamPassDirection_Out:
349 printf(" out");
350 break;
351 case CXCommentParamPassDirection_InOut:
352 printf(" in,out");
353 break;
354 }
355 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
356 printf(" explicitly");
357 else
358 printf(" implicitly");
359 PrintCXStringWithPrefixAndDispose(
360 "ParamName",
361 clang_ParamCommandComment_getParamName(Comment));
362 if (clang_ParamCommandComment_isParamIndexValid(Comment))
363 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
364 else
365 printf(" ParamIndex=Invalid");
366 break;
367 case CXComment_VerbatimBlockCommand:
368 printf("CXComment_VerbatimBlockCommand");
369 PrintCXStringWithPrefixAndDispose(
370 "CommandName",
371 clang_BlockCommandComment_getCommandName(Comment));
372 break;
373 case CXComment_VerbatimBlockLine:
374 printf("CXComment_VerbatimBlockLine");
375 PrintCXStringWithPrefixAndDispose(
376 "Text",
377 clang_VerbatimBlockLineComment_getText(Comment));
378 break;
379 case CXComment_VerbatimLine:
380 printf("CXComment_VerbatimLine");
381 PrintCXStringWithPrefixAndDispose(
382 "Text",
383 clang_VerbatimLineComment_getText(Comment));
384 break;
385 case CXComment_FullComment:
386 printf("CXComment_FullComment");
387 break;
388 }
389 if (Kind != CXComment_Null) {
390 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenko5ef6ea52012-07-20 22:00:35 +0000391 unsigned i;
392 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000393 printf("\n// %s: ", FileCheckPrefix);
394 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
395 }
396 }
397 printf(")");
398 Ctx->IndentLevel--;
399}
400
401static void DumpCXComment(CXComment Comment) {
402 struct CommentASTDumpingContext Ctx;
403 Ctx.IndentLevel = 1;
404 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
405 DumpCXCommentInternal(&Ctx, Comment);
406 printf("]");
407}
408
409static void PrintCursorComments(CXCursor Cursor) {
410 {
411 CXString RawComment;
412 const char *RawCommentCString;
413 CXString BriefComment;
414 const char *BriefCommentCString;
415
416 RawComment = clang_Cursor_getRawCommentText(Cursor);
417 RawCommentCString = clang_getCString(RawComment);
418 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
419 PrintCStringWithPrefix("RawComment", RawCommentCString);
420 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
421
422 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
423 BriefCommentCString = clang_getCString(BriefComment);
424 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
425 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
426 clang_disposeString(BriefComment);
427 }
428 clang_disposeString(RawComment);
429 }
430
431 {
432 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
433 if (clang_Comment_getKind(Comment) != CXComment_Null) {
434 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
435 clang_FullComment_getAsHTML(Comment));
436 DumpCXComment(Comment);
437 }
438 }
439}
440
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000441static void PrintCursor(CXCursor Cursor) {
442 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000443 if (clang_isInvalid(Cursor.kind)) {
444 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
445 printf("Invalid Cursor => %s", clang_getCString(ks));
446 clang_disposeString(ks);
447 }
Steve Naroff699a07d2009-09-25 21:32:34 +0000448 else {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000449 CXString string, ks;
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000450 CXCursor Referenced;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000451 unsigned line, column;
Douglas Gregore0329ac2010-09-02 00:07:54 +0000452 CXCursor SpecializationOf;
Douglas Gregor9f592342010-10-01 20:25:15 +0000453 CXCursor *overridden;
454 unsigned num_overridden;
Douglas Gregor430d7a12011-07-25 17:48:11 +0000455 unsigned RefNameRangeNr;
456 CXSourceRange CursorExtent;
457 CXSourceRange RefNameRange;
Douglas Gregorcc889662012-05-08 00:14:45 +0000458 int AlwaysUnavailable;
459 int AlwaysDeprecated;
460 CXString UnavailableMessage;
461 CXString DeprecatedMessage;
462 CXPlatformAvailability PlatformAvailability[2];
463 int NumPlatformAvailability;
464 int I;
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000465
Ted Kremeneke68fff62010-02-17 00:41:32 +0000466 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor358559d2010-10-02 22:49:11 +0000467 string = want_display_name? clang_getCursorDisplayName(Cursor)
468 : clang_getCursorSpelling(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000469 printf("%s=%s", clang_getCString(ks),
470 clang_getCString(string));
471 clang_disposeString(ks);
Steve Naroffef0cef62009-11-09 17:45:52 +0000472 clang_disposeString(string);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000473
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000474 Referenced = clang_getCursorReferenced(Cursor);
475 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000476 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
477 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
478 printf("[");
479 for (I = 0; I != N; ++I) {
480 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor1f6206e2010-09-14 00:20:32 +0000481 CXSourceLocation Loc;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000482 if (I)
483 printf(", ");
484
Douglas Gregor1f6206e2010-09-14 00:20:32 +0000485 Loc = clang_getCursorLocation(Ovl);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000486 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000487 printf("%d:%d", line, column);
488 }
489 printf("]");
490 } else {
491 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000492 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +0000493 printf(":%d:%d", line, column);
494 }
Douglas Gregorc5d1e932010-01-19 01:20:04 +0000495 }
Douglas Gregorb6998662010-01-19 19:34:47 +0000496
497 if (clang_isCursorDefinition(Cursor))
498 printf(" (Definition)");
Douglas Gregor58ddb602010-08-23 23:00:57 +0000499
500 switch (clang_getCursorAvailability(Cursor)) {
501 case CXAvailability_Available:
502 break;
503
504 case CXAvailability_Deprecated:
505 printf(" (deprecated)");
506 break;
507
508 case CXAvailability_NotAvailable:
509 printf(" (unavailable)");
510 break;
Erik Verbruggend1205962011-10-06 07:27:49 +0000511
512 case CXAvailability_NotAccessible:
513 printf(" (inaccessible)");
514 break;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000515 }
Ted Kremenek95f33552010-08-26 01:42:22 +0000516
Douglas Gregorcc889662012-05-08 00:14:45 +0000517 NumPlatformAvailability
518 = clang_getCursorPlatformAvailability(Cursor,
519 &AlwaysDeprecated,
520 &DeprecatedMessage,
521 &AlwaysUnavailable,
522 &UnavailableMessage,
523 PlatformAvailability, 2);
524 if (AlwaysUnavailable) {
525 printf(" (always unavailable: \"%s\")",
526 clang_getCString(UnavailableMessage));
527 } else if (AlwaysDeprecated) {
528 printf(" (always deprecated: \"%s\")",
529 clang_getCString(DeprecatedMessage));
530 } else {
531 for (I = 0; I != NumPlatformAvailability; ++I) {
532 if (I >= 2)
533 break;
534
535 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
536 if (PlatformAvailability[I].Unavailable)
537 printf(", unavailable");
538 else {
539 printVersion(", introduced=", PlatformAvailability[I].Introduced);
540 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
541 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
542 }
543 if (clang_getCString(PlatformAvailability[I].Message)[0])
544 printf(", message=\"%s\"",
545 clang_getCString(PlatformAvailability[I].Message));
546 printf(")");
547 }
548 }
549 for (I = 0; I != NumPlatformAvailability; ++I) {
550 if (I >= 2)
551 break;
552 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
553 }
554
555 clang_disposeString(DeprecatedMessage);
556 clang_disposeString(UnavailableMessage);
557
Douglas Gregorb83d4d72011-05-13 15:54:42 +0000558 if (clang_CXXMethod_isStatic(Cursor))
559 printf(" (static)");
560 if (clang_CXXMethod_isVirtual(Cursor))
561 printf(" (virtual)");
562
Ted Kremenek95f33552010-08-26 01:42:22 +0000563 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
564 CXType T =
565 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
566 CXString S = clang_getTypeKindSpelling(T.kind);
567 printf(" [IBOutletCollection=%s]", clang_getCString(S));
568 clang_disposeString(S);
569 }
Ted Kremenek3064ef92010-08-27 21:34:58 +0000570
571 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
572 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
573 unsigned isVirtual = clang_isVirtualBase(Cursor);
574 const char *accessStr = 0;
575
576 switch (access) {
577 case CX_CXXInvalidAccessSpecifier:
578 accessStr = "invalid"; break;
579 case CX_CXXPublic:
580 accessStr = "public"; break;
581 case CX_CXXProtected:
582 accessStr = "protected"; break;
583 case CX_CXXPrivate:
584 accessStr = "private"; break;
585 }
586
587 printf(" [access=%s isVirtual=%s]", accessStr,
588 isVirtual ? "true" : "false");
589 }
Douglas Gregore0329ac2010-09-02 00:07:54 +0000590
591 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
592 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
593 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
594 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000595 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregore0329ac2010-09-02 00:07:54 +0000596 printf(" [Specialization of %s:%d:%d]",
597 clang_getCString(Name), line, column);
598 clang_disposeString(Name);
599 }
Douglas Gregor9f592342010-10-01 20:25:15 +0000600
601 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
602 if (num_overridden) {
603 unsigned I;
604 printf(" [Overrides ");
605 for (I = 0; I != num_overridden; ++I) {
606 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000607 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor9f592342010-10-01 20:25:15 +0000608 if (I)
609 printf(", ");
610 printf("@%d:%d", line, column);
611 }
612 printf("]");
613 clang_disposeOverriddenCursors(overridden);
614 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000615
616 if (Cursor.kind == CXCursor_InclusionDirective) {
617 CXFile File = clang_getIncludedFile(Cursor);
618 CXString Included = clang_getFileName(File);
619 printf(" (%s)", clang_getCString(Included));
620 clang_disposeString(Included);
Douglas Gregordd3e5542011-05-04 00:14:37 +0000621
622 if (clang_isFileMultipleIncludeGuarded(TU, File))
623 printf(" [multi-include guarded]");
Douglas Gregorecdcb882010-10-20 22:00:55 +0000624 }
Douglas Gregor430d7a12011-07-25 17:48:11 +0000625
626 CursorExtent = clang_getCursorExtent(Cursor);
627 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
628 CXNameRange_WantQualifier
629 | CXNameRange_WantSinglePiece
630 | CXNameRange_WantTemplateArgs,
631 0);
632 if (!clang_equalRanges(CursorExtent, RefNameRange))
633 PrintRange(RefNameRange, "SingleRefName");
634
635 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
636 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
637 CXNameRange_WantQualifier
638 | CXNameRange_WantTemplateArgs,
639 RefNameRangeNr);
640 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
641 break;
642 if (!clang_equalRanges(CursorExtent, RefNameRange))
643 PrintRange(RefNameRange, "RefName");
644 }
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000645
Dmitri Gribenkoae99b752012-07-20 21:34:34 +0000646 PrintCursorComments(Cursor);
Steve Naroff699a07d2009-09-25 21:32:34 +0000647 }
Steve Naroffaf08ddc2009-09-03 15:49:00 +0000648}
Steve Naroff89922f82009-08-31 00:59:03 +0000649
Ted Kremeneke68fff62010-02-17 00:41:32 +0000650static const char* GetCursorSource(CXCursor Cursor) {
Douglas Gregor1db19de2010-01-19 21:36:55 +0000651 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenek74844072010-02-17 00:41:20 +0000652 CXString source;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000653 CXFile file;
Argyrios Kyrtzidisb4efaa02011-11-03 02:20:36 +0000654 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000655 source = clang_getFileName(file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000656 if (!clang_getCString(source)) {
Ted Kremenek74844072010-02-17 00:41:20 +0000657 clang_disposeString(source);
658 return "<invalid loc>";
659 }
660 else {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000661 const char *b = basename(clang_getCString(source));
Ted Kremenek74844072010-02-17 00:41:20 +0000662 clang_disposeString(source);
663 return b;
664 }
Ted Kremenek9298cfc2009-11-17 05:31:58 +0000665}
666
Ted Kremenek0d435192009-11-17 18:13:31 +0000667/******************************************************************************/
Ted Kremenekce2ae882010-01-26 17:59:48 +0000668/* Callbacks. */
669/******************************************************************************/
670
671typedef void (*PostVisitTU)(CXTranslationUnit);
672
Douglas Gregora88084b2010-02-18 18:08:43 +0000673void PrintDiagnostic(CXDiagnostic Diagnostic) {
674 FILE *out = stderr;
Douglas Gregor5352ac02010-01-28 00:27:43 +0000675 CXFile file;
Douglas Gregor274f1902010-02-22 23:17:23 +0000676 CXString Msg;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000677 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregoraa5f1352010-11-19 16:18:16 +0000678 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
679 | CXDiagnostic_DisplayOption;
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000680 unsigned i, num_fixits;
Ted Kremenekf7b714d2010-03-25 02:00:39 +0000681
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000682 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor5352ac02010-01-28 00:27:43 +0000683 return;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000684
Douglas Gregor274f1902010-02-22 23:17:23 +0000685 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
686 fprintf(stderr, "%s\n", clang_getCString(Msg));
687 clang_disposeString(Msg);
Ted Kremenekf7b714d2010-03-25 02:00:39 +0000688
Douglas Gregora9b06d42010-11-09 06:24:54 +0000689 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
690 &file, 0, 0, 0);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000691 if (!file)
692 return;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000693
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000694 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek3739b322012-03-20 20:49:45 +0000695 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000696 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor473d7012010-02-19 18:16:06 +0000697 CXSourceRange range;
698 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
699 CXSourceLocation start = clang_getRangeStart(range);
700 CXSourceLocation end = clang_getRangeEnd(range);
701 unsigned start_line, start_column, end_line, end_column;
702 CXFile start_file, end_file;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000703 clang_getSpellingLocation(start, &start_file, &start_line,
704 &start_column, 0);
705 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor473d7012010-02-19 18:16:06 +0000706 if (clang_equalLocations(start, end)) {
707 /* Insertion. */
708 if (start_file == file)
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000709 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor473d7012010-02-19 18:16:06 +0000710 clang_getCString(insertion_text), start_line, start_column);
711 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
712 /* Removal. */
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000713 if (start_file == file && end_file == file) {
714 fprintf(out, "FIX-IT: Remove ");
715 PrintExtent(out, start_line, start_column, end_line, end_column);
716 fprintf(out, "\n");
Douglas Gregor51c6d382010-01-29 00:41:11 +0000717 }
Douglas Gregor473d7012010-02-19 18:16:06 +0000718 } else {
719 /* Replacement. */
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000720 if (start_file == end_file) {
721 fprintf(out, "FIX-IT: Replace ");
722 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor473d7012010-02-19 18:16:06 +0000723 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor436f3f02010-02-18 22:27:07 +0000724 }
Douglas Gregor0a812cf2010-02-18 23:07:20 +0000725 break;
726 }
Douglas Gregor473d7012010-02-19 18:16:06 +0000727 clang_disposeString(insertion_text);
Douglas Gregor51c6d382010-01-29 00:41:11 +0000728 }
Douglas Gregor5352ac02010-01-28 00:27:43 +0000729}
730
Ted Kremenek7473b1c2012-02-14 02:46:03 +0000731void PrintDiagnosticSet(CXDiagnosticSet Set) {
732 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
733 for ( ; i != n ; ++i) {
734 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
735 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregora88084b2010-02-18 18:08:43 +0000736 PrintDiagnostic(Diag);
Ted Kremenek7473b1c2012-02-14 02:46:03 +0000737 if (ChildDiags)
738 PrintDiagnosticSet(ChildDiags);
739 }
740}
741
742void PrintDiagnostics(CXTranslationUnit TU) {
743 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
744 PrintDiagnosticSet(TUSet);
745 clang_disposeDiagnosticSet(TUSet);
Douglas Gregora88084b2010-02-18 18:08:43 +0000746}
747
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000748void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayb2273232011-08-29 16:37:29 +0000749 unsigned long total = 0;
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000750 unsigned i = 0;
Ted Kremenekf7870022011-04-20 16:41:07 +0000751 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet3c683362011-04-18 23:33:22 +0000752 fprintf(stderr, "Memory usage:\n");
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000753 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenekf7870022011-04-20 16:41:07 +0000754 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000755 unsigned long amount = usage.entries[i].amount;
756 total += amount;
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000757 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000758 ((double) amount)/(1024*1024));
759 }
Ted Kremenek4e6a3f72011-04-18 23:42:53 +0000760 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000761 ((double) total)/(1024*1024));
Ted Kremenekf7870022011-04-20 16:41:07 +0000762 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek59fc1e52011-04-18 22:47:10 +0000763}
764
Ted Kremenekce2ae882010-01-26 17:59:48 +0000765/******************************************************************************/
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000766/* Logic for testing traversal. */
Ted Kremenek0d435192009-11-17 18:13:31 +0000767/******************************************************************************/
768
Douglas Gregora7bde202010-01-19 00:34:46 +0000769static void PrintCursorExtent(CXCursor C) {
770 CXSourceRange extent = clang_getCursorExtent(C);
Douglas Gregor430d7a12011-07-25 17:48:11 +0000771 PrintRange(extent, "Extent");
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000772}
773
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000774/* Data used by all of the visitors. */
775typedef struct {
776 CXTranslationUnit TU;
777 enum CXCursorKind *Filter;
778} VisitorData;
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000779
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000780
Ted Kremeneke68fff62010-02-17 00:41:32 +0000781enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000782 CXCursor Parent,
783 CXClientData ClientData) {
784 VisitorData *Data = (VisitorData *)ClientData;
785 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000786 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor1db19de2010-01-19 21:36:55 +0000787 unsigned line, column;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000788 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +0000789 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor1db19de2010-01-19 21:36:55 +0000790 GetCursorSource(Cursor), line, column);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000791 PrintCursor(Cursor);
Douglas Gregora7bde202010-01-19 00:34:46 +0000792 PrintCursorExtent(Cursor);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000793 printf("\n");
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000794 return CXChildVisit_Recurse;
Steve Naroff2d4d6292009-08-31 14:26:51 +0000795 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000796
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000797 return CXChildVisit_Continue;
Steve Naroff89922f82009-08-31 00:59:03 +0000798}
Steve Naroff50398192009-08-28 15:28:48 +0000799
Ted Kremeneke68fff62010-02-17 00:41:32 +0000800static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000801 CXCursor Parent,
802 CXClientData ClientData) {
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000803 const char *startBuf, *endBuf;
804 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
805 CXCursor Ref;
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000806 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000807
Douglas Gregorb6998662010-01-19 19:34:47 +0000808 if (Cursor.kind != CXCursor_FunctionDecl ||
809 !clang_isCursorDefinition(Cursor))
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000810 return CXChildVisit_Continue;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000811
812 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
813 &startLine, &startColumn,
814 &endLine, &endColumn);
815 /* Probe the entire body, looking for both decls and refs. */
816 curLine = startLine;
817 curColumn = startColumn;
818
819 while (startBuf < endBuf) {
Douglas Gregor98258af2010-01-18 22:46:11 +0000820 CXSourceLocation Loc;
Douglas Gregor1db19de2010-01-19 21:36:55 +0000821 CXFile file;
Ted Kremenek74844072010-02-17 00:41:20 +0000822 CXString source;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000823
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000824 if (*startBuf == '\n') {
825 startBuf++;
826 curLine++;
827 curColumn = 1;
828 } else if (*startBuf != '\t')
829 curColumn++;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000830
Douglas Gregor98258af2010-01-18 22:46:11 +0000831 Loc = clang_getCursorLocation(Cursor);
Douglas Gregora9b06d42010-11-09 06:24:54 +0000832 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000833
Douglas Gregor1db19de2010-01-19 21:36:55 +0000834 source = clang_getFileName(file);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000835 if (clang_getCString(source)) {
Douglas Gregorb9790342010-01-22 21:44:22 +0000836 CXSourceLocation RefLoc
837 = clang_getLocation(Data->TU, file, curLine, curColumn);
838 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor98258af2010-01-18 22:46:11 +0000839 if (Ref.kind == CXCursor_NoDeclFound) {
840 /* Nothing found here; that's fine. */
841 } else if (Ref.kind != CXCursor_FunctionDecl) {
842 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
843 curLine, curColumn);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000844 PrintCursor(Ref);
Douglas Gregor98258af2010-01-18 22:46:11 +0000845 printf("\n");
846 }
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000847 }
Ted Kremenek74844072010-02-17 00:41:20 +0000848 clang_disposeString(source);
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000849 startBuf++;
850 }
Ted Kremeneke68fff62010-02-17 00:41:32 +0000851
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000852 return CXChildVisit_Continue;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +0000853}
854
Ted Kremenek7d405622010-01-12 23:34:26 +0000855/******************************************************************************/
856/* USR testing. */
857/******************************************************************************/
858
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000859enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
860 CXClientData ClientData) {
861 VisitorData *Data = (VisitorData *)ClientData;
862 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Ted Kremenekcf84aa42010-01-18 20:23:29 +0000863 CXString USR = clang_getCursorUSR(C);
Ted Kremeneke542f772010-04-20 23:15:40 +0000864 const char *cstr = clang_getCString(USR);
865 if (!cstr || cstr[0] == '\0') {
Ted Kremenek7d405622010-01-12 23:34:26 +0000866 clang_disposeString(USR);
Ted Kremeneke74ef122010-04-16 21:31:52 +0000867 return CXChildVisit_Recurse;
Ted Kremenek7d405622010-01-12 23:34:26 +0000868 }
Ted Kremeneke542f772010-04-20 23:15:40 +0000869 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
870
Douglas Gregora7bde202010-01-19 00:34:46 +0000871 PrintCursorExtent(C);
Ted Kremenek7d405622010-01-12 23:34:26 +0000872 printf("\n");
873 clang_disposeString(USR);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000874
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000875 return CXChildVisit_Recurse;
Ted Kremeneke68fff62010-02-17 00:41:32 +0000876 }
877
Douglas Gregore5b72ba2010-01-20 21:32:04 +0000878 return CXChildVisit_Continue;
Ted Kremenek7d405622010-01-12 23:34:26 +0000879}
880
881/******************************************************************************/
Ted Kremenek16b55a72010-01-26 19:31:51 +0000882/* Inclusion stack testing. */
883/******************************************************************************/
884
885void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
886 unsigned includeStackLen, CXClientData data) {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000887
Ted Kremenek16b55a72010-01-26 19:31:51 +0000888 unsigned i;
Ted Kremenek74844072010-02-17 00:41:20 +0000889 CXString fname;
890
891 fname = clang_getFileName(includedFile);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000892 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenek74844072010-02-17 00:41:20 +0000893 clang_disposeString(fname);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000894
Ted Kremenek16b55a72010-01-26 19:31:51 +0000895 for (i = 0; i < includeStackLen; ++i) {
896 CXFile includingFile;
897 unsigned line, column;
Douglas Gregora9b06d42010-11-09 06:24:54 +0000898 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
899 &column, 0);
Ted Kremenek74844072010-02-17 00:41:20 +0000900 fname = clang_getFileName(includingFile);
Ted Kremeneke68fff62010-02-17 00:41:32 +0000901 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenek74844072010-02-17 00:41:20 +0000902 clang_disposeString(fname);
Ted Kremenek16b55a72010-01-26 19:31:51 +0000903 }
904 printf("\n");
905}
906
907void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremeneke68fff62010-02-17 00:41:32 +0000908 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek16b55a72010-01-26 19:31:51 +0000909}
910
911/******************************************************************************/
Ted Kremenek3bed5272010-03-03 06:37:58 +0000912/* Linkage testing. */
913/******************************************************************************/
914
915static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
916 CXClientData d) {
917 const char *linkage = 0;
918
919 if (clang_isInvalid(clang_getCursorKind(cursor)))
920 return CXChildVisit_Recurse;
921
922 switch (clang_getCursorLinkage(cursor)) {
923 case CXLinkage_Invalid: break;
Douglas Gregorc2a2b3c2010-03-04 19:36:27 +0000924 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
925 case CXLinkage_Internal: linkage = "Internal"; break;
926 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
927 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek3bed5272010-03-03 06:37:58 +0000928 }
929
930 if (linkage) {
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000931 PrintCursor(cursor);
Ted Kremenek3bed5272010-03-03 06:37:58 +0000932 printf("linkage=%s\n", linkage);
933 }
934
935 return CXChildVisit_Recurse;
936}
937
938/******************************************************************************/
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000939/* Typekind testing. */
940/******************************************************************************/
941
942static enum CXChildVisitResult PrintTypeKind(CXCursor cursor, CXCursor p,
943 CXClientData d) {
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000944 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
945 CXType T = clang_getCursorType(cursor);
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000946 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +0000947 PrintCursor(cursor);
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000948 printf(" typekind=%s", clang_getCString(S));
Douglas Gregore72fb6f2011-01-27 16:27:11 +0000949 if (clang_isConstQualifiedType(T))
950 printf(" const");
951 if (clang_isVolatileQualifiedType(T))
952 printf(" volatile");
953 if (clang_isRestrictQualifiedType(T))
954 printf(" restrict");
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000955 clang_disposeString(S);
Benjamin Kramere1403d22010-06-22 09:29:44 +0000956 /* Print the canonical type if it is different. */
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000957 {
958 CXType CT = clang_getCanonicalType(T);
959 if (!clang_equalTypes(T, CT)) {
960 CXString CS = clang_getTypeKindSpelling(CT.kind);
961 printf(" [canonical=%s]", clang_getCString(CS));
962 clang_disposeString(CS);
963 }
964 }
Benjamin Kramere1403d22010-06-22 09:29:44 +0000965 /* Print the return type if it exists. */
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000966 {
Ted Kremenek9a140842010-06-21 20:48:56 +0000967 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000968 if (RT.kind != CXType_Invalid) {
969 CXString RS = clang_getTypeKindSpelling(RT.kind);
970 printf(" [result=%s]", clang_getCString(RS));
971 clang_disposeString(RS);
972 }
973 }
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +0000974 /* Print the argument types if they exist. */
975 {
976 int numArgs = clang_Cursor_getNumArguments(cursor);
977 if (numArgs != -1 && numArgs != 0) {
Argyrios Kyrtzidis47f11652012-04-11 19:54:09 +0000978 int i;
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +0000979 printf(" [args=");
Argyrios Kyrtzidis47f11652012-04-11 19:54:09 +0000980 for (i = 0; i < numArgs; ++i) {
Argyrios Kyrtzidisd98ef9a2012-04-11 19:32:19 +0000981 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
982 if (T.kind != CXType_Invalid) {
983 CXString S = clang_getTypeKindSpelling(T.kind);
984 printf(" %s", clang_getCString(S));
985 clang_disposeString(S);
986 }
987 }
988 printf("]");
989 }
990 }
Ted Kremenek3ce9e7d2010-07-30 00:14:11 +0000991 /* Print if this is a non-POD type. */
992 printf(" [isPOD=%d]", clang_isPODType(T));
Ted Kremenek04c3cf32010-06-21 20:15:39 +0000993
Ted Kremenek8e0ac172010-05-14 21:29:26 +0000994 printf("\n");
995 }
996 return CXChildVisit_Recurse;
997}
998
999
1000/******************************************************************************/
Ted Kremenek7d405622010-01-12 23:34:26 +00001001/* Loading ASTs/source. */
1002/******************************************************************************/
1003
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001004static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek98271562010-01-12 18:53:15 +00001005 const char *filter, const char *prefix,
Ted Kremenekce2ae882010-01-26 17:59:48 +00001006 CXCursorVisitor Visitor,
1007 PostVisitTU PV) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001008
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00001009 if (prefix)
Ted Kremeneke68fff62010-02-17 00:41:32 +00001010 FileCheckPrefix = prefix;
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001011
1012 if (Visitor) {
1013 enum CXCursorKind K = CXCursor_NotImplemented;
1014 enum CXCursorKind *ck = &K;
1015 VisitorData Data;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001016
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001017 /* Perform some simple filtering. */
1018 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor358559d2010-10-02 22:49:11 +00001019 else if (!strcmp(filter, "all-display") ||
1020 !strcmp(filter, "local-display")) {
1021 ck = NULL;
1022 want_display_name = 1;
1023 }
Daniel Dunbarb1ffee62010-02-10 20:42:40 +00001024 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001025 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1026 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1027 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1028 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1029 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1030 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1031 else {
1032 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1033 return 1;
1034 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001035
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001036 Data.TU = TU;
1037 Data.Filter = ck;
1038 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek0d435192009-11-17 18:13:31 +00001039 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001040
Ted Kremenekce2ae882010-01-26 17:59:48 +00001041 if (PV)
1042 PV(TU);
Ted Kremeneke3ee02a2010-01-26 17:55:33 +00001043
Douglas Gregora88084b2010-02-18 18:08:43 +00001044 PrintDiagnostics(TU);
Argyrios Kyrtzidis16ac8be2011-11-13 23:39:14 +00001045 if (checkForErrors(TU) != 0) {
1046 clang_disposeTranslationUnit(TU);
1047 return -1;
1048 }
1049
Ted Kremenek0d435192009-11-17 18:13:31 +00001050 clang_disposeTranslationUnit(TU);
1051 return 0;
1052}
1053
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00001054int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekce2ae882010-01-26 17:59:48 +00001055 const char *prefix, CXCursorVisitor Visitor,
1056 PostVisitTU PV) {
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001057 CXIndex Idx;
1058 CXTranslationUnit TU;
Ted Kremenek020a0952010-02-11 07:41:25 +00001059 int result;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001060 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001061 !strcmp(filter, "local") ? 1 : 0,
1062 /* displayDiagnosics=*/1);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001063
Ted Kremenek020a0952010-02-11 07:41:25 +00001064 if (!CreateTranslationUnit(Idx, file, &TU)) {
1065 clang_disposeIndex(Idx);
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001066 return 1;
Ted Kremenek020a0952010-02-11 07:41:25 +00001067 }
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001068
Ted Kremenek020a0952010-02-11 07:41:25 +00001069 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV);
1070 clang_disposeIndex(Idx);
1071 return result;
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00001072}
1073
Ted Kremenekce2ae882010-01-26 17:59:48 +00001074int perform_test_load_source(int argc, const char **argv,
1075 const char *filter, CXCursorVisitor Visitor,
1076 PostVisitTU PV) {
Daniel Dunbarada487d2009-12-01 02:03:10 +00001077 CXIndex Idx;
1078 CXTranslationUnit TU;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001079 struct CXUnsavedFile *unsaved_files = 0;
1080 int num_unsaved_files = 0;
1081 int result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001082
Daniel Dunbarada487d2009-12-01 02:03:10 +00001083 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor358559d2010-10-02 22:49:11 +00001084 (!strcmp(filter, "local") ||
1085 !strcmp(filter, "local-display"))? 1 : 0,
Douglas Gregor4814fb52011-02-03 23:41:12 +00001086 /* displayDiagnosics=*/0);
Daniel Dunbarada487d2009-12-01 02:03:10 +00001087
Ted Kremenek020a0952010-02-11 07:41:25 +00001088 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1089 clang_disposeIndex(Idx);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001090 return -1;
Ted Kremenek020a0952010-02-11 07:41:25 +00001091 }
Douglas Gregor4db64a42010-01-23 00:14:00 +00001092
Douglas Gregordca8ee82011-05-06 16:33:08 +00001093 TU = clang_parseTranslationUnit(Idx, 0,
1094 argv + num_unsaved_files,
1095 argc - num_unsaved_files,
1096 unsaved_files, num_unsaved_files,
1097 getDefaultParsingOptions());
Daniel Dunbarada487d2009-12-01 02:03:10 +00001098 if (!TU) {
1099 fprintf(stderr, "Unable to load translation unit!\n");
Douglas Gregorabc563f2010-07-19 21:46:24 +00001100 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek020a0952010-02-11 07:41:25 +00001101 clang_disposeIndex(Idx);
Daniel Dunbarada487d2009-12-01 02:03:10 +00001102 return 1;
1103 }
1104
Ted Kremenekce2ae882010-01-26 17:59:48 +00001105 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001106 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek020a0952010-02-11 07:41:25 +00001107 clang_disposeIndex(Idx);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001108 return result;
Daniel Dunbarada487d2009-12-01 02:03:10 +00001109}
1110
Douglas Gregorabc563f2010-07-19 21:46:24 +00001111int perform_test_reparse_source(int argc, const char **argv, int trials,
1112 const char *filter, CXCursorVisitor Visitor,
1113 PostVisitTU PV) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001114 CXIndex Idx;
1115 CXTranslationUnit TU;
1116 struct CXUnsavedFile *unsaved_files = 0;
1117 int num_unsaved_files = 0;
1118 int result;
1119 int trial;
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001120 int remap_after_trial = 0;
1121 char *endptr = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001122
1123 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1124 !strcmp(filter, "local") ? 1 : 0,
Douglas Gregor1aa27302011-01-27 18:02:58 +00001125 /* displayDiagnosics=*/0);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001126
Douglas Gregorabc563f2010-07-19 21:46:24 +00001127 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1128 clang_disposeIndex(Idx);
1129 return -1;
1130 }
1131
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001132 /* Load the initial translation unit -- we do this without honoring remapped
1133 * files, so that we have a way to test results after changing the source. */
Douglas Gregor44c181a2010-07-23 00:33:23 +00001134 TU = clang_parseTranslationUnit(Idx, 0,
1135 argv + num_unsaved_files,
1136 argc - num_unsaved_files,
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001137 0, 0, getDefaultParsingOptions());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001138 if (!TU) {
1139 fprintf(stderr, "Unable to load translation unit!\n");
1140 free_remapped_files(unsaved_files, num_unsaved_files);
1141 clang_disposeIndex(Idx);
1142 return 1;
1143 }
1144
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001145 if (checkForErrors(TU) != 0)
1146 return -1;
1147
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001148 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1149 remap_after_trial =
1150 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1151 }
1152
Douglas Gregorabc563f2010-07-19 21:46:24 +00001153 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis40098e82011-09-12 18:09:31 +00001154 if (clang_reparseTranslationUnit(TU,
1155 trial >= remap_after_trial ? num_unsaved_files : 0,
1156 trial >= remap_after_trial ? unsaved_files : 0,
Douglas Gregore1e13bf2010-08-11 15:58:42 +00001157 clang_defaultReparseOptions(TU))) {
Daniel Dunbarc8a61802010-08-18 23:09:16 +00001158 fprintf(stderr, "Unable to reparse translation unit!\n");
Douglas Gregorabc563f2010-07-19 21:46:24 +00001159 clang_disposeTranslationUnit(TU);
1160 free_remapped_files(unsaved_files, num_unsaved_files);
1161 clang_disposeIndex(Idx);
1162 return -1;
1163 }
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001164
1165 if (checkForErrors(TU) != 0)
1166 return -1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001167 }
1168
1169 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV);
Argyrios Kyrtzidisbda536d2011-11-13 22:08:33 +00001170
Douglas Gregorabc563f2010-07-19 21:46:24 +00001171 free_remapped_files(unsaved_files, num_unsaved_files);
1172 clang_disposeIndex(Idx);
1173 return result;
1174}
1175
Ted Kremenek0d435192009-11-17 18:13:31 +00001176/******************************************************************************/
Ted Kremenek1c6da172009-11-17 19:37:36 +00001177/* Logic for testing clang_getCursor(). */
1178/******************************************************************************/
1179
Douglas Gregordd3e5542011-05-04 00:14:37 +00001180static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek1c6da172009-11-17 19:37:36 +00001181 unsigned start_line, unsigned start_col,
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001182 unsigned end_line, unsigned end_col,
1183 const char *prefix) {
Ted Kremenek9096a202010-01-07 01:17:12 +00001184 printf("// %s: ", FileCheckPrefix);
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001185 if (prefix)
1186 printf("-%s", prefix);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00001187 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1188 printf(" ");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001189 PrintCursor(cursor);
Ted Kremenek1c6da172009-11-17 19:37:36 +00001190 printf("\n");
1191}
1192
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00001193static int perform_file_scan(const char *ast_file, const char *source_file,
1194 const char *prefix) {
Ted Kremenek1c6da172009-11-17 19:37:36 +00001195 CXIndex Idx;
1196 CXTranslationUnit TU;
1197 FILE *fp;
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001198 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregorb9790342010-01-22 21:44:22 +00001199 CXFile file;
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001200 unsigned line = 1, col = 1;
Daniel Dunbar8f0bf812010-02-14 08:32:51 +00001201 unsigned start_line = 1, start_col = 1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001202
Douglas Gregor0a812cf2010-02-18 23:07:20 +00001203 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
1204 /* displayDiagnosics=*/1))) {
Ted Kremenek1c6da172009-11-17 19:37:36 +00001205 fprintf(stderr, "Could not create Index\n");
1206 return 1;
1207 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001208
Ted Kremenek1c6da172009-11-17 19:37:36 +00001209 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1210 return 1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001211
Ted Kremenek1c6da172009-11-17 19:37:36 +00001212 if ((fp = fopen(source_file, "r")) == NULL) {
1213 fprintf(stderr, "Could not open '%s'\n", source_file);
1214 return 1;
1215 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001216
Douglas Gregorb9790342010-01-22 21:44:22 +00001217 file = clang_getFile(TU, source_file);
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001218 for (;;) {
1219 CXCursor cursor;
1220 int c = fgetc(fp);
Benjamin Kramera9933b92009-11-17 20:51:40 +00001221
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001222 if (c == '\n') {
1223 ++line;
1224 col = 1;
1225 } else
1226 ++col;
1227
1228 /* Check the cursor at this position, and dump the previous one if we have
1229 * found something new.
1230 */
1231 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1232 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1233 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregordd3e5542011-05-04 00:14:37 +00001234 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbard52864b2010-02-14 10:02:57 +00001235 line, col, prefix);
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001236 start_line = line;
1237 start_col = col;
Benjamin Kramera9933b92009-11-17 20:51:40 +00001238 }
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001239 if (c == EOF)
1240 break;
Benjamin Kramera9933b92009-11-17 20:51:40 +00001241
Daniel Dunbar2389eff2010-02-14 08:32:32 +00001242 prevCursor = cursor;
Ted Kremenek1c6da172009-11-17 19:37:36 +00001243 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001244
Ted Kremenek1c6da172009-11-17 19:37:36 +00001245 fclose(fp);
Douglas Gregor4f5e21e2011-01-31 22:04:05 +00001246 clang_disposeTranslationUnit(TU);
1247 clang_disposeIndex(Idx);
Ted Kremenek1c6da172009-11-17 19:37:36 +00001248 return 0;
1249}
1250
1251/******************************************************************************/
Douglas Gregor32be4a52010-10-11 21:37:58 +00001252/* Logic for testing clang code completion. */
Ted Kremenek0d435192009-11-17 18:13:31 +00001253/******************************************************************************/
1254
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001255/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1256 on failure. If successful, the pointer *filename will contain newly-allocated
1257 memory (that will be owned by the caller) to store the file name. */
Ted Kremeneke68fff62010-02-17 00:41:32 +00001258int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001259 unsigned *column, unsigned *second_line,
1260 unsigned *second_column) {
Douglas Gregor88d23952009-11-09 18:19:57 +00001261 /* Find the second colon. */
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001262 const char *last_colon = strrchr(input, ':');
1263 unsigned values[4], i;
1264 unsigned num_values = (second_line && second_column)? 4 : 2;
1265
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001266 char *endptr = 0;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001267 if (!last_colon || last_colon == input) {
1268 if (num_values == 4)
1269 fprintf(stderr, "could not parse filename:line:column:line:column in "
1270 "'%s'\n", input);
1271 else
1272 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001273 return 1;
1274 }
1275
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001276 for (i = 0; i != num_values; ++i) {
1277 const char *prev_colon;
1278
1279 /* Parse the next line or column. */
1280 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1281 if (*endptr != 0 && *endptr != ':') {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001282 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001283 (i % 2 ? "column" : "line"), input);
1284 return 1;
1285 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001286
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001287 if (i + 1 == num_values)
1288 break;
1289
1290 /* Find the previous colon. */
1291 prev_colon = last_colon - 1;
1292 while (prev_colon != input && *prev_colon != ':')
1293 --prev_colon;
1294 if (prev_colon == input) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00001295 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001296 (i % 2 == 0? "column" : "line"), input);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001297 return 1;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001298 }
1299
1300 last_colon = prev_colon;
Douglas Gregor88d23952009-11-09 18:19:57 +00001301 }
1302
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001303 *line = values[0];
1304 *column = values[1];
Ted Kremeneke68fff62010-02-17 00:41:32 +00001305
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001306 if (second_line && second_column) {
1307 *second_line = values[2];
1308 *second_column = values[3];
1309 }
1310
Douglas Gregor88d23952009-11-09 18:19:57 +00001311 /* Copy the file name. */
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001312 *filename = (char*)malloc(last_colon - input + 1);
1313 memcpy(*filename, input, last_colon - input);
1314 (*filename)[last_colon - input] = 0;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001315 return 0;
1316}
1317
1318const char *
1319clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1320 switch (Kind) {
1321 case CXCompletionChunk_Optional: return "Optional";
1322 case CXCompletionChunk_TypedText: return "TypedText";
1323 case CXCompletionChunk_Text: return "Text";
1324 case CXCompletionChunk_Placeholder: return "Placeholder";
1325 case CXCompletionChunk_Informative: return "Informative";
1326 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1327 case CXCompletionChunk_LeftParen: return "LeftParen";
1328 case CXCompletionChunk_RightParen: return "RightParen";
1329 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1330 case CXCompletionChunk_RightBracket: return "RightBracket";
1331 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1332 case CXCompletionChunk_RightBrace: return "RightBrace";
1333 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1334 case CXCompletionChunk_RightAngle: return "RightAngle";
1335 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorff5ce6e2009-12-18 18:53:37 +00001336 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor01dfea02010-01-10 23:08:15 +00001337 case CXCompletionChunk_Colon: return "Colon";
1338 case CXCompletionChunk_SemiColon: return "SemiColon";
1339 case CXCompletionChunk_Equal: return "Equal";
1340 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1341 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001342 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001343
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001344 return "Unknown";
1345}
1346
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001347static int checkForErrors(CXTranslationUnit TU) {
1348 unsigned Num, i;
1349 CXDiagnostic Diag;
1350 CXString DiagStr;
1351
1352 if (!getenv("CINDEXTEST_FAILONERROR"))
1353 return 0;
1354
1355 Num = clang_getNumDiagnostics(TU);
1356 for (i = 0; i != Num; ++i) {
1357 Diag = clang_getDiagnostic(TU, i);
1358 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1359 DiagStr = clang_formatDiagnostic(Diag,
1360 clang_defaultDiagnosticDisplayOptions());
1361 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1362 clang_disposeString(DiagStr);
1363 clang_disposeDiagnostic(Diag);
1364 return -1;
1365 }
1366 clang_disposeDiagnostic(Diag);
1367 }
1368
1369 return 0;
1370}
1371
Douglas Gregor3ac73852009-11-09 16:04:45 +00001372void print_completion_string(CXCompletionString completion_string, FILE *file) {
Daniel Dunbarf8297f12009-11-07 18:34:24 +00001373 int I, N;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001374
Douglas Gregor3ac73852009-11-09 16:04:45 +00001375 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001376 for (I = 0; I != N; ++I) {
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001377 CXString text;
1378 const char *cstr;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001379 enum CXCompletionChunkKind Kind
Douglas Gregor3ac73852009-11-09 16:04:45 +00001380 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001381
Douglas Gregor3ac73852009-11-09 16:04:45 +00001382 if (Kind == CXCompletionChunk_Optional) {
1383 fprintf(file, "{Optional ");
1384 print_completion_string(
Ted Kremeneke68fff62010-02-17 00:41:32 +00001385 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor3ac73852009-11-09 16:04:45 +00001386 file);
1387 fprintf(file, "}");
1388 continue;
Douglas Gregor5a9c0bc2010-10-08 20:39:29 +00001389 }
1390
1391 if (Kind == CXCompletionChunk_VerticalSpace) {
1392 fprintf(file, "{VerticalSpace }");
1393 continue;
Douglas Gregor3ac73852009-11-09 16:04:45 +00001394 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001395
Douglas Gregord5a20892009-11-09 17:05:28 +00001396 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001397 cstr = clang_getCString(text);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001398 fprintf(file, "{%s %s}",
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001399 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001400 cstr ? cstr : "");
1401 clang_disposeString(text);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001402 }
Ted Kremenek2ef6f8f2010-02-17 01:42:24 +00001403
Douglas Gregor3ac73852009-11-09 16:04:45 +00001404}
1405
1406void print_completion_result(CXCompletionResult *completion_result,
1407 CXClientData client_data) {
1408 FILE *file = (FILE *)client_data;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001409 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen6164ea12011-10-14 15:31:08 +00001410 unsigned annotationCount;
Douglas Gregorba103062012-03-27 23:34:16 +00001411 enum CXCursorKind ParentKind;
1412 CXString ParentName;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001413 CXString BriefComment;
1414 const char *BriefCommentCString;
Douglas Gregorba103062012-03-27 23:34:16 +00001415
Ted Kremeneke68fff62010-02-17 00:41:32 +00001416 fprintf(file, "%s:", clang_getCString(ks));
1417 clang_disposeString(ks);
1418
Douglas Gregor3ac73852009-11-09 16:04:45 +00001419 print_completion_string(completion_result->CompletionString, file);
Douglas Gregor58ddb602010-08-23 23:00:57 +00001420 fprintf(file, " (%u)",
Douglas Gregor12e13132010-05-26 22:00:08 +00001421 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregor58ddb602010-08-23 23:00:57 +00001422 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1423 case CXAvailability_Available:
1424 break;
1425
1426 case CXAvailability_Deprecated:
1427 fprintf(file, " (deprecated)");
1428 break;
1429
1430 case CXAvailability_NotAvailable:
1431 fprintf(file, " (unavailable)");
1432 break;
Erik Verbruggend1205962011-10-06 07:27:49 +00001433
1434 case CXAvailability_NotAccessible:
1435 fprintf(file, " (inaccessible)");
1436 break;
Douglas Gregor58ddb602010-08-23 23:00:57 +00001437 }
Erik Verbruggen6164ea12011-10-14 15:31:08 +00001438
1439 annotationCount = clang_getCompletionNumAnnotations(
1440 completion_result->CompletionString);
1441 if (annotationCount) {
1442 unsigned i;
1443 fprintf(file, " (");
1444 for (i = 0; i < annotationCount; ++i) {
1445 if (i != 0)
1446 fprintf(file, ", ");
1447 fprintf(file, "\"%s\"",
1448 clang_getCString(clang_getCompletionAnnotation(
1449 completion_result->CompletionString, i)));
1450 }
1451 fprintf(file, ")");
1452 }
1453
Douglas Gregorba103062012-03-27 23:34:16 +00001454 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1455 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1456 &ParentKind);
1457 if (ParentKind != CXCursor_NotImplemented) {
1458 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
1459 fprintf(file, " (parent: %s '%s')",
1460 clang_getCString(KindSpelling),
1461 clang_getCString(ParentName));
1462 clang_disposeString(KindSpelling);
1463 }
1464 clang_disposeString(ParentName);
1465 }
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001466
1467 BriefComment = clang_getCompletionBriefComment(
1468 completion_result->CompletionString);
1469 BriefCommentCString = clang_getCString(BriefComment);
1470 if (BriefCommentCString && *BriefCommentCString != '\0') {
1471 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1472 }
1473 clang_disposeString(BriefComment);
Douglas Gregorba103062012-03-27 23:34:16 +00001474
Douglas Gregor58ddb602010-08-23 23:00:57 +00001475 fprintf(file, "\n");
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001476}
1477
Douglas Gregor3da626b2011-07-07 16:03:39 +00001478void print_completion_contexts(unsigned long long contexts, FILE *file) {
1479 fprintf(file, "Completion contexts:\n");
1480 if (contexts == CXCompletionContext_Unknown) {
1481 fprintf(file, "Unknown\n");
1482 }
1483 if (contexts & CXCompletionContext_AnyType) {
1484 fprintf(file, "Any type\n");
1485 }
1486 if (contexts & CXCompletionContext_AnyValue) {
1487 fprintf(file, "Any value\n");
1488 }
1489 if (contexts & CXCompletionContext_ObjCObjectValue) {
1490 fprintf(file, "Objective-C object value\n");
1491 }
1492 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1493 fprintf(file, "Objective-C selector value\n");
1494 }
1495 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1496 fprintf(file, "C++ class type value\n");
1497 }
1498 if (contexts & CXCompletionContext_DotMemberAccess) {
1499 fprintf(file, "Dot member access\n");
1500 }
1501 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1502 fprintf(file, "Arrow member access\n");
1503 }
1504 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1505 fprintf(file, "Objective-C property access\n");
1506 }
1507 if (contexts & CXCompletionContext_EnumTag) {
1508 fprintf(file, "Enum tag\n");
1509 }
1510 if (contexts & CXCompletionContext_UnionTag) {
1511 fprintf(file, "Union tag\n");
1512 }
1513 if (contexts & CXCompletionContext_StructTag) {
1514 fprintf(file, "Struct tag\n");
1515 }
1516 if (contexts & CXCompletionContext_ClassTag) {
1517 fprintf(file, "Class name\n");
1518 }
1519 if (contexts & CXCompletionContext_Namespace) {
1520 fprintf(file, "Namespace or namespace alias\n");
1521 }
1522 if (contexts & CXCompletionContext_NestedNameSpecifier) {
1523 fprintf(file, "Nested name specifier\n");
1524 }
1525 if (contexts & CXCompletionContext_ObjCInterface) {
1526 fprintf(file, "Objective-C interface\n");
1527 }
1528 if (contexts & CXCompletionContext_ObjCProtocol) {
1529 fprintf(file, "Objective-C protocol\n");
1530 }
1531 if (contexts & CXCompletionContext_ObjCCategory) {
1532 fprintf(file, "Objective-C category\n");
1533 }
1534 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
1535 fprintf(file, "Objective-C instance method\n");
1536 }
1537 if (contexts & CXCompletionContext_ObjCClassMessage) {
1538 fprintf(file, "Objective-C class method\n");
1539 }
1540 if (contexts & CXCompletionContext_ObjCSelectorName) {
1541 fprintf(file, "Objective-C selector name\n");
1542 }
1543 if (contexts & CXCompletionContext_MacroName) {
1544 fprintf(file, "Macro name\n");
1545 }
1546 if (contexts & CXCompletionContext_NaturalLanguage) {
1547 fprintf(file, "Natural language\n");
1548 }
1549}
1550
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001551int my_stricmp(const char *s1, const char *s2) {
1552 while (*s1 && *s2) {
NAKAMURA Takumi6d555212011-03-09 03:02:28 +00001553 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001554 if (c1 < c2)
1555 return -1;
1556 else if (c1 > c2)
1557 return 1;
1558
1559 ++s1;
1560 ++s2;
1561 }
1562
1563 if (*s1)
1564 return 1;
1565 else if (*s2)
1566 return -1;
1567 return 0;
1568}
1569
Douglas Gregor1982c182010-07-12 18:38:41 +00001570int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001571 const char *input = argv[1];
1572 char *filename = 0;
1573 unsigned line;
1574 unsigned column;
Daniel Dunbarf8297f12009-11-07 18:34:24 +00001575 CXIndex CIdx;
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001576 int errorCode;
Douglas Gregor735df882009-12-02 09:21:34 +00001577 struct CXUnsavedFile *unsaved_files = 0;
1578 int num_unsaved_files = 0;
Douglas Gregorec6762c2009-12-18 16:20:58 +00001579 CXCodeCompleteResults *results = 0;
Dawn Perchik25d9b002010-09-30 22:26:05 +00001580 CXTranslationUnit TU = 0;
Douglas Gregor32be4a52010-10-11 21:37:58 +00001581 unsigned I, Repeats = 1;
1582 unsigned completionOptions = clang_defaultCodeCompleteOptions();
1583
1584 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
1585 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001586 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
1587 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregordf95a132010-08-09 20:45:32 +00001588
Douglas Gregor1982c182010-07-12 18:38:41 +00001589 if (timing_only)
1590 input += strlen("-code-completion-timing=");
1591 else
1592 input += strlen("-code-completion-at=");
1593
Ted Kremeneke68fff62010-02-17 00:41:32 +00001594 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001595 0, 0)))
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001596 return errorCode;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001597
Douglas Gregor735df882009-12-02 09:21:34 +00001598 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
1599 return -1;
1600
Douglas Gregor32be4a52010-10-11 21:37:58 +00001601 CIdx = clang_createIndex(0, 0);
1602
1603 if (getenv("CINDEXTEST_EDITING"))
1604 Repeats = 5;
1605
1606 TU = clang_parseTranslationUnit(CIdx, 0,
1607 argv + num_unsaved_files + 2,
1608 argc - num_unsaved_files - 2,
1609 0, 0, getDefaultParsingOptions());
1610 if (!TU) {
1611 fprintf(stderr, "Unable to load translation unit!\n");
1612 return 1;
1613 }
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001614
1615 if (clang_reparseTranslationUnit(TU, 0, 0, clang_defaultReparseOptions(TU))) {
1616 fprintf(stderr, "Unable to reparse translation init!\n");
1617 return 1;
1618 }
Douglas Gregor32be4a52010-10-11 21:37:58 +00001619
1620 for (I = 0; I != Repeats; ++I) {
1621 results = clang_codeCompleteAt(TU, filename, line, column,
1622 unsaved_files, num_unsaved_files,
1623 completionOptions);
1624 if (!results) {
1625 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar2de41c92010-08-19 23:44:06 +00001626 return 1;
1627 }
Douglas Gregor32be4a52010-10-11 21:37:58 +00001628 if (I != Repeats-1)
1629 clang_disposeCodeCompleteResults(results);
1630 }
Douglas Gregor936ea3b2010-01-28 00:56:43 +00001631
Douglas Gregorec6762c2009-12-18 16:20:58 +00001632 if (results) {
Douglas Gregore081a612011-07-21 01:05:26 +00001633 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor3da626b2011-07-07 16:03:39 +00001634 unsigned long long contexts;
Douglas Gregore081a612011-07-21 01:05:26 +00001635 enum CXCursorKind containerKind;
Douglas Gregor0a47d692011-07-26 15:24:30 +00001636 CXString objCSelector;
1637 const char *selectorString;
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001638 if (!timing_only) {
1639 /* Sort the code-completion results based on the typed text. */
1640 clang_sortCodeCompletionResults(results->Results, results->NumResults);
1641
Douglas Gregor1982c182010-07-12 18:38:41 +00001642 for (i = 0; i != n; ++i)
1643 print_completion_result(results->Results + i, stdout);
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001644 }
Douglas Gregora88084b2010-02-18 18:08:43 +00001645 n = clang_codeCompleteGetNumDiagnostics(results);
1646 for (i = 0; i != n; ++i) {
1647 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
1648 PrintDiagnostic(diag);
1649 clang_disposeDiagnostic(diag);
1650 }
Douglas Gregor3da626b2011-07-07 16:03:39 +00001651
1652 contexts = clang_codeCompleteGetContexts(results);
1653 print_completion_contexts(contexts, stdout);
1654
Douglas Gregor0a47d692011-07-26 15:24:30 +00001655 containerKind = clang_codeCompleteGetContainerKind(results,
1656 &containerIsIncomplete);
Douglas Gregore081a612011-07-21 01:05:26 +00001657
1658 if (containerKind != CXCursor_InvalidCode) {
1659 /* We have found a container */
1660 CXString containerUSR, containerKindSpelling;
1661 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
1662 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
1663 clang_disposeString(containerKindSpelling);
1664
1665 if (containerIsIncomplete) {
1666 printf("Container is incomplete\n");
1667 }
1668 else {
1669 printf("Container is complete\n");
1670 }
1671
1672 containerUSR = clang_codeCompleteGetContainerUSR(results);
1673 printf("Container USR: %s\n", clang_getCString(containerUSR));
1674 clang_disposeString(containerUSR);
1675 }
1676
Douglas Gregor0a47d692011-07-26 15:24:30 +00001677 objCSelector = clang_codeCompleteGetObjCSelector(results);
1678 selectorString = clang_getCString(objCSelector);
1679 if (selectorString && strlen(selectorString) > 0) {
1680 printf("Objective-C selector: %s\n", selectorString);
1681 }
1682 clang_disposeString(objCSelector);
1683
Douglas Gregorec6762c2009-12-18 16:20:58 +00001684 clang_disposeCodeCompleteResults(results);
1685 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001686 clang_disposeTranslationUnit(TU);
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001687 clang_disposeIndex(CIdx);
1688 free(filename);
Ted Kremeneke68fff62010-02-17 00:41:32 +00001689
Douglas Gregor735df882009-12-02 09:21:34 +00001690 free_remapped_files(unsaved_files, num_unsaved_files);
1691
Ted Kremenekf5d9c932009-11-17 18:09:14 +00001692 return 0;
Douglas Gregor0c8296d2009-11-07 00:00:49 +00001693}
1694
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001695typedef struct {
1696 char *filename;
1697 unsigned line;
1698 unsigned column;
1699} CursorSourceLocation;
1700
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001701static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001702 CXIndex CIdx;
1703 int errorCode;
1704 struct CXUnsavedFile *unsaved_files = 0;
1705 int num_unsaved_files = 0;
1706 CXTranslationUnit TU;
1707 CXCursor Cursor;
1708 CursorSourceLocation *Locations = 0;
1709 unsigned NumLocations = 0, Loc;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001710 unsigned Repeats = 1;
Douglas Gregorbdc4b362010-11-30 06:04:54 +00001711 unsigned I;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001712
Ted Kremeneke68fff62010-02-17 00:41:32 +00001713 /* Count the number of locations. */
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001714 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
1715 ++NumLocations;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001716
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001717 /* Parse the locations. */
1718 assert(NumLocations > 0 && "Unable to count locations?");
1719 Locations = (CursorSourceLocation *)malloc(
1720 NumLocations * sizeof(CursorSourceLocation));
1721 for (Loc = 0; Loc < NumLocations; ++Loc) {
1722 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremeneke68fff62010-02-17 00:41:32 +00001723 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
1724 &Locations[Loc].line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00001725 &Locations[Loc].column, 0, 0)))
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001726 return errorCode;
1727 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001728
1729 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001730 &num_unsaved_files))
1731 return -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001732
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001733 if (getenv("CINDEXTEST_EDITING"))
1734 Repeats = 5;
1735
1736 /* Parse the translation unit. When we're testing clang_getCursor() after
1737 reparsing, don't remap unsaved files until the second parse. */
1738 CIdx = clang_createIndex(1, 1);
1739 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
1740 argv + num_unsaved_files + 1 + NumLocations,
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001741 argc - num_unsaved_files - 2 - NumLocations,
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001742 unsaved_files,
1743 Repeats > 1? 0 : num_unsaved_files,
1744 getDefaultParsingOptions());
1745
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001746 if (!TU) {
1747 fprintf(stderr, "unable to parse input\n");
1748 return -1;
1749 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00001750
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001751 if (checkForErrors(TU) != 0)
1752 return -1;
1753
Douglas Gregorbdc4b362010-11-30 06:04:54 +00001754 for (I = 0; I != Repeats; ++I) {
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001755 if (Repeats > 1 &&
1756 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1757 clang_defaultReparseOptions(TU))) {
1758 clang_disposeTranslationUnit(TU);
1759 return 1;
1760 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001761
1762 if (checkForErrors(TU) != 0)
1763 return -1;
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001764
1765 for (Loc = 0; Loc < NumLocations; ++Loc) {
1766 CXFile file = clang_getFile(TU, Locations[Loc].filename);
1767 if (!file)
1768 continue;
Ted Kremeneke68fff62010-02-17 00:41:32 +00001769
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001770 Cursor = clang_getCursor(TU,
1771 clang_getLocation(TU, file, Locations[Loc].line,
1772 Locations[Loc].column));
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001773
1774 if (checkForErrors(TU) != 0)
1775 return -1;
1776
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001777 if (I + 1 == Repeats) {
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001778 CXCompletionString completionString = clang_getCursorCompletionString(
1779 Cursor);
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00001780 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
1781 CXString Spelling;
1782 const char *cspell;
1783 unsigned line, column;
1784 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
1785 printf("%d:%d ", line, column);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001786 PrintCursor(Cursor);
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00001787 PrintCursorExtent(Cursor);
1788 Spelling = clang_getCursorSpelling(Cursor);
1789 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00001790 if (cspell && strlen(cspell) != 0) {
1791 unsigned pieceIndex;
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00001792 printf(" Spelling=%s (", cspell);
1793 for (pieceIndex = 0; ; ++pieceIndex) {
Benjamin Kramer6c235bc2012-03-31 10:23:28 +00001794 CXSourceRange range =
1795 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidisba1da142012-03-30 20:58:35 +00001796 if (clang_Range_isNull(range))
1797 break;
1798 PrintRange(range, 0);
1799 }
1800 printf(")");
1801 }
Argyrios Kyrtzidis66373dd2012-03-30 00:19:05 +00001802 clang_disposeString(Spelling);
Argyrios Kyrtzidis34ebe1e2012-03-30 22:15:48 +00001803 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
1804 printf(" Selector index=%d",clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisf39a7ae2012-07-02 23:54:36 +00001805 if (clang_Cursor_isDynamicCall(Cursor))
1806 printf(" Dynamic-call");
1807
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001808 if (completionString != NULL) {
1809 printf("\nCompletion string: ");
1810 print_completion_string(completionString, stdout);
1811 }
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001812 printf("\n");
1813 free(Locations[Loc].filename);
1814 }
1815 }
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001816 }
Douglas Gregor8e08dec2010-11-30 05:52:55 +00001817
Douglas Gregora88084b2010-02-18 18:08:43 +00001818 PrintDiagnostics(TU);
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00001819 clang_disposeTranslationUnit(TU);
1820 clang_disposeIndex(CIdx);
1821 free(Locations);
1822 free_remapped_files(unsaved_files, num_unsaved_files);
1823 return 0;
1824}
1825
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001826static enum CXVisitorResult findFileRefsVisit(void *context,
1827 CXCursor cursor, CXSourceRange range) {
1828 if (clang_Range_isNull(range))
1829 return CXVisit_Continue;
1830
1831 PrintCursor(cursor);
1832 PrintRange(range, "");
1833 printf("\n");
1834 return CXVisit_Continue;
1835}
1836
1837static int find_file_refs_at(int argc, const char **argv) {
1838 CXIndex CIdx;
1839 int errorCode;
1840 struct CXUnsavedFile *unsaved_files = 0;
1841 int num_unsaved_files = 0;
1842 CXTranslationUnit TU;
1843 CXCursor Cursor;
1844 CursorSourceLocation *Locations = 0;
1845 unsigned NumLocations = 0, Loc;
1846 unsigned Repeats = 1;
1847 unsigned I;
1848
1849 /* Count the number of locations. */
1850 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
1851 ++NumLocations;
1852
1853 /* Parse the locations. */
1854 assert(NumLocations > 0 && "Unable to count locations?");
1855 Locations = (CursorSourceLocation *)malloc(
1856 NumLocations * sizeof(CursorSourceLocation));
1857 for (Loc = 0; Loc < NumLocations; ++Loc) {
1858 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
1859 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
1860 &Locations[Loc].line,
1861 &Locations[Loc].column, 0, 0)))
1862 return errorCode;
1863 }
1864
1865 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
1866 &num_unsaved_files))
1867 return -1;
1868
1869 if (getenv("CINDEXTEST_EDITING"))
1870 Repeats = 5;
1871
1872 /* Parse the translation unit. When we're testing clang_getCursor() after
1873 reparsing, don't remap unsaved files until the second parse. */
1874 CIdx = clang_createIndex(1, 1);
1875 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
1876 argv + num_unsaved_files + 1 + NumLocations,
1877 argc - num_unsaved_files - 2 - NumLocations,
1878 unsaved_files,
1879 Repeats > 1? 0 : num_unsaved_files,
1880 getDefaultParsingOptions());
1881
1882 if (!TU) {
1883 fprintf(stderr, "unable to parse input\n");
1884 return -1;
1885 }
1886
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001887 if (checkForErrors(TU) != 0)
1888 return -1;
1889
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001890 for (I = 0; I != Repeats; ++I) {
1891 if (Repeats > 1 &&
1892 clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1893 clang_defaultReparseOptions(TU))) {
1894 clang_disposeTranslationUnit(TU);
1895 return 1;
1896 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001897
1898 if (checkForErrors(TU) != 0)
1899 return -1;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001900
1901 for (Loc = 0; Loc < NumLocations; ++Loc) {
1902 CXFile file = clang_getFile(TU, Locations[Loc].filename);
1903 if (!file)
1904 continue;
1905
1906 Cursor = clang_getCursor(TU,
1907 clang_getLocation(TU, file, Locations[Loc].line,
1908 Locations[Loc].column));
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001909
1910 if (checkForErrors(TU) != 0)
1911 return -1;
1912
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001913 if (I + 1 == Repeats) {
Erik Verbruggen26fc0f92011-10-06 11:38:08 +00001914 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001915 PrintCursor(Cursor);
1916 printf("\n");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001917 clang_findReferencesInFile(Cursor, file, visitor);
1918 free(Locations[Loc].filename);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001919
1920 if (checkForErrors(TU) != 0)
1921 return -1;
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00001922 }
1923 }
1924 }
1925
1926 PrintDiagnostics(TU);
1927 clang_disposeTranslationUnit(TU);
1928 clang_disposeIndex(CIdx);
1929 free(Locations);
1930 free_remapped_files(unsaved_files, num_unsaved_files);
1931 return 0;
1932}
1933
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001934typedef struct {
1935 const char *check_prefix;
1936 int first_check_printed;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00001937 int fail_for_error;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001938 int abort;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001939 const char *main_filename;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001940} IndexData;
1941
1942static void printCheck(IndexData *data) {
1943 if (data->check_prefix) {
1944 if (data->first_check_printed) {
1945 printf("// %s-NEXT: ", data->check_prefix);
1946 } else {
1947 printf("// %s : ", data->check_prefix);
1948 data->first_check_printed = 1;
1949 }
1950 }
1951}
1952
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00001953static void printCXIndexFile(CXIdxClientFile file) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001954 CXString filename = clang_getFileName((CXFile)file);
1955 printf("%s", clang_getCString(filename));
1956 clang_disposeString(filename);
1957}
1958
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001959static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
1960 IndexData *index_data;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001961 CXString filename;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001962 const char *cname;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00001963 CXIdxClientFile file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001964 unsigned line, column;
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001965 int isMainFile;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001966
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001967 index_data = (IndexData *)client_data;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001968 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
1969 if (line == 0) {
1970 printf("<null loc>");
1971 return;
1972 }
Argyrios Kyrtzidisc2be04e2011-12-13 18:47:35 +00001973 if (!file) {
1974 printf("<no idxfile>");
1975 return;
1976 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001977 filename = clang_getFileName((CXFile)file);
1978 cname = clang_getCString(filename);
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001979 if (strcmp(cname, index_data->main_filename) == 0)
1980 isMainFile = 1;
1981 else
1982 isMainFile = 0;
1983 clang_disposeString(filename);
1984
1985 if (!isMainFile) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00001986 printCXIndexFile(file);
1987 printf(":");
1988 }
1989 printf("%d:%d", line, column);
1990}
1991
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00001992static unsigned digitCount(unsigned val) {
1993 unsigned c = 1;
1994 while (1) {
1995 if (val < 10)
1996 return c;
1997 ++c;
1998 val /= 10;
1999 }
2000}
2001
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002002static CXIdxClientContainer makeClientContainer(const CXIdxEntityInfo *info,
2003 CXIdxLoc loc) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002004 const char *name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002005 char *newStr;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002006 CXIdxClientFile file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002007 unsigned line, column;
2008
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002009 name = info->name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002010 if (!name)
2011 name = "<anon-tag>";
2012
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002013 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Argyrios Kyrtzidisf89bc052011-10-20 17:21:46 +00002014 /* FIXME: free these.*/
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002015 newStr = (char *)malloc(strlen(name) +
2016 digitCount(line) + digitCount(column) + 3);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002017 sprintf(newStr, "%s:%d:%d", name, line, column);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002018 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002019}
2020
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002021static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2022 CXIdxClientContainer container;
2023 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidis3e340a62011-11-16 02:35:05 +00002024 if (!container)
2025 printf("[<<NULL>>]");
2026 else
2027 printf("[%s]", (const char *)container);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002028}
2029
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002030static const char *getEntityKindString(CXIdxEntityKind kind) {
2031 switch (kind) {
2032 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2033 case CXIdxEntity_Typedef: return "typedef";
2034 case CXIdxEntity_Function: return "function";
2035 case CXIdxEntity_Variable: return "variable";
2036 case CXIdxEntity_Field: return "field";
2037 case CXIdxEntity_EnumConstant: return "enumerator";
2038 case CXIdxEntity_ObjCClass: return "objc-class";
2039 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2040 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002041 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2042 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002043 case CXIdxEntity_ObjCProperty: return "objc-property";
2044 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2045 case CXIdxEntity_Enum: return "enum";
2046 case CXIdxEntity_Struct: return "struct";
2047 case CXIdxEntity_Union: return "union";
2048 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002049 case CXIdxEntity_CXXNamespace: return "namespace";
2050 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2051 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2052 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2053 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2054 case CXIdxEntity_CXXConstructor: return "constructor";
2055 case CXIdxEntity_CXXDestructor: return "destructor";
2056 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2057 case CXIdxEntity_CXXTypeAlias: return "type-alias";
2058 }
2059 assert(0 && "Garbage entity kind");
2060 return 0;
2061}
2062
2063static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2064 switch (kind) {
2065 case CXIdxEntity_NonTemplate: return "";
2066 case CXIdxEntity_Template: return "-template";
2067 case CXIdxEntity_TemplatePartialSpecialization:
2068 return "-template-partial-spec";
2069 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002070 }
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002071 assert(0 && "Garbage entity kind");
2072 return 0;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002073}
2074
Argyrios Kyrtzidis838d3c22011-12-07 20:44:12 +00002075static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2076 switch (kind) {
2077 case CXIdxEntityLang_None: return "<none>";
2078 case CXIdxEntityLang_C: return "C";
2079 case CXIdxEntityLang_ObjC: return "ObjC";
2080 case CXIdxEntityLang_CXX: return "C++";
2081 }
2082 assert(0 && "Garbage language kind");
2083 return 0;
2084}
2085
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002086static void printEntityInfo(const char *cb,
2087 CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002088 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002089 const char *name;
2090 IndexData *index_data;
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002091 unsigned i;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002092 index_data = (IndexData *)client_data;
2093 printCheck(index_data);
2094
Argyrios Kyrtzidisc6b4a502011-11-16 02:34:59 +00002095 if (!info) {
2096 printf("%s: <<NULL>>", cb);
2097 return;
2098 }
2099
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002100 name = info->name;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002101 if (!name)
2102 name = "<anon-tag>";
2103
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002104 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2105 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002106 printf(" | name: %s", name);
2107 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisc2be04e2011-12-13 18:47:35 +00002108 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis643d3ce2011-12-15 00:05:00 +00002109
2110 for (i = 0; i != info->numAttributes; ++i) {
2111 const CXIdxAttrInfo *Attr = info->attributes[i];
2112 printf(" <attribute>: ");
2113 PrintCursor(Attr->cursor);
2114 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002115}
2116
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002117static void printBaseClassInfo(CXClientData client_data,
2118 const CXIdxBaseClassInfo *info) {
2119 printEntityInfo(" <base>", client_data, info->base);
2120 printf(" | cursor: ");
2121 PrintCursor(info->cursor);
2122 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002123 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002124}
2125
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002126static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2127 CXClientData client_data) {
2128 unsigned i;
2129 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2130 printEntityInfo(" <protocol>", client_data,
2131 ProtoInfo->protocols[i]->protocol);
2132 printf(" | cursor: ");
2133 PrintCursor(ProtoInfo->protocols[i]->cursor);
2134 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002135 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002136 printf("\n");
2137 }
2138}
2139
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002140static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002141 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002142 CXString str;
2143 const char *cstr;
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002144 unsigned numDiags, i;
2145 CXDiagnostic diag;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002146 IndexData *index_data;
2147 index_data = (IndexData *)client_data;
2148 printCheck(index_data);
2149
Argyrios Kyrtzidis996e6e52011-12-01 02:42:50 +00002150 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2151 for (i = 0; i != numDiags; ++i) {
2152 diag = clang_getDiagnosticInSet(diagSet, i);
2153 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2154 cstr = clang_getCString(str);
2155 printf("[diagnostic]: %s\n", cstr);
2156 clang_disposeString(str);
2157
2158 if (getenv("CINDEXTEST_FAILONERROR") &&
2159 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2160 index_data->fail_for_error = 1;
2161 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002162 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002163}
2164
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002165static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2166 CXFile file, void *reserved) {
2167 IndexData *index_data;
Argyrios Kyrtzidis62d7fea2012-03-15 18:48:52 +00002168 CXString filename;
2169
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002170 index_data = (IndexData *)client_data;
2171 printCheck(index_data);
2172
Argyrios Kyrtzidis62d7fea2012-03-15 18:48:52 +00002173 filename = clang_getFileName(file);
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002174 index_data->main_filename = clang_getCString(filename);
2175 clang_disposeString(filename);
2176
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002177 printf("[enteredMainFile]: ");
2178 printCXIndexFile((CXIdxClientFile)file);
2179 printf("\n");
2180
2181 return (CXIdxClientFile)file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002182}
2183
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002184static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002185 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002186 IndexData *index_data;
2187 index_data = (IndexData *)client_data;
2188 printCheck(index_data);
2189
Argyrios Kyrtzidis66042b32011-11-05 04:03:35 +00002190 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002191 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002192 printf(" | name: \"%s\"", info->filename);
2193 printf(" | hash loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002194 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002195 printf(" | isImport: %d | isAngled: %d\n", info->isImport, info->isAngled);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002196
2197 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002198}
2199
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002200static CXIdxClientContainer index_startedTranslationUnit(CXClientData client_data,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002201 void *reserved) {
2202 IndexData *index_data;
2203 index_data = (IndexData *)client_data;
2204 printCheck(index_data);
2205
Argyrios Kyrtzidis66042b32011-11-05 04:03:35 +00002206 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002207 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002208}
2209
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002210static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002211 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002212 IndexData *index_data;
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002213 const CXIdxObjCCategoryDeclInfo *CatInfo;
2214 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002215 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis792db262012-02-28 17:50:33 +00002216 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002217 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002218 unsigned i;
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002219 index_data = (IndexData *)client_data;
2220
2221 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2222 printf(" | cursor: ");
2223 PrintCursor(info->cursor);
2224 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002225 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb1febb62011-12-07 20:44:19 +00002226 printf(" | semantic-container: ");
2227 printCXIndexContainer(info->semanticContainer);
2228 printf(" | lexical-container: ");
2229 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002230 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002231 printf(" | isDef: %d", info->isDefinition);
2232 printf(" | isContainer: %d", info->isContainer);
2233 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002234
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002235 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi87adb0b2011-11-18 00:51:03 +00002236 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002237 printf(" <attribute>: ");
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002238 PrintCursor(Attr->cursor);
2239 printf("\n");
2240 }
2241
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002242 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2243 const char *kindName = 0;
2244 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2245 switch (K) {
2246 case CXIdxObjCContainer_ForwardRef:
2247 kindName = "forward-ref"; break;
2248 case CXIdxObjCContainer_Interface:
2249 kindName = "interface"; break;
2250 case CXIdxObjCContainer_Implementation:
2251 kindName = "implementation"; break;
2252 }
2253 printCheck(index_data);
2254 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2255 }
2256
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002257 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002258 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
2259 CatInfo->objcClass);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002260 printf(" | cursor: ");
2261 PrintCursor(CatInfo->classCursor);
2262 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002263 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002264 printf("\n");
2265 }
2266
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002267 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
2268 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002269 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002270 printf("\n");
2271 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002272 }
2273
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002274 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
2275 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002276 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002277
Argyrios Kyrtzidis792db262012-02-28 17:50:33 +00002278 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
2279 if (PropInfo->getter) {
2280 printEntityInfo(" <getter>", client_data, PropInfo->getter);
2281 printf("\n");
2282 }
2283 if (PropInfo->setter) {
2284 printEntityInfo(" <setter>", client_data, PropInfo->setter);
2285 printf("\n");
2286 }
2287 }
2288
Argyrios Kyrtzidisb526a872011-12-07 20:44:15 +00002289 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
2290 for (i = 0; i != CXXClassInfo->numBases; ++i) {
2291 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
2292 printf("\n");
2293 }
2294 }
2295
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002296 if (info->declAsContainer)
2297 clang_index_setClientContainer(info->declAsContainer,
2298 makeClientContainer(info->entityInfo, info->loc));
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002299}
2300
2301static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis6ec43ad2011-11-12 02:16:30 +00002302 const CXIdxEntityRefInfo *info) {
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002303 printEntityInfo("[indexEntityReference]", client_data, info->referencedEntity);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002304 printf(" | cursor: ");
2305 PrintCursor(info->cursor);
2306 printf(" | loc: ");
Argyrios Kyrtzidis13c20a72012-03-15 18:07:22 +00002307 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002308 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002309 printf(" | container: ");
2310 printCXIndexContainer(info->container);
Argyrios Kyrtzidisc71d5542011-11-14 22:39:19 +00002311 printf(" | refkind: ");
Argyrios Kyrtzidisaca19be2011-10-18 15:50:50 +00002312 switch (info->kind) {
2313 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002314 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidisaca19be2011-10-18 15:50:50 +00002315 }
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002316 printf("\n");
2317}
2318
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002319static int index_abortQuery(CXClientData client_data, void *reserved) {
2320 IndexData *index_data;
2321 index_data = (IndexData *)client_data;
2322 return index_data->abort;
2323}
2324
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002325static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002326 index_abortQuery,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002327 index_diagnostic,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002328 index_enteredMainFile,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002329 index_ppIncludedFile,
Argyrios Kyrtzidisf89bc052011-10-20 17:21:46 +00002330 0, /*importedASTFile*/
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002331 index_startedTranslationUnit,
Argyrios Kyrtzidisdd93c592011-11-11 00:23:36 +00002332 index_indexDeclaration,
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002333 index_indexEntityReference
2334};
2335
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002336static unsigned getIndexOptions(void) {
2337 unsigned index_opts;
2338 index_opts = 0;
2339 if (getenv("CINDEXTEST_SUPPRESSREFS"))
2340 index_opts |= CXIndexOpt_SuppressRedundantRefs;
2341 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
2342 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
2343
2344 return index_opts;
2345}
2346
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002347static int index_file(int argc, const char **argv) {
2348 const char *check_prefix;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002349 CXIndex Idx;
2350 CXIndexAction idxAction;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002351 IndexData index_data;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002352 unsigned index_opts;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002353 int result;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002354
2355 check_prefix = 0;
2356 if (argc > 0) {
2357 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2358 check_prefix = argv[0] + strlen("-check-prefix=");
2359 ++argv;
2360 --argc;
2361 }
2362 }
2363
2364 if (argc == 0) {
2365 fprintf(stderr, "no compiler arguments\n");
2366 return -1;
2367 }
2368
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002369 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2370 /* displayDiagnosics=*/1))) {
2371 fprintf(stderr, "Could not create Index\n");
2372 return 1;
2373 }
2374 idxAction = 0;
2375 result = 1;
2376
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002377 index_data.check_prefix = check_prefix;
2378 index_data.first_check_printed = 0;
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002379 index_data.fail_for_error = 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002380 index_data.abort = 0;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002381
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002382 index_opts = getIndexOptions();
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002383 idxAction = clang_IndexAction_create(Idx);
2384 result = clang_indexSourceFile(idxAction, &index_data,
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002385 &IndexCB,sizeof(IndexCB), index_opts,
Argyrios Kyrtzidisc6b4a502011-11-16 02:34:59 +00002386 0, argv, argc, 0, 0, 0, 0);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002387 if (index_data.fail_for_error)
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002388 result = -1;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002389
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002390 clang_IndexAction_dispose(idxAction);
2391 clang_disposeIndex(Idx);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002392 return result;
2393}
2394
2395static int index_tu(int argc, const char **argv) {
2396 CXIndex Idx;
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002397 CXIndexAction idxAction;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002398 CXTranslationUnit TU;
2399 const char *check_prefix;
2400 IndexData index_data;
Argyrios Kyrtzidisb395c632011-11-18 00:26:51 +00002401 unsigned index_opts;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002402 int result;
2403
2404 check_prefix = 0;
2405 if (argc > 0) {
2406 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
2407 check_prefix = argv[0] + strlen("-check-prefix=");
2408 ++argv;
2409 --argc;
2410 }
2411 }
2412
2413 if (argc == 0) {
2414 fprintf(stderr, "no ast file\n");
2415 return -1;
2416 }
2417
2418 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
2419 /* displayDiagnosics=*/1))) {
2420 fprintf(stderr, "Could not create Index\n");
2421 return 1;
2422 }
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002423 idxAction = 0;
2424 result = 1;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002425
2426 if (!CreateTranslationUnit(Idx, argv[0], &TU))
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002427 goto finished;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002428
2429 index_data.check_prefix = check_prefix;
2430 index_data.first_check_printed = 0;
2431 index_data.fail_for_error = 0;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00002432 index_data.abort = 0;
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00002433
Argyrios Kyrtzidis22490742012-01-14 00:11:49 +00002434 index_opts = getIndexOptions();
Argyrios Kyrtzidis2957e6f2011-11-22 07:24:51 +00002435 idxAction = clang_IndexAction_create(Idx);
2436 result = clang_indexTranslationUnit(idxAction, &index_data,
2437 &IndexCB,sizeof(IndexCB),
2438 index_opts, TU);
2439 if (index_data.fail_for_error)
2440 goto finished;
2441
2442 finished:
2443 clang_IndexAction_dispose(idxAction);
2444 clang_disposeIndex(Idx);
2445
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002446 return result;
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00002447}
2448
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002449int perform_token_annotation(int argc, const char **argv) {
2450 const char *input = argv[1];
2451 char *filename = 0;
2452 unsigned line, second_line;
2453 unsigned column, second_column;
2454 CXIndex CIdx;
2455 CXTranslationUnit TU = 0;
2456 int errorCode;
2457 struct CXUnsavedFile *unsaved_files = 0;
2458 int num_unsaved_files = 0;
2459 CXToken *tokens;
2460 unsigned num_tokens;
2461 CXSourceRange range;
2462 CXSourceLocation startLoc, endLoc;
2463 CXFile file = 0;
2464 CXCursor *cursors = 0;
2465 unsigned i;
2466
2467 input += strlen("-test-annotate-tokens=");
2468 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
2469 &second_line, &second_column)))
2470 return errorCode;
2471
Richard Smithe07c5f82012-07-05 08:20:49 +00002472 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
2473 free(filename);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002474 return -1;
Richard Smithe07c5f82012-07-05 08:20:49 +00002475 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002476
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002477 CIdx = clang_createIndex(0, 1);
Douglas Gregordca8ee82011-05-06 16:33:08 +00002478 TU = clang_parseTranslationUnit(CIdx, argv[argc - 1],
2479 argv + num_unsaved_files + 2,
2480 argc - num_unsaved_files - 3,
2481 unsaved_files,
2482 num_unsaved_files,
2483 getDefaultParsingOptions());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002484 if (!TU) {
2485 fprintf(stderr, "unable to parse input\n");
2486 clang_disposeIndex(CIdx);
2487 free(filename);
2488 free_remapped_files(unsaved_files, num_unsaved_files);
2489 return -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002490 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002491 errorCode = 0;
2492
Richard Smithe07c5f82012-07-05 08:20:49 +00002493 if (checkForErrors(TU) != 0) {
2494 errorCode = -1;
2495 goto teardown;
2496 }
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002497
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002498 if (getenv("CINDEXTEST_EDITING")) {
2499 for (i = 0; i < 5; ++i) {
2500 if (clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2501 clang_defaultReparseOptions(TU))) {
2502 fprintf(stderr, "Unable to reparse translation unit!\n");
2503 errorCode = -1;
2504 goto teardown;
2505 }
2506 }
2507 }
2508
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002509 if (checkForErrors(TU) != 0) {
2510 errorCode = -1;
2511 goto teardown;
2512 }
2513
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002514 file = clang_getFile(TU, filename);
2515 if (!file) {
2516 fprintf(stderr, "file %s is not in this translation unit\n", filename);
2517 errorCode = -1;
2518 goto teardown;
2519 }
2520
2521 startLoc = clang_getLocation(TU, file, line, column);
2522 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002523 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002524 column);
2525 errorCode = -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002526 goto teardown;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002527 }
2528
2529 endLoc = clang_getLocation(TU, file, second_line, second_column);
2530 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002531 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002532 second_line, second_column);
2533 errorCode = -1;
Ted Kremeneke68fff62010-02-17 00:41:32 +00002534 goto teardown;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002535 }
2536
2537 range = clang_getRange(startLoc, endLoc);
2538 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002539
2540 if (checkForErrors(TU) != 0) {
2541 errorCode = -1;
2542 goto teardown;
2543 }
2544
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002545 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
2546 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisdfca64d2011-10-28 22:54:36 +00002547
2548 if (checkForErrors(TU) != 0) {
2549 errorCode = -1;
2550 goto teardown;
2551 }
2552
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002553 for (i = 0; i != num_tokens; ++i) {
2554 const char *kind = "<unknown>";
2555 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
2556 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
2557 unsigned start_line, start_column, end_line, end_column;
2558
2559 switch (clang_getTokenKind(tokens[i])) {
2560 case CXToken_Punctuation: kind = "Punctuation"; break;
2561 case CXToken_Keyword: kind = "Keyword"; break;
2562 case CXToken_Identifier: kind = "Identifier"; break;
2563 case CXToken_Literal: kind = "Literal"; break;
2564 case CXToken_Comment: kind = "Comment"; break;
2565 }
Douglas Gregora9b06d42010-11-09 06:24:54 +00002566 clang_getSpellingLocation(clang_getRangeStart(extent),
2567 0, &start_line, &start_column, 0);
2568 clang_getSpellingLocation(clang_getRangeEnd(extent),
2569 0, &end_line, &end_column, 0);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00002570 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Kramer342742a2012-04-14 09:11:51 +00002571 clang_disposeString(spelling);
Daniel Dunbar51b058c2010-02-14 08:32:24 +00002572 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002573 if (!clang_isInvalid(cursors[i].kind)) {
2574 printf(" ");
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00002575 PrintCursor(cursors[i]);
Douglas Gregor0045e9f2010-01-26 18:31:56 +00002576 }
2577 printf("\n");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002578 }
2579 free(cursors);
Ted Kremenek93f5e6a2010-10-20 21:22:15 +00002580 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002581
2582 teardown:
Douglas Gregora88084b2010-02-18 18:08:43 +00002583 PrintDiagnostics(TU);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00002584 clang_disposeTranslationUnit(TU);
2585 clang_disposeIndex(CIdx);
2586 free(filename);
2587 free_remapped_files(unsaved_files, num_unsaved_files);
2588 return errorCode;
2589}
2590
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002591static int
2592perform_test_compilation_db(const char *database, int argc, const char **argv) {
2593 CXCompilationDatabase db;
2594 CXCompileCommands CCmds;
2595 CXCompileCommand CCmd;
2596 CXCompilationDatabase_Error ec;
2597 CXString wd;
2598 CXString arg;
2599 int errorCode = 0;
2600 char *tmp;
2601 unsigned len;
2602 char *buildDir;
2603 int i, j, a, numCmds, numArgs;
2604
2605 len = strlen(database);
2606 tmp = (char *) malloc(len+1);
2607 memcpy(tmp, database, len+1);
2608 buildDir = dirname(tmp);
2609
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002610 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002611
2612 if (db) {
2613
2614 if (ec!=CXCompilationDatabase_NoError) {
2615 printf("unexpected error %d code while loading compilation database\n", ec);
2616 errorCode = -1;
2617 goto cdb_end;
2618 }
2619
2620 for (i=0; i<argc && errorCode==0; ) {
2621 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002622 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002623
2624 if (!CCmds) {
2625 printf("file %s not found in compilation db\n", argv[i+1]);
2626 errorCode = -1;
2627 break;
2628 }
2629
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002630 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002631
2632 if (numCmds==0) {
2633 fprintf(stderr, "should not get an empty compileCommand set for file"
2634 " '%s'\n", argv[i+1]);
2635 errorCode = -1;
2636 break;
2637 }
2638
2639 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002640 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002641
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002642 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002643 printf("workdir:'%s'", clang_getCString(wd));
2644 clang_disposeString(wd);
2645
2646 printf(" cmdline:'");
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002647 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002648 for (a=0; a<numArgs; ++a) {
2649 if (a) printf(" ");
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002650 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002651 printf("%s", clang_getCString(arg));
2652 clang_disposeString(arg);
2653 }
2654 printf("'\n");
2655 }
2656
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002657 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002658
2659 i += 2;
2660 }
2661 }
Arnaud A. de Grandmaisonc70851b2012-07-03 20:38:12 +00002662 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00002663 } else {
2664 printf("database loading failed with error code %d.\n", ec);
2665 errorCode = -1;
2666 }
2667
2668cdb_end:
2669 free(tmp);
2670
2671 return errorCode;
2672}
2673
Ted Kremenek0d435192009-11-17 18:13:31 +00002674/******************************************************************************/
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002675/* USR printing. */
2676/******************************************************************************/
2677
2678static int insufficient_usr(const char *kind, const char *usage) {
2679 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
2680 return 1;
2681}
2682
2683static unsigned isUSR(const char *s) {
2684 return s[0] == 'c' && s[1] == ':';
2685}
2686
2687static int not_usr(const char *s, const char *arg) {
2688 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
2689 return 1;
2690}
2691
2692static void print_usr(CXString usr) {
2693 const char *s = clang_getCString(usr);
2694 printf("%s\n", s);
2695 clang_disposeString(usr);
2696}
2697
2698static void display_usrs() {
2699 fprintf(stderr, "-print-usrs options:\n"
2700 " ObjCCategory <class name> <category name>\n"
2701 " ObjCClass <class name>\n"
2702 " ObjCIvar <ivar name> <class USR>\n"
2703 " ObjCMethod <selector> [0=class method|1=instance method] "
2704 "<class USR>\n"
2705 " ObjCProperty <property name> <class USR>\n"
2706 " ObjCProtocol <protocol name>\n");
2707}
2708
2709int print_usrs(const char **I, const char **E) {
2710 while (I != E) {
2711 const char *kind = *I;
2712 unsigned len = strlen(kind);
2713 switch (len) {
2714 case 8:
2715 if (memcmp(kind, "ObjCIvar", 8) == 0) {
2716 if (I + 2 >= E)
2717 return insufficient_usr(kind, "<ivar name> <class USR>");
2718 if (!isUSR(I[2]))
2719 return not_usr("<class USR>", I[2]);
2720 else {
2721 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002722 x.data = (void*) I[2];
Ted Kremeneked122732010-11-16 01:56:27 +00002723 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002724 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
2725 }
2726
2727 I += 3;
2728 continue;
2729 }
2730 break;
2731 case 9:
2732 if (memcmp(kind, "ObjCClass", 9) == 0) {
2733 if (I + 1 >= E)
2734 return insufficient_usr(kind, "<class name>");
2735 print_usr(clang_constructUSR_ObjCClass(I[1]));
2736 I += 2;
2737 continue;
2738 }
2739 break;
2740 case 10:
2741 if (memcmp(kind, "ObjCMethod", 10) == 0) {
2742 if (I + 3 >= E)
2743 return insufficient_usr(kind, "<method selector> "
2744 "[0=class method|1=instance method] <class USR>");
2745 if (!isUSR(I[3]))
2746 return not_usr("<class USR>", I[3]);
2747 else {
2748 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002749 x.data = (void*) I[3];
Ted Kremeneked122732010-11-16 01:56:27 +00002750 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002751 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
2752 }
2753 I += 4;
2754 continue;
2755 }
2756 break;
2757 case 12:
2758 if (memcmp(kind, "ObjCCategory", 12) == 0) {
2759 if (I + 2 >= E)
2760 return insufficient_usr(kind, "<class name> <category name>");
2761 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
2762 I += 3;
2763 continue;
2764 }
2765 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
2766 if (I + 1 >= E)
2767 return insufficient_usr(kind, "<protocol name>");
2768 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
2769 I += 2;
2770 continue;
2771 }
2772 if (memcmp(kind, "ObjCProperty", 12) == 0) {
2773 if (I + 2 >= E)
2774 return insufficient_usr(kind, "<property name> <class USR>");
2775 if (!isUSR(I[2]))
2776 return not_usr("<class USR>", I[2]);
2777 else {
2778 CXString x;
Ted Kremeneka60ed472010-11-16 08:15:36 +00002779 x.data = (void*) I[2];
Ted Kremeneked122732010-11-16 01:56:27 +00002780 x.private_flags = 0;
Ted Kremenekf7b714d2010-03-25 02:00:39 +00002781 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
2782 }
2783 I += 3;
2784 continue;
2785 }
2786 break;
2787 default:
2788 break;
2789 }
2790 break;
2791 }
2792
2793 if (I != E) {
2794 fprintf(stderr, "Invalid USR kind: %s\n", *I);
2795 display_usrs();
2796 return 1;
2797 }
2798 return 0;
2799}
2800
2801int print_usrs_file(const char *file_name) {
2802 char line[2048];
2803 const char *args[128];
2804 unsigned numChars = 0;
2805
2806 FILE *fp = fopen(file_name, "r");
2807 if (!fp) {
2808 fprintf(stderr, "error: cannot open '%s'\n", file_name);
2809 return 1;
2810 }
2811
2812 /* This code is not really all that safe, but it works fine for testing. */
2813 while (!feof(fp)) {
2814 char c = fgetc(fp);
2815 if (c == '\n') {
2816 unsigned i = 0;
2817 const char *s = 0;
2818
2819 if (numChars == 0)
2820 continue;
2821
2822 line[numChars] = '\0';
2823 numChars = 0;
2824
2825 if (line[0] == '/' && line[1] == '/')
2826 continue;
2827
2828 s = strtok(line, " ");
2829 while (s) {
2830 args[i] = s;
2831 ++i;
2832 s = strtok(0, " ");
2833 }
2834 if (print_usrs(&args[0], &args[i]))
2835 return 1;
2836 }
2837 else
2838 line[numChars++] = c;
2839 }
2840
2841 fclose(fp);
2842 return 0;
2843}
2844
2845/******************************************************************************/
Ted Kremenek0d435192009-11-17 18:13:31 +00002846/* Command line processing. */
2847/******************************************************************************/
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002848int write_pch_file(const char *filename, int argc, const char *argv[]) {
2849 CXIndex Idx;
2850 CXTranslationUnit TU;
2851 struct CXUnsavedFile *unsaved_files = 0;
2852 int num_unsaved_files = 0;
Francois Pichet08aa6222011-07-06 22:09:44 +00002853 int result = 0;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002854
2855 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnosics=*/1);
2856
2857 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
2858 clang_disposeIndex(Idx);
2859 return -1;
2860 }
2861
2862 TU = clang_parseTranslationUnit(Idx, 0,
2863 argv + num_unsaved_files,
2864 argc - num_unsaved_files,
2865 unsaved_files,
2866 num_unsaved_files,
2867 CXTranslationUnit_Incomplete);
2868 if (!TU) {
2869 fprintf(stderr, "Unable to load translation unit!\n");
2870 free_remapped_files(unsaved_files, num_unsaved_files);
2871 clang_disposeIndex(Idx);
2872 return 1;
2873 }
2874
Douglas Gregor39c411f2011-07-06 16:43:36 +00002875 switch (clang_saveTranslationUnit(TU, filename,
2876 clang_defaultSaveOptions(TU))) {
2877 case CXSaveError_None:
2878 break;
2879
2880 case CXSaveError_TranslationErrors:
2881 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
2882 filename);
2883 result = 2;
2884 break;
2885
2886 case CXSaveError_InvalidTU:
2887 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
2888 filename);
2889 result = 3;
2890 break;
2891
2892 case CXSaveError_Unknown:
2893 default:
2894 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
2895 result = 1;
2896 break;
2897 }
2898
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002899 clang_disposeTranslationUnit(TU);
2900 free_remapped_files(unsaved_files, num_unsaved_files);
2901 clang_disposeIndex(Idx);
Douglas Gregor39c411f2011-07-06 16:43:36 +00002902 return result;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002903}
2904
2905/******************************************************************************/
Ted Kremenek15322172011-11-10 08:43:12 +00002906/* Serialized diagnostics. */
2907/******************************************************************************/
2908
2909static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
2910 switch (error) {
2911 case CXLoadDiag_CannotLoad: return "Cannot Load File";
2912 case CXLoadDiag_None: break;
2913 case CXLoadDiag_Unknown: return "Unknown";
2914 case CXLoadDiag_InvalidFile: return "Invalid File";
2915 }
2916 return "None";
2917}
2918
2919static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
2920 switch (severity) {
2921 case CXDiagnostic_Note: return "note";
2922 case CXDiagnostic_Error: return "error";
2923 case CXDiagnostic_Fatal: return "fatal";
2924 case CXDiagnostic_Ignored: return "ignored";
2925 case CXDiagnostic_Warning: return "warning";
2926 }
2927 return "unknown";
2928}
2929
2930static void printIndent(unsigned indent) {
Ted Kremeneka7e8a832011-11-11 00:46:43 +00002931 if (indent == 0)
2932 return;
2933 fprintf(stderr, "+");
2934 --indent;
Ted Kremenek15322172011-11-10 08:43:12 +00002935 while (indent > 0) {
Ted Kremeneka7e8a832011-11-11 00:46:43 +00002936 fprintf(stderr, "-");
Ted Kremenek15322172011-11-10 08:43:12 +00002937 --indent;
2938 }
2939}
2940
2941static void printLocation(CXSourceLocation L) {
2942 CXFile File;
2943 CXString FileName;
2944 unsigned line, column, offset;
2945
2946 clang_getExpansionLocation(L, &File, &line, &column, &offset);
2947 FileName = clang_getFileName(File);
2948
2949 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
2950 clang_disposeString(FileName);
2951}
2952
2953static void printRanges(CXDiagnostic D, unsigned indent) {
2954 unsigned i, n = clang_getDiagnosticNumRanges(D);
2955
2956 for (i = 0; i < n; ++i) {
2957 CXSourceLocation Start, End;
2958 CXSourceRange SR = clang_getDiagnosticRange(D, i);
2959 Start = clang_getRangeStart(SR);
2960 End = clang_getRangeEnd(SR);
2961
2962 printIndent(indent);
2963 fprintf(stderr, "Range: ");
2964 printLocation(Start);
2965 fprintf(stderr, " ");
2966 printLocation(End);
2967 fprintf(stderr, "\n");
2968 }
2969}
2970
2971static void printFixIts(CXDiagnostic D, unsigned indent) {
2972 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek3739b322012-03-20 20:49:45 +00002973 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenek15322172011-11-10 08:43:12 +00002974 for (i = 0 ; i < n; ++i) {
2975 CXSourceRange ReplacementRange;
2976 CXString text;
2977 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
2978
2979 printIndent(indent);
2980 fprintf(stderr, "FIXIT: (");
2981 printLocation(clang_getRangeStart(ReplacementRange));
2982 fprintf(stderr, " - ");
2983 printLocation(clang_getRangeEnd(ReplacementRange));
2984 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
2985 clang_disposeString(text);
2986 }
2987}
2988
2989static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi91909432011-11-10 09:30:15 +00002990 unsigned i, n;
2991
Ted Kremenek15322172011-11-10 08:43:12 +00002992 if (!Diags)
2993 return;
2994
NAKAMURA Takumi91909432011-11-10 09:30:15 +00002995 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenek15322172011-11-10 08:43:12 +00002996 for (i = 0; i < n; ++i) {
2997 CXSourceLocation DiagLoc;
2998 CXDiagnostic D;
2999 CXFile File;
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003000 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenek15322172011-11-10 08:43:12 +00003001 unsigned line, column, offset;
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003002 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenek15322172011-11-10 08:43:12 +00003003
3004 D = clang_getDiagnosticInSet(Diags, i);
3005 DiagLoc = clang_getDiagnosticLocation(D);
3006 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3007 FileName = clang_getFileName(File);
3008 DiagSpelling = clang_getDiagnosticSpelling(D);
3009
3010 printIndent(indent);
3011
3012 fprintf(stderr, "%s:%d:%d: %s: %s",
3013 clang_getCString(FileName),
3014 line,
3015 column,
3016 getSeverityString(clang_getDiagnosticSeverity(D)),
3017 clang_getCString(DiagSpelling));
3018
3019 DiagOption = clang_getDiagnosticOption(D, 0);
3020 DiagOptionStr = clang_getCString(DiagOption);
3021 if (DiagOptionStr) {
3022 fprintf(stderr, " [%s]", DiagOptionStr);
3023 }
3024
Ted Kremenek78d5d3b2012-04-12 00:03:31 +00003025 DiagCat = clang_getDiagnosticCategoryText(D);
3026 DiagCatStr = clang_getCString(DiagCat);
3027 if (DiagCatStr) {
3028 fprintf(stderr, " [%s]", DiagCatStr);
3029 }
3030
Ted Kremenek15322172011-11-10 08:43:12 +00003031 fprintf(stderr, "\n");
3032
3033 printRanges(D, indent);
3034 printFixIts(D, indent);
3035
NAKAMURA Takumia4ca95a2011-11-10 10:07:57 +00003036 /* Print subdiagnostics. */
Ted Kremenek15322172011-11-10 08:43:12 +00003037 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3038
3039 clang_disposeString(FileName);
3040 clang_disposeString(DiagSpelling);
3041 clang_disposeString(DiagOption);
3042 }
3043}
3044
3045static int read_diagnostics(const char *filename) {
3046 enum CXLoadDiag_Error error;
3047 CXString errorString;
3048 CXDiagnosticSet Diags = 0;
3049
3050 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3051 if (!Diags) {
3052 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3053 getDiagnosticCodeStr(error),
3054 clang_getCString(errorString));
3055 clang_disposeString(errorString);
3056 return 1;
3057 }
3058
3059 printDiagnosticSet(Diags, 0);
Ted Kremeneka7e8a832011-11-11 00:46:43 +00003060 fprintf(stderr, "Number of diagnostics: %d\n",
3061 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenek15322172011-11-10 08:43:12 +00003062 clang_disposeDiagnosticSet(Diags);
3063 return 0;
3064}
3065
3066/******************************************************************************/
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003067/* Command line processing. */
3068/******************************************************************************/
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003069
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003070static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek7d405622010-01-12 23:34:26 +00003071 if (s[0] == '\0')
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003072 return FilteredPrintingVisitor;
Ted Kremenek7d405622010-01-12 23:34:26 +00003073 if (strcmp(s, "-usrs") == 0)
3074 return USRVisitor;
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003075 if (strncmp(s, "-memory-usage", 13) == 0)
3076 return GetVisitor(s + 13);
Ted Kremenek7d405622010-01-12 23:34:26 +00003077 return NULL;
3078}
3079
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003080static void print_usage(void) {
3081 fprintf(stderr,
Ted Kremenek0d435192009-11-17 18:13:31 +00003082 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003083 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003084 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003085 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003086 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00003087 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00003088 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen26fc0f92011-10-06 11:38:08 +00003089 "[FileCheck prefix]\n");
3090 fprintf(stderr,
Ted Kremenekfe6fd3d2010-01-05 23:18:49 +00003091 " c-index-test -test-load-tu <AST file> <symbol filter> "
3092 "[FileCheck prefix]\n"
Ted Kremenek7d405622010-01-12 23:34:26 +00003093 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
3094 "[FileCheck prefix]\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003095 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003096 fprintf(stderr,
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003097 " c-index-test -test-load-source-memory-usage "
3098 "<symbol filter> {<args>}*\n"
Douglas Gregorabc563f2010-07-19 21:46:24 +00003099 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
3100 " {<args>}*\n"
Douglas Gregor1982c182010-07-12 18:38:41 +00003101 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003102 " c-index-test -test-load-source-usrs-memory-usage "
3103 "<symbol filter> {<args>}*\n"
Ted Kremenek16b55a72010-01-26 19:31:51 +00003104 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
3105 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00003106 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth53513d22010-07-22 06:29:13 +00003107 fprintf(stderr,
Ted Kremenek4e6a3f72011-04-18 23:42:53 +00003108 " c-index-test -test-print-linkage-source {<args>}*\n"
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003109 " c-index-test -test-print-typekind {<args>}*\n"
3110 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003111 " c-index-test -print-usr-file <file>\n"
Ted Kremenek15322172011-11-10 08:43:12 +00003112 " c-index-test -write-pch <file> <compiler arguments>\n");
3113 fprintf(stderr,
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003114 " c-index-test -compilation-db [lookup <filename>] database\n");
3115 fprintf(stderr,
Ted Kremenek15322172011-11-10 08:43:12 +00003116 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregorcaf4bd32010-07-20 14:34:35 +00003117 fprintf(stderr,
Ted Kremenek7d405622010-01-12 23:34:26 +00003118 " <symbol filter> values:\n%s",
Ted Kremenek0d435192009-11-17 18:13:31 +00003119 " all - load all symbols, including those from PCH\n"
3120 " local - load all symbols except those in PCH\n"
3121 " category - only load ObjC categories (non-PCH)\n"
3122 " interface - only load ObjC interfaces (non-PCH)\n"
3123 " protocol - only load ObjC protocols (non-PCH)\n"
3124 " function - only load functions (non-PCH)\n"
Daniel Dunbar625e4ef2009-12-01 02:35:37 +00003125 " typedef - only load typdefs (non-PCH)\n"
3126 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003127}
3128
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003129/***/
3130
3131int cindextest_main(int argc, const char **argv) {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003132 clang_enableStackTraces();
Ted Kremenek15322172011-11-10 08:43:12 +00003133 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
3134 return read_diagnostics(argv[2]);
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003135 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor1982c182010-07-12 18:38:41 +00003136 return perform_code_completion(argc, argv, 0);
3137 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
3138 return perform_code_completion(argc, argv, 1);
Douglas Gregorf2c87bd2010-01-15 19:40:17 +00003139 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
3140 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidisaed123e2011-10-06 07:00:54 +00003141 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
3142 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis4e7064f2011-10-17 19:48:19 +00003143 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
3144 return index_file(argc - 2, argv + 2);
Argyrios Kyrtzidis21ee5702011-11-15 06:20:16 +00003145 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
3146 return index_tu(argc - 2, argv + 2);
Ted Kremenek7d405622010-01-12 23:34:26 +00003147 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003148 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek7d405622010-01-12 23:34:26 +00003149 if (I)
Ted Kremenekce2ae882010-01-26 17:59:48 +00003150 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
3151 NULL);
Ted Kremenek7d405622010-01-12 23:34:26 +00003152 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00003153 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
3154 CXCursorVisitor I = GetVisitor(argv[1] + 25);
3155 if (I) {
3156 int trials = atoi(argv[2]);
3157 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
3158 NULL);
3159 }
3160 }
Ted Kremenek7d405622010-01-12 23:34:26 +00003161 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregore5b72ba2010-01-20 21:32:04 +00003162 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003163
3164 PostVisitTU postVisit = 0;
3165 if (strstr(argv[1], "-memory-usage"))
3166 postVisit = PrintMemoryUsage;
3167
Ted Kremenek7d405622010-01-12 23:34:26 +00003168 if (I)
Ted Kremenek59fc1e52011-04-18 22:47:10 +00003169 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
3170 postVisit);
Ted Kremenek7d405622010-01-12 23:34:26 +00003171 }
3172 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek1d5fdf32009-11-18 02:02:52 +00003173 return perform_file_scan(argv[2], argv[3],
3174 argc >= 5 ? argv[4] : 0);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003175 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
3176 return perform_token_annotation(argc, argv);
Ted Kremenek16b55a72010-01-26 19:31:51 +00003177 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
3178 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
3179 PrintInclusionStack);
3180 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
3181 return perform_test_load_tu(argv[2], "all", NULL, NULL,
3182 PrintInclusionStack);
Ted Kremenek3bed5272010-03-03 06:37:58 +00003183 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
3184 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
3185 NULL);
Ted Kremenek8e0ac172010-05-14 21:29:26 +00003186 else if (argc > 2 && strcmp(argv[1], "-test-print-typekind") == 0)
3187 return perform_test_load_source(argc - 2, argv + 2, "all",
3188 PrintTypeKind, 0);
Ted Kremenekf7b714d2010-03-25 02:00:39 +00003189 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
3190 if (argc > 2)
3191 return print_usrs(argv + 2, argv + argc);
3192 else {
3193 display_usrs();
3194 return 1;
3195 }
3196 }
3197 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
3198 return print_usrs_file(argv[2]);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00003199 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
3200 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaisondb293182012-06-30 11:27:57 +00003201 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
3202 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
3203
Ted Kremenekf5d9c932009-11-17 18:09:14 +00003204 print_usage();
3205 return 1;
Steve Naroff50398192009-08-28 15:28:48 +00003206}
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003207
3208/***/
3209
3210/* We intentionally run in a separate thread to ensure we at least minimal
3211 * testing of a multithreaded environment (for example, having a reduced stack
3212 * size). */
3213
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003214typedef struct thread_info {
3215 int argc;
3216 const char **argv;
3217 int result;
3218} thread_info;
Benjamin Kramer84294912010-11-04 19:11:31 +00003219void thread_runner(void *client_data_v) {
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003220 thread_info *client_data = client_data_v;
3221 client_data->result = cindextest_main(client_data->argc, client_data->argv);
NAKAMURA Takumi3be55cd2012-04-07 06:59:28 +00003222#ifdef __CYGWIN__
3223 fflush(stdout); /* stdout is not flushed on Cygwin. */
3224#endif
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003225}
3226
3227int main(int argc, const char **argv) {
3228 thread_info client_data;
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003229
Douglas Gregor61605982010-10-27 16:00:01 +00003230 if (getenv("CINDEXTEST_NOTHREADS"))
3231 return cindextest_main(argc, argv);
3232
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003233 client_data.argc = argc;
3234 client_data.argv = argv;
Daniel Dunbara32a6e12010-11-04 01:26:31 +00003235 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar6edc8002010-09-30 20:39:47 +00003236 return client_data.result;
3237}