blob: 8336491c0158d56d30c6ba8f58210c1169e6c8ae [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"
Douglas Gregor49f67ce2010-08-26 13:48:20 +00008#include <ctype.h>
Douglas Gregor9eb77012009-11-07 00:00:49 +00009#include <stdlib.h>
Steve Naroff1054e602009-08-31 00:59:03 +000010#include <stdio.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000011#include <string.h>
Douglas Gregor082c3e62010-01-15 19:40:17 +000012#include <assert.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000013
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +000014#ifdef CLANG_HAVE_LIBXML
15#include <libxml/parser.h>
16#include <libxml/relaxng.h>
17#include <libxml/xmlerror.h>
18#endif
19
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +000020#ifdef _WIN32
21# include <direct.h>
22#else
23# include <unistd.h>
24#endif
25
Ted Kremenek1cd27d52009-11-17 18:13:31 +000026/******************************************************************************/
27/* Utility functions. */
28/******************************************************************************/
29
John Thompsonde258b52009-10-27 13:42:56 +000030#ifdef _MSC_VER
31char *basename(const char* path)
32{
33 char* base1 = (char*)strrchr(path, '/');
34 char* base2 = (char*)strrchr(path, '\\');
35 if (base1 && base2)
36 return((base1 > base2) ? base1 + 1 : base2 + 1);
37 else if (base1)
38 return(base1 + 1);
39 else if (base2)
40 return(base2 + 1);
41
42 return((char*)path);
43}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000044char *dirname(char* path)
45{
46 char* base1 = (char*)strrchr(path, '/');
47 char* base2 = (char*)strrchr(path, '\\');
48 if (base1 && base2)
49 if (base1 > base2)
50 *base1 = 0;
51 else
52 *base2 = 0;
53 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000054 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000055 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000056 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000057
58 return path;
59}
John Thompsonde258b52009-10-27 13:42:56 +000060#else
Steve Naroffa7753c42009-09-24 20:03:06 +000061extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000062extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000063#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000064
Douglas Gregorf2430ba2010-07-25 17:39:21 +000065/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000066static unsigned getDefaultParsingOptions() {
67 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
68
69 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000070 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000071 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
72 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000073 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
74 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000075 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
76 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000077 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
78 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Benjamin Kramer5c248d82015-12-15 09:30:31 +000079 if (getenv("CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
80 options |= CXTranslationUnit_CreatePreambleOnFirstParse;
81
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000082 return options;
83}
84
Patrik Hagglund55701d22014-02-17 11:54:08 +000085/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000086static int checkForErrors(CXTranslationUnit TU);
87
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000088static void describeLibclangFailure(enum CXErrorCode Err) {
89 switch (Err) {
90 case CXError_Success:
91 fprintf(stderr, "Success\n");
92 return;
93
94 case CXError_Failure:
95 fprintf(stderr, "Failure (no details available)\n");
96 return;
97
98 case CXError_Crashed:
99 fprintf(stderr, "Failure: libclang crashed\n");
100 return;
101
102 case CXError_InvalidArguments:
103 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
104 return;
105
106 case CXError_ASTReadError:
107 fprintf(stderr, "Failure: AST deserialization error occurred\n");
108 return;
109 }
110}
111
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000112static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
113 unsigned end_line, unsigned end_column) {
114 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000115 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000116}
117
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000118static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
119 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000120 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
121 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000122 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000123 describeLibclangFailure(Err);
124 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000125 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000126 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000127 return 1;
128}
129
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000130void free_remapped_files(struct CXUnsavedFile *unsaved_files,
131 int num_unsaved_files) {
132 int i;
133 for (i = 0; i != num_unsaved_files; ++i) {
134 free((char *)unsaved_files[i].Filename);
135 free((char *)unsaved_files[i].Contents);
136 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000137 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000138}
139
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000140static int parse_remapped_files_with_opt(const char *opt_name,
141 int argc, const char **argv,
142 int start_arg,
143 struct CXUnsavedFile **unsaved_files,
144 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000145 int i;
146 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000147 int prefix_len = strlen(opt_name);
148 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000149 *unsaved_files = 0;
150 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000151
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000152 /* Count the number of remapped files. */
153 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000154 if (strncmp(argv[arg], opt_name, prefix_len))
155 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000156
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000157 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
158 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000159 ++*num_unsaved_files;
160 }
Ted Kremenek29004672010-02-17 00:41:32 +0000161
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000162 if (*num_unsaved_files == 0)
163 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000164
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000165 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000166 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
167 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000168 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000169 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000170 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000171 int filename_len;
172 char *filename;
173 char *contents;
174 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000175 const char *sep = strchr(arg_string, ',');
176 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000177 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000178 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000179 free_remapped_files(*unsaved_files, i);
180 *unsaved_files = 0;
181 *num_unsaved_files = 0;
182 return -1;
183 }
Ted Kremenek29004672010-02-17 00:41:32 +0000184
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000185 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000186 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000187 if (!to_file) {
188 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000189 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000190 free_remapped_files(*unsaved_files, i);
191 *unsaved_files = 0;
192 *num_unsaved_files = 0;
193 return -1;
194 }
Ted Kremenek29004672010-02-17 00:41:32 +0000195
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000196 /* Determine the length of the file we're remapping to. */
197 fseek(to_file, 0, SEEK_END);
198 unsaved->Length = ftell(to_file);
199 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000200
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000201 /* Read the contents of the file we're remapping to. */
202 contents = (char *)malloc(unsaved->Length + 1);
203 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
204 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000205 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000206 fclose(to_file);
207 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000208 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000209 *unsaved_files = 0;
210 *num_unsaved_files = 0;
211 return -1;
212 }
213 contents[unsaved->Length] = 0;
214 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000215
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000216 /* Close the file. */
217 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000218
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000219 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000220 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000221 filename = (char *)malloc(filename_len + 1);
222 memcpy(filename, arg_string, filename_len);
223 filename[filename_len] = 0;
224 unsaved->Filename = filename;
225 }
Ted Kremenek29004672010-02-17 00:41:32 +0000226
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000227 return 0;
228}
229
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000230static int parse_remapped_files(int argc, const char **argv, int start_arg,
231 struct CXUnsavedFile **unsaved_files,
232 int *num_unsaved_files) {
233 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
234 unsaved_files, num_unsaved_files);
235}
236
237static int parse_remapped_files_with_try(int try_idx,
238 int argc, const char **argv,
239 int start_arg,
240 struct CXUnsavedFile **unsaved_files,
241 int *num_unsaved_files) {
242 struct CXUnsavedFile *unsaved_files_no_try_idx;
243 int num_unsaved_files_no_try_idx;
244 struct CXUnsavedFile *unsaved_files_try_idx;
245 int num_unsaved_files_try_idx;
246 int ret;
247 char opt_name[32];
248
249 ret = parse_remapped_files(argc, argv, start_arg,
250 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
251 if (ret)
252 return ret;
253
254 sprintf(opt_name, "-remap-file-%d=", try_idx);
255 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
256 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
257 if (ret)
258 return ret;
259
Chandler Carruth6ac555f2015-08-04 03:53:04 +0000260 if (num_unsaved_files_no_try_idx == 0) {
261 *unsaved_files = unsaved_files_try_idx;
262 *num_unsaved_files = num_unsaved_files_try_idx;
263 return 0;
264 }
265 if (num_unsaved_files_try_idx == 0) {
266 *unsaved_files = unsaved_files_no_try_idx;
267 *num_unsaved_files = num_unsaved_files_no_try_idx;
268 return 0;
269 }
270
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000271 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
272 *unsaved_files
273 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
274 sizeof(struct CXUnsavedFile) *
275 *num_unsaved_files);
276 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
277 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
278 num_unsaved_files_try_idx);
279 free(unsaved_files_try_idx);
280 return 0;
281}
282
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000283static const char *parse_comments_schema(int argc, const char **argv) {
284 const char *CommentsSchemaArg = "-comments-xml-schema=";
285 const char *CommentSchemaFile = NULL;
286
287 if (argc == 0)
288 return CommentSchemaFile;
289
290 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
291 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
292
293 return CommentSchemaFile;
294}
295
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000296/******************************************************************************/
297/* Pretty-printing. */
298/******************************************************************************/
299
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000300static const char *FileCheckPrefix = "CHECK";
301
302static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000303 if (CStr != NULL && CStr[0] != '\0') {
304 for ( ; *CStr; ++CStr) {
305 const char C = *CStr;
306 switch (C) {
307 case '\n': printf("\\n"); break;
308 case '\r': printf("\\r"); break;
309 case '\t': printf("\\t"); break;
310 case '\v': printf("\\v"); break;
311 case '\f': printf("\\f"); break;
312 default: putchar(C); break;
313 }
314 }
315 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000316}
317
318static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
319 printf(" %s=[", Prefix);
320 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000321 printf("]");
322}
323
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000324static void PrintCXStringAndDispose(CXString Str) {
325 PrintCString(clang_getCString(Str));
326 clang_disposeString(Str);
327}
328
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000329static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
330 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
331}
332
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000333static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
334 CXString Str) {
335 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
336 clang_disposeString(Str);
337}
338
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000339static void PrintRange(CXSourceRange R, const char *str) {
340 CXFile begin_file, end_file;
341 unsigned begin_line, begin_column, end_line, end_column;
342
343 clang_getSpellingLocation(clang_getRangeStart(R),
344 &begin_file, &begin_line, &begin_column, 0);
345 clang_getSpellingLocation(clang_getRangeEnd(R),
346 &end_file, &end_line, &end_column, 0);
347 if (!begin_file || !end_file)
348 return;
349
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000350 if (str)
351 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000352 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
353}
354
Douglas Gregor97c75712010-10-02 22:49:11 +0000355int want_display_name = 0;
356
Douglas Gregord6225d32012-05-08 00:14:45 +0000357static void printVersion(const char *Prefix, CXVersion Version) {
358 if (Version.Major < 0)
359 return;
360 printf("%s%d", Prefix, Version.Major);
361
362 if (Version.Minor < 0)
363 return;
364 printf(".%d", Version.Minor);
365
366 if (Version.Subminor < 0)
367 return;
368 printf(".%d", Version.Subminor);
369}
370
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000371struct CommentASTDumpingContext {
372 int IndentLevel;
373};
374
375static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
376 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000377 unsigned i;
378 unsigned e;
379 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
380
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000381 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000382 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000383 printf(" ");
384
385 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000386 switch (Kind) {
387 case CXComment_Null:
388 printf("CXComment_Null");
389 break;
390 case CXComment_Text:
391 printf("CXComment_Text");
392 PrintCXStringWithPrefixAndDispose("Text",
393 clang_TextComment_getText(Comment));
394 if (clang_Comment_isWhitespace(Comment))
395 printf(" IsWhitespace");
396 if (clang_InlineContentComment_hasTrailingNewline(Comment))
397 printf(" HasTrailingNewline");
398 break;
399 case CXComment_InlineCommand:
400 printf("CXComment_InlineCommand");
401 PrintCXStringWithPrefixAndDispose(
402 "CommandName",
403 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000404 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
405 case CXCommentInlineCommandRenderKind_Normal:
406 printf(" RenderNormal");
407 break;
408 case CXCommentInlineCommandRenderKind_Bold:
409 printf(" RenderBold");
410 break;
411 case CXCommentInlineCommandRenderKind_Monospaced:
412 printf(" RenderMonospaced");
413 break;
414 case CXCommentInlineCommandRenderKind_Emphasized:
415 printf(" RenderEmphasized");
416 break;
417 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000418 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000419 i != e; ++i) {
420 printf(" Arg[%u]=", i);
421 PrintCXStringAndDispose(
422 clang_InlineCommandComment_getArgText(Comment, i));
423 }
424 if (clang_InlineContentComment_hasTrailingNewline(Comment))
425 printf(" HasTrailingNewline");
426 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000427 case CXComment_HTMLStartTag: {
428 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000429 printf("CXComment_HTMLStartTag");
430 PrintCXStringWithPrefixAndDispose(
431 "Name",
432 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000433 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000434 if (NumAttrs != 0) {
435 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000436 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000437 printf(" ");
438 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
439 printf("=");
440 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
441 }
442 }
443 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
444 printf(" SelfClosing");
445 if (clang_InlineContentComment_hasTrailingNewline(Comment))
446 printf(" HasTrailingNewline");
447 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000448 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000449 case CXComment_HTMLEndTag:
450 printf("CXComment_HTMLEndTag");
451 PrintCXStringWithPrefixAndDispose(
452 "Name",
453 clang_HTMLTagComment_getTagName(Comment));
454 if (clang_InlineContentComment_hasTrailingNewline(Comment))
455 printf(" HasTrailingNewline");
456 break;
457 case CXComment_Paragraph:
458 printf("CXComment_Paragraph");
459 if (clang_Comment_isWhitespace(Comment))
460 printf(" IsWhitespace");
461 break;
462 case CXComment_BlockCommand:
463 printf("CXComment_BlockCommand");
464 PrintCXStringWithPrefixAndDispose(
465 "CommandName",
466 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000467 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000468 i != e; ++i) {
469 printf(" Arg[%u]=", i);
470 PrintCXStringAndDispose(
471 clang_BlockCommandComment_getArgText(Comment, i));
472 }
473 break;
474 case CXComment_ParamCommand:
475 printf("CXComment_ParamCommand");
476 switch (clang_ParamCommandComment_getDirection(Comment)) {
477 case CXCommentParamPassDirection_In:
478 printf(" in");
479 break;
480 case CXCommentParamPassDirection_Out:
481 printf(" out");
482 break;
483 case CXCommentParamPassDirection_InOut:
484 printf(" in,out");
485 break;
486 }
487 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
488 printf(" explicitly");
489 else
490 printf(" implicitly");
491 PrintCXStringWithPrefixAndDispose(
492 "ParamName",
493 clang_ParamCommandComment_getParamName(Comment));
494 if (clang_ParamCommandComment_isParamIndexValid(Comment))
495 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
496 else
497 printf(" ParamIndex=Invalid");
498 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000499 case CXComment_TParamCommand:
500 printf("CXComment_TParamCommand");
501 PrintCXStringWithPrefixAndDispose(
502 "ParamName",
503 clang_TParamCommandComment_getParamName(Comment));
504 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
505 printf(" ParamPosition={");
506 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
507 i != e; ++i) {
508 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
509 if (i != e - 1)
510 printf(", ");
511 }
512 printf("}");
513 } else
514 printf(" ParamPosition=Invalid");
515 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000516 case CXComment_VerbatimBlockCommand:
517 printf("CXComment_VerbatimBlockCommand");
518 PrintCXStringWithPrefixAndDispose(
519 "CommandName",
520 clang_BlockCommandComment_getCommandName(Comment));
521 break;
522 case CXComment_VerbatimBlockLine:
523 printf("CXComment_VerbatimBlockLine");
524 PrintCXStringWithPrefixAndDispose(
525 "Text",
526 clang_VerbatimBlockLineComment_getText(Comment));
527 break;
528 case CXComment_VerbatimLine:
529 printf("CXComment_VerbatimLine");
530 PrintCXStringWithPrefixAndDispose(
531 "Text",
532 clang_VerbatimLineComment_getText(Comment));
533 break;
534 case CXComment_FullComment:
535 printf("CXComment_FullComment");
536 break;
537 }
538 if (Kind != CXComment_Null) {
539 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000540 unsigned i;
541 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000542 printf("\n// %s: ", FileCheckPrefix);
543 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
544 }
545 }
546 printf(")");
547 Ctx->IndentLevel--;
548}
549
550static void DumpCXComment(CXComment Comment) {
551 struct CommentASTDumpingContext Ctx;
552 Ctx.IndentLevel = 1;
553 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
554 DumpCXCommentInternal(&Ctx, Comment);
555 printf("]");
556}
557
Chandler Carruthb2faa592014-05-02 23:30:59 +0000558static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000559#ifdef CLANG_HAVE_LIBXML
560 xmlRelaxNGParserCtxtPtr RNGParser;
561 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000562 xmlDocPtr Doc;
563 xmlRelaxNGValidCtxtPtr ValidationCtxt;
564 int status;
565
Chandler Carruthb2faa592014-05-02 23:30:59 +0000566 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000567 return;
568
Chandler Carruthb2faa592014-05-02 23:30:59 +0000569 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
570 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000571 printf(" libXMLError");
572 return;
573 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000574 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000575
576 Doc = xmlParseDoc((const xmlChar *) Str);
577
578 if (!Doc) {
579 xmlErrorPtr Error = xmlGetLastError();
580 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
581 return;
582 }
583
Chandler Carruthb2faa592014-05-02 23:30:59 +0000584 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000585 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
586 if (!status)
587 printf(" CommentXMLValid");
588 else if (status > 0) {
589 xmlErrorPtr Error = xmlGetLastError();
590 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
591 } else
592 printf(" libXMLError");
593
594 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
595 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000596 xmlRelaxNGFree(Schema);
597 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000598#endif
599}
600
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000601static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000602 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000603 {
604 CXString RawComment;
605 const char *RawCommentCString;
606 CXString BriefComment;
607 const char *BriefCommentCString;
608
609 RawComment = clang_Cursor_getRawCommentText(Cursor);
610 RawCommentCString = clang_getCString(RawComment);
611 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
612 PrintCStringWithPrefix("RawComment", RawCommentCString);
613 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
614
615 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
616 BriefCommentCString = clang_getCString(BriefComment);
617 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
618 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
619 clang_disposeString(BriefComment);
620 }
621 clang_disposeString(RawComment);
622 }
623
624 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000625 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000626 if (clang_Comment_getKind(Comment) != CXComment_Null) {
627 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
628 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000629 {
630 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000631 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000632 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000633 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000634 clang_disposeString(XML);
635 }
636
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000637 DumpCXComment(Comment);
638 }
639 }
640}
641
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000642typedef struct {
643 unsigned line;
644 unsigned col;
645} LineCol;
646
647static int lineCol_cmp(const void *p1, const void *p2) {
648 const LineCol *lhs = p1;
649 const LineCol *rhs = p2;
650 if (lhs->line != rhs->line)
651 return (int)lhs->line - (int)rhs->line;
652 return (int)lhs->col - (int)rhs->col;
653}
654
Chandler Carruthb2faa592014-05-02 23:30:59 +0000655static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000656 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000657 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000658 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000659 printf("Invalid Cursor => %s", clang_getCString(ks));
660 clang_disposeString(ks);
661 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000662 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000663 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000664 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000665 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000666 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000667 CXCursor *overridden;
668 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000669 unsigned RefNameRangeNr;
670 CXSourceRange CursorExtent;
671 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000672 int AlwaysUnavailable;
673 int AlwaysDeprecated;
674 CXString UnavailableMessage;
675 CXString DeprecatedMessage;
676 CXPlatformAvailability PlatformAvailability[2];
677 int NumPlatformAvailability;
678 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000679
Ted Kremenek29004672010-02-17 00:41:32 +0000680 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000681 string = want_display_name? clang_getCursorDisplayName(Cursor)
682 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000683 printf("%s=%s", clang_getCString(ks),
684 clang_getCString(string));
685 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000686 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000687
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000688 Referenced = clang_getCursorReferenced(Cursor);
689 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000690 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
691 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
692 printf("[");
693 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000694 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000695 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000696 if (I)
697 printf(", ");
698
Douglas Gregor2967e282010-09-14 00:20:32 +0000699 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000700 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000701 printf("%d:%d", line, column);
702 }
703 printf("]");
704 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000705 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000706 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000707 printf(":%d:%d", line, column);
708 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000709 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000710
711 if (clang_isCursorDefinition(Cursor))
712 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000713
714 switch (clang_getCursorAvailability(Cursor)) {
715 case CXAvailability_Available:
716 break;
717
718 case CXAvailability_Deprecated:
719 printf(" (deprecated)");
720 break;
721
722 case CXAvailability_NotAvailable:
723 printf(" (unavailable)");
724 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000725
726 case CXAvailability_NotAccessible:
727 printf(" (inaccessible)");
728 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000729 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000730
Douglas Gregord6225d32012-05-08 00:14:45 +0000731 NumPlatformAvailability
732 = clang_getCursorPlatformAvailability(Cursor,
733 &AlwaysDeprecated,
734 &DeprecatedMessage,
735 &AlwaysUnavailable,
736 &UnavailableMessage,
737 PlatformAvailability, 2);
738 if (AlwaysUnavailable) {
739 printf(" (always unavailable: \"%s\")",
740 clang_getCString(UnavailableMessage));
741 } else if (AlwaysDeprecated) {
742 printf(" (always deprecated: \"%s\")",
743 clang_getCString(DeprecatedMessage));
744 } else {
745 for (I = 0; I != NumPlatformAvailability; ++I) {
746 if (I >= 2)
747 break;
748
749 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
750 if (PlatformAvailability[I].Unavailable)
751 printf(", unavailable");
752 else {
753 printVersion(", introduced=", PlatformAvailability[I].Introduced);
754 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
755 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
756 }
757 if (clang_getCString(PlatformAvailability[I].Message)[0])
758 printf(", message=\"%s\"",
759 clang_getCString(PlatformAvailability[I].Message));
760 printf(")");
761 }
762 }
763 for (I = 0; I != NumPlatformAvailability; ++I) {
764 if (I >= 2)
765 break;
766 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
767 }
768
769 clang_disposeString(DeprecatedMessage);
770 clang_disposeString(UnavailableMessage);
771
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000772 if (clang_CXXField_isMutable(Cursor))
773 printf(" (mutable)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000774 if (clang_CXXMethod_isStatic(Cursor))
775 printf(" (static)");
776 if (clang_CXXMethod_isVirtual(Cursor))
777 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000778 if (clang_CXXMethod_isConst(Cursor))
779 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000780 if (clang_CXXMethod_isPureVirtual(Cursor))
781 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000782 if (clang_Cursor_isVariadic(Cursor))
783 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000784 if (clang_Cursor_isObjCOptional(Cursor))
785 printf(" (@optional)");
786
Ted Kremeneka5940822010-08-26 01:42:22 +0000787 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000788 CXType T =
789 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
790 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000791 printf(" [IBOutletCollection=%s]", clang_getCString(S));
792 clang_disposeString(S);
793 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000794
795 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
796 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
797 unsigned isVirtual = clang_isVirtualBase(Cursor);
798 const char *accessStr = 0;
799
800 switch (access) {
801 case CX_CXXInvalidAccessSpecifier:
802 accessStr = "invalid"; break;
803 case CX_CXXPublic:
804 accessStr = "public"; break;
805 case CX_CXXProtected:
806 accessStr = "protected"; break;
807 case CX_CXXPrivate:
808 accessStr = "private"; break;
809 }
810
811 printf(" [access=%s isVirtual=%s]", accessStr,
812 isVirtual ? "true" : "false");
813 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000814
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000815 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
816 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000817 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
818 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000819 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000820 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000821 clang_getCString(Name), line, column);
822 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000823
824 if (Cursor.kind == CXCursor_FunctionDecl) {
825 /* Collect the template parameter kinds from the base template. */
826 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
827 unsigned I;
828 for (I = 0; I < NumTemplateArgs; I++) {
829 enum CXTemplateArgumentKind TAK =
830 clang_Cursor_getTemplateArgumentKind(Cursor, I);
831 switch(TAK) {
832 case CXTemplateArgumentKind_Type:
833 {
834 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
835 CXString S = clang_getTypeSpelling(T);
836 printf(" [Template arg %d: kind: %d, type: %s]",
837 I, TAK, clang_getCString(S));
838 clang_disposeString(S);
839 }
840 break;
841 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000842 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000843 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
844 break;
845 default:
846 printf(" [Template arg %d: kind: %d]\n", I, TAK);
847 }
848 }
849 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000850 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000851
852 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
853 if (num_overridden) {
854 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000855 LineCol lineCols[50];
856 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000857 printf(" [Overrides ");
858 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000859 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000860 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000861 lineCols[I].line = line;
862 lineCols[I].col = column;
863 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000864 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000865 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
866 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000867 if (I)
868 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000869 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000870 }
871 printf("]");
872 clang_disposeOverriddenCursors(overridden);
873 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000874
875 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000876 CXFile File = clang_getIncludedFile(Cursor);
877 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000878 printf(" (%s)", clang_getCString(Included));
879 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000880
881 if (clang_isFileMultipleIncludeGuarded(TU, File))
882 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000883 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000884
885 CursorExtent = clang_getCursorExtent(Cursor);
886 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
887 CXNameRange_WantQualifier
888 | CXNameRange_WantSinglePiece
889 | CXNameRange_WantTemplateArgs,
890 0);
891 if (!clang_equalRanges(CursorExtent, RefNameRange))
892 PrintRange(RefNameRange, "SingleRefName");
893
894 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
895 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
896 CXNameRange_WantQualifier
897 | CXNameRange_WantTemplateArgs,
898 RefNameRangeNr);
899 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
900 break;
901 if (!clang_equalRanges(CursorExtent, RefNameRange))
902 PrintRange(RefNameRange, "RefName");
903 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000904
Chandler Carruthb2faa592014-05-02 23:30:59 +0000905 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000906
907 {
908 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
909 if (PropAttrs != CXObjCPropertyAttr_noattr) {
910 printf(" [");
911 #define PRINT_PROP_ATTR(A) \
912 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
913 PRINT_PROP_ATTR(readonly);
914 PRINT_PROP_ATTR(getter);
915 PRINT_PROP_ATTR(assign);
916 PRINT_PROP_ATTR(readwrite);
917 PRINT_PROP_ATTR(retain);
918 PRINT_PROP_ATTR(copy);
919 PRINT_PROP_ATTR(nonatomic);
920 PRINT_PROP_ATTR(setter);
921 PRINT_PROP_ATTR(atomic);
922 PRINT_PROP_ATTR(weak);
923 PRINT_PROP_ATTR(strong);
924 PRINT_PROP_ATTR(unsafe_unretained);
925 printf("]");
926 }
927 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000928
929 {
930 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
931 if (QT != CXObjCDeclQualifier_None) {
932 printf(" [");
933 #define PRINT_OBJC_QUAL(A) \
934 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
935 PRINT_OBJC_QUAL(In);
936 PRINT_OBJC_QUAL(Inout);
937 PRINT_OBJC_QUAL(Out);
938 PRINT_OBJC_QUAL(Bycopy);
939 PRINT_OBJC_QUAL(Byref);
940 PRINT_OBJC_QUAL(Oneway);
941 printf("]");
942 }
943 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000944 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000945}
Steve Naroff1054e602009-08-31 00:59:03 +0000946
Ted Kremenek29004672010-02-17 00:41:32 +0000947static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000948 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000949 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000950 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000951 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000952 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000953 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000954 clang_disposeString(source);
955 return "<invalid loc>";
956 }
957 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000958 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000959 clang_disposeString(source);
960 return b;
961 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000962}
963
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000964/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000965/* Callbacks. */
966/******************************************************************************/
967
968typedef void (*PostVisitTU)(CXTranslationUnit);
969
Douglas Gregor33cdd812010-02-18 18:08:43 +0000970void PrintDiagnostic(CXDiagnostic Diagnostic) {
971 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000972 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000973 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000974 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000975 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
976 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000977 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000978
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000979 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000980 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000981
Douglas Gregord770f732010-02-22 23:17:23 +0000982 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
983 fprintf(stderr, "%s\n", clang_getCString(Msg));
984 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000985
Douglas Gregor229bebd2010-11-09 06:24:54 +0000986 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
987 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000988 if (!file)
989 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000990
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000991 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000992 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000993 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000994 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000995 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
996 CXSourceLocation start = clang_getRangeStart(range);
997 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000998 unsigned start_line, start_column, end_line, end_column;
999 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001000 clang_getSpellingLocation(start, &start_file, &start_line,
1001 &start_column, 0);
1002 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001003 if (clang_equalLocations(start, end)) {
1004 /* Insertion. */
1005 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001006 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001007 clang_getCString(insertion_text), start_line, start_column);
1008 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1009 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001010 if (start_file == file && end_file == file) {
1011 fprintf(out, "FIX-IT: Remove ");
1012 PrintExtent(out, start_line, start_column, end_line, end_column);
1013 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001014 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001015 } else {
1016 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001017 if (start_file == end_file) {
1018 fprintf(out, "FIX-IT: Replace ");
1019 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001020 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001021 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001022 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001023 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001024 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001025}
1026
Ted Kremenek914c7e62012-02-14 02:46:03 +00001027void PrintDiagnosticSet(CXDiagnosticSet Set) {
1028 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1029 for ( ; i != n ; ++i) {
1030 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1031 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001032 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001033 if (ChildDiags)
1034 PrintDiagnosticSet(ChildDiags);
1035 }
1036}
1037
1038void PrintDiagnostics(CXTranslationUnit TU) {
1039 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1040 PrintDiagnosticSet(TUSet);
1041 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001042}
1043
Ted Kremenek83f642e2011-04-18 22:47:10 +00001044void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001045 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001046 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001047 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001048 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001049 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001050 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001051 unsigned long amount = usage.entries[i].amount;
1052 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001053 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001054 ((double) amount)/(1024*1024));
1055 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001056 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001057 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001058 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001059}
1060
Ted Kremenekb478ff42010-01-26 17:59:48 +00001061/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001062/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001063/******************************************************************************/
1064
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001065static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001066 CXSourceRange extent = clang_getCursorExtent(C);
1067 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001068}
1069
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001070/* Data used by the visitors. */
1071typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001072 CXTranslationUnit TU;
1073 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001074 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001075} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001076
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001077
Ted Kremenek29004672010-02-17 00:41:32 +00001078enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001079 CXCursor Parent,
1080 CXClientData ClientData) {
1081 VisitorData *Data = (VisitorData *)ClientData;
1082 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001083 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001084 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001085 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001086 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001087 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001088 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001089 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001090 if (clang_isDeclaration(Cursor.kind)) {
1091 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1092 const char *accessStr = 0;
1093
1094 switch (access) {
1095 case CX_CXXInvalidAccessSpecifier: break;
1096 case CX_CXXPublic:
1097 accessStr = "public"; break;
1098 case CX_CXXProtected:
1099 accessStr = "protected"; break;
1100 case CX_CXXPrivate:
1101 accessStr = "private"; break;
1102 }
1103
1104 if (accessStr)
1105 printf(" [access=%s]", accessStr);
1106 }
Ted Kremenek29004672010-02-17 00:41:32 +00001107 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001108 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001109 }
Ted Kremenek29004672010-02-17 00:41:32 +00001110
Douglas Gregor720d0052010-01-20 21:32:04 +00001111 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001112}
Steve Naroffa1c72842009-08-28 15:28:48 +00001113
Ted Kremenek29004672010-02-17 00:41:32 +00001114static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001115 CXCursor Parent,
1116 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001117 const char *startBuf, *endBuf;
1118 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1119 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001120 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001121
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001122 if (Cursor.kind != CXCursor_FunctionDecl ||
1123 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001124 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001125
1126 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1127 &startLine, &startColumn,
1128 &endLine, &endColumn);
1129 /* Probe the entire body, looking for both decls and refs. */
1130 curLine = startLine;
1131 curColumn = startColumn;
1132
1133 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001134 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001135 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001136 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001137
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001138 if (*startBuf == '\n') {
1139 startBuf++;
1140 curLine++;
1141 curColumn = 1;
1142 } else if (*startBuf != '\t')
1143 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001144
Douglas Gregor66a58812010-01-18 22:46:11 +00001145 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001146 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001147
Douglas Gregor4f46e782010-01-19 21:36:55 +00001148 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001149 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001150 CXSourceLocation RefLoc
1151 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001152 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001153 if (Ref.kind == CXCursor_NoDeclFound) {
1154 /* Nothing found here; that's fine. */
1155 } else if (Ref.kind != CXCursor_FunctionDecl) {
1156 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1157 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001158 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001159 printf("\n");
1160 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001161 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001162 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001163 startBuf++;
1164 }
Ted Kremenek29004672010-02-17 00:41:32 +00001165
Douglas Gregor720d0052010-01-20 21:32:04 +00001166 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001167}
1168
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001169/******************************************************************************/
1170/* USR testing. */
1171/******************************************************************************/
1172
Douglas Gregor720d0052010-01-20 21:32:04 +00001173enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1174 CXClientData ClientData) {
1175 VisitorData *Data = (VisitorData *)ClientData;
1176 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001177 CXString USR = clang_getCursorUSR(C);
1178 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001179 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001180 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001181 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001182 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001183 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1184
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001185 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001186 printf("\n");
1187 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001188
Douglas Gregor720d0052010-01-20 21:32:04 +00001189 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001190 }
1191
Douglas Gregor720d0052010-01-20 21:32:04 +00001192 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001193}
1194
1195/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001196/* Inclusion stack testing. */
1197/******************************************************************************/
1198
1199void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1200 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001201
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001202 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001203 CXString fname;
1204
1205 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001206 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001207 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001208
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001209 for (i = 0; i < includeStackLen; ++i) {
1210 CXFile includingFile;
1211 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001212 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1213 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001214 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001215 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001216 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001217 }
1218 printf("\n");
1219}
1220
1221void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001222 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001223}
1224
1225/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001226/* Linkage testing. */
1227/******************************************************************************/
1228
1229static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1230 CXClientData d) {
1231 const char *linkage = 0;
1232
1233 if (clang_isInvalid(clang_getCursorKind(cursor)))
1234 return CXChildVisit_Recurse;
1235
1236 switch (clang_getCursorLinkage(cursor)) {
1237 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001238 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1239 case CXLinkage_Internal: linkage = "Internal"; break;
1240 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1241 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001242 }
1243
1244 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001245 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001246 printf("linkage=%s\n", linkage);
1247 }
1248
1249 return CXChildVisit_Recurse;
1250}
1251
1252/******************************************************************************/
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00001253/* Visibility testing. */
1254/******************************************************************************/
1255
1256static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1257 CXClientData d) {
1258 const char *visibility = 0;
1259
1260 if (clang_isInvalid(clang_getCursorKind(cursor)))
1261 return CXChildVisit_Recurse;
1262
1263 switch (clang_getCursorVisibility(cursor)) {
1264 case CXVisibility_Invalid: break;
1265 case CXVisibility_Hidden: visibility = "Hidden"; break;
1266 case CXVisibility_Protected: visibility = "Protected"; break;
1267 case CXVisibility_Default: visibility = "Default"; break;
1268 }
1269
1270 if (visibility) {
1271 PrintCursor(cursor, NULL);
1272 printf("visibility=%s\n", visibility);
1273 }
1274
1275 return CXChildVisit_Recurse;
1276}
1277
1278/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001279/* Typekind testing. */
1280/******************************************************************************/
1281
Dmitri Gribenko00353722013-02-15 21:15:49 +00001282static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1283 CXString TypeSpelling, TypeKindSpelling;
1284
1285 TypeSpelling = clang_getTypeSpelling(T);
1286 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1287 printf(Format,
1288 clang_getCString(TypeSpelling),
1289 clang_getCString(TypeKindSpelling));
1290 clang_disposeString(TypeSpelling);
1291 clang_disposeString(TypeKindSpelling);
1292}
1293
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001294static enum CXVisitorResult FieldVisitor(CXCursor C,
1295 CXClientData client_data) {
1296 (*(int *) client_data)+=1;
1297 return CXVisit_Continue;
1298}
1299
Dmitri Gribenko00353722013-02-15 21:15:49 +00001300static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1301 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001302 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001303 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001304 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001305 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001306 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001307 if (clang_isConstQualifiedType(T))
1308 printf(" const");
1309 if (clang_isVolatileQualifiedType(T))
1310 printf(" volatile");
1311 if (clang_isRestrictQualifiedType(T))
1312 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001313 if (RQ == CXRefQualifier_LValue)
1314 printf(" lvalue-ref-qualifier");
1315 if (RQ == CXRefQualifier_RValue)
1316 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001317 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001318 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001319 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001320 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001321 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001322 }
1323 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001324 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001325 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001326 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001327 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001328 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001329 }
1330 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001331 /* Print the argument types if they exist. */
1332 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001333 int NumArgs = clang_Cursor_getNumArguments(cursor);
1334 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001335 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001336 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001337 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001338 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001339 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001340 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001341 }
1342 }
1343 printf("]");
1344 }
1345 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001346 /* Print the template argument types if they exist. */
1347 {
1348 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1349 if (NumTArgs != -1 && NumTArgs != 0) {
1350 int i;
1351 printf(" [templateargs/%d=", NumTArgs);
1352 for (i = 0; i < NumTArgs; ++i) {
1353 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1354 if (TArg.kind != CXType_Invalid) {
1355 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1356 }
1357 }
1358 printf("]");
1359 }
1360 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001361 /* Print if this is a non-POD type. */
1362 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001363 /* Print the pointee type. */
1364 {
1365 CXType PT = clang_getPointeeType(T);
1366 if (PT.kind != CXType_Invalid) {
1367 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1368 }
1369 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001370 /* Print the number of fields if they exist. */
1371 {
1372 int numFields = 0;
1373 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1374 if (numFields != 0) {
1375 printf(" [nbFields=%d]", numFields);
1376 }
1377 /* Print if it is an anonymous record. */
1378 {
1379 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1380 if (isAnon != 0) {
1381 printf(" [isAnon=%d]", isAnon);
1382 }
1383 }
1384 }
1385 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001386
Ted Kremenek6bca9842010-05-14 21:29:26 +00001387 printf("\n");
1388 }
1389 return CXChildVisit_Recurse;
1390}
1391
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001392static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1393 CXClientData d) {
1394 CXType T;
1395 enum CXCursorKind K = clang_getCursorKind(cursor);
1396 if (clang_isInvalid(K))
1397 return CXChildVisit_Recurse;
1398 T = clang_getCursorType(cursor);
1399 PrintCursor(cursor, NULL);
1400 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1401 /* Print the type sizeof if applicable. */
1402 {
1403 long long Size = clang_Type_getSizeOf(T);
1404 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001405 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001406 }
1407 }
1408 /* Print the type alignof if applicable. */
1409 {
1410 long long Align = clang_Type_getAlignOf(T);
1411 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001412 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001413 }
1414 }
1415 /* Print the record field offset if applicable. */
1416 {
Nico Weber82098cb2014-04-24 04:14:12 +00001417 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1418 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001419 /* recurse to get the first parent record that is not anonymous. */
1420 CXCursor Parent, Record;
1421 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001422 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001423 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001424 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001425 Record = Parent;
1426 Parent = clang_getCursorSemanticParent(Record);
1427 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1428 /* Recurse as long as the parent is a CXType_Record and the Record
1429 is anonymous */
1430 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1431 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001432 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001433 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001434 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001435 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1436 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001437 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001438 } else {
1439 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001440 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001441 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001442 }
1443 }
Nico Weber82098cb2014-04-24 04:14:12 +00001444 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001445 }
1446 /* Print if its a bitfield */
1447 {
1448 int IsBitfield = clang_Cursor_isBitField(cursor);
1449 if (IsBitfield)
1450 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1451 }
1452 printf("\n");
1453 return CXChildVisit_Recurse;
1454}
1455
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001456/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001457/* Mangling testing. */
1458/******************************************************************************/
1459
1460static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1461 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001462 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001463 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1464 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001465 PrintCursor(cursor, NULL);
1466 MangledName = clang_Cursor_getMangling(cursor);
1467 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001468 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001469 return CXChildVisit_Continue;
1470}
1471
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001472static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1473 CXClientData d) {
1474 unsigned I, E;
1475 CXStringSet *Manglings = NULL;
1476 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1477 return CXChildVisit_Recurse;
1478 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1479 return CXChildVisit_Recurse;
1480 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1481 return CXChildVisit_Continue;
1482 PrintCursor(cursor, NULL);
1483 Manglings = clang_Cursor_getCXXManglings(cursor);
1484 for (I = 0, E = Manglings->Count; I < E; ++I)
1485 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1486 clang_disposeStringSet(Manglings);
1487 printf("\n");
1488 return CXChildVisit_Recurse;
1489}
1490
Eli Bendersky44a206f2014-07-31 18:04:56 +00001491/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001492/* Bitwidth testing. */
1493/******************************************************************************/
1494
1495static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1496 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001497 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001498 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1499 return CXChildVisit_Recurse;
1500
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001501 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001502 if (Bitwidth >= 0) {
1503 PrintCursor(cursor, NULL);
1504 printf(" bitwidth=%d\n", Bitwidth);
1505 }
1506
1507 return CXChildVisit_Recurse;
1508}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001509
1510/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001511/* Loading ASTs/source. */
1512/******************************************************************************/
1513
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001514static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001515 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001516 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001517 PostVisitTU PV,
1518 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001519
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001520 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001521 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001522
1523 if (Visitor) {
1524 enum CXCursorKind K = CXCursor_NotImplemented;
1525 enum CXCursorKind *ck = &K;
1526 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001527
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001528 /* Perform some simple filtering. */
1529 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001530 else if (!strcmp(filter, "all-display") ||
1531 !strcmp(filter, "local-display")) {
1532 ck = NULL;
1533 want_display_name = 1;
1534 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001535 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001536 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1537 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1538 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1539 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1540 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1541 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1542 else {
1543 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1544 return 1;
1545 }
Ted Kremenek29004672010-02-17 00:41:32 +00001546
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001547 Data.TU = TU;
1548 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001549 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001550 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001551 }
Ted Kremenek29004672010-02-17 00:41:32 +00001552
Ted Kremenekb478ff42010-01-26 17:59:48 +00001553 if (PV)
1554 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001555
Douglas Gregor33cdd812010-02-18 18:08:43 +00001556 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001557 if (checkForErrors(TU) != 0) {
1558 clang_disposeTranslationUnit(TU);
1559 return -1;
1560 }
1561
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001562 clang_disposeTranslationUnit(TU);
1563 return 0;
1564}
1565
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001566int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001567 const char *prefix, CXCursorVisitor Visitor,
1568 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001569 CXIndex Idx;
1570 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001571 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001572 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001573 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001574 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001575
Ted Kremenek50228be2010-02-11 07:41:25 +00001576 if (!CreateTranslationUnit(Idx, file, &TU)) {
1577 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001578 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001579 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001580
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001581 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001582 clang_disposeIndex(Idx);
1583 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001584}
1585
Ted Kremenekb478ff42010-01-26 17:59:48 +00001586int perform_test_load_source(int argc, const char **argv,
1587 const char *filter, CXCursorVisitor Visitor,
1588 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001589 CXIndex Idx;
1590 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001591 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001592 struct CXUnsavedFile *unsaved_files = 0;
1593 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001594 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001595 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001596 unsigned Repeats = 0;
1597 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001598
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001599 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001600 (!strcmp(filter, "local") ||
1601 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001602 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001603
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001604 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1605 argc--;
1606 argv++;
1607 }
1608
Ted Kremenek50228be2010-02-11 07:41:25 +00001609 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1610 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001611 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001612 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001613
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001614 if (getenv("CINDEXTEST_EDITING"))
1615 Repeats = 5;
1616
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001617 Err = clang_parseTranslationUnit2(Idx, 0,
1618 argv + num_unsaved_files,
1619 argc - num_unsaved_files,
1620 unsaved_files, num_unsaved_files,
1621 getDefaultParsingOptions(), &TU);
1622 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001623 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001624 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001625 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001626 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001627 return 1;
1628 }
1629
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001630 for (I = 0; I != Repeats; ++I) {
1631 if (checkForErrors(TU) != 0)
1632 return -1;
1633
1634 if (Repeats > 1) {
1635 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1636 clang_defaultReparseOptions(TU));
1637 if (Err != CXError_Success) {
1638 describeLibclangFailure(Err);
1639 free_remapped_files(unsaved_files, num_unsaved_files);
1640 clang_disposeIndex(Idx);
1641 return 1;
1642 }
1643 }
1644 }
1645
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001646 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1647 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001648 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001649 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001650 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001651}
1652
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001653int perform_test_reparse_source(int argc, const char **argv, int trials,
1654 const char *filter, CXCursorVisitor Visitor,
1655 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001656 CXIndex Idx;
1657 CXTranslationUnit TU;
1658 struct CXUnsavedFile *unsaved_files = 0;
1659 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001660 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001661 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001662 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001663 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001664 int remap_after_trial = 0;
1665 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001666
1667 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1668 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001669 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001670
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001671 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1672 clang_disposeIndex(Idx);
1673 return -1;
1674 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001675
1676 for (i = 0; i < argc; ++i) {
1677 if (strcmp(argv[i], "--") == 0)
1678 break;
1679 }
1680 if (i < argc)
1681 compiler_arg_idx = i+1;
1682 if (num_unsaved_files > compiler_arg_idx)
1683 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001684
Daniel Dunbarec29d712010-08-18 23:09:16 +00001685 /* Load the initial translation unit -- we do this without honoring remapped
1686 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001687 Err = clang_parseTranslationUnit2(Idx, 0,
1688 argv + compiler_arg_idx,
1689 argc - compiler_arg_idx,
1690 0, 0, getDefaultParsingOptions(), &TU);
1691 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001692 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001693 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001694 free_remapped_files(unsaved_files, num_unsaved_files);
1695 clang_disposeIndex(Idx);
1696 return 1;
1697 }
1698
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001699 if (checkForErrors(TU) != 0)
1700 return -1;
1701
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001702 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1703 remap_after_trial =
1704 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1705 }
1706
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001707 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001708 free_remapped_files(unsaved_files, num_unsaved_files);
1709 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1710 &unsaved_files, &num_unsaved_files)) {
1711 clang_disposeTranslationUnit(TU);
1712 clang_disposeIndex(Idx);
1713 return -1;
1714 }
1715
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001716 Err = clang_reparseTranslationUnit(
1717 TU,
1718 trial >= remap_after_trial ? num_unsaved_files : 0,
1719 trial >= remap_after_trial ? unsaved_files : 0,
1720 clang_defaultReparseOptions(TU));
1721 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001722 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001723 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001724 clang_disposeTranslationUnit(TU);
1725 free_remapped_files(unsaved_files, num_unsaved_files);
1726 clang_disposeIndex(Idx);
1727 return -1;
1728 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001729
1730 if (checkForErrors(TU) != 0)
1731 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001732 }
1733
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001734 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001735
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001736 free_remapped_files(unsaved_files, num_unsaved_files);
1737 clang_disposeIndex(Idx);
1738 return result;
1739}
1740
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001741/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001742/* Logic for testing clang_getCursor(). */
1743/******************************************************************************/
1744
Douglas Gregor37aa4932011-05-04 00:14:37 +00001745static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001746 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001747 unsigned end_line, unsigned end_col,
1748 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001749 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001750 if (prefix)
1751 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001752 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1753 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001754 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001755 printf("\n");
1756}
1757
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001758static int perform_file_scan(const char *ast_file, const char *source_file,
1759 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001760 CXIndex Idx;
1761 CXTranslationUnit TU;
1762 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001763 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001764 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001765 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001766 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001767
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001768 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001769 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001770 fprintf(stderr, "Could not create Index\n");
1771 return 1;
1772 }
Ted Kremenek29004672010-02-17 00:41:32 +00001773
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001774 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1775 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001776
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001777 if ((fp = fopen(source_file, "r")) == NULL) {
1778 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001779 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001780 return 1;
1781 }
Ted Kremenek29004672010-02-17 00:41:32 +00001782
Douglas Gregor816fd362010-01-22 21:44:22 +00001783 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001784 for (;;) {
1785 CXCursor cursor;
1786 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001787
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001788 if (c == '\n') {
1789 ++line;
1790 col = 1;
1791 } else
1792 ++col;
1793
1794 /* Check the cursor at this position, and dump the previous one if we have
1795 * found something new.
1796 */
1797 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1798 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1799 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001800 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001801 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001802 start_line = line;
1803 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001804 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001805 if (c == EOF)
1806 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001807
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001808 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001809 }
Ted Kremenek29004672010-02-17 00:41:32 +00001810
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001811 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001812 clang_disposeTranslationUnit(TU);
1813 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001814 return 0;
1815}
1816
1817/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001818/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001819/******************************************************************************/
1820
Douglas Gregor9eb77012009-11-07 00:00:49 +00001821/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1822 on failure. If successful, the pointer *filename will contain newly-allocated
1823 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001824int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001825 unsigned *column, unsigned *second_line,
1826 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001827 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001828 const char *last_colon = strrchr(input, ':');
1829 unsigned values[4], i;
1830 unsigned num_values = (second_line && second_column)? 4 : 2;
1831
Douglas Gregor9eb77012009-11-07 00:00:49 +00001832 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001833 if (!last_colon || last_colon == input) {
1834 if (num_values == 4)
1835 fprintf(stderr, "could not parse filename:line:column:line:column in "
1836 "'%s'\n", input);
1837 else
1838 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001839 return 1;
1840 }
1841
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001842 for (i = 0; i != num_values; ++i) {
1843 const char *prev_colon;
1844
1845 /* Parse the next line or column. */
1846 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1847 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001848 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001849 (i % 2 ? "column" : "line"), input);
1850 return 1;
1851 }
Ted Kremenek29004672010-02-17 00:41:32 +00001852
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001853 if (i + 1 == num_values)
1854 break;
1855
1856 /* Find the previous colon. */
1857 prev_colon = last_colon - 1;
1858 while (prev_colon != input && *prev_colon != ':')
1859 --prev_colon;
1860 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001861 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001862 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001863 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001864 }
1865
1866 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001867 }
1868
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001869 *line = values[0];
1870 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001871
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001872 if (second_line && second_column) {
1873 *second_line = values[2];
1874 *second_column = values[3];
1875 }
1876
Douglas Gregorf96ea292009-11-09 18:19:57 +00001877 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001878 *filename = (char*)malloc(last_colon - input + 1);
1879 memcpy(*filename, input, last_colon - input);
1880 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001881 return 0;
1882}
1883
1884const char *
1885clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1886 switch (Kind) {
1887 case CXCompletionChunk_Optional: return "Optional";
1888 case CXCompletionChunk_TypedText: return "TypedText";
1889 case CXCompletionChunk_Text: return "Text";
1890 case CXCompletionChunk_Placeholder: return "Placeholder";
1891 case CXCompletionChunk_Informative: return "Informative";
1892 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1893 case CXCompletionChunk_LeftParen: return "LeftParen";
1894 case CXCompletionChunk_RightParen: return "RightParen";
1895 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1896 case CXCompletionChunk_RightBracket: return "RightBracket";
1897 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1898 case CXCompletionChunk_RightBrace: return "RightBrace";
1899 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1900 case CXCompletionChunk_RightAngle: return "RightAngle";
1901 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001902 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001903 case CXCompletionChunk_Colon: return "Colon";
1904 case CXCompletionChunk_SemiColon: return "SemiColon";
1905 case CXCompletionChunk_Equal: return "Equal";
1906 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1907 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001908 }
Ted Kremenek29004672010-02-17 00:41:32 +00001909
Douglas Gregor9eb77012009-11-07 00:00:49 +00001910 return "Unknown";
1911}
1912
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001913static int checkForErrors(CXTranslationUnit TU) {
1914 unsigned Num, i;
1915 CXDiagnostic Diag;
1916 CXString DiagStr;
1917
1918 if (!getenv("CINDEXTEST_FAILONERROR"))
1919 return 0;
1920
1921 Num = clang_getNumDiagnostics(TU);
1922 for (i = 0; i != Num; ++i) {
1923 Diag = clang_getDiagnostic(TU, i);
1924 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1925 DiagStr = clang_formatDiagnostic(Diag,
1926 clang_defaultDiagnosticDisplayOptions());
1927 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1928 clang_disposeString(DiagStr);
1929 clang_disposeDiagnostic(Diag);
1930 return -1;
1931 }
1932 clang_disposeDiagnostic(Diag);
1933 }
1934
1935 return 0;
1936}
1937
Nico Weber8d19dff2014-05-07 21:05:22 +00001938static void print_completion_string(CXCompletionString completion_string,
1939 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001940 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001941
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001942 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001943 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001944 CXString text;
1945 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001946 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001947 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001948
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001949 if (Kind == CXCompletionChunk_Optional) {
1950 fprintf(file, "{Optional ");
1951 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001952 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001953 file);
1954 fprintf(file, "}");
1955 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001956 }
1957
1958 if (Kind == CXCompletionChunk_VerticalSpace) {
1959 fprintf(file, "{VerticalSpace }");
1960 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001961 }
Ted Kremenek29004672010-02-17 00:41:32 +00001962
Douglas Gregorf81f5282009-11-09 17:05:28 +00001963 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001964 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001965 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001966 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001967 cstr ? cstr : "");
1968 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001969 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001970
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001971}
1972
Nico Weber8d19dff2014-05-07 21:05:22 +00001973static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001974 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001975 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001976 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001977 enum CXCursorKind ParentKind;
1978 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001979 CXString BriefComment;
1980 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001981
Ted Kremenek29004672010-02-17 00:41:32 +00001982 fprintf(file, "%s:", clang_getCString(ks));
1983 clang_disposeString(ks);
1984
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001985 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001986 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001987 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001988 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1989 case CXAvailability_Available:
1990 break;
1991
1992 case CXAvailability_Deprecated:
1993 fprintf(file, " (deprecated)");
1994 break;
1995
1996 case CXAvailability_NotAvailable:
1997 fprintf(file, " (unavailable)");
1998 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001999
2000 case CXAvailability_NotAccessible:
2001 fprintf(file, " (inaccessible)");
2002 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002003 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002004
2005 annotationCount = clang_getCompletionNumAnnotations(
2006 completion_result->CompletionString);
2007 if (annotationCount) {
2008 unsigned i;
2009 fprintf(file, " (");
2010 for (i = 0; i < annotationCount; ++i) {
2011 if (i != 0)
2012 fprintf(file, ", ");
2013 fprintf(file, "\"%s\"",
2014 clang_getCString(clang_getCompletionAnnotation(
2015 completion_result->CompletionString, i)));
2016 }
2017 fprintf(file, ")");
2018 }
2019
Douglas Gregor78254c82012-03-27 23:34:16 +00002020 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2021 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2022 &ParentKind);
2023 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002024 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002025 fprintf(file, " (parent: %s '%s')",
2026 clang_getCString(KindSpelling),
2027 clang_getCString(ParentName));
2028 clang_disposeString(KindSpelling);
2029 }
2030 clang_disposeString(ParentName);
2031 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002032
2033 BriefComment = clang_getCompletionBriefComment(
2034 completion_result->CompletionString);
2035 BriefCommentCString = clang_getCString(BriefComment);
2036 if (BriefCommentCString && *BriefCommentCString != '\0') {
2037 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2038 }
2039 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002040
Douglas Gregorf757a122010-08-23 23:00:57 +00002041 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002042}
2043
Douglas Gregor21325842011-07-07 16:03:39 +00002044void print_completion_contexts(unsigned long long contexts, FILE *file) {
2045 fprintf(file, "Completion contexts:\n");
2046 if (contexts == CXCompletionContext_Unknown) {
2047 fprintf(file, "Unknown\n");
2048 }
2049 if (contexts & CXCompletionContext_AnyType) {
2050 fprintf(file, "Any type\n");
2051 }
2052 if (contexts & CXCompletionContext_AnyValue) {
2053 fprintf(file, "Any value\n");
2054 }
2055 if (contexts & CXCompletionContext_ObjCObjectValue) {
2056 fprintf(file, "Objective-C object value\n");
2057 }
2058 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2059 fprintf(file, "Objective-C selector value\n");
2060 }
2061 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2062 fprintf(file, "C++ class type value\n");
2063 }
2064 if (contexts & CXCompletionContext_DotMemberAccess) {
2065 fprintf(file, "Dot member access\n");
2066 }
2067 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2068 fprintf(file, "Arrow member access\n");
2069 }
2070 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2071 fprintf(file, "Objective-C property access\n");
2072 }
2073 if (contexts & CXCompletionContext_EnumTag) {
2074 fprintf(file, "Enum tag\n");
2075 }
2076 if (contexts & CXCompletionContext_UnionTag) {
2077 fprintf(file, "Union tag\n");
2078 }
2079 if (contexts & CXCompletionContext_StructTag) {
2080 fprintf(file, "Struct tag\n");
2081 }
2082 if (contexts & CXCompletionContext_ClassTag) {
2083 fprintf(file, "Class name\n");
2084 }
2085 if (contexts & CXCompletionContext_Namespace) {
2086 fprintf(file, "Namespace or namespace alias\n");
2087 }
2088 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2089 fprintf(file, "Nested name specifier\n");
2090 }
2091 if (contexts & CXCompletionContext_ObjCInterface) {
2092 fprintf(file, "Objective-C interface\n");
2093 }
2094 if (contexts & CXCompletionContext_ObjCProtocol) {
2095 fprintf(file, "Objective-C protocol\n");
2096 }
2097 if (contexts & CXCompletionContext_ObjCCategory) {
2098 fprintf(file, "Objective-C category\n");
2099 }
2100 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2101 fprintf(file, "Objective-C instance method\n");
2102 }
2103 if (contexts & CXCompletionContext_ObjCClassMessage) {
2104 fprintf(file, "Objective-C class method\n");
2105 }
2106 if (contexts & CXCompletionContext_ObjCSelectorName) {
2107 fprintf(file, "Objective-C selector name\n");
2108 }
2109 if (contexts & CXCompletionContext_MacroName) {
2110 fprintf(file, "Macro name\n");
2111 }
2112 if (contexts & CXCompletionContext_NaturalLanguage) {
2113 fprintf(file, "Natural language\n");
2114 }
2115}
2116
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002117int my_stricmp(const char *s1, const char *s2) {
2118 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00002119 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002120 if (c1 < c2)
2121 return -1;
2122 else if (c1 > c2)
2123 return 1;
2124
2125 ++s1;
2126 ++s2;
2127 }
2128
2129 if (*s1)
2130 return 1;
2131 else if (*s2)
2132 return -1;
2133 return 0;
2134}
2135
Douglas Gregor47815d52010-07-12 18:38:41 +00002136int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002137 const char *input = argv[1];
2138 char *filename = 0;
2139 unsigned line;
2140 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002141 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002142 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002143 struct CXUnsavedFile *unsaved_files = 0;
2144 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002145 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002146 enum CXErrorCode Err;
2147 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002148 unsigned I, Repeats = 1;
2149 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2150
2151 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2152 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002153 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2154 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002155
Douglas Gregor47815d52010-07-12 18:38:41 +00002156 if (timing_only)
2157 input += strlen("-code-completion-timing=");
2158 else
2159 input += strlen("-code-completion-at=");
2160
Ted Kremenek29004672010-02-17 00:41:32 +00002161 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002162 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002163 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002164
Douglas Gregor9485bf92009-12-02 09:21:34 +00002165 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2166 return -1;
2167
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002168 CIdx = clang_createIndex(0, 0);
2169
2170 if (getenv("CINDEXTEST_EDITING"))
2171 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002172
2173 Err = clang_parseTranslationUnit2(CIdx, 0,
2174 argv + num_unsaved_files + 2,
2175 argc - num_unsaved_files - 2,
2176 0, 0, getDefaultParsingOptions(), &TU);
2177 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002178 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002179 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002180 return 1;
2181 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002182
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002183 Err = clang_reparseTranslationUnit(TU, 0, 0,
2184 clang_defaultReparseOptions(TU));
2185
2186 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002187 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002188 describeLibclangFailure(Err);
2189 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002190 return 1;
2191 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002192
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002193 for (I = 0; I != Repeats; ++I) {
2194 results = clang_codeCompleteAt(TU, filename, line, column,
2195 unsaved_files, num_unsaved_files,
2196 completionOptions);
2197 if (!results) {
2198 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002199 return 1;
2200 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002201 if (I != Repeats-1)
2202 clang_disposeCodeCompleteResults(results);
2203 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002204
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002205 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002206 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002207 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002208 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002209 CXString objCSelector;
2210 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002211 if (!timing_only) {
2212 /* Sort the code-completion results based on the typed text. */
2213 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2214
Douglas Gregor47815d52010-07-12 18:38:41 +00002215 for (i = 0; i != n; ++i)
2216 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002217 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002218 n = clang_codeCompleteGetNumDiagnostics(results);
2219 for (i = 0; i != n; ++i) {
2220 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2221 PrintDiagnostic(diag);
2222 clang_disposeDiagnostic(diag);
2223 }
Douglas Gregor21325842011-07-07 16:03:39 +00002224
2225 contexts = clang_codeCompleteGetContexts(results);
2226 print_completion_contexts(contexts, stdout);
2227
Douglas Gregorea777402011-07-26 15:24:30 +00002228 containerKind = clang_codeCompleteGetContainerKind(results,
2229 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002230
2231 if (containerKind != CXCursor_InvalidCode) {
2232 /* We have found a container */
2233 CXString containerUSR, containerKindSpelling;
2234 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2235 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2236 clang_disposeString(containerKindSpelling);
2237
2238 if (containerIsIncomplete) {
2239 printf("Container is incomplete\n");
2240 }
2241 else {
2242 printf("Container is complete\n");
2243 }
2244
2245 containerUSR = clang_codeCompleteGetContainerUSR(results);
2246 printf("Container USR: %s\n", clang_getCString(containerUSR));
2247 clang_disposeString(containerUSR);
2248 }
2249
Douglas Gregorea777402011-07-26 15:24:30 +00002250 objCSelector = clang_codeCompleteGetObjCSelector(results);
2251 selectorString = clang_getCString(objCSelector);
2252 if (selectorString && strlen(selectorString) > 0) {
2253 printf("Objective-C selector: %s\n", selectorString);
2254 }
2255 clang_disposeString(objCSelector);
2256
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002257 clang_disposeCodeCompleteResults(results);
2258 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002259 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002260 clang_disposeIndex(CIdx);
2261 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002262
Douglas Gregor9485bf92009-12-02 09:21:34 +00002263 free_remapped_files(unsaved_files, num_unsaved_files);
2264
Ted Kremenekef3339b2009-11-17 18:09:14 +00002265 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002266}
2267
Douglas Gregor082c3e62010-01-15 19:40:17 +00002268typedef struct {
2269 char *filename;
2270 unsigned line;
2271 unsigned column;
2272} CursorSourceLocation;
2273
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002274static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002275 CXIndex CIdx;
2276 int errorCode;
2277 struct CXUnsavedFile *unsaved_files = 0;
2278 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002279 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002280 CXTranslationUnit TU;
2281 CXCursor Cursor;
2282 CursorSourceLocation *Locations = 0;
2283 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002284 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002285 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002286
Ted Kremenek29004672010-02-17 00:41:32 +00002287 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002288 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2289 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002290
Douglas Gregor082c3e62010-01-15 19:40:17 +00002291 /* Parse the locations. */
2292 assert(NumLocations > 0 && "Unable to count locations?");
2293 Locations = (CursorSourceLocation *)malloc(
2294 NumLocations * sizeof(CursorSourceLocation));
2295 for (Loc = 0; Loc < NumLocations; ++Loc) {
2296 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002297 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2298 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002299 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002300 return errorCode;
2301 }
Ted Kremenek29004672010-02-17 00:41:32 +00002302
2303 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002304 &num_unsaved_files))
2305 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002306
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002307 if (getenv("CINDEXTEST_EDITING"))
2308 Repeats = 5;
2309
2310 /* Parse the translation unit. When we're testing clang_getCursor() after
2311 reparsing, don't remap unsaved files until the second parse. */
2312 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002313 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2314 argv + num_unsaved_files + 1 + NumLocations,
2315 argc - num_unsaved_files - 2 - NumLocations,
2316 unsaved_files,
2317 Repeats > 1? 0 : num_unsaved_files,
2318 getDefaultParsingOptions(), &TU);
2319 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002320 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002321 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002322 return -1;
2323 }
Ted Kremenek29004672010-02-17 00:41:32 +00002324
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002325 if (checkForErrors(TU) != 0)
2326 return -1;
2327
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002328 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002329 if (Repeats > 1) {
2330 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2331 clang_defaultReparseOptions(TU));
2332 if (Err != CXError_Success) {
2333 describeLibclangFailure(Err);
2334 clang_disposeTranslationUnit(TU);
2335 return 1;
2336 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002337 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002338
2339 if (checkForErrors(TU) != 0)
2340 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002341
2342 for (Loc = 0; Loc < NumLocations; ++Loc) {
2343 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2344 if (!file)
2345 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002346
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002347 Cursor = clang_getCursor(TU,
2348 clang_getLocation(TU, file, Locations[Loc].line,
2349 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002350
2351 if (checkForErrors(TU) != 0)
2352 return -1;
2353
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002354 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002355 CXCompletionString completionString = clang_getCursorCompletionString(
2356 Cursor);
2357 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002358 CXString Spelling;
2359 const char *cspell;
2360 unsigned line, column;
2361 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2362 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002363 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002364 PrintCursorExtent(Cursor);
2365 Spelling = clang_getCursorSpelling(Cursor);
2366 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002367 if (cspell && strlen(cspell) != 0) {
2368 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002369 printf(" Spelling=%s (", cspell);
2370 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002371 CXSourceRange range =
2372 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002373 if (clang_Range_isNull(range))
2374 break;
2375 PrintRange(range, 0);
2376 }
2377 printf(")");
2378 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002379 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002380 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
Nico Weber8d19dff2014-05-07 21:05:22 +00002381 printf(" Selector index=%d",
2382 clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002383 if (clang_Cursor_isDynamicCall(Cursor))
2384 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002385 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002386 CXType T = clang_Cursor_getReceiverType(Cursor);
2387 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002388 printf(" Receiver-type=%s", clang_getCString(S));
2389 clang_disposeString(S);
2390 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002391
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002392 {
2393 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002394 CXFile astFile;
2395 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002396 unsigned i, numHeaders;
2397 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002398 astFile = clang_Module_getASTFile(mod);
2399 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002400 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002401 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002402 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002403 clang_getCString(name), clang_getCString(astFilename),
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002404 clang_Module_isSystem(mod), numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002405 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002406 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002407 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002408 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2409 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002410 printf("\n%s", clang_getCString(filename));
2411 clang_disposeString(filename);
2412 }
2413 }
2414 }
2415
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002416 if (completionString != NULL) {
2417 printf("\nCompletion string: ");
2418 print_completion_string(completionString, stdout);
2419 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002420 printf("\n");
2421 free(Locations[Loc].filename);
2422 }
2423 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002424 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002425
Douglas Gregor33cdd812010-02-18 18:08:43 +00002426 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002427 clang_disposeTranslationUnit(TU);
2428 clang_disposeIndex(CIdx);
2429 free(Locations);
2430 free_remapped_files(unsaved_files, num_unsaved_files);
2431 return 0;
2432}
2433
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002434static enum CXVisitorResult findFileRefsVisit(void *context,
2435 CXCursor cursor, CXSourceRange range) {
2436 if (clang_Range_isNull(range))
2437 return CXVisit_Continue;
2438
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002439 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002440 PrintRange(range, "");
2441 printf("\n");
2442 return CXVisit_Continue;
2443}
2444
2445static int find_file_refs_at(int argc, const char **argv) {
2446 CXIndex CIdx;
2447 int errorCode;
2448 struct CXUnsavedFile *unsaved_files = 0;
2449 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002450 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002451 CXTranslationUnit TU;
2452 CXCursor Cursor;
2453 CursorSourceLocation *Locations = 0;
2454 unsigned NumLocations = 0, Loc;
2455 unsigned Repeats = 1;
2456 unsigned I;
2457
2458 /* Count the number of locations. */
2459 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2460 ++NumLocations;
2461
2462 /* Parse the locations. */
2463 assert(NumLocations > 0 && "Unable to count locations?");
2464 Locations = (CursorSourceLocation *)malloc(
2465 NumLocations * sizeof(CursorSourceLocation));
2466 for (Loc = 0; Loc < NumLocations; ++Loc) {
2467 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2468 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2469 &Locations[Loc].line,
2470 &Locations[Loc].column, 0, 0)))
2471 return errorCode;
2472 }
2473
2474 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2475 &num_unsaved_files))
2476 return -1;
2477
2478 if (getenv("CINDEXTEST_EDITING"))
2479 Repeats = 5;
2480
2481 /* Parse the translation unit. When we're testing clang_getCursor() after
2482 reparsing, don't remap unsaved files until the second parse. */
2483 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002484 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2485 argv + num_unsaved_files + 1 + NumLocations,
2486 argc - num_unsaved_files - 2 - NumLocations,
2487 unsaved_files,
2488 Repeats > 1? 0 : num_unsaved_files,
2489 getDefaultParsingOptions(), &TU);
2490 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002491 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002492 describeLibclangFailure(Err);
2493 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002494 return -1;
2495 }
2496
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002497 if (checkForErrors(TU) != 0)
2498 return -1;
2499
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002500 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002501 if (Repeats > 1) {
2502 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2503 clang_defaultReparseOptions(TU));
2504 if (Err != CXError_Success) {
2505 describeLibclangFailure(Err);
2506 clang_disposeTranslationUnit(TU);
2507 return 1;
2508 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002509 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002510
2511 if (checkForErrors(TU) != 0)
2512 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002513
2514 for (Loc = 0; Loc < NumLocations; ++Loc) {
2515 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2516 if (!file)
2517 continue;
2518
2519 Cursor = clang_getCursor(TU,
2520 clang_getLocation(TU, file, Locations[Loc].line,
2521 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002522
2523 if (checkForErrors(TU) != 0)
2524 return -1;
2525
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002526 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002527 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002528 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002529 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002530 clang_findReferencesInFile(Cursor, file, visitor);
2531 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002532
2533 if (checkForErrors(TU) != 0)
2534 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002535 }
2536 }
2537 }
2538
2539 PrintDiagnostics(TU);
2540 clang_disposeTranslationUnit(TU);
2541 clang_disposeIndex(CIdx);
2542 free(Locations);
2543 free_remapped_files(unsaved_files, num_unsaved_files);
2544 return 0;
2545}
2546
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002547static enum CXVisitorResult findFileIncludesVisit(void *context,
2548 CXCursor cursor, CXSourceRange range) {
2549 PrintCursor(cursor, NULL);
2550 PrintRange(range, "");
2551 printf("\n");
2552 return CXVisit_Continue;
2553}
2554
2555static int find_file_includes_in(int argc, const char **argv) {
2556 CXIndex CIdx;
2557 struct CXUnsavedFile *unsaved_files = 0;
2558 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002559 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002560 CXTranslationUnit TU;
2561 const char **Filenames = 0;
2562 unsigned NumFilenames = 0;
2563 unsigned Repeats = 1;
2564 unsigned I, FI;
2565
2566 /* Count the number of locations. */
2567 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2568 ++NumFilenames;
2569
2570 /* Parse the locations. */
2571 assert(NumFilenames > 0 && "Unable to count filenames?");
2572 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2573 for (I = 0; I < NumFilenames; ++I) {
2574 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2575 /* Copy the file name. */
2576 Filenames[I] = input;
2577 }
2578
2579 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2580 &num_unsaved_files))
2581 return -1;
2582
2583 if (getenv("CINDEXTEST_EDITING"))
2584 Repeats = 2;
2585
2586 /* Parse the translation unit. When we're testing clang_getCursor() after
2587 reparsing, don't remap unsaved files until the second parse. */
2588 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002589 Err = clang_parseTranslationUnit2(
2590 CIdx, argv[argc - 1],
2591 argv + num_unsaved_files + 1 + NumFilenames,
2592 argc - num_unsaved_files - 2 - NumFilenames,
2593 unsaved_files,
2594 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002595
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002596 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002597 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002598 describeLibclangFailure(Err);
2599 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002600 return -1;
2601 }
2602
2603 if (checkForErrors(TU) != 0)
2604 return -1;
2605
2606 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002607 if (Repeats > 1) {
2608 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2609 clang_defaultReparseOptions(TU));
2610 if (Err != CXError_Success) {
2611 describeLibclangFailure(Err);
2612 clang_disposeTranslationUnit(TU);
2613 return 1;
2614 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002615 }
2616
2617 if (checkForErrors(TU) != 0)
2618 return -1;
2619
2620 for (FI = 0; FI < NumFilenames; ++FI) {
2621 CXFile file = clang_getFile(TU, Filenames[FI]);
2622 if (!file)
2623 continue;
2624
2625 if (checkForErrors(TU) != 0)
2626 return -1;
2627
2628 if (I + 1 == Repeats) {
2629 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2630 clang_findIncludesInFile(TU, file, visitor);
2631
2632 if (checkForErrors(TU) != 0)
2633 return -1;
2634 }
2635 }
2636 }
2637
2638 PrintDiagnostics(TU);
2639 clang_disposeTranslationUnit(TU);
2640 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002641 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002642 free_remapped_files(unsaved_files, num_unsaved_files);
2643 return 0;
2644}
2645
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002646#define MAX_IMPORTED_ASTFILES 200
2647
2648typedef struct {
2649 char **filenames;
2650 unsigned num_files;
2651} ImportedASTFilesData;
2652
2653static ImportedASTFilesData *importedASTs_create() {
2654 ImportedASTFilesData *p;
2655 p = malloc(sizeof(ImportedASTFilesData));
2656 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2657 p->num_files = 0;
2658 return p;
2659}
2660
2661static void importedASTs_dispose(ImportedASTFilesData *p) {
2662 unsigned i;
2663 if (!p)
2664 return;
2665
2666 for (i = 0; i < p->num_files; ++i)
2667 free(p->filenames[i]);
2668 free(p->filenames);
2669 free(p);
2670}
2671
2672static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2673 unsigned i;
2674 assert(p && file);
2675 for (i = 0; i < p->num_files; ++i)
2676 if (strcmp(file, p->filenames[i]) == 0)
2677 return;
2678 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2679 p->filenames[p->num_files++] = strdup(file);
2680}
2681
Nico Weberdf686022014-05-07 21:09:42 +00002682typedef struct IndexDataStringList_ {
2683 struct IndexDataStringList_ *next;
2684 char data[1]; /* Dynamically sized. */
2685} IndexDataStringList;
2686
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002687typedef struct {
2688 const char *check_prefix;
2689 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002690 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002691 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002692 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002693 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002694 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002695 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002696} IndexData;
2697
Nico Weberdf686022014-05-07 21:09:42 +00002698static void free_client_data(IndexData *index_data) {
2699 IndexDataStringList *node = index_data->strings;
2700 while (node) {
2701 IndexDataStringList *next = node->next;
2702 free(node);
2703 node = next;
2704 }
2705 index_data->strings = NULL;
2706}
2707
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002708static void printCheck(IndexData *data) {
2709 if (data->check_prefix) {
2710 if (data->first_check_printed) {
2711 printf("// %s-NEXT: ", data->check_prefix);
2712 } else {
2713 printf("// %s : ", data->check_prefix);
2714 data->first_check_printed = 1;
2715 }
2716 }
2717}
2718
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002719static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002720 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002721 printf("%s", clang_getCString(filename));
2722 clang_disposeString(filename);
2723}
2724
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002725static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2726 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002727 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002728 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002729 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002730 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002731 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002732
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002733 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002734 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2735 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002736 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002737 return;
2738 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002739 if (!file) {
2740 printf("<no idxfile>");
2741 return;
2742 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002743 filename = clang_getFileName((CXFile)file);
2744 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002745 if (strcmp(cname, index_data->main_filename) == 0)
2746 isMainFile = 1;
2747 else
2748 isMainFile = 0;
2749 clang_disposeString(filename);
2750
2751 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002752 printCXIndexFile(file);
2753 printf(":");
2754 }
2755 printf("%d:%d", line, column);
2756}
2757
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002758static unsigned digitCount(unsigned val) {
2759 unsigned c = 1;
2760 while (1) {
2761 if (val < 10)
2762 return c;
2763 ++c;
2764 val /= 10;
2765 }
2766}
2767
Nico Weberdf686022014-05-07 21:09:42 +00002768static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2769 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002770 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002771 IndexData *index_data;
2772 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002773 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002774 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002775 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002776 unsigned line, column;
2777
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002778 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002779 if (!name)
2780 name = "<anon-tag>";
2781
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002782 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002783
2784 node =
2785 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2786 digitCount(line) + digitCount(column) + 2);
2787 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002788 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002789
2790 /* Remember string so it can be freed later. */
2791 index_data = (IndexData *)client_data;
2792 node->next = index_data->strings;
2793 index_data->strings = node;
2794
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002795 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002796}
2797
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002798static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2799 CXIdxClientContainer container;
2800 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002801 if (!container)
2802 printf("[<<NULL>>]");
2803 else
2804 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002805}
2806
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002807static const char *getEntityKindString(CXIdxEntityKind kind) {
2808 switch (kind) {
2809 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2810 case CXIdxEntity_Typedef: return "typedef";
2811 case CXIdxEntity_Function: return "function";
2812 case CXIdxEntity_Variable: return "variable";
2813 case CXIdxEntity_Field: return "field";
2814 case CXIdxEntity_EnumConstant: return "enumerator";
2815 case CXIdxEntity_ObjCClass: return "objc-class";
2816 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2817 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002818 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2819 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002820 case CXIdxEntity_ObjCProperty: return "objc-property";
2821 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2822 case CXIdxEntity_Enum: return "enum";
2823 case CXIdxEntity_Struct: return "struct";
2824 case CXIdxEntity_Union: return "union";
2825 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002826 case CXIdxEntity_CXXNamespace: return "namespace";
2827 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2828 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2829 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2830 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2831 case CXIdxEntity_CXXConstructor: return "constructor";
2832 case CXIdxEntity_CXXDestructor: return "destructor";
2833 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2834 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002835 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002836 }
2837 assert(0 && "Garbage entity kind");
2838 return 0;
2839}
2840
2841static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2842 switch (kind) {
2843 case CXIdxEntity_NonTemplate: return "";
2844 case CXIdxEntity_Template: return "-template";
2845 case CXIdxEntity_TemplatePartialSpecialization:
2846 return "-template-partial-spec";
2847 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002848 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002849 assert(0 && "Garbage entity kind");
2850 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002851}
2852
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002853static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2854 switch (kind) {
2855 case CXIdxEntityLang_None: return "<none>";
2856 case CXIdxEntityLang_C: return "C";
2857 case CXIdxEntityLang_ObjC: return "ObjC";
2858 case CXIdxEntityLang_CXX: return "C++";
2859 }
2860 assert(0 && "Garbage language kind");
2861 return 0;
2862}
2863
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002864static void printEntityInfo(const char *cb,
2865 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002866 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002867 const char *name;
2868 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002869 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002870 index_data = (IndexData *)client_data;
2871 printCheck(index_data);
2872
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002873 if (!info) {
2874 printf("%s: <<NULL>>", cb);
2875 return;
2876 }
2877
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002878 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002879 if (!name)
2880 name = "<anon-tag>";
2881
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002882 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2883 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002884 printf(" | name: %s", name);
2885 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002886 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002887
2888 for (i = 0; i != info->numAttributes; ++i) {
2889 const CXIdxAttrInfo *Attr = info->attributes[i];
2890 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002891 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002892 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002893}
2894
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002895static void printBaseClassInfo(CXClientData client_data,
2896 const CXIdxBaseClassInfo *info) {
2897 printEntityInfo(" <base>", client_data, info->base);
2898 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002899 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002900 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002901 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002902}
2903
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002904static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2905 CXClientData client_data) {
2906 unsigned i;
2907 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2908 printEntityInfo(" <protocol>", client_data,
2909 ProtoInfo->protocols[i]->protocol);
2910 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002911 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002912 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002913 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002914 printf("\n");
2915 }
2916}
2917
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002918static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002919 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002920 CXString str;
2921 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002922 unsigned numDiags, i;
2923 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002924 IndexData *index_data;
2925 index_data = (IndexData *)client_data;
2926 printCheck(index_data);
2927
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002928 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2929 for (i = 0; i != numDiags; ++i) {
2930 diag = clang_getDiagnosticInSet(diagSet, i);
2931 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2932 cstr = clang_getCString(str);
2933 printf("[diagnostic]: %s\n", cstr);
2934 clang_disposeString(str);
2935
2936 if (getenv("CINDEXTEST_FAILONERROR") &&
2937 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2938 index_data->fail_for_error = 1;
2939 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002940 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002941}
2942
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002943static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2944 CXFile file, void *reserved) {
2945 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002946 CXString filename;
2947
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002948 index_data = (IndexData *)client_data;
2949 printCheck(index_data);
2950
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002951 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002952 index_data->main_filename = clang_getCString(filename);
2953 clang_disposeString(filename);
2954
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002955 printf("[enteredMainFile]: ");
2956 printCXIndexFile((CXIdxClientFile)file);
2957 printf("\n");
2958
2959 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002960}
2961
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002962static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002963 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002964 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002965 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002966 index_data = (IndexData *)client_data;
2967 printCheck(index_data);
2968
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002969 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002970 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002971 printf(" | name: \"%s\"", info->filename);
2972 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002973 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002974 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002975 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002976
2977 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
2978 if (Mod) {
2979 CXString str = clang_Module_getFullName(Mod);
2980 const char *cstr = clang_getCString(str);
2981 printf(" | module: %s", cstr);
2982 clang_disposeString(str);
2983 }
2984
2985 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002986
2987 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002988}
2989
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002990static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2991 const CXIdxImportedASTFileInfo *info) {
2992 IndexData *index_data;
2993 index_data = (IndexData *)client_data;
2994 printCheck(index_data);
2995
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002996 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002997 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002998 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2999 clang_disposeString(filename);
3000 }
3001
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003002 printf("[importedASTFile]: ");
3003 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003004 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003005 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003006 printf(" | loc: ");
3007 printCXIndexLoc(info->loc, client_data);
3008 printf(" | name: \"%s\"", clang_getCString(name));
3009 printf(" | isImplicit: %d\n", info->isImplicit);
3010 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003011 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003012 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003013 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003014 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003015
3016 return (CXIdxClientFile)info->file;
3017}
3018
Nico Weber8d19dff2014-05-07 21:05:22 +00003019static CXIdxClientContainer
3020index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003021 IndexData *index_data;
3022 index_data = (IndexData *)client_data;
3023 printCheck(index_data);
3024
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003025 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003026 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003027}
3028
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003029static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003030 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003031 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003032 const CXIdxObjCCategoryDeclInfo *CatInfo;
3033 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003034 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003035 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003036 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003037 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003038 index_data = (IndexData *)client_data;
3039
3040 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3041 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003042 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003043 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003044 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003045 printf(" | semantic-container: ");
3046 printCXIndexContainer(info->semanticContainer);
3047 printf(" | lexical-container: ");
3048 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003049 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003050 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003051 if (info->flags & CXIdxDeclFlag_Skipped) {
3052 assert(!info->isContainer);
3053 printf(" | isContainer: skipped");
3054 } else {
3055 printf(" | isContainer: %d", info->isContainer);
3056 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003057 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003058
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003059 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003060 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003061 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003062 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003063 printf("\n");
3064 }
3065
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003066 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3067 const char *kindName = 0;
3068 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3069 switch (K) {
3070 case CXIdxObjCContainer_ForwardRef:
3071 kindName = "forward-ref"; break;
3072 case CXIdxObjCContainer_Interface:
3073 kindName = "interface"; break;
3074 case CXIdxObjCContainer_Implementation:
3075 kindName = "implementation"; break;
3076 }
3077 printCheck(index_data);
3078 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3079 }
3080
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003081 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003082 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3083 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003084 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003085 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003086 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003087 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003088 printf("\n");
3089 }
3090
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003091 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3092 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003093 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003094 printf("\n");
3095 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003096 }
3097
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003098 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3099 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003100 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003101
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003102 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3103 if (PropInfo->getter) {
3104 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3105 printf("\n");
3106 }
3107 if (PropInfo->setter) {
3108 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3109 printf("\n");
3110 }
3111 }
3112
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003113 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3114 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3115 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3116 printf("\n");
3117 }
3118 }
3119
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003120 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003121 clang_index_setClientContainer(
3122 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003123 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003124}
3125
3126static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003127 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003128 printEntityInfo("[indexEntityReference]", client_data,
3129 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003130 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003131 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003132 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003133 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003134 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003135 printf(" | container: ");
3136 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003137 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003138 switch (info->kind) {
3139 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003140 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003141 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003142 printf("\n");
3143}
3144
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003145static int index_abortQuery(CXClientData client_data, void *reserved) {
3146 IndexData *index_data;
3147 index_data = (IndexData *)client_data;
3148 return index_data->abort;
3149}
3150
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003151static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003152 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003153 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003154 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003155 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003156 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003157 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003158 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003159 index_indexEntityReference
3160};
3161
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003162static unsigned getIndexOptions(void) {
3163 unsigned index_opts;
3164 index_opts = 0;
3165 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3166 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3167 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3168 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003169 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3170 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003171
3172 return index_opts;
3173}
3174
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003175static int index_compile_args(int num_args, const char **args,
3176 CXIndexAction idxAction,
3177 ImportedASTFilesData *importedASTs,
3178 const char *check_prefix) {
3179 IndexData index_data;
3180 unsigned index_opts;
3181 int result;
3182
3183 if (num_args == 0) {
3184 fprintf(stderr, "no compiler arguments\n");
3185 return -1;
3186 }
3187
3188 index_data.check_prefix = check_prefix;
3189 index_data.first_check_printed = 0;
3190 index_data.fail_for_error = 0;
3191 index_data.abort = 0;
3192 index_data.main_filename = "";
3193 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003194 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003195 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003196
3197 index_opts = getIndexOptions();
3198 result = clang_indexSourceFile(idxAction, &index_data,
3199 &IndexCB,sizeof(IndexCB), index_opts,
3200 0, args, num_args, 0, 0, 0,
3201 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003202 if (result != CXError_Success)
3203 describeLibclangFailure(result);
3204
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003205 if (index_data.fail_for_error)
3206 result = -1;
3207
Nico Weberdf686022014-05-07 21:09:42 +00003208 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003209 return result;
3210}
3211
3212static int index_ast_file(const char *ast_file,
3213 CXIndex Idx,
3214 CXIndexAction idxAction,
3215 ImportedASTFilesData *importedASTs,
3216 const char *check_prefix) {
3217 CXTranslationUnit TU;
3218 IndexData index_data;
3219 unsigned index_opts;
3220 int result;
3221
3222 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3223 return -1;
3224
3225 index_data.check_prefix = check_prefix;
3226 index_data.first_check_printed = 0;
3227 index_data.fail_for_error = 0;
3228 index_data.abort = 0;
3229 index_data.main_filename = "";
3230 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003231 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003232 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003233
3234 index_opts = getIndexOptions();
3235 result = clang_indexTranslationUnit(idxAction, &index_data,
3236 &IndexCB,sizeof(IndexCB),
3237 index_opts, TU);
3238 if (index_data.fail_for_error)
3239 result = -1;
3240
3241 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003242 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003243 return result;
3244}
3245
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003246static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003247 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003248 CXIndex Idx;
3249 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003250 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003251 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003252
3253 check_prefix = 0;
3254 if (argc > 0) {
3255 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3256 check_prefix = argv[0] + strlen("-check-prefix=");
3257 ++argv;
3258 --argc;
3259 }
3260 }
3261
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003262 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003263 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003264 fprintf(stderr, "Could not create Index\n");
3265 return 1;
3266 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003267 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003268 importedASTs = 0;
3269 if (full)
3270 importedASTs = importedASTs_create();
3271
3272 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3273 if (result != 0)
3274 goto finished;
3275
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003276 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003277 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003278 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3279 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3280 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003281 }
3282 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003283
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003284finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003285 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003286 clang_IndexAction_dispose(idxAction);
3287 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003288 return result;
3289}
3290
3291static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003292 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003293 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003294 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003295 int result;
3296
3297 check_prefix = 0;
3298 if (argc > 0) {
3299 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3300 check_prefix = argv[0] + strlen("-check-prefix=");
3301 ++argv;
3302 --argc;
3303 }
3304 }
3305
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003306 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003307 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003308 fprintf(stderr, "Could not create Index\n");
3309 return 1;
3310 }
3311 idxAction = clang_IndexAction_create(Idx);
3312
3313 result = index_ast_file(argv[0], Idx, idxAction,
3314 /*importedASTs=*/0, check_prefix);
3315
3316 clang_IndexAction_dispose(idxAction);
3317 clang_disposeIndex(Idx);
3318 return result;
3319}
3320
3321static int index_compile_db(int argc, const char **argv) {
3322 const char *check_prefix;
3323 CXIndex Idx;
3324 CXIndexAction idxAction;
3325 int errorCode = 0;
3326
3327 check_prefix = 0;
3328 if (argc > 0) {
3329 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3330 check_prefix = argv[0] + strlen("-check-prefix=");
3331 ++argv;
3332 --argc;
3333 }
3334 }
3335
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003336 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003337 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003338 return -1;
3339 }
3340
3341 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003342 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003343 fprintf(stderr, "Could not create Index\n");
3344 return 1;
3345 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003346 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003347
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003348 {
3349 const char *database = argv[0];
3350 CXCompilationDatabase db = 0;
3351 CXCompileCommands CCmds = 0;
3352 CXCompileCommand CCmd;
3353 CXCompilationDatabase_Error ec;
3354 CXString wd;
3355#define MAX_COMPILE_ARGS 512
3356 CXString cxargs[MAX_COMPILE_ARGS];
3357 const char *args[MAX_COMPILE_ARGS];
3358 char *tmp;
3359 unsigned len;
3360 char *buildDir;
3361 int i, a, numCmds, numArgs;
3362
3363 len = strlen(database);
3364 tmp = (char *) malloc(len+1);
3365 memcpy(tmp, database, len+1);
3366 buildDir = dirname(tmp);
3367
3368 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3369
3370 if (db) {
3371
3372 if (ec!=CXCompilationDatabase_NoError) {
3373 printf("unexpected error %d code while loading compilation database\n", ec);
3374 errorCode = -1;
3375 goto cdb_end;
3376 }
3377
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003378 if (chdir(buildDir) != 0) {
3379 printf("Could not chdir to %s\n", buildDir);
3380 errorCode = -1;
3381 goto cdb_end;
3382 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003383
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003384 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003385 if (!CCmds) {
3386 printf("compilation db is empty\n");
3387 errorCode = -1;
3388 goto cdb_end;
3389 }
3390
3391 numCmds = clang_CompileCommands_getSize(CCmds);
3392
3393 if (numCmds==0) {
3394 fprintf(stderr, "should not get an empty compileCommand set\n");
3395 errorCode = -1;
3396 goto cdb_end;
3397 }
3398
3399 for (i=0; i<numCmds && errorCode == 0; ++i) {
3400 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3401
3402 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003403 if (chdir(clang_getCString(wd)) != 0) {
3404 printf("Could not chdir to %s\n", clang_getCString(wd));
3405 errorCode = -1;
3406 goto cdb_end;
3407 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003408 clang_disposeString(wd);
3409
3410 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3411 if (numArgs > MAX_COMPILE_ARGS){
3412 fprintf(stderr, "got more compile arguments than maximum\n");
3413 errorCode = -1;
3414 goto cdb_end;
3415 }
3416 for (a=0; a<numArgs; ++a) {
3417 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3418 args[a] = clang_getCString(cxargs[a]);
3419 }
3420
3421 errorCode = index_compile_args(numArgs, args, idxAction,
3422 /*importedASTs=*/0, check_prefix);
3423
3424 for (a=0; a<numArgs; ++a)
3425 clang_disposeString(cxargs[a]);
3426 }
3427 } else {
3428 printf("database loading failed with error code %d.\n", ec);
3429 errorCode = -1;
3430 }
3431
3432 cdb_end:
3433 clang_CompileCommands_dispose(CCmds);
3434 clang_CompilationDatabase_dispose(db);
3435 free(tmp);
3436
3437 }
3438
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003439 clang_IndexAction_dispose(idxAction);
3440 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003441 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003442}
3443
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003444int perform_token_annotation(int argc, const char **argv) {
3445 const char *input = argv[1];
3446 char *filename = 0;
3447 unsigned line, second_line;
3448 unsigned column, second_column;
3449 CXIndex CIdx;
3450 CXTranslationUnit TU = 0;
3451 int errorCode;
3452 struct CXUnsavedFile *unsaved_files = 0;
3453 int num_unsaved_files = 0;
3454 CXToken *tokens;
3455 unsigned num_tokens;
3456 CXSourceRange range;
3457 CXSourceLocation startLoc, endLoc;
3458 CXFile file = 0;
3459 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003460 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003461 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003462 unsigned i;
3463
3464 input += strlen("-test-annotate-tokens=");
3465 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3466 &second_line, &second_column)))
3467 return errorCode;
3468
Richard Smith1ea42eb2012-07-05 08:20:49 +00003469 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3470 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003471 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003472 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003473
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003474 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003475 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3476 argv + num_unsaved_files + 2,
3477 argc - num_unsaved_files - 3,
3478 unsaved_files,
3479 num_unsaved_files,
3480 getDefaultParsingOptions(), &TU);
3481 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003482 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003483 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003484 clang_disposeIndex(CIdx);
3485 free(filename);
3486 free_remapped_files(unsaved_files, num_unsaved_files);
3487 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003488 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003489 errorCode = 0;
3490
Richard Smith1ea42eb2012-07-05 08:20:49 +00003491 if (checkForErrors(TU) != 0) {
3492 errorCode = -1;
3493 goto teardown;
3494 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003495
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003496 if (getenv("CINDEXTEST_EDITING")) {
3497 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003498 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3499 clang_defaultReparseOptions(TU));
3500 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003501 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003502 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003503 errorCode = -1;
3504 goto teardown;
3505 }
3506 }
3507 }
3508
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003509 if (checkForErrors(TU) != 0) {
3510 errorCode = -1;
3511 goto teardown;
3512 }
3513
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003514 file = clang_getFile(TU, filename);
3515 if (!file) {
3516 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3517 errorCode = -1;
3518 goto teardown;
3519 }
3520
3521 startLoc = clang_getLocation(TU, file, line, column);
3522 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003523 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003524 column);
3525 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003526 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003527 }
3528
3529 endLoc = clang_getLocation(TU, file, second_line, second_column);
3530 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003531 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003532 second_line, second_column);
3533 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003534 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003535 }
3536
3537 range = clang_getRange(startLoc, endLoc);
3538 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003539
3540 if (checkForErrors(TU) != 0) {
3541 errorCode = -1;
3542 goto teardown;
3543 }
3544
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003545 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3546 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003547
3548 if (checkForErrors(TU) != 0) {
3549 errorCode = -1;
3550 goto teardown;
3551 }
3552
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003553 skipped_ranges = clang_getSkippedRanges(TU, file);
3554 for (i = 0; i != skipped_ranges->count; ++i) {
3555 unsigned start_line, start_column, end_line, end_column;
3556 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3557 0, &start_line, &start_column, 0);
3558 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3559 0, &end_line, &end_column, 0);
3560 printf("Skipping: ");
3561 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3562 printf("\n");
3563 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003564 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003565
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003566 for (i = 0; i != num_tokens; ++i) {
3567 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003568 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3569 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003570 unsigned start_line, start_column, end_line, end_column;
3571
3572 switch (clang_getTokenKind(tokens[i])) {
3573 case CXToken_Punctuation: kind = "Punctuation"; break;
3574 case CXToken_Keyword: kind = "Keyword"; break;
3575 case CXToken_Identifier: kind = "Identifier"; break;
3576 case CXToken_Literal: kind = "Literal"; break;
3577 case CXToken_Comment: kind = "Comment"; break;
3578 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003579 clang_getSpellingLocation(clang_getRangeStart(extent),
3580 0, &start_line, &start_column, 0);
3581 clang_getSpellingLocation(clang_getRangeEnd(extent),
3582 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003583 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003584 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003585 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003586 if (!clang_isInvalid(cursors[i].kind)) {
3587 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003588 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003589 }
3590 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003591 }
3592 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003593 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003594
3595 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003596 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003597 clang_disposeTranslationUnit(TU);
3598 clang_disposeIndex(CIdx);
3599 free(filename);
3600 free_remapped_files(unsaved_files, num_unsaved_files);
3601 return errorCode;
3602}
3603
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003604static int
3605perform_test_compilation_db(const char *database, int argc, const char **argv) {
3606 CXCompilationDatabase db;
3607 CXCompileCommands CCmds;
3608 CXCompileCommand CCmd;
3609 CXCompilationDatabase_Error ec;
3610 CXString wd;
3611 CXString arg;
3612 int errorCode = 0;
3613 char *tmp;
3614 unsigned len;
3615 char *buildDir;
3616 int i, j, a, numCmds, numArgs;
3617
3618 len = strlen(database);
3619 tmp = (char *) malloc(len+1);
3620 memcpy(tmp, database, len+1);
3621 buildDir = dirname(tmp);
3622
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003623 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003624
3625 if (db) {
3626
3627 if (ec!=CXCompilationDatabase_NoError) {
3628 printf("unexpected error %d code while loading compilation database\n", ec);
3629 errorCode = -1;
3630 goto cdb_end;
3631 }
3632
3633 for (i=0; i<argc && errorCode==0; ) {
3634 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003635 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003636
3637 if (!CCmds) {
3638 printf("file %s not found in compilation db\n", argv[i+1]);
3639 errorCode = -1;
3640 break;
3641 }
3642
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003643 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003644
3645 if (numCmds==0) {
3646 fprintf(stderr, "should not get an empty compileCommand set for file"
3647 " '%s'\n", argv[i+1]);
3648 errorCode = -1;
3649 break;
3650 }
3651
3652 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003653 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003654
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003655 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003656 printf("workdir:'%s'", clang_getCString(wd));
3657 clang_disposeString(wd);
3658
3659 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003660 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003661 for (a=0; a<numArgs; ++a) {
3662 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003663 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003664 printf("%s", clang_getCString(arg));
3665 clang_disposeString(arg);
3666 }
3667 printf("'\n");
3668 }
3669
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003670 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003671
3672 i += 2;
3673 }
3674 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003675 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003676 } else {
3677 printf("database loading failed with error code %d.\n", ec);
3678 errorCode = -1;
3679 }
3680
3681cdb_end:
3682 free(tmp);
3683
3684 return errorCode;
3685}
3686
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003687/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003688/* USR printing. */
3689/******************************************************************************/
3690
3691static int insufficient_usr(const char *kind, const char *usage) {
3692 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3693 return 1;
3694}
3695
3696static unsigned isUSR(const char *s) {
3697 return s[0] == 'c' && s[1] == ':';
3698}
3699
3700static int not_usr(const char *s, const char *arg) {
3701 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3702 return 1;
3703}
3704
3705static void print_usr(CXString usr) {
3706 const char *s = clang_getCString(usr);
3707 printf("%s\n", s);
3708 clang_disposeString(usr);
3709}
3710
3711static void display_usrs() {
3712 fprintf(stderr, "-print-usrs options:\n"
3713 " ObjCCategory <class name> <category name>\n"
3714 " ObjCClass <class name>\n"
3715 " ObjCIvar <ivar name> <class USR>\n"
3716 " ObjCMethod <selector> [0=class method|1=instance method] "
3717 "<class USR>\n"
3718 " ObjCProperty <property name> <class USR>\n"
3719 " ObjCProtocol <protocol name>\n");
3720}
3721
3722int print_usrs(const char **I, const char **E) {
3723 while (I != E) {
3724 const char *kind = *I;
3725 unsigned len = strlen(kind);
3726 switch (len) {
3727 case 8:
3728 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3729 if (I + 2 >= E)
3730 return insufficient_usr(kind, "<ivar name> <class USR>");
3731 if (!isUSR(I[2]))
3732 return not_usr("<class USR>", I[2]);
3733 else {
3734 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003735 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003736 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003737 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3738 }
3739
3740 I += 3;
3741 continue;
3742 }
3743 break;
3744 case 9:
3745 if (memcmp(kind, "ObjCClass", 9) == 0) {
3746 if (I + 1 >= E)
3747 return insufficient_usr(kind, "<class name>");
3748 print_usr(clang_constructUSR_ObjCClass(I[1]));
3749 I += 2;
3750 continue;
3751 }
3752 break;
3753 case 10:
3754 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3755 if (I + 3 >= E)
3756 return insufficient_usr(kind, "<method selector> "
3757 "[0=class method|1=instance method] <class USR>");
3758 if (!isUSR(I[3]))
3759 return not_usr("<class USR>", I[3]);
3760 else {
3761 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003762 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003763 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003764 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3765 }
3766 I += 4;
3767 continue;
3768 }
3769 break;
3770 case 12:
3771 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3772 if (I + 2 >= E)
3773 return insufficient_usr(kind, "<class name> <category name>");
3774 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3775 I += 3;
3776 continue;
3777 }
3778 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3779 if (I + 1 >= E)
3780 return insufficient_usr(kind, "<protocol name>");
3781 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3782 I += 2;
3783 continue;
3784 }
3785 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3786 if (I + 2 >= E)
3787 return insufficient_usr(kind, "<property name> <class USR>");
3788 if (!isUSR(I[2]))
3789 return not_usr("<class USR>", I[2]);
3790 else {
3791 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003792 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003793 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003794 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3795 }
3796 I += 3;
3797 continue;
3798 }
3799 break;
3800 default:
3801 break;
3802 }
3803 break;
3804 }
3805
3806 if (I != E) {
3807 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3808 display_usrs();
3809 return 1;
3810 }
3811 return 0;
3812}
3813
3814int print_usrs_file(const char *file_name) {
3815 char line[2048];
3816 const char *args[128];
3817 unsigned numChars = 0;
3818
3819 FILE *fp = fopen(file_name, "r");
3820 if (!fp) {
3821 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3822 return 1;
3823 }
3824
3825 /* This code is not really all that safe, but it works fine for testing. */
3826 while (!feof(fp)) {
3827 char c = fgetc(fp);
3828 if (c == '\n') {
3829 unsigned i = 0;
3830 const char *s = 0;
3831
3832 if (numChars == 0)
3833 continue;
3834
3835 line[numChars] = '\0';
3836 numChars = 0;
3837
3838 if (line[0] == '/' && line[1] == '/')
3839 continue;
3840
3841 s = strtok(line, " ");
3842 while (s) {
3843 args[i] = s;
3844 ++i;
3845 s = strtok(0, " ");
3846 }
3847 if (print_usrs(&args[0], &args[i]))
3848 return 1;
3849 }
3850 else
3851 line[numChars++] = c;
3852 }
3853
3854 fclose(fp);
3855 return 0;
3856}
3857
3858/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003859/* Command line processing. */
3860/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003861int write_pch_file(const char *filename, int argc, const char *argv[]) {
3862 CXIndex Idx;
3863 CXTranslationUnit TU;
3864 struct CXUnsavedFile *unsaved_files = 0;
3865 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003866 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003867 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003868
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003869 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003870
3871 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3872 clang_disposeIndex(Idx);
3873 return -1;
3874 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003875
3876 Err = clang_parseTranslationUnit2(
3877 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3878 unsaved_files, num_unsaved_files,
3879 CXTranslationUnit_Incomplete |
3880 CXTranslationUnit_DetailedPreprocessingRecord |
3881 CXTranslationUnit_ForSerialization,
3882 &TU);
3883 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003884 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003885 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003886 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003887 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003888 clang_disposeIndex(Idx);
3889 return 1;
3890 }
3891
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003892 switch (clang_saveTranslationUnit(TU, filename,
3893 clang_defaultSaveOptions(TU))) {
3894 case CXSaveError_None:
3895 break;
3896
3897 case CXSaveError_TranslationErrors:
3898 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3899 filename);
3900 result = 2;
3901 break;
3902
3903 case CXSaveError_InvalidTU:
3904 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3905 filename);
3906 result = 3;
3907 break;
3908
3909 case CXSaveError_Unknown:
3910 default:
3911 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3912 result = 1;
3913 break;
3914 }
3915
Douglas Gregore9386682010-08-13 05:36:37 +00003916 clang_disposeTranslationUnit(TU);
3917 free_remapped_files(unsaved_files, num_unsaved_files);
3918 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003919 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003920}
3921
3922/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003923/* Serialized diagnostics. */
3924/******************************************************************************/
3925
3926static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3927 switch (error) {
3928 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3929 case CXLoadDiag_None: break;
3930 case CXLoadDiag_Unknown: return "Unknown";
3931 case CXLoadDiag_InvalidFile: return "Invalid File";
3932 }
3933 return "None";
3934}
3935
3936static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3937 switch (severity) {
3938 case CXDiagnostic_Note: return "note";
3939 case CXDiagnostic_Error: return "error";
3940 case CXDiagnostic_Fatal: return "fatal";
3941 case CXDiagnostic_Ignored: return "ignored";
3942 case CXDiagnostic_Warning: return "warning";
3943 }
3944 return "unknown";
3945}
3946
3947static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003948 if (indent == 0)
3949 return;
3950 fprintf(stderr, "+");
3951 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003952 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003953 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003954 --indent;
3955 }
3956}
3957
3958static void printLocation(CXSourceLocation L) {
3959 CXFile File;
3960 CXString FileName;
3961 unsigned line, column, offset;
3962
3963 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3964 FileName = clang_getFileName(File);
3965
3966 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3967 clang_disposeString(FileName);
3968}
3969
3970static void printRanges(CXDiagnostic D, unsigned indent) {
3971 unsigned i, n = clang_getDiagnosticNumRanges(D);
3972
3973 for (i = 0; i < n; ++i) {
3974 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003975 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003976 Start = clang_getRangeStart(SR);
3977 End = clang_getRangeEnd(SR);
3978
3979 printIndent(indent);
3980 fprintf(stderr, "Range: ");
3981 printLocation(Start);
3982 fprintf(stderr, " ");
3983 printLocation(End);
3984 fprintf(stderr, "\n");
3985 }
3986}
3987
3988static void printFixIts(CXDiagnostic D, unsigned indent) {
3989 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003990 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003991 for (i = 0 ; i < n; ++i) {
3992 CXSourceRange ReplacementRange;
3993 CXString text;
3994 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3995
3996 printIndent(indent);
3997 fprintf(stderr, "FIXIT: (");
3998 printLocation(clang_getRangeStart(ReplacementRange));
3999 fprintf(stderr, " - ");
4000 printLocation(clang_getRangeEnd(ReplacementRange));
4001 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4002 clang_disposeString(text);
4003 }
4004}
4005
4006static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004007 unsigned i, n;
4008
Ted Kremenekd010ba42011-11-10 08:43:12 +00004009 if (!Diags)
4010 return;
4011
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004012 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004013 for (i = 0; i < n; ++i) {
4014 CXSourceLocation DiagLoc;
4015 CXDiagnostic D;
4016 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004017 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004018 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004019 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004020
4021 D = clang_getDiagnosticInSet(Diags, i);
4022 DiagLoc = clang_getDiagnosticLocation(D);
4023 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4024 FileName = clang_getFileName(File);
4025 DiagSpelling = clang_getDiagnosticSpelling(D);
4026
4027 printIndent(indent);
4028
4029 fprintf(stderr, "%s:%d:%d: %s: %s",
4030 clang_getCString(FileName),
4031 line,
4032 column,
4033 getSeverityString(clang_getDiagnosticSeverity(D)),
4034 clang_getCString(DiagSpelling));
4035
4036 DiagOption = clang_getDiagnosticOption(D, 0);
4037 DiagOptionStr = clang_getCString(DiagOption);
4038 if (DiagOptionStr) {
4039 fprintf(stderr, " [%s]", DiagOptionStr);
4040 }
4041
Ted Kremenek26a6d492012-04-12 00:03:31 +00004042 DiagCat = clang_getDiagnosticCategoryText(D);
4043 DiagCatStr = clang_getCString(DiagCat);
4044 if (DiagCatStr) {
4045 fprintf(stderr, " [%s]", DiagCatStr);
4046 }
4047
Ted Kremenekd010ba42011-11-10 08:43:12 +00004048 fprintf(stderr, "\n");
4049
4050 printRanges(D, indent);
4051 printFixIts(D, indent);
4052
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004053 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004054 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4055
4056 clang_disposeString(FileName);
4057 clang_disposeString(DiagSpelling);
4058 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004059 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004060 }
4061}
4062
4063static int read_diagnostics(const char *filename) {
4064 enum CXLoadDiag_Error error;
4065 CXString errorString;
4066 CXDiagnosticSet Diags = 0;
4067
4068 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4069 if (!Diags) {
4070 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4071 getDiagnosticCodeStr(error),
4072 clang_getCString(errorString));
4073 clang_disposeString(errorString);
4074 return 1;
4075 }
4076
4077 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004078 fprintf(stderr, "Number of diagnostics: %d\n",
4079 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004080 clang_disposeDiagnosticSet(Diags);
4081 return 0;
4082}
4083
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004084static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004085 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004086 return 0;
4087}
4088
Ted Kremenekd010ba42011-11-10 08:43:12 +00004089/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004090/* Command line processing. */
4091/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004092
Douglas Gregor720d0052010-01-20 21:32:04 +00004093static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004094 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004095 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004096 if (strcmp(s, "-usrs") == 0)
4097 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004098 if (strncmp(s, "-memory-usage", 13) == 0)
4099 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004100 return NULL;
4101}
4102
Ted Kremenekef3339b2009-11-17 18:09:14 +00004103static void print_usage(void) {
4104 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004105 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004106 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004107 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004108 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4109 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004110 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004111 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004112 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004113 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004114 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004115 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004116 "[FileCheck prefix]\n");
4117 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004118 " c-index-test -test-load-tu <AST file> <symbol filter> "
4119 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004120 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4121 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004122 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004123 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004124 " c-index-test -test-load-source-memory-usage "
4125 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004126 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4127 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004128 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004129 " c-index-test -test-load-source-usrs-memory-usage "
4130 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004131 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4132 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004133 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004134 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004135 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004136 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004137 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004138 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004139 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004140 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004141 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004142 " c-index-test -write-pch <file> <compiler arguments>\n");
4143 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004144 " c-index-test -compilation-db [lookup <filename>] database\n");
4145 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004146 " c-index-test -print-build-session-timestamp\n");
4147 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004148 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004149 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004150 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004151 " all - load all symbols, including those from PCH\n"
4152 " local - load all symbols except those in PCH\n"
4153 " category - only load ObjC categories (non-PCH)\n"
4154 " interface - only load ObjC interfaces (non-PCH)\n"
4155 " protocol - only load ObjC protocols (non-PCH)\n"
4156 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004157 " typedef - only load typdefs (non-PCH)\n"
4158 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004159}
4160
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004161/***/
4162
4163int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004164 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004165 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4166 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004167 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004168 return perform_code_completion(argc, argv, 0);
4169 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4170 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004171 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
4172 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004173 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4174 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004175 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4176 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004177 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004178 return index_file(argc - 2, argv + 2, /*full=*/0);
4179 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4180 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004181 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4182 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004183 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4184 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004185 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004186 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004187 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004188 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4189 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004190 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004191 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4192 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4193 if (I) {
4194 int trials = atoi(argv[2]);
4195 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4196 NULL);
4197 }
4198 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004199 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004200 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004201
4202 PostVisitTU postVisit = 0;
4203 if (strstr(argv[1], "-memory-usage"))
4204 postVisit = PrintMemoryUsage;
4205
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004206 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004207 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4208 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004209 }
4210 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004211 return perform_file_scan(argv[2], argv[3],
4212 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004213 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4214 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004215 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4216 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4217 PrintInclusionStack);
4218 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4219 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4220 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004221 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4222 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4223 NULL);
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004224 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4225 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4226 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004227 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004228 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004229 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004230 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4231 return perform_test_load_source(argc - 2, argv + 2, "all",
4232 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004233 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4234 return perform_test_load_source(argc - 2, argv + 2, "all",
4235 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004236 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4237 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004238 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4239 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004240 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4241 if (argc > 2)
4242 return print_usrs(argv + 2, argv + argc);
4243 else {
4244 display_usrs();
4245 return 1;
4246 }
4247 }
4248 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4249 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004250 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4251 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004252 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4253 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004254 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4255 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004256
Ted Kremenekef3339b2009-11-17 18:09:14 +00004257 print_usage();
4258 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004259}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004260
4261/***/
4262
4263/* We intentionally run in a separate thread to ensure we at least minimal
4264 * testing of a multithreaded environment (for example, having a reduced stack
4265 * size). */
4266
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004267typedef struct thread_info {
4268 int argc;
4269 const char **argv;
4270 int result;
4271} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004272void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004273 thread_info *client_data = client_data_v;
4274 client_data->result = cindextest_main(client_data->argc, client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004275}
4276
4277static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004278 /* stdout, and surprisingly even stderr, are not always flushed on process
4279 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004280 fflush(stdout);
4281 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004282}
4283
4284int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004285 thread_info client_data;
4286
Reid Klecknere931c062014-06-05 00:13:43 +00004287 atexit(flush_atexit);
4288
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004289#ifdef CLANG_HAVE_LIBXML
4290 LIBXML_TEST_VERSION
4291#endif
4292
Douglas Gregorf428bf82010-10-27 16:00:01 +00004293 if (getenv("CINDEXTEST_NOTHREADS"))
4294 return cindextest_main(argc, argv);
4295
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004296 client_data.argc = argc;
4297 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004298 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004299 return client_data.result;
4300}