blob: 5bf5f3d019d9cac1cfdf4fafa2c7d5d8e5880322 [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
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +000026extern int indextest_core_main(int argc, const char **argv);
27
Ted Kremenek1cd27d52009-11-17 18:13:31 +000028/******************************************************************************/
29/* Utility functions. */
30/******************************************************************************/
31
John Thompsonde258b52009-10-27 13:42:56 +000032#ifdef _MSC_VER
33char *basename(const char* path)
34{
35 char* base1 = (char*)strrchr(path, '/');
36 char* base2 = (char*)strrchr(path, '\\');
37 if (base1 && base2)
38 return((base1 > base2) ? base1 + 1 : base2 + 1);
39 else if (base1)
40 return(base1 + 1);
41 else if (base2)
42 return(base2 + 1);
43
44 return((char*)path);
45}
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000046char *dirname(char* path)
47{
48 char* base1 = (char*)strrchr(path, '/');
49 char* base2 = (char*)strrchr(path, '\\');
50 if (base1 && base2)
51 if (base1 > base2)
52 *base1 = 0;
53 else
54 *base2 = 0;
55 else if (base1)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000056 *base1 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000057 else if (base2)
NAKAMURA Takumi1e43baa62012-06-30 11:47:18 +000058 *base2 = 0;
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000059
60 return path;
61}
John Thompsonde258b52009-10-27 13:42:56 +000062#else
Steve Naroffa7753c42009-09-24 20:03:06 +000063extern char *basename(const char *);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +000064extern char *dirname(char *);
John Thompsonde258b52009-10-27 13:42:56 +000065#endif
Steve Naroffa7753c42009-09-24 20:03:06 +000066
Douglas Gregorf2430ba2010-07-25 17:39:21 +000067/** \brief Return the default parsing options. */
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000068static unsigned getDefaultParsingOptions() {
69 unsigned options = CXTranslationUnit_DetailedPreprocessingRecord;
70
71 if (getenv("CINDEXTEST_EDITING"))
Douglas Gregor4a47bca2010-08-09 22:28:58 +000072 options |= clang_defaultEditingTranslationUnitOptions();
Douglas Gregorb14904c2010-08-13 22:48:40 +000073 if (getenv("CINDEXTEST_COMPLETION_CACHING"))
74 options |= CXTranslationUnit_CacheCompletionResults;
Argyrios Kyrtzidiscb373e32011-11-03 02:20:25 +000075 if (getenv("CINDEXTEST_COMPLETION_NO_CACHING"))
76 options &= ~CXTranslationUnit_CacheCompletionResults;
Erik Verbruggen6e922512012-04-12 10:11:59 +000077 if (getenv("CINDEXTEST_SKIP_FUNCTION_BODIES"))
78 options |= CXTranslationUnit_SkipFunctionBodies;
Dmitri Gribenko3292d062012-07-02 17:35:10 +000079 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
80 options |= CXTranslationUnit_IncludeBriefCommentsInCodeCompletion;
Benjamin Kramer5c248d82015-12-15 09:30:31 +000081 if (getenv("CINDEXTEST_CREATE_PREAMBLE_ON_FIRST_PARSE"))
82 options |= CXTranslationUnit_CreatePreambleOnFirstParse;
Manuel Klimek016c0242016-03-01 10:56:19 +000083 if (getenv("CINDEXTEST_KEEP_GOING"))
84 options |= CXTranslationUnit_KeepGoing;
Benjamin Kramer5c248d82015-12-15 09:30:31 +000085
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000086 return options;
87}
88
Patrik Hagglund55701d22014-02-17 11:54:08 +000089/** \brief Returns 0 in case of success, non-zero in case of a failure. */
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +000090static int checkForErrors(CXTranslationUnit TU);
91
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +000092static void describeLibclangFailure(enum CXErrorCode Err) {
93 switch (Err) {
94 case CXError_Success:
95 fprintf(stderr, "Success\n");
96 return;
97
98 case CXError_Failure:
99 fprintf(stderr, "Failure (no details available)\n");
100 return;
101
102 case CXError_Crashed:
103 fprintf(stderr, "Failure: libclang crashed\n");
104 return;
105
106 case CXError_InvalidArguments:
107 fprintf(stderr, "Failure: invalid arguments passed to a libclang routine\n");
108 return;
109
110 case CXError_ASTReadError:
111 fprintf(stderr, "Failure: AST deserialization error occurred\n");
112 return;
113 }
114}
115
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000116static void PrintExtent(FILE *out, unsigned begin_line, unsigned begin_column,
117 unsigned end_line, unsigned end_column) {
118 fprintf(out, "[%d:%d - %d:%d]", begin_line, begin_column,
Daniel Dunbar02968e52010-02-14 10:02:57 +0000119 end_line, end_column);
Daniel Dunbar98c07e02010-02-14 08:32:24 +0000120}
121
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000122static unsigned CreateTranslationUnit(CXIndex Idx, const char *file,
123 CXTranslationUnit *TU) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000124 enum CXErrorCode Err = clang_createTranslationUnit2(Idx, file, TU);
125 if (Err != CXError_Success) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000126 fprintf(stderr, "Unable to load translation unit from '%s'!\n", file);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +0000127 describeLibclangFailure(Err);
128 *TU = 0;
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000129 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000130 }
Ted Kremenek2df52dc2009-11-17 19:37:36 +0000131 return 1;
132}
133
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000134void free_remapped_files(struct CXUnsavedFile *unsaved_files,
135 int num_unsaved_files) {
136 int i;
137 for (i = 0; i != num_unsaved_files; ++i) {
138 free((char *)unsaved_files[i].Filename);
139 free((char *)unsaved_files[i].Contents);
140 }
Douglas Gregor0e3da272010-08-19 20:50:29 +0000141 free(unsaved_files);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000142}
143
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000144static int parse_remapped_files_with_opt(const char *opt_name,
145 int argc, const char **argv,
146 int start_arg,
147 struct CXUnsavedFile **unsaved_files,
148 int *num_unsaved_files) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000149 int i;
150 int arg;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000151 int prefix_len = strlen(opt_name);
152 int arg_indices[20];
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000153 *unsaved_files = 0;
154 *num_unsaved_files = 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000155
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000156 /* Count the number of remapped files. */
157 for (arg = start_arg; arg < argc; ++arg) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000158 if (strncmp(argv[arg], opt_name, prefix_len))
159 continue;
Ted Kremenek29004672010-02-17 00:41:32 +0000160
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000161 assert(*num_unsaved_files < (int)(sizeof(arg_indices)/sizeof(int)));
162 arg_indices[*num_unsaved_files] = arg;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000163 ++*num_unsaved_files;
164 }
Ted Kremenek29004672010-02-17 00:41:32 +0000165
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000166 if (*num_unsaved_files == 0)
167 return 0;
Ted Kremenek29004672010-02-17 00:41:32 +0000168
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000169 *unsaved_files
Douglas Gregor0e3da272010-08-19 20:50:29 +0000170 = (struct CXUnsavedFile *)malloc(sizeof(struct CXUnsavedFile) *
171 *num_unsaved_files);
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000172 for (i = 0; i != *num_unsaved_files; ++i) {
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000173 struct CXUnsavedFile *unsaved = *unsaved_files + i;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000174 const char *arg_string = argv[arg_indices[i]] + prefix_len;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000175 int filename_len;
176 char *filename;
177 char *contents;
178 FILE *to_file;
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000179 const char *sep = strchr(arg_string, ',');
180 if (!sep) {
Ted Kremenek29004672010-02-17 00:41:32 +0000181 fprintf(stderr,
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000182 "error: %sfrom:to argument is missing comma\n", opt_name);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000183 free_remapped_files(*unsaved_files, i);
184 *unsaved_files = 0;
185 *num_unsaved_files = 0;
186 return -1;
187 }
Ted Kremenek29004672010-02-17 00:41:32 +0000188
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000189 /* Open the file that we're remapping to. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000190 to_file = fopen(sep + 1, "rb");
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000191 if (!to_file) {
192 fprintf(stderr, "error: cannot open file %s that we are remapping to\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000193 sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000194 free_remapped_files(*unsaved_files, i);
195 *unsaved_files = 0;
196 *num_unsaved_files = 0;
197 return -1;
198 }
Ted Kremenek29004672010-02-17 00:41:32 +0000199
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000200 /* Determine the length of the file we're remapping to. */
201 fseek(to_file, 0, SEEK_END);
202 unsaved->Length = ftell(to_file);
203 fseek(to_file, 0, SEEK_SET);
Ted Kremenek29004672010-02-17 00:41:32 +0000204
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000205 /* Read the contents of the file we're remapping to. */
206 contents = (char *)malloc(unsaved->Length + 1);
207 if (fread(contents, 1, unsaved->Length, to_file) != unsaved->Length) {
208 fprintf(stderr, "error: unexpected %s reading 'to' file %s\n",
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000209 (feof(to_file) ? "EOF" : "error"), sep + 1);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000210 fclose(to_file);
211 free_remapped_files(*unsaved_files, i);
Richard Smith1ea42eb2012-07-05 08:20:49 +0000212 free(contents);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000213 *unsaved_files = 0;
214 *num_unsaved_files = 0;
215 return -1;
216 }
217 contents[unsaved->Length] = 0;
218 unsaved->Contents = contents;
Ted Kremenek29004672010-02-17 00:41:32 +0000219
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000220 /* Close the file. */
221 fclose(to_file);
Ted Kremenek29004672010-02-17 00:41:32 +0000222
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000223 /* Copy the file name that we're remapping from. */
Argyrios Kyrtzidis5899e892013-12-05 20:13:27 +0000224 filename_len = sep - arg_string;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000225 filename = (char *)malloc(filename_len + 1);
226 memcpy(filename, arg_string, filename_len);
227 filename[filename_len] = 0;
228 unsaved->Filename = filename;
229 }
Ted Kremenek29004672010-02-17 00:41:32 +0000230
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000231 return 0;
232}
233
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000234static int parse_remapped_files(int argc, const char **argv, int start_arg,
235 struct CXUnsavedFile **unsaved_files,
236 int *num_unsaved_files) {
237 return parse_remapped_files_with_opt("-remap-file=", argc, argv, start_arg,
238 unsaved_files, num_unsaved_files);
239}
240
241static int parse_remapped_files_with_try(int try_idx,
242 int argc, const char **argv,
243 int start_arg,
244 struct CXUnsavedFile **unsaved_files,
245 int *num_unsaved_files) {
246 struct CXUnsavedFile *unsaved_files_no_try_idx;
247 int num_unsaved_files_no_try_idx;
248 struct CXUnsavedFile *unsaved_files_try_idx;
249 int num_unsaved_files_try_idx;
250 int ret;
251 char opt_name[32];
252
253 ret = parse_remapped_files(argc, argv, start_arg,
254 &unsaved_files_no_try_idx, &num_unsaved_files_no_try_idx);
255 if (ret)
256 return ret;
257
258 sprintf(opt_name, "-remap-file-%d=", try_idx);
259 ret = parse_remapped_files_with_opt(opt_name, argc, argv, start_arg,
260 &unsaved_files_try_idx, &num_unsaved_files_try_idx);
261 if (ret)
262 return ret;
263
Chandler Carruth6ac555f2015-08-04 03:53:04 +0000264 if (num_unsaved_files_no_try_idx == 0) {
265 *unsaved_files = unsaved_files_try_idx;
266 *num_unsaved_files = num_unsaved_files_try_idx;
267 return 0;
268 }
269 if (num_unsaved_files_try_idx == 0) {
270 *unsaved_files = unsaved_files_no_try_idx;
271 *num_unsaved_files = num_unsaved_files_no_try_idx;
272 return 0;
273 }
274
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +0000275 *num_unsaved_files = num_unsaved_files_no_try_idx + num_unsaved_files_try_idx;
276 *unsaved_files
277 = (struct CXUnsavedFile *)realloc(unsaved_files_no_try_idx,
278 sizeof(struct CXUnsavedFile) *
279 *num_unsaved_files);
280 memcpy(*unsaved_files + num_unsaved_files_no_try_idx,
281 unsaved_files_try_idx, sizeof(struct CXUnsavedFile) *
282 num_unsaved_files_try_idx);
283 free(unsaved_files_try_idx);
284 return 0;
285}
286
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000287static const char *parse_comments_schema(int argc, const char **argv) {
288 const char *CommentsSchemaArg = "-comments-xml-schema=";
289 const char *CommentSchemaFile = NULL;
290
291 if (argc == 0)
292 return CommentSchemaFile;
293
294 if (!strncmp(argv[0], CommentsSchemaArg, strlen(CommentsSchemaArg)))
295 CommentSchemaFile = argv[0] + strlen(CommentsSchemaArg);
296
297 return CommentSchemaFile;
298}
299
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000300/******************************************************************************/
301/* Pretty-printing. */
302/******************************************************************************/
303
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000304static const char *FileCheckPrefix = "CHECK";
305
306static void PrintCString(const char *CStr) {
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000307 if (CStr != NULL && CStr[0] != '\0') {
308 for ( ; *CStr; ++CStr) {
309 const char C = *CStr;
310 switch (C) {
311 case '\n': printf("\\n"); break;
312 case '\r': printf("\\r"); break;
313 case '\t': printf("\\t"); break;
314 case '\v': printf("\\v"); break;
315 case '\f': printf("\\f"); break;
316 default: putchar(C); break;
317 }
318 }
319 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000320}
321
322static void PrintCStringWithPrefix(const char *Prefix, const char *CStr) {
323 printf(" %s=[", Prefix);
324 PrintCString(CStr);
Dmitri Gribenko5188c4b2012-06-26 20:39:18 +0000325 printf("]");
326}
327
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000328static void PrintCXStringAndDispose(CXString Str) {
329 PrintCString(clang_getCString(Str));
330 clang_disposeString(Str);
331}
332
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000333static void PrintCXStringWithPrefix(const char *Prefix, CXString Str) {
334 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
335}
336
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000337static void PrintCXStringWithPrefixAndDispose(const char *Prefix,
338 CXString Str) {
339 PrintCStringWithPrefix(Prefix, clang_getCString(Str));
340 clang_disposeString(Str);
341}
342
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000343static void PrintRange(CXSourceRange R, const char *str) {
344 CXFile begin_file, end_file;
345 unsigned begin_line, begin_column, end_line, end_column;
346
347 clang_getSpellingLocation(clang_getRangeStart(R),
348 &begin_file, &begin_line, &begin_column, 0);
349 clang_getSpellingLocation(clang_getRangeEnd(R),
350 &end_file, &end_line, &end_column, 0);
351 if (!begin_file || !end_file)
352 return;
353
Argyrios Kyrtzidis191a6a82012-03-30 20:58:35 +0000354 if (str)
355 printf(" %s=", str);
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000356 PrintExtent(stdout, begin_line, begin_column, end_line, end_column);
357}
358
Douglas Gregor97c75712010-10-02 22:49:11 +0000359int want_display_name = 0;
360
Douglas Gregord6225d32012-05-08 00:14:45 +0000361static void printVersion(const char *Prefix, CXVersion Version) {
362 if (Version.Major < 0)
363 return;
364 printf("%s%d", Prefix, Version.Major);
365
366 if (Version.Minor < 0)
367 return;
368 printf(".%d", Version.Minor);
369
370 if (Version.Subminor < 0)
371 return;
372 printf(".%d", Version.Subminor);
373}
374
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000375struct CommentASTDumpingContext {
376 int IndentLevel;
377};
378
379static void DumpCXCommentInternal(struct CommentASTDumpingContext *Ctx,
380 CXComment Comment) {
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000381 unsigned i;
382 unsigned e;
383 enum CXCommentKind Kind = clang_Comment_getKind(Comment);
384
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000385 Ctx->IndentLevel++;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000386 for (i = 0, e = Ctx->IndentLevel; i != e; ++i)
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000387 printf(" ");
388
389 printf("(");
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000390 switch (Kind) {
391 case CXComment_Null:
392 printf("CXComment_Null");
393 break;
394 case CXComment_Text:
395 printf("CXComment_Text");
396 PrintCXStringWithPrefixAndDispose("Text",
397 clang_TextComment_getText(Comment));
398 if (clang_Comment_isWhitespace(Comment))
399 printf(" IsWhitespace");
400 if (clang_InlineContentComment_hasTrailingNewline(Comment))
401 printf(" HasTrailingNewline");
402 break;
403 case CXComment_InlineCommand:
404 printf("CXComment_InlineCommand");
405 PrintCXStringWithPrefixAndDispose(
406 "CommandName",
407 clang_InlineCommandComment_getCommandName(Comment));
Dmitri Gribenkod73e4ce2012-07-23 16:43:01 +0000408 switch (clang_InlineCommandComment_getRenderKind(Comment)) {
409 case CXCommentInlineCommandRenderKind_Normal:
410 printf(" RenderNormal");
411 break;
412 case CXCommentInlineCommandRenderKind_Bold:
413 printf(" RenderBold");
414 break;
415 case CXCommentInlineCommandRenderKind_Monospaced:
416 printf(" RenderMonospaced");
417 break;
418 case CXCommentInlineCommandRenderKind_Emphasized:
419 printf(" RenderEmphasized");
420 break;
421 }
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000422 for (i = 0, e = clang_InlineCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000423 i != e; ++i) {
424 printf(" Arg[%u]=", i);
425 PrintCXStringAndDispose(
426 clang_InlineCommandComment_getArgText(Comment, i));
427 }
428 if (clang_InlineContentComment_hasTrailingNewline(Comment))
429 printf(" HasTrailingNewline");
430 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000431 case CXComment_HTMLStartTag: {
432 unsigned NumAttrs;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000433 printf("CXComment_HTMLStartTag");
434 PrintCXStringWithPrefixAndDispose(
435 "Name",
436 clang_HTMLTagComment_getTagName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000437 NumAttrs = clang_HTMLStartTag_getNumAttrs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000438 if (NumAttrs != 0) {
439 printf(" Attrs:");
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000440 for (i = 0; i != NumAttrs; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000441 printf(" ");
442 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrName(Comment, i));
443 printf("=");
444 PrintCXStringAndDispose(clang_HTMLStartTag_getAttrValue(Comment, i));
445 }
446 }
447 if (clang_HTMLStartTagComment_isSelfClosing(Comment))
448 printf(" SelfClosing");
449 if (clang_InlineContentComment_hasTrailingNewline(Comment))
450 printf(" HasTrailingNewline");
451 break;
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000452 }
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000453 case CXComment_HTMLEndTag:
454 printf("CXComment_HTMLEndTag");
455 PrintCXStringWithPrefixAndDispose(
456 "Name",
457 clang_HTMLTagComment_getTagName(Comment));
458 if (clang_InlineContentComment_hasTrailingNewline(Comment))
459 printf(" HasTrailingNewline");
460 break;
461 case CXComment_Paragraph:
462 printf("CXComment_Paragraph");
463 if (clang_Comment_isWhitespace(Comment))
464 printf(" IsWhitespace");
465 break;
466 case CXComment_BlockCommand:
467 printf("CXComment_BlockCommand");
468 PrintCXStringWithPrefixAndDispose(
469 "CommandName",
470 clang_BlockCommandComment_getCommandName(Comment));
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000471 for (i = 0, e = clang_BlockCommandComment_getNumArgs(Comment);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000472 i != e; ++i) {
473 printf(" Arg[%u]=", i);
474 PrintCXStringAndDispose(
475 clang_BlockCommandComment_getArgText(Comment, i));
476 }
477 break;
478 case CXComment_ParamCommand:
479 printf("CXComment_ParamCommand");
480 switch (clang_ParamCommandComment_getDirection(Comment)) {
481 case CXCommentParamPassDirection_In:
482 printf(" in");
483 break;
484 case CXCommentParamPassDirection_Out:
485 printf(" out");
486 break;
487 case CXCommentParamPassDirection_InOut:
488 printf(" in,out");
489 break;
490 }
491 if (clang_ParamCommandComment_isDirectionExplicit(Comment))
492 printf(" explicitly");
493 else
494 printf(" implicitly");
495 PrintCXStringWithPrefixAndDispose(
496 "ParamName",
497 clang_ParamCommandComment_getParamName(Comment));
498 if (clang_ParamCommandComment_isParamIndexValid(Comment))
499 printf(" ParamIndex=%u", clang_ParamCommandComment_getParamIndex(Comment));
500 else
501 printf(" ParamIndex=Invalid");
502 break;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000503 case CXComment_TParamCommand:
504 printf("CXComment_TParamCommand");
505 PrintCXStringWithPrefixAndDispose(
506 "ParamName",
507 clang_TParamCommandComment_getParamName(Comment));
508 if (clang_TParamCommandComment_isParamPositionValid(Comment)) {
509 printf(" ParamPosition={");
510 for (i = 0, e = clang_TParamCommandComment_getDepth(Comment);
511 i != e; ++i) {
512 printf("%u", clang_TParamCommandComment_getIndex(Comment, i));
513 if (i != e - 1)
514 printf(", ");
515 }
516 printf("}");
517 } else
518 printf(" ParamPosition=Invalid");
519 break;
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000520 case CXComment_VerbatimBlockCommand:
521 printf("CXComment_VerbatimBlockCommand");
522 PrintCXStringWithPrefixAndDispose(
523 "CommandName",
524 clang_BlockCommandComment_getCommandName(Comment));
525 break;
526 case CXComment_VerbatimBlockLine:
527 printf("CXComment_VerbatimBlockLine");
528 PrintCXStringWithPrefixAndDispose(
529 "Text",
530 clang_VerbatimBlockLineComment_getText(Comment));
531 break;
532 case CXComment_VerbatimLine:
533 printf("CXComment_VerbatimLine");
534 PrintCXStringWithPrefixAndDispose(
535 "Text",
536 clang_VerbatimLineComment_getText(Comment));
537 break;
538 case CXComment_FullComment:
539 printf("CXComment_FullComment");
540 break;
541 }
542 if (Kind != CXComment_Null) {
543 const unsigned NumChildren = clang_Comment_getNumChildren(Comment);
Dmitri Gribenkof267c872012-07-20 22:00:35 +0000544 unsigned i;
545 for (i = 0; i != NumChildren; ++i) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000546 printf("\n// %s: ", FileCheckPrefix);
547 DumpCXCommentInternal(Ctx, clang_Comment_getChild(Comment, i));
548 }
549 }
550 printf(")");
551 Ctx->IndentLevel--;
552}
553
554static void DumpCXComment(CXComment Comment) {
555 struct CommentASTDumpingContext Ctx;
556 Ctx.IndentLevel = 1;
557 printf("\n// %s: CommentAST=[\n// %s:", FileCheckPrefix, FileCheckPrefix);
558 DumpCXCommentInternal(&Ctx, Comment);
559 printf("]");
560}
561
Chandler Carruthb2faa592014-05-02 23:30:59 +0000562static void ValidateCommentXML(const char *Str, const char *CommentSchemaFile) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000563#ifdef CLANG_HAVE_LIBXML
564 xmlRelaxNGParserCtxtPtr RNGParser;
565 xmlRelaxNGPtr Schema;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000566 xmlDocPtr Doc;
567 xmlRelaxNGValidCtxtPtr ValidationCtxt;
568 int status;
569
Chandler Carruthb2faa592014-05-02 23:30:59 +0000570 if (!CommentSchemaFile)
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000571 return;
572
Chandler Carruthb2faa592014-05-02 23:30:59 +0000573 RNGParser = xmlRelaxNGNewParserCtxt(CommentSchemaFile);
574 if (!RNGParser) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000575 printf(" libXMLError");
576 return;
577 }
Chandler Carruthb2faa592014-05-02 23:30:59 +0000578 Schema = xmlRelaxNGParse(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000579
580 Doc = xmlParseDoc((const xmlChar *) Str);
581
582 if (!Doc) {
583 xmlErrorPtr Error = xmlGetLastError();
584 printf(" CommentXMLInvalid [not well-formed XML: %s]", Error->message);
585 return;
586 }
587
Chandler Carruthb2faa592014-05-02 23:30:59 +0000588 ValidationCtxt = xmlRelaxNGNewValidCtxt(Schema);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000589 status = xmlRelaxNGValidateDoc(ValidationCtxt, Doc);
590 if (!status)
591 printf(" CommentXMLValid");
592 else if (status > 0) {
593 xmlErrorPtr Error = xmlGetLastError();
594 printf(" CommentXMLInvalid [not vaild XML: %s]", Error->message);
595 } else
596 printf(" libXMLError");
597
598 xmlRelaxNGFreeValidCtxt(ValidationCtxt);
599 xmlFreeDoc(Doc);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000600 xmlRelaxNGFree(Schema);
601 xmlRelaxNGFreeParserCtxt(RNGParser);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000602#endif
603}
604
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000605static void PrintCursorComments(CXCursor Cursor,
Chandler Carruthb2faa592014-05-02 23:30:59 +0000606 const char *CommentSchemaFile) {
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000607 {
608 CXString RawComment;
609 const char *RawCommentCString;
610 CXString BriefComment;
611 const char *BriefCommentCString;
612
613 RawComment = clang_Cursor_getRawCommentText(Cursor);
614 RawCommentCString = clang_getCString(RawComment);
615 if (RawCommentCString != NULL && RawCommentCString[0] != '\0') {
616 PrintCStringWithPrefix("RawComment", RawCommentCString);
617 PrintRange(clang_Cursor_getCommentRange(Cursor), "RawCommentRange");
618
619 BriefComment = clang_Cursor_getBriefCommentText(Cursor);
620 BriefCommentCString = clang_getCString(BriefComment);
621 if (BriefCommentCString != NULL && BriefCommentCString[0] != '\0')
622 PrintCStringWithPrefix("BriefComment", BriefCommentCString);
623 clang_disposeString(BriefComment);
624 }
625 clang_disposeString(RawComment);
626 }
627
628 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000629 CXComment Comment = clang_Cursor_getParsedComment(Cursor);
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000630 if (clang_Comment_getKind(Comment) != CXComment_Null) {
631 PrintCXStringWithPrefixAndDispose("FullCommentAsHTML",
632 clang_FullComment_getAsHTML(Comment));
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000633 {
634 CXString XML;
Dmitri Gribenko7acbf002012-09-10 20:32:42 +0000635 XML = clang_FullComment_getAsXML(Comment);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000636 PrintCXStringWithPrefix("FullCommentAsXML", XML);
Chandler Carruthb2faa592014-05-02 23:30:59 +0000637 ValidateCommentXML(clang_getCString(XML), CommentSchemaFile);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +0000638 clang_disposeString(XML);
639 }
640
Dmitri Gribenko5e4fe002012-07-20 21:34:34 +0000641 DumpCXComment(Comment);
642 }
643 }
644}
645
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000646typedef struct {
647 unsigned line;
648 unsigned col;
649} LineCol;
650
651static int lineCol_cmp(const void *p1, const void *p2) {
652 const LineCol *lhs = p1;
653 const LineCol *rhs = p2;
654 if (lhs->line != rhs->line)
655 return (int)lhs->line - (int)rhs->line;
656 return (int)lhs->col - (int)rhs->col;
657}
658
Chandler Carruthb2faa592014-05-02 23:30:59 +0000659static void PrintCursor(CXCursor Cursor, const char *CommentSchemaFile) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +0000660 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000661 if (clang_isInvalid(Cursor.kind)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000662 CXString ks = clang_getCursorKindSpelling(Cursor.kind);
Ted Kremenek29004672010-02-17 00:41:32 +0000663 printf("Invalid Cursor => %s", clang_getCString(ks));
664 clang_disposeString(ks);
665 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000666 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000667 CXString string, ks;
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000668 CXCursor Referenced;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000669 unsigned line, column;
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000670 CXCursor SpecializationOf;
Douglas Gregor99a26af2010-10-01 20:25:15 +0000671 CXCursor *overridden;
672 unsigned num_overridden;
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000673 unsigned RefNameRangeNr;
674 CXSourceRange CursorExtent;
675 CXSourceRange RefNameRange;
Douglas Gregord6225d32012-05-08 00:14:45 +0000676 int AlwaysUnavailable;
677 int AlwaysDeprecated;
678 CXString UnavailableMessage;
679 CXString DeprecatedMessage;
680 CXPlatformAvailability PlatformAvailability[2];
681 int NumPlatformAvailability;
682 int I;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000683
Ted Kremenek29004672010-02-17 00:41:32 +0000684 ks = clang_getCursorKindSpelling(Cursor.kind);
Douglas Gregor97c75712010-10-02 22:49:11 +0000685 string = want_display_name? clang_getCursorDisplayName(Cursor)
686 : clang_getCursorSpelling(Cursor);
Ted Kremenek29004672010-02-17 00:41:32 +0000687 printf("%s=%s", clang_getCString(ks),
688 clang_getCString(string));
689 clang_disposeString(ks);
Steve Naroff8675d5c2009-11-09 17:45:52 +0000690 clang_disposeString(string);
Ted Kremenek29004672010-02-17 00:41:32 +0000691
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000692 Referenced = clang_getCursorReferenced(Cursor);
693 if (!clang_equalCursors(Referenced, clang_getNullCursor())) {
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000694 if (clang_getCursorKind(Referenced) == CXCursor_OverloadedDeclRef) {
695 unsigned I, N = clang_getNumOverloadedDecls(Referenced);
696 printf("[");
697 for (I = 0; I != N; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000698 CXCursor Ovl = clang_getOverloadedDecl(Referenced, I);
Douglas Gregor2967e282010-09-14 00:20:32 +0000699 CXSourceLocation Loc;
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000700 if (I)
701 printf(", ");
702
Douglas Gregor2967e282010-09-14 00:20:32 +0000703 Loc = clang_getCursorLocation(Ovl);
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 }
707 printf("]");
708 } else {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000709 CXSourceLocation Loc = clang_getCursorLocation(Referenced);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000710 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Douglas Gregor16a2bdd2010-09-13 22:52:57 +0000711 printf(":%d:%d", line, column);
712 }
Douglas Gregorad27e8b2010-01-19 01:20:04 +0000713 }
Douglas Gregor6b8232f2010-01-19 19:34:47 +0000714
715 if (clang_isCursorDefinition(Cursor))
716 printf(" (Definition)");
Douglas Gregorf757a122010-08-23 23:00:57 +0000717
718 switch (clang_getCursorAvailability(Cursor)) {
719 case CXAvailability_Available:
720 break;
721
722 case CXAvailability_Deprecated:
723 printf(" (deprecated)");
724 break;
725
726 case CXAvailability_NotAvailable:
727 printf(" (unavailable)");
728 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000729
730 case CXAvailability_NotAccessible:
731 printf(" (inaccessible)");
732 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000733 }
Ted Kremeneka5940822010-08-26 01:42:22 +0000734
Douglas Gregord6225d32012-05-08 00:14:45 +0000735 NumPlatformAvailability
736 = clang_getCursorPlatformAvailability(Cursor,
737 &AlwaysDeprecated,
738 &DeprecatedMessage,
739 &AlwaysUnavailable,
740 &UnavailableMessage,
741 PlatformAvailability, 2);
742 if (AlwaysUnavailable) {
743 printf(" (always unavailable: \"%s\")",
744 clang_getCString(UnavailableMessage));
745 } else if (AlwaysDeprecated) {
746 printf(" (always deprecated: \"%s\")",
747 clang_getCString(DeprecatedMessage));
748 } else {
749 for (I = 0; I != NumPlatformAvailability; ++I) {
750 if (I >= 2)
751 break;
752
753 printf(" (%s", clang_getCString(PlatformAvailability[I].Platform));
754 if (PlatformAvailability[I].Unavailable)
755 printf(", unavailable");
756 else {
757 printVersion(", introduced=", PlatformAvailability[I].Introduced);
758 printVersion(", deprecated=", PlatformAvailability[I].Deprecated);
759 printVersion(", obsoleted=", PlatformAvailability[I].Obsoleted);
760 }
761 if (clang_getCString(PlatformAvailability[I].Message)[0])
762 printf(", message=\"%s\"",
763 clang_getCString(PlatformAvailability[I].Message));
764 printf(")");
765 }
766 }
767 for (I = 0; I != NumPlatformAvailability; ++I) {
768 if (I >= 2)
769 break;
770 clang_disposeCXPlatformAvailability(PlatformAvailability + I);
771 }
772
773 clang_disposeString(DeprecatedMessage);
774 clang_disposeString(UnavailableMessage);
Jonathan Coe29565352016-04-27 12:48:25 +0000775
776 if (clang_CXXConstructor_isDefaultConstructor(Cursor))
777 printf(" (default constructor)");
778
779 if (clang_CXXConstructor_isMoveConstructor(Cursor))
780 printf(" (move constructor)");
781 if (clang_CXXConstructor_isCopyConstructor(Cursor))
782 printf(" (copy constructor)");
783 if (clang_CXXConstructor_isConvertingConstructor(Cursor))
784 printf(" (converting constructor)");
Saleem Abdulrasool6ea75db2015-10-27 15:50:22 +0000785 if (clang_CXXField_isMutable(Cursor))
786 printf(" (mutable)");
Jonathan Coe29565352016-04-27 12:48:25 +0000787 if (clang_CXXMethod_isDefaulted(Cursor))
788 printf(" (defaulted)");
Douglas Gregora8d0c772011-05-13 15:54:42 +0000789 if (clang_CXXMethod_isStatic(Cursor))
790 printf(" (static)");
791 if (clang_CXXMethod_isVirtual(Cursor))
792 printf(" (virtual)");
Dmitri Gribenkoe570ede2014-04-07 14:59:13 +0000793 if (clang_CXXMethod_isConst(Cursor))
794 printf(" (const)");
Dmitri Gribenko62770be2013-05-17 18:38:35 +0000795 if (clang_CXXMethod_isPureVirtual(Cursor))
796 printf(" (pure)");
Argyrios Kyrtzidis23814e42013-04-18 23:53:05 +0000797 if (clang_Cursor_isVariadic(Cursor))
798 printf(" (variadic)");
Argyrios Kyrtzidis7b50fc52013-07-05 20:44:37 +0000799 if (clang_Cursor_isObjCOptional(Cursor))
800 printf(" (@optional)");
801
Ted Kremeneka5940822010-08-26 01:42:22 +0000802 if (Cursor.kind == CXCursor_IBOutletCollectionAttr) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000803 CXType T =
804 clang_getCanonicalType(clang_getIBOutletCollectionType(Cursor));
805 CXString S = clang_getTypeKindSpelling(T.kind);
Ted Kremeneka5940822010-08-26 01:42:22 +0000806 printf(" [IBOutletCollection=%s]", clang_getCString(S));
807 clang_disposeString(S);
808 }
Ted Kremenekae9e2212010-08-27 21:34:58 +0000809
810 if (Cursor.kind == CXCursor_CXXBaseSpecifier) {
811 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
812 unsigned isVirtual = clang_isVirtualBase(Cursor);
813 const char *accessStr = 0;
814
815 switch (access) {
816 case CX_CXXInvalidAccessSpecifier:
817 accessStr = "invalid"; break;
818 case CX_CXXPublic:
819 accessStr = "public"; break;
820 case CX_CXXProtected:
821 accessStr = "protected"; break;
822 case CX_CXXPrivate:
823 accessStr = "private"; break;
824 }
825
826 printf(" [access=%s isVirtual=%s]", accessStr,
827 isVirtual ? "true" : "false");
828 }
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000829
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000830 SpecializationOf = clang_getSpecializedCursorTemplate(Cursor);
831 if (!clang_equalCursors(SpecializationOf, clang_getNullCursor())) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000832 CXSourceLocation Loc = clang_getCursorLocation(SpecializationOf);
833 CXString Name = clang_getCursorSpelling(SpecializationOf);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000834 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000835 printf(" [Specialization of %s:%d:%d]",
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000836 clang_getCString(Name), line, column);
837 clang_disposeString(Name);
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000838
839 if (Cursor.kind == CXCursor_FunctionDecl) {
840 /* Collect the template parameter kinds from the base template. */
841 unsigned NumTemplateArgs = clang_Cursor_getNumTemplateArguments(Cursor);
842 unsigned I;
843 for (I = 0; I < NumTemplateArgs; I++) {
844 enum CXTemplateArgumentKind TAK =
845 clang_Cursor_getTemplateArgumentKind(Cursor, I);
846 switch(TAK) {
847 case CXTemplateArgumentKind_Type:
848 {
849 CXType T = clang_Cursor_getTemplateArgumentType(Cursor, I);
850 CXString S = clang_getTypeSpelling(T);
851 printf(" [Template arg %d: kind: %d, type: %s]",
852 I, TAK, clang_getCString(S));
853 clang_disposeString(S);
854 }
855 break;
856 case CXTemplateArgumentKind_Integral:
Yaron Keren129dfbf2015-05-14 06:53:31 +0000857 printf(" [Template arg %d: kind: %d, intval: %lld]",
Eli Benderskyc27a0c42014-10-10 20:01:05 +0000858 I, TAK, clang_Cursor_getTemplateArgumentValue(Cursor, I));
859 break;
860 default:
861 printf(" [Template arg %d: kind: %d]\n", I, TAK);
862 }
863 }
864 }
Douglas Gregord3f48bd2010-09-02 00:07:54 +0000865 }
Douglas Gregor99a26af2010-10-01 20:25:15 +0000866
867 clang_getOverriddenCursors(Cursor, &overridden, &num_overridden);
868 if (num_overridden) {
869 unsigned I;
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000870 LineCol lineCols[50];
871 assert(num_overridden <= 50);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000872 printf(" [Overrides ");
873 for (I = 0; I != num_overridden; ++I) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000874 CXSourceLocation Loc = clang_getCursorLocation(overridden[I]);
Douglas Gregor229bebd2010-11-09 06:24:54 +0000875 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000876 lineCols[I].line = line;
877 lineCols[I].col = column;
878 }
Michael Liaob94f47a2012-08-30 00:45:32 +0000879 /* Make the order of the override list deterministic. */
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000880 qsort(lineCols, num_overridden, sizeof(LineCol), lineCol_cmp);
881 for (I = 0; I != num_overridden; ++I) {
Douglas Gregor99a26af2010-10-01 20:25:15 +0000882 if (I)
883 printf(", ");
Argyrios Kyrtzidis079ff5c2012-08-22 23:15:52 +0000884 printf("@%d:%d", lineCols[I].line, lineCols[I].col);
Douglas Gregor99a26af2010-10-01 20:25:15 +0000885 }
886 printf("]");
887 clang_disposeOverriddenCursors(overridden);
888 }
Douglas Gregor796d76a2010-10-20 22:00:55 +0000889
890 if (Cursor.kind == CXCursor_InclusionDirective) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000891 CXFile File = clang_getIncludedFile(Cursor);
892 CXString Included = clang_getFileName(File);
Douglas Gregor796d76a2010-10-20 22:00:55 +0000893 printf(" (%s)", clang_getCString(Included));
894 clang_disposeString(Included);
Douglas Gregor37aa4932011-05-04 00:14:37 +0000895
896 if (clang_isFileMultipleIncludeGuarded(TU, File))
897 printf(" [multi-include guarded]");
Douglas Gregor796d76a2010-10-20 22:00:55 +0000898 }
Douglas Gregorc1679ec2011-07-25 17:48:11 +0000899
900 CursorExtent = clang_getCursorExtent(Cursor);
901 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
902 CXNameRange_WantQualifier
903 | CXNameRange_WantSinglePiece
904 | CXNameRange_WantTemplateArgs,
905 0);
906 if (!clang_equalRanges(CursorExtent, RefNameRange))
907 PrintRange(RefNameRange, "SingleRefName");
908
909 for (RefNameRangeNr = 0; 1; RefNameRangeNr++) {
910 RefNameRange = clang_getCursorReferenceNameRange(Cursor,
911 CXNameRange_WantQualifier
912 | CXNameRange_WantTemplateArgs,
913 RefNameRangeNr);
914 if (clang_equalRanges(clang_getNullRange(), RefNameRange))
915 break;
916 if (!clang_equalRanges(CursorExtent, RefNameRange))
917 PrintRange(RefNameRange, "RefName");
918 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000919
Chandler Carruthb2faa592014-05-02 23:30:59 +0000920 PrintCursorComments(Cursor, CommentSchemaFile);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000921
922 {
923 unsigned PropAttrs = clang_Cursor_getObjCPropertyAttributes(Cursor, 0);
924 if (PropAttrs != CXObjCPropertyAttr_noattr) {
925 printf(" [");
926 #define PRINT_PROP_ATTR(A) \
927 if (PropAttrs & CXObjCPropertyAttr_##A) printf(#A ",")
928 PRINT_PROP_ATTR(readonly);
929 PRINT_PROP_ATTR(getter);
930 PRINT_PROP_ATTR(assign);
931 PRINT_PROP_ATTR(readwrite);
932 PRINT_PROP_ATTR(retain);
933 PRINT_PROP_ATTR(copy);
934 PRINT_PROP_ATTR(nonatomic);
935 PRINT_PROP_ATTR(setter);
936 PRINT_PROP_ATTR(atomic);
937 PRINT_PROP_ATTR(weak);
938 PRINT_PROP_ATTR(strong);
939 PRINT_PROP_ATTR(unsafe_unretained);
Manman Ren04fd4d82016-05-31 23:22:04 +0000940 PRINT_PROP_ATTR(class);
Argyrios Kyrtzidis9adfd8a2013-04-18 22:15:49 +0000941 printf("]");
942 }
943 }
Argyrios Kyrtzidis9d9bc012013-04-18 23:29:12 +0000944
945 {
946 unsigned QT = clang_Cursor_getObjCDeclQualifiers(Cursor);
947 if (QT != CXObjCDeclQualifier_None) {
948 printf(" [");
949 #define PRINT_OBJC_QUAL(A) \
950 if (QT & CXObjCDeclQualifier_##A) printf(#A ",")
951 PRINT_OBJC_QUAL(In);
952 PRINT_OBJC_QUAL(Inout);
953 PRINT_OBJC_QUAL(Out);
954 PRINT_OBJC_QUAL(Bycopy);
955 PRINT_OBJC_QUAL(Byref);
956 PRINT_OBJC_QUAL(Oneway);
957 printf("]");
958 }
959 }
Steve Naroff63f475a2009-09-25 21:32:34 +0000960 }
Steve Naroff38c1a7b2009-09-03 15:49:00 +0000961}
Steve Naroff1054e602009-08-31 00:59:03 +0000962
Ted Kremenek29004672010-02-17 00:41:32 +0000963static const char* GetCursorSource(CXCursor Cursor) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +0000964 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Ted Kremenekc560b682010-02-17 00:41:20 +0000965 CXString source;
Douglas Gregor4f46e782010-01-19 21:36:55 +0000966 CXFile file;
Argyrios Kyrtzidis7ca77352011-11-03 02:20:36 +0000967 clang_getExpansionLocation(Loc, &file, 0, 0, 0);
Douglas Gregor4f46e782010-01-19 21:36:55 +0000968 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +0000969 if (!clang_getCString(source)) {
Ted Kremenekc560b682010-02-17 00:41:20 +0000970 clang_disposeString(source);
971 return "<invalid loc>";
972 }
973 else {
Ted Kremenek29004672010-02-17 00:41:32 +0000974 const char *b = basename(clang_getCString(source));
Ted Kremenekc560b682010-02-17 00:41:20 +0000975 clang_disposeString(source);
976 return b;
977 }
Ted Kremenek4c4d6432009-11-17 05:31:58 +0000978}
979
Ted Kremenek1cd27d52009-11-17 18:13:31 +0000980/******************************************************************************/
Ted Kremenekb478ff42010-01-26 17:59:48 +0000981/* Callbacks. */
982/******************************************************************************/
983
984typedef void (*PostVisitTU)(CXTranslationUnit);
985
Douglas Gregor33cdd812010-02-18 18:08:43 +0000986void PrintDiagnostic(CXDiagnostic Diagnostic) {
987 FILE *out = stderr;
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000988 CXFile file;
Douglas Gregord770f732010-02-22 23:17:23 +0000989 CXString Msg;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000990 unsigned display_opts = CXDiagnostic_DisplaySourceLocation
Douglas Gregora750e8e2010-11-19 16:18:16 +0000991 | CXDiagnostic_DisplayColumn | CXDiagnostic_DisplaySourceRanges
992 | CXDiagnostic_DisplayOption;
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000993 unsigned i, num_fixits;
Ted Kremenek599d73a2010-03-25 02:00:39 +0000994
Douglas Gregor1e21cc72010-02-18 23:07:20 +0000995 if (clang_getDiagnosticSeverity(Diagnostic) == CXDiagnostic_Ignored)
Douglas Gregor4f9c3762010-01-28 00:27:43 +0000996 return;
Ted Kremenek29004672010-02-17 00:41:32 +0000997
Douglas Gregord770f732010-02-22 23:17:23 +0000998 Msg = clang_formatDiagnostic(Diagnostic, display_opts);
999 fprintf(stderr, "%s\n", clang_getCString(Msg));
1000 clang_disposeString(Msg);
Ted Kremenek599d73a2010-03-25 02:00:39 +00001001
Douglas Gregor229bebd2010-11-09 06:24:54 +00001002 clang_getSpellingLocation(clang_getDiagnosticLocation(Diagnostic),
1003 &file, 0, 0, 0);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001004 if (!file)
1005 return;
Ted Kremenek29004672010-02-17 00:41:32 +00001006
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001007 num_fixits = clang_getDiagnosticNumFixIts(Diagnostic);
Ted Kremenek4a642302012-03-20 20:49:45 +00001008 fprintf(stderr, "Number FIX-ITs = %d\n", num_fixits);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001009 for (i = 0; i != num_fixits; ++i) {
Douglas Gregor836ec942010-02-19 18:16:06 +00001010 CXSourceRange range;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001011 CXString insertion_text = clang_getDiagnosticFixIt(Diagnostic, i, &range);
1012 CXSourceLocation start = clang_getRangeStart(range);
1013 CXSourceLocation end = clang_getRangeEnd(range);
Douglas Gregor836ec942010-02-19 18:16:06 +00001014 unsigned start_line, start_column, end_line, end_column;
1015 CXFile start_file, end_file;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001016 clang_getSpellingLocation(start, &start_file, &start_line,
1017 &start_column, 0);
1018 clang_getSpellingLocation(end, &end_file, &end_line, &end_column, 0);
Douglas Gregor836ec942010-02-19 18:16:06 +00001019 if (clang_equalLocations(start, end)) {
1020 /* Insertion. */
1021 if (start_file == file)
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001022 fprintf(out, "FIX-IT: Insert \"%s\" at %d:%d\n",
Douglas Gregor836ec942010-02-19 18:16:06 +00001023 clang_getCString(insertion_text), start_line, start_column);
1024 } else if (strcmp(clang_getCString(insertion_text), "") == 0) {
1025 /* Removal. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001026 if (start_file == file && end_file == file) {
1027 fprintf(out, "FIX-IT: Remove ");
1028 PrintExtent(out, start_line, start_column, end_line, end_column);
1029 fprintf(out, "\n");
Douglas Gregor60b11f62010-01-29 00:41:11 +00001030 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001031 } else {
1032 /* Replacement. */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001033 if (start_file == end_file) {
1034 fprintf(out, "FIX-IT: Replace ");
1035 PrintExtent(out, start_line, start_column, end_line, end_column);
Douglas Gregor836ec942010-02-19 18:16:06 +00001036 fprintf(out, " with \"%s\"\n", clang_getCString(insertion_text));
Douglas Gregor9773e3d2010-02-18 22:27:07 +00001037 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001038 }
Douglas Gregor836ec942010-02-19 18:16:06 +00001039 clang_disposeString(insertion_text);
Douglas Gregor60b11f62010-01-29 00:41:11 +00001040 }
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001041}
1042
Ted Kremenek914c7e62012-02-14 02:46:03 +00001043void PrintDiagnosticSet(CXDiagnosticSet Set) {
1044 int i = 0, n = clang_getNumDiagnosticsInSet(Set);
1045 for ( ; i != n ; ++i) {
1046 CXDiagnostic Diag = clang_getDiagnosticInSet(Set, i);
1047 CXDiagnosticSet ChildDiags = clang_getChildDiagnostics(Diag);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001048 PrintDiagnostic(Diag);
Ted Kremenek914c7e62012-02-14 02:46:03 +00001049 if (ChildDiags)
1050 PrintDiagnosticSet(ChildDiags);
1051 }
1052}
1053
1054void PrintDiagnostics(CXTranslationUnit TU) {
1055 CXDiagnosticSet TUSet = clang_getDiagnosticSetFromTU(TU);
1056 PrintDiagnosticSet(TUSet);
1057 clang_disposeDiagnosticSet(TUSet);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001058}
1059
Ted Kremenek83f642e2011-04-18 22:47:10 +00001060void PrintMemoryUsage(CXTranslationUnit TU) {
Matt Beaumont-Gayd6238f42011-08-29 16:37:29 +00001061 unsigned long total = 0;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001062 unsigned i = 0;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001063 CXTUResourceUsage usage = clang_getCXTUResourceUsage(TU);
Francois Pichet45cc5462011-04-18 23:33:22 +00001064 fprintf(stderr, "Memory usage:\n");
Ted Kremenek11d1a422011-04-18 23:42:53 +00001065 for (i = 0 ; i != usage.numEntries; ++i) {
Ted Kremenek23324122011-04-20 16:41:07 +00001066 const char *name = clang_getTUResourceUsageName(usage.entries[i].kind);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001067 unsigned long amount = usage.entries[i].amount;
1068 total += amount;
Ted Kremenek11d1a422011-04-18 23:42:53 +00001069 fprintf(stderr, " %s : %ld bytes (%f MBytes)\n", name, amount,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001070 ((double) amount)/(1024*1024));
1071 }
Ted Kremenek11d1a422011-04-18 23:42:53 +00001072 fprintf(stderr, " TOTAL = %ld bytes (%f MBytes)\n", total,
Ted Kremenek83f642e2011-04-18 22:47:10 +00001073 ((double) total)/(1024*1024));
Ted Kremenek23324122011-04-20 16:41:07 +00001074 clang_disposeCXTUResourceUsage(usage);
Ted Kremenek83f642e2011-04-18 22:47:10 +00001075}
1076
Ted Kremenekb478ff42010-01-26 17:59:48 +00001077/******************************************************************************/
Douglas Gregor720d0052010-01-20 21:32:04 +00001078/* Logic for testing traversal. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001079/******************************************************************************/
1080
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001081static void PrintCursorExtent(CXCursor C) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001082 CXSourceRange extent = clang_getCursorExtent(C);
1083 PrintRange(extent, "Extent");
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001084}
1085
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001086/* Data used by the visitors. */
1087typedef struct {
Douglas Gregor720d0052010-01-20 21:32:04 +00001088 CXTranslationUnit TU;
1089 enum CXCursorKind *Filter;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001090 const char *CommentSchemaFile;
Douglas Gregor720d0052010-01-20 21:32:04 +00001091} VisitorData;
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001092
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001093
Ted Kremenek29004672010-02-17 00:41:32 +00001094enum CXChildVisitResult FilteredPrintingVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001095 CXCursor Parent,
1096 CXClientData ClientData) {
1097 VisitorData *Data = (VisitorData *)ClientData;
1098 if (!Data->Filter || (Cursor.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001099 CXSourceLocation Loc = clang_getCursorLocation(Cursor);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001100 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001101 clang_getSpellingLocation(Loc, 0, &line, &column, 0);
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001102 printf("// %s: %s:%d:%d: ", FileCheckPrefix,
Douglas Gregor4f46e782010-01-19 21:36:55 +00001103 GetCursorSource(Cursor), line, column);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001104 PrintCursor(Cursor, Data->CommentSchemaFile);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001105 PrintCursorExtent(Cursor);
Argyrios Kyrtzidis1ab09cc2013-04-11 17:02:10 +00001106 if (clang_isDeclaration(Cursor.kind)) {
1107 enum CX_CXXAccessSpecifier access = clang_getCXXAccessSpecifier(Cursor);
1108 const char *accessStr = 0;
1109
1110 switch (access) {
1111 case CX_CXXInvalidAccessSpecifier: break;
1112 case CX_CXXPublic:
1113 accessStr = "public"; break;
1114 case CX_CXXProtected:
1115 accessStr = "protected"; break;
1116 case CX_CXXPrivate:
1117 accessStr = "private"; break;
1118 }
1119
1120 if (accessStr)
1121 printf(" [access=%s]", accessStr);
1122 }
Ted Kremenek29004672010-02-17 00:41:32 +00001123 printf("\n");
Douglas Gregor720d0052010-01-20 21:32:04 +00001124 return CXChildVisit_Recurse;
Steve Naroff772c1a42009-08-31 14:26:51 +00001125 }
Ted Kremenek29004672010-02-17 00:41:32 +00001126
Douglas Gregor720d0052010-01-20 21:32:04 +00001127 return CXChildVisit_Continue;
Steve Naroff1054e602009-08-31 00:59:03 +00001128}
Steve Naroffa1c72842009-08-28 15:28:48 +00001129
Ted Kremenek29004672010-02-17 00:41:32 +00001130static enum CXChildVisitResult FunctionScanVisitor(CXCursor Cursor,
Douglas Gregor720d0052010-01-20 21:32:04 +00001131 CXCursor Parent,
1132 CXClientData ClientData) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001133 const char *startBuf, *endBuf;
1134 unsigned startLine, startColumn, endLine, endColumn, curLine, curColumn;
1135 CXCursor Ref;
Douglas Gregor720d0052010-01-20 21:32:04 +00001136 VisitorData *Data = (VisitorData *)ClientData;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001137
Douglas Gregor6b8232f2010-01-19 19:34:47 +00001138 if (Cursor.kind != CXCursor_FunctionDecl ||
1139 !clang_isCursorDefinition(Cursor))
Douglas Gregor720d0052010-01-20 21:32:04 +00001140 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001141
1142 clang_getDefinitionSpellingAndExtent(Cursor, &startBuf, &endBuf,
1143 &startLine, &startColumn,
1144 &endLine, &endColumn);
1145 /* Probe the entire body, looking for both decls and refs. */
1146 curLine = startLine;
1147 curColumn = startColumn;
1148
1149 while (startBuf < endBuf) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001150 CXSourceLocation Loc;
Douglas Gregor4f46e782010-01-19 21:36:55 +00001151 CXFile file;
Ted Kremenekc560b682010-02-17 00:41:20 +00001152 CXString source;
Ted Kremenek29004672010-02-17 00:41:32 +00001153
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001154 if (*startBuf == '\n') {
1155 startBuf++;
1156 curLine++;
1157 curColumn = 1;
1158 } else if (*startBuf != '\t')
1159 curColumn++;
Ted Kremenek29004672010-02-17 00:41:32 +00001160
Douglas Gregor66a58812010-01-18 22:46:11 +00001161 Loc = clang_getCursorLocation(Cursor);
Douglas Gregor229bebd2010-11-09 06:24:54 +00001162 clang_getSpellingLocation(Loc, &file, 0, 0, 0);
Ted Kremenek29004672010-02-17 00:41:32 +00001163
Douglas Gregor4f46e782010-01-19 21:36:55 +00001164 source = clang_getFileName(file);
Ted Kremenek29004672010-02-17 00:41:32 +00001165 if (clang_getCString(source)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001166 CXSourceLocation RefLoc
1167 = clang_getLocation(Data->TU, file, curLine, curColumn);
Douglas Gregor816fd362010-01-22 21:44:22 +00001168 Ref = clang_getCursor(Data->TU, RefLoc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001169 if (Ref.kind == CXCursor_NoDeclFound) {
1170 /* Nothing found here; that's fine. */
1171 } else if (Ref.kind != CXCursor_FunctionDecl) {
1172 printf("// %s: %s:%d:%d: ", FileCheckPrefix, GetCursorSource(Ref),
1173 curLine, curColumn);
Chandler Carruthb2faa592014-05-02 23:30:59 +00001174 PrintCursor(Ref, Data->CommentSchemaFile);
Douglas Gregor66a58812010-01-18 22:46:11 +00001175 printf("\n");
1176 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001177 }
Ted Kremenekc560b682010-02-17 00:41:20 +00001178 clang_disposeString(source);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001179 startBuf++;
1180 }
Ted Kremenek29004672010-02-17 00:41:32 +00001181
Douglas Gregor720d0052010-01-20 21:32:04 +00001182 return CXChildVisit_Continue;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001183}
1184
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001185/******************************************************************************/
1186/* USR testing. */
1187/******************************************************************************/
1188
Douglas Gregor720d0052010-01-20 21:32:04 +00001189enum CXChildVisitResult USRVisitor(CXCursor C, CXCursor parent,
1190 CXClientData ClientData) {
1191 VisitorData *Data = (VisitorData *)ClientData;
1192 if (!Data->Filter || (C.kind == *(enum CXCursorKind *)Data->Filter)) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001193 CXString USR = clang_getCursorUSR(C);
1194 const char *cstr = clang_getCString(USR);
Ted Kremenek6d159c12010-04-20 23:15:40 +00001195 if (!cstr || cstr[0] == '\0') {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001196 clang_disposeString(USR);
Ted Kremenek7afa85b2010-04-16 21:31:52 +00001197 return CXChildVisit_Recurse;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001198 }
Ted Kremenek6d159c12010-04-20 23:15:40 +00001199 printf("// %s: %s %s", FileCheckPrefix, GetCursorSource(C), cstr);
1200
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001201 PrintCursorExtent(C);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001202 printf("\n");
1203 clang_disposeString(USR);
Ted Kremenek29004672010-02-17 00:41:32 +00001204
Douglas Gregor720d0052010-01-20 21:32:04 +00001205 return CXChildVisit_Recurse;
Ted Kremenek29004672010-02-17 00:41:32 +00001206 }
1207
Douglas Gregor720d0052010-01-20 21:32:04 +00001208 return CXChildVisit_Continue;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001209}
1210
1211/******************************************************************************/
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001212/* Inclusion stack testing. */
1213/******************************************************************************/
1214
1215void InclusionVisitor(CXFile includedFile, CXSourceLocation *includeStack,
1216 unsigned includeStackLen, CXClientData data) {
Ted Kremenek29004672010-02-17 00:41:32 +00001217
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001218 unsigned i;
Ted Kremenekc560b682010-02-17 00:41:20 +00001219 CXString fname;
1220
1221 fname = clang_getFileName(includedFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001222 printf("file: %s\nincluded by:\n", clang_getCString(fname));
Ted Kremenekc560b682010-02-17 00:41:20 +00001223 clang_disposeString(fname);
Ted Kremenek29004672010-02-17 00:41:32 +00001224
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001225 for (i = 0; i < includeStackLen; ++i) {
1226 CXFile includingFile;
1227 unsigned line, column;
Douglas Gregor229bebd2010-11-09 06:24:54 +00001228 clang_getSpellingLocation(includeStack[i], &includingFile, &line,
1229 &column, 0);
Ted Kremenekc560b682010-02-17 00:41:20 +00001230 fname = clang_getFileName(includingFile);
Ted Kremenek29004672010-02-17 00:41:32 +00001231 printf(" %s:%d:%d\n", clang_getCString(fname), line, column);
Ted Kremenekc560b682010-02-17 00:41:20 +00001232 clang_disposeString(fname);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001233 }
1234 printf("\n");
1235}
1236
1237void PrintInclusionStack(CXTranslationUnit TU) {
Ted Kremenek29004672010-02-17 00:41:32 +00001238 clang_getInclusions(TU, InclusionVisitor, NULL);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00001239}
1240
1241/******************************************************************************/
Ted Kremenek83b28a22010-03-03 06:37:58 +00001242/* Linkage testing. */
1243/******************************************************************************/
1244
1245static enum CXChildVisitResult PrintLinkage(CXCursor cursor, CXCursor p,
1246 CXClientData d) {
1247 const char *linkage = 0;
1248
1249 if (clang_isInvalid(clang_getCursorKind(cursor)))
1250 return CXChildVisit_Recurse;
1251
1252 switch (clang_getCursorLinkage(cursor)) {
1253 case CXLinkage_Invalid: break;
Douglas Gregor0b466502010-03-04 19:36:27 +00001254 case CXLinkage_NoLinkage: linkage = "NoLinkage"; break;
1255 case CXLinkage_Internal: linkage = "Internal"; break;
1256 case CXLinkage_UniqueExternal: linkage = "UniqueExternal"; break;
1257 case CXLinkage_External: linkage = "External"; break;
Ted Kremenek83b28a22010-03-03 06:37:58 +00001258 }
1259
1260 if (linkage) {
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001261 PrintCursor(cursor, NULL);
Ted Kremenek83b28a22010-03-03 06:37:58 +00001262 printf("linkage=%s\n", linkage);
1263 }
1264
1265 return CXChildVisit_Recurse;
1266}
1267
1268/******************************************************************************/
Ehsan Akhgarib743de72016-05-31 15:55:51 +00001269/* Visibility testing. */
1270/******************************************************************************/
1271
1272static enum CXChildVisitResult PrintVisibility(CXCursor cursor, CXCursor p,
1273 CXClientData d) {
1274 const char *visibility = 0;
1275
1276 if (clang_isInvalid(clang_getCursorKind(cursor)))
1277 return CXChildVisit_Recurse;
1278
1279 switch (clang_getCursorVisibility(cursor)) {
1280 case CXVisibility_Invalid: break;
1281 case CXVisibility_Hidden: visibility = "Hidden"; break;
1282 case CXVisibility_Protected: visibility = "Protected"; break;
1283 case CXVisibility_Default: visibility = "Default"; break;
1284 }
1285
1286 if (visibility) {
1287 PrintCursor(cursor, NULL);
1288 printf("visibility=%s\n", visibility);
1289 }
1290
1291 return CXChildVisit_Recurse;
1292}
1293
1294/******************************************************************************/
Ted Kremenek6bca9842010-05-14 21:29:26 +00001295/* Typekind testing. */
1296/******************************************************************************/
1297
Dmitri Gribenko00353722013-02-15 21:15:49 +00001298static void PrintTypeAndTypeKind(CXType T, const char *Format) {
1299 CXString TypeSpelling, TypeKindSpelling;
1300
1301 TypeSpelling = clang_getTypeSpelling(T);
1302 TypeKindSpelling = clang_getTypeKindSpelling(T.kind);
1303 printf(Format,
1304 clang_getCString(TypeSpelling),
1305 clang_getCString(TypeKindSpelling));
1306 clang_disposeString(TypeSpelling);
1307 clang_disposeString(TypeKindSpelling);
1308}
1309
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001310static enum CXVisitorResult FieldVisitor(CXCursor C,
1311 CXClientData client_data) {
1312 (*(int *) client_data)+=1;
1313 return CXVisit_Continue;
1314}
1315
Dmitri Gribenko00353722013-02-15 21:15:49 +00001316static enum CXChildVisitResult PrintType(CXCursor cursor, CXCursor p,
1317 CXClientData d) {
Ted Kremenek6bca9842010-05-14 21:29:26 +00001318 if (!clang_isInvalid(clang_getCursorKind(cursor))) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001319 CXType T = clang_getCursorType(cursor);
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001320 enum CXRefQualifierKind RQ = clang_Type_getCXXRefQualifier(T);
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001321 PrintCursor(cursor, NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00001322 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
Douglas Gregor56a63802011-01-27 16:27:11 +00001323 if (clang_isConstQualifiedType(T))
1324 printf(" const");
1325 if (clang_isVolatileQualifiedType(T))
1326 printf(" volatile");
1327 if (clang_isRestrictQualifiedType(T))
1328 printf(" restrict");
Argyrios Kyrtzidisadff3ae2013-10-11 19:58:38 +00001329 if (RQ == CXRefQualifier_LValue)
1330 printf(" lvalue-ref-qualifier");
1331 if (RQ == CXRefQualifier_RValue)
1332 printf(" rvalue-ref-qualifier");
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001333 /* Print the canonical type if it is different. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001334 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001335 CXType CT = clang_getCanonicalType(T);
Ted Kremenekc1508872010-06-21 20:15:39 +00001336 if (!clang_equalTypes(T, CT)) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001337 PrintTypeAndTypeKind(CT, " [canonicaltype=%s] [canonicaltypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001338 }
1339 }
Benjamin Kramer1e63c742010-06-22 09:29:44 +00001340 /* Print the return type if it exists. */
Ted Kremenekc1508872010-06-21 20:15:39 +00001341 {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001342 CXType RT = clang_getCursorResultType(cursor);
Ted Kremenekc1508872010-06-21 20:15:39 +00001343 if (RT.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001344 PrintTypeAndTypeKind(RT, " [resulttype=%s] [resulttypekind=%s]");
Ted Kremenekc1508872010-06-21 20:15:39 +00001345 }
1346 }
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001347 /* Print the argument types if they exist. */
1348 {
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001349 int NumArgs = clang_Cursor_getNumArguments(cursor);
1350 if (NumArgs != -1 && NumArgs != 0) {
Argyrios Kyrtzidis08804172012-04-11 19:54:09 +00001351 int i;
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001352 printf(" [args=");
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001353 for (i = 0; i < NumArgs; ++i) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001354 CXType T = clang_getCursorType(clang_Cursor_getArgument(cursor, i));
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001355 if (T.kind != CXType_Invalid) {
Dmitri Gribenko00353722013-02-15 21:15:49 +00001356 PrintTypeAndTypeKind(T, " [%s] [%s]");
Argyrios Kyrtzidis0c27e4b2012-04-11 19:32:19 +00001357 }
1358 }
1359 printf("]");
1360 }
1361 }
Dmitri Gribenko6ede6ab2014-02-27 16:05:05 +00001362 /* Print the template argument types if they exist. */
1363 {
1364 int NumTArgs = clang_Type_getNumTemplateArguments(T);
1365 if (NumTArgs != -1 && NumTArgs != 0) {
1366 int i;
1367 printf(" [templateargs/%d=", NumTArgs);
1368 for (i = 0; i < NumTArgs; ++i) {
1369 CXType TArg = clang_Type_getTemplateArgumentAsType(T, i);
1370 if (TArg.kind != CXType_Invalid) {
1371 PrintTypeAndTypeKind(TArg, " [type=%s] [typekind=%s]");
1372 }
1373 }
1374 printf("]");
1375 }
1376 }
Ted Kremenek0c7476a2010-07-30 00:14:11 +00001377 /* Print if this is a non-POD type. */
1378 printf(" [isPOD=%d]", clang_isPODType(T));
Anders Waldenborgddce74f2014-04-09 19:16:08 +00001379 /* Print the pointee type. */
1380 {
1381 CXType PT = clang_getPointeeType(T);
1382 if (PT.kind != CXType_Invalid) {
1383 PrintTypeAndTypeKind(PT, " [pointeetype=%s] [pointeekind=%s]");
1384 }
1385 }
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001386 /* Print the number of fields if they exist. */
1387 {
1388 int numFields = 0;
1389 if (clang_Type_visitFields(T, FieldVisitor, &numFields)){
1390 if (numFields != 0) {
1391 printf(" [nbFields=%d]", numFields);
1392 }
1393 /* Print if it is an anonymous record. */
1394 {
1395 unsigned isAnon = clang_Cursor_isAnonymous(cursor);
1396 if (isAnon != 0) {
1397 printf(" [isAnon=%d]", isAnon);
1398 }
1399 }
1400 }
1401 }
Ted Kremenekc1508872010-06-21 20:15:39 +00001402
Ted Kremenek6bca9842010-05-14 21:29:26 +00001403 printf("\n");
1404 }
1405 return CXChildVisit_Recurse;
1406}
1407
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001408static enum CXChildVisitResult PrintTypeSize(CXCursor cursor, CXCursor p,
1409 CXClientData d) {
1410 CXType T;
1411 enum CXCursorKind K = clang_getCursorKind(cursor);
1412 if (clang_isInvalid(K))
1413 return CXChildVisit_Recurse;
1414 T = clang_getCursorType(cursor);
1415 PrintCursor(cursor, NULL);
1416 PrintTypeAndTypeKind(T, " [type=%s] [typekind=%s]");
1417 /* Print the type sizeof if applicable. */
1418 {
1419 long long Size = clang_Type_getSizeOf(T);
1420 if (Size >= 0 || Size < -1 ) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001421 printf(" [sizeof=%lld]", Size);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001422 }
1423 }
1424 /* Print the type alignof if applicable. */
1425 {
1426 long long Align = clang_Type_getAlignOf(T);
1427 if (Align >= 0 || Align < -1) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00001428 printf(" [alignof=%lld]", Align);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001429 }
1430 }
1431 /* Print the record field offset if applicable. */
1432 {
Nico Weber82098cb2014-04-24 04:14:12 +00001433 CXString FieldSpelling = clang_getCursorSpelling(cursor);
1434 const char *FieldName = clang_getCString(FieldSpelling);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001435 /* recurse to get the first parent record that is not anonymous. */
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001436 unsigned RecordIsAnonymous = 0;
Nico Weber82098cb2014-04-24 04:14:12 +00001437 if (clang_getCursorKind(cursor) == CXCursor_FieldDecl) {
David Blaikie263942f2016-05-03 22:14:14 +00001438 CXCursor Record;
1439 CXCursor Parent = p;
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001440 do {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001441 Record = Parent;
1442 Parent = clang_getCursorSemanticParent(Record);
1443 RecordIsAnonymous = clang_Cursor_isAnonymous(Record);
1444 /* Recurse as long as the parent is a CXType_Record and the Record
1445 is anonymous */
1446 } while ( clang_getCursorType(Parent).kind == CXType_Record &&
1447 RecordIsAnonymous > 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001448 {
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001449 long long Offset = clang_Type_getOffsetOf(clang_getCursorType(Record),
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001450 FieldName);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001451 long long Offset2 = clang_Cursor_getOffsetOfField(cursor);
1452 if (Offset == Offset2){
Yaron Keren129dfbf2015-05-14 06:53:31 +00001453 printf(" [offsetof=%lld]", Offset);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001454 } else {
1455 /* Offsets will be different in anonymous records. */
Yaron Keren129dfbf2015-05-14 06:53:31 +00001456 printf(" [offsetof=%lld/%lld]", Offset, Offset2);
Argyrios Kyrtzidis2bff5162015-04-13 16:55:04 +00001457 }
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001458 }
1459 }
Nico Weber82098cb2014-04-24 04:14:12 +00001460 clang_disposeString(FieldSpelling);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00001461 }
1462 /* Print if its a bitfield */
1463 {
1464 int IsBitfield = clang_Cursor_isBitField(cursor);
1465 if (IsBitfield)
1466 printf(" [BitFieldSize=%d]", clang_getFieldDeclBitWidth(cursor));
1467 }
1468 printf("\n");
1469 return CXChildVisit_Recurse;
1470}
1471
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001472/******************************************************************************/
Eli Bendersky44a206f2014-07-31 18:04:56 +00001473/* Mangling testing. */
1474/******************************************************************************/
1475
1476static enum CXChildVisitResult PrintMangledName(CXCursor cursor, CXCursor p,
1477 CXClientData d) {
Craig Topper416421c2015-10-08 03:37:36 +00001478 CXString MangledName;
Ehsan Akhgarif8d44de2015-10-08 00:01:20 +00001479 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1480 return CXChildVisit_Recurse;
Eli Bendersky44a206f2014-07-31 18:04:56 +00001481 PrintCursor(cursor, NULL);
1482 MangledName = clang_Cursor_getMangling(cursor);
1483 printf(" [mangled=%s]\n", clang_getCString(MangledName));
Eli Bendersky78e83d82014-08-01 12:55:44 +00001484 clang_disposeString(MangledName);
Eli Bendersky44a206f2014-07-31 18:04:56 +00001485 return CXChildVisit_Continue;
1486}
1487
Saleem Abdulrasool60034432015-11-12 03:57:22 +00001488static enum CXChildVisitResult PrintManglings(CXCursor cursor, CXCursor p,
1489 CXClientData d) {
1490 unsigned I, E;
1491 CXStringSet *Manglings = NULL;
1492 if (clang_isUnexposed(clang_getCursorKind(cursor)))
1493 return CXChildVisit_Recurse;
1494 if (!clang_isDeclaration(clang_getCursorKind(cursor)))
1495 return CXChildVisit_Recurse;
1496 if (clang_getCursorKind(cursor) == CXCursor_ParmDecl)
1497 return CXChildVisit_Continue;
1498 PrintCursor(cursor, NULL);
1499 Manglings = clang_Cursor_getCXXManglings(cursor);
1500 for (I = 0, E = Manglings->Count; I < E; ++I)
1501 printf(" [mangled=%s]", clang_getCString(Manglings->Strings[I]));
1502 clang_disposeStringSet(Manglings);
1503 printf("\n");
1504 return CXChildVisit_Recurse;
1505}
1506
Eli Bendersky44a206f2014-07-31 18:04:56 +00001507/******************************************************************************/
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001508/* Bitwidth testing. */
1509/******************************************************************************/
1510
1511static enum CXChildVisitResult PrintBitWidth(CXCursor cursor, CXCursor p,
1512 CXClientData d) {
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001513 int Bitwidth;
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001514 if (clang_getCursorKind(cursor) != CXCursor_FieldDecl)
1515 return CXChildVisit_Recurse;
1516
NAKAMURA Takumidfaed1b2012-12-04 15:32:03 +00001517 Bitwidth = clang_getFieldDeclBitWidth(cursor);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00001518 if (Bitwidth >= 0) {
1519 PrintCursor(cursor, NULL);
1520 printf(" bitwidth=%d\n", Bitwidth);
1521 }
1522
1523 return CXChildVisit_Recurse;
1524}
Ted Kremenek6bca9842010-05-14 21:29:26 +00001525
1526/******************************************************************************/
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00001527/* Type declaration testing */
1528/******************************************************************************/
1529
1530static enum CXChildVisitResult PrintTypeDeclaration(CXCursor cursor, CXCursor p,
1531 CXClientData d) {
1532 CXCursor typeDeclaration = clang_getTypeDeclaration(clang_getCursorType(cursor));
1533
1534 if (clang_isDeclaration(typeDeclaration.kind)) {
1535 PrintCursor(cursor, NULL);
1536 PrintTypeAndTypeKind(clang_getCursorType(typeDeclaration), " [typedeclaration=%s] [typekind=%s]\n");
1537 }
1538
1539 return CXChildVisit_Recurse;
1540}
1541
1542/******************************************************************************/
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00001543/* Loading ASTs/source. */
1544/******************************************************************************/
1545
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001546static int perform_test_load(CXIndex Idx, CXTranslationUnit TU,
Ted Kremenek73eccd22010-01-12 18:53:15 +00001547 const char *filter, const char *prefix,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001548 CXCursorVisitor Visitor,
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001549 PostVisitTU PV,
1550 const char *CommentSchemaFile) {
Ted Kremenek29004672010-02-17 00:41:32 +00001551
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001552 if (prefix)
Ted Kremenek29004672010-02-17 00:41:32 +00001553 FileCheckPrefix = prefix;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001554
1555 if (Visitor) {
1556 enum CXCursorKind K = CXCursor_NotImplemented;
1557 enum CXCursorKind *ck = &K;
1558 VisitorData Data;
Ted Kremenek29004672010-02-17 00:41:32 +00001559
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001560 /* Perform some simple filtering. */
1561 if (!strcmp(filter, "all") || !strcmp(filter, "local")) ck = NULL;
Douglas Gregor97c75712010-10-02 22:49:11 +00001562 else if (!strcmp(filter, "all-display") ||
1563 !strcmp(filter, "local-display")) {
1564 ck = NULL;
1565 want_display_name = 1;
1566 }
Daniel Dunbard64ce7b2010-02-10 20:42:40 +00001567 else if (!strcmp(filter, "none")) K = (enum CXCursorKind) ~0;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001568 else if (!strcmp(filter, "category")) K = CXCursor_ObjCCategoryDecl;
1569 else if (!strcmp(filter, "interface")) K = CXCursor_ObjCInterfaceDecl;
1570 else if (!strcmp(filter, "protocol")) K = CXCursor_ObjCProtocolDecl;
1571 else if (!strcmp(filter, "function")) K = CXCursor_FunctionDecl;
1572 else if (!strcmp(filter, "typedef")) K = CXCursor_TypedefDecl;
1573 else if (!strcmp(filter, "scan-function")) Visitor = FunctionScanVisitor;
1574 else {
1575 fprintf(stderr, "Unknown filter for -test-load-tu: %s\n", filter);
1576 return 1;
1577 }
Ted Kremenek29004672010-02-17 00:41:32 +00001578
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001579 Data.TU = TU;
1580 Data.Filter = ck;
Chandler Carruthb2faa592014-05-02 23:30:59 +00001581 Data.CommentSchemaFile = CommentSchemaFile;
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001582 clang_visitChildren(clang_getTranslationUnitCursor(TU), Visitor, &Data);
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001583 }
Ted Kremenek29004672010-02-17 00:41:32 +00001584
Ted Kremenekb478ff42010-01-26 17:59:48 +00001585 if (PV)
1586 PV(TU);
Ted Kremeneka97a5cd2010-01-26 17:55:33 +00001587
Douglas Gregor33cdd812010-02-18 18:08:43 +00001588 PrintDiagnostics(TU);
Argyrios Kyrtzidis70480492011-11-13 23:39:14 +00001589 if (checkForErrors(TU) != 0) {
1590 clang_disposeTranslationUnit(TU);
1591 return -1;
1592 }
1593
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001594 clang_disposeTranslationUnit(TU);
1595 return 0;
1596}
1597
Ted Kremeneka44d99c2010-01-05 23:18:49 +00001598int perform_test_load_tu(const char *file, const char *filter,
Ted Kremenekb478ff42010-01-26 17:59:48 +00001599 const char *prefix, CXCursorVisitor Visitor,
1600 PostVisitTU PV) {
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001601 CXIndex Idx;
1602 CXTranslationUnit TU;
Ted Kremenek50228be2010-02-11 07:41:25 +00001603 int result;
Ted Kremenek29004672010-02-17 00:41:32 +00001604 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001605 !strcmp(filter, "local") ? 1 : 0,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001606 /* displayDiagnostics=*/1);
Ted Kremenek29004672010-02-17 00:41:32 +00001607
Ted Kremenek50228be2010-02-11 07:41:25 +00001608 if (!CreateTranslationUnit(Idx, file, &TU)) {
1609 clang_disposeIndex(Idx);
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001610 return 1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001611 }
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001612
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001613 result = perform_test_load(Idx, TU, filter, prefix, Visitor, PV, NULL);
Ted Kremenek50228be2010-02-11 07:41:25 +00001614 clang_disposeIndex(Idx);
1615 return result;
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00001616}
1617
Ted Kremenekb478ff42010-01-26 17:59:48 +00001618int perform_test_load_source(int argc, const char **argv,
1619 const char *filter, CXCursorVisitor Visitor,
1620 PostVisitTU PV) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001621 CXIndex Idx;
1622 CXTranslationUnit TU;
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001623 const char *CommentSchemaFile;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001624 struct CXUnsavedFile *unsaved_files = 0;
1625 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001626 enum CXErrorCode Err;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001627 int result;
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001628 unsigned Repeats = 0;
1629 unsigned I;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001630
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001631 Idx = clang_createIndex(/* excludeDeclsFromPCH */
Douglas Gregor97c75712010-10-02 22:49:11 +00001632 (!strcmp(filter, "local") ||
1633 !strcmp(filter, "local-display"))? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001634 /* displayDiagnostics=*/1);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001635
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001636 if ((CommentSchemaFile = parse_comments_schema(argc, argv))) {
1637 argc--;
1638 argv++;
1639 }
1640
Ted Kremenek50228be2010-02-11 07:41:25 +00001641 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1642 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001643 return -1;
Ted Kremenek50228be2010-02-11 07:41:25 +00001644 }
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001645
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001646 if (getenv("CINDEXTEST_EDITING"))
1647 Repeats = 5;
1648
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001649 Err = clang_parseTranslationUnit2(Idx, 0,
1650 argv + num_unsaved_files,
1651 argc - num_unsaved_files,
1652 unsaved_files, num_unsaved_files,
1653 getDefaultParsingOptions(), &TU);
1654 if (Err != CXError_Success) {
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001655 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001656 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001657 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001658 clang_disposeIndex(Idx);
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001659 return 1;
1660 }
1661
Erik Verbruggen8f9d1802016-01-06 15:12:51 +00001662 for (I = 0; I != Repeats; ++I) {
1663 if (checkForErrors(TU) != 0)
1664 return -1;
1665
1666 if (Repeats > 1) {
1667 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
1668 clang_defaultReparseOptions(TU));
1669 if (Err != CXError_Success) {
1670 describeLibclangFailure(Err);
1671 free_remapped_files(unsaved_files, num_unsaved_files);
1672 clang_disposeIndex(Idx);
1673 return 1;
1674 }
1675 }
1676 }
1677
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001678 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV,
1679 CommentSchemaFile);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001680 free_remapped_files(unsaved_files, num_unsaved_files);
Ted Kremenek50228be2010-02-11 07:41:25 +00001681 clang_disposeIndex(Idx);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001682 return result;
Daniel Dunbar3e535d72009-12-01 02:03:10 +00001683}
1684
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001685int perform_test_reparse_source(int argc, const char **argv, int trials,
1686 const char *filter, CXCursorVisitor Visitor,
1687 PostVisitTU PV) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001688 CXIndex Idx;
1689 CXTranslationUnit TU;
1690 struct CXUnsavedFile *unsaved_files = 0;
1691 int num_unsaved_files = 0;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001692 int compiler_arg_idx = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001693 enum CXErrorCode Err;
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001694 int result, i;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001695 int trial;
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001696 int remap_after_trial = 0;
1697 char *endptr = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001698
1699 Idx = clang_createIndex(/* excludeDeclsFromPCH */
1700 !strcmp(filter, "local") ? 1 : 0,
Argyrios Kyrtzidisbcc8a5a2013-04-09 20:29:24 +00001701 /* displayDiagnostics=*/1);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001702
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001703 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
1704 clang_disposeIndex(Idx);
1705 return -1;
1706 }
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001707
1708 for (i = 0; i < argc; ++i) {
1709 if (strcmp(argv[i], "--") == 0)
1710 break;
1711 }
1712 if (i < argc)
1713 compiler_arg_idx = i+1;
1714 if (num_unsaved_files > compiler_arg_idx)
1715 compiler_arg_idx = num_unsaved_files;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001716
Daniel Dunbarec29d712010-08-18 23:09:16 +00001717 /* Load the initial translation unit -- we do this without honoring remapped
1718 * files, so that we have a way to test results after changing the source. */
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001719 Err = clang_parseTranslationUnit2(Idx, 0,
1720 argv + compiler_arg_idx,
1721 argc - compiler_arg_idx,
1722 0, 0, getDefaultParsingOptions(), &TU);
1723 if (Err != CXError_Success) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001724 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001725 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001726 free_remapped_files(unsaved_files, num_unsaved_files);
1727 clang_disposeIndex(Idx);
1728 return 1;
1729 }
1730
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001731 if (checkForErrors(TU) != 0)
1732 return -1;
1733
Argyrios Kyrtzidis3405baa2011-09-12 18:09:31 +00001734 if (getenv("CINDEXTEST_REMAP_AFTER_TRIAL")) {
1735 remap_after_trial =
1736 strtol(getenv("CINDEXTEST_REMAP_AFTER_TRIAL"), &endptr, 10);
1737 }
1738
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001739 for (trial = 0; trial < trials; ++trial) {
Argyrios Kyrtzidis011e6a52013-12-05 08:19:23 +00001740 free_remapped_files(unsaved_files, num_unsaved_files);
1741 if (parse_remapped_files_with_try(trial, argc, argv, 0,
1742 &unsaved_files, &num_unsaved_files)) {
1743 clang_disposeTranslationUnit(TU);
1744 clang_disposeIndex(Idx);
1745 return -1;
1746 }
1747
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001748 Err = clang_reparseTranslationUnit(
1749 TU,
1750 trial >= remap_after_trial ? num_unsaved_files : 0,
1751 trial >= remap_after_trial ? unsaved_files : 0,
1752 clang_defaultReparseOptions(TU));
1753 if (Err != CXError_Success) {
Daniel Dunbarec29d712010-08-18 23:09:16 +00001754 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00001755 describeLibclangFailure(Err);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001756 clang_disposeTranslationUnit(TU);
1757 free_remapped_files(unsaved_files, num_unsaved_files);
1758 clang_disposeIndex(Idx);
1759 return -1;
1760 }
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001761
1762 if (checkForErrors(TU) != 0)
1763 return -1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001764 }
1765
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001766 result = perform_test_load(Idx, TU, filter, NULL, Visitor, PV, NULL);
Argyrios Kyrtzidise74e8222011-11-13 22:08:33 +00001767
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001768 free_remapped_files(unsaved_files, num_unsaved_files);
1769 clang_disposeIndex(Idx);
1770 return result;
1771}
1772
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001773/******************************************************************************/
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001774/* Logic for testing clang_getCursor(). */
1775/******************************************************************************/
1776
Douglas Gregor37aa4932011-05-04 00:14:37 +00001777static void print_cursor_file_scan(CXTranslationUnit TU, CXCursor cursor,
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001778 unsigned start_line, unsigned start_col,
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001779 unsigned end_line, unsigned end_col,
1780 const char *prefix) {
Ted Kremenekb58514e2010-01-07 01:17:12 +00001781 printf("// %s: ", FileCheckPrefix);
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001782 if (prefix)
1783 printf("-%s", prefix);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00001784 PrintExtent(stdout, start_line, start_col, end_line, end_col);
1785 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00001786 PrintCursor(cursor, NULL);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001787 printf("\n");
1788}
1789
Ted Kremenek0469b7e2009-11-18 02:02:52 +00001790static int perform_file_scan(const char *ast_file, const char *source_file,
1791 const char *prefix) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001792 CXIndex Idx;
1793 CXTranslationUnit TU;
1794 FILE *fp;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00001795 CXCursor prevCursor = clang_getNullCursor();
Douglas Gregor816fd362010-01-22 21:44:22 +00001796 CXFile file;
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001797 unsigned line = 1, col = 1;
Daniel Dunbar6092d502010-02-14 08:32:51 +00001798 unsigned start_line = 1, start_col = 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001799
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001800 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00001801 /* displayDiagnostics=*/1))) {
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001802 fprintf(stderr, "Could not create Index\n");
1803 return 1;
1804 }
Ted Kremenek29004672010-02-17 00:41:32 +00001805
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001806 if (!CreateTranslationUnit(Idx, ast_file, &TU))
1807 return 1;
Ted Kremenek29004672010-02-17 00:41:32 +00001808
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001809 if ((fp = fopen(source_file, "r")) == NULL) {
1810 fprintf(stderr, "Could not open '%s'\n", source_file);
Sylvestre Ledrub2482562014-08-18 15:18:56 +00001811 clang_disposeTranslationUnit(TU);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001812 return 1;
1813 }
Ted Kremenek29004672010-02-17 00:41:32 +00001814
Douglas Gregor816fd362010-01-22 21:44:22 +00001815 file = clang_getFile(TU, source_file);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001816 for (;;) {
1817 CXCursor cursor;
1818 int c = fgetc(fp);
Benjamin Kramer10d083172009-11-17 20:51:40 +00001819
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001820 if (c == '\n') {
1821 ++line;
1822 col = 1;
1823 } else
1824 ++col;
1825
1826 /* Check the cursor at this position, and dump the previous one if we have
1827 * found something new.
1828 */
1829 cursor = clang_getCursor(TU, clang_getLocation(TU, file, line, col));
1830 if ((c == EOF || !clang_equalCursors(cursor, prevCursor)) &&
1831 prevCursor.kind != CXCursor_InvalidFile) {
Douglas Gregor37aa4932011-05-04 00:14:37 +00001832 print_cursor_file_scan(TU, prevCursor, start_line, start_col,
Daniel Dunbar02968e52010-02-14 10:02:57 +00001833 line, col, prefix);
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001834 start_line = line;
1835 start_col = col;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001836 }
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001837 if (c == EOF)
1838 break;
Benjamin Kramer10d083172009-11-17 20:51:40 +00001839
Daniel Dunbareb27e7d2010-02-14 08:32:32 +00001840 prevCursor = cursor;
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001841 }
Ted Kremenek29004672010-02-17 00:41:32 +00001842
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001843 fclose(fp);
Douglas Gregor7a964ad2011-01-31 22:04:05 +00001844 clang_disposeTranslationUnit(TU);
1845 clang_disposeIndex(Idx);
Ted Kremenek2df52dc2009-11-17 19:37:36 +00001846 return 0;
1847}
1848
1849/******************************************************************************/
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001850/* Logic for testing clang code completion. */
Ted Kremenek1cd27d52009-11-17 18:13:31 +00001851/******************************************************************************/
1852
Douglas Gregor9eb77012009-11-07 00:00:49 +00001853/* Parse file:line:column from the input string. Returns 0 on success, non-zero
1854 on failure. If successful, the pointer *filename will contain newly-allocated
1855 memory (that will be owned by the caller) to store the file name. */
Ted Kremenek29004672010-02-17 00:41:32 +00001856int parse_file_line_column(const char *input, char **filename, unsigned *line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001857 unsigned *column, unsigned *second_line,
1858 unsigned *second_column) {
Douglas Gregorf96ea292009-11-09 18:19:57 +00001859 /* Find the second colon. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001860 const char *last_colon = strrchr(input, ':');
1861 unsigned values[4], i;
1862 unsigned num_values = (second_line && second_column)? 4 : 2;
1863
Douglas Gregor9eb77012009-11-07 00:00:49 +00001864 char *endptr = 0;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001865 if (!last_colon || last_colon == input) {
1866 if (num_values == 4)
1867 fprintf(stderr, "could not parse filename:line:column:line:column in "
1868 "'%s'\n", input);
1869 else
1870 fprintf(stderr, "could not parse filename:line:column in '%s'\n", input);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001871 return 1;
1872 }
1873
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001874 for (i = 0; i != num_values; ++i) {
1875 const char *prev_colon;
1876
1877 /* Parse the next line or column. */
1878 values[num_values - i - 1] = strtol(last_colon + 1, &endptr, 10);
1879 if (*endptr != 0 && *endptr != ':') {
Ted Kremenek29004672010-02-17 00:41:32 +00001880 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001881 (i % 2 ? "column" : "line"), input);
1882 return 1;
1883 }
Ted Kremenek29004672010-02-17 00:41:32 +00001884
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001885 if (i + 1 == num_values)
1886 break;
1887
1888 /* Find the previous colon. */
1889 prev_colon = last_colon - 1;
1890 while (prev_colon != input && *prev_colon != ':')
1891 --prev_colon;
1892 if (prev_colon == input) {
Ted Kremenek29004672010-02-17 00:41:32 +00001893 fprintf(stderr, "could not parse %s in '%s'\n",
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001894 (i % 2 == 0? "column" : "line"), input);
Ted Kremenek29004672010-02-17 00:41:32 +00001895 return 1;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001896 }
1897
1898 last_colon = prev_colon;
Douglas Gregorf96ea292009-11-09 18:19:57 +00001899 }
1900
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001901 *line = values[0];
1902 *column = values[1];
Ted Kremenek29004672010-02-17 00:41:32 +00001903
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001904 if (second_line && second_column) {
1905 *second_line = values[2];
1906 *second_column = values[3];
1907 }
1908
Douglas Gregorf96ea292009-11-09 18:19:57 +00001909 /* Copy the file name. */
Douglas Gregor27b4fa92010-01-26 17:06:03 +00001910 *filename = (char*)malloc(last_colon - input + 1);
1911 memcpy(*filename, input, last_colon - input);
1912 (*filename)[last_colon - input] = 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001913 return 0;
1914}
1915
1916const char *
1917clang_getCompletionChunkKindSpelling(enum CXCompletionChunkKind Kind) {
1918 switch (Kind) {
1919 case CXCompletionChunk_Optional: return "Optional";
1920 case CXCompletionChunk_TypedText: return "TypedText";
1921 case CXCompletionChunk_Text: return "Text";
1922 case CXCompletionChunk_Placeholder: return "Placeholder";
1923 case CXCompletionChunk_Informative: return "Informative";
1924 case CXCompletionChunk_CurrentParameter: return "CurrentParameter";
1925 case CXCompletionChunk_LeftParen: return "LeftParen";
1926 case CXCompletionChunk_RightParen: return "RightParen";
1927 case CXCompletionChunk_LeftBracket: return "LeftBracket";
1928 case CXCompletionChunk_RightBracket: return "RightBracket";
1929 case CXCompletionChunk_LeftBrace: return "LeftBrace";
1930 case CXCompletionChunk_RightBrace: return "RightBrace";
1931 case CXCompletionChunk_LeftAngle: return "LeftAngle";
1932 case CXCompletionChunk_RightAngle: return "RightAngle";
1933 case CXCompletionChunk_Comma: return "Comma";
Douglas Gregorb3fa9192009-12-18 18:53:37 +00001934 case CXCompletionChunk_ResultType: return "ResultType";
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001935 case CXCompletionChunk_Colon: return "Colon";
1936 case CXCompletionChunk_SemiColon: return "SemiColon";
1937 case CXCompletionChunk_Equal: return "Equal";
1938 case CXCompletionChunk_HorizontalSpace: return "HorizontalSpace";
1939 case CXCompletionChunk_VerticalSpace: return "VerticalSpace";
Douglas Gregor9eb77012009-11-07 00:00:49 +00001940 }
Ted Kremenek29004672010-02-17 00:41:32 +00001941
Douglas Gregor9eb77012009-11-07 00:00:49 +00001942 return "Unknown";
1943}
1944
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00001945static int checkForErrors(CXTranslationUnit TU) {
1946 unsigned Num, i;
1947 CXDiagnostic Diag;
1948 CXString DiagStr;
1949
1950 if (!getenv("CINDEXTEST_FAILONERROR"))
1951 return 0;
1952
1953 Num = clang_getNumDiagnostics(TU);
1954 for (i = 0; i != Num; ++i) {
1955 Diag = clang_getDiagnostic(TU, i);
1956 if (clang_getDiagnosticSeverity(Diag) >= CXDiagnostic_Error) {
1957 DiagStr = clang_formatDiagnostic(Diag,
1958 clang_defaultDiagnosticDisplayOptions());
1959 fprintf(stderr, "%s\n", clang_getCString(DiagStr));
1960 clang_disposeString(DiagStr);
1961 clang_disposeDiagnostic(Diag);
1962 return -1;
1963 }
1964 clang_disposeDiagnostic(Diag);
1965 }
1966
1967 return 0;
1968}
1969
Nico Weber8d19dff2014-05-07 21:05:22 +00001970static void print_completion_string(CXCompletionString completion_string,
1971 FILE *file) {
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00001972 int I, N;
Ted Kremenek29004672010-02-17 00:41:32 +00001973
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001974 N = clang_getNumCompletionChunks(completion_string);
Douglas Gregor9eb77012009-11-07 00:00:49 +00001975 for (I = 0; I != N; ++I) {
Ted Kremenekf602f962010-02-17 01:42:24 +00001976 CXString text;
1977 const char *cstr;
Douglas Gregor9eb77012009-11-07 00:00:49 +00001978 enum CXCompletionChunkKind Kind
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001979 = clang_getCompletionChunkKind(completion_string, I);
Ted Kremenek29004672010-02-17 00:41:32 +00001980
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001981 if (Kind == CXCompletionChunk_Optional) {
1982 fprintf(file, "{Optional ");
1983 print_completion_string(
Ted Kremenek29004672010-02-17 00:41:32 +00001984 clang_getCompletionChunkCompletionString(completion_string, I),
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001985 file);
1986 fprintf(file, "}");
1987 continue;
Douglas Gregor8ed5b772010-10-08 20:39:29 +00001988 }
1989
1990 if (Kind == CXCompletionChunk_VerticalSpace) {
1991 fprintf(file, "{VerticalSpace }");
1992 continue;
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00001993 }
Ted Kremenek29004672010-02-17 00:41:32 +00001994
Douglas Gregorf81f5282009-11-09 17:05:28 +00001995 text = clang_getCompletionChunkText(completion_string, I);
Ted Kremenekf602f962010-02-17 01:42:24 +00001996 cstr = clang_getCString(text);
Ted Kremenek29004672010-02-17 00:41:32 +00001997 fprintf(file, "{%s %s}",
Douglas Gregor9eb77012009-11-07 00:00:49 +00001998 clang_getCompletionChunkKindSpelling(Kind),
Ted Kremenekf602f962010-02-17 01:42:24 +00001999 cstr ? cstr : "");
2000 clang_disposeString(text);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002001 }
Ted Kremenekf602f962010-02-17 01:42:24 +00002002
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002003}
2004
Nico Weber8d19dff2014-05-07 21:05:22 +00002005static void print_completion_result(CXCompletionResult *completion_result,
Nico Weberdf686022014-05-07 21:09:42 +00002006 FILE *file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002007 CXString ks = clang_getCursorKindSpelling(completion_result->CursorKind);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002008 unsigned annotationCount;
Douglas Gregor78254c82012-03-27 23:34:16 +00002009 enum CXCursorKind ParentKind;
2010 CXString ParentName;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002011 CXString BriefComment;
Vedant Kumarf27d2272016-04-03 00:54:46 +00002012 CXString Annotation;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002013 const char *BriefCommentCString;
Douglas Gregor78254c82012-03-27 23:34:16 +00002014
Ted Kremenek29004672010-02-17 00:41:32 +00002015 fprintf(file, "%s:", clang_getCString(ks));
2016 clang_disposeString(ks);
2017
Douglas Gregor8b14f8f2009-11-09 16:04:45 +00002018 print_completion_string(completion_result->CompletionString, file);
Douglas Gregorf757a122010-08-23 23:00:57 +00002019 fprintf(file, " (%u)",
Douglas Gregora2db7932010-05-26 22:00:08 +00002020 clang_getCompletionPriority(completion_result->CompletionString));
Douglas Gregorf757a122010-08-23 23:00:57 +00002021 switch (clang_getCompletionAvailability(completion_result->CompletionString)){
2022 case CXAvailability_Available:
2023 break;
2024
2025 case CXAvailability_Deprecated:
2026 fprintf(file, " (deprecated)");
2027 break;
2028
2029 case CXAvailability_NotAvailable:
2030 fprintf(file, " (unavailable)");
2031 break;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00002032
2033 case CXAvailability_NotAccessible:
2034 fprintf(file, " (inaccessible)");
2035 break;
Douglas Gregorf757a122010-08-23 23:00:57 +00002036 }
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002037
2038 annotationCount = clang_getCompletionNumAnnotations(
2039 completion_result->CompletionString);
2040 if (annotationCount) {
2041 unsigned i;
2042 fprintf(file, " (");
2043 for (i = 0; i < annotationCount; ++i) {
2044 if (i != 0)
2045 fprintf(file, ", ");
Vedant Kumarf27d2272016-04-03 00:54:46 +00002046 Annotation =
2047 clang_getCompletionAnnotation(completion_result->CompletionString, i);
2048 fprintf(file, "\"%s\"", clang_getCString(Annotation));
2049 clang_disposeString(Annotation);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +00002050 }
2051 fprintf(file, ")");
2052 }
2053
Douglas Gregor78254c82012-03-27 23:34:16 +00002054 if (!getenv("CINDEXTEST_NO_COMPLETION_PARENTS")) {
2055 ParentName = clang_getCompletionParent(completion_result->CompletionString,
2056 &ParentKind);
2057 if (ParentKind != CXCursor_NotImplemented) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002058 CXString KindSpelling = clang_getCursorKindSpelling(ParentKind);
Douglas Gregor78254c82012-03-27 23:34:16 +00002059 fprintf(file, " (parent: %s '%s')",
2060 clang_getCString(KindSpelling),
2061 clang_getCString(ParentName));
2062 clang_disposeString(KindSpelling);
2063 }
2064 clang_disposeString(ParentName);
2065 }
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002066
2067 BriefComment = clang_getCompletionBriefComment(
2068 completion_result->CompletionString);
2069 BriefCommentCString = clang_getCString(BriefComment);
2070 if (BriefCommentCString && *BriefCommentCString != '\0') {
2071 fprintf(file, "(brief comment: %s)", BriefCommentCString);
2072 }
2073 clang_disposeString(BriefComment);
Douglas Gregor78254c82012-03-27 23:34:16 +00002074
Douglas Gregorf757a122010-08-23 23:00:57 +00002075 fprintf(file, "\n");
Douglas Gregor9eb77012009-11-07 00:00:49 +00002076}
2077
Douglas Gregor21325842011-07-07 16:03:39 +00002078void print_completion_contexts(unsigned long long contexts, FILE *file) {
2079 fprintf(file, "Completion contexts:\n");
2080 if (contexts == CXCompletionContext_Unknown) {
2081 fprintf(file, "Unknown\n");
2082 }
2083 if (contexts & CXCompletionContext_AnyType) {
2084 fprintf(file, "Any type\n");
2085 }
2086 if (contexts & CXCompletionContext_AnyValue) {
2087 fprintf(file, "Any value\n");
2088 }
2089 if (contexts & CXCompletionContext_ObjCObjectValue) {
2090 fprintf(file, "Objective-C object value\n");
2091 }
2092 if (contexts & CXCompletionContext_ObjCSelectorValue) {
2093 fprintf(file, "Objective-C selector value\n");
2094 }
2095 if (contexts & CXCompletionContext_CXXClassTypeValue) {
2096 fprintf(file, "C++ class type value\n");
2097 }
2098 if (contexts & CXCompletionContext_DotMemberAccess) {
2099 fprintf(file, "Dot member access\n");
2100 }
2101 if (contexts & CXCompletionContext_ArrowMemberAccess) {
2102 fprintf(file, "Arrow member access\n");
2103 }
2104 if (contexts & CXCompletionContext_ObjCPropertyAccess) {
2105 fprintf(file, "Objective-C property access\n");
2106 }
2107 if (contexts & CXCompletionContext_EnumTag) {
2108 fprintf(file, "Enum tag\n");
2109 }
2110 if (contexts & CXCompletionContext_UnionTag) {
2111 fprintf(file, "Union tag\n");
2112 }
2113 if (contexts & CXCompletionContext_StructTag) {
2114 fprintf(file, "Struct tag\n");
2115 }
2116 if (contexts & CXCompletionContext_ClassTag) {
2117 fprintf(file, "Class name\n");
2118 }
2119 if (contexts & CXCompletionContext_Namespace) {
2120 fprintf(file, "Namespace or namespace alias\n");
2121 }
2122 if (contexts & CXCompletionContext_NestedNameSpecifier) {
2123 fprintf(file, "Nested name specifier\n");
2124 }
2125 if (contexts & CXCompletionContext_ObjCInterface) {
2126 fprintf(file, "Objective-C interface\n");
2127 }
2128 if (contexts & CXCompletionContext_ObjCProtocol) {
2129 fprintf(file, "Objective-C protocol\n");
2130 }
2131 if (contexts & CXCompletionContext_ObjCCategory) {
2132 fprintf(file, "Objective-C category\n");
2133 }
2134 if (contexts & CXCompletionContext_ObjCInstanceMessage) {
2135 fprintf(file, "Objective-C instance method\n");
2136 }
2137 if (contexts & CXCompletionContext_ObjCClassMessage) {
2138 fprintf(file, "Objective-C class method\n");
2139 }
2140 if (contexts & CXCompletionContext_ObjCSelectorName) {
2141 fprintf(file, "Objective-C selector name\n");
2142 }
2143 if (contexts & CXCompletionContext_MacroName) {
2144 fprintf(file, "Macro name\n");
2145 }
2146 if (contexts & CXCompletionContext_NaturalLanguage) {
2147 fprintf(file, "Natural language\n");
2148 }
2149}
2150
Douglas Gregor47815d52010-07-12 18:38:41 +00002151int perform_code_completion(int argc, const char **argv, int timing_only) {
Douglas Gregor9eb77012009-11-07 00:00:49 +00002152 const char *input = argv[1];
2153 char *filename = 0;
2154 unsigned line;
2155 unsigned column;
Daniel Dunbar4ba3b292009-11-07 18:34:24 +00002156 CXIndex CIdx;
Ted Kremenekef3339b2009-11-17 18:09:14 +00002157 int errorCode;
Douglas Gregor9485bf92009-12-02 09:21:34 +00002158 struct CXUnsavedFile *unsaved_files = 0;
2159 int num_unsaved_files = 0;
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002160 CXCodeCompleteResults *results = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002161 enum CXErrorCode Err;
2162 CXTranslationUnit TU;
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002163 unsigned I, Repeats = 1;
2164 unsigned completionOptions = clang_defaultCodeCompleteOptions();
2165
2166 if (getenv("CINDEXTEST_CODE_COMPLETE_PATTERNS"))
2167 completionOptions |= CXCodeComplete_IncludeCodePatterns;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002168 if (getenv("CINDEXTEST_COMPLETION_BRIEF_COMMENTS"))
2169 completionOptions |= CXCodeComplete_IncludeBriefComments;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002170
Douglas Gregor47815d52010-07-12 18:38:41 +00002171 if (timing_only)
2172 input += strlen("-code-completion-timing=");
2173 else
2174 input += strlen("-code-completion-at=");
2175
Ted Kremenek29004672010-02-17 00:41:32 +00002176 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002177 0, 0)))
Ted Kremenekef3339b2009-11-17 18:09:14 +00002178 return errorCode;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002179
Douglas Gregor9485bf92009-12-02 09:21:34 +00002180 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files))
2181 return -1;
2182
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002183 CIdx = clang_createIndex(0, 0);
2184
2185 if (getenv("CINDEXTEST_EDITING"))
2186 Repeats = 5;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002187
2188 Err = clang_parseTranslationUnit2(CIdx, 0,
2189 argv + num_unsaved_files + 2,
2190 argc - num_unsaved_files - 2,
2191 0, 0, getDefaultParsingOptions(), &TU);
2192 if (Err != CXError_Success) {
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002193 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002194 describeLibclangFailure(Err);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002195 return 1;
2196 }
Douglas Gregorc6592922010-11-15 23:00:34 +00002197
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002198 Err = clang_reparseTranslationUnit(TU, 0, 0,
2199 clang_defaultReparseOptions(TU));
2200
2201 if (Err != CXError_Success) {
Adrian Prantlcd399222015-06-18 16:41:51 +00002202 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002203 describeLibclangFailure(Err);
2204 clang_disposeTranslationUnit(TU);
Douglas Gregorc6592922010-11-15 23:00:34 +00002205 return 1;
2206 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002207
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002208 for (I = 0; I != Repeats; ++I) {
2209 results = clang_codeCompleteAt(TU, filename, line, column,
2210 unsaved_files, num_unsaved_files,
2211 completionOptions);
2212 if (!results) {
2213 fprintf(stderr, "Unable to perform code completion!\n");
Daniel Dunbar186f7422010-08-19 23:44:06 +00002214 return 1;
2215 }
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00002216 if (I != Repeats-1)
2217 clang_disposeCodeCompleteResults(results);
2218 }
Douglas Gregorba965fb2010-01-28 00:56:43 +00002219
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002220 if (results) {
Douglas Gregor63745d52011-07-21 01:05:26 +00002221 unsigned i, n = results->NumResults, containerIsIncomplete = 0;
Douglas Gregor21325842011-07-07 16:03:39 +00002222 unsigned long long contexts;
Douglas Gregor63745d52011-07-21 01:05:26 +00002223 enum CXCursorKind containerKind;
Douglas Gregorea777402011-07-26 15:24:30 +00002224 CXString objCSelector;
2225 const char *selectorString;
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002226 if (!timing_only) {
2227 /* Sort the code-completion results based on the typed text. */
2228 clang_sortCodeCompletionResults(results->Results, results->NumResults);
2229
Douglas Gregor47815d52010-07-12 18:38:41 +00002230 for (i = 0; i != n; ++i)
2231 print_completion_result(results->Results + i, stdout);
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002232 }
Douglas Gregor33cdd812010-02-18 18:08:43 +00002233 n = clang_codeCompleteGetNumDiagnostics(results);
2234 for (i = 0; i != n; ++i) {
2235 CXDiagnostic diag = clang_codeCompleteGetDiagnostic(results, i);
2236 PrintDiagnostic(diag);
2237 clang_disposeDiagnostic(diag);
2238 }
Douglas Gregor21325842011-07-07 16:03:39 +00002239
2240 contexts = clang_codeCompleteGetContexts(results);
2241 print_completion_contexts(contexts, stdout);
2242
Douglas Gregorea777402011-07-26 15:24:30 +00002243 containerKind = clang_codeCompleteGetContainerKind(results,
2244 &containerIsIncomplete);
Douglas Gregor63745d52011-07-21 01:05:26 +00002245
2246 if (containerKind != CXCursor_InvalidCode) {
2247 /* We have found a container */
2248 CXString containerUSR, containerKindSpelling;
2249 containerKindSpelling = clang_getCursorKindSpelling(containerKind);
2250 printf("Container Kind: %s\n", clang_getCString(containerKindSpelling));
2251 clang_disposeString(containerKindSpelling);
2252
2253 if (containerIsIncomplete) {
2254 printf("Container is incomplete\n");
2255 }
2256 else {
2257 printf("Container is complete\n");
2258 }
2259
2260 containerUSR = clang_codeCompleteGetContainerUSR(results);
2261 printf("Container USR: %s\n", clang_getCString(containerUSR));
2262 clang_disposeString(containerUSR);
2263 }
2264
Douglas Gregorea777402011-07-26 15:24:30 +00002265 objCSelector = clang_codeCompleteGetObjCSelector(results);
2266 selectorString = clang_getCString(objCSelector);
2267 if (selectorString && strlen(selectorString) > 0) {
2268 printf("Objective-C selector: %s\n", selectorString);
2269 }
2270 clang_disposeString(objCSelector);
2271
Douglas Gregorf72b6ac2009-12-18 16:20:58 +00002272 clang_disposeCodeCompleteResults(results);
2273 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002274 clang_disposeTranslationUnit(TU);
Douglas Gregor9eb77012009-11-07 00:00:49 +00002275 clang_disposeIndex(CIdx);
2276 free(filename);
Ted Kremenek29004672010-02-17 00:41:32 +00002277
Douglas Gregor9485bf92009-12-02 09:21:34 +00002278 free_remapped_files(unsaved_files, num_unsaved_files);
2279
Ted Kremenekef3339b2009-11-17 18:09:14 +00002280 return 0;
Douglas Gregor9eb77012009-11-07 00:00:49 +00002281}
2282
Douglas Gregor082c3e62010-01-15 19:40:17 +00002283typedef struct {
2284 char *filename;
2285 unsigned line;
2286 unsigned column;
2287} CursorSourceLocation;
2288
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002289typedef void (*cursor_handler_t)(CXCursor cursor);
2290
2291static int inspect_cursor_at(int argc, const char **argv,
2292 const char *locations_flag,
2293 cursor_handler_t handler) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002294 CXIndex CIdx;
2295 int errorCode;
2296 struct CXUnsavedFile *unsaved_files = 0;
2297 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002298 enum CXErrorCode Err;
Douglas Gregor082c3e62010-01-15 19:40:17 +00002299 CXTranslationUnit TU;
2300 CXCursor Cursor;
2301 CursorSourceLocation *Locations = 0;
2302 unsigned NumLocations = 0, Loc;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002303 unsigned Repeats = 1;
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002304 unsigned I;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002305
Ted Kremenek29004672010-02-17 00:41:32 +00002306 /* Count the number of locations. */
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002307 while (strstr(argv[NumLocations+1], locations_flag) == argv[NumLocations+1])
Douglas Gregor082c3e62010-01-15 19:40:17 +00002308 ++NumLocations;
Ted Kremenek29004672010-02-17 00:41:32 +00002309
Douglas Gregor082c3e62010-01-15 19:40:17 +00002310 /* Parse the locations. */
2311 assert(NumLocations > 0 && "Unable to count locations?");
2312 Locations = (CursorSourceLocation *)malloc(
2313 NumLocations * sizeof(CursorSourceLocation));
2314 for (Loc = 0; Loc < NumLocations; ++Loc) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002315 const char *input = argv[Loc + 1] + strlen(locations_flag);
Ted Kremenek29004672010-02-17 00:41:32 +00002316 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2317 &Locations[Loc].line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002318 &Locations[Loc].column, 0, 0)))
Douglas Gregor082c3e62010-01-15 19:40:17 +00002319 return errorCode;
2320 }
Ted Kremenek29004672010-02-17 00:41:32 +00002321
2322 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
Douglas Gregor082c3e62010-01-15 19:40:17 +00002323 &num_unsaved_files))
2324 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00002325
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002326 if (getenv("CINDEXTEST_EDITING"))
2327 Repeats = 5;
2328
2329 /* Parse the translation unit. When we're testing clang_getCursor() after
2330 reparsing, don't remap unsaved files until the second parse. */
2331 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002332 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2333 argv + num_unsaved_files + 1 + NumLocations,
2334 argc - num_unsaved_files - 2 - NumLocations,
2335 unsaved_files,
2336 Repeats > 1? 0 : num_unsaved_files,
2337 getDefaultParsingOptions(), &TU);
2338 if (Err != CXError_Success) {
Douglas Gregor082c3e62010-01-15 19:40:17 +00002339 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002340 describeLibclangFailure(Err);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002341 return -1;
2342 }
Ted Kremenek29004672010-02-17 00:41:32 +00002343
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002344 if (checkForErrors(TU) != 0)
2345 return -1;
2346
Douglas Gregorb42f34b2010-11-30 06:04:54 +00002347 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002348 if (Repeats > 1) {
2349 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2350 clang_defaultReparseOptions(TU));
2351 if (Err != CXError_Success) {
2352 describeLibclangFailure(Err);
2353 clang_disposeTranslationUnit(TU);
2354 return 1;
2355 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002356 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002357
2358 if (checkForErrors(TU) != 0)
2359 return -1;
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002360
2361 for (Loc = 0; Loc < NumLocations; ++Loc) {
2362 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2363 if (!file)
2364 continue;
Ted Kremenek29004672010-02-17 00:41:32 +00002365
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002366 Cursor = clang_getCursor(TU,
2367 clang_getLocation(TU, file, Locations[Loc].line,
2368 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002369
2370 if (checkForErrors(TU) != 0)
2371 return -1;
2372
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002373 if (I + 1 == Repeats) {
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002374 handler(Cursor);
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002375 free(Locations[Loc].filename);
2376 }
2377 }
Douglas Gregor082c3e62010-01-15 19:40:17 +00002378 }
Douglas Gregor2f6358b2010-11-30 05:52:55 +00002379
Douglas Gregor33cdd812010-02-18 18:08:43 +00002380 PrintDiagnostics(TU);
Douglas Gregor082c3e62010-01-15 19:40:17 +00002381 clang_disposeTranslationUnit(TU);
2382 clang_disposeIndex(CIdx);
2383 free(Locations);
2384 free_remapped_files(unsaved_files, num_unsaved_files);
2385 return 0;
2386}
2387
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00002388static void inspect_print_cursor(CXCursor Cursor) {
2389 CXTranslationUnit TU = clang_Cursor_getTranslationUnit(Cursor);
2390 CXCompletionString completionString = clang_getCursorCompletionString(
2391 Cursor);
2392 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2393 CXString Spelling;
2394 const char *cspell;
2395 unsigned line, column;
2396 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2397 printf("%d:%d ", line, column);
2398 PrintCursor(Cursor, NULL);
2399 PrintCursorExtent(Cursor);
2400 Spelling = clang_getCursorSpelling(Cursor);
2401 cspell = clang_getCString(Spelling);
2402 if (cspell && strlen(cspell) != 0) {
2403 unsigned pieceIndex;
2404 printf(" Spelling=%s (", cspell);
2405 for (pieceIndex = 0; ; ++pieceIndex) {
2406 CXSourceRange range =
2407 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2408 if (clang_Range_isNull(range))
2409 break;
2410 PrintRange(range, 0);
2411 }
2412 printf(")");
2413 }
2414 clang_disposeString(Spelling);
2415 if (clang_Cursor_getObjCSelectorIndex(Cursor) != -1)
2416 printf(" Selector index=%d",
2417 clang_Cursor_getObjCSelectorIndex(Cursor));
2418 if (clang_Cursor_isDynamicCall(Cursor))
2419 printf(" Dynamic-call");
2420 if (Cursor.kind == CXCursor_ObjCMessageExpr) {
2421 CXType T = clang_Cursor_getReceiverType(Cursor);
2422 CXString S = clang_getTypeKindSpelling(T.kind);
2423 printf(" Receiver-type=%s", clang_getCString(S));
2424 clang_disposeString(S);
2425 }
2426
2427 {
2428 CXModule mod = clang_Cursor_getModule(Cursor);
2429 CXFile astFile;
2430 CXString name, astFilename;
2431 unsigned i, numHeaders;
2432 if (mod) {
2433 astFile = clang_Module_getASTFile(mod);
2434 astFilename = clang_getFileName(astFile);
2435 name = clang_Module_getFullName(mod);
2436 numHeaders = clang_Module_getNumTopLevelHeaders(TU, mod);
2437 printf(" ModuleName=%s (%s) system=%d Headers(%d):",
2438 clang_getCString(name), clang_getCString(astFilename),
2439 clang_Module_isSystem(mod), numHeaders);
2440 clang_disposeString(name);
2441 clang_disposeString(astFilename);
2442 for (i = 0; i < numHeaders; ++i) {
2443 CXFile file = clang_Module_getTopLevelHeader(TU, mod, i);
2444 CXString filename = clang_getFileName(file);
2445 printf("\n%s", clang_getCString(filename));
2446 clang_disposeString(filename);
2447 }
2448 }
2449 }
2450
2451 if (completionString != NULL) {
2452 printf("\nCompletion string: ");
2453 print_completion_string(completionString, stdout);
2454 }
2455 printf("\n");
2456}
2457
2458static void display_evaluate_results(CXEvalResult result) {
2459 switch (clang_EvalResult_getKind(result)) {
2460 case CXEval_Int:
2461 {
2462 int val = clang_EvalResult_getAsInt(result);
2463 printf("Kind: Int , Value: %d", val);
2464 break;
2465 }
2466 case CXEval_Float:
2467 {
2468 double val = clang_EvalResult_getAsDouble(result);
2469 printf("Kind: Float , Value: %f", val);
2470 break;
2471 }
2472 case CXEval_ObjCStrLiteral:
2473 {
2474 const char* str = clang_EvalResult_getAsStr(result);
2475 printf("Kind: ObjCString , Value: %s", str);
2476 break;
2477 }
2478 case CXEval_StrLiteral:
2479 {
2480 const char* str = clang_EvalResult_getAsStr(result);
2481 printf("Kind: CString , Value: %s", str);
2482 break;
2483 }
2484 case CXEval_CFStr:
2485 {
2486 const char* str = clang_EvalResult_getAsStr(result);
2487 printf("Kind: CFString , Value: %s", str);
2488 break;
2489 }
2490 default:
2491 printf("Unexposed");
2492 break;
2493 }
2494}
2495
2496static void inspect_evaluate_cursor(CXCursor Cursor) {
2497 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2498 CXString Spelling;
2499 const char *cspell;
2500 unsigned line, column;
2501 CXEvalResult ER;
2502
2503 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2504 printf("%d:%d ", line, column);
2505 PrintCursor(Cursor, NULL);
2506 PrintCursorExtent(Cursor);
2507 Spelling = clang_getCursorSpelling(Cursor);
2508 cspell = clang_getCString(Spelling);
2509 if (cspell && strlen(cspell) != 0) {
2510 unsigned pieceIndex;
2511 printf(" Spelling=%s (", cspell);
2512 for (pieceIndex = 0; ; ++pieceIndex) {
2513 CXSourceRange range =
2514 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2515 if (clang_Range_isNull(range))
2516 break;
2517 PrintRange(range, 0);
2518 }
2519 printf(")");
2520 }
2521 clang_disposeString(Spelling);
2522
2523 ER = clang_Cursor_Evaluate(Cursor);
2524 if (!ER) {
2525 printf("Not Evaluatable");
2526 } else {
2527 display_evaluate_results(ER);
2528 clang_EvalResult_dispose(ER);
2529 }
2530 printf("\n");
2531}
2532
2533static void inspect_macroinfo_cursor(CXCursor Cursor) {
2534 CXSourceLocation CursorLoc = clang_getCursorLocation(Cursor);
2535 CXString Spelling;
2536 const char *cspell;
2537 unsigned line, column;
2538 clang_getSpellingLocation(CursorLoc, 0, &line, &column, 0);
2539 printf("%d:%d ", line, column);
2540 PrintCursor(Cursor, NULL);
2541 PrintCursorExtent(Cursor);
2542 Spelling = clang_getCursorSpelling(Cursor);
2543 cspell = clang_getCString(Spelling);
2544 if (cspell && strlen(cspell) != 0) {
2545 unsigned pieceIndex;
2546 printf(" Spelling=%s (", cspell);
2547 for (pieceIndex = 0; ; ++pieceIndex) {
2548 CXSourceRange range =
2549 clang_Cursor_getSpellingNameRange(Cursor, pieceIndex, 0);
2550 if (clang_Range_isNull(range))
2551 break;
2552 PrintRange(range, 0);
2553 }
2554 printf(")");
2555 }
2556 clang_disposeString(Spelling);
2557
2558 if (clang_Cursor_isMacroBuiltin(Cursor)) {
2559 printf("[builtin macro]");
2560 } else if (clang_Cursor_isMacroFunctionLike(Cursor)) {
2561 printf("[function macro]");
2562 }
2563 printf("\n");
2564}
2565
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002566static enum CXVisitorResult findFileRefsVisit(void *context,
2567 CXCursor cursor, CXSourceRange range) {
2568 if (clang_Range_isNull(range))
2569 return CXVisit_Continue;
2570
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002571 PrintCursor(cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002572 PrintRange(range, "");
2573 printf("\n");
2574 return CXVisit_Continue;
2575}
2576
2577static int find_file_refs_at(int argc, const char **argv) {
2578 CXIndex CIdx;
2579 int errorCode;
2580 struct CXUnsavedFile *unsaved_files = 0;
2581 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002582 enum CXErrorCode Err;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002583 CXTranslationUnit TU;
2584 CXCursor Cursor;
2585 CursorSourceLocation *Locations = 0;
2586 unsigned NumLocations = 0, Loc;
2587 unsigned Repeats = 1;
2588 unsigned I;
2589
2590 /* Count the number of locations. */
2591 while (strstr(argv[NumLocations+1], "-file-refs-at=") == argv[NumLocations+1])
2592 ++NumLocations;
2593
2594 /* Parse the locations. */
2595 assert(NumLocations > 0 && "Unable to count locations?");
2596 Locations = (CursorSourceLocation *)malloc(
2597 NumLocations * sizeof(CursorSourceLocation));
2598 for (Loc = 0; Loc < NumLocations; ++Loc) {
2599 const char *input = argv[Loc + 1] + strlen("-file-refs-at=");
2600 if ((errorCode = parse_file_line_column(input, &Locations[Loc].filename,
2601 &Locations[Loc].line,
2602 &Locations[Loc].column, 0, 0)))
2603 return errorCode;
2604 }
2605
2606 if (parse_remapped_files(argc, argv, NumLocations + 1, &unsaved_files,
2607 &num_unsaved_files))
2608 return -1;
2609
2610 if (getenv("CINDEXTEST_EDITING"))
2611 Repeats = 5;
2612
2613 /* Parse the translation unit. When we're testing clang_getCursor() after
2614 reparsing, don't remap unsaved files until the second parse. */
2615 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002616 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
2617 argv + num_unsaved_files + 1 + NumLocations,
2618 argc - num_unsaved_files - 2 - NumLocations,
2619 unsaved_files,
2620 Repeats > 1? 0 : num_unsaved_files,
2621 getDefaultParsingOptions(), &TU);
2622 if (Err != CXError_Success) {
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002623 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002624 describeLibclangFailure(Err);
2625 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002626 return -1;
2627 }
2628
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002629 if (checkForErrors(TU) != 0)
2630 return -1;
2631
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002632 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002633 if (Repeats > 1) {
2634 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2635 clang_defaultReparseOptions(TU));
2636 if (Err != CXError_Success) {
2637 describeLibclangFailure(Err);
2638 clang_disposeTranslationUnit(TU);
2639 return 1;
2640 }
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002641 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002642
2643 if (checkForErrors(TU) != 0)
2644 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002645
2646 for (Loc = 0; Loc < NumLocations; ++Loc) {
2647 CXFile file = clang_getFile(TU, Locations[Loc].filename);
2648 if (!file)
2649 continue;
2650
2651 Cursor = clang_getCursor(TU,
2652 clang_getLocation(TU, file, Locations[Loc].line,
2653 Locations[Loc].column));
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002654
2655 if (checkForErrors(TU) != 0)
2656 return -1;
2657
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002658 if (I + 1 == Repeats) {
Erik Verbruggen338b55c2011-10-06 11:38:08 +00002659 CXCursorAndRangeVisitor visitor = { 0, findFileRefsVisit };
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00002660 PrintCursor(Cursor, NULL);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002661 printf("\n");
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002662 clang_findReferencesInFile(Cursor, file, visitor);
2663 free(Locations[Loc].filename);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002664
2665 if (checkForErrors(TU) != 0)
2666 return -1;
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00002667 }
2668 }
2669 }
2670
2671 PrintDiagnostics(TU);
2672 clang_disposeTranslationUnit(TU);
2673 clang_disposeIndex(CIdx);
2674 free(Locations);
2675 free_remapped_files(unsaved_files, num_unsaved_files);
2676 return 0;
2677}
2678
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002679static enum CXVisitorResult findFileIncludesVisit(void *context,
2680 CXCursor cursor, CXSourceRange range) {
2681 PrintCursor(cursor, NULL);
2682 PrintRange(range, "");
2683 printf("\n");
2684 return CXVisit_Continue;
2685}
2686
2687static int find_file_includes_in(int argc, const char **argv) {
2688 CXIndex CIdx;
2689 struct CXUnsavedFile *unsaved_files = 0;
2690 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002691 enum CXErrorCode Err;
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002692 CXTranslationUnit TU;
2693 const char **Filenames = 0;
2694 unsigned NumFilenames = 0;
2695 unsigned Repeats = 1;
2696 unsigned I, FI;
2697
2698 /* Count the number of locations. */
2699 while (strstr(argv[NumFilenames+1], "-file-includes-in=") == argv[NumFilenames+1])
2700 ++NumFilenames;
2701
2702 /* Parse the locations. */
2703 assert(NumFilenames > 0 && "Unable to count filenames?");
2704 Filenames = (const char **)malloc(NumFilenames * sizeof(const char *));
2705 for (I = 0; I < NumFilenames; ++I) {
2706 const char *input = argv[I + 1] + strlen("-file-includes-in=");
2707 /* Copy the file name. */
2708 Filenames[I] = input;
2709 }
2710
2711 if (parse_remapped_files(argc, argv, NumFilenames + 1, &unsaved_files,
2712 &num_unsaved_files))
2713 return -1;
2714
2715 if (getenv("CINDEXTEST_EDITING"))
2716 Repeats = 2;
2717
2718 /* Parse the translation unit. When we're testing clang_getCursor() after
2719 reparsing, don't remap unsaved files until the second parse. */
2720 CIdx = clang_createIndex(1, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002721 Err = clang_parseTranslationUnit2(
2722 CIdx, argv[argc - 1],
2723 argv + num_unsaved_files + 1 + NumFilenames,
2724 argc - num_unsaved_files - 2 - NumFilenames,
2725 unsaved_files,
2726 Repeats > 1 ? 0 : num_unsaved_files, getDefaultParsingOptions(), &TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002727
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002728 if (Err != CXError_Success) {
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002729 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002730 describeLibclangFailure(Err);
2731 clang_disposeTranslationUnit(TU);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002732 return -1;
2733 }
2734
2735 if (checkForErrors(TU) != 0)
2736 return -1;
2737
2738 for (I = 0; I != Repeats; ++I) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00002739 if (Repeats > 1) {
2740 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
2741 clang_defaultReparseOptions(TU));
2742 if (Err != CXError_Success) {
2743 describeLibclangFailure(Err);
2744 clang_disposeTranslationUnit(TU);
2745 return 1;
2746 }
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002747 }
2748
2749 if (checkForErrors(TU) != 0)
2750 return -1;
2751
2752 for (FI = 0; FI < NumFilenames; ++FI) {
2753 CXFile file = clang_getFile(TU, Filenames[FI]);
2754 if (!file)
2755 continue;
2756
2757 if (checkForErrors(TU) != 0)
2758 return -1;
2759
2760 if (I + 1 == Repeats) {
2761 CXCursorAndRangeVisitor visitor = { 0, findFileIncludesVisit };
2762 clang_findIncludesInFile(TU, file, visitor);
2763
2764 if (checkForErrors(TU) != 0)
2765 return -1;
2766 }
2767 }
2768 }
2769
2770 PrintDiagnostics(TU);
2771 clang_disposeTranslationUnit(TU);
2772 clang_disposeIndex(CIdx);
Argyrios Kyrtzidis1b5b1ce2013-03-11 16:03:17 +00002773 free((void *)Filenames);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00002774 free_remapped_files(unsaved_files, num_unsaved_files);
2775 return 0;
2776}
2777
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002778#define MAX_IMPORTED_ASTFILES 200
2779
2780typedef struct {
2781 char **filenames;
2782 unsigned num_files;
2783} ImportedASTFilesData;
2784
2785static ImportedASTFilesData *importedASTs_create() {
2786 ImportedASTFilesData *p;
2787 p = malloc(sizeof(ImportedASTFilesData));
2788 p->filenames = malloc(MAX_IMPORTED_ASTFILES * sizeof(const char *));
2789 p->num_files = 0;
2790 return p;
2791}
2792
2793static void importedASTs_dispose(ImportedASTFilesData *p) {
2794 unsigned i;
2795 if (!p)
2796 return;
2797
2798 for (i = 0; i < p->num_files; ++i)
2799 free(p->filenames[i]);
2800 free(p->filenames);
2801 free(p);
2802}
2803
2804static void importedASTS_insert(ImportedASTFilesData *p, const char *file) {
2805 unsigned i;
2806 assert(p && file);
2807 for (i = 0; i < p->num_files; ++i)
2808 if (strcmp(file, p->filenames[i]) == 0)
2809 return;
2810 assert(p->num_files + 1 < MAX_IMPORTED_ASTFILES);
2811 p->filenames[p->num_files++] = strdup(file);
2812}
2813
Nico Weberdf686022014-05-07 21:09:42 +00002814typedef struct IndexDataStringList_ {
2815 struct IndexDataStringList_ *next;
2816 char data[1]; /* Dynamically sized. */
2817} IndexDataStringList;
2818
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002819typedef struct {
2820 const char *check_prefix;
2821 int first_check_printed;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00002822 int fail_for_error;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00002823 int abort;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002824 const char *main_filename;
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00002825 ImportedASTFilesData *importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00002826 IndexDataStringList *strings;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00002827 CXTranslationUnit TU;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002828} IndexData;
2829
Nico Weberdf686022014-05-07 21:09:42 +00002830static void free_client_data(IndexData *index_data) {
2831 IndexDataStringList *node = index_data->strings;
2832 while (node) {
2833 IndexDataStringList *next = node->next;
2834 free(node);
2835 node = next;
2836 }
2837 index_data->strings = NULL;
2838}
2839
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002840static void printCheck(IndexData *data) {
2841 if (data->check_prefix) {
2842 if (data->first_check_printed) {
2843 printf("// %s-NEXT: ", data->check_prefix);
2844 } else {
2845 printf("// %s : ", data->check_prefix);
2846 data->first_check_printed = 1;
2847 }
2848 }
2849}
2850
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002851static void printCXIndexFile(CXIdxClientFile file) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00002852 CXString filename = clang_getFileName((CXFile)file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002853 printf("%s", clang_getCString(filename));
2854 clang_disposeString(filename);
2855}
2856
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002857static void printCXIndexLoc(CXIdxLoc loc, CXClientData client_data) {
2858 IndexData *index_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002859 CXString filename;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002860 const char *cname;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002861 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002862 unsigned line, column;
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002863 int isMainFile;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002864
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002865 index_data = (IndexData *)client_data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002866 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
2867 if (line == 0) {
Argyrios Kyrtzidis9f571862012-10-11 19:00:44 +00002868 printf("<invalid>");
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002869 return;
2870 }
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00002871 if (!file) {
2872 printf("<no idxfile>");
2873 return;
2874 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002875 filename = clang_getFileName((CXFile)file);
2876 cname = clang_getCString(filename);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002877 if (strcmp(cname, index_data->main_filename) == 0)
2878 isMainFile = 1;
2879 else
2880 isMainFile = 0;
2881 clang_disposeString(filename);
2882
2883 if (!isMainFile) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002884 printCXIndexFile(file);
2885 printf(":");
2886 }
2887 printf("%d:%d", line, column);
2888}
2889
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00002890static unsigned digitCount(unsigned val) {
2891 unsigned c = 1;
2892 while (1) {
2893 if (val < 10)
2894 return c;
2895 ++c;
2896 val /= 10;
2897 }
2898}
2899
Nico Weberdf686022014-05-07 21:09:42 +00002900static CXIdxClientContainer makeClientContainer(CXClientData *client_data,
2901 const CXIdxEntityInfo *info,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002902 CXIdxLoc loc) {
Nico Weberdf686022014-05-07 21:09:42 +00002903 IndexData *index_data;
2904 IndexDataStringList *node;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002905 const char *name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002906 char *newStr;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002907 CXIdxClientFile file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002908 unsigned line, column;
2909
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002910 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002911 if (!name)
2912 name = "<anon-tag>";
2913
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002914 clang_indexLoc_getFileLocation(loc, &file, 0, &line, &column, 0);
Nico Weberdf686022014-05-07 21:09:42 +00002915
2916 node =
2917 (IndexDataStringList *)malloc(sizeof(IndexDataStringList) + strlen(name) +
2918 digitCount(line) + digitCount(column) + 2);
2919 newStr = node->data;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002920 sprintf(newStr, "%s:%d:%d", name, line, column);
Nico Weberdf686022014-05-07 21:09:42 +00002921
2922 /* Remember string so it can be freed later. */
2923 index_data = (IndexData *)client_data;
2924 node->next = index_data->strings;
2925 index_data->strings = node;
2926
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002927 return (CXIdxClientContainer)newStr;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002928}
2929
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002930static void printCXIndexContainer(const CXIdxContainerInfo *info) {
2931 CXIdxClientContainer container;
2932 container = clang_index_getClientContainer(info);
Argyrios Kyrtzidisdf15c202011-11-16 02:35:05 +00002933 if (!container)
2934 printf("[<<NULL>>]");
2935 else
2936 printf("[%s]", (const char *)container);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002937}
2938
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002939static const char *getEntityKindString(CXIdxEntityKind kind) {
2940 switch (kind) {
2941 case CXIdxEntity_Unexposed: return "<<UNEXPOSED>>";
2942 case CXIdxEntity_Typedef: return "typedef";
2943 case CXIdxEntity_Function: return "function";
2944 case CXIdxEntity_Variable: return "variable";
2945 case CXIdxEntity_Field: return "field";
2946 case CXIdxEntity_EnumConstant: return "enumerator";
2947 case CXIdxEntity_ObjCClass: return "objc-class";
2948 case CXIdxEntity_ObjCProtocol: return "objc-protocol";
2949 case CXIdxEntity_ObjCCategory: return "objc-category";
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00002950 case CXIdxEntity_ObjCInstanceMethod: return "objc-instance-method";
2951 case CXIdxEntity_ObjCClassMethod: return "objc-class-method";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002952 case CXIdxEntity_ObjCProperty: return "objc-property";
2953 case CXIdxEntity_ObjCIvar: return "objc-ivar";
2954 case CXIdxEntity_Enum: return "enum";
2955 case CXIdxEntity_Struct: return "struct";
2956 case CXIdxEntity_Union: return "union";
2957 case CXIdxEntity_CXXClass: return "c++-class";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002958 case CXIdxEntity_CXXNamespace: return "namespace";
2959 case CXIdxEntity_CXXNamespaceAlias: return "namespace-alias";
2960 case CXIdxEntity_CXXStaticVariable: return "c++-static-var";
2961 case CXIdxEntity_CXXStaticMethod: return "c++-static-method";
2962 case CXIdxEntity_CXXInstanceMethod: return "c++-instance-method";
2963 case CXIdxEntity_CXXConstructor: return "constructor";
2964 case CXIdxEntity_CXXDestructor: return "destructor";
2965 case CXIdxEntity_CXXConversionFunction: return "conversion-func";
2966 case CXIdxEntity_CXXTypeAlias: return "type-alias";
David Blaikiedcefd952012-08-31 21:55:26 +00002967 case CXIdxEntity_CXXInterface: return "c++-__interface";
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00002968 }
2969 assert(0 && "Garbage entity kind");
2970 return 0;
2971}
2972
2973static const char *getEntityTemplateKindString(CXIdxEntityCXXTemplateKind kind) {
2974 switch (kind) {
2975 case CXIdxEntity_NonTemplate: return "";
2976 case CXIdxEntity_Template: return "-template";
2977 case CXIdxEntity_TemplatePartialSpecialization:
2978 return "-template-partial-spec";
2979 case CXIdxEntity_TemplateSpecialization: return "-template-spec";
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002980 }
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002981 assert(0 && "Garbage entity kind");
2982 return 0;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002983}
2984
Argyrios Kyrtzidis52002882011-12-07 20:44:12 +00002985static const char *getEntityLanguageString(CXIdxEntityLanguage kind) {
2986 switch (kind) {
2987 case CXIdxEntityLang_None: return "<none>";
2988 case CXIdxEntityLang_C: return "C";
2989 case CXIdxEntityLang_ObjC: return "ObjC";
2990 case CXIdxEntityLang_CXX: return "C++";
2991 }
2992 assert(0 && "Garbage language kind");
2993 return 0;
2994}
2995
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00002996static void printEntityInfo(const char *cb,
2997 CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00002998 const CXIdxEntityInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00002999 const char *name;
3000 IndexData *index_data;
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003001 unsigned i;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003002 index_data = (IndexData *)client_data;
3003 printCheck(index_data);
3004
Argyrios Kyrtzidise4acd232011-11-16 02:34:59 +00003005 if (!info) {
3006 printf("%s: <<NULL>>", cb);
3007 return;
3008 }
3009
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003010 name = info->name;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003011 if (!name)
3012 name = "<anon-tag>";
3013
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003014 printf("%s: kind: %s%s", cb, getEntityKindString(info->kind),
3015 getEntityTemplateKindString(info->templateKind));
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003016 printf(" | name: %s", name);
3017 printf(" | USR: %s", info->USR);
Argyrios Kyrtzidisccdf8272011-12-13 18:47:35 +00003018 printf(" | lang: %s", getEntityLanguageString(info->lang));
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003019
3020 for (i = 0; i != info->numAttributes; ++i) {
3021 const CXIdxAttrInfo *Attr = info->attributes[i];
3022 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003023 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidis4d873b72011-12-15 00:05:00 +00003024 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003025}
3026
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003027static void printBaseClassInfo(CXClientData client_data,
3028 const CXIdxBaseClassInfo *info) {
3029 printEntityInfo(" <base>", client_data, info->base);
3030 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003031 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003032 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003033 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003034}
3035
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003036static void printProtocolList(const CXIdxObjCProtocolRefListInfo *ProtoInfo,
3037 CXClientData client_data) {
3038 unsigned i;
3039 for (i = 0; i < ProtoInfo->numProtocols; ++i) {
3040 printEntityInfo(" <protocol>", client_data,
3041 ProtoInfo->protocols[i]->protocol);
3042 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003043 PrintCursor(ProtoInfo->protocols[i]->cursor, NULL);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003044 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003045 printCXIndexLoc(ProtoInfo->protocols[i]->loc, client_data);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003046 printf("\n");
3047 }
3048}
3049
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003050static void index_diagnostic(CXClientData client_data,
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003051 CXDiagnosticSet diagSet, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003052 CXString str;
3053 const char *cstr;
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003054 unsigned numDiags, i;
3055 CXDiagnostic diag;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003056 IndexData *index_data;
3057 index_data = (IndexData *)client_data;
3058 printCheck(index_data);
3059
Argyrios Kyrtzidisf2d99b02011-12-01 02:42:50 +00003060 numDiags = clang_getNumDiagnosticsInSet(diagSet);
3061 for (i = 0; i != numDiags; ++i) {
3062 diag = clang_getDiagnosticInSet(diagSet, i);
3063 str = clang_formatDiagnostic(diag, clang_defaultDiagnosticDisplayOptions());
3064 cstr = clang_getCString(str);
3065 printf("[diagnostic]: %s\n", cstr);
3066 clang_disposeString(str);
3067
3068 if (getenv("CINDEXTEST_FAILONERROR") &&
3069 clang_getDiagnosticSeverity(diag) >= CXDiagnostic_Error) {
3070 index_data->fail_for_error = 1;
3071 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003072 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003073}
3074
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003075static CXIdxClientFile index_enteredMainFile(CXClientData client_data,
3076 CXFile file, void *reserved) {
3077 IndexData *index_data;
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003078 CXString filename;
3079
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003080 index_data = (IndexData *)client_data;
3081 printCheck(index_data);
3082
Argyrios Kyrtzidisa15f8162012-03-15 18:48:52 +00003083 filename = clang_getFileName(file);
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003084 index_data->main_filename = clang_getCString(filename);
3085 clang_disposeString(filename);
3086
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003087 printf("[enteredMainFile]: ");
3088 printCXIndexFile((CXIdxClientFile)file);
3089 printf("\n");
3090
3091 return (CXIdxClientFile)file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003092}
3093
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003094static CXIdxClientFile index_ppIncludedFile(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003095 const CXIdxIncludedFileInfo *info) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003096 IndexData *index_data;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003097 CXModule Mod;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003098 index_data = (IndexData *)client_data;
3099 printCheck(index_data);
3100
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003101 printf("[ppIncludedFile]: ");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003102 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003103 printf(" | name: \"%s\"", info->filename);
3104 printf(" | hash loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003105 printCXIndexLoc(info->hashLoc, client_data);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003106 printf(" | isImport: %d | isAngled: %d | isModule: %d",
Argyrios Kyrtzidis5e2ec482012-10-18 00:17:05 +00003107 info->isImport, info->isAngled, info->isModuleImport);
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003108
3109 Mod = clang_getModuleForFile(index_data->TU, (CXFile)info->file);
3110 if (Mod) {
3111 CXString str = clang_Module_getFullName(Mod);
3112 const char *cstr = clang_getCString(str);
3113 printf(" | module: %s", cstr);
3114 clang_disposeString(str);
3115 }
3116
3117 printf("\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003118
3119 return (CXIdxClientFile)info->file;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003120}
3121
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003122static CXIdxClientFile index_importedASTFile(CXClientData client_data,
3123 const CXIdxImportedASTFileInfo *info) {
3124 IndexData *index_data;
3125 index_data = (IndexData *)client_data;
3126 printCheck(index_data);
3127
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003128 if (index_data->importedASTs) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003129 CXString filename = clang_getFileName(info->file);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003130 importedASTS_insert(index_data->importedASTs, clang_getCString(filename));
3131 clang_disposeString(filename);
3132 }
3133
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003134 printf("[importedASTFile]: ");
3135 printCXIndexFile((CXIdxClientFile)info->file);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003136 if (info->module) {
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003137 CXString name = clang_Module_getFullName(info->module);
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003138 printf(" | loc: ");
3139 printCXIndexLoc(info->loc, client_data);
3140 printf(" | name: \"%s\"", clang_getCString(name));
3141 printf(" | isImplicit: %d\n", info->isImplicit);
3142 clang_disposeString(name);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003143 } else {
NAKAMURA Takumie259d912012-10-12 14:25:52 +00003144 /* PCH file, the rest are not relevant. */
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00003145 printf("\n");
Argyrios Kyrtzidisdc78f3e2012-10-05 00:22:40 +00003146 }
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003147
3148 return (CXIdxClientFile)info->file;
3149}
3150
Nico Weber8d19dff2014-05-07 21:05:22 +00003151static CXIdxClientContainer
3152index_startedTranslationUnit(CXClientData client_data, void *reserved) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003153 IndexData *index_data;
3154 index_data = (IndexData *)client_data;
3155 printCheck(index_data);
3156
Argyrios Kyrtzidis8c258042011-11-05 04:03:35 +00003157 printf("[startedTranslationUnit]\n");
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003158 return (CXIdxClientContainer)"TU";
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003159}
3160
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003161static void index_indexDeclaration(CXClientData client_data,
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003162 const CXIdxDeclInfo *info) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003163 IndexData *index_data;
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003164 const CXIdxObjCCategoryDeclInfo *CatInfo;
3165 const CXIdxObjCInterfaceDeclInfo *InterInfo;
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003166 const CXIdxObjCProtocolRefListInfo *ProtoInfo;
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003167 const CXIdxObjCPropertyDeclInfo *PropInfo;
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003168 const CXIdxCXXClassDeclInfo *CXXClassInfo;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003169 unsigned i;
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003170 index_data = (IndexData *)client_data;
3171
3172 printEntityInfo("[indexDeclaration]", client_data, info->entityInfo);
3173 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003174 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003175 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003176 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis663c8ec2011-12-07 20:44:19 +00003177 printf(" | semantic-container: ");
3178 printCXIndexContainer(info->semanticContainer);
3179 printf(" | lexical-container: ");
3180 printCXIndexContainer(info->lexicalContainer);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003181 printf(" | isRedecl: %d", info->isRedeclaration);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003182 printf(" | isDef: %d", info->isDefinition);
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003183 if (info->flags & CXIdxDeclFlag_Skipped) {
3184 assert(!info->isContainer);
3185 printf(" | isContainer: skipped");
3186 } else {
3187 printf(" | isContainer: %d", info->isContainer);
3188 }
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003189 printf(" | isImplicit: %d\n", info->isImplicit);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003190
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003191 for (i = 0; i != info->numAttributes; ++i) {
NAKAMURA Takumi2a4859a2011-11-18 00:51:03 +00003192 const CXIdxAttrInfo *Attr = info->attributes[i];
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003193 printf(" <attribute>: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003194 PrintCursor(Attr->cursor, NULL);
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003195 printf("\n");
3196 }
3197
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003198 if (clang_index_isEntityObjCContainerKind(info->entityInfo->kind)) {
3199 const char *kindName = 0;
3200 CXIdxObjCContainerKind K = clang_index_getObjCContainerDeclInfo(info)->kind;
3201 switch (K) {
3202 case CXIdxObjCContainer_ForwardRef:
3203 kindName = "forward-ref"; break;
3204 case CXIdxObjCContainer_Interface:
3205 kindName = "interface"; break;
3206 case CXIdxObjCContainer_Implementation:
3207 kindName = "implementation"; break;
3208 }
3209 printCheck(index_data);
3210 printf(" <ObjCContainerInfo>: kind: %s\n", kindName);
3211 }
3212
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003213 if ((CatInfo = clang_index_getObjCCategoryDeclInfo(info))) {
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003214 printEntityInfo(" <ObjCCategoryInfo>: class", client_data,
3215 CatInfo->objcClass);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003216 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003217 PrintCursor(CatInfo->classCursor, NULL);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003218 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003219 printCXIndexLoc(CatInfo->classLoc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003220 printf("\n");
3221 }
3222
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003223 if ((InterInfo = clang_index_getObjCInterfaceDeclInfo(info))) {
3224 if (InterInfo->superInfo) {
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003225 printBaseClassInfo(client_data, InterInfo->superInfo);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003226 printf("\n");
3227 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003228 }
3229
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003230 if ((ProtoInfo = clang_index_getObjCProtocolRefListInfo(info))) {
3231 printProtocolList(ProtoInfo, client_data);
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003232 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003233
Argyrios Kyrtzidis93db2922012-02-28 17:50:33 +00003234 if ((PropInfo = clang_index_getObjCPropertyDeclInfo(info))) {
3235 if (PropInfo->getter) {
3236 printEntityInfo(" <getter>", client_data, PropInfo->getter);
3237 printf("\n");
3238 }
3239 if (PropInfo->setter) {
3240 printEntityInfo(" <setter>", client_data, PropInfo->setter);
3241 printf("\n");
3242 }
3243 }
3244
Argyrios Kyrtzidisb3c16ba2011-12-07 20:44:15 +00003245 if ((CXXClassInfo = clang_index_getCXXClassDeclInfo(info))) {
3246 for (i = 0; i != CXXClassInfo->numBases; ++i) {
3247 printBaseClassInfo(client_data, CXXClassInfo->bases[i]);
3248 printf("\n");
3249 }
3250 }
3251
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003252 if (info->declAsContainer)
Nico Weber8d19dff2014-05-07 21:05:22 +00003253 clang_index_setClientContainer(
3254 info->declAsContainer,
Nico Weberdf686022014-05-07 21:09:42 +00003255 makeClientContainer(client_data, info->entityInfo, info->loc));
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003256}
3257
3258static void index_indexEntityReference(CXClientData client_data,
Argyrios Kyrtzidis3e429e72011-11-12 02:16:30 +00003259 const CXIdxEntityRefInfo *info) {
Nico Weber8d19dff2014-05-07 21:05:22 +00003260 printEntityInfo("[indexEntityReference]", client_data,
3261 info->referencedEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003262 printf(" | cursor: ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003263 PrintCursor(info->cursor, NULL);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003264 printf(" | loc: ");
Argyrios Kyrtzidis0abc5eb2012-03-15 18:07:22 +00003265 printCXIndexLoc(info->loc, client_data);
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003266 printEntityInfo(" | <parent>:", client_data, info->parentEntity);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003267 printf(" | container: ");
3268 printCXIndexContainer(info->container);
Argyrios Kyrtzidis86acd722011-11-14 22:39:19 +00003269 printf(" | refkind: ");
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003270 switch (info->kind) {
3271 case CXIdxEntityRef_Direct: printf("direct"); break;
Argyrios Kyrtzidiseffdbf52011-11-18 00:26:51 +00003272 case CXIdxEntityRef_Implicit: printf("implicit"); break;
Argyrios Kyrtzidis0c7735e52011-10-18 15:50:50 +00003273 }
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003274 printf("\n");
3275}
3276
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003277static int index_abortQuery(CXClientData client_data, void *reserved) {
3278 IndexData *index_data;
3279 index_data = (IndexData *)client_data;
3280 return index_data->abort;
3281}
3282
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003283static IndexerCallbacks IndexCB = {
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00003284 index_abortQuery,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003285 index_diagnostic,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003286 index_enteredMainFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003287 index_ppIncludedFile,
Argyrios Kyrtzidis472eda02012-10-02 16:10:38 +00003288 index_importedASTFile,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003289 index_startedTranslationUnit,
Argyrios Kyrtzidis7519c5e2011-11-11 00:23:36 +00003290 index_indexDeclaration,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003291 index_indexEntityReference
3292};
3293
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003294static unsigned getIndexOptions(void) {
3295 unsigned index_opts;
3296 index_opts = 0;
3297 if (getenv("CINDEXTEST_SUPPRESSREFS"))
3298 index_opts |= CXIndexOpt_SuppressRedundantRefs;
3299 if (getenv("CINDEXTEST_INDEXLOCALSYMBOLS"))
3300 index_opts |= CXIndexOpt_IndexFunctionLocalSymbols;
Argyrios Kyrtzidis8b71bc72012-12-06 19:41:16 +00003301 if (!getenv("CINDEXTEST_DISABLE_SKIPPARSEDBODIES"))
3302 index_opts |= CXIndexOpt_SkipParsedBodiesInSession;
Argyrios Kyrtzidisfb7d1452012-01-14 00:11:49 +00003303
3304 return index_opts;
3305}
3306
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003307static int index_compile_args(int num_args, const char **args,
3308 CXIndexAction idxAction,
3309 ImportedASTFilesData *importedASTs,
3310 const char *check_prefix) {
3311 IndexData index_data;
3312 unsigned index_opts;
3313 int result;
3314
3315 if (num_args == 0) {
3316 fprintf(stderr, "no compiler arguments\n");
3317 return -1;
3318 }
3319
3320 index_data.check_prefix = check_prefix;
3321 index_data.first_check_printed = 0;
3322 index_data.fail_for_error = 0;
3323 index_data.abort = 0;
3324 index_data.main_filename = "";
3325 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003326 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003327 index_data.TU = NULL;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003328
3329 index_opts = getIndexOptions();
3330 result = clang_indexSourceFile(idxAction, &index_data,
3331 &IndexCB,sizeof(IndexCB), index_opts,
3332 0, args, num_args, 0, 0, 0,
3333 getDefaultParsingOptions());
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003334 if (result != CXError_Success)
3335 describeLibclangFailure(result);
3336
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003337 if (index_data.fail_for_error)
3338 result = -1;
3339
Nico Weberdf686022014-05-07 21:09:42 +00003340 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003341 return result;
3342}
3343
3344static int index_ast_file(const char *ast_file,
3345 CXIndex Idx,
3346 CXIndexAction idxAction,
3347 ImportedASTFilesData *importedASTs,
3348 const char *check_prefix) {
3349 CXTranslationUnit TU;
3350 IndexData index_data;
3351 unsigned index_opts;
3352 int result;
3353
3354 if (!CreateTranslationUnit(Idx, ast_file, &TU))
3355 return -1;
3356
3357 index_data.check_prefix = check_prefix;
3358 index_data.first_check_printed = 0;
3359 index_data.fail_for_error = 0;
3360 index_data.abort = 0;
3361 index_data.main_filename = "";
3362 index_data.importedASTs = importedASTs;
Nico Weberdf686022014-05-07 21:09:42 +00003363 index_data.strings = NULL;
Argyrios Kyrtzidisf6d49c32014-05-14 23:14:37 +00003364 index_data.TU = TU;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003365
3366 index_opts = getIndexOptions();
3367 result = clang_indexTranslationUnit(idxAction, &index_data,
3368 &IndexCB,sizeof(IndexCB),
3369 index_opts, TU);
3370 if (index_data.fail_for_error)
3371 result = -1;
3372
3373 clang_disposeTranslationUnit(TU);
Nico Weberdf686022014-05-07 21:09:42 +00003374 free_client_data(&index_data);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003375 return result;
3376}
3377
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003378static int index_file(int argc, const char **argv, int full) {
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003379 const char *check_prefix;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003380 CXIndex Idx;
3381 CXIndexAction idxAction;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003382 ImportedASTFilesData *importedASTs;
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003383 int result;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003384
3385 check_prefix = 0;
3386 if (argc > 0) {
3387 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3388 check_prefix = argv[0] + strlen("-check-prefix=");
3389 ++argv;
3390 --argc;
3391 }
3392 }
3393
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003394 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003395 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003396 fprintf(stderr, "Could not create Index\n");
3397 return 1;
3398 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003399 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003400 importedASTs = 0;
3401 if (full)
3402 importedASTs = importedASTs_create();
3403
3404 result = index_compile_args(argc, argv, idxAction, importedASTs, check_prefix);
3405 if (result != 0)
3406 goto finished;
3407
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003408 if (full) {
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003409 unsigned i;
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003410 for (i = 0; i < importedASTs->num_files && result == 0; ++i) {
3411 result = index_ast_file(importedASTs->filenames[i], Idx, idxAction,
3412 importedASTs, check_prefix);
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003413 }
3414 }
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003415
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00003416finished:
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003417 importedASTs_dispose(importedASTs);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003418 clang_IndexAction_dispose(idxAction);
3419 clang_disposeIndex(Idx);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003420 return result;
3421}
3422
3423static int index_tu(int argc, const char **argv) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003424 const char *check_prefix;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003425 CXIndex Idx;
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003426 CXIndexAction idxAction;
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003427 int result;
3428
3429 check_prefix = 0;
3430 if (argc > 0) {
3431 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3432 check_prefix = argv[0] + strlen("-check-prefix=");
3433 ++argv;
3434 --argc;
3435 }
3436 }
3437
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003438 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003439 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003440 fprintf(stderr, "Could not create Index\n");
3441 return 1;
3442 }
3443 idxAction = clang_IndexAction_create(Idx);
3444
3445 result = index_ast_file(argv[0], Idx, idxAction,
3446 /*importedASTs=*/0, check_prefix);
3447
3448 clang_IndexAction_dispose(idxAction);
3449 clang_disposeIndex(Idx);
3450 return result;
3451}
3452
3453static int index_compile_db(int argc, const char **argv) {
3454 const char *check_prefix;
3455 CXIndex Idx;
3456 CXIndexAction idxAction;
3457 int errorCode = 0;
3458
3459 check_prefix = 0;
3460 if (argc > 0) {
3461 if (strstr(argv[0], "-check-prefix=") == argv[0]) {
3462 check_prefix = argv[0] + strlen("-check-prefix=");
3463 ++argv;
3464 --argc;
3465 }
3466 }
3467
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003468 if (argc == 0) {
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003469 fprintf(stderr, "no compilation database\n");
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003470 return -1;
3471 }
3472
3473 if (!(Idx = clang_createIndex(/* excludeDeclsFromPCH */ 1,
Stefanus Du Toitb3318502013-03-01 21:41:22 +00003474 /* displayDiagnostics=*/1))) {
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00003475 fprintf(stderr, "Could not create Index\n");
3476 return 1;
3477 }
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003478 idxAction = clang_IndexAction_create(Idx);
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003479
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003480 {
3481 const char *database = argv[0];
3482 CXCompilationDatabase db = 0;
3483 CXCompileCommands CCmds = 0;
3484 CXCompileCommand CCmd;
3485 CXCompilationDatabase_Error ec;
3486 CXString wd;
3487#define MAX_COMPILE_ARGS 512
3488 CXString cxargs[MAX_COMPILE_ARGS];
3489 const char *args[MAX_COMPILE_ARGS];
3490 char *tmp;
3491 unsigned len;
3492 char *buildDir;
3493 int i, a, numCmds, numArgs;
3494
3495 len = strlen(database);
3496 tmp = (char *) malloc(len+1);
3497 memcpy(tmp, database, len+1);
3498 buildDir = dirname(tmp);
3499
3500 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
3501
3502 if (db) {
3503
3504 if (ec!=CXCompilationDatabase_NoError) {
3505 printf("unexpected error %d code while loading compilation database\n", ec);
3506 errorCode = -1;
3507 goto cdb_end;
3508 }
3509
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003510 if (chdir(buildDir) != 0) {
3511 printf("Could not chdir to %s\n", buildDir);
3512 errorCode = -1;
3513 goto cdb_end;
3514 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003515
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003516 CCmds = clang_CompilationDatabase_getAllCompileCommands(db);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003517 if (!CCmds) {
3518 printf("compilation db is empty\n");
3519 errorCode = -1;
3520 goto cdb_end;
3521 }
3522
3523 numCmds = clang_CompileCommands_getSize(CCmds);
3524
3525 if (numCmds==0) {
3526 fprintf(stderr, "should not get an empty compileCommand set\n");
3527 errorCode = -1;
3528 goto cdb_end;
3529 }
3530
3531 for (i=0; i<numCmds && errorCode == 0; ++i) {
3532 CCmd = clang_CompileCommands_getCommand(CCmds, i);
3533
3534 wd = clang_CompileCommand_getDirectory(CCmd);
Argyrios Kyrtzidisfdea8132012-12-17 20:19:56 +00003535 if (chdir(clang_getCString(wd)) != 0) {
3536 printf("Could not chdir to %s\n", clang_getCString(wd));
3537 errorCode = -1;
3538 goto cdb_end;
3539 }
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003540 clang_disposeString(wd);
3541
3542 numArgs = clang_CompileCommand_getNumArgs(CCmd);
3543 if (numArgs > MAX_COMPILE_ARGS){
3544 fprintf(stderr, "got more compile arguments than maximum\n");
3545 errorCode = -1;
3546 goto cdb_end;
3547 }
3548 for (a=0; a<numArgs; ++a) {
3549 cxargs[a] = clang_CompileCommand_getArg(CCmd, a);
3550 args[a] = clang_getCString(cxargs[a]);
3551 }
3552
3553 errorCode = index_compile_args(numArgs, args, idxAction,
3554 /*importedASTs=*/0, check_prefix);
3555
3556 for (a=0; a<numArgs; ++a)
3557 clang_disposeString(cxargs[a]);
3558 }
3559 } else {
3560 printf("database loading failed with error code %d.\n", ec);
3561 errorCode = -1;
3562 }
3563
3564 cdb_end:
3565 clang_CompileCommands_dispose(CCmds);
3566 clang_CompilationDatabase_dispose(db);
3567 free(tmp);
3568
3569 }
3570
Argyrios Kyrtzidis4c910b12011-11-22 07:24:51 +00003571 clang_IndexAction_dispose(idxAction);
3572 clang_disposeIndex(Idx);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00003573 return errorCode;
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00003574}
3575
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003576int perform_token_annotation(int argc, const char **argv) {
3577 const char *input = argv[1];
3578 char *filename = 0;
3579 unsigned line, second_line;
3580 unsigned column, second_column;
3581 CXIndex CIdx;
3582 CXTranslationUnit TU = 0;
3583 int errorCode;
3584 struct CXUnsavedFile *unsaved_files = 0;
3585 int num_unsaved_files = 0;
3586 CXToken *tokens;
3587 unsigned num_tokens;
3588 CXSourceRange range;
3589 CXSourceLocation startLoc, endLoc;
3590 CXFile file = 0;
3591 CXCursor *cursors = 0;
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003592 CXSourceRangeList *skipped_ranges = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003593 enum CXErrorCode Err;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003594 unsigned i;
3595
3596 input += strlen("-test-annotate-tokens=");
3597 if ((errorCode = parse_file_line_column(input, &filename, &line, &column,
3598 &second_line, &second_column)))
3599 return errorCode;
3600
Richard Smith1ea42eb2012-07-05 08:20:49 +00003601 if (parse_remapped_files(argc, argv, 2, &unsaved_files, &num_unsaved_files)) {
3602 free(filename);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003603 return -1;
Richard Smith1ea42eb2012-07-05 08:20:49 +00003604 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003605
Douglas Gregor1e21cc72010-02-18 23:07:20 +00003606 CIdx = clang_createIndex(0, 1);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003607 Err = clang_parseTranslationUnit2(CIdx, argv[argc - 1],
3608 argv + num_unsaved_files + 2,
3609 argc - num_unsaved_files - 3,
3610 unsaved_files,
3611 num_unsaved_files,
3612 getDefaultParsingOptions(), &TU);
3613 if (Err != CXError_Success) {
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003614 fprintf(stderr, "unable to parse input\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003615 describeLibclangFailure(Err);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003616 clang_disposeIndex(CIdx);
3617 free(filename);
3618 free_remapped_files(unsaved_files, num_unsaved_files);
3619 return -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003620 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003621 errorCode = 0;
3622
Richard Smith1ea42eb2012-07-05 08:20:49 +00003623 if (checkForErrors(TU) != 0) {
3624 errorCode = -1;
3625 goto teardown;
3626 }
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003627
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003628 if (getenv("CINDEXTEST_EDITING")) {
3629 for (i = 0; i < 5; ++i) {
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003630 Err = clang_reparseTranslationUnit(TU, num_unsaved_files, unsaved_files,
3631 clang_defaultReparseOptions(TU));
3632 if (Err != CXError_Success) {
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003633 fprintf(stderr, "Unable to reparse translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003634 describeLibclangFailure(Err);
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00003635 errorCode = -1;
3636 goto teardown;
3637 }
3638 }
3639 }
3640
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003641 if (checkForErrors(TU) != 0) {
3642 errorCode = -1;
3643 goto teardown;
3644 }
3645
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003646 file = clang_getFile(TU, filename);
3647 if (!file) {
3648 fprintf(stderr, "file %s is not in this translation unit\n", filename);
3649 errorCode = -1;
3650 goto teardown;
3651 }
3652
3653 startLoc = clang_getLocation(TU, file, line, column);
3654 if (clang_equalLocations(clang_getNullLocation(), startLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003655 fprintf(stderr, "invalid source location %s:%d:%d\n", filename, line,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003656 column);
3657 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003658 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003659 }
3660
3661 endLoc = clang_getLocation(TU, file, second_line, second_column);
3662 if (clang_equalLocations(clang_getNullLocation(), endLoc)) {
Ted Kremenek29004672010-02-17 00:41:32 +00003663 fprintf(stderr, "invalid source location %s:%d:%d\n", filename,
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003664 second_line, second_column);
3665 errorCode = -1;
Ted Kremenek29004672010-02-17 00:41:32 +00003666 goto teardown;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003667 }
3668
3669 range = clang_getRange(startLoc, endLoc);
3670 clang_tokenize(TU, range, &tokens, &num_tokens);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003671
3672 if (checkForErrors(TU) != 0) {
3673 errorCode = -1;
3674 goto teardown;
3675 }
3676
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003677 cursors = (CXCursor *)malloc(num_tokens * sizeof(CXCursor));
3678 clang_annotateTokens(TU, tokens, num_tokens, cursors);
Argyrios Kyrtzidisa109e002011-10-28 22:54:36 +00003679
3680 if (checkForErrors(TU) != 0) {
3681 errorCode = -1;
3682 goto teardown;
3683 }
3684
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003685 skipped_ranges = clang_getSkippedRanges(TU, file);
3686 for (i = 0; i != skipped_ranges->count; ++i) {
3687 unsigned start_line, start_column, end_line, end_column;
3688 clang_getSpellingLocation(clang_getRangeStart(skipped_ranges->ranges[i]),
3689 0, &start_line, &start_column, 0);
3690 clang_getSpellingLocation(clang_getRangeEnd(skipped_ranges->ranges[i]),
3691 0, &end_line, &end_column, 0);
3692 printf("Skipping: ");
3693 PrintExtent(stdout, start_line, start_column, end_line, end_column);
3694 printf("\n");
3695 }
Argyrios Kyrtzidis0e282ef2013-12-06 18:55:45 +00003696 clang_disposeSourceRangeList(skipped_ranges);
Argyrios Kyrtzidis9ef57752013-12-05 08:19:32 +00003697
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003698 for (i = 0; i != num_tokens; ++i) {
3699 const char *kind = "<unknown>";
Enea Zaffanella476f38a2013-07-22 20:58:30 +00003700 CXString spelling = clang_getTokenSpelling(TU, tokens[i]);
3701 CXSourceRange extent = clang_getTokenExtent(TU, tokens[i]);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003702 unsigned start_line, start_column, end_line, end_column;
3703
3704 switch (clang_getTokenKind(tokens[i])) {
3705 case CXToken_Punctuation: kind = "Punctuation"; break;
3706 case CXToken_Keyword: kind = "Keyword"; break;
3707 case CXToken_Identifier: kind = "Identifier"; break;
3708 case CXToken_Literal: kind = "Literal"; break;
3709 case CXToken_Comment: kind = "Comment"; break;
3710 }
Douglas Gregor229bebd2010-11-09 06:24:54 +00003711 clang_getSpellingLocation(clang_getRangeStart(extent),
3712 0, &start_line, &start_column, 0);
3713 clang_getSpellingLocation(clang_getRangeEnd(extent),
3714 0, &end_line, &end_column, 0);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003715 printf("%s: \"%s\" ", kind, clang_getCString(spelling));
Benjamin Krameraf7ae312012-04-14 09:11:51 +00003716 clang_disposeString(spelling);
Daniel Dunbar98c07e02010-02-14 08:32:24 +00003717 PrintExtent(stdout, start_line, start_column, end_line, end_column);
Douglas Gregor61656112010-01-26 18:31:56 +00003718 if (!clang_isInvalid(cursors[i].kind)) {
3719 printf(" ");
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00003720 PrintCursor(cursors[i], NULL);
Douglas Gregor61656112010-01-26 18:31:56 +00003721 }
3722 printf("\n");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003723 }
3724 free(cursors);
Ted Kremenek983fb5de2010-10-20 21:22:15 +00003725 clang_disposeTokens(TU, tokens, num_tokens);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003726
3727 teardown:
Douglas Gregor33cdd812010-02-18 18:08:43 +00003728 PrintDiagnostics(TU);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00003729 clang_disposeTranslationUnit(TU);
3730 clang_disposeIndex(CIdx);
3731 free(filename);
3732 free_remapped_files(unsaved_files, num_unsaved_files);
3733 return errorCode;
3734}
3735
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003736static int
3737perform_test_compilation_db(const char *database, int argc, const char **argv) {
3738 CXCompilationDatabase db;
3739 CXCompileCommands CCmds;
3740 CXCompileCommand CCmd;
3741 CXCompilationDatabase_Error ec;
3742 CXString wd;
3743 CXString arg;
3744 int errorCode = 0;
3745 char *tmp;
3746 unsigned len;
3747 char *buildDir;
3748 int i, j, a, numCmds, numArgs;
3749
3750 len = strlen(database);
3751 tmp = (char *) malloc(len+1);
3752 memcpy(tmp, database, len+1);
3753 buildDir = dirname(tmp);
3754
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003755 db = clang_CompilationDatabase_fromDirectory(buildDir, &ec);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003756
3757 if (db) {
3758
3759 if (ec!=CXCompilationDatabase_NoError) {
3760 printf("unexpected error %d code while loading compilation database\n", ec);
3761 errorCode = -1;
3762 goto cdb_end;
3763 }
3764
3765 for (i=0; i<argc && errorCode==0; ) {
3766 if (strcmp(argv[i],"lookup")==0){
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003767 CCmds = clang_CompilationDatabase_getCompileCommands(db, argv[i+1]);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003768
3769 if (!CCmds) {
3770 printf("file %s not found in compilation db\n", argv[i+1]);
3771 errorCode = -1;
3772 break;
3773 }
3774
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003775 numCmds = clang_CompileCommands_getSize(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003776
3777 if (numCmds==0) {
3778 fprintf(stderr, "should not get an empty compileCommand set for file"
3779 " '%s'\n", argv[i+1]);
3780 errorCode = -1;
3781 break;
3782 }
3783
3784 for (j=0; j<numCmds; ++j) {
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003785 CCmd = clang_CompileCommands_getCommand(CCmds, j);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003786
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003787 wd = clang_CompileCommand_getDirectory(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003788 printf("workdir:'%s'", clang_getCString(wd));
3789 clang_disposeString(wd);
3790
3791 printf(" cmdline:'");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003792 numArgs = clang_CompileCommand_getNumArgs(CCmd);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003793 for (a=0; a<numArgs; ++a) {
3794 if (a) printf(" ");
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003795 arg = clang_CompileCommand_getArg(CCmd, a);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003796 printf("%s", clang_getCString(arg));
3797 clang_disposeString(arg);
3798 }
3799 printf("'\n");
3800 }
3801
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003802 clang_CompileCommands_dispose(CCmds);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003803
3804 i += 2;
3805 }
3806 }
Arnaud A. de Grandmaisonfa6d73c2012-07-03 20:38:12 +00003807 clang_CompilationDatabase_dispose(db);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00003808 } else {
3809 printf("database loading failed with error code %d.\n", ec);
3810 errorCode = -1;
3811 }
3812
3813cdb_end:
3814 free(tmp);
3815
3816 return errorCode;
3817}
3818
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003819/******************************************************************************/
Ted Kremenek599d73a2010-03-25 02:00:39 +00003820/* USR printing. */
3821/******************************************************************************/
3822
3823static int insufficient_usr(const char *kind, const char *usage) {
3824 fprintf(stderr, "USR for '%s' requires: %s\n", kind, usage);
3825 return 1;
3826}
3827
3828static unsigned isUSR(const char *s) {
3829 return s[0] == 'c' && s[1] == ':';
3830}
3831
3832static int not_usr(const char *s, const char *arg) {
3833 fprintf(stderr, "'%s' argument ('%s') is not a USR\n", s, arg);
3834 return 1;
3835}
3836
3837static void print_usr(CXString usr) {
3838 const char *s = clang_getCString(usr);
3839 printf("%s\n", s);
3840 clang_disposeString(usr);
3841}
3842
3843static void display_usrs() {
3844 fprintf(stderr, "-print-usrs options:\n"
3845 " ObjCCategory <class name> <category name>\n"
3846 " ObjCClass <class name>\n"
3847 " ObjCIvar <ivar name> <class USR>\n"
3848 " ObjCMethod <selector> [0=class method|1=instance method] "
3849 "<class USR>\n"
3850 " ObjCProperty <property name> <class USR>\n"
3851 " ObjCProtocol <protocol name>\n");
3852}
3853
3854int print_usrs(const char **I, const char **E) {
3855 while (I != E) {
3856 const char *kind = *I;
3857 unsigned len = strlen(kind);
3858 switch (len) {
3859 case 8:
3860 if (memcmp(kind, "ObjCIvar", 8) == 0) {
3861 if (I + 2 >= E)
3862 return insufficient_usr(kind, "<ivar name> <class USR>");
3863 if (!isUSR(I[2]))
3864 return not_usr("<class USR>", I[2]);
3865 else {
3866 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003867 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003868 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003869 print_usr(clang_constructUSR_ObjCIvar(I[1], x));
3870 }
3871
3872 I += 3;
3873 continue;
3874 }
3875 break;
3876 case 9:
3877 if (memcmp(kind, "ObjCClass", 9) == 0) {
3878 if (I + 1 >= E)
3879 return insufficient_usr(kind, "<class name>");
3880 print_usr(clang_constructUSR_ObjCClass(I[1]));
3881 I += 2;
3882 continue;
3883 }
3884 break;
3885 case 10:
3886 if (memcmp(kind, "ObjCMethod", 10) == 0) {
3887 if (I + 3 >= E)
3888 return insufficient_usr(kind, "<method selector> "
3889 "[0=class method|1=instance method] <class USR>");
3890 if (!isUSR(I[3]))
3891 return not_usr("<class USR>", I[3]);
3892 else {
3893 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003894 x.data = (void*) I[3];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003895 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003896 print_usr(clang_constructUSR_ObjCMethod(I[1], atoi(I[2]), x));
3897 }
3898 I += 4;
3899 continue;
3900 }
3901 break;
3902 case 12:
3903 if (memcmp(kind, "ObjCCategory", 12) == 0) {
3904 if (I + 2 >= E)
3905 return insufficient_usr(kind, "<class name> <category name>");
3906 print_usr(clang_constructUSR_ObjCCategory(I[1], I[2]));
3907 I += 3;
3908 continue;
3909 }
3910 if (memcmp(kind, "ObjCProtocol", 12) == 0) {
3911 if (I + 1 >= E)
3912 return insufficient_usr(kind, "<protocol name>");
3913 print_usr(clang_constructUSR_ObjCProtocol(I[1]));
3914 I += 2;
3915 continue;
3916 }
3917 if (memcmp(kind, "ObjCProperty", 12) == 0) {
3918 if (I + 2 >= E)
3919 return insufficient_usr(kind, "<property name> <class USR>");
3920 if (!isUSR(I[2]))
3921 return not_usr("<class USR>", I[2]);
3922 else {
3923 CXString x;
Ted Kremenek91554282010-11-16 08:15:36 +00003924 x.data = (void*) I[2];
Ted Kremenek4b4f3692010-11-16 01:56:27 +00003925 x.private_flags = 0;
Ted Kremenek599d73a2010-03-25 02:00:39 +00003926 print_usr(clang_constructUSR_ObjCProperty(I[1], x));
3927 }
3928 I += 3;
3929 continue;
3930 }
3931 break;
3932 default:
3933 break;
3934 }
3935 break;
3936 }
3937
3938 if (I != E) {
3939 fprintf(stderr, "Invalid USR kind: %s\n", *I);
3940 display_usrs();
3941 return 1;
3942 }
3943 return 0;
3944}
3945
3946int print_usrs_file(const char *file_name) {
3947 char line[2048];
3948 const char *args[128];
3949 unsigned numChars = 0;
3950
3951 FILE *fp = fopen(file_name, "r");
3952 if (!fp) {
3953 fprintf(stderr, "error: cannot open '%s'\n", file_name);
3954 return 1;
3955 }
3956
3957 /* This code is not really all that safe, but it works fine for testing. */
3958 while (!feof(fp)) {
3959 char c = fgetc(fp);
3960 if (c == '\n') {
3961 unsigned i = 0;
3962 const char *s = 0;
3963
3964 if (numChars == 0)
3965 continue;
3966
3967 line[numChars] = '\0';
3968 numChars = 0;
3969
3970 if (line[0] == '/' && line[1] == '/')
3971 continue;
3972
3973 s = strtok(line, " ");
3974 while (s) {
3975 args[i] = s;
3976 ++i;
3977 s = strtok(0, " ");
3978 }
3979 if (print_usrs(&args[0], &args[i]))
3980 return 1;
3981 }
3982 else
3983 line[numChars++] = c;
3984 }
3985
3986 fclose(fp);
3987 return 0;
3988}
3989
3990/******************************************************************************/
Ted Kremenek1cd27d52009-11-17 18:13:31 +00003991/* Command line processing. */
3992/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00003993int write_pch_file(const char *filename, int argc, const char *argv[]) {
3994 CXIndex Idx;
3995 CXTranslationUnit TU;
3996 struct CXUnsavedFile *unsaved_files = 0;
3997 int num_unsaved_files = 0;
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00003998 enum CXErrorCode Err;
Francois Pichetabcfbec2011-07-06 22:09:44 +00003999 int result = 0;
Douglas Gregore9386682010-08-13 05:36:37 +00004000
Stefanus Du Toitb3318502013-03-01 21:41:22 +00004001 Idx = clang_createIndex(/* excludeDeclsFromPCH */1, /* displayDiagnostics=*/1);
Douglas Gregore9386682010-08-13 05:36:37 +00004002
4003 if (parse_remapped_files(argc, argv, 0, &unsaved_files, &num_unsaved_files)) {
4004 clang_disposeIndex(Idx);
4005 return -1;
4006 }
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004007
4008 Err = clang_parseTranslationUnit2(
4009 Idx, 0, argv + num_unsaved_files, argc - num_unsaved_files,
4010 unsaved_files, num_unsaved_files,
4011 CXTranslationUnit_Incomplete |
4012 CXTranslationUnit_DetailedPreprocessingRecord |
4013 CXTranslationUnit_ForSerialization,
4014 &TU);
4015 if (Err != CXError_Success) {
Douglas Gregore9386682010-08-13 05:36:37 +00004016 fprintf(stderr, "Unable to load translation unit!\n");
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004017 describeLibclangFailure(Err);
Douglas Gregore9386682010-08-13 05:36:37 +00004018 free_remapped_files(unsaved_files, num_unsaved_files);
Dmitri Gribenkoea4d1c32014-02-12 19:12:37 +00004019 clang_disposeTranslationUnit(TU);
Douglas Gregore9386682010-08-13 05:36:37 +00004020 clang_disposeIndex(Idx);
4021 return 1;
4022 }
4023
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004024 switch (clang_saveTranslationUnit(TU, filename,
4025 clang_defaultSaveOptions(TU))) {
4026 case CXSaveError_None:
4027 break;
4028
4029 case CXSaveError_TranslationErrors:
4030 fprintf(stderr, "Unable to write PCH file %s: translation errors\n",
4031 filename);
4032 result = 2;
4033 break;
4034
4035 case CXSaveError_InvalidTU:
4036 fprintf(stderr, "Unable to write PCH file %s: invalid translation unit\n",
4037 filename);
4038 result = 3;
4039 break;
4040
4041 case CXSaveError_Unknown:
4042 default:
4043 fprintf(stderr, "Unable to write PCH file %s: unknown error \n", filename);
4044 result = 1;
4045 break;
4046 }
4047
Douglas Gregore9386682010-08-13 05:36:37 +00004048 clang_disposeTranslationUnit(TU);
4049 free_remapped_files(unsaved_files, num_unsaved_files);
4050 clang_disposeIndex(Idx);
Douglas Gregor30c80fa2011-07-06 16:43:36 +00004051 return result;
Douglas Gregore9386682010-08-13 05:36:37 +00004052}
4053
4054/******************************************************************************/
Ted Kremenekd010ba42011-11-10 08:43:12 +00004055/* Serialized diagnostics. */
4056/******************************************************************************/
4057
4058static const char *getDiagnosticCodeStr(enum CXLoadDiag_Error error) {
4059 switch (error) {
4060 case CXLoadDiag_CannotLoad: return "Cannot Load File";
4061 case CXLoadDiag_None: break;
4062 case CXLoadDiag_Unknown: return "Unknown";
4063 case CXLoadDiag_InvalidFile: return "Invalid File";
4064 }
4065 return "None";
4066}
4067
4068static const char *getSeverityString(enum CXDiagnosticSeverity severity) {
4069 switch (severity) {
4070 case CXDiagnostic_Note: return "note";
4071 case CXDiagnostic_Error: return "error";
4072 case CXDiagnostic_Fatal: return "fatal";
4073 case CXDiagnostic_Ignored: return "ignored";
4074 case CXDiagnostic_Warning: return "warning";
4075 }
4076 return "unknown";
4077}
4078
4079static void printIndent(unsigned indent) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004080 if (indent == 0)
4081 return;
4082 fprintf(stderr, "+");
4083 --indent;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004084 while (indent > 0) {
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004085 fprintf(stderr, "-");
Ted Kremenekd010ba42011-11-10 08:43:12 +00004086 --indent;
4087 }
4088}
4089
4090static void printLocation(CXSourceLocation L) {
4091 CXFile File;
4092 CXString FileName;
4093 unsigned line, column, offset;
4094
4095 clang_getExpansionLocation(L, &File, &line, &column, &offset);
4096 FileName = clang_getFileName(File);
4097
4098 fprintf(stderr, "%s:%d:%d", clang_getCString(FileName), line, column);
4099 clang_disposeString(FileName);
4100}
4101
4102static void printRanges(CXDiagnostic D, unsigned indent) {
4103 unsigned i, n = clang_getDiagnosticNumRanges(D);
4104
4105 for (i = 0; i < n; ++i) {
4106 CXSourceLocation Start, End;
Enea Zaffanella476f38a2013-07-22 20:58:30 +00004107 CXSourceRange SR = clang_getDiagnosticRange(D, i);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004108 Start = clang_getRangeStart(SR);
4109 End = clang_getRangeEnd(SR);
4110
4111 printIndent(indent);
4112 fprintf(stderr, "Range: ");
4113 printLocation(Start);
4114 fprintf(stderr, " ");
4115 printLocation(End);
4116 fprintf(stderr, "\n");
4117 }
4118}
4119
4120static void printFixIts(CXDiagnostic D, unsigned indent) {
4121 unsigned i, n = clang_getDiagnosticNumFixIts(D);
Ted Kremenek4a642302012-03-20 20:49:45 +00004122 fprintf(stderr, "Number FIXITs = %d\n", n);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004123 for (i = 0 ; i < n; ++i) {
4124 CXSourceRange ReplacementRange;
4125 CXString text;
4126 text = clang_getDiagnosticFixIt(D, i, &ReplacementRange);
4127
4128 printIndent(indent);
4129 fprintf(stderr, "FIXIT: (");
4130 printLocation(clang_getRangeStart(ReplacementRange));
4131 fprintf(stderr, " - ");
4132 printLocation(clang_getRangeEnd(ReplacementRange));
4133 fprintf(stderr, "): \"%s\"\n", clang_getCString(text));
4134 clang_disposeString(text);
4135 }
4136}
4137
4138static void printDiagnosticSet(CXDiagnosticSet Diags, unsigned indent) {
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004139 unsigned i, n;
4140
Ted Kremenekd010ba42011-11-10 08:43:12 +00004141 if (!Diags)
4142 return;
4143
NAKAMURA Takumi77d97392011-11-10 09:30:15 +00004144 n = clang_getNumDiagnosticsInSet(Diags);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004145 for (i = 0; i < n; ++i) {
4146 CXSourceLocation DiagLoc;
4147 CXDiagnostic D;
4148 CXFile File;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004149 CXString FileName, DiagSpelling, DiagOption, DiagCat;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004150 unsigned line, column, offset;
Ted Kremenek26a6d492012-04-12 00:03:31 +00004151 const char *DiagOptionStr = 0, *DiagCatStr = 0;
Ted Kremenekd010ba42011-11-10 08:43:12 +00004152
4153 D = clang_getDiagnosticInSet(Diags, i);
4154 DiagLoc = clang_getDiagnosticLocation(D);
4155 clang_getExpansionLocation(DiagLoc, &File, &line, &column, &offset);
4156 FileName = clang_getFileName(File);
4157 DiagSpelling = clang_getDiagnosticSpelling(D);
4158
4159 printIndent(indent);
4160
4161 fprintf(stderr, "%s:%d:%d: %s: %s",
4162 clang_getCString(FileName),
4163 line,
4164 column,
4165 getSeverityString(clang_getDiagnosticSeverity(D)),
4166 clang_getCString(DiagSpelling));
4167
4168 DiagOption = clang_getDiagnosticOption(D, 0);
4169 DiagOptionStr = clang_getCString(DiagOption);
4170 if (DiagOptionStr) {
4171 fprintf(stderr, " [%s]", DiagOptionStr);
4172 }
4173
Ted Kremenek26a6d492012-04-12 00:03:31 +00004174 DiagCat = clang_getDiagnosticCategoryText(D);
4175 DiagCatStr = clang_getCString(DiagCat);
4176 if (DiagCatStr) {
4177 fprintf(stderr, " [%s]", DiagCatStr);
4178 }
4179
Ted Kremenekd010ba42011-11-10 08:43:12 +00004180 fprintf(stderr, "\n");
4181
4182 printRanges(D, indent);
4183 printFixIts(D, indent);
4184
NAKAMURA Takumi27dd3962011-11-10 10:07:57 +00004185 /* Print subdiagnostics. */
Ted Kremenekd010ba42011-11-10 08:43:12 +00004186 printDiagnosticSet(clang_getChildDiagnostics(D), indent+2);
4187
4188 clang_disposeString(FileName);
4189 clang_disposeString(DiagSpelling);
4190 clang_disposeString(DiagOption);
Nico Weberce5528a2014-05-11 17:16:59 +00004191 clang_disposeString(DiagCat);
Ted Kremenekd010ba42011-11-10 08:43:12 +00004192 }
4193}
4194
4195static int read_diagnostics(const char *filename) {
4196 enum CXLoadDiag_Error error;
4197 CXString errorString;
4198 CXDiagnosticSet Diags = 0;
4199
4200 Diags = clang_loadDiagnostics(filename, &error, &errorString);
4201 if (!Diags) {
4202 fprintf(stderr, "Trouble deserializing file (%s): %s\n",
4203 getDiagnosticCodeStr(error),
4204 clang_getCString(errorString));
4205 clang_disposeString(errorString);
4206 return 1;
4207 }
4208
4209 printDiagnosticSet(Diags, 0);
Ted Kremeneka0e32fc2011-11-11 00:46:43 +00004210 fprintf(stderr, "Number of diagnostics: %d\n",
4211 clang_getNumDiagnosticsInSet(Diags));
Ted Kremenekd010ba42011-11-10 08:43:12 +00004212 clang_disposeDiagnosticSet(Diags);
4213 return 0;
4214}
4215
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004216static int perform_print_build_session_timestamp(void) {
Yaron Keren129dfbf2015-05-14 06:53:31 +00004217 printf("%lld\n", clang_getBuildSessionTimestamp());
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004218 return 0;
4219}
4220
Ted Kremenekd010ba42011-11-10 08:43:12 +00004221/******************************************************************************/
Douglas Gregore9386682010-08-13 05:36:37 +00004222/* Command line processing. */
4223/******************************************************************************/
Ted Kremenekef3339b2009-11-17 18:09:14 +00004224
Douglas Gregor720d0052010-01-20 21:32:04 +00004225static CXCursorVisitor GetVisitor(const char *s) {
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004226 if (s[0] == '\0')
Douglas Gregor720d0052010-01-20 21:32:04 +00004227 return FilteredPrintingVisitor;
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004228 if (strcmp(s, "-usrs") == 0)
4229 return USRVisitor;
Ted Kremenek83f642e2011-04-18 22:47:10 +00004230 if (strncmp(s, "-memory-usage", 13) == 0)
4231 return GetVisitor(s + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004232 return NULL;
4233}
4234
Ted Kremenekef3339b2009-11-17 18:09:14 +00004235static void print_usage(void) {
4236 fprintf(stderr,
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004237 "usage: c-index-test -code-completion-at=<site> <compiler arguments>\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004238 " c-index-test -code-completion-timing=<site> <compiler arguments>\n"
Douglas Gregor082c3e62010-01-15 19:40:17 +00004239 " c-index-test -cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004240 " c-index-test -evaluate-cursor-at=<site> <compiler arguments>\n"
4241 " c-index-test -get-macro-info-cursor-at=<site> <compiler arguments>\n"
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004242 " c-index-test -file-refs-at=<site> <compiler arguments>\n"
4243 " c-index-test -file-includes-in=<filename> <compiler arguments>\n");
NAKAMURA Takumi4deb9a92012-10-24 22:52:04 +00004244 fprintf(stderr,
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004245 " c-index-test -index-file [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004246 " c-index-test -index-file-full [-check-prefix=<FileCheck prefix>] <compiler arguments>\n"
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004247 " c-index-test -index-tu [-check-prefix=<FileCheck prefix>] <AST file>\n"
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004248 " c-index-test -index-compile-db [-check-prefix=<FileCheck prefix>] <compilation database>\n"
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004249 " c-index-test -test-file-scan <AST file> <source file> "
Erik Verbruggen338b55c2011-10-06 11:38:08 +00004250 "[FileCheck prefix]\n");
4251 fprintf(stderr,
Ted Kremeneka44d99c2010-01-05 23:18:49 +00004252 " c-index-test -test-load-tu <AST file> <symbol filter> "
4253 "[FileCheck prefix]\n"
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004254 " c-index-test -test-load-tu-usrs <AST file> <symbol filter> "
4255 "[FileCheck prefix]\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004256 " c-index-test -test-load-source <symbol filter> {<args>}*\n");
Douglas Gregor082c3e62010-01-15 19:40:17 +00004257 fprintf(stderr,
Ted Kremenek83f642e2011-04-18 22:47:10 +00004258 " c-index-test -test-load-source-memory-usage "
4259 "<symbol filter> {<args>}*\n"
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004260 " c-index-test -test-load-source-reparse <trials> <symbol filter> "
4261 " {<args>}*\n"
Douglas Gregor47815d52010-07-12 18:38:41 +00004262 " c-index-test -test-load-source-usrs <symbol filter> {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004263 " c-index-test -test-load-source-usrs-memory-usage "
4264 "<symbol filter> {<args>}*\n"
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004265 " c-index-test -test-annotate-tokens=<range> {<args>}*\n"
4266 " c-index-test -test-inclusion-stack-source {<args>}*\n"
Ted Kremenek11d1a422011-04-18 23:42:53 +00004267 " c-index-test -test-inclusion-stack-tu <AST file>\n");
Chandler Carruth718df592010-07-22 06:29:13 +00004268 fprintf(stderr,
Ted Kremenek11d1a422011-04-18 23:42:53 +00004269 " c-index-test -test-print-linkage-source {<args>}*\n"
Ehsan Akhgarib743de72016-05-31 15:55:51 +00004270 " c-index-test -test-print-visibility {<args>}*\n"
Dmitri Gribenko00353722013-02-15 21:15:49 +00004271 " c-index-test -test-print-type {<args>}*\n"
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004272 " c-index-test -test-print-type-size {<args>}*\n"
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004273 " c-index-test -test-print-bitwidth {<args>}*\n"
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004274 " c-index-test -test-print-type-declaration {<args>}*\n"
Ted Kremenek83f642e2011-04-18 22:47:10 +00004275 " c-index-test -print-usr [<CursorKind> {<args>}]*\n"
Douglas Gregore9386682010-08-13 05:36:37 +00004276 " c-index-test -print-usr-file <file>\n"
Ted Kremenekd010ba42011-11-10 08:43:12 +00004277 " c-index-test -write-pch <file> <compiler arguments>\n");
4278 fprintf(stderr,
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004279 " c-index-test -compilation-db [lookup <filename>] database\n");
4280 fprintf(stderr,
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004281 " c-index-test -print-build-session-timestamp\n");
4282 fprintf(stderr,
Ted Kremenekd010ba42011-11-10 08:43:12 +00004283 " c-index-test -read-diagnostics <file>\n\n");
Douglas Gregor73a18fd2010-07-20 14:34:35 +00004284 fprintf(stderr,
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004285 " <symbol filter> values:\n%s",
Ted Kremenek1cd27d52009-11-17 18:13:31 +00004286 " all - load all symbols, including those from PCH\n"
4287 " local - load all symbols except those in PCH\n"
4288 " category - only load ObjC categories (non-PCH)\n"
4289 " interface - only load ObjC interfaces (non-PCH)\n"
4290 " protocol - only load ObjC protocols (non-PCH)\n"
4291 " function - only load functions (non-PCH)\n"
Daniel Dunbar5442bfc2009-12-01 02:35:37 +00004292 " typedef - only load typdefs (non-PCH)\n"
4293 " scan-function - scan function bodies (non-PCH)\n\n");
Ted Kremenekef3339b2009-11-17 18:09:14 +00004294}
4295
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004296/***/
4297
4298int cindextest_main(int argc, const char **argv) {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00004299 clang_enableStackTraces();
Ted Kremenekd010ba42011-11-10 08:43:12 +00004300 if (argc > 2 && strcmp(argv[1], "-read-diagnostics") == 0)
4301 return read_diagnostics(argv[2]);
Ted Kremenekef3339b2009-11-17 18:09:14 +00004302 if (argc > 2 && strstr(argv[1], "-code-completion-at=") == argv[1])
Douglas Gregor47815d52010-07-12 18:38:41 +00004303 return perform_code_completion(argc, argv, 0);
4304 if (argc > 2 && strstr(argv[1], "-code-completion-timing=") == argv[1])
4305 return perform_code_completion(argc, argv, 1);
Douglas Gregor082c3e62010-01-15 19:40:17 +00004306 if (argc > 2 && strstr(argv[1], "-cursor-at=") == argv[1])
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00004307 return inspect_cursor_at(argc, argv, "-cursor-at=", inspect_print_cursor);
4308 if (argc > 2 && strstr(argv[1], "-evaluate-cursor-at=") == argv[1])
4309 return inspect_cursor_at(argc, argv, "-evaluate-cursor-at=",
4310 inspect_evaluate_cursor);
4311 if (argc > 2 && strstr(argv[1], "-get-macro-info-cursor-at=") == argv[1])
4312 return inspect_cursor_at(argc, argv, "-get-macro-info-cursor-at=",
4313 inspect_macroinfo_cursor);
Argyrios Kyrtzidiscddafd32011-10-06 07:00:54 +00004314 if (argc > 2 && strstr(argv[1], "-file-refs-at=") == argv[1])
4315 return find_file_refs_at(argc, argv);
Argyrios Kyrtzidis503c83a2013-03-08 02:32:34 +00004316 if (argc > 2 && strstr(argv[1], "-file-includes-in=") == argv[1])
4317 return find_file_includes_in(argc, argv);
Argyrios Kyrtzidisdc199a32011-10-17 19:48:19 +00004318 if (argc > 2 && strcmp(argv[1], "-index-file") == 0)
Argyrios Kyrtzidise26c5572012-10-24 18:29:15 +00004319 return index_file(argc - 2, argv + 2, /*full=*/0);
4320 if (argc > 2 && strcmp(argv[1], "-index-file-full") == 0)
4321 return index_file(argc - 2, argv + 2, /*full=*/1);
Argyrios Kyrtzidisd992e142011-11-15 06:20:16 +00004322 if (argc > 2 && strcmp(argv[1], "-index-tu") == 0)
4323 return index_tu(argc - 2, argv + 2);
Argyrios Kyrtzidisf75d4982012-12-05 21:53:37 +00004324 if (argc > 2 && strcmp(argv[1], "-index-compile-db") == 0)
4325 return index_compile_db(argc - 2, argv + 2);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004326 else if (argc >= 4 && strncmp(argv[1], "-test-load-tu", 13) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004327 CXCursorVisitor I = GetVisitor(argv[1] + 13);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004328 if (I)
Ted Kremenekb478ff42010-01-26 17:59:48 +00004329 return perform_test_load_tu(argv[2], argv[3], argc >= 5 ? argv[4] : 0, I,
4330 NULL);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004331 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00004332 else if (argc >= 5 && strncmp(argv[1], "-test-load-source-reparse", 25) == 0){
4333 CXCursorVisitor I = GetVisitor(argv[1] + 25);
4334 if (I) {
4335 int trials = atoi(argv[2]);
4336 return perform_test_reparse_source(argc - 4, argv + 4, trials, argv[3], I,
4337 NULL);
4338 }
4339 }
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004340 else if (argc >= 4 && strncmp(argv[1], "-test-load-source", 17) == 0) {
Douglas Gregor720d0052010-01-20 21:32:04 +00004341 CXCursorVisitor I = GetVisitor(argv[1] + 17);
Ted Kremenek83f642e2011-04-18 22:47:10 +00004342
4343 PostVisitTU postVisit = 0;
4344 if (strstr(argv[1], "-memory-usage"))
4345 postVisit = PrintMemoryUsage;
4346
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004347 if (I)
Ted Kremenek83f642e2011-04-18 22:47:10 +00004348 return perform_test_load_source(argc - 3, argv + 3, argv[2], I,
4349 postVisit);
Ted Kremenek58a6a8e2010-01-12 23:34:26 +00004350 }
4351 else if (argc >= 4 && strcmp(argv[1], "-test-file-scan") == 0)
Ted Kremenek0469b7e2009-11-18 02:02:52 +00004352 return perform_file_scan(argv[2], argv[3],
4353 argc >= 5 ? argv[4] : 0);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00004354 else if (argc > 2 && strstr(argv[1], "-test-annotate-tokens=") == argv[1])
4355 return perform_token_annotation(argc, argv);
Ted Kremenek0b86e3a2010-01-26 19:31:51 +00004356 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-source") == 0)
4357 return perform_test_load_source(argc - 2, argv + 2, "all", NULL,
4358 PrintInclusionStack);
4359 else if (argc > 2 && strcmp(argv[1], "-test-inclusion-stack-tu") == 0)
4360 return perform_test_load_tu(argv[2], "all", NULL, NULL,
4361 PrintInclusionStack);
Ted Kremenek83b28a22010-03-03 06:37:58 +00004362 else if (argc > 2 && strcmp(argv[1], "-test-print-linkage-source") == 0)
4363 return perform_test_load_source(argc - 2, argv + 2, "all", PrintLinkage,
4364 NULL);
Ehsan Akhgarib743de72016-05-31 15:55:51 +00004365 else if (argc > 2 && strcmp(argv[1], "-test-print-visibility") == 0)
4366 return perform_test_load_source(argc - 2, argv + 2, "all", PrintVisibility,
4367 NULL);
Dmitri Gribenko00353722013-02-15 21:15:49 +00004368 else if (argc > 2 && strcmp(argv[1], "-test-print-type") == 0)
Ted Kremenek6bca9842010-05-14 21:29:26 +00004369 return perform_test_load_source(argc - 2, argv + 2, "all",
Dmitri Gribenko00353722013-02-15 21:15:49 +00004370 PrintType, 0);
Argyrios Kyrtzidise822f582013-04-11 01:20:11 +00004371 else if (argc > 2 && strcmp(argv[1], "-test-print-type-size") == 0)
4372 return perform_test_load_source(argc - 2, argv + 2, "all",
4373 PrintTypeSize, 0);
Sergey Kalinichevb8d516a2016-01-07 09:20:40 +00004374 else if (argc > 2 && strcmp(argv[1], "-test-print-type-declaration") == 0)
4375 return perform_test_load_source(argc - 2, argv + 2, "all",
4376 PrintTypeDeclaration, 0);
Dmitri Gribenkob506ba12012-12-04 15:13:46 +00004377 else if (argc > 2 && strcmp(argv[1], "-test-print-bitwidth") == 0)
4378 return perform_test_load_source(argc - 2, argv + 2, "all",
4379 PrintBitWidth, 0);
Eli Bendersky44a206f2014-07-31 18:04:56 +00004380 else if (argc > 2 && strcmp(argv[1], "-test-print-mangle") == 0)
4381 return perform_test_load_tu(argv[2], "all", NULL, PrintMangledName, NULL);
Saleem Abdulrasool60034432015-11-12 03:57:22 +00004382 else if (argc > 2 && strcmp(argv[1], "-test-print-manglings") == 0)
4383 return perform_test_load_tu(argv[2], "all", NULL, PrintManglings, NULL);
Ted Kremenek599d73a2010-03-25 02:00:39 +00004384 else if (argc > 1 && strcmp(argv[1], "-print-usr") == 0) {
4385 if (argc > 2)
4386 return print_usrs(argv + 2, argv + argc);
4387 else {
4388 display_usrs();
4389 return 1;
4390 }
4391 }
4392 else if (argc > 2 && strcmp(argv[1], "-print-usr-file") == 0)
4393 return print_usrs_file(argv[2]);
Douglas Gregore9386682010-08-13 05:36:37 +00004394 else if (argc > 2 && strcmp(argv[1], "-write-pch") == 0)
4395 return write_pch_file(argv[2], argc - 3, argv + 3);
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004396 else if (argc > 2 && strcmp(argv[1], "-compilation-db") == 0)
4397 return perform_test_compilation_db(argv[argc-1], argc - 3, argv + 2);
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004398 else if (argc == 2 && strcmp(argv[1], "-print-build-session-timestamp") == 0)
4399 return perform_print_build_session_timestamp();
Arnaud A. de Grandmaison0fe28a12012-06-30 11:27:57 +00004400
Ted Kremenekef3339b2009-11-17 18:09:14 +00004401 print_usage();
4402 return 1;
Steve Naroffa1c72842009-08-28 15:28:48 +00004403}
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004404
4405/***/
4406
4407/* We intentionally run in a separate thread to ensure we at least minimal
4408 * testing of a multithreaded environment (for example, having a reduced stack
4409 * size). */
4410
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004411typedef struct thread_info {
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004412 int (*main_func)(int argc, const char **argv);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004413 int argc;
4414 const char **argv;
4415 int result;
4416} thread_info;
Benjamin Kramer112fc6c2010-11-04 19:11:31 +00004417void thread_runner(void *client_data_v) {
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004418 thread_info *client_data = client_data_v;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004419 client_data->result = client_data->main_func(client_data->argc,
4420 client_data->argv);
Reid Klecknere931c062014-06-05 00:13:43 +00004421}
4422
4423static void flush_atexit(void) {
Timur Iskhodzhanoveae19462014-06-06 11:04:46 +00004424 /* stdout, and surprisingly even stderr, are not always flushed on process
4425 * and thread exit, particularly when the system is under heavy load. */
Reid Klecknere931c062014-06-05 00:13:43 +00004426 fflush(stdout);
4427 fflush(stderr);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004428}
4429
4430int main(int argc, const char **argv) {
Benjamin Kramer3a913ed2012-08-10 10:06:13 +00004431 thread_info client_data;
4432
Reid Klecknere931c062014-06-05 00:13:43 +00004433 atexit(flush_atexit);
4434
Dmitri Gribenko740c0fb2012-08-07 17:54:38 +00004435#ifdef CLANG_HAVE_LIBXML
4436 LIBXML_TEST_VERSION
4437#endif
4438
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004439 client_data.main_func = cindextest_main;
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004440 client_data.argc = argc;
4441 client_data.argv = argv;
Argyrios Kyrtzidis6fdcb9c2016-02-14 06:39:11 +00004442
4443 if (argc > 1 && strcmp(argv[1], "core") == 0) {
4444 client_data.main_func = indextest_core_main;
4445 --client_data.argc;
4446 ++client_data.argv;
4447 }
4448
4449 if (getenv("CINDEXTEST_NOTHREADS"))
4450 return client_data.main_func(client_data.argc, client_data.argv);
4451
Daniel Dunbar23397c32010-11-04 01:26:31 +00004452 clang_executeOnThread(thread_runner, &client_data, 0);
Daniel Dunbar08b33d02010-09-30 20:39:47 +00004453 return client_data.result;
4454}