blob: eeeb832cd873890f3439da8311fd5fb479185a82 [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
Douglas Gregora8d0c772011-05-13 15:54:42 +0000770 if (clang_CXXMethod_isStatic(Cursor))
771 printf(" (static)");
772 if (clang_CXXMethod_isVirtual(Cursor))
773 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000774 if (clang_CXXMethod_isConst(Cursor))
775 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000776 if (clang_CXXMethod_isPureVirtual(Cursor))
777 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000778 if (clang_Cursor_isVariadic(Cursor))
779 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000780 if (clang_Cursor_isObjCOptional(Cursor))
781 printf(" (@optional)");
782
Ted Kremeneka5940822010-08-26 01:42:22 +0000783 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000784 CXType T =
785 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
786 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000787 printf(" [IBOutletCollection=%s]", clang_getCString(S));
788 clang_disposeString(S);
789 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000790
791 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
792 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
793 unsigned isVirtual = clang_isVirtualBase(Cursor);
794 const char *accessStr = 0;
795
796 switch (access) {
797 case CX_CXXInvalidAccessSpecifier:
798 accessStr = "invalid"; break;
799 case CX_CXXPublic:
800 accessStr = "public"; break;
801 case CX_CXXProtected:
802 accessStr = "protected"; break;
803 case CX_CXXPrivate:
804 accessStr = "private"; break;
805 }
806
807 printf(" [access=%s isVirtual=%s]", accessStr,
808 isVirtual ? "true" : "false");
809 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000810
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000811 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
812 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000813 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
814 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000815 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000816 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000817 clang_getCString(Name), line, column);
818 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000819
820 if (Cursor.kind == CXCursor_FunctionDecl) {
821 /* Collect the template parameter kinds from the base template. */
822 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
823 unsigned I;
824 for (I = 0; I < NumTemplateArgs; I++) {
825 enum CXTemplateArgumentKind TAK =
826 clang_Cursor_getTemplateArgumentKind(Cursor, I);
827 switch(TAK) {
828 case CXTemplateArgumentKind_Type:
829 {
830 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
831 CXString S = clang_getTypeSpelling(T);
832 printf(" [Template arg %d: kind: %d, type: %s]",
833 I, TAK, clang_getCString(S));
834 clang_disposeString(S);
835 }
836 break;
837 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000838 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000839 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
840 break;
841 default:
842 printf(" [Template arg %d: kind: %d]\n", I, TAK);
843 }
844 }
845 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000846 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000847
848 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
849 if (num_overridden) {
850 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000851 LineCol lineCols[50];
852 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000853 printf(" [Overrides ");
854 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000855 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000856 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000857 lineCols[I].line = line;
858 lineCols[I].col = column;
859 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000860 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000861 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
862 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000863 if (I)
864 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000865 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000866 }
867 printf("]");
868 clang_disposeOverriddenCursors(overridden);
869 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000870
871 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000872 CXFile File = clang_getIncludedFile(Cursor);
873 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000874 printf(" (%s)", clang_getCString(Included));
875 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000876
877 if (clang_isFileMultipleIncludeGuarded(TU, File))
878 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000879 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000880
881 CursorExtent = clang_getCursorExtent(Cursor);
882 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
883 CXNameRange_WantQualifier
884 | CXNameRange_WantSinglePiece
885 | CXNameRange_WantTemplateArgs,
886 0);
887 if (!clang_equalRanges(CursorExtent, RefNameRange))
888 PrintRange(RefNameRange, "SingleRefName");
889
890 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
891 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
892 CXNameRange_WantQualifier
893 | CXNameRange_WantTemplateArgs,
894 RefNameRangeNr);
895 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
896 break;
897 if (!clang_equalRanges(CursorExtent, RefNameRange))
898 PrintRange(RefNameRange, "RefName");
899 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000900
Chandler Carruthb2faa592014-05-02 23:30:59 +0000901 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000902
903 {
904 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
905 if (PropAttrs != CXObjCPropertyAttr_noattr) {
906 printf(" [");
907 #define PRINT_PROP_ATTR(A) \
908 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
909 PRINT_PROP_ATTR(readonly);
910 PRINT_PROP_ATTR(getter);
911 PRINT_PROP_ATTR(assign);
912 PRINT_PROP_ATTR(readwrite);
913 PRINT_PROP_ATTR(retain);
914 PRINT_PROP_ATTR(copy);
915 PRINT_PROP_ATTR(nonatomic);
916 PRINT_PROP_ATTR(setter);
917 PRINT_PROP_ATTR(atomic);
918 PRINT_PROP_ATTR(weak);
919 PRINT_PROP_ATTR(strong);
920 PRINT_PROP_ATTR(unsafe_unretained);
921 printf("]");
922 }
923 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000924
925 {
926 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
927 if (QT != CXObjCDeclQualifier_None) {
928 printf(" [");
929 #define PRINT_OBJC_QUAL(A) \
930 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
931 PRINT_OBJC_QUAL(In);
932 PRINT_OBJC_QUAL(Inout);
933 PRINT_OBJC_QUAL(Out);
934 PRINT_OBJC_QUAL(Bycopy);
935 PRINT_OBJC_QUAL(Byref);
936 PRINT_OBJC_QUAL(Oneway);
937 printf("]");
938 }
939 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000940 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000941}
Steve Naroff1054e602009-08-31 00:59:03 +0000942
Ted Kremenek29004672010-02-17 00:41:32 +0000943static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000944 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000945 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000946 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000947 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000948 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000949 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000950 clang_disposeString(source);
951 return "<invalid loc>";
952 }
953 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000954 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000955 clang_disposeString(source);
956 return b;
957 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000958}
959
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000960/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000961/* Callbacks. */
962/******************************************************************************/
963
964typedef void (*PostVisitTU)(CXTranslationUnit);
965
Douglas Gregor33cdd812010-02-18 18:08:43 +0000966void PrintDiagnostic(CXDiagnostic Diagnostic) {
967 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000968 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000969 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000970 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000971 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
972 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000973 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000974
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000975 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000976 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000977
Douglas Gregord770f732010-02-22 23:17:23 +0000978 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
979 fprintf(stderr, "%s\n", clang_getCString(Msg));
980 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000981
Douglas Gregor229bebd2010-11-09 06:24:54 +0000982 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
983 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000984 if (!file)
985 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000986
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000987 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000988 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000989 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000990 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000991 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
992 CXSourceLocation start = clang_getRangeStart(range);
993 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000994 unsigned start_line, start_column, end_line, end_column;
995 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +0000996 clang_getSpellingLocation(start, &start_file, &start_line,
997 &start_column, 0);
998 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +0000999 if (clang_equalLocations(start, end)) {
1000 /* Insertion. */
1001 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001002 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001003 clang_getCString(insertion_text), start_line, start_column);
1004 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1005 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001006 if (start_file == file && end_file == file) {
1007 fprintf(out, "FIX-IT: Remove ");
1008 PrintExtent(out, start_line, start_column, end_line, end_column);
1009 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001010 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001011 } else {
1012 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001013 if (start_file == end_file) {
1014 fprintf(out, "FIX-IT: Replace ");
1015 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001016 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001017 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001018 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001019 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001020 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001021}
1022
Ted Kremenek914c7e62012-02-14 02:46:03 +00001023void PrintDiagnosticSet(CXDiagnosticSet Set) {
1024 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1025 for ( ; i != n ; ++i) {
1026 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1027 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001028 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001029 if (ChildDiags)
1030 PrintDiagnosticSet(ChildDiags);
1031 }
1032}
1033
1034void PrintDiagnostics(CXTranslationUnit TU) {
1035 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1036 PrintDiagnosticSet(TUSet);
1037 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001038}
1039
Ted Kremenek83f642e2011-04-18 22:47:10 +00001040void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001041 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001042 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001043 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001044 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001045 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001046 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001047 unsigned long amount = usage.entries[i].amount;
1048 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001049 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001050 ((double) amount)/(1024*1024));
1051 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001052 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001053 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001054 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001055}
1056
Ted Kremenekb478ff42010-01-26 17:59:48 +00001057/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001058/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001059/******************************************************************************/
1060
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001061static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001062 CXSourceRange extent = clang_getCursorExtent(C);
1063 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001064}
1065
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001066/* Data used by the visitors. */
1067typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001068 CXTranslationUnit TU;
1069 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001070 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001071} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001072
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001073
Ted Kremenek29004672010-02-17 00:41:32 +00001074enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001075 CXCursor Parent,
1076 CXClientData ClientData) {
1077 VisitorData *Data = (VisitorData *)ClientData;
1078 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001079 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001080 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001081 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001082 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001083 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001084 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001085 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001086 if (clang_isDeclaration(Cursor.kind)) {
1087 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1088 const char *accessStr = 0;
1089
1090 switch (access) {
1091 case CX_CXXInvalidAccessSpecifier: break;
1092 case CX_CXXPublic:
1093 accessStr = "public"; break;
1094 case CX_CXXProtected:
1095 accessStr = "protected"; break;
1096 case CX_CXXPrivate:
1097 accessStr = "private"; break;
1098 }
1099
1100 if (accessStr)
1101 printf(" [access=%s]", accessStr);
1102 }
Ted Kremenek29004672010-02-17 00:41:32 +00001103 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001104 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001105 }
Ted Kremenek29004672010-02-17 00:41:32 +00001106
Douglas Gregor720d0052010-01-20 21:32:04 +00001107 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001108}
Steve Naroffa1c72842009-08-28 15:28:48 +00001109
Ted Kremenek29004672010-02-17 00:41:32 +00001110static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001111 CXCursor Parent,
1112 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001113 const char *startBuf, *endBuf;
1114 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1115 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001116 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001117
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001118 if (Cursor.kind != CXCursor_FunctionDecl ||
1119 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001120 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001121
1122 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1123 &startLine, &startColumn,
1124 &endLine, &endColumn);
1125 /* Probe the entire body, looking for both decls and refs. */
1126 curLine = startLine;
1127 curColumn = startColumn;
1128
1129 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001130 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001131 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001132 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001133
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001134 if (*startBuf == '\n') {
1135 startBuf++;
1136 curLine++;
1137 curColumn = 1;
1138 } else if (*startBuf != '\t')
1139 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001140
Douglas Gregor66a58812010-01-18 22:46:11 +00001141 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001142 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001143
Douglas Gregor4f46e782010-01-19 21:36:55 +00001144 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001145 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001146 CXSourceLocation RefLoc
1147 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001148 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001149 if (Ref.kind == CXCursor_NoDeclFound) {
1150 /* Nothing found here; that's fine. */
1151 } else if (Ref.kind != CXCursor_FunctionDecl) {
1152 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1153 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001154 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001155 printf("\n");
1156 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001157 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001158 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001159 startBuf++;
1160 }
Ted Kremenek29004672010-02-17 00:41:32 +00001161
Douglas Gregor720d0052010-01-20 21:32:04 +00001162 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001163}
1164
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001165/******************************************************************************/
1166/* USR testing. */
1167/******************************************************************************/
1168
Douglas Gregor720d0052010-01-20 21:32:04 +00001169enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1170 CXClientData ClientData) {
1171 VisitorData *Data = (VisitorData *)ClientData;
1172 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001173 CXString USR = clang_getCursorUSR(C);
1174 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001175 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001176 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001177 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001178 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001179 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1180
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001181 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001182 printf("\n");
1183 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001184
Douglas Gregor720d0052010-01-20 21:32:04 +00001185 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001186 }
1187
Douglas Gregor720d0052010-01-20 21:32:04 +00001188 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001189}
1190
1191/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001192/* Inclusion stack testing. */
1193/******************************************************************************/
1194
1195void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1196 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001197
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001198 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001199 CXString fname;
1200
1201 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001202 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001203 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001204
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001205 for (i = 0; i < includeStackLen; ++i) {
1206 CXFile includingFile;
1207 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001208 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1209 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001210 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001211 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001212 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001213 }
1214 printf("\n");
1215}
1216
1217void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001218 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001219}
1220
1221/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001222/* Linkage testing. */
1223/******************************************************************************/
1224
1225static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1226 CXClientData d) {
1227 const char *linkage = 0;
1228
1229 if (clang_isInvalid(clang_getCursorKind(cursor)))
1230 return CXChildVisit_Recurse;
1231
1232 switch (clang_getCursorLinkage(cursor)) {
1233 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001234 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1235 case CXLinkage_Internal: linkage = "Internal"; break;
1236 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1237 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001238 }
1239
1240 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001241 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001242 printf("linkage=%s\n", linkage);
1243 }
1244
1245 return CXChildVisit_Recurse;
1246}
1247
1248/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001249/* Typekind testing. */
1250/******************************************************************************/
1251
Dmitri Gribenko00353722013-02-15 21:15:49 +00001252static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1253 CXString TypeSpelling, TypeKindSpelling;
1254
1255 TypeSpelling = clang_getTypeSpelling(T);
1256 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1257 printf(Format,
1258 clang_getCString(TypeSpelling),
1259 clang_getCString(TypeKindSpelling));
1260 clang_disposeString(TypeSpelling);
1261 clang_disposeString(TypeKindSpelling);
1262}
1263
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001264static enum CXVisitorResult FieldVisitor(CXCursor C,
1265 CXClientData client_data) {
1266 (*(int *) client_data)+=1;
1267 return CXVisit_Continue;
1268}
1269
Dmitri Gribenko00353722013-02-15 21:15:49 +00001270static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1271 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001272 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001273 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001274 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001275 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001276 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001277 if (clang_isConstQualifiedType(T))
1278 printf(" const");
1279 if (clang_isVolatileQualifiedType(T))
1280 printf(" volatile");
1281 if (clang_isRestrictQualifiedType(T))
1282 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001283 if (RQ == CXRefQualifier_LValue)
1284 printf(" lvalue-ref-qualifier");
1285 if (RQ == CXRefQualifier_RValue)
1286 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001287 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001288 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001289 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001290 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001291 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001292 }
1293 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001294 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001295 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001296 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001297 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001298 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001299 }
1300 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001301 /* Print the argument types if they exist. */
1302 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001303 int NumArgs = clang_Cursor_getNumArguments(cursor);
1304 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001305 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001306 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001307 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001308 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001309 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001310 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001311 }
1312 }
1313 printf("]");
1314 }
1315 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001316 /* Print the template argument types if they exist. */
1317 {
1318 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1319 if (NumTArgs != -1 && NumTArgs != 0) {
1320 int i;
1321 printf(" [templateargs/%d=", NumTArgs);
1322 for (i = 0; i < NumTArgs; ++i) {
1323 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1324 if (TArg.kind != CXType_Invalid) {
1325 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1326 }
1327 }
1328 printf("]");
1329 }
1330 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001331 /* Print if this is a non-POD type. */
1332 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001333 /* Print the pointee type. */
1334 {
1335 CXType PT = clang_getPointeeType(T);
1336 if (PT.kind != CXType_Invalid) {
1337 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1338 }
1339 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001340 /* Print the number of fields if they exist. */
1341 {
1342 int numFields = 0;
1343 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1344 if (numFields != 0) {
1345 printf(" [nbFields=%d]", numFields);
1346 }
1347 /* Print if it is an anonymous record. */
1348 {
1349 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1350 if (isAnon != 0) {
1351 printf(" [isAnon=%d]", isAnon);
1352 }
1353 }
1354 }
1355 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001356
Ted Kremenek6bca9842010-05-14 21:29:26 +00001357 printf("\n");
1358 }
1359 return CXChildVisit_Recurse;
1360}
1361
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001362static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1363 CXClientData d) {
1364 CXType T;
1365 enum CXCursorKind K = clang_getCursorKind(cursor);
1366 if (clang_isInvalid(K))
1367 return CXChildVisit_Recurse;
1368 T = clang_getCursorType(cursor);
1369 PrintCursor(cursor, NULL);
1370 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1371 /* Print the type sizeof if applicable. */
1372 {
1373 long long Size = clang_Type_getSizeOf(T);
1374 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001375 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001376 }
1377 }
1378 /* Print the type alignof if applicable. */
1379 {
1380 long long Align = clang_Type_getAlignOf(T);
1381 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001382 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001383 }
1384 }
1385 /* Print the record field offset if applicable. */
1386 {
Nico Weber82098cb2014-04-24 04:14:12 +00001387 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1388 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001389 /* recurse to get the first parent record that is not anonymous. */
1390 CXCursor Parent, Record;
1391 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001392 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001393 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001394 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001395 Record = Parent;
1396 Parent = clang_getCursorSemanticParent(Record);
1397 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1398 /* Recurse as long as the parent is a CXType_Record and the Record
1399 is anonymous */
1400 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1401 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001402 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001403 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001404 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001405 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1406 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001407 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001408 } else {
1409 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001410 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001411 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001412 }
1413 }
Nico Weber82098cb2014-04-24 04:14:12 +00001414 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001415 }
1416 /* Print if its a bitfield */
1417 {
1418 int IsBitfield = clang_Cursor_isBitField(cursor);
1419 if (IsBitfield)
1420 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1421 }
1422 printf("\n");
1423 return CXChildVisit_Recurse;
1424}
1425
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001426/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001427/* Mangling testing. */
1428/******************************************************************************/
1429
1430static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1431 CXClientData d) {
1432 CXString MangledName;
1433 PrintCursor(cursor, NULL);
1434 MangledName = clang_Cursor_getMangling(cursor);
1435 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001436 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001437 return CXChildVisit_Continue;
1438}
1439
1440/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001441/* Bitwidth testing. */
1442/******************************************************************************/
1443
1444static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1445 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001446 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001447 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1448 return CXChildVisit_Recurse;
1449
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001450 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001451 if (Bitwidth >= 0) {
1452 PrintCursor(cursor, NULL);
1453 printf(" bitwidth=%d\n", Bitwidth);
1454 }
1455
1456 return CXChildVisit_Recurse;
1457}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001458
1459/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001460/* Loading ASTs/source. */
1461/******************************************************************************/
1462
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001463static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001464 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001465 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001466 PostVisitTU PV,
1467 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001468
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001469 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001470 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001471
1472 if (Visitor) {
1473 enum CXCursorKind K = CXCursor_NotImplemented;
1474 enum CXCursorKind *ck = &K;
1475 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001476
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001477 /* Perform some simple filtering. */
1478 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001479 else if (!strcmp(filter, "all-display") ||
1480 !strcmp(filter, "local-display")) {
1481 ck = NULL;
1482 want_display_name = 1;
1483 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001484 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001485 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1486 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1487 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1488 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1489 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1490 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1491 else {
1492 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1493 return 1;
1494 }
Ted Kremenek29004672010-02-17 00:41:32 +00001495
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001496 Data.TU = TU;
1497 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001498 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001499 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001500 }
Ted Kremenek29004672010-02-17 00:41:32 +00001501
Ted Kremenekb478ff42010-01-26 17:59:48 +00001502 if (PV)
1503 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001504
Douglas Gregor33cdd812010-02-18 18:08:43 +00001505 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001506 if (checkForErrors(TU) != 0) {
1507 clang_disposeTranslationUnit(TU);
1508 return -1;
1509 }
1510
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001511 clang_disposeTranslationUnit(TU);
1512 return 0;
1513}
1514
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001515int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001516 const char *prefix, CXCursorVisitor Visitor,
1517 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001518 CXIndex Idx;
1519 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001520 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001521 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001522 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001523 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001524
Ted Kremenek50228be2010-02-11 07:41:25 +00001525 if (!CreateTranslationUnit(Idx, file, &TU)) {
1526 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001527 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001528 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001529
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001530 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001531 clang_disposeIndex(Idx);
1532 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001533}
1534
Ted Kremenekb478ff42010-01-26 17:59:48 +00001535int perform_test_load_source(int argc, const char **argv,
1536 const char *filter, CXCursorVisitor Visitor,
1537 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001538 CXIndex Idx;
1539 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001540 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001541 struct CXUnsavedFile *unsaved_files = 0;
1542 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001543 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001544 int result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001545
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001546 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001547 (!strcmp(filter, "local") ||
1548 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001549 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001550
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001551 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1552 argc--;
1553 argv++;
1554 }
1555
Ted Kremenek50228be2010-02-11 07:41:25 +00001556 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1557 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001558 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001559 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001560
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001561 Err = clang_parseTranslationUnit2(Idx, 0,
1562 argv + num_unsaved_files,
1563 argc - num_unsaved_files,
1564 unsaved_files, num_unsaved_files,
1565 getDefaultParsingOptions(), &TU);
1566 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001567 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001568 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001569 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001570 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001571 return 1;
1572 }
1573
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001574 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1575 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001576 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001577 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001578 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001579}
1580
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001581int perform_test_reparse_source(int argc, const char **argv, int trials,
1582 const char *filter, CXCursorVisitor Visitor,
1583 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001584 CXIndex Idx;
1585 CXTranslationUnit TU;
1586 struct CXUnsavedFile *unsaved_files = 0;
1587 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001588 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001589 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001590 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001591 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001592 int remap_after_trial = 0;
1593 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001594
1595 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1596 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001597 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001598
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001599 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1600 clang_disposeIndex(Idx);
1601 return -1;
1602 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001603
1604 for (i = 0; i < argc; ++i) {
1605 if (strcmp(argv[i], "--") == 0)
1606 break;
1607 }
1608 if (i < argc)
1609 compiler_arg_idx = i+1;
1610 if (num_unsaved_files > compiler_arg_idx)
1611 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001612
Daniel Dunbarec29d712010-08-18 23:09:16 +00001613 /* Load the initial translation unit -- we do this without honoring remapped
1614 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001615 Err = clang_parseTranslationUnit2(Idx, 0,
1616 argv + compiler_arg_idx,
1617 argc - compiler_arg_idx,
1618 0, 0, getDefaultParsingOptions(), &TU);
1619 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001620 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001621 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001622 free_remapped_files(unsaved_files, num_unsaved_files);
1623 clang_disposeIndex(Idx);
1624 return 1;
1625 }
1626
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001627 if (checkForErrors(TU) != 0)
1628 return -1;
1629
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001630 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1631 remap_after_trial =
1632 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1633 }
1634
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001635 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001636 free_remapped_files(unsaved_files, num_unsaved_files);
1637 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1638 &unsaved_files, &num_unsaved_files)) {
1639 clang_disposeTranslationUnit(TU);
1640 clang_disposeIndex(Idx);
1641 return -1;
1642 }
1643
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001644 Err = clang_reparseTranslationUnit(
1645 TU,
1646 trial >= remap_after_trial ? num_unsaved_files : 0,
1647 trial >= remap_after_trial ? unsaved_files : 0,
1648 clang_defaultReparseOptions(TU));
1649 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001650 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001651 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001652 clang_disposeTranslationUnit(TU);
1653 free_remapped_files(unsaved_files, num_unsaved_files);
1654 clang_disposeIndex(Idx);
1655 return -1;
1656 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001657
1658 if (checkForErrors(TU) != 0)
1659 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001660 }
1661
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001662 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001663
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001664 free_remapped_files(unsaved_files, num_unsaved_files);
1665 clang_disposeIndex(Idx);
1666 return result;
1667}
1668
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001669/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001670/* Logic for testing clang_getCursor(). */
1671/******************************************************************************/
1672
Douglas Gregor37aa4932011-05-04 00:14:37 +00001673static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001674 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001675 unsigned end_line, unsigned end_col,
1676 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001677 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001678 if (prefix)
1679 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001680 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1681 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001682 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001683 printf("\n");
1684}
1685
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001686static int perform_file_scan(const char *ast_file, const char *source_file,
1687 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001688 CXIndex Idx;
1689 CXTranslationUnit TU;
1690 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001691 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001692 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001693 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001694 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001695
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001696 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001697 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001698 fprintf(stderr, "Could not create Index\n");
1699 return 1;
1700 }
Ted Kremenek29004672010-02-17 00:41:32 +00001701
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001702 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1703 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001704
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001705 if ((fp = fopen(source_file, "r")) == NULL) {
1706 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001707 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001708 return 1;
1709 }
Ted Kremenek29004672010-02-17 00:41:32 +00001710
Douglas Gregor816fd362010-01-22 21:44:22 +00001711 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001712 for (;;) {
1713 CXCursor cursor;
1714 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001715
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001716 if (c == '\n') {
1717 ++line;
1718 col = 1;
1719 } else
1720 ++col;
1721
1722 /* Check the cursor at this position, and dump the previous one if we have
1723 * found something new.
1724 */
1725 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1726 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1727 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001728 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001729 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001730 start_line = line;
1731 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001732 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001733 if (c == EOF)
1734 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001735
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001736 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001737 }
Ted Kremenek29004672010-02-17 00:41:32 +00001738
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001739 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001740 clang_disposeTranslationUnit(TU);
1741 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001742 return 0;
1743}
1744
1745/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001746/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001747/******************************************************************************/
1748
Douglas Gregor9eb77012009-11-07 00:00:49 +00001749/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1750 on failure. If successful, the pointer *filename will contain newly-allocated
1751 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001752int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001753 unsigned *column, unsigned *second_line,
1754 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001755 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001756 const char *last_colon = strrchr(input, ':');
1757 unsigned values[4], i;
1758 unsigned num_values = (second_line && second_column)? 4 : 2;
1759
Douglas Gregor9eb77012009-11-07 00:00:49 +00001760 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001761 if (!last_colon || last_colon == input) {
1762 if (num_values == 4)
1763 fprintf(stderr, "could not parse filename:line:column:line:column in "
1764 "'%s'\n", input);
1765 else
1766 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001767 return 1;
1768 }
1769
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001770 for (i = 0; i != num_values; ++i) {
1771 const char *prev_colon;
1772
1773 /* Parse the next line or column. */
1774 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1775 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001776 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001777 (i % 2 ? "column" : "line"), input);
1778 return 1;
1779 }
Ted Kremenek29004672010-02-17 00:41:32 +00001780
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001781 if (i + 1 == num_values)
1782 break;
1783
1784 /* Find the previous colon. */
1785 prev_colon = last_colon - 1;
1786 while (prev_colon != input && *prev_colon != ':')
1787 --prev_colon;
1788 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001789 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001790 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001791 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001792 }
1793
1794 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001795 }
1796
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001797 *line = values[0];
1798 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001799
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001800 if (second_line && second_column) {
1801 *second_line = values[2];
1802 *second_column = values[3];
1803 }
1804
Douglas Gregorf96ea292009-11-09 18:19:57 +00001805 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001806 *filename = (char*)malloc(last_colon - input + 1);
1807 memcpy(*filename, input, last_colon - input);
1808 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001809 return 0;
1810}
1811
1812const char *
1813clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1814 switch (Kind) {
1815 case CXCompletionChunk_Optional: return "Optional";
1816 case CXCompletionChunk_TypedText: return "TypedText";
1817 case CXCompletionChunk_Text: return "Text";
1818 case CXCompletionChunk_Placeholder: return "Placeholder";
1819 case CXCompletionChunk_Informative: return "Informative";
1820 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1821 case CXCompletionChunk_LeftParen: return "LeftParen";
1822 case CXCompletionChunk_RightParen: return "RightParen";
1823 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1824 case CXCompletionChunk_RightBracket: return "RightBracket";
1825 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1826 case CXCompletionChunk_RightBrace: return "RightBrace";
1827 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1828 case CXCompletionChunk_RightAngle: return "RightAngle";
1829 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001830 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001831 case CXCompletionChunk_Colon: return "Colon";
1832 case CXCompletionChunk_SemiColon: return "SemiColon";
1833 case CXCompletionChunk_Equal: return "Equal";
1834 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1835 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001836 }
Ted Kremenek29004672010-02-17 00:41:32 +00001837
Douglas Gregor9eb77012009-11-07 00:00:49 +00001838 return "Unknown";
1839}
1840
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001841static int checkForErrors(CXTranslationUnit TU) {
1842 unsigned Num, i;
1843 CXDiagnostic Diag;
1844 CXString DiagStr;
1845
1846 if (!getenv("CINDEXTEST_FAILONERROR"))
1847 return 0;
1848
1849 Num = clang_getNumDiagnostics(TU);
1850 for (i = 0; i != Num; ++i) {
1851 Diag = clang_getDiagnostic(TU, i);
1852 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1853 DiagStr = clang_formatDiagnostic(Diag,
1854 clang_defaultDiagnosticDisplayOptions());
1855 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1856 clang_disposeString(DiagStr);
1857 clang_disposeDiagnostic(Diag);
1858 return -1;
1859 }
1860 clang_disposeDiagnostic(Diag);
1861 }
1862
1863 return 0;
1864}
1865
Nico Weber8d19dff2014-05-07 21:05:22 +00001866static void print_completion_string(CXCompletionString completion_string,
1867 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001868 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001869
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001870 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001871 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001872 CXString text;
1873 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001874 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001875 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001876
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001877 if (Kind == CXCompletionChunk_Optional) {
1878 fprintf(file, "{Optional ");
1879 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001880 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001881 file);
1882 fprintf(file, "}");
1883 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001884 }
1885
1886 if (Kind == CXCompletionChunk_VerticalSpace) {
1887 fprintf(file, "{VerticalSpace }");
1888 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001889 }
Ted Kremenek29004672010-02-17 00:41:32 +00001890
Douglas Gregorf81f5282009-11-09 17:05:28 +00001891 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001892 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001893 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001894 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001895 cstr ? cstr : "");
1896 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001897 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001898
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001899}
1900
Nico Weber8d19dff2014-05-07 21:05:22 +00001901static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001902 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001903 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001904 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001905 enum CXCursorKind ParentKind;
1906 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001907 CXString BriefComment;
1908 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001909
Ted Kremenek29004672010-02-17 00:41:32 +00001910 fprintf(file, "%s:", clang_getCString(ks));
1911 clang_disposeString(ks);
1912
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001913 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001914 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001915 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001916 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1917 case CXAvailability_Available:
1918 break;
1919
1920 case CXAvailability_Deprecated:
1921 fprintf(file, " (deprecated)");
1922 break;
1923
1924 case CXAvailability_NotAvailable:
1925 fprintf(file, " (unavailable)");
1926 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001927
1928 case CXAvailability_NotAccessible:
1929 fprintf(file, " (inaccessible)");
1930 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00001931 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001932
1933 annotationCount = clang_getCompletionNumAnnotations(
1934 completion_result->CompletionString);
1935 if (annotationCount) {
1936 unsigned i;
1937 fprintf(file, " (");
1938 for (i = 0; i < annotationCount; ++i) {
1939 if (i != 0)
1940 fprintf(file, ", ");
1941 fprintf(file, "\"%s\"",
1942 clang_getCString(clang_getCompletionAnnotation(
1943 completion_result->CompletionString, i)));
1944 }
1945 fprintf(file, ")");
1946 }
1947
Douglas Gregor78254c82012-03-27 23:34:16 +00001948 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1949 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1950 &ParentKind);
1951 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001952 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00001953 fprintf(file, " (parent: %s '%s')",
1954 clang_getCString(KindSpelling),
1955 clang_getCString(ParentName));
1956 clang_disposeString(KindSpelling);
1957 }
1958 clang_disposeString(ParentName);
1959 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001960
1961 BriefComment = clang_getCompletionBriefComment(
1962 completion_result->CompletionString);
1963 BriefCommentCString = clang_getCString(BriefComment);
1964 if (BriefCommentCString && *BriefCommentCString != '\0') {
1965 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1966 }
1967 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00001968
Douglas Gregorf757a122010-08-23 23:00:57 +00001969 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00001970}
1971
Douglas Gregor21325842011-07-07 16:03:39 +00001972void print_completion_contexts(unsigned long long contexts, FILE *file) {
1973 fprintf(file, "Completion contexts:\n");
1974 if (contexts == CXCompletionContext_Unknown) {
1975 fprintf(file, "Unknown\n");
1976 }
1977 if (contexts & CXCompletionContext_AnyType) {
1978 fprintf(file, "Any type\n");
1979 }
1980 if (contexts & CXCompletionContext_AnyValue) {
1981 fprintf(file, "Any value\n");
1982 }
1983 if (contexts & CXCompletionContext_ObjCObjectValue) {
1984 fprintf(file, "Objective-C object value\n");
1985 }
1986 if (contexts & CXCompletionContext_ObjCSelectorValue) {
1987 fprintf(file, "Objective-C selector value\n");
1988 }
1989 if (contexts & CXCompletionContext_CXXClassTypeValue) {
1990 fprintf(file, "C++ class type value\n");
1991 }
1992 if (contexts & CXCompletionContext_DotMemberAccess) {
1993 fprintf(file, "Dot member access\n");
1994 }
1995 if (contexts & CXCompletionContext_ArrowMemberAccess) {
1996 fprintf(file, "Arrow member access\n");
1997 }
1998 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
1999 fprintf(file, "Objective-C property access\n");
2000 }
2001 if (contexts & CXCompletionContext_EnumTag) {
2002 fprintf(file, "Enum tag\n");
2003 }
2004 if (contexts & CXCompletionContext_UnionTag) {
2005 fprintf(file, "Union tag\n");
2006 }
2007 if (contexts & CXCompletionContext_StructTag) {
2008 fprintf(file, "Struct tag\n");
2009 }
2010 if (contexts & CXCompletionContext_ClassTag) {
2011 fprintf(file, "Class name\n");
2012 }
2013 if (contexts & CXCompletionContext_Namespace) {
2014 fprintf(file, "Namespace or namespace alias\n");
2015 }
2016 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2017 fprintf(file, "Nested name specifier\n");
2018 }
2019 if (contexts & CXCompletionContext_ObjCInterface) {
2020 fprintf(file, "Objective-C interface\n");
2021 }
2022 if (contexts & CXCompletionContext_ObjCProtocol) {
2023 fprintf(file, "Objective-C protocol\n");
2024 }
2025 if (contexts & CXCompletionContext_ObjCCategory) {
2026 fprintf(file, "Objective-C category\n");
2027 }
2028 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2029 fprintf(file, "Objective-C instance method\n");
2030 }
2031 if (contexts & CXCompletionContext_ObjCClassMessage) {
2032 fprintf(file, "Objective-C class method\n");
2033 }
2034 if (contexts & CXCompletionContext_ObjCSelectorName) {
2035 fprintf(file, "Objective-C selector name\n");
2036 }
2037 if (contexts & CXCompletionContext_MacroName) {
2038 fprintf(file, "Macro name\n");
2039 }
2040 if (contexts & CXCompletionContext_NaturalLanguage) {
2041 fprintf(file, "Natural language\n");
2042 }
2043}
2044
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002045int my_stricmp(const char *s1, const char *s2) {
2046 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00002047 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002048 if (c1 < c2)
2049 return -1;
2050 else if (c1 > c2)
2051 return 1;
2052
2053 ++s1;
2054 ++s2;
2055 }
2056
2057 if (*s1)
2058 return 1;
2059 else if (*s2)
2060 return -1;
2061 return 0;
2062}
2063
Douglas Gregor47815d52010-07-12 18:38:41 +00002064int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002065 const char *input = argv[1];
2066 char *filename = 0;
2067 unsigned line;
2068 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002069 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002070 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002071 struct CXUnsavedFile *unsaved_files = 0;
2072 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002073 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002074 enum CXErrorCode Err;
2075 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002076 unsigned I, Repeats = 1;
2077 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2078
2079 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2080 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002081 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2082 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002083
Douglas Gregor47815d52010-07-12 18:38:41 +00002084 if (timing_only)
2085 input += strlen("-code-completion-timing=");
2086 else
2087 input += strlen("-code-completion-at=");
2088
Ted Kremenek29004672010-02-17 00:41:32 +00002089 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002090 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002091 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002092
Douglas Gregor9485bf92009-12-02 09:21:34 +00002093 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2094 return -1;
2095
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002096 CIdx = clang_createIndex(0, 0);
2097
2098 if (getenv("CINDEXTEST_EDITING"))
2099 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002100
2101 Err = clang_parseTranslationUnit2(CIdx, 0,
2102 argv + num_unsaved_files + 2,
2103 argc - num_unsaved_files - 2,
2104 0, 0, getDefaultParsingOptions(), &TU);
2105 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002106 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002107 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002108 return 1;
2109 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002110
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002111 Err = clang_reparseTranslationUnit(TU, 0, 0,
2112 clang_defaultReparseOptions(TU));
2113
2114 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002115 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002116 describeLibclangFailure(Err);
2117 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002118 return 1;
2119 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002120
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002121 for (I = 0; I != Repeats; ++I) {
2122 results = clang_codeCompleteAt(TU, filename, line, column,
2123 unsaved_files, num_unsaved_files,
2124 completionOptions);
2125 if (!results) {
2126 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002127 return 1;
2128 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002129 if (I != Repeats-1)
2130 clang_disposeCodeCompleteResults(results);
2131 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002132
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002133 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002134 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002135 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002136 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002137 CXString objCSelector;
2138 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002139 if (!timing_only) {
2140 /* Sort the code-completion results based on the typed text. */
2141 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2142
Douglas Gregor47815d52010-07-12 18:38:41 +00002143 for (i = 0; i != n; ++i)
2144 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002145 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002146 n = clang_codeCompleteGetNumDiagnostics(results);
2147 for (i = 0; i != n; ++i) {
2148 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2149 PrintDiagnostic(diag);
2150 clang_disposeDiagnostic(diag);
2151 }
Douglas Gregor21325842011-07-07 16:03:39 +00002152
2153 contexts = clang_codeCompleteGetContexts(results);
2154 print_completion_contexts(contexts, stdout);
2155
Douglas Gregorea777402011-07-26 15:24:30 +00002156 containerKind = clang_codeCompleteGetContainerKind(results,
2157 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002158
2159 if (containerKind != CXCursor_InvalidCode) {
2160 /* We have found a container */
2161 CXString containerUSR, containerKindSpelling;
2162 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2163 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2164 clang_disposeString(containerKindSpelling);
2165
2166 if (containerIsIncomplete) {
2167 printf("Container is incomplete\n");
2168 }
2169 else {
2170 printf("Container is complete\n");
2171 }
2172
2173 containerUSR = clang_codeCompleteGetContainerUSR(results);
2174 printf("Container USR: %s\n", clang_getCString(containerUSR));
2175 clang_disposeString(containerUSR);
2176 }
2177
Douglas Gregorea777402011-07-26 15:24:30 +00002178 objCSelector = clang_codeCompleteGetObjCSelector(results);
2179 selectorString = clang_getCString(objCSelector);
2180 if (selectorString && strlen(selectorString) > 0) {
2181 printf("Objective-C selector: %s\n", selectorString);
2182 }
2183 clang_disposeString(objCSelector);
2184
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002185 clang_disposeCodeCompleteResults(results);
2186 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002187 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002188 clang_disposeIndex(CIdx);
2189 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002190
Douglas Gregor9485bf92009-12-02 09:21:34 +00002191 free_remapped_files(unsaved_files, num_unsaved_files);
2192
Ted Kremenekef3339b2009-11-17 18:09:14 +00002193 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002194}
2195
Douglas Gregor082c3e62010-01-15 19:40:17 +00002196typedef struct {
2197 char *filename;
2198 unsigned line;
2199 unsigned column;
2200} CursorSourceLocation;
2201
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002202static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002203 CXIndex CIdx;
2204 int errorCode;
2205 struct CXUnsavedFile *unsaved_files = 0;
2206 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002207 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002208 CXTranslationUnit TU;
2209 CXCursor Cursor;
2210 CursorSourceLocation *Locations = 0;
2211 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002212 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002213 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002214
Ted Kremenek29004672010-02-17 00:41:32 +00002215 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002216 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2217 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002218
Douglas Gregor082c3e62010-01-15 19:40:17 +00002219 /* Parse the locations. */
2220 assert(NumLocations > 0 && "Unable to count locations?");
2221 Locations = (CursorSourceLocation *)malloc(
2222 NumLocations * sizeof(CursorSourceLocation));
2223 for (Loc = 0; Loc < NumLocations; ++Loc) {
2224 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002225 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2226 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002227 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002228 return errorCode;
2229 }
Ted Kremenek29004672010-02-17 00:41:32 +00002230
2231 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002232 &num_unsaved_files))
2233 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002234
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002235 if (getenv("CINDEXTEST_EDITING"))
2236 Repeats = 5;
2237
2238 /* Parse the translation unit. When we're testing clang_getCursor() after
2239 reparsing, don't remap unsaved files until the second parse. */
2240 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002241 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2242 argv + num_unsaved_files + 1 + NumLocations,
2243 argc - num_unsaved_files - 2 - NumLocations,
2244 unsaved_files,
2245 Repeats > 1? 0 : num_unsaved_files,
2246 getDefaultParsingOptions(), &TU);
2247 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002248 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002249 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002250 return -1;
2251 }
Ted Kremenek29004672010-02-17 00:41:32 +00002252
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002253 if (checkForErrors(TU) != 0)
2254 return -1;
2255
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002256 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002257 if (Repeats > 1) {
2258 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2259 clang_defaultReparseOptions(TU));
2260 if (Err != CXError_Success) {
2261 describeLibclangFailure(Err);
2262 clang_disposeTranslationUnit(TU);
2263 return 1;
2264 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002265 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002266
2267 if (checkForErrors(TU) != 0)
2268 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002269
2270 for (Loc = 0; Loc < NumLocations; ++Loc) {
2271 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2272 if (!file)
2273 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002274
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002275 Cursor = clang_getCursor(TU,
2276 clang_getLocation(TU, file, Locations[Loc].line,
2277 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002278
2279 if (checkForErrors(TU) != 0)
2280 return -1;
2281
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002282 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002283 CXCompletionString completionString = clang_getCursorCompletionString(
2284 Cursor);
2285 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002286 CXString Spelling;
2287 const char *cspell;
2288 unsigned line, column;
2289 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2290 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002291 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002292 PrintCursorExtent(Cursor);
2293 Spelling = clang_getCursorSpelling(Cursor);
2294 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002295 if (cspell && strlen(cspell) != 0) {
2296 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002297 printf(" Spelling=%s (", cspell);
2298 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002299 CXSourceRange range =
2300 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002301 if (clang_Range_isNull(range))
2302 break;
2303 PrintRange(range, 0);
2304 }
2305 printf(")");
2306 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002307 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002308 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
Nico Weber8d19dff2014-05-07 21:05:22 +00002309 printf(" Selector index=%d",
2310 clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002311 if (clang_Cursor_isDynamicCall(Cursor))
2312 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002313 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002314 CXType T = clang_Cursor_getReceiverType(Cursor);
2315 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002316 printf(" Receiver-type=%s", clang_getCString(S));
2317 clang_disposeString(S);
2318 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002319
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002320 {
2321 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002322 CXFile astFile;
2323 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002324 unsigned i, numHeaders;
2325 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002326 astFile = clang_Module_getASTFile(mod);
2327 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002328 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002329 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002330 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002331 clang_getCString(name), clang_getCString(astFilename),
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002332 clang_Module_isSystem(mod), numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002333 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002334 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002335 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002336 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2337 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002338 printf("\n%s", clang_getCString(filename));
2339 clang_disposeString(filename);
2340 }
2341 }
2342 }
2343
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002344 if (completionString != NULL) {
2345 printf("\nCompletion string: ");
2346 print_completion_string(completionString, stdout);
2347 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002348 printf("\n");
2349 free(Locations[Loc].filename);
2350 }
2351 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002352 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002353
Douglas Gregor33cdd812010-02-18 18:08:43 +00002354 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002355 clang_disposeTranslationUnit(TU);
2356 clang_disposeIndex(CIdx);
2357 free(Locations);
2358 free_remapped_files(unsaved_files, num_unsaved_files);
2359 return 0;
2360}
2361
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002362static enum CXVisitorResult findFileRefsVisit(void *context,
2363 CXCursor cursor, CXSourceRange range) {
2364 if (clang_Range_isNull(range))
2365 return CXVisit_Continue;
2366
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002367 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002368 PrintRange(range, "");
2369 printf("\n");
2370 return CXVisit_Continue;
2371}
2372
2373static int find_file_refs_at(int argc, const char **argv) {
2374 CXIndex CIdx;
2375 int errorCode;
2376 struct CXUnsavedFile *unsaved_files = 0;
2377 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002378 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002379 CXTranslationUnit TU;
2380 CXCursor Cursor;
2381 CursorSourceLocation *Locations = 0;
2382 unsigned NumLocations = 0, Loc;
2383 unsigned Repeats = 1;
2384 unsigned I;
2385
2386 /* Count the number of locations. */
2387 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2388 ++NumLocations;
2389
2390 /* Parse the locations. */
2391 assert(NumLocations > 0 && "Unable to count locations?");
2392 Locations = (CursorSourceLocation *)malloc(
2393 NumLocations * sizeof(CursorSourceLocation));
2394 for (Loc = 0; Loc < NumLocations; ++Loc) {
2395 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2396 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2397 &Locations[Loc].line,
2398 &Locations[Loc].column, 0, 0)))
2399 return errorCode;
2400 }
2401
2402 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2403 &num_unsaved_files))
2404 return -1;
2405
2406 if (getenv("CINDEXTEST_EDITING"))
2407 Repeats = 5;
2408
2409 /* Parse the translation unit. When we're testing clang_getCursor() after
2410 reparsing, don't remap unsaved files until the second parse. */
2411 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002412 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2413 argv + num_unsaved_files + 1 + NumLocations,
2414 argc - num_unsaved_files - 2 - NumLocations,
2415 unsaved_files,
2416 Repeats > 1? 0 : num_unsaved_files,
2417 getDefaultParsingOptions(), &TU);
2418 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002419 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002420 describeLibclangFailure(Err);
2421 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002422 return -1;
2423 }
2424
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002425 if (checkForErrors(TU) != 0)
2426 return -1;
2427
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002428 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002429 if (Repeats > 1) {
2430 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2431 clang_defaultReparseOptions(TU));
2432 if (Err != CXError_Success) {
2433 describeLibclangFailure(Err);
2434 clang_disposeTranslationUnit(TU);
2435 return 1;
2436 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002437 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002438
2439 if (checkForErrors(TU) != 0)
2440 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002441
2442 for (Loc = 0; Loc < NumLocations; ++Loc) {
2443 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2444 if (!file)
2445 continue;
2446
2447 Cursor = clang_getCursor(TU,
2448 clang_getLocation(TU, file, Locations[Loc].line,
2449 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002450
2451 if (checkForErrors(TU) != 0)
2452 return -1;
2453
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002454 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002455 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002456 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002457 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002458 clang_findReferencesInFile(Cursor, file, visitor);
2459 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002460
2461 if (checkForErrors(TU) != 0)
2462 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002463 }
2464 }
2465 }
2466
2467 PrintDiagnostics(TU);
2468 clang_disposeTranslationUnit(TU);
2469 clang_disposeIndex(CIdx);
2470 free(Locations);
2471 free_remapped_files(unsaved_files, num_unsaved_files);
2472 return 0;
2473}
2474
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002475static enum CXVisitorResult findFileIncludesVisit(void *context,
2476 CXCursor cursor, CXSourceRange range) {
2477 PrintCursor(cursor, NULL);
2478 PrintRange(range, "");
2479 printf("\n");
2480 return CXVisit_Continue;
2481}
2482
2483static int find_file_includes_in(int argc, const char **argv) {
2484 CXIndex CIdx;
2485 struct CXUnsavedFile *unsaved_files = 0;
2486 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002487 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002488 CXTranslationUnit TU;
2489 const char **Filenames = 0;
2490 unsigned NumFilenames = 0;
2491 unsigned Repeats = 1;
2492 unsigned I, FI;
2493
2494 /* Count the number of locations. */
2495 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2496 ++NumFilenames;
2497
2498 /* Parse the locations. */
2499 assert(NumFilenames > 0 && "Unable to count filenames?");
2500 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2501 for (I = 0; I < NumFilenames; ++I) {
2502 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2503 /* Copy the file name. */
2504 Filenames[I] = input;
2505 }
2506
2507 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2508 &num_unsaved_files))
2509 return -1;
2510
2511 if (getenv("CINDEXTEST_EDITING"))
2512 Repeats = 2;
2513
2514 /* Parse the translation unit. When we're testing clang_getCursor() after
2515 reparsing, don't remap unsaved files until the second parse. */
2516 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002517 Err = clang_parseTranslationUnit2(
2518 CIdx, argv[argc - 1],
2519 argv + num_unsaved_files + 1 + NumFilenames,
2520 argc - num_unsaved_files - 2 - NumFilenames,
2521 unsaved_files,
2522 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002523
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002524 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002525 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002526 describeLibclangFailure(Err);
2527 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002528 return -1;
2529 }
2530
2531 if (checkForErrors(TU) != 0)
2532 return -1;
2533
2534 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002535 if (Repeats > 1) {
2536 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2537 clang_defaultReparseOptions(TU));
2538 if (Err != CXError_Success) {
2539 describeLibclangFailure(Err);
2540 clang_disposeTranslationUnit(TU);
2541 return 1;
2542 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002543 }
2544
2545 if (checkForErrors(TU) != 0)
2546 return -1;
2547
2548 for (FI = 0; FI < NumFilenames; ++FI) {
2549 CXFile file = clang_getFile(TU, Filenames[FI]);
2550 if (!file)
2551 continue;
2552
2553 if (checkForErrors(TU) != 0)
2554 return -1;
2555
2556 if (I + 1 == Repeats) {
2557 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2558 clang_findIncludesInFile(TU, file, visitor);
2559
2560 if (checkForErrors(TU) != 0)
2561 return -1;
2562 }
2563 }
2564 }
2565
2566 PrintDiagnostics(TU);
2567 clang_disposeTranslationUnit(TU);
2568 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002569 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002570 free_remapped_files(unsaved_files, num_unsaved_files);
2571 return 0;
2572}
2573
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002574#define MAX_IMPORTED_ASTFILES 200
2575
2576typedef struct {
2577 char **filenames;
2578 unsigned num_files;
2579} ImportedASTFilesData;
2580
2581static ImportedASTFilesData *importedASTs_create() {
2582 ImportedASTFilesData *p;
2583 p = malloc(sizeof(ImportedASTFilesData));
2584 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2585 p->num_files = 0;
2586 return p;
2587}
2588
2589static void importedASTs_dispose(ImportedASTFilesData *p) {
2590 unsigned i;
2591 if (!p)
2592 return;
2593
2594 for (i = 0; i < p->num_files; ++i)
2595 free(p->filenames[i]);
2596 free(p->filenames);
2597 free(p);
2598}
2599
2600static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2601 unsigned i;
2602 assert(p && file);
2603 for (i = 0; i < p->num_files; ++i)
2604 if (strcmp(file, p->filenames[i]) == 0)
2605 return;
2606 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2607 p->filenames[p->num_files++] = strdup(file);
2608}
2609
Nico Weberdf686022014-05-07 21:09:42 +00002610typedef struct IndexDataStringList_ {
2611 struct IndexDataStringList_ *next;
2612 char data[1]; /* Dynamically sized. */
2613} IndexDataStringList;
2614
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002615typedef struct {
2616 const char *check_prefix;
2617 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002618 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002619 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002620 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002621 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002622 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002623 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002624} IndexData;
2625
Nico Weberdf686022014-05-07 21:09:42 +00002626static void free_client_data(IndexData *index_data) {
2627 IndexDataStringList *node = index_data->strings;
2628 while (node) {
2629 IndexDataStringList *next = node->next;
2630 free(node);
2631 node = next;
2632 }
2633 index_data->strings = NULL;
2634}
2635
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002636static void printCheck(IndexData *data) {
2637 if (data->check_prefix) {
2638 if (data->first_check_printed) {
2639 printf("// %s-NEXT: ", data->check_prefix);
2640 } else {
2641 printf("// %s : ", data->check_prefix);
2642 data->first_check_printed = 1;
2643 }
2644 }
2645}
2646
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002647static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002648 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002649 printf("%s", clang_getCString(filename));
2650 clang_disposeString(filename);
2651}
2652
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002653static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2654 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002655 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002656 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002657 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002658 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002659 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002660
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002661 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002662 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2663 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002664 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002665 return;
2666 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002667 if (!file) {
2668 printf("<no idxfile>");
2669 return;
2670 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002671 filename = clang_getFileName((CXFile)file);
2672 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002673 if (strcmp(cname, index_data->main_filename) == 0)
2674 isMainFile = 1;
2675 else
2676 isMainFile = 0;
2677 clang_disposeString(filename);
2678
2679 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002680 printCXIndexFile(file);
2681 printf(":");
2682 }
2683 printf("%d:%d", line, column);
2684}
2685
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002686static unsigned digitCount(unsigned val) {
2687 unsigned c = 1;
2688 while (1) {
2689 if (val < 10)
2690 return c;
2691 ++c;
2692 val /= 10;
2693 }
2694}
2695
Nico Weberdf686022014-05-07 21:09:42 +00002696static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2697 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002698 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002699 IndexData *index_data;
2700 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002701 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002702 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002703 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002704 unsigned line, column;
2705
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002706 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002707 if (!name)
2708 name = "<anon-tag>";
2709
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002710 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002711
2712 node =
2713 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2714 digitCount(line) + digitCount(column) + 2);
2715 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002716 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002717
2718 /* Remember string so it can be freed later. */
2719 index_data = (IndexData *)client_data;
2720 node->next = index_data->strings;
2721 index_data->strings = node;
2722
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002723 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002724}
2725
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002726static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2727 CXIdxClientContainer container;
2728 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002729 if (!container)
2730 printf("[<<NULL>>]");
2731 else
2732 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002733}
2734
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002735static const char *getEntityKindString(CXIdxEntityKind kind) {
2736 switch (kind) {
2737 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2738 case CXIdxEntity_Typedef: return "typedef";
2739 case CXIdxEntity_Function: return "function";
2740 case CXIdxEntity_Variable: return "variable";
2741 case CXIdxEntity_Field: return "field";
2742 case CXIdxEntity_EnumConstant: return "enumerator";
2743 case CXIdxEntity_ObjCClass: return "objc-class";
2744 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2745 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002746 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2747 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002748 case CXIdxEntity_ObjCProperty: return "objc-property";
2749 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2750 case CXIdxEntity_Enum: return "enum";
2751 case CXIdxEntity_Struct: return "struct";
2752 case CXIdxEntity_Union: return "union";
2753 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002754 case CXIdxEntity_CXXNamespace: return "namespace";
2755 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2756 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2757 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2758 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2759 case CXIdxEntity_CXXConstructor: return "constructor";
2760 case CXIdxEntity_CXXDestructor: return "destructor";
2761 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2762 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002763 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002764 }
2765 assert(0 && "Garbage entity kind");
2766 return 0;
2767}
2768
2769static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2770 switch (kind) {
2771 case CXIdxEntity_NonTemplate: return "";
2772 case CXIdxEntity_Template: return "-template";
2773 case CXIdxEntity_TemplatePartialSpecialization:
2774 return "-template-partial-spec";
2775 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002776 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002777 assert(0 && "Garbage entity kind");
2778 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002779}
2780
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002781static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2782 switch (kind) {
2783 case CXIdxEntityLang_None: return "<none>";
2784 case CXIdxEntityLang_C: return "C";
2785 case CXIdxEntityLang_ObjC: return "ObjC";
2786 case CXIdxEntityLang_CXX: return "C++";
2787 }
2788 assert(0 && "Garbage language kind");
2789 return 0;
2790}
2791
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002792static void printEntityInfo(const char *cb,
2793 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002794 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002795 const char *name;
2796 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002797 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002798 index_data = (IndexData *)client_data;
2799 printCheck(index_data);
2800
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002801 if (!info) {
2802 printf("%s: <<NULL>>", cb);
2803 return;
2804 }
2805
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002806 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002807 if (!name)
2808 name = "<anon-tag>";
2809
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002810 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2811 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002812 printf(" | name: %s", name);
2813 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002814 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002815
2816 for (i = 0; i != info->numAttributes; ++i) {
2817 const CXIdxAttrInfo *Attr = info->attributes[i];
2818 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002819 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002820 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002821}
2822
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002823static void printBaseClassInfo(CXClientData client_data,
2824 const CXIdxBaseClassInfo *info) {
2825 printEntityInfo(" <base>", client_data, info->base);
2826 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002827 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002828 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002829 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002830}
2831
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002832static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2833 CXClientData client_data) {
2834 unsigned i;
2835 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2836 printEntityInfo(" <protocol>", client_data,
2837 ProtoInfo->protocols[i]->protocol);
2838 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002839 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002840 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002841 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002842 printf("\n");
2843 }
2844}
2845
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002846static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002847 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002848 CXString str;
2849 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002850 unsigned numDiags, i;
2851 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002852 IndexData *index_data;
2853 index_data = (IndexData *)client_data;
2854 printCheck(index_data);
2855
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002856 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2857 for (i = 0; i != numDiags; ++i) {
2858 diag = clang_getDiagnosticInSet(diagSet, i);
2859 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2860 cstr = clang_getCString(str);
2861 printf("[diagnostic]: %s\n", cstr);
2862 clang_disposeString(str);
2863
2864 if (getenv("CINDEXTEST_FAILONERROR") &&
2865 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2866 index_data->fail_for_error = 1;
2867 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002868 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002869}
2870
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002871static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2872 CXFile file, void *reserved) {
2873 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002874 CXString filename;
2875
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002876 index_data = (IndexData *)client_data;
2877 printCheck(index_data);
2878
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002879 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002880 index_data->main_filename = clang_getCString(filename);
2881 clang_disposeString(filename);
2882
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002883 printf("[enteredMainFile]: ");
2884 printCXIndexFile((CXIdxClientFile)file);
2885 printf("\n");
2886
2887 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002888}
2889
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002890static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002891 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002892 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002893 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002894 index_data = (IndexData *)client_data;
2895 printCheck(index_data);
2896
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002897 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002898 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002899 printf(" | name: \"%s\"", info->filename);
2900 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002901 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002902 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002903 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002904
2905 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
2906 if (Mod) {
2907 CXString str = clang_Module_getFullName(Mod);
2908 const char *cstr = clang_getCString(str);
2909 printf(" | module: %s", cstr);
2910 clang_disposeString(str);
2911 }
2912
2913 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002914
2915 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002916}
2917
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002918static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2919 const CXIdxImportedASTFileInfo *info) {
2920 IndexData *index_data;
2921 index_data = (IndexData *)client_data;
2922 printCheck(index_data);
2923
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002924 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002925 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002926 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2927 clang_disposeString(filename);
2928 }
2929
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002930 printf("[importedASTFile]: ");
2931 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002932 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002933 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002934 printf(" | loc: ");
2935 printCXIndexLoc(info->loc, client_data);
2936 printf(" | name: \"%s\"", clang_getCString(name));
2937 printf(" | isImplicit: %d\n", info->isImplicit);
2938 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002939 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00002940 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002941 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002942 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002943
2944 return (CXIdxClientFile)info->file;
2945}
2946
Nico Weber8d19dff2014-05-07 21:05:22 +00002947static CXIdxClientContainer
2948index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002949 IndexData *index_data;
2950 index_data = (IndexData *)client_data;
2951 printCheck(index_data);
2952
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002953 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002954 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002955}
2956
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002957static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002958 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002959 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002960 const CXIdxObjCCategoryDeclInfo *CatInfo;
2961 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002962 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002963 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002964 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002965 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002966 index_data = (IndexData *)client_data;
2967
2968 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2969 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002970 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002971 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002972 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00002973 printf(" | semantic-container: ");
2974 printCXIndexContainer(info->semanticContainer);
2975 printf(" | lexical-container: ");
2976 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002977 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002978 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00002979 if (info->flags & CXIdxDeclFlag_Skipped) {
2980 assert(!info->isContainer);
2981 printf(" | isContainer: skipped");
2982 } else {
2983 printf(" | isContainer: %d", info->isContainer);
2984 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002985 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002986
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002987 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00002988 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002989 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002990 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002991 printf("\n");
2992 }
2993
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002994 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
2995 const char *kindName = 0;
2996 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
2997 switch (K) {
2998 case CXIdxObjCContainer_ForwardRef:
2999 kindName = "forward-ref"; break;
3000 case CXIdxObjCContainer_Interface:
3001 kindName = "interface"; break;
3002 case CXIdxObjCContainer_Implementation:
3003 kindName = "implementation"; break;
3004 }
3005 printCheck(index_data);
3006 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3007 }
3008
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003009 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003010 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3011 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003012 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003013 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003014 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003015 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003016 printf("\n");
3017 }
3018
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003019 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3020 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003021 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003022 printf("\n");
3023 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003024 }
3025
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003026 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3027 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003028 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003029
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003030 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3031 if (PropInfo->getter) {
3032 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3033 printf("\n");
3034 }
3035 if (PropInfo->setter) {
3036 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3037 printf("\n");
3038 }
3039 }
3040
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003041 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3042 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3043 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3044 printf("\n");
3045 }
3046 }
3047
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003048 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003049 clang_index_setClientContainer(
3050 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003051 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003052}
3053
3054static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003055 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003056 printEntityInfo("[indexEntityReference]", client_data,
3057 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003058 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003059 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003060 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003061 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003062 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003063 printf(" | container: ");
3064 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003065 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003066 switch (info->kind) {
3067 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003068 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003069 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003070 printf("\n");
3071}
3072
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003073static int index_abortQuery(CXClientData client_data, void *reserved) {
3074 IndexData *index_data;
3075 index_data = (IndexData *)client_data;
3076 return index_data->abort;
3077}
3078
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003079static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003080 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003081 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003082 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003083 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003084 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003085 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003086 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003087 index_indexEntityReference
3088};
3089
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003090static unsigned getIndexOptions(void) {
3091 unsigned index_opts;
3092 index_opts = 0;
3093 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3094 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3095 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3096 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003097 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3098 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003099
3100 return index_opts;
3101}
3102
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003103static int index_compile_args(int num_args, const char **args,
3104 CXIndexAction idxAction,
3105 ImportedASTFilesData *importedASTs,
3106 const char *check_prefix) {
3107 IndexData index_data;
3108 unsigned index_opts;
3109 int result;
3110
3111 if (num_args == 0) {
3112 fprintf(stderr, "no compiler arguments\n");
3113 return -1;
3114 }
3115
3116 index_data.check_prefix = check_prefix;
3117 index_data.first_check_printed = 0;
3118 index_data.fail_for_error = 0;
3119 index_data.abort = 0;
3120 index_data.main_filename = "";
3121 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003122 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003123 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003124
3125 index_opts = getIndexOptions();
3126 result = clang_indexSourceFile(idxAction, &index_data,
3127 &IndexCB,sizeof(IndexCB), index_opts,
3128 0, args, num_args, 0, 0, 0,
3129 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003130 if (result != CXError_Success)
3131 describeLibclangFailure(result);
3132
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003133 if (index_data.fail_for_error)
3134 result = -1;
3135
Nico Weberdf686022014-05-07 21:09:42 +00003136 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003137 return result;
3138}
3139
3140static int index_ast_file(const char *ast_file,
3141 CXIndex Idx,
3142 CXIndexAction idxAction,
3143 ImportedASTFilesData *importedASTs,
3144 const char *check_prefix) {
3145 CXTranslationUnit TU;
3146 IndexData index_data;
3147 unsigned index_opts;
3148 int result;
3149
3150 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3151 return -1;
3152
3153 index_data.check_prefix = check_prefix;
3154 index_data.first_check_printed = 0;
3155 index_data.fail_for_error = 0;
3156 index_data.abort = 0;
3157 index_data.main_filename = "";
3158 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003159 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003160 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003161
3162 index_opts = getIndexOptions();
3163 result = clang_indexTranslationUnit(idxAction, &index_data,
3164 &IndexCB,sizeof(IndexCB),
3165 index_opts, TU);
3166 if (index_data.fail_for_error)
3167 result = -1;
3168
3169 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003170 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003171 return result;
3172}
3173
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003174static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003175 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003176 CXIndex Idx;
3177 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003178 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003179 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003180
3181 check_prefix = 0;
3182 if (argc > 0) {
3183 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3184 check_prefix = argv[0] + strlen("-check-prefix=");
3185 ++argv;
3186 --argc;
3187 }
3188 }
3189
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003190 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003191 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003192 fprintf(stderr, "Could not create Index\n");
3193 return 1;
3194 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003195 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003196 importedASTs = 0;
3197 if (full)
3198 importedASTs = importedASTs_create();
3199
3200 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3201 if (result != 0)
3202 goto finished;
3203
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003204 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003205 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003206 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3207 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3208 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003209 }
3210 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003211
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003212finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003213 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003214 clang_IndexAction_dispose(idxAction);
3215 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003216 return result;
3217}
3218
3219static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003220 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003221 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003222 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003223 int result;
3224
3225 check_prefix = 0;
3226 if (argc > 0) {
3227 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3228 check_prefix = argv[0] + strlen("-check-prefix=");
3229 ++argv;
3230 --argc;
3231 }
3232 }
3233
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003234 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003235 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003236 fprintf(stderr, "Could not create Index\n");
3237 return 1;
3238 }
3239 idxAction = clang_IndexAction_create(Idx);
3240
3241 result = index_ast_file(argv[0], Idx, idxAction,
3242 /*importedASTs=*/0, check_prefix);
3243
3244 clang_IndexAction_dispose(idxAction);
3245 clang_disposeIndex(Idx);
3246 return result;
3247}
3248
3249static int index_compile_db(int argc, const char **argv) {
3250 const char *check_prefix;
3251 CXIndex Idx;
3252 CXIndexAction idxAction;
3253 int errorCode = 0;
3254
3255 check_prefix = 0;
3256 if (argc > 0) {
3257 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3258 check_prefix = argv[0] + strlen("-check-prefix=");
3259 ++argv;
3260 --argc;
3261 }
3262 }
3263
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003264 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003265 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003266 return -1;
3267 }
3268
3269 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003270 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003271 fprintf(stderr, "Could not create Index\n");
3272 return 1;
3273 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003274 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003275
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003276 {
3277 const char *database = argv[0];
3278 CXCompilationDatabase db = 0;
3279 CXCompileCommands CCmds = 0;
3280 CXCompileCommand CCmd;
3281 CXCompilationDatabase_Error ec;
3282 CXString wd;
3283#define MAX_COMPILE_ARGS 512
3284 CXString cxargs[MAX_COMPILE_ARGS];
3285 const char *args[MAX_COMPILE_ARGS];
3286 char *tmp;
3287 unsigned len;
3288 char *buildDir;
3289 int i, a, numCmds, numArgs;
3290
3291 len = strlen(database);
3292 tmp = (char *) malloc(len+1);
3293 memcpy(tmp, database, len+1);
3294 buildDir = dirname(tmp);
3295
3296 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3297
3298 if (db) {
3299
3300 if (ec!=CXCompilationDatabase_NoError) {
3301 printf("unexpected error %d code while loading compilation database\n", ec);
3302 errorCode = -1;
3303 goto cdb_end;
3304 }
3305
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003306 if (chdir(buildDir) != 0) {
3307 printf("Could not chdir to %s\n", buildDir);
3308 errorCode = -1;
3309 goto cdb_end;
3310 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003311
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003312 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003313 if (!CCmds) {
3314 printf("compilation db is empty\n");
3315 errorCode = -1;
3316 goto cdb_end;
3317 }
3318
3319 numCmds = clang_CompileCommands_getSize(CCmds);
3320
3321 if (numCmds==0) {
3322 fprintf(stderr, "should not get an empty compileCommand set\n");
3323 errorCode = -1;
3324 goto cdb_end;
3325 }
3326
3327 for (i=0; i<numCmds && errorCode == 0; ++i) {
3328 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3329
3330 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003331 if (chdir(clang_getCString(wd)) != 0) {
3332 printf("Could not chdir to %s\n", clang_getCString(wd));
3333 errorCode = -1;
3334 goto cdb_end;
3335 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003336 clang_disposeString(wd);
3337
3338 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3339 if (numArgs > MAX_COMPILE_ARGS){
3340 fprintf(stderr, "got more compile arguments than maximum\n");
3341 errorCode = -1;
3342 goto cdb_end;
3343 }
3344 for (a=0; a<numArgs; ++a) {
3345 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3346 args[a] = clang_getCString(cxargs[a]);
3347 }
3348
3349 errorCode = index_compile_args(numArgs, args, idxAction,
3350 /*importedASTs=*/0, check_prefix);
3351
3352 for (a=0; a<numArgs; ++a)
3353 clang_disposeString(cxargs[a]);
3354 }
3355 } else {
3356 printf("database loading failed with error code %d.\n", ec);
3357 errorCode = -1;
3358 }
3359
3360 cdb_end:
3361 clang_CompileCommands_dispose(CCmds);
3362 clang_CompilationDatabase_dispose(db);
3363 free(tmp);
3364
3365 }
3366
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003367 clang_IndexAction_dispose(idxAction);
3368 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003369 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003370}
3371
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003372int perform_token_annotation(int argc, const char **argv) {
3373 const char *input = argv[1];
3374 char *filename = 0;
3375 unsigned line, second_line;
3376 unsigned column, second_column;
3377 CXIndex CIdx;
3378 CXTranslationUnit TU = 0;
3379 int errorCode;
3380 struct CXUnsavedFile *unsaved_files = 0;
3381 int num_unsaved_files = 0;
3382 CXToken *tokens;
3383 unsigned num_tokens;
3384 CXSourceRange range;
3385 CXSourceLocation startLoc, endLoc;
3386 CXFile file = 0;
3387 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003388 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003389 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003390 unsigned i;
3391
3392 input += strlen("-test-annotate-tokens=");
3393 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3394 &second_line, &second_column)))
3395 return errorCode;
3396
Richard Smith1ea42eb2012-07-05 08:20:49 +00003397 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3398 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003399 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003400 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003401
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003402 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003403 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3404 argv + num_unsaved_files + 2,
3405 argc - num_unsaved_files - 3,
3406 unsaved_files,
3407 num_unsaved_files,
3408 getDefaultParsingOptions(), &TU);
3409 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003410 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003411 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003412 clang_disposeIndex(CIdx);
3413 free(filename);
3414 free_remapped_files(unsaved_files, num_unsaved_files);
3415 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003416 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003417 errorCode = 0;
3418
Richard Smith1ea42eb2012-07-05 08:20:49 +00003419 if (checkForErrors(TU) != 0) {
3420 errorCode = -1;
3421 goto teardown;
3422 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003423
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003424 if (getenv("CINDEXTEST_EDITING")) {
3425 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003426 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3427 clang_defaultReparseOptions(TU));
3428 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003429 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003430 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003431 errorCode = -1;
3432 goto teardown;
3433 }
3434 }
3435 }
3436
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003437 if (checkForErrors(TU) != 0) {
3438 errorCode = -1;
3439 goto teardown;
3440 }
3441
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003442 file = clang_getFile(TU, filename);
3443 if (!file) {
3444 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3445 errorCode = -1;
3446 goto teardown;
3447 }
3448
3449 startLoc = clang_getLocation(TU, file, line, column);
3450 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003451 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003452 column);
3453 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003454 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003455 }
3456
3457 endLoc = clang_getLocation(TU, file, second_line, second_column);
3458 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003459 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003460 second_line, second_column);
3461 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003462 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003463 }
3464
3465 range = clang_getRange(startLoc, endLoc);
3466 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003467
3468 if (checkForErrors(TU) != 0) {
3469 errorCode = -1;
3470 goto teardown;
3471 }
3472
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003473 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3474 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003475
3476 if (checkForErrors(TU) != 0) {
3477 errorCode = -1;
3478 goto teardown;
3479 }
3480
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003481 skipped_ranges = clang_getSkippedRanges(TU, file);
3482 for (i = 0; i != skipped_ranges->count; ++i) {
3483 unsigned start_line, start_column, end_line, end_column;
3484 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3485 0, &start_line, &start_column, 0);
3486 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3487 0, &end_line, &end_column, 0);
3488 printf("Skipping: ");
3489 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3490 printf("\n");
3491 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003492 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003493
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003494 for (i = 0; i != num_tokens; ++i) {
3495 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003496 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3497 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003498 unsigned start_line, start_column, end_line, end_column;
3499
3500 switch (clang_getTokenKind(tokens[i])) {
3501 case CXToken_Punctuation: kind = "Punctuation"; break;
3502 case CXToken_Keyword: kind = "Keyword"; break;
3503 case CXToken_Identifier: kind = "Identifier"; break;
3504 case CXToken_Literal: kind = "Literal"; break;
3505 case CXToken_Comment: kind = "Comment"; break;
3506 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003507 clang_getSpellingLocation(clang_getRangeStart(extent),
3508 0, &start_line, &start_column, 0);
3509 clang_getSpellingLocation(clang_getRangeEnd(extent),
3510 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003511 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003512 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003513 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003514 if (!clang_isInvalid(cursors[i].kind)) {
3515 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003516 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003517 }
3518 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003519 }
3520 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003521 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003522
3523 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003524 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003525 clang_disposeTranslationUnit(TU);
3526 clang_disposeIndex(CIdx);
3527 free(filename);
3528 free_remapped_files(unsaved_files, num_unsaved_files);
3529 return errorCode;
3530}
3531
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003532static int
3533perform_test_compilation_db(const char *database, int argc, const char **argv) {
3534 CXCompilationDatabase db;
3535 CXCompileCommands CCmds;
3536 CXCompileCommand CCmd;
3537 CXCompilationDatabase_Error ec;
3538 CXString wd;
3539 CXString arg;
3540 int errorCode = 0;
3541 char *tmp;
3542 unsigned len;
3543 char *buildDir;
3544 int i, j, a, numCmds, numArgs;
3545
3546 len = strlen(database);
3547 tmp = (char *) malloc(len+1);
3548 memcpy(tmp, database, len+1);
3549 buildDir = dirname(tmp);
3550
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003551 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003552
3553 if (db) {
3554
3555 if (ec!=CXCompilationDatabase_NoError) {
3556 printf("unexpected error %d code while loading compilation database\n", ec);
3557 errorCode = -1;
3558 goto cdb_end;
3559 }
3560
3561 for (i=0; i<argc && errorCode==0; ) {
3562 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003563 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003564
3565 if (!CCmds) {
3566 printf("file %s not found in compilation db\n", argv[i+1]);
3567 errorCode = -1;
3568 break;
3569 }
3570
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003571 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003572
3573 if (numCmds==0) {
3574 fprintf(stderr, "should not get an empty compileCommand set for file"
3575 " '%s'\n", argv[i+1]);
3576 errorCode = -1;
3577 break;
3578 }
3579
3580 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003581 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003582
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003583 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003584 printf("workdir:'%s'", clang_getCString(wd));
3585 clang_disposeString(wd);
3586
3587 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003588 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003589 for (a=0; a<numArgs; ++a) {
3590 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003591 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003592 printf("%s", clang_getCString(arg));
3593 clang_disposeString(arg);
3594 }
3595 printf("'\n");
3596 }
3597
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003598 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003599
3600 i += 2;
3601 }
3602 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003603 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003604 } else {
3605 printf("database loading failed with error code %d.\n", ec);
3606 errorCode = -1;
3607 }
3608
3609cdb_end:
3610 free(tmp);
3611
3612 return errorCode;
3613}
3614
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003615/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003616/* USR printing. */
3617/******************************************************************************/
3618
3619static int insufficient_usr(const char *kind, const char *usage) {
3620 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3621 return 1;
3622}
3623
3624static unsigned isUSR(const char *s) {
3625 return s[0] == 'c' && s[1] == ':';
3626}
3627
3628static int not_usr(const char *s, const char *arg) {
3629 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3630 return 1;
3631}
3632
3633static void print_usr(CXString usr) {
3634 const char *s = clang_getCString(usr);
3635 printf("%s\n", s);
3636 clang_disposeString(usr);
3637}
3638
3639static void display_usrs() {
3640 fprintf(stderr, "-print-usrs options:\n"
3641 " ObjCCategory <class name> <category name>\n"
3642 " ObjCClass <class name>\n"
3643 " ObjCIvar <ivar name> <class USR>\n"
3644 " ObjCMethod <selector> [0=class method|1=instance method] "
3645 "<class USR>\n"
3646 " ObjCProperty <property name> <class USR>\n"
3647 " ObjCProtocol <protocol name>\n");
3648}
3649
3650int print_usrs(const char **I, const char **E) {
3651 while (I != E) {
3652 const char *kind = *I;
3653 unsigned len = strlen(kind);
3654 switch (len) {
3655 case 8:
3656 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3657 if (I + 2 >= E)
3658 return insufficient_usr(kind, "<ivar name> <class USR>");
3659 if (!isUSR(I[2]))
3660 return not_usr("<class USR>", I[2]);
3661 else {
3662 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003663 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003664 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003665 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3666 }
3667
3668 I += 3;
3669 continue;
3670 }
3671 break;
3672 case 9:
3673 if (memcmp(kind, "ObjCClass", 9) == 0) {
3674 if (I + 1 >= E)
3675 return insufficient_usr(kind, "<class name>");
3676 print_usr(clang_constructUSR_ObjCClass(I[1]));
3677 I += 2;
3678 continue;
3679 }
3680 break;
3681 case 10:
3682 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3683 if (I + 3 >= E)
3684 return insufficient_usr(kind, "<method selector> "
3685 "[0=class method|1=instance method] <class USR>");
3686 if (!isUSR(I[3]))
3687 return not_usr("<class USR>", I[3]);
3688 else {
3689 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003690 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003691 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003692 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3693 }
3694 I += 4;
3695 continue;
3696 }
3697 break;
3698 case 12:
3699 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3700 if (I + 2 >= E)
3701 return insufficient_usr(kind, "<class name> <category name>");
3702 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3703 I += 3;
3704 continue;
3705 }
3706 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3707 if (I + 1 >= E)
3708 return insufficient_usr(kind, "<protocol name>");
3709 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3710 I += 2;
3711 continue;
3712 }
3713 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3714 if (I + 2 >= E)
3715 return insufficient_usr(kind, "<property name> <class USR>");
3716 if (!isUSR(I[2]))
3717 return not_usr("<class USR>", I[2]);
3718 else {
3719 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003720 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003721 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003722 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3723 }
3724 I += 3;
3725 continue;
3726 }
3727 break;
3728 default:
3729 break;
3730 }
3731 break;
3732 }
3733
3734 if (I != E) {
3735 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3736 display_usrs();
3737 return 1;
3738 }
3739 return 0;
3740}
3741
3742int print_usrs_file(const char *file_name) {
3743 char line[2048];
3744 const char *args[128];
3745 unsigned numChars = 0;
3746
3747 FILE *fp = fopen(file_name, "r");
3748 if (!fp) {
3749 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3750 return 1;
3751 }
3752
3753 /* This code is not really all that safe, but it works fine for testing. */
3754 while (!feof(fp)) {
3755 char c = fgetc(fp);
3756 if (c == '\n') {
3757 unsigned i = 0;
3758 const char *s = 0;
3759
3760 if (numChars == 0)
3761 continue;
3762
3763 line[numChars] = '\0';
3764 numChars = 0;
3765
3766 if (line[0] == '/' && line[1] == '/')
3767 continue;
3768
3769 s = strtok(line, " ");
3770 while (s) {
3771 args[i] = s;
3772 ++i;
3773 s = strtok(0, " ");
3774 }
3775 if (print_usrs(&args[0], &args[i]))
3776 return 1;
3777 }
3778 else
3779 line[numChars++] = c;
3780 }
3781
3782 fclose(fp);
3783 return 0;
3784}
3785
3786/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003787/* Command line processing. */
3788/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003789int write_pch_file(const char *filename, int argc, const char *argv[]) {
3790 CXIndex Idx;
3791 CXTranslationUnit TU;
3792 struct CXUnsavedFile *unsaved_files = 0;
3793 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003794 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003795 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003796
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003797 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003798
3799 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3800 clang_disposeIndex(Idx);
3801 return -1;
3802 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003803
3804 Err = clang_parseTranslationUnit2(
3805 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3806 unsaved_files, num_unsaved_files,
3807 CXTranslationUnit_Incomplete |
3808 CXTranslationUnit_DetailedPreprocessingRecord |
3809 CXTranslationUnit_ForSerialization,
3810 &TU);
3811 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003812 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003813 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003814 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003815 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003816 clang_disposeIndex(Idx);
3817 return 1;
3818 }
3819
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003820 switch (clang_saveTranslationUnit(TU, filename,
3821 clang_defaultSaveOptions(TU))) {
3822 case CXSaveError_None:
3823 break;
3824
3825 case CXSaveError_TranslationErrors:
3826 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3827 filename);
3828 result = 2;
3829 break;
3830
3831 case CXSaveError_InvalidTU:
3832 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3833 filename);
3834 result = 3;
3835 break;
3836
3837 case CXSaveError_Unknown:
3838 default:
3839 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3840 result = 1;
3841 break;
3842 }
3843
Douglas Gregore9386682010-08-13 05:36:37 +00003844 clang_disposeTranslationUnit(TU);
3845 free_remapped_files(unsaved_files, num_unsaved_files);
3846 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003847 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003848}
3849
3850/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003851/* Serialized diagnostics. */
3852/******************************************************************************/
3853
3854static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3855 switch (error) {
3856 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3857 case CXLoadDiag_None: break;
3858 case CXLoadDiag_Unknown: return "Unknown";
3859 case CXLoadDiag_InvalidFile: return "Invalid File";
3860 }
3861 return "None";
3862}
3863
3864static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3865 switch (severity) {
3866 case CXDiagnostic_Note: return "note";
3867 case CXDiagnostic_Error: return "error";
3868 case CXDiagnostic_Fatal: return "fatal";
3869 case CXDiagnostic_Ignored: return "ignored";
3870 case CXDiagnostic_Warning: return "warning";
3871 }
3872 return "unknown";
3873}
3874
3875static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003876 if (indent == 0)
3877 return;
3878 fprintf(stderr, "+");
3879 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003880 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003881 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003882 --indent;
3883 }
3884}
3885
3886static void printLocation(CXSourceLocation L) {
3887 CXFile File;
3888 CXString FileName;
3889 unsigned line, column, offset;
3890
3891 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3892 FileName = clang_getFileName(File);
3893
3894 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3895 clang_disposeString(FileName);
3896}
3897
3898static void printRanges(CXDiagnostic D, unsigned indent) {
3899 unsigned i, n = clang_getDiagnosticNumRanges(D);
3900
3901 for (i = 0; i < n; ++i) {
3902 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003903 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003904 Start = clang_getRangeStart(SR);
3905 End = clang_getRangeEnd(SR);
3906
3907 printIndent(indent);
3908 fprintf(stderr, "Range: ");
3909 printLocation(Start);
3910 fprintf(stderr, " ");
3911 printLocation(End);
3912 fprintf(stderr, "\n");
3913 }
3914}
3915
3916static void printFixIts(CXDiagnostic D, unsigned indent) {
3917 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003918 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003919 for (i = 0 ; i < n; ++i) {
3920 CXSourceRange ReplacementRange;
3921 CXString text;
3922 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3923
3924 printIndent(indent);
3925 fprintf(stderr, "FIXIT: (");
3926 printLocation(clang_getRangeStart(ReplacementRange));
3927 fprintf(stderr, " - ");
3928 printLocation(clang_getRangeEnd(ReplacementRange));
3929 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3930 clang_disposeString(text);
3931 }
3932}
3933
3934static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003935 unsigned i, n;
3936
Ted Kremenekd010ba42011-11-10 08:43:12 +00003937 if (!Diags)
3938 return;
3939
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003940 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003941 for (i = 0; i < n; ++i) {
3942 CXSourceLocation DiagLoc;
3943 CXDiagnostic D;
3944 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003945 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003946 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003947 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003948
3949 D = clang_getDiagnosticInSet(Diags, i);
3950 DiagLoc = clang_getDiagnosticLocation(D);
3951 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3952 FileName = clang_getFileName(File);
3953 DiagSpelling = clang_getDiagnosticSpelling(D);
3954
3955 printIndent(indent);
3956
3957 fprintf(stderr, "%s:%d:%d: %s: %s",
3958 clang_getCString(FileName),
3959 line,
3960 column,
3961 getSeverityString(clang_getDiagnosticSeverity(D)),
3962 clang_getCString(DiagSpelling));
3963
3964 DiagOption = clang_getDiagnosticOption(D, 0);
3965 DiagOptionStr = clang_getCString(DiagOption);
3966 if (DiagOptionStr) {
3967 fprintf(stderr, " [%s]", DiagOptionStr);
3968 }
3969
Ted Kremenek26a6d492012-04-12 00:03:31 +00003970 DiagCat = clang_getDiagnosticCategoryText(D);
3971 DiagCatStr = clang_getCString(DiagCat);
3972 if (DiagCatStr) {
3973 fprintf(stderr, " [%s]", DiagCatStr);
3974 }
3975
Ted Kremenekd010ba42011-11-10 08:43:12 +00003976 fprintf(stderr, "\n");
3977
3978 printRanges(D, indent);
3979 printFixIts(D, indent);
3980
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00003981 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00003982 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
3983
3984 clang_disposeString(FileName);
3985 clang_disposeString(DiagSpelling);
3986 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00003987 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003988 }
3989}
3990
3991static int read_diagnostics(const char *filename) {
3992 enum CXLoadDiag_Error error;
3993 CXString errorString;
3994 CXDiagnosticSet Diags = 0;
3995
3996 Diags = clang_loadDiagnostics(filename, &error, &errorString);
3997 if (!Diags) {
3998 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
3999 getDiagnosticCodeStr(error),
4000 clang_getCString(errorString));
4001 clang_disposeString(errorString);
4002 return 1;
4003 }
4004
4005 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004006 fprintf(stderr, "Number of diagnostics: %d\n",
4007 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004008 clang_disposeDiagnosticSet(Diags);
4009 return 0;
4010}
4011
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004012static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004013 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004014 return 0;
4015}
4016
Ted Kremenekd010ba42011-11-10 08:43:12 +00004017/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004018/* Command line processing. */
4019/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004020
Douglas Gregor720d0052010-01-20 21:32:04 +00004021static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004022 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004023 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004024 if (strcmp(s, "-usrs") == 0)
4025 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004026 if (strncmp(s, "-memory-usage", 13) == 0)
4027 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004028 return NULL;
4029}
4030
Ted Kremenekef3339b2009-11-17 18:09:14 +00004031static void print_usage(void) {
4032 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004033 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004034 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004035 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004036 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4037 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004038 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004039 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004040 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004041 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004042 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004043 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004044 "[FileCheck prefix]\n");
4045 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004046 " c-index-test -test-load-tu <AST file> <symbol filter> "
4047 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004048 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4049 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004050 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004051 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004052 " c-index-test -test-load-source-memory-usage "
4053 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004054 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4055 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004056 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004057 " c-index-test -test-load-source-usrs-memory-usage "
4058 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004059 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4060 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004061 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004062 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004063 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004064 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004065 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004066 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004067 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004068 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004069 " c-index-test -write-pch <file> <compiler arguments>\n");
4070 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004071 " c-index-test -compilation-db [lookup <filename>] database\n");
4072 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004073 " c-index-test -print-build-session-timestamp\n");
4074 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004075 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004076 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004077 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004078 " all - load all symbols, including those from PCH\n"
4079 " local - load all symbols except those in PCH\n"
4080 " category - only load ObjC categories (non-PCH)\n"
4081 " interface - only load ObjC interfaces (non-PCH)\n"
4082 " protocol - only load ObjC protocols (non-PCH)\n"
4083 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004084 " typedef - only load typdefs (non-PCH)\n"
4085 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004086}
4087
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004088/***/
4089
4090int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004091 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004092 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4093 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004094 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004095 return perform_code_completion(argc, argv, 0);
4096 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4097 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004098 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
4099 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004100 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4101 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004102 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4103 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004104 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004105 return index_file(argc - 2, argv + 2, /*full=*/0);
4106 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4107 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004108 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4109 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004110 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4111 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004112 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004113 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004114 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004115 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4116 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004117 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004118 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4119 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4120 if (I) {
4121 int trials = atoi(argv[2]);
4122 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4123 NULL);
4124 }
4125 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004126 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004127 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004128
4129 PostVisitTU postVisit = 0;
4130 if (strstr(argv[1], "-memory-usage"))
4131 postVisit = PrintMemoryUsage;
4132
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004133 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004134 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4135 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004136 }
4137 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004138 return perform_file_scan(argv[2], argv[3],
4139 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004140 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4141 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004142 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4143 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4144 PrintInclusionStack);
4145 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4146 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4147 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004148 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4149 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4150 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004151 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004152 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004153 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004154 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4155 return perform_test_load_source(argc - 2, argv + 2, "all",
4156 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004157 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4158 return perform_test_load_source(argc - 2, argv + 2, "all",
4159 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004160 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4161 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004162 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4163 if (argc > 2)
4164 return print_usrs(argv + 2, argv + argc);
4165 else {
4166 display_usrs();
4167 return 1;
4168 }
4169 }
4170 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4171 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004172 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4173 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004174 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4175 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004176 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4177 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004178
Ted Kremenekef3339b2009-11-17 18:09:14 +00004179 print_usage();
4180 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004181}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004182
4183/***/
4184
4185/* We intentionally run in a separate thread to ensure we at least minimal
4186 * testing of a multithreaded environment (for example, having a reduced stack
4187 * size). */
4188
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004189typedef struct thread_info {
4190 int argc;
4191 const char **argv;
4192 int result;
4193} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004194void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004195 thread_info *client_data = client_data_v;
4196 client_data->result = cindextest_main(client_data->argc, client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004197}
4198
4199static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004200 /* stdout, and surprisingly even stderr, are not always flushed on process
4201 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004202 fflush(stdout);
4203 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004204}
4205
4206int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004207 thread_info client_data;
4208
Reid Klecknere931c062014-06-05 00:13:43 +00004209 atexit(flush_atexit);
4210
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004211#ifdef CLANG_HAVE_LIBXML
4212 LIBXML_TEST_VERSION
4213#endif
4214
Douglas Gregorf428bf82010-10-27 16:00:01 +00004215 if (getenv("CINDEXTEST_NOTHREADS"))
4216 return cindextest_main(argc, argv);
4217
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004218 client_data.argc = argc;
4219 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004220 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004221 return client_data.result;
4222}