blob: 8181642d71bda0b6c556ad4907b487ad9df2393a [file] [log] [blame]
Steve Naroff69b10fd2009-09-01 15:55:40 +00001/* c-index-test.c */
Steve Naroffa1c72842009-08-28 15:28:48 +00002
Alp Toker1d257e12014-06-04 03:28:55 +00003#include "clang/Config/config.h"
Steve Naroffa1c72842009-08-28 15:28:48 +00004#include "clang-c/Index.h"
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00005#include "clang-c/CXCompilationDatabase.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +00006#include "clang-c/BuildSystem.h"
Alp Toker59c6bc52014-04-28 02:39:27 +00007#include "clang-c/Documentation.h"
Douglas Gregor49f67ce2010-08-26 13:48:20 +00008#include <ctype.h>
Douglas Gregor9eb77012009-11-07 00:00:49 +00009#include <stdlib.h>
Steve Naroff1054e602009-08-31 00:59:03 +000010#include <stdio.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000011#include <string.h>
Douglas Gregor082c3e62010-01-15 19:40:17 +000012#include <assert.h>
Steve Naroff38c1a7b2009-09-03 15:49:00 +000013
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +000014#ifdef CLANG_HAVE_LIBXML
15#include <libxml/parser.h>
16#include <libxml/relaxng.h>
17#include <libxml/xmlerror.h>
18#endif
19
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +000020#ifdef _WIN32
21# include <direct.h>
22#else
23# include <unistd.h>
24#endif
25
Ted Kremenek1cd27d52009-11-17 18:13:31 +000026/******************************************************************************/
27/* Utility functions. */
28/******************************************************************************/
29
John Thompsonde258b52009-10-27 13:42:56 +000030#ifdef _MSC_VER
31char *basename(const char* path)
32{
33 char* base1 = (char*)strrchr(path, '/');
34 char* base2 = (char*)strrchr(path, '\\');
35 if (base1 && base2)
36 return((base1 > base2) ? base1 + 1 : base2 + 1);
37 else if (base1)
38 return(base1 + 1);
39 else if (base2)
40 return(base2 + 1);
41
42 return((char*)path);
43}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000044char *dirname(char* path)
45{
46 char* base1 = (char*)strrchr(path, '/');
47 char* base2 = (char*)strrchr(path, '\\');
48 if (base1 && base2)
49 if (base1 > base2)
50 *base1 = 0;
51 else
52 *base2 = 0;
53 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000054 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000055 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000056 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000057
58 return path;
59}
John Thompsonde258b52009-10-27 13:42:56 +000060#else
Steve Naroffa7753c42009-09-24 20:03:06 +000061extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000062extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000063#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000064
Douglas Gregorf2430ba2010-07-25 17:39:21 +000065/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000066static unsigned getDefaultParsingOptions() {
67 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
68
69 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000070 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000071 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
72 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000073 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
74 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000075 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
76 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000077 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
78 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000079
80 return options;
81}
82
Patrik Hagglund55701d22014-02-17 11:54:08 +000083/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000084static int checkForErrors(CXTranslationUnit TU);
85
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000086static void describeLibclangFailure(enum CXErrorCode Err) {
87 switch (Err) {
88 case CXError_Success:
89 fprintf(stderr, "Success\n");
90 return;
91
92 case CXError_Failure:
93 fprintf(stderr, "Failure (no details available)\n");
94 return;
95
96 case CXError_Crashed:
97 fprintf(stderr, "Failure: libclang crashed\n");
98 return;
99
100 case CXError_InvalidArguments:
101 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
102 return;
103
104 case CXError_ASTReadError:
105 fprintf(stderr, "Failure: AST deserialization error occurred\n");
106 return;
107 }
108}
109
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000110static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
111 unsigned end_line, unsigned end_column) {
112 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000113 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000114}
115
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000116static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
117 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000118 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
119 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000120 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000121 describeLibclangFailure(Err);
122 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000123 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000124 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000125 return 1;
126}
127
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000128void free_remapped_files(struct CXUnsavedFile *unsaved_files,
129 int num_unsaved_files) {
130 int i;
131 for (i = 0; i != num_unsaved_files; ++i) {
132 free((char *)unsaved_files[i].Filename);
133 free((char *)unsaved_files[i].Contents);
134 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000135 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000136}
137
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000138static int parse_remapped_files_with_opt(const char *opt_name,
139 int argc, const char **argv,
140 int start_arg,
141 struct CXUnsavedFile **unsaved_files,
142 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000143 int i;
144 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000145 int prefix_len = strlen(opt_name);
146 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000147 *unsaved_files = 0;
148 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000149
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000150 /* Count the number of remapped files. */
151 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000152 if (strncmp(argv[arg], opt_name, prefix_len))
153 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000154
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000155 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
156 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000157 ++*num_unsaved_files;
158 }
Ted Kremenek29004672010-02-17 00:41:32 +0000159
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000160 if (*num_unsaved_files == 0)
161 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000162
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000163 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000164 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
165 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000166 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000167 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000168 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000169 int filename_len;
170 char *filename;
171 char *contents;
172 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000173 const char *sep = strchr(arg_string, ',');
174 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000175 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000176 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000177 free_remapped_files(*unsaved_files, i);
178 *unsaved_files = 0;
179 *num_unsaved_files = 0;
180 return -1;
181 }
Ted Kremenek29004672010-02-17 00:41:32 +0000182
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000183 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000184 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000185 if (!to_file) {
186 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000187 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000188 free_remapped_files(*unsaved_files, i);
189 *unsaved_files = 0;
190 *num_unsaved_files = 0;
191 return -1;
192 }
Ted Kremenek29004672010-02-17 00:41:32 +0000193
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000194 /* Determine the length of the file we're remapping to. */
195 fseek(to_file, 0, SEEK_END);
196 unsaved->Length = ftell(to_file);
197 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000198
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000199 /* Read the contents of the file we're remapping to. */
200 contents = (char *)malloc(unsaved->Length + 1);
201 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
202 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000203 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000204 fclose(to_file);
205 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000206 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000207 *unsaved_files = 0;
208 *num_unsaved_files = 0;
209 return -1;
210 }
211 contents[unsaved->Length] = 0;
212 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000213
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000214 /* Close the file. */
215 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000216
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000217 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000218 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000219 filename = (char *)malloc(filename_len + 1);
220 memcpy(filename, arg_string, filename_len);
221 filename[filename_len] = 0;
222 unsaved->Filename = filename;
223 }
Ted Kremenek29004672010-02-17 00:41:32 +0000224
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000225 return 0;
226}
227
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000228static int parse_remapped_files(int argc, const char **argv, int start_arg,
229 struct CXUnsavedFile **unsaved_files,
230 int *num_unsaved_files) {
231 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
232 unsaved_files, num_unsaved_files);
233}
234
235static int parse_remapped_files_with_try(int try_idx,
236 int argc, const char **argv,
237 int start_arg,
238 struct CXUnsavedFile **unsaved_files,
239 int *num_unsaved_files) {
240 struct CXUnsavedFile *unsaved_files_no_try_idx;
241 int num_unsaved_files_no_try_idx;
242 struct CXUnsavedFile *unsaved_files_try_idx;
243 int num_unsaved_files_try_idx;
244 int ret;
245 char opt_name[32];
246
247 ret = parse_remapped_files(argc, argv, start_arg,
248 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
249 if (ret)
250 return ret;
251
252 sprintf(opt_name, "-remap-file-%d=", try_idx);
253 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
254 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
255 if (ret)
256 return ret;
257
Chandler Carruth6ac555f2015-08-04 03:53:04 +0000258 if (num_unsaved_files_no_try_idx == 0) {
259 *unsaved_files = unsaved_files_try_idx;
260 *num_unsaved_files = num_unsaved_files_try_idx;
261 return 0;
262 }
263 if (num_unsaved_files_try_idx == 0) {
264 *unsaved_files = unsaved_files_no_try_idx;
265 *num_unsaved_files = num_unsaved_files_no_try_idx;
266 return 0;
267 }
268
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000269 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
270 *unsaved_files
271 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
272 sizeof(struct CXUnsavedFile) *
273 *num_unsaved_files);
274 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
275 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
276 num_unsaved_files_try_idx);
277 free(unsaved_files_try_idx);
278 return 0;
279}
280
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000281static const char *parse_comments_schema(int argc, const char **argv) {
282 const char *CommentsSchemaArg = "-comments-xml-schema=";
283 const char *CommentSchemaFile = NULL;
284
285 if (argc == 0)
286 return CommentSchemaFile;
287
288 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
289 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
290
291 return CommentSchemaFile;
292}
293
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000294/******************************************************************************/
295/* Pretty-printing. */
296/******************************************************************************/
297
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000298static const char *FileCheckPrefix = "CHECK";
299
300static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000301 if (CStr != NULL && CStr[0] != '\0') {
302 for ( ; *CStr; ++CStr) {
303 const char C = *CStr;
304 switch (C) {
305 case '\n': printf("\\n"); break;
306 case '\r': printf("\\r"); break;
307 case '\t': printf("\\t"); break;
308 case '\v': printf("\\v"); break;
309 case '\f': printf("\\f"); break;
310 default: putchar(C); break;
311 }
312 }
313 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000314}
315
316static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
317 printf(" %s=[", Prefix);
318 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000319 printf("]");
320}
321
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000322static void PrintCXStringAndDispose(CXString Str) {
323 PrintCString(clang_getCString(Str));
324 clang_disposeString(Str);
325}
326
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000327static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
328 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
329}
330
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000331static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
332 CXString Str) {
333 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
334 clang_disposeString(Str);
335}
336
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000337static void PrintRange(CXSourceRange R, const char *str) {
338 CXFile begin_file, end_file;
339 unsigned begin_line, begin_column, end_line, end_column;
340
341 clang_getSpellingLocation(clang_getRangeStart(R),
342 &begin_file, &begin_line, &begin_column, 0);
343 clang_getSpellingLocation(clang_getRangeEnd(R),
344 &end_file, &end_line, &end_column, 0);
345 if (!begin_file || !end_file)
346 return;
347
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000348 if (str)
349 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000350 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
351}
352
Douglas Gregor97c75712010-10-02 22:49:11 +0000353int want_display_name = 0;
354
Douglas Gregord6225d32012-05-08 00:14:45 +0000355static void printVersion(const char *Prefix, CXVersion Version) {
356 if (Version.Major < 0)
357 return;
358 printf("%s%d", Prefix, Version.Major);
359
360 if (Version.Minor < 0)
361 return;
362 printf(".%d", Version.Minor);
363
364 if (Version.Subminor < 0)
365 return;
366 printf(".%d", Version.Subminor);
367}
368
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000369struct CommentASTDumpingContext {
370 int IndentLevel;
371};
372
373static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
374 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000375 unsigned i;
376 unsigned e;
377 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
378
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000379 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000380 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000381 printf(" ");
382
383 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000384 switch (Kind) {
385 case CXComment_Null:
386 printf("CXComment_Null");
387 break;
388 case CXComment_Text:
389 printf("CXComment_Text");
390 PrintCXStringWithPrefixAndDispose("Text",
391 clang_TextComment_getText(Comment));
392 if (clang_Comment_isWhitespace(Comment))
393 printf(" IsWhitespace");
394 if (clang_InlineContentComment_hasTrailingNewline(Comment))
395 printf(" HasTrailingNewline");
396 break;
397 case CXComment_InlineCommand:
398 printf("CXComment_InlineCommand");
399 PrintCXStringWithPrefixAndDispose(
400 "CommandName",
401 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000402 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
403 case CXCommentInlineCommandRenderKind_Normal:
404 printf(" RenderNormal");
405 break;
406 case CXCommentInlineCommandRenderKind_Bold:
407 printf(" RenderBold");
408 break;
409 case CXCommentInlineCommandRenderKind_Monospaced:
410 printf(" RenderMonospaced");
411 break;
412 case CXCommentInlineCommandRenderKind_Emphasized:
413 printf(" RenderEmphasized");
414 break;
415 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000416 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000417 i != e; ++i) {
418 printf(" Arg[%u]=", i);
419 PrintCXStringAndDispose(
420 clang_InlineCommandComment_getArgText(Comment, i));
421 }
422 if (clang_InlineContentComment_hasTrailingNewline(Comment))
423 printf(" HasTrailingNewline");
424 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000425 case CXComment_HTMLStartTag: {
426 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000427 printf("CXComment_HTMLStartTag");
428 PrintCXStringWithPrefixAndDispose(
429 "Name",
430 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000431 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000432 if (NumAttrs != 0) {
433 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000434 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000435 printf(" ");
436 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
437 printf("=");
438 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
439 }
440 }
441 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
442 printf(" SelfClosing");
443 if (clang_InlineContentComment_hasTrailingNewline(Comment))
444 printf(" HasTrailingNewline");
445 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000446 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000447 case CXComment_HTMLEndTag:
448 printf("CXComment_HTMLEndTag");
449 PrintCXStringWithPrefixAndDispose(
450 "Name",
451 clang_HTMLTagComment_getTagName(Comment));
452 if (clang_InlineContentComment_hasTrailingNewline(Comment))
453 printf(" HasTrailingNewline");
454 break;
455 case CXComment_Paragraph:
456 printf("CXComment_Paragraph");
457 if (clang_Comment_isWhitespace(Comment))
458 printf(" IsWhitespace");
459 break;
460 case CXComment_BlockCommand:
461 printf("CXComment_BlockCommand");
462 PrintCXStringWithPrefixAndDispose(
463 "CommandName",
464 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000465 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000466 i != e; ++i) {
467 printf(" Arg[%u]=", i);
468 PrintCXStringAndDispose(
469 clang_BlockCommandComment_getArgText(Comment, i));
470 }
471 break;
472 case CXComment_ParamCommand:
473 printf("CXComment_ParamCommand");
474 switch (clang_ParamCommandComment_getDirection(Comment)) {
475 case CXCommentParamPassDirection_In:
476 printf(" in");
477 break;
478 case CXCommentParamPassDirection_Out:
479 printf(" out");
480 break;
481 case CXCommentParamPassDirection_InOut:
482 printf(" in,out");
483 break;
484 }
485 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
486 printf(" explicitly");
487 else
488 printf(" implicitly");
489 PrintCXStringWithPrefixAndDispose(
490 "ParamName",
491 clang_ParamCommandComment_getParamName(Comment));
492 if (clang_ParamCommandComment_isParamIndexValid(Comment))
493 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
494 else
495 printf(" ParamIndex=Invalid");
496 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000497 case CXComment_TParamCommand:
498 printf("CXComment_TParamCommand");
499 PrintCXStringWithPrefixAndDispose(
500 "ParamName",
501 clang_TParamCommandComment_getParamName(Comment));
502 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
503 printf(" ParamPosition={");
504 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
505 i != e; ++i) {
506 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
507 if (i != e - 1)
508 printf(", ");
509 }
510 printf("}");
511 } else
512 printf(" ParamPosition=Invalid");
513 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000514 case CXComment_VerbatimBlockCommand:
515 printf("CXComment_VerbatimBlockCommand");
516 PrintCXStringWithPrefixAndDispose(
517 "CommandName",
518 clang_BlockCommandComment_getCommandName(Comment));
519 break;
520 case CXComment_VerbatimBlockLine:
521 printf("CXComment_VerbatimBlockLine");
522 PrintCXStringWithPrefixAndDispose(
523 "Text",
524 clang_VerbatimBlockLineComment_getText(Comment));
525 break;
526 case CXComment_VerbatimLine:
527 printf("CXComment_VerbatimLine");
528 PrintCXStringWithPrefixAndDispose(
529 "Text",
530 clang_VerbatimLineComment_getText(Comment));
531 break;
532 case CXComment_FullComment:
533 printf("CXComment_FullComment");
534 break;
535 }
536 if (Kind != CXComment_Null) {
537 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000538 unsigned i;
539 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000540 printf("\n// %s: ", FileCheckPrefix);
541 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
542 }
543 }
544 printf(")");
545 Ctx->IndentLevel--;
546}
547
548static void DumpCXComment(CXComment Comment) {
549 struct CommentASTDumpingContext Ctx;
550 Ctx.IndentLevel = 1;
551 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
552 DumpCXCommentInternal(&Ctx, Comment);
553 printf("]");
554}
555
Chandler Carruthb2faa592014-05-02 23:30:59 +0000556static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000557#ifdef CLANG_HAVE_LIBXML
558 xmlRelaxNGParserCtxtPtr RNGParser;
559 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000560 xmlDocPtr Doc;
561 xmlRelaxNGValidCtxtPtr ValidationCtxt;
562 int status;
563
Chandler Carruthb2faa592014-05-02 23:30:59 +0000564 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000565 return;
566
Chandler Carruthb2faa592014-05-02 23:30:59 +0000567 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
568 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000569 printf(" libXMLError");
570 return;
571 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000572 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000573
574 Doc = xmlParseDoc((const xmlChar *) Str);
575
576 if (!Doc) {
577 xmlErrorPtr Error = xmlGetLastError();
578 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
579 return;
580 }
581
Chandler Carruthb2faa592014-05-02 23:30:59 +0000582 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000583 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
584 if (!status)
585 printf(" CommentXMLValid");
586 else if (status > 0) {
587 xmlErrorPtr Error = xmlGetLastError();
588 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
589 } else
590 printf(" libXMLError");
591
592 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
593 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000594 xmlRelaxNGFree(Schema);
595 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000596#endif
597}
598
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000599static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000600 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000601 {
602 CXString RawComment;
603 const char *RawCommentCString;
604 CXString BriefComment;
605 const char *BriefCommentCString;
606
607 RawComment = clang_Cursor_getRawCommentText(Cursor);
608 RawCommentCString = clang_getCString(RawComment);
609 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
610 PrintCStringWithPrefix("RawComment", RawCommentCString);
611 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
612
613 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
614 BriefCommentCString = clang_getCString(BriefComment);
615 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
616 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
617 clang_disposeString(BriefComment);
618 }
619 clang_disposeString(RawComment);
620 }
621
622 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000623 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000624 if (clang_Comment_getKind(Comment) != CXComment_Null) {
625 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
626 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000627 {
628 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000629 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000630 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000631 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000632 clang_disposeString(XML);
633 }
634
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000635 DumpCXComment(Comment);
636 }
637 }
638}
639
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000640typedef struct {
641 unsigned line;
642 unsigned col;
643} LineCol;
644
645static int lineCol_cmp(const void *p1, const void *p2) {
646 const LineCol *lhs = p1;
647 const LineCol *rhs = p2;
648 if (lhs->line != rhs->line)
649 return (int)lhs->line - (int)rhs->line;
650 return (int)lhs->col - (int)rhs->col;
651}
652
Chandler Carruthb2faa592014-05-02 23:30:59 +0000653static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000654 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000655 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000656 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000657 printf("Invalid Cursor => %s", clang_getCString(ks));
658 clang_disposeString(ks);
659 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000660 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000661 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000662 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000663 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000664 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000665 CXCursor *overridden;
666 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000667 unsigned RefNameRangeNr;
668 CXSourceRange CursorExtent;
669 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000670 int AlwaysUnavailable;
671 int AlwaysDeprecated;
672 CXString UnavailableMessage;
673 CXString DeprecatedMessage;
674 CXPlatformAvailability PlatformAvailability[2];
675 int NumPlatformAvailability;
676 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000677
Ted Kremenek29004672010-02-17 00:41:32 +0000678 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000679 string = want_display_name? clang_getCursorDisplayName(Cursor)
680 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000681 printf("%s=%s", clang_getCString(ks),
682 clang_getCString(string));
683 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000684 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000685
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000686 Referenced = clang_getCursorReferenced(Cursor);
687 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000688 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
689 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
690 printf("[");
691 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000692 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000693 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000694 if (I)
695 printf(", ");
696
Douglas Gregor2967e282010-09-14 00:20:32 +0000697 Loc = clang_getCursorLocation(Ovl);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000698 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000699 printf("%d:%d", line, column);
700 }
701 printf("]");
702 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000703 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000704 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000705 printf(":%d:%d", line, column);
706 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000707 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000708
709 if (clang_isCursorDefinition(Cursor))
710 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000711
712 switch (clang_getCursorAvailability(Cursor)) {
713 case CXAvailability_Available:
714 break;
715
716 case CXAvailability_Deprecated:
717 printf(" (deprecated)");
718 break;
719
720 case CXAvailability_NotAvailable:
721 printf(" (unavailable)");
722 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000723
724 case CXAvailability_NotAccessible:
725 printf(" (inaccessible)");
726 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000727 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000728
Douglas Gregord6225d32012-05-08 00:14:45 +0000729 NumPlatformAvailability
730 = clang_getCursorPlatformAvailability(Cursor,
731 &AlwaysDeprecated,
732 &DeprecatedMessage,
733 &AlwaysUnavailable,
734 &UnavailableMessage,
735 PlatformAvailability, 2);
736 if (AlwaysUnavailable) {
737 printf(" (always unavailable: \"%s\")",
738 clang_getCString(UnavailableMessage));
739 } else if (AlwaysDeprecated) {
740 printf(" (always deprecated: \"%s\")",
741 clang_getCString(DeprecatedMessage));
742 } else {
743 for (I = 0; I != NumPlatformAvailability; ++I) {
744 if (I >= 2)
745 break;
746
747 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
748 if (PlatformAvailability[I].Unavailable)
749 printf(", unavailable");
750 else {
751 printVersion(", introduced=", PlatformAvailability[I].Introduced);
752 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
753 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
754 }
755 if (clang_getCString(PlatformAvailability[I].Message)[0])
756 printf(", message=\"%s\"",
757 clang_getCString(PlatformAvailability[I].Message));
758 printf(")");
759 }
760 }
761 for (I = 0; I != NumPlatformAvailability; ++I) {
762 if (I >= 2)
763 break;
764 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
765 }
766
767 clang_disposeString(DeprecatedMessage);
768 clang_disposeString(UnavailableMessage);
769
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000770 if (clang_CXXField_isMutable(Cursor))
771 printf(" (mutable)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000772 if (clang_CXXMethod_isStatic(Cursor))
773 printf(" (static)");
774 if (clang_CXXMethod_isVirtual(Cursor))
775 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000776 if (clang_CXXMethod_isConst(Cursor))
777 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000778 if (clang_CXXMethod_isPureVirtual(Cursor))
779 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000780 if (clang_Cursor_isVariadic(Cursor))
781 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000782 if (clang_Cursor_isObjCOptional(Cursor))
783 printf(" (@optional)");
784
Ted Kremeneka5940822010-08-26 01:42:22 +0000785 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000786 CXType T =
787 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
788 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000789 printf(" [IBOutletCollection=%s]", clang_getCString(S));
790 clang_disposeString(S);
791 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000792
793 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
794 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
795 unsigned isVirtual = clang_isVirtualBase(Cursor);
796 const char *accessStr = 0;
797
798 switch (access) {
799 case CX_CXXInvalidAccessSpecifier:
800 accessStr = "invalid"; break;
801 case CX_CXXPublic:
802 accessStr = "public"; break;
803 case CX_CXXProtected:
804 accessStr = "protected"; break;
805 case CX_CXXPrivate:
806 accessStr = "private"; break;
807 }
808
809 printf(" [access=%s isVirtual=%s]", accessStr,
810 isVirtual ? "true" : "false");
811 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000812
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000813 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
814 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000815 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
816 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000817 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000818 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000819 clang_getCString(Name), line, column);
820 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000821
822 if (Cursor.kind == CXCursor_FunctionDecl) {
823 /* Collect the template parameter kinds from the base template. */
824 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
825 unsigned I;
826 for (I = 0; I < NumTemplateArgs; I++) {
827 enum CXTemplateArgumentKind TAK =
828 clang_Cursor_getTemplateArgumentKind(Cursor, I);
829 switch(TAK) {
830 case CXTemplateArgumentKind_Type:
831 {
832 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
833 CXString S = clang_getTypeSpelling(T);
834 printf(" [Template arg %d: kind: %d, type: %s]",
835 I, TAK, clang_getCString(S));
836 clang_disposeString(S);
837 }
838 break;
839 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000840 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000841 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
842 break;
843 default:
844 printf(" [Template arg %d: kind: %d]\n", I, TAK);
845 }
846 }
847 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000848 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000849
850 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
851 if (num_overridden) {
852 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000853 LineCol lineCols[50];
854 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000855 printf(" [Overrides ");
856 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000857 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000858 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000859 lineCols[I].line = line;
860 lineCols[I].col = column;
861 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000862 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000863 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
864 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000865 if (I)
866 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000867 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000868 }
869 printf("]");
870 clang_disposeOverriddenCursors(overridden);
871 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000872
873 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000874 CXFile File = clang_getIncludedFile(Cursor);
875 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000876 printf(" (%s)", clang_getCString(Included));
877 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000878
879 if (clang_isFileMultipleIncludeGuarded(TU, File))
880 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000881 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000882
883 CursorExtent = clang_getCursorExtent(Cursor);
884 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
885 CXNameRange_WantQualifier
886 | CXNameRange_WantSinglePiece
887 | CXNameRange_WantTemplateArgs,
888 0);
889 if (!clang_equalRanges(CursorExtent, RefNameRange))
890 PrintRange(RefNameRange, "SingleRefName");
891
892 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
893 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
894 CXNameRange_WantQualifier
895 | CXNameRange_WantTemplateArgs,
896 RefNameRangeNr);
897 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
898 break;
899 if (!clang_equalRanges(CursorExtent, RefNameRange))
900 PrintRange(RefNameRange, "RefName");
901 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000902
Chandler Carruthb2faa592014-05-02 23:30:59 +0000903 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000904
905 {
906 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
907 if (PropAttrs != CXObjCPropertyAttr_noattr) {
908 printf(" [");
909 #define PRINT_PROP_ATTR(A) \
910 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
911 PRINT_PROP_ATTR(readonly);
912 PRINT_PROP_ATTR(getter);
913 PRINT_PROP_ATTR(assign);
914 PRINT_PROP_ATTR(readwrite);
915 PRINT_PROP_ATTR(retain);
916 PRINT_PROP_ATTR(copy);
917 PRINT_PROP_ATTR(nonatomic);
918 PRINT_PROP_ATTR(setter);
919 PRINT_PROP_ATTR(atomic);
920 PRINT_PROP_ATTR(weak);
921 PRINT_PROP_ATTR(strong);
922 PRINT_PROP_ATTR(unsafe_unretained);
923 printf("]");
924 }
925 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000926
927 {
928 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
929 if (QT != CXObjCDeclQualifier_None) {
930 printf(" [");
931 #define PRINT_OBJC_QUAL(A) \
932 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
933 PRINT_OBJC_QUAL(In);
934 PRINT_OBJC_QUAL(Inout);
935 PRINT_OBJC_QUAL(Out);
936 PRINT_OBJC_QUAL(Bycopy);
937 PRINT_OBJC_QUAL(Byref);
938 PRINT_OBJC_QUAL(Oneway);
939 printf("]");
940 }
941 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000942 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000943}
Steve Naroff1054e602009-08-31 00:59:03 +0000944
Ted Kremenek29004672010-02-17 00:41:32 +0000945static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000946 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000947 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000948 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000949 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000950 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000951 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000952 clang_disposeString(source);
953 return "<invalid loc>";
954 }
955 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000956 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000957 clang_disposeString(source);
958 return b;
959 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000960}
961
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000962/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000963/* Callbacks. */
964/******************************************************************************/
965
966typedef void (*PostVisitTU)(CXTranslationUnit);
967
Douglas Gregor33cdd812010-02-18 18:08:43 +0000968void PrintDiagnostic(CXDiagnostic Diagnostic) {
969 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000970 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000971 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000972 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000973 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
974 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000975 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000976
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000977 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000978 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000979
Douglas Gregord770f732010-02-22 23:17:23 +0000980 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
981 fprintf(stderr, "%s\n", clang_getCString(Msg));
982 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +0000983
Douglas Gregor229bebd2010-11-09 06:24:54 +0000984 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
985 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000986 if (!file)
987 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000988
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000989 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +0000990 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000991 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +0000992 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000993 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
994 CXSourceLocation start = clang_getRangeStart(range);
995 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +0000996 unsigned start_line, start_column, end_line, end_column;
997 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +0000998 clang_getSpellingLocation(start, &start_file, &start_line,
999 &start_column, 0);
1000 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001001 if (clang_equalLocations(start, end)) {
1002 /* Insertion. */
1003 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001004 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001005 clang_getCString(insertion_text), start_line, start_column);
1006 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1007 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001008 if (start_file == file && end_file == file) {
1009 fprintf(out, "FIX-IT: Remove ");
1010 PrintExtent(out, start_line, start_column, end_line, end_column);
1011 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001012 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001013 } else {
1014 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001015 if (start_file == end_file) {
1016 fprintf(out, "FIX-IT: Replace ");
1017 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001018 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001019 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001020 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001021 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001022 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001023}
1024
Ted Kremenek914c7e62012-02-14 02:46:03 +00001025void PrintDiagnosticSet(CXDiagnosticSet Set) {
1026 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1027 for ( ; i != n ; ++i) {
1028 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1029 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001030 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001031 if (ChildDiags)
1032 PrintDiagnosticSet(ChildDiags);
1033 }
1034}
1035
1036void PrintDiagnostics(CXTranslationUnit TU) {
1037 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1038 PrintDiagnosticSet(TUSet);
1039 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001040}
1041
Ted Kremenek83f642e2011-04-18 22:47:10 +00001042void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001043 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001044 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001045 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001046 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001047 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001048 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001049 unsigned long amount = usage.entries[i].amount;
1050 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001051 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001052 ((double) amount)/(1024*1024));
1053 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001054 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001055 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001056 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001057}
1058
Ted Kremenekb478ff42010-01-26 17:59:48 +00001059/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001060/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001061/******************************************************************************/
1062
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001063static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001064 CXSourceRange extent = clang_getCursorExtent(C);
1065 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001066}
1067
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001068/* Data used by the visitors. */
1069typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001070 CXTranslationUnit TU;
1071 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001072 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001073} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001074
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001075
Ted Kremenek29004672010-02-17 00:41:32 +00001076enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001077 CXCursor Parent,
1078 CXClientData ClientData) {
1079 VisitorData *Data = (VisitorData *)ClientData;
1080 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001081 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001082 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001083 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001084 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001085 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001086 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001087 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001088 if (clang_isDeclaration(Cursor.kind)) {
1089 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1090 const char *accessStr = 0;
1091
1092 switch (access) {
1093 case CX_CXXInvalidAccessSpecifier: break;
1094 case CX_CXXPublic:
1095 accessStr = "public"; break;
1096 case CX_CXXProtected:
1097 accessStr = "protected"; break;
1098 case CX_CXXPrivate:
1099 accessStr = "private"; break;
1100 }
1101
1102 if (accessStr)
1103 printf(" [access=%s]", accessStr);
1104 }
Ted Kremenek29004672010-02-17 00:41:32 +00001105 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001106 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001107 }
Ted Kremenek29004672010-02-17 00:41:32 +00001108
Douglas Gregor720d0052010-01-20 21:32:04 +00001109 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001110}
Steve Naroffa1c72842009-08-28 15:28:48 +00001111
Ted Kremenek29004672010-02-17 00:41:32 +00001112static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001113 CXCursor Parent,
1114 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001115 const char *startBuf, *endBuf;
1116 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1117 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001118 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001119
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001120 if (Cursor.kind != CXCursor_FunctionDecl ||
1121 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001122 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001123
1124 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1125 &startLine, &startColumn,
1126 &endLine, &endColumn);
1127 /* Probe the entire body, looking for both decls and refs. */
1128 curLine = startLine;
1129 curColumn = startColumn;
1130
1131 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001132 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001133 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001134 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001135
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001136 if (*startBuf == '\n') {
1137 startBuf++;
1138 curLine++;
1139 curColumn = 1;
1140 } else if (*startBuf != '\t')
1141 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001142
Douglas Gregor66a58812010-01-18 22:46:11 +00001143 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001144 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001145
Douglas Gregor4f46e782010-01-19 21:36:55 +00001146 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001147 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001148 CXSourceLocation RefLoc
1149 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001150 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001151 if (Ref.kind == CXCursor_NoDeclFound) {
1152 /* Nothing found here; that's fine. */
1153 } else if (Ref.kind != CXCursor_FunctionDecl) {
1154 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1155 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001156 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001157 printf("\n");
1158 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001159 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001160 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001161 startBuf++;
1162 }
Ted Kremenek29004672010-02-17 00:41:32 +00001163
Douglas Gregor720d0052010-01-20 21:32:04 +00001164 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001165}
1166
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001167/******************************************************************************/
1168/* USR testing. */
1169/******************************************************************************/
1170
Douglas Gregor720d0052010-01-20 21:32:04 +00001171enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1172 CXClientData ClientData) {
1173 VisitorData *Data = (VisitorData *)ClientData;
1174 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001175 CXString USR = clang_getCursorUSR(C);
1176 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001177 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001178 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001179 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001180 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001181 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1182
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001183 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001184 printf("\n");
1185 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001186
Douglas Gregor720d0052010-01-20 21:32:04 +00001187 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001188 }
1189
Douglas Gregor720d0052010-01-20 21:32:04 +00001190 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001191}
1192
1193/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001194/* Inclusion stack testing. */
1195/******************************************************************************/
1196
1197void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1198 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001199
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001200 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001201 CXString fname;
1202
1203 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001204 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001205 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001206
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001207 for (i = 0; i < includeStackLen; ++i) {
1208 CXFile includingFile;
1209 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001210 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1211 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001212 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001213 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001214 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001215 }
1216 printf("\n");
1217}
1218
1219void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001220 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001221}
1222
1223/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001224/* Linkage testing. */
1225/******************************************************************************/
1226
1227static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1228 CXClientData d) {
1229 const char *linkage = 0;
1230
1231 if (clang_isInvalid(clang_getCursorKind(cursor)))
1232 return CXChildVisit_Recurse;
1233
1234 switch (clang_getCursorLinkage(cursor)) {
1235 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001236 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1237 case CXLinkage_Internal: linkage = "Internal"; break;
1238 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1239 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001240 }
1241
1242 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001243 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001244 printf("linkage=%s\n", linkage);
1245 }
1246
1247 return CXChildVisit_Recurse;
1248}
1249
1250/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001251/* Typekind testing. */
1252/******************************************************************************/
1253
Dmitri Gribenko00353722013-02-15 21:15:49 +00001254static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1255 CXString TypeSpelling, TypeKindSpelling;
1256
1257 TypeSpelling = clang_getTypeSpelling(T);
1258 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1259 printf(Format,
1260 clang_getCString(TypeSpelling),
1261 clang_getCString(TypeKindSpelling));
1262 clang_disposeString(TypeSpelling);
1263 clang_disposeString(TypeKindSpelling);
1264}
1265
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001266static enum CXVisitorResult FieldVisitor(CXCursor C,
1267 CXClientData client_data) {
1268 (*(int *) client_data)+=1;
1269 return CXVisit_Continue;
1270}
1271
Dmitri Gribenko00353722013-02-15 21:15:49 +00001272static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1273 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001274 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001275 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001276 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001277 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001278 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001279 if (clang_isConstQualifiedType(T))
1280 printf(" const");
1281 if (clang_isVolatileQualifiedType(T))
1282 printf(" volatile");
1283 if (clang_isRestrictQualifiedType(T))
1284 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001285 if (RQ == CXRefQualifier_LValue)
1286 printf(" lvalue-ref-qualifier");
1287 if (RQ == CXRefQualifier_RValue)
1288 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001289 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001290 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001291 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001292 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001293 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001294 }
1295 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001296 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001297 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001298 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001299 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001300 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001301 }
1302 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001303 /* Print the argument types if they exist. */
1304 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001305 int NumArgs = clang_Cursor_getNumArguments(cursor);
1306 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001307 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001308 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001309 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001310 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001311 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001312 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001313 }
1314 }
1315 printf("]");
1316 }
1317 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001318 /* Print the template argument types if they exist. */
1319 {
1320 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1321 if (NumTArgs != -1 && NumTArgs != 0) {
1322 int i;
1323 printf(" [templateargs/%d=", NumTArgs);
1324 for (i = 0; i < NumTArgs; ++i) {
1325 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1326 if (TArg.kind != CXType_Invalid) {
1327 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1328 }
1329 }
1330 printf("]");
1331 }
1332 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001333 /* Print if this is a non-POD type. */
1334 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001335 /* Print the pointee type. */
1336 {
1337 CXType PT = clang_getPointeeType(T);
1338 if (PT.kind != CXType_Invalid) {
1339 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1340 }
1341 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001342 /* Print the number of fields if they exist. */
1343 {
1344 int numFields = 0;
1345 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1346 if (numFields != 0) {
1347 printf(" [nbFields=%d]", numFields);
1348 }
1349 /* Print if it is an anonymous record. */
1350 {
1351 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1352 if (isAnon != 0) {
1353 printf(" [isAnon=%d]", isAnon);
1354 }
1355 }
1356 }
1357 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001358
Ted Kremenek6bca9842010-05-14 21:29:26 +00001359 printf("\n");
1360 }
1361 return CXChildVisit_Recurse;
1362}
1363
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001364static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1365 CXClientData d) {
1366 CXType T;
1367 enum CXCursorKind K = clang_getCursorKind(cursor);
1368 if (clang_isInvalid(K))
1369 return CXChildVisit_Recurse;
1370 T = clang_getCursorType(cursor);
1371 PrintCursor(cursor, NULL);
1372 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1373 /* Print the type sizeof if applicable. */
1374 {
1375 long long Size = clang_Type_getSizeOf(T);
1376 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001377 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001378 }
1379 }
1380 /* Print the type alignof if applicable. */
1381 {
1382 long long Align = clang_Type_getAlignOf(T);
1383 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001384 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001385 }
1386 }
1387 /* Print the record field offset if applicable. */
1388 {
Nico Weber82098cb2014-04-24 04:14:12 +00001389 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1390 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001391 /* recurse to get the first parent record that is not anonymous. */
1392 CXCursor Parent, Record;
1393 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001394 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001395 Record = Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001396 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001397 Record = Parent;
1398 Parent = clang_getCursorSemanticParent(Record);
1399 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1400 /* Recurse as long as the parent is a CXType_Record and the Record
1401 is anonymous */
1402 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1403 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001404 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001405 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001406 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001407 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1408 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001409 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001410 } else {
1411 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001412 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001413 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001414 }
1415 }
Nico Weber82098cb2014-04-24 04:14:12 +00001416 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001417 }
1418 /* Print if its a bitfield */
1419 {
1420 int IsBitfield = clang_Cursor_isBitField(cursor);
1421 if (IsBitfield)
1422 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1423 }
1424 printf("\n");
1425 return CXChildVisit_Recurse;
1426}
1427
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001428/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001429/* Mangling testing. */
1430/******************************************************************************/
1431
1432static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1433 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001434 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001435 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1436 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001437 PrintCursor(cursor, NULL);
1438 MangledName = clang_Cursor_getMangling(cursor);
1439 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001440 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001441 return CXChildVisit_Continue;
1442}
1443
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001444static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1445 CXClientData d) {
1446 unsigned I, E;
1447 CXStringSet *Manglings = NULL;
1448 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1449 return CXChildVisit_Recurse;
1450 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1451 return CXChildVisit_Recurse;
1452 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1453 return CXChildVisit_Continue;
1454 PrintCursor(cursor, NULL);
1455 Manglings = clang_Cursor_getCXXManglings(cursor);
1456 for (I = 0, E = Manglings->Count; I < E; ++I)
1457 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1458 clang_disposeStringSet(Manglings);
1459 printf("\n");
1460 return CXChildVisit_Recurse;
1461}
1462
Eli Bendersky44a206f2014-07-31 18:04:56 +00001463/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001464/* Bitwidth testing. */
1465/******************************************************************************/
1466
1467static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1468 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001469 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001470 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1471 return CXChildVisit_Recurse;
1472
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001473 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001474 if (Bitwidth >= 0) {
1475 PrintCursor(cursor, NULL);
1476 printf(" bitwidth=%d\n", Bitwidth);
1477 }
1478
1479 return CXChildVisit_Recurse;
1480}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001481
1482/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001483/* Loading ASTs/source. */
1484/******************************************************************************/
1485
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001486static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001487 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001488 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001489 PostVisitTU PV,
1490 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001491
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001492 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001493 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001494
1495 if (Visitor) {
1496 enum CXCursorKind K = CXCursor_NotImplemented;
1497 enum CXCursorKind *ck = &K;
1498 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001499
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001500 /* Perform some simple filtering. */
1501 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001502 else if (!strcmp(filter, "all-display") ||
1503 !strcmp(filter, "local-display")) {
1504 ck = NULL;
1505 want_display_name = 1;
1506 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001507 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001508 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1509 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1510 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1511 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1512 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1513 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1514 else {
1515 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1516 return 1;
1517 }
Ted Kremenek29004672010-02-17 00:41:32 +00001518
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001519 Data.TU = TU;
1520 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001521 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001522 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001523 }
Ted Kremenek29004672010-02-17 00:41:32 +00001524
Ted Kremenekb478ff42010-01-26 17:59:48 +00001525 if (PV)
1526 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001527
Douglas Gregor33cdd812010-02-18 18:08:43 +00001528 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001529 if (checkForErrors(TU) != 0) {
1530 clang_disposeTranslationUnit(TU);
1531 return -1;
1532 }
1533
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001534 clang_disposeTranslationUnit(TU);
1535 return 0;
1536}
1537
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001538int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001539 const char *prefix, CXCursorVisitor Visitor,
1540 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001541 CXIndex Idx;
1542 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001543 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001544 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001545 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001546 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001547
Ted Kremenek50228be2010-02-11 07:41:25 +00001548 if (!CreateTranslationUnit(Idx, file, &TU)) {
1549 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001550 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001551 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001552
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001553 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001554 clang_disposeIndex(Idx);
1555 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001556}
1557
Ted Kremenekb478ff42010-01-26 17:59:48 +00001558int perform_test_load_source(int argc, const char **argv,
1559 const char *filter, CXCursorVisitor Visitor,
1560 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001561 CXIndex Idx;
1562 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001563 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001564 struct CXUnsavedFile *unsaved_files = 0;
1565 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001566 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001567 int result;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001568
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001569 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001570 (!strcmp(filter, "local") ||
1571 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001572 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001573
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001574 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1575 argc--;
1576 argv++;
1577 }
1578
Ted Kremenek50228be2010-02-11 07:41:25 +00001579 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1580 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001581 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001582 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001583
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001584 Err = clang_parseTranslationUnit2(Idx, 0,
1585 argv + num_unsaved_files,
1586 argc - num_unsaved_files,
1587 unsaved_files, num_unsaved_files,
1588 getDefaultParsingOptions(), &TU);
1589 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001590 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001591 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001592 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001593 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001594 return 1;
1595 }
1596
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001597 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1598 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001599 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001600 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001601 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001602}
1603
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001604int perform_test_reparse_source(int argc, const char **argv, int trials,
1605 const char *filter, CXCursorVisitor Visitor,
1606 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001607 CXIndex Idx;
1608 CXTranslationUnit TU;
1609 struct CXUnsavedFile *unsaved_files = 0;
1610 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001611 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001612 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001613 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001614 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001615 int remap_after_trial = 0;
1616 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001617
1618 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1619 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001620 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001621
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001622 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1623 clang_disposeIndex(Idx);
1624 return -1;
1625 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001626
1627 for (i = 0; i < argc; ++i) {
1628 if (strcmp(argv[i], "--") == 0)
1629 break;
1630 }
1631 if (i < argc)
1632 compiler_arg_idx = i+1;
1633 if (num_unsaved_files > compiler_arg_idx)
1634 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001635
Daniel Dunbarec29d712010-08-18 23:09:16 +00001636 /* Load the initial translation unit -- we do this without honoring remapped
1637 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001638 Err = clang_parseTranslationUnit2(Idx, 0,
1639 argv + compiler_arg_idx,
1640 argc - compiler_arg_idx,
1641 0, 0, getDefaultParsingOptions(), &TU);
1642 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001643 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001644 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001645 free_remapped_files(unsaved_files, num_unsaved_files);
1646 clang_disposeIndex(Idx);
1647 return 1;
1648 }
1649
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001650 if (checkForErrors(TU) != 0)
1651 return -1;
1652
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001653 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1654 remap_after_trial =
1655 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1656 }
1657
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001658 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001659 free_remapped_files(unsaved_files, num_unsaved_files);
1660 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1661 &unsaved_files, &num_unsaved_files)) {
1662 clang_disposeTranslationUnit(TU);
1663 clang_disposeIndex(Idx);
1664 return -1;
1665 }
1666
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001667 Err = clang_reparseTranslationUnit(
1668 TU,
1669 trial >= remap_after_trial ? num_unsaved_files : 0,
1670 trial >= remap_after_trial ? unsaved_files : 0,
1671 clang_defaultReparseOptions(TU));
1672 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001673 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001674 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001675 clang_disposeTranslationUnit(TU);
1676 free_remapped_files(unsaved_files, num_unsaved_files);
1677 clang_disposeIndex(Idx);
1678 return -1;
1679 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001680
1681 if (checkForErrors(TU) != 0)
1682 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001683 }
1684
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001685 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001686
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001687 free_remapped_files(unsaved_files, num_unsaved_files);
1688 clang_disposeIndex(Idx);
1689 return result;
1690}
1691
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001692/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001693/* Logic for testing clang_getCursor(). */
1694/******************************************************************************/
1695
Douglas Gregor37aa4932011-05-04 00:14:37 +00001696static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001697 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001698 unsigned end_line, unsigned end_col,
1699 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001700 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001701 if (prefix)
1702 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001703 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1704 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001705 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001706 printf("\n");
1707}
1708
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001709static int perform_file_scan(const char *ast_file, const char *source_file,
1710 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001711 CXIndex Idx;
1712 CXTranslationUnit TU;
1713 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001714 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001715 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001716 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001717 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001718
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001719 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001720 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001721 fprintf(stderr, "Could not create Index\n");
1722 return 1;
1723 }
Ted Kremenek29004672010-02-17 00:41:32 +00001724
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001725 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1726 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001727
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001728 if ((fp = fopen(source_file, "r")) == NULL) {
1729 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001730 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001731 return 1;
1732 }
Ted Kremenek29004672010-02-17 00:41:32 +00001733
Douglas Gregor816fd362010-01-22 21:44:22 +00001734 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001735 for (;;) {
1736 CXCursor cursor;
1737 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001738
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001739 if (c == '\n') {
1740 ++line;
1741 col = 1;
1742 } else
1743 ++col;
1744
1745 /* Check the cursor at this position, and dump the previous one if we have
1746 * found something new.
1747 */
1748 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1749 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1750 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001751 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001752 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001753 start_line = line;
1754 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001755 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001756 if (c == EOF)
1757 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001758
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001759 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001760 }
Ted Kremenek29004672010-02-17 00:41:32 +00001761
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001762 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001763 clang_disposeTranslationUnit(TU);
1764 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001765 return 0;
1766}
1767
1768/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001769/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001770/******************************************************************************/
1771
Douglas Gregor9eb77012009-11-07 00:00:49 +00001772/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1773 on failure. If successful, the pointer *filename will contain newly-allocated
1774 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001775int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001776 unsigned *column, unsigned *second_line,
1777 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001778 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001779 const char *last_colon = strrchr(input, ':');
1780 unsigned values[4], i;
1781 unsigned num_values = (second_line && second_column)? 4 : 2;
1782
Douglas Gregor9eb77012009-11-07 00:00:49 +00001783 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001784 if (!last_colon || last_colon == input) {
1785 if (num_values == 4)
1786 fprintf(stderr, "could not parse filename:line:column:line:column in "
1787 "'%s'\n", input);
1788 else
1789 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001790 return 1;
1791 }
1792
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001793 for (i = 0; i != num_values; ++i) {
1794 const char *prev_colon;
1795
1796 /* Parse the next line or column. */
1797 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1798 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001799 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001800 (i % 2 ? "column" : "line"), input);
1801 return 1;
1802 }
Ted Kremenek29004672010-02-17 00:41:32 +00001803
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001804 if (i + 1 == num_values)
1805 break;
1806
1807 /* Find the previous colon. */
1808 prev_colon = last_colon - 1;
1809 while (prev_colon != input && *prev_colon != ':')
1810 --prev_colon;
1811 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001812 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001813 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001814 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001815 }
1816
1817 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001818 }
1819
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001820 *line = values[0];
1821 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001822
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001823 if (second_line && second_column) {
1824 *second_line = values[2];
1825 *second_column = values[3];
1826 }
1827
Douglas Gregorf96ea292009-11-09 18:19:57 +00001828 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001829 *filename = (char*)malloc(last_colon - input + 1);
1830 memcpy(*filename, input, last_colon - input);
1831 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001832 return 0;
1833}
1834
1835const char *
1836clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1837 switch (Kind) {
1838 case CXCompletionChunk_Optional: return "Optional";
1839 case CXCompletionChunk_TypedText: return "TypedText";
1840 case CXCompletionChunk_Text: return "Text";
1841 case CXCompletionChunk_Placeholder: return "Placeholder";
1842 case CXCompletionChunk_Informative: return "Informative";
1843 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1844 case CXCompletionChunk_LeftParen: return "LeftParen";
1845 case CXCompletionChunk_RightParen: return "RightParen";
1846 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1847 case CXCompletionChunk_RightBracket: return "RightBracket";
1848 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1849 case CXCompletionChunk_RightBrace: return "RightBrace";
1850 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1851 case CXCompletionChunk_RightAngle: return "RightAngle";
1852 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001853 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001854 case CXCompletionChunk_Colon: return "Colon";
1855 case CXCompletionChunk_SemiColon: return "SemiColon";
1856 case CXCompletionChunk_Equal: return "Equal";
1857 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1858 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001859 }
Ted Kremenek29004672010-02-17 00:41:32 +00001860
Douglas Gregor9eb77012009-11-07 00:00:49 +00001861 return "Unknown";
1862}
1863
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001864static int checkForErrors(CXTranslationUnit TU) {
1865 unsigned Num, i;
1866 CXDiagnostic Diag;
1867 CXString DiagStr;
1868
1869 if (!getenv("CINDEXTEST_FAILONERROR"))
1870 return 0;
1871
1872 Num = clang_getNumDiagnostics(TU);
1873 for (i = 0; i != Num; ++i) {
1874 Diag = clang_getDiagnostic(TU, i);
1875 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1876 DiagStr = clang_formatDiagnostic(Diag,
1877 clang_defaultDiagnosticDisplayOptions());
1878 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1879 clang_disposeString(DiagStr);
1880 clang_disposeDiagnostic(Diag);
1881 return -1;
1882 }
1883 clang_disposeDiagnostic(Diag);
1884 }
1885
1886 return 0;
1887}
1888
Nico Weber8d19dff2014-05-07 21:05:22 +00001889static void print_completion_string(CXCompletionString completion_string,
1890 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001891 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001892
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001893 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001894 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001895 CXString text;
1896 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001897 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001898 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001899
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001900 if (Kind == CXCompletionChunk_Optional) {
1901 fprintf(file, "{Optional ");
1902 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001903 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001904 file);
1905 fprintf(file, "}");
1906 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001907 }
1908
1909 if (Kind == CXCompletionChunk_VerticalSpace) {
1910 fprintf(file, "{VerticalSpace }");
1911 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001912 }
Ted Kremenek29004672010-02-17 00:41:32 +00001913
Douglas Gregorf81f5282009-11-09 17:05:28 +00001914 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001915 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001916 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001917 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001918 cstr ? cstr : "");
1919 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001920 }
Ted Kremenekf602f962010-02-17 01:42:24 +00001921
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001922}
1923
Nico Weber8d19dff2014-05-07 21:05:22 +00001924static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00001925 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001926 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001927 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00001928 enum CXCursorKind ParentKind;
1929 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001930 CXString BriefComment;
1931 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00001932
Ted Kremenek29004672010-02-17 00:41:32 +00001933 fprintf(file, "%s:", clang_getCString(ks));
1934 clang_disposeString(ks);
1935
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001936 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00001937 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00001938 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00001939 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
1940 case CXAvailability_Available:
1941 break;
1942
1943 case CXAvailability_Deprecated:
1944 fprintf(file, " (deprecated)");
1945 break;
1946
1947 case CXAvailability_NotAvailable:
1948 fprintf(file, " (unavailable)");
1949 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001950
1951 case CXAvailability_NotAccessible:
1952 fprintf(file, " (inaccessible)");
1953 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00001954 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00001955
1956 annotationCount = clang_getCompletionNumAnnotations(
1957 completion_result->CompletionString);
1958 if (annotationCount) {
1959 unsigned i;
1960 fprintf(file, " (");
1961 for (i = 0; i < annotationCount; ++i) {
1962 if (i != 0)
1963 fprintf(file, ", ");
1964 fprintf(file, "\"%s\"",
1965 clang_getCString(clang_getCompletionAnnotation(
1966 completion_result->CompletionString, i)));
1967 }
1968 fprintf(file, ")");
1969 }
1970
Douglas Gregor78254c82012-03-27 23:34:16 +00001971 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
1972 ParentName = clang_getCompletionParent(completion_result->CompletionString,
1973 &ParentKind);
1974 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001975 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00001976 fprintf(file, " (parent: %s '%s')",
1977 clang_getCString(KindSpelling),
1978 clang_getCString(ParentName));
1979 clang_disposeString(KindSpelling);
1980 }
1981 clang_disposeString(ParentName);
1982 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001983
1984 BriefComment = clang_getCompletionBriefComment(
1985 completion_result->CompletionString);
1986 BriefCommentCString = clang_getCString(BriefComment);
1987 if (BriefCommentCString && *BriefCommentCString != '\0') {
1988 fprintf(file, "(brief comment: %s)", BriefCommentCString);
1989 }
1990 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00001991
Douglas Gregorf757a122010-08-23 23:00:57 +00001992 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00001993}
1994
Douglas Gregor21325842011-07-07 16:03:39 +00001995void print_completion_contexts(unsigned long long contexts, FILE *file) {
1996 fprintf(file, "Completion contexts:\n");
1997 if (contexts == CXCompletionContext_Unknown) {
1998 fprintf(file, "Unknown\n");
1999 }
2000 if (contexts & CXCompletionContext_AnyType) {
2001 fprintf(file, "Any type\n");
2002 }
2003 if (contexts & CXCompletionContext_AnyValue) {
2004 fprintf(file, "Any value\n");
2005 }
2006 if (contexts & CXCompletionContext_ObjCObjectValue) {
2007 fprintf(file, "Objective-C object value\n");
2008 }
2009 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2010 fprintf(file, "Objective-C selector value\n");
2011 }
2012 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2013 fprintf(file, "C++ class type value\n");
2014 }
2015 if (contexts & CXCompletionContext_DotMemberAccess) {
2016 fprintf(file, "Dot member access\n");
2017 }
2018 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2019 fprintf(file, "Arrow member access\n");
2020 }
2021 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2022 fprintf(file, "Objective-C property access\n");
2023 }
2024 if (contexts & CXCompletionContext_EnumTag) {
2025 fprintf(file, "Enum tag\n");
2026 }
2027 if (contexts & CXCompletionContext_UnionTag) {
2028 fprintf(file, "Union tag\n");
2029 }
2030 if (contexts & CXCompletionContext_StructTag) {
2031 fprintf(file, "Struct tag\n");
2032 }
2033 if (contexts & CXCompletionContext_ClassTag) {
2034 fprintf(file, "Class name\n");
2035 }
2036 if (contexts & CXCompletionContext_Namespace) {
2037 fprintf(file, "Namespace or namespace alias\n");
2038 }
2039 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2040 fprintf(file, "Nested name specifier\n");
2041 }
2042 if (contexts & CXCompletionContext_ObjCInterface) {
2043 fprintf(file, "Objective-C interface\n");
2044 }
2045 if (contexts & CXCompletionContext_ObjCProtocol) {
2046 fprintf(file, "Objective-C protocol\n");
2047 }
2048 if (contexts & CXCompletionContext_ObjCCategory) {
2049 fprintf(file, "Objective-C category\n");
2050 }
2051 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2052 fprintf(file, "Objective-C instance method\n");
2053 }
2054 if (contexts & CXCompletionContext_ObjCClassMessage) {
2055 fprintf(file, "Objective-C class method\n");
2056 }
2057 if (contexts & CXCompletionContext_ObjCSelectorName) {
2058 fprintf(file, "Objective-C selector name\n");
2059 }
2060 if (contexts & CXCompletionContext_MacroName) {
2061 fprintf(file, "Macro name\n");
2062 }
2063 if (contexts & CXCompletionContext_NaturalLanguage) {
2064 fprintf(file, "Natural language\n");
2065 }
2066}
2067
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002068int my_stricmp(const char *s1, const char *s2) {
2069 while (*s1 && *s2) {
NAKAMURA Takumid3cc2202011-03-09 03:02:28 +00002070 int c1 = tolower((unsigned char)*s1), c2 = tolower((unsigned char)*s2);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002071 if (c1 < c2)
2072 return -1;
2073 else if (c1 > c2)
2074 return 1;
2075
2076 ++s1;
2077 ++s2;
2078 }
2079
2080 if (*s1)
2081 return 1;
2082 else if (*s2)
2083 return -1;
2084 return 0;
2085}
2086
Douglas Gregor47815d52010-07-12 18:38:41 +00002087int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002088 const char *input = argv[1];
2089 char *filename = 0;
2090 unsigned line;
2091 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002092 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002093 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002094 struct CXUnsavedFile *unsaved_files = 0;
2095 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002096 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002097 enum CXErrorCode Err;
2098 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002099 unsigned I, Repeats = 1;
2100 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2101
2102 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2103 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002104 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2105 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002106
Douglas Gregor47815d52010-07-12 18:38:41 +00002107 if (timing_only)
2108 input += strlen("-code-completion-timing=");
2109 else
2110 input += strlen("-code-completion-at=");
2111
Ted Kremenek29004672010-02-17 00:41:32 +00002112 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002113 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002114 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002115
Douglas Gregor9485bf92009-12-02 09:21:34 +00002116 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2117 return -1;
2118
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002119 CIdx = clang_createIndex(0, 0);
2120
2121 if (getenv("CINDEXTEST_EDITING"))
2122 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002123
2124 Err = clang_parseTranslationUnit2(CIdx, 0,
2125 argv + num_unsaved_files + 2,
2126 argc - num_unsaved_files - 2,
2127 0, 0, getDefaultParsingOptions(), &TU);
2128 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002129 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002130 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002131 return 1;
2132 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002133
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002134 Err = clang_reparseTranslationUnit(TU, 0, 0,
2135 clang_defaultReparseOptions(TU));
2136
2137 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002138 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002139 describeLibclangFailure(Err);
2140 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002141 return 1;
2142 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002143
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002144 for (I = 0; I != Repeats; ++I) {
2145 results = clang_codeCompleteAt(TU, filename, line, column,
2146 unsaved_files, num_unsaved_files,
2147 completionOptions);
2148 if (!results) {
2149 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002150 return 1;
2151 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002152 if (I != Repeats-1)
2153 clang_disposeCodeCompleteResults(results);
2154 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002155
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002156 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002157 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002158 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002159 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002160 CXString objCSelector;
2161 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002162 if (!timing_only) {
2163 /* Sort the code-completion results based on the typed text. */
2164 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2165
Douglas Gregor47815d52010-07-12 18:38:41 +00002166 for (i = 0; i != n; ++i)
2167 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002168 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002169 n = clang_codeCompleteGetNumDiagnostics(results);
2170 for (i = 0; i != n; ++i) {
2171 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2172 PrintDiagnostic(diag);
2173 clang_disposeDiagnostic(diag);
2174 }
Douglas Gregor21325842011-07-07 16:03:39 +00002175
2176 contexts = clang_codeCompleteGetContexts(results);
2177 print_completion_contexts(contexts, stdout);
2178
Douglas Gregorea777402011-07-26 15:24:30 +00002179 containerKind = clang_codeCompleteGetContainerKind(results,
2180 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002181
2182 if (containerKind != CXCursor_InvalidCode) {
2183 /* We have found a container */
2184 CXString containerUSR, containerKindSpelling;
2185 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2186 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2187 clang_disposeString(containerKindSpelling);
2188
2189 if (containerIsIncomplete) {
2190 printf("Container is incomplete\n");
2191 }
2192 else {
2193 printf("Container is complete\n");
2194 }
2195
2196 containerUSR = clang_codeCompleteGetContainerUSR(results);
2197 printf("Container USR: %s\n", clang_getCString(containerUSR));
2198 clang_disposeString(containerUSR);
2199 }
2200
Douglas Gregorea777402011-07-26 15:24:30 +00002201 objCSelector = clang_codeCompleteGetObjCSelector(results);
2202 selectorString = clang_getCString(objCSelector);
2203 if (selectorString && strlen(selectorString) > 0) {
2204 printf("Objective-C selector: %s\n", selectorString);
2205 }
2206 clang_disposeString(objCSelector);
2207
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002208 clang_disposeCodeCompleteResults(results);
2209 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002210 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002211 clang_disposeIndex(CIdx);
2212 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002213
Douglas Gregor9485bf92009-12-02 09:21:34 +00002214 free_remapped_files(unsaved_files, num_unsaved_files);
2215
Ted Kremenekef3339b2009-11-17 18:09:14 +00002216 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002217}
2218
Douglas Gregor082c3e62010-01-15 19:40:17 +00002219typedef struct {
2220 char *filename;
2221 unsigned line;
2222 unsigned column;
2223} CursorSourceLocation;
2224
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002225static int inspect_cursor_at(int argc, const char **argv) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002226 CXIndex CIdx;
2227 int errorCode;
2228 struct CXUnsavedFile *unsaved_files = 0;
2229 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002230 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002231 CXTranslationUnit TU;
2232 CXCursor Cursor;
2233 CursorSourceLocation *Locations = 0;
2234 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002235 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002236 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002237
Ted Kremenek29004672010-02-17 00:41:32 +00002238 /* Count the number of locations. */
Douglas Gregor082c3e62010-01-15 19:40:17 +00002239 while (strstr(argv[NumLocations+1], "-cursor-at=") == argv[NumLocations+1])
2240 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002241
Douglas Gregor082c3e62010-01-15 19:40:17 +00002242 /* Parse the locations. */
2243 assert(NumLocations > 0 && "Unable to count locations?");
2244 Locations = (CursorSourceLocation *)malloc(
2245 NumLocations * sizeof(CursorSourceLocation));
2246 for (Loc = 0; Loc < NumLocations; ++Loc) {
2247 const char *input = argv[Loc + 1] + strlen("-cursor-at=");
Ted Kremenek29004672010-02-17 00:41:32 +00002248 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2249 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002250 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002251 return errorCode;
2252 }
Ted Kremenek29004672010-02-17 00:41:32 +00002253
2254 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002255 &num_unsaved_files))
2256 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002257
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002258 if (getenv("CINDEXTEST_EDITING"))
2259 Repeats = 5;
2260
2261 /* Parse the translation unit. When we're testing clang_getCursor() after
2262 reparsing, don't remap unsaved files until the second parse. */
2263 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002264 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2265 argv + num_unsaved_files + 1 + NumLocations,
2266 argc - num_unsaved_files - 2 - NumLocations,
2267 unsaved_files,
2268 Repeats > 1? 0 : num_unsaved_files,
2269 getDefaultParsingOptions(), &TU);
2270 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002271 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002272 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002273 return -1;
2274 }
Ted Kremenek29004672010-02-17 00:41:32 +00002275
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002276 if (checkForErrors(TU) != 0)
2277 return -1;
2278
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002279 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002280 if (Repeats > 1) {
2281 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2282 clang_defaultReparseOptions(TU));
2283 if (Err != CXError_Success) {
2284 describeLibclangFailure(Err);
2285 clang_disposeTranslationUnit(TU);
2286 return 1;
2287 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002288 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002289
2290 if (checkForErrors(TU) != 0)
2291 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002292
2293 for (Loc = 0; Loc < NumLocations; ++Loc) {
2294 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2295 if (!file)
2296 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002297
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002298 Cursor = clang_getCursor(TU,
2299 clang_getLocation(TU, file, Locations[Loc].line,
2300 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002301
2302 if (checkForErrors(TU) != 0)
2303 return -1;
2304
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002305 if (I + 1 == Repeats) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002306 CXCompletionString completionString = clang_getCursorCompletionString(
2307 Cursor);
2308 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002309 CXString Spelling;
2310 const char *cspell;
2311 unsigned line, column;
2312 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2313 printf("%d:%d ", line, column);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002314 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002315 PrintCursorExtent(Cursor);
2316 Spelling = clang_getCursorSpelling(Cursor);
2317 cspell = clang_getCString(Spelling);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002318 if (cspell && strlen(cspell) != 0) {
2319 unsigned pieceIndex;
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002320 printf(" Spelling=%s (", cspell);
2321 for (pieceIndex = 0; ; ++pieceIndex) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002322 CXSourceRange range =
2323 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +00002324 if (clang_Range_isNull(range))
2325 break;
2326 PrintRange(range, 0);
2327 }
2328 printf(")");
2329 }
Argyrios Kyrtzidis7aa274f2012-03-30 00:19:05 +00002330 clang_disposeString(Spelling);
Argyrios Kyrtzidis210f29f2012-03-30 22:15:48 +00002331 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
Nico Weber8d19dff2014-05-07 21:05:22 +00002332 printf(" Selector index=%d",
2333 clang_Cursor_getObjCSelectorIndex(Cursor));
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002334 if (clang_Cursor_isDynamicCall(Cursor))
2335 printf(" Dynamic-call");
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002336 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002337 CXType T = clang_Cursor_getReceiverType(Cursor);
2338 CXString S = clang_getTypeKindSpelling(T.kind);
Argyrios Kyrtzidisb26a24c2012-11-01 02:01:34 +00002339 printf(" Receiver-type=%s", clang_getCString(S));
2340 clang_disposeString(S);
2341 }
Argyrios Kyrtzidisb6df68212012-07-02 23:54:36 +00002342
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002343 {
2344 CXModule mod = clang_Cursor_getModule(Cursor);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002345 CXFile astFile;
2346 CXString name, astFilename;
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002347 unsigned i, numHeaders;
2348 if (mod) {
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002349 astFile = clang_Module_getASTFile(mod);
2350 astFilename = clang_getFileName(astFile);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002351 name = clang_Module_getFullName(mod);
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00002352 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002353 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002354 clang_getCString(name), clang_getCString(astFilename),
Argyrios Kyrtzidis884337f2014-05-15 04:44:25 +00002355 clang_Module_isSystem(mod), numHeaders);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002356 clang_disposeString(name);
Argyrios Kyrtzidis12fdb9e2013-04-26 22:47:49 +00002357 clang_disposeString(astFilename);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002358 for (i = 0; i < numHeaders; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002359 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2360 CXString filename = clang_getFileName(file);
Argyrios Kyrtzidis2b9b5bb2012-10-05 00:22:37 +00002361 printf("\n%s", clang_getCString(filename));
2362 clang_disposeString(filename);
2363 }
2364 }
2365 }
2366
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002367 if (completionString != NULL) {
2368 printf("\nCompletion string: ");
2369 print_completion_string(completionString, stdout);
2370 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002371 printf("\n");
2372 free(Locations[Loc].filename);
2373 }
2374 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002375 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002376
Douglas Gregor33cdd812010-02-18 18:08:43 +00002377 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002378 clang_disposeTranslationUnit(TU);
2379 clang_disposeIndex(CIdx);
2380 free(Locations);
2381 free_remapped_files(unsaved_files, num_unsaved_files);
2382 return 0;
2383}
2384
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002385static enum CXVisitorResult findFileRefsVisit(void *context,
2386 CXCursor cursor, CXSourceRange range) {
2387 if (clang_Range_isNull(range))
2388 return CXVisit_Continue;
2389
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002390 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002391 PrintRange(range, "");
2392 printf("\n");
2393 return CXVisit_Continue;
2394}
2395
2396static int find_file_refs_at(int argc, const char **argv) {
2397 CXIndex CIdx;
2398 int errorCode;
2399 struct CXUnsavedFile *unsaved_files = 0;
2400 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002401 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002402 CXTranslationUnit TU;
2403 CXCursor Cursor;
2404 CursorSourceLocation *Locations = 0;
2405 unsigned NumLocations = 0, Loc;
2406 unsigned Repeats = 1;
2407 unsigned I;
2408
2409 /* Count the number of locations. */
2410 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2411 ++NumLocations;
2412
2413 /* Parse the locations. */
2414 assert(NumLocations > 0 && "Unable to count locations?");
2415 Locations = (CursorSourceLocation *)malloc(
2416 NumLocations * sizeof(CursorSourceLocation));
2417 for (Loc = 0; Loc < NumLocations; ++Loc) {
2418 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2419 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2420 &Locations[Loc].line,
2421 &Locations[Loc].column, 0, 0)))
2422 return errorCode;
2423 }
2424
2425 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2426 &num_unsaved_files))
2427 return -1;
2428
2429 if (getenv("CINDEXTEST_EDITING"))
2430 Repeats = 5;
2431
2432 /* Parse the translation unit. When we're testing clang_getCursor() after
2433 reparsing, don't remap unsaved files until the second parse. */
2434 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002435 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2436 argv + num_unsaved_files + 1 + NumLocations,
2437 argc - num_unsaved_files - 2 - NumLocations,
2438 unsaved_files,
2439 Repeats > 1? 0 : num_unsaved_files,
2440 getDefaultParsingOptions(), &TU);
2441 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002442 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002443 describeLibclangFailure(Err);
2444 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002445 return -1;
2446 }
2447
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002448 if (checkForErrors(TU) != 0)
2449 return -1;
2450
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002451 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002452 if (Repeats > 1) {
2453 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2454 clang_defaultReparseOptions(TU));
2455 if (Err != CXError_Success) {
2456 describeLibclangFailure(Err);
2457 clang_disposeTranslationUnit(TU);
2458 return 1;
2459 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002460 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002461
2462 if (checkForErrors(TU) != 0)
2463 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002464
2465 for (Loc = 0; Loc < NumLocations; ++Loc) {
2466 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2467 if (!file)
2468 continue;
2469
2470 Cursor = clang_getCursor(TU,
2471 clang_getLocation(TU, file, Locations[Loc].line,
2472 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002473
2474 if (checkForErrors(TU) != 0)
2475 return -1;
2476
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002477 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002478 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002479 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002480 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002481 clang_findReferencesInFile(Cursor, file, visitor);
2482 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002483
2484 if (checkForErrors(TU) != 0)
2485 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002486 }
2487 }
2488 }
2489
2490 PrintDiagnostics(TU);
2491 clang_disposeTranslationUnit(TU);
2492 clang_disposeIndex(CIdx);
2493 free(Locations);
2494 free_remapped_files(unsaved_files, num_unsaved_files);
2495 return 0;
2496}
2497
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002498static enum CXVisitorResult findFileIncludesVisit(void *context,
2499 CXCursor cursor, CXSourceRange range) {
2500 PrintCursor(cursor, NULL);
2501 PrintRange(range, "");
2502 printf("\n");
2503 return CXVisit_Continue;
2504}
2505
2506static int find_file_includes_in(int argc, const char **argv) {
2507 CXIndex CIdx;
2508 struct CXUnsavedFile *unsaved_files = 0;
2509 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002510 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002511 CXTranslationUnit TU;
2512 const char **Filenames = 0;
2513 unsigned NumFilenames = 0;
2514 unsigned Repeats = 1;
2515 unsigned I, FI;
2516
2517 /* Count the number of locations. */
2518 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2519 ++NumFilenames;
2520
2521 /* Parse the locations. */
2522 assert(NumFilenames > 0 && "Unable to count filenames?");
2523 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2524 for (I = 0; I < NumFilenames; ++I) {
2525 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2526 /* Copy the file name. */
2527 Filenames[I] = input;
2528 }
2529
2530 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2531 &num_unsaved_files))
2532 return -1;
2533
2534 if (getenv("CINDEXTEST_EDITING"))
2535 Repeats = 2;
2536
2537 /* Parse the translation unit. When we're testing clang_getCursor() after
2538 reparsing, don't remap unsaved files until the second parse. */
2539 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002540 Err = clang_parseTranslationUnit2(
2541 CIdx, argv[argc - 1],
2542 argv + num_unsaved_files + 1 + NumFilenames,
2543 argc - num_unsaved_files - 2 - NumFilenames,
2544 unsaved_files,
2545 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002546
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002547 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002548 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002549 describeLibclangFailure(Err);
2550 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002551 return -1;
2552 }
2553
2554 if (checkForErrors(TU) != 0)
2555 return -1;
2556
2557 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002558 if (Repeats > 1) {
2559 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2560 clang_defaultReparseOptions(TU));
2561 if (Err != CXError_Success) {
2562 describeLibclangFailure(Err);
2563 clang_disposeTranslationUnit(TU);
2564 return 1;
2565 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002566 }
2567
2568 if (checkForErrors(TU) != 0)
2569 return -1;
2570
2571 for (FI = 0; FI < NumFilenames; ++FI) {
2572 CXFile file = clang_getFile(TU, Filenames[FI]);
2573 if (!file)
2574 continue;
2575
2576 if (checkForErrors(TU) != 0)
2577 return -1;
2578
2579 if (I + 1 == Repeats) {
2580 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2581 clang_findIncludesInFile(TU, file, visitor);
2582
2583 if (checkForErrors(TU) != 0)
2584 return -1;
2585 }
2586 }
2587 }
2588
2589 PrintDiagnostics(TU);
2590 clang_disposeTranslationUnit(TU);
2591 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002592 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002593 free_remapped_files(unsaved_files, num_unsaved_files);
2594 return 0;
2595}
2596
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002597#define MAX_IMPORTED_ASTFILES 200
2598
2599typedef struct {
2600 char **filenames;
2601 unsigned num_files;
2602} ImportedASTFilesData;
2603
2604static ImportedASTFilesData *importedASTs_create() {
2605 ImportedASTFilesData *p;
2606 p = malloc(sizeof(ImportedASTFilesData));
2607 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2608 p->num_files = 0;
2609 return p;
2610}
2611
2612static void importedASTs_dispose(ImportedASTFilesData *p) {
2613 unsigned i;
2614 if (!p)
2615 return;
2616
2617 for (i = 0; i < p->num_files; ++i)
2618 free(p->filenames[i]);
2619 free(p->filenames);
2620 free(p);
2621}
2622
2623static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2624 unsigned i;
2625 assert(p && file);
2626 for (i = 0; i < p->num_files; ++i)
2627 if (strcmp(file, p->filenames[i]) == 0)
2628 return;
2629 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2630 p->filenames[p->num_files++] = strdup(file);
2631}
2632
Nico Weberdf686022014-05-07 21:09:42 +00002633typedef struct IndexDataStringList_ {
2634 struct IndexDataStringList_ *next;
2635 char data[1]; /* Dynamically sized. */
2636} IndexDataStringList;
2637
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002638typedef struct {
2639 const char *check_prefix;
2640 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002641 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002642 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002643 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002644 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002645 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002646 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002647} IndexData;
2648
Nico Weberdf686022014-05-07 21:09:42 +00002649static void free_client_data(IndexData *index_data) {
2650 IndexDataStringList *node = index_data->strings;
2651 while (node) {
2652 IndexDataStringList *next = node->next;
2653 free(node);
2654 node = next;
2655 }
2656 index_data->strings = NULL;
2657}
2658
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002659static void printCheck(IndexData *data) {
2660 if (data->check_prefix) {
2661 if (data->first_check_printed) {
2662 printf("// %s-NEXT: ", data->check_prefix);
2663 } else {
2664 printf("// %s : ", data->check_prefix);
2665 data->first_check_printed = 1;
2666 }
2667 }
2668}
2669
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002670static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002671 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002672 printf("%s", clang_getCString(filename));
2673 clang_disposeString(filename);
2674}
2675
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002676static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2677 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002678 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002679 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002680 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002681 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002682 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002683
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002684 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002685 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2686 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002687 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002688 return;
2689 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002690 if (!file) {
2691 printf("<no idxfile>");
2692 return;
2693 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002694 filename = clang_getFileName((CXFile)file);
2695 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002696 if (strcmp(cname, index_data->main_filename) == 0)
2697 isMainFile = 1;
2698 else
2699 isMainFile = 0;
2700 clang_disposeString(filename);
2701
2702 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002703 printCXIndexFile(file);
2704 printf(":");
2705 }
2706 printf("%d:%d", line, column);
2707}
2708
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002709static unsigned digitCount(unsigned val) {
2710 unsigned c = 1;
2711 while (1) {
2712 if (val < 10)
2713 return c;
2714 ++c;
2715 val /= 10;
2716 }
2717}
2718
Nico Weberdf686022014-05-07 21:09:42 +00002719static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2720 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002721 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002722 IndexData *index_data;
2723 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002724 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002725 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002726 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002727 unsigned line, column;
2728
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002729 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002730 if (!name)
2731 name = "<anon-tag>";
2732
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002733 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002734
2735 node =
2736 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2737 digitCount(line) + digitCount(column) + 2);
2738 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002739 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002740
2741 /* Remember string so it can be freed later. */
2742 index_data = (IndexData *)client_data;
2743 node->next = index_data->strings;
2744 index_data->strings = node;
2745
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002746 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002747}
2748
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002749static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2750 CXIdxClientContainer container;
2751 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002752 if (!container)
2753 printf("[<<NULL>>]");
2754 else
2755 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002756}
2757
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002758static const char *getEntityKindString(CXIdxEntityKind kind) {
2759 switch (kind) {
2760 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2761 case CXIdxEntity_Typedef: return "typedef";
2762 case CXIdxEntity_Function: return "function";
2763 case CXIdxEntity_Variable: return "variable";
2764 case CXIdxEntity_Field: return "field";
2765 case CXIdxEntity_EnumConstant: return "enumerator";
2766 case CXIdxEntity_ObjCClass: return "objc-class";
2767 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2768 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002769 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2770 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002771 case CXIdxEntity_ObjCProperty: return "objc-property";
2772 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2773 case CXIdxEntity_Enum: return "enum";
2774 case CXIdxEntity_Struct: return "struct";
2775 case CXIdxEntity_Union: return "union";
2776 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002777 case CXIdxEntity_CXXNamespace: return "namespace";
2778 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2779 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2780 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2781 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2782 case CXIdxEntity_CXXConstructor: return "constructor";
2783 case CXIdxEntity_CXXDestructor: return "destructor";
2784 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2785 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002786 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002787 }
2788 assert(0 && "Garbage entity kind");
2789 return 0;
2790}
2791
2792static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2793 switch (kind) {
2794 case CXIdxEntity_NonTemplate: return "";
2795 case CXIdxEntity_Template: return "-template";
2796 case CXIdxEntity_TemplatePartialSpecialization:
2797 return "-template-partial-spec";
2798 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002799 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002800 assert(0 && "Garbage entity kind");
2801 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002802}
2803
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002804static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2805 switch (kind) {
2806 case CXIdxEntityLang_None: return "<none>";
2807 case CXIdxEntityLang_C: return "C";
2808 case CXIdxEntityLang_ObjC: return "ObjC";
2809 case CXIdxEntityLang_CXX: return "C++";
2810 }
2811 assert(0 && "Garbage language kind");
2812 return 0;
2813}
2814
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002815static void printEntityInfo(const char *cb,
2816 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002817 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002818 const char *name;
2819 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002820 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002821 index_data = (IndexData *)client_data;
2822 printCheck(index_data);
2823
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00002824 if (!info) {
2825 printf("%s: <<NULL>>", cb);
2826 return;
2827 }
2828
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002829 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002830 if (!name)
2831 name = "<anon-tag>";
2832
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002833 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
2834 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002835 printf(" | name: %s", name);
2836 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002837 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002838
2839 for (i = 0; i != info->numAttributes; ++i) {
2840 const CXIdxAttrInfo *Attr = info->attributes[i];
2841 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002842 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00002843 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002844}
2845
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002846static void printBaseClassInfo(CXClientData client_data,
2847 const CXIdxBaseClassInfo *info) {
2848 printEntityInfo(" <base>", client_data, info->base);
2849 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002850 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002851 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002852 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002853}
2854
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002855static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
2856 CXClientData client_data) {
2857 unsigned i;
2858 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
2859 printEntityInfo(" <protocol>", client_data,
2860 ProtoInfo->protocols[i]->protocol);
2861 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002862 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002863 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002864 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002865 printf("\n");
2866 }
2867}
2868
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002869static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002870 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002871 CXString str;
2872 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002873 unsigned numDiags, i;
2874 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002875 IndexData *index_data;
2876 index_data = (IndexData *)client_data;
2877 printCheck(index_data);
2878
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00002879 numDiags = clang_getNumDiagnosticsInSet(diagSet);
2880 for (i = 0; i != numDiags; ++i) {
2881 diag = clang_getDiagnosticInSet(diagSet, i);
2882 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
2883 cstr = clang_getCString(str);
2884 printf("[diagnostic]: %s\n", cstr);
2885 clang_disposeString(str);
2886
2887 if (getenv("CINDEXTEST_FAILONERROR") &&
2888 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
2889 index_data->fail_for_error = 1;
2890 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002891 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002892}
2893
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002894static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
2895 CXFile file, void *reserved) {
2896 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002897 CXString filename;
2898
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002899 index_data = (IndexData *)client_data;
2900 printCheck(index_data);
2901
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00002902 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002903 index_data->main_filename = clang_getCString(filename);
2904 clang_disposeString(filename);
2905
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002906 printf("[enteredMainFile]: ");
2907 printCXIndexFile((CXIdxClientFile)file);
2908 printf("\n");
2909
2910 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002911}
2912
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002913static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002914 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002915 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002916 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002917 index_data = (IndexData *)client_data;
2918 printCheck(index_data);
2919
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002920 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002921 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002922 printf(" | name: \"%s\"", info->filename);
2923 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002924 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002925 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00002926 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002927
2928 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
2929 if (Mod) {
2930 CXString str = clang_Module_getFullName(Mod);
2931 const char *cstr = clang_getCString(str);
2932 printf(" | module: %s", cstr);
2933 clang_disposeString(str);
2934 }
2935
2936 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002937
2938 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002939}
2940
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002941static CXIdxClientFile index_importedASTFile(CXClientData client_data,
2942 const CXIdxImportedASTFileInfo *info) {
2943 IndexData *index_data;
2944 index_data = (IndexData *)client_data;
2945 printCheck(index_data);
2946
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002947 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002948 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002949 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
2950 clang_disposeString(filename);
2951 }
2952
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002953 printf("[importedASTFile]: ");
2954 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002955 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002956 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002957 printf(" | loc: ");
2958 printCXIndexLoc(info->loc, client_data);
2959 printf(" | name: \"%s\"", clang_getCString(name));
2960 printf(" | isImplicit: %d\n", info->isImplicit);
2961 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002962 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00002963 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002964 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00002965 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00002966
2967 return (CXIdxClientFile)info->file;
2968}
2969
Nico Weber8d19dff2014-05-07 21:05:22 +00002970static CXIdxClientContainer
2971index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002972 IndexData *index_data;
2973 index_data = (IndexData *)client_data;
2974 printCheck(index_data);
2975
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00002976 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002977 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002978}
2979
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002980static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002981 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002982 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002983 const CXIdxObjCCategoryDeclInfo *CatInfo;
2984 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002985 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00002986 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00002987 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00002988 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002989 index_data = (IndexData *)client_data;
2990
2991 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
2992 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002993 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002994 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002995 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00002996 printf(" | semantic-container: ");
2997 printCXIndexContainer(info->semanticContainer);
2998 printf(" | lexical-container: ");
2999 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003000 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003001 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003002 if (info->flags & CXIdxDeclFlag_Skipped) {
3003 assert(!info->isContainer);
3004 printf(" | isContainer: skipped");
3005 } else {
3006 printf(" | isContainer: %d", info->isContainer);
3007 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003008 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003009
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003010 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003011 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003012 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003013 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003014 printf("\n");
3015 }
3016
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003017 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3018 const char *kindName = 0;
3019 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3020 switch (K) {
3021 case CXIdxObjCContainer_ForwardRef:
3022 kindName = "forward-ref"; break;
3023 case CXIdxObjCContainer_Interface:
3024 kindName = "interface"; break;
3025 case CXIdxObjCContainer_Implementation:
3026 kindName = "implementation"; break;
3027 }
3028 printCheck(index_data);
3029 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3030 }
3031
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003032 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003033 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3034 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003035 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003036 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003037 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003038 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003039 printf("\n");
3040 }
3041
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003042 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3043 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003044 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003045 printf("\n");
3046 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003047 }
3048
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003049 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3050 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003051 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003052
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003053 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3054 if (PropInfo->getter) {
3055 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3056 printf("\n");
3057 }
3058 if (PropInfo->setter) {
3059 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3060 printf("\n");
3061 }
3062 }
3063
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003064 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3065 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3066 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3067 printf("\n");
3068 }
3069 }
3070
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003071 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003072 clang_index_setClientContainer(
3073 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003074 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003075}
3076
3077static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003078 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003079 printEntityInfo("[indexEntityReference]", client_data,
3080 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003081 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003082 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003083 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003084 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003085 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003086 printf(" | container: ");
3087 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003088 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003089 switch (info->kind) {
3090 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003091 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003092 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003093 printf("\n");
3094}
3095
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003096static int index_abortQuery(CXClientData client_data, void *reserved) {
3097 IndexData *index_data;
3098 index_data = (IndexData *)client_data;
3099 return index_data->abort;
3100}
3101
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003102static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003103 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003104 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003105 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003106 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003107 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003108 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003109 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003110 index_indexEntityReference
3111};
3112
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003113static unsigned getIndexOptions(void) {
3114 unsigned index_opts;
3115 index_opts = 0;
3116 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3117 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3118 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3119 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003120 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3121 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003122
3123 return index_opts;
3124}
3125
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003126static int index_compile_args(int num_args, const char **args,
3127 CXIndexAction idxAction,
3128 ImportedASTFilesData *importedASTs,
3129 const char *check_prefix) {
3130 IndexData index_data;
3131 unsigned index_opts;
3132 int result;
3133
3134 if (num_args == 0) {
3135 fprintf(stderr, "no compiler arguments\n");
3136 return -1;
3137 }
3138
3139 index_data.check_prefix = check_prefix;
3140 index_data.first_check_printed = 0;
3141 index_data.fail_for_error = 0;
3142 index_data.abort = 0;
3143 index_data.main_filename = "";
3144 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003145 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003146 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003147
3148 index_opts = getIndexOptions();
3149 result = clang_indexSourceFile(idxAction, &index_data,
3150 &IndexCB,sizeof(IndexCB), index_opts,
3151 0, args, num_args, 0, 0, 0,
3152 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003153 if (result != CXError_Success)
3154 describeLibclangFailure(result);
3155
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003156 if (index_data.fail_for_error)
3157 result = -1;
3158
Nico Weberdf686022014-05-07 21:09:42 +00003159 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003160 return result;
3161}
3162
3163static int index_ast_file(const char *ast_file,
3164 CXIndex Idx,
3165 CXIndexAction idxAction,
3166 ImportedASTFilesData *importedASTs,
3167 const char *check_prefix) {
3168 CXTranslationUnit TU;
3169 IndexData index_data;
3170 unsigned index_opts;
3171 int result;
3172
3173 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3174 return -1;
3175
3176 index_data.check_prefix = check_prefix;
3177 index_data.first_check_printed = 0;
3178 index_data.fail_for_error = 0;
3179 index_data.abort = 0;
3180 index_data.main_filename = "";
3181 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003182 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003183 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003184
3185 index_opts = getIndexOptions();
3186 result = clang_indexTranslationUnit(idxAction, &index_data,
3187 &IndexCB,sizeof(IndexCB),
3188 index_opts, TU);
3189 if (index_data.fail_for_error)
3190 result = -1;
3191
3192 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003193 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003194 return result;
3195}
3196
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003197static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003198 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003199 CXIndex Idx;
3200 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003201 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003202 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003203
3204 check_prefix = 0;
3205 if (argc > 0) {
3206 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3207 check_prefix = argv[0] + strlen("-check-prefix=");
3208 ++argv;
3209 --argc;
3210 }
3211 }
3212
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003213 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003214 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003215 fprintf(stderr, "Could not create Index\n");
3216 return 1;
3217 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003218 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003219 importedASTs = 0;
3220 if (full)
3221 importedASTs = importedASTs_create();
3222
3223 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3224 if (result != 0)
3225 goto finished;
3226
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003227 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003228 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003229 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3230 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3231 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003232 }
3233 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003234
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003235finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003236 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003237 clang_IndexAction_dispose(idxAction);
3238 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003239 return result;
3240}
3241
3242static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003243 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003244 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003245 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003246 int result;
3247
3248 check_prefix = 0;
3249 if (argc > 0) {
3250 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3251 check_prefix = argv[0] + strlen("-check-prefix=");
3252 ++argv;
3253 --argc;
3254 }
3255 }
3256
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003257 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003258 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003259 fprintf(stderr, "Could not create Index\n");
3260 return 1;
3261 }
3262 idxAction = clang_IndexAction_create(Idx);
3263
3264 result = index_ast_file(argv[0], Idx, idxAction,
3265 /*importedASTs=*/0, check_prefix);
3266
3267 clang_IndexAction_dispose(idxAction);
3268 clang_disposeIndex(Idx);
3269 return result;
3270}
3271
3272static int index_compile_db(int argc, const char **argv) {
3273 const char *check_prefix;
3274 CXIndex Idx;
3275 CXIndexAction idxAction;
3276 int errorCode = 0;
3277
3278 check_prefix = 0;
3279 if (argc > 0) {
3280 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3281 check_prefix = argv[0] + strlen("-check-prefix=");
3282 ++argv;
3283 --argc;
3284 }
3285 }
3286
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003287 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003288 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003289 return -1;
3290 }
3291
3292 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003293 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003294 fprintf(stderr, "Could not create Index\n");
3295 return 1;
3296 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003297 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003298
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003299 {
3300 const char *database = argv[0];
3301 CXCompilationDatabase db = 0;
3302 CXCompileCommands CCmds = 0;
3303 CXCompileCommand CCmd;
3304 CXCompilationDatabase_Error ec;
3305 CXString wd;
3306#define MAX_COMPILE_ARGS 512
3307 CXString cxargs[MAX_COMPILE_ARGS];
3308 const char *args[MAX_COMPILE_ARGS];
3309 char *tmp;
3310 unsigned len;
3311 char *buildDir;
3312 int i, a, numCmds, numArgs;
3313
3314 len = strlen(database);
3315 tmp = (char *) malloc(len+1);
3316 memcpy(tmp, database, len+1);
3317 buildDir = dirname(tmp);
3318
3319 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3320
3321 if (db) {
3322
3323 if (ec!=CXCompilationDatabase_NoError) {
3324 printf("unexpected error %d code while loading compilation database\n", ec);
3325 errorCode = -1;
3326 goto cdb_end;
3327 }
3328
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003329 if (chdir(buildDir) != 0) {
3330 printf("Could not chdir to %s\n", buildDir);
3331 errorCode = -1;
3332 goto cdb_end;
3333 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003334
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003335 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003336 if (!CCmds) {
3337 printf("compilation db is empty\n");
3338 errorCode = -1;
3339 goto cdb_end;
3340 }
3341
3342 numCmds = clang_CompileCommands_getSize(CCmds);
3343
3344 if (numCmds==0) {
3345 fprintf(stderr, "should not get an empty compileCommand set\n");
3346 errorCode = -1;
3347 goto cdb_end;
3348 }
3349
3350 for (i=0; i<numCmds && errorCode == 0; ++i) {
3351 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3352
3353 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003354 if (chdir(clang_getCString(wd)) != 0) {
3355 printf("Could not chdir to %s\n", clang_getCString(wd));
3356 errorCode = -1;
3357 goto cdb_end;
3358 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003359 clang_disposeString(wd);
3360
3361 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3362 if (numArgs > MAX_COMPILE_ARGS){
3363 fprintf(stderr, "got more compile arguments than maximum\n");
3364 errorCode = -1;
3365 goto cdb_end;
3366 }
3367 for (a=0; a<numArgs; ++a) {
3368 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3369 args[a] = clang_getCString(cxargs[a]);
3370 }
3371
3372 errorCode = index_compile_args(numArgs, args, idxAction,
3373 /*importedASTs=*/0, check_prefix);
3374
3375 for (a=0; a<numArgs; ++a)
3376 clang_disposeString(cxargs[a]);
3377 }
3378 } else {
3379 printf("database loading failed with error code %d.\n", ec);
3380 errorCode = -1;
3381 }
3382
3383 cdb_end:
3384 clang_CompileCommands_dispose(CCmds);
3385 clang_CompilationDatabase_dispose(db);
3386 free(tmp);
3387
3388 }
3389
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003390 clang_IndexAction_dispose(idxAction);
3391 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003392 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003393}
3394
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003395int perform_token_annotation(int argc, const char **argv) {
3396 const char *input = argv[1];
3397 char *filename = 0;
3398 unsigned line, second_line;
3399 unsigned column, second_column;
3400 CXIndex CIdx;
3401 CXTranslationUnit TU = 0;
3402 int errorCode;
3403 struct CXUnsavedFile *unsaved_files = 0;
3404 int num_unsaved_files = 0;
3405 CXToken *tokens;
3406 unsigned num_tokens;
3407 CXSourceRange range;
3408 CXSourceLocation startLoc, endLoc;
3409 CXFile file = 0;
3410 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003411 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003412 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003413 unsigned i;
3414
3415 input += strlen("-test-annotate-tokens=");
3416 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3417 &second_line, &second_column)))
3418 return errorCode;
3419
Richard Smith1ea42eb2012-07-05 08:20:49 +00003420 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3421 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003422 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003423 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003424
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003425 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003426 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3427 argv + num_unsaved_files + 2,
3428 argc - num_unsaved_files - 3,
3429 unsaved_files,
3430 num_unsaved_files,
3431 getDefaultParsingOptions(), &TU);
3432 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003433 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003434 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003435 clang_disposeIndex(CIdx);
3436 free(filename);
3437 free_remapped_files(unsaved_files, num_unsaved_files);
3438 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003439 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003440 errorCode = 0;
3441
Richard Smith1ea42eb2012-07-05 08:20:49 +00003442 if (checkForErrors(TU) != 0) {
3443 errorCode = -1;
3444 goto teardown;
3445 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003446
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003447 if (getenv("CINDEXTEST_EDITING")) {
3448 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003449 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3450 clang_defaultReparseOptions(TU));
3451 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003452 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003453 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003454 errorCode = -1;
3455 goto teardown;
3456 }
3457 }
3458 }
3459
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003460 if (checkForErrors(TU) != 0) {
3461 errorCode = -1;
3462 goto teardown;
3463 }
3464
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003465 file = clang_getFile(TU, filename);
3466 if (!file) {
3467 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3468 errorCode = -1;
3469 goto teardown;
3470 }
3471
3472 startLoc = clang_getLocation(TU, file, line, column);
3473 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003474 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003475 column);
3476 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003477 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003478 }
3479
3480 endLoc = clang_getLocation(TU, file, second_line, second_column);
3481 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003482 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003483 second_line, second_column);
3484 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003485 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003486 }
3487
3488 range = clang_getRange(startLoc, endLoc);
3489 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003490
3491 if (checkForErrors(TU) != 0) {
3492 errorCode = -1;
3493 goto teardown;
3494 }
3495
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003496 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3497 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003498
3499 if (checkForErrors(TU) != 0) {
3500 errorCode = -1;
3501 goto teardown;
3502 }
3503
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003504 skipped_ranges = clang_getSkippedRanges(TU, file);
3505 for (i = 0; i != skipped_ranges->count; ++i) {
3506 unsigned start_line, start_column, end_line, end_column;
3507 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3508 0, &start_line, &start_column, 0);
3509 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3510 0, &end_line, &end_column, 0);
3511 printf("Skipping: ");
3512 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3513 printf("\n");
3514 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003515 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003516
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003517 for (i = 0; i != num_tokens; ++i) {
3518 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003519 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3520 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003521 unsigned start_line, start_column, end_line, end_column;
3522
3523 switch (clang_getTokenKind(tokens[i])) {
3524 case CXToken_Punctuation: kind = "Punctuation"; break;
3525 case CXToken_Keyword: kind = "Keyword"; break;
3526 case CXToken_Identifier: kind = "Identifier"; break;
3527 case CXToken_Literal: kind = "Literal"; break;
3528 case CXToken_Comment: kind = "Comment"; break;
3529 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003530 clang_getSpellingLocation(clang_getRangeStart(extent),
3531 0, &start_line, &start_column, 0);
3532 clang_getSpellingLocation(clang_getRangeEnd(extent),
3533 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003534 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003535 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003536 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003537 if (!clang_isInvalid(cursors[i].kind)) {
3538 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003539 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003540 }
3541 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003542 }
3543 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003544 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003545
3546 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003547 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003548 clang_disposeTranslationUnit(TU);
3549 clang_disposeIndex(CIdx);
3550 free(filename);
3551 free_remapped_files(unsaved_files, num_unsaved_files);
3552 return errorCode;
3553}
3554
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003555static int
3556perform_test_compilation_db(const char *database, int argc, const char **argv) {
3557 CXCompilationDatabase db;
3558 CXCompileCommands CCmds;
3559 CXCompileCommand CCmd;
3560 CXCompilationDatabase_Error ec;
3561 CXString wd;
3562 CXString arg;
3563 int errorCode = 0;
3564 char *tmp;
3565 unsigned len;
3566 char *buildDir;
3567 int i, j, a, numCmds, numArgs;
3568
3569 len = strlen(database);
3570 tmp = (char *) malloc(len+1);
3571 memcpy(tmp, database, len+1);
3572 buildDir = dirname(tmp);
3573
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003574 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003575
3576 if (db) {
3577
3578 if (ec!=CXCompilationDatabase_NoError) {
3579 printf("unexpected error %d code while loading compilation database\n", ec);
3580 errorCode = -1;
3581 goto cdb_end;
3582 }
3583
3584 for (i=0; i<argc && errorCode==0; ) {
3585 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003586 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003587
3588 if (!CCmds) {
3589 printf("file %s not found in compilation db\n", argv[i+1]);
3590 errorCode = -1;
3591 break;
3592 }
3593
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003594 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003595
3596 if (numCmds==0) {
3597 fprintf(stderr, "should not get an empty compileCommand set for file"
3598 " '%s'\n", argv[i+1]);
3599 errorCode = -1;
3600 break;
3601 }
3602
3603 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003604 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003605
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003606 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003607 printf("workdir:'%s'", clang_getCString(wd));
3608 clang_disposeString(wd);
3609
3610 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003611 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003612 for (a=0; a<numArgs; ++a) {
3613 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003614 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003615 printf("%s", clang_getCString(arg));
3616 clang_disposeString(arg);
3617 }
3618 printf("'\n");
3619 }
3620
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003621 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003622
3623 i += 2;
3624 }
3625 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003626 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003627 } else {
3628 printf("database loading failed with error code %d.\n", ec);
3629 errorCode = -1;
3630 }
3631
3632cdb_end:
3633 free(tmp);
3634
3635 return errorCode;
3636}
3637
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003638/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003639/* USR printing. */
3640/******************************************************************************/
3641
3642static int insufficient_usr(const char *kind, const char *usage) {
3643 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3644 return 1;
3645}
3646
3647static unsigned isUSR(const char *s) {
3648 return s[0] == 'c' && s[1] == ':';
3649}
3650
3651static int not_usr(const char *s, const char *arg) {
3652 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3653 return 1;
3654}
3655
3656static void print_usr(CXString usr) {
3657 const char *s = clang_getCString(usr);
3658 printf("%s\n", s);
3659 clang_disposeString(usr);
3660}
3661
3662static void display_usrs() {
3663 fprintf(stderr, "-print-usrs options:\n"
3664 " ObjCCategory <class name> <category name>\n"
3665 " ObjCClass <class name>\n"
3666 " ObjCIvar <ivar name> <class USR>\n"
3667 " ObjCMethod <selector> [0=class method|1=instance method] "
3668 "<class USR>\n"
3669 " ObjCProperty <property name> <class USR>\n"
3670 " ObjCProtocol <protocol name>\n");
3671}
3672
3673int print_usrs(const char **I, const char **E) {
3674 while (I != E) {
3675 const char *kind = *I;
3676 unsigned len = strlen(kind);
3677 switch (len) {
3678 case 8:
3679 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3680 if (I + 2 >= E)
3681 return insufficient_usr(kind, "<ivar name> <class USR>");
3682 if (!isUSR(I[2]))
3683 return not_usr("<class USR>", I[2]);
3684 else {
3685 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003686 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003687 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003688 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3689 }
3690
3691 I += 3;
3692 continue;
3693 }
3694 break;
3695 case 9:
3696 if (memcmp(kind, "ObjCClass", 9) == 0) {
3697 if (I + 1 >= E)
3698 return insufficient_usr(kind, "<class name>");
3699 print_usr(clang_constructUSR_ObjCClass(I[1]));
3700 I += 2;
3701 continue;
3702 }
3703 break;
3704 case 10:
3705 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3706 if (I + 3 >= E)
3707 return insufficient_usr(kind, "<method selector> "
3708 "[0=class method|1=instance method] <class USR>");
3709 if (!isUSR(I[3]))
3710 return not_usr("<class USR>", I[3]);
3711 else {
3712 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003713 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003714 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003715 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3716 }
3717 I += 4;
3718 continue;
3719 }
3720 break;
3721 case 12:
3722 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3723 if (I + 2 >= E)
3724 return insufficient_usr(kind, "<class name> <category name>");
3725 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3726 I += 3;
3727 continue;
3728 }
3729 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3730 if (I + 1 >= E)
3731 return insufficient_usr(kind, "<protocol name>");
3732 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3733 I += 2;
3734 continue;
3735 }
3736 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3737 if (I + 2 >= E)
3738 return insufficient_usr(kind, "<property name> <class USR>");
3739 if (!isUSR(I[2]))
3740 return not_usr("<class USR>", I[2]);
3741 else {
3742 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003743 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003744 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003745 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3746 }
3747 I += 3;
3748 continue;
3749 }
3750 break;
3751 default:
3752 break;
3753 }
3754 break;
3755 }
3756
3757 if (I != E) {
3758 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3759 display_usrs();
3760 return 1;
3761 }
3762 return 0;
3763}
3764
3765int print_usrs_file(const char *file_name) {
3766 char line[2048];
3767 const char *args[128];
3768 unsigned numChars = 0;
3769
3770 FILE *fp = fopen(file_name, "r");
3771 if (!fp) {
3772 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3773 return 1;
3774 }
3775
3776 /* This code is not really all that safe, but it works fine for testing. */
3777 while (!feof(fp)) {
3778 char c = fgetc(fp);
3779 if (c == '\n') {
3780 unsigned i = 0;
3781 const char *s = 0;
3782
3783 if (numChars == 0)
3784 continue;
3785
3786 line[numChars] = '\0';
3787 numChars = 0;
3788
3789 if (line[0] == '/' && line[1] == '/')
3790 continue;
3791
3792 s = strtok(line, " ");
3793 while (s) {
3794 args[i] = s;
3795 ++i;
3796 s = strtok(0, " ");
3797 }
3798 if (print_usrs(&args[0], &args[i]))
3799 return 1;
3800 }
3801 else
3802 line[numChars++] = c;
3803 }
3804
3805 fclose(fp);
3806 return 0;
3807}
3808
3809/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003810/* Command line processing. */
3811/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003812int write_pch_file(const char *filename, int argc, const char *argv[]) {
3813 CXIndex Idx;
3814 CXTranslationUnit TU;
3815 struct CXUnsavedFile *unsaved_files = 0;
3816 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003817 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003818 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00003819
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003820 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00003821
3822 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
3823 clang_disposeIndex(Idx);
3824 return -1;
3825 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003826
3827 Err = clang_parseTranslationUnit2(
3828 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
3829 unsaved_files, num_unsaved_files,
3830 CXTranslationUnit_Incomplete |
3831 CXTranslationUnit_DetailedPreprocessingRecord |
3832 CXTranslationUnit_ForSerialization,
3833 &TU);
3834 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00003835 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003836 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00003837 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003838 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00003839 clang_disposeIndex(Idx);
3840 return 1;
3841 }
3842
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003843 switch (clang_saveTranslationUnit(TU, filename,
3844 clang_defaultSaveOptions(TU))) {
3845 case CXSaveError_None:
3846 break;
3847
3848 case CXSaveError_TranslationErrors:
3849 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
3850 filename);
3851 result = 2;
3852 break;
3853
3854 case CXSaveError_InvalidTU:
3855 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
3856 filename);
3857 result = 3;
3858 break;
3859
3860 case CXSaveError_Unknown:
3861 default:
3862 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
3863 result = 1;
3864 break;
3865 }
3866
Douglas Gregore9386682010-08-13 05:36:37 +00003867 clang_disposeTranslationUnit(TU);
3868 free_remapped_files(unsaved_files, num_unsaved_files);
3869 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00003870 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00003871}
3872
3873/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00003874/* Serialized diagnostics. */
3875/******************************************************************************/
3876
3877static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
3878 switch (error) {
3879 case CXLoadDiag_CannotLoad: return "Cannot Load File";
3880 case CXLoadDiag_None: break;
3881 case CXLoadDiag_Unknown: return "Unknown";
3882 case CXLoadDiag_InvalidFile: return "Invalid File";
3883 }
3884 return "None";
3885}
3886
3887static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
3888 switch (severity) {
3889 case CXDiagnostic_Note: return "note";
3890 case CXDiagnostic_Error: return "error";
3891 case CXDiagnostic_Fatal: return "fatal";
3892 case CXDiagnostic_Ignored: return "ignored";
3893 case CXDiagnostic_Warning: return "warning";
3894 }
3895 return "unknown";
3896}
3897
3898static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003899 if (indent == 0)
3900 return;
3901 fprintf(stderr, "+");
3902 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003903 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00003904 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00003905 --indent;
3906 }
3907}
3908
3909static void printLocation(CXSourceLocation L) {
3910 CXFile File;
3911 CXString FileName;
3912 unsigned line, column, offset;
3913
3914 clang_getExpansionLocation(L, &File, &line, &column, &offset);
3915 FileName = clang_getFileName(File);
3916
3917 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
3918 clang_disposeString(FileName);
3919}
3920
3921static void printRanges(CXDiagnostic D, unsigned indent) {
3922 unsigned i, n = clang_getDiagnosticNumRanges(D);
3923
3924 for (i = 0; i < n; ++i) {
3925 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003926 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003927 Start = clang_getRangeStart(SR);
3928 End = clang_getRangeEnd(SR);
3929
3930 printIndent(indent);
3931 fprintf(stderr, "Range: ");
3932 printLocation(Start);
3933 fprintf(stderr, " ");
3934 printLocation(End);
3935 fprintf(stderr, "\n");
3936 }
3937}
3938
3939static void printFixIts(CXDiagnostic D, unsigned indent) {
3940 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00003941 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003942 for (i = 0 ; i < n; ++i) {
3943 CXSourceRange ReplacementRange;
3944 CXString text;
3945 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
3946
3947 printIndent(indent);
3948 fprintf(stderr, "FIXIT: (");
3949 printLocation(clang_getRangeStart(ReplacementRange));
3950 fprintf(stderr, " - ");
3951 printLocation(clang_getRangeEnd(ReplacementRange));
3952 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
3953 clang_disposeString(text);
3954 }
3955}
3956
3957static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003958 unsigned i, n;
3959
Ted Kremenekd010ba42011-11-10 08:43:12 +00003960 if (!Diags)
3961 return;
3962
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00003963 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00003964 for (i = 0; i < n; ++i) {
3965 CXSourceLocation DiagLoc;
3966 CXDiagnostic D;
3967 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003968 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003969 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00003970 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00003971
3972 D = clang_getDiagnosticInSet(Diags, i);
3973 DiagLoc = clang_getDiagnosticLocation(D);
3974 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
3975 FileName = clang_getFileName(File);
3976 DiagSpelling = clang_getDiagnosticSpelling(D);
3977
3978 printIndent(indent);
3979
3980 fprintf(stderr, "%s:%d:%d: %s: %s",
3981 clang_getCString(FileName),
3982 line,
3983 column,
3984 getSeverityString(clang_getDiagnosticSeverity(D)),
3985 clang_getCString(DiagSpelling));
3986
3987 DiagOption = clang_getDiagnosticOption(D, 0);
3988 DiagOptionStr = clang_getCString(DiagOption);
3989 if (DiagOptionStr) {
3990 fprintf(stderr, " [%s]", DiagOptionStr);
3991 }
3992
Ted Kremenek26a6d492012-04-12 00:03:31 +00003993 DiagCat = clang_getDiagnosticCategoryText(D);
3994 DiagCatStr = clang_getCString(DiagCat);
3995 if (DiagCatStr) {
3996 fprintf(stderr, " [%s]", DiagCatStr);
3997 }
3998
Ted Kremenekd010ba42011-11-10 08:43:12 +00003999 fprintf(stderr, "\n");
4000
4001 printRanges(D, indent);
4002 printFixIts(D, indent);
4003
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004004 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004005 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4006
4007 clang_disposeString(FileName);
4008 clang_disposeString(DiagSpelling);
4009 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004010 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004011 }
4012}
4013
4014static int read_diagnostics(const char *filename) {
4015 enum CXLoadDiag_Error error;
4016 CXString errorString;
4017 CXDiagnosticSet Diags = 0;
4018
4019 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4020 if (!Diags) {
4021 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4022 getDiagnosticCodeStr(error),
4023 clang_getCString(errorString));
4024 clang_disposeString(errorString);
4025 return 1;
4026 }
4027
4028 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004029 fprintf(stderr, "Number of diagnostics: %d\n",
4030 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004031 clang_disposeDiagnosticSet(Diags);
4032 return 0;
4033}
4034
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004035static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004036 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004037 return 0;
4038}
4039
Ted Kremenekd010ba42011-11-10 08:43:12 +00004040/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004041/* Command line processing. */
4042/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004043
Douglas Gregor720d0052010-01-20 21:32:04 +00004044static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004045 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004046 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004047 if (strcmp(s, "-usrs") == 0)
4048 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004049 if (strncmp(s, "-memory-usage", 13) == 0)
4050 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004051 return NULL;
4052}
4053
Ted Kremenekef3339b2009-11-17 18:09:14 +00004054static void print_usage(void) {
4055 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004056 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004057 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004058 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004059 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4060 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004061 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004062 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004063 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004064 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004065 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004066 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004067 "[FileCheck prefix]\n");
4068 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004069 " c-index-test -test-load-tu <AST file> <symbol filter> "
4070 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004071 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4072 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004073 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004074 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004075 " c-index-test -test-load-source-memory-usage "
4076 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004077 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4078 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004079 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004080 " c-index-test -test-load-source-usrs-memory-usage "
4081 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004082 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4083 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004084 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004085 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004086 " c-index-test -test-print-linkage-source {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004087 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004088 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004089 " c-index-test -test-print-bitwidth {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004090 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004091 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004092 " c-index-test -write-pch <file> <compiler arguments>\n");
4093 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004094 " c-index-test -compilation-db [lookup <filename>] database\n");
4095 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004096 " c-index-test -print-build-session-timestamp\n");
4097 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004098 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004099 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004100 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004101 " all - load all symbols, including those from PCH\n"
4102 " local - load all symbols except those in PCH\n"
4103 " category - only load ObjC categories (non-PCH)\n"
4104 " interface - only load ObjC interfaces (non-PCH)\n"
4105 " protocol - only load ObjC protocols (non-PCH)\n"
4106 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004107 " typedef - only load typdefs (non-PCH)\n"
4108 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004109}
4110
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004111/***/
4112
4113int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004114 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004115 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4116 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004117 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004118 return perform_code_completion(argc, argv, 0);
4119 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4120 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004121 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
4122 return inspect_cursor_at(argc, argv);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004123 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4124 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004125 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4126 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004127 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004128 return index_file(argc - 2, argv + 2, /*full=*/0);
4129 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4130 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004131 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4132 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004133 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4134 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004135 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004136 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004137 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004138 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4139 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004140 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004141 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4142 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4143 if (I) {
4144 int trials = atoi(argv[2]);
4145 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4146 NULL);
4147 }
4148 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004149 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004150 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004151
4152 PostVisitTU postVisit = 0;
4153 if (strstr(argv[1], "-memory-usage"))
4154 postVisit = PrintMemoryUsage;
4155
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004156 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004157 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4158 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004159 }
4160 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004161 return perform_file_scan(argv[2], argv[3],
4162 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004163 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4164 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004165 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4166 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4167 PrintInclusionStack);
4168 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4169 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4170 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004171 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4172 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4173 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004174 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004175 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004176 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004177 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4178 return perform_test_load_source(argc - 2, argv + 2, "all",
4179 PrintTypeSize, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004180 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4181 return perform_test_load_source(argc - 2, argv + 2, "all",
4182 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004183 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4184 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004185 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4186 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004187 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4188 if (argc > 2)
4189 return print_usrs(argv + 2, argv + argc);
4190 else {
4191 display_usrs();
4192 return 1;
4193 }
4194 }
4195 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4196 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004197 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4198 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004199 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4200 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004201 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4202 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004203
Ted Kremenekef3339b2009-11-17 18:09:14 +00004204 print_usage();
4205 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004206}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004207
4208/***/
4209
4210/* We intentionally run in a separate thread to ensure we at least minimal
4211 * testing of a multithreaded environment (for example, having a reduced stack
4212 * size). */
4213
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004214typedef struct thread_info {
4215 int argc;
4216 const char **argv;
4217 int result;
4218} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004219void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004220 thread_info *client_data = client_data_v;
4221 client_data->result = cindextest_main(client_data->argc, client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004222}
4223
4224static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004225 /* stdout, and surprisingly even stderr, are not always flushed on process
4226 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004227 fflush(stdout);
4228 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004229}
4230
4231int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004232 thread_info client_data;
4233
Reid Klecknere931c062014-06-05 00:13:43 +00004234 atexit(flush_atexit);
4235
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004236#ifdef CLANG_HAVE_LIBXML
4237 LIBXML_TEST_VERSION
4238#endif
4239
Douglas Gregorf428bf82010-10-27 16:00:01 +00004240 if (getenv("CINDEXTEST_NOTHREADS"))
4241 return cindextest_main(argc, argv);
4242
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004243 client_data.argc = argc;
4244 client_data.argv = argv;
Daniel Dunbar23397c32010-11-04 01:26:31 +00004245 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004246 return client_data.result;
4247}