blob: 948195debaefcb9bd20a4a72a2f38649d9101135 [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;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000079
80 return options;
81}
82
Patrik Hagglund55701d22014-02-17 11:54:08 +000083/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000084static int checkForErrors(CXTranslationUnit TU);
85
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000086static void describeLibclangFailure(enum CXErrorCode Err) {
87 switch (Err) {
88 case CXError_Success:
89 fprintf(stderr, "Success\n");
90 return;
91
92 case CXError_Failure:
93 fprintf(stderr, "Failure (no details available)\n");
94 return;
95
96 case CXError_Crashed:
97 fprintf(stderr, "Failure: libclang crashed\n");
98 return;
99
100 case CXError_InvalidArguments:
101 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
102 return;
103
104 case CXError_ASTReadError:
105 fprintf(stderr, "Failure: AST deserialization error occurred\n");
106 return;
107 }
108}
109
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000110static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
111 unsigned end_line, unsigned end_column) {
112 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000113 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000114}
115
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000116static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
117 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000118 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
119 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000120 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000121 describeLibclangFailure(Err);
122 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000123 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000124 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000125 return 1;
126}
127
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000128void free_remapped_files(struct CXUnsavedFile *unsaved_files,
129 int num_unsaved_files) {
130 int i;
131 for (i = 0; i != num_unsaved_files; ++i) {
132 free((char *)unsaved_files[i].Filename);
133 free((char *)unsaved_files[i].Contents);
134 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000135 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000136}
137
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000138static int parse_remapped_files_with_opt(const char *opt_name,
139 int argc, const char **argv,
140 int start_arg,
141 struct CXUnsavedFile **unsaved_files,
142 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000143 int i;
144 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000145 int prefix_len = strlen(opt_name);
146 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000147 *unsaved_files = 0;
148 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000149
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000150 /* Count the number of remapped files. */
151 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000152 if (strncmp(argv[arg], opt_name, prefix_len))
153 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000154
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000155 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
156 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000157 ++*num_unsaved_files;
158 }
Ted Kremenek29004672010-02-17 00:41:32 +0000159
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000160 if (*num_unsaved_files == 0)
161 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000162
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000163 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000164 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
165 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000166 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000167 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000168 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000169 int filename_len;
170 char *filename;
171 char *contents;
172 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000173 const char *sep = strchr(arg_string, ',');
174 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000175 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000176 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000177 free_remapped_files(*unsaved_files, i);
178 *unsaved_files = 0;
179 *num_unsaved_files = 0;
180 return -1;
181 }
Ted Kremenek29004672010-02-17 00:41:32 +0000182
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000183 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000184 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000185 if (!to_file) {
186 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000187 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000188 free_remapped_files(*unsaved_files, i);
189 *unsaved_files = 0;
190 *num_unsaved_files = 0;
191 return -1;
192 }
Ted Kremenek29004672010-02-17 00:41:32 +0000193
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000194 /* Determine the length of the file we're remapping to. */
195 fseek(to_file, 0, SEEK_END);
196 unsaved->Length = ftell(to_file);
197 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000198
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000199 /* Read the contents of the file we're remapping to. */
200 contents = (char *)malloc(unsaved->Length + 1);
201 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
202 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000203 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000204 fclose(to_file);
205 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000206 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000207 *unsaved_files = 0;
208 *num_unsaved_files = 0;
209 return -1;
210 }
211 contents[unsaved->Length] = 0;
212 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000213
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000214 /* Close the file. */
215 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000216
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000217 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000218 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000219 filename = (char *)malloc(filename_len + 1);
220 memcpy(filename, arg_string, filename_len);
221 filename[filename_len] = 0;
222 unsaved->Filename = filename;
223 }
Ted Kremenek29004672010-02-17 00:41:32 +0000224
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000225 return 0;
226}
227
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000228static int parse_remapped_files(int argc, const char **argv, int start_arg,
229 struct CXUnsavedFile **unsaved_files,
230 int *num_unsaved_files) {
231 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
232 unsaved_files, num_unsaved_files);
233}
234
235static int parse_remapped_files_with_try(int try_idx,
236 int argc, const char **argv,
237 int start_arg,
238 struct CXUnsavedFile **unsaved_files,
239 int *num_unsaved_files) {
240 struct CXUnsavedFile *unsaved_files_no_try_idx;
241 int num_unsaved_files_no_try_idx;
242 struct CXUnsavedFile *unsaved_files_try_idx;
243 int num_unsaved_files_try_idx;
244 int ret;
245 char opt_name[32];
246
247 ret = parse_remapped_files(argc, argv, start_arg,
248 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
249 if (ret)
250 return ret;
251
252 sprintf(opt_name, "-remap-file-%d=", try_idx);
253 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
254 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
255 if (ret)
256 return ret;
257
Chandler Carruth6ac555f2015-08-04 03:53:04 +0000258 if (num_unsaved_files_no_try_idx == 0) {
259 *unsaved_files = unsaved_files_try_idx;
260 *num_unsaved_files = num_unsaved_files_try_idx;
261 return 0;
262 }
263 if (num_unsaved_files_try_idx == 0) {
264 *unsaved_files = unsaved_files_no_try_idx;
265 *num_unsaved_files = num_unsaved_files_no_try_idx;
266 return 0;
267 }
268
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000269 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
270 *unsaved_files
271 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
272 sizeof(struct CXUnsavedFile) *
273 *num_unsaved_files);
274 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
275 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
276 num_unsaved_files_try_idx);
277 free(unsaved_files_try_idx);
278 return 0;
279}
280
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000281static const char *parse_comments_schema(int argc, const char **argv) {
282 const char *CommentsSchemaArg = "-comments-xml-schema=";
283 const char *CommentSchemaFile = NULL;
284
285 if (argc == 0)
286 return CommentSchemaFile;
287
288 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
289 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
290
291 return CommentSchemaFile;
292}
293
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000294/******************************************************************************/
295/* Pretty-printing. */
296/******************************************************************************/
297
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000298static const char *FileCheckPrefix = "CHECK";
299
300static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000301 if (CStr != NULL && CStr[0] != '\0') {
302 for ( ; *CStr; ++CStr) {
303 const char C = *CStr;
304 switch (C) {
305 case '\n': printf("\\n"); break;
306 case '\r': printf("\\r"); break;
307 case '\t': printf("\\t"); break;
308 case '\v': printf("\\v"); break;
309 case '\f': printf("\\f"); break;
310 default: putchar(C); break;
311 }
312 }
313 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000314}
315
316static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
317 printf(" %s=[", Prefix);
318 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000319 printf("]");
320}
321
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000322static void PrintCXStringAndDispose(CXString Str) {
323 PrintCString(clang_getCString(Str));
324 clang_disposeString(Str);
325}
326
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000327static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
328 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
329}
330
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000331static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
332 CXString Str) {
333 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
334 clang_disposeString(Str);
335}
336
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000337static void PrintRange(CXSourceRange R, const char *str) {
338 CXFile begin_file, end_file;
339 unsigned begin_line, begin_column, end_line, end_column;
340
341 clang_getSpellingLocation(clang_getRangeStart(R),
342 &begin_file, &begin_line, &begin_column, 0);
343 clang_getSpellingLocation(clang_getRangeEnd(R),
344 &end_file, &end_line, &end_column, 0);
345 if (!begin_file || !end_file)
346 return;
347
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000348 if (str)
349 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000350 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
351}
352
Douglas Gregor97c75712010-10-02 22:49:11 +0000353int want_display_name = 0;
354
Douglas Gregord6225d32012-05-08 00:14:45 +0000355static void printVersion(const char *Prefix, CXVersion Version) {
356 if (Version.Major < 0)
357 return;
358 printf("%s%d", Prefix, Version.Major);
359
360 if (Version.Minor < 0)
361 return;
362 printf(".%d", Version.Minor);
363
364 if (Version.Subminor < 0)
365 return;
366 printf(".%d", Version.Subminor);
367}
368
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000369struct CommentASTDumpingContext {
370 int IndentLevel;
371};
372
373static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
374 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000375 unsigned i;
376 unsigned e;
377 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
378
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000379 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000380 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000381 printf(" ");
382
383 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000384 switch (Kind) {
385 case CXComment_Null:
386 printf("CXComment_Null");
387 break;
388 case CXComment_Text:
389 printf("CXComment_Text");
390 PrintCXStringWithPrefixAndDispose("Text",
391 clang_TextComment_getText(Comment));
392 if (clang_Comment_isWhitespace(Comment))
393 printf(" IsWhitespace");
394 if (clang_InlineContentComment_hasTrailingNewline(Comment))
395 printf(" HasTrailingNewline");
396 break;
397 case CXComment_InlineCommand:
398 printf("CXComment_InlineCommand");
399 PrintCXStringWithPrefixAndDispose(
400 "CommandName",
401 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000402 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
403 case CXCommentInlineCommandRenderKind_Normal:
404 printf(" RenderNormal");
405 break;
406 case CXCommentInlineCommandRenderKind_Bold:
407 printf(" RenderBold");
408 break;
409 case CXCommentInlineCommandRenderKind_Monospaced:
410 printf(" RenderMonospaced");
411 break;
412 case CXCommentInlineCommandRenderKind_Emphasized:
413 printf(" RenderEmphasized");
414 break;
415 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000416 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000417 i != e; ++i) {
418 printf(" Arg[%u]=", i);
419 PrintCXStringAndDispose(
420 clang_InlineCommandComment_getArgText(Comment, i));
421 }
422 if (clang_InlineContentComment_hasTrailingNewline(Comment))
423 printf(" HasTrailingNewline");
424 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000425 case CXComment_HTMLStartTag: {
426 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000427 printf("CXComment_HTMLStartTag");
428 PrintCXStringWithPrefixAndDispose(
429 "Name",
430 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000431 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000432 if (NumAttrs != 0) {
433 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000434 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000435 printf(" ");
436 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
437 printf("=");
438 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
439 }
440 }
441 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
442 printf(" SelfClosing");
443 if (clang_InlineContentComment_hasTrailingNewline(Comment))
444 printf(" HasTrailingNewline");
445 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000446 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000447 case CXComment_HTMLEndTag:
448 printf("CXComment_HTMLEndTag");
449 PrintCXStringWithPrefixAndDispose(
450 "Name",
451 clang_HTMLTagComment_getTagName(Comment));
452 if (clang_InlineContentComment_hasTrailingNewline(Comment))
453 printf(" HasTrailingNewline");
454 break;
455 case CXComment_Paragraph:
456 printf("CXComment_Paragraph");
457 if (clang_Comment_isWhitespace(Comment))
458 printf(" IsWhitespace");
459 break;
460 case CXComment_BlockCommand:
461 printf("CXComment_BlockCommand");
462 PrintCXStringWithPrefixAndDispose(
463 "CommandName",
464 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000465 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000466 i != e; ++i) {
467 printf(" Arg[%u]=", i);
468 PrintCXStringAndDispose(
469 clang_BlockCommandComment_getArgText(Comment, i));
470 }
471 break;
472 case CXComment_ParamCommand:
473 printf("CXComment_ParamCommand");
474 switch (clang_ParamCommandComment_getDirection(Comment)) {
475 case CXCommentParamPassDirection_In:
476 printf(" in");
477 break;
478 case CXCommentParamPassDirection_Out:
479 printf(" out");
480 break;
481 case CXCommentParamPassDirection_InOut:
482 printf(" in,out");
483 break;
484 }
485 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
486 printf(" explicitly");
487 else
488 printf(" implicitly");
489 PrintCXStringWithPrefixAndDispose(
490 "ParamName",
491 clang_ParamCommandComment_getParamName(Comment));
492 if (clang_ParamCommandComment_isParamIndexValid(Comment))
493 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
494 else
495 printf(" ParamIndex=Invalid");
496 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000497 case CXComment_TParamCommand:
498 printf("CXComment_TParamCommand");
499 PrintCXStringWithPrefixAndDispose(
500 "ParamName",
501 clang_TParamCommandComment_getParamName(Comment));
502 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
503 printf(" ParamPosition={");
504 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
505 i != e; ++i) {
506 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
507 if (i != e - 1)
508 printf(", ");
509 }
510 printf("}");
511 } else
512 printf(" ParamPosition=Invalid");
513 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000514 case CXComment_VerbatimBlockCommand:
515 printf("CXComment_VerbatimBlockCommand");
516 PrintCXStringWithPrefixAndDispose(
517 "CommandName",
518 clang_BlockCommandComment_getCommandName(Comment));
519 break;
520 case CXComment_VerbatimBlockLine:
521 printf("CXComment_VerbatimBlockLine");
522 PrintCXStringWithPrefixAndDispose(
523 "Text",
524 clang_VerbatimBlockLineComment_getText(Comment));
525 break;
526 case CXComment_VerbatimLine:
527 printf("CXComment_VerbatimLine");
528 PrintCXStringWithPrefixAndDispose(
529 "Text",
530 clang_VerbatimLineComment_getText(Comment));
531 break;
532 case CXComment_FullComment:
533 printf("CXComment_FullComment");
534 break;
535 }
536 if (Kind != CXComment_Null) {
537 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000538 unsigned i;
539 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000540 printf("\n// %s: ", FileCheckPrefix);
541 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
542 }
543 }
544 printf(")");
545 Ctx->IndentLevel--;
546}
547
548static void DumpCXComment(CXComment Comment) {
549 struct CommentASTDumpingContext Ctx;
550 Ctx.IndentLevel = 1;
551 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
552 DumpCXCommentInternal(&Ctx, Comment);
553 printf("]");
554}
555
Chandler Carruthb2faa592014-05-02 23:30:59 +0000556static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000557#ifdef CLANG_HAVE_LIBXML
558 xmlRelaxNGParserCtxtPtr RNGParser;
559 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000560 xmlDocPtr Doc;
561 xmlRelaxNGValidCtxtPtr ValidationCtxt;
562 int status;
563
Chandler Carruthb2faa592014-05-02 23:30:59 +0000564 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000565 return;
566
Chandler Carruthb2faa592014-05-02 23:30:59 +0000567 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
568 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000569 printf(" libXMLError");
570 return;
571 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000572 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000573
574 Doc = xmlParseDoc((const xmlChar *) Str);
575
576 if (!Doc) {
577 xmlErrorPtr Error = xmlGetLastError();
578 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
579 return;
580 }
581
Chandler Carruthb2faa592014-05-02 23:30:59 +0000582 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000583 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
584 if (!status)
585 printf(" CommentXMLValid");
586 else if (status > 0) {
587 xmlErrorPtr Error = xmlGetLastError();
588 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
589 } else
590 printf(" libXMLError");
591
592 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
593 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000594 xmlRelaxNGFree(Schema);
595 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000596#endif
597}
598
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000599static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000600 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000601 {
602 CXString RawComment;
603 const char *RawCommentCString;
604 CXString BriefComment;
605 const char *BriefCommentCString;
606
607 RawComment = clang_Cursor_getRawCommentText(Cursor);
608 RawCommentCString = clang_getCString(RawComment);
609 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
610 PrintCStringWithPrefix("RawComment", RawCommentCString);
611 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
612
613 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
614 BriefCommentCString = clang_getCString(BriefComment);
615 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
616 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
617 clang_disposeString(BriefComment);
618 }
619 clang_disposeString(RawComment);
620 }
621
622 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000623 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000624 if (clang_Comment_getKind(Comment) != CXComment_Null) {
625 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
626 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000627 {
628 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000629 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000630 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000631 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000632 clang_disposeString(XML);
633 }
634
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000635 DumpCXComment(Comment);
636 }
637 }
638}
639
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000640typedef struct {
641 unsigned line;
642 unsigned col;
643} LineCol;
644
645static int lineCol_cmp(const void *p1, const void *p2) {
646 const LineCol *lhs = p1;
647 const LineCol *rhs = p2;
648 if (lhs->line != rhs->line)
649 return (int)lhs->line - (int)rhs->line;
650 return (int)lhs->col - (int)rhs->col;
651}
652
Chandler Carruthb2faa592014-05-02 23:30:59 +0000653static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000654 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000655 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000656 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000657 printf("Invalid Cursor => %s", clang_getCString(ks));
658 clang_disposeString(ks);
659 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000660 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000661 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000662 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000663 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000664 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000665 CXCursor *overridden;
666 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000667 unsigned RefNameRangeNr;
668 CXSourceRange CursorExtent;
669 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000670 int AlwaysUnavailable;
671 int AlwaysDeprecated;
672 CXString UnavailableMessage;
673 CXString DeprecatedMessage;
674 CXPlatformAvailability PlatformAvailability[2];
675 int NumPlatformAvailability;
676 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000677
Ted Kremenek29004672010-02-17 00:41:32 +0000678 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000679 string = want_display_name? clang_getCursorDisplayName(Cursor)
680 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000681 printf("%s=%s", clang_getCString(ks),
682 clang_getCString(string));
683 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000684 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000685
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000686 Referenced = clang_getCursorReferenced(Cursor);
687 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000688 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
689 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
690 printf("[");
691 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000692 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000693 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000694 if (I)
695 printf(", ");
696
Douglas Gregor2967e282010-09-14 00:20:32 +0000697 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000698 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000699 printf("%d:%d", line, column);
700 }
701 printf("]");
702 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000703 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000704 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000705 printf(":%d:%d", line, column);
706 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000707 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000708
709 if (clang_isCursorDefinition(Cursor))
710 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000711
712 switch (clang_getCursorAvailability(Cursor)) {
713 case CXAvailability_Available:
714 break;
715
716 case CXAvailability_Deprecated:
717 printf(" (deprecated)");
718 break;
719
720 case CXAvailability_NotAvailable:
721 printf(" (unavailable)");
722 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000723
724 case CXAvailability_NotAccessible:
725 printf(" (inaccessible)");
726 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000727 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000728
Douglas Gregord6225d32012-05-08 00:14:45 +0000729 NumPlatformAvailability
730 = clang_getCursorPlatformAvailability(Cursor,
731 &AlwaysDeprecated,
732 &DeprecatedMessage,
733 &AlwaysUnavailable,
734 &UnavailableMessage,
735 PlatformAvailability, 2);
736 if (AlwaysUnavailable) {
737 printf(" (always unavailable: \"%s\")",
738 clang_getCString(UnavailableMessage));
739 } else if (AlwaysDeprecated) {
740 printf(" (always deprecated: \"%s\")",
741 clang_getCString(DeprecatedMessage));
742 } else {
743 for (I = 0; I != NumPlatformAvailability; ++I) {
744 if (I >= 2)
745 break;
746
747 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
748 if (PlatformAvailability[I].Unavailable)
749 printf(", unavailable");
750 else {
751 printVersion(", introduced=", PlatformAvailability[I].Introduced);
752 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
753 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
754 }
755 if (clang_getCString(PlatformAvailability[I].Message)[0])
756 printf(", message=\"%s\"",
757 clang_getCString(PlatformAvailability[I].Message));
758 printf(")");
759 }
760 }
761 for (I = 0; I != NumPlatformAvailability; ++I) {
762 if (I >= 2)
763 break;
764 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
765 }
766
767 clang_disposeString(DeprecatedMessage);
768 clang_disposeString(UnavailableMessage);
769
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000770 if (clang_CXXField_isMutable(Cursor))
771 printf(" (mutable)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000772 if (clang_CXXMethod_isStatic(Cursor))
773 printf(" (static)");
774 if (clang_CXXMethod_isVirtual(Cursor))
775 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000776 if (clang_CXXMethod_isConst(Cursor))
777 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000778 if (clang_CXXMethod_isPureVirtual(Cursor))
779 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000780 if (clang_Cursor_isVariadic(Cursor))
781 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000782 if (clang_Cursor_isObjCOptional(Cursor))
783 printf(" (@optional)");
784
Ted Kremeneka5940822010-08-26 01:42:22 +0000785 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000786 CXType T =
787 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
788 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000789 printf(" [IBOutletCollection=%s]", clang_getCString(S));
790 clang_disposeString(S);
791 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000792
793 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
794 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
795 unsigned isVirtual = clang_isVirtualBase(Cursor);
796 const char *accessStr = 0;
797
798 switch (access) {
799 case CX_CXXInvalidAccessSpecifier:
800 accessStr = "invalid"; break;
801 case CX_CXXPublic:
802 accessStr = "public"; break;
803 case CX_CXXProtected:
804 accessStr = "protected"; break;
805 case CX_CXXPrivate:
806 accessStr = "private"; break;
807 }
808
809 printf(" [access=%s isVirtual=%s]", accessStr,
810 isVirtual ? "true" : "false");
811 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000812
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000813 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
814 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000815 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
816 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000817 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000818 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000819 clang_getCString(Name), line, column);
820 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000821
822 if (Cursor.kind == CXCursor_FunctionDecl) {
823 /* Collect the template parameter kinds from the base template. */
824 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
825 unsigned I;
826 for (I = 0; I < NumTemplateArgs; I++) {
827 enum CXTemplateArgumentKind TAK =
828 clang_Cursor_getTemplateArgumentKind(Cursor, I);
829 switch(TAK) {
830 case CXTemplateArgumentKind_Type:
831 {
832 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
833 CXString S = clang_getTypeSpelling(T);
834 printf(" [Template arg %d: kind: %d, type: %s]",
835 I, TAK, clang_getCString(S));
836 clang_disposeString(S);
837 }
838 break;
839 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000840 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000841 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
842 break;
843 default:
844 printf(" [Template arg %d: kind: %d]\n", I, TAK);
845 }
846 }
847 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000848 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000849
850 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
851 if (num_overridden) {
852 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000853 LineCol lineCols[50];
854 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000855 printf(" [Overrides ");
856 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000857 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000858 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000859 lineCols[I].line = line;
860 lineCols[I].col = column;
861 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000862 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000863 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
864 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000865 if (I)
866 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000867 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000868 }
869 printf("]");
870 clang_disposeOverriddenCursors(overridden);
871 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000872
873 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000874 CXFile File = clang_getIncludedFile(Cursor);
875 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000876 printf(" (%s)", clang_getCString(Included));
877 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000878
879 if (clang_isFileMultipleIncludeGuarded(TU, File))
880 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000881 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000882
883 CursorExtent = clang_getCursorExtent(Cursor);
884 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
885 CXNameRange_WantQualifier
886 | CXNameRange_WantSinglePiece
887 | CXNameRange_WantTemplateArgs,
888 0);
889 if (!clang_equalRanges(CursorExtent, RefNameRange))
890 PrintRange(RefNameRange, "SingleRefName");
891
892 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
893 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
894 CXNameRange_WantQualifier
895 | CXNameRange_WantTemplateArgs,
896 RefNameRangeNr);
897 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
898 break;
899 if (!clang_equalRanges(CursorExtent, RefNameRange))
900 PrintRange(RefNameRange, "RefName");
901 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000902
Chandler Carruthb2faa592014-05-02 23:30:59 +0000903 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000904
905 {
906 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
907 if (PropAttrs != CXObjCPropertyAttr_noattr) {
908 printf(" [");
909 #define PRINT_PROP_ATTR(A) \
910 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
911 PRINT_PROP_ATTR(readonly);
912 PRINT_PROP_ATTR(getter);
913 PRINT_PROP_ATTR(assign);
914 PRINT_PROP_ATTR(readwrite);
915 PRINT_PROP_ATTR(retain);
916 PRINT_PROP_ATTR(copy);
917 PRINT_PROP_ATTR(nonatomic);
918 PRINT_PROP_ATTR(setter);
919 PRINT_PROP_ATTR(atomic);
920 PRINT_PROP_ATTR(weak);
921 PRINT_PROP_ATTR(strong);
922 PRINT_PROP_ATTR(unsafe_unretained);
923 printf("]");
924 }
925 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000926
927 {
928 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
929 if (QT != CXObjCDeclQualifier_None) {
930 printf(" [");
931 #define PRINT_OBJC_QUAL(A) \
932 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
933 PRINT_OBJC_QUAL(In);
934 PRINT_OBJC_QUAL(Inout);
935 PRINT_OBJC_QUAL(Out);
936 PRINT_OBJC_QUAL(Bycopy);
937 PRINT_OBJC_QUAL(Byref);
938 PRINT_OBJC_QUAL(Oneway);
939 printf("]");
940 }
941 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000942 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000943}
Steve Naroff1054e602009-08-31 00:59:03 +0000944
Ted Kremenek29004672010-02-17 00:41:32 +0000945static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000946 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000947 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000948 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000949 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000950 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000951 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000952 clang_disposeString(source);
953 return "<invalid loc>";
954 }
955 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000956 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000957 clang_disposeString(source);
958 return b;
959 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000960}
961
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000962/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000963/* Callbacks. */
964/******************************************************************************/
965
966typedef void (*PostVisitTU)(CXTranslationUnit);
967
Douglas Gregor33cdd812010-02-18 18:08:43 +0000968void PrintDiagnostic(CXDiagnostic Diagnostic) {
969 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000970 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000971 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000972 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000973 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
974 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000975 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000976
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000977 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000978 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000979
Douglas Gregord770f732010-02-22 23:17:23 +0000980 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
981 fprintf(stderr, "%s\n", clang_getCString(Msg));
982 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000983
Douglas Gregor229bebd2010-11-09 06:24:54 +0000984 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
985 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000986 if (!file)
987 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000988
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000989 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000990 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000991 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000992 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000993 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
994 CXSourceLocation start = clang_getRangeStart(range);
995 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000996 unsigned start_line, start_column, end_line, end_column;
997 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +0000998 clang_getSpellingLocation(start, &start_file, &start_line,
999 &start_column, 0);
1000 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001001 if (clang_equalLocations(start, end)) {
1002 /* Insertion. */
1003 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001004 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001005 clang_getCString(insertion_text), start_line, start_column);
1006 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1007 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001008 if (start_file == file && end_file == file) {
1009 fprintf(out, "FIX-IT: Remove ");
1010 PrintExtent(out, start_line, start_column, end_line, end_column);
1011 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001012 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001013 } else {
1014 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001015 if (start_file == end_file) {
1016 fprintf(out, "FIX-IT: Replace ");
1017 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001018 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001019 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001020 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001021 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001022 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001023}
1024
Ted Kremenek914c7e62012-02-14 02:46:03 +00001025void PrintDiagnosticSet(CXDiagnosticSet Set) {
1026 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1027 for ( ; i != n ; ++i) {
1028 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1029 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001030 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001031 if (ChildDiags)
1032 PrintDiagnosticSet(ChildDiags);
1033 }
1034}
1035
1036void PrintDiagnostics(CXTranslationUnit TU) {
1037 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1038 PrintDiagnosticSet(TUSet);
1039 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001040}
1041
Ted Kremenek83f642e2011-04-18 22:47:10 +00001042void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001043 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001044 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001045 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001046 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001047 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001048 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001049 unsigned long amount = usage.entries[i].amount;
1050 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001051 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001052 ((double) amount)/(1024*1024));
1053 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001054 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001055 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001056 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001057}
1058
Ted Kremenekb478ff42010-01-26 17:59:48 +00001059/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001060/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001061/******************************************************************************/
1062
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001063static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001064 CXSourceRange extent = clang_getCursorExtent(C);
1065 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001066}
1067
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001068/* Data used by the visitors. */
1069typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001070 CXTranslationUnit TU;
1071 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001072 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001073} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001074
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001075
Ted Kremenek29004672010-02-17 00:41:32 +00001076enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001077 CXCursor Parent,
1078 CXClientData ClientData) {
1079 VisitorData *Data = (VisitorData *)ClientData;
1080 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001081 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001082 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001083 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001084 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001085 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001086 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001087 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001088 if (clang_isDeclaration(Cursor.kind)) {
1089 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1090 const char *accessStr = 0;
1091
1092 switch (access) {
1093 case CX_CXXInvalidAccessSpecifier: break;
1094 case CX_CXXPublic:
1095 accessStr = "public"; break;
1096 case CX_CXXProtected:
1097 accessStr = "protected"; break;
1098 case CX_CXXPrivate:
1099 accessStr = "private"; break;
1100 }
1101
1102 if (accessStr)
1103 printf(" [access=%s]", accessStr);
1104 }
Ted Kremenek29004672010-02-17 00:41:32 +00001105 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001106 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001107 }
Ted Kremenek29004672010-02-17 00:41:32 +00001108
Douglas Gregor720d0052010-01-20 21:32:04 +00001109 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001110}
Steve Naroffa1c72842009-08-28 15:28:48 +00001111
Ted Kremenek29004672010-02-17 00:41:32 +00001112static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001113 CXCursor Parent,
1114 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001115 const char *startBuf, *endBuf;
1116 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1117 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001118 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001119
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001120 if (Cursor.kind != CXCursor_FunctionDecl ||
1121 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001122 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001123
1124 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1125 &startLine, &startColumn,
1126 &endLine, &endColumn);
1127 /* Probe the entire body, looking for both decls and refs. */
1128 curLine = startLine;
1129 curColumn = startColumn;
1130
1131 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001132 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001133 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001134 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001135
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001136 if (*startBuf == '\n') {
1137 startBuf++;
1138 curLine++;
1139 curColumn = 1;
1140 } else if (*startBuf != '\t')
1141 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001142
Douglas Gregor66a58812010-01-18 22:46:11 +00001143 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001144 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001145
Douglas Gregor4f46e782010-01-19 21:36:55 +00001146 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001147 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001148 CXSourceLocation RefLoc
1149 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001150 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001151 if (Ref.kind == CXCursor_NoDeclFound) {
1152 /* Nothing found here; that's fine. */
1153 } else if (Ref.kind != CXCursor_FunctionDecl) {
1154 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1155 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001156 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001157 printf("\n");
1158 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001159 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001160 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001161 startBuf++;
1162 }
Ted Kremenek29004672010-02-17 00:41:32 +00001163
Douglas Gregor720d0052010-01-20 21:32:04 +00001164 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001165}
1166
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001167/******************************************************************************/
1168/* USR testing. */
1169/******************************************************************************/
1170
Douglas Gregor720d0052010-01-20 21:32:04 +00001171enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1172 CXClientData ClientData) {
1173 VisitorData *Data = (VisitorData *)ClientData;
1174 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001175 CXString USR = clang_getCursorUSR(C);
1176 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001177 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001178 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001179 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001180 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001181 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1182
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001183 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001184 printf("\n");
1185 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001186
Douglas Gregor720d0052010-01-20 21:32:04 +00001187 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001188 }
1189
Douglas Gregor720d0052010-01-20 21:32:04 +00001190 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001191}
1192
1193/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001194/* Inclusion stack testing. */
1195/******************************************************************************/
1196
1197void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1198 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001199
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001200 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001201 CXString fname;
1202
1203 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001204 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001205 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001206
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001207 for (i = 0; i < includeStackLen; ++i) {
1208 CXFile includingFile;
1209 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001210 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1211 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001212 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001213 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001214 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001215 }
1216 printf("\n");
1217}
1218
1219void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001220 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001221}
1222
1223/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001224/* Linkage testing. */
1225/******************************************************************************/
1226
1227static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1228 CXClientData d) {
1229 const char *linkage = 0;
1230
1231 if (clang_isInvalid(clang_getCursorKind(cursor)))
1232 return CXChildVisit_Recurse;
1233
1234 switch (clang_getCursorLinkage(cursor)) {
1235 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001236 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1237 case CXLinkage_Internal: linkage = "Internal"; break;
1238 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1239 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001240 }
1241
1242 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001243 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001244 printf("linkage=%s\n", linkage);
1245 }
1246
1247 return CXChildVisit_Recurse;
1248}
1249
1250/******************************************************************************/
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00001251/* Visibility testing. */
1252/******************************************************************************/
1253
1254static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1255 CXClientData d) {
1256 const char *visibility = 0;
1257
1258 if (clang_isInvalid(clang_getCursorKind(cursor)))
1259 return CXChildVisit_Recurse;
1260
1261 switch (clang_getCursorVisibility(cursor)) {
1262 case CXVisibility_Invalid: break;
1263 case CXVisibility_Hidden: visibility = "Hidden"; break;
1264 case CXVisibility_Protected: visibility = "Protected"; break;
1265 case CXVisibility_Default: visibility = "Default"; break;
1266 }
1267
1268 if (visibility) {
1269 PrintCursor(cursor, NULL);
1270 printf("visibility=%s\n", visibility);
1271 }
1272
1273 return CXChildVisit_Recurse;
1274}
1275
1276/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001277/* Typekind testing. */
1278/******************************************************************************/
1279
Dmitri Gribenko00353722013-02-15 21:15:49 +00001280static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1281 CXString TypeSpelling, TypeKindSpelling;
1282
1283 TypeSpelling = clang_getTypeSpelling(T);
1284 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1285 printf(Format,
1286 clang_getCString(TypeSpelling),
1287 clang_getCString(TypeKindSpelling));
1288 clang_disposeString(TypeSpelling);
1289 clang_disposeString(TypeKindSpelling);
1290}
1291
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001292static enum CXVisitorResult FieldVisitor(CXCursor C,
1293 CXClientData client_data) {
1294 (*(int *) client_data)+=1;
1295 return CXVisit_Continue;
1296}
1297
Dmitri Gribenko00353722013-02-15 21:15:49 +00001298static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1299 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001300 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001301 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001302 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001303 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001304 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001305 if (clang_isConstQualifiedType(T))
1306 printf(" const");
1307 if (clang_isVolatileQualifiedType(T))
1308 printf(" volatile");
1309 if (clang_isRestrictQualifiedType(T))
1310 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001311 if (RQ == CXRefQualifier_LValue)
1312 printf(" lvalue-ref-qualifier");
1313 if (RQ == CXRefQualifier_RValue)
1314 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001315 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001316 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001317 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001318 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001319 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001320 }
1321 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001322 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001323 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001324 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001325 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001326 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001327 }
1328 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001329 /* Print the argument types if they exist. */
1330 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001331 int NumArgs = clang_Cursor_getNumArguments(cursor);
1332 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001333 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001334 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001335 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001336 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001337 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001338 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001339 }
1340 }
1341 printf("]");
1342 }
1343 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001344 /* Print the template argument types if they exist. */
1345 {
1346 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1347 if (NumTArgs != -1 && NumTArgs != 0) {
1348 int i;
1349 printf(" [templateargs/%d=", NumTArgs);
1350 for (i = 0; i < NumTArgs; ++i) {
1351 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1352 if (TArg.kind != CXType_Invalid) {
1353 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1354 }
1355 }
1356 printf("]");
1357 }
1358 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001359 /* Print if this is a non-POD type. */
1360 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001361 /* Print the pointee type. */
1362 {
1363 CXType PT = clang_getPointeeType(T);
1364 if (PT.kind != CXType_Invalid) {
1365 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1366 }
1367 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001368 /* Print the number of fields if they exist. */
1369 {
1370 int numFields = 0;
1371 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1372 if (numFields != 0) {
1373 printf(" [nbFields=%d]", numFields);
1374 }
1375 /* Print if it is an anonymous record. */
1376 {
1377 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1378 if (isAnon != 0) {
1379 printf(" [isAnon=%d]", isAnon);
1380 }
1381 }
1382 }
1383 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001384
Ted Kremenek6bca9842010-05-14 21:29:26 +00001385 printf("\n");
1386 }
1387 return CXChildVisit_Recurse;
1388}
1389
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001390static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1391 CXClientData d) {
1392 CXType T;
1393 enum CXCursorKind K = clang_getCursorKind(cursor);
1394 if (clang_isInvalid(K))
1395 return CXChildVisit_Recurse;
1396 T = clang_getCursorType(cursor);
1397 PrintCursor(cursor, NULL);
1398 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1399 /* Print the type sizeof if applicable. */
1400 {
1401 long long Size = clang_Type_getSizeOf(T);
1402 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001403 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001404 }
1405 }
1406 /* Print the type alignof if applicable. */
1407 {
1408 long long Align = clang_Type_getAlignOf(T);
1409 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001410 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001411 }
1412 }
1413 /* Print the record field offset if applicable. */
1414 {
Nico Weber82098cb2014-04-24 04:14:12 +00001415 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1416 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001417 /* recurse to get the first parent record that is not anonymous. */
1418 CXCursor Parent, Record;
1419 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001420 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001421 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001422 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001423 Record = Parent;
1424 Parent = clang_getCursorSemanticParent(Record);
1425 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1426 /* Recurse as long as the parent is a CXType_Record and the Record
1427 is anonymous */
1428 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1429 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001430 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001431 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001432 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001433 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1434 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001435 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001436 } else {
1437 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001438 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001439 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001440 }
1441 }
Nico Weber82098cb2014-04-24 04:14:12 +00001442 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001443 }
1444 /* Print if its a bitfield */
1445 {
1446 int IsBitfield = clang_Cursor_isBitField(cursor);
1447 if (IsBitfield)
1448 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1449 }
1450 printf("\n");
1451 return CXChildVisit_Recurse;
1452}
1453
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001454/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001455/* Mangling testing. */
1456/******************************************************************************/
1457
1458static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1459 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001460 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001461 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1462 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001463 PrintCursor(cursor, NULL);
1464 MangledName = clang_Cursor_getMangling(cursor);
1465 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001466 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001467 return CXChildVisit_Continue;
1468}
1469
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001470static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1471 CXClientData d) {
1472 unsigned I, E;
1473 CXStringSet *Manglings = NULL;
1474 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1475 return CXChildVisit_Recurse;
1476 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1477 return CXChildVisit_Recurse;
1478 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1479 return CXChildVisit_Continue;
1480 PrintCursor(cursor, NULL);
1481 Manglings = clang_Cursor_getCXXManglings(cursor);
1482 for (I = 0, E = Manglings->Count; I < E; ++I)
1483 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1484 clang_disposeStringSet(Manglings);
1485 printf("\n");
1486 return CXChildVisit_Recurse;
1487}
1488
Eli Bendersky44a206f2014-07-31 18:04:56 +00001489/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001490/* Bitwidth testing. */
1491/******************************************************************************/
1492
1493static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1494 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001495 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001496 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1497 return CXChildVisit_Recurse;
1498
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001499 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001500 if (Bitwidth >= 0) {
1501 PrintCursor(cursor, NULL);
1502 printf(" bitwidth=%d\n", Bitwidth);
1503 }
1504
1505 return CXChildVisit_Recurse;
1506}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001507
1508/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001509/* Loading ASTs/source. */
1510/******************************************************************************/
1511
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001512static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001513 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001514 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001515 PostVisitTU PV,
1516 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001517
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001518 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001519 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001520
1521 if (Visitor) {
1522 enum CXCursorKind K = CXCursor_NotImplemented;
1523 enum CXCursorKind *ck = &K;
1524 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001525
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001526 /* Perform some simple filtering. */
1527 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001528 else if (!strcmp(filter, "all-display") ||
1529 !strcmp(filter, "local-display")) {
1530 ck = NULL;
1531 want_display_name = 1;
1532 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001533 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001534 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1535 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1536 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1537 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1538 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1539 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1540 else {
1541 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1542 return 1;
1543 }
Ted Kremenek29004672010-02-17 00:41:32 +00001544
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001545 Data.TU = TU;
1546 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001547 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001548 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001549 }
Ted Kremenek29004672010-02-17 00:41:32 +00001550
Ted Kremenekb478ff42010-01-26 17:59:48 +00001551 if (PV)
1552 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001553
Douglas Gregor33cdd812010-02-18 18:08:43 +00001554 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001555 if (checkForErrors(TU) != 0) {
1556 clang_disposeTranslationUnit(TU);
1557 return -1;
1558 }
1559
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001560 clang_disposeTranslationUnit(TU);
1561 return 0;
1562}
1563
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001564int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001565 const char *prefix, CXCursorVisitor Visitor,
1566 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001567 CXIndex Idx;
1568 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001569 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001570 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001571 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001572 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001573
Ted Kremenek50228be2010-02-11 07:41:25 +00001574 if (!CreateTranslationUnit(Idx, file, &TU)) {
1575 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001576 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001577 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001578
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001579 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001580 clang_disposeIndex(Idx);
1581 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001582}
1583
Ted Kremenekb478ff42010-01-26 17:59:48 +00001584int perform_test_load_source(int argc, const char **argv,
1585 const char *filter, CXCursorVisitor Visitor,
1586 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001587 CXIndex Idx;
1588 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001589 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001590 struct CXUnsavedFile *unsaved_files = 0;
1591 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001592 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001593 int result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001594
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001595 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001596 (!strcmp(filter, "local") ||
1597 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001598 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001599
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001600 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1601 argc--;
1602 argv++;
1603 }
1604
Ted Kremenek50228be2010-02-11 07:41:25 +00001605 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1606 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001607 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001608 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001609
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001610 Err = clang_parseTranslationUnit2(Idx, 0,
1611 argv + num_unsaved_files,
1612 argc - num_unsaved_files,
1613 unsaved_files, num_unsaved_files,
1614 getDefaultParsingOptions(), &TU);
1615 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001616 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001617 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001618 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001619 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001620 return 1;
1621 }
1622
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001623 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1624 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001625 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001626 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001627 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001628}
1629
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001630int perform_test_reparse_source(int argc, const char **argv, int trials,
1631 const char *filter, CXCursorVisitor Visitor,
1632 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001633 CXIndex Idx;
1634 CXTranslationUnit TU;
1635 struct CXUnsavedFile *unsaved_files = 0;
1636 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001637 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001638 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001639 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001640 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001641 int remap_after_trial = 0;
1642 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001643
1644 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1645 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001646 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001647
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001648 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1649 clang_disposeIndex(Idx);
1650 return -1;
1651 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001652
1653 for (i = 0; i < argc; ++i) {
1654 if (strcmp(argv[i], "--") == 0)
1655 break;
1656 }
1657 if (i < argc)
1658 compiler_arg_idx = i+1;
1659 if (num_unsaved_files > compiler_arg_idx)
1660 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001661
Daniel Dunbarec29d712010-08-18 23:09:16 +00001662 /* Load the initial translation unit -- we do this without honoring remapped
1663 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001664 Err = clang_parseTranslationUnit2(Idx, 0,
1665 argv + compiler_arg_idx,
1666 argc - compiler_arg_idx,
1667 0, 0, getDefaultParsingOptions(), &TU);
1668 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001669 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001670 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001671 free_remapped_files(unsaved_files, num_unsaved_files);
1672 clang_disposeIndex(Idx);
1673 return 1;
1674 }
1675
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001676 if (checkForErrors(TU) != 0)
1677 return -1;
1678
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001679 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1680 remap_after_trial =
1681 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1682 }
1683
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001684 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001685 free_remapped_files(unsaved_files, num_unsaved_files);
1686 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1687 &unsaved_files, &num_unsaved_files)) {
1688 clang_disposeTranslationUnit(TU);
1689 clang_disposeIndex(Idx);
1690 return -1;
1691 }
1692
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001693 Err = clang_reparseTranslationUnit(
1694 TU,
1695 trial >= remap_after_trial ? num_unsaved_files : 0,
1696 trial >= remap_after_trial ? unsaved_files : 0,
1697 clang_defaultReparseOptions(TU));
1698 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001699 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001700 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001701 clang_disposeTranslationUnit(TU);
1702 free_remapped_files(unsaved_files, num_unsaved_files);
1703 clang_disposeIndex(Idx);
1704 return -1;
1705 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001706
1707 if (checkForErrors(TU) != 0)
1708 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001709 }
1710
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001711 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001712
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001713 free_remapped_files(unsaved_files, num_unsaved_files);
1714 clang_disposeIndex(Idx);
1715 return result;
1716}
1717
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001718/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001719/* Logic for testing clang_getCursor(). */
1720/******************************************************************************/
1721
Douglas Gregor37aa4932011-05-04 00:14:37 +00001722static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001723 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001724 unsigned end_line, unsigned end_col,
1725 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001726 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001727 if (prefix)
1728 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001729 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1730 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001731 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001732 printf("\n");
1733}
1734
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001735static int perform_file_scan(const char *ast_file, const char *source_file,
1736 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001737 CXIndex Idx;
1738 CXTranslationUnit TU;
1739 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001740 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001741 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001742 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001743 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001744
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001745 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001746 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001747 fprintf(stderr, "Could not create Index\n");
1748 return 1;
1749 }
Ted Kremenek29004672010-02-17 00:41:32 +00001750
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001751 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1752 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001753
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001754 if ((fp = fopen(source_file, "r")) == NULL) {
1755 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001756 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001757 return 1;
1758 }
Ted Kremenek29004672010-02-17 00:41:32 +00001759
Douglas Gregor816fd362010-01-22 21:44:22 +00001760 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001761 for (;;) {
1762 CXCursor cursor;
1763 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001764
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001765 if (c == '\n') {
1766 ++line;
1767 col = 1;
1768 } else
1769 ++col;
1770
1771 /* Check the cursor at this position, and dump the previous one if we have
1772 * found something new.
1773 */
1774 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1775 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1776 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001777 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001778 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001779 start_line = line;
1780 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001781 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001782 if (c == EOF)
1783 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001784
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001785 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001786 }
Ted Kremenek29004672010-02-17 00:41:32 +00001787
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001788 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001789 clang_disposeTranslationUnit(TU);
1790 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001791 return 0;
1792}
1793
1794/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001795/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001796/******************************************************************************/
1797
Douglas Gregor9eb77012009-11-07 00:00:49 +00001798/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1799 on failure. If successful, the pointer *filename will contain newly-allocated
1800 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001801int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001802 unsigned *column, unsigned *second_line,
1803 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001804 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001805 const char *last_colon = strrchr(input, ':');
1806 unsigned values[4], i;
1807 unsigned num_values = (second_line && second_column)? 4 : 2;
1808
Douglas Gregor9eb77012009-11-07 00:00:49 +00001809 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001810 if (!last_colon || last_colon == input) {
1811 if (num_values == 4)
1812 fprintf(stderr, "could not parse filename:line:column:line:column in "
1813 "'%s'\n", input);
1814 else
1815 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001816 return 1;
1817 }
1818
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001819 for (i = 0; i != num_values; ++i) {
1820 const char *prev_colon;
1821
1822 /* Parse the next line or column. */
1823 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1824 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001825 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001826 (i % 2 ? "column" : "line"), input);
1827 return 1;
1828 }
Ted Kremenek29004672010-02-17 00:41:32 +00001829
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001830 if (i + 1 == num_values)
1831 break;
1832
1833 /* Find the previous colon. */
1834 prev_colon = last_colon - 1;
1835 while (prev_colon != input && *prev_colon != ':')
1836 --prev_colon;
1837 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001838 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001839 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001840 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001841 }
1842
1843 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001844 }
1845
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001846 *line = values[0];
1847 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001848
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001849 if (second_line && second_column) {
1850 *second_line = values[2];
1851 *second_column = values[3];
1852 }
1853
Douglas Gregorf96ea292009-11-09 18:19:57 +00001854 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001855 *filename = (char*)malloc(last_colon - input + 1);
1856 memcpy(*filename, input, last_colon - input);
1857 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001858 return 0;
1859}
1860
1861const char *
1862clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1863 switch (Kind) {
1864 case CXCompletionChunk_Optional: return "Optional";
1865 case CXCompletionChunk_TypedText: return "TypedText";
1866 case CXCompletionChunk_Text: return "Text";
1867 case CXCompletionChunk_Placeholder: return "Placeholder";
1868 case CXCompletionChunk_Informative: return "Informative";
1869 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1870 case CXCompletionChunk_LeftParen: return "LeftParen";
1871 case CXCompletionChunk_RightParen: return "RightParen";
1872 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1873 case CXCompletionChunk_RightBracket: return "RightBracket";
1874 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1875 case CXCompletionChunk_RightBrace: return "RightBrace";
1876 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1877 case CXCompletionChunk_RightAngle: return "RightAngle";
1878 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001879 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001880 case CXCompletionChunk_Colon: return "Colon";
1881 case CXCompletionChunk_SemiColon: return "SemiColon";
1882 case CXCompletionChunk_Equal: return "Equal";
1883 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1884 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001885 }
Ted Kremenek29004672010-02-17 00:41:32 +00001886
Douglas Gregor9eb77012009-11-07 00:00:49 +00001887 return "Unknown";
1888}
1889
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001890static int checkForErrors(CXTranslationUnit TU) {
1891 unsigned Num, i;
1892 CXDiagnostic Diag;
1893 CXString DiagStr;
1894
1895 if (!getenv("CINDEXTEST_FAILONERROR"))
1896 return 0;
1897
1898 Num = clang_getNumDiagnostics(TU);
1899 for (i = 0; i != Num; ++i) {
1900 Diag = clang_getDiagnostic(TU, i);
1901 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1902 DiagStr = clang_formatDiagnostic(Diag,
1903 clang_defaultDiagnosticDisplayOptions());
1904 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1905 clang_disposeString(DiagStr);
1906 clang_disposeDiagnostic(Diag);
1907 return -1;
1908 }
1909 clang_disposeDiagnostic(Diag);
1910 }
1911
1912 return 0;
1913}
1914
Nico Weber8d19dff2014-05-07 21:05:22 +00001915static void print_completion_string(CXCompletionString completion_string,
1916 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001917 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001918
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001919 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001920 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001921 CXString text;
1922 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001923 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001924 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001925
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001926 if (Kind == CXCompletionChunk_Optional) {
1927 fprintf(file, "{Optional ");
1928 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001929 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001930 file);
1931 fprintf(file, "}");
1932 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001933 }
1934
1935 if (Kind == CXCompletionChunk_VerticalSpace) {
1936 fprintf(file, "{VerticalSpace }");
1937 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001938 }
Ted Kremenek29004672010-02-17 00:41:32 +00001939
Douglas Gregorf81f5282009-11-09 17:05:28 +00001940 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001941 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001942 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001943 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001944 cstr ? cstr : "");
1945 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001946 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001947
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001948}
1949
Nico Weber8d19dff2014-05-07 21:05:22 +00001950static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001951 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001952 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001953 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001954 enum CXCursorKind ParentKind;
1955 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001956 CXString BriefComment;
1957 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001958
Ted Kremenek29004672010-02-17 00:41:32 +00001959 fprintf(file, "%s:", clang_getCString(ks));
1960 clang_disposeString(ks);
1961
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001962 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001963 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001964 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001965 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1966 case CXAvailability_Available:
1967 break;
1968
1969 case CXAvailability_Deprecated:
1970 fprintf(file, " (deprecated)");
1971 break;
1972
1973 case CXAvailability_NotAvailable:
1974 fprintf(file, " (unavailable)");
1975 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001976
1977 case CXAvailability_NotAccessible:
1978 fprintf(file, " (inaccessible)");
1979 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00001980 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001981
1982 annotationCount = clang_getCompletionNumAnnotations(
1983 completion_result->CompletionString);
1984 if (annotationCount) {
1985 unsigned i;
1986 fprintf(file, " (");
1987 for (i = 0; i < annotationCount; ++i) {
1988 if (i != 0)
1989 fprintf(file, ", ");
1990 fprintf(file, "\"%s\"",
1991 clang_getCString(clang_getCompletionAnnotation(
1992 completion_result->CompletionString, i)));
1993 }
1994 fprintf(file, ")");
1995 }
1996
Douglas Gregor78254c82012-03-27 23:34:16 +00001997 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1998 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1999 &ParentKind);
2000 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002001 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002002 fprintf(file, " (parent: %s '%s')",
2003 clang_getCString(KindSpelling),
2004 clang_getCString(ParentName));
2005 clang_disposeString(KindSpelling);
2006 }
2007 clang_disposeString(ParentName);
2008 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002009
2010 BriefComment = clang_getCompletionBriefComment(
2011 completion_result->CompletionString);
2012 BriefCommentCString = clang_getCString(BriefComment);
2013 if (BriefCommentCString && *BriefCommentCString != '\0') {
2014 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2015 }
2016 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002017
Douglas Gregorf757a122010-08-23 23:00:57 +00002018 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002019}
2020
Douglas Gregor21325842011-07-07 16:03:39 +00002021void print_completion_contexts(unsigned long long contexts, FILE *file) {
2022 fprintf(file, "Completion contexts:\n");
2023 if (contexts == CXCompletionContext_Unknown) {
2024 fprintf(file, "Unknown\n");
2025 }
2026 if (contexts & CXCompletionContext_AnyType) {
2027 fprintf(file, "Any type\n");
2028 }
2029 if (contexts & CXCompletionContext_AnyValue) {
2030 fprintf(file, "Any value\n");
2031 }
2032 if (contexts & CXCompletionContext_ObjCObjectValue) {
2033 fprintf(file, "Objective-C object value\n");
2034 }
2035 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2036 fprintf(file, "Objective-C selector value\n");
2037 }
2038 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2039 fprintf(file, "C++ class type value\n");
2040 }
2041 if (contexts & CXCompletionContext_DotMemberAccess) {
2042 fprintf(file, "Dot member access\n");
2043 }
2044 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2045 fprintf(file, "Arrow member access\n");
2046 }
2047 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2048 fprintf(file, "Objective-C property access\n");
2049 }
2050 if (contexts & CXCompletionContext_EnumTag) {
2051 fprintf(file, "Enum tag\n");
2052 }
2053 if (contexts & CXCompletionContext_UnionTag) {
2054 fprintf(file, "Union tag\n");
2055 }
2056 if (contexts & CXCompletionContext_StructTag) {
2057 fprintf(file, "Struct tag\n");
2058 }
2059 if (contexts & CXCompletionContext_ClassTag) {
2060 fprintf(file, "Class name\n");
2061 }
2062 if (contexts & CXCompletionContext_Namespace) {
2063 fprintf(file, "Namespace or namespace alias\n");
2064 }
2065 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2066 fprintf(file, "Nested name specifier\n");
2067 }
2068 if (contexts & CXCompletionContext_ObjCInterface) {
2069 fprintf(file, "Objective-C interface\n");
2070 }
2071 if (contexts & CXCompletionContext_ObjCProtocol) {
2072 fprintf(file, "Objective-C protocol\n");
2073 }
2074 if (contexts & CXCompletionContext_ObjCCategory) {
2075 fprintf(file, "Objective-C category\n");
2076 }
2077 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2078 fprintf(file, "Objective-C instance method\n");
2079 }
2080 if (contexts & CXCompletionContext_ObjCClassMessage) {
2081 fprintf(file, "Objective-C class method\n");
2082 }
2083 if (contexts & CXCompletionContext_ObjCSelectorName) {
2084 fprintf(file, "Objective-C selector name\n");
2085 }
2086 if (contexts & CXCompletionContext_MacroName) {
2087 fprintf(file, "Macro name\n");
2088 }
2089 if (contexts & CXCompletionContext_NaturalLanguage) {
2090 fprintf(file, "Natural language\n");
2091 }
2092}
2093
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002094int my_stricmp(const char *s1, const char *s2) {
2095 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00002096 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002097 if (c1 < c2)
2098 return -1;
2099 else if (c1 > c2)
2100 return 1;
2101
2102 ++s1;
2103 ++s2;
2104 }
2105
2106 if (*s1)
2107 return 1;
2108 else if (*s2)
2109 return -1;
2110 return 0;
2111}
2112
Douglas Gregor47815d52010-07-12 18:38:41 +00002113int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002114 const char *input = argv[1];
2115 char *filename = 0;
2116 unsigned line;
2117 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002118 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002119 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002120 struct CXUnsavedFile *unsaved_files = 0;
2121 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002122 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002123 enum CXErrorCode Err;
2124 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002125 unsigned I, Repeats = 1;
2126 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2127
2128 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2129 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002130 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2131 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002132
Douglas Gregor47815d52010-07-12 18:38:41 +00002133 if (timing_only)
2134 input += strlen("-code-completion-timing=");
2135 else
2136 input += strlen("-code-completion-at=");
2137
Ted Kremenek29004672010-02-17 00:41:32 +00002138 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002139 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002140 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002141
Douglas Gregor9485bf92009-12-02 09:21:34 +00002142 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2143 return -1;
2144
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002145 CIdx = clang_createIndex(0, 0);
2146
2147 if (getenv("CINDEXTEST_EDITING"))
2148 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002149
2150 Err = clang_parseTranslationUnit2(CIdx, 0,
2151 argv + num_unsaved_files + 2,
2152 argc - num_unsaved_files - 2,
2153 0, 0, getDefaultParsingOptions(), &TU);
2154 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002155 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002156 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002157 return 1;
2158 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002159
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002160 Err = clang_reparseTranslationUnit(TU, 0, 0,
2161 clang_defaultReparseOptions(TU));
2162
2163 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002164 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002165 describeLibclangFailure(Err);
2166 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002167 return 1;
2168 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002169
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002170 for (I = 0; I != Repeats; ++I) {
2171 results = clang_codeCompleteAt(TU, filename, line, column,
2172 unsaved_files, num_unsaved_files,
2173 completionOptions);
2174 if (!results) {
2175 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002176 return 1;
2177 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002178 if (I != Repeats-1)
2179 clang_disposeCodeCompleteResults(results);
2180 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002181
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002182 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002183 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002184 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002185 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002186 CXString objCSelector;
2187 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002188 if (!timing_only) {
2189 /* Sort the code-completion results based on the typed text. */
2190 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2191
Douglas Gregor47815d52010-07-12 18:38:41 +00002192 for (i = 0; i != n; ++i)
2193 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002194 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002195 n = clang_codeCompleteGetNumDiagnostics(results);
2196 for (i = 0; i != n; ++i) {
2197 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2198 PrintDiagnostic(diag);
2199 clang_disposeDiagnostic(diag);
2200 }
Douglas Gregor21325842011-07-07 16:03:39 +00002201
2202 contexts = clang_codeCompleteGetContexts(results);
2203 print_completion_contexts(contexts, stdout);
2204
Douglas Gregorea777402011-07-26 15:24:30 +00002205 containerKind = clang_codeCompleteGetContainerKind(results,
2206 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002207
2208 if (containerKind != CXCursor_InvalidCode) {
2209 /* We have found a container */
2210 CXString containerUSR, containerKindSpelling;
2211 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2212 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2213 clang_disposeString(containerKindSpelling);
2214
2215 if (containerIsIncomplete) {
2216 printf("Container is incomplete\n");
2217 }
2218 else {
2219 printf("Container is complete\n");
2220 }
2221
2222 containerUSR = clang_codeCompleteGetContainerUSR(results);
2223 printf("Container USR: %s\n", clang_getCString(containerUSR));
2224 clang_disposeString(containerUSR);
2225 }
2226
Douglas Gregorea777402011-07-26 15:24:30 +00002227 objCSelector = clang_codeCompleteGetObjCSelector(results);
2228 selectorString = clang_getCString(objCSelector);
2229 if (selectorString && strlen(selectorString) > 0) {
2230 printf("Objective-C selector: %s\n", selectorString);
2231 }
2232 clang_disposeString(objCSelector);
2233
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002234 clang_disposeCodeCompleteResults(results);
2235 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002236 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002237 clang_disposeIndex(CIdx);
2238 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002239
Douglas Gregor9485bf92009-12-02 09:21:34 +00002240 free_remapped_files(unsaved_files, num_unsaved_files);
2241
Ted Kremenekef3339b2009-11-17 18:09:14 +00002242 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002243}
2244
Douglas Gregor082c3e62010-01-15 19:40:17 +00002245typedef struct {
2246 char *filename;
2247 unsigned line;
2248 unsigned column;
2249} CursorSourceLocation;
2250
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002251static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002252 CXIndex CIdx;
2253 int errorCode;
2254 struct CXUnsavedFile *unsaved_files = 0;
2255 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002256 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002257 CXTranslationUnit TU;
2258 CXCursor Cursor;
2259 CursorSourceLocation *Locations = 0;
2260 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002261 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002262 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002263
Ted Kremenek29004672010-02-17 00:41:32 +00002264 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002265 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2266 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002267
Douglas Gregor082c3e62010-01-15 19:40:17 +00002268 /* Parse the locations. */
2269 assert(NumLocations > 0 && "Unable to count locations?");
2270 Locations = (CursorSourceLocation *)malloc(
2271 NumLocations * sizeof(CursorSourceLocation));
2272 for (Loc = 0; Loc < NumLocations; ++Loc) {
2273 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002274 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2275 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002276 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002277 return errorCode;
2278 }
Ted Kremenek29004672010-02-17 00:41:32 +00002279
2280 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002281 &num_unsaved_files))
2282 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002283
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002284 if (getenv("CINDEXTEST_EDITING"))
2285 Repeats = 5;
2286
2287 /* Parse the translation unit. When we're testing clang_getCursor() after
2288 reparsing, don't remap unsaved files until the second parse. */
2289 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002290 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2291 argv + num_unsaved_files + 1 + NumLocations,
2292 argc - num_unsaved_files - 2 - NumLocations,
2293 unsaved_files,
2294 Repeats > 1? 0 : num_unsaved_files,
2295 getDefaultParsingOptions(), &TU);
2296 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002297 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002298 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002299 return -1;
2300 }
Ted Kremenek29004672010-02-17 00:41:32 +00002301
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002302 if (checkForErrors(TU) != 0)
2303 return -1;
2304
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002305 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002306 if (Repeats > 1) {
2307 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2308 clang_defaultReparseOptions(TU));
2309 if (Err != CXError_Success) {
2310 describeLibclangFailure(Err);
2311 clang_disposeTranslationUnit(TU);
2312 return 1;
2313 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002314 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002315
2316 if (checkForErrors(TU) != 0)
2317 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002318
2319 for (Loc = 0; Loc < NumLocations; ++Loc) {
2320 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2321 if (!file)
2322 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002323
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002324 Cursor = clang_getCursor(TU,
2325 clang_getLocation(TU, file, Locations[Loc].line,
2326 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002327
2328 if (checkForErrors(TU) != 0)
2329 return -1;
2330
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002331 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002332 CXCompletionString completionString = clang_getCursorCompletionString(
2333 Cursor);
2334 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002335 CXString Spelling;
2336 const char *cspell;
2337 unsigned line, column;
2338 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2339 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002340 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002341 PrintCursorExtent(Cursor);
2342 Spelling = clang_getCursorSpelling(Cursor);
2343 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002344 if (cspell && strlen(cspell) != 0) {
2345 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002346 printf(" Spelling=%s (", cspell);
2347 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002348 CXSourceRange range =
2349 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002350 if (clang_Range_isNull(range))
2351 break;
2352 PrintRange(range, 0);
2353 }
2354 printf(")");
2355 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002356 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002357 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
Nico Weber8d19dff2014-05-07 21:05:22 +00002358 printf(" Selector index=%d",
2359 clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002360 if (clang_Cursor_isDynamicCall(Cursor))
2361 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002362 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002363 CXType T = clang_Cursor_getReceiverType(Cursor);
2364 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002365 printf(" Receiver-type=%s", clang_getCString(S));
2366 clang_disposeString(S);
2367 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002368
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002369 {
2370 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002371 CXFile astFile;
2372 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002373 unsigned i, numHeaders;
2374 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002375 astFile = clang_Module_getASTFile(mod);
2376 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002377 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002378 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002379 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002380 clang_getCString(name), clang_getCString(astFilename),
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002381 clang_Module_isSystem(mod), numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002382 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002383 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002384 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002385 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2386 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002387 printf("\n%s", clang_getCString(filename));
2388 clang_disposeString(filename);
2389 }
2390 }
2391 }
2392
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002393 if (completionString != NULL) {
2394 printf("\nCompletion string: ");
2395 print_completion_string(completionString, stdout);
2396 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002397 printf("\n");
2398 free(Locations[Loc].filename);
2399 }
2400 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002401 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002402
Douglas Gregor33cdd812010-02-18 18:08:43 +00002403 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002404 clang_disposeTranslationUnit(TU);
2405 clang_disposeIndex(CIdx);
2406 free(Locations);
2407 free_remapped_files(unsaved_files, num_unsaved_files);
2408 return 0;
2409}
2410
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002411static enum CXVisitorResult findFileRefsVisit(void *context,
2412 CXCursor cursor, CXSourceRange range) {
2413 if (clang_Range_isNull(range))
2414 return CXVisit_Continue;
2415
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002416 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002417 PrintRange(range, "");
2418 printf("\n");
2419 return CXVisit_Continue;
2420}
2421
2422static int find_file_refs_at(int argc, const char **argv) {
2423 CXIndex CIdx;
2424 int errorCode;
2425 struct CXUnsavedFile *unsaved_files = 0;
2426 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002427 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002428 CXTranslationUnit TU;
2429 CXCursor Cursor;
2430 CursorSourceLocation *Locations = 0;
2431 unsigned NumLocations = 0, Loc;
2432 unsigned Repeats = 1;
2433 unsigned I;
2434
2435 /* Count the number of locations. */
2436 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2437 ++NumLocations;
2438
2439 /* Parse the locations. */
2440 assert(NumLocations > 0 && "Unable to count locations?");
2441 Locations = (CursorSourceLocation *)malloc(
2442 NumLocations * sizeof(CursorSourceLocation));
2443 for (Loc = 0; Loc < NumLocations; ++Loc) {
2444 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2445 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2446 &Locations[Loc].line,
2447 &Locations[Loc].column, 0, 0)))
2448 return errorCode;
2449 }
2450
2451 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2452 &num_unsaved_files))
2453 return -1;
2454
2455 if (getenv("CINDEXTEST_EDITING"))
2456 Repeats = 5;
2457
2458 /* Parse the translation unit. When we're testing clang_getCursor() after
2459 reparsing, don't remap unsaved files until the second parse. */
2460 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002461 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2462 argv + num_unsaved_files + 1 + NumLocations,
2463 argc - num_unsaved_files - 2 - NumLocations,
2464 unsaved_files,
2465 Repeats > 1? 0 : num_unsaved_files,
2466 getDefaultParsingOptions(), &TU);
2467 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002468 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002469 describeLibclangFailure(Err);
2470 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002471 return -1;
2472 }
2473
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002474 if (checkForErrors(TU) != 0)
2475 return -1;
2476
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002477 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002478 if (Repeats > 1) {
2479 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2480 clang_defaultReparseOptions(TU));
2481 if (Err != CXError_Success) {
2482 describeLibclangFailure(Err);
2483 clang_disposeTranslationUnit(TU);
2484 return 1;
2485 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002486 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002487
2488 if (checkForErrors(TU) != 0)
2489 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002490
2491 for (Loc = 0; Loc < NumLocations; ++Loc) {
2492 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2493 if (!file)
2494 continue;
2495
2496 Cursor = clang_getCursor(TU,
2497 clang_getLocation(TU, file, Locations[Loc].line,
2498 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002499
2500 if (checkForErrors(TU) != 0)
2501 return -1;
2502
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002503 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002504 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002505 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002506 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002507 clang_findReferencesInFile(Cursor, file, visitor);
2508 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002509
2510 if (checkForErrors(TU) != 0)
2511 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002512 }
2513 }
2514 }
2515
2516 PrintDiagnostics(TU);
2517 clang_disposeTranslationUnit(TU);
2518 clang_disposeIndex(CIdx);
2519 free(Locations);
2520 free_remapped_files(unsaved_files, num_unsaved_files);
2521 return 0;
2522}
2523
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002524static enum CXVisitorResult findFileIncludesVisit(void *context,
2525 CXCursor cursor, CXSourceRange range) {
2526 PrintCursor(cursor, NULL);
2527 PrintRange(range, "");
2528 printf("\n");
2529 return CXVisit_Continue;
2530}
2531
2532static int find_file_includes_in(int argc, const char **argv) {
2533 CXIndex CIdx;
2534 struct CXUnsavedFile *unsaved_files = 0;
2535 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002536 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002537 CXTranslationUnit TU;
2538 const char **Filenames = 0;
2539 unsigned NumFilenames = 0;
2540 unsigned Repeats = 1;
2541 unsigned I, FI;
2542
2543 /* Count the number of locations. */
2544 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2545 ++NumFilenames;
2546
2547 /* Parse the locations. */
2548 assert(NumFilenames > 0 && "Unable to count filenames?");
2549 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2550 for (I = 0; I < NumFilenames; ++I) {
2551 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2552 /* Copy the file name. */
2553 Filenames[I] = input;
2554 }
2555
2556 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2557 &num_unsaved_files))
2558 return -1;
2559
2560 if (getenv("CINDEXTEST_EDITING"))
2561 Repeats = 2;
2562
2563 /* Parse the translation unit. When we're testing clang_getCursor() after
2564 reparsing, don't remap unsaved files until the second parse. */
2565 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002566 Err = clang_parseTranslationUnit2(
2567 CIdx, argv[argc - 1],
2568 argv + num_unsaved_files + 1 + NumFilenames,
2569 argc - num_unsaved_files - 2 - NumFilenames,
2570 unsaved_files,
2571 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002572
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002573 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002574 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002575 describeLibclangFailure(Err);
2576 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002577 return -1;
2578 }
2579
2580 if (checkForErrors(TU) != 0)
2581 return -1;
2582
2583 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002584 if (Repeats > 1) {
2585 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2586 clang_defaultReparseOptions(TU));
2587 if (Err != CXError_Success) {
2588 describeLibclangFailure(Err);
2589 clang_disposeTranslationUnit(TU);
2590 return 1;
2591 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002592 }
2593
2594 if (checkForErrors(TU) != 0)
2595 return -1;
2596
2597 for (FI = 0; FI < NumFilenames; ++FI) {
2598 CXFile file = clang_getFile(TU, Filenames[FI]);
2599 if (!file)
2600 continue;
2601
2602 if (checkForErrors(TU) != 0)
2603 return -1;
2604
2605 if (I + 1 == Repeats) {
2606 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2607 clang_findIncludesInFile(TU, file, visitor);
2608
2609 if (checkForErrors(TU) != 0)
2610 return -1;
2611 }
2612 }
2613 }
2614
2615 PrintDiagnostics(TU);
2616 clang_disposeTranslationUnit(TU);
2617 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002618 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002619 free_remapped_files(unsaved_files, num_unsaved_files);
2620 return 0;
2621}
2622
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002623#define MAX_IMPORTED_ASTFILES 200
2624
2625typedef struct {
2626 char **filenames;
2627 unsigned num_files;
2628} ImportedASTFilesData;
2629
2630static ImportedASTFilesData *importedASTs_create() {
2631 ImportedASTFilesData *p;
2632 p = malloc(sizeof(ImportedASTFilesData));
2633 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2634 p->num_files = 0;
2635 return p;
2636}
2637
2638static void importedASTs_dispose(ImportedASTFilesData *p) {
2639 unsigned i;
2640 if (!p)
2641 return;
2642
2643 for (i = 0; i < p->num_files; ++i)
2644 free(p->filenames[i]);
2645 free(p->filenames);
2646 free(p);
2647}
2648
2649static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2650 unsigned i;
2651 assert(p && file);
2652 for (i = 0; i < p->num_files; ++i)
2653 if (strcmp(file, p->filenames[i]) == 0)
2654 return;
2655 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2656 p->filenames[p->num_files++] = strdup(file);
2657}
2658
Nico Weberdf686022014-05-07 21:09:42 +00002659typedef struct IndexDataStringList_ {
2660 struct IndexDataStringList_ *next;
2661 char data[1]; /* Dynamically sized. */
2662} IndexDataStringList;
2663
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002664typedef struct {
2665 const char *check_prefix;
2666 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002667 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002668 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002669 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002670 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002671 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002672 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002673} IndexData;
2674
Nico Weberdf686022014-05-07 21:09:42 +00002675static void free_client_data(IndexData *index_data) {
2676 IndexDataStringList *node = index_data->strings;
2677 while (node) {
2678 IndexDataStringList *next = node->next;
2679 free(node);
2680 node = next;
2681 }
2682 index_data->strings = NULL;
2683}
2684
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002685static void printCheck(IndexData *data) {
2686 if (data->check_prefix) {
2687 if (data->first_check_printed) {
2688 printf("// %s-NEXT: ", data->check_prefix);
2689 } else {
2690 printf("// %s : ", data->check_prefix);
2691 data->first_check_printed = 1;
2692 }
2693 }
2694}
2695
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002696static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002697 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002698 printf("%s", clang_getCString(filename));
2699 clang_disposeString(filename);
2700}
2701
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002702static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2703 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002704 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002705 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002706 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002707 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002708 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002709
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002710 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002711 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2712 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002713 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002714 return;
2715 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002716 if (!file) {
2717 printf("<no idxfile>");
2718 return;
2719 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002720 filename = clang_getFileName((CXFile)file);
2721 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002722 if (strcmp(cname, index_data->main_filename) == 0)
2723 isMainFile = 1;
2724 else
2725 isMainFile = 0;
2726 clang_disposeString(filename);
2727
2728 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002729 printCXIndexFile(file);
2730 printf(":");
2731 }
2732 printf("%d:%d", line, column);
2733}
2734
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002735static unsigned digitCount(unsigned val) {
2736 unsigned c = 1;
2737 while (1) {
2738 if (val < 10)
2739 return c;
2740 ++c;
2741 val /= 10;
2742 }
2743}
2744
Nico Weberdf686022014-05-07 21:09:42 +00002745static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2746 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002747 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002748 IndexData *index_data;
2749 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002750 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002751 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002752 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002753 unsigned line, column;
2754
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002755 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002756 if (!name)
2757 name = "<anon-tag>";
2758
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002759 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002760
2761 node =
2762 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2763 digitCount(line) + digitCount(column) + 2);
2764 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002765 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002766
2767 /* Remember string so it can be freed later. */
2768 index_data = (IndexData *)client_data;
2769 node->next = index_data->strings;
2770 index_data->strings = node;
2771
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002772 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002773}
2774
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002775static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2776 CXIdxClientContainer container;
2777 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002778 if (!container)
2779 printf("[<<NULL>>]");
2780 else
2781 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002782}
2783
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002784static const char *getEntityKindString(CXIdxEntityKind kind) {
2785 switch (kind) {
2786 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2787 case CXIdxEntity_Typedef: return "typedef";
2788 case CXIdxEntity_Function: return "function";
2789 case CXIdxEntity_Variable: return "variable";
2790 case CXIdxEntity_Field: return "field";
2791 case CXIdxEntity_EnumConstant: return "enumerator";
2792 case CXIdxEntity_ObjCClass: return "objc-class";
2793 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2794 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002795 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2796 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002797 case CXIdxEntity_ObjCProperty: return "objc-property";
2798 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2799 case CXIdxEntity_Enum: return "enum";
2800 case CXIdxEntity_Struct: return "struct";
2801 case CXIdxEntity_Union: return "union";
2802 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002803 case CXIdxEntity_CXXNamespace: return "namespace";
2804 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2805 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2806 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2807 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2808 case CXIdxEntity_CXXConstructor: return "constructor";
2809 case CXIdxEntity_CXXDestructor: return "destructor";
2810 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2811 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002812 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002813 }
2814 assert(0 && "Garbage entity kind");
2815 return 0;
2816}
2817
2818static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2819 switch (kind) {
2820 case CXIdxEntity_NonTemplate: return "";
2821 case CXIdxEntity_Template: return "-template";
2822 case CXIdxEntity_TemplatePartialSpecialization:
2823 return "-template-partial-spec";
2824 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002825 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002826 assert(0 && "Garbage entity kind");
2827 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002828}
2829
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002830static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2831 switch (kind) {
2832 case CXIdxEntityLang_None: return "<none>";
2833 case CXIdxEntityLang_C: return "C";
2834 case CXIdxEntityLang_ObjC: return "ObjC";
2835 case CXIdxEntityLang_CXX: return "C++";
2836 }
2837 assert(0 && "Garbage language kind");
2838 return 0;
2839}
2840
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002841static void printEntityInfo(const char *cb,
2842 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002843 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002844 const char *name;
2845 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002846 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002847 index_data = (IndexData *)client_data;
2848 printCheck(index_data);
2849
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002850 if (!info) {
2851 printf("%s: <<NULL>>", cb);
2852 return;
2853 }
2854
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002855 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002856 if (!name)
2857 name = "<anon-tag>";
2858
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002859 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2860 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002861 printf(" | name: %s", name);
2862 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002863 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002864
2865 for (i = 0; i != info->numAttributes; ++i) {
2866 const CXIdxAttrInfo *Attr = info->attributes[i];
2867 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002868 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002869 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002870}
2871
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002872static void printBaseClassInfo(CXClientData client_data,
2873 const CXIdxBaseClassInfo *info) {
2874 printEntityInfo(" <base>", client_data, info->base);
2875 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002876 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002877 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002878 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002879}
2880
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002881static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2882 CXClientData client_data) {
2883 unsigned i;
2884 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2885 printEntityInfo(" <protocol>", client_data,
2886 ProtoInfo->protocols[i]->protocol);
2887 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002888 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002889 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002890 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002891 printf("\n");
2892 }
2893}
2894
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002895static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002896 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002897 CXString str;
2898 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002899 unsigned numDiags, i;
2900 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002901 IndexData *index_data;
2902 index_data = (IndexData *)client_data;
2903 printCheck(index_data);
2904
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002905 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2906 for (i = 0; i != numDiags; ++i) {
2907 diag = clang_getDiagnosticInSet(diagSet, i);
2908 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2909 cstr = clang_getCString(str);
2910 printf("[diagnostic]: %s\n", cstr);
2911 clang_disposeString(str);
2912
2913 if (getenv("CINDEXTEST_FAILONERROR") &&
2914 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2915 index_data->fail_for_error = 1;
2916 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002917 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002918}
2919
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002920static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2921 CXFile file, void *reserved) {
2922 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002923 CXString filename;
2924
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002925 index_data = (IndexData *)client_data;
2926 printCheck(index_data);
2927
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002928 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002929 index_data->main_filename = clang_getCString(filename);
2930 clang_disposeString(filename);
2931
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002932 printf("[enteredMainFile]: ");
2933 printCXIndexFile((CXIdxClientFile)file);
2934 printf("\n");
2935
2936 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002937}
2938
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002939static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002940 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002941 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002942 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002943 index_data = (IndexData *)client_data;
2944 printCheck(index_data);
2945
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002946 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002947 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002948 printf(" | name: \"%s\"", info->filename);
2949 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002950 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002951 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002952 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002953
2954 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
2955 if (Mod) {
2956 CXString str = clang_Module_getFullName(Mod);
2957 const char *cstr = clang_getCString(str);
2958 printf(" | module: %s", cstr);
2959 clang_disposeString(str);
2960 }
2961
2962 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002963
2964 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002965}
2966
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002967static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2968 const CXIdxImportedASTFileInfo *info) {
2969 IndexData *index_data;
2970 index_data = (IndexData *)client_data;
2971 printCheck(index_data);
2972
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002973 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002974 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002975 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2976 clang_disposeString(filename);
2977 }
2978
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002979 printf("[importedASTFile]: ");
2980 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002981 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002982 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002983 printf(" | loc: ");
2984 printCXIndexLoc(info->loc, client_data);
2985 printf(" | name: \"%s\"", clang_getCString(name));
2986 printf(" | isImplicit: %d\n", info->isImplicit);
2987 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002988 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00002989 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002990 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002991 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002992
2993 return (CXIdxClientFile)info->file;
2994}
2995
Nico Weber8d19dff2014-05-07 21:05:22 +00002996static CXIdxClientContainer
2997index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002998 IndexData *index_data;
2999 index_data = (IndexData *)client_data;
3000 printCheck(index_data);
3001
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003002 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003003 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003004}
3005
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003006static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003007 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003008 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003009 const CXIdxObjCCategoryDeclInfo *CatInfo;
3010 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003011 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003012 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003013 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003014 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003015 index_data = (IndexData *)client_data;
3016
3017 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3018 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003019 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003020 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003021 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003022 printf(" | semantic-container: ");
3023 printCXIndexContainer(info->semanticContainer);
3024 printf(" | lexical-container: ");
3025 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003026 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003027 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003028 if (info->flags & CXIdxDeclFlag_Skipped) {
3029 assert(!info->isContainer);
3030 printf(" | isContainer: skipped");
3031 } else {
3032 printf(" | isContainer: %d", info->isContainer);
3033 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003034 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003035
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003036 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003037 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003038 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003039 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003040 printf("\n");
3041 }
3042
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003043 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3044 const char *kindName = 0;
3045 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3046 switch (K) {
3047 case CXIdxObjCContainer_ForwardRef:
3048 kindName = "forward-ref"; break;
3049 case CXIdxObjCContainer_Interface:
3050 kindName = "interface"; break;
3051 case CXIdxObjCContainer_Implementation:
3052 kindName = "implementation"; break;
3053 }
3054 printCheck(index_data);
3055 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3056 }
3057
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003058 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003059 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3060 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003061 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003062 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003063 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003064 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003065 printf("\n");
3066 }
3067
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003068 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3069 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003070 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003071 printf("\n");
3072 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003073 }
3074
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003075 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3076 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003077 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003078
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003079 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3080 if (PropInfo->getter) {
3081 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3082 printf("\n");
3083 }
3084 if (PropInfo->setter) {
3085 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3086 printf("\n");
3087 }
3088 }
3089
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003090 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3091 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3092 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3093 printf("\n");
3094 }
3095 }
3096
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003097 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003098 clang_index_setClientContainer(
3099 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003100 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003101}
3102
3103static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003104 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003105 printEntityInfo("[indexEntityReference]", client_data,
3106 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003107 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003108 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003109 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003110 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003111 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003112 printf(" | container: ");
3113 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003114 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003115 switch (info->kind) {
3116 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003117 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003118 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003119 printf("\n");
3120}
3121
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003122static int index_abortQuery(CXClientData client_data, void *reserved) {
3123 IndexData *index_data;
3124 index_data = (IndexData *)client_data;
3125 return index_data->abort;
3126}
3127
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003128static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003129 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003130 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003131 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003132 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003133 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003134 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003135 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003136 index_indexEntityReference
3137};
3138
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003139static unsigned getIndexOptions(void) {
3140 unsigned index_opts;
3141 index_opts = 0;
3142 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3143 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3144 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3145 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003146 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3147 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003148
3149 return index_opts;
3150}
3151
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003152static int index_compile_args(int num_args, const char **args,
3153 CXIndexAction idxAction,
3154 ImportedASTFilesData *importedASTs,
3155 const char *check_prefix) {
3156 IndexData index_data;
3157 unsigned index_opts;
3158 int result;
3159
3160 if (num_args == 0) {
3161 fprintf(stderr, "no compiler arguments\n");
3162 return -1;
3163 }
3164
3165 index_data.check_prefix = check_prefix;
3166 index_data.first_check_printed = 0;
3167 index_data.fail_for_error = 0;
3168 index_data.abort = 0;
3169 index_data.main_filename = "";
3170 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003171 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003172 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003173
3174 index_opts = getIndexOptions();
3175 result = clang_indexSourceFile(idxAction, &index_data,
3176 &IndexCB,sizeof(IndexCB), index_opts,
3177 0, args, num_args, 0, 0, 0,
3178 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003179 if (result != CXError_Success)
3180 describeLibclangFailure(result);
3181
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003182 if (index_data.fail_for_error)
3183 result = -1;
3184
Nico Weberdf686022014-05-07 21:09:42 +00003185 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003186 return result;
3187}
3188
3189static int index_ast_file(const char *ast_file,
3190 CXIndex Idx,
3191 CXIndexAction idxAction,
3192 ImportedASTFilesData *importedASTs,
3193 const char *check_prefix) {
3194 CXTranslationUnit TU;
3195 IndexData index_data;
3196 unsigned index_opts;
3197 int result;
3198
3199 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3200 return -1;
3201
3202 index_data.check_prefix = check_prefix;
3203 index_data.first_check_printed = 0;
3204 index_data.fail_for_error = 0;
3205 index_data.abort = 0;
3206 index_data.main_filename = "";
3207 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003208 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003209 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003210
3211 index_opts = getIndexOptions();
3212 result = clang_indexTranslationUnit(idxAction, &index_data,
3213 &IndexCB,sizeof(IndexCB),
3214 index_opts, TU);
3215 if (index_data.fail_for_error)
3216 result = -1;
3217
3218 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003219 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003220 return result;
3221}
3222
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003223static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003224 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003225 CXIndex Idx;
3226 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003227 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003228 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003229
3230 check_prefix = 0;
3231 if (argc > 0) {
3232 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3233 check_prefix = argv[0] + strlen("-check-prefix=");
3234 ++argv;
3235 --argc;
3236 }
3237 }
3238
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003239 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003240 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003241 fprintf(stderr, "Could not create Index\n");
3242 return 1;
3243 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003244 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003245 importedASTs = 0;
3246 if (full)
3247 importedASTs = importedASTs_create();
3248
3249 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3250 if (result != 0)
3251 goto finished;
3252
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003253 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003254 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003255 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3256 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3257 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003258 }
3259 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003260
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003261finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003262 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003263 clang_IndexAction_dispose(idxAction);
3264 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003265 return result;
3266}
3267
3268static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003269 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003270 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003271 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003272 int result;
3273
3274 check_prefix = 0;
3275 if (argc > 0) {
3276 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3277 check_prefix = argv[0] + strlen("-check-prefix=");
3278 ++argv;
3279 --argc;
3280 }
3281 }
3282
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003283 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003284 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003285 fprintf(stderr, "Could not create Index\n");
3286 return 1;
3287 }
3288 idxAction = clang_IndexAction_create(Idx);
3289
3290 result = index_ast_file(argv[0], Idx, idxAction,
3291 /*importedASTs=*/0, check_prefix);
3292
3293 clang_IndexAction_dispose(idxAction);
3294 clang_disposeIndex(Idx);
3295 return result;
3296}
3297
3298static int index_compile_db(int argc, const char **argv) {
3299 const char *check_prefix;
3300 CXIndex Idx;
3301 CXIndexAction idxAction;
3302 int errorCode = 0;
3303
3304 check_prefix = 0;
3305 if (argc > 0) {
3306 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3307 check_prefix = argv[0] + strlen("-check-prefix=");
3308 ++argv;
3309 --argc;
3310 }
3311 }
3312
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003313 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003314 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003315 return -1;
3316 }
3317
3318 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003319 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003320 fprintf(stderr, "Could not create Index\n");
3321 return 1;
3322 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003323 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003324
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003325 {
3326 const char *database = argv[0];
3327 CXCompilationDatabase db = 0;
3328 CXCompileCommands CCmds = 0;
3329 CXCompileCommand CCmd;
3330 CXCompilationDatabase_Error ec;
3331 CXString wd;
3332#define MAX_COMPILE_ARGS 512
3333 CXString cxargs[MAX_COMPILE_ARGS];
3334 const char *args[MAX_COMPILE_ARGS];
3335 char *tmp;
3336 unsigned len;
3337 char *buildDir;
3338 int i, a, numCmds, numArgs;
3339
3340 len = strlen(database);
3341 tmp = (char *) malloc(len+1);
3342 memcpy(tmp, database, len+1);
3343 buildDir = dirname(tmp);
3344
3345 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3346
3347 if (db) {
3348
3349 if (ec!=CXCompilationDatabase_NoError) {
3350 printf("unexpected error %d code while loading compilation database\n", ec);
3351 errorCode = -1;
3352 goto cdb_end;
3353 }
3354
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003355 if (chdir(buildDir) != 0) {
3356 printf("Could not chdir to %s\n", buildDir);
3357 errorCode = -1;
3358 goto cdb_end;
3359 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003360
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003361 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003362 if (!CCmds) {
3363 printf("compilation db is empty\n");
3364 errorCode = -1;
3365 goto cdb_end;
3366 }
3367
3368 numCmds = clang_CompileCommands_getSize(CCmds);
3369
3370 if (numCmds==0) {
3371 fprintf(stderr, "should not get an empty compileCommand set\n");
3372 errorCode = -1;
3373 goto cdb_end;
3374 }
3375
3376 for (i=0; i<numCmds && errorCode == 0; ++i) {
3377 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3378
3379 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003380 if (chdir(clang_getCString(wd)) != 0) {
3381 printf("Could not chdir to %s\n", clang_getCString(wd));
3382 errorCode = -1;
3383 goto cdb_end;
3384 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003385 clang_disposeString(wd);
3386
3387 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3388 if (numArgs > MAX_COMPILE_ARGS){
3389 fprintf(stderr, "got more compile arguments than maximum\n");
3390 errorCode = -1;
3391 goto cdb_end;
3392 }
3393 for (a=0; a<numArgs; ++a) {
3394 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3395 args[a] = clang_getCString(cxargs[a]);
3396 }
3397
3398 errorCode = index_compile_args(numArgs, args, idxAction,
3399 /*importedASTs=*/0, check_prefix);
3400
3401 for (a=0; a<numArgs; ++a)
3402 clang_disposeString(cxargs[a]);
3403 }
3404 } else {
3405 printf("database loading failed with error code %d.\n", ec);
3406 errorCode = -1;
3407 }
3408
3409 cdb_end:
3410 clang_CompileCommands_dispose(CCmds);
3411 clang_CompilationDatabase_dispose(db);
3412 free(tmp);
3413
3414 }
3415
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003416 clang_IndexAction_dispose(idxAction);
3417 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003418 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003419}
3420
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003421int perform_token_annotation(int argc, const char **argv) {
3422 const char *input = argv[1];
3423 char *filename = 0;
3424 unsigned line, second_line;
3425 unsigned column, second_column;
3426 CXIndex CIdx;
3427 CXTranslationUnit TU = 0;
3428 int errorCode;
3429 struct CXUnsavedFile *unsaved_files = 0;
3430 int num_unsaved_files = 0;
3431 CXToken *tokens;
3432 unsigned num_tokens;
3433 CXSourceRange range;
3434 CXSourceLocation startLoc, endLoc;
3435 CXFile file = 0;
3436 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003437 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003438 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003439 unsigned i;
3440
3441 input += strlen("-test-annotate-tokens=");
3442 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3443 &second_line, &second_column)))
3444 return errorCode;
3445
Richard Smith1ea42eb2012-07-05 08:20:49 +00003446 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3447 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003448 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003449 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003450
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003451 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003452 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3453 argv + num_unsaved_files + 2,
3454 argc - num_unsaved_files - 3,
3455 unsaved_files,
3456 num_unsaved_files,
3457 getDefaultParsingOptions(), &TU);
3458 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003459 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003460 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003461 clang_disposeIndex(CIdx);
3462 free(filename);
3463 free_remapped_files(unsaved_files, num_unsaved_files);
3464 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003465 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003466 errorCode = 0;
3467
Richard Smith1ea42eb2012-07-05 08:20:49 +00003468 if (checkForErrors(TU) != 0) {
3469 errorCode = -1;
3470 goto teardown;
3471 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003472
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003473 if (getenv("CINDEXTEST_EDITING")) {
3474 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003475 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3476 clang_defaultReparseOptions(TU));
3477 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003478 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003479 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003480 errorCode = -1;
3481 goto teardown;
3482 }
3483 }
3484 }
3485
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003486 if (checkForErrors(TU) != 0) {
3487 errorCode = -1;
3488 goto teardown;
3489 }
3490
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003491 file = clang_getFile(TU, filename);
3492 if (!file) {
3493 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3494 errorCode = -1;
3495 goto teardown;
3496 }
3497
3498 startLoc = clang_getLocation(TU, file, line, column);
3499 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003500 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003501 column);
3502 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003503 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003504 }
3505
3506 endLoc = clang_getLocation(TU, file, second_line, second_column);
3507 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003508 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003509 second_line, second_column);
3510 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003511 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003512 }
3513
3514 range = clang_getRange(startLoc, endLoc);
3515 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003516
3517 if (checkForErrors(TU) != 0) {
3518 errorCode = -1;
3519 goto teardown;
3520 }
3521
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003522 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3523 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003524
3525 if (checkForErrors(TU) != 0) {
3526 errorCode = -1;
3527 goto teardown;
3528 }
3529
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003530 skipped_ranges = clang_getSkippedRanges(TU, file);
3531 for (i = 0; i != skipped_ranges->count; ++i) {
3532 unsigned start_line, start_column, end_line, end_column;
3533 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3534 0, &start_line, &start_column, 0);
3535 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3536 0, &end_line, &end_column, 0);
3537 printf("Skipping: ");
3538 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3539 printf("\n");
3540 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003541 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003542
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003543 for (i = 0; i != num_tokens; ++i) {
3544 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003545 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3546 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003547 unsigned start_line, start_column, end_line, end_column;
3548
3549 switch (clang_getTokenKind(tokens[i])) {
3550 case CXToken_Punctuation: kind = "Punctuation"; break;
3551 case CXToken_Keyword: kind = "Keyword"; break;
3552 case CXToken_Identifier: kind = "Identifier"; break;
3553 case CXToken_Literal: kind = "Literal"; break;
3554 case CXToken_Comment: kind = "Comment"; break;
3555 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003556 clang_getSpellingLocation(clang_getRangeStart(extent),
3557 0, &start_line, &start_column, 0);
3558 clang_getSpellingLocation(clang_getRangeEnd(extent),
3559 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003560 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003561 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003562 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003563 if (!clang_isInvalid(cursors[i].kind)) {
3564 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003565 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003566 }
3567 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003568 }
3569 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003570 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003571
3572 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003573 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003574 clang_disposeTranslationUnit(TU);
3575 clang_disposeIndex(CIdx);
3576 free(filename);
3577 free_remapped_files(unsaved_files, num_unsaved_files);
3578 return errorCode;
3579}
3580
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003581static int
3582perform_test_compilation_db(const char *database, int argc, const char **argv) {
3583 CXCompilationDatabase db;
3584 CXCompileCommands CCmds;
3585 CXCompileCommand CCmd;
3586 CXCompilationDatabase_Error ec;
3587 CXString wd;
3588 CXString arg;
3589 int errorCode = 0;
3590 char *tmp;
3591 unsigned len;
3592 char *buildDir;
3593 int i, j, a, numCmds, numArgs;
3594
3595 len = strlen(database);
3596 tmp = (char *) malloc(len+1);
3597 memcpy(tmp, database, len+1);
3598 buildDir = dirname(tmp);
3599
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003600 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003601
3602 if (db) {
3603
3604 if (ec!=CXCompilationDatabase_NoError) {
3605 printf("unexpected error %d code while loading compilation database\n", ec);
3606 errorCode = -1;
3607 goto cdb_end;
3608 }
3609
3610 for (i=0; i<argc && errorCode==0; ) {
3611 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003612 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003613
3614 if (!CCmds) {
3615 printf("file %s not found in compilation db\n", argv[i+1]);
3616 errorCode = -1;
3617 break;
3618 }
3619
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003620 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003621
3622 if (numCmds==0) {
3623 fprintf(stderr, "should not get an empty compileCommand set for file"
3624 " '%s'\n", argv[i+1]);
3625 errorCode = -1;
3626 break;
3627 }
3628
3629 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003630 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003631
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003632 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003633 printf("workdir:'%s'", clang_getCString(wd));
3634 clang_disposeString(wd);
3635
3636 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003637 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003638 for (a=0; a<numArgs; ++a) {
3639 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003640 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003641 printf("%s", clang_getCString(arg));
3642 clang_disposeString(arg);
3643 }
3644 printf("'\n");
3645 }
3646
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003647 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003648
3649 i += 2;
3650 }
3651 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003652 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003653 } else {
3654 printf("database loading failed with error code %d.\n", ec);
3655 errorCode = -1;
3656 }
3657
3658cdb_end:
3659 free(tmp);
3660
3661 return errorCode;
3662}
3663
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003664/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003665/* USR printing. */
3666/******************************************************************************/
3667
3668static int insufficient_usr(const char *kind, const char *usage) {
3669 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3670 return 1;
3671}
3672
3673static unsigned isUSR(const char *s) {
3674 return s[0] == 'c' && s[1] == ':';
3675}
3676
3677static int not_usr(const char *s, const char *arg) {
3678 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3679 return 1;
3680}
3681
3682static void print_usr(CXString usr) {
3683 const char *s = clang_getCString(usr);
3684 printf("%s\n", s);
3685 clang_disposeString(usr);
3686}
3687
3688static void display_usrs() {
3689 fprintf(stderr, "-print-usrs options:\n"
3690 " ObjCCategory <class name> <category name>\n"
3691 " ObjCClass <class name>\n"
3692 " ObjCIvar <ivar name> <class USR>\n"
3693 " ObjCMethod <selector> [0=class method|1=instance method] "
3694 "<class USR>\n"
3695 " ObjCProperty <property name> <class USR>\n"
3696 " ObjCProtocol <protocol name>\n");
3697}
3698
3699int print_usrs(const char **I, const char **E) {
3700 while (I != E) {
3701 const char *kind = *I;
3702 unsigned len = strlen(kind);
3703 switch (len) {
3704 case 8:
3705 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3706 if (I + 2 >= E)
3707 return insufficient_usr(kind, "<ivar name> <class USR>");
3708 if (!isUSR(I[2]))
3709 return not_usr("<class USR>", I[2]);
3710 else {
3711 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003712 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003713 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003714 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3715 }
3716
3717 I += 3;
3718 continue;
3719 }
3720 break;
3721 case 9:
3722 if (memcmp(kind, "ObjCClass", 9) == 0) {
3723 if (I + 1 >= E)
3724 return insufficient_usr(kind, "<class name>");
3725 print_usr(clang_constructUSR_ObjCClass(I[1]));
3726 I += 2;
3727 continue;
3728 }
3729 break;
3730 case 10:
3731 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3732 if (I + 3 >= E)
3733 return insufficient_usr(kind, "<method selector> "
3734 "[0=class method|1=instance method] <class USR>");
3735 if (!isUSR(I[3]))
3736 return not_usr("<class USR>", I[3]);
3737 else {
3738 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003739 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003740 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003741 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3742 }
3743 I += 4;
3744 continue;
3745 }
3746 break;
3747 case 12:
3748 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3749 if (I + 2 >= E)
3750 return insufficient_usr(kind, "<class name> <category name>");
3751 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3752 I += 3;
3753 continue;
3754 }
3755 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3756 if (I + 1 >= E)
3757 return insufficient_usr(kind, "<protocol name>");
3758 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3759 I += 2;
3760 continue;
3761 }
3762 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3763 if (I + 2 >= E)
3764 return insufficient_usr(kind, "<property name> <class USR>");
3765 if (!isUSR(I[2]))
3766 return not_usr("<class USR>", I[2]);
3767 else {
3768 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003769 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003770 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003771 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3772 }
3773 I += 3;
3774 continue;
3775 }
3776 break;
3777 default:
3778 break;
3779 }
3780 break;
3781 }
3782
3783 if (I != E) {
3784 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3785 display_usrs();
3786 return 1;
3787 }
3788 return 0;
3789}
3790
3791int print_usrs_file(const char *file_name) {
3792 char line[2048];
3793 const char *args[128];
3794 unsigned numChars = 0;
3795
3796 FILE *fp = fopen(file_name, "r");
3797 if (!fp) {
3798 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3799 return 1;
3800 }
3801
3802 /* This code is not really all that safe, but it works fine for testing. */
3803 while (!feof(fp)) {
3804 char c = fgetc(fp);
3805 if (c == '\n') {
3806 unsigned i = 0;
3807 const char *s = 0;
3808
3809 if (numChars == 0)
3810 continue;
3811
3812 line[numChars] = '\0';
3813 numChars = 0;
3814
3815 if (line[0] == '/' && line[1] == '/')
3816 continue;
3817
3818 s = strtok(line, " ");
3819 while (s) {
3820 args[i] = s;
3821 ++i;
3822 s = strtok(0, " ");
3823 }
3824 if (print_usrs(&args[0], &args[i]))
3825 return 1;
3826 }
3827 else
3828 line[numChars++] = c;
3829 }
3830
3831 fclose(fp);
3832 return 0;
3833}
3834
3835/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003836/* Command line processing. */
3837/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003838int write_pch_file(const char *filename, int argc, const char *argv[]) {
3839 CXIndex Idx;
3840 CXTranslationUnit TU;
3841 struct CXUnsavedFile *unsaved_files = 0;
3842 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003843 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003844 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003845
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003846 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003847
3848 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3849 clang_disposeIndex(Idx);
3850 return -1;
3851 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003852
3853 Err = clang_parseTranslationUnit2(
3854 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3855 unsaved_files, num_unsaved_files,
3856 CXTranslationUnit_Incomplete |
3857 CXTranslationUnit_DetailedPreprocessingRecord |
3858 CXTranslationUnit_ForSerialization,
3859 &TU);
3860 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003861 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003862 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003863 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003864 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003865 clang_disposeIndex(Idx);
3866 return 1;
3867 }
3868
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003869 switch (clang_saveTranslationUnit(TU, filename,
3870 clang_defaultSaveOptions(TU))) {
3871 case CXSaveError_None:
3872 break;
3873
3874 case CXSaveError_TranslationErrors:
3875 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3876 filename);
3877 result = 2;
3878 break;
3879
3880 case CXSaveError_InvalidTU:
3881 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3882 filename);
3883 result = 3;
3884 break;
3885
3886 case CXSaveError_Unknown:
3887 default:
3888 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3889 result = 1;
3890 break;
3891 }
3892
Douglas Gregore9386682010-08-13 05:36:37 +00003893 clang_disposeTranslationUnit(TU);
3894 free_remapped_files(unsaved_files, num_unsaved_files);
3895 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003896 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003897}
3898
3899/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003900/* Serialized diagnostics. */
3901/******************************************************************************/
3902
3903static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3904 switch (error) {
3905 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3906 case CXLoadDiag_None: break;
3907 case CXLoadDiag_Unknown: return "Unknown";
3908 case CXLoadDiag_InvalidFile: return "Invalid File";
3909 }
3910 return "None";
3911}
3912
3913static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3914 switch (severity) {
3915 case CXDiagnostic_Note: return "note";
3916 case CXDiagnostic_Error: return "error";
3917 case CXDiagnostic_Fatal: return "fatal";
3918 case CXDiagnostic_Ignored: return "ignored";
3919 case CXDiagnostic_Warning: return "warning";
3920 }
3921 return "unknown";
3922}
3923
3924static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003925 if (indent == 0)
3926 return;
3927 fprintf(stderr, "+");
3928 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003929 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003930 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003931 --indent;
3932 }
3933}
3934
3935static void printLocation(CXSourceLocation L) {
3936 CXFile File;
3937 CXString FileName;
3938 unsigned line, column, offset;
3939
3940 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3941 FileName = clang_getFileName(File);
3942
3943 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3944 clang_disposeString(FileName);
3945}
3946
3947static void printRanges(CXDiagnostic D, unsigned indent) {
3948 unsigned i, n = clang_getDiagnosticNumRanges(D);
3949
3950 for (i = 0; i < n; ++i) {
3951 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003952 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003953 Start = clang_getRangeStart(SR);
3954 End = clang_getRangeEnd(SR);
3955
3956 printIndent(indent);
3957 fprintf(stderr, "Range: ");
3958 printLocation(Start);
3959 fprintf(stderr, " ");
3960 printLocation(End);
3961 fprintf(stderr, "\n");
3962 }
3963}
3964
3965static void printFixIts(CXDiagnostic D, unsigned indent) {
3966 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003967 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003968 for (i = 0 ; i < n; ++i) {
3969 CXSourceRange ReplacementRange;
3970 CXString text;
3971 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3972
3973 printIndent(indent);
3974 fprintf(stderr, "FIXIT: (");
3975 printLocation(clang_getRangeStart(ReplacementRange));
3976 fprintf(stderr, " - ");
3977 printLocation(clang_getRangeEnd(ReplacementRange));
3978 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3979 clang_disposeString(text);
3980 }
3981}
3982
3983static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003984 unsigned i, n;
3985
Ted Kremenekd010ba42011-11-10 08:43:12 +00003986 if (!Diags)
3987 return;
3988
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003989 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003990 for (i = 0; i < n; ++i) {
3991 CXSourceLocation DiagLoc;
3992 CXDiagnostic D;
3993 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003994 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003995 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003996 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003997
3998 D = clang_getDiagnosticInSet(Diags, i);
3999 DiagLoc = clang_getDiagnosticLocation(D);
4000 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4001 FileName = clang_getFileName(File);
4002 DiagSpelling = clang_getDiagnosticSpelling(D);
4003
4004 printIndent(indent);
4005
4006 fprintf(stderr, "%s:%d:%d: %s: %s",
4007 clang_getCString(FileName),
4008 line,
4009 column,
4010 getSeverityString(clang_getDiagnosticSeverity(D)),
4011 clang_getCString(DiagSpelling));
4012
4013 DiagOption = clang_getDiagnosticOption(D, 0);
4014 DiagOptionStr = clang_getCString(DiagOption);
4015 if (DiagOptionStr) {
4016 fprintf(stderr, " [%s]", DiagOptionStr);
4017 }
4018
Ted Kremenek26a6d492012-04-12 00:03:31 +00004019 DiagCat = clang_getDiagnosticCategoryText(D);
4020 DiagCatStr = clang_getCString(DiagCat);
4021 if (DiagCatStr) {
4022 fprintf(stderr, " [%s]", DiagCatStr);
4023 }
4024
Ted Kremenekd010ba42011-11-10 08:43:12 +00004025 fprintf(stderr, "\n");
4026
4027 printRanges(D, indent);
4028 printFixIts(D, indent);
4029
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004030 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004031 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4032
4033 clang_disposeString(FileName);
4034 clang_disposeString(DiagSpelling);
4035 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004036 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004037 }
4038}
4039
4040static int read_diagnostics(const char *filename) {
4041 enum CXLoadDiag_Error error;
4042 CXString errorString;
4043 CXDiagnosticSet Diags = 0;
4044
4045 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4046 if (!Diags) {
4047 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4048 getDiagnosticCodeStr(error),
4049 clang_getCString(errorString));
4050 clang_disposeString(errorString);
4051 return 1;
4052 }
4053
4054 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004055 fprintf(stderr, "Number of diagnostics: %d\n",
4056 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004057 clang_disposeDiagnosticSet(Diags);
4058 return 0;
4059}
4060
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004061static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004062 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004063 return 0;
4064}
4065
Ted Kremenekd010ba42011-11-10 08:43:12 +00004066/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004067/* Command line processing. */
4068/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004069
Douglas Gregor720d0052010-01-20 21:32:04 +00004070static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004071 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004072 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004073 if (strcmp(s, "-usrs") == 0)
4074 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004075 if (strncmp(s, "-memory-usage", 13) == 0)
4076 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004077 return NULL;
4078}
4079
Ted Kremenekef3339b2009-11-17 18:09:14 +00004080static void print_usage(void) {
4081 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004082 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004083 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004084 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004085 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4086 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004087 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004088 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004089 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004090 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004091 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004092 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004093 "[FileCheck prefix]\n");
4094 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004095 " c-index-test -test-load-tu <AST file> <symbol filter> "
4096 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004097 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4098 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004099 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004100 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004101 " c-index-test -test-load-source-memory-usage "
4102 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004103 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4104 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004105 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004106 " c-index-test -test-load-source-usrs-memory-usage "
4107 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004108 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4109 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004110 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004111 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004112 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004113 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004114 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004115 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004116 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004117 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004118 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004119 " c-index-test -write-pch <file> <compiler arguments>\n");
4120 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004121 " c-index-test -compilation-db [lookup <filename>] database\n");
4122 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004123 " c-index-test -print-build-session-timestamp\n");
4124 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004125 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004126 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004127 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004128 " all - load all symbols, including those from PCH\n"
4129 " local - load all symbols except those in PCH\n"
4130 " category - only load ObjC categories (non-PCH)\n"
4131 " interface - only load ObjC interfaces (non-PCH)\n"
4132 " protocol - only load ObjC protocols (non-PCH)\n"
4133 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004134 " typedef - only load typdefs (non-PCH)\n"
4135 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004136}
4137
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004138/***/
4139
4140int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004141 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004142 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4143 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004144 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004145 return perform_code_completion(argc, argv, 0);
4146 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4147 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004148 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
4149 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004150 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4151 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004152 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4153 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004154 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004155 return index_file(argc - 2, argv + 2, /*full=*/0);
4156 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4157 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004158 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4159 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004160 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4161 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004162 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004163 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004164 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004165 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4166 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004167 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004168 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4169 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4170 if (I) {
4171 int trials = atoi(argv[2]);
4172 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4173 NULL);
4174 }
4175 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004176 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004177 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004178
4179 PostVisitTU postVisit = 0;
4180 if (strstr(argv[1], "-memory-usage"))
4181 postVisit = PrintMemoryUsage;
4182
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004183 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004184 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4185 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004186 }
4187 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004188 return perform_file_scan(argv[2], argv[3],
4189 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004190 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4191 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004192 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4193 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4194 PrintInclusionStack);
4195 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4196 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4197 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004198 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4199 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4200 NULL);
Ehsan Akhgari93697fa2015-11-23 19:56:46 +00004201 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4202 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4203 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004204 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004205 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004206 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004207 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4208 return perform_test_load_source(argc - 2, argv + 2, "all",
4209 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004210 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4211 return perform_test_load_source(argc - 2, argv + 2, "all",
4212 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004213 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4214 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004215 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4216 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004217 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4218 if (argc > 2)
4219 return print_usrs(argv + 2, argv + argc);
4220 else {
4221 display_usrs();
4222 return 1;
4223 }
4224 }
4225 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4226 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004227 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4228 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004229 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4230 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004231 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4232 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004233
Ted Kremenekef3339b2009-11-17 18:09:14 +00004234 print_usage();
4235 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004236}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004237
4238/***/
4239
4240/* We intentionally run in a separate thread to ensure we at least minimal
4241 * testing of a multithreaded environment (for example, having a reduced stack
4242 * size). */
4243
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004244typedef struct thread_info {
4245 int argc;
4246 const char **argv;
4247 int result;
4248} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004249void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004250 thread_info *client_data = client_data_v;
4251 client_data->result = cindextest_main(client_data->argc, client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004252}
4253
4254static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004255 /* stdout, and surprisingly even stderr, are not always flushed on process
4256 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004257 fflush(stdout);
4258 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004259}
4260
4261int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004262 thread_info client_data;
4263
Reid Klecknere931c062014-06-05 00:13:43 +00004264 atexit(flush_atexit);
4265
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004266#ifdef CLANG_HAVE_LIBXML
4267 LIBXML_TEST_VERSION
4268#endif
4269
Douglas Gregorf428bf82010-10-27 16:00:01 +00004270 if (getenv("CINDEXTEST_NOTHREADS"))
4271 return cindextest_main(argc, argv);
4272
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004273 client_data.argc = argc;
4274 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004275 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004276 return client_data.result;
4277}