blob: c19648bba4b3c26fbf43923950536c5033e8537d [file] [log] [blame]
Steve Naroff69b10fd2009-09-01 15:55:40 +00001/* c-index-test.c */
Steve Naroffa1c72842009-08-28 15:28:48 +00002
Alp Toker1d257e12014-06-04 03:28:55 +00003#include "clang/Config/config.h"
Steve Naroffa1c72842009-08-28 15:28:48 +00004#include "clang-c/Index.h"
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00005#include "clang-c/CXCompilationDatabase.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +00006#include "clang-c/BuildSystem.h"
Alp Toker59c6bc52014-04-28 02:39:27 +00007#include "clang-c/Documentation.h"
Yaron Kerene7aad462015-05-14 05:40:50 +00008#include "llvm/Support/DataTypes.h"
Douglas Gregor49f67ce2010-08-26 13:48:20 +00009#include <ctype.h>
Douglas Gregor9eb77012009-11-07 00:00:49 +000010#include <stdlib.h>
Steve Naroff1054e602009-08-31 00:59:03 +000011#include <stdio.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000012#include <string.h>
Douglas Gregor082c3e62010-01-15 19:40:17 +000013#include <assert.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000014
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +000015#ifdef CLANG_HAVE_LIBXML
16#include <libxml/parser.h>
17#include <libxml/relaxng.h>
18#include <libxml/xmlerror.h>
19#endif
20
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +000021#ifdef _WIN32
22# include <direct.h>
23#else
24# include <unistd.h>
25#endif
26
Ted Kremenek1cd27d52009-11-17 18:13:31 +000027/******************************************************************************/
28/* Utility functions. */
29/******************************************************************************/
30
John Thompsonde258b52009-10-27 13:42:56 +000031#ifdef _MSC_VER
32char *basename(const char* path)
33{
34 char* base1 = (char*)strrchr(path, '/');
35 char* base2 = (char*)strrchr(path, '\\');
36 if (base1 && base2)
37 return((base1 > base2) ? base1 + 1 : base2 + 1);
38 else if (base1)
39 return(base1 + 1);
40 else if (base2)
41 return(base2 + 1);
42
43 return((char*)path);
44}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000045char *dirname(char* path)
46{
47 char* base1 = (char*)strrchr(path, '/');
48 char* base2 = (char*)strrchr(path, '\\');
49 if (base1 && base2)
50 if (base1 > base2)
51 *base1 = 0;
52 else
53 *base2 = 0;
54 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000055 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000056 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000057 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000058
59 return path;
60}
John Thompsonde258b52009-10-27 13:42:56 +000061#else
Steve Naroffa7753c42009-09-24 20:03:06 +000062extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000063extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000064#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000065
Douglas Gregorf2430ba2010-07-25 17:39:21 +000066/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000067static unsigned getDefaultParsingOptions() {
68 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
69
70 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000071 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000072 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
73 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000074 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
75 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000076 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
77 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000078 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
79 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000080
81 return options;
82}
83
Patrik Hagglund55701d22014-02-17 11:54:08 +000084/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000085static int checkForErrors(CXTranslationUnit TU);
86
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000087static void describeLibclangFailure(enum CXErrorCode Err) {
88 switch (Err) {
89 case CXError_Success:
90 fprintf(stderr, "Success\n");
91 return;
92
93 case CXError_Failure:
94 fprintf(stderr, "Failure (no details available)\n");
95 return;
96
97 case CXError_Crashed:
98 fprintf(stderr, "Failure: libclang crashed\n");
99 return;
100
101 case CXError_InvalidArguments:
102 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
103 return;
104
105 case CXError_ASTReadError:
106 fprintf(stderr, "Failure: AST deserialization error occurred\n");
107 return;
108 }
109}
110
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000111static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
112 unsigned end_line, unsigned end_column) {
113 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000114 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000115}
116
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000117static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
118 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000119 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
120 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000121 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000122 describeLibclangFailure(Err);
123 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000124 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000125 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000126 return 1;
127}
128
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000129void free_remapped_files(struct CXUnsavedFile *unsaved_files,
130 int num_unsaved_files) {
131 int i;
132 for (i = 0; i != num_unsaved_files; ++i) {
133 free((char *)unsaved_files[i].Filename);
134 free((char *)unsaved_files[i].Contents);
135 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000136 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000137}
138
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000139static int parse_remapped_files_with_opt(const char *opt_name,
140 int argc, const char **argv,
141 int start_arg,
142 struct CXUnsavedFile **unsaved_files,
143 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000144 int i;
145 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000146 int prefix_len = strlen(opt_name);
147 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000148 *unsaved_files = 0;
149 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000150
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000151 /* Count the number of remapped files. */
152 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000153 if (strncmp(argv[arg], opt_name, prefix_len))
154 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000155
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000156 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
157 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000158 ++*num_unsaved_files;
159 }
Ted Kremenek29004672010-02-17 00:41:32 +0000160
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000161 if (*num_unsaved_files == 0)
162 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000163
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000164 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000165 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
166 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000167 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000168 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000169 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000170 int filename_len;
171 char *filename;
172 char *contents;
173 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000174 const char *sep = strchr(arg_string, ',');
175 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000176 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000177 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000178 free_remapped_files(*unsaved_files, i);
179 *unsaved_files = 0;
180 *num_unsaved_files = 0;
181 return -1;
182 }
Ted Kremenek29004672010-02-17 00:41:32 +0000183
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000184 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000185 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000186 if (!to_file) {
187 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000188 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000189 free_remapped_files(*unsaved_files, i);
190 *unsaved_files = 0;
191 *num_unsaved_files = 0;
192 return -1;
193 }
Ted Kremenek29004672010-02-17 00:41:32 +0000194
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000195 /* Determine the length of the file we're remapping to. */
196 fseek(to_file, 0, SEEK_END);
197 unsaved->Length = ftell(to_file);
198 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000199
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000200 /* Read the contents of the file we're remapping to. */
201 contents = (char *)malloc(unsaved->Length + 1);
202 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
203 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000204 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000205 fclose(to_file);
206 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000207 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000208 *unsaved_files = 0;
209 *num_unsaved_files = 0;
210 return -1;
211 }
212 contents[unsaved->Length] = 0;
213 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000214
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000215 /* Close the file. */
216 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000217
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000218 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000219 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000220 filename = (char *)malloc(filename_len + 1);
221 memcpy(filename, arg_string, filename_len);
222 filename[filename_len] = 0;
223 unsaved->Filename = filename;
224 }
Ted Kremenek29004672010-02-17 00:41:32 +0000225
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000226 return 0;
227}
228
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000229static int parse_remapped_files(int argc, const char **argv, int start_arg,
230 struct CXUnsavedFile **unsaved_files,
231 int *num_unsaved_files) {
232 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
233 unsaved_files, num_unsaved_files);
234}
235
236static int parse_remapped_files_with_try(int try_idx,
237 int argc, const char **argv,
238 int start_arg,
239 struct CXUnsavedFile **unsaved_files,
240 int *num_unsaved_files) {
241 struct CXUnsavedFile *unsaved_files_no_try_idx;
242 int num_unsaved_files_no_try_idx;
243 struct CXUnsavedFile *unsaved_files_try_idx;
244 int num_unsaved_files_try_idx;
245 int ret;
246 char opt_name[32];
247
248 ret = parse_remapped_files(argc, argv, start_arg,
249 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
250 if (ret)
251 return ret;
252
253 sprintf(opt_name, "-remap-file-%d=", try_idx);
254 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
255 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
256 if (ret)
257 return ret;
258
259 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
260 *unsaved_files
261 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
262 sizeof(struct CXUnsavedFile) *
263 *num_unsaved_files);
264 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
265 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
266 num_unsaved_files_try_idx);
267 free(unsaved_files_try_idx);
268 return 0;
269}
270
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000271static const char *parse_comments_schema(int argc, const char **argv) {
272 const char *CommentsSchemaArg = "-comments-xml-schema=";
273 const char *CommentSchemaFile = NULL;
274
275 if (argc == 0)
276 return CommentSchemaFile;
277
278 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
279 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
280
281 return CommentSchemaFile;
282}
283
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000284/******************************************************************************/
285/* Pretty-printing. */
286/******************************************************************************/
287
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000288static const char *FileCheckPrefix = "CHECK";
289
290static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000291 if (CStr != NULL && CStr[0] != '\0') {
292 for ( ; *CStr; ++CStr) {
293 const char C = *CStr;
294 switch (C) {
295 case '\n': printf("\\n"); break;
296 case '\r': printf("\\r"); break;
297 case '\t': printf("\\t"); break;
298 case '\v': printf("\\v"); break;
299 case '\f': printf("\\f"); break;
300 default: putchar(C); break;
301 }
302 }
303 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000304}
305
306static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
307 printf(" %s=[", Prefix);
308 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000309 printf("]");
310}
311
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000312static void PrintCXStringAndDispose(CXString Str) {
313 PrintCString(clang_getCString(Str));
314 clang_disposeString(Str);
315}
316
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000317static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
318 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
319}
320
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000321static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
322 CXString Str) {
323 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
324 clang_disposeString(Str);
325}
326
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000327static void PrintRange(CXSourceRange R, const char *str) {
328 CXFile begin_file, end_file;
329 unsigned begin_line, begin_column, end_line, end_column;
330
331 clang_getSpellingLocation(clang_getRangeStart(R),
332 &begin_file, &begin_line, &begin_column, 0);
333 clang_getSpellingLocation(clang_getRangeEnd(R),
334 &end_file, &end_line, &end_column, 0);
335 if (!begin_file || !end_file)
336 return;
337
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000338 if (str)
339 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000340 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
341}
342
Douglas Gregor97c75712010-10-02 22:49:11 +0000343int want_display_name = 0;
344
Douglas Gregord6225d32012-05-08 00:14:45 +0000345static void printVersion(const char *Prefix, CXVersion Version) {
346 if (Version.Major < 0)
347 return;
348 printf("%s%d", Prefix, Version.Major);
349
350 if (Version.Minor < 0)
351 return;
352 printf(".%d", Version.Minor);
353
354 if (Version.Subminor < 0)
355 return;
356 printf(".%d", Version.Subminor);
357}
358
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000359struct CommentASTDumpingContext {
360 int IndentLevel;
361};
362
363static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
364 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000365 unsigned i;
366 unsigned e;
367 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
368
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000369 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000370 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000371 printf(" ");
372
373 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000374 switch (Kind) {
375 case CXComment_Null:
376 printf("CXComment_Null");
377 break;
378 case CXComment_Text:
379 printf("CXComment_Text");
380 PrintCXStringWithPrefixAndDispose("Text",
381 clang_TextComment_getText(Comment));
382 if (clang_Comment_isWhitespace(Comment))
383 printf(" IsWhitespace");
384 if (clang_InlineContentComment_hasTrailingNewline(Comment))
385 printf(" HasTrailingNewline");
386 break;
387 case CXComment_InlineCommand:
388 printf("CXComment_InlineCommand");
389 PrintCXStringWithPrefixAndDispose(
390 "CommandName",
391 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000392 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
393 case CXCommentInlineCommandRenderKind_Normal:
394 printf(" RenderNormal");
395 break;
396 case CXCommentInlineCommandRenderKind_Bold:
397 printf(" RenderBold");
398 break;
399 case CXCommentInlineCommandRenderKind_Monospaced:
400 printf(" RenderMonospaced");
401 break;
402 case CXCommentInlineCommandRenderKind_Emphasized:
403 printf(" RenderEmphasized");
404 break;
405 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000406 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000407 i != e; ++i) {
408 printf(" Arg[%u]=", i);
409 PrintCXStringAndDispose(
410 clang_InlineCommandComment_getArgText(Comment, i));
411 }
412 if (clang_InlineContentComment_hasTrailingNewline(Comment))
413 printf(" HasTrailingNewline");
414 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000415 case CXComment_HTMLStartTag: {
416 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000417 printf("CXComment_HTMLStartTag");
418 PrintCXStringWithPrefixAndDispose(
419 "Name",
420 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000421 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000422 if (NumAttrs != 0) {
423 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000424 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000425 printf(" ");
426 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
427 printf("=");
428 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
429 }
430 }
431 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
432 printf(" SelfClosing");
433 if (clang_InlineContentComment_hasTrailingNewline(Comment))
434 printf(" HasTrailingNewline");
435 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000436 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000437 case CXComment_HTMLEndTag:
438 printf("CXComment_HTMLEndTag");
439 PrintCXStringWithPrefixAndDispose(
440 "Name",
441 clang_HTMLTagComment_getTagName(Comment));
442 if (clang_InlineContentComment_hasTrailingNewline(Comment))
443 printf(" HasTrailingNewline");
444 break;
445 case CXComment_Paragraph:
446 printf("CXComment_Paragraph");
447 if (clang_Comment_isWhitespace(Comment))
448 printf(" IsWhitespace");
449 break;
450 case CXComment_BlockCommand:
451 printf("CXComment_BlockCommand");
452 PrintCXStringWithPrefixAndDispose(
453 "CommandName",
454 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000455 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000456 i != e; ++i) {
457 printf(" Arg[%u]=", i);
458 PrintCXStringAndDispose(
459 clang_BlockCommandComment_getArgText(Comment, i));
460 }
461 break;
462 case CXComment_ParamCommand:
463 printf("CXComment_ParamCommand");
464 switch (clang_ParamCommandComment_getDirection(Comment)) {
465 case CXCommentParamPassDirection_In:
466 printf(" in");
467 break;
468 case CXCommentParamPassDirection_Out:
469 printf(" out");
470 break;
471 case CXCommentParamPassDirection_InOut:
472 printf(" in,out");
473 break;
474 }
475 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
476 printf(" explicitly");
477 else
478 printf(" implicitly");
479 PrintCXStringWithPrefixAndDispose(
480 "ParamName",
481 clang_ParamCommandComment_getParamName(Comment));
482 if (clang_ParamCommandComment_isParamIndexValid(Comment))
483 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
484 else
485 printf(" ParamIndex=Invalid");
486 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000487 case CXComment_TParamCommand:
488 printf("CXComment_TParamCommand");
489 PrintCXStringWithPrefixAndDispose(
490 "ParamName",
491 clang_TParamCommandComment_getParamName(Comment));
492 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
493 printf(" ParamPosition={");
494 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
495 i != e; ++i) {
496 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
497 if (i != e - 1)
498 printf(", ");
499 }
500 printf("}");
501 } else
502 printf(" ParamPosition=Invalid");
503 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000504 case CXComment_VerbatimBlockCommand:
505 printf("CXComment_VerbatimBlockCommand");
506 PrintCXStringWithPrefixAndDispose(
507 "CommandName",
508 clang_BlockCommandComment_getCommandName(Comment));
509 break;
510 case CXComment_VerbatimBlockLine:
511 printf("CXComment_VerbatimBlockLine");
512 PrintCXStringWithPrefixAndDispose(
513 "Text",
514 clang_VerbatimBlockLineComment_getText(Comment));
515 break;
516 case CXComment_VerbatimLine:
517 printf("CXComment_VerbatimLine");
518 PrintCXStringWithPrefixAndDispose(
519 "Text",
520 clang_VerbatimLineComment_getText(Comment));
521 break;
522 case CXComment_FullComment:
523 printf("CXComment_FullComment");
524 break;
525 }
526 if (Kind != CXComment_Null) {
527 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000528 unsigned i;
529 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000530 printf("\n// %s: ", FileCheckPrefix);
531 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
532 }
533 }
534 printf(")");
535 Ctx->IndentLevel--;
536}
537
538static void DumpCXComment(CXComment Comment) {
539 struct CommentASTDumpingContext Ctx;
540 Ctx.IndentLevel = 1;
541 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
542 DumpCXCommentInternal(&Ctx, Comment);
543 printf("]");
544}
545
Chandler Carruthb2faa592014-05-02 23:30:59 +0000546static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000547#ifdef CLANG_HAVE_LIBXML
548 xmlRelaxNGParserCtxtPtr RNGParser;
549 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000550 xmlDocPtr Doc;
551 xmlRelaxNGValidCtxtPtr ValidationCtxt;
552 int status;
553
Chandler Carruthb2faa592014-05-02 23:30:59 +0000554 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000555 return;
556
Chandler Carruthb2faa592014-05-02 23:30:59 +0000557 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
558 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000559 printf(" libXMLError");
560 return;
561 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000562 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000563
564 Doc = xmlParseDoc((const xmlChar *) Str);
565
566 if (!Doc) {
567 xmlErrorPtr Error = xmlGetLastError();
568 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
569 return;
570 }
571
Chandler Carruthb2faa592014-05-02 23:30:59 +0000572 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000573 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
574 if (!status)
575 printf(" CommentXMLValid");
576 else if (status > 0) {
577 xmlErrorPtr Error = xmlGetLastError();
578 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
579 } else
580 printf(" libXMLError");
581
582 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
583 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000584 xmlRelaxNGFree(Schema);
585 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000586#endif
587}
588
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000589static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000590 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000591 {
592 CXString RawComment;
593 const char *RawCommentCString;
594 CXString BriefComment;
595 const char *BriefCommentCString;
596
597 RawComment = clang_Cursor_getRawCommentText(Cursor);
598 RawCommentCString = clang_getCString(RawComment);
599 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
600 PrintCStringWithPrefix("RawComment", RawCommentCString);
601 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
602
603 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
604 BriefCommentCString = clang_getCString(BriefComment);
605 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
606 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
607 clang_disposeString(BriefComment);
608 }
609 clang_disposeString(RawComment);
610 }
611
612 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000613 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000614 if (clang_Comment_getKind(Comment) != CXComment_Null) {
615 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
616 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000617 {
618 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000619 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000620 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000621 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000622 clang_disposeString(XML);
623 }
624
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000625 DumpCXComment(Comment);
626 }
627 }
628}
629
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000630typedef struct {
631 unsigned line;
632 unsigned col;
633} LineCol;
634
635static int lineCol_cmp(const void *p1, const void *p2) {
636 const LineCol *lhs = p1;
637 const LineCol *rhs = p2;
638 if (lhs->line != rhs->line)
639 return (int)lhs->line - (int)rhs->line;
640 return (int)lhs->col - (int)rhs->col;
641}
642
Chandler Carruthb2faa592014-05-02 23:30:59 +0000643static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000644 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000645 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000646 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000647 printf("Invalid Cursor => %s", clang_getCString(ks));
648 clang_disposeString(ks);
649 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000650 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000651 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000652 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000653 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000654 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000655 CXCursor *overridden;
656 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000657 unsigned RefNameRangeNr;
658 CXSourceRange CursorExtent;
659 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000660 int AlwaysUnavailable;
661 int AlwaysDeprecated;
662 CXString UnavailableMessage;
663 CXString DeprecatedMessage;
664 CXPlatformAvailability PlatformAvailability[2];
665 int NumPlatformAvailability;
666 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000667
Ted Kremenek29004672010-02-17 00:41:32 +0000668 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000669 string = want_display_name? clang_getCursorDisplayName(Cursor)
670 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000671 printf("%s=%s", clang_getCString(ks),
672 clang_getCString(string));
673 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000674 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000675
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000676 Referenced = clang_getCursorReferenced(Cursor);
677 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000678 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
679 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
680 printf("[");
681 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000682 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000683 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000684 if (I)
685 printf(", ");
686
Douglas Gregor2967e282010-09-14 00:20:32 +0000687 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000688 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000689 printf("%d:%d", line, column);
690 }
691 printf("]");
692 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000693 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000694 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000695 printf(":%d:%d", line, column);
696 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000697 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000698
699 if (clang_isCursorDefinition(Cursor))
700 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000701
702 switch (clang_getCursorAvailability(Cursor)) {
703 case CXAvailability_Available:
704 break;
705
706 case CXAvailability_Deprecated:
707 printf(" (deprecated)");
708 break;
709
710 case CXAvailability_NotAvailable:
711 printf(" (unavailable)");
712 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000713
714 case CXAvailability_NotAccessible:
715 printf(" (inaccessible)");
716 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000717 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000718
Douglas Gregord6225d32012-05-08 00:14:45 +0000719 NumPlatformAvailability
720 = clang_getCursorPlatformAvailability(Cursor,
721 &AlwaysDeprecated,
722 &DeprecatedMessage,
723 &AlwaysUnavailable,
724 &UnavailableMessage,
725 PlatformAvailability, 2);
726 if (AlwaysUnavailable) {
727 printf(" (always unavailable: \"%s\")",
728 clang_getCString(UnavailableMessage));
729 } else if (AlwaysDeprecated) {
730 printf(" (always deprecated: \"%s\")",
731 clang_getCString(DeprecatedMessage));
732 } else {
733 for (I = 0; I != NumPlatformAvailability; ++I) {
734 if (I >= 2)
735 break;
736
737 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
738 if (PlatformAvailability[I].Unavailable)
739 printf(", unavailable");
740 else {
741 printVersion(", introduced=", PlatformAvailability[I].Introduced);
742 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
743 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
744 }
745 if (clang_getCString(PlatformAvailability[I].Message)[0])
746 printf(", message=\"%s\"",
747 clang_getCString(PlatformAvailability[I].Message));
748 printf(")");
749 }
750 }
751 for (I = 0; I != NumPlatformAvailability; ++I) {
752 if (I >= 2)
753 break;
754 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
755 }
756
757 clang_disposeString(DeprecatedMessage);
758 clang_disposeString(UnavailableMessage);
759
Douglas Gregora8d0c772011-05-13 15:54:42 +0000760 if (clang_CXXMethod_isStatic(Cursor))
761 printf(" (static)");
762 if (clang_CXXMethod_isVirtual(Cursor))
763 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000764 if (clang_CXXMethod_isConst(Cursor))
765 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000766 if (clang_CXXMethod_isPureVirtual(Cursor))
767 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000768 if (clang_Cursor_isVariadic(Cursor))
769 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000770 if (clang_Cursor_isObjCOptional(Cursor))
771 printf(" (@optional)");
772
Ted Kremeneka5940822010-08-26 01:42:22 +0000773 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000774 CXType T =
775 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
776 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000777 printf(" [IBOutletCollection=%s]", clang_getCString(S));
778 clang_disposeString(S);
779 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000780
781 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
782 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
783 unsigned isVirtual = clang_isVirtualBase(Cursor);
784 const char *accessStr = 0;
785
786 switch (access) {
787 case CX_CXXInvalidAccessSpecifier:
788 accessStr = "invalid"; break;
789 case CX_CXXPublic:
790 accessStr = "public"; break;
791 case CX_CXXProtected:
792 accessStr = "protected"; break;
793 case CX_CXXPrivate:
794 accessStr = "private"; break;
795 }
796
797 printf(" [access=%s isVirtual=%s]", accessStr,
798 isVirtual ? "true" : "false");
799 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000800
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000801 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
802 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000803 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
804 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000805 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000806 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000807 clang_getCString(Name), line, column);
808 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000809
810 if (Cursor.kind == CXCursor_FunctionDecl) {
811 /* Collect the template parameter kinds from the base template. */
812 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
813 unsigned I;
814 for (I = 0; I < NumTemplateArgs; I++) {
815 enum CXTemplateArgumentKind TAK =
816 clang_Cursor_getTemplateArgumentKind(Cursor, I);
817 switch(TAK) {
818 case CXTemplateArgumentKind_Type:
819 {
820 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
821 CXString S = clang_getTypeSpelling(T);
822 printf(" [Template arg %d: kind: %d, type: %s]",
823 I, TAK, clang_getCString(S));
824 clang_disposeString(S);
825 }
826 break;
827 case CXTemplateArgumentKind_Integral:
Yaron Kerene7aad462015-05-14 05:40:50 +0000828 printf(" [Template arg %d: kind: %d, intval: %" PRId64 "]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000829 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
830 break;
831 default:
832 printf(" [Template arg %d: kind: %d]\n", I, TAK);
833 }
834 }
835 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000836 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000837
838 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
839 if (num_overridden) {
840 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000841 LineCol lineCols[50];
842 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000843 printf(" [Overrides ");
844 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000845 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000846 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000847 lineCols[I].line = line;
848 lineCols[I].col = column;
849 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000850 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000851 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
852 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000853 if (I)
854 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000855 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000856 }
857 printf("]");
858 clang_disposeOverriddenCursors(overridden);
859 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000860
861 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000862 CXFile File = clang_getIncludedFile(Cursor);
863 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000864 printf(" (%s)", clang_getCString(Included));
865 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000866
867 if (clang_isFileMultipleIncludeGuarded(TU, File))
868 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000869 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000870
871 CursorExtent = clang_getCursorExtent(Cursor);
872 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
873 CXNameRange_WantQualifier
874 | CXNameRange_WantSinglePiece
875 | CXNameRange_WantTemplateArgs,
876 0);
877 if (!clang_equalRanges(CursorExtent, RefNameRange))
878 PrintRange(RefNameRange, "SingleRefName");
879
880 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
881 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
882 CXNameRange_WantQualifier
883 | CXNameRange_WantTemplateArgs,
884 RefNameRangeNr);
885 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
886 break;
887 if (!clang_equalRanges(CursorExtent, RefNameRange))
888 PrintRange(RefNameRange, "RefName");
889 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000890
Chandler Carruthb2faa592014-05-02 23:30:59 +0000891 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000892
893 {
894 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
895 if (PropAttrs != CXObjCPropertyAttr_noattr) {
896 printf(" [");
897 #define PRINT_PROP_ATTR(A) \
898 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
899 PRINT_PROP_ATTR(readonly);
900 PRINT_PROP_ATTR(getter);
901 PRINT_PROP_ATTR(assign);
902 PRINT_PROP_ATTR(readwrite);
903 PRINT_PROP_ATTR(retain);
904 PRINT_PROP_ATTR(copy);
905 PRINT_PROP_ATTR(nonatomic);
906 PRINT_PROP_ATTR(setter);
907 PRINT_PROP_ATTR(atomic);
908 PRINT_PROP_ATTR(weak);
909 PRINT_PROP_ATTR(strong);
910 PRINT_PROP_ATTR(unsafe_unretained);
911 printf("]");
912 }
913 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000914
915 {
916 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
917 if (QT != CXObjCDeclQualifier_None) {
918 printf(" [");
919 #define PRINT_OBJC_QUAL(A) \
920 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
921 PRINT_OBJC_QUAL(In);
922 PRINT_OBJC_QUAL(Inout);
923 PRINT_OBJC_QUAL(Out);
924 PRINT_OBJC_QUAL(Bycopy);
925 PRINT_OBJC_QUAL(Byref);
926 PRINT_OBJC_QUAL(Oneway);
927 printf("]");
928 }
929 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000930 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000931}
Steve Naroff1054e602009-08-31 00:59:03 +0000932
Ted Kremenek29004672010-02-17 00:41:32 +0000933static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000934 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000935 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000936 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000937 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000938 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000939 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000940 clang_disposeString(source);
941 return "<invalid loc>";
942 }
943 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000944 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000945 clang_disposeString(source);
946 return b;
947 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000948}
949
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000950/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000951/* Callbacks. */
952/******************************************************************************/
953
954typedef void (*PostVisitTU)(CXTranslationUnit);
955
Douglas Gregor33cdd812010-02-18 18:08:43 +0000956void PrintDiagnostic(CXDiagnostic Diagnostic) {
957 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000958 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000959 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000960 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000961 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
962 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000963 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000964
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000965 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000966 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000967
Douglas Gregord770f732010-02-22 23:17:23 +0000968 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
969 fprintf(stderr, "%s\n", clang_getCString(Msg));
970 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000971
Douglas Gregor229bebd2010-11-09 06:24:54 +0000972 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
973 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000974 if (!file)
975 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000976
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000977 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000978 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000979 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000980 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000981 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
982 CXSourceLocation start = clang_getRangeStart(range);
983 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000984 unsigned start_line, start_column, end_line, end_column;
985 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +0000986 clang_getSpellingLocation(start, &start_file, &start_line,
987 &start_column, 0);
988 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +0000989 if (clang_equalLocations(start, end)) {
990 /* Insertion. */
991 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000992 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +0000993 clang_getCString(insertion_text), start_line, start_column);
994 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
995 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000996 if (start_file == file && end_file == file) {
997 fprintf(out, "FIX-IT: Remove ");
998 PrintExtent(out, start_line, start_column, end_line, end_column);
999 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001000 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001001 } else {
1002 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001003 if (start_file == end_file) {
1004 fprintf(out, "FIX-IT: Replace ");
1005 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001006 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001007 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001008 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001009 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001010 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001011}
1012
Ted Kremenek914c7e62012-02-14 02:46:03 +00001013void PrintDiagnosticSet(CXDiagnosticSet Set) {
1014 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1015 for ( ; i != n ; ++i) {
1016 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1017 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001018 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001019 if (ChildDiags)
1020 PrintDiagnosticSet(ChildDiags);
1021 }
1022}
1023
1024void PrintDiagnostics(CXTranslationUnit TU) {
1025 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1026 PrintDiagnosticSet(TUSet);
1027 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001028}
1029
Ted Kremenek83f642e2011-04-18 22:47:10 +00001030void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001031 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001032 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001033 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001034 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001035 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001036 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001037 unsigned long amount = usage.entries[i].amount;
1038 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001039 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001040 ((double) amount)/(1024*1024));
1041 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001042 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001043 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001044 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001045}
1046
Ted Kremenekb478ff42010-01-26 17:59:48 +00001047/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001048/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001049/******************************************************************************/
1050
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001051static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001052 CXSourceRange extent = clang_getCursorExtent(C);
1053 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001054}
1055
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001056/* Data used by the visitors. */
1057typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001058 CXTranslationUnit TU;
1059 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001060 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001061} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001062
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001063
Ted Kremenek29004672010-02-17 00:41:32 +00001064enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001065 CXCursor Parent,
1066 CXClientData ClientData) {
1067 VisitorData *Data = (VisitorData *)ClientData;
1068 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001069 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001070 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001071 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001072 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001073 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001074 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001075 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001076 if (clang_isDeclaration(Cursor.kind)) {
1077 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1078 const char *accessStr = 0;
1079
1080 switch (access) {
1081 case CX_CXXInvalidAccessSpecifier: break;
1082 case CX_CXXPublic:
1083 accessStr = "public"; break;
1084 case CX_CXXProtected:
1085 accessStr = "protected"; break;
1086 case CX_CXXPrivate:
1087 accessStr = "private"; break;
1088 }
1089
1090 if (accessStr)
1091 printf(" [access=%s]", accessStr);
1092 }
Ted Kremenek29004672010-02-17 00:41:32 +00001093 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001094 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001095 }
Ted Kremenek29004672010-02-17 00:41:32 +00001096
Douglas Gregor720d0052010-01-20 21:32:04 +00001097 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001098}
Steve Naroffa1c72842009-08-28 15:28:48 +00001099
Ted Kremenek29004672010-02-17 00:41:32 +00001100static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001101 CXCursor Parent,
1102 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001103 const char *startBuf, *endBuf;
1104 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1105 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001106 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001107
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001108 if (Cursor.kind != CXCursor_FunctionDecl ||
1109 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001110 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001111
1112 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1113 &startLine, &startColumn,
1114 &endLine, &endColumn);
1115 /* Probe the entire body, looking for both decls and refs. */
1116 curLine = startLine;
1117 curColumn = startColumn;
1118
1119 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001120 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001121 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001122 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001123
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001124 if (*startBuf == '\n') {
1125 startBuf++;
1126 curLine++;
1127 curColumn = 1;
1128 } else if (*startBuf != '\t')
1129 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001130
Douglas Gregor66a58812010-01-18 22:46:11 +00001131 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001132 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001133
Douglas Gregor4f46e782010-01-19 21:36:55 +00001134 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001135 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001136 CXSourceLocation RefLoc
1137 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001138 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001139 if (Ref.kind == CXCursor_NoDeclFound) {
1140 /* Nothing found here; that's fine. */
1141 } else if (Ref.kind != CXCursor_FunctionDecl) {
1142 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1143 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001144 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001145 printf("\n");
1146 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001147 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001148 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001149 startBuf++;
1150 }
Ted Kremenek29004672010-02-17 00:41:32 +00001151
Douglas Gregor720d0052010-01-20 21:32:04 +00001152 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001153}
1154
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001155/******************************************************************************/
1156/* USR testing. */
1157/******************************************************************************/
1158
Douglas Gregor720d0052010-01-20 21:32:04 +00001159enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1160 CXClientData ClientData) {
1161 VisitorData *Data = (VisitorData *)ClientData;
1162 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001163 CXString USR = clang_getCursorUSR(C);
1164 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001165 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001166 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001167 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001168 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001169 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1170
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001171 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001172 printf("\n");
1173 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001174
Douglas Gregor720d0052010-01-20 21:32:04 +00001175 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001176 }
1177
Douglas Gregor720d0052010-01-20 21:32:04 +00001178 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001179}
1180
1181/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001182/* Inclusion stack testing. */
1183/******************************************************************************/
1184
1185void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1186 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001187
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001188 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001189 CXString fname;
1190
1191 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001192 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001193 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001194
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001195 for (i = 0; i < includeStackLen; ++i) {
1196 CXFile includingFile;
1197 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001198 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1199 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001200 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001201 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001202 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001203 }
1204 printf("\n");
1205}
1206
1207void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001208 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001209}
1210
1211/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001212/* Linkage testing. */
1213/******************************************************************************/
1214
1215static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1216 CXClientData d) {
1217 const char *linkage = 0;
1218
1219 if (clang_isInvalid(clang_getCursorKind(cursor)))
1220 return CXChildVisit_Recurse;
1221
1222 switch (clang_getCursorLinkage(cursor)) {
1223 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001224 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1225 case CXLinkage_Internal: linkage = "Internal"; break;
1226 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1227 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001228 }
1229
1230 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001231 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001232 printf("linkage=%s\n", linkage);
1233 }
1234
1235 return CXChildVisit_Recurse;
1236}
1237
1238/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001239/* Typekind testing. */
1240/******************************************************************************/
1241
Dmitri Gribenko00353722013-02-15 21:15:49 +00001242static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1243 CXString TypeSpelling, TypeKindSpelling;
1244
1245 TypeSpelling = clang_getTypeSpelling(T);
1246 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1247 printf(Format,
1248 clang_getCString(TypeSpelling),
1249 clang_getCString(TypeKindSpelling));
1250 clang_disposeString(TypeSpelling);
1251 clang_disposeString(TypeKindSpelling);
1252}
1253
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001254static enum CXVisitorResult FieldVisitor(CXCursor C,
1255 CXClientData client_data) {
1256 (*(int *) client_data)+=1;
1257 return CXVisit_Continue;
1258}
1259
Dmitri Gribenko00353722013-02-15 21:15:49 +00001260static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1261 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001262 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001263 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001264 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001265 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001266 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001267 if (clang_isConstQualifiedType(T))
1268 printf(" const");
1269 if (clang_isVolatileQualifiedType(T))
1270 printf(" volatile");
1271 if (clang_isRestrictQualifiedType(T))
1272 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001273 if (RQ == CXRefQualifier_LValue)
1274 printf(" lvalue-ref-qualifier");
1275 if (RQ == CXRefQualifier_RValue)
1276 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001277 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001278 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001279 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001280 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001281 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001282 }
1283 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001284 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001285 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001286 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001287 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001288 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001289 }
1290 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001291 /* Print the argument types if they exist. */
1292 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001293 int NumArgs = clang_Cursor_getNumArguments(cursor);
1294 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001295 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001296 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001297 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001298 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001299 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001300 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001301 }
1302 }
1303 printf("]");
1304 }
1305 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001306 /* Print the template argument types if they exist. */
1307 {
1308 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1309 if (NumTArgs != -1 && NumTArgs != 0) {
1310 int i;
1311 printf(" [templateargs/%d=", NumTArgs);
1312 for (i = 0; i < NumTArgs; ++i) {
1313 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1314 if (TArg.kind != CXType_Invalid) {
1315 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1316 }
1317 }
1318 printf("]");
1319 }
1320 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001321 /* Print if this is a non-POD type. */
1322 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001323 /* Print the pointee type. */
1324 {
1325 CXType PT = clang_getPointeeType(T);
1326 if (PT.kind != CXType_Invalid) {
1327 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1328 }
1329 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001330 /* Print the number of fields if they exist. */
1331 {
1332 int numFields = 0;
1333 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1334 if (numFields != 0) {
1335 printf(" [nbFields=%d]", numFields);
1336 }
1337 /* Print if it is an anonymous record. */
1338 {
1339 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1340 if (isAnon != 0) {
1341 printf(" [isAnon=%d]", isAnon);
1342 }
1343 }
1344 }
1345 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001346
Ted Kremenek6bca9842010-05-14 21:29:26 +00001347 printf("\n");
1348 }
1349 return CXChildVisit_Recurse;
1350}
1351
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001352static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1353 CXClientData d) {
1354 CXType T;
1355 enum CXCursorKind K = clang_getCursorKind(cursor);
1356 if (clang_isInvalid(K))
1357 return CXChildVisit_Recurse;
1358 T = clang_getCursorType(cursor);
1359 PrintCursor(cursor, NULL);
1360 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1361 /* Print the type sizeof if applicable. */
1362 {
1363 long long Size = clang_Type_getSizeOf(T);
1364 if (Size >= 0 || Size < -1 ) {
Yaron Kerene7aad462015-05-14 05:40:50 +00001365 printf(" [sizeof=%" PRId64 "]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001366 }
1367 }
1368 /* Print the type alignof if applicable. */
1369 {
1370 long long Align = clang_Type_getAlignOf(T);
1371 if (Align >= 0 || Align < -1) {
Yaron Kerene7aad462015-05-14 05:40:50 +00001372 printf(" [alignof=%" PRId64 "]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001373 }
1374 }
1375 /* Print the record field offset if applicable. */
1376 {
Nico Weber82098cb2014-04-24 04:14:12 +00001377 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1378 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001379 /* recurse to get the first parent record that is not anonymous. */
1380 CXCursor Parent, Record;
1381 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001382 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001383 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001384 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001385 Record = Parent;
1386 Parent = clang_getCursorSemanticParent(Record);
1387 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1388 /* Recurse as long as the parent is a CXType_Record and the Record
1389 is anonymous */
1390 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1391 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001392 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001393 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001394 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001395 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1396 if (Offset == Offset2){
Yaron Kerene7aad462015-05-14 05:40:50 +00001397 printf(" [offsetof=%" PRId64 "]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001398 } else {
1399 /* Offsets will be different in anonymous records. */
Yaron Kerene7aad462015-05-14 05:40:50 +00001400 printf(" [offsetof=%" PRId64 "/%" PRId64 "]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001401 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001402 }
1403 }
Nico Weber82098cb2014-04-24 04:14:12 +00001404 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001405 }
1406 /* Print if its a bitfield */
1407 {
1408 int IsBitfield = clang_Cursor_isBitField(cursor);
1409 if (IsBitfield)
1410 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1411 }
1412 printf("\n");
1413 return CXChildVisit_Recurse;
1414}
1415
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001416/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001417/* Mangling testing. */
1418/******************************************************************************/
1419
1420static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1421 CXClientData d) {
1422 CXString MangledName;
1423 PrintCursor(cursor, NULL);
1424 MangledName = clang_Cursor_getMangling(cursor);
1425 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001426 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001427 return CXChildVisit_Continue;
1428}
1429
1430/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001431/* Bitwidth testing. */
1432/******************************************************************************/
1433
1434static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1435 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001436 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001437 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1438 return CXChildVisit_Recurse;
1439
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001440 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001441 if (Bitwidth >= 0) {
1442 PrintCursor(cursor, NULL);
1443 printf(" bitwidth=%d\n", Bitwidth);
1444 }
1445
1446 return CXChildVisit_Recurse;
1447}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001448
1449/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001450/* Loading ASTs/source. */
1451/******************************************************************************/
1452
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001453static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001454 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001455 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001456 PostVisitTU PV,
1457 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001458
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001459 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001460 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001461
1462 if (Visitor) {
1463 enum CXCursorKind K = CXCursor_NotImplemented;
1464 enum CXCursorKind *ck = &K;
1465 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001466
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001467 /* Perform some simple filtering. */
1468 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001469 else if (!strcmp(filter, "all-display") ||
1470 !strcmp(filter, "local-display")) {
1471 ck = NULL;
1472 want_display_name = 1;
1473 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001474 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001475 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1476 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1477 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1478 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1479 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1480 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1481 else {
1482 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1483 return 1;
1484 }
Ted Kremenek29004672010-02-17 00:41:32 +00001485
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001486 Data.TU = TU;
1487 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001488 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001489 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001490 }
Ted Kremenek29004672010-02-17 00:41:32 +00001491
Ted Kremenekb478ff42010-01-26 17:59:48 +00001492 if (PV)
1493 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001494
Douglas Gregor33cdd812010-02-18 18:08:43 +00001495 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001496 if (checkForErrors(TU) != 0) {
1497 clang_disposeTranslationUnit(TU);
1498 return -1;
1499 }
1500
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001501 clang_disposeTranslationUnit(TU);
1502 return 0;
1503}
1504
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001505int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001506 const char *prefix, CXCursorVisitor Visitor,
1507 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001508 CXIndex Idx;
1509 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001510 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001511 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001512 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001513 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001514
Ted Kremenek50228be2010-02-11 07:41:25 +00001515 if (!CreateTranslationUnit(Idx, file, &TU)) {
1516 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001517 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001518 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001519
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001520 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001521 clang_disposeIndex(Idx);
1522 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001523}
1524
Ted Kremenekb478ff42010-01-26 17:59:48 +00001525int perform_test_load_source(int argc, const char **argv,
1526 const char *filter, CXCursorVisitor Visitor,
1527 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001528 CXIndex Idx;
1529 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001530 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001531 struct CXUnsavedFile *unsaved_files = 0;
1532 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001533 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001534 int result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001535
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001536 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001537 (!strcmp(filter, "local") ||
1538 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001539 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001540
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001541 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1542 argc--;
1543 argv++;
1544 }
1545
Ted Kremenek50228be2010-02-11 07:41:25 +00001546 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1547 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001548 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001549 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001550
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001551 Err = clang_parseTranslationUnit2(Idx, 0,
1552 argv + num_unsaved_files,
1553 argc - num_unsaved_files,
1554 unsaved_files, num_unsaved_files,
1555 getDefaultParsingOptions(), &TU);
1556 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001557 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001558 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001559 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001560 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001561 return 1;
1562 }
1563
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001564 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1565 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001566 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001567 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001568 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001569}
1570
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001571int perform_test_reparse_source(int argc, const char **argv, int trials,
1572 const char *filter, CXCursorVisitor Visitor,
1573 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001574 CXIndex Idx;
1575 CXTranslationUnit TU;
1576 struct CXUnsavedFile *unsaved_files = 0;
1577 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001578 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001579 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001580 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001581 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001582 int remap_after_trial = 0;
1583 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001584
1585 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1586 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001587 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001588
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001589 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1590 clang_disposeIndex(Idx);
1591 return -1;
1592 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001593
1594 for (i = 0; i < argc; ++i) {
1595 if (strcmp(argv[i], "--") == 0)
1596 break;
1597 }
1598 if (i < argc)
1599 compiler_arg_idx = i+1;
1600 if (num_unsaved_files > compiler_arg_idx)
1601 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001602
Daniel Dunbarec29d712010-08-18 23:09:16 +00001603 /* Load the initial translation unit -- we do this without honoring remapped
1604 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001605 Err = clang_parseTranslationUnit2(Idx, 0,
1606 argv + compiler_arg_idx,
1607 argc - compiler_arg_idx,
1608 0, 0, getDefaultParsingOptions(), &TU);
1609 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001610 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001611 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001612 free_remapped_files(unsaved_files, num_unsaved_files);
1613 clang_disposeIndex(Idx);
1614 return 1;
1615 }
1616
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001617 if (checkForErrors(TU) != 0)
1618 return -1;
1619
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001620 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1621 remap_after_trial =
1622 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1623 }
1624
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001625 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001626 free_remapped_files(unsaved_files, num_unsaved_files);
1627 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1628 &unsaved_files, &num_unsaved_files)) {
1629 clang_disposeTranslationUnit(TU);
1630 clang_disposeIndex(Idx);
1631 return -1;
1632 }
1633
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001634 Err = clang_reparseTranslationUnit(
1635 TU,
1636 trial >= remap_after_trial ? num_unsaved_files : 0,
1637 trial >= remap_after_trial ? unsaved_files : 0,
1638 clang_defaultReparseOptions(TU));
1639 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001640 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001641 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001642 clang_disposeTranslationUnit(TU);
1643 free_remapped_files(unsaved_files, num_unsaved_files);
1644 clang_disposeIndex(Idx);
1645 return -1;
1646 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001647
1648 if (checkForErrors(TU) != 0)
1649 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001650 }
1651
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001652 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001653
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001654 free_remapped_files(unsaved_files, num_unsaved_files);
1655 clang_disposeIndex(Idx);
1656 return result;
1657}
1658
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001659/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001660/* Logic for testing clang_getCursor(). */
1661/******************************************************************************/
1662
Douglas Gregor37aa4932011-05-04 00:14:37 +00001663static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001664 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001665 unsigned end_line, unsigned end_col,
1666 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001667 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001668 if (prefix)
1669 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001670 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1671 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001672 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001673 printf("\n");
1674}
1675
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001676static int perform_file_scan(const char *ast_file, const char *source_file,
1677 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001678 CXIndex Idx;
1679 CXTranslationUnit TU;
1680 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001681 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001682 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001683 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001684 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001685
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001686 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001687 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001688 fprintf(stderr, "Could not create Index\n");
1689 return 1;
1690 }
Ted Kremenek29004672010-02-17 00:41:32 +00001691
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001692 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1693 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001694
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001695 if ((fp = fopen(source_file, "r")) == NULL) {
1696 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001697 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001698 return 1;
1699 }
Ted Kremenek29004672010-02-17 00:41:32 +00001700
Douglas Gregor816fd362010-01-22 21:44:22 +00001701 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001702 for (;;) {
1703 CXCursor cursor;
1704 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001705
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001706 if (c == '\n') {
1707 ++line;
1708 col = 1;
1709 } else
1710 ++col;
1711
1712 /* Check the cursor at this position, and dump the previous one if we have
1713 * found something new.
1714 */
1715 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1716 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1717 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001718 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001719 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001720 start_line = line;
1721 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001722 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001723 if (c == EOF)
1724 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001725
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001726 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001727 }
Ted Kremenek29004672010-02-17 00:41:32 +00001728
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001729 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001730 clang_disposeTranslationUnit(TU);
1731 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001732 return 0;
1733}
1734
1735/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001736/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001737/******************************************************************************/
1738
Douglas Gregor9eb77012009-11-07 00:00:49 +00001739/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1740 on failure. If successful, the pointer *filename will contain newly-allocated
1741 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001742int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001743 unsigned *column, unsigned *second_line,
1744 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001745 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001746 const char *last_colon = strrchr(input, ':');
1747 unsigned values[4], i;
1748 unsigned num_values = (second_line && second_column)? 4 : 2;
1749
Douglas Gregor9eb77012009-11-07 00:00:49 +00001750 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001751 if (!last_colon || last_colon == input) {
1752 if (num_values == 4)
1753 fprintf(stderr, "could not parse filename:line:column:line:column in "
1754 "'%s'\n", input);
1755 else
1756 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001757 return 1;
1758 }
1759
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001760 for (i = 0; i != num_values; ++i) {
1761 const char *prev_colon;
1762
1763 /* Parse the next line or column. */
1764 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1765 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001766 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001767 (i % 2 ? "column" : "line"), input);
1768 return 1;
1769 }
Ted Kremenek29004672010-02-17 00:41:32 +00001770
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001771 if (i + 1 == num_values)
1772 break;
1773
1774 /* Find the previous colon. */
1775 prev_colon = last_colon - 1;
1776 while (prev_colon != input && *prev_colon != ':')
1777 --prev_colon;
1778 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001779 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001780 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001781 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001782 }
1783
1784 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001785 }
1786
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001787 *line = values[0];
1788 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001789
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001790 if (second_line && second_column) {
1791 *second_line = values[2];
1792 *second_column = values[3];
1793 }
1794
Douglas Gregorf96ea292009-11-09 18:19:57 +00001795 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001796 *filename = (char*)malloc(last_colon - input + 1);
1797 memcpy(*filename, input, last_colon - input);
1798 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001799 return 0;
1800}
1801
1802const char *
1803clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1804 switch (Kind) {
1805 case CXCompletionChunk_Optional: return "Optional";
1806 case CXCompletionChunk_TypedText: return "TypedText";
1807 case CXCompletionChunk_Text: return "Text";
1808 case CXCompletionChunk_Placeholder: return "Placeholder";
1809 case CXCompletionChunk_Informative: return "Informative";
1810 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1811 case CXCompletionChunk_LeftParen: return "LeftParen";
1812 case CXCompletionChunk_RightParen: return "RightParen";
1813 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1814 case CXCompletionChunk_RightBracket: return "RightBracket";
1815 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1816 case CXCompletionChunk_RightBrace: return "RightBrace";
1817 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1818 case CXCompletionChunk_RightAngle: return "RightAngle";
1819 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001820 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001821 case CXCompletionChunk_Colon: return "Colon";
1822 case CXCompletionChunk_SemiColon: return "SemiColon";
1823 case CXCompletionChunk_Equal: return "Equal";
1824 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1825 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001826 }
Ted Kremenek29004672010-02-17 00:41:32 +00001827
Douglas Gregor9eb77012009-11-07 00:00:49 +00001828 return "Unknown";
1829}
1830
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001831static int checkForErrors(CXTranslationUnit TU) {
1832 unsigned Num, i;
1833 CXDiagnostic Diag;
1834 CXString DiagStr;
1835
1836 if (!getenv("CINDEXTEST_FAILONERROR"))
1837 return 0;
1838
1839 Num = clang_getNumDiagnostics(TU);
1840 for (i = 0; i != Num; ++i) {
1841 Diag = clang_getDiagnostic(TU, i);
1842 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1843 DiagStr = clang_formatDiagnostic(Diag,
1844 clang_defaultDiagnosticDisplayOptions());
1845 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1846 clang_disposeString(DiagStr);
1847 clang_disposeDiagnostic(Diag);
1848 return -1;
1849 }
1850 clang_disposeDiagnostic(Diag);
1851 }
1852
1853 return 0;
1854}
1855
Nico Weber8d19dff2014-05-07 21:05:22 +00001856static void print_completion_string(CXCompletionString completion_string,
1857 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001858 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001859
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001860 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001861 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001862 CXString text;
1863 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001864 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001865 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001866
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001867 if (Kind == CXCompletionChunk_Optional) {
1868 fprintf(file, "{Optional ");
1869 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001870 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001871 file);
1872 fprintf(file, "}");
1873 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001874 }
1875
1876 if (Kind == CXCompletionChunk_VerticalSpace) {
1877 fprintf(file, "{VerticalSpace }");
1878 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001879 }
Ted Kremenek29004672010-02-17 00:41:32 +00001880
Douglas Gregorf81f5282009-11-09 17:05:28 +00001881 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001882 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001883 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001884 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001885 cstr ? cstr : "");
1886 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001887 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001888
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001889}
1890
Nico Weber8d19dff2014-05-07 21:05:22 +00001891static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001892 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001893 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001894 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001895 enum CXCursorKind ParentKind;
1896 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001897 CXString BriefComment;
1898 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001899
Ted Kremenek29004672010-02-17 00:41:32 +00001900 fprintf(file, "%s:", clang_getCString(ks));
1901 clang_disposeString(ks);
1902
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001903 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001904 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001905 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001906 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1907 case CXAvailability_Available:
1908 break;
1909
1910 case CXAvailability_Deprecated:
1911 fprintf(file, " (deprecated)");
1912 break;
1913
1914 case CXAvailability_NotAvailable:
1915 fprintf(file, " (unavailable)");
1916 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001917
1918 case CXAvailability_NotAccessible:
1919 fprintf(file, " (inaccessible)");
1920 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00001921 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001922
1923 annotationCount = clang_getCompletionNumAnnotations(
1924 completion_result->CompletionString);
1925 if (annotationCount) {
1926 unsigned i;
1927 fprintf(file, " (");
1928 for (i = 0; i < annotationCount; ++i) {
1929 if (i != 0)
1930 fprintf(file, ", ");
1931 fprintf(file, "\"%s\"",
1932 clang_getCString(clang_getCompletionAnnotation(
1933 completion_result->CompletionString, i)));
1934 }
1935 fprintf(file, ")");
1936 }
1937
Douglas Gregor78254c82012-03-27 23:34:16 +00001938 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1939 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1940 &ParentKind);
1941 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001942 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00001943 fprintf(file, " (parent: %s '%s')",
1944 clang_getCString(KindSpelling),
1945 clang_getCString(ParentName));
1946 clang_disposeString(KindSpelling);
1947 }
1948 clang_disposeString(ParentName);
1949 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001950
1951 BriefComment = clang_getCompletionBriefComment(
1952 completion_result->CompletionString);
1953 BriefCommentCString = clang_getCString(BriefComment);
1954 if (BriefCommentCString && *BriefCommentCString != '\0') {
1955 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1956 }
1957 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00001958
Douglas Gregorf757a122010-08-23 23:00:57 +00001959 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00001960}
1961
Douglas Gregor21325842011-07-07 16:03:39 +00001962void print_completion_contexts(unsigned long long contexts, FILE *file) {
1963 fprintf(file, "Completion contexts:\n");
1964 if (contexts == CXCompletionContext_Unknown) {
1965 fprintf(file, "Unknown\n");
1966 }
1967 if (contexts & CXCompletionContext_AnyType) {
1968 fprintf(file, "Any type\n");
1969 }
1970 if (contexts & CXCompletionContext_AnyValue) {
1971 fprintf(file, "Any value\n");
1972 }
1973 if (contexts & CXCompletionContext_ObjCObjectValue) {
1974 fprintf(file, "Objective-C object value\n");
1975 }
1976 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1977 fprintf(file, "Objective-C selector value\n");
1978 }
1979 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1980 fprintf(file, "C++ class type value\n");
1981 }
1982 if (contexts & CXCompletionContext_DotMemberAccess) {
1983 fprintf(file, "Dot member access\n");
1984 }
1985 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1986 fprintf(file, "Arrow member access\n");
1987 }
1988 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1989 fprintf(file, "Objective-C property access\n");
1990 }
1991 if (contexts & CXCompletionContext_EnumTag) {
1992 fprintf(file, "Enum tag\n");
1993 }
1994 if (contexts & CXCompletionContext_UnionTag) {
1995 fprintf(file, "Union tag\n");
1996 }
1997 if (contexts & CXCompletionContext_StructTag) {
1998 fprintf(file, "Struct tag\n");
1999 }
2000 if (contexts & CXCompletionContext_ClassTag) {
2001 fprintf(file, "Class name\n");
2002 }
2003 if (contexts & CXCompletionContext_Namespace) {
2004 fprintf(file, "Namespace or namespace alias\n");
2005 }
2006 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2007 fprintf(file, "Nested name specifier\n");
2008 }
2009 if (contexts & CXCompletionContext_ObjCInterface) {
2010 fprintf(file, "Objective-C interface\n");
2011 }
2012 if (contexts & CXCompletionContext_ObjCProtocol) {
2013 fprintf(file, "Objective-C protocol\n");
2014 }
2015 if (contexts & CXCompletionContext_ObjCCategory) {
2016 fprintf(file, "Objective-C category\n");
2017 }
2018 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2019 fprintf(file, "Objective-C instance method\n");
2020 }
2021 if (contexts & CXCompletionContext_ObjCClassMessage) {
2022 fprintf(file, "Objective-C class method\n");
2023 }
2024 if (contexts & CXCompletionContext_ObjCSelectorName) {
2025 fprintf(file, "Objective-C selector name\n");
2026 }
2027 if (contexts & CXCompletionContext_MacroName) {
2028 fprintf(file, "Macro name\n");
2029 }
2030 if (contexts & CXCompletionContext_NaturalLanguage) {
2031 fprintf(file, "Natural language\n");
2032 }
2033}
2034
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002035int my_stricmp(const char *s1, const char *s2) {
2036 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00002037 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002038 if (c1 < c2)
2039 return -1;
2040 else if (c1 > c2)
2041 return 1;
2042
2043 ++s1;
2044 ++s2;
2045 }
2046
2047 if (*s1)
2048 return 1;
2049 else if (*s2)
2050 return -1;
2051 return 0;
2052}
2053
Douglas Gregor47815d52010-07-12 18:38:41 +00002054int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002055 const char *input = argv[1];
2056 char *filename = 0;
2057 unsigned line;
2058 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002059 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002060 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002061 struct CXUnsavedFile *unsaved_files = 0;
2062 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002063 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002064 enum CXErrorCode Err;
2065 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002066 unsigned I, Repeats = 1;
2067 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2068
2069 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2070 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002071 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2072 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002073
Douglas Gregor47815d52010-07-12 18:38:41 +00002074 if (timing_only)
2075 input += strlen("-code-completion-timing=");
2076 else
2077 input += strlen("-code-completion-at=");
2078
Ted Kremenek29004672010-02-17 00:41:32 +00002079 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002080 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002081 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002082
Douglas Gregor9485bf92009-12-02 09:21:34 +00002083 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2084 return -1;
2085
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002086 CIdx = clang_createIndex(0, 0);
2087
2088 if (getenv("CINDEXTEST_EDITING"))
2089 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002090
2091 Err = clang_parseTranslationUnit2(CIdx, 0,
2092 argv + num_unsaved_files + 2,
2093 argc - num_unsaved_files - 2,
2094 0, 0, getDefaultParsingOptions(), &TU);
2095 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002096 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002097 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002098 return 1;
2099 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002100
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002101 Err = clang_reparseTranslationUnit(TU, 0, 0,
2102 clang_defaultReparseOptions(TU));
2103
2104 if (Err != CXError_Success) {
Douglas Gregorc6592922010-11-15 23:00:34 +00002105 fprintf(stderr, "Unable to reparse translation init!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002106 describeLibclangFailure(Err);
2107 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002108 return 1;
2109 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002110
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002111 for (I = 0; I != Repeats; ++I) {
2112 results = clang_codeCompleteAt(TU, filename, line, column,
2113 unsaved_files, num_unsaved_files,
2114 completionOptions);
2115 if (!results) {
2116 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002117 return 1;
2118 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002119 if (I != Repeats-1)
2120 clang_disposeCodeCompleteResults(results);
2121 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002122
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002123 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002124 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002125 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002126 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002127 CXString objCSelector;
2128 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002129 if (!timing_only) {
2130 /* Sort the code-completion results based on the typed text. */
2131 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2132
Douglas Gregor47815d52010-07-12 18:38:41 +00002133 for (i = 0; i != n; ++i)
2134 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002135 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002136 n = clang_codeCompleteGetNumDiagnostics(results);
2137 for (i = 0; i != n; ++i) {
2138 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2139 PrintDiagnostic(diag);
2140 clang_disposeDiagnostic(diag);
2141 }
Douglas Gregor21325842011-07-07 16:03:39 +00002142
2143 contexts = clang_codeCompleteGetContexts(results);
2144 print_completion_contexts(contexts, stdout);
2145
Douglas Gregorea777402011-07-26 15:24:30 +00002146 containerKind = clang_codeCompleteGetContainerKind(results,
2147 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002148
2149 if (containerKind != CXCursor_InvalidCode) {
2150 /* We have found a container */
2151 CXString containerUSR, containerKindSpelling;
2152 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2153 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2154 clang_disposeString(containerKindSpelling);
2155
2156 if (containerIsIncomplete) {
2157 printf("Container is incomplete\n");
2158 }
2159 else {
2160 printf("Container is complete\n");
2161 }
2162
2163 containerUSR = clang_codeCompleteGetContainerUSR(results);
2164 printf("Container USR: %s\n", clang_getCString(containerUSR));
2165 clang_disposeString(containerUSR);
2166 }
2167
Douglas Gregorea777402011-07-26 15:24:30 +00002168 objCSelector = clang_codeCompleteGetObjCSelector(results);
2169 selectorString = clang_getCString(objCSelector);
2170 if (selectorString && strlen(selectorString) > 0) {
2171 printf("Objective-C selector: %s\n", selectorString);
2172 }
2173 clang_disposeString(objCSelector);
2174
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002175 clang_disposeCodeCompleteResults(results);
2176 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002177 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002178 clang_disposeIndex(CIdx);
2179 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002180
Douglas Gregor9485bf92009-12-02 09:21:34 +00002181 free_remapped_files(unsaved_files, num_unsaved_files);
2182
Ted Kremenekef3339b2009-11-17 18:09:14 +00002183 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002184}
2185
Douglas Gregor082c3e62010-01-15 19:40:17 +00002186typedef struct {
2187 char *filename;
2188 unsigned line;
2189 unsigned column;
2190} CursorSourceLocation;
2191
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002192static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002193 CXIndex CIdx;
2194 int errorCode;
2195 struct CXUnsavedFile *unsaved_files = 0;
2196 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002197 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002198 CXTranslationUnit TU;
2199 CXCursor Cursor;
2200 CursorSourceLocation *Locations = 0;
2201 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002202 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002203 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002204
Ted Kremenek29004672010-02-17 00:41:32 +00002205 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002206 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2207 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002208
Douglas Gregor082c3e62010-01-15 19:40:17 +00002209 /* Parse the locations. */
2210 assert(NumLocations > 0 && "Unable to count locations?");
2211 Locations = (CursorSourceLocation *)malloc(
2212 NumLocations * sizeof(CursorSourceLocation));
2213 for (Loc = 0; Loc < NumLocations; ++Loc) {
2214 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002215 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2216 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002217 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002218 return errorCode;
2219 }
Ted Kremenek29004672010-02-17 00:41:32 +00002220
2221 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002222 &num_unsaved_files))
2223 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002224
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002225 if (getenv("CINDEXTEST_EDITING"))
2226 Repeats = 5;
2227
2228 /* Parse the translation unit. When we're testing clang_getCursor() after
2229 reparsing, don't remap unsaved files until the second parse. */
2230 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002231 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2232 argv + num_unsaved_files + 1 + NumLocations,
2233 argc - num_unsaved_files - 2 - NumLocations,
2234 unsaved_files,
2235 Repeats > 1? 0 : num_unsaved_files,
2236 getDefaultParsingOptions(), &TU);
2237 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002238 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002239 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002240 return -1;
2241 }
Ted Kremenek29004672010-02-17 00:41:32 +00002242
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002243 if (checkForErrors(TU) != 0)
2244 return -1;
2245
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002246 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002247 if (Repeats > 1) {
2248 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2249 clang_defaultReparseOptions(TU));
2250 if (Err != CXError_Success) {
2251 describeLibclangFailure(Err);
2252 clang_disposeTranslationUnit(TU);
2253 return 1;
2254 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002255 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002256
2257 if (checkForErrors(TU) != 0)
2258 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002259
2260 for (Loc = 0; Loc < NumLocations; ++Loc) {
2261 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2262 if (!file)
2263 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002264
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002265 Cursor = clang_getCursor(TU,
2266 clang_getLocation(TU, file, Locations[Loc].line,
2267 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002268
2269 if (checkForErrors(TU) != 0)
2270 return -1;
2271
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002272 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002273 CXCompletionString completionString = clang_getCursorCompletionString(
2274 Cursor);
2275 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002276 CXString Spelling;
2277 const char *cspell;
2278 unsigned line, column;
2279 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2280 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002281 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002282 PrintCursorExtent(Cursor);
2283 Spelling = clang_getCursorSpelling(Cursor);
2284 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002285 if (cspell && strlen(cspell) != 0) {
2286 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002287 printf(" Spelling=%s (", cspell);
2288 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002289 CXSourceRange range =
2290 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002291 if (clang_Range_isNull(range))
2292 break;
2293 PrintRange(range, 0);
2294 }
2295 printf(")");
2296 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002297 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002298 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
Nico Weber8d19dff2014-05-07 21:05:22 +00002299 printf(" Selector index=%d",
2300 clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002301 if (clang_Cursor_isDynamicCall(Cursor))
2302 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002303 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002304 CXType T = clang_Cursor_getReceiverType(Cursor);
2305 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002306 printf(" Receiver-type=%s", clang_getCString(S));
2307 clang_disposeString(S);
2308 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002309
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002310 {
2311 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002312 CXFile astFile;
2313 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002314 unsigned i, numHeaders;
2315 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002316 astFile = clang_Module_getASTFile(mod);
2317 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002318 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002319 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002320 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002321 clang_getCString(name), clang_getCString(astFilename),
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002322 clang_Module_isSystem(mod), numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002323 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002324 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002325 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002326 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2327 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002328 printf("\n%s", clang_getCString(filename));
2329 clang_disposeString(filename);
2330 }
2331 }
2332 }
2333
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002334 if (completionString != NULL) {
2335 printf("\nCompletion string: ");
2336 print_completion_string(completionString, stdout);
2337 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002338 printf("\n");
2339 free(Locations[Loc].filename);
2340 }
2341 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002342 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002343
Douglas Gregor33cdd812010-02-18 18:08:43 +00002344 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002345 clang_disposeTranslationUnit(TU);
2346 clang_disposeIndex(CIdx);
2347 free(Locations);
2348 free_remapped_files(unsaved_files, num_unsaved_files);
2349 return 0;
2350}
2351
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002352static enum CXVisitorResult findFileRefsVisit(void *context,
2353 CXCursor cursor, CXSourceRange range) {
2354 if (clang_Range_isNull(range))
2355 return CXVisit_Continue;
2356
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002357 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002358 PrintRange(range, "");
2359 printf("\n");
2360 return CXVisit_Continue;
2361}
2362
2363static int find_file_refs_at(int argc, const char **argv) {
2364 CXIndex CIdx;
2365 int errorCode;
2366 struct CXUnsavedFile *unsaved_files = 0;
2367 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002368 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002369 CXTranslationUnit TU;
2370 CXCursor Cursor;
2371 CursorSourceLocation *Locations = 0;
2372 unsigned NumLocations = 0, Loc;
2373 unsigned Repeats = 1;
2374 unsigned I;
2375
2376 /* Count the number of locations. */
2377 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2378 ++NumLocations;
2379
2380 /* Parse the locations. */
2381 assert(NumLocations > 0 && "Unable to count locations?");
2382 Locations = (CursorSourceLocation *)malloc(
2383 NumLocations * sizeof(CursorSourceLocation));
2384 for (Loc = 0; Loc < NumLocations; ++Loc) {
2385 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2386 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2387 &Locations[Loc].line,
2388 &Locations[Loc].column, 0, 0)))
2389 return errorCode;
2390 }
2391
2392 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2393 &num_unsaved_files))
2394 return -1;
2395
2396 if (getenv("CINDEXTEST_EDITING"))
2397 Repeats = 5;
2398
2399 /* Parse the translation unit. When we're testing clang_getCursor() after
2400 reparsing, don't remap unsaved files until the second parse. */
2401 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002402 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2403 argv + num_unsaved_files + 1 + NumLocations,
2404 argc - num_unsaved_files - 2 - NumLocations,
2405 unsaved_files,
2406 Repeats > 1? 0 : num_unsaved_files,
2407 getDefaultParsingOptions(), &TU);
2408 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002409 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002410 describeLibclangFailure(Err);
2411 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002412 return -1;
2413 }
2414
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002415 if (checkForErrors(TU) != 0)
2416 return -1;
2417
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002418 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002419 if (Repeats > 1) {
2420 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2421 clang_defaultReparseOptions(TU));
2422 if (Err != CXError_Success) {
2423 describeLibclangFailure(Err);
2424 clang_disposeTranslationUnit(TU);
2425 return 1;
2426 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002427 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002428
2429 if (checkForErrors(TU) != 0)
2430 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002431
2432 for (Loc = 0; Loc < NumLocations; ++Loc) {
2433 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2434 if (!file)
2435 continue;
2436
2437 Cursor = clang_getCursor(TU,
2438 clang_getLocation(TU, file, Locations[Loc].line,
2439 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002440
2441 if (checkForErrors(TU) != 0)
2442 return -1;
2443
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002444 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002445 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002446 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002447 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002448 clang_findReferencesInFile(Cursor, file, visitor);
2449 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002450
2451 if (checkForErrors(TU) != 0)
2452 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002453 }
2454 }
2455 }
2456
2457 PrintDiagnostics(TU);
2458 clang_disposeTranslationUnit(TU);
2459 clang_disposeIndex(CIdx);
2460 free(Locations);
2461 free_remapped_files(unsaved_files, num_unsaved_files);
2462 return 0;
2463}
2464
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002465static enum CXVisitorResult findFileIncludesVisit(void *context,
2466 CXCursor cursor, CXSourceRange range) {
2467 PrintCursor(cursor, NULL);
2468 PrintRange(range, "");
2469 printf("\n");
2470 return CXVisit_Continue;
2471}
2472
2473static int find_file_includes_in(int argc, const char **argv) {
2474 CXIndex CIdx;
2475 struct CXUnsavedFile *unsaved_files = 0;
2476 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002477 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002478 CXTranslationUnit TU;
2479 const char **Filenames = 0;
2480 unsigned NumFilenames = 0;
2481 unsigned Repeats = 1;
2482 unsigned I, FI;
2483
2484 /* Count the number of locations. */
2485 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2486 ++NumFilenames;
2487
2488 /* Parse the locations. */
2489 assert(NumFilenames > 0 && "Unable to count filenames?");
2490 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2491 for (I = 0; I < NumFilenames; ++I) {
2492 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2493 /* Copy the file name. */
2494 Filenames[I] = input;
2495 }
2496
2497 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2498 &num_unsaved_files))
2499 return -1;
2500
2501 if (getenv("CINDEXTEST_EDITING"))
2502 Repeats = 2;
2503
2504 /* Parse the translation unit. When we're testing clang_getCursor() after
2505 reparsing, don't remap unsaved files until the second parse. */
2506 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002507 Err = clang_parseTranslationUnit2(
2508 CIdx, argv[argc - 1],
2509 argv + num_unsaved_files + 1 + NumFilenames,
2510 argc - num_unsaved_files - 2 - NumFilenames,
2511 unsaved_files,
2512 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002513
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002514 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002515 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002516 describeLibclangFailure(Err);
2517 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002518 return -1;
2519 }
2520
2521 if (checkForErrors(TU) != 0)
2522 return -1;
2523
2524 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002525 if (Repeats > 1) {
2526 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2527 clang_defaultReparseOptions(TU));
2528 if (Err != CXError_Success) {
2529 describeLibclangFailure(Err);
2530 clang_disposeTranslationUnit(TU);
2531 return 1;
2532 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002533 }
2534
2535 if (checkForErrors(TU) != 0)
2536 return -1;
2537
2538 for (FI = 0; FI < NumFilenames; ++FI) {
2539 CXFile file = clang_getFile(TU, Filenames[FI]);
2540 if (!file)
2541 continue;
2542
2543 if (checkForErrors(TU) != 0)
2544 return -1;
2545
2546 if (I + 1 == Repeats) {
2547 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2548 clang_findIncludesInFile(TU, file, visitor);
2549
2550 if (checkForErrors(TU) != 0)
2551 return -1;
2552 }
2553 }
2554 }
2555
2556 PrintDiagnostics(TU);
2557 clang_disposeTranslationUnit(TU);
2558 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002559 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002560 free_remapped_files(unsaved_files, num_unsaved_files);
2561 return 0;
2562}
2563
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002564#define MAX_IMPORTED_ASTFILES 200
2565
2566typedef struct {
2567 char **filenames;
2568 unsigned num_files;
2569} ImportedASTFilesData;
2570
2571static ImportedASTFilesData *importedASTs_create() {
2572 ImportedASTFilesData *p;
2573 p = malloc(sizeof(ImportedASTFilesData));
2574 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2575 p->num_files = 0;
2576 return p;
2577}
2578
2579static void importedASTs_dispose(ImportedASTFilesData *p) {
2580 unsigned i;
2581 if (!p)
2582 return;
2583
2584 for (i = 0; i < p->num_files; ++i)
2585 free(p->filenames[i]);
2586 free(p->filenames);
2587 free(p);
2588}
2589
2590static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2591 unsigned i;
2592 assert(p && file);
2593 for (i = 0; i < p->num_files; ++i)
2594 if (strcmp(file, p->filenames[i]) == 0)
2595 return;
2596 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2597 p->filenames[p->num_files++] = strdup(file);
2598}
2599
Nico Weberdf686022014-05-07 21:09:42 +00002600typedef struct IndexDataStringList_ {
2601 struct IndexDataStringList_ *next;
2602 char data[1]; /* Dynamically sized. */
2603} IndexDataStringList;
2604
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002605typedef struct {
2606 const char *check_prefix;
2607 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002608 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002609 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002610 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002611 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002612 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002613 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002614} IndexData;
2615
Nico Weberdf686022014-05-07 21:09:42 +00002616static void free_client_data(IndexData *index_data) {
2617 IndexDataStringList *node = index_data->strings;
2618 while (node) {
2619 IndexDataStringList *next = node->next;
2620 free(node);
2621 node = next;
2622 }
2623 index_data->strings = NULL;
2624}
2625
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002626static void printCheck(IndexData *data) {
2627 if (data->check_prefix) {
2628 if (data->first_check_printed) {
2629 printf("// %s-NEXT: ", data->check_prefix);
2630 } else {
2631 printf("// %s : ", data->check_prefix);
2632 data->first_check_printed = 1;
2633 }
2634 }
2635}
2636
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002637static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002638 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002639 printf("%s", clang_getCString(filename));
2640 clang_disposeString(filename);
2641}
2642
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002643static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2644 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002645 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002646 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002647 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002648 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002649 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002650
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002651 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002652 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2653 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002654 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002655 return;
2656 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002657 if (!file) {
2658 printf("<no idxfile>");
2659 return;
2660 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002661 filename = clang_getFileName((CXFile)file);
2662 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002663 if (strcmp(cname, index_data->main_filename) == 0)
2664 isMainFile = 1;
2665 else
2666 isMainFile = 0;
2667 clang_disposeString(filename);
2668
2669 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002670 printCXIndexFile(file);
2671 printf(":");
2672 }
2673 printf("%d:%d", line, column);
2674}
2675
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002676static unsigned digitCount(unsigned val) {
2677 unsigned c = 1;
2678 while (1) {
2679 if (val < 10)
2680 return c;
2681 ++c;
2682 val /= 10;
2683 }
2684}
2685
Nico Weberdf686022014-05-07 21:09:42 +00002686static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2687 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002688 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002689 IndexData *index_data;
2690 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002691 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002692 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002693 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002694 unsigned line, column;
2695
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002696 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002697 if (!name)
2698 name = "<anon-tag>";
2699
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002700 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002701
2702 node =
2703 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2704 digitCount(line) + digitCount(column) + 2);
2705 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002706 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002707
2708 /* Remember string so it can be freed later. */
2709 index_data = (IndexData *)client_data;
2710 node->next = index_data->strings;
2711 index_data->strings = node;
2712
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002713 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002714}
2715
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002716static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2717 CXIdxClientContainer container;
2718 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002719 if (!container)
2720 printf("[<<NULL>>]");
2721 else
2722 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002723}
2724
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002725static const char *getEntityKindString(CXIdxEntityKind kind) {
2726 switch (kind) {
2727 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2728 case CXIdxEntity_Typedef: return "typedef";
2729 case CXIdxEntity_Function: return "function";
2730 case CXIdxEntity_Variable: return "variable";
2731 case CXIdxEntity_Field: return "field";
2732 case CXIdxEntity_EnumConstant: return "enumerator";
2733 case CXIdxEntity_ObjCClass: return "objc-class";
2734 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2735 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002736 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2737 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002738 case CXIdxEntity_ObjCProperty: return "objc-property";
2739 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2740 case CXIdxEntity_Enum: return "enum";
2741 case CXIdxEntity_Struct: return "struct";
2742 case CXIdxEntity_Union: return "union";
2743 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002744 case CXIdxEntity_CXXNamespace: return "namespace";
2745 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2746 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2747 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2748 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2749 case CXIdxEntity_CXXConstructor: return "constructor";
2750 case CXIdxEntity_CXXDestructor: return "destructor";
2751 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2752 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002753 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002754 }
2755 assert(0 && "Garbage entity kind");
2756 return 0;
2757}
2758
2759static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2760 switch (kind) {
2761 case CXIdxEntity_NonTemplate: return "";
2762 case CXIdxEntity_Template: return "-template";
2763 case CXIdxEntity_TemplatePartialSpecialization:
2764 return "-template-partial-spec";
2765 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002766 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002767 assert(0 && "Garbage entity kind");
2768 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002769}
2770
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002771static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2772 switch (kind) {
2773 case CXIdxEntityLang_None: return "<none>";
2774 case CXIdxEntityLang_C: return "C";
2775 case CXIdxEntityLang_ObjC: return "ObjC";
2776 case CXIdxEntityLang_CXX: return "C++";
2777 }
2778 assert(0 && "Garbage language kind");
2779 return 0;
2780}
2781
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002782static void printEntityInfo(const char *cb,
2783 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002784 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002785 const char *name;
2786 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002787 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002788 index_data = (IndexData *)client_data;
2789 printCheck(index_data);
2790
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002791 if (!info) {
2792 printf("%s: <<NULL>>", cb);
2793 return;
2794 }
2795
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002796 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002797 if (!name)
2798 name = "<anon-tag>";
2799
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002800 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2801 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002802 printf(" | name: %s", name);
2803 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002804 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002805
2806 for (i = 0; i != info->numAttributes; ++i) {
2807 const CXIdxAttrInfo *Attr = info->attributes[i];
2808 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002809 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002810 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002811}
2812
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002813static void printBaseClassInfo(CXClientData client_data,
2814 const CXIdxBaseClassInfo *info) {
2815 printEntityInfo(" <base>", client_data, info->base);
2816 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002817 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002818 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002819 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002820}
2821
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002822static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2823 CXClientData client_data) {
2824 unsigned i;
2825 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2826 printEntityInfo(" <protocol>", client_data,
2827 ProtoInfo->protocols[i]->protocol);
2828 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002829 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002830 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002831 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002832 printf("\n");
2833 }
2834}
2835
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002836static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002837 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002838 CXString str;
2839 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002840 unsigned numDiags, i;
2841 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002842 IndexData *index_data;
2843 index_data = (IndexData *)client_data;
2844 printCheck(index_data);
2845
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002846 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2847 for (i = 0; i != numDiags; ++i) {
2848 diag = clang_getDiagnosticInSet(diagSet, i);
2849 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2850 cstr = clang_getCString(str);
2851 printf("[diagnostic]: %s\n", cstr);
2852 clang_disposeString(str);
2853
2854 if (getenv("CINDEXTEST_FAILONERROR") &&
2855 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2856 index_data->fail_for_error = 1;
2857 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002858 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002859}
2860
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002861static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2862 CXFile file, void *reserved) {
2863 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002864 CXString filename;
2865
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002866 index_data = (IndexData *)client_data;
2867 printCheck(index_data);
2868
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002869 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002870 index_data->main_filename = clang_getCString(filename);
2871 clang_disposeString(filename);
2872
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002873 printf("[enteredMainFile]: ");
2874 printCXIndexFile((CXIdxClientFile)file);
2875 printf("\n");
2876
2877 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002878}
2879
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002880static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002881 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002882 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002883 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002884 index_data = (IndexData *)client_data;
2885 printCheck(index_data);
2886
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002887 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002888 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002889 printf(" | name: \"%s\"", info->filename);
2890 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002891 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002892 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002893 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002894
2895 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
2896 if (Mod) {
2897 CXString str = clang_Module_getFullName(Mod);
2898 const char *cstr = clang_getCString(str);
2899 printf(" | module: %s", cstr);
2900 clang_disposeString(str);
2901 }
2902
2903 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002904
2905 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002906}
2907
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002908static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2909 const CXIdxImportedASTFileInfo *info) {
2910 IndexData *index_data;
2911 index_data = (IndexData *)client_data;
2912 printCheck(index_data);
2913
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002914 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002915 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002916 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2917 clang_disposeString(filename);
2918 }
2919
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002920 printf("[importedASTFile]: ");
2921 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002922 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002923 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002924 printf(" | loc: ");
2925 printCXIndexLoc(info->loc, client_data);
2926 printf(" | name: \"%s\"", clang_getCString(name));
2927 printf(" | isImplicit: %d\n", info->isImplicit);
2928 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002929 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00002930 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002931 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002932 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002933
2934 return (CXIdxClientFile)info->file;
2935}
2936
Nico Weber8d19dff2014-05-07 21:05:22 +00002937static CXIdxClientContainer
2938index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002939 IndexData *index_data;
2940 index_data = (IndexData *)client_data;
2941 printCheck(index_data);
2942
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002943 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002944 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002945}
2946
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002947static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002948 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002949 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002950 const CXIdxObjCCategoryDeclInfo *CatInfo;
2951 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002952 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002953 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002954 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002955 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002956 index_data = (IndexData *)client_data;
2957
2958 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2959 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002960 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002961 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002962 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00002963 printf(" | semantic-container: ");
2964 printCXIndexContainer(info->semanticContainer);
2965 printf(" | lexical-container: ");
2966 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002967 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002968 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00002969 if (info->flags & CXIdxDeclFlag_Skipped) {
2970 assert(!info->isContainer);
2971 printf(" | isContainer: skipped");
2972 } else {
2973 printf(" | isContainer: %d", info->isContainer);
2974 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002975 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002976
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002977 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00002978 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002979 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002980 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002981 printf("\n");
2982 }
2983
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002984 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2985 const char *kindName = 0;
2986 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2987 switch (K) {
2988 case CXIdxObjCContainer_ForwardRef:
2989 kindName = "forward-ref"; break;
2990 case CXIdxObjCContainer_Interface:
2991 kindName = "interface"; break;
2992 case CXIdxObjCContainer_Implementation:
2993 kindName = "implementation"; break;
2994 }
2995 printCheck(index_data);
2996 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
2997 }
2998
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002999 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003000 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3001 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003002 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003003 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003004 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003005 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003006 printf("\n");
3007 }
3008
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003009 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3010 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003011 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003012 printf("\n");
3013 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003014 }
3015
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003016 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3017 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003018 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003019
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003020 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3021 if (PropInfo->getter) {
3022 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3023 printf("\n");
3024 }
3025 if (PropInfo->setter) {
3026 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3027 printf("\n");
3028 }
3029 }
3030
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003031 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3032 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3033 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3034 printf("\n");
3035 }
3036 }
3037
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003038 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003039 clang_index_setClientContainer(
3040 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003041 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003042}
3043
3044static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003045 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003046 printEntityInfo("[indexEntityReference]", client_data,
3047 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003048 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003049 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003050 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003051 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003052 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003053 printf(" | container: ");
3054 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003055 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003056 switch (info->kind) {
3057 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003058 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003059 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003060 printf("\n");
3061}
3062
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003063static int index_abortQuery(CXClientData client_data, void *reserved) {
3064 IndexData *index_data;
3065 index_data = (IndexData *)client_data;
3066 return index_data->abort;
3067}
3068
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003069static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003070 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003071 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003072 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003073 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003074 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003075 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003076 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003077 index_indexEntityReference
3078};
3079
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003080static unsigned getIndexOptions(void) {
3081 unsigned index_opts;
3082 index_opts = 0;
3083 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3084 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3085 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3086 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003087 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3088 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003089
3090 return index_opts;
3091}
3092
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003093static int index_compile_args(int num_args, const char **args,
3094 CXIndexAction idxAction,
3095 ImportedASTFilesData *importedASTs,
3096 const char *check_prefix) {
3097 IndexData index_data;
3098 unsigned index_opts;
3099 int result;
3100
3101 if (num_args == 0) {
3102 fprintf(stderr, "no compiler arguments\n");
3103 return -1;
3104 }
3105
3106 index_data.check_prefix = check_prefix;
3107 index_data.first_check_printed = 0;
3108 index_data.fail_for_error = 0;
3109 index_data.abort = 0;
3110 index_data.main_filename = "";
3111 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003112 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003113 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003114
3115 index_opts = getIndexOptions();
3116 result = clang_indexSourceFile(idxAction, &index_data,
3117 &IndexCB,sizeof(IndexCB), index_opts,
3118 0, args, num_args, 0, 0, 0,
3119 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003120 if (result != CXError_Success)
3121 describeLibclangFailure(result);
3122
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003123 if (index_data.fail_for_error)
3124 result = -1;
3125
Nico Weberdf686022014-05-07 21:09:42 +00003126 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003127 return result;
3128}
3129
3130static int index_ast_file(const char *ast_file,
3131 CXIndex Idx,
3132 CXIndexAction idxAction,
3133 ImportedASTFilesData *importedASTs,
3134 const char *check_prefix) {
3135 CXTranslationUnit TU;
3136 IndexData index_data;
3137 unsigned index_opts;
3138 int result;
3139
3140 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3141 return -1;
3142
3143 index_data.check_prefix = check_prefix;
3144 index_data.first_check_printed = 0;
3145 index_data.fail_for_error = 0;
3146 index_data.abort = 0;
3147 index_data.main_filename = "";
3148 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003149 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003150 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003151
3152 index_opts = getIndexOptions();
3153 result = clang_indexTranslationUnit(idxAction, &index_data,
3154 &IndexCB,sizeof(IndexCB),
3155 index_opts, TU);
3156 if (index_data.fail_for_error)
3157 result = -1;
3158
3159 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003160 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003161 return result;
3162}
3163
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003164static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003165 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003166 CXIndex Idx;
3167 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003168 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003169 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003170
3171 check_prefix = 0;
3172 if (argc > 0) {
3173 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3174 check_prefix = argv[0] + strlen("-check-prefix=");
3175 ++argv;
3176 --argc;
3177 }
3178 }
3179
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003180 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003181 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003182 fprintf(stderr, "Could not create Index\n");
3183 return 1;
3184 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003185 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003186 importedASTs = 0;
3187 if (full)
3188 importedASTs = importedASTs_create();
3189
3190 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3191 if (result != 0)
3192 goto finished;
3193
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003194 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003195 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003196 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3197 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3198 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003199 }
3200 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003201
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003202finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003203 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003204 clang_IndexAction_dispose(idxAction);
3205 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003206 return result;
3207}
3208
3209static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003210 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003211 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003212 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003213 int result;
3214
3215 check_prefix = 0;
3216 if (argc > 0) {
3217 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3218 check_prefix = argv[0] + strlen("-check-prefix=");
3219 ++argv;
3220 --argc;
3221 }
3222 }
3223
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003224 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003225 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003226 fprintf(stderr, "Could not create Index\n");
3227 return 1;
3228 }
3229 idxAction = clang_IndexAction_create(Idx);
3230
3231 result = index_ast_file(argv[0], Idx, idxAction,
3232 /*importedASTs=*/0, check_prefix);
3233
3234 clang_IndexAction_dispose(idxAction);
3235 clang_disposeIndex(Idx);
3236 return result;
3237}
3238
3239static int index_compile_db(int argc, const char **argv) {
3240 const char *check_prefix;
3241 CXIndex Idx;
3242 CXIndexAction idxAction;
3243 int errorCode = 0;
3244
3245 check_prefix = 0;
3246 if (argc > 0) {
3247 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3248 check_prefix = argv[0] + strlen("-check-prefix=");
3249 ++argv;
3250 --argc;
3251 }
3252 }
3253
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003254 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003255 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003256 return -1;
3257 }
3258
3259 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003260 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003261 fprintf(stderr, "Could not create Index\n");
3262 return 1;
3263 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003264 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003265
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003266 {
3267 const char *database = argv[0];
3268 CXCompilationDatabase db = 0;
3269 CXCompileCommands CCmds = 0;
3270 CXCompileCommand CCmd;
3271 CXCompilationDatabase_Error ec;
3272 CXString wd;
3273#define MAX_COMPILE_ARGS 512
3274 CXString cxargs[MAX_COMPILE_ARGS];
3275 const char *args[MAX_COMPILE_ARGS];
3276 char *tmp;
3277 unsigned len;
3278 char *buildDir;
3279 int i, a, numCmds, numArgs;
3280
3281 len = strlen(database);
3282 tmp = (char *) malloc(len+1);
3283 memcpy(tmp, database, len+1);
3284 buildDir = dirname(tmp);
3285
3286 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3287
3288 if (db) {
3289
3290 if (ec!=CXCompilationDatabase_NoError) {
3291 printf("unexpected error %d code while loading compilation database\n", ec);
3292 errorCode = -1;
3293 goto cdb_end;
3294 }
3295
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003296 if (chdir(buildDir) != 0) {
3297 printf("Could not chdir to %s\n", buildDir);
3298 errorCode = -1;
3299 goto cdb_end;
3300 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003301
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003302 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003303 if (!CCmds) {
3304 printf("compilation db is empty\n");
3305 errorCode = -1;
3306 goto cdb_end;
3307 }
3308
3309 numCmds = clang_CompileCommands_getSize(CCmds);
3310
3311 if (numCmds==0) {
3312 fprintf(stderr, "should not get an empty compileCommand set\n");
3313 errorCode = -1;
3314 goto cdb_end;
3315 }
3316
3317 for (i=0; i<numCmds && errorCode == 0; ++i) {
3318 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3319
3320 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003321 if (chdir(clang_getCString(wd)) != 0) {
3322 printf("Could not chdir to %s\n", clang_getCString(wd));
3323 errorCode = -1;
3324 goto cdb_end;
3325 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003326 clang_disposeString(wd);
3327
3328 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3329 if (numArgs > MAX_COMPILE_ARGS){
3330 fprintf(stderr, "got more compile arguments than maximum\n");
3331 errorCode = -1;
3332 goto cdb_end;
3333 }
3334 for (a=0; a<numArgs; ++a) {
3335 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3336 args[a] = clang_getCString(cxargs[a]);
3337 }
3338
3339 errorCode = index_compile_args(numArgs, args, idxAction,
3340 /*importedASTs=*/0, check_prefix);
3341
3342 for (a=0; a<numArgs; ++a)
3343 clang_disposeString(cxargs[a]);
3344 }
3345 } else {
3346 printf("database loading failed with error code %d.\n", ec);
3347 errorCode = -1;
3348 }
3349
3350 cdb_end:
3351 clang_CompileCommands_dispose(CCmds);
3352 clang_CompilationDatabase_dispose(db);
3353 free(tmp);
3354
3355 }
3356
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003357 clang_IndexAction_dispose(idxAction);
3358 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003359 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003360}
3361
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003362int perform_token_annotation(int argc, const char **argv) {
3363 const char *input = argv[1];
3364 char *filename = 0;
3365 unsigned line, second_line;
3366 unsigned column, second_column;
3367 CXIndex CIdx;
3368 CXTranslationUnit TU = 0;
3369 int errorCode;
3370 struct CXUnsavedFile *unsaved_files = 0;
3371 int num_unsaved_files = 0;
3372 CXToken *tokens;
3373 unsigned num_tokens;
3374 CXSourceRange range;
3375 CXSourceLocation startLoc, endLoc;
3376 CXFile file = 0;
3377 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003378 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003379 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003380 unsigned i;
3381
3382 input += strlen("-test-annotate-tokens=");
3383 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3384 &second_line, &second_column)))
3385 return errorCode;
3386
Richard Smith1ea42eb2012-07-05 08:20:49 +00003387 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3388 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003389 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003390 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003391
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003392 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003393 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3394 argv + num_unsaved_files + 2,
3395 argc - num_unsaved_files - 3,
3396 unsaved_files,
3397 num_unsaved_files,
3398 getDefaultParsingOptions(), &TU);
3399 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003400 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003401 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003402 clang_disposeIndex(CIdx);
3403 free(filename);
3404 free_remapped_files(unsaved_files, num_unsaved_files);
3405 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003406 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003407 errorCode = 0;
3408
Richard Smith1ea42eb2012-07-05 08:20:49 +00003409 if (checkForErrors(TU) != 0) {
3410 errorCode = -1;
3411 goto teardown;
3412 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003413
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003414 if (getenv("CINDEXTEST_EDITING")) {
3415 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003416 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3417 clang_defaultReparseOptions(TU));
3418 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003419 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003420 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003421 errorCode = -1;
3422 goto teardown;
3423 }
3424 }
3425 }
3426
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003427 if (checkForErrors(TU) != 0) {
3428 errorCode = -1;
3429 goto teardown;
3430 }
3431
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003432 file = clang_getFile(TU, filename);
3433 if (!file) {
3434 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3435 errorCode = -1;
3436 goto teardown;
3437 }
3438
3439 startLoc = clang_getLocation(TU, file, line, column);
3440 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003441 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003442 column);
3443 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003444 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003445 }
3446
3447 endLoc = clang_getLocation(TU, file, second_line, second_column);
3448 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003449 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003450 second_line, second_column);
3451 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003452 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003453 }
3454
3455 range = clang_getRange(startLoc, endLoc);
3456 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003457
3458 if (checkForErrors(TU) != 0) {
3459 errorCode = -1;
3460 goto teardown;
3461 }
3462
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003463 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3464 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003465
3466 if (checkForErrors(TU) != 0) {
3467 errorCode = -1;
3468 goto teardown;
3469 }
3470
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003471 skipped_ranges = clang_getSkippedRanges(TU, file);
3472 for (i = 0; i != skipped_ranges->count; ++i) {
3473 unsigned start_line, start_column, end_line, end_column;
3474 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3475 0, &start_line, &start_column, 0);
3476 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3477 0, &end_line, &end_column, 0);
3478 printf("Skipping: ");
3479 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3480 printf("\n");
3481 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003482 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003483
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003484 for (i = 0; i != num_tokens; ++i) {
3485 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003486 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3487 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003488 unsigned start_line, start_column, end_line, end_column;
3489
3490 switch (clang_getTokenKind(tokens[i])) {
3491 case CXToken_Punctuation: kind = "Punctuation"; break;
3492 case CXToken_Keyword: kind = "Keyword"; break;
3493 case CXToken_Identifier: kind = "Identifier"; break;
3494 case CXToken_Literal: kind = "Literal"; break;
3495 case CXToken_Comment: kind = "Comment"; break;
3496 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003497 clang_getSpellingLocation(clang_getRangeStart(extent),
3498 0, &start_line, &start_column, 0);
3499 clang_getSpellingLocation(clang_getRangeEnd(extent),
3500 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003501 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003502 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003503 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003504 if (!clang_isInvalid(cursors[i].kind)) {
3505 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003506 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003507 }
3508 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003509 }
3510 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003511 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003512
3513 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003514 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003515 clang_disposeTranslationUnit(TU);
3516 clang_disposeIndex(CIdx);
3517 free(filename);
3518 free_remapped_files(unsaved_files, num_unsaved_files);
3519 return errorCode;
3520}
3521
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003522static int
3523perform_test_compilation_db(const char *database, int argc, const char **argv) {
3524 CXCompilationDatabase db;
3525 CXCompileCommands CCmds;
3526 CXCompileCommand CCmd;
3527 CXCompilationDatabase_Error ec;
3528 CXString wd;
3529 CXString arg;
3530 int errorCode = 0;
3531 char *tmp;
3532 unsigned len;
3533 char *buildDir;
3534 int i, j, a, numCmds, numArgs;
3535
3536 len = strlen(database);
3537 tmp = (char *) malloc(len+1);
3538 memcpy(tmp, database, len+1);
3539 buildDir = dirname(tmp);
3540
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003541 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003542
3543 if (db) {
3544
3545 if (ec!=CXCompilationDatabase_NoError) {
3546 printf("unexpected error %d code while loading compilation database\n", ec);
3547 errorCode = -1;
3548 goto cdb_end;
3549 }
3550
3551 for (i=0; i<argc && errorCode==0; ) {
3552 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003553 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003554
3555 if (!CCmds) {
3556 printf("file %s not found in compilation db\n", argv[i+1]);
3557 errorCode = -1;
3558 break;
3559 }
3560
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003561 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003562
3563 if (numCmds==0) {
3564 fprintf(stderr, "should not get an empty compileCommand set for file"
3565 " '%s'\n", argv[i+1]);
3566 errorCode = -1;
3567 break;
3568 }
3569
3570 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003571 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003572
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003573 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003574 printf("workdir:'%s'", clang_getCString(wd));
3575 clang_disposeString(wd);
3576
3577 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003578 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003579 for (a=0; a<numArgs; ++a) {
3580 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003581 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003582 printf("%s", clang_getCString(arg));
3583 clang_disposeString(arg);
3584 }
3585 printf("'\n");
3586 }
3587
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003588 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003589
3590 i += 2;
3591 }
3592 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003593 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003594 } else {
3595 printf("database loading failed with error code %d.\n", ec);
3596 errorCode = -1;
3597 }
3598
3599cdb_end:
3600 free(tmp);
3601
3602 return errorCode;
3603}
3604
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003605/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003606/* USR printing. */
3607/******************************************************************************/
3608
3609static int insufficient_usr(const char *kind, const char *usage) {
3610 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3611 return 1;
3612}
3613
3614static unsigned isUSR(const char *s) {
3615 return s[0] == 'c' && s[1] == ':';
3616}
3617
3618static int not_usr(const char *s, const char *arg) {
3619 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3620 return 1;
3621}
3622
3623static void print_usr(CXString usr) {
3624 const char *s = clang_getCString(usr);
3625 printf("%s\n", s);
3626 clang_disposeString(usr);
3627}
3628
3629static void display_usrs() {
3630 fprintf(stderr, "-print-usrs options:\n"
3631 " ObjCCategory <class name> <category name>\n"
3632 " ObjCClass <class name>\n"
3633 " ObjCIvar <ivar name> <class USR>\n"
3634 " ObjCMethod <selector> [0=class method|1=instance method] "
3635 "<class USR>\n"
3636 " ObjCProperty <property name> <class USR>\n"
3637 " ObjCProtocol <protocol name>\n");
3638}
3639
3640int print_usrs(const char **I, const char **E) {
3641 while (I != E) {
3642 const char *kind = *I;
3643 unsigned len = strlen(kind);
3644 switch (len) {
3645 case 8:
3646 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3647 if (I + 2 >= E)
3648 return insufficient_usr(kind, "<ivar name> <class USR>");
3649 if (!isUSR(I[2]))
3650 return not_usr("<class USR>", I[2]);
3651 else {
3652 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003653 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003654 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003655 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3656 }
3657
3658 I += 3;
3659 continue;
3660 }
3661 break;
3662 case 9:
3663 if (memcmp(kind, "ObjCClass", 9) == 0) {
3664 if (I + 1 >= E)
3665 return insufficient_usr(kind, "<class name>");
3666 print_usr(clang_constructUSR_ObjCClass(I[1]));
3667 I += 2;
3668 continue;
3669 }
3670 break;
3671 case 10:
3672 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3673 if (I + 3 >= E)
3674 return insufficient_usr(kind, "<method selector> "
3675 "[0=class method|1=instance method] <class USR>");
3676 if (!isUSR(I[3]))
3677 return not_usr("<class USR>", I[3]);
3678 else {
3679 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003680 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003681 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003682 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3683 }
3684 I += 4;
3685 continue;
3686 }
3687 break;
3688 case 12:
3689 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3690 if (I + 2 >= E)
3691 return insufficient_usr(kind, "<class name> <category name>");
3692 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3693 I += 3;
3694 continue;
3695 }
3696 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3697 if (I + 1 >= E)
3698 return insufficient_usr(kind, "<protocol name>");
3699 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3700 I += 2;
3701 continue;
3702 }
3703 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3704 if (I + 2 >= E)
3705 return insufficient_usr(kind, "<property name> <class USR>");
3706 if (!isUSR(I[2]))
3707 return not_usr("<class USR>", I[2]);
3708 else {
3709 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003710 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003711 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003712 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3713 }
3714 I += 3;
3715 continue;
3716 }
3717 break;
3718 default:
3719 break;
3720 }
3721 break;
3722 }
3723
3724 if (I != E) {
3725 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3726 display_usrs();
3727 return 1;
3728 }
3729 return 0;
3730}
3731
3732int print_usrs_file(const char *file_name) {
3733 char line[2048];
3734 const char *args[128];
3735 unsigned numChars = 0;
3736
3737 FILE *fp = fopen(file_name, "r");
3738 if (!fp) {
3739 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3740 return 1;
3741 }
3742
3743 /* This code is not really all that safe, but it works fine for testing. */
3744 while (!feof(fp)) {
3745 char c = fgetc(fp);
3746 if (c == '\n') {
3747 unsigned i = 0;
3748 const char *s = 0;
3749
3750 if (numChars == 0)
3751 continue;
3752
3753 line[numChars] = '\0';
3754 numChars = 0;
3755
3756 if (line[0] == '/' && line[1] == '/')
3757 continue;
3758
3759 s = strtok(line, " ");
3760 while (s) {
3761 args[i] = s;
3762 ++i;
3763 s = strtok(0, " ");
3764 }
3765 if (print_usrs(&args[0], &args[i]))
3766 return 1;
3767 }
3768 else
3769 line[numChars++] = c;
3770 }
3771
3772 fclose(fp);
3773 return 0;
3774}
3775
3776/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003777/* Command line processing. */
3778/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003779int write_pch_file(const char *filename, int argc, const char *argv[]) {
3780 CXIndex Idx;
3781 CXTranslationUnit TU;
3782 struct CXUnsavedFile *unsaved_files = 0;
3783 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003784 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003785 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003786
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003787 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003788
3789 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3790 clang_disposeIndex(Idx);
3791 return -1;
3792 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003793
3794 Err = clang_parseTranslationUnit2(
3795 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3796 unsaved_files, num_unsaved_files,
3797 CXTranslationUnit_Incomplete |
3798 CXTranslationUnit_DetailedPreprocessingRecord |
3799 CXTranslationUnit_ForSerialization,
3800 &TU);
3801 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003802 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003803 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003804 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003805 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003806 clang_disposeIndex(Idx);
3807 return 1;
3808 }
3809
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003810 switch (clang_saveTranslationUnit(TU, filename,
3811 clang_defaultSaveOptions(TU))) {
3812 case CXSaveError_None:
3813 break;
3814
3815 case CXSaveError_TranslationErrors:
3816 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3817 filename);
3818 result = 2;
3819 break;
3820
3821 case CXSaveError_InvalidTU:
3822 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3823 filename);
3824 result = 3;
3825 break;
3826
3827 case CXSaveError_Unknown:
3828 default:
3829 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3830 result = 1;
3831 break;
3832 }
3833
Douglas Gregore9386682010-08-13 05:36:37 +00003834 clang_disposeTranslationUnit(TU);
3835 free_remapped_files(unsaved_files, num_unsaved_files);
3836 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003837 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003838}
3839
3840/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003841/* Serialized diagnostics. */
3842/******************************************************************************/
3843
3844static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3845 switch (error) {
3846 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3847 case CXLoadDiag_None: break;
3848 case CXLoadDiag_Unknown: return "Unknown";
3849 case CXLoadDiag_InvalidFile: return "Invalid File";
3850 }
3851 return "None";
3852}
3853
3854static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3855 switch (severity) {
3856 case CXDiagnostic_Note: return "note";
3857 case CXDiagnostic_Error: return "error";
3858 case CXDiagnostic_Fatal: return "fatal";
3859 case CXDiagnostic_Ignored: return "ignored";
3860 case CXDiagnostic_Warning: return "warning";
3861 }
3862 return "unknown";
3863}
3864
3865static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003866 if (indent == 0)
3867 return;
3868 fprintf(stderr, "+");
3869 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003870 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003871 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003872 --indent;
3873 }
3874}
3875
3876static void printLocation(CXSourceLocation L) {
3877 CXFile File;
3878 CXString FileName;
3879 unsigned line, column, offset;
3880
3881 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3882 FileName = clang_getFileName(File);
3883
3884 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3885 clang_disposeString(FileName);
3886}
3887
3888static void printRanges(CXDiagnostic D, unsigned indent) {
3889 unsigned i, n = clang_getDiagnosticNumRanges(D);
3890
3891 for (i = 0; i < n; ++i) {
3892 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003893 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003894 Start = clang_getRangeStart(SR);
3895 End = clang_getRangeEnd(SR);
3896
3897 printIndent(indent);
3898 fprintf(stderr, "Range: ");
3899 printLocation(Start);
3900 fprintf(stderr, " ");
3901 printLocation(End);
3902 fprintf(stderr, "\n");
3903 }
3904}
3905
3906static void printFixIts(CXDiagnostic D, unsigned indent) {
3907 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003908 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003909 for (i = 0 ; i < n; ++i) {
3910 CXSourceRange ReplacementRange;
3911 CXString text;
3912 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3913
3914 printIndent(indent);
3915 fprintf(stderr, "FIXIT: (");
3916 printLocation(clang_getRangeStart(ReplacementRange));
3917 fprintf(stderr, " - ");
3918 printLocation(clang_getRangeEnd(ReplacementRange));
3919 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3920 clang_disposeString(text);
3921 }
3922}
3923
3924static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003925 unsigned i, n;
3926
Ted Kremenekd010ba42011-11-10 08:43:12 +00003927 if (!Diags)
3928 return;
3929
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003930 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003931 for (i = 0; i < n; ++i) {
3932 CXSourceLocation DiagLoc;
3933 CXDiagnostic D;
3934 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003935 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003936 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003937 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003938
3939 D = clang_getDiagnosticInSet(Diags, i);
3940 DiagLoc = clang_getDiagnosticLocation(D);
3941 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3942 FileName = clang_getFileName(File);
3943 DiagSpelling = clang_getDiagnosticSpelling(D);
3944
3945 printIndent(indent);
3946
3947 fprintf(stderr, "%s:%d:%d: %s: %s",
3948 clang_getCString(FileName),
3949 line,
3950 column,
3951 getSeverityString(clang_getDiagnosticSeverity(D)),
3952 clang_getCString(DiagSpelling));
3953
3954 DiagOption = clang_getDiagnosticOption(D, 0);
3955 DiagOptionStr = clang_getCString(DiagOption);
3956 if (DiagOptionStr) {
3957 fprintf(stderr, " [%s]", DiagOptionStr);
3958 }
3959
Ted Kremenek26a6d492012-04-12 00:03:31 +00003960 DiagCat = clang_getDiagnosticCategoryText(D);
3961 DiagCatStr = clang_getCString(DiagCat);
3962 if (DiagCatStr) {
3963 fprintf(stderr, " [%s]", DiagCatStr);
3964 }
3965
Ted Kremenekd010ba42011-11-10 08:43:12 +00003966 fprintf(stderr, "\n");
3967
3968 printRanges(D, indent);
3969 printFixIts(D, indent);
3970
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00003971 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00003972 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3973
3974 clang_disposeString(FileName);
3975 clang_disposeString(DiagSpelling);
3976 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00003977 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003978 }
3979}
3980
3981static int read_diagnostics(const char *filename) {
3982 enum CXLoadDiag_Error error;
3983 CXString errorString;
3984 CXDiagnosticSet Diags = 0;
3985
3986 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3987 if (!Diags) {
3988 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3989 getDiagnosticCodeStr(error),
3990 clang_getCString(errorString));
3991 clang_disposeString(errorString);
3992 return 1;
3993 }
3994
3995 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003996 fprintf(stderr, "Number of diagnostics: %d\n",
3997 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00003998 clang_disposeDiagnosticSet(Diags);
3999 return 0;
4000}
4001
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004002static int perform_print_build_session_timestamp(void) {
Yaron Kerene7aad462015-05-14 05:40:50 +00004003 printf("%" PRId64 "\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004004 return 0;
4005}
4006
Ted Kremenekd010ba42011-11-10 08:43:12 +00004007/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004008/* Command line processing. */
4009/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004010
Douglas Gregor720d0052010-01-20 21:32:04 +00004011static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004012 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004013 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004014 if (strcmp(s, "-usrs") == 0)
4015 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004016 if (strncmp(s, "-memory-usage", 13) == 0)
4017 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004018 return NULL;
4019}
4020
Ted Kremenekef3339b2009-11-17 18:09:14 +00004021static void print_usage(void) {
4022 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004023 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004024 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004025 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004026 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4027 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004028 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004029 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004030 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004031 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004032 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004033 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004034 "[FileCheck prefix]\n");
4035 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004036 " c-index-test -test-load-tu <AST file> <symbol filter> "
4037 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004038 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4039 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004040 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004041 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004042 " c-index-test -test-load-source-memory-usage "
4043 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004044 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4045 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004046 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004047 " c-index-test -test-load-source-usrs-memory-usage "
4048 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004049 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4050 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004051 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004052 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004053 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004054 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004055 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004056 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004057 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004058 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004059 " c-index-test -write-pch <file> <compiler arguments>\n");
4060 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004061 " c-index-test -compilation-db [lookup <filename>] database\n");
4062 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004063 " c-index-test -print-build-session-timestamp\n");
4064 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004065 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004066 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004067 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004068 " all - load all symbols, including those from PCH\n"
4069 " local - load all symbols except those in PCH\n"
4070 " category - only load ObjC categories (non-PCH)\n"
4071 " interface - only load ObjC interfaces (non-PCH)\n"
4072 " protocol - only load ObjC protocols (non-PCH)\n"
4073 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004074 " typedef - only load typdefs (non-PCH)\n"
4075 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004076}
4077
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004078/***/
4079
4080int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004081 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004082 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4083 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004084 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004085 return perform_code_completion(argc, argv, 0);
4086 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4087 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004088 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
4089 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004090 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4091 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004092 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4093 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004094 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004095 return index_file(argc - 2, argv + 2, /*full=*/0);
4096 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4097 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004098 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4099 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004100 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4101 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004102 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004103 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004104 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004105 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4106 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004107 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004108 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4109 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4110 if (I) {
4111 int trials = atoi(argv[2]);
4112 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4113 NULL);
4114 }
4115 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004116 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004117 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004118
4119 PostVisitTU postVisit = 0;
4120 if (strstr(argv[1], "-memory-usage"))
4121 postVisit = PrintMemoryUsage;
4122
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004123 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004124 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4125 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004126 }
4127 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004128 return perform_file_scan(argv[2], argv[3],
4129 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004130 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4131 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004132 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4133 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4134 PrintInclusionStack);
4135 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4136 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4137 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004138 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4139 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4140 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004141 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004142 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004143 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004144 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4145 return perform_test_load_source(argc - 2, argv + 2, "all",
4146 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004147 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4148 return perform_test_load_source(argc - 2, argv + 2, "all",
4149 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004150 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4151 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004152 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4153 if (argc > 2)
4154 return print_usrs(argv + 2, argv + argc);
4155 else {
4156 display_usrs();
4157 return 1;
4158 }
4159 }
4160 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4161 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004162 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4163 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004164 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4165 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004166 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4167 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004168
Ted Kremenekef3339b2009-11-17 18:09:14 +00004169 print_usage();
4170 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004171}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004172
4173/***/
4174
4175/* We intentionally run in a separate thread to ensure we at least minimal
4176 * testing of a multithreaded environment (for example, having a reduced stack
4177 * size). */
4178
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004179typedef struct thread_info {
4180 int argc;
4181 const char **argv;
4182 int result;
4183} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004184void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004185 thread_info *client_data = client_data_v;
4186 client_data->result = cindextest_main(client_data->argc, client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004187}
4188
4189static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004190 /* stdout, and surprisingly even stderr, are not always flushed on process
4191 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004192 fflush(stdout);
4193 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004194}
4195
4196int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004197 thread_info client_data;
4198
Reid Klecknere931c062014-06-05 00:13:43 +00004199 atexit(flush_atexit);
4200
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004201#ifdef CLANG_HAVE_LIBXML
4202 LIBXML_TEST_VERSION
4203#endif
4204
Douglas Gregorf428bf82010-10-27 16:00:01 +00004205 if (getenv("CINDEXTEST_NOTHREADS"))
4206 return cindextest_main(argc, argv);
4207
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004208 client_data.argc = argc;
4209 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004210 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004211 return client_data.result;
4212}